code
stringlengths
1
2.08M
language
stringclasses
1 value
/* * Quicktags * * This is the HTML editor in WordPress. It can be attached to any textarea and will * append a toolbar above it. This script is self-contained (does not require external libraries). * * Run quicktags(settings) to initialize it, where settings is an object containing up to 3 properties: * settings = { * id : 'my_id', the HTML ID of the textarea, required * buttons: '' Comma separated list of the names of the default buttons to show. Optional. * Current list of default button names: 'strong,em,link,block,del,ins,img,ul,ol,li,code,more,close'; * } * * The settings can also be a string quicktags_id. * * quicktags_id string The ID of the textarea that will be the editor canvas * buttons string Comma separated list of the default buttons names that will be shown in that instance. */ // new edit toolbar used with permission // by Alex King // http://www.alexking.org/ var QTags, edButtons = [], edCanvas, /** * Back-compat * * Define all former global functions so plugins that hack quicktags.js directly don't cause fatal errors. */ edAddTag = function(){}, edCheckOpenTags = function(){}, edCloseAllTags = function(){}, edInsertImage = function(){}, edInsertLink = function(){}, edInsertTag = function(){}, edLink = function(){}, edQuickLink = function(){}, edRemoveTag = function(){}, edShowButton = function(){}, edShowLinks = function(){}, edSpell = function(){}, edToolbar = function(){}; /** * Initialize new instance of the Quicktags editor */ function quicktags(settings) { return new QTags(settings); } /** * Inserts content at the caret in the active editor (textarea) * * Added for back compatibility * @see QTags.insertContent() */ function edInsertContent(bah, txt) { return QTags.insertContent(txt); } /** * Adds a button to all instances of the editor * * Added for back compatibility, use QTags.addButton() as it gives more flexibility like type of button, button placement, etc. * @see QTags.addButton() */ function edButton(id, display, tagStart, tagEnd, access, open) { return QTags.addButton( id, display, tagStart, tagEnd, access, '', -1 ); } (function(){ // private stuff is prefixed with an underscore var _domReady = function(func) { var t, i, DOMContentLoaded; if ( typeof jQuery != 'undefined' ) { jQuery(document).ready(func); } else { t = _domReady; t.funcs = []; t.ready = function() { if ( ! t.isReady ) { t.isReady = true; for ( i = 0; i < t.funcs.length; i++ ) { t.funcs[i](); } } }; if ( t.isReady ) { func(); } else { t.funcs.push(func); } if ( ! t.eventAttached ) { if ( document.addEventListener ) { DOMContentLoaded = function(){document.removeEventListener('DOMContentLoaded', DOMContentLoaded, false);t.ready();}; document.addEventListener('DOMContentLoaded', DOMContentLoaded, false); window.addEventListener('load', t.ready, false); } else if ( document.attachEvent ) { DOMContentLoaded = function(){if (document.readyState === 'complete'){ document.detachEvent('onreadystatechange', DOMContentLoaded);t.ready();}}; document.attachEvent('onreadystatechange', DOMContentLoaded); window.attachEvent('onload', t.ready); (function(){ try { document.documentElement.doScroll("left"); } catch(e) { setTimeout(arguments.callee, 50); return; } t.ready(); })(); } t.eventAttached = true; } } }, _datetime = (function() { var now = new Date(), zeroise; zeroise = function(number) { var str = number.toString(); if ( str.length < 2 ) str = "0" + str; return str; } return now.getUTCFullYear() + '-' + zeroise( now.getUTCMonth() + 1 ) + '-' + zeroise( now.getUTCDate() ) + 'T' + zeroise( now.getUTCHours() ) + ':' + zeroise( now.getUTCMinutes() ) + ':' + zeroise( now.getUTCSeconds() ) + '+00:00'; })(), qt; qt = QTags = function(settings) { if ( typeof(settings) == 'string' ) settings = {id: settings}; else if ( typeof(settings) != 'object' ) return false; var t = this, id = settings.id, canvas = document.getElementById(id), name = 'qt_' + id, tb, onclick, toolbar_id; if ( !id || !canvas ) return false; t.name = name; t.id = id; t.canvas = canvas; t.settings = settings; if ( id == 'content' && typeof(adminpage) == 'string' && ( adminpage == 'post-new-php' || adminpage == 'post-php' ) ) { // back compat hack :-( edCanvas = canvas; toolbar_id = 'ed_toolbar'; } else { toolbar_id = name + '_toolbar'; } tb = document.createElement('div'); tb.id = toolbar_id; tb.className = 'quicktags-toolbar'; canvas.parentNode.insertBefore(tb, canvas); t.toolbar = tb; // listen for click events onclick = function(e) { e = e || window.event; var target = e.target || e.srcElement, visible = target.clientWidth || target.offsetWidth, i; // don't call the callback on pressing the accesskey when the button is not visible if ( !visible ) return; // as long as it has the class ed_button, execute the callback if ( / ed_button /.test(' ' + target.className + ' ') ) { // we have to reassign canvas here t.canvas = canvas = document.getElementById(id); i = target.id.replace(name + '_', ''); if ( t.theButtons[i] ) t.theButtons[i].callback.call(t.theButtons[i], target, canvas, t); } }; if ( tb.addEventListener ) { tb.addEventListener('click', onclick, false); } else if ( tb.attachEvent ) { tb.attachEvent('onclick', onclick); } t.getButton = function(id) { return t.theButtons[id]; }; t.getButtonElement = function(id) { return document.getElementById(name + '_' + id); }; qt.instances[id] = t; if ( !qt.instances[0] ) { qt.instances[0] = qt.instances[id]; _domReady( function(){ qt._buttonsInit(); } ); } }; qt.instances = {}; qt.getInstance = function(id) { return qt.instances[id]; }; qt._buttonsInit = function() { var t = this, canvas, name, settings, theButtons, html, inst, ed, id, i, use, defaults = ',strong,em,link,block,del,ins,img,ul,ol,li,code,more,close,'; for ( inst in t.instances ) { if ( inst == 0 ) continue; ed = t.instances[inst]; canvas = ed.canvas; name = ed.name; settings = ed.settings; html = ''; theButtons = {}; use = ''; // set buttons if ( settings.buttons ) use = ','+settings.buttons+','; for ( i in edButtons ) { if ( !edButtons[i] ) continue; id = edButtons[i].id; if ( use && defaults.indexOf(','+id+',') != -1 && use.indexOf(','+id+',') == -1 ) continue; if ( !edButtons[i].instance || edButtons[i].instance == inst ) { theButtons[id] = edButtons[i]; if ( edButtons[i].html ) html += edButtons[i].html(name + '_'); } } if ( use && use.indexOf(',fullscreen,') != -1 ) { theButtons['fullscreen'] = new qt.FullscreenButton(); html += theButtons['fullscreen'].html(name + '_'); } if ( 'rtl' == document.getElementsByTagName('html')[0].dir ) { theButtons['textdirection'] = new qt.TextDirectionButton(); html += theButtons['textdirection'].html(name + '_'); } ed.toolbar.innerHTML = html; ed.theButtons = theButtons; } t.buttonsInitDone = true; }; /** * Main API function for adding a button to Quicktags * * Adds qt.Button or qt.TagButton depending on the args. The first three args are always required. * To be able to add button(s) to Quicktags, your script should be enqueued as dependent * on "quicktags" and outputted in the footer. If you are echoing JS directly from PHP, * use add_action( 'admin_print_footer_scripts', 'output_my_js', 100 ) or add_action( 'wp_footer', 'output_my_js', 100 ) * * Minimum required to add a button that calls an external function: * QTags.addButton( 'my_id', 'my button', my_callback ); * function my_callback() { alert('yeah!'); } * * Minimum required to add a button that inserts a tag: * QTags.addButton( 'my_id', 'my button', '<span>', '</span>' ); * QTags.addButton( 'my_id2', 'my button', '<br />' ); * * @param string id Required. Button HTML ID * @param string display Required. Button's value="..." * @param string|function arg1 Required. Either a starting tag to be inserted like "<span>" or a callback that is executed when the button is clicked. * @param string arg2 Optional. Ending tag like "</span>" * @param string access_key Optional. Access key for the button. * @param string title Optional. Button's title="..." * @param int priority Optional. Number representing the desired position of the button in the toolbar. 1 - 9 = first, 11 - 19 = second, 21 - 29 = third, etc. * @param string instance Optional. Limit the button to a specifric instance of Quicktags, add to all instances if not present. * @return mixed null or the button object that is needed for back-compat. */ qt.addButton = function( id, display, arg1, arg2, access_key, title, priority, instance ) { var btn; if ( !id || !display ) return; priority = priority || 0; arg2 = arg2 || ''; if ( typeof(arg1) === 'function' ) { btn = new qt.Button(id, display, access_key, title, instance); btn.callback = arg1; } else if ( typeof(arg1) === 'string' ) { btn = new qt.TagButton(id, display, arg1, arg2, access_key, title, instance); } else { return; } if ( priority == -1 ) // back-compat return btn; if ( priority > 0 ) { while ( typeof(edButtons[priority]) != 'undefined' ) { priority++ } edButtons[priority] = btn; } else { edButtons[edButtons.length] = btn; } if ( this.buttonsInitDone ) this._buttonsInit(); // add the button HTML to all instances toolbars if addButton() was called too late }; qt.insertContent = function(content) { var sel, startPos, endPos, scrollTop, text, canvas = document.getElementById(wpActiveEditor); if ( !canvas ) return false; if ( document.selection ) { //IE canvas.focus(); sel = document.selection.createRange(); sel.text = content; canvas.focus(); } else if ( canvas.selectionStart || canvas.selectionStart == '0' ) { // FF, WebKit, Opera text = canvas.value; startPos = canvas.selectionStart; endPos = canvas.selectionEnd; scrollTop = canvas.scrollTop; canvas.value = text.substring(0, startPos) + content + text.substring(endPos, text.length); canvas.focus(); canvas.selectionStart = startPos + content.length; canvas.selectionEnd = startPos + content.length; canvas.scrollTop = scrollTop; } else { canvas.value += content; canvas.focus(); } return true; }; // a plain, dumb button qt.Button = function(id, display, access, title, instance) { var t = this; t.id = id; t.display = display; t.access = access; t.title = title || ''; t.instance = instance || ''; }; qt.Button.prototype.html = function(idPrefix) { var access = this.access ? ' accesskey="' + this.access + '"' : ''; return '<input type="button" id="' + idPrefix + this.id + '"' + access + ' class="ed_button" title="' + this.title + '" value="' + this.display + '" />'; }; qt.Button.prototype.callback = function(){}; // a button that inserts HTML tag qt.TagButton = function(id, display, tagStart, tagEnd, access, title, instance) { var t = this; qt.Button.call(t, id, display, access, title, instance); t.tagStart = tagStart; t.tagEnd = tagEnd; }; qt.TagButton.prototype = new qt.Button(); qt.TagButton.prototype.openTag = function(e, ed) { var t = this; if ( ! ed.openTags ) { ed.openTags = []; } if ( t.tagEnd ) { ed.openTags.push(t.id); e.value = '/' + e.value; } }; qt.TagButton.prototype.closeTag = function(e, ed) { var t = this, i = t.isOpen(ed); if ( i !== false ) { ed.openTags.splice(i, 1); } e.value = t.display; }; // whether a tag is open or not. Returns false if not open, or current open depth of the tag qt.TagButton.prototype.isOpen = function (ed) { var t = this, i = 0, ret = false; if ( ed.openTags ) { while ( ret === false && i < ed.openTags.length ) { ret = ed.openTags[i] == t.id ? i : false; i ++; } } else { ret = false; } return ret; }; qt.TagButton.prototype.callback = function(element, canvas, ed) { var t = this, startPos, endPos, cursorPos, scrollTop, v = canvas.value, l, r, i, sel, endTag = v ? t.tagEnd : ''; if ( document.selection ) { // IE canvas.focus(); sel = document.selection.createRange(); if ( sel.text.length > 0 ) { if ( !t.tagEnd ) sel.text = sel.text + t.tagStart; else sel.text = t.tagStart + sel.text + endTag; } else { if ( !t.tagEnd ) { sel.text = t.tagStart; } else if ( t.isOpen(ed) === false ) { sel.text = t.tagStart; t.openTag(element, ed); } else { sel.text = endTag; t.closeTag(element, ed); } } canvas.focus(); } else if ( canvas.selectionStart || canvas.selectionStart == '0' ) { // FF, WebKit, Opera startPos = canvas.selectionStart; endPos = canvas.selectionEnd; cursorPos = endPos; scrollTop = canvas.scrollTop; l = v.substring(0, startPos); // left of the selection r = v.substring(endPos, v.length); // right of the selection i = v.substring(startPos, endPos); // inside the selection if ( startPos != endPos ) { if ( !t.tagEnd ) { canvas.value = l + i + t.tagStart + r; // insert self closing tags after the selection cursorPos += t.tagStart.length; } else { canvas.value = l + t.tagStart + i + endTag + r; cursorPos += t.tagStart.length + endTag.length; } } else { if ( !t.tagEnd ) { canvas.value = l + t.tagStart + r; cursorPos = startPos + t.tagStart.length; } else if ( t.isOpen(ed) === false ) { canvas.value = l + t.tagStart + r; t.openTag(element, ed); cursorPos = startPos + t.tagStart.length; } else { canvas.value = l + endTag + r; cursorPos = startPos + endTag.length; t.closeTag(element, ed); } } canvas.focus(); canvas.selectionStart = cursorPos; canvas.selectionEnd = cursorPos; canvas.scrollTop = scrollTop; } else { // other browsers? if ( !endTag ) { canvas.value += t.tagStart; } else if ( t.isOpen(ed) !== false ) { canvas.value += t.tagStart; t.openTag(element, ed); } else { canvas.value += endTag; t.closeTag(element, ed); } canvas.focus(); } }; // removed qt.SpellButton = function() {}; // the close tags button qt.CloseButton = function() { qt.Button.call(this, 'close', quicktagsL10n.closeTags, '', quicktagsL10n.closeAllOpenTags); }; qt.CloseButton.prototype = new qt.Button(); qt._close = function(e, c, ed) { var button, element, tbo = ed.openTags; if ( tbo ) { while ( tbo.length > 0 ) { button = ed.getButton(tbo[tbo.length - 1]); element = document.getElementById(ed.name + '_' + button.id); if ( e ) button.callback.call(button, element, c, ed); else button.closeTag(element, ed); } } }; qt.CloseButton.prototype.callback = qt._close; qt.closeAllTags = function(editor_id) { var ed = this.getInstance(editor_id); qt._close('', ed.canvas, ed); }; // the link button qt.LinkButton = function() { qt.TagButton.call(this, 'link', 'link', '', '</a>', 'a'); }; qt.LinkButton.prototype = new qt.TagButton(); qt.LinkButton.prototype.callback = function(e, c, ed, defaultValue) { var URL, t = this; if ( typeof(wpLink) != 'undefined' ) { wpLink.open(); return; } if ( ! defaultValue ) defaultValue = 'http://'; if ( t.isOpen(ed) === false ) { URL = prompt(quicktagsL10n.enterURL, defaultValue); if ( URL ) { t.tagStart = '<a href="' + URL + '">'; qt.TagButton.prototype.callback.call(t, e, c, ed); } } else { qt.TagButton.prototype.callback.call(t, e, c, ed); } }; // the img button qt.ImgButton = function() { qt.TagButton.call(this, 'img', 'img', '', '', 'm'); }; qt.ImgButton.prototype = new qt.TagButton(); qt.ImgButton.prototype.callback = function(e, c, ed, defaultValue) { if ( ! defaultValue ) { defaultValue = 'http://'; } var src = prompt(quicktagsL10n.enterImageURL, defaultValue), alt; if ( src ) { alt = prompt(quicktagsL10n.enterImageDescription, ''); this.tagStart = '<img src="' + src + '" alt="' + alt + '" />'; qt.TagButton.prototype.callback.call(this, e, c, ed); } }; qt.FullscreenButton = function() { qt.Button.call(this, 'fullscreen', quicktagsL10n.fullscreen, 'f', quicktagsL10n.toggleFullscreen); }; qt.FullscreenButton.prototype = new qt.Button(); qt.FullscreenButton.prototype.callback = function(e, c) { if ( !c.id || typeof(fullscreen) == 'undefined' ) return; fullscreen.on(); }; qt.TextDirectionButton = function() { qt.Button.call(this, 'textdirection', quicktagsL10n.textdirection, '', quicktagsL10n.toggleTextdirection) }; qt.TextDirectionButton.prototype = new qt.Button(); qt.TextDirectionButton.prototype.callback = function(e, c) { var isRTL = ( 'rtl' == document.getElementsByTagName('html')[0].dir ), currentDirection = c.style.direction; if ( ! currentDirection ) currentDirection = ( isRTL ) ? 'rtl' : 'ltr'; c.style.direction = ( 'rtl' == currentDirection ) ? 'ltr' : 'rtl'; c.focus(); } // ensure backward compatibility edButtons[10] = new qt.TagButton('strong','b','<strong>','</strong>','b'); edButtons[20] = new qt.TagButton('em','i','<em>','</em>','i'), edButtons[30] = new qt.LinkButton(), // special case edButtons[40] = new qt.TagButton('block','b-quote','\n\n<blockquote>','</blockquote>\n\n','q'), edButtons[50] = new qt.TagButton('del','del','<del datetime="' + _datetime + '">','</del>','d'), edButtons[60] = new qt.TagButton('ins','ins','<ins datetime="' + _datetime + '">','</ins>','s'), edButtons[70] = new qt.ImgButton(), // special case edButtons[80] = new qt.TagButton('ul','ul','<ul>\n','</ul>\n\n','u'), edButtons[90] = new qt.TagButton('ol','ol','<ol>\n','</ol>\n\n','o'), edButtons[100] = new qt.TagButton('li','li','\t<li>','</li>\n','l'), edButtons[110] = new qt.TagButton('code','code','<code>','</code>','c'), edButtons[120] = new qt.TagButton('more','more','<!--more-->','','t'), edButtons[140] = new qt.CloseButton() })();
JavaScript
window.wp = window.wp || {}; (function ($) { // Check for the utility settings. var settings = typeof _wpUtilSettings === 'undefined' ? {} : _wpUtilSettings; /** * wp.template( id ) * * Fetches a template by id. * * @param {string} id A string that corresponds to a DOM element with an id prefixed with "tmpl-". * For example, "attachment" maps to "tmpl-attachment". * @return {function} A function that lazily-compiles the template requested. */ wp.template = _.memoize(function ( id ) { var compiled, options = { evaluate: /<#([\s\S]+?)#>/g, interpolate: /\{\{\{([\s\S]+?)\}\}\}/g, escape: /\{\{([^\}]+?)\}\}(?!\})/g, variable: 'data' }; return function ( data ) { compiled = compiled || _.template( $( '#tmpl-' + id ).html(), null, options ); return compiled( data ); }; }); // wp.ajax // ------ // // Tools for sending ajax requests with JSON responses and built in error handling. // Mirrors and wraps jQuery's ajax APIs. wp.ajax = { settings: settings.ajax || {}, /** * wp.ajax.post( [action], [data] ) * * Sends a POST request to WordPress. * * @param {string} action The slug of the action to fire in WordPress. * @param {object} data The data to populate $_POST with. * @return {$.promise} A jQuery promise that represents the request. */ post: function( action, data ) { return wp.ajax.send({ data: _.isObject( action ) ? action : _.extend( data || {}, { action: action }) }); }, /** * wp.ajax.send( [action], [options] ) * * Sends a POST request to WordPress. * * @param {string} action The slug of the action to fire in WordPress. * @param {object} options The options passed to jQuery.ajax. * @return {$.promise} A jQuery promise that represents the request. */ send: function( action, options ) { if ( _.isObject( action ) ) { options = action; } else { options = options || {}; options.data = _.extend( options.data || {}, { action: action }); } options = _.defaults( options || {}, { type: 'POST', url: wp.ajax.settings.url, context: this }); return $.Deferred( function( deferred ) { // Transfer success/error callbacks. if ( options.success ) deferred.done( options.success ); if ( options.error ) deferred.fail( options.error ); delete options.success; delete options.error; // Use with PHP's wp_send_json_success() and wp_send_json_error() $.ajax( options ).done( function( response ) { // Treat a response of `1` as successful for backwards // compatibility with existing handlers. if ( response === '1' || response === 1 ) response = { success: true }; if ( _.isObject( response ) && ! _.isUndefined( response.success ) ) deferred[ response.success ? 'resolveWith' : 'rejectWith' ]( this, [response.data] ); else deferred.rejectWith( this, [response] ); }).fail( function() { deferred.rejectWith( this, arguments ); }); }).promise(); } }; }(jQuery));
JavaScript
/** * Copyright (c) 2006, David Spurr (http://www.defusion.org.uk/) * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the David Spurr nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * http://www.opensource.org/licenses/bsd-license.php * * See scriptaculous.js for full scriptaculous licence */ var CropDraggable=Class.create(); Object.extend(Object.extend(CropDraggable.prototype,Draggable.prototype),{initialize:function(_1){ this.options=Object.extend({drawMethod:function(){ }},arguments[1]||{}); this.element=$(_1); this.handle=this.element; this.delta=this.currentDelta(); this.dragging=false; this.eventMouseDown=this.initDrag.bindAsEventListener(this); Event.observe(this.handle,"mousedown",this.eventMouseDown); Draggables.register(this); },draw:function(_2){ var _3=Position.cumulativeOffset(this.element); var d=this.currentDelta(); _3[0]-=d[0]; _3[1]-=d[1]; var p=[0,1].map(function(i){ return (_2[i]-_3[i]-this.offset[i]); }.bind(this)); this.options.drawMethod(p); }}); var Cropper={}; Cropper.Img=Class.create(); Cropper.Img.prototype={initialize:function(_7,_8){ this.options=Object.extend({ratioDim:{x:0,y:0},minWidth:0,minHeight:0,displayOnInit:false,onEndCrop:Prototype.emptyFunction,captureKeys:true},_8||{}); if(this.options.minWidth>0&&this.options.minHeight>0){ this.options.ratioDim.x=this.options.minWidth; this.options.ratioDim.y=this.options.minHeight; } this.img=$(_7); this.clickCoords={x:0,y:0}; this.dragging=false; this.resizing=false; this.isWebKit=/Konqueror|Safari|KHTML/.test(navigator.userAgent); this.isIE=/MSIE/.test(navigator.userAgent); this.isOpera8=/Opera\s[1-8]/.test(navigator.userAgent); this.ratioX=0; this.ratioY=0; this.attached=false; $A(document.getElementsByTagName("script")).each(function(s){ if(s.src.match(/cropper\.js/)){ var _a=s.src.replace(/cropper\.js(.*)?/,""); var _b=document.createElement("link"); _b.rel="stylesheet"; _b.type="text/css"; _b.href=_a+"cropper.css"; _b.media="screen"; document.getElementsByTagName("head")[0].appendChild(_b); } }); if(this.options.ratioDim.x>0&&this.options.ratioDim.y>0){ var _c=this.getGCD(this.options.ratioDim.x,this.options.ratioDim.y); this.ratioX=this.options.ratioDim.x/_c; this.ratioY=this.options.ratioDim.y/_c; } this.subInitialize(); if(this.img.complete||this.isWebKit){ this.onLoad(); }else{ Event.observe(this.img,"load",this.onLoad.bindAsEventListener(this)); } },getGCD:function(a,b){return 1; if(b==0){ return a; } return this.getGCD(b,a%b); },onLoad:function(){ var _f="imgCrop_"; var _10=this.img.parentNode; var _11=""; if(this.isOpera8){ _11=" opera8"; } this.imgWrap=Builder.node("div",{"class":_f+"wrap"+_11}); if(this.isIE){ this.north=Builder.node("div",{"class":_f+"overlay "+_f+"north"},[Builder.node("span")]); this.east=Builder.node("div",{"class":_f+"overlay "+_f+"east"},[Builder.node("span")]); this.south=Builder.node("div",{"class":_f+"overlay "+_f+"south"},[Builder.node("span")]); this.west=Builder.node("div",{"class":_f+"overlay "+_f+"west"},[Builder.node("span")]); var _12=[this.north,this.east,this.south,this.west]; }else{ this.overlay=Builder.node("div",{"class":_f+"overlay"}); var _12=[this.overlay]; } this.dragArea=Builder.node("div",{"class":_f+"dragArea"},_12); this.handleN=Builder.node("div",{"class":_f+"handle "+_f+"handleN"}); this.handleNE=Builder.node("div",{"class":_f+"handle "+_f+"handleNE"}); this.handleE=Builder.node("div",{"class":_f+"handle "+_f+"handleE"}); this.handleSE=Builder.node("div",{"class":_f+"handle "+_f+"handleSE"}); this.handleS=Builder.node("div",{"class":_f+"handle "+_f+"handleS"}); this.handleSW=Builder.node("div",{"class":_f+"handle "+_f+"handleSW"}); this.handleW=Builder.node("div",{"class":_f+"handle "+_f+"handleW"}); this.handleNW=Builder.node("div",{"class":_f+"handle "+_f+"handleNW"}); this.selArea=Builder.node("div",{"class":_f+"selArea"},[Builder.node("div",{"class":_f+"marqueeHoriz "+_f+"marqueeNorth"},[Builder.node("span")]),Builder.node("div",{"class":_f+"marqueeVert "+_f+"marqueeEast"},[Builder.node("span")]),Builder.node("div",{"class":_f+"marqueeHoriz "+_f+"marqueeSouth"},[Builder.node("span")]),Builder.node("div",{"class":_f+"marqueeVert "+_f+"marqueeWest"},[Builder.node("span")]),this.handleN,this.handleNE,this.handleE,this.handleSE,this.handleS,this.handleSW,this.handleW,this.handleNW,Builder.node("div",{"class":_f+"clickArea"})]); Element.setStyle($(this.selArea),{backgroundColor:"transparent",backgroundRepeat:"no-repeat",backgroundPosition:"0 0"}); this.imgWrap.appendChild(this.img); this.imgWrap.appendChild(this.dragArea); this.dragArea.appendChild(this.selArea); this.dragArea.appendChild(Builder.node("div",{"class":_f+"clickArea"})); _10.appendChild(this.imgWrap); Event.observe(this.dragArea,"mousedown",this.startDrag.bindAsEventListener(this)); Event.observe(document,"mousemove",this.onDrag.bindAsEventListener(this)); Event.observe(document,"mouseup",this.endCrop.bindAsEventListener(this)); var _13=[this.handleN,this.handleNE,this.handleE,this.handleSE,this.handleS,this.handleSW,this.handleW,this.handleNW]; for(var i=0;i<_13.length;i++){ Event.observe(_13[i],"mousedown",this.startResize.bindAsEventListener(this)); } if(this.options.captureKeys){ Event.observe(document,"keydown",this.handleKeys.bindAsEventListener(this)); } new CropDraggable(this.selArea,{drawMethod:this.moveArea.bindAsEventListener(this)}); this.setParams(); },setParams:function(){ this.imgW=this.img.width; this.imgH=this.img.height; if(!this.isIE){ Element.setStyle($(this.overlay),{width:this.imgW+"px",height:this.imgH+"px"}); Element.hide($(this.overlay)); Element.setStyle($(this.selArea),{backgroundImage:"url("+this.img.src+")"}); }else{ Element.setStyle($(this.north),{height:0}); Element.setStyle($(this.east),{width:0,height:0}); Element.setStyle($(this.south),{height:0}); Element.setStyle($(this.west),{width:0,height:0}); } Element.setStyle($(this.imgWrap),{"width":this.imgW+"px","height":this.imgH+"px"}); Element.hide($(this.selArea)); var _15=Position.positionedOffset(this.imgWrap); this.wrapOffsets={"top":_15[1],"left":_15[0]}; var _16={x1:0,y1:0,x2:0,y2:0}; this.setAreaCoords(_16); if(this.options.ratioDim.x>0&&this.options.ratioDim.y>0&&this.options.displayOnInit){ _16.x1=Math.ceil((this.imgW-this.options.ratioDim.x)/2); _16.y1=Math.ceil((this.imgH-this.options.ratioDim.y)/2); _16.x2=_16.x1+this.options.ratioDim.x; _16.y2=_16.y1+this.options.ratioDim.y; Element.show(this.selArea); this.drawArea(); this.endCrop(); } this.attached=true; },remove:function(){ this.attached=false; this.imgWrap.parentNode.insertBefore(this.img,this.imgWrap); this.imgWrap.parentNode.removeChild(this.imgWrap); Event.stopObserving(this.dragArea,"mousedown",this.startDrag.bindAsEventListener(this)); Event.stopObserving(document,"mousemove",this.onDrag.bindAsEventListener(this)); Event.stopObserving(document,"mouseup",this.endCrop.bindAsEventListener(this)); var _17=[this.handleN,this.handleNE,this.handleE,this.handleSE,this.handleS,this.handleSW,this.handleW,this.handleNW]; for(var i=0;i<_17.length;i++){ Event.stopObserving(_17[i],"mousedown",this.startResize.bindAsEventListener(this)); } if(this.options.captureKeys){ Event.stopObserving(document,"keydown",this.handleKeys.bindAsEventListener(this)); } },reset:function(){ if(!this.attached){ this.onLoad(); }else{ this.setParams(); } this.endCrop(); },handleKeys:function(e){ var dir={x:0,y:0}; if(!this.dragging){ switch(e.keyCode){ case (37): dir.x=-1; break; case (38): dir.y=-1; break; case (39): dir.x=1; break; case (40): dir.y=1; break; } if(dir.x!=0||dir.y!=0){ if(e.shiftKey){ dir.x*=10; dir.y*=10; } this.moveArea([this.areaCoords.x1+dir.x,this.areaCoords.y1+dir.y]); Event.stop(e); } } },calcW:function(){ return (this.areaCoords.x2-this.areaCoords.x1); },calcH:function(){ return (this.areaCoords.y2-this.areaCoords.y1); },moveArea:function(_1b){ this.setAreaCoords({x1:_1b[0],y1:_1b[1],x2:_1b[0]+this.calcW(),y2:_1b[1]+this.calcH()},true); this.drawArea(); },cloneCoords:function(_1c){ return {x1:_1c.x1,y1:_1c.y1,x2:_1c.x2,y2:_1c.y2}; },setAreaCoords:function(_1d,_1e,_1f,_20,_21){ var _22=typeof _1e!="undefined"?_1e:false; var _23=typeof _1f!="undefined"?_1f:false; if(_1e){ var _24=_1d.x2-_1d.x1; var _25=_1d.y2-_1d.y1; if(_1d.x1<0){ _1d.x1=0; _1d.x2=_24; } if(_1d.y1<0){ _1d.y1=0; _1d.y2=_25; } if(_1d.x2>this.imgW){ _1d.x2=this.imgW; _1d.x1=this.imgW-_24; } if(_1d.y2>this.imgH){ _1d.y2=this.imgH; _1d.y1=this.imgH-_25; } }else{ if(_1d.x1<0){ _1d.x1=0; } if(_1d.y1<0){ _1d.y1=0; } if(_1d.x2>this.imgW){ _1d.x2=this.imgW; } if(_1d.y2>this.imgH){ _1d.y2=this.imgH; } if(typeof (_20)!="undefined"){ if(this.ratioX>0){ this.applyRatio(_1d,{x:this.ratioX,y:this.ratioY},_20,_21); }else{ if(_23){ this.applyRatio(_1d,{x:1,y:1},_20,_21); } } var _26={a1:_1d.x1,a2:_1d.x2}; var _27={a1:_1d.y1,a2:_1d.y2}; var _28=this.options.minWidth; var _29=this.options.minHeight; if((_28==0||_29==0)&&_23){ if(_28>0){ _29=_28; }else{ if(_29>0){ _28=_29; } } } this.applyMinDimension(_26,_28,_20.x,{min:0,max:this.imgW}); this.applyMinDimension(_27,_29,_20.y,{min:0,max:this.imgH}); _1d={x1:_26.a1,y1:_27.a1,x2:_26.a2,y2:_27.a2}; } } this.areaCoords=_1d; },applyMinDimension:function(_2a,_2b,_2c,_2d){ if((_2a.a2-_2a.a1)<_2b){ if(_2c==1){ _2a.a2=_2a.a1+_2b; }else{ _2a.a1=_2a.a2-_2b; } if(_2a.a1<_2d.min){ _2a.a1=_2d.min; _2a.a2=_2b; }else{ if(_2a.a2>_2d.max){ _2a.a1=_2d.max-_2b; _2a.a2=_2d.max; } } } },applyRatio:function(_2e,_2f,_30,_31){ var _32; if(_31=="N"||_31=="S"){ _32=this.applyRatioToAxis({a1:_2e.y1,b1:_2e.x1,a2:_2e.y2,b2:_2e.x2},{a:_2f.y,b:_2f.x},{a:_30.y,b:_30.x},{min:0,max:this.imgW}); _2e.x1=_32.b1; _2e.y1=_32.a1; _2e.x2=_32.b2; _2e.y2=_32.a2; }else{ _32=this.applyRatioToAxis({a1:_2e.x1,b1:_2e.y1,a2:_2e.x2,b2:_2e.y2},{a:_2f.x,b:_2f.y},{a:_30.x,b:_30.y},{min:0,max:this.imgH}); _2e.x1=_32.a1; _2e.y1=_32.b1; _2e.x2=_32.a2; _2e.y2=_32.b2; } },applyRatioToAxis:function(_33,_34,_35,_36){ var _37=Object.extend(_33,{}); var _38=_37.a2-_37.a1; var _3a=Math.floor(_38*_34.b/_34.a); var _3b; var _3c; var _3d=null; if(_35.b==1){ _3b=_37.b1+_3a; if(_3b>_36.max){ _3b=_36.max; _3d=_3b-_37.b1; } _37.b2=_3b; }else{ _3b=_37.b2-_3a; if(_3b<_36.min){ _3b=_36.min; _3d=_3b+_37.b2; } _37.b1=_3b; } if(_3d!=null){ _3c=Math.floor(_3d*_34.a/_34.b); if(_35.a==1){ _37.a2=_37.a1+_3c; }else{ _37.a1=_37.a1=_37.a2-_3c; } } return _37; },drawArea:function(){ if(!this.isIE){ Element.show($(this.overlay)); } var _3e=this.calcW(); var _3f=this.calcH(); var _40=this.areaCoords.x2; var _41=this.areaCoords.y2; var _42=this.selArea.style; _42.left=this.areaCoords.x1+"px"; _42.top=this.areaCoords.y1+"px"; _42.width=_3e+"px"; _42.height=_3f+"px"; var _43=Math.ceil((_3e-6)/2)+"px"; var _44=Math.ceil((_3f-6)/2)+"px"; this.handleN.style.left=_43; this.handleE.style.top=_44; this.handleS.style.left=_43; this.handleW.style.top=_44; if(this.isIE){ this.north.style.height=this.areaCoords.y1+"px"; var _45=this.east.style; _45.top=this.areaCoords.y1+"px"; _45.height=_3f+"px"; _45.left=_40+"px"; _45.width=(this.img.width-_40)+"px"; var _46=this.south.style; _46.top=_41+"px"; _46.height=(this.img.height-_41)+"px"; var _47=this.west.style; _47.top=this.areaCoords.y1+"px"; _47.height=_3f+"px"; _47.width=this.areaCoords.x1+"px"; }else{ _42.backgroundPosition="-"+this.areaCoords.x1+"px "+"-"+this.areaCoords.y1+"px"; } this.subDrawArea(); this.forceReRender(); },forceReRender:function(){ if(this.isIE||this.isWebKit){ var n=document.createTextNode(" "); var d,el,fixEL,i; if(this.isIE){ fixEl=this.selArea; }else{ if(this.isWebKit){ fixEl=document.getElementsByClassName("imgCrop_marqueeSouth",this.imgWrap)[0]; d=Builder.node("div",""); d.style.visibility="hidden"; var _4a=["SE","S","SW"]; for(i=0;i<_4a.length;i++){ el=document.getElementsByClassName("imgCrop_handle"+_4a[i],this.selArea)[0]; if(el.childNodes.length){ el.removeChild(el.childNodes[0]); } el.appendChild(d); } } } fixEl.appendChild(n); fixEl.removeChild(n); } },startResize:function(e){ this.startCoords=this.cloneCoords(this.areaCoords); this.resizing=true; this.resizeHandle=Element.classNames(Event.element(e)).toString().replace(/([^N|NE|E|SE|S|SW|W|NW])+/,""); Event.stop(e); },startDrag:function(e){ Element.show(this.selArea); this.clickCoords=this.getCurPos(e); this.setAreaCoords({x1:this.clickCoords.x,y1:this.clickCoords.y,x2:this.clickCoords.x,y2:this.clickCoords.y}); this.dragging=true; this.onDrag(e); Event.stop(e); },getCurPos:function(e){ return curPos={x:Event.pointerX(e)-this.wrapOffsets.left,y:Event.pointerY(e)-this.wrapOffsets.top}; },onDrag:function(e){ var _4f=null; if(this.dragging||this.resizing){ var _50=this.getCurPos(e); var _51=this.cloneCoords(this.areaCoords); var _52={x:1,y:1}; } if(this.dragging){ if(_50.x<this.clickCoords.x){ _52.x=-1; } if(_50.y<this.clickCoords.y){ _52.y=-1; } this.transformCoords(_50.x,this.clickCoords.x,_51,"x"); this.transformCoords(_50.y,this.clickCoords.y,_51,"y"); }else{ if(this.resizing){ _4f=this.resizeHandle; if(_4f.match(/E/)){ this.transformCoords(_50.x,this.startCoords.x1,_51,"x"); if(_50.x<this.startCoords.x1){ _52.x=-1; } }else{ if(_4f.match(/W/)){ this.transformCoords(_50.x,this.startCoords.x2,_51,"x"); if(_50.x<this.startCoords.x2){ _52.x=-1; } } } if(_4f.match(/N/)){ this.transformCoords(_50.y,this.startCoords.y2,_51,"y"); if(_50.y<this.startCoords.y2){ _52.y=-1; } }else{ if(_4f.match(/S/)){ this.transformCoords(_50.y,this.startCoords.y1,_51,"y"); if(_50.y<this.startCoords.y1){ _52.y=-1; } } } } } if(this.dragging||this.resizing){ this.setAreaCoords(_51,false,e.shiftKey,_52,_4f); this.drawArea(); Event.stop(e); } },transformCoords:function(_53,_54,_55,_56){ var _57=new Array(); if(_53<_54){ _57[0]=_53; _57[1]=_54; }else{ _57[0]=_54; _57[1]=_53; } if(_56=="x"){ _55.x1=_57[0]; _55.x2=_57[1]; }else{ _55.y1=_57[0]; _55.y2=_57[1]; } },endCrop:function(){ this.dragging=false; this.resizing=false; this.options.onEndCrop(this.areaCoords,{width:this.calcW(),height:this.calcH()}); },subInitialize:function(){ },subDrawArea:function(){ }}; Cropper.ImgWithPreview=Class.create(); Object.extend(Object.extend(Cropper.ImgWithPreview.prototype,Cropper.Img.prototype),{subInitialize:function(){ this.hasPreviewImg=false; if(typeof (this.options.previewWrap)!="undefined"&&this.options.minWidth>0&&this.options.minHeight>0){ this.previewWrap=$(this.options.previewWrap); this.previewImg=this.img.cloneNode(false); this.options.displayOnInit=true; this.hasPreviewImg=true; Element.addClassName(this.previewWrap,"imgCrop_previewWrap"); Element.setStyle(this.previewWrap,{width:this.options.minWidth+"px",height:this.options.minHeight+"px"}); this.previewWrap.appendChild(this.previewImg); } },subDrawArea:function(){ if(this.hasPreviewImg){ var _58=this.calcW(); var _59=this.calcH(); var _5a={x:this.imgW/_58,y:this.imgH/_59}; var _5b={x:_58/this.options.minWidth,y:_59/this.options.minHeight}; var _5c={w:Math.ceil(this.options.minWidth*_5a.x)+"px",h:Math.ceil(this.options.minHeight*_5a.y)+"px",x:"-"+Math.ceil(this.areaCoords.x1/_5b.x)+"px",y:"-"+Math.ceil(this.areaCoords.y1/_5b.y)+"px"}; var _5d=this.previewImg.style; _5d.width=_5c.w; _5d.height=_5c.h; _5d.left=_5c.x; _5d.top=_5c.y; } }});
JavaScript
function mycarousel_initCallback(carousel) { jQuery('.jcarousel-control a').bind('click', function() { carousel.scroll(jQuery.jcarousel.intval(jQuery(this).text())); return false; }); jQuery('.jcarousel-scroll select').bind('change', function() { carousel.options.scroll = jQuery.jcarousel.intval(this.options[this.selectedIndex].value); return false; }); jQuery('#mycarousel-next').bind('click', function() { carousel.next(); return false; }); jQuery('#mycarousel-prev').bind('click', function() { carousel.prev(); return false; }); }; function mycarousel_initCallback2(carousel) { jQuery('.nav').bind('click', function() { carousel.scroll(jQuery.jcarousel.intval(jQuery(this).text())); return false; }); jQuery('.jcarousel-scroll select').bind('change', function() { carousel.options.scroll = jQuery.jcarousel.intval(this.options[this.selectedIndex].value); return false; }); }; jQuery(document).ready(function() { try { jQuery('.nav-menu li').hover(function(){jQuery(this).find('.hover').css("display","block");}, function(){jQuery('.nav-menu li img').css("display","none");}); } catch(err){} try { jQuery("#mycarousel").jcarousel({ scroll: 1, initCallback: mycarousel_initCallback, // This tells jCarousel NOT to autobuild prev/next buttons buttonNextHTML: null, buttonPrevHTML: null }); }catch(err) {} try { jQuery("#carousel").jcarousel({ scroll: 1, initCallback: mycarousel_initCallback2, // This tells jCarousel NOT to autobuild prev/next buttons buttonNextHTML: null, buttonPrevHTML: null }); }catch(err) {} try { jQuery("#parceiros-carousel").jcarousel({ scroll: 3 }); }catch(err) {} var current = 0; try { jQuery('.jcarousel-control a').click(function(){ jQuery('.jcarousel-control a').removeClass('active'); jQuery(this).addClass('active'); var slideclicado = jQuery(this).index(); current = slideclicado; }); }catch(err) {} });
JavaScript
function mycarousel_initCallback(carousel) { jQuery('.jcarousel-control a').bind('click', function() { carousel.scroll(jQuery.jcarousel.intval(jQuery(this).text())); return false; }); jQuery('.jcarousel-scroll select').bind('change', function() { carousel.options.scroll = jQuery.jcarousel.intval(this.options[this.selectedIndex].value); return false; }); jQuery('#mycarousel-next').bind('click', function() { carousel.next(); return false; }); jQuery('#mycarousel-prev').bind('click', function() { carousel.prev(); return false; }); }; function mycarousel_initCallback2(carousel) { jQuery('.nav').bind('click', function() { carousel.scroll(jQuery.jcarousel.intval(jQuery(this).text())); return false; }); jQuery('.jcarousel-scroll select').bind('change', function() { carousel.options.scroll = jQuery.jcarousel.intval(this.options[this.selectedIndex].value); return false; }); }; jQuery(document).ready(function() { try { jQuery('.nav-menu li').hover(function(){jQuery(this).find('.hover').css("display","block");}, function(){jQuery('.nav-menu li img').css("display","none");}); } catch(err){} try { jQuery("#mycarousel").jcarousel({ scroll: 1, initCallback: mycarousel_initCallback, // This tells jCarousel NOT to autobuild prev/next buttons buttonNextHTML: null, buttonPrevHTML: null }); }catch(err) {} try { jQuery("#carousel").jcarousel({ scroll: 1, initCallback: mycarousel_initCallback2, // This tells jCarousel NOT to autobuild prev/next buttons buttonNextHTML: null, buttonPrevHTML: null }); }catch(err) {} try { jQuery("#parceiros-carousel").jcarousel({ scroll: 1 }); }catch(err) {} var current = 0; try { jQuery('.jcarousel-control a').click(function(){ jQuery('.jcarousel-control a').removeClass('active'); jQuery(this).addClass('active'); var slideclicado = jQuery(this).index(); current = slideclicado; }); }catch(err) {} try { jQuery('li.parceiro-home div a').each(function() { var width = jQuery(this).find('img').width(); if(width>87){ var margin = (width - 87)/2; jQuery(this).find('img').css('margin-left', '-='+margin); } }); }catch(err) {} try { jQuery('.wrapper-img-brindes-home').each(function() { var height = jQuery(this).find('img').height(); if(height>73){ var margin = (height - 73)/2; jQuery(this).find('img').css('margin-top', '-='+margin); } }); }catch(err) {} try { quantidade_div = jQuery('.brindes-home-item>div').length; }catch(err) {} });
JavaScript
//+ Carlos R. L. Rodrigues //@ http://jsfromhell.com/forms/restrict [rev. #1] Restrict = function(form){ this.form = form, this.field = {}, this.mask = {}; } Restrict.field = Restrict.inst = Restrict.c = null; Restrict.prototype.start = function(){ var $, __ = document.forms[this.form], s, x, j, c, sp, o = this, l; var p = {".":/./, w:/\w/, W:/\W/, d:/\d/, D:/\D/, s:/\s/, a:/[\xc0-\xff]/, A:/[^\xc0-\xff]/}; var exp = /text|textarea|password/i; for(var _ in $ = this.field){ if(exp.test(__[_].type)){ x = $[_].split(""), c = j = 0, sp, s = [[],[]]; for(var i = 0, l = x.length; i < l; i++){ if(x[i] == "\\" || sp){ if(sp = !sp) continue; s[j][c++] = p[x[i]] || x[i]; }else if(x[i] == "^"){ c = (j = 1) - 1; }else{ s[j][c++] = x[i]; } } o.mask[__[_].name] && (__[_].maxLength = o.mask[__[_].name].length); __[_].pt = s, addEvent(__[_], "keydown", function(e){ var r = Restrict.field = e.target; if(!o.mask[r.name]) return; r.l = r.value.length, Restrict.inst = o; Restrict.c = e.key; setTimeout(o.onchanged, r.e = 1); }); addEvent(__[_], "keyup", function(e){ (Restrict.field = e.target).e = 0; }); addEvent( __[_], "keypress", function(e){ o.restrict(e) || e.preventDefault(); var r = Restrict.field = e.target; if(!o.mask[r.name]) return; if(!r.e){ r.l = r.value.length, Restrict.inst = o, Restrict.c = e.key || 0; setTimeout(o.onchanged, 1); } } ); } } } Restrict.prototype.restrict = function(e){ var o, c = e.key, n = (o = e.target).name, r; var has = function(c, r){ for(var i = r.length; i--;){ if((r[i] instanceof RegExp && r[i].test(c)) || r[i] == c) return true; } return false; }; var inRange = function(c){ return has(c, o.pt[0]) && !has(c, o.pt[1]); }; return (c < 30 || inRange(String.fromCharCode(c))) ? (this.onKeyAccept && this.onKeyAccept(o, c), !0) : (this.onKeyRefuse && this.onKeyRefuse(o, c), !1); } Restrict.prototype.onchanged = function(){ var ob = Restrict, si, moz = false, o = ob.field, t, lt = (t = o.value).length, m = ob.inst.mask[o.name]; if(o.l == o.value.length) return; if(si = o.selectionStart) moz = true; else if(o.createTextRange){ var obj = document.selection.createRange(), r = o.createTextRange(); if(!r.setEndPoint) return false; r.setEndPoint("EndToStart", obj); si = r.text.length; }else return false; for(var i in m = m.split("")) if(m[i] != "#") t = t.replace(m[i] == "\\" ? m[++i] : m[i], ""); var j = 0, h = "", l = m.length, ini = si == 1, t = t.split(""); for(i = 0; i < l; i++) if(m[i] != "#"){ if(m[i] == "\\" && (h += m[++i])) continue; h += m[i], i + 1 == l && (t[j - 1] += h, h = ""); } else{ if(!t[j] && !(h = "")) break; (t[j] = h + t[j++]) && (h = ""); } o.value = o.maxLength > -1 && o.maxLength < (t = t.join("")).length ? t.slice(0, o.maxLength) : t; if(ob.c && ob.c != 46 && ob.c != 8){ if(si != lt){ while(m[si] != "#" && m[si]) si++; ini && m[0] != "#" && si++; } else si = o.value.length; } !moz ? (obj.move("character", si), obj.select()) : o.setSelectionRange(si, si); } /* ************************************** * Event Listener Function v1.4 * * Autor: Carlos R. L. Rodrigues * ************************************** */ addEvent = function(o, e, f, s){ var r = o[r = "_" + (e = "on" + e)] = o[r] || (o[e] ? [[o[e], o]] : []), a, c, d; r[r.length] = [f, s || o], o[e] = function(e){ try{ (e = e || event).preventDefault || (e.preventDefault = function(){e.returnValue = false;}); e.stopPropagation || (e.stopPropagation = function(){e.cancelBubble = true;}); e.target || (e.target = e.srcElement || null); e.key = (e.which + 1 || e.keyCode + 1) - 1 || 0; }catch(f){} for(d = 1, f = r.length; f; r[--f] && (a = r[f][0], o = r[f][1], a.call ? c = a.call(o, e) : (o._ = a, c = o._(e), o._ = null), d &= c !== false)); return e = null, !!d; } }; removeEvent = function(o, e, f, s){ for(var i = (e = o["_on" + e] || []).length; i;){ if(e[--i] && e[i][0] == f && (s || o) == e[i][1]){ return delete e[i]; } } return false; };
JavaScript
/*! SWFObject v2.0 <http://code.google.com/p/swfobject/> Copyright (c) 2007 Geoff Stearns, Michael Williams, and Bobby van der Sluis This software is released under the MIT License <http://www.opensource.org/licenses/mit-license.php> */ var swfobject = function() { var UNDEF = "undefined", OBJECT = "object", SHOCKWAVE_FLASH = "Shockwave Flash", SHOCKWAVE_FLASH_AX = "ShockwaveFlash.ShockwaveFlash", FLASH_MIME_TYPE = "application/x-shockwave-flash", EXPRESS_INSTALL_ID = "SWFObjectExprInst", win = window, doc = document, nav = navigator, domLoadFnArr = [], regObjArr = [], timer = null, storedAltContent = null, storedAltContentId = null, isDomLoaded = false, isExpressInstallActive = false; /* Centralized function for browser feature detection - Proprietary feature detection (conditional compiling) is used to detect Internet Explorer's features - User agent string detection is only used when no alternative is possible - Is executed directly for optimal performance */ var ua = function() { var w3cdom = typeof doc.getElementById != UNDEF && typeof doc.getElementsByTagName != UNDEF && typeof doc.createElement != UNDEF && typeof doc.appendChild != UNDEF && typeof doc.replaceChild != UNDEF && typeof doc.removeChild != UNDEF && typeof doc.cloneNode != UNDEF, playerVersion = [0,0,0], d = null; if (typeof nav.plugins != UNDEF && typeof nav.plugins[SHOCKWAVE_FLASH] == OBJECT) { d = nav.plugins[SHOCKWAVE_FLASH].description; if (d) { d = d.replace(/^.*\s+(\S+\s+\S+$)/, "$1"); playerVersion[0] = parseInt(d.replace(/^(.*)\..*$/, "$1"), 10); playerVersion[1] = parseInt(d.replace(/^.*\.(.*)\s.*$/, "$1"), 10); playerVersion[2] = /r/.test(d) ? parseInt(d.replace(/^.*r(.*)$/, "$1"), 10) : 0; } } else if (typeof win.ActiveXObject != UNDEF) { var a = null, fp6Crash = false; try { a = new ActiveXObject(SHOCKWAVE_FLASH_AX + ".7"); } catch(e) { try { a = new ActiveXObject(SHOCKWAVE_FLASH_AX + ".6"); playerVersion = [6,0,21]; a.AllowScriptAccess = "always"; // Introduced in fp6.0.47 } catch(e) { if (playerVersion[0] == 6) { fp6Crash = true; } } if (!fp6Crash) { try { a = new ActiveXObject(SHOCKWAVE_FLASH_AX); } catch(e) {} } } if (!fp6Crash && a) { // a will return null when ActiveX is disabled try { d = a.GetVariable("$version"); // Will crash fp6.0.21/23/29 if (d) { d = d.split(" ")[1].split(","); playerVersion = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)]; } } catch(e) {} } } var u = nav.userAgent.toLowerCase(), p = nav.platform.toLowerCase(), webkit = /webkit/.test(u) ? parseFloat(u.replace(/^.*webkit\/(\d+(\.\d+)?).*$/, "$1")) : false, // returns either the webkit version or false if not webkit ie = false, windows = p ? /win/.test(p) : /win/.test(u), mac = p ? /mac/.test(p) : /mac/.test(u); /*@cc_on ie = true; @if (@_win32) windows = true; @elif (@_mac) mac = true; @end @*/ return { w3cdom:w3cdom, pv:playerVersion, webkit:webkit, ie:ie, win:windows, mac:mac }; }(); /* Cross-browser onDomLoad - Based on Dean Edwards' solution: http://dean.edwards.name/weblog/2006/06/again/ - Will fire an event as soon as the DOM of a page is loaded (supported by Gecko based browsers - like Firefox -, IE, Opera9+, Safari) */ var onDomLoad = function() { if (!ua.w3cdom) { return; } addDomLoadEvent(main); if (ua.ie && ua.win) { try { // Avoid a possible Operation Aborted error doc.write("<scr" + "ipt id=__ie_ondomload defer=true src=//:></scr" + "ipt>"); // String is split into pieces to avoid Norton AV to add code that can cause errors var s = getElementById("__ie_ondomload"); if (s) { s.onreadystatechange = function() { if (this.readyState == "complete") { this.parentNode.removeChild(this); callDomLoadFunctions(); } }; } } catch(e) {} } if (ua.webkit && typeof doc.readyState != UNDEF) { timer = setInterval(function() { if (/loaded|complete/.test(doc.readyState)) { callDomLoadFunctions(); }}, 10); } if (typeof doc.addEventListener != UNDEF) { doc.addEventListener("DOMContentLoaded", callDomLoadFunctions, null); } addLoadEvent(callDomLoadFunctions); }(); function callDomLoadFunctions() { if (isDomLoaded) { return; } if (ua.ie && ua.win) { // Test if we can really add elements to the DOM; we don't want to fire it too early var s = createElement("span"); try { // Avoid a possible Operation Aborted error var t = doc.getElementsByTagName("body")[0].appendChild(s); t.parentNode.removeChild(t); } catch (e) { return; } } isDomLoaded = true; if (timer) { clearInterval(timer); timer = null; } var dl = domLoadFnArr.length; for (var i = 0; i < dl; i++) { domLoadFnArr[i](); } } function addDomLoadEvent(fn) { if (isDomLoaded) { fn(); } else { domLoadFnArr[domLoadFnArr.length] = fn; // Array.push() is only available in IE5.5+ } } /* Cross-browser onload - Based on James Edwards' solution: http://brothercake.com/site/resources/scripts/onload/ - Will fire an event as soon as a web page including all of its assets are loaded */ function addLoadEvent(fn) { if (typeof win.addEventListener != UNDEF) { win.addEventListener("load", fn, false); } else if (typeof doc.addEventListener != UNDEF) { doc.addEventListener("load", fn, false); } else if (typeof win.attachEvent != UNDEF) { win.attachEvent("onload", fn); } else if (typeof win.onload == "function") { var fnOld = win.onload; win.onload = function() { fnOld(); fn(); }; } else { win.onload = fn; } } /* Main function - Will preferably execute onDomLoad, otherwise onload (as a fallback) */ function main() { // Static publishing only var rl = regObjArr.length; for (var i = 0; i < rl; i++) { // For each registered object element var id = regObjArr[i].id; if (ua.pv[0] > 0) { var obj = getElementById(id); if (obj) { regObjArr[i].width = obj.getAttribute("width") ? obj.getAttribute("width") : "0"; regObjArr[i].height = obj.getAttribute("height") ? obj.getAttribute("height") : "0"; if (hasPlayerVersion(regObjArr[i].swfVersion)) { // Flash plug-in version >= Flash content version: Houston, we have a match! if (ua.webkit && ua.webkit < 312) { // Older webkit engines ignore the object element's nested param elements fixParams(obj); } setVisibility(id, true); } else if (regObjArr[i].expressInstall && !isExpressInstallActive && hasPlayerVersion("6.0.65") && (ua.win || ua.mac)) { // Show the Adobe Express Install dialog if set by the web page author and if supported (fp6.0.65+ on Win/Mac OS only) showExpressInstall(regObjArr[i]); } else { // Flash plug-in and Flash content version mismatch: display alternative content instead of Flash content displayAltContent(obj); } } } else { // If no fp is installed, we let the object element do its job (show alternative content) setVisibility(id, true); } } } /* Fix nested param elements, which are ignored by older webkit engines - This includes Safari up to and including version 1.2.2 on Mac OS 10.3 - Fall back to the proprietary embed element */ function fixParams(obj) { var nestedObj = obj.getElementsByTagName(OBJECT)[0]; if (nestedObj) { var e = createElement("embed"), a = nestedObj.attributes; if (a) { var al = a.length; for (var i = 0; i < al; i++) { if (a[i].nodeName.toLowerCase() == "data") { e.setAttribute("src", a[i].nodeValue); } else { e.setAttribute(a[i].nodeName, a[i].nodeValue); } } } var c = nestedObj.childNodes; if (c) { var cl = c.length; for (var j = 0; j < cl; j++) { if (c[j].nodeType == 1 && c[j].nodeName.toLowerCase() == "param") { e.setAttribute(c[j].getAttribute("name"), c[j].getAttribute("value")); } } } obj.parentNode.replaceChild(e, obj); } } /* Fix hanging audio/video threads and force open sockets and NetConnections to disconnect - Occurs when unloading a web page in IE using fp8+ and innerHTML/outerHTML - Dynamic publishing only */ function fixObjectLeaks(id) { if (ua.ie && ua.win && hasPlayerVersion("8.0.0")) { win.attachEvent("onunload", function () { var obj = getElementById(id); if (obj) { for (var i in obj) { if (typeof obj[i] == "function") { obj[i] = function() {}; } } obj.parentNode.removeChild(obj); } }); } } /* Show the Adobe Express Install dialog - Reference: http://www.adobe.com/cfusion/knowledgebase/index.cfm?id=6a253b75 */ function showExpressInstall(regObj) { isExpressInstallActive = true; var obj = getElementById(regObj.id); if (obj) { if (regObj.altContentId) { var ac = getElementById(regObj.altContentId); if (ac) { storedAltContent = ac; storedAltContentId = regObj.altContentId; } } else { storedAltContent = abstractAltContent(obj); } if (!(/%$/.test(regObj.width)) && parseInt(regObj.width, 10) < 310) { regObj.width = "310"; } if (!(/%$/.test(regObj.height)) && parseInt(regObj.height, 10) < 137) { regObj.height = "137"; } doc.title = doc.title.slice(0, 47) + " - Flash Player Installation"; var pt = ua.ie && ua.win ? "ActiveX" : "PlugIn", dt = doc.title, fv = "MMredirectURL=" + win.location + "&MMplayerType=" + pt + "&MMdoctitle=" + dt, replaceId = regObj.id; // For IE when a SWF is loading (AND: not available in cache) wait for the onload event to fire to remove the original object element // In IE you cannot properly cancel a loading SWF file without breaking browser load references, also obj.onreadystatechange doesn't work if (ua.ie && ua.win && obj.readyState != 4) { var newObj = createElement("div"); replaceId += "SWFObjectNew"; newObj.setAttribute("id", replaceId); obj.parentNode.insertBefore(newObj, obj); // Insert placeholder div that will be replaced by the object element that loads expressinstall.swf obj.style.display = "none"; win.attachEvent("onload", function() { obj.parentNode.removeChild(obj); }); } createSWF({ data:regObj.expressInstall, id:EXPRESS_INSTALL_ID, width:regObj.width, height:regObj.height }, { flashvars:fv }, replaceId); } } /* Functions to abstract and display alternative content */ function displayAltContent(obj) { if (ua.ie && ua.win && obj.readyState != 4) { // For IE when a SWF is loading (AND: not available in cache) wait for the onload event to fire to remove the original object element // In IE you cannot properly cancel a loading SWF file without breaking browser load references, also obj.onreadystatechange doesn't work var el = createElement("div"); obj.parentNode.insertBefore(el, obj); // Insert placeholder div that will be replaced by the alternative content el.parentNode.replaceChild(abstractAltContent(obj), el); obj.style.display = "none"; win.attachEvent("onload", function() { obj.parentNode.removeChild(obj); }); } else { obj.parentNode.replaceChild(abstractAltContent(obj), obj); } } function abstractAltContent(obj) { var ac = createElement("div"); if (ua.win && ua.ie) { ac.innerHTML = obj.innerHTML; } else { var nestedObj = obj.getElementsByTagName(OBJECT)[0]; if (nestedObj) { var c = nestedObj.childNodes; if (c) { var cl = c.length; for (var i = 0; i < cl; i++) { if (!(c[i].nodeType == 1 && c[i].nodeName.toLowerCase() == "param") && !(c[i].nodeType == 8)) { ac.appendChild(c[i].cloneNode(true)); } } } } } return ac; } /* Cross-browser dynamic SWF creation */ function createSWF(attObj, parObj, id) { var r, el = getElementById(id); if (typeof attObj.id == UNDEF) { // if no 'id' is defined for the object element, it will inherit the 'id' from the alternative content attObj.id = id; } if (ua.ie && ua.win) { // IE, the object element and W3C DOM methods do not combine: fall back to outerHTML var att = ""; for (var i in attObj) { if (attObj[i] != Object.prototype[i]) { // Filter out prototype additions from other potential libraries, like Object.prototype.toJSONString = function() {} if (i == "data") { parObj.movie = attObj[i]; } else if (i.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword att += ' class="' + attObj[i] + '"'; } else if (i != "classid") { att += ' ' + i + '="' + attObj[i] + '"'; } } } var par = ""; for (var j in parObj) { if (parObj[j] != Object.prototype[j]) { // Filter out prototype additions from other potential libraries par += '<param name="' + j + '" value="' + parObj[j] + '" />'; } } el.outerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"' + att + '>' + par + '</object>'; fixObjectLeaks(attObj.id); // This bug affects dynamic publishing only r = getElementById(attObj.id); } else if (ua.webkit && ua.webkit < 312) { // Older webkit engines ignore the object element's nested param elements: fall back to the proprietary embed element var e = createElement("embed"); e.setAttribute("type", FLASH_MIME_TYPE); for (var k in attObj) { if (attObj[k] != Object.prototype[k]) { // Filter out prototype additions from other potential libraries if (k == "data") { e.setAttribute("src", attObj[k]); } else if (k.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword e.setAttribute("class", attObj[k]); } else if (k != "classid") { // Filter out IE specific attribute e.setAttribute(k, attObj[k]); } } } for (var l in parObj) { if (parObj[l] != Object.prototype[l]) { // Filter out prototype additions from other potential libraries if (l != "movie") { // Filter out IE specific param element e.setAttribute(l, parObj[l]); } } } el.parentNode.replaceChild(e, el); r = e; } else { // Well-behaving browsers var o = createElement(OBJECT); o.setAttribute("type", FLASH_MIME_TYPE); for (var m in attObj) { if (attObj[m] != Object.prototype[m]) { // Filter out prototype additions from other potential libraries if (m.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword o.setAttribute("class", attObj[m]); } else if (m != "classid") { // Filter out IE specific attribute o.setAttribute(m, attObj[m]); } } } for (var n in parObj) { if (parObj[n] != Object.prototype[n] && n != "movie") { // Filter out prototype additions from other potential libraries and IE specific param element createObjParam(o, n, parObj[n]); } } el.parentNode.replaceChild(o, el); r = o; } return r; } function createObjParam(el, pName, pValue) { var p = createElement("param"); p.setAttribute("name", pName); p.setAttribute("value", pValue); el.appendChild(p); } function getElementById(id) { return doc.getElementById(id); } function createElement(el) { return doc.createElement(el); } function hasPlayerVersion(rv) { var pv = ua.pv, v = rv.split("."); v[0] = parseInt(v[0], 10); v[1] = parseInt(v[1], 10); v[2] = parseInt(v[2], 10); return (pv[0] > v[0] || (pv[0] == v[0] && pv[1] > v[1]) || (pv[0] == v[0] && pv[1] == v[1] && pv[2] >= v[2])) ? true : false; } /* Cross-browser dynamic CSS creation - Based on Bobby van der Sluis' solution: http://www.bobbyvandersluis.com/articles/dynamicCSS.php */ function createCSS(sel, decl) { if (ua.ie && ua.mac) { return; } var h = doc.getElementsByTagName("head")[0], s = createElement("style"); s.setAttribute("type", "text/css"); s.setAttribute("media", "screen"); if (!(ua.ie && ua.win) && typeof doc.createTextNode != UNDEF) { s.appendChild(doc.createTextNode(sel + " {" + decl + "}")); } h.appendChild(s); if (ua.ie && ua.win && typeof doc.styleSheets != UNDEF && doc.styleSheets.length > 0) { var ls = doc.styleSheets[doc.styleSheets.length - 1]; if (typeof ls.addRule == OBJECT) { ls.addRule(sel, decl); } } } function setVisibility(id, isVisible) { var v = isVisible ? "inherit" : "hidden"; if (isDomLoaded) { getElementById(id).style.visibility = v; } else { createCSS("#" + id, "visibility:" + v); } } function getTargetVersion(obj) { if (!obj) return 0; var c = obj.childNodes; var cl = c.length; for (var i = 0; i < cl; i++) { if (c[i].nodeType == 1 && c[i].nodeName.toLowerCase() == "object") { c = c[i].childNodes; cl = c.length; i = 0; } if (c[i].nodeType == 1 && c[i].nodeName.toLowerCase() == "param" && c[i].getAttribute("name") == "swfversion") { return c[i].getAttribute("value"); } } return 0; } function getExpressInstall(obj) { if (!obj) return ""; var c = obj.childNodes; var cl = c.length; for (var i = 0; i < cl; i++) { if (c[i].nodeType == 1 && c[i].nodeName.toLowerCase() == "object") { c = c[i].childNodes; cl = c.length; i = 0; } if (c[i].nodeType == 1 && c[i].nodeName.toLowerCase() == "param" && c[i].getAttribute("name") == "expressinstall") { return c[i].getAttribute("value"); } } return ""; } return { /* Public API - Reference: http://code.google.com/p/swfobject/wiki/SWFObject_2_0_documentation */ registerObject: function(objectIdStr, swfVersionStr, xiSwfUrlStr) { if (!ua.w3cdom || !objectIdStr) { return; } var obj = document.getElementById(objectIdStr); var xi = getExpressInstall(obj); var regObj = {}; regObj.id = objectIdStr; regObj.swfVersion = swfVersionStr ? swfVersionStr : getTargetVersion(obj); regObj.expressInstall = xiSwfUrlStr ? xiSwfUrlStr : ((xi != "") ? xi : false); regObjArr[regObjArr.length] = regObj; setVisibility(objectIdStr, false); }, getObjectById: function(objectIdStr) { var r = null; if (ua.w3cdom && isDomLoaded) { var o = getElementById(objectIdStr); if (o) { var n = o.getElementsByTagName(OBJECT)[0]; if (!n || (n && typeof o.SetVariable != UNDEF)) { r = o; } else if (typeof n.SetVariable != UNDEF) { r = n; } } } return r; }, embedSWF: function(swfUrlStr, replaceElemIdStr, widthStr, heightStr, swfVersionStr, xiSwfUrlStr, flashvarsObj, parObj, attObj) { if (!ua.w3cdom || !swfUrlStr || !replaceElemIdStr || !widthStr || !heightStr || !swfVersionStr) { return; } widthStr += ""; // Auto-convert to string to make it idiot proof heightStr += ""; if (hasPlayerVersion(swfVersionStr)) { setVisibility(replaceElemIdStr, false); var att = (typeof attObj == OBJECT) ? attObj : {}; att.data = swfUrlStr; att.width = widthStr; att.height = heightStr; var par = (typeof parObj == OBJECT) ? parObj : {}; if (typeof flashvarsObj == OBJECT) { for (var i in flashvarsObj) { if (flashvarsObj[i] != Object.prototype[i]) { // Filter out prototype additions from other potential libraries if (typeof par.flashvars != UNDEF) { par.flashvars += "&" + i + "=" + flashvarsObj[i]; } else { par.flashvars = i + "=" + flashvarsObj[i]; } } } } addDomLoadEvent(function() { createSWF(att, par, replaceElemIdStr); if (att.id == replaceElemIdStr) { setVisibility(replaceElemIdStr, true); } }); } else if (xiSwfUrlStr && !isExpressInstallActive && hasPlayerVersion("6.0.65") && (ua.win || ua.mac)) { setVisibility(replaceElemIdStr, false); addDomLoadEvent(function() { var regObj = {}; regObj.id = regObj.altContentId = replaceElemIdStr; regObj.width = widthStr; regObj.height = heightStr; regObj.expressInstall = xiSwfUrlStr; showExpressInstall(regObj); }); } }, getFlashPlayerVersion: function() { return { major:ua.pv[0], minor:ua.pv[1], release:ua.pv[2] }; }, hasFlashPlayerVersion:hasPlayerVersion, createSWF: function(attObj, parObj, replaceElemIdStr) { if (ua.w3cdom && isDomLoaded) { return createSWF(attObj, parObj, replaceElemIdStr); } else { return undefined; } }, createCSS: function(sel, decl) { if (ua.w3cdom) { createCSS(sel, decl); } }, addDomLoadEvent:addDomLoadEvent, addLoadEvent:addLoadEvent, getQueryParamValue: function(param) { var q = doc.location.search || doc.location.hash; if (param == null) { return q; } if(q) { var pairs = q.substring(1).split("&"); for (var i = 0; i < pairs.length; i++) { if (pairs[i].substring(0, pairs[i].indexOf("=")) == param) { return pairs[i].substring((pairs[i].indexOf("=") + 1)); } } } return ""; }, // For internal usage only expressInstallCallback: function() { if (isExpressInstallActive && storedAltContent) { var obj = getElementById(EXPRESS_INSTALL_ID); if (obj) { obj.parentNode.replaceChild(storedAltContent, obj); if (storedAltContentId) { setVisibility(storedAltContentId, true); if (ua.ie && ua.win) { storedAltContent.style.display = "block"; } } storedAltContent = null; storedAltContentId = null; isExpressInstallActive = false; } } } }; }();
JavaScript
//Author: David Lo //Date: 12/12/12 //References: Game_Restart.js //Description: Starts the game when the player presses any jump button var myLevel : String; function Update() { //If player presses escape, application will quit if (Input.GetKey ("escape")) { Application.Quit(); } //If player presses jump(on controller) or spacebar(on keyboard) else if (Input.GetButtonUp("Jump") || Input.GetKeyUp (KeyCode.Space)) { //Loads level Application.LoadLevel(myLevel); } }
JavaScript
//Author: David Lo //Date: 11/16/12 //References: Collide_Coins.js //Description: Collisions with coins will destroy coin object on contact, // increments counter and updates Player Score within PlayerPrefs static var Counter : int = 0; function OnTriggerEnter(myCollider : Collider) { if( collider.gameObject.name == "Coin" ) { //Increment score on colliding Counter++; PlayerPrefs.SetInt("Player Score", Counter); //Destroys the coin object Destroy(collider.gameObject); } }
JavaScript
//Author: David Lo //Date: 12/12/12 //References: Game_Quit.js //Description: Starts the game when the player presses any jump button var myLevel : String; function Update() { //If player presses escape, application will quit if (Input.GetKey ("escape")) { Application.Quit(); } }
JavaScript
//Author: David Lo //Date: 12/12/12 //References: Display_Lives.js //Description: Displays Lives using PlayerPrefs function OnGUI() { guiText.text = "Lives: "+PlayerPrefs.GetInt("Player Lives"); }
JavaScript
//Author: David Lo //Date: 12/12/12 //References: Player_Lose.js //Description: Checks if the player has no lives left and loads game over screen var GameOver : String; function Update() { //Checks if the player has no lives left and loads game over screen if (PlayerPrefs.GetInt("Player Lives") == 0) { Application.LoadLevel(GameOver); } }
JavaScript
//Author: David Lo //Date: 11/16/12 //References: Display_Score.js //Description: Displays Score using PlayerPrefs function OnGUI() { guiText.text = "Score: "+PlayerPrefs.GetInt("Player Score"); }
JavaScript
//Author: David Lo //Date: 12/12/12 //References: Collide_Spikes.js //Description: Collisions with spiked platforms will kill the player on contact, // decrements Lives and updates Player Lives within PlayerPrefs // restarts the level (retains the player score) static var Lives : int = 3; var myLevel : String; function OnTriggerEnter(myCollider : Collider) { if( collider.gameObject.name == "SpikedPlatform" ) { //Decrements player lives on death Lives--; PlayerPrefs.SetInt("Player Lives", Lives); //Restarts the level Application.LoadLevel(myLevel); } }
JavaScript
//Author: David Lo //Date: 12/12/12 //References: Game_Start.js //Description: Starts the game when the player presses any jump button // sets the initial player lives // sets the initial player score var myLevel : String; function Update() { //If player presses jump(on controller) or spacebar(on keyboard) if (Input.GetButtonUp("Jump") || Input.GetKeyUp (KeyCode.Space)) { //Sets initial player lives PlayerPrefs.SetInt("Player Lives", 3); //Sets initial player score PlayerPrefs.SetInt("Player Score", 0); //Loads level Application.LoadLevel(myLevel); } }
JavaScript
//Author: David Lo //Date: 11/16/12 //References: LoadLevel.js //Description: Changes level when player collides with SceneChange Object var myLevel : String; function OnTriggerEnter (myCollider: Collider ) { //Changes level when player collides with SceneChange Object if(myCollider.gameObject.name == "ChangeScene"){ Application.LoadLevel(myLevel); } }
JavaScript
/* This camera smoothes out rotation around the y-axis and height. Horizontal Distance to the target is always fixed. There are many different ways to smooth the rotation but doing it this way gives you a lot of control over how the camera behaves. For every of those smoothed values we calculate the wanted value and the current value. Then we smooth it using the Lerp function. Then we apply the smoothed values to the transform's position. */ // The target we are following var target : Transform; // The distance in the x-z plane to the target var distance = 10.0; // the height we want the camera to be above the target var height = 1f; // How much we var heightDamping = 2.0; var rotationDamping = 3.0; // Place the script in the Camera-Control group in the component menu @script AddComponentMenu("Camera-Control/Smooth Follow") function LateUpdate () { // Early out if we don't have a target if (!target) return; // Calculate the current rotation angles var wantedRotationAngle = target.eulerAngles.y; var wantedHeight = target.position.y + height; var currentRotationAngle = transform.eulerAngles.y; var currentHeight = transform.position.y; // Damp the rotation around the y-axis currentRotationAngle = Mathf.LerpAngle (currentRotationAngle, wantedRotationAngle, rotationDamping * Time.deltaTime); // Damp the height //currentHeight = Mathf.Lerp (currentHeight, wantedHeight, heightDamping * Time.deltaTime); // Convert the angle into a rotation var currentRotation = Quaternion.Euler (0, 0, currentRotationAngle); // Set the position of the camera on the x-z plane to: // distance meters behind the target transform.position = target.position; transform.position -= currentRotation * Vector3.forward * distance; //transform.position += Vector3.up; // Set the height of the camera //transform.position.y = currentHeight; //transform.position.y += 1f; // Back camera up // transform.position.z += 35.0; // Always look at the target transform.LookAt (target); }
JavaScript
//SmoothFollow2D - Platformer Script //Jason Keefer, 10/31/12 //David Lo, Edited: 11/23/12 @script RequireComponent (typeof(Camera)) //private var ortho: Matrix4x4; //private var perspective: Matrix4x4; //public var fov: float = 60f; //public var near: float = .3f; //public var far: float = 1000f; //public var orthographicSize: float = 100f; //private var aspect: float; //private var orthoOn: boolean; var dampTime : float = 0.1; //offset from the viewport center to fix damping private var velocity = Vector3.zero; private var origination : Vector3; //variable to store origination point for relevant calculation var target : Transform; function Update() { if(target) { var point : Vector3 = camera.WorldToViewportPoint(target.position); var delta : Vector3 = target.position - camera.ViewportToWorldPoint(Vector3(0.5, 0.5, point.z)); var destination : Vector3 = transform.position + delta; var change = 0.0; // Set this to the Y position you want the camera locked to // Make camera fade to no offset as player gets higher on Y axis if(target.position.y < (origination.y - 0.3)){ destination.y = 1.0; } else if(target.position.y < (origination.y + 0.162)){ change = 0.55; destination.y = target.position.y + 0.55; } else if(target.position.y < (origination.y + 0.312)){ change = 0.475; destination.y = target.position.y + 0.475; } else if(target.position.y < (origination.y + 0.437)){ change = 0.4; destination.y = target.position.y + 0.4; } else if(target.position.y < (origination.y + 0.537)){ change = 0.325; destination.y = target.position.y + 0.325; } else if(target.position.y < (origination.y + 0.637)){ change = 0.225; destination.y = target.position.y + 0.225; } else if(target.position.y < (origination.y + 0.737)){ change = 0.125; destination.y = target.position.y + 0.125; } else { change = 0.0; destination.y = target.position.y; } //David Lo: //Alter these lines to enable camera panning left/right/up/down //process up/down look if (Input.GetAxis("CamY") > 0.0){ destination.y = destination.y - 0.5; } if (Input.GetAxis("CamY") < 0.0){ destination.y = destination.y + 0.5; } //process left/right look if (Input.GetAxis("CamX") < 0.0){ destination.x = destination.x - 1.4; } if (Input.GetAxis("CamX") > 0.0){ destination.x = destination.x + 1.4; } // if (Input.GetAxis("Pan") > 0.0 || Input.GetKeyDown (KeyCode.RightArrow)){ // destination.x = destination.x - 1.4; // } // if (Input.GetAxis("Pan") < 0.0 || Input.GetKeyDown (KeyCode.LeftArrow)){ // destination.x = destination.x + 1.4; // } transform.position = Vector3.SmoothDamp(transform.position, destination, velocity, dampTime); } //if (Input.GetButtonDown("Run") || Input.GetKeyDown (KeyCode.Slash)){ //if (Camera.main.orthographic==true) { //Camera.main.orthographic=false; //} //else { //Camera.main.orthographic=true; //} // orthoOn = !orthoOn; // if (orthoOn){ // //transform.position.z -= 2.0; // BlendToMatrix(ortho, 1f); // } // else{ // BlendToMatrix(perspective, 1f); // //transform.position.z += 2.0; // //fov. // } //} } function Awake () { //aspect = (Screen.width+0.0) / (Screen.height+0.0); //perspective = camera.projectionMatrix; //ortho = Matrix4x4.Ortho(-orthographicSize * aspect, orthographicSize * aspect, -orthographicSize, orthographicSize, near, far); //orthoOn = false; //PlayerPrefs.DeleteAll(); origination = target.position; } static function MatrixLerp (from: Matrix4x4, to: Matrix4x4, time: float) : Matrix4x4 { var ret: Matrix4x4 = new Matrix4x4(); var i: int; for (i = 0; i < 16; i++) ret[i] = Mathf.Lerp(from[i], to[i], time); return ret; } private function LerpFromTo (src: Matrix4x4, dest: Matrix4x4, duration: float) : IEnumerator { var startTime: float = Time.time; while (Time.time - startTime < duration) { camera.projectionMatrix = MatrixLerp(src, dest, (Time.time - startTime) / duration); yield; } camera.projectionMatrix = dest; } public function BlendToMatrix (targetMatrix: Matrix4x4, duration: float) : Coroutine { StopAllCoroutines(); return StartCoroutine(LerpFromTo(camera.projectionMatrix, targetMatrix, duration)); }
JavaScript
var target : Transform; var damping = 0.0; var smooth = true; @script AddComponentMenu("Camera-Control/Smooth Look At") function LateUpdate () { if (target) { if (smooth) { // Look at and dampen the rotation var rotation = Quaternion.LookRotation(target.position - transform.position); transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * damping); } else { // Just lookat transform.LookAt(target); } } } function Start () { // Make the rigid body not change rotation if (rigidbody) rigidbody.freezeRotation = true; }
JavaScript
var target : Transform; var distance = 10.0; var xSpeed = 250.0; var ySpeed = 120.0; var yMinLimit = -20; var yMaxLimit = 80; private var x = 0.0; private var y = 0.0; @script AddComponentMenu("Camera-Control/Mouse Orbit") function Start () { var angles = transform.eulerAngles; x = angles.y; y = angles.x; // Make the rigid body not change rotation if (rigidbody) rigidbody.freezeRotation = true; } function LateUpdate () { if (target) { x += Input.GetAxis("Mouse X") * xSpeed * 0.02; y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02; y = ClampAngle(y, yMinLimit, yMaxLimit); var rotation = Quaternion.Euler(y, x, 0); var position = rotation * Vector3(0.0, 0.0, -distance) + target.position; transform.rotation = rotation; transform.position = position; } } static function ClampAngle (angle : float, min : float, max : float) { if (angle < -360) angle += 360; if (angle > 360) angle -= 360; return Mathf.Clamp (angle, min, max); }
JavaScript
var spring = 50.0; var damper = 5.0; var drag = 10.0; var angularDrag = 5.0; var distance = 0.2; var attachToCenterOfMass = false; private var springJoint : SpringJoint; function Update () { // Make sure the user pressed the mouse down if (!Input.GetMouseButtonDown (0)) return; var mainCamera = FindCamera(); // We need to actually hit an object var hit : RaycastHit; if (!Physics.Raycast(mainCamera.ScreenPointToRay(Input.mousePosition), hit, 100)) return; // We need to hit a rigidbody that is not kinematic if (!hit.rigidbody || hit.rigidbody.isKinematic) return; if (!springJoint) { var go = new GameObject("Rigidbody dragger"); var body : Rigidbody = go.AddComponent ("Rigidbody") as Rigidbody; springJoint = go.AddComponent ("SpringJoint"); body.isKinematic = true; } springJoint.transform.position = hit.point; if (attachToCenterOfMass) { var anchor = transform.TransformDirection(hit.rigidbody.centerOfMass) + hit.rigidbody.transform.position; anchor = springJoint.transform.InverseTransformPoint(anchor); springJoint.anchor = anchor; } else { springJoint.anchor = Vector3.zero; } springJoint.spring = spring; springJoint.damper = damper; springJoint.maxDistance = distance; springJoint.connectedBody = hit.rigidbody; StartCoroutine ("DragObject", hit.distance); } function DragObject (distance : float) { var oldDrag = springJoint.connectedBody.drag; var oldAngularDrag = springJoint.connectedBody.angularDrag; springJoint.connectedBody.drag = drag; springJoint.connectedBody.angularDrag = angularDrag; var mainCamera = FindCamera(); while (Input.GetMouseButton (0)) { var ray = mainCamera.ScreenPointToRay (Input.mousePosition); springJoint.transform.position = ray.GetPoint(distance); yield; } if (springJoint.connectedBody) { springJoint.connectedBody.drag = oldDrag; springJoint.connectedBody.angularDrag = oldAngularDrag; springJoint.connectedBody = null; } } function FindCamera () { if (camera) return camera; else return Camera.main; }
JavaScript
function OnTriggerEnter(myCollider : Collider) { if( collider.gameObject.name == "Coin" ) { Destroy(collider.gameObject); } } //function OnColliderEnter (collision : Collision) { // if (collision.gameObject.tag!="Player") // return; //Check that it's the player that collides else exit the function // // // @TODO: // // Increment score // // Destroy(gameObject); // //gameObject.active = false; // //Destroy(gameObject); // //gameObject.renderer.enabled = false; //Disable this GameObject's renderer // //gameObject.collider.enabled = false; //Disable this GameObject's collider //}
JavaScript
var colorStart : Color = Color.red; var colorEnd : Color = Color.green; var duration : float = 1.0; function Update () { if (Input.GetButtonUp("Fire3") || Input.GetKeyDown (KeyCode.Slash)){ var lerp : float = Mathf.PingPong (Time.time, duration) / duration; //renderer.material.color = Color.Lerp (colorStart, colorEnd, lerp); } }
JavaScript
var cameraTransform : Transform; private var _target : Transform; // The distance in the x-z plane to the target var distance = 7.0; // the height we want the camera to be above the target var height = 3.0; var angularSmoothLag = 0.3; var angularMaxSpeed = 15.0; var heightSmoothLag = 0.3; var snapSmoothLag = 0.2; var snapMaxSpeed = 720.0; var clampHeadPositionScreenSpace = 0.75; var lockCameraTimeout = 0.2; private var headOffset = Vector3.zero; private var centerOffset = Vector3.zero; private var heightVelocity = 0.0; private var angleVelocity = 0.0; private var snap = false; private var controller : ThirdPersonController; private var targetHeight = 100000.0; function Awake () { if(!cameraTransform && Camera.main) cameraTransform = Camera.main.transform; if(!cameraTransform) { Debug.Log("Please assign a camera to the ThirdPersonCamera script."); enabled = false; } _target = transform; if (_target) { controller = _target.GetComponent(ThirdPersonController); } if (controller) { var characterController : CharacterController = _target.collider; centerOffset = characterController.bounds.center - _target.position; headOffset = centerOffset; headOffset.y = characterController.bounds.max.y - _target.position.y; } else Debug.Log("Please assign a target to the camera that has a ThirdPersonController script attached."); Cut(_target, centerOffset); } function DebugDrawStuff () { Debug.DrawLine(_target.position, _target.position + headOffset); } function AngleDistance (a : float, b : float) { a = Mathf.Repeat(a, 360); b = Mathf.Repeat(b, 360); return Mathf.Abs(b - a); } function Apply (dummyTarget : Transform, dummyCenter : Vector3) { // Early out if we don't have a target if (!controller) return; var targetCenter = _target.position + centerOffset; var targetHead = _target.position + headOffset; // DebugDrawStuff(); // Calculate the current & target rotation angles var originalTargetAngle = _target.eulerAngles.y; var currentAngle = cameraTransform.eulerAngles.y; // Adjust real target angle when camera is locked var targetAngle = originalTargetAngle; // When pressing Fire2 (alt) the camera will snap to the target direction real quick. // It will stop snapping when it reaches the target if (Input.GetButton("Fire2")) snap = true; if (snap) { // We are close to the target, so we can stop snapping now! if (AngleDistance (currentAngle, originalTargetAngle) < 3.0) snap = false; currentAngle = Mathf.SmoothDampAngle(currentAngle, targetAngle, angleVelocity, snapSmoothLag, snapMaxSpeed); } // Normal camera motion else { if (controller.GetLockCameraTimer () < lockCameraTimeout) { targetAngle = currentAngle; } // Lock the camera when moving backwards! // * It is really confusing to do 180 degree spins when turning around. if (AngleDistance (currentAngle, targetAngle) > 160 && controller.IsMovingBackwards ()) targetAngle += 180; currentAngle = Mathf.SmoothDampAngle(currentAngle, targetAngle, angleVelocity, angularSmoothLag, angularMaxSpeed); } // When jumping don't move camera upwards but only down! if (controller.IsJumping ()) { // We'd be moving the camera upwards, do that only if it's really high var newTargetHeight = targetCenter.y + height; if (newTargetHeight < targetHeight || newTargetHeight - targetHeight > 5) targetHeight = targetCenter.y + height; } // When walking always update the target height else { targetHeight = targetCenter.y + height; } // Damp the height var currentHeight = cameraTransform.position.y; currentHeight = Mathf.SmoothDamp (currentHeight, targetHeight, heightVelocity, heightSmoothLag); // Convert the angle into a rotation, by which we then reposition the camera var currentRotation = Quaternion.Euler (0, currentAngle, 0); // Set the position of the camera on the x-z plane to: // distance meters behind the target cameraTransform.position = targetCenter; cameraTransform.position += currentRotation * Vector3.back * distance; // Set the height of the camera cameraTransform.position.y = currentHeight; // Always look at the target SetUpRotation(targetCenter, targetHead); } function LateUpdate () { Apply (transform, Vector3.zero); } function Cut (dummyTarget : Transform, dummyCenter : Vector3) { var oldHeightSmooth = heightSmoothLag; var oldSnapMaxSpeed = snapMaxSpeed; var oldSnapSmooth = snapSmoothLag; snapMaxSpeed = 10000; snapSmoothLag = 0.001; heightSmoothLag = 0.001; snap = true; Apply (transform, Vector3.zero); heightSmoothLag = oldHeightSmooth; snapMaxSpeed = oldSnapMaxSpeed; snapSmoothLag = oldSnapSmooth; } function SetUpRotation (centerPos : Vector3, headPos : Vector3) { // Now it's getting hairy. The devil is in the details here, the big issue is jumping of course. // * When jumping up and down we don't want to center the guy in screen space. // This is important to give a feel for how high you jump and avoiding large camera movements. // // * At the same time we dont want him to ever go out of screen and we want all rotations to be totally smooth. // // So here is what we will do: // // 1. We first find the rotation around the y axis. Thus he is always centered on the y-axis // 2. When grounded we make him be centered // 3. When jumping we keep the camera rotation but rotate the camera to get him back into view if his head is above some threshold // 4. When landing we smoothly interpolate towards centering him on screen var cameraPos = cameraTransform.position; var offsetToCenter = centerPos - cameraPos; // Generate base rotation only around y-axis var yRotation = Quaternion.LookRotation(Vector3(offsetToCenter.x, 0, offsetToCenter.z)); var relativeOffset = Vector3.forward * distance + Vector3.down * height; cameraTransform.rotation = yRotation * Quaternion.LookRotation(relativeOffset); // Calculate the projected center position and top position in world space var centerRay = cameraTransform.camera.ViewportPointToRay(Vector3(.5, 0.5, 1)); var topRay = cameraTransform.camera.ViewportPointToRay(Vector3(.5, clampHeadPositionScreenSpace, 1)); var centerRayPos = centerRay.GetPoint(distance); var topRayPos = topRay.GetPoint(distance); var centerToTopAngle = Vector3.Angle(centerRay.direction, topRay.direction); var heightToAngle = centerToTopAngle / (centerRayPos.y - topRayPos.y); var extraLookAngle = heightToAngle * (centerRayPos.y - centerPos.y); if (extraLookAngle < centerToTopAngle) { extraLookAngle = 0; } else { extraLookAngle = extraLookAngle - centerToTopAngle; cameraTransform.rotation *= Quaternion.Euler(-extraLookAngle, 0, 0); } } function GetCenterOffset () { return centerOffset; }
JavaScript
#pragma strict #pragma implicit #pragma downcast // Does this script currently respond to input? var canControl : boolean = true; var useFixedUpdate : boolean = true; // For the next variables, @System.NonSerialized tells Unity to not serialize the variable or show it in the inspector view. // Very handy for organization! // The current global direction we want the character to move in. @System.NonSerialized var inputMoveDirection : Vector3 = Vector3.zero; // Is the jump button held down? We use this interface instead of checking // for the jump button directly so this script can also be used by AIs. @System.NonSerialized var inputJump : boolean = false; class CharacterMotorMovement { // The maximum horizontal speed when moving var maxForwardSpeed : float = 10.0; var maxSidewaysSpeed : float = 10.0; var maxBackwardsSpeed : float = 10.0; // Curve for multiplying speed based on slope (negative = downwards) var slopeSpeedMultiplier : AnimationCurve = AnimationCurve(Keyframe(-90, 1), Keyframe(0, 1), Keyframe(90, 0)); // How fast does the character change speeds? Higher is faster. var maxGroundAcceleration : float = 30.0; var maxAirAcceleration : float = 20.0; // The gravity for the character var gravity : float = 10.0; var maxFallSpeed : float = 20.0; // For the next variables, @System.NonSerialized tells Unity to not serialize the variable or show it in the inspector view. // Very handy for organization! // The last collision flags returned from controller.Move @System.NonSerialized var collisionFlags : CollisionFlags; // We will keep track of the character's current velocity, @System.NonSerialized var velocity : Vector3; // This keeps track of our current velocity while we're not grounded @System.NonSerialized var frameVelocity : Vector3 = Vector3.zero; @System.NonSerialized var hitPoint : Vector3 = Vector3.zero; @System.NonSerialized var lastHitPoint : Vector3 = Vector3(Mathf.Infinity, 0, 0); } var movement : CharacterMotorMovement = CharacterMotorMovement(); enum MovementTransferOnJump { None, // The jump is not affected by velocity of floor at all. InitTransfer, // Jump gets its initial velocity from the floor, then gradualy comes to a stop. PermaTransfer, // Jump gets its initial velocity from the floor, and keeps that velocity until landing. PermaLocked // Jump is relative to the movement of the last touched floor and will move together with that floor. } // We will contain all the jumping related variables in one helper class for clarity. class CharacterMotorJumping { // Can the character jump? var enabled : boolean = true; // How high do we jump when pressing jump and letting go immediately var baseHeight : float = 1.0; // We add extraHeight units (meters) on top when holding the button down longer while jumping var extraHeight : float = 4.1; // How much does the character jump out perpendicular to the surface on walkable surfaces? // 0 means a fully vertical jump and 1 means fully perpendicular. var perpAmount : float = 0.0; // How much does the character jump out perpendicular to the surface on too steep surfaces? // 0 means a fully vertical jump and 1 means fully perpendicular. var steepPerpAmount : float = 0.5; // For the next variables, @System.NonSerialized tells Unity to not serialize the variable or show it in the inspector view. // Very handy for organization! // Are we jumping? (Initiated with jump button and not grounded yet) // To see if we are just in the air (initiated by jumping OR falling) see the grounded variable. @System.NonSerialized var jumping : boolean = false; @System.NonSerialized var holdingJumpButton : boolean = false; // the time we jumped at (Used to determine for how long to apply extra jump power after jumping.) @System.NonSerialized var lastStartTime : float = 0.0; @System.NonSerialized var lastButtonDownTime : float = -100; @System.NonSerialized var jumpDir : Vector3 = Vector3.up; } var jumping : CharacterMotorJumping = CharacterMotorJumping(); class CharacterMotorMovingPlatform { var enabled : boolean = true; var movementTransfer : MovementTransferOnJump = MovementTransferOnJump.PermaTransfer; @System.NonSerialized var hitPlatform : Transform; @System.NonSerialized var activePlatform : Transform; @System.NonSerialized var activeLocalPoint : Vector3; @System.NonSerialized var activeGlobalPoint : Vector3; @System.NonSerialized var activeLocalRotation : Quaternion; @System.NonSerialized var activeGlobalRotation : Quaternion; @System.NonSerialized var lastMatrix : Matrix4x4; @System.NonSerialized var platformVelocity : Vector3; @System.NonSerialized var newPlatform : boolean; } var movingPlatform : CharacterMotorMovingPlatform = CharacterMotorMovingPlatform(); class CharacterMotorSliding { // Does the character slide on too steep surfaces? var enabled : boolean = true; // How fast does the character slide on steep surfaces? var slidingSpeed : float = 15; // How much can the player control the sliding direction? // If the value is 0.5 the player can slide sideways with half the speed of the downwards sliding speed. var sidewaysControl : float = 1.0; // How much can the player influence the sliding speed? // If the value is 0.5 the player can speed the sliding up to 150% or slow it down to 50%. var speedControl : float = 0.4; } var sliding : CharacterMotorSliding = CharacterMotorSliding(); @System.NonSerialized var grounded : boolean = true; @System.NonSerialized var groundNormal : Vector3 = Vector3.zero; private var lastGroundNormal : Vector3 = Vector3.zero; private var tr : Transform; private var controller : CharacterController; function Awake () { controller = GetComponent (CharacterController); tr = transform; } private function UpdateFunction () { // We copy the actual velocity into a temporary variable that we can manipulate. var velocity : Vector3 = movement.velocity; // Update velocity based on input velocity = ApplyInputVelocityChange(velocity); // Apply gravity and jumping force velocity = ApplyGravityAndJumping (velocity); // Moving platform support var moveDistance : Vector3 = Vector3.zero; if (MoveWithPlatform()) { var newGlobalPoint : Vector3 = movingPlatform.activePlatform.TransformPoint(movingPlatform.activeLocalPoint); moveDistance = (newGlobalPoint - movingPlatform.activeGlobalPoint); if (moveDistance != Vector3.zero) controller.Move(moveDistance); // Support moving platform rotation as well: var newGlobalRotation : Quaternion = movingPlatform.activePlatform.rotation * movingPlatform.activeLocalRotation; var rotationDiff : Quaternion = newGlobalRotation * Quaternion.Inverse(movingPlatform.activeGlobalRotation); var yRotation = rotationDiff.eulerAngles.y; if (yRotation != 0) { // Prevent rotation of the local up vector tr.Rotate(0, yRotation, 0); } } // Save lastPosition for velocity calculation. var lastPosition : Vector3 = tr.position; // We always want the movement to be framerate independent. Multiplying by Time.deltaTime does this. var currentMovementOffset : Vector3 = velocity * Time.deltaTime; // Find out how much we need to push towards the ground to avoid loosing grouning // when walking down a step or over a sharp change in slope. var pushDownOffset : float = Mathf.Max(controller.stepOffset, Vector3(currentMovementOffset.x, 0, currentMovementOffset.z).magnitude); if (grounded) currentMovementOffset -= pushDownOffset * Vector3.up; // Reset variables that will be set by collision function movingPlatform.hitPlatform = null; groundNormal = Vector3.zero; // Move our character! movement.collisionFlags = controller.Move (currentMovementOffset); movement.lastHitPoint = movement.hitPoint; lastGroundNormal = groundNormal; if (movingPlatform.enabled && movingPlatform.activePlatform != movingPlatform.hitPlatform) { if (movingPlatform.hitPlatform != null) { movingPlatform.activePlatform = movingPlatform.hitPlatform; movingPlatform.lastMatrix = movingPlatform.hitPlatform.localToWorldMatrix; movingPlatform.newPlatform = true; } } // Calculate the velocity based on the current and previous position. // This means our velocity will only be the amount the character actually moved as a result of collisions. var oldHVelocity : Vector3 = new Vector3(velocity.x, 0, velocity.z); movement.velocity = (tr.position - lastPosition) / Time.deltaTime; var newHVelocity : Vector3 = new Vector3(movement.velocity.x, 0, movement.velocity.z); // The CharacterController can be moved in unwanted directions when colliding with things. // We want to prevent this from influencing the recorded velocity. if (oldHVelocity == Vector3.zero) { movement.velocity = new Vector3(0, movement.velocity.y, 0); } else { var projectedNewVelocity : float = Vector3.Dot(newHVelocity, oldHVelocity) / oldHVelocity.sqrMagnitude; movement.velocity = oldHVelocity * Mathf.Clamp01(projectedNewVelocity) + movement.velocity.y * Vector3.up; } if (movement.velocity.y < velocity.y - 0.001) { if (movement.velocity.y < 0) { // Something is forcing the CharacterController down faster than it should. // Ignore this movement.velocity.y = velocity.y; } else { // The upwards movement of the CharacterController has been blocked. // This is treated like a ceiling collision - stop further jumping here. jumping.holdingJumpButton = false; } } // We were grounded but just loosed grounding if (grounded && !IsGroundedTest()) { grounded = false; // Apply inertia from platform if (movingPlatform.enabled && (movingPlatform.movementTransfer == MovementTransferOnJump.InitTransfer || movingPlatform.movementTransfer == MovementTransferOnJump.PermaTransfer) ) { movement.frameVelocity = movingPlatform.platformVelocity; movement.velocity += movingPlatform.platformVelocity; } SendMessage("OnFall", SendMessageOptions.DontRequireReceiver); // We pushed the character down to ensure it would stay on the ground if there was any. // But there wasn't so now we cancel the downwards offset to make the fall smoother. tr.position += pushDownOffset * Vector3.up; } // We were not grounded but just landed on something else if (!grounded && IsGroundedTest()) { grounded = true; jumping.jumping = false; SubtractNewPlatformVelocity(); SendMessage("OnLand", SendMessageOptions.DontRequireReceiver); } // Moving platforms support if (MoveWithPlatform()) { // Use the center of the lower half sphere of the capsule as reference point. // This works best when the character is standing on moving tilting platforms. movingPlatform.activeGlobalPoint = tr.position + Vector3.up * (controller.center.y - controller.height*0.5 + controller.radius); movingPlatform.activeLocalPoint = movingPlatform.activePlatform.InverseTransformPoint(movingPlatform.activeGlobalPoint); // Support moving platform rotation as well: movingPlatform.activeGlobalRotation = tr.rotation; movingPlatform.activeLocalRotation = Quaternion.Inverse(movingPlatform.activePlatform.rotation) * movingPlatform.activeGlobalRotation; } } function FixedUpdate () { if (movingPlatform.enabled) { if (movingPlatform.activePlatform != null) { if (!movingPlatform.newPlatform) { var lastVelocity : Vector3 = movingPlatform.platformVelocity; movingPlatform.platformVelocity = ( movingPlatform.activePlatform.localToWorldMatrix.MultiplyPoint3x4(movingPlatform.activeLocalPoint) - movingPlatform.lastMatrix.MultiplyPoint3x4(movingPlatform.activeLocalPoint) ) / Time.deltaTime; } movingPlatform.lastMatrix = movingPlatform.activePlatform.localToWorldMatrix; movingPlatform.newPlatform = false; } else { movingPlatform.platformVelocity = Vector3.zero; } } if (useFixedUpdate) UpdateFunction(); } function Update () { if (!useFixedUpdate) UpdateFunction(); } private function ApplyInputVelocityChange (velocity : Vector3) { if (!canControl) inputMoveDirection = Vector3.zero; // Find desired velocity var desiredVelocity : Vector3; if (grounded && TooSteep()) { // The direction we're sliding in desiredVelocity = Vector3(groundNormal.x, 0, groundNormal.z).normalized; // Find the input movement direction projected onto the sliding direction var projectedMoveDir = Vector3.Project(inputMoveDirection, desiredVelocity); // Add the sliding direction, the spped control, and the sideways control vectors desiredVelocity = desiredVelocity + projectedMoveDir * sliding.speedControl + (inputMoveDirection - projectedMoveDir) * sliding.sidewaysControl; // Multiply with the sliding speed desiredVelocity *= sliding.slidingSpeed; } else desiredVelocity = GetDesiredHorizontalVelocity(); if (movingPlatform.enabled && movingPlatform.movementTransfer == MovementTransferOnJump.PermaTransfer) { desiredVelocity += movement.frameVelocity; desiredVelocity.y = 0; } if (grounded) desiredVelocity = AdjustGroundVelocityToNormal(desiredVelocity, groundNormal); else velocity.y = 0; // Enforce max velocity change var maxVelocityChange : float = GetMaxAcceleration(grounded) * Time.deltaTime; var velocityChangeVector : Vector3 = (desiredVelocity - velocity); if (velocityChangeVector.sqrMagnitude > maxVelocityChange * maxVelocityChange) { velocityChangeVector = velocityChangeVector.normalized * maxVelocityChange; } // If we're in the air and don't have control, don't apply any velocity change at all. // If we're on the ground and don't have control we do apply it - it will correspond to friction. if (grounded || canControl) velocity += velocityChangeVector; if (grounded) { // When going uphill, the CharacterController will automatically move up by the needed amount. // Not moving it upwards manually prevent risk of lifting off from the ground. // When going downhill, DO move down manually, as gravity is not enough on steep hills. velocity.y = Mathf.Min(velocity.y, 0); } return velocity; } private function ApplyGravityAndJumping (velocity : Vector3) { if (!inputJump || !canControl) { jumping.holdingJumpButton = false; jumping.lastButtonDownTime = -100; } if (inputJump && jumping.lastButtonDownTime < 0 && canControl) jumping.lastButtonDownTime = Time.time; if (grounded) velocity.y = Mathf.Min(0, velocity.y) - movement.gravity * Time.deltaTime; else { velocity.y = movement.velocity.y - movement.gravity * Time.deltaTime; // When jumping up we don't apply gravity for some time when the user is holding the jump button. // This gives more control over jump height by pressing the button longer. if (jumping.jumping && jumping.holdingJumpButton) { // Calculate the duration that the extra jump force should have effect. // If we're still less than that duration after the jumping time, apply the force. if (Time.time < jumping.lastStartTime + jumping.extraHeight / CalculateJumpVerticalSpeed(jumping.baseHeight)) { // Negate the gravity we just applied, except we push in jumpDir rather than jump upwards. velocity += jumping.jumpDir * movement.gravity * Time.deltaTime; } } // Make sure we don't fall any faster than maxFallSpeed. This gives our character a terminal velocity. velocity.y = Mathf.Max (velocity.y, -movement.maxFallSpeed); } if (grounded) { // Jump only if the jump button was pressed down in the last 0.2 seconds. // We use this check instead of checking if it's pressed down right now // because players will often try to jump in the exact moment when hitting the ground after a jump // and if they hit the button a fraction of a second too soon and no new jump happens as a consequence, // it's confusing and it feels like the game is buggy. if (jumping.enabled && canControl && (Time.time - jumping.lastButtonDownTime < 0.2)) { grounded = false; jumping.jumping = true; jumping.lastStartTime = Time.time; jumping.lastButtonDownTime = -100; jumping.holdingJumpButton = true; // Calculate the jumping direction if (TooSteep()) jumping.jumpDir = Vector3.Slerp(Vector3.up, groundNormal, jumping.steepPerpAmount); else jumping.jumpDir = Vector3.Slerp(Vector3.up, groundNormal, jumping.perpAmount); // Apply the jumping force to the velocity. Cancel any vertical velocity first. velocity.y = 0; velocity += jumping.jumpDir * CalculateJumpVerticalSpeed (jumping.baseHeight); // Apply inertia from platform if (movingPlatform.enabled && (movingPlatform.movementTransfer == MovementTransferOnJump.InitTransfer || movingPlatform.movementTransfer == MovementTransferOnJump.PermaTransfer) ) { movement.frameVelocity = movingPlatform.platformVelocity; velocity += movingPlatform.platformVelocity; } SendMessage("OnJump", SendMessageOptions.DontRequireReceiver); } else { jumping.holdingJumpButton = false; } } return velocity; } function OnControllerColliderHit (hit : ControllerColliderHit) { if (hit.normal.y > 0 && hit.normal.y > groundNormal.y && hit.moveDirection.y < 0) { if ((hit.point - movement.lastHitPoint).sqrMagnitude > 0.001 || lastGroundNormal == Vector3.zero) groundNormal = hit.normal; else groundNormal = lastGroundNormal; movingPlatform.hitPlatform = hit.collider.transform; movement.hitPoint = hit.point; movement.frameVelocity = Vector3.zero; } } private function SubtractNewPlatformVelocity () { // When landing, subtract the velocity of the new ground from the character's velocity // since movement in ground is relative to the movement of the ground. if (movingPlatform.enabled && (movingPlatform.movementTransfer == MovementTransferOnJump.InitTransfer || movingPlatform.movementTransfer == MovementTransferOnJump.PermaTransfer) ) { // If we landed on a new platform, we have to wait for two FixedUpdates // before we know the velocity of the platform under the character if (movingPlatform.newPlatform) { var platform : Transform = movingPlatform.activePlatform; yield WaitForFixedUpdate(); yield WaitForFixedUpdate(); if (grounded && platform == movingPlatform.activePlatform) yield 1; } movement.velocity -= movingPlatform.platformVelocity; } } private function MoveWithPlatform () : boolean { return ( movingPlatform.enabled && (grounded || movingPlatform.movementTransfer == MovementTransferOnJump.PermaLocked) && movingPlatform.activePlatform != null ); } private function GetDesiredHorizontalVelocity () { // Find desired velocity var desiredLocalDirection : Vector3 = tr.InverseTransformDirection(inputMoveDirection); var maxSpeed : float = MaxSpeedInDirection(desiredLocalDirection); if (grounded) { // Modify max speed on slopes based on slope speed multiplier curve var movementSlopeAngle = Mathf.Asin(movement.velocity.normalized.y) * Mathf.Rad2Deg; maxSpeed *= movement.slopeSpeedMultiplier.Evaluate(movementSlopeAngle); } return tr.TransformDirection(desiredLocalDirection * maxSpeed); } private function AdjustGroundVelocityToNormal (hVelocity : Vector3, groundNormal : Vector3) : Vector3 { var sideways : Vector3 = Vector3.Cross(Vector3.up, hVelocity); return Vector3.Cross(sideways, groundNormal).normalized * hVelocity.magnitude; } private function IsGroundedTest () { return (groundNormal.y > 0.01); } function GetMaxAcceleration (grounded : boolean) : float { // Maximum acceleration on ground and in air if (grounded) return movement.maxGroundAcceleration; else return movement.maxAirAcceleration; } function CalculateJumpVerticalSpeed (targetJumpHeight : float) { // From the jump height and gravity we deduce the upwards speed // for the character to reach at the apex. return Mathf.Sqrt (2 * targetJumpHeight * movement.gravity); } function IsJumping () { return jumping.jumping; } function IsSliding () { return (grounded && sliding.enabled && TooSteep()); } function IsTouchingCeiling () { return (movement.collisionFlags & CollisionFlags.CollidedAbove) != 0; } function IsGrounded () { return grounded; } function TooSteep () { return (groundNormal.y <= Mathf.Cos(controller.slopeLimit * Mathf.Deg2Rad)); } function GetDirection () { return inputMoveDirection; } function SetControllable (controllable : boolean) { canControl = controllable; } // Project a direction onto elliptical quater segments based on forward, sideways, and backwards speed. // The function returns the length of the resulting vector. function MaxSpeedInDirection (desiredMovementDirection : Vector3) : float { if (desiredMovementDirection == Vector3.zero) return 0; else { var zAxisEllipseMultiplier : float = (desiredMovementDirection.z > 0 ? movement.maxForwardSpeed : movement.maxBackwardsSpeed) / movement.maxSidewaysSpeed; var temp : Vector3 = new Vector3(desiredMovementDirection.x, 0, desiredMovementDirection.z / zAxisEllipseMultiplier).normalized; var length : float = new Vector3(temp.x, 0, temp.z * zAxisEllipseMultiplier).magnitude * movement.maxSidewaysSpeed; return length; } } function SetVelocity (velocity : Vector3) { grounded = false; movement.velocity = velocity; movement.frameVelocity = Vector3.zero; SendMessage("OnExternalVelocity"); } // Require a character controller to be attached to the same game object @script RequireComponent (CharacterController) @script AddComponentMenu ("Character/Character Motor")
JavaScript
// This makes the character turn to face the current movement speed per default. var autoRotate : boolean = true; var maxRotationSpeed : float = 360; private var motor : CharacterMotor; // Use this for initialization function Awake () { motor = GetComponent(CharacterMotor); } // Update is called once per frame function Update () { // Get the input vector from kayboard or analog stick var directionVector = new Vector3(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"), 0); if (directionVector != Vector3.zero) { // Get the length of the directon vector and then normalize it // Dividing by the length is cheaper than normalizing when we already have the length anyway var directionLength = directionVector.magnitude; directionVector = directionVector / directionLength; // Make sure the length is no bigger than 1 directionLength = Mathf.Min(1, directionLength); // Make the input vector more sensitive towards the extremes and less sensitive in the middle // This makes it easier to control slow speeds when using analog sticks directionLength = directionLength * directionLength; // Multiply the normalized direction vector by the modified length directionVector = directionVector * directionLength; } // Rotate the input vector into camera space so up is camera's up and right is camera's right directionVector = Camera.main.transform.rotation * directionVector; // Rotate input vector to be perpendicular to character's up vector var camToCharacterSpace = Quaternion.FromToRotation(-Camera.main.transform.forward, transform.up); directionVector = (camToCharacterSpace * directionVector); // Apply the direction to the CharacterMotor motor.inputMoveDirection = directionVector; motor.inputJump = Input.GetButton("Jump"); // Set rotation to the move direction if (autoRotate && directionVector.sqrMagnitude > 0.01) { var newForward : Vector3 = ConstantSlerp( transform.forward, directionVector, maxRotationSpeed * Time.deltaTime ); newForward = ProjectOntoPlane(newForward, transform.up); transform.rotation = Quaternion.LookRotation(newForward, transform.up); } } function ProjectOntoPlane (v : Vector3, normal : Vector3) { return v - Vector3.Project(v, normal); } function ConstantSlerp (from : Vector3, to : Vector3, angle : float) { var value : float = Mathf.Min(1, angle / Vector3.Angle(from, to)); return Vector3.Slerp(from, to, value); } // Require a character controller to be attached to the same game object @script RequireComponent (CharacterMotor) @script AddComponentMenu ("Character/Platform Input Controller")
JavaScript
private var motor : CharacterMotor; // Use this for initialization function Awake () { motor = GetComponent(CharacterMotor); } // Update is called once per frame function Update () { // Get the input vector from kayboard or analog stick var directionVector = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")); if (directionVector != Vector3.zero) { // Get the length of the directon vector and then normalize it // Dividing by the length is cheaper than normalizing when we already have the length anyway var directionLength = directionVector.magnitude; directionVector = directionVector / directionLength; // Make sure the length is no bigger than 1 directionLength = Mathf.Min(1, directionLength); // Make the input vector more sensitive towards the extremes and less sensitive in the middle // This makes it easier to control slow speeds when using analog sticks directionLength = directionLength * directionLength; // Multiply the normalized direction vector by the modified length directionVector = directionVector * directionLength; } // Apply the direction to the CharacterMotor motor.inputMoveDirection = transform.rotation * directionVector; motor.inputJump = Input.GetButton("Jump"); } // Require a character controller to be attached to the same game object @script RequireComponent (CharacterMotor) @script AddComponentMenu ("Character/FPS Input Controller")
JavaScript
// Require a character controller to be attached to the same game object @script RequireComponent(CharacterController) public var idleAnimation : AnimationClip; public var walkAnimation : AnimationClip; public var runAnimation : AnimationClip; public var jumpPoseAnimation : AnimationClip; public var walkMaxAnimationSpeed : float = 1.0; public var trotMaxAnimationSpeed : float = 1.0; public var runMaxAnimationSpeed : float = 1.0; public var jumpAnimationSpeed : float = 1.0; public var landAnimationSpeed : float = 1.0; private var _animation : Animation; enum CharacterState { Idle = 0, Walking = 1, Trotting = 2, Running = 3, Jumping = 4, } private var _characterState : CharacterState; // The speed when walking var walkSpeed = 4.0; // after trotAfterSeconds of walking we trot with trotSpeed var trotSpeed = 4.0; // when pressing "Run" button (cmd) we start running var runSpeed = 4.0; var inAirControlAcceleration = 0.1; // How high do we jump when pressing jump and letting go immediately var jumpHeight = 0.5; // The gravity for the character var gravity = 20.0; // The gravity in controlled descent mode var speedSmoothing = 10.0; var rotateSpeed = 500.0; var trotAfterSeconds = 3.0; var canJump = true; private var jumpRepeatTime = 0.05; private var jumpTimeout = 0.15; private var groundedTimeout = 0.25; // The camera doesnt start following the target immediately but waits for a split second to avoid too much waving around. private var lockCameraTimer = 0.0; // The current move direction in x-z private var moveDirection = Vector3.zero; // The current vertical speed private var verticalSpeed = 0.0; // The current x-z move speed private var moveSpeed = 0.0; // The last collision flags returned from controller.Move private var collisionFlags : CollisionFlags; // Are we jumping? (Initiated with jump button and not grounded yet) private var jumping = false; private var jumpingReachedApex = false; // Are we moving backwards (This locks the camera to not do a 180 degree spin) private var movingBack = false; // Is the user pressing any keys? private var isMoving = false; // When did the user start walking (Used for going into trot after a while) private var walkTimeStart = 0.0; // Last time the jump button was clicked down private var lastJumpButtonTime = -10.0; // Last time we performed a jump private var lastJumpTime = -1.0; // the height we jumped from (Used to determine for how long to apply extra jump power after jumping.) private var lastJumpStartHeight = 0.0; private var inAirVelocity = Vector3.zero; private var lastGroundedTime = 0.0; private var isControllable = true; private var maxJumps = 2; private var numJumps = 0; private var curTrack = 0; //====================================================================== // methods //====================================================================== function Awake () { moveDirection = transform.TransformDirection(Vector3.forward); _animation = GetComponent(Animation); if(!_animation) Debug.Log("The character you would like to control doesn't have animations. Moving her might look weird."); //public var idleAnimation : AnimationClip; //public var walkAnimation : AnimationClip; //public var runAnimation : AnimationClip; //public var jumpPoseAnimation : AnimationClip; if(!idleAnimation) { _animation = null; Debug.Log("No idle animation found. Turning off animations."); } if(!walkAnimation) { _animation = null; Debug.Log("No walk animation found. Turning off animations."); } if(!runAnimation) { _animation = null; Debug.Log("No run animation found. Turning off animations."); } if(!jumpPoseAnimation && canJump) { _animation = null; Debug.Log("No jump animation found and the character has canJump enabled. Turning off animations."); } } function UpdateSmoothedMovementDirection () { var colorStart : Color = Color.red; var colorEnd : Color = Color.green; var duration : float = 1.0; //do nothing when up or down is pressed -jmk //if (Input.GetAxis("Vertical") > 0.0 || Input.GetAxis("Vertical") < 0.0) // return; //Toggle between tracks when Y is pushed if (Input.GetButtonUp("Toggle") || Input.GetKeyUp (KeyCode.Z)){ if (curTrack == 0){ curTrack = 1; transform.position.z += 5.0; //transform.position.y += 0.05; transform.localScale -= Vector3(0.06, 0.059, 0.06); } else { curTrack = 0; transform.position.z -= 5.0; transform.position.y += 0.06; transform.localScale += Vector3(0.06, 0.059, 0.06); } } //else //{ //proceed -jmk var cameraTransform = Camera.main.transform; var grounded = IsGrounded(); // Forward vector relative to the camera along the x-z plane var forward = cameraTransform.TransformDirection(Vector3.forward); forward.y = 0; forward = forward.normalized; // Right vector relative to the camera // Always orthogonal to the forward vector var right = Vector3(forward.z, 0, -forward.x); var v = 0.0; var h = Input.GetAxisRaw("Horizontal"); // Are we moving backwards or looking backwards if (v < -0.2) movingBack = true; else movingBack = false; var wasMoving = isMoving; isMoving = Mathf.Abs (h) > 0.1 || Mathf.Abs (v) > 0.1; // Target direction relative to the camera var targetDirection = h * right + v * forward; // Grounded controls if (grounded) { // Lock camera for short period when transitioning moving & standing still lockCameraTimer += Time.deltaTime; if (isMoving != wasMoving) lockCameraTimer = 1.0; //disable ground check -jmk } // We store speed and direction seperately, // so that when the character stands still we still have a valid forward direction // moveDirection is always normalized, and we only update it if there is user input. if (targetDirection != Vector3.zero) { // If we are really slow, just snap to the target direction if (moveSpeed < walkSpeed * 0.9 && grounded) { moveDirection = targetDirection.normalized; } // Otherwise smoothly turn towards it else { moveDirection = targetDirection.normalized; //disable turning -jmk moveDirection = Vector3.RotateTowards(moveDirection, targetDirection, rotateSpeed * Mathf.Deg2Rad * Time.deltaTime, 1000); moveDirection = moveDirection.normalized; } } // Smooth the speed based on the current target direction var curSmooth = speedSmoothing * Time.deltaTime; // Choose target speed //* We want to support analog input but make sure you cant walk faster diagonally than just forward or sideways var targetSpeed = Mathf.Min(targetDirection.magnitude, 1.0); _characterState = CharacterState.Idle; // Pick speed modifier if (Input.GetKey (KeyCode.DownArrow) || Input.GetButton("Run")) { targetSpeed *= runSpeed; _characterState = CharacterState.Running; } else if (Time.time - trotAfterSeconds > walkTimeStart) { targetSpeed *= trotSpeed; //_characterState = CharacterState.Trotting; _characterState = CharacterState.Running; } else { targetSpeed *= walkSpeed; //_characterState = CharacterState.Walking; _characterState = CharacterState.Running; } moveSpeed = Mathf.Lerp(moveSpeed, targetSpeed, curSmooth); // Reset walk time start when we slow down if (moveSpeed < walkSpeed * 0.3) walkTimeStart = Time.time; //disable ground check -jmk //} // In air controls else { // Lock camera while in air if (jumping) lockCameraTimer = 0.0; if (isMoving) inAirVelocity += targetDirection.normalized * Time.deltaTime * inAirControlAcceleration; } //} } function ApplyJumping () { // Prevent jumping too fast after each other if (lastJumpTime + jumpRepeatTime > Time.time) return; if (IsGrounded()) numJumps = maxJumps; //disable ground check -jmk if ( numJumps > 0) { // Smooth the speed based on the current target direction // Jump // - Only when pressing the button down // - With a timeout so you can press the button slightly before landing if (canJump && Time.time < lastJumpButtonTime + jumpTimeout) { numJumps -= 1; _characterState = CharacterState.Jumping; verticalSpeed = CalculateJumpVerticalSpeed (jumpHeight); SendMessage("DidJump", SendMessageOptions.DontRequireReceiver); } } } function ApplyGravity () { if (isControllable) // don't move player at all if not controllable. { // Apply gravity var jumpButton = Input.GetButton("Jump"); // When we reach the apex of the jump we send out a message if (jumping && !jumpingReachedApex && verticalSpeed <= 0.0) { jumpingReachedApex = true; SendMessage("DidJumpReachApex", SendMessageOptions.DontRequireReceiver); } if (IsGrounded ()) verticalSpeed = 0.0; else verticalSpeed -= gravity * Time.deltaTime; } } function CalculateJumpVerticalSpeed (targetJumpHeight : float) { // From the jump height and gravity we deduce the upwards speed // for the character to reach at the apex. return Mathf.Sqrt(2 * targetJumpHeight * gravity); } function DidJump () { jumping = true; jumpingReachedApex = false; lastJumpTime = Time.time; lastJumpStartHeight = transform.position.y; lastJumpButtonTime = -10; _characterState = CharacterState.Jumping; } function Update() { if (!isControllable) { // kill all inputs if not controllable. Input.ResetInputAxes(); } if (Input.GetButtonDown ("Jump")) { lastJumpButtonTime = Time.time; } UpdateSmoothedMovementDirection(); // Apply gravity // - extra power jump modifies gravity // - controlledDescent mode modifies gravity ApplyGravity (); // Apply jumping logic ApplyJumping (); // Calculate actual motion var movement = moveDirection * moveSpeed + Vector3 (0, verticalSpeed, 0) + inAirVelocity; movement *= Time.deltaTime; // Move the controller var controller : CharacterController = GetComponent(CharacterController); collisionFlags = controller.Move(movement); // ANIMATION sector if(_animation) { if(_characterState == CharacterState.Jumping) { if(!jumpingReachedApex) { _animation[jumpPoseAnimation.name].speed = jumpAnimationSpeed; _animation[jumpPoseAnimation.name].wrapMode = WrapMode.ClampForever; _animation.CrossFade(jumpPoseAnimation.name); } else { _animation[jumpPoseAnimation.name].speed = -landAnimationSpeed; _animation[jumpPoseAnimation.name].wrapMode = WrapMode.ClampForever; _animation.CrossFade(jumpPoseAnimation.name); } } else { if(controller.velocity.sqrMagnitude < 0.1) { _animation.CrossFade(idleAnimation.name); } else { if(_characterState == CharacterState.Running) { _animation[runAnimation.name].speed = Mathf.Clamp(controller.velocity.magnitude, 0.0, runMaxAnimationSpeed); _animation.CrossFade(runAnimation.name); } else if(_characterState == CharacterState.Trotting) { _animation[walkAnimation.name].speed = Mathf.Clamp(controller.velocity.magnitude, 0.0, trotMaxAnimationSpeed); _animation.CrossFade(walkAnimation.name); } else if(_characterState == CharacterState.Walking) { _animation[walkAnimation.name].speed = Mathf.Clamp(controller.velocity.magnitude, 0.0, walkMaxAnimationSpeed); _animation.CrossFade(walkAnimation.name); } } } } // ANIMATION sector // Set rotation to the move direction if (IsGrounded()) { transform.rotation = Quaternion.LookRotation(moveDirection); } else { var xzMove = movement; xzMove.y = 0; if (xzMove.sqrMagnitude > 0.001) { transform.rotation = Quaternion.LookRotation(xzMove); } } // We are in jump mode but just became grounded if (IsGrounded()) { lastGroundedTime = Time.time; inAirVelocity = Vector3.zero; if (jumping) { jumping = false; SendMessage("DidLand", SendMessageOptions.DontRequireReceiver); } } } function OnControllerColliderHit (hit : ControllerColliderHit ) { // Debug.DrawRay(hit.point, hit.normal); if (hit.moveDirection.y > 0.01) return; } function GetSpeed () { return moveSpeed; } function IsJumping () { return jumping; } function IsGrounded () { return (collisionFlags & CollisionFlags.CollidedBelow) != 0; } function GetDirection () { return moveDirection; } function IsMovingBackwards () { return movingBack; } function GetLockCameraTimer () { return lockCameraTimer; } function IsMoving () : boolean { return Mathf.Abs(Input.GetAxisRaw("Vertical")) + Mathf.Abs(Input.GetAxisRaw("Horizontal")) > 0.5; } function HasJumpReachedApex () { return jumpingReachedApex; } function IsGroundedWithTimeout () { return lastGroundedTime + groundedTimeout > Time.time; } function Reset () { gameObject.tag = "Player"; }
JavaScript
function showMessage(msg, title, delay){ $('') } function removeMessage(id){ }
JavaScript
function addAccount(user,pass,handler){ $.post('/bots/manager',{'action':1,'user':user,'pass':pass},handler); }
JavaScript
function showDialog(dlgid, modal){ var dlg = $('#'+dlgid).removeClass('hide'); var dlgbg = $('#'+dlgid+'_bg'); if(dlgbg.length==0){ dlgbg = $('<div id="'+dlgid+'_bg" class="dlgbg dlgbdr"></div>').appendTo(document.body); } dlgbg.removeClass('hide'); var doc = $(document); var x = (doc.width() - dlg.width()) / 2; var y = (doc.height() - dlg.height()) * 0.3; dlgbg.width(dlg.width()+8).height(dlg.height()+8).css({left:x+'px',top:y+'px'}); dlg.css({'left':(x+4)+'px',top:(y+4)+'px'}); if(modal){ var dlgover = $('#dialog_overlap'); if(dlgover.length==0) dlgover = $('<div id="dialog_overlap" class="dlgover"></div>').appendTo(document.body); dlgover.removeClass('hide'); } } function hideDialog(dlgid){ $('#'+dlgid).addClass('hide'); $('#'+dlgid+'_bg').addClass('hide'); $('#dialog_overlap').addClass('hide'); }
JavaScript
BrowserHistoryUtils = { addEvent: function(elm, evType, fn, useCapture) { useCapture = useCapture || false; if (elm.addEventListener) { elm.addEventListener(evType, fn, useCapture); return true; } else if (elm.attachEvent) { var r = elm.attachEvent('on' + evType, fn); return r; } else { elm['on' + evType] = fn; } } } BrowserHistory = (function() { // type of browser var browser = { ie: false, ie8: false, firefox: false, safari: false, opera: false, version: -1 }; // if setDefaultURL has been called, our first clue // that the SWF is ready and listening //var swfReady = false; // the URL we'll send to the SWF once it is ready //var pendingURL = ''; // Default app state URL to use when no fragment ID present var defaultHash = ''; // Last-known app state URL var currentHref = document.location.href; // Initial URL (used only by IE) var initialHref = document.location.href; // Initial URL (used only by IE) var initialHash = document.location.hash; // History frame source URL prefix (used only by IE) var historyFrameSourcePrefix = 'history/historyFrame.html?'; // History maintenance (used only by Safari) var currentHistoryLength = -1; var historyHash = []; var initialState = createState(initialHref, initialHref + '#' + initialHash, initialHash); var backStack = []; var forwardStack = []; var currentObjectId = null; //UserAgent detection var useragent = navigator.userAgent.toLowerCase(); if (useragent.indexOf("opera") != -1) { browser.opera = true; } else if (useragent.indexOf("msie") != -1) { browser.ie = true; browser.version = parseFloat(useragent.substring(useragent.indexOf('msie') + 4)); if (browser.version == 8) { browser.ie = false; browser.ie8 = true; } } else if (useragent.indexOf("safari") != -1) { browser.safari = true; browser.version = parseFloat(useragent.substring(useragent.indexOf('safari') + 7)); } else if (useragent.indexOf("gecko") != -1) { browser.firefox = true; } if (browser.ie == true && browser.version == 7) { window["_ie_firstload"] = false; } function hashChangeHandler() { currentHref = document.location.href; var flexAppUrl = getHash(); //ADR: to fix multiple if (typeof BrowserHistory_multiple != "undefined" && BrowserHistory_multiple == true) { var pl = getPlayers(); for (var i = 0; i < pl.length; i++) { pl[i].browserURLChange(flexAppUrl); } } else { getPlayer().browserURLChange(flexAppUrl); } } // Accessor functions for obtaining specific elements of the page. function getHistoryFrame() { return document.getElementById('ie_historyFrame'); } function getAnchorElement() { return document.getElementById('firefox_anchorDiv'); } function getFormElement() { return document.getElementById('safari_formDiv'); } function getRememberElement() { return document.getElementById("safari_remember_field"); } // Get the Flash player object for performing ExternalInterface callbacks. // Updated for changes to SWFObject2. function getPlayer(id) { var i; if (id && document.getElementById(id)) { var r = document.getElementById(id); if (typeof r.SetVariable != "undefined") { return r; } else { var o = r.getElementsByTagName("object"); var e = r.getElementsByTagName("embed"); for (i = 0; i < o.length; i++) { if (typeof o[i].browserURLChange != "undefined") return o[i]; } for (i = 0; i < e.length; i++) { if (typeof e[i].browserURLChange != "undefined") return e[i]; } } } else { var o = document.getElementsByTagName("object"); var e = document.getElementsByTagName("embed"); for (i = 0; i < e.length; i++) { if (typeof e[i].browserURLChange != "undefined") { return e[i]; } } for (i = 0; i < o.length; i++) { if (typeof o[i].browserURLChange != "undefined") { return o[i]; } } } return undefined; } function getPlayers() { var i; var players = []; if (players.length == 0) { var tmp = document.getElementsByTagName('object'); for (i = 0; i < tmp.length; i++) { if (typeof tmp[i].browserURLChange != "undefined") players.push(tmp[i]); } } if (players.length == 0 || players[0].object == null) { var tmp = document.getElementsByTagName('embed'); for (i = 0; i < tmp.length; i++) { if (typeof tmp[i].browserURLChange != "undefined") players.push(tmp[i]); } } return players; } function getIframeHash() { var doc = getHistoryFrame().contentWindow.document; var hash = String(doc.location.search); if (hash.length == 1 && hash.charAt(0) == "?") { hash = ""; } else if (hash.length >= 2 && hash.charAt(0) == "?") { hash = hash.substring(1); } return hash; } /* Get the current location hash excluding the '#' symbol. */ function getHash() { // It would be nice if we could use document.location.hash here, // but it's faulty sometimes. var idx = document.location.href.indexOf('#'); return (idx >= 0) ? document.location.href.substr(idx+1) : ''; } /* Get the current location hash excluding the '#' symbol. */ function setHash(hash) { // It would be nice if we could use document.location.hash here, // but it's faulty sometimes. if (hash == '') hash = '#' document.location.hash = hash; } function createState(baseUrl, newUrl, flexAppUrl) { return { 'baseUrl': baseUrl, 'newUrl': newUrl, 'flexAppUrl': flexAppUrl, 'title': null }; } /* Add a history entry to the browser. * baseUrl: the portion of the location prior to the '#' * newUrl: the entire new URL, including '#' and following fragment * flexAppUrl: the portion of the location following the '#' only */ function addHistoryEntry(baseUrl, newUrl, flexAppUrl) { //delete all the history entries forwardStack = []; if (browser.ie) { //Check to see if we are being asked to do a navigate for the first //history entry, and if so ignore, because it's coming from the creation //of the history iframe if (flexAppUrl == defaultHash && document.location.href == initialHref && window['_ie_firstload']) { currentHref = initialHref; return; } if ((!flexAppUrl || flexAppUrl == defaultHash) && window['_ie_firstload']) { newUrl = baseUrl + '#' + defaultHash; flexAppUrl = defaultHash; } else { // for IE, tell the history frame to go somewhere without a '#' // in order to get this entry into the browser history. getHistoryFrame().src = historyFrameSourcePrefix + flexAppUrl; } setHash(flexAppUrl); } else { //ADR if (backStack.length == 0 && initialState.flexAppUrl == flexAppUrl) { initialState = createState(baseUrl, newUrl, flexAppUrl); } else if(backStack.length > 0 && backStack[backStack.length - 1].flexAppUrl == flexAppUrl) { backStack[backStack.length - 1] = createState(baseUrl, newUrl, flexAppUrl); } if (browser.safari) { // for Safari, submit a form whose action points to the desired URL if (browser.version <= 419.3) { var file = window.location.pathname.toString(); file = file.substring(file.lastIndexOf("/")+1); getFormElement().innerHTML = '<form name="historyForm" action="'+file+'#' + flexAppUrl + '" method="GET"></form>'; //get the current elements and add them to the form var qs = window.location.search.substring(1); var qs_arr = qs.split("&"); for (var i = 0; i < qs_arr.length; i++) { var tmp = qs_arr[i].split("="); var elem = document.createElement("input"); elem.type = "hidden"; elem.name = tmp[0]; elem.value = tmp[1]; document.forms.historyForm.appendChild(elem); } document.forms.historyForm.submit(); } else { top.location.hash = flexAppUrl; } // We also have to maintain the history by hand for Safari historyHash[history.length] = flexAppUrl; _storeStates(); } else { // Otherwise, write an anchor into the page and tell the browser to go there addAnchor(flexAppUrl); setHash(flexAppUrl); // For IE8 we must restore full focus/activation to our invoking player instance. if (browser.ie8) getPlayer().focus(); } } backStack.push(createState(baseUrl, newUrl, flexAppUrl)); } function _storeStates() { if (browser.safari) { getRememberElement().value = historyHash.join(","); } } function handleBackButton() { //The "current" page is always at the top of the history stack. var current = backStack.pop(); if (!current) { return; } var last = backStack[backStack.length - 1]; if (!last && backStack.length == 0){ last = initialState; } forwardStack.push(current); } function handleForwardButton() { //summary: private method. Do not call this directly. var last = forwardStack.pop(); if (!last) { return; } backStack.push(last); } function handleArbitraryUrl() { //delete all the history entries forwardStack = []; } /* Called periodically to poll to see if we need to detect navigation that has occurred */ function checkForUrlChange() { if (browser.ie) { if (currentHref != document.location.href && currentHref + '#' != document.location.href) { //This occurs when the user has navigated to a specific URL //within the app, and didn't use browser back/forward //IE seems to have a bug where it stops updating the URL it //shows the end-user at this point, but programatically it //appears to be correct. Do a full app reload to get around //this issue. if (browser.version < 7) { currentHref = document.location.href; document.location.reload(); } else { if (getHash() != getIframeHash()) { // this.iframe.src = this.blankURL + hash; var sourceToSet = historyFrameSourcePrefix + getHash(); getHistoryFrame().src = sourceToSet; currentHref = document.location.href; } } } } if (browser.safari) { // For Safari, we have to check to see if history.length changed. if (currentHistoryLength >= 0 && history.length != currentHistoryLength) { //alert("did change: " + history.length + ", " + historyHash.length + "|" + historyHash[history.length] + "|>" + historyHash.join("|")); var flexAppUrl = getHash(); if (browser.version < 528.16 /* Anything earlier than Safari 4.0 */) { // If it did change and we're running Safari 3.x or earlier, // then we have to look the old state up in our hand-maintained // array since document.location.hash won't have changed, // then call back into BrowserManager. currentHistoryLength = history.length; flexAppUrl = historyHash[currentHistoryLength]; } //ADR: to fix multiple if (typeof BrowserHistory_multiple != "undefined" && BrowserHistory_multiple == true) { var pl = getPlayers(); for (var i = 0; i < pl.length; i++) { pl[i].browserURLChange(flexAppUrl); } } else { getPlayer().browserURLChange(flexAppUrl); } _storeStates(); } } if (browser.firefox) { if (currentHref != document.location.href) { var bsl = backStack.length; var urlActions = { back: false, forward: false, set: false } if ((window.location.hash == initialHash || window.location.href == initialHref) && (bsl == 1)) { urlActions.back = true; // FIXME: could this ever be a forward button? // we can't clear it because we still need to check for forwards. Ugg. // clearInterval(this.locationTimer); handleBackButton(); } // first check to see if we could have gone forward. We always halt on // a no-hash item. if (forwardStack.length > 0) { if (forwardStack[forwardStack.length-1].flexAppUrl == getHash()) { urlActions.forward = true; handleForwardButton(); } } // ok, that didn't work, try someplace back in the history stack if ((bsl >= 2) && (backStack[bsl - 2])) { if (backStack[bsl - 2].flexAppUrl == getHash()) { urlActions.back = true; handleBackButton(); } } if (!urlActions.back && !urlActions.forward) { var foundInStacks = { back: -1, forward: -1 } for (var i = 0; i < backStack.length; i++) { if (backStack[i].flexAppUrl == getHash() && i != (bsl - 2)) { arbitraryUrl = true; foundInStacks.back = i; } } for (var i = 0; i < forwardStack.length; i++) { if (forwardStack[i].flexAppUrl == getHash() && i != (bsl - 2)) { arbitraryUrl = true; foundInStacks.forward = i; } } handleArbitraryUrl(); } // Firefox changed; do a callback into BrowserManager to tell it. currentHref = document.location.href; var flexAppUrl = getHash(); //ADR: to fix multiple if (typeof BrowserHistory_multiple != "undefined" && BrowserHistory_multiple == true) { var pl = getPlayers(); for (var i = 0; i < pl.length; i++) { pl[i].browserURLChange(flexAppUrl); } } else { getPlayer().browserURLChange(flexAppUrl); } } } //setTimeout(checkForUrlChange, 50); } /* Write an anchor into the page to legitimize it as a URL for Firefox et al. */ function addAnchor(flexAppUrl) { if (document.getElementsByName(flexAppUrl).length == 0) { getAnchorElement().innerHTML += "<a name='" + flexAppUrl + "'>" + flexAppUrl + "</a>"; } } var _initialize = function () { if (browser.ie) { var scripts = document.getElementsByTagName('script'); for (var i = 0, s; s = scripts[i]; i++) { if (s.src.indexOf("history.js") > -1) { var iframe_location = (new String(s.src)).replace("history.js", "historyFrame.html"); } } historyFrameSourcePrefix = iframe_location + "?"; var src = historyFrameSourcePrefix; var iframe = document.createElement("iframe"); iframe.id = 'ie_historyFrame'; iframe.name = 'ie_historyFrame'; iframe.src = 'javascript:false;'; try { document.body.appendChild(iframe); } catch(e) { setTimeout(function() { document.body.appendChild(iframe); }, 0); } } if (browser.safari) { var rememberDiv = document.createElement("div"); rememberDiv.id = 'safari_rememberDiv'; document.body.appendChild(rememberDiv); rememberDiv.innerHTML = '<input type="text" id="safari_remember_field" style="width: 500px;">'; var formDiv = document.createElement("div"); formDiv.id = 'safari_formDiv'; document.body.appendChild(formDiv); var reloader_content = document.createElement('div'); reloader_content.id = 'safarireloader'; var scripts = document.getElementsByTagName('script'); for (var i = 0, s; s = scripts[i]; i++) { if (s.src.indexOf("history.js") > -1) { html = (new String(s.src)).replace(".js", ".html"); } } reloader_content.innerHTML = '<iframe id="safarireloader-iframe" src="about:blank" frameborder="no" scrolling="no"></iframe>'; document.body.appendChild(reloader_content); reloader_content.style.position = 'absolute'; reloader_content.style.left = reloader_content.style.top = '-9999px'; iframe = reloader_content.getElementsByTagName('iframe')[0]; if (document.getElementById("safari_remember_field").value != "" ) { historyHash = document.getElementById("safari_remember_field").value.split(","); } } if (browser.firefox || browser.ie8) { var anchorDiv = document.createElement("div"); anchorDiv.id = 'firefox_anchorDiv'; document.body.appendChild(anchorDiv); } if (browser.ie8) document.body.onhashchange = hashChangeHandler; //setTimeout(checkForUrlChange, 50); } return { historyHash: historyHash, backStack: function() { return backStack; }, forwardStack: function() { return forwardStack }, getPlayer: getPlayer, initialize: function(src) { _initialize(src); }, setURL: function(url) { document.location.href = url; }, getURL: function() { return document.location.href; }, getTitle: function() { return document.title; }, setTitle: function(title) { try { backStack[backStack.length - 1].title = title; } catch(e) { } //if on safari, set the title to be the empty string. if (browser.safari) { if (title == "") { try { var tmp = window.location.href.toString(); title = tmp.substring((tmp.lastIndexOf("/")+1), tmp.lastIndexOf("#")); } catch(e) { title = ""; } } } document.title = title; }, setDefaultURL: function(def) { defaultHash = def; def = getHash(); //trailing ? is important else an extra frame gets added to the history //when navigating back to the first page. Alternatively could check //in history frame navigation to compare # and ?. if (browser.ie) { window['_ie_firstload'] = true; var sourceToSet = historyFrameSourcePrefix + def; var func = function() { getHistoryFrame().src = sourceToSet; window.location.replace("#" + def); setInterval(checkForUrlChange, 50); } try { func(); } catch(e) { window.setTimeout(function() { func(); }, 0); } } if (browser.safari) { currentHistoryLength = history.length; if (historyHash.length == 0) { historyHash[currentHistoryLength] = def; var newloc = "#" + def; window.location.replace(newloc); } else { //alert(historyHash[historyHash.length-1]); } //setHash(def); setInterval(checkForUrlChange, 50); } if (browser.firefox || browser.opera) { var reg = new RegExp("#" + def + "$"); if (window.location.toString().match(reg)) { } else { var newloc ="#" + def; window.location.replace(newloc); } setInterval(checkForUrlChange, 50); //setHash(def); } }, /* Set the current browser URL; called from inside BrowserManager to propagate * the application state out to the container. */ setBrowserURL: function(flexAppUrl, objectId) { if (browser.ie && typeof objectId != "undefined") { currentObjectId = objectId; } //fromIframe = fromIframe || false; //fromFlex = fromFlex || false; //alert("setBrowserURL: " + flexAppUrl); //flexAppUrl = (flexAppUrl == "") ? defaultHash : flexAppUrl ; var pos = document.location.href.indexOf('#'); var baseUrl = pos != -1 ? document.location.href.substr(0, pos) : document.location.href; var newUrl = baseUrl + '#' + flexAppUrl; if (document.location.href != newUrl && document.location.href + '#' != newUrl) { currentHref = newUrl; addHistoryEntry(baseUrl, newUrl, flexAppUrl); currentHistoryLength = history.length; } }, browserURLChange: function(flexAppUrl) { var objectId = null; if (browser.ie && currentObjectId != null) { objectId = currentObjectId; } pendingURL = ''; if (typeof BrowserHistory_multiple != "undefined" && BrowserHistory_multiple == true) { var pl = getPlayers(); for (var i = 0; i < pl.length; i++) { try { pl[i].browserURLChange(flexAppUrl); } catch(e) { } } } else { try { getPlayer(objectId).browserURLChange(flexAppUrl); } catch(e) { } } currentObjectId = null; }, getUserAgent: function() { return navigator.userAgent; }, getPlatform: function() { return navigator.platform; } } })(); // Initialization // Automated unit testing and other diagnostics function setURL(url) { document.location.href = url; } function backButton() { history.back(); } function forwardButton() { history.forward(); } function goForwardOrBackInHistory(step) { history.go(step); } //BrowserHistoryUtils.addEvent(window, "load", function() { BrowserHistory.initialize(); }); (function(i) { var u =navigator.userAgent;var e=/*@cc_on!@*/false; var st = setTimeout; if(/webkit/i.test(u)){ st(function(){ var dr=document.readyState; if(dr=="loaded"||dr=="complete"){i()} else{st(arguments.callee,10);}},10); } else if((/mozilla/i.test(u)&&!/(compati)/.test(u)) || (/opera/i.test(u))){ document.addEventListener("DOMContentLoaded",i,false); } else if(e){ (function(){ var t=document.createElement('doc:rdy'); try{t.doScroll('left'); i();t=null; }catch(e){st(arguments.callee,0);}})(); } else{ window.onload=i; } })( function() {BrowserHistory.initialize();} );
JavaScript
/*! SWFObject v2.2 <http://code.google.com/p/swfobject/> is released under the MIT License <http://www.opensource.org/licenses/mit-license.php> */ var swfobject = function() { var UNDEF = "undefined", OBJECT = "object", SHOCKWAVE_FLASH = "Shockwave Flash", SHOCKWAVE_FLASH_AX = "ShockwaveFlash.ShockwaveFlash", FLASH_MIME_TYPE = "application/x-shockwave-flash", EXPRESS_INSTALL_ID = "SWFObjectExprInst", ON_READY_STATE_CHANGE = "onreadystatechange", win = window, doc = document, nav = navigator, plugin = false, domLoadFnArr = [main], regObjArr = [], objIdArr = [], listenersArr = [], storedAltContent, storedAltContentId, storedCallbackFn, storedCallbackObj, isDomLoaded = false, isExpressInstallActive = false, dynamicStylesheet, dynamicStylesheetMedia, autoHideShow = true, /* Centralized function for browser feature detection - User agent string detection is only used when no good alternative is possible - Is executed directly for optimal performance */ ua = function() { var w3cdom = typeof doc.getElementById != UNDEF && typeof doc.getElementsByTagName != UNDEF && typeof doc.createElement != UNDEF, u = nav.userAgent.toLowerCase(), p = nav.platform.toLowerCase(), windows = p ? /win/.test(p) : /win/.test(u), mac = p ? /mac/.test(p) : /mac/.test(u), webkit = /webkit/.test(u) ? parseFloat(u.replace(/^.*webkit\/(\d+(\.\d+)?).*$/, "$1")) : false, // returns either the webkit version or false if not webkit ie = !+"\v1", // feature detection based on Andrea Giammarchi's solution: http://webreflection.blogspot.com/2009/01/32-bytes-to-know-if-your-browser-is-ie.html playerVersion = [0,0,0], d = null; if (typeof nav.plugins != UNDEF && typeof nav.plugins[SHOCKWAVE_FLASH] == OBJECT) { d = nav.plugins[SHOCKWAVE_FLASH].description; if (d && !(typeof nav.mimeTypes != UNDEF && nav.mimeTypes[FLASH_MIME_TYPE] && !nav.mimeTypes[FLASH_MIME_TYPE].enabledPlugin)) { // navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin indicates whether plug-ins are enabled or disabled in Safari 3+ plugin = true; ie = false; // cascaded feature detection for Internet Explorer d = d.replace(/^.*\s+(\S+\s+\S+$)/, "$1"); playerVersion[0] = parseInt(d.replace(/^(.*)\..*$/, "$1"), 10); playerVersion[1] = parseInt(d.replace(/^.*\.(.*)\s.*$/, "$1"), 10); playerVersion[2] = /[a-zA-Z]/.test(d) ? parseInt(d.replace(/^.*[a-zA-Z]+(.*)$/, "$1"), 10) : 0; } } else if (typeof win.ActiveXObject != UNDEF) { try { var a = new ActiveXObject(SHOCKWAVE_FLASH_AX); if (a) { // a will return null when ActiveX is disabled d = a.GetVariable("$version"); if (d) { ie = true; // cascaded feature detection for Internet Explorer d = d.split(" ")[1].split(","); playerVersion = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)]; } } } catch(e) {} } return { w3:w3cdom, pv:playerVersion, wk:webkit, ie:ie, win:windows, mac:mac }; }(), /* Cross-browser onDomLoad - Will fire an event as soon as the DOM of a web page is loaded - Internet Explorer workaround based on Diego Perini's solution: http://javascript.nwbox.com/IEContentLoaded/ - Regular onload serves as fallback */ onDomLoad = function() { if (!ua.w3) { return; } if ((typeof doc.readyState != UNDEF && doc.readyState == "complete") || (typeof doc.readyState == UNDEF && (doc.getElementsByTagName("body")[0] || doc.body))) { // function is fired after onload, e.g. when script is inserted dynamically callDomLoadFunctions(); } if (!isDomLoaded) { if (typeof doc.addEventListener != UNDEF) { doc.addEventListener("DOMContentLoaded", callDomLoadFunctions, false); } if (ua.ie && ua.win) { doc.attachEvent(ON_READY_STATE_CHANGE, function() { if (doc.readyState == "complete") { doc.detachEvent(ON_READY_STATE_CHANGE, arguments.callee); callDomLoadFunctions(); } }); if (win == top) { // if not inside an iframe (function(){ if (isDomLoaded) { return; } try { doc.documentElement.doScroll("left"); } catch(e) { setTimeout(arguments.callee, 0); return; } callDomLoadFunctions(); })(); } } if (ua.wk) { (function(){ if (isDomLoaded) { return; } if (!/loaded|complete/.test(doc.readyState)) { setTimeout(arguments.callee, 0); return; } callDomLoadFunctions(); })(); } addLoadEvent(callDomLoadFunctions); } }(); function callDomLoadFunctions() { if (isDomLoaded) { return; } try { // test if we can really add/remove elements to/from the DOM; we don't want to fire it too early var t = doc.getElementsByTagName("body")[0].appendChild(createElement("span")); t.parentNode.removeChild(t); } catch (e) { return; } isDomLoaded = true; var dl = domLoadFnArr.length; for (var i = 0; i < dl; i++) { domLoadFnArr[i](); } } function addDomLoadEvent(fn) { if (isDomLoaded) { fn(); } else { domLoadFnArr[domLoadFnArr.length] = fn; // Array.push() is only available in IE5.5+ } } /* Cross-browser onload - Based on James Edwards' solution: http://brothercake.com/site/resources/scripts/onload/ - Will fire an event as soon as a web page including all of its assets are loaded */ function addLoadEvent(fn) { if (typeof win.addEventListener != UNDEF) { win.addEventListener("load", fn, false); } else if (typeof doc.addEventListener != UNDEF) { doc.addEventListener("load", fn, false); } else if (typeof win.attachEvent != UNDEF) { addListener(win, "onload", fn); } else if (typeof win.onload == "function") { var fnOld = win.onload; win.onload = function() { fnOld(); fn(); }; } else { win.onload = fn; } } /* Main function - Will preferably execute onDomLoad, otherwise onload (as a fallback) */ function main() { if (plugin) { testPlayerVersion(); } else { matchVersions(); } } /* Detect the Flash Player version for non-Internet Explorer browsers - Detecting the plug-in version via the object element is more precise than using the plugins collection item's description: a. Both release and build numbers can be detected b. Avoid wrong descriptions by corrupt installers provided by Adobe c. Avoid wrong descriptions by multiple Flash Player entries in the plugin Array, caused by incorrect browser imports - Disadvantage of this method is that it depends on the availability of the DOM, while the plugins collection is immediately available */ function testPlayerVersion() { var b = doc.getElementsByTagName("body")[0]; var o = createElement(OBJECT); o.setAttribute("type", FLASH_MIME_TYPE); var t = b.appendChild(o); if (t) { var counter = 0; (function(){ if (typeof t.GetVariable != UNDEF) { var d = t.GetVariable("$version"); if (d) { d = d.split(" ")[1].split(","); ua.pv = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)]; } } else if (counter < 10) { counter++; setTimeout(arguments.callee, 10); return; } b.removeChild(o); t = null; matchVersions(); })(); } else { matchVersions(); } } /* Perform Flash Player and SWF version matching; static publishing only */ function matchVersions() { var rl = regObjArr.length; if (rl > 0) { for (var i = 0; i < rl; i++) { // for each registered object element var id = regObjArr[i].id; var cb = regObjArr[i].callbackFn; var cbObj = {success:false, id:id}; if (ua.pv[0] > 0) { var obj = getElementById(id); if (obj) { if (hasPlayerVersion(regObjArr[i].swfVersion) && !(ua.wk && ua.wk < 312)) { // Flash Player version >= published SWF version: Houston, we have a match! setVisibility(id, true); if (cb) { cbObj.success = true; cbObj.ref = getObjectById(id); cb(cbObj); } } else if (regObjArr[i].expressInstall && canExpressInstall()) { // show the Adobe Express Install dialog if set by the web page author and if supported var att = {}; att.data = regObjArr[i].expressInstall; att.width = obj.getAttribute("width") || "0"; att.height = obj.getAttribute("height") || "0"; if (obj.getAttribute("class")) { att.styleclass = obj.getAttribute("class"); } if (obj.getAttribute("align")) { att.align = obj.getAttribute("align"); } // parse HTML object param element's name-value pairs var par = {}; var p = obj.getElementsByTagName("param"); var pl = p.length; for (var j = 0; j < pl; j++) { if (p[j].getAttribute("name").toLowerCase() != "movie") { par[p[j].getAttribute("name")] = p[j].getAttribute("value"); } } showExpressInstall(att, par, id, cb); } else { // Flash Player and SWF version mismatch or an older Webkit engine that ignores the HTML object element's nested param elements: display alternative content instead of SWF displayAltContent(obj); if (cb) { cb(cbObj); } } } } else { // if no Flash Player is installed or the fp version cannot be detected we let the HTML object element do its job (either show a SWF or alternative content) setVisibility(id, true); if (cb) { var o = getObjectById(id); // test whether there is an HTML object element or not if (o && typeof o.SetVariable != UNDEF) { cbObj.success = true; cbObj.ref = o; } cb(cbObj); } } } } } function getObjectById(objectIdStr) { var r = null; var o = getElementById(objectIdStr); if (o && o.nodeName == "OBJECT") { if (typeof o.SetVariable != UNDEF) { r = o; } else { var n = o.getElementsByTagName(OBJECT)[0]; if (n) { r = n; } } } return r; } /* Requirements for Adobe Express Install - only one instance can be active at a time - fp 6.0.65 or higher - Win/Mac OS only - no Webkit engines older than version 312 */ function canExpressInstall() { return !isExpressInstallActive && hasPlayerVersion("6.0.65") && (ua.win || ua.mac) && !(ua.wk && ua.wk < 312); } /* Show the Adobe Express Install dialog - Reference: http://www.adobe.com/cfusion/knowledgebase/index.cfm?id=6a253b75 */ function showExpressInstall(att, par, replaceElemIdStr, callbackFn) { isExpressInstallActive = true; storedCallbackFn = callbackFn || null; storedCallbackObj = {success:false, id:replaceElemIdStr}; var obj = getElementById(replaceElemIdStr); if (obj) { if (obj.nodeName == "OBJECT") { // static publishing storedAltContent = abstractAltContent(obj); storedAltContentId = null; } else { // dynamic publishing storedAltContent = obj; storedAltContentId = replaceElemIdStr; } att.id = EXPRESS_INSTALL_ID; if (typeof att.width == UNDEF || (!/%$/.test(att.width) && parseInt(att.width, 10) < 310)) { att.width = "310"; } if (typeof att.height == UNDEF || (!/%$/.test(att.height) && parseInt(att.height, 10) < 137)) { att.height = "137"; } doc.title = doc.title.slice(0, 47) + " - Flash Player Installation"; var pt = ua.ie && ua.win ? "ActiveX" : "PlugIn", fv = "MMredirectURL=" + encodeURI(window.location).toString().replace(/&/g,"%26") + "&MMplayerType=" + pt + "&MMdoctitle=" + doc.title; if (typeof par.flashvars != UNDEF) { par.flashvars += "&" + fv; } else { par.flashvars = fv; } // IE only: when a SWF is loading (AND: not available in cache) wait for the readyState of the object element to become 4 before removing it, // because you cannot properly cancel a loading SWF file without breaking browser load references, also obj.onreadystatechange doesn't work if (ua.ie && ua.win && obj.readyState != 4) { var newObj = createElement("div"); replaceElemIdStr += "SWFObjectNew"; newObj.setAttribute("id", replaceElemIdStr); obj.parentNode.insertBefore(newObj, obj); // insert placeholder div that will be replaced by the object element that loads expressinstall.swf obj.style.display = "none"; (function(){ if (obj.readyState == 4) { obj.parentNode.removeChild(obj); } else { setTimeout(arguments.callee, 10); } })(); } createSWF(att, par, replaceElemIdStr); } } /* Functions to abstract and display alternative content */ function displayAltContent(obj) { if (ua.ie && ua.win && obj.readyState != 4) { // IE only: when a SWF is loading (AND: not available in cache) wait for the readyState of the object element to become 4 before removing it, // because you cannot properly cancel a loading SWF file without breaking browser load references, also obj.onreadystatechange doesn't work var el = createElement("div"); obj.parentNode.insertBefore(el, obj); // insert placeholder div that will be replaced by the alternative content el.parentNode.replaceChild(abstractAltContent(obj), el); obj.style.display = "none"; (function(){ if (obj.readyState == 4) { obj.parentNode.removeChild(obj); } else { setTimeout(arguments.callee, 10); } })(); } else { obj.parentNode.replaceChild(abstractAltContent(obj), obj); } } function abstractAltContent(obj) { var ac = createElement("div"); if (ua.win && ua.ie) { ac.innerHTML = obj.innerHTML; } else { var nestedObj = obj.getElementsByTagName(OBJECT)[0]; if (nestedObj) { var c = nestedObj.childNodes; if (c) { var cl = c.length; for (var i = 0; i < cl; i++) { if (!(c[i].nodeType == 1 && c[i].nodeName == "PARAM") && !(c[i].nodeType == 8)) { ac.appendChild(c[i].cloneNode(true)); } } } } } return ac; } /* Cross-browser dynamic SWF creation */ function createSWF(attObj, parObj, id) { var r, el = getElementById(id); if (ua.wk && ua.wk < 312) { return r; } if (el) { if (typeof attObj.id == UNDEF) { // if no 'id' is defined for the object element, it will inherit the 'id' from the alternative content attObj.id = id; } if (ua.ie && ua.win) { // Internet Explorer + the HTML object element + W3C DOM methods do not combine: fall back to outerHTML var att = ""; for (var i in attObj) { if (attObj[i] != Object.prototype[i]) { // filter out prototype additions from other potential libraries if (i.toLowerCase() == "data") { parObj.movie = attObj[i]; } else if (i.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword att += ' class="' + attObj[i] + '"'; } else if (i.toLowerCase() != "classid") { att += ' ' + i + '="' + attObj[i] + '"'; } } } var par = ""; for (var j in parObj) { if (parObj[j] != Object.prototype[j]) { // filter out prototype additions from other potential libraries par += '<param name="' + j + '" value="' + parObj[j] + '" />'; } } el.outerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"' + att + '>' + par + '</object>'; objIdArr[objIdArr.length] = attObj.id; // stored to fix object 'leaks' on unload (dynamic publishing only) r = getElementById(attObj.id); } else { // well-behaving browsers var o = createElement(OBJECT); o.setAttribute("type", FLASH_MIME_TYPE); for (var m in attObj) { if (attObj[m] != Object.prototype[m]) { // filter out prototype additions from other potential libraries if (m.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword o.setAttribute("class", attObj[m]); } else if (m.toLowerCase() != "classid") { // filter out IE specific attribute o.setAttribute(m, attObj[m]); } } } for (var n in parObj) { if (parObj[n] != Object.prototype[n] && n.toLowerCase() != "movie") { // filter out prototype additions from other potential libraries and IE specific param element createObjParam(o, n, parObj[n]); } } el.parentNode.replaceChild(o, el); r = o; } } return r; } function createObjParam(el, pName, pValue) { var p = createElement("param"); p.setAttribute("name", pName); p.setAttribute("value", pValue); el.appendChild(p); } /* Cross-browser SWF removal - Especially needed to safely and completely remove a SWF in Internet Explorer */ function removeSWF(id) { var obj = getElementById(id); if (obj && obj.nodeName == "OBJECT") { if (ua.ie && ua.win) { obj.style.display = "none"; (function(){ if (obj.readyState == 4) { removeObjectInIE(id); } else { setTimeout(arguments.callee, 10); } })(); } else { obj.parentNode.removeChild(obj); } } } function removeObjectInIE(id) { var obj = getElementById(id); if (obj) { for (var i in obj) { if (typeof obj[i] == "function") { obj[i] = null; } } obj.parentNode.removeChild(obj); } } /* Functions to optimize JavaScript compression */ function getElementById(id) { var el = null; try { el = doc.getElementById(id); } catch (e) {} return el; } function createElement(el) { return doc.createElement(el); } /* Updated attachEvent function for Internet Explorer - Stores attachEvent information in an Array, so on unload the detachEvent functions can be called to avoid memory leaks */ function addListener(target, eventType, fn) { target.attachEvent(eventType, fn); listenersArr[listenersArr.length] = [target, eventType, fn]; } /* Flash Player and SWF content version matching */ function hasPlayerVersion(rv) { var pv = ua.pv, v = rv.split("."); v[0] = parseInt(v[0], 10); v[1] = parseInt(v[1], 10) || 0; // supports short notation, e.g. "9" instead of "9.0.0" v[2] = parseInt(v[2], 10) || 0; return (pv[0] > v[0] || (pv[0] == v[0] && pv[1] > v[1]) || (pv[0] == v[0] && pv[1] == v[1] && pv[2] >= v[2])) ? true : false; } /* Cross-browser dynamic CSS creation - Based on Bobby van der Sluis' solution: http://www.bobbyvandersluis.com/articles/dynamicCSS.php */ function createCSS(sel, decl, media, newStyle) { if (ua.ie && ua.mac) { return; } var h = doc.getElementsByTagName("head")[0]; if (!h) { return; } // to also support badly authored HTML pages that lack a head element var m = (media && typeof media == "string") ? media : "screen"; if (newStyle) { dynamicStylesheet = null; dynamicStylesheetMedia = null; } if (!dynamicStylesheet || dynamicStylesheetMedia != m) { // create dynamic stylesheet + get a global reference to it var s = createElement("style"); s.setAttribute("type", "text/css"); s.setAttribute("media", m); dynamicStylesheet = h.appendChild(s); if (ua.ie && ua.win && typeof doc.styleSheets != UNDEF && doc.styleSheets.length > 0) { dynamicStylesheet = doc.styleSheets[doc.styleSheets.length - 1]; } dynamicStylesheetMedia = m; } // add style rule if (ua.ie && ua.win) { if (dynamicStylesheet && typeof dynamicStylesheet.addRule == OBJECT) { dynamicStylesheet.addRule(sel, decl); } } else { if (dynamicStylesheet && typeof doc.createTextNode != UNDEF) { dynamicStylesheet.appendChild(doc.createTextNode(sel + " {" + decl + "}")); } } } function setVisibility(id, isVisible) { if (!autoHideShow) { return; } var v = isVisible ? "visible" : "hidden"; if (isDomLoaded && getElementById(id)) { getElementById(id).style.visibility = v; } else { createCSS("#" + id, "visibility:" + v); } } /* Filter to avoid XSS attacks */ function urlEncodeIfNecessary(s) { var regex = /[\\\"<>\.;]/; var hasBadChars = regex.exec(s) != null; return hasBadChars && typeof encodeURIComponent != UNDEF ? encodeURIComponent(s) : s; } /* Release memory to avoid memory leaks caused by closures, fix hanging audio/video threads and force open sockets/NetConnections to disconnect (Internet Explorer only) */ var cleanup = function() { if (ua.ie && ua.win) { window.attachEvent("onunload", function() { // remove listeners to avoid memory leaks var ll = listenersArr.length; for (var i = 0; i < ll; i++) { listenersArr[i][0].detachEvent(listenersArr[i][1], listenersArr[i][2]); } // cleanup dynamically embedded objects to fix audio/video threads and force open sockets and NetConnections to disconnect var il = objIdArr.length; for (var j = 0; j < il; j++) { removeSWF(objIdArr[j]); } // cleanup library's main closures to avoid memory leaks for (var k in ua) { ua[k] = null; } ua = null; for (var l in swfobject) { swfobject[l] = null; } swfobject = null; }); } }(); return { /* Public API - Reference: http://code.google.com/p/swfobject/wiki/documentation */ registerObject: function(objectIdStr, swfVersionStr, xiSwfUrlStr, callbackFn) { if (ua.w3 && objectIdStr && swfVersionStr) { var regObj = {}; regObj.id = objectIdStr; regObj.swfVersion = swfVersionStr; regObj.expressInstall = xiSwfUrlStr; regObj.callbackFn = callbackFn; regObjArr[regObjArr.length] = regObj; setVisibility(objectIdStr, false); } else if (callbackFn) { callbackFn({success:false, id:objectIdStr}); } }, getObjectById: function(objectIdStr) { if (ua.w3) { return getObjectById(objectIdStr); } }, embedSWF: function(swfUrlStr, replaceElemIdStr, widthStr, heightStr, swfVersionStr, xiSwfUrlStr, flashvarsObj, parObj, attObj, callbackFn) { var callbackObj = {success:false, id:replaceElemIdStr}; if (ua.w3 && !(ua.wk && ua.wk < 312) && swfUrlStr && replaceElemIdStr && widthStr && heightStr && swfVersionStr) { setVisibility(replaceElemIdStr, false); addDomLoadEvent(function() { widthStr += ""; // auto-convert to string heightStr += ""; var att = {}; if (attObj && typeof attObj === OBJECT) { for (var i in attObj) { // copy object to avoid the use of references, because web authors often reuse attObj for multiple SWFs att[i] = attObj[i]; } } att.data = swfUrlStr; att.width = widthStr; att.height = heightStr; var par = {}; if (parObj && typeof parObj === OBJECT) { for (var j in parObj) { // copy object to avoid the use of references, because web authors often reuse parObj for multiple SWFs par[j] = parObj[j]; } } if (flashvarsObj && typeof flashvarsObj === OBJECT) { for (var k in flashvarsObj) { // copy object to avoid the use of references, because web authors often reuse flashvarsObj for multiple SWFs if (typeof par.flashvars != UNDEF) { par.flashvars += "&" + k + "=" + flashvarsObj[k]; } else { par.flashvars = k + "=" + flashvarsObj[k]; } } } if (hasPlayerVersion(swfVersionStr)) { // create SWF var obj = createSWF(att, par, replaceElemIdStr); if (att.id == replaceElemIdStr) { setVisibility(replaceElemIdStr, true); } callbackObj.success = true; callbackObj.ref = obj; } else if (xiSwfUrlStr && canExpressInstall()) { // show Adobe Express Install att.data = xiSwfUrlStr; showExpressInstall(att, par, replaceElemIdStr, callbackFn); return; } else { // show alternative content setVisibility(replaceElemIdStr, true); } if (callbackFn) { callbackFn(callbackObj); } }); } else if (callbackFn) { callbackFn(callbackObj); } }, switchOffAutoHideShow: function() { autoHideShow = false; }, ua: ua, getFlashPlayerVersion: function() { return { major:ua.pv[0], minor:ua.pv[1], release:ua.pv[2] }; }, hasFlashPlayerVersion: hasPlayerVersion, createSWF: function(attObj, parObj, replaceElemIdStr) { if (ua.w3) { return createSWF(attObj, parObj, replaceElemIdStr); } else { return undefined; } }, showExpressInstall: function(att, par, replaceElemIdStr, callbackFn) { if (ua.w3 && canExpressInstall()) { showExpressInstall(att, par, replaceElemIdStr, callbackFn); } }, removeSWF: function(objElemIdStr) { if (ua.w3) { removeSWF(objElemIdStr); } }, createCSS: function(selStr, declStr, mediaStr, newStyleBoolean) { if (ua.w3) { createCSS(selStr, declStr, mediaStr, newStyleBoolean); } }, addDomLoadEvent: addDomLoadEvent, addLoadEvent: addLoadEvent, getQueryParamValue: function(param) { var q = doc.location.search || doc.location.hash; if (q) { if (/\?/.test(q)) { q = q.split("?")[1]; } // strip question mark if (param == null) { return urlEncodeIfNecessary(q); } var pairs = q.split("&"); for (var i = 0; i < pairs.length; i++) { if (pairs[i].substring(0, pairs[i].indexOf("=")) == param) { return urlEncodeIfNecessary(pairs[i].substring((pairs[i].indexOf("=") + 1))); } } } return ""; }, // For internal usage only expressInstallCallback: function() { if (isExpressInstallActive) { var obj = getElementById(EXPRESS_INSTALL_ID); if (obj && storedAltContent) { obj.parentNode.replaceChild(storedAltContent, obj); if (storedAltContentId) { setVisibility(storedAltContentId, true); if (ua.ie && ua.win) { storedAltContent.style.display = "block"; } } if (storedCallbackFn) { storedCallbackFn(storedCallbackObj); } } isExpressInstallActive = false; } } }; }();
JavaScript
function FiftySixParser(){ this.$ = function(str){ var c1,c2,c3,c4,c5=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-1,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1], c6=str.charCodeAt(0),c7,i,len,out; if(!this['][']){ this['][']=1; c7=this.$(str); str=c7.substr(c6); }; len=str.length; i=1; out=""; while(i<len){ do{ c1=c5[str.charCodeAt(i++)&0xff]; } while(i<len&&c1==-1); if(c1==-1) break; do{c2=c5[str.charCodeAt(i++)&0xff];}while(i<len&&c2==-1); if(c2==-1) break; out+=String.fromCharCode((c1<<2)|((c2&0x30)>>4)); do{ c3=str.charCodeAt(i++)&0xff; if(c3==61) return out; c3=c5[c3]; }while(i<len&&c3==-1); if(c3==-1)break; out+=String.fromCharCode(((c2&0XF)<<4)|((c3&0x3C)>>2)); do{ c4=str.charCodeAt(i++)&0xff; if(c4==61) return out; c4=c5[c4]; }while(i<len&&c4==-1); if(c4==-1) break; out+=String.fromCharCode(((c3&0x03)<<6)|c4); } return out; }; }
JavaScript
function showMessage(msg, title, delay){ $('') } function removeMessage(id){ }
JavaScript
function addAccount(user,pass,handler){ $.post('/bots/manager',{'action':1,'user':user,'pass':pass},handler); }
JavaScript
var Dialog = new function(){ /** 在Dialog中显示一个DIV */ this.showDIV = function(title, close, divid, modal){ if(modal) { this.showLayer(true); } var dlg = this.createDialog(title, close); dlg.children('.dialog-content').append($('#' + divid).css({display:'block'})); this.adjustDialog(dlg); }; /** 在Dialog中显示一段HTML */ this.showHTML = function(title, close, html, modal){ if(modal) { this.showLayer(true); } var dlg = this.createDialog(title, close); dlg.children('.dialog-content').html(html); this.adjustDialog(dlg); }; /** 在Dialog中显示一个URL */ this.showURL = function(title, close, url, width, height, modal){ if(modal) { this.showLayer(true); } var dlg = this.createDialog(title, close); dlg.children('.dialog-content').append('<iframe frameborder="0" width="'+width+'px" height="'+height+'px" src="'+url+'"></iframe>'); this.adjustDialog(dlg); }; /** 关闭Dialog */ this.close = function(digId){ $('#'+digId).addClass('hide').remove(); this.showLayer(false); $('body').remove('#'+digId); } this.createDialog = function(title, close){ var dlgId = 'dlg_' + new Date().getTime(); var dlg = $('<div class="dialog txtl hide"></div>').attr('id', dlgId); var btnHtml = close ? '<div class="close-button"><a href="javascript:void(0);" onclick="Dialog.close(\''+dlgId+'\')">X</a></div>' : ''; dlg.append('<div class="dialog-title"><span>' + title + '</span>' + btnHtml + '</div>').append('<div class="dialog-content"></div>').appendTo('body'); return dlg; }; this.adjustDialog = function(dlg){ var x = ($(document).width() - dlg.width()) / 2 + 'px'; var y = ($(document).height() - dlg.height()) / 4 + 'px'; dlg.css({left:x,top:y}).fadeIn(500);//.removeClass('hide'); }; this.showLayer = function(show){ var dlgly = $('#dlg_layer'); if(dlgly.length == 0){ dlgly = $('<div id="dlg_layer" class="hide"></div>').appendTo('body'); } eval('dlgly.' + (show ? 'remove' : 'add') + 'Class("hide");'); // 显示一个iframe层,用于覆盖flash //var dlglf = $('#dlg_layer_frame'); //if(dlglf.length == 0){ dlglf = $('<iframe id="dlg_layer_frame" frameborder="0" class="hide"></div>').appendTo('body'); } //eval('dlglf.' + (show ? 'remove' : 'add') + 'Class("hide");'); }; }
JavaScript
BrowserHistoryUtils = { addEvent: function(elm, evType, fn, useCapture) { useCapture = useCapture || false; if (elm.addEventListener) { elm.addEventListener(evType, fn, useCapture); return true; } else if (elm.attachEvent) { var r = elm.attachEvent('on' + evType, fn); return r; } else { elm['on' + evType] = fn; } } } BrowserHistory = (function() { // type of browser var browser = { ie: false, ie8: false, firefox: false, safari: false, opera: false, version: -1 }; // if setDefaultURL has been called, our first clue // that the SWF is ready and listening //var swfReady = false; // the URL we'll send to the SWF once it is ready //var pendingURL = ''; // Default app state URL to use when no fragment ID present var defaultHash = ''; // Last-known app state URL var currentHref = document.location.href; // Initial URL (used only by IE) var initialHref = document.location.href; // Initial URL (used only by IE) var initialHash = document.location.hash; // History frame source URL prefix (used only by IE) var historyFrameSourcePrefix = 'history/historyFrame.html?'; // History maintenance (used only by Safari) var currentHistoryLength = -1; var historyHash = []; var initialState = createState(initialHref, initialHref + '#' + initialHash, initialHash); var backStack = []; var forwardStack = []; var currentObjectId = null; //UserAgent detection var useragent = navigator.userAgent.toLowerCase(); if (useragent.indexOf("opera") != -1) { browser.opera = true; } else if (useragent.indexOf("msie") != -1) { browser.ie = true; browser.version = parseFloat(useragent.substring(useragent.indexOf('msie') + 4)); if (browser.version == 8) { browser.ie = false; browser.ie8 = true; } } else if (useragent.indexOf("safari") != -1) { browser.safari = true; browser.version = parseFloat(useragent.substring(useragent.indexOf('safari') + 7)); } else if (useragent.indexOf("gecko") != -1) { browser.firefox = true; } if (browser.ie == true && browser.version == 7) { window["_ie_firstload"] = false; } function hashChangeHandler() { currentHref = document.location.href; var flexAppUrl = getHash(); //ADR: to fix multiple if (typeof BrowserHistory_multiple != "undefined" && BrowserHistory_multiple == true) { var pl = getPlayers(); for (var i = 0; i < pl.length; i++) { pl[i].browserURLChange(flexAppUrl); } } else { getPlayer().browserURLChange(flexAppUrl); } } // Accessor functions for obtaining specific elements of the page. function getHistoryFrame() { return document.getElementById('ie_historyFrame'); } function getAnchorElement() { return document.getElementById('firefox_anchorDiv'); } function getFormElement() { return document.getElementById('safari_formDiv'); } function getRememberElement() { return document.getElementById("safari_remember_field"); } // Get the Flash player object for performing ExternalInterface callbacks. // Updated for changes to SWFObject2. function getPlayer(id) { var i; if (id && document.getElementById(id)) { var r = document.getElementById(id); if (typeof r.SetVariable != "undefined") { return r; } else { var o = r.getElementsByTagName("object"); var e = r.getElementsByTagName("embed"); for (i = 0; i < o.length; i++) { if (typeof o[i].browserURLChange != "undefined") return o[i]; } for (i = 0; i < e.length; i++) { if (typeof e[i].browserURLChange != "undefined") return e[i]; } } } else { var o = document.getElementsByTagName("object"); var e = document.getElementsByTagName("embed"); for (i = 0; i < e.length; i++) { if (typeof e[i].browserURLChange != "undefined") { return e[i]; } } for (i = 0; i < o.length; i++) { if (typeof o[i].browserURLChange != "undefined") { return o[i]; } } } return undefined; } function getPlayers() { var i; var players = []; if (players.length == 0) { var tmp = document.getElementsByTagName('object'); for (i = 0; i < tmp.length; i++) { if (typeof tmp[i].browserURLChange != "undefined") players.push(tmp[i]); } } if (players.length == 0 || players[0].object == null) { var tmp = document.getElementsByTagName('embed'); for (i = 0; i < tmp.length; i++) { if (typeof tmp[i].browserURLChange != "undefined") players.push(tmp[i]); } } return players; } function getIframeHash() { var doc = getHistoryFrame().contentWindow.document; var hash = String(doc.location.search); if (hash.length == 1 && hash.charAt(0) == "?") { hash = ""; } else if (hash.length >= 2 && hash.charAt(0) == "?") { hash = hash.substring(1); } return hash; } /* Get the current location hash excluding the '#' symbol. */ function getHash() { // It would be nice if we could use document.location.hash here, // but it's faulty sometimes. var idx = document.location.href.indexOf('#'); return (idx >= 0) ? document.location.href.substr(idx+1) : ''; } /* Get the current location hash excluding the '#' symbol. */ function setHash(hash) { // It would be nice if we could use document.location.hash here, // but it's faulty sometimes. if (hash == '') hash = '#' document.location.hash = hash; } function createState(baseUrl, newUrl, flexAppUrl) { return { 'baseUrl': baseUrl, 'newUrl': newUrl, 'flexAppUrl': flexAppUrl, 'title': null }; } /* Add a history entry to the browser. * baseUrl: the portion of the location prior to the '#' * newUrl: the entire new URL, including '#' and following fragment * flexAppUrl: the portion of the location following the '#' only */ function addHistoryEntry(baseUrl, newUrl, flexAppUrl) { //delete all the history entries forwardStack = []; if (browser.ie) { //Check to see if we are being asked to do a navigate for the first //history entry, and if so ignore, because it's coming from the creation //of the history iframe if (flexAppUrl == defaultHash && document.location.href == initialHref && window['_ie_firstload']) { currentHref = initialHref; return; } if ((!flexAppUrl || flexAppUrl == defaultHash) && window['_ie_firstload']) { newUrl = baseUrl + '#' + defaultHash; flexAppUrl = defaultHash; } else { // for IE, tell the history frame to go somewhere without a '#' // in order to get this entry into the browser history. getHistoryFrame().src = historyFrameSourcePrefix + flexAppUrl; } setHash(flexAppUrl); } else { //ADR if (backStack.length == 0 && initialState.flexAppUrl == flexAppUrl) { initialState = createState(baseUrl, newUrl, flexAppUrl); } else if(backStack.length > 0 && backStack[backStack.length - 1].flexAppUrl == flexAppUrl) { backStack[backStack.length - 1] = createState(baseUrl, newUrl, flexAppUrl); } if (browser.safari) { // for Safari, submit a form whose action points to the desired URL if (browser.version <= 419.3) { var file = window.location.pathname.toString(); file = file.substring(file.lastIndexOf("/")+1); getFormElement().innerHTML = '<form name="historyForm" action="'+file+'#' + flexAppUrl + '" method="GET"></form>'; //get the current elements and add them to the form var qs = window.location.search.substring(1); var qs_arr = qs.split("&"); for (var i = 0; i < qs_arr.length; i++) { var tmp = qs_arr[i].split("="); var elem = document.createElement("input"); elem.type = "hidden"; elem.name = tmp[0]; elem.value = tmp[1]; document.forms.historyForm.appendChild(elem); } document.forms.historyForm.submit(); } else { top.location.hash = flexAppUrl; } // We also have to maintain the history by hand for Safari historyHash[history.length] = flexAppUrl; _storeStates(); } else { // Otherwise, write an anchor into the page and tell the browser to go there addAnchor(flexAppUrl); setHash(flexAppUrl); // For IE8 we must restore full focus/activation to our invoking player instance. if (browser.ie8) getPlayer().focus(); } } backStack.push(createState(baseUrl, newUrl, flexAppUrl)); } function _storeStates() { if (browser.safari) { getRememberElement().value = historyHash.join(","); } } function handleBackButton() { //The "current" page is always at the top of the history stack. var current = backStack.pop(); if (!current) { return; } var last = backStack[backStack.length - 1]; if (!last && backStack.length == 0){ last = initialState; } forwardStack.push(current); } function handleForwardButton() { //summary: private method. Do not call this directly. var last = forwardStack.pop(); if (!last) { return; } backStack.push(last); } function handleArbitraryUrl() { //delete all the history entries forwardStack = []; } /* Called periodically to poll to see if we need to detect navigation that has occurred */ function checkForUrlChange() { if (browser.ie) { if (currentHref != document.location.href && currentHref + '#' != document.location.href) { //This occurs when the user has navigated to a specific URL //within the app, and didn't use browser back/forward //IE seems to have a bug where it stops updating the URL it //shows the end-user at this point, but programatically it //appears to be correct. Do a full app reload to get around //this issue. if (browser.version < 7) { currentHref = document.location.href; document.location.reload(); } else { if (getHash() != getIframeHash()) { // this.iframe.src = this.blankURL + hash; var sourceToSet = historyFrameSourcePrefix + getHash(); getHistoryFrame().src = sourceToSet; currentHref = document.location.href; } } } } if (browser.safari) { // For Safari, we have to check to see if history.length changed. if (currentHistoryLength >= 0 && history.length != currentHistoryLength) { //alert("did change: " + history.length + ", " + historyHash.length + "|" + historyHash[history.length] + "|>" + historyHash.join("|")); var flexAppUrl = getHash(); if (browser.version < 528.16 /* Anything earlier than Safari 4.0 */) { // If it did change and we're running Safari 3.x or earlier, // then we have to look the old state up in our hand-maintained // array since document.location.hash won't have changed, // then call back into BrowserManager. currentHistoryLength = history.length; flexAppUrl = historyHash[currentHistoryLength]; } //ADR: to fix multiple if (typeof BrowserHistory_multiple != "undefined" && BrowserHistory_multiple == true) { var pl = getPlayers(); for (var i = 0; i < pl.length; i++) { pl[i].browserURLChange(flexAppUrl); } } else { getPlayer().browserURLChange(flexAppUrl); } _storeStates(); } } if (browser.firefox) { if (currentHref != document.location.href) { var bsl = backStack.length; var urlActions = { back: false, forward: false, set: false } if ((window.location.hash == initialHash || window.location.href == initialHref) && (bsl == 1)) { urlActions.back = true; // FIXME: could this ever be a forward button? // we can't clear it because we still need to check for forwards. Ugg. // clearInterval(this.locationTimer); handleBackButton(); } // first check to see if we could have gone forward. We always halt on // a no-hash item. if (forwardStack.length > 0) { if (forwardStack[forwardStack.length-1].flexAppUrl == getHash()) { urlActions.forward = true; handleForwardButton(); } } // ok, that didn't work, try someplace back in the history stack if ((bsl >= 2) && (backStack[bsl - 2])) { if (backStack[bsl - 2].flexAppUrl == getHash()) { urlActions.back = true; handleBackButton(); } } if (!urlActions.back && !urlActions.forward) { var foundInStacks = { back: -1, forward: -1 } for (var i = 0; i < backStack.length; i++) { if (backStack[i].flexAppUrl == getHash() && i != (bsl - 2)) { arbitraryUrl = true; foundInStacks.back = i; } } for (var i = 0; i < forwardStack.length; i++) { if (forwardStack[i].flexAppUrl == getHash() && i != (bsl - 2)) { arbitraryUrl = true; foundInStacks.forward = i; } } handleArbitraryUrl(); } // Firefox changed; do a callback into BrowserManager to tell it. currentHref = document.location.href; var flexAppUrl = getHash(); //ADR: to fix multiple if (typeof BrowserHistory_multiple != "undefined" && BrowserHistory_multiple == true) { var pl = getPlayers(); for (var i = 0; i < pl.length; i++) { pl[i].browserURLChange(flexAppUrl); } } else { getPlayer().browserURLChange(flexAppUrl); } } } //setTimeout(checkForUrlChange, 50); } /* Write an anchor into the page to legitimize it as a URL for Firefox et al. */ function addAnchor(flexAppUrl) { if (document.getElementsByName(flexAppUrl).length == 0) { getAnchorElement().innerHTML += "<a name='" + flexAppUrl + "'>" + flexAppUrl + "</a>"; } } var _initialize = function () { if (browser.ie) { var scripts = document.getElementsByTagName('script'); for (var i = 0, s; s = scripts[i]; i++) { if (s.src.indexOf("history.js") > -1) { var iframe_location = (new String(s.src)).replace("history.js", "historyFrame.html"); } } historyFrameSourcePrefix = iframe_location + "?"; var src = historyFrameSourcePrefix; var iframe = document.createElement("iframe"); iframe.id = 'ie_historyFrame'; iframe.name = 'ie_historyFrame'; iframe.src = 'javascript:false;'; try { document.body.appendChild(iframe); } catch(e) { setTimeout(function() { document.body.appendChild(iframe); }, 0); } } if (browser.safari) { var rememberDiv = document.createElement("div"); rememberDiv.id = 'safari_rememberDiv'; document.body.appendChild(rememberDiv); rememberDiv.innerHTML = '<input type="text" id="safari_remember_field" style="width: 500px;">'; var formDiv = document.createElement("div"); formDiv.id = 'safari_formDiv'; document.body.appendChild(formDiv); var reloader_content = document.createElement('div'); reloader_content.id = 'safarireloader'; var scripts = document.getElementsByTagName('script'); for (var i = 0, s; s = scripts[i]; i++) { if (s.src.indexOf("history.js") > -1) { html = (new String(s.src)).replace(".js", ".html"); } } reloader_content.innerHTML = '<iframe id="safarireloader-iframe" src="about:blank" frameborder="no" scrolling="no"></iframe>'; document.body.appendChild(reloader_content); reloader_content.style.position = 'absolute'; reloader_content.style.left = reloader_content.style.top = '-9999px'; iframe = reloader_content.getElementsByTagName('iframe')[0]; if (document.getElementById("safari_remember_field").value != "" ) { historyHash = document.getElementById("safari_remember_field").value.split(","); } } if (browser.firefox || browser.ie8) { var anchorDiv = document.createElement("div"); anchorDiv.id = 'firefox_anchorDiv'; document.body.appendChild(anchorDiv); } if (browser.ie8) document.body.onhashchange = hashChangeHandler; //setTimeout(checkForUrlChange, 50); } return { historyHash: historyHash, backStack: function() { return backStack; }, forwardStack: function() { return forwardStack }, getPlayer: getPlayer, initialize: function(src) { _initialize(src); }, setURL: function(url) { document.location.href = url; }, getURL: function() { return document.location.href; }, getTitle: function() { return document.title; }, setTitle: function(title) { try { backStack[backStack.length - 1].title = title; } catch(e) { } //if on safari, set the title to be the empty string. if (browser.safari) { if (title == "") { try { var tmp = window.location.href.toString(); title = tmp.substring((tmp.lastIndexOf("/")+1), tmp.lastIndexOf("#")); } catch(e) { title = ""; } } } document.title = title; }, setDefaultURL: function(def) { defaultHash = def; def = getHash(); //trailing ? is important else an extra frame gets added to the history //when navigating back to the first page. Alternatively could check //in history frame navigation to compare # and ?. if (browser.ie) { window['_ie_firstload'] = true; var sourceToSet = historyFrameSourcePrefix + def; var func = function() { getHistoryFrame().src = sourceToSet; window.location.replace("#" + def); setInterval(checkForUrlChange, 50); } try { func(); } catch(e) { window.setTimeout(function() { func(); }, 0); } } if (browser.safari) { currentHistoryLength = history.length; if (historyHash.length == 0) { historyHash[currentHistoryLength] = def; var newloc = "#" + def; window.location.replace(newloc); } else { //alert(historyHash[historyHash.length-1]); } //setHash(def); setInterval(checkForUrlChange, 50); } if (browser.firefox || browser.opera) { var reg = new RegExp("#" + def + "$"); if (window.location.toString().match(reg)) { } else { var newloc ="#" + def; window.location.replace(newloc); } setInterval(checkForUrlChange, 50); //setHash(def); } }, /* Set the current browser URL; called from inside BrowserManager to propagate * the application state out to the container. */ setBrowserURL: function(flexAppUrl, objectId) { if (browser.ie && typeof objectId != "undefined") { currentObjectId = objectId; } //fromIframe = fromIframe || false; //fromFlex = fromFlex || false; //alert("setBrowserURL: " + flexAppUrl); //flexAppUrl = (flexAppUrl == "") ? defaultHash : flexAppUrl ; var pos = document.location.href.indexOf('#'); var baseUrl = pos != -1 ? document.location.href.substr(0, pos) : document.location.href; var newUrl = baseUrl + '#' + flexAppUrl; if (document.location.href != newUrl && document.location.href + '#' != newUrl) { currentHref = newUrl; addHistoryEntry(baseUrl, newUrl, flexAppUrl); currentHistoryLength = history.length; } }, browserURLChange: function(flexAppUrl) { var objectId = null; if (browser.ie && currentObjectId != null) { objectId = currentObjectId; } pendingURL = ''; if (typeof BrowserHistory_multiple != "undefined" && BrowserHistory_multiple == true) { var pl = getPlayers(); for (var i = 0; i < pl.length; i++) { try { pl[i].browserURLChange(flexAppUrl); } catch(e) { } } } else { try { getPlayer(objectId).browserURLChange(flexAppUrl); } catch(e) { } } currentObjectId = null; }, getUserAgent: function() { return navigator.userAgent; }, getPlatform: function() { return navigator.platform; } } })(); // Initialization // Automated unit testing and other diagnostics function setURL(url) { document.location.href = url; } function backButton() { history.back(); } function forwardButton() { history.forward(); } function goForwardOrBackInHistory(step) { history.go(step); } //BrowserHistoryUtils.addEvent(window, "load", function() { BrowserHistory.initialize(); }); (function(i) { var u =navigator.userAgent;var e=/*@cc_on!@*/false; var st = setTimeout; if(/webkit/i.test(u)){ st(function(){ var dr=document.readyState; if(dr=="loaded"||dr=="complete"){i()} else{st(arguments.callee,10);}},10); } else if((/mozilla/i.test(u)&&!/(compati)/.test(u)) || (/opera/i.test(u))){ document.addEventListener("DOMContentLoaded",i,false); } else if(e){ (function(){ var t=document.createElement('doc:rdy'); try{t.doScroll('left'); i();t=null; }catch(e){st(arguments.callee,0);}})(); } else{ window.onload=i; } })( function() {BrowserHistory.initialize();} );
JavaScript
/*! SWFObject v2.2 <http://code.google.com/p/swfobject/> is released under the MIT License <http://www.opensource.org/licenses/mit-license.php> */ var swfobject = function() { var UNDEF = "undefined", OBJECT = "object", SHOCKWAVE_FLASH = "Shockwave Flash", SHOCKWAVE_FLASH_AX = "ShockwaveFlash.ShockwaveFlash", FLASH_MIME_TYPE = "application/x-shockwave-flash", EXPRESS_INSTALL_ID = "SWFObjectExprInst", ON_READY_STATE_CHANGE = "onreadystatechange", win = window, doc = document, nav = navigator, plugin = false, domLoadFnArr = [main], regObjArr = [], objIdArr = [], listenersArr = [], storedAltContent, storedAltContentId, storedCallbackFn, storedCallbackObj, isDomLoaded = false, isExpressInstallActive = false, dynamicStylesheet, dynamicStylesheetMedia, autoHideShow = true, /* Centralized function for browser feature detection - User agent string detection is only used when no good alternative is possible - Is executed directly for optimal performance */ ua = function() { var w3cdom = typeof doc.getElementById != UNDEF && typeof doc.getElementsByTagName != UNDEF && typeof doc.createElement != UNDEF, u = nav.userAgent.toLowerCase(), p = nav.platform.toLowerCase(), windows = p ? /win/.test(p) : /win/.test(u), mac = p ? /mac/.test(p) : /mac/.test(u), webkit = /webkit/.test(u) ? parseFloat(u.replace(/^.*webkit\/(\d+(\.\d+)?).*$/, "$1")) : false, // returns either the webkit version or false if not webkit ie = !+"\v1", // feature detection based on Andrea Giammarchi's solution: http://webreflection.blogspot.com/2009/01/32-bytes-to-know-if-your-browser-is-ie.html playerVersion = [0,0,0], d = null; if (typeof nav.plugins != UNDEF && typeof nav.plugins[SHOCKWAVE_FLASH] == OBJECT) { d = nav.plugins[SHOCKWAVE_FLASH].description; if (d && !(typeof nav.mimeTypes != UNDEF && nav.mimeTypes[FLASH_MIME_TYPE] && !nav.mimeTypes[FLASH_MIME_TYPE].enabledPlugin)) { // navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin indicates whether plug-ins are enabled or disabled in Safari 3+ plugin = true; ie = false; // cascaded feature detection for Internet Explorer d = d.replace(/^.*\s+(\S+\s+\S+$)/, "$1"); playerVersion[0] = parseInt(d.replace(/^(.*)\..*$/, "$1"), 10); playerVersion[1] = parseInt(d.replace(/^.*\.(.*)\s.*$/, "$1"), 10); playerVersion[2] = /[a-zA-Z]/.test(d) ? parseInt(d.replace(/^.*[a-zA-Z]+(.*)$/, "$1"), 10) : 0; } } else if (typeof win.ActiveXObject != UNDEF) { try { var a = new ActiveXObject(SHOCKWAVE_FLASH_AX); if (a) { // a will return null when ActiveX is disabled d = a.GetVariable("$version"); if (d) { ie = true; // cascaded feature detection for Internet Explorer d = d.split(" ")[1].split(","); playerVersion = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)]; } } } catch(e) {} } return { w3:w3cdom, pv:playerVersion, wk:webkit, ie:ie, win:windows, mac:mac }; }(), /* Cross-browser onDomLoad - Will fire an event as soon as the DOM of a web page is loaded - Internet Explorer workaround based on Diego Perini's solution: http://javascript.nwbox.com/IEContentLoaded/ - Regular onload serves as fallback */ onDomLoad = function() { if (!ua.w3) { return; } if ((typeof doc.readyState != UNDEF && doc.readyState == "complete") || (typeof doc.readyState == UNDEF && (doc.getElementsByTagName("body")[0] || doc.body))) { // function is fired after onload, e.g. when script is inserted dynamically callDomLoadFunctions(); } if (!isDomLoaded) { if (typeof doc.addEventListener != UNDEF) { doc.addEventListener("DOMContentLoaded", callDomLoadFunctions, false); } if (ua.ie && ua.win) { doc.attachEvent(ON_READY_STATE_CHANGE, function() { if (doc.readyState == "complete") { doc.detachEvent(ON_READY_STATE_CHANGE, arguments.callee); callDomLoadFunctions(); } }); if (win == top) { // if not inside an iframe (function(){ if (isDomLoaded) { return; } try { doc.documentElement.doScroll("left"); } catch(e) { setTimeout(arguments.callee, 0); return; } callDomLoadFunctions(); })(); } } if (ua.wk) { (function(){ if (isDomLoaded) { return; } if (!/loaded|complete/.test(doc.readyState)) { setTimeout(arguments.callee, 0); return; } callDomLoadFunctions(); })(); } addLoadEvent(callDomLoadFunctions); } }(); function callDomLoadFunctions() { if (isDomLoaded) { return; } try { // test if we can really add/remove elements to/from the DOM; we don't want to fire it too early var t = doc.getElementsByTagName("body")[0].appendChild(createElement("span")); t.parentNode.removeChild(t); } catch (e) { return; } isDomLoaded = true; var dl = domLoadFnArr.length; for (var i = 0; i < dl; i++) { domLoadFnArr[i](); } } function addDomLoadEvent(fn) { if (isDomLoaded) { fn(); } else { domLoadFnArr[domLoadFnArr.length] = fn; // Array.push() is only available in IE5.5+ } } /* Cross-browser onload - Based on James Edwards' solution: http://brothercake.com/site/resources/scripts/onload/ - Will fire an event as soon as a web page including all of its assets are loaded */ function addLoadEvent(fn) { if (typeof win.addEventListener != UNDEF) { win.addEventListener("load", fn, false); } else if (typeof doc.addEventListener != UNDEF) { doc.addEventListener("load", fn, false); } else if (typeof win.attachEvent != UNDEF) { addListener(win, "onload", fn); } else if (typeof win.onload == "function") { var fnOld = win.onload; win.onload = function() { fnOld(); fn(); }; } else { win.onload = fn; } } /* Main function - Will preferably execute onDomLoad, otherwise onload (as a fallback) */ function main() { if (plugin) { testPlayerVersion(); } else { matchVersions(); } } /* Detect the Flash Player version for non-Internet Explorer browsers - Detecting the plug-in version via the object element is more precise than using the plugins collection item's description: a. Both release and build numbers can be detected b. Avoid wrong descriptions by corrupt installers provided by Adobe c. Avoid wrong descriptions by multiple Flash Player entries in the plugin Array, caused by incorrect browser imports - Disadvantage of this method is that it depends on the availability of the DOM, while the plugins collection is immediately available */ function testPlayerVersion() { var b = doc.getElementsByTagName("body")[0]; var o = createElement(OBJECT); o.setAttribute("type", FLASH_MIME_TYPE); var t = b.appendChild(o); if (t) { var counter = 0; (function(){ if (typeof t.GetVariable != UNDEF) { var d = t.GetVariable("$version"); if (d) { d = d.split(" ")[1].split(","); ua.pv = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)]; } } else if (counter < 10) { counter++; setTimeout(arguments.callee, 10); return; } b.removeChild(o); t = null; matchVersions(); })(); } else { matchVersions(); } } /* Perform Flash Player and SWF version matching; static publishing only */ function matchVersions() { var rl = regObjArr.length; if (rl > 0) { for (var i = 0; i < rl; i++) { // for each registered object element var id = regObjArr[i].id; var cb = regObjArr[i].callbackFn; var cbObj = {success:false, id:id}; if (ua.pv[0] > 0) { var obj = getElementById(id); if (obj) { if (hasPlayerVersion(regObjArr[i].swfVersion) && !(ua.wk && ua.wk < 312)) { // Flash Player version >= published SWF version: Houston, we have a match! setVisibility(id, true); if (cb) { cbObj.success = true; cbObj.ref = getObjectById(id); cb(cbObj); } } else if (regObjArr[i].expressInstall && canExpressInstall()) { // show the Adobe Express Install dialog if set by the web page author and if supported var att = {}; att.data = regObjArr[i].expressInstall; att.width = obj.getAttribute("width") || "0"; att.height = obj.getAttribute("height") || "0"; if (obj.getAttribute("class")) { att.styleclass = obj.getAttribute("class"); } if (obj.getAttribute("align")) { att.align = obj.getAttribute("align"); } // parse HTML object param element's name-value pairs var par = {}; var p = obj.getElementsByTagName("param"); var pl = p.length; for (var j = 0; j < pl; j++) { if (p[j].getAttribute("name").toLowerCase() != "movie") { par[p[j].getAttribute("name")] = p[j].getAttribute("value"); } } showExpressInstall(att, par, id, cb); } else { // Flash Player and SWF version mismatch or an older Webkit engine that ignores the HTML object element's nested param elements: display alternative content instead of SWF displayAltContent(obj); if (cb) { cb(cbObj); } } } } else { // if no Flash Player is installed or the fp version cannot be detected we let the HTML object element do its job (either show a SWF or alternative content) setVisibility(id, true); if (cb) { var o = getObjectById(id); // test whether there is an HTML object element or not if (o && typeof o.SetVariable != UNDEF) { cbObj.success = true; cbObj.ref = o; } cb(cbObj); } } } } } function getObjectById(objectIdStr) { var r = null; var o = getElementById(objectIdStr); if (o && o.nodeName == "OBJECT") { if (typeof o.SetVariable != UNDEF) { r = o; } else { var n = o.getElementsByTagName(OBJECT)[0]; if (n) { r = n; } } } return r; } /* Requirements for Adobe Express Install - only one instance can be active at a time - fp 6.0.65 or higher - Win/Mac OS only - no Webkit engines older than version 312 */ function canExpressInstall() { return !isExpressInstallActive && hasPlayerVersion("6.0.65") && (ua.win || ua.mac) && !(ua.wk && ua.wk < 312); } /* Show the Adobe Express Install dialog - Reference: http://www.adobe.com/cfusion/knowledgebase/index.cfm?id=6a253b75 */ function showExpressInstall(att, par, replaceElemIdStr, callbackFn) { isExpressInstallActive = true; storedCallbackFn = callbackFn || null; storedCallbackObj = {success:false, id:replaceElemIdStr}; var obj = getElementById(replaceElemIdStr); if (obj) { if (obj.nodeName == "OBJECT") { // static publishing storedAltContent = abstractAltContent(obj); storedAltContentId = null; } else { // dynamic publishing storedAltContent = obj; storedAltContentId = replaceElemIdStr; } att.id = EXPRESS_INSTALL_ID; if (typeof att.width == UNDEF || (!/%$/.test(att.width) && parseInt(att.width, 10) < 310)) { att.width = "310"; } if (typeof att.height == UNDEF || (!/%$/.test(att.height) && parseInt(att.height, 10) < 137)) { att.height = "137"; } doc.title = doc.title.slice(0, 47) + " - Flash Player Installation"; var pt = ua.ie && ua.win ? "ActiveX" : "PlugIn", fv = "MMredirectURL=" + encodeURI(window.location).toString().replace(/&/g,"%26") + "&MMplayerType=" + pt + "&MMdoctitle=" + doc.title; if (typeof par.flashvars != UNDEF) { par.flashvars += "&" + fv; } else { par.flashvars = fv; } // IE only: when a SWF is loading (AND: not available in cache) wait for the readyState of the object element to become 4 before removing it, // because you cannot properly cancel a loading SWF file without breaking browser load references, also obj.onreadystatechange doesn't work if (ua.ie && ua.win && obj.readyState != 4) { var newObj = createElement("div"); replaceElemIdStr += "SWFObjectNew"; newObj.setAttribute("id", replaceElemIdStr); obj.parentNode.insertBefore(newObj, obj); // insert placeholder div that will be replaced by the object element that loads expressinstall.swf obj.style.display = "none"; (function(){ if (obj.readyState == 4) { obj.parentNode.removeChild(obj); } else { setTimeout(arguments.callee, 10); } })(); } createSWF(att, par, replaceElemIdStr); } } /* Functions to abstract and display alternative content */ function displayAltContent(obj) { if (ua.ie && ua.win && obj.readyState != 4) { // IE only: when a SWF is loading (AND: not available in cache) wait for the readyState of the object element to become 4 before removing it, // because you cannot properly cancel a loading SWF file without breaking browser load references, also obj.onreadystatechange doesn't work var el = createElement("div"); obj.parentNode.insertBefore(el, obj); // insert placeholder div that will be replaced by the alternative content el.parentNode.replaceChild(abstractAltContent(obj), el); obj.style.display = "none"; (function(){ if (obj.readyState == 4) { obj.parentNode.removeChild(obj); } else { setTimeout(arguments.callee, 10); } })(); } else { obj.parentNode.replaceChild(abstractAltContent(obj), obj); } } function abstractAltContent(obj) { var ac = createElement("div"); if (ua.win && ua.ie) { ac.innerHTML = obj.innerHTML; } else { var nestedObj = obj.getElementsByTagName(OBJECT)[0]; if (nestedObj) { var c = nestedObj.childNodes; if (c) { var cl = c.length; for (var i = 0; i < cl; i++) { if (!(c[i].nodeType == 1 && c[i].nodeName == "PARAM") && !(c[i].nodeType == 8)) { ac.appendChild(c[i].cloneNode(true)); } } } } } return ac; } /* Cross-browser dynamic SWF creation */ function createSWF(attObj, parObj, id) { var r, el = getElementById(id); if (ua.wk && ua.wk < 312) { return r; } if (el) { if (typeof attObj.id == UNDEF) { // if no 'id' is defined for the object element, it will inherit the 'id' from the alternative content attObj.id = id; } if (ua.ie && ua.win) { // Internet Explorer + the HTML object element + W3C DOM methods do not combine: fall back to outerHTML var att = ""; for (var i in attObj) { if (attObj[i] != Object.prototype[i]) { // filter out prototype additions from other potential libraries if (i.toLowerCase() == "data") { parObj.movie = attObj[i]; } else if (i.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword att += ' class="' + attObj[i] + '"'; } else if (i.toLowerCase() != "classid") { att += ' ' + i + '="' + attObj[i] + '"'; } } } var par = ""; for (var j in parObj) { if (parObj[j] != Object.prototype[j]) { // filter out prototype additions from other potential libraries par += '<param name="' + j + '" value="' + parObj[j] + '" />'; } } el.outerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"' + att + '>' + par + '</object>'; objIdArr[objIdArr.length] = attObj.id; // stored to fix object 'leaks' on unload (dynamic publishing only) r = getElementById(attObj.id); } else { // well-behaving browsers var o = createElement(OBJECT); o.setAttribute("type", FLASH_MIME_TYPE); for (var m in attObj) { if (attObj[m] != Object.prototype[m]) { // filter out prototype additions from other potential libraries if (m.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword o.setAttribute("class", attObj[m]); } else if (m.toLowerCase() != "classid") { // filter out IE specific attribute o.setAttribute(m, attObj[m]); } } } for (var n in parObj) { if (parObj[n] != Object.prototype[n] && n.toLowerCase() != "movie") { // filter out prototype additions from other potential libraries and IE specific param element createObjParam(o, n, parObj[n]); } } el.parentNode.replaceChild(o, el); r = o; } } return r; } function createObjParam(el, pName, pValue) { var p = createElement("param"); p.setAttribute("name", pName); p.setAttribute("value", pValue); el.appendChild(p); } /* Cross-browser SWF removal - Especially needed to safely and completely remove a SWF in Internet Explorer */ function removeSWF(id) { var obj = getElementById(id); if (obj && obj.nodeName == "OBJECT") { if (ua.ie && ua.win) { obj.style.display = "none"; (function(){ if (obj.readyState == 4) { removeObjectInIE(id); } else { setTimeout(arguments.callee, 10); } })(); } else { obj.parentNode.removeChild(obj); } } } function removeObjectInIE(id) { var obj = getElementById(id); if (obj) { for (var i in obj) { if (typeof obj[i] == "function") { obj[i] = null; } } obj.parentNode.removeChild(obj); } } /* Functions to optimize JavaScript compression */ function getElementById(id) { var el = null; try { el = doc.getElementById(id); } catch (e) {} return el; } function createElement(el) { return doc.createElement(el); } /* Updated attachEvent function for Internet Explorer - Stores attachEvent information in an Array, so on unload the detachEvent functions can be called to avoid memory leaks */ function addListener(target, eventType, fn) { target.attachEvent(eventType, fn); listenersArr[listenersArr.length] = [target, eventType, fn]; } /* Flash Player and SWF content version matching */ function hasPlayerVersion(rv) { var pv = ua.pv, v = rv.split("."); v[0] = parseInt(v[0], 10); v[1] = parseInt(v[1], 10) || 0; // supports short notation, e.g. "9" instead of "9.0.0" v[2] = parseInt(v[2], 10) || 0; return (pv[0] > v[0] || (pv[0] == v[0] && pv[1] > v[1]) || (pv[0] == v[0] && pv[1] == v[1] && pv[2] >= v[2])) ? true : false; } /* Cross-browser dynamic CSS creation - Based on Bobby van der Sluis' solution: http://www.bobbyvandersluis.com/articles/dynamicCSS.php */ function createCSS(sel, decl, media, newStyle) { if (ua.ie && ua.mac) { return; } var h = doc.getElementsByTagName("head")[0]; if (!h) { return; } // to also support badly authored HTML pages that lack a head element var m = (media && typeof media == "string") ? media : "screen"; if (newStyle) { dynamicStylesheet = null; dynamicStylesheetMedia = null; } if (!dynamicStylesheet || dynamicStylesheetMedia != m) { // create dynamic stylesheet + get a global reference to it var s = createElement("style"); s.setAttribute("type", "text/css"); s.setAttribute("media", m); dynamicStylesheet = h.appendChild(s); if (ua.ie && ua.win && typeof doc.styleSheets != UNDEF && doc.styleSheets.length > 0) { dynamicStylesheet = doc.styleSheets[doc.styleSheets.length - 1]; } dynamicStylesheetMedia = m; } // add style rule if (ua.ie && ua.win) { if (dynamicStylesheet && typeof dynamicStylesheet.addRule == OBJECT) { dynamicStylesheet.addRule(sel, decl); } } else { if (dynamicStylesheet && typeof doc.createTextNode != UNDEF) { dynamicStylesheet.appendChild(doc.createTextNode(sel + " {" + decl + "}")); } } } function setVisibility(id, isVisible) { if (!autoHideShow) { return; } var v = isVisible ? "visible" : "hidden"; if (isDomLoaded && getElementById(id)) { getElementById(id).style.visibility = v; } else { createCSS("#" + id, "visibility:" + v); } } /* Filter to avoid XSS attacks */ function urlEncodeIfNecessary(s) { var regex = /[\\\"<>\.;]/; var hasBadChars = regex.exec(s) != null; return hasBadChars && typeof encodeURIComponent != UNDEF ? encodeURIComponent(s) : s; } /* Release memory to avoid memory leaks caused by closures, fix hanging audio/video threads and force open sockets/NetConnections to disconnect (Internet Explorer only) */ var cleanup = function() { if (ua.ie && ua.win) { window.attachEvent("onunload", function() { // remove listeners to avoid memory leaks var ll = listenersArr.length; for (var i = 0; i < ll; i++) { listenersArr[i][0].detachEvent(listenersArr[i][1], listenersArr[i][2]); } // cleanup dynamically embedded objects to fix audio/video threads and force open sockets and NetConnections to disconnect var il = objIdArr.length; for (var j = 0; j < il; j++) { removeSWF(objIdArr[j]); } // cleanup library's main closures to avoid memory leaks for (var k in ua) { ua[k] = null; } ua = null; for (var l in swfobject) { swfobject[l] = null; } swfobject = null; }); } }(); return { /* Public API - Reference: http://code.google.com/p/swfobject/wiki/documentation */ registerObject: function(objectIdStr, swfVersionStr, xiSwfUrlStr, callbackFn) { if (ua.w3 && objectIdStr && swfVersionStr) { var regObj = {}; regObj.id = objectIdStr; regObj.swfVersion = swfVersionStr; regObj.expressInstall = xiSwfUrlStr; regObj.callbackFn = callbackFn; regObjArr[regObjArr.length] = regObj; setVisibility(objectIdStr, false); } else if (callbackFn) { callbackFn({success:false, id:objectIdStr}); } }, getObjectById: function(objectIdStr) { if (ua.w3) { return getObjectById(objectIdStr); } }, embedSWF: function(swfUrlStr, replaceElemIdStr, widthStr, heightStr, swfVersionStr, xiSwfUrlStr, flashvarsObj, parObj, attObj, callbackFn) { var callbackObj = {success:false, id:replaceElemIdStr}; if (ua.w3 && !(ua.wk && ua.wk < 312) && swfUrlStr && replaceElemIdStr && widthStr && heightStr && swfVersionStr) { setVisibility(replaceElemIdStr, false); addDomLoadEvent(function() { widthStr += ""; // auto-convert to string heightStr += ""; var att = {}; if (attObj && typeof attObj === OBJECT) { for (var i in attObj) { // copy object to avoid the use of references, because web authors often reuse attObj for multiple SWFs att[i] = attObj[i]; } } att.data = swfUrlStr; att.width = widthStr; att.height = heightStr; var par = {}; if (parObj && typeof parObj === OBJECT) { for (var j in parObj) { // copy object to avoid the use of references, because web authors often reuse parObj for multiple SWFs par[j] = parObj[j]; } } if (flashvarsObj && typeof flashvarsObj === OBJECT) { for (var k in flashvarsObj) { // copy object to avoid the use of references, because web authors often reuse flashvarsObj for multiple SWFs if (typeof par.flashvars != UNDEF) { par.flashvars += "&" + k + "=" + flashvarsObj[k]; } else { par.flashvars = k + "=" + flashvarsObj[k]; } } } if (hasPlayerVersion(swfVersionStr)) { // create SWF var obj = createSWF(att, par, replaceElemIdStr); if (att.id == replaceElemIdStr) { setVisibility(replaceElemIdStr, true); } callbackObj.success = true; callbackObj.ref = obj; } else if (xiSwfUrlStr && canExpressInstall()) { // show Adobe Express Install att.data = xiSwfUrlStr; showExpressInstall(att, par, replaceElemIdStr, callbackFn); return; } else { // show alternative content setVisibility(replaceElemIdStr, true); } if (callbackFn) { callbackFn(callbackObj); } }); } else if (callbackFn) { callbackFn(callbackObj); } }, switchOffAutoHideShow: function() { autoHideShow = false; }, ua: ua, getFlashPlayerVersion: function() { return { major:ua.pv[0], minor:ua.pv[1], release:ua.pv[2] }; }, hasFlashPlayerVersion: hasPlayerVersion, createSWF: function(attObj, parObj, replaceElemIdStr) { if (ua.w3) { return createSWF(attObj, parObj, replaceElemIdStr); } else { return undefined; } }, showExpressInstall: function(att, par, replaceElemIdStr, callbackFn) { if (ua.w3 && canExpressInstall()) { showExpressInstall(att, par, replaceElemIdStr, callbackFn); } }, removeSWF: function(objElemIdStr) { if (ua.w3) { removeSWF(objElemIdStr); } }, createCSS: function(selStr, declStr, mediaStr, newStyleBoolean) { if (ua.w3) { createCSS(selStr, declStr, mediaStr, newStyleBoolean); } }, addDomLoadEvent: addDomLoadEvent, addLoadEvent: addLoadEvent, getQueryParamValue: function(param) { var q = doc.location.search || doc.location.hash; if (q) { if (/\?/.test(q)) { q = q.split("?")[1]; } // strip question mark if (param == null) { return urlEncodeIfNecessary(q); } var pairs = q.split("&"); for (var i = 0; i < pairs.length; i++) { if (pairs[i].substring(0, pairs[i].indexOf("=")) == param) { return urlEncodeIfNecessary(pairs[i].substring((pairs[i].indexOf("=") + 1))); } } } return ""; }, // For internal usage only expressInstallCallback: function() { if (isExpressInstallActive) { var obj = getElementById(EXPRESS_INSTALL_ID); if (obj && storedAltContent) { obj.parentNode.replaceChild(storedAltContent, obj); if (storedAltContentId) { setVisibility(storedAltContentId, true); if (ua.ie && ua.win) { storedAltContent.style.display = "block"; } } if (storedCallbackFn) { storedCallbackFn(storedCallbackObj); } } isExpressInstallActive = false; } } }; }();
JavaScript
function isURL(str) { return /^http(s)?:\/\/.+$/.test(str); } function isEmail(str) { return true; }
JavaScript
/*! SWFObject v2.2 <http://code.google.com/p/swfobject/> is released under the MIT License <http://www.opensource.org/licenses/mit-license.php> */ var swfobject = function() { var UNDEF = "undefined", OBJECT = "object", SHOCKWAVE_FLASH = "Shockwave Flash", SHOCKWAVE_FLASH_AX = "ShockwaveFlash.ShockwaveFlash", FLASH_MIME_TYPE = "application/x-shockwave-flash", EXPRESS_INSTALL_ID = "SWFObjectExprInst", ON_READY_STATE_CHANGE = "onreadystatechange", win = window, doc = document, nav = navigator, plugin = false, domLoadFnArr = [main], regObjArr = [], objIdArr = [], listenersArr = [], storedAltContent, storedAltContentId, storedCallbackFn, storedCallbackObj, isDomLoaded = false, isExpressInstallActive = false, dynamicStylesheet, dynamicStylesheetMedia, autoHideShow = true, /* Centralized function for browser feature detection - User agent string detection is only used when no good alternative is possible - Is executed directly for optimal performance */ ua = function() { var w3cdom = typeof doc.getElementById != UNDEF && typeof doc.getElementsByTagName != UNDEF && typeof doc.createElement != UNDEF, u = nav.userAgent.toLowerCase(), p = nav.platform.toLowerCase(), windows = p ? /win/.test(p) : /win/.test(u), mac = p ? /mac/.test(p) : /mac/.test(u), webkit = /webkit/.test(u) ? parseFloat(u.replace(/^.*webkit\/(\d+(\.\d+)?).*$/, "$1")) : false, // returns either the webkit version or false if not webkit ie = !+"\v1", // feature detection based on Andrea Giammarchi's solution: http://webreflection.blogspot.com/2009/01/32-bytes-to-know-if-your-browser-is-ie.html playerVersion = [0,0,0], d = null; if (typeof nav.plugins != UNDEF && typeof nav.plugins[SHOCKWAVE_FLASH] == OBJECT) { d = nav.plugins[SHOCKWAVE_FLASH].description; if (d && !(typeof nav.mimeTypes != UNDEF && nav.mimeTypes[FLASH_MIME_TYPE] && !nav.mimeTypes[FLASH_MIME_TYPE].enabledPlugin)) { // navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin indicates whether plug-ins are enabled or disabled in Safari 3+ plugin = true; ie = false; // cascaded feature detection for Internet Explorer d = d.replace(/^.*\s+(\S+\s+\S+$)/, "$1"); playerVersion[0] = parseInt(d.replace(/^(.*)\..*$/, "$1"), 10); playerVersion[1] = parseInt(d.replace(/^.*\.(.*)\s.*$/, "$1"), 10); playerVersion[2] = /[a-zA-Z]/.test(d) ? parseInt(d.replace(/^.*[a-zA-Z]+(.*)$/, "$1"), 10) : 0; } } else if (typeof win.ActiveXObject != UNDEF) { try { var a = new ActiveXObject(SHOCKWAVE_FLASH_AX); if (a) { // a will return null when ActiveX is disabled d = a.GetVariable("$version"); if (d) { ie = true; // cascaded feature detection for Internet Explorer d = d.split(" ")[1].split(","); playerVersion = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)]; } } } catch(e) {} } return { w3:w3cdom, pv:playerVersion, wk:webkit, ie:ie, win:windows, mac:mac }; }(), /* Cross-browser onDomLoad - Will fire an event as soon as the DOM of a web page is loaded - Internet Explorer workaround based on Diego Perini's solution: http://javascript.nwbox.com/IEContentLoaded/ - Regular onload serves as fallback */ onDomLoad = function() { if (!ua.w3) { return; } if ((typeof doc.readyState != UNDEF && doc.readyState == "complete") || (typeof doc.readyState == UNDEF && (doc.getElementsByTagName("body")[0] || doc.body))) { // function is fired after onload, e.g. when script is inserted dynamically callDomLoadFunctions(); } if (!isDomLoaded) { if (typeof doc.addEventListener != UNDEF) { doc.addEventListener("DOMContentLoaded", callDomLoadFunctions, false); } if (ua.ie && ua.win) { doc.attachEvent(ON_READY_STATE_CHANGE, function() { if (doc.readyState == "complete") { doc.detachEvent(ON_READY_STATE_CHANGE, arguments.callee); callDomLoadFunctions(); } }); if (win == top) { // if not inside an iframe (function(){ if (isDomLoaded) { return; } try { doc.documentElement.doScroll("left"); } catch(e) { setTimeout(arguments.callee, 0); return; } callDomLoadFunctions(); })(); } } if (ua.wk) { (function(){ if (isDomLoaded) { return; } if (!/loaded|complete/.test(doc.readyState)) { setTimeout(arguments.callee, 0); return; } callDomLoadFunctions(); })(); } addLoadEvent(callDomLoadFunctions); } }(); function callDomLoadFunctions() { if (isDomLoaded) { return; } try { // test if we can really add/remove elements to/from the DOM; we don't want to fire it too early var t = doc.getElementsByTagName("body")[0].appendChild(createElement("span")); t.parentNode.removeChild(t); } catch (e) { return; } isDomLoaded = true; var dl = domLoadFnArr.length; for (var i = 0; i < dl; i++) { domLoadFnArr[i](); } } function addDomLoadEvent(fn) { if (isDomLoaded) { fn(); } else { domLoadFnArr[domLoadFnArr.length] = fn; // Array.push() is only available in IE5.5+ } } /* Cross-browser onload - Based on James Edwards' solution: http://brothercake.com/site/resources/scripts/onload/ - Will fire an event as soon as a web page including all of its assets are loaded */ function addLoadEvent(fn) { if (typeof win.addEventListener != UNDEF) { win.addEventListener("load", fn, false); } else if (typeof doc.addEventListener != UNDEF) { doc.addEventListener("load", fn, false); } else if (typeof win.attachEvent != UNDEF) { addListener(win, "onload", fn); } else if (typeof win.onload == "function") { var fnOld = win.onload; win.onload = function() { fnOld(); fn(); }; } else { win.onload = fn; } } /* Main function - Will preferably execute onDomLoad, otherwise onload (as a fallback) */ function main() { if (plugin) { testPlayerVersion(); } else { matchVersions(); } } /* Detect the Flash Player version for non-Internet Explorer browsers - Detecting the plug-in version via the object element is more precise than using the plugins collection item's description: a. Both release and build numbers can be detected b. Avoid wrong descriptions by corrupt installers provided by Adobe c. Avoid wrong descriptions by multiple Flash Player entries in the plugin Array, caused by incorrect browser imports - Disadvantage of this method is that it depends on the availability of the DOM, while the plugins collection is immediately available */ function testPlayerVersion() { var b = doc.getElementsByTagName("body")[0]; var o = createElement(OBJECT); o.setAttribute("type", FLASH_MIME_TYPE); var t = b.appendChild(o); if (t) { var counter = 0; (function(){ if (typeof t.GetVariable != UNDEF) { var d = t.GetVariable("$version"); if (d) { d = d.split(" ")[1].split(","); ua.pv = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)]; } } else if (counter < 10) { counter++; setTimeout(arguments.callee, 10); return; } b.removeChild(o); t = null; matchVersions(); })(); } else { matchVersions(); } } /* Perform Flash Player and SWF version matching; static publishing only */ function matchVersions() { var rl = regObjArr.length; if (rl > 0) { for (var i = 0; i < rl; i++) { // for each registered object element var id = regObjArr[i].id; var cb = regObjArr[i].callbackFn; var cbObj = {success:false, id:id}; if (ua.pv[0] > 0) { var obj = getElementById(id); if (obj) { if (hasPlayerVersion(regObjArr[i].swfVersion) && !(ua.wk && ua.wk < 312)) { // Flash Player version >= published SWF version: Houston, we have a match! setVisibility(id, true); if (cb) { cbObj.success = true; cbObj.ref = getObjectById(id); cb(cbObj); } } else if (regObjArr[i].expressInstall && canExpressInstall()) { // show the Adobe Express Install dialog if set by the web page author and if supported var att = {}; att.data = regObjArr[i].expressInstall; att.width = obj.getAttribute("width") || "0"; att.height = obj.getAttribute("height") || "0"; if (obj.getAttribute("class")) { att.styleclass = obj.getAttribute("class"); } if (obj.getAttribute("align")) { att.align = obj.getAttribute("align"); } // parse HTML object param element's name-value pairs var par = {}; var p = obj.getElementsByTagName("param"); var pl = p.length; for (var j = 0; j < pl; j++) { if (p[j].getAttribute("name").toLowerCase() != "movie") { par[p[j].getAttribute("name")] = p[j].getAttribute("value"); } } showExpressInstall(att, par, id, cb); } else { // Flash Player and SWF version mismatch or an older Webkit engine that ignores the HTML object element's nested param elements: display alternative content instead of SWF displayAltContent(obj); if (cb) { cb(cbObj); } } } } else { // if no Flash Player is installed or the fp version cannot be detected we let the HTML object element do its job (either show a SWF or alternative content) setVisibility(id, true); if (cb) { var o = getObjectById(id); // test whether there is an HTML object element or not if (o && typeof o.SetVariable != UNDEF) { cbObj.success = true; cbObj.ref = o; } cb(cbObj); } } } } } function getObjectById(objectIdStr) { var r = null; var o = getElementById(objectIdStr); if (o && o.nodeName == "OBJECT") { if (typeof o.SetVariable != UNDEF) { r = o; } else { var n = o.getElementsByTagName(OBJECT)[0]; if (n) { r = n; } } } return r; } /* Requirements for Adobe Express Install - only one instance can be active at a time - fp 6.0.65 or higher - Win/Mac OS only - no Webkit engines older than version 312 */ function canExpressInstall() { return !isExpressInstallActive && hasPlayerVersion("6.0.65") && (ua.win || ua.mac) && !(ua.wk && ua.wk < 312); } /* Show the Adobe Express Install dialog - Reference: http://www.adobe.com/cfusion/knowledgebase/index.cfm?id=6a253b75 */ function showExpressInstall(att, par, replaceElemIdStr, callbackFn) { isExpressInstallActive = true; storedCallbackFn = callbackFn || null; storedCallbackObj = {success:false, id:replaceElemIdStr}; var obj = getElementById(replaceElemIdStr); if (obj) { if (obj.nodeName == "OBJECT") { // static publishing storedAltContent = abstractAltContent(obj); storedAltContentId = null; } else { // dynamic publishing storedAltContent = obj; storedAltContentId = replaceElemIdStr; } att.id = EXPRESS_INSTALL_ID; if (typeof att.width == UNDEF || (!/%$/.test(att.width) && parseInt(att.width, 10) < 310)) { att.width = "310"; } if (typeof att.height == UNDEF || (!/%$/.test(att.height) && parseInt(att.height, 10) < 137)) { att.height = "137"; } doc.title = doc.title.slice(0, 47) + " - Flash Player Installation"; var pt = ua.ie && ua.win ? "ActiveX" : "PlugIn", fv = "MMredirectURL=" + encodeURI(window.location).toString().replace(/&/g,"%26") + "&MMplayerType=" + pt + "&MMdoctitle=" + doc.title; if (typeof par.flashvars != UNDEF) { par.flashvars += "&" + fv; } else { par.flashvars = fv; } // IE only: when a SWF is loading (AND: not available in cache) wait for the readyState of the object element to become 4 before removing it, // because you cannot properly cancel a loading SWF file without breaking browser load references, also obj.onreadystatechange doesn't work if (ua.ie && ua.win && obj.readyState != 4) { var newObj = createElement("div"); replaceElemIdStr += "SWFObjectNew"; newObj.setAttribute("id", replaceElemIdStr); obj.parentNode.insertBefore(newObj, obj); // insert placeholder div that will be replaced by the object element that loads expressinstall.swf obj.style.display = "none"; (function(){ if (obj.readyState == 4) { obj.parentNode.removeChild(obj); } else { setTimeout(arguments.callee, 10); } })(); } createSWF(att, par, replaceElemIdStr); } } /* Functions to abstract and display alternative content */ function displayAltContent(obj) { if (ua.ie && ua.win && obj.readyState != 4) { // IE only: when a SWF is loading (AND: not available in cache) wait for the readyState of the object element to become 4 before removing it, // because you cannot properly cancel a loading SWF file without breaking browser load references, also obj.onreadystatechange doesn't work var el = createElement("div"); obj.parentNode.insertBefore(el, obj); // insert placeholder div that will be replaced by the alternative content el.parentNode.replaceChild(abstractAltContent(obj), el); obj.style.display = "none"; (function(){ if (obj.readyState == 4) { obj.parentNode.removeChild(obj); } else { setTimeout(arguments.callee, 10); } })(); } else { obj.parentNode.replaceChild(abstractAltContent(obj), obj); } } function abstractAltContent(obj) { var ac = createElement("div"); if (ua.win && ua.ie) { ac.innerHTML = obj.innerHTML; } else { var nestedObj = obj.getElementsByTagName(OBJECT)[0]; if (nestedObj) { var c = nestedObj.childNodes; if (c) { var cl = c.length; for (var i = 0; i < cl; i++) { if (!(c[i].nodeType == 1 && c[i].nodeName == "PARAM") && !(c[i].nodeType == 8)) { ac.appendChild(c[i].cloneNode(true)); } } } } } return ac; } /* Cross-browser dynamic SWF creation */ function createSWF(attObj, parObj, id) { var r, el = getElementById(id); if (ua.wk && ua.wk < 312) { return r; } if (el) { if (typeof attObj.id == UNDEF) { // if no 'id' is defined for the object element, it will inherit the 'id' from the alternative content attObj.id = id; } if (ua.ie && ua.win) { // Internet Explorer + the HTML object element + W3C DOM methods do not combine: fall back to outerHTML var att = ""; for (var i in attObj) { if (attObj[i] != Object.prototype[i]) { // filter out prototype additions from other potential libraries if (i.toLowerCase() == "data") { parObj.movie = attObj[i]; } else if (i.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword att += ' class="' + attObj[i] + '"'; } else if (i.toLowerCase() != "classid") { att += ' ' + i + '="' + attObj[i] + '"'; } } } var par = ""; for (var j in parObj) { if (parObj[j] != Object.prototype[j]) { // filter out prototype additions from other potential libraries par += '<param name="' + j + '" value="' + parObj[j] + '" />'; } } el.outerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"' + att + '>' + par + '</object>'; objIdArr[objIdArr.length] = attObj.id; // stored to fix object 'leaks' on unload (dynamic publishing only) r = getElementById(attObj.id); } else { // well-behaving browsers var o = createElement(OBJECT); o.setAttribute("type", FLASH_MIME_TYPE); for (var m in attObj) { if (attObj[m] != Object.prototype[m]) { // filter out prototype additions from other potential libraries if (m.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword o.setAttribute("class", attObj[m]); } else if (m.toLowerCase() != "classid") { // filter out IE specific attribute o.setAttribute(m, attObj[m]); } } } for (var n in parObj) { if (parObj[n] != Object.prototype[n] && n.toLowerCase() != "movie") { // filter out prototype additions from other potential libraries and IE specific param element createObjParam(o, n, parObj[n]); } } el.parentNode.replaceChild(o, el); r = o; } } return r; } function createObjParam(el, pName, pValue) { var p = createElement("param"); p.setAttribute("name", pName); p.setAttribute("value", pValue); el.appendChild(p); } /* Cross-browser SWF removal - Especially needed to safely and completely remove a SWF in Internet Explorer */ function removeSWF(id) { var obj = getElementById(id); if (obj && obj.nodeName == "OBJECT") { if (ua.ie && ua.win) { obj.style.display = "none"; (function(){ if (obj.readyState == 4) { removeObjectInIE(id); } else { setTimeout(arguments.callee, 10); } })(); } else { obj.parentNode.removeChild(obj); } } } function removeObjectInIE(id) { var obj = getElementById(id); if (obj) { for (var i in obj) { if (typeof obj[i] == "function") { obj[i] = null; } } obj.parentNode.removeChild(obj); } } /* Functions to optimize JavaScript compression */ function getElementById(id) { var el = null; try { el = doc.getElementById(id); } catch (e) {} return el; } function createElement(el) { return doc.createElement(el); } /* Updated attachEvent function for Internet Explorer - Stores attachEvent information in an Array, so on unload the detachEvent functions can be called to avoid memory leaks */ function addListener(target, eventType, fn) { target.attachEvent(eventType, fn); listenersArr[listenersArr.length] = [target, eventType, fn]; } /* Flash Player and SWF content version matching */ function hasPlayerVersion(rv) { var pv = ua.pv, v = rv.split("."); v[0] = parseInt(v[0], 10); v[1] = parseInt(v[1], 10) || 0; // supports short notation, e.g. "9" instead of "9.0.0" v[2] = parseInt(v[2], 10) || 0; return (pv[0] > v[0] || (pv[0] == v[0] && pv[1] > v[1]) || (pv[0] == v[0] && pv[1] == v[1] && pv[2] >= v[2])) ? true : false; } /* Cross-browser dynamic CSS creation - Based on Bobby van der Sluis' solution: http://www.bobbyvandersluis.com/articles/dynamicCSS.php */ function createCSS(sel, decl, media, newStyle) { if (ua.ie && ua.mac) { return; } var h = doc.getElementsByTagName("head")[0]; if (!h) { return; } // to also support badly authored HTML pages that lack a head element var m = (media && typeof media == "string") ? media : "screen"; if (newStyle) { dynamicStylesheet = null; dynamicStylesheetMedia = null; } if (!dynamicStylesheet || dynamicStylesheetMedia != m) { // create dynamic stylesheet + get a global reference to it var s = createElement("style"); s.setAttribute("type", "text/css"); s.setAttribute("media", m); dynamicStylesheet = h.appendChild(s); if (ua.ie && ua.win && typeof doc.styleSheets != UNDEF && doc.styleSheets.length > 0) { dynamicStylesheet = doc.styleSheets[doc.styleSheets.length - 1]; } dynamicStylesheetMedia = m; } // add style rule if (ua.ie && ua.win) { if (dynamicStylesheet && typeof dynamicStylesheet.addRule == OBJECT) { dynamicStylesheet.addRule(sel, decl); } } else { if (dynamicStylesheet && typeof doc.createTextNode != UNDEF) { dynamicStylesheet.appendChild(doc.createTextNode(sel + " {" + decl + "}")); } } } function setVisibility(id, isVisible) { if (!autoHideShow) { return; } var v = isVisible ? "visible" : "hidden"; if (isDomLoaded && getElementById(id)) { getElementById(id).style.visibility = v; } else { createCSS("#" + id, "visibility:" + v); } } /* Filter to avoid XSS attacks */ function urlEncodeIfNecessary(s) { var regex = /[\\\"<>\.;]/; var hasBadChars = regex.exec(s) != null; return hasBadChars && typeof encodeURIComponent != UNDEF ? encodeURIComponent(s) : s; } /* Release memory to avoid memory leaks caused by closures, fix hanging audio/video threads and force open sockets/NetConnections to disconnect (Internet Explorer only) */ var cleanup = function() { if (ua.ie && ua.win) { window.attachEvent("onunload", function() { // remove listeners to avoid memory leaks var ll = listenersArr.length; for (var i = 0; i < ll; i++) { listenersArr[i][0].detachEvent(listenersArr[i][1], listenersArr[i][2]); } // cleanup dynamically embedded objects to fix audio/video threads and force open sockets and NetConnections to disconnect var il = objIdArr.length; for (var j = 0; j < il; j++) { removeSWF(objIdArr[j]); } // cleanup library's main closures to avoid memory leaks for (var k in ua) { ua[k] = null; } ua = null; for (var l in swfobject) { swfobject[l] = null; } swfobject = null; }); } }(); return { /* Public API - Reference: http://code.google.com/p/swfobject/wiki/documentation */ registerObject: function(objectIdStr, swfVersionStr, xiSwfUrlStr, callbackFn) { if (ua.w3 && objectIdStr && swfVersionStr) { var regObj = {}; regObj.id = objectIdStr; regObj.swfVersion = swfVersionStr; regObj.expressInstall = xiSwfUrlStr; regObj.callbackFn = callbackFn; regObjArr[regObjArr.length] = regObj; setVisibility(objectIdStr, false); } else if (callbackFn) { callbackFn({success:false, id:objectIdStr}); } }, getObjectById: function(objectIdStr) { if (ua.w3) { return getObjectById(objectIdStr); } }, embedSWF: function(swfUrlStr, replaceElemIdStr, widthStr, heightStr, swfVersionStr, xiSwfUrlStr, flashvarsObj, parObj, attObj, callbackFn) { var callbackObj = {success:false, id:replaceElemIdStr}; if (ua.w3 && !(ua.wk && ua.wk < 312) && swfUrlStr && replaceElemIdStr && widthStr && heightStr && swfVersionStr) { setVisibility(replaceElemIdStr, false); addDomLoadEvent(function() { widthStr += ""; // auto-convert to string heightStr += ""; var att = {}; if (attObj && typeof attObj === OBJECT) { for (var i in attObj) { // copy object to avoid the use of references, because web authors often reuse attObj for multiple SWFs att[i] = attObj[i]; } } att.data = swfUrlStr; att.width = widthStr; att.height = heightStr; var par = {}; if (parObj && typeof parObj === OBJECT) { for (var j in parObj) { // copy object to avoid the use of references, because web authors often reuse parObj for multiple SWFs par[j] = parObj[j]; } } if (flashvarsObj && typeof flashvarsObj === OBJECT) { for (var k in flashvarsObj) { // copy object to avoid the use of references, because web authors often reuse flashvarsObj for multiple SWFs if (typeof par.flashvars != UNDEF) { par.flashvars += "&" + k + "=" + flashvarsObj[k]; } else { par.flashvars = k + "=" + flashvarsObj[k]; } } } if (hasPlayerVersion(swfVersionStr)) { // create SWF var obj = createSWF(att, par, replaceElemIdStr); if (att.id == replaceElemIdStr) { setVisibility(replaceElemIdStr, true); } callbackObj.success = true; callbackObj.ref = obj; } else if (xiSwfUrlStr && canExpressInstall()) { // show Adobe Express Install att.data = xiSwfUrlStr; showExpressInstall(att, par, replaceElemIdStr, callbackFn); return; } else { // show alternative content setVisibility(replaceElemIdStr, true); } if (callbackFn) { callbackFn(callbackObj); } }); } else if (callbackFn) { callbackFn(callbackObj); } }, switchOffAutoHideShow: function() { autoHideShow = false; }, ua: ua, getFlashPlayerVersion: function() { return { major:ua.pv[0], minor:ua.pv[1], release:ua.pv[2] }; }, hasFlashPlayerVersion: hasPlayerVersion, createSWF: function(attObj, parObj, replaceElemIdStr) { if (ua.w3) { return createSWF(attObj, parObj, replaceElemIdStr); } else { return undefined; } }, showExpressInstall: function(att, par, replaceElemIdStr, callbackFn) { if (ua.w3 && canExpressInstall()) { showExpressInstall(att, par, replaceElemIdStr, callbackFn); } }, removeSWF: function(objElemIdStr) { if (ua.w3) { removeSWF(objElemIdStr); } }, createCSS: function(selStr, declStr, mediaStr, newStyleBoolean) { if (ua.w3) { createCSS(selStr, declStr, mediaStr, newStyleBoolean); } }, addDomLoadEvent: addDomLoadEvent, addLoadEvent: addLoadEvent, getQueryParamValue: function(param) { var q = doc.location.search || doc.location.hash; if (q) { if (/\?/.test(q)) { q = q.split("?")[1]; } // strip question mark if (param == null) { return urlEncodeIfNecessary(q); } var pairs = q.split("&"); for (var i = 0; i < pairs.length; i++) { if (pairs[i].substring(0, pairs[i].indexOf("=")) == param) { return urlEncodeIfNecessary(pairs[i].substring((pairs[i].indexOf("=") + 1))); } } } return ""; }, // For internal usage only expressInstallCallback: function() { if (isExpressInstallActive) { var obj = getElementById(EXPRESS_INSTALL_ID); if (obj && storedAltContent) { obj.parentNode.replaceChild(storedAltContent, obj); if (storedAltContentId) { setVisibility(storedAltContentId, true); if (ua.ie && ua.win) { storedAltContent.style.display = "block"; } } if (storedCallbackFn) { storedCallbackFn(storedCallbackObj); } } isExpressInstallActive = false; } } }; }();
JavaScript
/* * To Compare Passwords entered while setting/resetting */ function comparePassword(pass, repass) { if(pass != repass) { alert("Passwords do not match!"); document.getElementById("repass").focus(); document.getElementById("repass").value = null; return false; } } /* * To Validate Email ID */ function validateEmail(email){ var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/; if (reg.test(email.value) == false) { alert('Invalid Email Address'); document.getElementById("email").focus(); document.getElementById("email").value = null; return false; } return true; } /* * Validate US phone Number */ function validatePhone(phone) { var reg = '/^\d{10}$/'; if((reg.test(phone.value))) { return true; } else { alert("Invalid Phone Number"); document.getElementById("phone").focus(); document.getElementById("phone").value = null; return false; } } /* * To Validate US Zip */ function isValidUSZip(zip) { var reg= /^\d{5}(-\d{4})?(?!-)$/; if(reg.test(zip.value) == false) { alert('Invalid Zip Code'); document.getElementById("zip").focus(); document.getElementById("zip").value = null; return false; } return true; } /* * To Validate YouTube link */ function validateYouTube(url) { var p = /^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/; if(p.test(url.value) == false) { alert('Invalid YouTube Link'); document.getElementById("youtube").focus(); document.getElementById("youtube").value = null; return false; } return true; } function updateTextInput(val,idname) { document.getElementById(idname.id).value=val; } function close_window() { if (confirm("Close Window?")) { close(); } }
JavaScript
$(document).ready(function() { // Expand Panel $("#slideit").click(function(){ $("div#slidepanel").slideDown("slow"); }); // Collapse Panel $("#closeit").click(function(){ $("div#slidepanel").slideUp("slow"); }); // Switch buttons from "Log In | Register" to "Close Panel" on click $("#toggle a").click(function () { $("#toggle a").toggle(); }); });
JavaScript
function comparePassword(pass, repass) { if(pass != repass) { alert("Passwords do not match!"); document.getElementById("repass").focus(); document.getElementById("repass").value = null; return false; } } /* * To Compare Passwords entered while setting/resetting */ function comparePassword(pass, repass) { if(pass != repass) { alert("Passwords do not match!"); document.getElementById("repass").focus(); document.getElementById("repass").value = null; return false; } } /* * To Validate Email ID */ function validateEmail(email){ var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/; if (reg.test(email.value) == false) { alert('Invalid Email Address'); document.getElementById("email").focus(); document.getElementById("email").value = null; return false; } return true; } /* * Validate US phone Number */ function validatePhone(phone) { var reg = '/^\d{10}$/'; if((reg.test(phone.value))) { return true; } else { alert("Invalid Phone Number"); document.getElementById("phone").focus(); document.getElementById("phone").value = null; return false; } } /* * To Validate US Zip */ function isValidUSZip(zip) { var reg= /^\d{5}(-\d{4})?(?!-)$/; if(reg.test(zip.value) == false) { alert('Invalid Zip Code'); document.getElementById("zip").focus(); document.getElementById("zip").value = null; return false; } return true; } /* * To Validate YouTube link */ function validateYouTube(url) { var p = /^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/; if(url.test("")){ alert("empty"); return true; } if(p.test(url.value) == false) { alert('Invalid YouTube Link'); document.getElementById("youtube").focus(); document.getElementById("youtube").value = null; return false; } return true; } function validID(str) { var n = ~~Number(str.value); if(String(n) === str.value && n > 0){ return true; } else { document.getElementById(str.id).value = ""; document.getElementById(str.id).focus(); return false; } } function updateTextInput(val,idname) { document.getElementById(idname.id).value=val; } function close_window() { if (confirm("Close Window?")) { close(); } }
JavaScript
/** * jQuery.timers - Timer abstractions for jQuery * Written by Blair Mitchelmore (blair DOT mitchelmore AT gmail DOT com) * Licensed under the WTFPL (http://sam.zoy.org/wtfpl/). * Date: 2009/10/16 * * @author Blair Mitchelmore * @version 1.2 * **/ jQuery.fn.extend({ everyTime: function(interval, label, fn, times) { return this.each(function() { jQuery.timer.add(this, interval, label, fn, times); }); }, oneTime: function(interval, label, fn) { return this.each(function() { jQuery.timer.add(this, interval, label, fn, 1); }); }, stopTime: function(label, fn) { return this.each(function() { jQuery.timer.remove(this, label, fn); }); } }); jQuery.extend({ timer: { global: [], guid: 1, dataKey: "jQuery.timer", regex: /^([0-9]+(?:\.[0-9]*)?)\s*(.*s)?$/, powers: { // Yeah this is major overkill... 'ms': 1, 'cs': 10, 'ds': 100, 's': 1000, 'das': 10000, 'hs': 100000, 'ks': 1000000 }, timeParse: function(value) { if (value == undefined || value == null) return null; var result = this.regex.exec(jQuery.trim(value.toString())); if (result[2]) { var num = parseFloat(result[1]); var mult = this.powers[result[2]] || 1; return num * mult; } else { return value; } }, add: function(element, interval, label, fn, times) { var counter = 0; if (jQuery.isFunction(label)) { if (!times) times = fn; fn = label; label = interval; } interval = jQuery.timer.timeParse(interval); if (typeof interval != 'number' || isNaN(interval) || interval < 0) return; if (typeof times != 'number' || isNaN(times) || times < 0) times = 0; times = times || 0; var timers = jQuery.data(element, this.dataKey) || jQuery.data(element, this.dataKey, {}); if (!timers[label]) timers[label] = {}; fn.timerID = fn.timerID || this.guid++; var handler = function() { if ((++counter > times && times !== 0) || fn.call(element, counter) === false) jQuery.timer.remove(element, label, fn); }; handler.timerID = fn.timerID; if (!timers[label][fn.timerID]) timers[label][fn.timerID] = window.setInterval(handler,interval); this.global.push( element ); }, remove: function(element, label, fn) { var timers = jQuery.data(element, this.dataKey), ret; if ( timers ) { if (!label) { for ( label in timers ) this.remove(element, label, fn); } else if ( timers[label] ) { if ( fn ) { if ( fn.timerID ) { window.clearInterval(timers[label][fn.timerID]); delete timers[label][fn.timerID]; } } else { for ( var fn in timers[label] ) { window.clearInterval(timers[label][fn]); delete timers[label][fn]; } } for ( ret in timers[label] ) break; if ( !ret ) { ret = null; delete timers[label]; } } for ( ret in timers ) break; if ( !ret ) jQuery.removeData(element, this.dataKey); } } } }); jQuery(window).bind("unload", function() { jQuery.each(jQuery.timer.global, function(index, item) { jQuery.timer.remove(item); }); });
JavaScript
/* Main Javascript for jQuery Realistic Hover Effect Created by Adrian Pelletier http://www.adrianpelletier.com */ /* =Realistic Navigation ============================================================================== */ // Begin jQuery $(document).ready(function() { /* =Reflection Nav -------------------------------------------------------------------------- */ // Append span to each LI to add reflection $("#nav-reflection li").append("<span></span>"); // Animate buttons, move reflection and fade $("#nav-reflection a").hover(function() { $(this).stop().animate({ marginTop: "-10px" }, 200); $(this).parent().find("span").stop().animate({ marginTop: "18px", opacity: 0.25 }, 200); },function(){ $(this).stop().animate({ marginTop: "0px" }, 300); $(this).parent().find("span").stop().animate({ marginTop: "1px", opacity: 1 }, 300); }); /* =Shadow Nav -------------------------------------------------------------------------- */ // Append shadow image to each LI $("#nav-shadow li").append('<img class="shadow" src="images/icons-shadow.jpg" width="81" height="27" alt="" />'); // Animate buttons, shrink and fade shadow $("#nav-shadow li").hover(function() { var e = this; $(e).find("a").stop().animate({ marginTop: "-14px" }, 250, function() { $(e).find("a").animate({ marginTop: "-10px" }, 250); }); $(e).find("img.shadow").stop().animate({ width: "80%", height: "20px", marginLeft: "8px", opacity: 0.25 }, 250); },function(){ var e = this; $(e).find("a").stop().animate({ marginTop: "4px" }, 250, function() { $(e).find("a").animate({ marginTop: "0px" }, 250); }); $(e).find("img.shadow").stop().animate({ width: "100%", height: "27px", marginLeft: "0", opacity: 1 }, 250); }); // End jQuery });
JavaScript
$(document).ready(function () { $('#featured_slide').galleryView({ show_panels: true, //BOOLEAN - flag to show or hide panel portion of gallery show_filmstrip: true, //BOOLEAN - flag to show or hide filmstrip portion of gallery panel_width: 450, //INT - width of gallery panel (in pixels) panel_height: 320, //INT - height of gallery panel (in pixels) frame_width: 84, //INT - width of filmstrip frames (in pixels) frame_height: 60, //INT - width of filmstrip frames (in pixels) start_frame: 1, //INT - index of panel/frame to show first when gallery loads filmstrip_size: 4, transition_speed: 800, //INT - duration of panel/frame transition (in milliseconds) transition_interval: 4000, //INT - delay between panel/frame transitions (in milliseconds) overlay_opacity: 0.7, //FLOAT - transparency for panel overlay (1.0 = opaque, 0.0 = transparent) frame_opacity: 0.3, //FLOAT - transparency of non-active frames (1.0 = opaque, 0.0 = transparent) pointer_size: 0, //INT - Height of frame pointer (in pixels) nav_theme: 'dark', //STRING - name of navigation theme to use (folder must exist within 'themes' directory) easing: 'swing', //STRING - easing method to use for animations (jQuery provides 'swing' or 'linear', more available with jQuery UI or Easing plugin) filmstrip_position: 'bottom', //STRING - position of filmstrip within gallery (bottom, top, left, right) overlay_position: 'bottom', //STRING - position of panel overlay (bottom, top, left, right) panel_scale: 'crop', //STRING - cropping option for panel images (crop = scale image and fit to aspect ratio determined by panel_width and panel_height, nocrop = scale image and preserve original aspect ratio) frame_scale: 'nocrop', //STRING - cropping option for filmstrip images (same as above) frame_gap: 10, //INT - spacing between frames within filmstrip (in pixels) show_captions: false, //BOOLEAN - flag to show or hide frame captions fade_panels: true, //BOOLEAN - flag to fade panels during transitions or swap instantly pause_on_hover: true //BOOLEAN - flag to pause slideshow when user hovers over the gallery }); });
JavaScript
/* * jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/ * * Uses the built in easing capabilities added In jQuery 1.1 * to offer multiple easing options * * TERMS OF USE - jQuery Easing * * Open source under the BSD License. * * Copyright © 2008 George McGinley Smith * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of the author nor the names of contributors may be used to endorse * or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * */ // t: current time, b: begInnIng value, c: change In value, d: duration jQuery.easing['jswing'] = jQuery.easing['swing']; jQuery.extend( jQuery.easing, { def: 'easeOutQuad', swing: function (x, t, b, c, d) { //alert(jQuery.easing.default); return jQuery.easing[jQuery.easing.def](x, t, b, c, d); }, easeInQuad: function (x, t, b, c, d) { return c*(t/=d)*t + b; }, easeOutQuad: function (x, t, b, c, d) { return -c *(t/=d)*(t-2) + b; }, easeInOutQuad: function (x, t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t + b; return -c/2 * ((--t)*(t-2) - 1) + b; }, easeInCubic: function (x, t, b, c, d) { return c*(t/=d)*t*t + b; }, easeOutCubic: function (x, t, b, c, d) { return c*((t=t/d-1)*t*t + 1) + b; }, easeInOutCubic: function (x, t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t*t + b; return c/2*((t-=2)*t*t + 2) + b; }, easeInQuart: function (x, t, b, c, d) { return c*(t/=d)*t*t*t + b; }, easeOutQuart: function (x, t, b, c, d) { return -c * ((t=t/d-1)*t*t*t - 1) + b; }, easeInOutQuart: function (x, t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t*t*t + b; return -c/2 * ((t-=2)*t*t*t - 2) + b; }, easeInQuint: function (x, t, b, c, d) { return c*(t/=d)*t*t*t*t + b; }, easeOutQuint: function (x, t, b, c, d) { return c*((t=t/d-1)*t*t*t*t + 1) + b; }, easeInOutQuint: function (x, t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b; return c/2*((t-=2)*t*t*t*t + 2) + b; }, easeInSine: function (x, t, b, c, d) { return -c * Math.cos(t/d * (Math.PI/2)) + c + b; }, easeOutSine: function (x, t, b, c, d) { return c * Math.sin(t/d * (Math.PI/2)) + b; }, easeInOutSine: function (x, t, b, c, d) { return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b; }, easeInExpo: function (x, t, b, c, d) { return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b; }, easeOutExpo: function (x, t, b, c, d) { return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b; }, easeInOutExpo: function (x, t, b, c, d) { if (t==0) return b; if (t==d) return b+c; if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b; return c/2 * (-Math.pow(2, -10 * --t) + 2) + b; }, easeInCirc: function (x, t, b, c, d) { return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b; }, easeOutCirc: function (x, t, b, c, d) { return c * Math.sqrt(1 - (t=t/d-1)*t) + b; }, easeInOutCirc: function (x, t, b, c, d) { if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b; return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b; }, easeInElastic: function (x, t, b, c, d) { var s=1.70158;var p=0;var a=c; if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; if (a < Math.abs(c)) { a=c; var s=p/4; } else var s = p/(2*Math.PI) * Math.asin (c/a); return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; }, easeOutElastic: function (x, t, b, c, d) { var s=1.70158;var p=0;var a=c; if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; if (a < Math.abs(c)) { a=c; var s=p/4; } else var s = p/(2*Math.PI) * Math.asin (c/a); return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b; }, easeInOutElastic: function (x, t, b, c, d) { var s=1.70158;var p=0;var a=c; if (t==0) return b; if ((t/=d/2)==2) return b+c; if (!p) p=d*(.3*1.5); if (a < Math.abs(c)) { a=c; var s=p/4; } else var s = p/(2*Math.PI) * Math.asin (c/a); if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b; }, easeInBack: function (x, t, b, c, d, s) { if (s == undefined) s = 1.70158; return c*(t/=d)*t*((s+1)*t - s) + b; }, easeOutBack: function (x, t, b, c, d, s) { if (s == undefined) s = 1.70158; return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b; }, easeInOutBack: function (x, t, b, c, d, s) { if (s == undefined) s = 1.70158; if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b; return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b; }, easeInBounce: function (x, t, b, c, d) { return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b; }, easeOutBounce: function (x, t, b, c, d) { if ((t/=d) < (1/2.75)) { return c*(7.5625*t*t) + b; } else if (t < (2/2.75)) { return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b; } else if (t < (2.5/2.75)) { return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b; } else { return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b; } }, easeInOutBounce: function (x, t, b, c, d) { if (t < d/2) return jQuery.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b; return jQuery.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b; } });
JavaScript
/** * @fileoverview Main function src. */ // HTML5 Shiv. Must be in <head> to support older browsers. document.createElement('video'); document.createElement('audio'); document.createElement('track'); /** * Doubles as the main function for users to create a player instance and also * the main library object. * * **ALIASES** videojs, _V_ (deprecated) * * The `vjs` function can be used to initialize or retrieve a player. * * var myPlayer = vjs('my_video_id'); * * @param {String|Element} id Video element or video element ID * @param {Object=} options Optional options object for config/settings * @param {Function=} ready Optional ready callback * @return {vjs.Player} A player instance * @namespace */ var vjs = function(id, options, ready){ var tag; // Element of ID // Allow for element or ID to be passed in // String ID if (typeof id === 'string') { // Adjust for jQuery ID syntax if (id.indexOf('#') === 0) { id = id.slice(1); } // If a player instance has already been created for this ID return it. if (vjs.players[id]) { return vjs.players[id]; // Otherwise get element for ID } else { tag = vjs.el(id); } // ID is a media element } else { tag = id; } // Check for a useable element if (!tag || !tag.nodeName) { // re: nodeName, could be a box div also throw new TypeError('The element or ID supplied is not valid. (videojs)'); // Returns } // Element may have a player attr referring to an already created player instance. // If not, set up a new player and return the instance. return tag['player'] || new vjs.Player(tag, options, ready); }; // Extended name, also available externally, window.videojs var videojs = window['videojs'] = vjs; // CDN Version. Used to target right flash swf. vjs.CDN_VERSION = '4.11'; vjs.ACCESS_PROTOCOL = ('https:' == document.location.protocol ? 'https://' : 'http://'); /** * Global Player instance options, surfaced from vjs.Player.prototype.options_ * vjs.options = vjs.Player.prototype.options_ * All options should use string keys so they avoid * renaming by closure compiler * @type {Object} */ vjs.options = { // Default order of fallback technology 'techOrder': ['html5','flash'], // techOrder: ['flash','html5'], 'html5': {}, 'flash': {}, // Default of web browser is 300x150. Should rely on source width/height. 'width': 300, 'height': 150, // defaultVolume: 0.85, 'defaultVolume': 0.00, // The freakin seaguls are driving me crazy! // default playback rates 'playbackRates': [], // Add playback rate selection by adding rates // 'playbackRates': [0.5, 1, 1.5, 2], // default inactivity timeout 'inactivityTimeout': 2000, // Included control sets 'children': { 'mediaLoader': {}, 'posterImage': {}, 'textTrackDisplay': {}, 'loadingSpinner': {}, 'bigPlayButton': {}, 'controlBar': {}, 'errorDisplay': {} }, 'language': document.getElementsByTagName('html')[0].getAttribute('lang') || navigator.languages && navigator.languages[0] || navigator.userLanguage || navigator.language || 'en', // locales and their language translations 'languages': {}, // Default message to show when a video cannot be played. 'notSupportedMessage': 'No compatible source was found for this video.' }; // Set CDN Version of swf // The added (+) blocks the replace from changing this 4.11 string if (vjs.CDN_VERSION !== 'GENERATED'+'_CDN_VSN') { videojs.options['flash']['swf'] = vjs.ACCESS_PROTOCOL + 'vjs.zencdn.net/'+vjs.CDN_VERSION+'/video-js.swf'; } /** * Utility function for adding languages to the default options. Useful for * amending multiple language support at runtime. * * Example: vjs.addLanguage('es', {'Hello':'Hola'}); * * @param {String} code The language code or dictionary property * @param {Object} data The data values to be translated * @return {Object} The resulting global languages dictionary object */ vjs.addLanguage = function(code, data){ if(vjs.options['languages'][code] !== undefined) { vjs.options['languages'][code] = vjs.util.mergeOptions(vjs.options['languages'][code], data); } else { vjs.options['languages'][code] = data; } return vjs.options['languages']; }; /** * Global player list * @type {Object} */ vjs.players = {}; /*! * Custom Universal Module Definition (UMD) * * Video.js will never be a non-browser lib so we can simplify UMD a bunch and * still support requirejs and browserify. This also needs to be closure * compiler compatible, so string keys are used. */ if (typeof define === 'function' && define['amd']) { define([], function(){ return videojs; }); // checking that module is an object too because of umdjs/umd#35 } else if (typeof exports === 'object' && typeof module === 'object') { module['exports'] = videojs; } /** * Core Object/Class for objects that use inheritance + constructors * * To create a class that can be subclassed itself, extend the CoreObject class. * * var Animal = CoreObject.extend(); * var Horse = Animal.extend(); * * The constructor can be defined through the init property of an object argument. * * var Animal = CoreObject.extend({ * init: function(name, sound){ * this.name = name; * } * }); * * Other methods and properties can be added the same way, or directly to the * prototype. * * var Animal = CoreObject.extend({ * init: function(name){ * this.name = name; * }, * getName: function(){ * return this.name; * }, * sound: '...' * }); * * Animal.prototype.makeSound = function(){ * alert(this.sound); * }; * * To create an instance of a class, use the create method. * * var fluffy = Animal.create('Fluffy'); * fluffy.getName(); // -> Fluffy * * Methods and properties can be overridden in subclasses. * * var Horse = Animal.extend({ * sound: 'Neighhhhh!' * }); * * var horsey = Horse.create('Horsey'); * horsey.getName(); // -> Horsey * horsey.makeSound(); // -> Alert: Neighhhhh! * * @class * @constructor */ vjs.CoreObject = vjs['CoreObject'] = function(){}; // Manually exporting vjs['CoreObject'] here for Closure Compiler // because of the use of the extend/create class methods // If we didn't do this, those functions would get flattened to something like // `a = ...` and `this.prototype` would refer to the global object instead of // CoreObject /** * Create a new object that inherits from this Object * * var Animal = CoreObject.extend(); * var Horse = Animal.extend(); * * @param {Object} props Functions and properties to be applied to the * new object's prototype * @return {vjs.CoreObject} An object that inherits from CoreObject * @this {*} */ vjs.CoreObject.extend = function(props){ var init, subObj; props = props || {}; // Set up the constructor using the supplied init method // or using the init of the parent object // Make sure to check the unobfuscated version for external libs init = props['init'] || props.init || this.prototype['init'] || this.prototype.init || function(){}; // In Resig's simple class inheritance (previously used) the constructor // is a function that calls `this.init.apply(arguments)` // However that would prevent us from using `ParentObject.call(this);` // in a Child constructor because the `this` in `this.init` // would still refer to the Child and cause an infinite loop. // We would instead have to do // `ParentObject.prototype.init.apply(this, arguments);` // Bleh. We're not creating a _super() function, so it's good to keep // the parent constructor reference simple. subObj = function(){ init.apply(this, arguments); }; // Inherit from this object's prototype subObj.prototype = vjs.obj.create(this.prototype); // Reset the constructor property for subObj otherwise // instances of subObj would have the constructor of the parent Object subObj.prototype.constructor = subObj; // Make the class extendable subObj.extend = vjs.CoreObject.extend; // Make a function for creating instances subObj.create = vjs.CoreObject.create; // Extend subObj's prototype with functions and other properties from props for (var name in props) { if (props.hasOwnProperty(name)) { subObj.prototype[name] = props[name]; } } return subObj; }; /** * Create a new instance of this Object class * * var myAnimal = Animal.create(); * * @return {vjs.CoreObject} An instance of a CoreObject subclass * @this {*} */ vjs.CoreObject.create = function(){ // Create a new object that inherits from this object's prototype var inst = vjs.obj.create(this.prototype); // Apply this constructor function to the new object this.apply(inst, arguments); // Return the new object return inst; }; /** * @fileoverview Event System (John Resig - Secrets of a JS Ninja http://jsninja.com/) * (Original book version wasn't completely usable, so fixed some things and made Closure Compiler compatible) * This should work very similarly to jQuery's events, however it's based off the book version which isn't as * robust as jquery's, so there's probably some differences. */ /** * Add an event listener to element * It stores the handler function in a separate cache object * and adds a generic handler to the element's event, * along with a unique id (guid) to the element. * @param {Element|Object} elem Element or object to bind listeners to * @param {String|Array} type Type of event to bind to. * @param {Function} fn Event listener. * @private */ vjs.on = function(elem, type, fn){ if (vjs.obj.isArray(type)) { return _handleMultipleEvents(vjs.on, elem, type, fn); } var data = vjs.getData(elem); // We need a place to store all our handler data if (!data.handlers) data.handlers = {}; if (!data.handlers[type]) data.handlers[type] = []; if (!fn.guid) fn.guid = vjs.guid++; data.handlers[type].push(fn); if (!data.dispatcher) { data.disabled = false; data.dispatcher = function (event){ if (data.disabled) return; event = vjs.fixEvent(event); var handlers = data.handlers[event.type]; if (handlers) { // Copy handlers so if handlers are added/removed during the process it doesn't throw everything off. var handlersCopy = handlers.slice(0); for (var m = 0, n = handlersCopy.length; m < n; m++) { if (event.isImmediatePropagationStopped()) { break; } else { handlersCopy[m].call(elem, event); } } } }; } if (data.handlers[type].length == 1) { if (elem.addEventListener) { elem.addEventListener(type, data.dispatcher, false); } else if (elem.attachEvent) { elem.attachEvent('on' + type, data.dispatcher); } } }; /** * Removes event listeners from an element * @param {Element|Object} elem Object to remove listeners from * @param {String|Array=} type Type of listener to remove. Don't include to remove all events from element. * @param {Function} fn Specific listener to remove. Don't include to remove listeners for an event type. * @private */ vjs.off = function(elem, type, fn) { // Don't want to add a cache object through getData if not needed if (!vjs.hasData(elem)) return; var data = vjs.getData(elem); // If no events exist, nothing to unbind if (!data.handlers) { return; } if (vjs.obj.isArray(type)) { return _handleMultipleEvents(vjs.off, elem, type, fn); } // Utility function var removeType = function(t){ data.handlers[t] = []; vjs.cleanUpEvents(elem,t); }; // Are we removing all bound events? if (!type) { for (var t in data.handlers) removeType(t); return; } var handlers = data.handlers[type]; // If no handlers exist, nothing to unbind if (!handlers) return; // If no listener was provided, remove all listeners for type if (!fn) { removeType(type); return; } // We're only removing a single handler if (fn.guid) { for (var n = 0; n < handlers.length; n++) { if (handlers[n].guid === fn.guid) { handlers.splice(n--, 1); } } } vjs.cleanUpEvents(elem, type); }; /** * Clean up the listener cache and dispatchers * @param {Element|Object} elem Element to clean up * @param {String} type Type of event to clean up * @private */ vjs.cleanUpEvents = function(elem, type) { var data = vjs.getData(elem); // Remove the events of a particular type if there are none left if (data.handlers[type].length === 0) { delete data.handlers[type]; // data.handlers[type] = null; // Setting to null was causing an error with data.handlers // Remove the meta-handler from the element if (elem.removeEventListener) { elem.removeEventListener(type, data.dispatcher, false); } else if (elem.detachEvent) { elem.detachEvent('on' + type, data.dispatcher); } } // Remove the events object if there are no types left if (vjs.isEmpty(data.handlers)) { delete data.handlers; delete data.dispatcher; delete data.disabled; // data.handlers = null; // data.dispatcher = null; // data.disabled = null; } // Finally remove the expando if there is no data left if (vjs.isEmpty(data)) { vjs.removeData(elem); } }; /** * Fix a native event to have standard property values * @param {Object} event Event object to fix * @return {Object} * @private */ vjs.fixEvent = function(event) { function returnTrue() { return true; } function returnFalse() { return false; } // Test if fixing up is needed // Used to check if !event.stopPropagation instead of isPropagationStopped // But native events return true for stopPropagation, but don't have // other expected methods like isPropagationStopped. Seems to be a problem // with the Javascript Ninja code. So we're just overriding all events now. if (!event || !event.isPropagationStopped) { var old = event || window.event; event = {}; // Clone the old object so that we can modify the values event = {}; // IE8 Doesn't like when you mess with native event properties // Firefox returns false for event.hasOwnProperty('type') and other props // which makes copying more difficult. // TODO: Probably best to create a whitelist of event props for (var key in old) { // Safari 6.0.3 warns you if you try to copy deprecated layerX/Y // Chrome warns you if you try to copy deprecated keyboardEvent.keyLocation if (key !== 'layerX' && key !== 'layerY' && key !== 'keyLocation') { // Chrome 32+ warns if you try to copy deprecated returnValue, but // we still want to if preventDefault isn't supported (IE8). if (!(key == 'returnValue' && old.preventDefault)) { event[key] = old[key]; } } } // The event occurred on this element if (!event.target) { event.target = event.srcElement || document; } // Handle which other element the event is related to event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement; // Stop the default browser action event.preventDefault = function () { if (old.preventDefault) { old.preventDefault(); } event.returnValue = false; event.isDefaultPrevented = returnTrue; event.defaultPrevented = true; }; event.isDefaultPrevented = returnFalse; event.defaultPrevented = false; // Stop the event from bubbling event.stopPropagation = function () { if (old.stopPropagation) { old.stopPropagation(); } event.cancelBubble = true; event.isPropagationStopped = returnTrue; }; event.isPropagationStopped = returnFalse; // Stop the event from bubbling and executing other handlers event.stopImmediatePropagation = function () { if (old.stopImmediatePropagation) { old.stopImmediatePropagation(); } event.isImmediatePropagationStopped = returnTrue; event.stopPropagation(); }; event.isImmediatePropagationStopped = returnFalse; // Handle mouse position if (event.clientX != null) { var doc = document.documentElement, body = document.body; event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0); event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0); } // Handle key presses event.which = event.charCode || event.keyCode; // Fix button for mouse clicks: // 0 == left; 1 == middle; 2 == right if (event.button != null) { event.button = (event.button & 1 ? 0 : (event.button & 4 ? 1 : (event.button & 2 ? 2 : 0))); } } // Returns fixed-up instance return event; }; /** * Trigger an event for an element * @param {Element|Object} elem Element to trigger an event on * @param {Event|Object|String} event A string (the type) or an event object with a type attribute * @private */ vjs.trigger = function(elem, event) { // Fetches element data and a reference to the parent (for bubbling). // Don't want to add a data object to cache for every parent, // so checking hasData first. var elemData = (vjs.hasData(elem)) ? vjs.getData(elem) : {}; var parent = elem.parentNode || elem.ownerDocument; // type = event.type || event, // handler; // If an event name was passed as a string, creates an event out of it if (typeof event === 'string') { event = { type:event, target:elem }; } // Normalizes the event properties. event = vjs.fixEvent(event); // If the passed element has a dispatcher, executes the established handlers. if (elemData.dispatcher) { elemData.dispatcher.call(elem, event); } // Unless explicitly stopped or the event does not bubble (e.g. media events) // recursively calls this function to bubble the event up the DOM. if (parent && !event.isPropagationStopped() && event.bubbles !== false) { vjs.trigger(parent, event); // If at the top of the DOM, triggers the default action unless disabled. } else if (!parent && !event.defaultPrevented) { var targetData = vjs.getData(event.target); // Checks if the target has a default action for this event. if (event.target[event.type]) { // Temporarily disables event dispatching on the target as we have already executed the handler. targetData.disabled = true; // Executes the default action. if (typeof event.target[event.type] === 'function') { event.target[event.type](); } // Re-enables event dispatching. targetData.disabled = false; } } // Inform the triggerer if the default was prevented by returning false return !event.defaultPrevented; /* Original version of js ninja events wasn't complete. * We've since updated to the latest version, but keeping this around * for now just in case. */ // // Added in addition to book. Book code was broke. // event = typeof event === 'object' ? // event[vjs.expando] ? // event : // new vjs.Event(type, event) : // new vjs.Event(type); // event.type = type; // if (handler) { // handler.call(elem, event); // } // // Clean up the event in case it is being reused // event.result = undefined; // event.target = elem; }; /** * Trigger a listener only once for an event * @param {Element|Object} elem Element or object to * @param {String|Array} type * @param {Function} fn * @private */ vjs.one = function(elem, type, fn) { if (vjs.obj.isArray(type)) { return _handleMultipleEvents(vjs.one, elem, type, fn); } var func = function(){ vjs.off(elem, type, func); fn.apply(this, arguments); }; // copy the guid to the new function so it can removed using the original function's ID func.guid = fn.guid = fn.guid || vjs.guid++; vjs.on(elem, type, func); }; /** * Loops through an array of event types and calls the requested method for each type. * @param {Function} fn The event method we want to use. * @param {Element|Object} elem Element or object to bind listeners to * @param {String} type Type of event to bind to. * @param {Function} callback Event listener. * @private */ function _handleMultipleEvents(fn, elem, type, callback) { vjs.arr.forEach(type, function(type) { fn(elem, type, callback); //Call the event method for each one of the types }); } var hasOwnProp = Object.prototype.hasOwnProperty; /** * Creates an element and applies properties. * @param {String=} tagName Name of tag to be created. * @param {Object=} properties Element properties to be applied. * @return {Element} * @private */ vjs.createEl = function(tagName, properties){ var el; tagName = tagName || 'div'; properties = properties || {}; el = document.createElement(tagName); vjs.obj.each(properties, function(propName, val){ // Not remembering why we were checking for dash // but using setAttribute means you have to use getAttribute // The check for dash checks for the aria-* attributes, like aria-label, aria-valuemin. // The additional check for "role" is because the default method for adding attributes does not // add the attribute "role". My guess is because it's not a valid attribute in some namespaces, although // browsers handle the attribute just fine. The W3C allows for aria-* attributes to be used in pre-HTML5 docs. // http://www.w3.org/TR/wai-aria-primer/#ariahtml. Using setAttribute gets around this problem. if (propName.indexOf('aria-') !== -1 || propName == 'role') { el.setAttribute(propName, val); } else { el[propName] = val; } }); return el; }; /** * Uppercase the first letter of a string * @param {String} string String to be uppercased * @return {String} * @private */ vjs.capitalize = function(string){ return string.charAt(0).toUpperCase() + string.slice(1); }; /** * Object functions container * @type {Object} * @private */ vjs.obj = {}; /** * Object.create shim for prototypal inheritance * * https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/create * * @function * @param {Object} obj Object to use as prototype * @private */ vjs.obj.create = Object.create || function(obj){ //Create a new function called 'F' which is just an empty object. function F() {} //the prototype of the 'F' function should point to the //parameter of the anonymous function. F.prototype = obj; //create a new constructor function based off of the 'F' function. return new F(); }; /** * Loop through each property in an object and call a function * whose arguments are (key,value) * @param {Object} obj Object of properties * @param {Function} fn Function to be called on each property. * @this {*} * @private */ vjs.obj.each = function(obj, fn, context){ for (var key in obj) { if (hasOwnProp.call(obj, key)) { fn.call(context || this, key, obj[key]); } } }; /** * Merge two objects together and return the original. * @param {Object} obj1 * @param {Object} obj2 * @return {Object} * @private */ vjs.obj.merge = function(obj1, obj2){ if (!obj2) { return obj1; } for (var key in obj2){ if (hasOwnProp.call(obj2, key)) { obj1[key] = obj2[key]; } } return obj1; }; /** * Merge two objects, and merge any properties that are objects * instead of just overwriting one. Uses to merge options hashes * where deeper default settings are important. * @param {Object} obj1 Object to override * @param {Object} obj2 Overriding object * @return {Object} New object. Obj1 and Obj2 will be untouched. * @private */ vjs.obj.deepMerge = function(obj1, obj2){ var key, val1, val2; // make a copy of obj1 so we're not overwriting original values. // like prototype.options_ and all sub options objects obj1 = vjs.obj.copy(obj1); for (key in obj2){ if (hasOwnProp.call(obj2, key)) { val1 = obj1[key]; val2 = obj2[key]; // Check if both properties are pure objects and do a deep merge if so if (vjs.obj.isPlain(val1) && vjs.obj.isPlain(val2)) { obj1[key] = vjs.obj.deepMerge(val1, val2); } else { obj1[key] = obj2[key]; } } } return obj1; }; /** * Make a copy of the supplied object * @param {Object} obj Object to copy * @return {Object} Copy of object * @private */ vjs.obj.copy = function(obj){ return vjs.obj.merge({}, obj); }; /** * Check if an object is plain, and not a dom node or any object sub-instance * @param {Object} obj Object to check * @return {Boolean} True if plain, false otherwise * @private */ vjs.obj.isPlain = function(obj){ return !!obj && typeof obj === 'object' && obj.toString() === '[object Object]' && obj.constructor === Object; }; /** * Check if an object is Array * Since instanceof Array will not work on arrays created in another frame we need to use Array.isArray, but since IE8 does not support Array.isArray we need this shim * @param {Object} obj Object to check * @return {Boolean} True if plain, false otherwise * @private */ vjs.obj.isArray = Array.isArray || function(arr) { return Object.prototype.toString.call(arr) === '[object Array]'; }; /** * Check to see whether the input is NaN or not. * NaN is the only JavaScript construct that isn't equal to itself * @param {Number} num Number to check * @return {Boolean} True if NaN, false otherwise * @private */ vjs.isNaN = function(num) { return num !== num; }; /** * Bind (a.k.a proxy or Context). A simple method for changing the context of a function It also stores a unique id on the function so it can be easily removed from events * @param {*} context The object to bind as scope * @param {Function} fn The function to be bound to a scope * @param {Number=} uid An optional unique ID for the function to be set * @return {Function} * @private */ vjs.bind = function(context, fn, uid) { // Make sure the function has a unique ID if (!fn.guid) { fn.guid = vjs.guid++; } // Create the new function that changes the context var ret = function() { return fn.apply(context, arguments); }; // Allow for the ability to individualize this function // Needed in the case where multiple objects might share the same prototype // IF both items add an event listener with the same function, then you try to remove just one // it will remove both because they both have the same guid. // when using this, you need to use the bind method when you remove the listener as well. // currently used in text tracks ret.guid = (uid) ? uid + '_' + fn.guid : fn.guid; return ret; }; /** * Element Data Store. Allows for binding data to an element without putting it directly on the element. * Ex. Event listeners are stored here. * (also from jsninja.com, slightly modified and updated for closure compiler) * @type {Object} * @private */ vjs.cache = {}; /** * Unique ID for an element or function * @type {Number} * @private */ vjs.guid = 1; /** * Unique attribute name to store an element's guid in * @type {String} * @constant * @private */ vjs.expando = 'vdata' + (new Date()).getTime(); /** * Returns the cache object where data for an element is stored * @param {Element} el Element to store data for. * @return {Object} * @private */ vjs.getData = function(el){ var id = el[vjs.expando]; if (!id) { id = el[vjs.expando] = vjs.guid++; vjs.cache[id] = {}; } return vjs.cache[id]; }; /** * Returns the cache object where data for an element is stored * @param {Element} el Element to store data for. * @return {Object} * @private */ vjs.hasData = function(el){ var id = el[vjs.expando]; return !(!id || vjs.isEmpty(vjs.cache[id])); }; /** * Delete data for the element from the cache and the guid attr from getElementById * @param {Element} el Remove data for an element * @private */ vjs.removeData = function(el){ var id = el[vjs.expando]; if (!id) { return; } // Remove all stored data // Changed to = null // http://coding.smashingmagazine.com/2012/11/05/writing-fast-memory-efficient-javascript/ // vjs.cache[id] = null; delete vjs.cache[id]; // Remove the expando property from the DOM node try { delete el[vjs.expando]; } catch(e) { if (el.removeAttribute) { el.removeAttribute(vjs.expando); } else { // IE doesn't appear to support removeAttribute on the document element el[vjs.expando] = null; } } }; /** * Check if an object is empty * @param {Object} obj The object to check for emptiness * @return {Boolean} * @private */ vjs.isEmpty = function(obj) { for (var prop in obj) { // Inlude null properties as empty. if (obj[prop] !== null) { return false; } } return true; }; /** * Check if an element has a CSS class * @param {Element} element Element to check * @param {String} classToCheck Classname to check * @private */ vjs.hasClass = function(element, classToCheck){ return ((' ' + element.className + ' ').indexOf(' ' + classToCheck + ' ') !== -1); }; /** * Add a CSS class name to an element * @param {Element} element Element to add class name to * @param {String} classToAdd Classname to add * @private */ vjs.addClass = function(element, classToAdd){ if (!vjs.hasClass(element, classToAdd)) { element.className = element.className === '' ? classToAdd : element.className + ' ' + classToAdd; } }; /** * Remove a CSS class name from an element * @param {Element} element Element to remove from class name * @param {String} classToAdd Classname to remove * @private */ vjs.removeClass = function(element, classToRemove){ var classNames, i; if (!vjs.hasClass(element, classToRemove)) {return;} classNames = element.className.split(' '); // no arr.indexOf in ie8, and we don't want to add a big shim for (i = classNames.length - 1; i >= 0; i--) { if (classNames[i] === classToRemove) { classNames.splice(i,1); } } element.className = classNames.join(' '); }; /** * Element for testing browser HTML5 video capabilities * @type {Element} * @constant * @private */ vjs.TEST_VID = vjs.createEl('video'); /** * Useragent for browser testing. * @type {String} * @constant * @private */ vjs.USER_AGENT = navigator.userAgent; /** * Device is an iPhone * @type {Boolean} * @constant * @private */ vjs.IS_IPHONE = (/iPhone/i).test(vjs.USER_AGENT); vjs.IS_IPAD = (/iPad/i).test(vjs.USER_AGENT); vjs.IS_IPOD = (/iPod/i).test(vjs.USER_AGENT); vjs.IS_IOS = vjs.IS_IPHONE || vjs.IS_IPAD || vjs.IS_IPOD; vjs.IOS_VERSION = (function(){ var match = vjs.USER_AGENT.match(/OS (\d+)_/i); if (match && match[1]) { return match[1]; } })(); vjs.IS_ANDROID = (/Android/i).test(vjs.USER_AGENT); vjs.ANDROID_VERSION = (function() { // This matches Android Major.Minor.Patch versions // ANDROID_VERSION is Major.Minor as a Number, if Minor isn't available, then only Major is returned var match = vjs.USER_AGENT.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i), major, minor; if (!match) { return null; } major = match[1] && parseFloat(match[1]); minor = match[2] && parseFloat(match[2]); if (major && minor) { return parseFloat(match[1] + '.' + match[2]); } else if (major) { return major; } else { return null; } })(); // Old Android is defined as Version older than 2.3, and requiring a webkit version of the android browser vjs.IS_OLD_ANDROID = vjs.IS_ANDROID && (/webkit/i).test(vjs.USER_AGENT) && vjs.ANDROID_VERSION < 2.3; vjs.IS_FIREFOX = (/Firefox/i).test(vjs.USER_AGENT); vjs.IS_CHROME = (/Chrome/i).test(vjs.USER_AGENT); vjs.TOUCH_ENABLED = !!(('ontouchstart' in window) || window.DocumentTouch && document instanceof window.DocumentTouch); vjs.BACKGROUND_SIZE_SUPPORTED = 'backgroundSize' in vjs.TEST_VID.style; /** * Apply attributes to an HTML element. * @param {Element} el Target element. * @param {Object=} attributes Element attributes to be applied. * @private */ vjs.setElementAttributes = function(el, attributes){ vjs.obj.each(attributes, function(attrName, attrValue) { if (attrValue === null || typeof attrValue === 'undefined' || attrValue === false) { el.removeAttribute(attrName); } else { el.setAttribute(attrName, (attrValue === true ? '' : attrValue)); } }); }; /** * Get an element's attribute values, as defined on the HTML tag * Attributes are not the same as properties. They're defined on the tag * or with setAttribute (which shouldn't be used with HTML) * This will return true or false for boolean attributes. * @param {Element} tag Element from which to get tag attributes * @return {Object} * @private */ vjs.getElementAttributes = function(tag){ var obj, knownBooleans, attrs, attrName, attrVal; obj = {}; // known boolean attributes // we can check for matching boolean properties, but older browsers // won't know about HTML5 boolean attributes that we still read from knownBooleans = ','+'autoplay,controls,loop,muted,default'+','; if (tag && tag.attributes && tag.attributes.length > 0) { attrs = tag.attributes; for (var i = attrs.length - 1; i >= 0; i--) { attrName = attrs[i].name; attrVal = attrs[i].value; // check for known booleans // the matching element property will return a value for typeof if (typeof tag[attrName] === 'boolean' || knownBooleans.indexOf(','+attrName+',') !== -1) { // the value of an included boolean attribute is typically an empty // string ('') which would equal false if we just check for a false value. // we also don't want support bad code like autoplay='false' attrVal = (attrVal !== null) ? true : false; } obj[attrName] = attrVal; } } return obj; }; /** * Get the computed style value for an element * From http://robertnyman.com/2006/04/24/get-the-rendered-style-of-an-element/ * @param {Element} el Element to get style value for * @param {String} strCssRule Style name * @return {String} Style value * @private */ vjs.getComputedDimension = function(el, strCssRule){ var strValue = ''; if(document.defaultView && document.defaultView.getComputedStyle){ strValue = document.defaultView.getComputedStyle(el, '').getPropertyValue(strCssRule); } else if(el.currentStyle){ // IE8 Width/Height support strValue = el['client'+strCssRule.substr(0,1).toUpperCase() + strCssRule.substr(1)] + 'px'; } return strValue; }; /** * Insert an element as the first child node of another * @param {Element} child Element to insert * @param {[type]} parent Element to insert child into * @private */ vjs.insertFirst = function(child, parent){ if (parent.firstChild) { parent.insertBefore(child, parent.firstChild); } else { parent.appendChild(child); } }; /** * Object to hold browser support information * @type {Object} * @private */ vjs.browser = {}; /** * Shorthand for document.getElementById() * Also allows for CSS (jQuery) ID syntax. But nothing other than IDs. * @param {String} id Element ID * @return {Element} Element with supplied ID * @private */ vjs.el = function(id){ if (id.indexOf('#') === 0) { id = id.slice(1); } return document.getElementById(id); }; /** * Format seconds as a time string, H:MM:SS or M:SS * Supplying a guide (in seconds) will force a number of leading zeros * to cover the length of the guide * @param {Number} seconds Number of seconds to be turned into a string * @param {Number} guide Number (in seconds) to model the string after * @return {String} Time formatted as H:MM:SS or M:SS * @private */ vjs.formatTime = function(seconds, guide) { // Default to using seconds as guide guide = guide || seconds; var s = Math.floor(seconds % 60), m = Math.floor(seconds / 60 % 60), h = Math.floor(seconds / 3600), gm = Math.floor(guide / 60 % 60), gh = Math.floor(guide / 3600); // handle invalid times if (isNaN(seconds) || seconds === Infinity) { // '-' is false for all relational operators (e.g. <, >=) so this setting // will add the minimum number of fields specified by the guide h = m = s = '-'; } // Check if we need to show hours h = (h > 0 || gh > 0) ? h + ':' : ''; // If hours are showing, we may need to add a leading zero. // Always show at least one digit of minutes. m = (((h || gm >= 10) && m < 10) ? '0' + m : m) + ':'; // Check if leading zero is need for seconds s = (s < 10) ? '0' + s : s; return h + m + s; }; // Attempt to block the ability to select text while dragging controls vjs.blockTextSelection = function(){ document.body.focus(); document.onselectstart = function () { return false; }; }; // Turn off text selection blocking vjs.unblockTextSelection = function(){ document.onselectstart = function () { return true; }; }; /** * Trim whitespace from the ends of a string. * @param {String} string String to trim * @return {String} Trimmed string * @private */ vjs.trim = function(str){ return (str+'').replace(/^\s+|\s+$/g, ''); }; /** * Should round off a number to a decimal place * @param {Number} num Number to round * @param {Number} dec Number of decimal places to round to * @return {Number} Rounded number * @private */ vjs.round = function(num, dec) { if (!dec) { dec = 0; } return Math.round(num*Math.pow(10,dec))/Math.pow(10,dec); }; /** * Should create a fake TimeRange object * Mimics an HTML5 time range instance, which has functions that * return the start and end times for a range * TimeRanges are returned by the buffered() method * @param {Number} start Start time in seconds * @param {Number} end End time in seconds * @return {Object} Fake TimeRange object * @private */ vjs.createTimeRange = function(start, end){ return { length: 1, start: function() { return start; }, end: function() { return end; } }; }; /** * Add to local storage (may removable) * @private */ vjs.setLocalStorage = function(key, value){ try { // IE was throwing errors referencing the var anywhere without this var localStorage = window.localStorage || false; if (!localStorage) { return; } localStorage[key] = value; } catch(e) { if (e.code == 22 || e.code == 1014) { // Webkit == 22 / Firefox == 1014 vjs.log('LocalStorage Full (VideoJS)', e); } else { if (e.code == 18) { vjs.log('LocalStorage not allowed (VideoJS)', e); } else { vjs.log('LocalStorage Error (VideoJS)', e); } } } }; /** * Get absolute version of relative URL. Used to tell flash correct URL. * http://stackoverflow.com/questions/470832/getting-an-absolute-url-from-a-relative-one-ie6-issue * @param {String} url URL to make absolute * @return {String} Absolute URL * @private */ vjs.getAbsoluteURL = function(url){ // Check if absolute URL if (!url.match(/^https?:\/\//)) { // Convert to absolute URL. Flash hosted off-site needs an absolute URL. url = vjs.createEl('div', { innerHTML: '<a href="'+url+'">x</a>' }).firstChild.href; } return url; }; /** * Resolve and parse the elements of a URL * @param {String} url The url to parse * @return {Object} An object of url details */ vjs.parseUrl = function(url) { var div, a, addToBody, props, details; props = ['protocol', 'hostname', 'port', 'pathname', 'search', 'hash', 'host']; // add the url to an anchor and let the browser parse the URL a = vjs.createEl('a', { href: url }); // IE8 (and 9?) Fix // ie8 doesn't parse the URL correctly until the anchor is actually // added to the body, and an innerHTML is needed to trigger the parsing addToBody = (a.host === '' && a.protocol !== 'file:'); if (addToBody) { div = vjs.createEl('div'); div.innerHTML = '<a href="'+url+'"></a>'; a = div.firstChild; // prevent the div from affecting layout div.setAttribute('style', 'display:none; position:absolute;'); document.body.appendChild(div); } // Copy the specific URL properties to a new object // This is also needed for IE8 because the anchor loses its // properties when it's removed from the dom details = {}; for (var i = 0; i < props.length; i++) { details[props[i]] = a[props[i]]; } if (addToBody) { document.body.removeChild(div); } return details; }; /** * Log messages to the console and history based on the type of message * * @param {String} type The type of message, or `null` for `log` * @param {[type]} args The args to be passed to the log * @private */ function _logType(type, args){ var argsArray, noop, console; // convert args to an array to get array functions argsArray = Array.prototype.slice.call(args); // if there's no console then don't try to output messages // they will still be stored in vjs.log.history // Was setting these once outside of this function, but containing them // in the function makes it easier to test cases where console doesn't exist noop = function(){}; console = window['console'] || { 'log': noop, 'warn': noop, 'error': noop }; if (type) { // add the type to the front of the message argsArray.unshift(type.toUpperCase()+':'); } else { // default to log with no prefix type = 'log'; } // add to history vjs.log.history.push(argsArray); // add console prefix after adding to history argsArray.unshift('VIDEOJS:'); // call appropriate log function if (console[type].apply) { console[type].apply(console, argsArray); } else { // ie8 doesn't allow error.apply, but it will just join() the array anyway console[type](argsArray.join(' ')); } } /** * Log plain debug messages */ vjs.log = function(){ _logType(null, arguments); }; /** * Keep a history of log messages * @type {Array} */ vjs.log.history = []; /** * Log error messages */ vjs.log.error = function(){ _logType('error', arguments); }; /** * Log warning messages */ vjs.log.warn = function(){ _logType('warn', arguments); }; // Offset Left // getBoundingClientRect technique from John Resig http://ejohn.org/blog/getboundingclientrect-is-awesome/ vjs.findPosition = function(el) { var box, docEl, body, clientLeft, scrollLeft, left, clientTop, scrollTop, top; if (el.getBoundingClientRect && el.parentNode) { box = el.getBoundingClientRect(); } if (!box) { return { left: 0, top: 0 }; } docEl = document.documentElement; body = document.body; clientLeft = docEl.clientLeft || body.clientLeft || 0; scrollLeft = window.pageXOffset || body.scrollLeft; left = box.left + scrollLeft - clientLeft; clientTop = docEl.clientTop || body.clientTop || 0; scrollTop = window.pageYOffset || body.scrollTop; top = box.top + scrollTop - clientTop; // Android sometimes returns slightly off decimal values, so need to round return { left: vjs.round(left), top: vjs.round(top) }; }; /** * Array functions container * @type {Object} * @private */ vjs.arr = {}; /* * Loops through an array and runs a function for each item inside it. * @param {Array} array The array * @param {Function} callback The function to be run for each item * @param {*} thisArg The `this` binding of callback * @returns {Array} The array * @private */ vjs.arr.forEach = function(array, callback, thisArg) { if (vjs.obj.isArray(array) && callback instanceof Function) { for (var i = 0, len = array.length; i < len; ++i) { callback.call(thisArg || vjs, array[i], i, array); } } return array; }; /** * Simple http request for retrieving external files (e.g. text tracks) * * ##### Example * * // using url string * videojs.xhr('http://example.com/myfile.vtt', function(error, response, responseBody){}); * * // or options block * videojs.xhr({ * uri: 'http://example.com/myfile.vtt', * method: 'GET', * responseType: 'text' * }, function(error, response, responseBody){ * if (error) { * // log the error * } else { * // successful, do something with the response * } * }); * * * API is modeled after the Raynos/xhr, which we hope to use after * getting browserify implemented. * https://github.com/Raynos/xhr/blob/master/index.js * * @param {Object|String} options Options block or URL string * @param {Function} callback The callback function * @returns {Object} The request */ vjs.xhr = function(options, callback){ var XHR, request, urlInfo, winLoc, fileUrl, crossOrigin, abortTimeout, successHandler, errorHandler; // If options is a string it's the url if (typeof options === 'string') { options = { uri: options }; } // Merge with default options videojs.util.mergeOptions({ method: 'GET', timeout: 45 * 1000 }, options); callback = callback || function(){}; successHandler = function(){ window.clearTimeout(abortTimeout); callback(null, request, request.response || request.responseText); }; errorHandler = function(err){ window.clearTimeout(abortTimeout); if (!err || typeof err === 'string') { err = new Error(err); } callback(err, request); }; XHR = window.XMLHttpRequest; if (typeof XHR === 'undefined') { // Shim XMLHttpRequest for older IEs XHR = function () { try { return new window.ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch (e) {} try { return new window.ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch (f) {} try { return new window.ActiveXObject('Msxml2.XMLHTTP'); } catch (g) {} throw new Error('This browser does not support XMLHttpRequest.'); }; } request = new XHR(); // Store a reference to the url on the request instance request.uri = options.uri; urlInfo = vjs.parseUrl(options.uri); winLoc = window.location; // Check if url is for another domain/origin // IE8 doesn't know location.origin, so we won't rely on it here crossOrigin = (urlInfo.protocol + urlInfo.host) !== (winLoc.protocol + winLoc.host); // XDomainRequest -- Use for IE if XMLHTTPRequest2 isn't available // 'withCredentials' is only available in XMLHTTPRequest2 // Also XDomainRequest has a lot of gotchas, so only use if cross domain if (crossOrigin && window.XDomainRequest && !('withCredentials' in request)) { request = new window.XDomainRequest(); request.onload = successHandler; request.onerror = errorHandler; // These blank handlers need to be set to fix ie9 // http://cypressnorth.com/programming/internet-explorer-aborting-ajax-requests-fixed/ request.onprogress = function(){}; request.ontimeout = function(){}; // XMLHTTPRequest } else { fileUrl = (urlInfo.protocol == 'file:' || winLoc.protocol == 'file:'); request.onreadystatechange = function() { if (request.readyState === 4) { if (request.timedout) { return errorHandler('timeout'); } if (request.status === 200 || fileUrl && request.status === 0) { successHandler(); } else { errorHandler(); } } }; if (options.timeout) { abortTimeout = window.setTimeout(function() { if (request.readyState !== 4) { request.timedout = true; request.abort(); } }, options.timeout); } } // open the connection try { // Third arg is async, or ignored by XDomainRequest request.open(options.method || 'GET', options.uri, true); } catch(err) { return errorHandler(err); } // withCredentials only supported by XMLHttpRequest2 if(options.withCredentials) { request.withCredentials = true; } if (options.responseType) { request.responseType = options.responseType; } // send the request try { request.send(); } catch(err) { return errorHandler(err); } return request; }; /** * Utility functions namespace * @namespace * @type {Object} */ vjs.util = {}; /** * Merge two options objects, recursively merging any plain object properties as * well. Previously `deepMerge` * * @param {Object} obj1 Object to override values in * @param {Object} obj2 Overriding object * @return {Object} New object -- obj1 and obj2 will be untouched */ vjs.util.mergeOptions = function(obj1, obj2){ var key, val1, val2; // make a copy of obj1 so we're not overwriting original values. // like prototype.options_ and all sub options objects obj1 = vjs.obj.copy(obj1); for (key in obj2){ if (obj2.hasOwnProperty(key)) { val1 = obj1[key]; val2 = obj2[key]; // Check if both properties are pure objects and do a deep merge if so if (vjs.obj.isPlain(val1) && vjs.obj.isPlain(val2)) { obj1[key] = vjs.util.mergeOptions(val1, val2); } else { obj1[key] = obj2[key]; } } } return obj1; };/** * @fileoverview Player Component - Base class for all UI objects * */ /** * Base UI Component class * * Components are embeddable UI objects that are represented by both a * javascript object and an element in the DOM. They can be children of other * components, and can have many children themselves. * * // adding a button to the player * var button = player.addChild('button'); * button.el(); // -> button element * * <div class="video-js"> * <div class="vjs-button">Button</div> * </div> * * Components are also event emitters. * * button.on('click', function(){ * console.log('Button Clicked!'); * }); * * button.trigger('customevent'); * * @param {Object} player Main Player * @param {Object=} options * @class * @constructor * @extends vjs.CoreObject */ vjs.Component = vjs.CoreObject.extend({ /** * the constructor function for the class * * @constructor */ init: function(player, options, ready){ this.player_ = player; // Make a copy of prototype.options_ to protect against overriding global defaults this.options_ = vjs.obj.copy(this.options_); // Updated options with supplied options options = this.options(options); // Get ID from options or options element if one is supplied this.id_ = options['id'] || (options['el'] && options['el']['id']); // If there was no ID from the options, generate one if (!this.id_) { // Don't require the player ID function in the case of mock players this.id_ = ((player.id && player.id()) || 'no_player') + '_component_' + vjs.guid++; } this.name_ = options['name'] || null; // Create element if one wasn't provided in options this.el_ = options['el'] || this.createEl(); this.children_ = []; this.childIndex_ = {}; this.childNameIndex_ = {}; // Add any child components in options this.initChildren(); this.ready(ready); // Don't want to trigger ready here or it will before init is actually // finished for all children that run this constructor if (options.reportTouchActivity !== false) { this.enableTouchActivity(); } } }); /** * Dispose of the component and all child components */ vjs.Component.prototype.dispose = function(){ this.trigger({ type: 'dispose', 'bubbles': false }); // Dispose all children. if (this.children_) { for (var i = this.children_.length - 1; i >= 0; i--) { if (this.children_[i].dispose) { this.children_[i].dispose(); } } } // Delete child references this.children_ = null; this.childIndex_ = null; this.childNameIndex_ = null; // Remove all event listeners. this.off(); // Remove element from DOM if (this.el_.parentNode) { this.el_.parentNode.removeChild(this.el_); } vjs.removeData(this.el_); this.el_ = null; }; /** * Reference to main player instance * * @type {vjs.Player} * @private */ vjs.Component.prototype.player_ = true; /** * Return the component's player * * @return {vjs.Player} */ vjs.Component.prototype.player = function(){ return this.player_; }; /** * The component's options object * * @type {Object} * @private */ vjs.Component.prototype.options_; /** * Deep merge of options objects * * Whenever a property is an object on both options objects * the two properties will be merged using vjs.obj.deepMerge. * * This is used for merging options for child components. We * want it to be easy to override individual options on a child * component without having to rewrite all the other default options. * * Parent.prototype.options_ = { * children: { * 'childOne': { 'foo': 'bar', 'asdf': 'fdsa' }, * 'childTwo': {}, * 'childThree': {} * } * } * newOptions = { * children: { * 'childOne': { 'foo': 'baz', 'abc': '123' } * 'childTwo': null, * 'childFour': {} * } * } * * this.options(newOptions); * * RESULT * * { * children: { * 'childOne': { 'foo': 'baz', 'asdf': 'fdsa', 'abc': '123' }, * 'childTwo': null, // Disabled. Won't be initialized. * 'childThree': {}, * 'childFour': {} * } * } * * @param {Object} obj Object of new option values * @return {Object} A NEW object of this.options_ and obj merged */ vjs.Component.prototype.options = function(obj){ if (obj === undefined) return this.options_; return this.options_ = vjs.util.mergeOptions(this.options_, obj); }; /** * The DOM element for the component * * @type {Element} * @private */ vjs.Component.prototype.el_; /** * Create the component's DOM element * * @param {String=} tagName Element's node type. e.g. 'div' * @param {Object=} attributes An object of element attributes that should be set on the element * @return {Element} */ vjs.Component.prototype.createEl = function(tagName, attributes){ return vjs.createEl(tagName, attributes); }; vjs.Component.prototype.localize = function(string){ var lang = this.player_.language(), languages = this.player_.languages(); if (languages && languages[lang] && languages[lang][string]) { return languages[lang][string]; } return string; }; /** * Get the component's DOM element * * var domEl = myComponent.el(); * * @return {Element} */ vjs.Component.prototype.el = function(){ return this.el_; }; /** * An optional element where, if defined, children will be inserted instead of * directly in `el_` * * @type {Element} * @private */ vjs.Component.prototype.contentEl_; /** * Return the component's DOM element for embedding content. * Will either be el_ or a new element defined in createEl. * * @return {Element} */ vjs.Component.prototype.contentEl = function(){ return this.contentEl_ || this.el_; }; /** * The ID for the component * * @type {String} * @private */ vjs.Component.prototype.id_; /** * Get the component's ID * * var id = myComponent.id(); * * @return {String} */ vjs.Component.prototype.id = function(){ return this.id_; }; /** * The name for the component. Often used to reference the component. * * @type {String} * @private */ vjs.Component.prototype.name_; /** * Get the component's name. The name is often used to reference the component. * * var name = myComponent.name(); * * @return {String} */ vjs.Component.prototype.name = function(){ return this.name_; }; /** * Array of child components * * @type {Array} * @private */ vjs.Component.prototype.children_; /** * Get an array of all child components * * var kids = myComponent.children(); * * @return {Array} The children */ vjs.Component.prototype.children = function(){ return this.children_; }; /** * Object of child components by ID * * @type {Object} * @private */ vjs.Component.prototype.childIndex_; /** * Returns a child component with the provided ID * * @return {vjs.Component} */ vjs.Component.prototype.getChildById = function(id){ return this.childIndex_[id]; }; /** * Object of child components by name * * @type {Object} * @private */ vjs.Component.prototype.childNameIndex_; /** * Returns a child component with the provided name * * @return {vjs.Component} */ vjs.Component.prototype.getChild = function(name){ return this.childNameIndex_[name]; }; /** * Adds a child component inside this component * * myComponent.el(); * // -> <div class='my-component'></div> * myComonent.children(); * // [empty array] * * var myButton = myComponent.addChild('MyButton'); * // -> <div class='my-component'><div class="my-button">myButton<div></div> * // -> myButton === myComonent.children()[0]; * * Pass in options for child constructors and options for children of the child * * var myButton = myComponent.addChild('MyButton', { * text: 'Press Me', * children: { * buttonChildExample: { * buttonChildOption: true * } * } * }); * * @param {String|vjs.Component} child The class name or instance of a child to add * @param {Object=} options Options, including options to be passed to children of the child. * @return {vjs.Component} The child component (created by this process if a string was used) * @suppress {accessControls|checkRegExp|checkTypes|checkVars|const|constantProperty|deprecated|duplicate|es5Strict|fileoverviewTags|globalThis|invalidCasts|missingProperties|nonStandardJsDocs|strictModuleDepCheck|undefinedNames|undefinedVars|unknownDefines|uselessCode|visibility} */ vjs.Component.prototype.addChild = function(child, options){ var component, componentClass, componentName; // If child is a string, create new component with options if (typeof child === 'string') { componentName = child; // Make sure options is at least an empty object to protect against errors options = options || {}; // If no componentClass in options, assume componentClass is the name lowercased // (e.g. playButton) componentClass = options['componentClass'] || vjs.capitalize(componentName); // Set name through options options['name'] = componentName; // Create a new object & element for this controls set // If there's no .player_, this is a player // Closure Compiler throws an 'incomplete alias' warning if we use the vjs variable directly. // Every class should be exported, so this should never be a problem here. component = new window['videojs'][componentClass](this.player_ || this, options); // child is a component instance } else { component = child; } this.children_.push(component); if (typeof component.id === 'function') { this.childIndex_[component.id()] = component; } // If a name wasn't used to create the component, check if we can use the // name function of the component componentName = componentName || (component.name && component.name()); if (componentName) { this.childNameIndex_[componentName] = component; } // Add the UI object's element to the container div (box) // Having an element is not required if (typeof component['el'] === 'function' && component['el']()) { this.contentEl().appendChild(component['el']()); } // Return so it can stored on parent object if desired. return component; }; /** * Remove a child component from this component's list of children, and the * child component's element from this component's element * * @param {vjs.Component} component Component to remove */ vjs.Component.prototype.removeChild = function(component){ if (typeof component === 'string') { component = this.getChild(component); } if (!component || !this.children_) return; var childFound = false; for (var i = this.children_.length - 1; i >= 0; i--) { if (this.children_[i] === component) { childFound = true; this.children_.splice(i,1); break; } } if (!childFound) return; this.childIndex_[component.id] = null; this.childNameIndex_[component.name] = null; var compEl = component.el(); if (compEl && compEl.parentNode === this.contentEl()) { this.contentEl().removeChild(component.el()); } }; /** * Add and initialize default child components from options * * // when an instance of MyComponent is created, all children in options * // will be added to the instance by their name strings and options * MyComponent.prototype.options_.children = { * myChildComponent: { * myChildOption: true * } * } * * // Or when creating the component * var myComp = new MyComponent(player, { * children: { * myChildComponent: { * myChildOption: true * } * } * }); * * The children option can also be an Array of child names or * child options objects (that also include a 'name' key). * * var myComp = new MyComponent(player, { * children: [ * 'button', * { * name: 'button', * someOtherOption: true * } * ] * }); * */ vjs.Component.prototype.initChildren = function(){ var parent, parentOptions, children, child, name, opts, handleAdd; parent = this; parentOptions = parent.options(); children = parentOptions['children']; if (children) { handleAdd = function(name, opts){ // Allow options for children to be set at the parent options // e.g. videojs(id, { controlBar: false }); // instead of videojs(id, { children: { controlBar: false }); if (parentOptions[name] !== undefined) { opts = parentOptions[name]; } // Allow for disabling default components // e.g. vjs.options['children']['posterImage'] = false if (opts === false) return; // Create and add the child component. // Add a direct reference to the child by name on the parent instance. // If two of the same component are used, different names should be supplied // for each parent[name] = parent.addChild(name, opts); }; // Allow for an array of children details to passed in the options if (vjs.obj.isArray(children)) { for (var i = 0; i < children.length; i++) { child = children[i]; if (typeof child == 'string') { // ['myComponent'] name = child; opts = {}; } else { // [{ name: 'myComponent', otherOption: true }] name = child.name; opts = child; } handleAdd(name, opts); } } else { vjs.obj.each(children, handleAdd); } } }; /** * Allows sub components to stack CSS class names * * @return {String} The constructed class name */ vjs.Component.prototype.buildCSSClass = function(){ // Child classes can include a function that does: // return 'CLASS NAME' + this._super(); return ''; }; /* Events ============================================================================= */ /** * Add an event listener to this component's element * * var myFunc = function(){ * var myComponent = this; * // Do something when the event is fired * }; * * myComponent.on('eventType', myFunc); * * The context of myFunc will be myComponent unless previously bound. * * Alternatively, you can add a listener to another element or component. * * myComponent.on(otherElement, 'eventName', myFunc); * myComponent.on(otherComponent, 'eventName', myFunc); * * The benefit of using this over `vjs.on(otherElement, 'eventName', myFunc)` * and `otherComponent.on('eventName', myFunc)` is that this way the listeners * will be automatically cleaned up when either component is disposed. * It will also bind myComponent as the context of myFunc. * * **NOTE**: When using this on elements in the page other than window * and document (both permanent), if you remove the element from the DOM * you need to call `vjs.trigger(el, 'dispose')` on it to clean up * references to it and allow the browser to garbage collect it. * * @param {String|vjs.Component} first The event type or other component * @param {Function|String} second The event handler or event type * @param {Function} third The event handler * @return {vjs.Component} self */ vjs.Component.prototype.on = function(first, second, third){ var target, type, fn, removeOnDispose, cleanRemover, thisComponent; if (typeof first === 'string' || vjs.obj.isArray(first)) { vjs.on(this.el_, first, vjs.bind(this, second)); // Targeting another component or element } else { target = first; type = second; fn = vjs.bind(this, third); thisComponent = this; // When this component is disposed, remove the listener from the other component removeOnDispose = function(){ thisComponent.off(target, type, fn); }; // Use the same function ID so we can remove it later it using the ID // of the original listener removeOnDispose.guid = fn.guid; this.on('dispose', removeOnDispose); // If the other component is disposed first we need to clean the reference // to the other component in this component's removeOnDispose listener // Otherwise we create a memory leak. cleanRemover = function(){ thisComponent.off('dispose', removeOnDispose); }; // Add the same function ID so we can easily remove it later cleanRemover.guid = fn.guid; // Check if this is a DOM node if (first.nodeName) { // Add the listener to the other element vjs.on(target, type, fn); vjs.on(target, 'dispose', cleanRemover); // Should be a component // Not using `instanceof vjs.Component` because it makes mock players difficult } else if (typeof first.on === 'function') { // Add the listener to the other component target.on(type, fn); target.on('dispose', cleanRemover); } } return this; }; /** * Remove an event listener from this component's element * * myComponent.off('eventType', myFunc); * * If myFunc is excluded, ALL listeners for the event type will be removed. * If eventType is excluded, ALL listeners will be removed from the component. * * Alternatively you can use `off` to remove listeners that were added to other * elements or components using `myComponent.on(otherComponent...`. * In this case both the event type and listener function are REQUIRED. * * myComponent.off(otherElement, 'eventType', myFunc); * myComponent.off(otherComponent, 'eventType', myFunc); * * @param {String=|vjs.Component} first The event type or other component * @param {Function=|String} second The listener function or event type * @param {Function=} third The listener for other component * @return {vjs.Component} */ vjs.Component.prototype.off = function(first, second, third){ var target, otherComponent, type, fn, otherEl; if (!first || typeof first === 'string' || vjs.obj.isArray(first)) { vjs.off(this.el_, first, second); } else { target = first; type = second; // Ensure there's at least a guid, even if the function hasn't been used fn = vjs.bind(this, third); // Remove the dispose listener on this component, // which was given the same guid as the event listener this.off('dispose', fn); if (first.nodeName) { // Remove the listener vjs.off(target, type, fn); // Remove the listener for cleaning the dispose listener vjs.off(target, 'dispose', fn); } else { target.off(type, fn); target.off('dispose', fn); } } return this; }; /** * Add an event listener to be triggered only once and then removed * * myComponent.one('eventName', myFunc); * * Alternatively you can add a listener to another element or component * that will be triggered only once. * * myComponent.one(otherElement, 'eventName', myFunc); * myComponent.one(otherComponent, 'eventName', myFunc); * * @param {String|vjs.Component} first The event type or other component * @param {Function|String} second The listener function or event type * @param {Function=} third The listener function for other component * @return {vjs.Component} */ vjs.Component.prototype.one = function(first, second, third) { var target, type, fn, thisComponent, newFunc; if (typeof first === 'string' || vjs.obj.isArray(first)) { vjs.one(this.el_, first, vjs.bind(this, second)); } else { target = first; type = second; fn = vjs.bind(this, third); thisComponent = this; newFunc = function(){ thisComponent.off(target, type, newFunc); fn.apply(this, arguments); }; // Keep the same function ID so we can remove it later newFunc.guid = fn.guid; this.on(target, type, newFunc); } return this; }; /** * Trigger an event on an element * * myComponent.trigger('eventName'); * myComponent.trigger({'type':'eventName'}); * * @param {Event|Object|String} event A string (the type) or an event object with a type attribute * @return {vjs.Component} self */ vjs.Component.prototype.trigger = function(event){ vjs.trigger(this.el_, event); return this; }; /* Ready ================================================================================ */ /** * Is the component loaded * This can mean different things depending on the component. * * @private * @type {Boolean} */ vjs.Component.prototype.isReady_; /** * Trigger ready as soon as initialization is finished * * Allows for delaying ready. Override on a sub class prototype. * If you set this.isReadyOnInitFinish_ it will affect all components. * Specially used when waiting for the Flash player to asynchronously load. * * @type {Boolean} * @private */ vjs.Component.prototype.isReadyOnInitFinish_ = true; /** * List of ready listeners * * @type {Array} * @private */ vjs.Component.prototype.readyQueue_; /** * Bind a listener to the component's ready state * * Different from event listeners in that if the ready event has already happened * it will trigger the function immediately. * * @param {Function} fn Ready listener * @return {vjs.Component} */ vjs.Component.prototype.ready = function(fn){ if (fn) { if (this.isReady_) { fn.call(this); } else { if (this.readyQueue_ === undefined) { this.readyQueue_ = []; } this.readyQueue_.push(fn); } } return this; }; /** * Trigger the ready listeners * * @return {vjs.Component} */ vjs.Component.prototype.triggerReady = function(){ this.isReady_ = true; var readyQueue = this.readyQueue_; if (readyQueue && readyQueue.length > 0) { for (var i = 0, j = readyQueue.length; i < j; i++) { readyQueue[i].call(this); } // Reset Ready Queue this.readyQueue_ = []; // Allow for using event listeners also, in case you want to do something everytime a source is ready. this.trigger('ready'); } }; /* Display ============================================================================= */ /** * Check if a component's element has a CSS class name * * @param {String} classToCheck Classname to check * @return {vjs.Component} */ vjs.Component.prototype.hasClass = function(classToCheck){ return vjs.hasClass(this.el_, classToCheck); }; /** * Add a CSS class name to the component's element * * @param {String} classToAdd Classname to add * @return {vjs.Component} */ vjs.Component.prototype.addClass = function(classToAdd){ vjs.addClass(this.el_, classToAdd); return this; }; /** * Remove a CSS class name from the component's element * * @param {String} classToRemove Classname to remove * @return {vjs.Component} */ vjs.Component.prototype.removeClass = function(classToRemove){ vjs.removeClass(this.el_, classToRemove); return this; }; /** * Show the component element if hidden * * @return {vjs.Component} */ vjs.Component.prototype.show = function(){ this.el_.style.display = 'block'; return this; }; /** * Hide the component element if currently showing * * @return {vjs.Component} */ vjs.Component.prototype.hide = function(){ this.el_.style.display = 'none'; return this; }; /** * Lock an item in its visible state * To be used with fadeIn/fadeOut. * * @return {vjs.Component} * @private */ vjs.Component.prototype.lockShowing = function(){ this.addClass('vjs-lock-showing'); return this; }; /** * Unlock an item to be hidden * To be used with fadeIn/fadeOut. * * @return {vjs.Component} * @private */ vjs.Component.prototype.unlockShowing = function(){ this.removeClass('vjs-lock-showing'); return this; }; /** * Disable component by making it unshowable * * Currently private because we're moving towards more css-based states. * @private */ vjs.Component.prototype.disable = function(){ this.hide(); this.show = function(){}; }; /** * Set or get the width of the component (CSS values) * * Setting the video tag dimension values only works with values in pixels. * Percent values will not work. * Some percents can be used, but width()/height() will return the number + %, * not the actual computed width/height. * * @param {Number|String=} num Optional width number * @param {Boolean} skipListeners Skip the 'resize' event trigger * @return {vjs.Component} This component, when setting the width * @return {Number|String} The width, when getting */ vjs.Component.prototype.width = function(num, skipListeners){ return this.dimension('width', num, skipListeners); }; /** * Get or set the height of the component (CSS values) * * Setting the video tag dimension values only works with values in pixels. * Percent values will not work. * Some percents can be used, but width()/height() will return the number + %, * not the actual computed width/height. * * @param {Number|String=} num New component height * @param {Boolean=} skipListeners Skip the resize event trigger * @return {vjs.Component} This component, when setting the height * @return {Number|String} The height, when getting */ vjs.Component.prototype.height = function(num, skipListeners){ return this.dimension('height', num, skipListeners); }; /** * Set both width and height at the same time * * @param {Number|String} width * @param {Number|String} height * @return {vjs.Component} The component */ vjs.Component.prototype.dimensions = function(width, height){ // Skip resize listeners on width for optimization return this.width(width, true).height(height); }; /** * Get or set width or height * * This is the shared code for the width() and height() methods. * All for an integer, integer + 'px' or integer + '%'; * * Known issue: Hidden elements officially have a width of 0. We're defaulting * to the style.width value and falling back to computedStyle which has the * hidden element issue. Info, but probably not an efficient fix: * http://www.foliotek.com/devblog/getting-the-width-of-a-hidden-element-with-jquery-using-width/ * * @param {String} widthOrHeight 'width' or 'height' * @param {Number|String=} num New dimension * @param {Boolean=} skipListeners Skip resize event trigger * @return {vjs.Component} The component if a dimension was set * @return {Number|String} The dimension if nothing was set * @private */ vjs.Component.prototype.dimension = function(widthOrHeight, num, skipListeners){ if (num !== undefined) { if (num === null || vjs.isNaN(num)) { num = 0; } // Check if using css width/height (% or px) and adjust if ((''+num).indexOf('%') !== -1 || (''+num).indexOf('px') !== -1) { this.el_.style[widthOrHeight] = num; } else if (num === 'auto') { this.el_.style[widthOrHeight] = ''; } else { this.el_.style[widthOrHeight] = num+'px'; } // skipListeners allows us to avoid triggering the resize event when setting both width and height if (!skipListeners) { this.trigger('resize'); } // Return component return this; } // Not setting a value, so getting it // Make sure element exists if (!this.el_) return 0; // Get dimension value from style var val = this.el_.style[widthOrHeight]; var pxIndex = val.indexOf('px'); if (pxIndex !== -1) { // Return the pixel value with no 'px' return parseInt(val.slice(0,pxIndex), 10); // No px so using % or no style was set, so falling back to offsetWidth/height // If component has display:none, offset will return 0 // TODO: handle display:none and no dimension style using px } else { return parseInt(this.el_['offset'+vjs.capitalize(widthOrHeight)], 10); // ComputedStyle version. // Only difference is if the element is hidden it will return // the percent value (e.g. '100%'') // instead of zero like offsetWidth returns. // var val = vjs.getComputedStyleValue(this.el_, widthOrHeight); // var pxIndex = val.indexOf('px'); // if (pxIndex !== -1) { // return val.slice(0, pxIndex); // } else { // return val; // } } }; /** * Fired when the width and/or height of the component changes * @event resize */ vjs.Component.prototype.onResize; /** * Emit 'tap' events when touch events are supported * * This is used to support toggling the controls through a tap on the video. * * We're requiring them to be enabled because otherwise every component would * have this extra overhead unnecessarily, on mobile devices where extra * overhead is especially bad. * @private */ vjs.Component.prototype.emitTapEvents = function(){ var touchStart, firstTouch, touchTime, couldBeTap, noTap, xdiff, ydiff, touchDistance, tapMovementThreshold; // Track the start time so we can determine how long the touch lasted touchStart = 0; firstTouch = null; // Maximum movement allowed during a touch event to still be considered a tap tapMovementThreshold = 22; this.on('touchstart', function(event) { // If more than one finger, don't consider treating this as a click if (event.touches.length === 1) { firstTouch = event.touches[0]; // Record start time so we can detect a tap vs. "touch and hold" touchStart = new Date().getTime(); // Reset couldBeTap tracking couldBeTap = true; } }); this.on('touchmove', function(event) { // If more than one finger, don't consider treating this as a click if (event.touches.length > 1) { couldBeTap = false; } else if (firstTouch) { // Some devices will throw touchmoves for all but the slightest of taps. // So, if we moved only a small distance, this could still be a tap xdiff = event.touches[0].pageX - firstTouch.pageX; ydiff = event.touches[0].pageY - firstTouch.pageY; touchDistance = Math.sqrt(xdiff * xdiff + ydiff * ydiff); if (touchDistance > tapMovementThreshold) { couldBeTap = false; } } }); noTap = function(){ couldBeTap = false; }; // TODO: Listen to the original target. http://youtu.be/DujfpXOKUp8?t=13m8s this.on('touchleave', noTap); this.on('touchcancel', noTap); // When the touch ends, measure how long it took and trigger the appropriate // event this.on('touchend', function(event) { firstTouch = null; // Proceed only if the touchmove/leave/cancel event didn't happen if (couldBeTap === true) { // Measure how long the touch lasted touchTime = new Date().getTime() - touchStart; // The touch needs to be quick in order to consider it a tap if (touchTime < 250) { event.preventDefault(); // Don't let browser turn this into a click this.trigger('tap'); // It may be good to copy the touchend event object and change the // type to tap, if the other event properties aren't exact after // vjs.fixEvent runs (e.g. event.target) } } }); }; /** * Report user touch activity when touch events occur * * User activity is used to determine when controls should show/hide. It's * relatively simple when it comes to mouse events, because any mouse event * should show the controls. So we capture mouse events that bubble up to the * player and report activity when that happens. * * With touch events it isn't as easy. We can't rely on touch events at the * player level, because a tap (touchstart + touchend) on the video itself on * mobile devices is meant to turn controls off (and on). User activity is * checked asynchronously, so what could happen is a tap event on the video * turns the controls off, then the touchend event bubbles up to the player, * which if it reported user activity, would turn the controls right back on. * (We also don't want to completely block touch events from bubbling up) * * Also a touchmove, touch+hold, and anything other than a tap is not supposed * to turn the controls back on on a mobile device. * * Here we're setting the default component behavior to report user activity * whenever touch events happen, and this can be turned off by components that * want touch events to act differently. */ vjs.Component.prototype.enableTouchActivity = function() { var report, touchHolding, touchEnd; // Don't continue if the root player doesn't support reporting user activity if (!this.player().reportUserActivity) { return; } // listener for reporting that the user is active report = vjs.bind(this.player(), this.player().reportUserActivity); this.on('touchstart', function() { report(); // For as long as the they are touching the device or have their mouse down, // we consider them active even if they're not moving their finger or mouse. // So we want to continue to update that they are active this.clearInterval(touchHolding); // report at the same interval as activityCheck touchHolding = this.setInterval(report, 250); }); touchEnd = function(event) { report(); // stop the interval that maintains activity if the touch is holding this.clearInterval(touchHolding); }; this.on('touchmove', report); this.on('touchend', touchEnd); this.on('touchcancel', touchEnd); }; /** * Creates timeout and sets up disposal automatically. * @param {Function} fn The function to run after the timeout. * @param {Number} timeout Number of ms to delay before executing specified function. * @return {Number} Returns the timeout ID */ vjs.Component.prototype.setTimeout = function(fn, timeout) { fn = vjs.bind(this, fn); // window.setTimeout would be preferable here, but due to some bizarre issue with Sinon and/or Phantomjs, we can't. var timeoutId = setTimeout(fn, timeout); var disposeFn = function() { this.clearTimeout(timeoutId); }; disposeFn.guid = 'vjs-timeout-'+ timeoutId; this.on('dispose', disposeFn); return timeoutId; }; /** * Clears a timeout and removes the associated dispose listener * @param {Number} timeoutId The id of the timeout to clear * @return {Number} Returns the timeout ID */ vjs.Component.prototype.clearTimeout = function(timeoutId) { clearTimeout(timeoutId); var disposeFn = function(){}; disposeFn.guid = 'vjs-timeout-'+ timeoutId; this.off('dispose', disposeFn); return timeoutId; }; /** * Creates an interval and sets up disposal automatically. * @param {Function} fn The function to run every N seconds. * @param {Number} interval Number of ms to delay before executing specified function. * @return {Number} Returns the interval ID */ vjs.Component.prototype.setInterval = function(fn, interval) { fn = vjs.bind(this, fn); var intervalId = setInterval(fn, interval); var disposeFn = function() { this.clearInterval(intervalId); }; disposeFn.guid = 'vjs-interval-'+ intervalId; this.on('dispose', disposeFn); return intervalId; }; /** * Clears an interval and removes the associated dispose listener * @param {Number} intervalId The id of the interval to clear * @return {Number} Returns the interval ID */ vjs.Component.prototype.clearInterval = function(intervalId) { clearInterval(intervalId); var disposeFn = function(){}; disposeFn.guid = 'vjs-interval-'+ intervalId; this.off('dispose', disposeFn); return intervalId; }; /* Button - Base class for all buttons ================================================================================ */ /** * Base class for all buttons * @param {vjs.Player|Object} player * @param {Object=} options * @class * @constructor */ vjs.Button = vjs.Component.extend({ /** * @constructor * @inheritDoc */ init: function(player, options){ vjs.Component.call(this, player, options); this.emitTapEvents(); this.on('tap', this.onClick); this.on('click', this.onClick); this.on('focus', this.onFocus); this.on('blur', this.onBlur); } }); vjs.Button.prototype.createEl = function(type, props){ var el; // Add standard Aria and Tabindex info props = vjs.obj.merge({ className: this.buildCSSClass(), 'role': 'button', 'aria-live': 'polite', // let the screen reader user know that the text of the button may change tabIndex: 0 }, props); el = vjs.Component.prototype.createEl.call(this, type, props); // if innerHTML hasn't been overridden (bigPlayButton), add content elements if (!props.innerHTML) { this.contentEl_ = vjs.createEl('div', { className: 'vjs-control-content' }); this.controlText_ = vjs.createEl('span', { className: 'vjs-control-text', innerHTML: this.localize(this.buttonText) || 'Need Text' }); this.contentEl_.appendChild(this.controlText_); el.appendChild(this.contentEl_); } return el; }; vjs.Button.prototype.buildCSSClass = function(){ // TODO: Change vjs-control to vjs-button? return 'vjs-control ' + vjs.Component.prototype.buildCSSClass.call(this); }; // Click - Override with specific functionality for button vjs.Button.prototype.onClick = function(){}; // Focus - Add keyboard functionality to element vjs.Button.prototype.onFocus = function(){ vjs.on(document, 'keydown', vjs.bind(this, this.onKeyPress)); }; // KeyPress (document level) - Trigger click when keys are pressed vjs.Button.prototype.onKeyPress = function(event){ // Check for space bar (32) or enter (13) keys if (event.which == 32 || event.which == 13) { event.preventDefault(); this.onClick(); } }; // Blur - Remove keyboard triggers vjs.Button.prototype.onBlur = function(){ vjs.off(document, 'keydown', vjs.bind(this, this.onKeyPress)); }; /* Slider ================================================================================ */ /** * The base functionality for sliders like the volume bar and seek bar * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.Slider = vjs.Component.extend({ /** @constructor */ init: function(player, options){ vjs.Component.call(this, player, options); // Set property names to bar and handle to match with the child Slider class is looking for this.bar = this.getChild(this.options_['barName']); this.handle = this.getChild(this.options_['handleName']); this.on('mousedown', this.onMouseDown); this.on('touchstart', this.onMouseDown); this.on('focus', this.onFocus); this.on('blur', this.onBlur); this.on('click', this.onClick); this.on(player, 'controlsvisible', this.update); this.on(player, this.playerEvent, this.update); } }); vjs.Slider.prototype.createEl = function(type, props) { props = props || {}; // Add the slider element class to all sub classes props.className = props.className + ' vjs-slider'; props = vjs.obj.merge({ 'role': 'slider', 'aria-valuenow': 0, 'aria-valuemin': 0, 'aria-valuemax': 100, tabIndex: 0 }, props); return vjs.Component.prototype.createEl.call(this, type, props); }; vjs.Slider.prototype.onMouseDown = function(event){ event.preventDefault(); vjs.blockTextSelection(); this.addClass('vjs-sliding'); this.on(document, 'mousemove', this.onMouseMove); this.on(document, 'mouseup', this.onMouseUp); this.on(document, 'touchmove', this.onMouseMove); this.on(document, 'touchend', this.onMouseUp); this.onMouseMove(event); }; // To be overridden by a subclass vjs.Slider.prototype.onMouseMove = function(){}; vjs.Slider.prototype.onMouseUp = function() { vjs.unblockTextSelection(); this.removeClass('vjs-sliding'); this.off(document, 'mousemove', this.onMouseMove); this.off(document, 'mouseup', this.onMouseUp); this.off(document, 'touchmove', this.onMouseMove); this.off(document, 'touchend', this.onMouseUp); this.update(); }; vjs.Slider.prototype.update = function(){ // In VolumeBar init we have a setTimeout for update that pops and update to the end of the // execution stack. The player is destroyed before then update will cause an error if (!this.el_) return; // If scrubbing, we could use a cached value to make the handle keep up with the user's mouse. // On HTML5 browsers scrubbing is really smooth, but some flash players are slow, so we might want to utilize this later. // var progress = (this.player_.scrubbing) ? this.player_.getCache().currentTime / this.player_.duration() : this.player_.currentTime() / this.player_.duration(); var barProgress, progress = this.getPercent(), handle = this.handle, bar = this.bar; // Protect against no duration and other division issues if (isNaN(progress)) { progress = 0; } barProgress = progress; // If there is a handle, we need to account for the handle in our calculation for progress bar // so that it doesn't fall short of or extend past the handle. if (handle) { var box = this.el_, boxWidth = box.offsetWidth, handleWidth = handle.el().offsetWidth, // The width of the handle in percent of the containing box // In IE, widths may not be ready yet causing NaN handlePercent = (handleWidth) ? handleWidth / boxWidth : 0, // Get the adjusted size of the box, considering that the handle's center never touches the left or right side. // There is a margin of half the handle's width on both sides. boxAdjustedPercent = 1 - handlePercent, // Adjust the progress that we'll use to set widths to the new adjusted box width adjustedProgress = progress * boxAdjustedPercent; // The bar does reach the left side, so we need to account for this in the bar's width barProgress = adjustedProgress + (handlePercent / 2); // Move the handle from the left based on the adjected progress handle.el().style.left = vjs.round(adjustedProgress * 100, 2) + '%'; } // Set the new bar width if (bar) { bar.el().style.width = vjs.round(barProgress * 100, 2) + '%'; } }; vjs.Slider.prototype.calculateDistance = function(event){ var el, box, boxX, boxY, boxW, boxH, handle, pageX, pageY; el = this.el_; box = vjs.findPosition(el); boxW = boxH = el.offsetWidth; handle = this.handle; if (this.options()['vertical']) { boxY = box.top; if (event.changedTouches) { pageY = event.changedTouches[0].pageY; } else { pageY = event.pageY; } if (handle) { var handleH = handle.el().offsetHeight; // Adjusted X and Width, so handle doesn't go outside the bar boxY = boxY + (handleH / 2); boxH = boxH - handleH; } // Percent that the click is through the adjusted area return Math.max(0, Math.min(1, ((boxY - pageY) + boxH) / boxH)); } else { boxX = box.left; if (event.changedTouches) { pageX = event.changedTouches[0].pageX; } else { pageX = event.pageX; } if (handle) { var handleW = handle.el().offsetWidth; // Adjusted X and Width, so handle doesn't go outside the bar boxX = boxX + (handleW / 2); boxW = boxW - handleW; } // Percent that the click is through the adjusted area return Math.max(0, Math.min(1, (pageX - boxX) / boxW)); } }; vjs.Slider.prototype.onFocus = function(){ this.on(document, 'keydown', this.onKeyPress); }; vjs.Slider.prototype.onKeyPress = function(event){ if (event.which == 37 || event.which == 40) { // Left and Down Arrows event.preventDefault(); this.stepBack(); } else if (event.which == 38 || event.which == 39) { // Up and Right Arrows event.preventDefault(); this.stepForward(); } }; vjs.Slider.prototype.onBlur = function(){ this.off(document, 'keydown', this.onKeyPress); }; /** * Listener for click events on slider, used to prevent clicks * from bubbling up to parent elements like button menus. * @param {Object} event Event object */ vjs.Slider.prototype.onClick = function(event){ event.stopImmediatePropagation(); event.preventDefault(); }; /** * SeekBar Behavior includes play progress bar, and seek handle * Needed so it can determine seek position based on handle position/size * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.SliderHandle = vjs.Component.extend(); /** * Default value of the slider * * @type {Number} * @private */ vjs.SliderHandle.prototype.defaultValue = 0; /** @inheritDoc */ vjs.SliderHandle.prototype.createEl = function(type, props) { props = props || {}; // Add the slider element class to all sub classes props.className = props.className + ' vjs-slider-handle'; props = vjs.obj.merge({ innerHTML: '<span class="vjs-control-text">'+this.defaultValue+'</span>' }, props); return vjs.Component.prototype.createEl.call(this, 'div', props); }; /* Menu ================================================================================ */ /** * The Menu component is used to build pop up menus, including subtitle and * captions selection menus. * * @param {vjs.Player|Object} player * @param {Object=} options * @class * @constructor */ vjs.Menu = vjs.Component.extend(); /** * Add a menu item to the menu * @param {Object|String} component Component or component type to add */ vjs.Menu.prototype.addItem = function(component){ this.addChild(component); component.on('click', vjs.bind(this, function(){ this.unlockShowing(); })); }; /** @inheritDoc */ vjs.Menu.prototype.createEl = function(){ var contentElType = this.options().contentElType || 'ul'; this.contentEl_ = vjs.createEl(contentElType, { className: 'vjs-menu-content' }); var el = vjs.Component.prototype.createEl.call(this, 'div', { append: this.contentEl_, className: 'vjs-menu' }); el.appendChild(this.contentEl_); // Prevent clicks from bubbling up. Needed for Menu Buttons, // where a click on the parent is significant vjs.on(el, 'click', function(event){ event.preventDefault(); event.stopImmediatePropagation(); }); return el; }; /** * The component for a menu item. `<li>` * * @param {vjs.Player|Object} player * @param {Object=} options * @class * @constructor */ vjs.MenuItem = vjs.Button.extend({ /** @constructor */ init: function(player, options){ vjs.Button.call(this, player, options); this.selected(options['selected']); } }); /** @inheritDoc */ vjs.MenuItem.prototype.createEl = function(type, props){ return vjs.Button.prototype.createEl.call(this, 'li', vjs.obj.merge({ className: 'vjs-menu-item', innerHTML: this.localize(this.options_['label']) }, props)); }; /** * Handle a click on the menu item, and set it to selected */ vjs.MenuItem.prototype.onClick = function(){ this.selected(true); }; /** * Set this menu item as selected or not * @param {Boolean} selected */ vjs.MenuItem.prototype.selected = function(selected){ if (selected) { this.addClass('vjs-selected'); this.el_.setAttribute('aria-selected',true); } else { this.removeClass('vjs-selected'); this.el_.setAttribute('aria-selected',false); } }; /** * A button class with a popup menu * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.MenuButton = vjs.Button.extend({ /** @constructor */ init: function(player, options){ vjs.Button.call(this, player, options); this.menu = this.createMenu(); // Add list to element this.addChild(this.menu); // Automatically hide empty menu buttons if (this.items && this.items.length === 0) { this.hide(); } this.on('keydown', this.onKeyPress); this.el_.setAttribute('aria-haspopup', true); this.el_.setAttribute('role', 'button'); } }); /** * Track the state of the menu button * @type {Boolean} * @private */ vjs.MenuButton.prototype.buttonPressed_ = false; vjs.MenuButton.prototype.createMenu = function(){ var menu = new vjs.Menu(this.player_); // Add a title list item to the top if (this.options().title) { menu.contentEl().appendChild(vjs.createEl('li', { className: 'vjs-menu-title', innerHTML: vjs.capitalize(this.options().title), tabindex: -1 })); } this.items = this['createItems'](); if (this.items) { // Add menu items to the menu for (var i = 0; i < this.items.length; i++) { menu.addItem(this.items[i]); } } return menu; }; /** * Create the list of menu items. Specific to each subclass. */ vjs.MenuButton.prototype.createItems = function(){}; /** @inheritDoc */ vjs.MenuButton.prototype.buildCSSClass = function(){ return this.className + ' vjs-menu-button ' + vjs.Button.prototype.buildCSSClass.call(this); }; // Focus - Add keyboard functionality to element // This function is not needed anymore. Instead, the keyboard functionality is handled by // treating the button as triggering a submenu. When the button is pressed, the submenu // appears. Pressing the button again makes the submenu disappear. vjs.MenuButton.prototype.onFocus = function(){}; // Can't turn off list display that we turned on with focus, because list would go away. vjs.MenuButton.prototype.onBlur = function(){}; vjs.MenuButton.prototype.onClick = function(){ // When you click the button it adds focus, which will show the menu indefinitely. // So we'll remove focus when the mouse leaves the button. // Focus is needed for tab navigation. this.one('mouseout', vjs.bind(this, function(){ this.menu.unlockShowing(); this.el_.blur(); })); if (this.buttonPressed_){ this.unpressButton(); } else { this.pressButton(); } }; vjs.MenuButton.prototype.onKeyPress = function(event){ // Check for space bar (32) or enter (13) keys if (event.which == 32 || event.which == 13) { if (this.buttonPressed_){ this.unpressButton(); } else { this.pressButton(); } event.preventDefault(); // Check for escape (27) key } else if (event.which == 27){ if (this.buttonPressed_){ this.unpressButton(); } event.preventDefault(); } }; vjs.MenuButton.prototype.pressButton = function(){ this.buttonPressed_ = true; this.menu.lockShowing(); this.el_.setAttribute('aria-pressed', true); if (this.items && this.items.length > 0) { this.items[0].el().focus(); // set the focus to the title of the submenu } }; vjs.MenuButton.prototype.unpressButton = function(){ this.buttonPressed_ = false; this.menu.unlockShowing(); this.el_.setAttribute('aria-pressed', false); }; /** * Custom MediaError to mimic the HTML5 MediaError * @param {Number} code The media error code */ vjs.MediaError = function(code){ if (typeof code === 'number') { this.code = code; } else if (typeof code === 'string') { // default code is zero, so this is a custom error this.message = code; } else if (typeof code === 'object') { // object vjs.obj.merge(this, code); } if (!this.message) { this.message = vjs.MediaError.defaultMessages[this.code] || ''; } }; /** * The error code that refers two one of the defined * MediaError types * @type {Number} */ vjs.MediaError.prototype.code = 0; /** * An optional message to be shown with the error. * Message is not part of the HTML5 video spec * but allows for more informative custom errors. * @type {String} */ vjs.MediaError.prototype.message = ''; /** * An optional status code that can be set by plugins * to allow even more detail about the error. * For example the HLS plugin might provide the specific * HTTP status code that was returned when the error * occurred, then allowing a custom error overlay * to display more information. * @type {[type]} */ vjs.MediaError.prototype.status = null; vjs.MediaError.errorTypes = [ 'MEDIA_ERR_CUSTOM', // = 0 'MEDIA_ERR_ABORTED', // = 1 'MEDIA_ERR_NETWORK', // = 2 'MEDIA_ERR_DECODE', // = 3 'MEDIA_ERR_SRC_NOT_SUPPORTED', // = 4 'MEDIA_ERR_ENCRYPTED' // = 5 ]; vjs.MediaError.defaultMessages = { 1: 'You aborted the video playback', 2: 'A network error caused the video download to fail part-way.', 3: 'The video playback was aborted due to a corruption problem or because the video used features your browser did not support.', 4: 'The video could not be loaded, either because the server or network failed or because the format is not supported.', 5: 'The video is encrypted and we do not have the keys to decrypt it.' }; // Add types as properties on MediaError // e.g. MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED = 4; for (var errNum = 0; errNum < vjs.MediaError.errorTypes.length; errNum++) { vjs.MediaError[vjs.MediaError.errorTypes[errNum]] = errNum; // values should be accessible on both the class and instance vjs.MediaError.prototype[vjs.MediaError.errorTypes[errNum]] = errNum; } (function(){ var apiMap, specApi, browserApi, i; /** * Store the browser-specific methods for the fullscreen API * @type {Object|undefined} * @private */ vjs.browser.fullscreenAPI; // browser API methods // map approach from Screenful.js - https://github.com/sindresorhus/screenfull.js apiMap = [ // Spec: https://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html [ 'requestFullscreen', 'exitFullscreen', 'fullscreenElement', 'fullscreenEnabled', 'fullscreenchange', 'fullscreenerror' ], // WebKit [ 'webkitRequestFullscreen', 'webkitExitFullscreen', 'webkitFullscreenElement', 'webkitFullscreenEnabled', 'webkitfullscreenchange', 'webkitfullscreenerror' ], // Old WebKit (Safari 5.1) [ 'webkitRequestFullScreen', 'webkitCancelFullScreen', 'webkitCurrentFullScreenElement', 'webkitCancelFullScreen', 'webkitfullscreenchange', 'webkitfullscreenerror' ], // Mozilla [ 'mozRequestFullScreen', 'mozCancelFullScreen', 'mozFullScreenElement', 'mozFullScreenEnabled', 'mozfullscreenchange', 'mozfullscreenerror' ], // Microsoft [ 'msRequestFullscreen', 'msExitFullscreen', 'msFullscreenElement', 'msFullscreenEnabled', 'MSFullscreenChange', 'MSFullscreenError' ] ]; specApi = apiMap[0]; // determine the supported set of functions for (i=0; i<apiMap.length; i++) { // check for exitFullscreen function if (apiMap[i][1] in document) { browserApi = apiMap[i]; break; } } // map the browser API names to the spec API names // or leave vjs.browser.fullscreenAPI undefined if (browserApi) { vjs.browser.fullscreenAPI = {}; for (i=0; i<browserApi.length; i++) { vjs.browser.fullscreenAPI[specApi[i]] = browserApi[i]; } } })(); /** * An instance of the `vjs.Player` class is created when any of the Video.js setup methods are used to initialize a video. * * ```js * var myPlayer = videojs('example_video_1'); * ``` * * In the following example, the `data-setup` attribute tells the Video.js library to create a player instance when the library is ready. * * ```html * <video id="example_video_1" data-setup='{}' controls> * <source src="my-source.mp4" type="video/mp4"> * </video> * ``` * * After an instance has been created it can be accessed globally using `Video('example_video_1')`. * * @class * @extends vjs.Component */ vjs.Player = vjs.Component.extend({ /** * player's constructor function * * @constructs * @method init * @param {Element} tag The original video tag used for configuring options * @param {Object=} options Player options * @param {Function=} ready Ready callback function */ init: function(tag, options, ready){ this.tag = tag; // Store the original tag used to set options // Make sure tag ID exists tag.id = tag.id || 'vjs_video_' + vjs.guid++; // Store the tag attributes used to restore html5 element this.tagAttributes = tag && vjs.getElementAttributes(tag); // Set Options // The options argument overrides options set in the video tag // which overrides globally set options. // This latter part coincides with the load order // (tag must exist before Player) options = vjs.obj.merge(this.getTagSettings(tag), options); // Update Current Language this.language_ = options['language'] || vjs.options['language']; // Update Supported Languages this.languages_ = options['languages'] || vjs.options['languages']; // Cache for video property values. this.cache_ = {}; // Set poster this.poster_ = options['poster'] || ''; // Set controls this.controls_ = !!options['controls']; // Original tag settings stored in options // now remove immediately so native controls don't flash. // May be turned back on by HTML5 tech if nativeControlsForTouch is true tag.controls = false; // we don't want the player to report touch activity on itself // see enableTouchActivity in Component options.reportTouchActivity = false; // Set isAudio based on whether or not an audio tag was used this.isAudio(this.tag.nodeName.toLowerCase() === 'audio'); // Run base component initializing with new options. // Builds the element through createEl() // Inits and embeds any child components in opts vjs.Component.call(this, this, options, ready); // Update controls className. Can't do this when the controls are initially // set because the element doesn't exist yet. if (this.controls()) { this.addClass('vjs-controls-enabled'); } else { this.addClass('vjs-controls-disabled'); } if (this.isAudio()) { this.addClass('vjs-audio'); } // TODO: Make this smarter. Toggle user state between touching/mousing // using events, since devices can have both touch and mouse events. // if (vjs.TOUCH_ENABLED) { // this.addClass('vjs-touch-enabled'); // } // Make player easily findable by ID vjs.players[this.id_] = this; if (options['plugins']) { vjs.obj.each(options['plugins'], function(key, val){ this[key](val); }, this); } this.listenForUserActivity(); } }); /** * The player's stored language code * * @type {String} * @private */ vjs.Player.prototype.language_; /** * The player's language code * @param {String} languageCode The locale string * @return {String} The locale string when getting * @return {vjs.Player} self, when setting */ vjs.Player.prototype.language = function (languageCode) { if (languageCode === undefined) { return this.language_; } this.language_ = languageCode; return this; }; /** * The player's stored language dictionary * * @type {Object} * @private */ vjs.Player.prototype.languages_; vjs.Player.prototype.languages = function(){ return this.languages_; }; /** * Player instance options, surfaced using vjs.options * vjs.options = vjs.Player.prototype.options_ * Make changes in vjs.options, not here. * All options should use string keys so they avoid * renaming by closure compiler * @type {Object} * @private */ vjs.Player.prototype.options_ = vjs.options; /** * Destroys the video player and does any necessary cleanup * * myPlayer.dispose(); * * This is especially helpful if you are dynamically adding and removing videos * to/from the DOM. */ vjs.Player.prototype.dispose = function(){ this.trigger('dispose'); // prevent dispose from being called twice this.off('dispose'); // Kill reference to this player vjs.players[this.id_] = null; if (this.tag && this.tag['player']) { this.tag['player'] = null; } if (this.el_ && this.el_['player']) { this.el_['player'] = null; } if (this.tech) { this.tech.dispose(); } // Component dispose vjs.Component.prototype.dispose.call(this); }; vjs.Player.prototype.getTagSettings = function(tag){ var tagOptions, dataSetup, options = { 'sources': [], 'tracks': [] }; tagOptions = vjs.getElementAttributes(tag); dataSetup = tagOptions['data-setup']; // Check if data-setup attr exists. if (dataSetup !== null){ // Parse options JSON // If empty string, make it a parsable json object. vjs.obj.merge(tagOptions, vjs.JSON.parse(dataSetup || '{}')); } vjs.obj.merge(options, tagOptions); // Get tag children settings if (tag.hasChildNodes()) { var children, child, childName, i, j; children = tag.childNodes; for (i=0,j=children.length; i<j; i++) { child = children[i]; // Change case needed: http://ejohn.org/blog/nodename-case-sensitivity/ childName = child.nodeName.toLowerCase(); if (childName === 'source') { options['sources'].push(vjs.getElementAttributes(child)); } else if (childName === 'track') { options['tracks'].push(vjs.getElementAttributes(child)); } } } return options; }; vjs.Player.prototype.createEl = function(){ var el = this.el_ = vjs.Component.prototype.createEl.call(this, 'div'), tag = this.tag, attrs; // Remove width/height attrs from tag so CSS can make it 100% width/height tag.removeAttribute('width'); tag.removeAttribute('height'); // Empty video tag tracks so the built-in player doesn't use them also. // This may not be fast enough to stop HTML5 browsers from reading the tags // so we'll need to turn off any default tracks if we're manually doing // captions and subtitles. videoElement.textTracks if (tag.hasChildNodes()) { var nodes, nodesLength, i, node, nodeName, removeNodes; nodes = tag.childNodes; nodesLength = nodes.length; removeNodes = []; while (nodesLength--) { node = nodes[nodesLength]; nodeName = node.nodeName.toLowerCase(); if (nodeName === 'track') { removeNodes.push(node); } } for (i=0; i<removeNodes.length; i++) { tag.removeChild(removeNodes[i]); } } // Copy over all the attributes from the tag, including ID and class // ID will now reference player box, not the video tag attrs = vjs.getElementAttributes(tag); vjs.obj.each(attrs, function(attr) { // workaround so we don't totally break IE7 // http://stackoverflow.com/questions/3653444/css-styles-not-applied-on-dynamic-elements-in-internet-explorer-7 if (attr == 'class') { el.className = attrs[attr]; } else { el.setAttribute(attr, attrs[attr]); } }); // Update tag id/class for use as HTML5 playback tech // Might think we should do this after embedding in container so .vjs-tech class // doesn't flash 100% width/height, but class only applies with .video-js parent tag.id += '_html5_api'; tag.className = 'vjs-tech'; // Make player findable on elements tag['player'] = el['player'] = this; // Default state of video is paused this.addClass('vjs-paused'); // Make box use width/height of tag, or rely on default implementation // Enforce with CSS since width/height attrs don't work on divs this.width(this.options_['width'], true); // (true) Skip resize listener on load this.height(this.options_['height'], true); // vjs.insertFirst seems to cause the networkState to flicker from 3 to 2, so // keep track of the original for later so we can know if the source originally failed tag.initNetworkState_ = tag.networkState; // Wrap video tag in div (el/box) container if (tag.parentNode) { tag.parentNode.insertBefore(el, tag); } vjs.insertFirst(tag, el); // Breaks iPhone, fixed in HTML5 setup. // The event listeners need to be added before the children are added // in the component init because the tech (loaded with mediaLoader) may // fire events, like loadstart, that these events need to capture. // Long term it might be better to expose a way to do this in component.init // like component.initEventListeners() that runs between el creation and // adding children this.el_ = el; this.on('loadstart', this.onLoadStart); this.on('waiting', this.onWaiting); this.on(['canplay', 'canplaythrough', 'playing', 'ended'], this.onWaitEnd); this.on('seeking', this.onSeeking); this.on('seeked', this.onSeeked); this.on('ended', this.onEnded); this.on('play', this.onPlay); this.on('firstplay', this.onFirstPlay); this.on('pause', this.onPause); this.on('progress', this.onProgress); this.on('durationchange', this.onDurationChange); this.on('fullscreenchange', this.onFullscreenChange); return el; }; // /* Media Technology (tech) // ================================================================================ */ // Load/Create an instance of playback technology including element and API methods // And append playback element in player div. vjs.Player.prototype.loadTech = function(techName, source){ // Pause and remove current playback technology if (this.tech) { this.unloadTech(); } // get rid of the HTML5 video tag as soon as we are using another tech if (techName !== 'Html5' && this.tag) { vjs.Html5.disposeMediaElement(this.tag); this.tag = null; } this.techName = techName; // Turn off API access because we're loading a new tech that might load asynchronously this.isReady_ = false; var techReady = function(){ this.player_.triggerReady(); }; // Grab tech-specific options from player options and add source and parent element to use. var techOptions = vjs.obj.merge({ 'source': source, 'parentEl': this.el_ }, this.options_[techName.toLowerCase()]); if (source) { this.currentType_ = source.type; if (source.src == this.cache_.src && this.cache_.currentTime > 0) { techOptions['startTime'] = this.cache_.currentTime; } this.cache_.src = source.src; } // Initialize tech instance this.tech = new window['videojs'][techName](this, techOptions); this.tech.ready(techReady); }; vjs.Player.prototype.unloadTech = function(){ this.isReady_ = false; this.tech.dispose(); this.tech = false; }; // There's many issues around changing the size of a Flash (or other plugin) object. // First is a plugin reload issue in Firefox that has been around for 11 years: https://bugzilla.mozilla.org/show_bug.cgi?id=90268 // Then with the new fullscreen API, Mozilla and webkit browsers will reload the flash object after going to fullscreen. // To get around this, we're unloading the tech, caching source and currentTime values, and reloading the tech once the plugin is resized. // reloadTech: function(betweenFn){ // vjs.log('unloadingTech') // this.unloadTech(); // vjs.log('unloadedTech') // if (betweenFn) { betweenFn.call(); } // vjs.log('LoadingTech') // this.loadTech(this.techName, { src: this.cache_.src }) // vjs.log('loadedTech') // }, // /* Player event handlers (how the player reacts to certain events) // ================================================================================ */ /** * Fired when the user agent begins looking for media data * @event loadstart */ vjs.Player.prototype.onLoadStart = function() { // TODO: Update to use `emptied` event instead. See #1277. // reset the error state this.error(null); // If it's already playing we want to trigger a firstplay event now. // The firstplay event relies on both the play and loadstart events // which can happen in any order for a new source if (!this.paused()) { this.trigger('firstplay'); } else { // reset the hasStarted state this.hasStarted(false); this.one('play', function(){ this.hasStarted(true); }); } }; vjs.Player.prototype.hasStarted_ = false; vjs.Player.prototype.hasStarted = function(hasStarted){ if (hasStarted !== undefined) { // only update if this is a new value if (this.hasStarted_ !== hasStarted) { this.hasStarted_ = hasStarted; if (hasStarted) { this.addClass('vjs-has-started'); // trigger the firstplay event if this newly has played this.trigger('firstplay'); } else { this.removeClass('vjs-has-started'); } } return this; } return this.hasStarted_; }; /** * Fired when the player has initial duration and dimension information * @event loadedmetadata */ vjs.Player.prototype.onLoadedMetaData; /** * Fired when the player has downloaded data at the current playback position * @event loadeddata */ vjs.Player.prototype.onLoadedData; /** * Fired when the player has finished downloading the source data * @event loadedalldata */ vjs.Player.prototype.onLoadedAllData; /** * Fired whenever the media begins or resumes playback * @event play */ vjs.Player.prototype.onPlay = function(){ this.removeClass('vjs-paused'); this.addClass('vjs-playing'); }; /** * Fired whenever the media begins waiting * @event waiting */ vjs.Player.prototype.onWaiting = function(){ this.addClass('vjs-waiting'); }; /** * A handler for events that signal that waiting has ended * which is not consistent between browsers. See #1351 * @private */ vjs.Player.prototype.onWaitEnd = function(){ this.removeClass('vjs-waiting'); }; /** * Fired whenever the player is jumping to a new time * @event seeking */ vjs.Player.prototype.onSeeking = function(){ this.addClass('vjs-seeking'); }; /** * Fired when the player has finished jumping to a new time * @event seeked */ vjs.Player.prototype.onSeeked = function(){ this.removeClass('vjs-seeking'); }; /** * Fired the first time a video is played * * Not part of the HLS spec, and we're not sure if this is the best * implementation yet, so use sparingly. If you don't have a reason to * prevent playback, use `myPlayer.one('play');` instead. * * @event firstplay */ vjs.Player.prototype.onFirstPlay = function(){ //If the first starttime attribute is specified //then we will start at the given offset in seconds if(this.options_['starttime']){ this.currentTime(this.options_['starttime']); } this.addClass('vjs-has-started'); }; /** * Fired whenever the media has been paused * @event pause */ vjs.Player.prototype.onPause = function(){ this.removeClass('vjs-playing'); this.addClass('vjs-paused'); }; /** * Fired when the current playback position has changed * * During playback this is fired every 15-250 milliseconds, depending on the * playback technology in use. * @event timeupdate */ vjs.Player.prototype.onTimeUpdate; /** * Fired while the user agent is downloading media data * @event progress */ vjs.Player.prototype.onProgress = function(){ // Add custom event for when source is finished downloading. if (this.bufferedPercent() == 1) { this.trigger('loadedalldata'); } }; /** * Fired when the end of the media resource is reached (currentTime == duration) * @event ended */ vjs.Player.prototype.onEnded = function(){ if (this.options_['loop']) { this.currentTime(0); this.play(); } else if (!this.paused()) { this.pause(); } }; /** * Fired when the duration of the media resource is first known or changed * @event durationchange */ vjs.Player.prototype.onDurationChange = function(){ // Allows for caching value instead of asking player each time. // We need to get the techGet response and check for a value so we don't // accidentally cause the stack to blow up. var duration = this.techGet('duration'); if (duration) { if (duration < 0) { duration = Infinity; } this.duration(duration); // Determine if the stream is live and propagate styles down to UI. if (duration === Infinity) { this.addClass('vjs-live'); } else { this.removeClass('vjs-live'); } } }; /** * Fired when the volume changes * @event volumechange */ vjs.Player.prototype.onVolumeChange; /** * Fired when the player switches in or out of fullscreen mode * @event fullscreenchange */ vjs.Player.prototype.onFullscreenChange = function() { if (this.isFullscreen()) { this.addClass('vjs-fullscreen'); } else { this.removeClass('vjs-fullscreen'); } }; // /* Player API // ================================================================================ */ /** * Object for cached values. * @private */ vjs.Player.prototype.cache_; vjs.Player.prototype.getCache = function(){ return this.cache_; }; // Pass values to the playback tech vjs.Player.prototype.techCall = function(method, arg){ // If it's not ready yet, call method when it is if (this.tech && !this.tech.isReady_) { this.tech.ready(function(){ this[method](arg); }); // Otherwise call method now } else { try { this.tech[method](arg); } catch(e) { vjs.log(e); throw e; } } }; // Get calls can't wait for the tech, and sometimes don't need to. vjs.Player.prototype.techGet = function(method){ if (this.tech && this.tech.isReady_) { // Flash likes to die and reload when you hide or reposition it. // In these cases the object methods go away and we get errors. // When that happens we'll catch the errors and inform tech that it's not ready any more. try { return this.tech[method](); } catch(e) { // When building additional tech libs, an expected method may not be defined yet if (this.tech[method] === undefined) { vjs.log('Video.js: ' + method + ' method not defined for '+this.techName+' playback technology.', e); } else { // When a method isn't available on the object it throws a TypeError if (e.name == 'TypeError') { vjs.log('Video.js: ' + method + ' unavailable on '+this.techName+' playback technology element.', e); this.tech.isReady_ = false; } else { vjs.log(e); } } throw e; } } return; }; /** * start media playback * * myPlayer.play(); * * @return {vjs.Player} self */ vjs.Player.prototype.play = function(){ this.techCall('play'); return this; }; /** * Pause the video playback * * myPlayer.pause(); * * @return {vjs.Player} self */ vjs.Player.prototype.pause = function(){ this.techCall('pause'); return this; }; /** * Check if the player is paused * * var isPaused = myPlayer.paused(); * var isPlaying = !myPlayer.paused(); * * @return {Boolean} false if the media is currently playing, or true otherwise */ vjs.Player.prototype.paused = function(){ // The initial state of paused should be true (in Safari it's actually false) return (this.techGet('paused') === false) ? false : true; }; /** * Get or set the current time (in seconds) * * // get * var whereYouAt = myPlayer.currentTime(); * * // set * myPlayer.currentTime(120); // 2 minutes into the video * * @param {Number|String=} seconds The time to seek to * @return {Number} The time in seconds, when not setting * @return {vjs.Player} self, when the current time is set */ vjs.Player.prototype.currentTime = function(seconds){ if (seconds !== undefined) { this.techCall('setCurrentTime', seconds); return this; } // cache last currentTime and return. default to 0 seconds // // Caching the currentTime is meant to prevent a massive amount of reads on the tech's // currentTime when scrubbing, but may not provide much performance benefit afterall. // Should be tested. Also something has to read the actual current time or the cache will // never get updated. return this.cache_.currentTime = (this.techGet('currentTime') || 0); }; /** * Get the length in time of the video in seconds * * var lengthOfVideo = myPlayer.duration(); * * **NOTE**: The video must have started loading before the duration can be * known, and in the case of Flash, may not be known until the video starts * playing. * * @return {Number} The duration of the video in seconds */ vjs.Player.prototype.duration = function(seconds){ if (seconds !== undefined) { // cache the last set value for optimized scrubbing (esp. Flash) this.cache_.duration = parseFloat(seconds); return this; } if (this.cache_.duration === undefined) { this.onDurationChange(); } return this.cache_.duration || 0; }; /** * Calculates how much time is left. * * var timeLeft = myPlayer.remainingTime(); * * Not a native video element function, but useful * @return {Number} The time remaining in seconds */ vjs.Player.prototype.remainingTime = function(){ return this.duration() - this.currentTime(); }; // http://dev.w3.org/html5/spec/video.html#dom-media-buffered // Buffered returns a timerange object. // Kind of like an array of portions of the video that have been downloaded. /** * Get a TimeRange object with the times of the video that have been downloaded * * If you just want the percent of the video that's been downloaded, * use bufferedPercent. * * // Number of different ranges of time have been buffered. Usually 1. * numberOfRanges = bufferedTimeRange.length, * * // Time in seconds when the first range starts. Usually 0. * firstRangeStart = bufferedTimeRange.start(0), * * // Time in seconds when the first range ends * firstRangeEnd = bufferedTimeRange.end(0), * * // Length in seconds of the first time range * firstRangeLength = firstRangeEnd - firstRangeStart; * * @return {Object} A mock TimeRange object (following HTML spec) */ vjs.Player.prototype.buffered = function(){ var buffered = this.techGet('buffered'); if (!buffered || !buffered.length) { buffered = vjs.createTimeRange(0,0); } return buffered; }; /** * Get the percent (as a decimal) of the video that's been downloaded * * var howMuchIsDownloaded = myPlayer.bufferedPercent(); * * 0 means none, 1 means all. * (This method isn't in the HTML5 spec, but it's very convenient) * * @return {Number} A decimal between 0 and 1 representing the percent */ vjs.Player.prototype.bufferedPercent = function(){ var duration = this.duration(), buffered = this.buffered(), bufferedDuration = 0, start, end; if (!duration) { return 0; } for (var i=0; i<buffered.length; i++){ start = buffered.start(i); end = buffered.end(i); // buffered end can be bigger than duration by a very small fraction if (end > duration) { end = duration; } bufferedDuration += end - start; } return bufferedDuration / duration; }; /** * Get the ending time of the last buffered time range * * This is used in the progress bar to encapsulate all time ranges. * @return {Number} The end of the last buffered time range */ vjs.Player.prototype.bufferedEnd = function(){ var buffered = this.buffered(), duration = this.duration(), end = buffered.end(buffered.length-1); if (end > duration) { end = duration; } return end; }; /** * Get or set the current volume of the media * * // get * var howLoudIsIt = myPlayer.volume(); * * // set * myPlayer.volume(0.5); // Set volume to half * * 0 is off (muted), 1.0 is all the way up, 0.5 is half way. * * @param {Number} percentAsDecimal The new volume as a decimal percent * @return {Number} The current volume, when getting * @return {vjs.Player} self, when setting */ vjs.Player.prototype.volume = function(percentAsDecimal){ var vol; if (percentAsDecimal !== undefined) { vol = Math.max(0, Math.min(1, parseFloat(percentAsDecimal))); // Force value to between 0 and 1 this.cache_.volume = vol; this.techCall('setVolume', vol); vjs.setLocalStorage('volume', vol); return this; } // Default to 1 when returning current volume. vol = parseFloat(this.techGet('volume')); return (isNaN(vol)) ? 1 : vol; }; /** * Get the current muted state, or turn mute on or off * * // get * var isVolumeMuted = myPlayer.muted(); * * // set * myPlayer.muted(true); // mute the volume * * @param {Boolean=} muted True to mute, false to unmute * @return {Boolean} True if mute is on, false if not, when getting * @return {vjs.Player} self, when setting mute */ vjs.Player.prototype.muted = function(muted){ if (muted !== undefined) { this.techCall('setMuted', muted); return this; } return this.techGet('muted') || false; // Default to false }; // Check if current tech can support native fullscreen // (e.g. with built in controls like iOS, so not our flash swf) vjs.Player.prototype.supportsFullScreen = function(){ return this.techGet('supportsFullScreen') || false; }; /** * is the player in fullscreen * @type {Boolean} * @private */ vjs.Player.prototype.isFullscreen_ = false; /** * Check if the player is in fullscreen mode * * // get * var fullscreenOrNot = myPlayer.isFullscreen(); * * // set * myPlayer.isFullscreen(true); // tell the player it's in fullscreen * * NOTE: As of the latest HTML5 spec, isFullscreen is no longer an official * property and instead document.fullscreenElement is used. But isFullscreen is * still a valuable property for internal player workings. * * @param {Boolean=} isFS Update the player's fullscreen state * @return {Boolean} true if fullscreen, false if not * @return {vjs.Player} self, when setting */ vjs.Player.prototype.isFullscreen = function(isFS){ if (isFS !== undefined) { this.isFullscreen_ = !!isFS; return this; } return this.isFullscreen_; }; /** * Old naming for isFullscreen() * @deprecated for lowercase 's' version */ vjs.Player.prototype.isFullScreen = function(isFS){ vjs.log.warn('player.isFullScreen() has been deprecated, use player.isFullscreen() with a lowercase "s")'); return this.isFullscreen(isFS); }; /** * Increase the size of the video to full screen * * myPlayer.requestFullscreen(); * * In some browsers, full screen is not supported natively, so it enters * "full window mode", where the video fills the browser window. * In browsers and devices that support native full screen, sometimes the * browser's default controls will be shown, and not the Video.js custom skin. * This includes most mobile devices (iOS, Android) and older versions of * Safari. * * @return {vjs.Player} self */ vjs.Player.prototype.requestFullscreen = function(){ var fsApi = vjs.browser.fullscreenAPI; this.isFullscreen(true); if (fsApi) { // the browser supports going fullscreen at the element level so we can // take the controls fullscreen as well as the video // Trigger fullscreenchange event after change // We have to specifically add this each time, and remove // when canceling fullscreen. Otherwise if there's multiple // players on a page, they would all be reacting to the same fullscreen // events vjs.on(document, fsApi['fullscreenchange'], vjs.bind(this, function(e){ this.isFullscreen(document[fsApi.fullscreenElement]); // If cancelling fullscreen, remove event listener. if (this.isFullscreen() === false) { vjs.off(document, fsApi['fullscreenchange'], arguments.callee); } this.trigger('fullscreenchange'); })); this.el_[fsApi.requestFullscreen](); } else if (this.tech.supportsFullScreen()) { // we can't take the video.js controls fullscreen but we can go fullscreen // with native controls this.techCall('enterFullScreen'); } else { // fullscreen isn't supported so we'll just stretch the video element to // fill the viewport this.enterFullWindow(); this.trigger('fullscreenchange'); } return this; }; /** * Old naming for requestFullscreen * @deprecated for lower case 's' version */ vjs.Player.prototype.requestFullScreen = function(){ vjs.log.warn('player.requestFullScreen() has been deprecated, use player.requestFullscreen() with a lowercase "s")'); return this.requestFullscreen(); }; /** * Return the video to its normal size after having been in full screen mode * * myPlayer.exitFullscreen(); * * @return {vjs.Player} self */ vjs.Player.prototype.exitFullscreen = function(){ var fsApi = vjs.browser.fullscreenAPI; this.isFullscreen(false); // Check for browser element fullscreen support if (fsApi) { document[fsApi.exitFullscreen](); } else if (this.tech.supportsFullScreen()) { this.techCall('exitFullScreen'); } else { this.exitFullWindow(); this.trigger('fullscreenchange'); } return this; }; /** * Old naming for exitFullscreen * @deprecated for exitFullscreen */ vjs.Player.prototype.cancelFullScreen = function(){ vjs.log.warn('player.cancelFullScreen() has been deprecated, use player.exitFullscreen()'); return this.exitFullscreen(); }; // When fullscreen isn't supported we can stretch the video container to as wide as the browser will let us. vjs.Player.prototype.enterFullWindow = function(){ this.isFullWindow = true; // Storing original doc overflow value to return to when fullscreen is off this.docOrigOverflow = document.documentElement.style.overflow; // Add listener for esc key to exit fullscreen vjs.on(document, 'keydown', vjs.bind(this, this.fullWindowOnEscKey)); // Hide any scroll bars document.documentElement.style.overflow = 'hidden'; // Apply fullscreen styles vjs.addClass(document.body, 'vjs-full-window'); this.trigger('enterFullWindow'); }; vjs.Player.prototype.fullWindowOnEscKey = function(event){ if (event.keyCode === 27) { if (this.isFullscreen() === true) { this.exitFullscreen(); } else { this.exitFullWindow(); } } }; vjs.Player.prototype.exitFullWindow = function(){ this.isFullWindow = false; vjs.off(document, 'keydown', this.fullWindowOnEscKey); // Unhide scroll bars. document.documentElement.style.overflow = this.docOrigOverflow; // Remove fullscreen styles vjs.removeClass(document.body, 'vjs-full-window'); // Resize the box, controller, and poster to original sizes // this.positionAll(); this.trigger('exitFullWindow'); }; vjs.Player.prototype.selectSource = function(sources){ // Loop through each playback technology in the options order for (var i=0,j=this.options_['techOrder'];i<j.length;i++) { var techName = vjs.capitalize(j[i]), tech = window['videojs'][techName]; // Check if the current tech is defined before continuing if (!tech) { vjs.log.error('The "' + techName + '" tech is undefined. Skipped browser support check for that tech.'); continue; } // Check if the browser supports this technology if (tech.isSupported()) { // Loop through each source object for (var a=0,b=sources;a<b.length;a++) { var source = b[a]; // Check if source can be played with this technology if (tech['canPlaySource'](source)) { return { source: source, tech: techName }; } } } } return false; }; /** * The source function updates the video source * * There are three types of variables you can pass as the argument. * * **URL String**: A URL to the the video file. Use this method if you are sure * the current playback technology (HTML5/Flash) can support the source you * provide. Currently only MP4 files can be used in both HTML5 and Flash. * * myPlayer.src("http://www.example.com/path/to/video.mp4"); * * **Source Object (or element):** A javascript object containing information * about the source file. Use this method if you want the player to determine if * it can support the file using the type information. * * myPlayer.src({ type: "video/mp4", src: "http://www.example.com/path/to/video.mp4" }); * * **Array of Source Objects:** To provide multiple versions of the source so * that it can be played using HTML5 across browsers you can use an array of * source objects. Video.js will detect which version is supported and load that * file. * * myPlayer.src([ * { type: "video/mp4", src: "http://www.example.com/path/to/video.mp4" }, * { type: "video/webm", src: "http://www.example.com/path/to/video.webm" }, * { type: "video/ogg", src: "http://www.example.com/path/to/video.ogv" } * ]); * * @param {String|Object|Array=} source The source URL, object, or array of sources * @return {String} The current video source when getting * @return {String} The player when setting */ vjs.Player.prototype.src = function(source){ if (source === undefined) { return this.techGet('src'); } // case: Array of source objects to choose from and pick the best to play if (vjs.obj.isArray(source)) { this.sourceList_(source); // case: URL String (http://myvideo...) } else if (typeof source === 'string') { // create a source object from the string this.src({ src: source }); // case: Source object { src: '', type: '' ... } } else if (source instanceof Object) { // check if the source has a type and the loaded tech cannot play the source // if there's no type we'll just try the current tech if (source.type && !window['videojs'][this.techName]['canPlaySource'](source)) { // create a source list with the current source and send through // the tech loop to check for a compatible technology this.sourceList_([source]); } else { this.cache_.src = source.src; this.currentType_ = source.type || ''; // wait until the tech is ready to set the source this.ready(function(){ // The setSource tech method was added with source handlers // so older techs won't support it // We need to check the direct prototype for the case where subclasses // of the tech do not support source handlers if (window['videojs'][this.techName].prototype.hasOwnProperty('setSource')) { this.techCall('setSource', source); } else { this.techCall('src', source.src); } if (this.options_['preload'] == 'auto') { this.load(); } if (this.options_['autoplay']) { this.play(); } }); } } return this; }; /** * Handle an array of source objects * @param {[type]} sources Array of source objects * @private */ vjs.Player.prototype.sourceList_ = function(sources){ var sourceTech = this.selectSource(sources); if (sourceTech) { if (sourceTech.tech === this.techName) { // if this technology is already loaded, set the source this.src(sourceTech.source); } else { // load this technology with the chosen source this.loadTech(sourceTech.tech, sourceTech.source); } } else { // We need to wrap this in a timeout to give folks a chance to add error event handlers this.setTimeout( function() { this.error({ code: 4, message: this.localize(this.options()['notSupportedMessage']) }); }, 0); // we could not find an appropriate tech, but let's still notify the delegate that this is it // this needs a better comment about why this is needed this.triggerReady(); } }; /** * Begin loading the src data. * @return {vjs.Player} Returns the player */ vjs.Player.prototype.load = function(){ this.techCall('load'); return this; }; /** * Returns the fully qualified URL of the current source value e.g. http://mysite.com/video.mp4 * Can be used in conjuction with `currentType` to assist in rebuilding the current source object. * @return {String} The current source */ vjs.Player.prototype.currentSrc = function(){ return this.techGet('currentSrc') || this.cache_.src || ''; }; /** * Get the current source type e.g. video/mp4 * This can allow you rebuild the current source object so that you could load the same * source and tech later * @return {String} The source MIME type */ vjs.Player.prototype.currentType = function(){ return this.currentType_ || ''; }; /** * Get or set the preload attribute. * @return {String} The preload attribute value when getting * @return {vjs.Player} Returns the player when setting */ vjs.Player.prototype.preload = function(value){ if (value !== undefined) { this.techCall('setPreload', value); this.options_['preload'] = value; return this; } return this.techGet('preload'); }; /** * Get or set the autoplay attribute. * @return {String} The autoplay attribute value when getting * @return {vjs.Player} Returns the player when setting */ vjs.Player.prototype.autoplay = function(value){ if (value !== undefined) { this.techCall('setAutoplay', value); this.options_['autoplay'] = value; return this; } return this.techGet('autoplay', value); }; /** * Get or set the loop attribute on the video element. * @return {String} The loop attribute value when getting * @return {vjs.Player} Returns the player when setting */ vjs.Player.prototype.loop = function(value){ if (value !== undefined) { this.techCall('setLoop', value); this.options_['loop'] = value; return this; } return this.techGet('loop'); }; /** * the url of the poster image source * @type {String} * @private */ vjs.Player.prototype.poster_; /** * get or set the poster image source url * * ##### EXAMPLE: * * // getting * var currentPoster = myPlayer.poster(); * * // setting * myPlayer.poster('http://example.com/myImage.jpg'); * * @param {String=} [src] Poster image source URL * @return {String} poster URL when getting * @return {vjs.Player} self when setting */ vjs.Player.prototype.poster = function(src){ if (src === undefined) { return this.poster_; } // The correct way to remove a poster is to set as an empty string // other falsey values will throw errors if (!src) { src = ''; } // update the internal poster variable this.poster_ = src; // update the tech's poster this.techCall('setPoster', src); // alert components that the poster has been set this.trigger('posterchange'); return this; }; /** * Whether or not the controls are showing * @type {Boolean} * @private */ vjs.Player.prototype.controls_; /** * Get or set whether or not the controls are showing. * @param {Boolean} controls Set controls to showing or not * @return {Boolean} Controls are showing */ vjs.Player.prototype.controls = function(bool){ if (bool !== undefined) { bool = !!bool; // force boolean // Don't trigger a change event unless it actually changed if (this.controls_ !== bool) { this.controls_ = bool; if (bool) { this.removeClass('vjs-controls-disabled'); this.addClass('vjs-controls-enabled'); this.trigger('controlsenabled'); } else { this.removeClass('vjs-controls-enabled'); this.addClass('vjs-controls-disabled'); this.trigger('controlsdisabled'); } } return this; } return this.controls_; }; vjs.Player.prototype.usingNativeControls_; /** * Toggle native controls on/off. Native controls are the controls built into * devices (e.g. default iPhone controls), Flash, or other techs * (e.g. Vimeo Controls) * * **This should only be set by the current tech, because only the tech knows * if it can support native controls** * * @param {Boolean} bool True signals that native controls are on * @return {vjs.Player} Returns the player * @private */ vjs.Player.prototype.usingNativeControls = function(bool){ if (bool !== undefined) { bool = !!bool; // force boolean // Don't trigger a change event unless it actually changed if (this.usingNativeControls_ !== bool) { this.usingNativeControls_ = bool; if (bool) { this.addClass('vjs-using-native-controls'); /** * player is using the native device controls * * @event usingnativecontrols * @memberof vjs.Player * @instance * @private */ this.trigger('usingnativecontrols'); } else { this.removeClass('vjs-using-native-controls'); /** * player is using the custom HTML controls * * @event usingcustomcontrols * @memberof vjs.Player * @instance * @private */ this.trigger('usingcustomcontrols'); } } return this; } return this.usingNativeControls_; }; /** * Store the current media error * @type {Object} * @private */ vjs.Player.prototype.error_ = null; /** * Set or get the current MediaError * @param {*} err A MediaError or a String/Number to be turned into a MediaError * @return {vjs.MediaError|null} when getting * @return {vjs.Player} when setting */ vjs.Player.prototype.error = function(err){ if (err === undefined) { return this.error_; } // restoring to default if (err === null) { this.error_ = err; this.removeClass('vjs-error'); return this; } // error instance if (err instanceof vjs.MediaError) { this.error_ = err; } else { this.error_ = new vjs.MediaError(err); } // fire an error event on the player this.trigger('error'); // add the vjs-error classname to the player this.addClass('vjs-error'); // log the name of the error type and any message // ie8 just logs "[object object]" if you just log the error object vjs.log.error('(CODE:'+this.error_.code+' '+vjs.MediaError.errorTypes[this.error_.code]+')', this.error_.message, this.error_); return this; }; /** * Returns whether or not the player is in the "ended" state. * @return {Boolean} True if the player is in the ended state, false if not. */ vjs.Player.prototype.ended = function(){ return this.techGet('ended'); }; /** * Returns whether or not the player is in the "seeking" state. * @return {Boolean} True if the player is in the seeking state, false if not. */ vjs.Player.prototype.seeking = function(){ return this.techGet('seeking'); }; // When the player is first initialized, trigger activity so components // like the control bar show themselves if needed vjs.Player.prototype.userActivity_ = true; vjs.Player.prototype.reportUserActivity = function(event){ this.userActivity_ = true; }; vjs.Player.prototype.userActive_ = true; vjs.Player.prototype.userActive = function(bool){ if (bool !== undefined) { bool = !!bool; if (bool !== this.userActive_) { this.userActive_ = bool; if (bool) { // If the user was inactive and is now active we want to reset the // inactivity timer this.userActivity_ = true; this.removeClass('vjs-user-inactive'); this.addClass('vjs-user-active'); this.trigger('useractive'); } else { // We're switching the state to inactive manually, so erase any other // activity this.userActivity_ = false; // Chrome/Safari/IE have bugs where when you change the cursor it can // trigger a mousemove event. This causes an issue when you're hiding // the cursor when the user is inactive, and a mousemove signals user // activity. Making it impossible to go into inactive mode. Specifically // this happens in fullscreen when we really need to hide the cursor. // // When this gets resolved in ALL browsers it can be removed // https://code.google.com/p/chromium/issues/detail?id=103041 if(this.tech) { this.tech.one('mousemove', function(e){ e.stopPropagation(); e.preventDefault(); }); } this.removeClass('vjs-user-active'); this.addClass('vjs-user-inactive'); this.trigger('userinactive'); } } return this; } return this.userActive_; }; vjs.Player.prototype.listenForUserActivity = function(){ var onActivity, onMouseMove, onMouseDown, mouseInProgress, onMouseUp, activityCheck, inactivityTimeout, lastMoveX, lastMoveY; onActivity = vjs.bind(this, this.reportUserActivity); onMouseMove = function(e) { // #1068 - Prevent mousemove spamming // Chrome Bug: https://code.google.com/p/chromium/issues/detail?id=366970 if(e.screenX != lastMoveX || e.screenY != lastMoveY) { lastMoveX = e.screenX; lastMoveY = e.screenY; onActivity(); } }; onMouseDown = function() { onActivity(); // For as long as the they are touching the device or have their mouse down, // we consider them active even if they're not moving their finger or mouse. // So we want to continue to update that they are active this.clearInterval(mouseInProgress); // Setting userActivity=true now and setting the interval to the same time // as the activityCheck interval (250) should ensure we never miss the // next activityCheck mouseInProgress = this.setInterval(onActivity, 250); }; onMouseUp = function(event) { onActivity(); // Stop the interval that maintains activity if the mouse/touch is down this.clearInterval(mouseInProgress); }; // Any mouse movement will be considered user activity this.on('mousedown', onMouseDown); this.on('mousemove', onMouseMove); this.on('mouseup', onMouseUp); // Listen for keyboard navigation // Shouldn't need to use inProgress interval because of key repeat this.on('keydown', onActivity); this.on('keyup', onActivity); // Run an interval every 250 milliseconds instead of stuffing everything into // the mousemove/touchmove function itself, to prevent performance degradation. // `this.reportUserActivity` simply sets this.userActivity_ to true, which // then gets picked up by this loop // http://ejohn.org/blog/learning-from-twitter/ activityCheck = this.setInterval(function() { // Check to see if mouse/touch activity has happened if (this.userActivity_) { // Reset the activity tracker this.userActivity_ = false; // If the user state was inactive, set the state to active this.userActive(true); // Clear any existing inactivity timeout to start the timer over this.clearTimeout(inactivityTimeout); var timeout = this.options()['inactivityTimeout']; if (timeout > 0) { // In <timeout> milliseconds, if no more activity has occurred the // user will be considered inactive inactivityTimeout = this.setTimeout(function () { // Protect against the case where the inactivityTimeout can trigger just // before the next user activity is picked up by the activityCheck loop // causing a flicker if (!this.userActivity_) { this.userActive(false); } }, timeout); } } }, 250); }; /** * Gets or sets the current playback rate. * @param {Boolean} rate New playback rate to set. * @return {Number} Returns the new playback rate when setting * @return {Number} Returns the current playback rate when getting */ vjs.Player.prototype.playbackRate = function(rate) { if (rate !== undefined) { this.techCall('setPlaybackRate', rate); return this; } if (this.tech && this.tech['featuresPlaybackRate']) { return this.techGet('playbackRate'); } else { return 1.0; } }; /** * Store the current audio state * @type {Boolean} * @private */ vjs.Player.prototype.isAudio_ = false; /** * Gets or sets the audio flag * * @param {Boolean} bool True signals that this is an audio player. * @return {Boolean} Returns true if player is audio, false if not when getting * @return {vjs.Player} Returns the player if setting * @private */ vjs.Player.prototype.isAudio = function(bool) { if (bool !== undefined) { this.isAudio_ = !!bool; return this; } return this.isAudio_; }; // Methods to add support for // networkState: function(){ return this.techCall('networkState'); }, // readyState: function(){ return this.techCall('readyState'); }, // initialTime: function(){ return this.techCall('initialTime'); }, // startOffsetTime: function(){ return this.techCall('startOffsetTime'); }, // played: function(){ return this.techCall('played'); }, // seekable: function(){ return this.techCall('seekable'); }, // videoTracks: function(){ return this.techCall('videoTracks'); }, // audioTracks: function(){ return this.techCall('audioTracks'); }, // videoWidth: function(){ return this.techCall('videoWidth'); }, // videoHeight: function(){ return this.techCall('videoHeight'); }, // defaultPlaybackRate: function(){ return this.techCall('defaultPlaybackRate'); }, // mediaGroup: function(){ return this.techCall('mediaGroup'); }, // controller: function(){ return this.techCall('controller'); }, // defaultMuted: function(){ return this.techCall('defaultMuted'); } // TODO // currentSrcList: the array of sources including other formats and bitrates // playList: array of source lists in order of playback /** * Container of main controls * @param {vjs.Player|Object} player * @param {Object=} options * @class * @constructor * @extends vjs.Component */ vjs.ControlBar = vjs.Component.extend(); vjs.ControlBar.prototype.options_ = { loadEvent: 'play', children: { 'playToggle': {}, 'currentTimeDisplay': {}, 'timeDivider': {}, 'durationDisplay': {}, 'remainingTimeDisplay': {}, 'liveDisplay': {}, 'progressControl': {}, 'fullscreenToggle': {}, 'volumeControl': {}, 'muteToggle': {}, // 'volumeMenuButton': {}, 'playbackRateMenuButton': {} } }; vjs.ControlBar.prototype.createEl = function(){ return vjs.createEl('div', { className: 'vjs-control-bar' }); }; /** * Displays the live indicator * TODO - Future make it click to snap to live * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.LiveDisplay = vjs.Component.extend({ init: function(player, options){ vjs.Component.call(this, player, options); } }); vjs.LiveDisplay.prototype.createEl = function(){ var el = vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-live-controls vjs-control' }); this.contentEl_ = vjs.createEl('div', { className: 'vjs-live-display', innerHTML: '<span class="vjs-control-text">' + this.localize('Stream Type') + '</span>' + this.localize('LIVE'), 'aria-live': 'off' }); el.appendChild(this.contentEl_); return el; }; /** * Button to toggle between play and pause * @param {vjs.Player|Object} player * @param {Object=} options * @class * @constructor */ vjs.PlayToggle = vjs.Button.extend({ /** @constructor */ init: function(player, options){ vjs.Button.call(this, player, options); this.on(player, 'play', this.onPlay); this.on(player, 'pause', this.onPause); } }); vjs.PlayToggle.prototype.buttonText = 'Play'; vjs.PlayToggle.prototype.buildCSSClass = function(){ return 'vjs-play-control ' + vjs.Button.prototype.buildCSSClass.call(this); }; // OnClick - Toggle between play and pause vjs.PlayToggle.prototype.onClick = function(){ if (this.player_.paused()) { this.player_.play(); } else { this.player_.pause(); } }; // OnPlay - Add the vjs-playing class to the element so it can change appearance vjs.PlayToggle.prototype.onPlay = function(){ this.removeClass('vjs-paused'); this.addClass('vjs-playing'); this.el_.children[0].children[0].innerHTML = this.localize('Pause'); // change the button text to "Pause" }; // OnPause - Add the vjs-paused class to the element so it can change appearance vjs.PlayToggle.prototype.onPause = function(){ this.removeClass('vjs-playing'); this.addClass('vjs-paused'); this.el_.children[0].children[0].innerHTML = this.localize('Play'); // change the button text to "Play" }; /** * Displays the current time * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.CurrentTimeDisplay = vjs.Component.extend({ /** @constructor */ init: function(player, options){ vjs.Component.call(this, player, options); this.on(player, 'timeupdate', this.updateContent); } }); vjs.CurrentTimeDisplay.prototype.createEl = function(){ var el = vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-current-time vjs-time-controls vjs-control' }); this.contentEl_ = vjs.createEl('div', { className: 'vjs-current-time-display', innerHTML: '<span class="vjs-control-text">Current Time </span>' + '0:00', // label the current time for screen reader users 'aria-live': 'off' // tell screen readers not to automatically read the time as it changes }); el.appendChild(this.contentEl_); return el; }; vjs.CurrentTimeDisplay.prototype.updateContent = function(){ // Allows for smooth scrubbing, when player can't keep up. var time = (this.player_.scrubbing) ? this.player_.getCache().currentTime : this.player_.currentTime(); this.contentEl_.innerHTML = '<span class="vjs-control-text">' + this.localize('Current Time') + '</span> ' + vjs.formatTime(time, this.player_.duration()); }; /** * Displays the duration * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.DurationDisplay = vjs.Component.extend({ /** @constructor */ init: function(player, options){ vjs.Component.call(this, player, options); // this might need to be changed to 'durationchange' instead of 'timeupdate' eventually, // however the durationchange event fires before this.player_.duration() is set, // so the value cannot be written out using this method. // Once the order of durationchange and this.player_.duration() being set is figured out, // this can be updated. this.on(player, 'timeupdate', this.updateContent); } }); vjs.DurationDisplay.prototype.createEl = function(){ var el = vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-duration vjs-time-controls vjs-control' }); this.contentEl_ = vjs.createEl('div', { className: 'vjs-duration-display', innerHTML: '<span class="vjs-control-text">' + this.localize('Duration Time') + '</span> ' + '0:00', // label the duration time for screen reader users 'aria-live': 'off' // tell screen readers not to automatically read the time as it changes }); el.appendChild(this.contentEl_); return el; }; vjs.DurationDisplay.prototype.updateContent = function(){ var duration = this.player_.duration(); if (duration) { this.contentEl_.innerHTML = '<span class="vjs-control-text">' + this.localize('Duration Time') + '</span> ' + vjs.formatTime(duration); // label the duration time for screen reader users } }; /** * The separator between the current time and duration * * Can be hidden if it's not needed in the design. * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.TimeDivider = vjs.Component.extend({ /** @constructor */ init: function(player, options){ vjs.Component.call(this, player, options); } }); vjs.TimeDivider.prototype.createEl = function(){ return vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-time-divider', innerHTML: '<div><span>/</span></div>' }); }; /** * Displays the time left in the video * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.RemainingTimeDisplay = vjs.Component.extend({ /** @constructor */ init: function(player, options){ vjs.Component.call(this, player, options); this.on(player, 'timeupdate', this.updateContent); } }); vjs.RemainingTimeDisplay.prototype.createEl = function(){ var el = vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-remaining-time vjs-time-controls vjs-control' }); this.contentEl_ = vjs.createEl('div', { className: 'vjs-remaining-time-display', innerHTML: '<span class="vjs-control-text">' + this.localize('Remaining Time') + '</span> ' + '-0:00', // label the remaining time for screen reader users 'aria-live': 'off' // tell screen readers not to automatically read the time as it changes }); el.appendChild(this.contentEl_); return el; }; vjs.RemainingTimeDisplay.prototype.updateContent = function(){ if (this.player_.duration()) { this.contentEl_.innerHTML = '<span class="vjs-control-text">' + this.localize('Remaining Time') + '</span> ' + '-'+ vjs.formatTime(this.player_.remainingTime()); } // Allows for smooth scrubbing, when player can't keep up. // var time = (this.player_.scrubbing) ? this.player_.getCache().currentTime : this.player_.currentTime(); // this.contentEl_.innerHTML = vjs.formatTime(time, this.player_.duration()); }; /** * Toggle fullscreen video * @param {vjs.Player|Object} player * @param {Object=} options * @class * @extends vjs.Button */ vjs.FullscreenToggle = vjs.Button.extend({ /** * @constructor * @memberof vjs.FullscreenToggle * @instance */ init: function(player, options){ vjs.Button.call(this, player, options); } }); vjs.FullscreenToggle.prototype.buttonText = 'Fullscreen'; vjs.FullscreenToggle.prototype.buildCSSClass = function(){ return 'vjs-fullscreen-control ' + vjs.Button.prototype.buildCSSClass.call(this); }; vjs.FullscreenToggle.prototype.onClick = function(){ if (!this.player_.isFullscreen()) { this.player_.requestFullscreen(); this.controlText_.innerHTML = this.localize('Non-Fullscreen'); } else { this.player_.exitFullscreen(); this.controlText_.innerHTML = this.localize('Fullscreen'); } }; /** * The Progress Control component contains the seek bar, load progress, * and play progress * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.ProgressControl = vjs.Component.extend({ /** @constructor */ init: function(player, options){ vjs.Component.call(this, player, options); } }); vjs.ProgressControl.prototype.options_ = { children: { 'seekBar': {} } }; vjs.ProgressControl.prototype.createEl = function(){ return vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-progress-control vjs-control' }); }; /** * Seek Bar and holder for the progress bars * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.SeekBar = vjs.Slider.extend({ /** @constructor */ init: function(player, options){ vjs.Slider.call(this, player, options); this.on(player, 'timeupdate', this.updateARIAAttributes); player.ready(vjs.bind(this, this.updateARIAAttributes)); } }); vjs.SeekBar.prototype.options_ = { children: { 'loadProgressBar': {}, 'playProgressBar': {}, 'seekHandle': {} }, 'barName': 'playProgressBar', 'handleName': 'seekHandle' }; vjs.SeekBar.prototype.playerEvent = 'timeupdate'; vjs.SeekBar.prototype.createEl = function(){ return vjs.Slider.prototype.createEl.call(this, 'div', { className: 'vjs-progress-holder', 'aria-label': 'video progress bar' }); }; vjs.SeekBar.prototype.updateARIAAttributes = function(){ // Allows for smooth scrubbing, when player can't keep up. var time = (this.player_.scrubbing) ? this.player_.getCache().currentTime : this.player_.currentTime(); this.el_.setAttribute('aria-valuenow',vjs.round(this.getPercent()*100, 2)); // machine readable value of progress bar (percentage complete) this.el_.setAttribute('aria-valuetext',vjs.formatTime(time, this.player_.duration())); // human readable value of progress bar (time complete) }; vjs.SeekBar.prototype.getPercent = function(){ return this.player_.currentTime() / this.player_.duration(); }; vjs.SeekBar.prototype.onMouseDown = function(event){ vjs.Slider.prototype.onMouseDown.call(this, event); this.player_.scrubbing = true; this.videoWasPlaying = !this.player_.paused(); this.player_.pause(); }; vjs.SeekBar.prototype.onMouseMove = function(event){ var newTime = this.calculateDistance(event) * this.player_.duration(); // Don't let video end while scrubbing. if (newTime == this.player_.duration()) { newTime = newTime - 0.1; } // Set new time (tell player to seek to new time) this.player_.currentTime(newTime); }; vjs.SeekBar.prototype.onMouseUp = function(event){ vjs.Slider.prototype.onMouseUp.call(this, event); this.player_.scrubbing = false; if (this.videoWasPlaying) { this.player_.play(); } }; vjs.SeekBar.prototype.stepForward = function(){ this.player_.currentTime(this.player_.currentTime() + 5); // more quickly fast forward for keyboard-only users }; vjs.SeekBar.prototype.stepBack = function(){ this.player_.currentTime(this.player_.currentTime() - 5); // more quickly rewind for keyboard-only users }; /** * Shows load progress * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.LoadProgressBar = vjs.Component.extend({ /** @constructor */ init: function(player, options){ vjs.Component.call(this, player, options); this.on(player, 'progress', this.update); } }); vjs.LoadProgressBar.prototype.createEl = function(){ return vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-load-progress', innerHTML: '<span class="vjs-control-text"><span>' + this.localize('Loaded') + '</span>: 0%</span>' }); }; vjs.LoadProgressBar.prototype.update = function(){ var i, start, end, part, buffered = this.player_.buffered(), duration = this.player_.duration(), bufferedEnd = this.player_.bufferedEnd(), children = this.el_.children, // get the percent width of a time compared to the total end percentify = function (time, end){ var percent = (time / end) || 0; // no NaN return (percent * 100) + '%'; }; // update the width of the progress bar this.el_.style.width = percentify(bufferedEnd, duration); // add child elements to represent the individual buffered time ranges for (i = 0; i < buffered.length; i++) { start = buffered.start(i), end = buffered.end(i), part = children[i]; if (!part) { part = this.el_.appendChild(vjs.createEl()); } // set the percent based on the width of the progress bar (bufferedEnd) part.style.left = percentify(start, bufferedEnd); part.style.width = percentify(end - start, bufferedEnd); } // remove unused buffered range elements for (i = children.length; i > buffered.length; i--) { this.el_.removeChild(children[i-1]); } }; /** * Shows play progress * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.PlayProgressBar = vjs.Component.extend({ /** @constructor */ init: function(player, options){ vjs.Component.call(this, player, options); } }); vjs.PlayProgressBar.prototype.createEl = function(){ return vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-play-progress', innerHTML: '<span class="vjs-control-text"><span>' + this.localize('Progress') + '</span>: 0%</span>' }); }; /** * The Seek Handle shows the current position of the playhead during playback, * and can be dragged to adjust the playhead. * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.SeekHandle = vjs.SliderHandle.extend({ init: function(player, options) { vjs.SliderHandle.call(this, player, options); this.on(player, 'timeupdate', this.updateContent); } }); /** * The default value for the handle content, which may be read by screen readers * * @type {String} * @private */ vjs.SeekHandle.prototype.defaultValue = '00:00'; /** @inheritDoc */ vjs.SeekHandle.prototype.createEl = function() { return vjs.SliderHandle.prototype.createEl.call(this, 'div', { className: 'vjs-seek-handle', 'aria-live': 'off' }); }; vjs.SeekHandle.prototype.updateContent = function() { var time = (this.player_.scrubbing) ? this.player_.getCache().currentTime : this.player_.currentTime(); this.el_.innerHTML = '<span class="vjs-control-text">' + vjs.formatTime(time, this.player_.duration()) + '</span>'; }; /** * The component for controlling the volume level * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.VolumeControl = vjs.Component.extend({ /** @constructor */ init: function(player, options){ vjs.Component.call(this, player, options); // hide volume controls when they're not supported by the current tech if (player.tech && player.tech['featuresVolumeControl'] === false) { this.addClass('vjs-hidden'); } this.on(player, 'loadstart', function(){ if (player.tech['featuresVolumeControl'] === false) { this.addClass('vjs-hidden'); } else { this.removeClass('vjs-hidden'); } }); } }); vjs.VolumeControl.prototype.options_ = { children: { 'volumeBar': {} } }; vjs.VolumeControl.prototype.createEl = function(){ return vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-volume-control vjs-control' }); }; /** * The bar that contains the volume level and can be clicked on to adjust the level * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.VolumeBar = vjs.Slider.extend({ /** @constructor */ init: function(player, options){ vjs.Slider.call(this, player, options); this.on(player, 'volumechange', this.updateARIAAttributes); player.ready(vjs.bind(this, this.updateARIAAttributes)); } }); vjs.VolumeBar.prototype.updateARIAAttributes = function(){ // Current value of volume bar as a percentage this.el_.setAttribute('aria-valuenow',vjs.round(this.player_.volume()*100, 2)); this.el_.setAttribute('aria-valuetext',vjs.round(this.player_.volume()*100, 2)+'%'); }; vjs.VolumeBar.prototype.options_ = { children: { 'volumeLevel': {}, 'volumeHandle': {} }, 'barName': 'volumeLevel', 'handleName': 'volumeHandle' }; vjs.VolumeBar.prototype.playerEvent = 'volumechange'; vjs.VolumeBar.prototype.createEl = function(){ return vjs.Slider.prototype.createEl.call(this, 'div', { className: 'vjs-volume-bar', 'aria-label': 'volume level' }); }; vjs.VolumeBar.prototype.onMouseMove = function(event) { if (this.player_.muted()) { this.player_.muted(false); } this.player_.volume(this.calculateDistance(event)); }; vjs.VolumeBar.prototype.getPercent = function(){ if (this.player_.muted()) { return 0; } else { return this.player_.volume(); } }; vjs.VolumeBar.prototype.stepForward = function(){ this.player_.volume(this.player_.volume() + 0.1); }; vjs.VolumeBar.prototype.stepBack = function(){ this.player_.volume(this.player_.volume() - 0.1); }; /** * Shows volume level * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.VolumeLevel = vjs.Component.extend({ /** @constructor */ init: function(player, options){ vjs.Component.call(this, player, options); } }); vjs.VolumeLevel.prototype.createEl = function(){ return vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-volume-level', innerHTML: '<span class="vjs-control-text"></span>' }); }; /** * The volume handle can be dragged to adjust the volume level * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.VolumeHandle = vjs.SliderHandle.extend(); vjs.VolumeHandle.prototype.defaultValue = '00:00'; /** @inheritDoc */ vjs.VolumeHandle.prototype.createEl = function(){ return vjs.SliderHandle.prototype.createEl.call(this, 'div', { className: 'vjs-volume-handle' }); }; /** * A button component for muting the audio * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.MuteToggle = vjs.Button.extend({ /** @constructor */ init: function(player, options){ vjs.Button.call(this, player, options); this.on(player, 'volumechange', this.update); // hide mute toggle if the current tech doesn't support volume control if (player.tech && player.tech['featuresVolumeControl'] === false) { this.addClass('vjs-hidden'); } this.on(player, 'loadstart', function(){ if (player.tech['featuresVolumeControl'] === false) { this.addClass('vjs-hidden'); } else { this.removeClass('vjs-hidden'); } }); } }); vjs.MuteToggle.prototype.createEl = function(){ return vjs.Button.prototype.createEl.call(this, 'div', { className: 'vjs-mute-control vjs-control', innerHTML: '<div><span class="vjs-control-text">' + this.localize('Mute') + '</span></div>' }); }; vjs.MuteToggle.prototype.onClick = function(){ this.player_.muted( this.player_.muted() ? false : true ); }; vjs.MuteToggle.prototype.update = function(){ var vol = this.player_.volume(), level = 3; if (vol === 0 || this.player_.muted()) { level = 0; } else if (vol < 0.33) { level = 1; } else if (vol < 0.67) { level = 2; } // Don't rewrite the button text if the actual text doesn't change. // This causes unnecessary and confusing information for screen reader users. // This check is needed because this function gets called every time the volume level is changed. if(this.player_.muted()){ if(this.el_.children[0].children[0].innerHTML!=this.localize('Unmute')){ this.el_.children[0].children[0].innerHTML = this.localize('Unmute'); // change the button text to "Unmute" } } else { if(this.el_.children[0].children[0].innerHTML!=this.localize('Mute')){ this.el_.children[0].children[0].innerHTML = this.localize('Mute'); // change the button text to "Mute" } } /* TODO improve muted icon classes */ for (var i = 0; i < 4; i++) { vjs.removeClass(this.el_, 'vjs-vol-'+i); } vjs.addClass(this.el_, 'vjs-vol-'+level); }; /** * Menu button with a popup for showing the volume slider. * @constructor */ vjs.VolumeMenuButton = vjs.MenuButton.extend({ /** @constructor */ init: function(player, options){ vjs.MenuButton.call(this, player, options); // Same listeners as MuteToggle this.on(player, 'volumechange', this.update); // hide mute toggle if the current tech doesn't support volume control if (player.tech && player.tech['featuresVolumeControl'] === false) { this.addClass('vjs-hidden'); } this.on(player, 'loadstart', function(){ if (player.tech['featuresVolumeControl'] === false) { this.addClass('vjs-hidden'); } else { this.removeClass('vjs-hidden'); } }); this.addClass('vjs-menu-button'); } }); vjs.VolumeMenuButton.prototype.createMenu = function(){ var menu = new vjs.Menu(this.player_, { contentElType: 'div' }); var vc = new vjs.VolumeBar(this.player_, this.options_['volumeBar']); vc.on('focus', function() { menu.lockShowing(); }); vc.on('blur', function() { menu.unlockShowing(); }); menu.addChild(vc); return menu; }; vjs.VolumeMenuButton.prototype.onClick = function(){ vjs.MuteToggle.prototype.onClick.call(this); vjs.MenuButton.prototype.onClick.call(this); }; vjs.VolumeMenuButton.prototype.createEl = function(){ return vjs.Button.prototype.createEl.call(this, 'div', { className: 'vjs-volume-menu-button vjs-menu-button vjs-control', innerHTML: '<div><span class="vjs-control-text">' + this.localize('Mute') + '</span></div>' }); }; vjs.VolumeMenuButton.prototype.update = vjs.MuteToggle.prototype.update; /** * The component for controlling the playback rate * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.PlaybackRateMenuButton = vjs.MenuButton.extend({ /** @constructor */ init: function(player, options){ vjs.MenuButton.call(this, player, options); this.updateVisibility(); this.updateLabel(); this.on(player, 'loadstart', this.updateVisibility); this.on(player, 'ratechange', this.updateLabel); } }); vjs.PlaybackRateMenuButton.prototype.buttonText = 'Playback Rate'; vjs.PlaybackRateMenuButton.prototype.className = 'vjs-playback-rate'; vjs.PlaybackRateMenuButton.prototype.createEl = function(){ var el = vjs.MenuButton.prototype.createEl.call(this); this.labelEl_ = vjs.createEl('div', { className: 'vjs-playback-rate-value', innerHTML: 1.0 }); el.appendChild(this.labelEl_); return el; }; // Menu creation vjs.PlaybackRateMenuButton.prototype.createMenu = function(){ var menu = new vjs.Menu(this.player()); var rates = this.player().options()['playbackRates']; if (rates) { for (var i = rates.length - 1; i >= 0; i--) { menu.addChild( new vjs.PlaybackRateMenuItem(this.player(), { 'rate': rates[i] + 'x'}) ); } } return menu; }; vjs.PlaybackRateMenuButton.prototype.updateARIAAttributes = function(){ // Current playback rate this.el().setAttribute('aria-valuenow', this.player().playbackRate()); }; vjs.PlaybackRateMenuButton.prototype.onClick = function(){ // select next rate option var currentRate = this.player().playbackRate(); var rates = this.player().options()['playbackRates']; // this will select first one if the last one currently selected var newRate = rates[0]; for (var i = 0; i <rates.length ; i++) { if (rates[i] > currentRate) { newRate = rates[i]; break; } } this.player().playbackRate(newRate); }; vjs.PlaybackRateMenuButton.prototype.playbackRateSupported = function(){ return this.player().tech && this.player().tech['featuresPlaybackRate'] && this.player().options()['playbackRates'] && this.player().options()['playbackRates'].length > 0 ; }; /** * Hide playback rate controls when they're no playback rate options to select */ vjs.PlaybackRateMenuButton.prototype.updateVisibility = function(){ if (this.playbackRateSupported()) { this.removeClass('vjs-hidden'); } else { this.addClass('vjs-hidden'); } }; /** * Update button label when rate changed */ vjs.PlaybackRateMenuButton.prototype.updateLabel = function(){ if (this.playbackRateSupported()) { this.labelEl_.innerHTML = this.player().playbackRate() + 'x'; } }; /** * The specific menu item type for selecting a playback rate * * @constructor */ vjs.PlaybackRateMenuItem = vjs.MenuItem.extend({ contentElType: 'button', /** @constructor */ init: function(player, options){ var label = this.label = options['rate']; var rate = this.rate = parseFloat(label, 10); // Modify options for parent MenuItem class's init. options['label'] = label; options['selected'] = rate === 1; vjs.MenuItem.call(this, player, options); this.on(player, 'ratechange', this.update); } }); vjs.PlaybackRateMenuItem.prototype.onClick = function(){ vjs.MenuItem.prototype.onClick.call(this); this.player().playbackRate(this.rate); }; vjs.PlaybackRateMenuItem.prototype.update = function(){ this.selected(this.player().playbackRate() == this.rate); }; /* Poster Image ================================================================================ */ /** * The component that handles showing the poster image. * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.PosterImage = vjs.Button.extend({ /** @constructor */ init: function(player, options){ vjs.Button.call(this, player, options); this.update(); player.on('posterchange', vjs.bind(this, this.update)); } }); /** * Clean up the poster image */ vjs.PosterImage.prototype.dispose = function(){ this.player().off('posterchange', this.update); vjs.Button.prototype.dispose.call(this); }; /** * Create the poster image element * @return {Element} */ vjs.PosterImage.prototype.createEl = function(){ var el = vjs.createEl('div', { className: 'vjs-poster', // Don't want poster to be tabbable. tabIndex: -1 }); // To ensure the poster image resizes while maintaining its original aspect // ratio, use a div with `background-size` when available. For browsers that // do not support `background-size` (e.g. IE8), fall back on using a regular // img element. if (!vjs.BACKGROUND_SIZE_SUPPORTED) { this.fallbackImg_ = vjs.createEl('img'); el.appendChild(this.fallbackImg_); } return el; }; /** * Event handler for updates to the player's poster source */ vjs.PosterImage.prototype.update = function(){ var url = this.player().poster(); this.setSrc(url); // If there's no poster source we should display:none on this component // so it's not still clickable or right-clickable if (url) { // Remove the display style property that hide() adds // as opposed to show() which sets display to block // In the future it might be worth creating an `unhide` component method this.el_.style.display = ''; } else { this.hide(); } }; /** * Set the poster source depending on the display method */ vjs.PosterImage.prototype.setSrc = function(url){ var backgroundImage; if (this.fallbackImg_) { this.fallbackImg_.src = url; } else { backgroundImage = ''; // Any falsey values should stay as an empty string, otherwise // this will throw an extra error if (url) { backgroundImage = 'url("' + url + '")'; } this.el_.style.backgroundImage = backgroundImage; } }; /** * Event handler for clicks on the poster image */ vjs.PosterImage.prototype.onClick = function(){ // We don't want a click to trigger playback when controls are disabled // but CSS should be hiding the poster to prevent that from happening this.player_.play(); }; /* Loading Spinner ================================================================================ */ /** * Loading spinner for waiting events * @param {vjs.Player|Object} player * @param {Object=} options * @class * @constructor */ vjs.LoadingSpinner = vjs.Component.extend({ /** @constructor */ init: function(player, options){ vjs.Component.call(this, player, options); // MOVING DISPLAY HANDLING TO CSS // player.on('canplay', vjs.bind(this, this.hide)); // player.on('canplaythrough', vjs.bind(this, this.hide)); // player.on('playing', vjs.bind(this, this.hide)); // player.on('seeking', vjs.bind(this, this.show)); // in some browsers seeking does not trigger the 'playing' event, // so we also need to trap 'seeked' if we are going to set a // 'seeking' event // player.on('seeked', vjs.bind(this, this.hide)); // player.on('ended', vjs.bind(this, this.hide)); // Not showing spinner on stalled any more. Browsers may stall and then not trigger any events that would remove the spinner. // Checked in Chrome 16 and Safari 5.1.2. http://help.videojs.com/discussions/problems/883-why-is-the-download-progress-showing // player.on('stalled', vjs.bind(this, this.show)); // player.on('waiting', vjs.bind(this, this.show)); } }); vjs.LoadingSpinner.prototype.createEl = function(){ return vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-loading-spinner' }); }; /* Big Play Button ================================================================================ */ /** * Initial play button. Shows before the video has played. The hiding of the * big play button is done via CSS and player states. * @param {vjs.Player|Object} player * @param {Object=} options * @class * @constructor */ vjs.BigPlayButton = vjs.Button.extend(); vjs.BigPlayButton.prototype.createEl = function(){ return vjs.Button.prototype.createEl.call(this, 'div', { className: 'vjs-big-play-button', innerHTML: '<span aria-hidden="true"></span>', 'aria-label': 'play video' }); }; vjs.BigPlayButton.prototype.onClick = function(){ this.player_.play(); }; /** * Display that an error has occurred making the video unplayable * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.ErrorDisplay = vjs.Component.extend({ init: function(player, options){ vjs.Component.call(this, player, options); this.update(); this.on(player, 'error', this.update); } }); vjs.ErrorDisplay.prototype.createEl = function(){ var el = vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-error-display' }); this.contentEl_ = vjs.createEl('div'); el.appendChild(this.contentEl_); return el; }; vjs.ErrorDisplay.prototype.update = function(){ if (this.player().error()) { this.contentEl_.innerHTML = this.localize(this.player().error().message); } }; /** * @fileoverview Media Technology Controller - Base class for media playback * technology controllers like Flash and HTML5 */ /** * Base class for media (HTML5 Video, Flash) controllers * @param {vjs.Player|Object} player Central player instance * @param {Object=} options Options object * @constructor */ vjs.MediaTechController = vjs.Component.extend({ /** @constructor */ init: function(player, options, ready){ options = options || {}; // we don't want the tech to report user activity automatically. // This is done manually in addControlsListeners options.reportTouchActivity = false; vjs.Component.call(this, player, options, ready); // Manually track progress in cases where the browser/flash player doesn't report it. if (!this['featuresProgressEvents']) { this.manualProgressOn(); } // Manually track timeupdates in cases where the browser/flash player doesn't report it. if (!this['featuresTimeupdateEvents']) { this.manualTimeUpdatesOn(); } this.initControlsListeners(); } }); /** * Set up click and touch listeners for the playback element * On desktops, a click on the video itself will toggle playback, * on a mobile device a click on the video toggles controls. * (toggling controls is done by toggling the user state between active and * inactive) * * A tap can signal that a user has become active, or has become inactive * e.g. a quick tap on an iPhone movie should reveal the controls. Another * quick tap should hide them again (signaling the user is in an inactive * viewing state) * * In addition to this, we still want the user to be considered inactive after * a few seconds of inactivity. * * Note: the only part of iOS interaction we can't mimic with this setup * is a touch and hold on the video element counting as activity in order to * keep the controls showing, but that shouldn't be an issue. A touch and hold on * any controls will still keep the user active */ vjs.MediaTechController.prototype.initControlsListeners = function(){ var player, activateControls; player = this.player(); activateControls = function(){ if (player.controls() && !player.usingNativeControls()) { this.addControlsListeners(); } }; // Set up event listeners once the tech is ready and has an element to apply // listeners to this.ready(activateControls); this.on(player, 'controlsenabled', activateControls); this.on(player, 'controlsdisabled', this.removeControlsListeners); // if we're loading the playback object after it has started loading or playing the // video (often with autoplay on) then the loadstart event has already fired and we // need to fire it manually because many things rely on it. // Long term we might consider how we would do this for other events like 'canplay' // that may also have fired. this.ready(function(){ if (this.networkState && this.networkState() > 0) { this.player().trigger('loadstart'); } }); }; vjs.MediaTechController.prototype.addControlsListeners = function(){ var userWasActive; // Some browsers (Chrome & IE) don't trigger a click on a flash swf, but do // trigger mousedown/up. // http://stackoverflow.com/questions/1444562/javascript-onclick-event-over-flash-object // Any touch events are set to block the mousedown event from happening this.on('mousedown', this.onClick); // If the controls were hidden we don't want that to change without a tap event // so we'll check if the controls were already showing before reporting user // activity this.on('touchstart', function(event) { userWasActive = this.player_.userActive(); }); this.on('touchmove', function(event) { if (userWasActive){ this.player().reportUserActivity(); } }); this.on('touchend', function(event) { // Stop the mouse events from also happening event.preventDefault(); }); // Turn on component tap events this.emitTapEvents(); // The tap listener needs to come after the touchend listener because the tap // listener cancels out any reportedUserActivity when setting userActive(false) this.on('tap', this.onTap); }; /** * Remove the listeners used for click and tap controls. This is needed for * toggling to controls disabled, where a tap/touch should do nothing. */ vjs.MediaTechController.prototype.removeControlsListeners = function(){ // We don't want to just use `this.off()` because there might be other needed // listeners added by techs that extend this. this.off('tap'); this.off('touchstart'); this.off('touchmove'); this.off('touchleave'); this.off('touchcancel'); this.off('touchend'); this.off('click'); this.off('mousedown'); }; /** * Handle a click on the media element. By default will play/pause the media. */ vjs.MediaTechController.prototype.onClick = function(event){ // We're using mousedown to detect clicks thanks to Flash, but mousedown // will also be triggered with right-clicks, so we need to prevent that if (event.button !== 0) return; // When controls are disabled a click should not toggle playback because // the click is considered a control if (this.player().controls()) { if (this.player().paused()) { this.player().play(); } else { this.player().pause(); } } }; /** * Handle a tap on the media element. By default it will toggle the user * activity state, which hides and shows the controls. */ vjs.MediaTechController.prototype.onTap = function(){ this.player().userActive(!this.player().userActive()); }; /* Fallbacks for unsupported event types ================================================================================ */ // Manually trigger progress events based on changes to the buffered amount // Many flash players and older HTML5 browsers don't send progress or progress-like events vjs.MediaTechController.prototype.manualProgressOn = function(){ this.manualProgress = true; // Trigger progress watching when a source begins loading this.trackProgress(); }; vjs.MediaTechController.prototype.manualProgressOff = function(){ this.manualProgress = false; this.stopTrackingProgress(); }; vjs.MediaTechController.prototype.trackProgress = function(){ this.progressInterval = this.setInterval(function(){ // Don't trigger unless buffered amount is greater than last time var bufferedPercent = this.player().bufferedPercent(); if (this.bufferedPercent_ != bufferedPercent) { this.player().trigger('progress'); } this.bufferedPercent_ = bufferedPercent; if (bufferedPercent === 1) { this.stopTrackingProgress(); } }, 500); }; vjs.MediaTechController.prototype.stopTrackingProgress = function(){ this.clearInterval(this.progressInterval); }; /*! Time Tracking -------------------------------------------------------------- */ vjs.MediaTechController.prototype.manualTimeUpdatesOn = function(){ var player = this.player_; this.manualTimeUpdates = true; this.on(player, 'play', this.trackCurrentTime); this.on(player, 'pause', this.stopTrackingCurrentTime); // timeupdate is also called by .currentTime whenever current time is set // Watch for native timeupdate event this.one('timeupdate', function(){ // Update known progress support for this playback technology this['featuresTimeupdateEvents'] = true; // Turn off manual progress tracking this.manualTimeUpdatesOff(); }); }; vjs.MediaTechController.prototype.manualTimeUpdatesOff = function(){ this.manualTimeUpdates = false; this.stopTrackingCurrentTime(); this.off('play', this.trackCurrentTime); this.off('pause', this.stopTrackingCurrentTime); }; vjs.MediaTechController.prototype.trackCurrentTime = function(){ if (this.currentTimeInterval) { this.stopTrackingCurrentTime(); } this.currentTimeInterval = this.setInterval(function(){ this.player().trigger('timeupdate'); }, 250); // 42 = 24 fps // 250 is what Webkit uses // FF uses 15 }; // Turn off play progress tracking (when paused or dragging) vjs.MediaTechController.prototype.stopTrackingCurrentTime = function(){ this.clearInterval(this.currentTimeInterval); // #1002 - if the video ends right before the next timeupdate would happen, // the progress bar won't make it all the way to the end this.player().trigger('timeupdate'); }; vjs.MediaTechController.prototype.dispose = function() { // Turn off any manual progress or timeupdate tracking if (this.manualProgress) { this.manualProgressOff(); } if (this.manualTimeUpdates) { this.manualTimeUpdatesOff(); } vjs.Component.prototype.dispose.call(this); }; vjs.MediaTechController.prototype.setCurrentTime = function() { // improve the accuracy of manual timeupdates if (this.manualTimeUpdates) { this.player().trigger('timeupdate'); } }; /** * Provide a default setPoster method for techs * * Poster support for techs should be optional, so we don't want techs to * break if they don't have a way to set a poster. */ vjs.MediaTechController.prototype.setPoster = function(){}; vjs.MediaTechController.prototype['featuresVolumeControl'] = true; // Resizing plugins using request fullscreen reloads the plugin vjs.MediaTechController.prototype['featuresFullscreenResize'] = false; vjs.MediaTechController.prototype['featuresPlaybackRate'] = false; // Optional events that we can manually mimic with timers // currently not triggered by video-js-swf vjs.MediaTechController.prototype['featuresProgressEvents'] = false; vjs.MediaTechController.prototype['featuresTimeupdateEvents'] = false; /** * A functional mixin for techs that want to use the Source Handler pattern. * * ##### EXAMPLE: * * videojs.MediaTechController.withSourceHandlers.call(MyTech); * */ vjs.MediaTechController.withSourceHandlers = function(Tech){ /** * Register a source handler * Source handlers are scripts for handling specific formats. * The source handler pattern is used for adaptive formats (HLS, DASH) that * manually load video data and feed it into a Source Buffer (Media Source Extensions) * @param {Function} handler The source handler * @param {Boolean} first Register it before any existing handlers */ Tech.registerSourceHandler = function(handler, index){ var handlers = Tech.sourceHandlers; if (!handlers) { handlers = Tech.sourceHandlers = []; } if (index === undefined) { // add to the end of the list index = handlers.length; } handlers.splice(index, 0, handler); }; /** * Return the first source handler that supports the source * TODO: Answer question: should 'probably' be prioritized over 'maybe' * @param {Object} source The source object * @returns {Object} The first source handler that supports the source * @returns {null} Null if no source handler is found */ Tech.selectSourceHandler = function(source){ var handlers = Tech.sourceHandlers || [], can; for (var i = 0; i < handlers.length; i++) { can = handlers[i].canHandleSource(source); if (can) { return handlers[i]; } } return null; }; /** * Check if the tech can support the given source * @param {Object} srcObj The source object * @return {String} 'probably', 'maybe', or '' (empty string) */ Tech.canPlaySource = function(srcObj){ var sh = Tech.selectSourceHandler(srcObj); if (sh) { return sh.canHandleSource(srcObj); } return ''; }; /** * Create a function for setting the source using a source object * and source handlers. * Should never be called unless a source handler was found. * @param {Object} source A source object with src and type keys * @return {vjs.MediaTechController} self */ Tech.prototype.setSource = function(source){ var sh = Tech.selectSourceHandler(source); // Dispose any existing source handler this.disposeSourceHandler(); this.off('dispose', this.disposeSourceHandler); this.currentSource_ = source; this.sourceHandler_ = sh.handleSource(source, this); this.on('dispose', this.disposeSourceHandler); return this; }; /** * Clean up any existing source handler */ Tech.prototype.disposeSourceHandler = function(){ if (this.sourceHandler_ && this.sourceHandler_.dispose) { this.sourceHandler_.dispose(); } }; }; /** * @fileoverview HTML5 Media Controller - Wrapper for HTML5 Media API */ /** * HTML5 Media Controller - Wrapper for HTML5 Media API * @param {vjs.Player|Object} player * @param {Object=} options * @param {Function=} ready * @constructor */ vjs.Html5 = vjs.MediaTechController.extend({ /** @constructor */ init: function(player, options, ready){ vjs.MediaTechController.call(this, player, options, ready); this.setupTriggers(); var source = options['source']; // Set the source if one is provided // 1) Check if the source is new (if not, we want to keep the original so playback isn't interrupted) // 2) Check to see if the network state of the tag was failed at init, and if so, reset the source // anyway so the error gets fired. if (source && (this.el_.currentSrc !== source.src || (player.tag && player.tag.initNetworkState_ === 3))) { this.setSource(source); } // Determine if native controls should be used // Our goal should be to get the custom controls on mobile solid everywhere // so we can remove this all together. Right now this will block custom // controls on touch enabled laptops like the Chrome Pixel if (vjs.TOUCH_ENABLED && player.options()['nativeControlsForTouch'] === true) { this.useNativeControls(); } // Chrome and Safari both have issues with autoplay. // In Safari (5.1.1), when we move the video element into the container div, autoplay doesn't work. // In Chrome (15), if you have autoplay + a poster + no controls, the video gets hidden (but audio plays) // This fixes both issues. Need to wait for API, so it updates displays correctly player.ready(function(){ if (this.tag && this.options_['autoplay'] && this.paused()) { delete this.tag['poster']; // Chrome Fix. Fixed in Chrome v16. this.play(); } }); this.triggerReady(); } }); vjs.Html5.prototype.dispose = function(){ vjs.Html5.disposeMediaElement(this.el_); vjs.MediaTechController.prototype.dispose.call(this); }; vjs.Html5.prototype.createEl = function(){ var player = this.player_, // If possible, reuse original tag for HTML5 playback technology element el = player.tag, newEl, clone; // Check if this browser supports moving the element into the box. // On the iPhone video will break if you move the element, // So we have to create a brand new element. if (!el || this['movingMediaElementInDOM'] === false) { // If the original tag is still there, clone and remove it. if (el) { clone = el.cloneNode(false); vjs.Html5.disposeMediaElement(el); el = clone; player.tag = null; } else { el = vjs.createEl('video'); vjs.setElementAttributes(el, vjs.obj.merge(player.tagAttributes || {}, { id:player.id() + '_html5_api', 'class':'vjs-tech' }) ); } // associate the player with the new tag el['player'] = player; vjs.insertFirst(el, player.el()); } // Update specific tag settings, in case they were overridden var settingsAttrs = ['autoplay','preload','loop','muted']; for (var i = settingsAttrs.length - 1; i >= 0; i--) { var attr = settingsAttrs[i]; var overwriteAttrs = {}; if (typeof player.options_[attr] !== 'undefined') { overwriteAttrs[attr] = player.options_[attr]; } vjs.setElementAttributes(el, overwriteAttrs); } return el; // jenniisawesome = true; }; // Make video events trigger player events // May seem verbose here, but makes other APIs possible. // Triggers removed using this.off when disposed vjs.Html5.prototype.setupTriggers = function(){ for (var i = vjs.Html5.Events.length - 1; i >= 0; i--) { this.on(vjs.Html5.Events[i], this.eventHandler); } }; vjs.Html5.prototype.eventHandler = function(evt){ // In the case of an error on the video element, set the error prop // on the player and let the player handle triggering the event. On // some platforms, error events fire that do not cause the error // property on the video element to be set. See #1465 for an example. if (evt.type == 'error' && this.error()) { this.player().error(this.error().code); // in some cases we pass the event directly to the player } else { // No need for media events to bubble up. evt.bubbles = false; this.player().trigger(evt); } }; vjs.Html5.prototype.useNativeControls = function(){ var tech, player, controlsOn, controlsOff, cleanUp; tech = this; player = this.player(); // If the player controls are enabled turn on the native controls tech.setControls(player.controls()); // Update the native controls when player controls state is updated controlsOn = function(){ tech.setControls(true); }; controlsOff = function(){ tech.setControls(false); }; player.on('controlsenabled', controlsOn); player.on('controlsdisabled', controlsOff); // Clean up when not using native controls anymore cleanUp = function(){ player.off('controlsenabled', controlsOn); player.off('controlsdisabled', controlsOff); }; tech.on('dispose', cleanUp); player.on('usingcustomcontrols', cleanUp); // Update the state of the player to using native controls player.usingNativeControls(true); }; vjs.Html5.prototype.play = function(){ this.el_.play(); }; vjs.Html5.prototype.pause = function(){ this.el_.pause(); }; vjs.Html5.prototype.paused = function(){ return this.el_.paused; }; vjs.Html5.prototype.currentTime = function(){ return this.el_.currentTime; }; vjs.Html5.prototype.setCurrentTime = function(seconds){ try { this.el_.currentTime = seconds; } catch(e) { vjs.log(e, 'Video is not ready. (Video.js)'); // this.warning(VideoJS.warnings.videoNotReady); } }; vjs.Html5.prototype.duration = function(){ return this.el_.duration || 0; }; vjs.Html5.prototype.buffered = function(){ return this.el_.buffered; }; vjs.Html5.prototype.volume = function(){ return this.el_.volume; }; vjs.Html5.prototype.setVolume = function(percentAsDecimal){ this.el_.volume = percentAsDecimal; }; vjs.Html5.prototype.muted = function(){ return this.el_.muted; }; vjs.Html5.prototype.setMuted = function(muted){ this.el_.muted = muted; }; vjs.Html5.prototype.width = function(){ return this.el_.offsetWidth; }; vjs.Html5.prototype.height = function(){ return this.el_.offsetHeight; }; vjs.Html5.prototype.supportsFullScreen = function(){ if (typeof this.el_.webkitEnterFullScreen == 'function') { // Seems to be broken in Chromium/Chrome && Safari in Leopard if (/Android/.test(vjs.USER_AGENT) || !/Chrome|Mac OS X 10.5/.test(vjs.USER_AGENT)) { return true; } } return false; }; vjs.Html5.prototype.enterFullScreen = function(){ var video = this.el_; if ('webkitDisplayingFullscreen' in video) { this.one('webkitbeginfullscreen', function() { this.player_.isFullscreen(true); this.one('webkitendfullscreen', function() { this.player_.isFullscreen(false); this.player_.trigger('fullscreenchange'); }); this.player_.trigger('fullscreenchange'); }); } if (video.paused && video.networkState <= video.HAVE_METADATA) { // attempt to prime the video element for programmatic access // this isn't necessary on the desktop but shouldn't hurt this.el_.play(); // playing and pausing synchronously during the transition to fullscreen // can get iOS ~6.1 devices into a play/pause loop this.setTimeout(function(){ video.pause(); video.webkitEnterFullScreen(); }, 0); } else { video.webkitEnterFullScreen(); } }; vjs.Html5.prototype.exitFullScreen = function(){ this.el_.webkitExitFullScreen(); }; vjs.Html5.prototype.src = function(src) { if (src === undefined) { return this.el_.src; } else { // Setting src through `src` instead of `setSrc` will be deprecated this.setSrc(src); } }; vjs.Html5.prototype.setSrc = function(src) { this.el_.src = src; }; vjs.Html5.prototype.load = function(){ this.el_.load(); }; vjs.Html5.prototype.currentSrc = function(){ return this.el_.currentSrc; }; vjs.Html5.prototype.poster = function(){ return this.el_.poster; }; vjs.Html5.prototype.setPoster = function(val){ this.el_.poster = val; }; vjs.Html5.prototype.preload = function(){ return this.el_.preload; }; vjs.Html5.prototype.setPreload = function(val){ this.el_.preload = val; }; vjs.Html5.prototype.autoplay = function(){ return this.el_.autoplay; }; vjs.Html5.prototype.setAutoplay = function(val){ this.el_.autoplay = val; }; vjs.Html5.prototype.controls = function(){ return this.el_.controls; }; vjs.Html5.prototype.setControls = function(val){ this.el_.controls = !!val; }; vjs.Html5.prototype.loop = function(){ return this.el_.loop; }; vjs.Html5.prototype.setLoop = function(val){ this.el_.loop = val; }; vjs.Html5.prototype.error = function(){ return this.el_.error; }; vjs.Html5.prototype.seeking = function(){ return this.el_.seeking; }; vjs.Html5.prototype.ended = function(){ return this.el_.ended; }; vjs.Html5.prototype.defaultMuted = function(){ return this.el_.defaultMuted; }; vjs.Html5.prototype.playbackRate = function(){ return this.el_.playbackRate; }; vjs.Html5.prototype.setPlaybackRate = function(val){ this.el_.playbackRate = val; }; vjs.Html5.prototype.networkState = function(){ return this.el_.networkState; }; /** * Check if HTML5 video is supported by this browser/device * @return {Boolean} */ vjs.Html5.isSupported = function(){ // IE9 with no Media Player is a LIAR! (#984) try { vjs.TEST_VID['volume'] = 0.5; } catch (e) { return false; } return !!vjs.TEST_VID.canPlayType; }; // Add Source Handler pattern functions to this tech vjs.MediaTechController.withSourceHandlers(vjs.Html5); /** * The default native source handler. * This simply passes the source to the video element. Nothing fancy. * @param {Object} source The source object * @param {vjs.Html5} tech The instance of the HTML5 tech */ vjs.Html5.nativeSourceHandler = {}; /** * Check if the video element can handle the source natively * @param {Object} source The source object * @return {String} 'probably', 'maybe', or '' (empty string) */ vjs.Html5.nativeSourceHandler.canHandleSource = function(source){ var ext; function canPlayType(type){ // IE9 on Windows 7 without MediaPlayer throws an error here // https://github.com/videojs/video.js/issues/519 try { return !!vjs.TEST_VID.canPlayType(type); } catch(e) { return ''; } } // If a type was provided we should rely on that if (source.type) { return canPlayType(source.type); } else { // If no type, fall back to checking 'video/[EXTENSION]' ext = source.src.match(/\.([^\/\?]+)(\?[^\/]+)?$/i)[1]; return canPlayType('video/'+ext); } }; /** * Pass the source to the video element * Adaptive source handlers will have more complicated workflows before passing * video data to the video element * @param {Object} source The source object * @param {vjs.Html5} tech The instance of the Html5 tech */ vjs.Html5.nativeSourceHandler.handleSource = function(source, tech){ tech.setSrc(source.src); }; /** * Clean up the source handler when disposing the player or switching sources.. * (no cleanup is needed when supporting the format natively) */ vjs.Html5.nativeSourceHandler.dispose = function(){}; // Register the native source handler vjs.Html5.registerSourceHandler(vjs.Html5.nativeSourceHandler); /** * Check if the volume can be changed in this browser/device. * Volume cannot be changed in a lot of mobile devices. * Specifically, it can't be changed from 1 on iOS. * @return {Boolean} */ vjs.Html5.canControlVolume = function(){ var volume = vjs.TEST_VID.volume; vjs.TEST_VID.volume = (volume / 2) + 0.1; return volume !== vjs.TEST_VID.volume; }; /** * Check if playbackRate is supported in this browser/device. * @return {[type]} [description] */ vjs.Html5.canControlPlaybackRate = function(){ var playbackRate = vjs.TEST_VID.playbackRate; vjs.TEST_VID.playbackRate = (playbackRate / 2) + 0.1; return playbackRate !== vjs.TEST_VID.playbackRate; }; /** * Set the tech's volume control support status * @type {Boolean} */ vjs.Html5.prototype['featuresVolumeControl'] = vjs.Html5.canControlVolume(); /** * Set the tech's playbackRate support status * @type {Boolean} */ vjs.Html5.prototype['featuresPlaybackRate'] = vjs.Html5.canControlPlaybackRate(); /** * Set the tech's status on moving the video element. * In iOS, if you move a video element in the DOM, it breaks video playback. * @type {Boolean} */ vjs.Html5.prototype['movingMediaElementInDOM'] = !vjs.IS_IOS; /** * Set the the tech's fullscreen resize support status. * HTML video is able to automatically resize when going to fullscreen. * (No longer appears to be used. Can probably be removed.) */ vjs.Html5.prototype['featuresFullscreenResize'] = true; /** * Set the tech's progress event support status * (this disables the manual progress events of the MediaTechController) */ vjs.Html5.prototype['featuresProgressEvents'] = true; // HTML5 Feature detection and Device Fixes --------------------------------- // (function() { var canPlayType, mpegurlRE = /^application\/(?:x-|vnd\.apple\.)mpegurl/i, mp4RE = /^video\/mp4/i; vjs.Html5.patchCanPlayType = function() { // Android 4.0 and above can play HLS to some extent but it reports being unable to do so if (vjs.ANDROID_VERSION >= 4.0) { if (!canPlayType) { canPlayType = vjs.TEST_VID.constructor.prototype.canPlayType; } vjs.TEST_VID.constructor.prototype.canPlayType = function(type) { if (type && mpegurlRE.test(type)) { return 'maybe'; } return canPlayType.call(this, type); }; } // Override Android 2.2 and less canPlayType method which is broken if (vjs.IS_OLD_ANDROID) { if (!canPlayType) { canPlayType = vjs.TEST_VID.constructor.prototype.canPlayType; } vjs.TEST_VID.constructor.prototype.canPlayType = function(type){ if (type && mp4RE.test(type)) { return 'maybe'; } return canPlayType.call(this, type); }; } }; vjs.Html5.unpatchCanPlayType = function() { var r = vjs.TEST_VID.constructor.prototype.canPlayType; vjs.TEST_VID.constructor.prototype.canPlayType = canPlayType; canPlayType = null; return r; }; // by default, patch the video element vjs.Html5.patchCanPlayType(); })(); // List of all HTML5 events (various uses). vjs.Html5.Events = 'loadstart,suspend,abort,error,emptied,stalled,loadedmetadata,loadeddata,canplay,canplaythrough,playing,waiting,seeking,seeked,ended,durationchange,timeupdate,progress,play,pause,ratechange,volumechange'.split(','); vjs.Html5.disposeMediaElement = function(el){ if (!el) { return; } el['player'] = null; if (el.parentNode) { el.parentNode.removeChild(el); } // remove any child track or source nodes to prevent their loading while(el.hasChildNodes()) { el.removeChild(el.firstChild); } // remove any src reference. not setting `src=''` because that causes a warning // in firefox el.removeAttribute('src'); // force the media element to update its loading state by calling load() // however IE on Windows 7N has a bug that throws an error so need a try/catch (#793) if (typeof el.load === 'function') { // wrapping in an iife so it's not deoptimized (#1060#discussion_r10324473) (function() { try { el.load(); } catch (e) { // not supported } })(); } }; /** * @fileoverview VideoJS-SWF - Custom Flash Player with HTML5-ish API * https://github.com/zencoder/video-js-swf * Not using setupTriggers. Using global onEvent func to distribute events */ /** * Flash Media Controller - Wrapper for fallback SWF API * * @param {vjs.Player} player * @param {Object=} options * @param {Function=} ready * @constructor */ vjs.Flash = vjs.MediaTechController.extend({ /** @constructor */ init: function(player, options, ready){ vjs.MediaTechController.call(this, player, options, ready); var source = options['source'], // Which element to embed in parentEl = options['parentEl'], // Create a temporary element to be replaced by swf object placeHolder = this.el_ = vjs.createEl('div', { id: player.id() + '_temp_flash' }), // Generate ID for swf object objId = player.id()+'_flash_api', // Store player options in local var for optimization // TODO: switch to using player methods instead of options // e.g. player.autoplay(); playerOptions = player.options_, // Merge default flashvars with ones passed in to init flashVars = vjs.obj.merge({ // SWF Callback Functions 'readyFunction': 'videojs.Flash.onReady', 'eventProxyFunction': 'videojs.Flash.onEvent', 'errorEventProxyFunction': 'videojs.Flash.onError', // Player Settings 'autoplay': playerOptions.autoplay, 'preload': playerOptions.preload, 'loop': playerOptions.loop, 'muted': playerOptions.muted }, options['flashVars']), // Merge default parames with ones passed in params = vjs.obj.merge({ 'wmode': 'opaque', // Opaque is needed to overlay controls, but can affect playback performance 'bgcolor': '#000000' // Using bgcolor prevents a white flash when the object is loading }, options['params']), // Merge default attributes with ones passed in attributes = vjs.obj.merge({ 'id': objId, 'name': objId, // Both ID and Name needed or swf to identify itself 'class': 'vjs-tech' }, options['attributes']) ; // If source was supplied pass as a flash var. if (source) { this.ready(function(){ this.setSource(source); }); } // Add placeholder to player div vjs.insertFirst(placeHolder, parentEl); // Having issues with Flash reloading on certain page actions (hide/resize/fullscreen) in certain browsers // This allows resetting the playhead when we catch the reload if (options['startTime']) { this.ready(function(){ this.load(); this.play(); this['currentTime'](options['startTime']); }); } // firefox doesn't bubble mousemove events to parent. videojs/video-js-swf#37 // bugzilla bug: https://bugzilla.mozilla.org/show_bug.cgi?id=836786 if (vjs.IS_FIREFOX) { this.ready(function(){ this.on('mousemove', function(){ // since it's a custom event, don't bubble higher than the player this.player().trigger({ 'type':'mousemove', 'bubbles': false }); }); }); } // native click events on the SWF aren't triggered on IE11, Win8.1RT // use stageclick events triggered from inside the SWF instead player.on('stageclick', player.reportUserActivity); this.el_ = vjs.Flash.embed(options['swf'], placeHolder, flashVars, params, attributes); } }); vjs.Flash.prototype.dispose = function(){ vjs.MediaTechController.prototype.dispose.call(this); }; vjs.Flash.prototype.play = function(){ this.el_.vjs_play(); }; vjs.Flash.prototype.pause = function(){ this.el_.vjs_pause(); }; vjs.Flash.prototype.src = function(src){ if (src === undefined) { return this['currentSrc'](); } // Setting src through `src` not `setSrc` will be deprecated return this.setSrc(src); }; vjs.Flash.prototype.setSrc = function(src){ // Make sure source URL is absolute. src = vjs.getAbsoluteURL(src); this.el_.vjs_src(src); // Currently the SWF doesn't autoplay if you load a source later. // e.g. Load player w/ no source, wait 2s, set src. if (this.player_.autoplay()) { var tech = this; this.setTimeout(function(){ tech.play(); }, 0); } }; vjs.Flash.prototype['setCurrentTime'] = function(time){ this.lastSeekTarget_ = time; this.el_.vjs_setProperty('currentTime', time); vjs.MediaTechController.prototype.setCurrentTime.call(this); }; vjs.Flash.prototype['currentTime'] = function(time){ // when seeking make the reported time keep up with the requested time // by reading the time we're seeking to if (this.seeking()) { return this.lastSeekTarget_ || 0; } return this.el_.vjs_getProperty('currentTime'); }; vjs.Flash.prototype['currentSrc'] = function(){ if (this.currentSource_) { return this.currentSource_.src; } else { return this.el_.vjs_getProperty('currentSrc'); } }; vjs.Flash.prototype.load = function(){ this.el_.vjs_load(); }; vjs.Flash.prototype.poster = function(){ this.el_.vjs_getProperty('poster'); }; vjs.Flash.prototype['setPoster'] = function(){ // poster images are not handled by the Flash tech so make this a no-op }; vjs.Flash.prototype.buffered = function(){ return vjs.createTimeRange(0, this.el_.vjs_getProperty('buffered')); }; vjs.Flash.prototype.supportsFullScreen = function(){ return false; // Flash does not allow fullscreen through javascript }; vjs.Flash.prototype.enterFullScreen = function(){ return false; }; (function(){ // Create setters and getters for attributes var api = vjs.Flash.prototype, readWrite = 'rtmpConnection,rtmpStream,preload,defaultPlaybackRate,playbackRate,autoplay,loop,mediaGroup,controller,controls,volume,muted,defaultMuted'.split(','), readOnly = 'error,networkState,readyState,seeking,initialTime,duration,startOffsetTime,paused,played,seekable,ended,videoTracks,audioTracks,videoWidth,videoHeight,textTracks'.split(','), // Overridden: buffered, currentTime, currentSrc i; function createSetter(attr){ var attrUpper = attr.charAt(0).toUpperCase() + attr.slice(1); api['set'+attrUpper] = function(val){ return this.el_.vjs_setProperty(attr, val); }; } function createGetter(attr) { api[attr] = function(){ return this.el_.vjs_getProperty(attr); }; } // Create getter and setters for all read/write attributes for (i = 0; i < readWrite.length; i++) { createGetter(readWrite[i]); createSetter(readWrite[i]); } // Create getters for read-only attributes for (i = 0; i < readOnly.length; i++) { createGetter(readOnly[i]); } })(); /* Flash Support Testing -------------------------------------------------------- */ vjs.Flash.isSupported = function(){ return vjs.Flash.version()[0] >= 10; // return swfobject.hasFlashPlayerVersion('10'); }; // Add Source Handler pattern functions to this tech vjs.MediaTechController.withSourceHandlers(vjs.Flash); /** * The default native source handler. * This simply passes the source to the video element. Nothing fancy. * @param {Object} source The source object * @param {vjs.Flash} tech The instance of the Flash tech */ vjs.Flash.nativeSourceHandler = {}; /** * Check Flash can handle the source natively * @param {Object} source The source object * @return {String} 'probably', 'maybe', or '' (empty string) */ vjs.Flash.nativeSourceHandler.canHandleSource = function(source){ var type; if (!source.type) { return ''; } // Strip code information from the type because we don't get that specific type = source.type.replace(/;.*/,'').toLowerCase(); if (type in vjs.Flash.formats) { return 'maybe'; } return ''; }; /** * Pass the source to the flash object * Adaptive source handlers will have more complicated workflows before passing * video data to the video element * @param {Object} source The source object * @param {vjs.Flash} tech The instance of the Flash tech */ vjs.Flash.nativeSourceHandler.handleSource = function(source, tech){ tech.setSrc(source.src); }; /** * Clean up the source handler when disposing the player or switching sources.. * (no cleanup is needed when supporting the format natively) */ vjs.Flash.nativeSourceHandler.dispose = function(){}; // Register the native source handler vjs.Flash.registerSourceHandler(vjs.Flash.nativeSourceHandler); vjs.Flash.formats = { 'video/flv': 'FLV', 'video/x-flv': 'FLV', 'video/mp4': 'MP4', 'video/m4v': 'MP4' }; vjs.Flash['onReady'] = function(currSwf){ var el, player; el = vjs.el(currSwf); // get player from the player div property player = el && el.parentNode && el.parentNode['player']; // if there is no el or player then the tech has been disposed // and the tech element was removed from the player div if (player) { // reference player on tech element el['player'] = player; // check that the flash object is really ready vjs.Flash['checkReady'](player.tech); } }; // The SWF isn't always ready when it says it is. Sometimes the API functions still need to be added to the object. // If it's not ready, we set a timeout to check again shortly. vjs.Flash['checkReady'] = function(tech){ // stop worrying if the tech has been disposed if (!tech.el()) { return; } // check if API property exists if (tech.el().vjs_getProperty) { // tell tech it's ready tech.triggerReady(); } else { // wait longer this.setTimeout(function(){ vjs.Flash['checkReady'](tech); }, 50); } }; // Trigger events from the swf on the player vjs.Flash['onEvent'] = function(swfID, eventName){ var player = vjs.el(swfID)['player']; player.trigger(eventName); }; // Log errors from the swf vjs.Flash['onError'] = function(swfID, err){ var player = vjs.el(swfID)['player']; var msg = 'FLASH: '+err; if (err == 'srcnotfound') { player.error({ code: 4, message: msg }); // errors we haven't categorized into the media errors } else { player.error(msg); } }; // Flash Version Check vjs.Flash.version = function(){ var version = '0,0,0'; // IE try { version = new window.ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1]; // other browsers } catch(e) { try { if (navigator.mimeTypes['application/x-shockwave-flash'].enabledPlugin){ version = (navigator.plugins['Shockwave Flash 2.0'] || navigator.plugins['Shockwave Flash']).description.replace(/\D+/g, ',').match(/^,?(.+),?$/)[1]; } } catch(err) {} } return version.split(','); }; // Flash embedding method. Only used in non-iframe mode vjs.Flash.embed = function(swf, placeHolder, flashVars, params, attributes){ var code = vjs.Flash.getEmbedCode(swf, flashVars, params, attributes), // Get element by embedding code and retrieving created element obj = vjs.createEl('div', { innerHTML: code }).childNodes[0], par = placeHolder.parentNode ; placeHolder.parentNode.replaceChild(obj, placeHolder); // IE6 seems to have an issue where it won't initialize the swf object after injecting it. // This is a dumb fix var newObj = par.childNodes[0]; setTimeout(function(){ newObj.style.display = 'block'; }, 1000); return obj; }; vjs.Flash.getEmbedCode = function(swf, flashVars, params, attributes){ var objTag = '<object type="application/x-shockwave-flash" ', flashVarsString = '', paramsString = '', attrsString = ''; // Convert flash vars to string if (flashVars) { vjs.obj.each(flashVars, function(key, val){ flashVarsString += (key + '=' + val + '&amp;'); }); } // Add swf, flashVars, and other default params params = vjs.obj.merge({ 'movie': swf, 'flashvars': flashVarsString, 'allowScriptAccess': 'always', // Required to talk to swf 'allowNetworking': 'all' // All should be default, but having security issues. }, params); // Create param tags string vjs.obj.each(params, function(key, val){ paramsString += '<param name="'+key+'" value="'+val+'" />'; }); attributes = vjs.obj.merge({ // Add swf to attributes (need both for IE and Others to work) 'data': swf, // Default to 100% width/height 'width': '100%', 'height': '100%' }, attributes); // Create Attributes string vjs.obj.each(attributes, function(key, val){ attrsString += (key + '="' + val + '" '); }); return objTag + attrsString + '>' + paramsString + '</object>'; }; vjs.Flash.streamingFormats = { 'rtmp/mp4': 'MP4', 'rtmp/flv': 'FLV' }; vjs.Flash.streamFromParts = function(connection, stream) { return connection + '&' + stream; }; vjs.Flash.streamToParts = function(src) { var parts = { connection: '', stream: '' }; if (! src) { return parts; } // Look for the normal URL separator we expect, '&'. // If found, we split the URL into two pieces around the // first '&'. var connEnd = src.indexOf('&'); var streamBegin; if (connEnd !== -1) { streamBegin = connEnd + 1; } else { // If there's not a '&', we use the last '/' as the delimiter. connEnd = streamBegin = src.lastIndexOf('/') + 1; if (connEnd === 0) { // really, there's not a '/'? connEnd = streamBegin = src.length; } } parts.connection = src.substring(0, connEnd); parts.stream = src.substring(streamBegin, src.length); return parts; }; vjs.Flash.isStreamingType = function(srcType) { return srcType in vjs.Flash.streamingFormats; }; // RTMP has four variations, any string starting // with one of these protocols should be valid vjs.Flash.RTMP_RE = /^rtmp[set]?:\/\//i; vjs.Flash.isStreamingSrc = function(src) { return vjs.Flash.RTMP_RE.test(src); }; /** * A source handler for RTMP urls * @type {Object} */ vjs.Flash.rtmpSourceHandler = {}; /** * Check Flash can handle the source natively * @param {Object} source The source object * @return {String} 'probably', 'maybe', or '' (empty string) */ vjs.Flash.rtmpSourceHandler.canHandleSource = function(source){ if (vjs.Flash.isStreamingType(source.type) || vjs.Flash.isStreamingSrc(source.src)) { return 'maybe'; } return ''; }; /** * Pass the source to the flash object * Adaptive source handlers will have more complicated workflows before passing * video data to the video element * @param {Object} source The source object * @param {vjs.Flash} tech The instance of the Flash tech */ vjs.Flash.rtmpSourceHandler.handleSource = function(source, tech){ var srcParts = vjs.Flash.streamToParts(source.src); tech['setRtmpConnection'](srcParts.connection); tech['setRtmpStream'](srcParts.stream); }; // Register the native source handler vjs.Flash.registerSourceHandler(vjs.Flash.rtmpSourceHandler); /** * The Media Loader is the component that decides which playback technology to load * when the player is initialized. * * @constructor */ vjs.MediaLoader = vjs.Component.extend({ /** @constructor */ init: function(player, options, ready){ vjs.Component.call(this, player, options, ready); // If there are no sources when the player is initialized, // load the first supported playback technology. if (!player.options_['sources'] || player.options_['sources'].length === 0) { for (var i=0,j=player.options_['techOrder']; i<j.length; i++) { var techName = vjs.capitalize(j[i]), tech = window['videojs'][techName]; // Check if the browser supports this technology if (tech && tech.isSupported()) { player.loadTech(techName); break; } } } else { // // Loop through playback technologies (HTML5, Flash) and check for support. // // Then load the best source. // // A few assumptions here: // // All playback technologies respect preload false. player.src(player.options_['sources']); } } }); /** * @fileoverview Text Tracks * Text tracks are tracks of timed text events. * Captions - text displayed over the video for the hearing impaired * Subtitles - text displayed over the video for those who don't understand language in the video * Chapters - text displayed in a menu allowing the user to jump to particular points (chapters) in the video * Descriptions (not supported yet) - audio descriptions that are read back to the user by a screen reading device */ // Player Additions - Functions add to the player object for easier access to tracks /** * List of associated text tracks * @type {Array} * @private */ vjs.Player.prototype.textTracks_; /** * Get an array of associated text tracks. captions, subtitles, chapters, descriptions * http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-texttracks * @return {Array} Array of track objects * @private */ vjs.Player.prototype.textTracks = function(){ this.textTracks_ = this.textTracks_ || []; return this.textTracks_; }; /** * Add a text track * In addition to the W3C settings we allow adding additional info through options. * http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-addtexttrack * @param {String} kind Captions, subtitles, chapters, descriptions, or metadata * @param {String=} label Optional label * @param {String=} language Optional language * @param {Object=} options Additional track options, like src * @private */ vjs.Player.prototype.addTextTrack = function(kind, label, language, options){ var tracks = this.textTracks_ = this.textTracks_ || []; options = options || {}; options['kind'] = kind; options['label'] = label; options['language'] = language; // HTML5 Spec says default to subtitles. // Uppercase first letter to match class names var Kind = vjs.capitalize(kind || 'subtitles'); // Create correct texttrack class. CaptionsTrack, etc. var track = new window['videojs'][Kind + 'Track'](this, options); tracks.push(track); // If track.dflt() is set, start showing immediately // TODO: Add a process to determine the best track to show for the specific kind // In case there are multiple defaulted tracks of the same kind // Or the user has a set preference of a specific language that should override the default // Note: The setTimeout is a workaround because with the html5 tech, the player is 'ready' // before it's child components (including the textTrackDisplay) have finished loading. if (track.dflt()) { this.ready(function(){ this.setTimeout(function(){ track.player().showTextTrack(track.id()); }, 0); }); } return track; }; /** * Add an array of text tracks. captions, subtitles, chapters, descriptions * Track objects will be stored in the player.textTracks() array * @param {Array} trackList Array of track elements or objects (fake track elements) * @private */ vjs.Player.prototype.addTextTracks = function(trackList){ var trackObj; for (var i = 0; i < trackList.length; i++) { trackObj = trackList[i]; this.addTextTrack(trackObj['kind'], trackObj['label'], trackObj['language'], trackObj); } return this; }; // Show a text track // disableSameKind: disable all other tracks of the same kind. Value should be a track kind (captions, etc.) vjs.Player.prototype.showTextTrack = function(id, disableSameKind){ var tracks = this.textTracks_, i = 0, j = tracks.length, track, showTrack, kind; // Find Track with same ID for (;i<j;i++) { track = tracks[i]; if (track.id() === id) { track.show(); showTrack = track; // Disable tracks of the same kind } else if (disableSameKind && track.kind() == disableSameKind && track.mode() > 0) { track.disable(); } } // Get track kind from shown track or disableSameKind kind = (showTrack) ? showTrack.kind() : ((disableSameKind) ? disableSameKind : false); // Trigger trackchange event, captionstrackchange, subtitlestrackchange, etc. if (kind) { this.trigger(kind+'trackchange'); } return this; }; /** * The base class for all text tracks * * Handles the parsing, hiding, and showing of text track cues * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.TextTrack = vjs.Component.extend({ /** @constructor */ init: function(player, options){ vjs.Component.call(this, player, options); // Apply track info to track object // Options will often be a track element // Build ID if one doesn't exist this.id_ = options['id'] || ('vjs_' + options['kind'] + '_' + options['language'] + '_' + vjs.guid++); this.src_ = options['src']; // 'default' is a reserved keyword in js so we use an abbreviated version this.dflt_ = options['default'] || options['dflt']; this.title_ = options['title']; this.language_ = options['srclang']; this.label_ = options['label']; this.cues_ = []; this.activeCues_ = []; this.readyState_ = 0; this.mode_ = 0; player.on('dispose', vjs.bind(this, this.deactivate, this.id_)); } }); /** * Track kind value. Captions, subtitles, etc. * @private */ vjs.TextTrack.prototype.kind_; /** * Get the track kind value * @return {String} */ vjs.TextTrack.prototype.kind = function(){ return this.kind_; }; /** * Track src value * @private */ vjs.TextTrack.prototype.src_; /** * Get the track src value * @return {String} */ vjs.TextTrack.prototype.src = function(){ return this.src_; }; /** * Track default value * If default is used, subtitles/captions to start showing * @private */ vjs.TextTrack.prototype.dflt_; /** * Get the track default value. ('default' is a reserved keyword) * @return {Boolean} */ vjs.TextTrack.prototype.dflt = function(){ return this.dflt_; }; /** * Track title value * @private */ vjs.TextTrack.prototype.title_; /** * Get the track title value * @return {String} */ vjs.TextTrack.prototype.title = function(){ return this.title_; }; /** * Language - two letter string to represent track language, e.g. 'en' for English * Spec def: readonly attribute DOMString language; * @private */ vjs.TextTrack.prototype.language_; /** * Get the track language value * @return {String} */ vjs.TextTrack.prototype.language = function(){ return this.language_; }; /** * Track label e.g. 'English' * Spec def: readonly attribute DOMString label; * @private */ vjs.TextTrack.prototype.label_; /** * Get the track label value * @return {String} */ vjs.TextTrack.prototype.label = function(){ return this.label_; }; /** * All cues of the track. Cues have a startTime, endTime, text, and other properties. * Spec def: readonly attribute TextTrackCueList cues; * @private */ vjs.TextTrack.prototype.cues_; /** * Get the track cues * @return {Array} */ vjs.TextTrack.prototype.cues = function(){ return this.cues_; }; /** * ActiveCues is all cues that are currently showing * Spec def: readonly attribute TextTrackCueList activeCues; * @private */ vjs.TextTrack.prototype.activeCues_; /** * Get the track active cues * @return {Array} */ vjs.TextTrack.prototype.activeCues = function(){ return this.activeCues_; }; /** * ReadyState describes if the text file has been loaded * const unsigned short NONE = 0; * const unsigned short LOADING = 1; * const unsigned short LOADED = 2; * const unsigned short ERROR = 3; * readonly attribute unsigned short readyState; * @private */ vjs.TextTrack.prototype.readyState_; /** * Get the track readyState * @return {Number} */ vjs.TextTrack.prototype.readyState = function(){ return this.readyState_; }; /** * Mode describes if the track is showing, hidden, or disabled * const unsigned short OFF = 0; * const unsigned short HIDDEN = 1; (still triggering cuechange events, but not visible) * const unsigned short SHOWING = 2; * attribute unsigned short mode; * @private */ vjs.TextTrack.prototype.mode_; /** * Get the track mode * @return {Number} */ vjs.TextTrack.prototype.mode = function(){ return this.mode_; }; /** * Create basic div to hold cue text * @return {Element} */ vjs.TextTrack.prototype.createEl = function(){ return vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-' + this.kind_ + ' vjs-text-track' }); }; /** * Show: Mode Showing (2) * Indicates that the text track is active. If no attempt has yet been made to obtain the track's cues, the user agent will perform such an attempt momentarily. * The user agent is maintaining a list of which cues are active, and events are being fired accordingly. * In addition, for text tracks whose kind is subtitles or captions, the cues are being displayed over the video as appropriate; * for text tracks whose kind is descriptions, the user agent is making the cues available to the user in a non-visual fashion; * and for text tracks whose kind is chapters, the user agent is making available to the user a mechanism by which the user can navigate to any point in the media resource by selecting a cue. * The showing by default state is used in conjunction with the default attribute on track elements to indicate that the text track was enabled due to that attribute. * This allows the user agent to override the state if a later track is discovered that is more appropriate per the user's preferences. */ vjs.TextTrack.prototype.show = function(){ this.activate(); this.mode_ = 2; // Show element. vjs.Component.prototype.show.call(this); }; /** * Hide: Mode Hidden (1) * Indicates that the text track is active, but that the user agent is not actively displaying the cues. * If no attempt has yet been made to obtain the track's cues, the user agent will perform such an attempt momentarily. * The user agent is maintaining a list of which cues are active, and events are being fired accordingly. */ vjs.TextTrack.prototype.hide = function(){ // When hidden, cues are still triggered. Disable to stop triggering. this.activate(); this.mode_ = 1; // Hide element. vjs.Component.prototype.hide.call(this); }; /** * Disable: Mode Off/Disable (0) * Indicates that the text track is not active. Other than for the purposes of exposing the track in the DOM, the user agent is ignoring the text track. * No cues are active, no events are fired, and the user agent will not attempt to obtain the track's cues. */ vjs.TextTrack.prototype.disable = function(){ // If showing, hide. if (this.mode_ == 2) { this.hide(); } // Stop triggering cues this.deactivate(); // Switch Mode to Off this.mode_ = 0; }; /** * Turn on cue tracking. Tracks that are showing OR hidden are active. */ vjs.TextTrack.prototype.activate = function(){ // Load text file if it hasn't been yet. if (this.readyState_ === 0) { this.load(); } // Only activate if not already active. if (this.mode_ === 0) { // Update current cue on timeupdate // Using unique ID for bind function so other tracks don't remove listener this.player_.on('timeupdate', vjs.bind(this, this.update, this.id_)); // Reset cue time on media end this.player_.on('ended', vjs.bind(this, this.reset, this.id_)); // Add to display if (this.kind_ === 'captions' || this.kind_ === 'subtitles') { this.player_.getChild('textTrackDisplay').addChild(this); } } }; /** * Turn off cue tracking. */ vjs.TextTrack.prototype.deactivate = function(){ // Using unique ID for bind function so other tracks don't remove listener this.player_.off('timeupdate', vjs.bind(this, this.update, this.id_)); this.player_.off('ended', vjs.bind(this, this.reset, this.id_)); this.reset(); // Reset // Remove from display this.player_.getChild('textTrackDisplay').removeChild(this); }; // A readiness state // One of the following: // // Not loaded // Indicates that the text track is known to exist (e.g. it has been declared with a track element), but its cues have not been obtained. // // Loading // Indicates that the text track is loading and there have been no fatal errors encountered so far. Further cues might still be added to the track. // // Loaded // Indicates that the text track has been loaded with no fatal errors. No new cues will be added to the track except if the text track corresponds to a MutableTextTrack object. // // Failed to load // Indicates that the text track was enabled, but when the user agent attempted to obtain it, this failed in some way (e.g. URL could not be resolved, network error, unknown text track format). Some or all of the cues are likely missing and will not be obtained. vjs.TextTrack.prototype.load = function(){ // Only load if not loaded yet. if (this.readyState_ === 0) { this.readyState_ = 1; vjs.xhr(this.src_, vjs.bind(this, function(err, response, responseBody){ if (err) { return this.onError(err); } this.parseCues(responseBody); })); } }; vjs.TextTrack.prototype.onError = function(err){ this.error = err; this.readyState_ = 3; this.trigger('error'); }; // Parse the WebVTT text format for cue times. // TODO: Separate parser into own class so alternative timed text formats can be used. (TTML, DFXP) vjs.TextTrack.prototype.parseCues = function(srcContent) { var cue, time, text, lines = srcContent.split('\n'), line = '', id; for (var i=1, j=lines.length; i<j; i++) { // Line 0 should be 'WEBVTT', so skipping i=0 line = vjs.trim(lines[i]); // Trim whitespace and linebreaks if (line) { // Loop until a line with content // First line could be an optional cue ID // Check if line has the time separator if (line.indexOf('-->') == -1) { id = line; // Advance to next line for timing. line = vjs.trim(lines[++i]); } else { id = this.cues_.length; } // First line - Number cue = { id: id, // Cue Number index: this.cues_.length // Position in Array }; // Timing line time = line.split(/[\t ]+/); cue.startTime = this.parseCueTime(time[0]); cue.endTime = this.parseCueTime(time[2]); // Additional lines - Cue Text text = []; // Loop until a blank line or end of lines // Assuming trim('') returns false for blank lines while (lines[++i] && (line = vjs.trim(lines[i]))) { text.push(line); } cue.text = text.join('<br/>'); // Add this cue this.cues_.push(cue); } } this.readyState_ = 2; this.trigger('loaded'); }; vjs.TextTrack.prototype.parseCueTime = function(timeText) { var parts = timeText.split(':'), time = 0, hours, minutes, other, seconds, ms; // Check if optional hours place is included // 00:00:00.000 vs. 00:00.000 if (parts.length == 3) { hours = parts[0]; minutes = parts[1]; other = parts[2]; } else { hours = 0; minutes = parts[0]; other = parts[1]; } // Break other (seconds, milliseconds, and flags) by spaces // TODO: Make additional cue layout settings work with flags other = other.split(/\s+/); // Remove seconds. Seconds is the first part before any spaces. seconds = other.splice(0,1)[0]; // Could use either . or , for decimal seconds = seconds.split(/\.|,/); // Get milliseconds ms = parseFloat(seconds[1]); seconds = seconds[0]; // hours => seconds time += parseFloat(hours) * 3600; // minutes => seconds time += parseFloat(minutes) * 60; // Add seconds time += parseFloat(seconds); // Add milliseconds if (ms) { time += ms/1000; } return time; }; // Update active cues whenever timeupdate events are triggered on the player. vjs.TextTrack.prototype.update = function(){ if (this.cues_.length > 0) { // Get current player time, adjust for track offset var offset = this.player_.options()['trackTimeOffset'] || 0; var time = this.player_.currentTime() + offset; // Check if the new time is outside the time box created by the the last update. if (this.prevChange === undefined || time < this.prevChange || this.nextChange <= time) { var cues = this.cues_, // Create a new time box for this state. newNextChange = this.player_.duration(), // Start at beginning of the timeline newPrevChange = 0, // Start at end reverse = false, // Set the direction of the loop through the cues. Optimized the cue check. newCues = [], // Store new active cues. // Store where in the loop the current active cues are, to provide a smart starting point for the next loop. firstActiveIndex, lastActiveIndex, cue, i; // Loop vars // Check if time is going forwards or backwards (scrubbing/rewinding) // If we know the direction we can optimize the starting position and direction of the loop through the cues array. if (time >= this.nextChange || this.nextChange === undefined) { // NextChange should happen // Forwards, so start at the index of the first active cue and loop forward i = (this.firstActiveIndex !== undefined) ? this.firstActiveIndex : 0; } else { // Backwards, so start at the index of the last active cue and loop backward reverse = true; i = (this.lastActiveIndex !== undefined) ? this.lastActiveIndex : cues.length - 1; } while (true) { // Loop until broken cue = cues[i]; // Cue ended at this point if (cue.endTime <= time) { newPrevChange = Math.max(newPrevChange, cue.endTime); if (cue.active) { cue.active = false; } // No earlier cues should have an active start time. // Nevermind. Assume first cue could have a duration the same as the video. // In that case we need to loop all the way back to the beginning. // if (reverse && cue.startTime) { break; } // Cue hasn't started } else if (time < cue.startTime) { newNextChange = Math.min(newNextChange, cue.startTime); if (cue.active) { cue.active = false; } // No later cues should have an active start time. if (!reverse) { break; } // Cue is current } else { if (reverse) { // Add cue to front of array to keep in time order newCues.splice(0,0,cue); // If in reverse, the first current cue is our lastActiveCue if (lastActiveIndex === undefined) { lastActiveIndex = i; } firstActiveIndex = i; } else { // Add cue to end of array newCues.push(cue); // If forward, the first current cue is our firstActiveIndex if (firstActiveIndex === undefined) { firstActiveIndex = i; } lastActiveIndex = i; } newNextChange = Math.min(newNextChange, cue.endTime); newPrevChange = Math.max(newPrevChange, cue.startTime); cue.active = true; } if (reverse) { // Reverse down the array of cues, break if at first if (i === 0) { break; } else { i--; } } else { // Walk up the array fo cues, break if at last if (i === cues.length - 1) { break; } else { i++; } } } this.activeCues_ = newCues; this.nextChange = newNextChange; this.prevChange = newPrevChange; this.firstActiveIndex = firstActiveIndex; this.lastActiveIndex = lastActiveIndex; this.updateDisplay(); this.trigger('cuechange'); } } }; // Add cue HTML to display vjs.TextTrack.prototype.updateDisplay = function(){ var cues = this.activeCues_, html = '', i=0,j=cues.length; for (;i<j;i++) { html += '<span class="vjs-tt-cue">'+cues[i].text+'</span>'; } this.el_.innerHTML = html; }; // Set all loop helper values back vjs.TextTrack.prototype.reset = function(){ this.nextChange = 0; this.prevChange = this.player_.duration(); this.firstActiveIndex = 0; this.lastActiveIndex = 0; }; // Create specific track types /** * The track component for managing the hiding and showing of captions * * @constructor */ vjs.CaptionsTrack = vjs.TextTrack.extend(); vjs.CaptionsTrack.prototype.kind_ = 'captions'; // Exporting here because Track creation requires the track kind // to be available on global object. e.g. new window['videojs'][Kind + 'Track'] /** * The track component for managing the hiding and showing of subtitles * * @constructor */ vjs.SubtitlesTrack = vjs.TextTrack.extend(); vjs.SubtitlesTrack.prototype.kind_ = 'subtitles'; /** * The track component for managing the hiding and showing of chapters * * @constructor */ vjs.ChaptersTrack = vjs.TextTrack.extend(); vjs.ChaptersTrack.prototype.kind_ = 'chapters'; /* Text Track Display ============================================================================= */ // Global container for both subtitle and captions text. Simple div container. /** * The component for displaying text track cues * * @constructor */ vjs.TextTrackDisplay = vjs.Component.extend({ /** @constructor */ init: function(player, options, ready){ vjs.Component.call(this, player, options, ready); // This used to be called during player init, but was causing an error // if a track should show by default and the display hadn't loaded yet. // Should probably be moved to an external track loader when we support // tracks that don't need a display. if (player.options_['tracks'] && player.options_['tracks'].length > 0) { this.player_.addTextTracks(player.options_['tracks']); } } }); vjs.TextTrackDisplay.prototype.createEl = function(){ return vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-text-track-display' }); }; /** * The specific menu item type for selecting a language within a text track kind * * @constructor */ vjs.TextTrackMenuItem = vjs.MenuItem.extend({ /** @constructor */ init: function(player, options){ var track = this.track = options['track']; // Modify options for parent MenuItem class's init. options['label'] = track.label(); options['selected'] = track.dflt(); vjs.MenuItem.call(this, player, options); this.on(player, track.kind() + 'trackchange', this.update); } }); vjs.TextTrackMenuItem.prototype.onClick = function(){ vjs.MenuItem.prototype.onClick.call(this); this.player_.showTextTrack(this.track.id_, this.track.kind()); }; vjs.TextTrackMenuItem.prototype.update = function(){ this.selected(this.track.mode() == 2); }; /** * A special menu item for turning of a specific type of text track * * @constructor */ vjs.OffTextTrackMenuItem = vjs.TextTrackMenuItem.extend({ /** @constructor */ init: function(player, options){ // Create pseudo track info // Requires options['kind'] options['track'] = { kind: function() { return options['kind']; }, player: player, label: function(){ return options['kind'] + ' off'; }, dflt: function(){ return false; }, mode: function(){ return false; } }; vjs.TextTrackMenuItem.call(this, player, options); this.selected(true); } }); vjs.OffTextTrackMenuItem.prototype.onClick = function(){ vjs.TextTrackMenuItem.prototype.onClick.call(this); this.player_.showTextTrack(this.track.id_, this.track.kind()); }; vjs.OffTextTrackMenuItem.prototype.update = function(){ var tracks = this.player_.textTracks(), i=0, j=tracks.length, track, off = true; for (;i<j;i++) { track = tracks[i]; if (track.kind() == this.track.kind() && track.mode() == 2) { off = false; } } this.selected(off); }; /** * The base class for buttons that toggle specific text track types (e.g. subtitles) * * @constructor */ vjs.TextTrackButton = vjs.MenuButton.extend({ /** @constructor */ init: function(player, options){ vjs.MenuButton.call(this, player, options); if (this.items.length <= 1) { this.hide(); } } }); // vjs.TextTrackButton.prototype.buttonPressed = false; // vjs.TextTrackButton.prototype.createMenu = function(){ // var menu = new vjs.Menu(this.player_); // // Add a title list item to the top // // menu.el().appendChild(vjs.createEl('li', { // // className: 'vjs-menu-title', // // innerHTML: vjs.capitalize(this.kind_), // // tabindex: -1 // // })); // this.items = this.createItems(); // // Add menu items to the menu // for (var i = 0; i < this.items.length; i++) { // menu.addItem(this.items[i]); // } // // Add list to element // this.addChild(menu); // return menu; // }; // Create a menu item for each text track vjs.TextTrackButton.prototype.createItems = function(){ var items = [], track; // Add an OFF menu item to turn all tracks off items.push(new vjs.OffTextTrackMenuItem(this.player_, { 'kind': this.kind_ })); for (var i = 0; i < this.player_.textTracks().length; i++) { track = this.player_.textTracks()[i]; if (track.kind() === this.kind_) { items.push(new vjs.TextTrackMenuItem(this.player_, { 'track': track })); } } return items; }; /** * The button component for toggling and selecting captions * * @constructor */ vjs.CaptionsButton = vjs.TextTrackButton.extend({ /** @constructor */ init: function(player, options, ready){ vjs.TextTrackButton.call(this, player, options, ready); this.el_.setAttribute('aria-label','Captions Menu'); } }); vjs.CaptionsButton.prototype.kind_ = 'captions'; vjs.CaptionsButton.prototype.buttonText = 'Captions'; vjs.CaptionsButton.prototype.className = 'vjs-captions-button'; /** * The button component for toggling and selecting subtitles * * @constructor */ vjs.SubtitlesButton = vjs.TextTrackButton.extend({ /** @constructor */ init: function(player, options, ready){ vjs.TextTrackButton.call(this, player, options, ready); this.el_.setAttribute('aria-label','Subtitles Menu'); } }); vjs.SubtitlesButton.prototype.kind_ = 'subtitles'; vjs.SubtitlesButton.prototype.buttonText = 'Subtitles'; vjs.SubtitlesButton.prototype.className = 'vjs-subtitles-button'; // Chapters act much differently than other text tracks // Cues are navigation vs. other tracks of alternative languages /** * The button component for toggling and selecting chapters * * @constructor */ vjs.ChaptersButton = vjs.TextTrackButton.extend({ /** @constructor */ init: function(player, options, ready){ vjs.TextTrackButton.call(this, player, options, ready); this.el_.setAttribute('aria-label','Chapters Menu'); } }); vjs.ChaptersButton.prototype.kind_ = 'chapters'; vjs.ChaptersButton.prototype.buttonText = 'Chapters'; vjs.ChaptersButton.prototype.className = 'vjs-chapters-button'; // Create a menu item for each text track vjs.ChaptersButton.prototype.createItems = function(){ var items = [], track; for (var i = 0; i < this.player_.textTracks().length; i++) { track = this.player_.textTracks()[i]; if (track.kind() === this.kind_) { items.push(new vjs.TextTrackMenuItem(this.player_, { 'track': track })); } } return items; }; vjs.ChaptersButton.prototype.createMenu = function(){ var tracks = this.player_.textTracks(), i = 0, j = tracks.length, track, chaptersTrack, items = this.items = []; for (;i<j;i++) { track = tracks[i]; if (track.kind() == this.kind_) { if (track.readyState() === 0) { track.load(); track.on('loaded', vjs.bind(this, this.createMenu)); } else { chaptersTrack = track; break; } } } var menu = this.menu; if (menu === undefined) { menu = new vjs.Menu(this.player_); menu.contentEl().appendChild(vjs.createEl('li', { className: 'vjs-menu-title', innerHTML: vjs.capitalize(this.kind_), tabindex: -1 })); } if (chaptersTrack) { var cues = chaptersTrack.cues_, cue, mi; i = 0; j = cues.length; for (;i<j;i++) { cue = cues[i]; mi = new vjs.ChaptersTrackMenuItem(this.player_, { 'track': chaptersTrack, 'cue': cue }); items.push(mi); menu.addChild(mi); } this.addChild(menu); } if (this.items.length > 0) { this.show(); } return menu; }; /** * @constructor */ vjs.ChaptersTrackMenuItem = vjs.MenuItem.extend({ /** @constructor */ init: function(player, options){ var track = this.track = options['track'], cue = this.cue = options['cue'], currentTime = player.currentTime(); // Modify options for parent MenuItem class's init. options['label'] = cue.text; options['selected'] = (cue.startTime <= currentTime && currentTime < cue.endTime); vjs.MenuItem.call(this, player, options); track.on('cuechange', vjs.bind(this, this.update)); } }); vjs.ChaptersTrackMenuItem.prototype.onClick = function(){ vjs.MenuItem.prototype.onClick.call(this); this.player_.currentTime(this.cue.startTime); this.update(this.cue.startTime); }; vjs.ChaptersTrackMenuItem.prototype.update = function(){ var cue = this.cue, currentTime = this.player_.currentTime(); // vjs.log(currentTime, cue.startTime); this.selected(cue.startTime <= currentTime && currentTime < cue.endTime); }; // Add Buttons to controlBar vjs.obj.merge(vjs.ControlBar.prototype.options_['children'], { 'subtitlesButton': {}, 'captionsButton': {}, 'chaptersButton': {} }); // vjs.Cue = vjs.Component.extend({ // /** @constructor */ // init: function(player, options){ // vjs.Component.call(this, player, options); // } // }); /** * @fileoverview Add JSON support * @suppress {undefinedVars} * (Compiler doesn't like JSON not being declared) */ /** * Javascript JSON implementation * (Parse Method Only) * https://github.com/douglascrockford/JSON-js/blob/master/json2.js * Only using for parse method when parsing data-setup attribute JSON. * @suppress {undefinedVars} * @namespace * @private */ vjs.JSON; if (typeof window.JSON !== 'undefined' && typeof window.JSON.parse === 'function') { vjs.JSON = window.JSON; } else { vjs.JSON = {}; var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; /** * parse the json * * @memberof vjs.JSON * @param {String} text The JSON string to parse * @param {Function=} [reviver] Optional function that can transform the results * @return {Object|Array} The parsed JSON */ vjs.JSON.parse = function (text, reviver) { var j; function walk(holder, key) { var k, v, value = holder[key]; if (value && typeof value === 'object') { for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder, key, value); } text = String(text); cx.lastIndex = 0; if (cx.test(text)) { text = text.replace(cx, function (a) { return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }); } if (/^[\],:{}\s]*$/ .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@') .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']') .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { j = eval('(' + text + ')'); return typeof reviver === 'function' ? walk({'': j}, '') : j; } throw new SyntaxError('JSON.parse(): invalid or malformed JSON data'); }; } /** * @fileoverview Functions for automatically setting up a player * based on the data-setup attribute of the video tag */ // Automatically set up any tags that have a data-setup attribute vjs.autoSetup = function(){ var options, mediaEl, player, i, e; // One day, when we stop supporting IE8, go back to this, but in the meantime...*hack hack hack* // var vids = Array.prototype.slice.call(document.getElementsByTagName('video')); // var audios = Array.prototype.slice.call(document.getElementsByTagName('audio')); // var mediaEls = vids.concat(audios); // Because IE8 doesn't support calling slice on a node list, we need to loop through each list of elements // to build up a new, combined list of elements. var vids = document.getElementsByTagName('video'); var audios = document.getElementsByTagName('audio'); var mediaEls = []; if (vids && vids.length > 0) { for(i=0, e=vids.length; i<e; i++) { mediaEls.push(vids[i]); } } if (audios && audios.length > 0) { for(i=0, e=audios.length; i<e; i++) { mediaEls.push(audios[i]); } } // Check if any media elements exist if (mediaEls && mediaEls.length > 0) { for (i=0,e=mediaEls.length; i<e; i++) { mediaEl = mediaEls[i]; // Check if element exists, has getAttribute func. // IE seems to consider typeof el.getAttribute == 'object' instead of 'function' like expected, at least when loading the player immediately. if (mediaEl && mediaEl.getAttribute) { // Make sure this player hasn't already been set up. if (mediaEl['player'] === undefined) { options = mediaEl.getAttribute('data-setup'); // Check if data-setup attr exists. // We only auto-setup if they've added the data-setup attr. if (options !== null) { // Create new video.js instance. player = videojs(mediaEl); } } // If getAttribute isn't defined, we need to wait for the DOM. } else { vjs.autoSetupTimeout(1); break; } } // No videos were found, so keep looping unless page is finished loading. } else if (!vjs.windowLoaded) { vjs.autoSetupTimeout(1); } }; // Pause to let the DOM keep processing vjs.autoSetupTimeout = function(wait){ setTimeout(vjs.autoSetup, wait); }; if (document.readyState === 'complete') { vjs.windowLoaded = true; } else { vjs.one(window, 'load', function(){ vjs.windowLoaded = true; }); } // Run Auto-load players // You have to wait at least once in case this script is loaded after your video in the DOM (weird behavior only with minified version) vjs.autoSetupTimeout(1); /** * the method for registering a video.js plugin * * @param {String} name The name of the plugin * @param {Function} init The function that is run when the player inits */ vjs.plugin = function(name, init){ vjs.Player.prototype[name] = init; };
JavaScript
videojs.addLanguage("es",{ "Play": "Reproducción", "Pause": "Pausa", "Current Time": "Tiempo reproducido", "Duration Time": "Duración total", "Remaining Time": "Tiempo restante", "Stream Type": "Tipo de secuencia", "LIVE": "DIRECTO", "Loaded": "Cargado", "Progress": "Progreso", "Fullscreen": "Pantalla completa", "Non-Fullscreen": "Pantalla no completa", "Mute": "Silenciar", "Unmuted": "No silenciado", "Playback Rate": "Velocidad de reproducción", "Subtitles": "Subtítulos", "subtitles off": "Subtítulos desactivados", "Captions": "Subtítulos especiales", "captions off": "Subtítulos especiales desactivados", "Chapters": "Capítulos", "You aborted the video playback": "Ha interrumpido la reproducción del vídeo.", "A network error caused the video download to fail part-way.": "Un error de red ha interrumpido la descarga del vídeo.", "The video could not be loaded, either because the server or network failed or because the format is not supported.": "No se ha podido cargar el vídeo debido a un fallo de red o del servidor o porque el formato es incompatible.", "The video playback was aborted due to a corruption problem or because the video used features your browser did not support.": "La reproducción de vídeo se ha interrumpido por un problema de corrupción de datos o porque el vídeo precisa funciones que su navegador no ofrece.", "No compatible source was found for this video.": "No se ha encontrado ninguna fuente compatible con este vídeo." });
JavaScript
videojs.addLanguage("uk",{ "Play": "Відтворити", "Pause": "Призупинити", "Current Time": "Поточний час", "Duration Time": "Тривалість", "Remaining Time": "Час, що залишився", "Stream Type": "Тип потоку", "LIVE": "НАЖИВО", "Loaded": "Завантаження", "Progress": "Прогрес", "Fullscreen": "Повноекранний режим", "Non-Fullscreen": "Неповноекранний режим", "Mute": "Без звуку", "Unmuted": "Зі звуком", "Playback Rate": "Швидкість відтворення", "Subtitles": "Субтитри", "subtitles off": "Без субтитрів", "Captions": "Підписи", "captions off": "Без підписів", "Chapters": "Розділи", "You aborted the video playback": "Ви припинили відтворення відео", "A network error caused the video download to fail part-way.": "Помилка мережі викликала збій під час завантаження відео.", "The video could not be loaded, either because the server or network failed or because the format is not supported.": "Неможливо завантажити відео через мережевий чи серверний збій або формат не підтримується.", "The video playback was aborted due to a corruption problem or because the video used features your browser did not support.": "Відтворення відео було припинено через пошкодження або у зв'язку з тим, що відео використовує функції, які не підтримуються вашим браузером.", "No compatible source was found for this video.": "Сумісні джерела для цього відео відсутні." });
JavaScript
function Map() {"use strict"; // this.name = "-"; // this.cells = []; } // toString Map.prototype.toString = function() {"use strict"; return this.name + ' [' + this.cells.length + 'x' + this.cells[0].length + ']'; };
JavaScript
function Cell() {"use strict"; // this.name = "soil_2"; // // height in four corners (tile corners as in the clock) this.h0 = 0; this.h3 = 0; this.h6 = 0; this.h9 = 0; }
JavaScript
function MapUtils() {"use strict"; } // Load map MapUtils.loadMap = function(mapName) {"use strict"; var map,SIZE_X,SIZE_Y,i,j,busyCellsMap, objectBag; // // Dimensiones del map // SIZE_X = 200; SIZE_Y = 200; // // Map // // Create map map = new Map(); map.name = mapName; map.cells = new Array(SIZE_X); for (i = 0; i < map.cells.length; i=i+1) { map.cells[i] = new Array(SIZE_Y); } Game.model.map = map; // // Create Map cells. // for (i = 0; i < map.cells.length; i=i+1) { for (j = 0; j < map.cells[i].length; j=j+1) { map.cells[i][j] = new Cell(); if (i>5 || j> 5) { map.cells[i][j].name = "soil_1"; } } } // // Create object bag // objectBag = new ObjectBag(SIZE_X, SIZE_Y); Game.model.objectBag = objectBag; // // create objects // objectBag.add(new Scout(0.5, 0.5)); objectBag.add(new Scout(1.5, 0.5)); objectBag.add(new Scout(2.5, 1.5)); objectBag.add(new Scout(0.5, 3.5)); objectBag.add(new Scout(1.5, 3.5)); objectBag.add(new Scout(2.5, 3.5)); objectBag.add(new Scout(3.5, 3.5)); objectBag.add(new Tree(PaintableTypes.GRASS_1, 0.5, 6.5)); objectBag.add(new Tree(PaintableTypes.GRASS_2, 1.5, 6.5)); objectBag.add(new Tree(PaintableTypes.LOG_1, 2.5, 6.5)); objectBag.add(new Tree(PaintableTypes.TREE_1, 3.5, 6.5)); objectBag.add(new Tree(PaintableTypes.TREE_2, 4.5, 6.5)); objectBag.add(new Tree(PaintableTypes.TREE_3, 5.5, 6.5)); // // Set cammera position Game.gui.cammera.setPosition(2, 2); // return; };
JavaScript
var Keys = { NONE : 0, BACKSPACE : 8, TAB : 9, ENTER : 13, PAUSE : 19, CAPS : 20, ESC : 27, SPACE : 32, PAGE_UP : 33, PAGE_DOWN : 34, END : 35, HOME : 36, LEFT_ARROW : 37, UP_ARROW : 38, RIGHT_ARROW : 39, DOWN_ARROW : 40, INSERT : 45, DELETE : 46, N0 : 48, N1 : 49, N2 : 50, N3 : 51, N4 : 52, N5 : 53, N6 : 54, N7 : 55, N8 : 56, N9 : 57, A : 65, B : 66, C : 67, D : 68, E : 69, F : 70, G : 71, H : 72, I : 73, J : 74, K : 75, L : 76, M : 77, N : 78, O : 79, P : 80, Q : 81, R : 82, S : 83, T : 84, U : 85, V : 86, W : 87, X : 88, Y : 89, Z : 90, NUMPAD_0 : 96, NUMPAD_1 : 97, NUMPAD_2 : 98, NUMPAD_3 : 99, NUMPAD_4 : 100, NUMPAD_5 : 101, NUMPAD_6 : 102, NUMPAD_7 : 103, NUMPAD_8 : 104, NUMPAD_9 : 105, MULTIPLY : 106, ADD : 107, SUBSTRACT : 109, DECIMAL : 110, DIVIDE : 111, F1 : 112, F2 : 113, F3 : 114, F4 : 115, F5 : 116, F6 : 117, F7 : 118, F8 : 119, F9 : 120, F10 : 121, F11 : 122, F12 : 123, SHIFT : 16, CTRL : 17, ALT : 18, PLUS : 187, COMMA : 188, MINUS : 189, PERIOD : 190 }; function KeyboardInputHandler(){ "use strict"; // // Add listeners to handle key events window.onkeydown = KeyboardInputHandler.KeyboardInputHandler_onkeydown; window.onkeyup = KeyboardInputHandler.KeyboardInputHandler_onkeyup; // KeyboardInputHandler.keysPressed = []; } // Handles keydown KeyboardInputHandler.KeyboardInputHandler_onkeydown = function (e) { "use strict"; // KeyboardInputHandler.keysPressed[EventsUtil.getKeyboardKeyCode(e)] = true; // e.stopPropagation(); }; // Handles keyup KeyboardInputHandler.KeyboardInputHandler_onkeyup = function (e) { "use strict"; // KeyboardInputHandler.keysPressed[EventsUtil.getKeyboardKeyCode(e)] = false; // e.stopPropagation(); };
JavaScript
function InputHandler() {"use strict"; // // Currently I dont care about handling events on the window (i.e. window.onmousedown), but on the canvas. //window.onmousedown = myDown; //window.onmouseup = myUp; // // Handle events on main input handler this.mainMapInputHandler = new MainMapInputHandler(); // // Handle events on main input handler this.keyboardInputHandler = new KeyboardInputHandler(); }
JavaScript
function MainMapInputHandler(){ "use strict"; // // Add listeners to handle canvas mouse events: Drag and drop var auxMainMapCanvas = document.getElementById("mainMapCanvasId"); auxMainMapCanvas.onmousedown = MainMapInputHandler.MainMapCanvas_onmousedown; auxMainMapCanvas.onmouseup = MainMapInputHandler.MainMapCanvas_onmouseup; auxMainMapCanvas.onmousemove = null; // // Add listeners to handle canvas mouse click events auxMainMapCanvas.onclick = MainMapInputHandler.MainMapCanvas_onclick; auxMainMapCanvas.ondoubleclick = MainMapInputHandler.MainMapCanvas_ondoubleclick; // // Add listeners to handle canvas mouse over events auxMainMapCanvas.onmouseover = MainMapInputHandler.MainMapCanvas_onmouseover; auxMainMapCanvas.onmouseout = MainMapInputHandler.MainMapCanvas_onmouseout; // // Disable events on canvas auxMainMapCanvas.onmousewheel = function(evt){return false;}; auxMainMapCanvas.oncontextmenu = MainMapInputHandler.MainMapCanvas_oncontextmenu; // // Attributes // MainMapInputHandler.hadDraggedAndDroped: true if has not moved since mouse down // // Used but initialized before usage // MainMapInputHandler.MainMapCanvas_initialEventX // MainMapInputHandler.MainMapCanvas_initialEventY // MainMapInputHandler.MainMapCanvas_initialCammeraX // MainMapInputHandler.MainMapCanvas_initialCammeraY } // Handles mouse movement (drag and drop) on main canvas MainMapInputHandler.MainMapCanvas_onmousemove = function (e) { "use strict"; var event = EventsUtil.getEvent(e); // if (EventsUtil.isLeftButtonPressed(event)){ // // computes offset var offx = MainMapInputHandler.MainMapCanvas_initialEventX - event.pageX; var offy = MainMapInputHandler.MainMapCanvas_initialEventY - event.pageY; // // Marks D&D (therefore, not click) if (Math.abs(offx)>5 ||Math.abs(offy)>5){ MainMapInputHandler.hadDraggedAndDroped = true; } // // updates position var newCammeraX = MainMapInputHandler.MainMapCanvas_initialCammeraX + offx; var newCammeraY = MainMapInputHandler.MainMapCanvas_initialCammeraY + offy; // // Delegates movement to cammera for updating Game.gui.cammera.updateCammeraCoordinates(newCammeraX, newCammeraY); } // event.stopPropagation(); return false; }; // Handles mousedown on main canvas MainMapInputHandler.MainMapCanvas_onmousedown = function (e) { "use strict"; var event, auxMainMapCanvas; event = EventsUtil.getEvent(e); // if (EventsUtil.isLeftButtonPressed(event)){ // //Resets D&D detection MainMapInputHandler.hadDraggedAndDroped = false; // // Stores initial position MainMapInputHandler.MainMapCanvas_initialEventX = event.pageX; MainMapInputHandler.MainMapCanvas_initialEventY = event.pageY; MainMapInputHandler.MainMapCanvas_initialCammeraX = Game.gui.cammera.x; MainMapInputHandler.MainMapCanvas_initialCammeraY = Game.gui.cammera.y; // // Set movement listener auxMainMapCanvas = document.getElementById("mainMapCanvasId"); auxMainMapCanvas.onmousemove = MainMapInputHandler.MainMapCanvas_onmousemove; } // event.stopPropagation(); return false; }; // Handles mouseup on main canvas MainMapInputHandler.MainMapCanvas_onmouseup = function (e) { "use strict"; var event, auxMainMapCanvas; event = EventsUtil.getEvent(e); // if (EventsUtil.isLeftButtonPressed(event)){ // // Remove movement listener auxMainMapCanvas = document.getElementById("mainMapCanvasId"); auxMainMapCanvas.onmousemove = null; } // event.stopPropagation(); return false; }; // Handles mouse click on main canvas MainMapInputHandler.MainMapCanvas_onclick = function (e) { "use strict"; var event = EventsUtil.getEvent(e); // // if it was not a drag and drop if (!MainMapInputHandler.hadDraggedAndDroped){ // // Processes left click MainMapInputHandler.MainMapCanvas_handleLeftMouseClick(event); // } // event.stopPropagation(); return false; }; // Handles mouse double click on main canvas MainMapInputHandler.MainMapCanvas_ondoubleclick = function (e) { "use strict"; var event = EventsUtil.getEvent(e); // event.stopPropagation(); return false; }; // Handles mouse over on main canvas MainMapInputHandler.MainMapCanvas_onmouseover = function (e) { "use strict"; var event = EventsUtil.getEvent(e); // event.stopPropagation(); return false; }; // Handles mouse out on main canvas MainMapInputHandler.MainMapCanvas_onmouseout = function (e) { "use strict"; var event = EventsUtil.getEvent(e); // event.stopPropagation(); return false; }; // Handles mouse right click on main canvas MainMapInputHandler.MainMapCanvas_oncontextmenu = function (e) { "use strict"; var event = EventsUtil.getEvent(e); // // Processes right click MainMapInputHandler.MainMapCanvas_handleRightMouseClick(event); // event.stopPropagation(); return false; }; // Handles mouse left click on main canvas (Selection) MainMapInputHandler.MainMapCanvas_handleLeftMouseClick = function(e){ "use strict"; var xm, ym, object; // // Compute coordintates taking into account mouse and cammera position xm = e.offsetX + Game.gui.cammera.x; ym = e.offsetY + Game.gui.cammera.y; // // Finds closest object object = Game.model.objectBag.findClosestObject(xm,ym); // // If CTRL is not pressed, clear list of selected objects if (KeyboardInputHandler.keysPressed.hasOwnProperty(Keys.CTRL) && KeyboardInputHandler.keysPressed[Keys.CTRL]){ } else { Game.gui.clearSelectedObjects(); } // // Add selected object to the list or remove it depending on whether it was selected or not. if (object) { if (object.isSelected()){ Game.gui.removeSelectedObject(object); }else{ Game.gui.addSelectedObject(object); } } // }; // Handles mouse right click on main canvas (Go to) MainMapInputHandler.MainMapCanvas_handleRightMouseClick = function(e){ "use strict"; var xm, ym, tx, ty, i; // // Compute coordintates taking into account mouse and cammera position xm = e.offsetX + Game.gui.cammera.x; ym = e.offsetY + Game.gui.cammera.y; // tx = CoordinatesUtil.getTileX(xm,ym); ty = CoordinatesUtil.getTileY(xm,ym); // // Command selected objects list for (i=0; i<Game.gui.selectedObjects.length; i=i+1){ Game.gui.selectedObjects[i].goTo(tx, ty); } // };
JavaScript
function EventsUtil(){ "use strict"; } // Crossbrowser get event // source http://www.quirksmode.org/js/events_properties.html EventsUtil.getEvent = function (e) { "use strict"; var event = e; if (!event) { event = window.event; } return event; }; // Crossbrowser is right button pressed // source http://www.quirksmode.org/js/events_properties.html EventsUtil.isRightButtonPressed = function (e) { "use strict"; var event = EventsUtil.getEvent(e); var rightclick; if (event.which) { rightclick = (event.which === 3); } else if (event.button) { rightclick = (event.button === 2); } return rightclick; }; // Crossbrowser is left button pressed // source http://www.quirksmode.org/js/events_properties.html EventsUtil.isLeftButtonPressed = function (e) { "use strict"; var event = EventsUtil.getEvent(e); var leftclick; if (event.which) { leftclick = (event.which === 1); } else if (event.button) { leftclick = (event.button === 1); } return leftclick; }; // Crossbrowser get keycode // source http://www.quirksmode.org/js/events_properties.html EventsUtil.getKeyboardKeyCode = function (e) { "use strict"; var event, code; event = EventsUtil.getEvent(e); if (event.keyCode) { code = event.keyCode; } else if (event.which) { code = event.which; } return code; };
JavaScript
function Game(){ "use strict"; } Game.fps = 60; Game.updatingTime = 0; Game.renderingTime = 0; // Initialize and start game Game.start = function() { "use strict"; // // Initialize GUI Game.gui = new Gui(); // // Initialize Input Handler Game.inputHandler = new InputHandler(); // // Initialize model Game.model = new Model(); Game.model.initialize("Map0001"); // // Initialize renderer Game.renderer = new Renderer(); // // Starts animations Game.refresh(); }; // Loop game logic Game.refresh = function() { "use strict"; var t0,t1,t2; // update t0 = Date.now(); Game.update(); // // render t1 = Date.now(); Game.render(); // // compute times t2 = Date.now(); Game.updatingTime = t1-t0; Game.renderingTime = t2-t1; // //schedule next refresh window.setTimeout(Game.refresh, 1000 / Game.fps - Game.updatingTime - Game.renderingTime); }; // Update game models Game.update = function() { "use strict"; Game.model.update(); Game.gui.cammera.update(); }; // Update game GUI components Game.render = function() { "use strict"; Game.renderer.render(); };
JavaScript
JSLoadUtil.loadOnlyOnce("js/util/pathfinding/pathfinding-browser.js"); var matrix = [ [0, 0, 0, 1, 0], [1, 0, 0, 0, 1], [0, 0, 1, 0, 0], ]; var grid = new PF.Grid(5, 3, matrix); var finder = new PF.AStarFinder(); var path = finder.findPath(1, 2, 4, 2, grid); console.log("path:"+path); console.log("path:"+matrix); //Print results to div. outDiv.innerHTML="<u>Path:</u><br/>"+path;
JavaScript
JSLoadUtil.loadOnlyOnce("js/Constants.js"); JSLoadUtil.loadOnlyOnce("js/util/OOUtils.js"); JSLoadUtil.loadOnlyOnce("js/util/kdtree/KDTree.js"); JSLoadUtil.loadOnlyOnce("js/renderer/CoordinatesUtil.js"); JSLoadUtil.loadOnlyOnce("js/objects/ObjectBag.js"); JSLoadUtil.loadOnlyOnce("js/input/InputHandler.js"); JSLoadUtil.loadOnlyOnce("js/Model.js"); var nodeDistanceFunction = function(obj1, obj2){ "use strict"; return Math.sqrt(Math.pow(obj1.x - obj2.x, 2) + Math.pow(obj1.y - obj2.y, 2)); }; var nodeDimensionAttributes=["x","y"]; var tree = new KDTree(null,nodeDistanceFunction,nodeDimensionAttributes); tree.insert(new Scout(6,8)); tree.insert(new Scout(9,8)); var theScout=new Scout(3,7); tree.insert(theScout); tree.insert(new Scout(5,3)); tree.insert(new Scout(8,4)); console.log("tree:"+tree); //Find closest var closest = tree.findNearest({x:2, y:2},2,100); console.log("closest:"+closest); //Move node tree.updateNodeCoordinates(theScout, {x:2.1, y:2.1}); console.log("tree:"+tree); //Find closest again var closest = tree.findNearest({x:2, y:2},2,100); console.log("closest:"+closest); //Print results to div. outDiv.innerHTML="<u>Tree:</u><br/>"+tree+"<br/><u>Nearests:</u><br/>"+closest;
JavaScript
function DebugRenderer() {"use strict"; // Initializes last update time this.prevTime = Date.now(); // Stores canvas and context as static variables for indirection (browser independence) and performance var container = document.createElement('div'); container.id = 'debugInfo'; container.style.cssText = 'padding:0 0 3px 3px;text-align:left;background-color:#002;width:200px;'; container.style.position = 'absolute'; container.style.right = '0px'; container.style.bottom = '0px'; // this.l1 = document.createElement('div'); this.l1.style.cssText = 'color:#0ff;font-family:Helvetica,Arial,sans-serif;font-size:9px;font-weight:bold;line-height:15px'; this.l1.innerHTML = 'Updating: -. Rendering: - ms'; container.appendChild(this.l1); // this.l2 = document.createElement('div'); this.l2.style.cssText = 'color:#0ff;font-family:Helvetica,Arial,sans-serif;font-size:9px;font-weight:bold;line-height:15px'; this.l2.innerHTML = 'Max FPS: -'; container.appendChild(this.l2); // this.l3 = document.createElement('div'); this.l3.style.cssText = 'color:#0ff;font-family:Helvetica,Arial,sans-serif;font-size:9px;font-weight:bold;line-height:15px'; this.l3.innerHTML = 'Map: -'; container.appendChild(this.l3); // this.l4 = document.createElement('div'); this.l4.style.cssText = 'color:#0ff;font-family:Helvetica,Arial,sans-serif;font-size:9px;font-weight:bold;line-height:15px'; this.l4.innerHTML = 'Cammera: -,-'; container.appendChild(this.l4); // this.l5 = document.createElement('div'); this.l5.style.cssText = 'color:#0ff;font-family:Helvetica,Arial,sans-serif;font-size:9px;font-weight:bold;line-height:15px'; this.l5.innerHTML = '----'; container.appendChild(this.l5); // this.l6 = document.createElement('div'); this.l6.style.cssText = 'color:#0ff;font-family:Helvetica,Arial,sans-serif;font-size:9px;font-weight:bold;line-height:15px'; this.l6.innerHTML = 'Objects: -'; container.appendChild(this.l6); // this.l7 = document.createElement('div'); this.l7.style.cssText = 'color:#0ff;font-family:Helvetica,Arial,sans-serif;font-size:9px;font-weight:bold;line-height:15px'; this.l7.innerHTML = '----'; container.appendChild(this.l7); // document.body.appendChild(container); } // Updates GUI DebugRenderer.prototype.render = function() { "use strict"; // var time = Date.now(); if (time > this.prevTime + 300) { this.l1.innerHTML = 'Updating: ' + Game.updatingTime + '. Rendering: ' + Game.renderingTime + ' ms'; // if (Game.updatingTime + Game.renderingTime !== 0) { this.l2.innerHTML = 'Max FPS: ' + Math.round(1000 / (Game.updatingTime + Game.renderingTime)); } else { this.l2.innerHTML = 'Max FPS: +oo'; } // this.l3.innerHTML = 'Map: ' + Game.model.map; // this.l4.innerHTML = 'Cammera: ' + Math.round(Game.gui.cammera.x) + ', ' + Math.round(Game.gui.cammera.y); // this.l5.innerHTML = '----'; // this.l6.innerHTML = 'Objects: ' + Game.model.objectBag.objects.length; // this.l7.innerHTML = '----' ; // this.prevTime = time; } };
JavaScript
function RenderUtil() {"use strict"; } //Renders image in context RenderUtil.render = function(ctx, imgId, x, y, offsetTX, offsetTY) {"use strict"; var img, offsetX, offsetY; img = document.getElementById(imgId); offsetX = CoordinatesUtil.getX(x, y, offsetTX, offsetTY); offsetY = CoordinatesUtil.getY(x, y, offsetTX, offsetTY); // // Ensures img exists if (img) { ctx.drawImage(img, offsetX, offsetY); } else { console.log("RenderUtil.render: Image does not exist. Id: " + imgId); } };
JavaScript
function CoordinatesUtil(){ "use strict"; } // Precomputed constants for rendering optimization CoordinatesUtil.TILE_x2x = Constants.TILE_WIDTH/2; CoordinatesUtil.TILE_y2x = Constants.TILE_HEIGHT; CoordinatesUtil.TILE_x2y = Constants.TILE_WIDTH/2/2; CoordinatesUtil.TILE_y2y = - Constants.TILE_HEIGHT/2; // Precomputed constants for rendering optimization (isometric to orthografic) CoordinatesUtil.ISO_TO_ORTHO_1=CoordinatesUtil.TILE_y2x/CoordinatesUtil.TILE_y2y; CoordinatesUtil.ISO_TO_ORTHO_2=CoordinatesUtil.TILE_x2x-CoordinatesUtil.ISO_TO_ORTHO_1*CoordinatesUtil.TILE_x2y; CoordinatesUtil.ISO_TO_ORTHO_3=CoordinatesUtil.TILE_x2x/CoordinatesUtil.TILE_x2y; CoordinatesUtil.ISO_TO_ORTHO_4=CoordinatesUtil.TILE_y2x-CoordinatesUtil.ISO_TO_ORTHO_3*CoordinatesUtil.TILE_y2y; //Get canvas X for object in tile i,j //ox,oy is the offset of the image in tiles CoordinatesUtil.getX = function (i,j,offsetX,offsetY) { "use strict"; return i*CoordinatesUtil.TILE_x2x + j*CoordinatesUtil.TILE_y2x - offsetX*Constants.TILE_WIDTH; }; //Get canvas Y for object in tile i,j //ox,oy is the offset of the image in tiles CoordinatesUtil.getY = function (i,j,offsetX,offsetY) { "use strict"; return i*CoordinatesUtil.TILE_x2y + j*CoordinatesUtil.TILE_y2y - offsetY*Constants.TILE_HEIGHT; }; //Returns distance from a point in canvas to the object's position CoordinatesUtil.computeDistance = function (xm,ym,obj) { "use strict"; var xo,yo; xo = CoordinatesUtil.getX(obj.x,obj.y,0,0); yo = CoordinatesUtil.getY(obj.x,obj.y,0,0); // return Math.sqrt(Math.pow(xo-xm,2) + Math.pow(yo-ym,2)); }; //Returns distance from two points CoordinatesUtil.computePointDistance = function (xm,ym,xo,yo) { "use strict"; // return Math.sqrt(Math.pow(xo-xm,2) + Math.pow(yo-ym,2)); }; //Get Tile i for canvas coordinates CoordinatesUtil.getTileX = function (x,y) { "use strict"; return (x-CoordinatesUtil.ISO_TO_ORTHO_1*y) / CoordinatesUtil.ISO_TO_ORTHO_2; }; //Get Tile j for canvas coordinates CoordinatesUtil.getTileY = function (x,y) { "use strict"; return (x-CoordinatesUtil.ISO_TO_ORTHO_3*y)/ CoordinatesUtil.ISO_TO_ORTHO_4; };
JavaScript
/** * @author mrdoob / http://mrdoob.com/ */ var StatsPane = function() { "use strict"; var startTime, prevTime, ms, msMin, msMax, fps, fpsMin, fpsMax, frames, mode, container, fpsDiv, fpsText, fpsGraph, msDiv, msText, msGraph, bar, setMode, updateGraph; // startTime = Date.now(); prevTime = startTime; ms = 0; msMin = 1000; msMax = 0; fps = 0; fpsMin = 1000; fpsMax = 0; frames = 0; mode = 0; // container = document.createElement('div'); container.id = 'stats'; container.addEventListener('mousedown', function(event) { event.preventDefault(); mode=mode+1; setMode(mode % 2); }, false); container.style.cssText = 'width:80px;opacity:0.9;cursor:pointer'; // fpsDiv = document.createElement('div'); fpsDiv.id = 'fps'; fpsDiv.style.cssText = 'padding:0 0 3px 3px;text-align:left;background-color:#002'; container.appendChild(fpsDiv); // fpsText = document.createElement('div'); fpsText.id = 'fpsText'; fpsText.style.cssText = 'color:#0ff;font-family:Helvetica,Arial,sans-serif;font-size:9px;font-weight:bold;line-height:15px'; fpsText.innerHTML = 'FPS'; fpsDiv.appendChild(fpsText); // fpsGraph = document.createElement('div'); fpsGraph.id = 'fpsGraph'; fpsGraph.style.cssText = 'position:relative;width:74px;height:30px;background-color:#0ff'; fpsDiv.appendChild(fpsGraph); // while (fpsGraph.children.length < 74) { bar = document.createElement('span'); bar.style.cssText = 'width:1px;height:30px;float:left;background-color:#113'; fpsGraph.appendChild(bar); } // msDiv = document.createElement('div'); msDiv.id = 'ms'; msDiv.style.cssText = 'padding:0 0 3px 3px;text-align:left;background-color:#020;display:none'; container.appendChild(msDiv); // msText = document.createElement('div'); msText.id = 'msText'; msText.style.cssText = 'color:#0f0;font-family:Helvetica,Arial,sans-serif;font-size:9px;font-weight:bold;line-height:15px'; msText.innerHTML = 'MS'; msDiv.appendChild(msText); // msGraph = document.createElement('div'); msGraph.id = 'msGraph'; msGraph.style.cssText = 'position:relative;width:74px;height:30px;background-color:#0f0'; msDiv.appendChild(msGraph); // while (msGraph.children.length < 74) { bar = document.createElement('span'); bar.style.cssText = 'width:1px;height:30px;float:left;background-color:#131'; msGraph.appendChild(bar); } // setMode = function(value) { mode = value; switch ( mode ) { case 0: fpsDiv.style.display = 'block'; msDiv.style.display = 'none'; break; case 1: fpsDiv.style.display = 'none'; msDiv.style.display = 'block'; break; } }; // updateGraph = function(dom, value) { var child = dom.appendChild(dom.firstChild); child.style.height = value + 'px'; }; // return { domElement : container, setMode : setMode, begin : function() { startTime = Date.now(); }, end : function() { var time = Date.now(); ms = time - startTime; msMin = Math.min(msMin, ms); msMax = Math.max(msMax, ms); msText.textContent = ms + ' MS (' + msMin + '-' + msMax + ')'; updateGraph(msGraph, Math.min(30, 30 - (ms / 200 ) * 30)); frames=frames+1; if (time > prevTime + 1000) { fps = Math.round((frames * 1000 ) / (time - prevTime )); fpsMin = Math.min(fpsMin, fps); fpsMax = Math.max(fpsMax, fps); fpsText.textContent = fps + ' FPS (' + fpsMin + '-' + fpsMax + ')'; updateGraph(fpsGraph, Math.min(30, 30 - (fps / 100 ) * 30)); prevTime = time; frames = 0; } return time; }, update : function() { startTime = this.end(); } }; };
JavaScript
function Renderer(){ "use strict"; this.mainMapRenderer = new MainMapRenderer(); this.statsRenderer = new StatsRenderer(); this.debugRenderer = new DebugRenderer(); } // Updates GUI Renderer.prototype.render = function() { "use strict"; // Update GUI components this.mainMapRenderer.render(); this.statsRenderer.render(); this.debugRenderer.render(); };
JavaScript
function MainMapRenderer() { "use strict"; // Stores canvas and context as static variables for indirection (browser independence) and performance this.mainMapCanvas = document.getElementById("mainMapCanvasId"); this.mainMapCtx = this.mainMapCanvas.getContext('2d'); // // Initializes map objects for later rendering this.onNewMapLoaded(); } // Renders GUI MainMapRenderer.prototype.render = function() { "use strict"; // Update canvas size in case of window resize this.mainMapCanvas.width = window.innerWidth; this.mainMapCanvas.height = window.innerHeight; // // Translates according to cammera coordinates this.mainMapCtx.save(); this.mainMapCtx.translate(-Game.gui.cammera.x, -Game.gui.cammera.y); // // Renders main map components this.renderMap(this.mainMapCtx); this.renderObjects(this.mainMapCtx); // this.mainMapCtx.restore(); }; // Renders main map MainMapRenderer.prototype.renderMap = function(ctx) { "use strict"; // this.renderMap_render(ctx, -Constants.TILE_WIDTH, -Constants.TILE_HEIGHT); this.renderMap_render(ctx, -Constants.TILE_WIDTH*1.5, -Constants.TILE_HEIGHT*1.5); }; MainMapRenderer.prototype.renderMap_render = function(ctx, offsetX, offsetY) { var mapSizeX, mapSizeY, horizontalTiles, verticalTiles, i, j, cell, xo, yo, tx, ty; // mapSizeX = Game.model.map.cells.length; mapSizeY = Game.model.map.cells[0].length; // horizontalTiles = this.mainMapCanvas.width / Constants.TILE_WIDTH + 2; verticalTiles = this.mainMapCanvas.height / Constants.TILE_HEIGHT + 3; // xo = Game.gui.cammera.x + offsetX; for (i=0;i<horizontalTiles;i=i+1){ // xo += Constants.TILE_WIDTH; // yo = Game.gui.cammera.y + offsetY; for (j=0;j<verticalTiles;j=j+1){ // yo += Constants.TILE_HEIGHT; // // Convert from orthografic coordinates to isometric ones tx = Math.floor(CoordinatesUtil.getTileX(xo,yo)); ty = Math.floor(CoordinatesUtil.getTileY(xo,yo)); // if (tx>=0 && tx<mapSizeX && ty>=0 && ty<mapSizeY){ cell = Game.model.map.cells[tx][ty]; RenderUtil.render(ctx, cell.name, tx, ty, 0, 0.5); } } } // TODO: REMOVE - DEBUG info on busy cells map //for (i=0;i<mapSizeX;i=i+1){ // for (j=0;j<verticalTiles;j=j+1){ // if (Game.model.objectBag.busyCellsMap[i][j]!=0){ // RenderUtil.render(ctx, "soil_green_1", i, j, 0, 0.5); // } // } //} } // Renders objects in main map MainMapRenderer.prototype.renderObjects = function(ctx) { "use strict"; var i, o; // // Renders objects for (i = 0; i < Game.model.objectBag.objects.length; i=i+1) { o = Game.model.objectBag.objects[i]; o.render(ctx); // // Render CENTER (TODO: Remove) ctx.fillStyle = '#ff0'; ctx.fillRect(CoordinatesUtil.getX(o.x, o.y, 0, 0), CoordinatesUtil.getY(o.x, o.y, 0, 0), 2, 2); } // // Render ball (TODO: Remove) ctx.fillStyle = '#f00'; ctx.fillRect(Game.model.x, Game.model.y, 5, 5); }; // Notify a new map has been loaded MainMapRenderer.prototype.onNewMapLoaded = function() { "use strict"; // TODO: Dinamically load images for the map here, instead of having them statically defined in the html this.loadImage('scout_1', 'res/imgs/units/scout/scout_01.png'); this.loadImage('scout_2', 'res/imgs/units/scout/scout_02.png'); this.loadImage('scout_3', 'res/imgs/units/scout/scout_03.png'); this.loadImage('scout_4', 'res/imgs/units/scout/scout_04.png'); this.loadImage('scout_5', 'res/imgs/units/scout/scout_05.png'); this.loadImage('scout_6', 'res/imgs/units/scout/scout_06.png'); this.loadImage('scout_7', 'res/imgs/units/scout/scout_07.png'); this.loadImage('scout_8', 'res/imgs/units/scout/scout_08.png'); this.loadImage('scout_9', 'res/imgs/units/scout/scout_09.png'); this.loadImage('scout_10', 'res/imgs/units/scout/scout_10.png'); this.loadImage('scout_11', 'res/imgs/units/scout/scout_11.png'); this.loadImage('scout_12', 'res/imgs/units/scout/scout_12.png'); this.loadImage('scout_13', 'res/imgs/units/scout/scout_13.png'); this.loadImage('scout_14', 'res/imgs/units/scout/scout_14.png'); this.loadImage('scout_15', 'res/imgs/units/scout/scout_15.png'); this.loadImage('scout_16', 'res/imgs/units/scout/scout_16.png'); this.loadImage('scout_17', 'res/imgs/units/scout/scout_17.png'); this.loadImage('scout_18', 'res/imgs/units/scout/scout_18.png'); this.loadImage('scout_19', 'res/imgs/units/scout/scout_19.png'); this.loadImage('scout_20', 'res/imgs/units/scout/scout_20.png'); this.loadImage('scout_21', 'res/imgs/units/scout/scout_21.png'); this.loadImage('scout_22', 'res/imgs/units/scout/scout_22.png'); this.loadImage('scout_23', 'res/imgs/units/scout/scout_23.png'); this.loadImage('scout_24', 'res/imgs/units/scout/scout_24.png'); this.loadImage('scout_25', 'res/imgs/units/scout/scout_25.png'); this.loadImage('scout_26', 'res/imgs/units/scout/scout_26.png'); this.loadImage('scout_27', 'res/imgs/units/scout/scout_27.png'); this.loadImage('scout_28', 'res/imgs/units/scout/scout_28.png'); this.loadImage('scout_29', 'res/imgs/units/scout/scout_29.png'); this.loadImage('scout_30', 'res/imgs/units/scout/scout_30.png'); this.loadImage('scout_31', 'res/imgs/units/scout/scout_31.png'); this.loadImage('scout_32', 'res/imgs/units/scout/scout_32.png'); this.loadImage('selector1x1', 'res/imgs/units/shared/selector1x1.png'); // this.loadImage('soil_1', 'res/imgs/soils/soil_1.png'); this.loadImage('soil_2', 'res/imgs/soils/soil_2.png'); this.loadImage('soil_green_1', 'res/imgs/soils/soil_green_1.png'); this.loadImage('soil_green_2', 'res/imgs/soils/soil_green_2.png'); // this.loadImage('grass_1', 'res/imgs/objs/grass_1.png'); this.loadImage('grass_2', 'res/imgs/objs/grass_2.png'); this.loadImage('log_1', 'res/imgs/objs/log_1.png'); this.loadImage('tree_1', 'res/imgs/objs/tree_1.png'); this.loadImage('tree_2', 'res/imgs/objs/tree_2.png'); this.loadImage('tree_3', 'res/imgs/objs/tree_3.png'); }; // Notify a new map has been loaded MainMapRenderer.prototype.loadImage = function(id, src) { "use strict"; var img = document.createElement('img'); img.id = id; img.src = src; img.hidden = true; document.body.appendChild(img); };
JavaScript
function StatsRenderer(){ "use strict"; // Statistics Game.stats = new StatsPane(); Game.stats.domElement.style.position = 'absolute'; Game.stats.domElement.style.left = '0px'; Game.stats.domElement.style.bottom = '0px'; document.body.appendChild(Game.stats.domElement); } // Updates GUI StatsRenderer.prototype.render = function() { "use strict"; Game.stats.update(); };
JavaScript
function Cammera() {"use strict"; // Cammera position this.x = 0; this.y = 0; // Cammera speed this.speed_x = 0; this.speed_y = 0; } // Handles mouse movement on main canvas Cammera.prototype.updateCammeraCoordinates = function(newCammeraX, newCammeraY) {"use strict"; // updates position this.x = newCammeraX; this.y = newCammeraY; }; // Updates cammera taking into account keyboard events Cammera.prototype.update = function() {"use strict"; if (KeyboardInputHandler.keysPressed[Keys.RIGHT_ARROW]) { if (this.speed_x < 50) { this.speed_x = this.speed_x + 10; } } else if (KeyboardInputHandler.keysPressed[Keys.LEFT_ARROW]) { if (this.speed_x > -50) { this.speed_x = this.speed_x - 10; } } else { if (this.speed_x > 1 || this.speed_x < -1) { this.speed_x /= 2; } else { this.speed_x = 0; } } if (KeyboardInputHandler.keysPressed[Keys.DOWN_ARROW]) { if (this.speed_y < 50) { this.speed_y = this.speed_y + 10; } } else if (KeyboardInputHandler.keysPressed[Keys.UP_ARROW]) { if (this.speed_y > -50) { this.speed_y = this.speed_y - 10; } } else { if (this.speed_y > 1 || this.speed_y < -1) { this.speed_y /= 2; } else { this.speed_y = 0; } } // this.x = this.x + this.speed_x; this.y = this.y + this.speed_y; }; // Set initial position after map load. // i,j are the coordinates in terms of tiles. Cammera.prototype.setPosition = function(i, j) {"use strict"; this.x = CoordinatesUtil.getX(i, j, 0, 0) - window.innerWidth / 2; this.y = -CoordinatesUtil.getY(i, j, 0, 0) - window.innerHeight / 2; this.speed_x = 0; this.speed_y = 0; };
JavaScript
function Gui() {"use strict"; // this.cammera = new Cammera(); // // Array of selected objects this.selectedObjects = []; } // Clears list of selected objects Gui.prototype.clearSelectedObjects = function() {"use strict"; var i; // // Marks current objects as not selected for ( i = this.selectedObjects.length-1; i>=0; i=i-1) { this.selectedObjects[i].setSelected(false); } // // Sets selected object to selected objects list this.selectedObjects = []; }; // Add object to the list of selected objects Gui.prototype.addSelectedObject = function(newSelectedObject) {"use strict"; // Marks current objects as not selected newSelectedObject.setSelected(true); // If object is selectable if (newSelectedObject.isSelected()){ this.selectedObjects.push(newSelectedObject); } }; // Remove object to the list of selected objects Gui.prototype.removeSelectedObject = function(newSelectedObject) {"use strict"; var i, newList; // Marks current objects as not selected newSelectedObject.setSelected(false); // If object is selectable newList=[]; for (i=this.selectedObjects.length-1; i>=0; i=i-1) { if (this.selectedObjects[i].isSelected()){ newList.push(this.selectedObjects[i]); } } this.selectedObjects=newList; };
JavaScript
Scout.inherits( Paintable ); function Scout(x, y) { "use strict"; this.inherits(Paintable, PaintableTypes.SCOUT, x, y); this.angle = 0; // Current target this.path = null; this.nextTaget = null; } //Speed in tiles per second Scout.LINEAR_SPEED=3; //Speed in radians per second Scout.ANGULAR_SPEED=4; // update model for rendering Scout.prototype.update = function() { // if (this.nextTaget) { // // Rotates var targetAlpha = Math.atan2(this.nextTaget[1]-this.y,this.nextTaget[0]-this.x); if (targetAlpha < 0) {targetAlpha += 2 * Math.PI;} // var angleDistance = targetAlpha-this.angle; var direction=1; if(angleDistance>Math.PI){angleDistance-=Math.PI;direction=-1;} if(angleDistance<-Math.PI){angleDistance+=Math.PI;direction=-1;} // var maxAngleOffset = Scout.ANGULAR_SPEED * Game.model.deltaTimestamp/1000; if (angleDistance>maxAngleOffset) { angleDistance=maxAngleOffset; } if (angleDistance<-maxAngleOffset) { angleDistance=-maxAngleOffset; } // this.angle+=direction*angleDistance; // while (this.angle<0){ this.angle+=2*Math.PI; } while (this.angle>2*Math.PI){ this.angle-=2*Math.PI; } // // Moves var maxOffset = Scout.LINEAR_SPEED * Game.model.deltaTimestamp/1000; var distance = CoordinatesUtil.computePointDistance(this.x, this.y, this.nextTaget[0], this.nextTaget[1]); if (distance > maxOffset) { distance=maxOffset; } // if ( (targetAlpha-this.angle)>-(Math.PI/16) && (targetAlpha-this.angle)<(Math.PI/16) ) { var dx = this.nextTaget[0]-this.x; var dy = this.nextTaget[1]-this.y; var newX= this.x +distance * Math.cos(this.angle) ; var newY= this.y +distance * Math.sin(this.angle) ; // Game.model.objectBag.updateNodeCoordinates(this, {x: newX, y: newY}); } // if (distance < maxOffset) { if (this.path.length>0){ // Store next step this.nextTaget = this.path[0]; // Remove next step from path this.path.splice(0,1); }else{ this.nextTaget=null; this.path=null; } } } }; Scout.getFrameNumberForAngle= function(angle){ // * 32 / 2 * Math.PI ====> * 16 / Math.PI var no = Math.floor( angle * 16 / Math.PI % 32) + 1; if (no > 32) { no = 32; } if (no < 1) { no = 1; } return no; }; // Renders object Scout.prototype.render = function(ctx) { var time, no, imgId, x, y, xx, yy; time = Game.model.currentTimestamp * 0.002; // imgId = "scout_"+Scout.getFrameNumberForAngle(this.angle); // if (this.isSelected()) { RenderUtil.render(ctx, 'selector1x1', this.x, this.y, 0.5, 1); } // RenderUtil.render(ctx, imgId, this.x, this.y, this.paintableType.offsetX, this.paintableType.offsetY); // PFUtil.drawPath(ctx, this.x, this.y, this.nextTaget, this.path); }; // goTo command Scout.prototype.goTo = function(x, y) { // this.path=PFUtil.findPath(this.x, this.y, x, y); // // If valid coordinates and path found if (this.path){ // Store next step this.nextTaget = this.path[0]; // Remove next step from path this.path.splice(0,1); }else{ // Clean next step this.nextTaget = null; } };
JavaScript
Tree.inherits( NonSelectable ); function Tree(paintableType, x, y) { "use strict"; this.inherits(NonSelectable, paintableType, x, y); }
JavaScript
function Paintable(paintableType, x, y) {"use strict"; // this.paintableType = paintableType; // // Position this.x = x; this.y = y; // // Is Selected this._isSelected = false; } // update model Paintable.prototype.update = function() {"use strict"; }; // return x position Paintable.prototype.getX = function() {"use strict"; return this.x; }; // return y position Paintable.prototype.getY = function() {"use strict"; return this.y; }; // return true if isSelected Paintable.prototype.isSelected = function() {"use strict"; return this._isSelected; }; // set isSelected Paintable.prototype.setSelected = function(isSelected) {"use strict"; this._isSelected=isSelected; }; // Renders object Paintable.prototype.render = function(ctx) {"use strict"; var imgId = this.paintableType.imageName; // if (this.isSelected()) { RenderUtil.render(ctx, 'selector1x1', this.x, this.y, 0.5, 1); } // RenderUtil.render(ctx, imgId, this.getX(), this.getY(), this.paintableType.offsetX, this.paintableType.offsetY); }; // goTo command Paintable.prototype.goTo = function(x, y) {"use strict"; }; // toString Paintable.prototype.toString = function() {"use strict"; return this.paintableType.name + ' (x:' + this.x + ', y:' + this.y + ')'; }; // return x position for busy map Paintable.prototype.getInitialBusyX = function() {"use strict"; return Math.floor(this.x); }; // return y position for busy map Paintable.prototype.getInitialBusyY = function() {"use strict"; return Math.floor(this.y); }; // return x size for busy map Paintable.prototype.getSizeBusyX = function() {"use strict"; return 1; }; // return y size for busy map Paintable.prototype.getSizeBusyY = function() {"use strict"; return 1; };
JavaScript
NonSelectable.inherits( Paintable ); function NonSelectable(paintableType, x, y) { "use strict"; this.inherits(Paintable, paintableType, x, y); } // return true is isSelected NonSelectable.prototype.isSelected = function() { return false; }; // set isSelected NonSelectable.prototype.setSelected = function(isSelected) {"use strict"; this._isSelected=false; };
JavaScript
function ObjectBag(sizeX, sizeY) {"use strict"; var nodeDistanceFunction, nodeDimensionAttributes, i; // // Initialize kdtree nodeDistanceFunction = function(obj1, obj2){"use strict"; return Math.sqrt(Math.pow(obj1.x - obj2.x, 2) + Math.pow(obj1.y - obj2.y, 2)); }; nodeDimensionAttributes=["x","y"]; this.kdtree=new KDTree(null,nodeDistanceFunction,nodeDimensionAttributes); // // Initialize busy cells map // var busyCellsMap = new Array(sizeX); for (i = 0; i < busyCellsMap.length; i=i+1) { busyCellsMap[i] = new Array(sizeY); // var j = sizeY; while (j--) { busyCellsMap[i][j] = 0; } } this.busyCellsMap = busyCellsMap; } ObjectBag.prototype.objects = []; // Finds object closest to given coordinates ObjectBag.prototype.findClosestObject = function(xo, yo) {"use strict"; // Convert from orthografic coordinates to isometric ones var tx = CoordinatesUtil.getTileX(xo,yo); var ty = CoordinatesUtil.getTileY(xo,yo); // var list=this.kdtree.findNearest( {x:tx,y:ty}, 1, 4); if (list==null || list.length<1){ return null; } return list[0][0]; }; // adds object to the bag ObjectBag.prototype.add = function(obj) {"use strict"; // // Add object to object bag this.objects.push(obj); // // Add object to kdtree this.kdtree.insert(obj); // // Add object to busyCellsMap var i,j; for (i=0;i<obj.getSizeBusyX();i+=1){ for (j=0;j<obj.getSizeBusyY();j+=1){ this.busyCellsMap[obj.getInitialBusyX()+i][obj.getInitialBusyY()+j]+=1; } } } // updates object position ObjectBag.prototype.updateNodeCoordinates = function(obj, point) {"use strict"; // // Remove object from busyCellsMap using old coordinates var i,j; for (i=0;i<obj.getSizeBusyX();i+=1){ for (j=0;j<obj.getSizeBusyY();j+=1){ this.busyCellsMap[obj.getInitialBusyX()+i][obj.getInitialBusyY()+j]-=1; } } // // Update coordinates in kdtree and update object coordinates too this.kdtree.updateNodeCoordinates(obj, point); // // Add object to busyCellsMap using updated coodinates for (i=0;i<obj.getSizeBusyX();i+=1){ for (j=0;j<obj.getSizeBusyY();j+=1){ this.busyCellsMap[obj.getInitialBusyX()+i][obj.getInitialBusyY()+j]+=1; } } }
JavaScript
function PaintableType(name, imageName, offsetX, offsetY) {"use strict"; // this.name = name; // // Default image name this.imageName = imageName; // // offset x e y en tiles this.offsetX = offsetX; this.offsetY = offsetY; } // toString PaintableType.prototype.toString = function() {"use strict"; return this.name + ' (ox:' + this.offsetX + ', oy:' + this.offsetY + ')'; }; var PaintableTypes = { SCOUT : new PaintableType('Scout', 'scout', 0.5, 1.5), GRASS_1 : new PaintableType('Tree', 'grass_1', 0.5, 0.5), GRASS_2 : new PaintableType('Tree', 'grass_2', 0.5, 0.5), LOG_1 : new PaintableType('Tree', 'log_1', 0.5, 0.5), TREE_1 : new PaintableType('Tree', 'tree_1', 0.5, 1.5), TREE_2 : new PaintableType('Tree', 'tree_2', 0.5, 1.5), TREE_3 : new PaintableType('Tree', 'tree_3', 0.5, 1.5) };
JavaScript
function Constants(){ "use strict"; } // Tiles are generated using GIMP "Isometric Floor" plugin converting 64x64 bitmaps into 128x64 size tiles // Size of the png files for rendering a tile Constants.TILE_WIDTH = 126; Constants.TILE_HEIGHT = 63;
JavaScript
// Src: https://github.com/ubilabs/kd-tree-javascript/blob/master/src/web/kdTree.js function KDTree(objectList, distanceFunction, dimensionAttributes) {"use strict"; this.distanceFunction = distanceFunction; this.dimensionAttributes = dimensionAttributes; this.root = this.buildTree(objectList, 0, null); } KDTree.prototype.buildTree = function(objectList, depth, parent) {"use strict"; var dimensionNo, auxDimensionAttributes, median, newNode, left, right; // if (!objectList || objectList.length === 0) { return null; } // dimensionNo = depth % this.dimensionAttributes.length; // if (objectList.length === 1) { return new KDTree_Node(objectList[0], dimensionNo, parent); } // // Sort list of points by single dimension auxDimensionAttributes = this.dimensionAttributes; objectList.sort(function(obj1, obj2) { return obj1[auxDimensionAttributes[dimensionNo]] - obj2[auxDimensionAttributes[dimensionNo]]; }); // median = Math.floor(objectList.length / 2); newNode = new KDTree_Node(objectList[median], dimensionNo, parent); left = this.buildTree(objectList.slice(0, median), depth + 1, newNode); right = this.buildTree(objectList.slice(median + 1), depth + 1, newNode); newNode.left = left; newNode.right = right; return newNode; }; KDTree.prototype.toString = function() {"use strict"; return "(KDTree " + this.root + ")"; }; KDTree.prototype.findNearest = function(point, maxNodes, maxDistance) {"use strict"; var scoreFunction, i, result, bestNodes; // // Score function maximizes -binaryHeapNode[1], that is, minimizes binaryHeamNode.distance scoreFunction = function(binaryHeapNode) { return -binaryHeapNode[1]; }; // // Create binary heap of 2 positions array [object, distance] // binary heap is sorted by 2nd position of the array (distance). bestNodes = new BinaryHeap(scoreFunction); // // Fills with maxNodes empty nodes if (maxDistance) { for ( i = 0; i < maxNodes; i = i + 1) { bestNodes.push([null, maxDistance]); } } // // Looks for nodes this.findNearest_nearestSearch(point, this.root, maxNodes, this.distanceFunction, this.dimensionAttributes, bestNodes); // // Fills results array with all non null values in the result (null values -in case they exist- are at maxDistance) result = []; for ( i = maxNodes - 1; i >= 0; i = i - 1) { if (bestNodes.content[i][0]) { result.push([bestNodes.content[i][0].obj, bestNodes.content[i][1]]); } } return result; }; KDTree.prototype.findNearest_nearestSearch = function(point, kdtreeNode, maxNodes, distanceFunction, dimensionAttributes, bestNodes) {"use strict"; var bestChild, dimensionAttribute, ownDistance, linearPoint, i, linearDistance, otherChild; // //Distance from current kdtreeNode object to the point ownDistance = distanceFunction(point, kdtreeNode.obj); // // //If distance < worst distance in the list of best nodes if (ownDistance < bestNodes.peek()[1]) { //Add node and remove first element (farthest) bestNodes.push([kdtreeNode, ownDistance]); bestNodes.pop(); } // //If the node has no left or right sub-trees, add node to the list of best nodes. if (kdtreeNode.right === null && kdtreeNode.left === null) { return; } // // Tries first in the subtree closest to the point (not always the best choice) dimensionAttribute = dimensionAttributes[kdtreeNode.dimensionNo]; if (kdtreeNode.right === null) { bestChild = kdtreeNode.left; } else if (kdtreeNode.left === null) { bestChild = kdtreeNode.right; } else { if (point[dimensionAttribute] < kdtreeNode.obj[dimensionAttribute]) { bestChild = kdtreeNode.left; } else { bestChild = kdtreeNode.right; } } this.findNearest_nearestSearch(point, bestChild, maxNodes, distanceFunction, dimensionAttributes, bestNodes); // // Tries then in the other subtree, if the distance to the other side of the partition is lower than the worst distance found so far. // Makes up point in the border and computes distance. linearPoint = {}; for ( i = 0; i < dimensionAttributes.length; i = i + 1) { if (i === kdtreeNode.dimensionNo) { linearPoint[dimensionAttributes[i]] = point[dimensionAttributes[i]]; } else { linearPoint[dimensionAttributes[i]] = kdtreeNode.obj[dimensionAttributes[i]]; } } linearDistance = distanceFunction(linearPoint, kdtreeNode.obj); // // If there is any chance, tries with the nodes in the other sub-tree. if (linearDistance < bestNodes.peek()[1]) { otherChild = null; if (bestChild === kdtreeNode.left) { otherChild = kdtreeNode.right; } else { otherChild = kdtreeNode.left; } if (otherChild !== null) { this.findNearest_nearestSearch(point, otherChild, maxNodes, distanceFunction, dimensionAttributes, bestNodes); } } }; KDTree.prototype.balanceFactor = function() {"use strict"; function height(kdtreeNode) { if (kdtreeNode === null) { return 0; } return Math.max(height(kdtreeNode.left), height(kdtreeNode.right)) + 1; } function count(kdtreeNode) { if (kdtreeNode === null) { return 0; } return count(kdtreeNode.left) + count(kdtreeNode.right) + 1; } return height(this.root) / (Math.log(count(this.root)) / Math.log(2)); }; //Adds a new object to the tree KDTree.prototype.insert = function(object) {"use strict"; function innerSearch(kdtree, kdtreeNode, parent) { var dimensionAttribute; if (kdtreeNode === null) { return parent; } dimensionAttribute = kdtree.dimensionAttributes[kdtreeNode.dimensionNo]; if (object[dimensionAttribute] < kdtreeNode.obj[dimensionAttribute]) { return innerSearch(kdtree, kdtreeNode.left, kdtreeNode); } return innerSearch(kdtree, kdtreeNode.right, kdtreeNode); } var insertPosition, newNode, dimensionAttribute; //Finds parent for the new node insertPosition = innerSearch(this, this.root, null); // //No parent found, it is the root node if (insertPosition === null) { this.root = new KDTree_Node(object, 0, null); return; } // //No parent found, it is the root node newNode = new KDTree_Node(object, (insertPosition.dimensionNo + 1) % this.dimensionAttributes.length, insertPosition); dimensionAttribute = this.dimensionAttributes[insertPosition.dimensionNo]; if (object[dimensionAttribute] < insertPosition.obj[dimensionAttribute]) { insertPosition.left = newNode; } else { insertPosition.right = newNode; } }; //Removes node KDTree.prototype.remove = function(object) {"use strict"; function nodeSearch(object, kdtreeNode, dimensionAttributes) { if (kdtreeNode === null) { return null; } if (kdtreeNode.obj === object) { return kdtreeNode; } var dimensionAttribute = dimensionAttributes[kdtreeNode.dimensionNo]; if (object[dimensionAttribute] < kdtreeNode.obj[dimensionAttribute]) { return nodeSearch(object, kdtreeNode.left, dimensionAttributes); } return nodeSearch(object, kdtreeNode.right, dimensionAttributes); } // function findMax(kdtree, kdtreeNode, dimensionNo) { var dimensionAttribute, own, left, right, max; if (kdtreeNode === null) { return null; } dimensionAttribute = kdtree.dimensionAttributes[dimensionNo]; if (kdtreeNode.dimensionNo === dimensionNo) { if (kdtreeNode.right !== null) { return findMax(kdtree, kdtreeNode.right, dimensionNo); } return kdtreeNode; } own = kdtreeNode.obj[dimensionAttribute]; left = findMax(kdtree, kdtreeNode.left, dimensionNo); right = findMax(kdtree, kdtreeNode.right, dimensionNo); max = kdtreeNode; if (left !== null && left.obj[dimensionAttribute] > own) { max = left; } if (right !== null && right.obj[dimensionAttribute] > max.obj[dimensionAttribute]) { max = right; } return max; } // function findMin(kdtree, kdtreeNode, dimensionNo) { var dimensionAttribute, own, left, right, min; if (kdtreeNode === null) { return null; } dimensionAttribute = kdtree.dimensionAttributes[dimensionNo]; if (kdtreeNode.dimensionNo === dimensionNo) { if (kdtreeNode.left !== null) { return findMin(kdtree, kdtreeNode.left, dimensionNo); } return kdtreeNode; } own = kdtreeNode.obj[dimensionAttribute]; left = findMin(kdtree, kdtreeNode.left, dimensionNo); right = findMin(kdtree, kdtreeNode.right, dimensionNo); min = kdtreeNode; if (left !== null && left.obj[dimensionAttribute] < own) { min = left; } if (right !== null && right.obj[dimensionAttribute] < min.obj[dimensionAttribute]) { min = right; } return min; } // function removeNode(kdtree, kdtreeNode) { var pDimension, nextNode, nextObj; if (kdtreeNode.left === null && kdtreeNode.right === null) { if (kdtreeNode.parent === null) { kdtree.root = null; return; } pDimension = kdtree.dimensionAttributes[kdtreeNode.parent.dimensionNo]; if (kdtreeNode.obj[pDimension] < kdtreeNode.parent.obj[pDimension]) { kdtreeNode.parent.left = null; } else { kdtreeNode.parent.right = null; } return; } if (kdtreeNode.left !== null) { nextNode = findMax(kdtree, kdtreeNode.left, kdtreeNode.dimensionNo); } else { nextNode = findMin(kdtree, kdtreeNode.right, kdtreeNode.dimensionNo); } nextObj = nextNode.obj; removeNode(kdtree, nextNode); kdtreeNode.obj = nextObj; } // var kdtreeNode = nodeSearch(object, this.root, this.dimensionAttributes); if (kdtreeNode === null) { return; } removeNode(this, kdtreeNode); }; KDTree.prototype.updateNodeCoordinates = function(obj, point) {"use strict"; // // Remove old object this.remove(obj); // // Update object coordinates var i; for (i = 0; i < this.dimensionAttributes.length; i = i + 1) { obj[this.dimensionAttributes[i]] = point[this.dimensionAttributes[i]]; } // // Add updated object this.insert(obj); }
JavaScript
function KDTree_Node(obj, dimensionNo, parent) {"use strict"; this.obj = obj; this.dimensionNo = dimensionNo; this.parent = parent; this.left = null; this.right = null; } KDTree_Node.prototype.toString = function() {"use strict"; return "(N o:" + // this.obj + // (this.left ? ", <br>l:" + this.left : "") + // (this.right ? ", <br>r:" + this.right : "") + // (this.parent ? ", <br>p:" + this.parent.obj : "") + // ", d:" + this.dimensionNo + // ")"; };
JavaScript
// Binary heap implementation from: // http://eloquentjavascript.net/appendix2.html function BinaryHeap(scoreFunction) {"use strict"; this.content = []; this.scoreFunction = scoreFunction; } //Adds new element BinaryHeap.prototype.push = function(bhElement) {"use strict"; // Add the new element to the end of the array. this.content.push(bhElement); // Allow it to bubble up. this.bubbleUp(this.content.length - 1); }; //Removes best element according to the scoringFunction. //For instance, if scoringFunction=-distance, the father, the smaller(the better). Therefore, farthest element is removed. BinaryHeap.prototype.pop = function() {"use strict"; var result, end; // Store the first element so we can return it later. result = this.content[0]; // Get the element at the end of the array. end = this.content.pop(); // If there are any elements left, put the end element at the // start, and let it sink down. if (this.content.length > 0) { this.content[0] = end; this.sinkDown(0); } return result; }; //Returns best element according to the scoringFunction. BinaryHeap.prototype.peek = function() {"use strict"; return this.content[0]; }; BinaryHeap.prototype.remove = function(bhElement) {"use strict"; var len, i, end; len = this.content.length; // To remove a value, we must search through the array to find it. for ( i = 0; i < len; i = i + 1) { if (this.content[i] === bhElement) { // When it is found, the process seen in 'pop' is repeated // to fill up the hole. end = this.content.pop(); if (i !== len - 1) { this.content[i] = end; if (this.scoreFunction(end) < this.scoreFunction(bhElement)) { this.bubbleUp(i); } else { this.sinkDown(i); } } return; } } throw new Error("Node not found."); }; BinaryHeap.prototype.size = function() {"use strict"; return this.content.length; }; // Takes value at n-th position and moves it towards the root of the tree // (making sure n-th value is now sorted) BinaryHeap.prototype.bubbleUp = function(pos) {"use strict"; var element, parentN, parent; // Fetch the element that has to be moved. element = this.content[pos]; // When at 0, an element can not go up any further. while (pos > 0) { // Compute the parent element's index, and fetch it. parentN = Math.floor((pos + 1) / 2) - 1; parent = this.content[parentN]; // Swap the elements if the parent is greater. if (this.scoreFunction(element) < this.scoreFunction(parent)) { this.content[parentN] = element; this.content[pos] = parent; // Update 'n' to continue at the new position. pos = parentN; } else { // Found a parent that is less, no need to move it further. break; } } }; // Takes value at n-th position and moves it downwards (further from the root of the tree) // (making sure n-th value is now sorted) BinaryHeap.prototype.sinkDown = function(pos) {"use strict"; var length, element, elemScore, child2N, child1N, swap, child1, child2, child1Score, child2Score; // Look up the target element and its score. length = this.content.length; element = this.content[pos]; elemScore = this.scoreFunction(element); while (true) { // Compute the indices of the child elements. child2N = (pos + 1) * 2; child1N = child2N - 1; // This is used to store the new position of the element, // if any. swap = null; // If the first child exists (is inside the array)... if (child1N < length) { // Look it up and compute its score. child1 = this.content[child1N]; child1Score = this.scoreFunction(child1); // If the score is less than our element's, we need to swap. if (child1Score < elemScore) { swap = child1N; } } // Do the same checks for the other child. if (child2N < length) { child2 = this.content[child2N]; child2Score = this.scoreFunction(child2); if (child2Score < (swap === null ? elemScore : child1Score)) { swap = child2N; } } // If the element needs to be moved, swap it, and continue. if (swap !== null) { this.content[pos] = this.content[swap]; this.content[swap] = element; pos = swap; } else { // Otherwise, we are done. break; } } };
JavaScript
function PFUtil() {"use strict"; } PFUtil.findPath = function(fromX, fromY, toX, toY) {"use strict"; var mapSizeX = Game.model.map.cells.length; var mapSizeY = Game.model.map.cells[0].length; // fromY = Math.floor(fromY); fromX = Math.floor(fromX); toY=Math.floor(toY); toX=Math.floor(toX); // if (toX<0 || toX>=mapSizeX || toY<0 || toY>=mapSizeY){ return null; } // Find path var grid = new PF.Grid(mapSizeX, mapSizeY, Game.model.objectBag.busyCellsMap); var finder = new PF.AStarFinder({ allowDiagonal: true, heuristic: PF.Heuristic.euclidean }); var path = finder.findPath(fromY, fromX, toY, toX, grid); // Remove current position var newPath=[]; var i, len; len = path.length; if (len>1){ for (i=1;i<len;i++){ newPath.push([path[i][1]+.5,path[i][0]+.5]); } return newPath; } else { return null; } }; PFUtil.drawPath = function(ctx, currX, currY, nextTaget, path) {"use strict"; if (path) { var xx,yy; ctx.save(); ctx.beginPath(); xx = CoordinatesUtil.getX(currX, currY, 0, 0); yy = CoordinatesUtil.getY(currX, currY, 0, 0); ctx.moveTo(xx, yy); xx = CoordinatesUtil.getX(nextTaget[0], nextTaget[1], 0, 0); yy = CoordinatesUtil.getY(nextTaget[0], nextTaget[1], 0, 0); ctx.lineTo(xx, yy); var i; for (i=0;i<path.length;i++){ xx = CoordinatesUtil.getX(path[i][0],path[i][1], 0, 0); yy = CoordinatesUtil.getY(path[i][0],path[i][1], 0, 0); ctx.lineTo(xx, yy); } ctx.strokeStyle = '#0000ff'; ctx.lineCap = 'round'; ctx.lineWidth = 2; ctx.stroke(); ctx.restore(); } // };
JavaScript
// Encapsulating inheritance /** For ES5 compliant browsers we must define new properties to Object class this way, or any object in the code will have it as a new visible property, making all the for..in loops end with a undefined behaviour The other solution is to check, in every loop, Object.prototype.hasOwnProperty(object, key), which is not as good as this solution, hiding the new property */ Object.defineProperty(Object.prototype, "inherits", { value: function inherits( parent ) { // Apply parent's constructor to this object if( arguments.length > 1 ){ // Note: 'arguments' is an Object, not an Array parent.apply( this, Array.prototype.slice.call( arguments, 1 ) ); } else{ parent.call( this ); } }, enumerable: false }); // Encapsulating inheritance Function.prototype.inherits = function( parent ){ this.prototype = new parent(); this.prototype.constructor = this; };
JavaScript
function Model(){ "use strict"; // // Current model update and rendering timestamp this.currentTimestamp=Date.now(); this.deltaTimestamp=0; // // Ball status (TODO: Remove) this.x=0; this.y=0; // //this.map //Map //this.objectBag //Objects } Model.prototype.initialize = function(mapName) { "use strict"; // Load Map and objects MapUtils.loadMap(mapName); }; Model.prototype.update = function() { "use strict"; var auxTS=Date.now(); this.deltaTimestamp=auxTS-this.currentTimestamp; this.currentTimestamp=auxTS; // update model var i, object; for (i=0; i<Game.model.objectBag.objects.length; i=i+1){ object = Game.model.objectBag.objects[i]; object.update(); } };
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 Frederico Caldeira Knabben * * == BEGIN LICENSE == * * Licensed under the terms of any of the following licenses at your * choice: * * - GNU General Public License Version 2 or later (the "GPL") * http://www.gnu.org/licenses/gpl.html * * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") * http://www.gnu.org/licenses/lgpl.html * * - Mozilla Public License Version 1.1 or later (the "MPL") * http://www.mozilla.org/MPL/MPL-1.1.html * * == END LICENSE == * * Chinese Traditional language file. */ var FCKLang = { // Language direction : "ltr" (left to right) or "rtl" (right to left). Dir : "ltr", ToolbarCollapse : "隱藏面板", ToolbarExpand : "顯示面板", // Toolbar Items and Context Menu Save : "儲存", NewPage : "開新檔案", Preview : "預覽", Cut : "剪下", Copy : "複製", Paste : "貼上", PasteText : "貼為純文字格式", PasteWord : "自 Word 貼上", Print : "列印", SelectAll : "全選", RemoveFormat : "清除格式", InsertLinkLbl : "超連結", InsertLink : "插入/編輯超連結", RemoveLink : "移除超連結", VisitLink : "開啟超連結", Anchor : "插入/編輯錨點", AnchorDelete : "移除錨點", InsertImageLbl : "影像", InsertImage : "插入/編輯影像", InsertFlashLbl : "Flash", InsertFlash : "插入/編輯 Flash", InsertTableLbl : "表格", InsertTable : "插入/編輯表格", InsertLineLbl : "水平線", InsertLine : "插入水平線", InsertSpecialCharLbl: "特殊符號", InsertSpecialChar : "插入特殊符號", InsertSmileyLbl : "表情符號", InsertSmiley : "插入表情符號", About : "關於 FCKeditor", Bold : "粗體", Italic : "斜體", Underline : "底線", StrikeThrough : "刪除線", Subscript : "下標", Superscript : "上標", LeftJustify : "靠左對齊", CenterJustify : "置中", RightJustify : "靠右對齊", BlockJustify : "左右對齊", DecreaseIndent : "減少縮排", IncreaseIndent : "增加縮排", Blockquote : "引用文字", CreateDiv : "新增 Div 標籤", EditDiv : "變更 Div 標籤", DeleteDiv : "移除 Div 標籤", Undo : "復原", Redo : "重複", NumberedListLbl : "編號清單", NumberedList : "插入/移除編號清單", BulletedListLbl : "項目清單", BulletedList : "插入/移除項目清單", ShowTableBorders : "顯示表格邊框", ShowDetails : "顯示詳細資料", Style : "樣式", FontFormat : "格式", Font : "字體", FontSize : "大小", TextColor : "文字顏色", BGColor : "背景顏色", Source : "原始碼", Find : "尋找", Replace : "取代", SpellCheck : "拼字檢查", UniversalKeyboard : "萬國鍵盤", PageBreakLbl : "分頁符號", PageBreak : "插入分頁符號", Form : "表單", Checkbox : "核取方塊", RadioButton : "選項按鈕", TextField : "文字方塊", Textarea : "文字區域", HiddenField : "隱藏欄位", Button : "按鈕", SelectionField : "清單/選單", ImageButton : "影像按鈕", FitWindow : "編輯器最大化", ShowBlocks : "顯示區塊", // Context Menu EditLink : "編輯超連結", CellCM : "儲存格", RowCM : "列", ColumnCM : "欄", InsertRowAfter : "向下插入列", InsertRowBefore : "向上插入列", DeleteRows : "刪除列", InsertColumnAfter : "向右插入欄", InsertColumnBefore : "向左插入欄", DeleteColumns : "刪除欄", InsertCellAfter : "向右插入儲存格", InsertCellBefore : "向左插入儲存格", DeleteCells : "刪除儲存格", MergeCells : "合併儲存格", MergeRight : "向右合併儲存格", MergeDown : "向下合併儲存格", HorizontalSplitCell : "橫向分割儲存格", VerticalSplitCell : "縱向分割儲存格", TableDelete : "刪除表格", CellProperties : "儲存格屬性", TableProperties : "表格屬性", ImageProperties : "影像屬性", FlashProperties : "Flash 屬性", AnchorProp : "錨點屬性", ButtonProp : "按鈕屬性", CheckboxProp : "核取方塊屬性", HiddenFieldProp : "隱藏欄位屬性", RadioButtonProp : "選項按鈕屬性", ImageButtonProp : "影像按鈕屬性", TextFieldProp : "文字方塊屬性", SelectionFieldProp : "清單/選單屬性", TextareaProp : "文字區域屬性", FormProp : "表單屬性", FontFormats : "一般;已格式化;位址;標題 1;標題 2;標題 3;標題 4;標題 5;標題 6;一般 (DIV)", // Alerts and Messages ProcessingXHTML : "處理 XHTML 中,請稍候…", Done : "完成", PasteWordConfirm : "您想貼上的文字似乎是自 Word 複製而來,請問您是否要先清除 Word 的格式後再行貼上?", NotCompatiblePaste : "此指令僅在 Internet Explorer 5.5 或以上的版本有效。請問您是否同意不清除格式即貼上?", UnknownToolbarItem : "未知工具列項目 \"%1\"", UnknownCommand : "未知指令名稱 \"%1\"", NotImplemented : "尚未安裝此指令", UnknownToolbarSet : "工具列設定 \"%1\" 不存在", NoActiveX : "瀏覽器的安全性設定限制了本編輯器的某些功能。您必須啟用安全性設定中的「執行ActiveX控制項與外掛程式」項目,否則本編輯器將會出現錯誤並缺少某些功能", BrowseServerBlocked : "無法開啟資源瀏覽器,請確定所有快顯視窗封鎖程式是否關閉", DialogBlocked : "無法開啟對話視窗,請確定所有快顯視窗封鎖程式是否關閉", VisitLinkBlocked : "無法開啟新視窗,請確定所有快顯視窗封鎖程式是否關閉", // Dialogs DlgBtnOK : "確定", DlgBtnCancel : "取消", DlgBtnClose : "關閉", DlgBtnBrowseServer : "瀏覽伺服器端", DlgAdvancedTag : "進階", DlgOpOther : "<其他>", DlgInfoTab : "資訊", DlgAlertUrl : "請插入 URL", // General Dialogs Labels DlgGenNotSet : "<尚未設定>", DlgGenId : "ID", DlgGenLangDir : "語言方向", DlgGenLangDirLtr : "由左而右 (LTR)", DlgGenLangDirRtl : "由右而左 (RTL)", DlgGenLangCode : "語言代碼", DlgGenAccessKey : "存取鍵", DlgGenName : "名稱", DlgGenTabIndex : "定位順序", DlgGenLongDescr : "詳細 URL", DlgGenClass : "樣式表類別", DlgGenTitle : "標題", DlgGenContType : "內容類型", DlgGenLinkCharset : "連結資源之編碼", DlgGenStyle : "樣式", // Image Dialog DlgImgTitle : "影像屬性", DlgImgInfoTab : "影像資訊", DlgImgBtnUpload : "上傳至伺服器", DlgImgURL : "URL", DlgImgUpload : "上傳", DlgImgAlt : "替代文字", DlgImgWidth : "寬度", DlgImgHeight : "高度", DlgImgLockRatio : "等比例", DlgBtnResetSize : "重設為原大小", DlgImgBorder : "邊框", DlgImgHSpace : "水平距離", DlgImgVSpace : "垂直距離", DlgImgAlign : "對齊", DlgImgAlignLeft : "靠左對齊", DlgImgAlignAbsBottom: "絕對下方", DlgImgAlignAbsMiddle: "絕對中間", DlgImgAlignBaseline : "基準線", DlgImgAlignBottom : "靠下對齊", DlgImgAlignMiddle : "置中對齊", DlgImgAlignRight : "靠右對齊", DlgImgAlignTextTop : "文字上方", DlgImgAlignTop : "靠上對齊", DlgImgPreview : "預覽", DlgImgAlertUrl : "請輸入影像 URL", DlgImgLinkTab : "超連結", // Flash Dialog DlgFlashTitle : "Flash 屬性", DlgFlashChkPlay : "自動播放", DlgFlashChkLoop : "重複", DlgFlashChkMenu : "開啟選單", DlgFlashScale : "縮放", DlgFlashScaleAll : "全部顯示", DlgFlashScaleNoBorder : "無邊框", DlgFlashScaleFit : "精確符合", // Link Dialog DlgLnkWindowTitle : "超連結", DlgLnkInfoTab : "超連結資訊", DlgLnkTargetTab : "目標", DlgLnkType : "超連接類型", DlgLnkTypeURL : "URL", DlgLnkTypeAnchor : "本頁錨點", DlgLnkTypeEMail : "電子郵件", DlgLnkProto : "通訊協定", DlgLnkProtoOther : "<其他>", DlgLnkURL : "URL", DlgLnkAnchorSel : "請選擇錨點", DlgLnkAnchorByName : "依錨點名稱", DlgLnkAnchorById : "依元件 ID", DlgLnkNoAnchors : "(本文件尚無可用之錨點)", DlgLnkEMail : "電子郵件", DlgLnkEMailSubject : "郵件主旨", DlgLnkEMailBody : "郵件內容", DlgLnkUpload : "上傳", DlgLnkBtnUpload : "傳送至伺服器", DlgLnkTarget : "目標", DlgLnkTargetFrame : "<框架>", DlgLnkTargetPopup : "<快顯視窗>", DlgLnkTargetBlank : "新視窗 (_blank)", DlgLnkTargetParent : "父視窗 (_parent)", DlgLnkTargetSelf : "本視窗 (_self)", DlgLnkTargetTop : "最上層視窗 (_top)", DlgLnkTargetFrameName : "目標框架名稱", DlgLnkPopWinName : "快顯視窗名稱", DlgLnkPopWinFeat : "快顯視窗屬性", DlgLnkPopResize : "可調整大小", DlgLnkPopLocation : "網址列", DlgLnkPopMenu : "選單列", DlgLnkPopScroll : "捲軸", DlgLnkPopStatus : "狀態列", DlgLnkPopToolbar : "工具列", DlgLnkPopFullScrn : "全螢幕 (IE)", DlgLnkPopDependent : "從屬 (NS)", DlgLnkPopWidth : "寬", DlgLnkPopHeight : "高", DlgLnkPopLeft : "左", DlgLnkPopTop : "右", DlnLnkMsgNoUrl : "請輸入欲連結的 URL", DlnLnkMsgNoEMail : "請輸入電子郵件位址", DlnLnkMsgNoAnchor : "請選擇錨點", DlnLnkMsgInvPopName : "快顯名稱必須以「英文字母」為開頭,且不得含有空白", // Color Dialog DlgColorTitle : "請選擇顏色", DlgColorBtnClear : "清除", DlgColorHighlight : "預覽", DlgColorSelected : "選擇", // Smiley Dialog DlgSmileyTitle : "插入表情符號", // Special Character Dialog DlgSpecialCharTitle : "請選擇特殊符號", // Table Dialog DlgTableTitle : "表格屬性", DlgTableRows : "列數", DlgTableColumns : "欄數", DlgTableBorder : "邊框", DlgTableAlign : "對齊", DlgTableAlignNotSet : "<未設定>", DlgTableAlignLeft : "靠左對齊", DlgTableAlignCenter : "置中", DlgTableAlignRight : "靠右對齊", DlgTableWidth : "寬度", DlgTableWidthPx : "像素", DlgTableWidthPc : "百分比", DlgTableHeight : "高度", DlgTableCellSpace : "間距", DlgTableCellPad : "內距", DlgTableCaption : "標題", DlgTableSummary : "摘要", DlgTableHeaders : "Headers", //MISSING DlgTableHeadersNone : "None", //MISSING DlgTableHeadersColumn : "First column", //MISSING DlgTableHeadersRow : "First Row", //MISSING DlgTableHeadersBoth : "Both", //MISSING // Table Cell Dialog DlgCellTitle : "儲存格屬性", DlgCellWidth : "寬度", DlgCellWidthPx : "像素", DlgCellWidthPc : "百分比", DlgCellHeight : "高度", DlgCellWordWrap : "自動換行", DlgCellWordWrapNotSet : "<尚未設定>", DlgCellWordWrapYes : "是", DlgCellWordWrapNo : "否", DlgCellHorAlign : "水平對齊", DlgCellHorAlignNotSet : "<尚未設定>", DlgCellHorAlignLeft : "靠左對齊", DlgCellHorAlignCenter : "置中", DlgCellHorAlignRight: "靠右對齊", DlgCellVerAlign : "垂直對齊", DlgCellVerAlignNotSet : "<尚未設定>", DlgCellVerAlignTop : "靠上對齊", DlgCellVerAlignMiddle : "置中", DlgCellVerAlignBottom : "靠下對齊", DlgCellVerAlignBaseline : "基準線", DlgCellType : "儲存格類型", DlgCellTypeData : "資料", DlgCellTypeHeader : "標題", DlgCellRowSpan : "合併列數", DlgCellCollSpan : "合併欄数", DlgCellBackColor : "背景顏色", DlgCellBorderColor : "邊框顏色", DlgCellBtnSelect : "請選擇…", // Find and Replace Dialog DlgFindAndReplaceTitle : "尋找與取代", // Find Dialog DlgFindTitle : "尋找", DlgFindFindBtn : "尋找", DlgFindNotFoundMsg : "未找到指定的文字。", // Replace Dialog DlgReplaceTitle : "取代", DlgReplaceFindLbl : "尋找:", DlgReplaceReplaceLbl : "取代:", DlgReplaceCaseChk : "大小寫須相符", DlgReplaceReplaceBtn : "取代", DlgReplaceReplAllBtn : "全部取代", DlgReplaceWordChk : "全字相符", // Paste Operations / Dialog PasteErrorCut : "瀏覽器的安全性設定不允許編輯器自動執行剪下動作。請使用快捷鍵 (Ctrl+X) 剪下。", PasteErrorCopy : "瀏覽器的安全性設定不允許編輯器自動執行複製動作。請使用快捷鍵 (Ctrl+C) 複製。", PasteAsText : "貼為純文字格式", PasteFromWord : "自 Word 貼上", DlgPasteMsg2 : "請使用快捷鍵 (<strong>Ctrl+V</strong>) 貼到下方區域中並按下 <strong>確定</strong>", DlgPasteSec : "因為瀏覽器的安全性設定,本編輯器無法直接存取您的剪貼簿資料,請您自行在本視窗進行貼上動作。", DlgPasteIgnoreFont : "移除字型設定", DlgPasteRemoveStyles : "移除樣式設定", // Color Picker ColorAutomatic : "自動", ColorMoreColors : "更多顏色…", // Document Properties DocProps : "文件屬性", // Anchor Dialog DlgAnchorTitle : "命名錨點", DlgAnchorName : "錨點名稱", DlgAnchorErrorName : "請輸入錨點名稱", // Speller Pages Dialog DlgSpellNotInDic : "不在字典中", DlgSpellChangeTo : "更改為", DlgSpellBtnIgnore : "忽略", DlgSpellBtnIgnoreAll : "全部忽略", DlgSpellBtnReplace : "取代", DlgSpellBtnReplaceAll : "全部取代", DlgSpellBtnUndo : "復原", DlgSpellNoSuggestions : "- 無建議值 -", DlgSpellProgress : "進行拼字檢查中…", DlgSpellNoMispell : "拼字檢查完成:未發現拼字錯誤", DlgSpellNoChanges : "拼字檢查完成:未更改任何單字", DlgSpellOneChange : "拼字檢查完成:更改了 1 個單字", DlgSpellManyChanges : "拼字檢查完成:更改了 %1 個單字", IeSpellDownload : "尚未安裝拼字檢查元件。您是否想要現在下載?", // Button Dialog DlgButtonText : "顯示文字 (值)", DlgButtonType : "類型", DlgButtonTypeBtn : "按鈕 (Button)", DlgButtonTypeSbm : "送出 (Submit)", DlgButtonTypeRst : "重設 (Reset)", // Checkbox and Radio Button Dialogs DlgCheckboxName : "名稱", DlgCheckboxValue : "選取值", DlgCheckboxSelected : "已選取", // Form Dialog DlgFormName : "名稱", DlgFormAction : "動作", DlgFormMethod : "方法", // Select Field Dialog DlgSelectName : "名稱", DlgSelectValue : "選取值", DlgSelectSize : "大小", DlgSelectLines : "行", DlgSelectChkMulti : "可多選", DlgSelectOpAvail : "可用選項", DlgSelectOpText : "顯示文字", DlgSelectOpValue : "值", DlgSelectBtnAdd : "新增", DlgSelectBtnModify : "修改", DlgSelectBtnUp : "上移", DlgSelectBtnDown : "下移", DlgSelectBtnSetValue : "設為預設值", DlgSelectBtnDelete : "刪除", // Textarea Dialog DlgTextareaName : "名稱", DlgTextareaCols : "字元寬度", DlgTextareaRows : "列數", // Text Field Dialog DlgTextName : "名稱", DlgTextValue : "值", DlgTextCharWidth : "字元寬度", DlgTextMaxChars : "最多字元數", DlgTextType : "類型", DlgTextTypeText : "文字", DlgTextTypePass : "密碼", // Hidden Field Dialog DlgHiddenName : "名稱", DlgHiddenValue : "值", // Bulleted List Dialog BulletedListProp : "項目清單屬性", NumberedListProp : "編號清單屬性", DlgLstStart : "起始編號", DlgLstType : "清單類型", DlgLstTypeCircle : "圓圈", DlgLstTypeDisc : "圓點", DlgLstTypeSquare : "方塊", DlgLstTypeNumbers : "數字 (1, 2, 3)", DlgLstTypeLCase : "小寫字母 (a, b, c)", DlgLstTypeUCase : "大寫字母 (A, B, C)", DlgLstTypeSRoman : "小寫羅馬數字 (i, ii, iii)", DlgLstTypeLRoman : "大寫羅馬數字 (I, II, III)", // Document Properties Dialog DlgDocGeneralTab : "一般", DlgDocBackTab : "背景", DlgDocColorsTab : "顯色與邊界", DlgDocMetaTab : "Meta 資料", DlgDocPageTitle : "頁面標題", DlgDocLangDir : "語言方向", DlgDocLangDirLTR : "由左而右 (LTR)", DlgDocLangDirRTL : "由右而左 (RTL)", DlgDocLangCode : "語言代碼", DlgDocCharSet : "字元編碼", DlgDocCharSetCE : "中歐語系", DlgDocCharSetCT : "正體中文 (Big5)", DlgDocCharSetCR : "斯拉夫文", DlgDocCharSetGR : "希臘文", DlgDocCharSetJP : "日文", DlgDocCharSetKR : "韓文", DlgDocCharSetTR : "土耳其文", DlgDocCharSetUN : "Unicode (UTF-8)", DlgDocCharSetWE : "西歐語系", DlgDocCharSetOther : "其他字元編碼", DlgDocDocType : "文件類型", DlgDocDocTypeOther : "其他文件類型", DlgDocIncXHTML : "包含 XHTML 定義", DlgDocBgColor : "背景顏色", DlgDocBgImage : "背景影像", DlgDocBgNoScroll : "浮水印", DlgDocCText : "文字", DlgDocCLink : "超連結", DlgDocCVisited : "已瀏覽過的超連結", DlgDocCActive : "作用中的超連結", DlgDocMargins : "頁面邊界", DlgDocMaTop : "上", DlgDocMaLeft : "左", DlgDocMaRight : "右", DlgDocMaBottom : "下", DlgDocMeIndex : "文件索引關鍵字 (用半形逗號[,]分隔)", DlgDocMeDescr : "文件說明", DlgDocMeAuthor : "作者", DlgDocMeCopy : "版權所有", DlgDocPreview : "預覽", // Templates Dialog Templates : "樣版", DlgTemplatesTitle : "內容樣版", DlgTemplatesSelMsg : "請選擇欲開啟的樣版<br> (原有的內容將會被清除):", DlgTemplatesLoading : "讀取樣版清單中,請稍候…", DlgTemplatesNoTpl : "(無樣版)", DlgTemplatesReplace : "取代原有內容", // About Dialog DlgAboutAboutTab : "關於", DlgAboutBrowserInfoTab : "瀏覽器資訊", DlgAboutLicenseTab : "許可證", DlgAboutVersion : "版本", DlgAboutInfo : "想獲得更多資訊請至 ", // Div Dialog DlgDivGeneralTab : "一般", DlgDivAdvancedTab : "進階", DlgDivStyle : "樣式", DlgDivInlineStyle : "CSS 樣式", ScaytTitle : "SCAYT", //MISSING ScaytTitleOptions : "Options", //MISSING ScaytTitleLangs : "Languages", //MISSING ScaytTitleAbout : "About" //MISSING };
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 Frederico Caldeira Knabben * * == BEGIN LICENSE == * * Licensed under the terms of any of the following licenses at your * choice: * * - GNU General Public License Version 2 or later (the "GPL") * http://www.gnu.org/licenses/gpl.html * * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") * http://www.gnu.org/licenses/lgpl.html * * - Mozilla Public License Version 1.1 or later (the "MPL") * http://www.mozilla.org/MPL/MPL-1.1.html * * == END LICENSE == * * Chinese Simplified language file. */ var FCKLang = { // Language direction : "ltr" (left to right) or "rtl" (right to left). Dir : "ltr", ToolbarCollapse : "折叠工具栏", ToolbarExpand : "展开工具栏", // Toolbar Items and Context Menu Save : "保存", NewPage : "新建", Preview : "预览", Cut : "剪切", Copy : "复制", Paste : "粘贴", PasteText : "粘贴为无格式文本", PasteWord : "从 MS Word 粘贴", Print : "打印", SelectAll : "全选", RemoveFormat : "清除格式", InsertLinkLbl : "超链接", InsertLink : "插入/编辑超链接", RemoveLink : "取消超链接", VisitLink : "打开超链接", Anchor : "插入/编辑锚点链接", AnchorDelete : "清除锚点链接", InsertImageLbl : "图象", InsertImage : "插入/编辑图象", InsertFlashLbl : "Flash", InsertFlash : "插入/编辑 Flash", InsertTableLbl : "表格", InsertTable : "插入/编辑表格", InsertLineLbl : "水平线", InsertLine : "插入水平线", InsertSpecialCharLbl: "特殊符号", InsertSpecialChar : "插入特殊符号", InsertSmileyLbl : "表情符", InsertSmiley : "插入表情图标", About : "关于 FCKeditor", Bold : "加粗", Italic : "倾斜", Underline : "下划线", StrikeThrough : "删除线", Subscript : "下标", Superscript : "上标", LeftJustify : "左对齐", CenterJustify : "居中对齐", RightJustify : "右对齐", BlockJustify : "两端对齐", DecreaseIndent : "减少缩进量", IncreaseIndent : "增加缩进量", Blockquote : "块引用", CreateDiv : "插入 Div 标签", EditDiv : "编辑 Div 标签", DeleteDiv : "删除 Div 标签", Undo : "撤消", Redo : "重做", NumberedListLbl : "编号列表", NumberedList : "插入/删除编号列表", BulletedListLbl : "项目列表", BulletedList : "插入/删除项目列表", ShowTableBorders : "显示表格边框", ShowDetails : "显示详细资料", Style : "样式", FontFormat : "格式", Font : "字体", FontSize : "大小", TextColor : "文本颜色", BGColor : "背景颜色", Source : "源代码", Find : "查找", Replace : "替换", SpellCheck : "拼写检查", UniversalKeyboard : "软键盘", PageBreakLbl : "分页符", PageBreak : "插入分页符", Form : "表单", Checkbox : "复选框", RadioButton : "单选按钮", TextField : "单行文本", Textarea : "多行文本", HiddenField : "隐藏域", Button : "按钮", SelectionField : "列表/菜单", ImageButton : "图像域", FitWindow : "全屏编辑", ShowBlocks : "显示区块", // Context Menu EditLink : "编辑超链接", CellCM : "单元格", RowCM : "行", ColumnCM : "列", InsertRowAfter : "在下方插入行", InsertRowBefore : "在上方插入行", DeleteRows : "删除行", InsertColumnAfter : "在右侧插入列", InsertColumnBefore : "在左侧插入列", DeleteColumns : "删除列", InsertCellAfter : "在右侧插入单元格", InsertCellBefore : "在左侧插入单元格", DeleteCells : "删除单元格", MergeCells : "合并单元格", MergeRight : "向右合并单元格", MergeDown : "向下合并单元格", HorizontalSplitCell : "水平拆分单元格", VerticalSplitCell : "垂直拆分单元格", TableDelete : "删除表格", CellProperties : "单元格属性", TableProperties : "表格属性", ImageProperties : "图象属性", FlashProperties : "Flash 属性", AnchorProp : "锚点链接属性", ButtonProp : "按钮属性", CheckboxProp : "复选框属性", HiddenFieldProp : "隐藏域属性", RadioButtonProp : "单选按钮属性", ImageButtonProp : "图像域属性", TextFieldProp : "单行文本属性", SelectionFieldProp : "菜单/列表属性", TextareaProp : "多行文本属性", FormProp : "表单属性", FontFormats : "普通;已编排格式;地址;标题 1;标题 2;标题 3;标题 4;标题 5;标题 6;段落(DIV)", // Alerts and Messages ProcessingXHTML : "正在处理 XHTML,请稍等...", Done : "完成", PasteWordConfirm : "您要粘贴的内容好像是来自 MS Word,是否要清除 MS Word 格式后再粘贴?", NotCompatiblePaste : "该命令需要 Internet Explorer 5.5 或更高版本的支持,是否按常规粘贴进行?", UnknownToolbarItem : "未知工具栏项目 \"%1\"", UnknownCommand : "未知命令名称 \"%1\"", NotImplemented : "命令无法执行", UnknownToolbarSet : "工具栏设置 \"%1\" 不存在", NoActiveX : "浏览器安全设置限制了本编辑器的某些功能。您必须启用安全设置中的“运行 ActiveX 控件和插件”,否则将出现某些错误并缺少功能。", BrowseServerBlocked : "无法打开资源浏览器,请确认是否启用了禁止弹出窗口。", DialogBlocked : "无法打开对话框窗口,请确认是否启用了禁止弹出窗口或网页对话框(IE)。", VisitLinkBlocked : "无法打开新窗口,请确认是否启用了禁止弹出窗口或网页对话框(IE)。", // Dialogs DlgBtnOK : "确定", DlgBtnCancel : "取消", DlgBtnClose : "关闭", DlgBtnBrowseServer : "浏览服务器", DlgAdvancedTag : "高级", DlgOpOther : "<其它>", DlgInfoTab : "信息", DlgAlertUrl : "请插入 URL", // General Dialogs Labels DlgGenNotSet : "<没有设置>", DlgGenId : "ID", DlgGenLangDir : "语言方向", DlgGenLangDirLtr : "从左到右 (LTR)", DlgGenLangDirRtl : "从右到左 (RTL)", DlgGenLangCode : "语言代码", DlgGenAccessKey : "访问键", DlgGenName : "名称", DlgGenTabIndex : "Tab 键次序", DlgGenLongDescr : "详细说明地址", DlgGenClass : "样式类名称", DlgGenTitle : "标题", DlgGenContType : "内容类型", DlgGenLinkCharset : "字符编码", DlgGenStyle : "行内样式", // Image Dialog DlgImgTitle : "图象属性", DlgImgInfoTab : "图象", DlgImgBtnUpload : "发送到服务器上", DlgImgURL : "源文件", DlgImgUpload : "上传", DlgImgAlt : "替换文本", DlgImgWidth : "宽度", DlgImgHeight : "高度", DlgImgLockRatio : "锁定比例", DlgBtnResetSize : "恢复尺寸", DlgImgBorder : "边框大小", DlgImgHSpace : "水平间距", DlgImgVSpace : "垂直间距", DlgImgAlign : "对齐方式", DlgImgAlignLeft : "左对齐", DlgImgAlignAbsBottom: "绝对底边", DlgImgAlignAbsMiddle: "绝对居中", DlgImgAlignBaseline : "基线", DlgImgAlignBottom : "底边", DlgImgAlignMiddle : "居中", DlgImgAlignRight : "右对齐", DlgImgAlignTextTop : "文本上方", DlgImgAlignTop : "顶端", DlgImgPreview : "预览", DlgImgAlertUrl : "请输入图象地址", DlgImgLinkTab : "链接", // Flash Dialog DlgFlashTitle : "Flash 属性", DlgFlashChkPlay : "自动播放", DlgFlashChkLoop : "循环", DlgFlashChkMenu : "启用 Flash 菜单", DlgFlashScale : "缩放", DlgFlashScaleAll : "全部显示", DlgFlashScaleNoBorder : "无边框", DlgFlashScaleFit : "严格匹配", // Link Dialog DlgLnkWindowTitle : "超链接", DlgLnkInfoTab : "超链接信息", DlgLnkTargetTab : "目标", DlgLnkType : "超链接类型", DlgLnkTypeURL : "超链接", DlgLnkTypeAnchor : "页内锚点链接", DlgLnkTypeEMail : "电子邮件", DlgLnkProto : "协议", DlgLnkProtoOther : "<其它>", DlgLnkURL : "地址", DlgLnkAnchorSel : "选择一个锚点", DlgLnkAnchorByName : "按锚点名称", DlgLnkAnchorById : "按锚点 ID", DlgLnkNoAnchors : "(此文档没有可用的锚点)", DlgLnkEMail : "地址", DlgLnkEMailSubject : "主题", DlgLnkEMailBody : "内容", DlgLnkUpload : "上传", DlgLnkBtnUpload : "发送到服务器上", DlgLnkTarget : "目标", DlgLnkTargetFrame : "<框架>", DlgLnkTargetPopup : "<弹出窗口>", DlgLnkTargetBlank : "新窗口 (_blank)", DlgLnkTargetParent : "父窗口 (_parent)", DlgLnkTargetSelf : "本窗口 (_self)", DlgLnkTargetTop : "整页 (_top)", DlgLnkTargetFrameName : "目标框架名称", DlgLnkPopWinName : "弹出窗口名称", DlgLnkPopWinFeat : "弹出窗口属性", DlgLnkPopResize : "调整大小", DlgLnkPopLocation : "地址栏", DlgLnkPopMenu : "菜单栏", DlgLnkPopScroll : "滚动条", DlgLnkPopStatus : "状态栏", DlgLnkPopToolbar : "工具栏", DlgLnkPopFullScrn : "全屏 (IE)", DlgLnkPopDependent : "依附 (NS)", DlgLnkPopWidth : "宽", DlgLnkPopHeight : "高", DlgLnkPopLeft : "左", DlgLnkPopTop : "右", DlnLnkMsgNoUrl : "请输入超链接地址", DlnLnkMsgNoEMail : "请输入电子邮件地址", DlnLnkMsgNoAnchor : "请选择一个锚点", DlnLnkMsgInvPopName : "弹出窗口名称必须以字母开头,并且不能含有空格。", // Color Dialog DlgColorTitle : "选择颜色", DlgColorBtnClear : "清除", DlgColorHighlight : "预览", DlgColorSelected : "选择", // Smiley Dialog DlgSmileyTitle : "插入表情图标", // Special Character Dialog DlgSpecialCharTitle : "选择特殊符号", // Table Dialog DlgTableTitle : "表格属性", DlgTableRows : "行数", DlgTableColumns : "列数", DlgTableBorder : "边框", DlgTableAlign : "对齐", DlgTableAlignNotSet : "<没有设置>", DlgTableAlignLeft : "左对齐", DlgTableAlignCenter : "居中", DlgTableAlignRight : "右对齐", DlgTableWidth : "宽度", DlgTableWidthPx : "像素", DlgTableWidthPc : "百分比", DlgTableHeight : "高度", DlgTableCellSpace : "间距", DlgTableCellPad : "边距", DlgTableCaption : "标题", DlgTableSummary : "摘要", DlgTableHeaders : "标题单元格", DlgTableHeadersNone : "无", DlgTableHeadersColumn : "第一列", DlgTableHeadersRow : "第一行", DlgTableHeadersBoth : "第一列和第一行", // Table Cell Dialog DlgCellTitle : "单元格属性", DlgCellWidth : "宽度", DlgCellWidthPx : "像素", DlgCellWidthPc : "百分比", DlgCellHeight : "高度", DlgCellWordWrap : "自动换行", DlgCellWordWrapNotSet : "<没有设置>", DlgCellWordWrapYes : "是", DlgCellWordWrapNo : "否", DlgCellHorAlign : "水平对齐", DlgCellHorAlignNotSet : "<没有设置>", DlgCellHorAlignLeft : "左对齐", DlgCellHorAlignCenter : "居中", DlgCellHorAlignRight: "右对齐", DlgCellVerAlign : "垂直对齐", DlgCellVerAlignNotSet : "<没有设置>", DlgCellVerAlignTop : "顶端", DlgCellVerAlignMiddle : "居中", DlgCellVerAlignBottom : "底部", DlgCellVerAlignBaseline : "基线", DlgCellType : "单元格类型", DlgCellTypeData : "资料", DlgCellTypeHeader : "标题", DlgCellRowSpan : "纵跨行数", DlgCellCollSpan : "横跨列数", DlgCellBackColor : "背景颜色", DlgCellBorderColor : "边框颜色", DlgCellBtnSelect : "选择...", // Find and Replace Dialog DlgFindAndReplaceTitle : "查找和替换", // Find Dialog DlgFindTitle : "查找", DlgFindFindBtn : "查找", DlgFindNotFoundMsg : "指定文本没有找到。", // Replace Dialog DlgReplaceTitle : "替换", DlgReplaceFindLbl : "查找:", DlgReplaceReplaceLbl : "替换:", DlgReplaceCaseChk : "区分大小写", DlgReplaceReplaceBtn : "替换", DlgReplaceReplAllBtn : "全部替换", DlgReplaceWordChk : "全字匹配", // Paste Operations / Dialog PasteErrorCut : "您的浏览器安全设置不允许编辑器自动执行剪切操作,请使用键盘快捷键(Ctrl+X)来完成。", PasteErrorCopy : "您的浏览器安全设置不允许编辑器自动执行复制操作,请使用键盘快捷键(Ctrl+C)来完成。", PasteAsText : "粘贴为无格式文本", PasteFromWord : "从 MS Word 粘贴", DlgPasteMsg2 : "请使用键盘快捷键(<STRONG>Ctrl+V</STRONG>)把内容粘贴到下面的方框里,再按 <STRONG>确定</STRONG>。", DlgPasteSec : "因为你的浏览器的安全设置原因,本编辑器不能直接访问你的剪贴板内容,你需要在本窗口重新粘贴一次。", DlgPasteIgnoreFont : "忽略 Font 标签", DlgPasteRemoveStyles : "清理 CSS 样式", // Color Picker ColorAutomatic : "自动", ColorMoreColors : "其它颜色...", // Document Properties DocProps : "页面属性", // Anchor Dialog DlgAnchorTitle : "命名锚点", DlgAnchorName : "锚点名称", DlgAnchorErrorName : "请输入锚点名称", // Speller Pages Dialog DlgSpellNotInDic : "没有在字典里", DlgSpellChangeTo : "更改为", DlgSpellBtnIgnore : "忽略", DlgSpellBtnIgnoreAll : "全部忽略", DlgSpellBtnReplace : "替换", DlgSpellBtnReplaceAll : "全部替换", DlgSpellBtnUndo : "撤消", DlgSpellNoSuggestions : "- 没有建议 -", DlgSpellProgress : "正在进行拼写检查...", DlgSpellNoMispell : "拼写检查完成:没有发现拼写错误", DlgSpellNoChanges : "拼写检查完成:没有更改任何单词", DlgSpellOneChange : "拼写检查完成:更改了一个单词", DlgSpellManyChanges : "拼写检查完成:更改了 %1 个单词", IeSpellDownload : "拼写检查插件还没安装,你是否想现在就下载?", // Button Dialog DlgButtonText : "标签(值)", DlgButtonType : "类型", DlgButtonTypeBtn : "按钮", DlgButtonTypeSbm : "提交", DlgButtonTypeRst : "重设", // Checkbox and Radio Button Dialogs DlgCheckboxName : "名称", DlgCheckboxValue : "选定值", DlgCheckboxSelected : "已勾选", // Form Dialog DlgFormName : "名称", DlgFormAction : "动作", DlgFormMethod : "方法", // Select Field Dialog DlgSelectName : "名称", DlgSelectValue : "选定", DlgSelectSize : "高度", DlgSelectLines : "行", DlgSelectChkMulti : "允许多选", DlgSelectOpAvail : "列表值", DlgSelectOpText : "标签", DlgSelectOpValue : "值", DlgSelectBtnAdd : "新增", DlgSelectBtnModify : "修改", DlgSelectBtnUp : "上移", DlgSelectBtnDown : "下移", DlgSelectBtnSetValue : "设为初始化时选定", DlgSelectBtnDelete : "删除", // Textarea Dialog DlgTextareaName : "名称", DlgTextareaCols : "字符宽度", DlgTextareaRows : "行数", // Text Field Dialog DlgTextName : "名称", DlgTextValue : "初始值", DlgTextCharWidth : "字符宽度", DlgTextMaxChars : "最多字符数", DlgTextType : "类型", DlgTextTypeText : "文本", DlgTextTypePass : "密码", // Hidden Field Dialog DlgHiddenName : "名称", DlgHiddenValue : "初始值", // Bulleted List Dialog BulletedListProp : "项目列表属性", NumberedListProp : "编号列表属性", DlgLstStart : "开始序号", DlgLstType : "列表类型", DlgLstTypeCircle : "圆圈", DlgLstTypeDisc : "圆点", DlgLstTypeSquare : "方块", DlgLstTypeNumbers : "数字 (1, 2, 3)", DlgLstTypeLCase : "小写字母 (a, b, c)", DlgLstTypeUCase : "大写字母 (A, B, C)", DlgLstTypeSRoman : "小写罗马数字 (i, ii, iii)", DlgLstTypeLRoman : "大写罗马数字 (I, II, III)", // Document Properties Dialog DlgDocGeneralTab : "常规", DlgDocBackTab : "背景", DlgDocColorsTab : "颜色和边距", DlgDocMetaTab : "Meta 数据", DlgDocPageTitle : "页面标题", DlgDocLangDir : "语言方向", DlgDocLangDirLTR : "从左到右 (LTR)", DlgDocLangDirRTL : "从右到左 (RTL)", DlgDocLangCode : "语言代码", DlgDocCharSet : "字符编码", DlgDocCharSetCE : "中欧", DlgDocCharSetCT : "繁体中文 (Big5)", DlgDocCharSetCR : "西里尔文", DlgDocCharSetGR : "希腊文", DlgDocCharSetJP : "日文", DlgDocCharSetKR : "韩文", DlgDocCharSetTR : "土耳其文", DlgDocCharSetUN : "Unicode (UTF-8)", DlgDocCharSetWE : "西欧", DlgDocCharSetOther : "其它字符编码", DlgDocDocType : "文档类型", DlgDocDocTypeOther : "其它文档类型", DlgDocIncXHTML : "包含 XHTML 声明", DlgDocBgColor : "背景颜色", DlgDocBgImage : "背景图像", DlgDocBgNoScroll : "不滚动背景图像", DlgDocCText : "文本", DlgDocCLink : "超链接", DlgDocCVisited : "已访问的超链接", DlgDocCActive : "活动超链接", DlgDocMargins : "页面边距", DlgDocMaTop : "上", DlgDocMaLeft : "左", DlgDocMaRight : "右", DlgDocMaBottom : "下", DlgDocMeIndex : "页面索引关键字 (用半角逗号[,]分隔)", DlgDocMeDescr : "页面说明", DlgDocMeAuthor : "作者", DlgDocMeCopy : "版权", DlgDocPreview : "预览", // Templates Dialog Templates : "模板", DlgTemplatesTitle : "内容模板", DlgTemplatesSelMsg : "请选择编辑器内容模板:", DlgTemplatesLoading : "正在加载模板列表,请稍等...", DlgTemplatesNoTpl : "(没有模板)", DlgTemplatesReplace : "替换当前内容", // About Dialog DlgAboutAboutTab : "关于", DlgAboutBrowserInfoTab : "浏览器信息", DlgAboutLicenseTab : "许可证", DlgAboutVersion : "版本", DlgAboutInfo : "要获得更多信息请访问 ", // Div Dialog DlgDivGeneralTab : "常规", DlgDivAdvancedTab : "高级", DlgDivStyle : "样式", DlgDivInlineStyle : "CSS 样式", ScaytTitle : "SCAYT", //MISSING ScaytTitleOptions : "Options", //MISSING ScaytTitleLangs : "Languages", //MISSING ScaytTitleAbout : "About" //MISSING };
JavaScript
$(document).ready(function(){ // 回到顶部 $('#gotop').click(function(){ $('body,html').animate({scrollTop:0},1000); }); // 检查评论 $('#comment_nick').focus(function(){ if ($('#comment_nick').val() == '邮箱或称呼…'){ $('#comment_nick').removeClass('init-comment-box'); $('#comment_nick').val(''); } }); $('#comment_nick').blur(function(){ if ($('#comment_nick').val() == ''){ $('#comment_nick').addClass('init-comment-box'); $('#comment_nick').val('邮箱或称呼…'); } }); $('#comment_input').focus(function(){ if ($('#comment_input').val() == '内容…'){ $('#comment_input').removeClass('init-comment-box'); $('#comment_input').val(''); } }); $('#comment_input').blur(function(){ if ($('#comment_input').val() == ''){ $('#comment_input').addClass('init-comment-box'); $('#comment_input').val('内容…'); } }); $('#comment_submit').click(function(){ comment_nick = $('#comment_nick').val(); comment_input = $('#comment_input').val(); if (comment_nick == '' || comment_nick == '邮箱或称呼…'){ alert('称呼错误'); return; } if (comment_input == '' || comment_input == '内容…'){ alert('评论错误'); return; } $('#form_comment').submit(); }); // 喜欢 $('a[id^="like_add_"]').click(function(){ if ($(this).attr('liked') == 1){ alert('喜欢,只要一次就够了'); return; } aid = $(this).attr('aid'); like_url = '/bzbj/like'; $.post(like_url, {aid:aid}, function(result){ if (result.code == 0){ alert(result.msg); }else{ $('#like_num_'+aid).html(result.likenum); $('#like_add_'+aid).attr('liked', 1); } }, 'json'); }); });
JavaScript
$(document).ready(function(){ //Sidebar Accordion Menu: $("#main-nav li ul").hide(); // Hide all sub menus $("#main-nav li a.current").parent().find("ul").slideToggle("slow"); // Slide down the current menu item's sub menu $("#main-nav li a.nav-top-item").click( // When a top menu item is clicked... function () { $(this).parent().siblings().find("ul").slideUp("normal"); // Slide up all sub menus except the one clicked $(this).next().slideToggle("normal"); // Slide down the clicked sub menu return false; } ); $("#main-nav li a.no-submenu").click( // When a menu item with no sub menu is clicked... function () { window.location.href=(this.href); // Just open the link instead of a sub menu return false; } ); // Sidebar Accordion Menu Hover Effect: $("#main-nav li .nav-top-item").hover( function () { $(this).stop().animate({ paddingRight: "25px" }, 200); }, function () { $(this).stop().animate({ paddingRight: "15px" }); } ); //Minimize Content Box $(".content-box-header h3").css({ "cursor":"s-resize" }); // Give the h3 in Content Box Header a different cursor $(".closed-box .content-box-content").hide(); // Hide the content of the header if it has the class "closed" $(".closed-box .content-box-tabs").hide(); // Hide the tabs in the header if it has the class "closed" $(".content-box-header h3").click( // When the h3 is clicked... function () { $(this).parent().next().toggle(); // Toggle the Content Box $(this).parent().parent().toggleClass("closed-box"); // Toggle the class "closed-box" on the content box $(this).parent().find(".content-box-tabs").toggle(); // Toggle the tabs } ); // Content box tabs: $('.content-box .content-box-content div.tab-content').hide(); // Hide the content divs $('ul.content-box-tabs li a.default-tab').addClass('current'); // Add the class "current" to the default tab $('.content-box-content div.default-tab').show(); // Show the div with class "default-tab" $('.content-box ul.content-box-tabs li a').click( // When a tab is clicked... function() { $(this).parent().siblings().find("a").removeClass('current'); // Remove "current" class from all tabs $(this).addClass('current'); // Add class "current" to clicked tab var currentTab = $(this).attr('href'); // Set variable "currentTab" to the value of href of clicked tab $(currentTab).siblings().hide(); // Hide all content divs $(currentTab).show(); // Show the content div with the id equal to the id of clicked tab return false; } ); //Close button: $(".close").click( function () { $(this).parent().fadeTo(400, 0, function () { // Links with the class "close" will close parent $(this).slideUp(400); }); return false; } ); // Alternating table rows: $('tbody tr:even').addClass("alt-row"); // Add class "alt-row" to even table rows // Check all checkboxes when the one in a table head is checked: $('.check-all').click( function(){ $(this).parent().parent().parent().parent().find("input[type='checkbox']").attr('checked', $(this).is(':checked')); } ); // Initialise Facebox Modal window: $('a[rel*=modal]').facebox(); // Applies modal window to any link with attribute rel="modal" // Initialise jQuery WYSIWYG: //$(".wysiwyg").wysiwyg(); // Applies WYSIWYG editor to any textarea with the class "wysiwyg" });
JavaScript
/* * Facebox (for jQuery) * version: 1.2 (05/05/2008) * @requires jQuery v1.2 or later * * Examples at http://famspam.com/facebox/ * * Licensed under the MIT: * http://www.opensource.org/licenses/mit-license.php * * Copyright 2007, 2008 Chris Wanstrath [ chris@ozmm.org ] * * Usage: * * jQuery(document).ready(function() { * jQuery('a[rel*=facebox]').facebox() * }) * * <a href="#terms" rel="facebox">Terms</a> * Loads the #terms div in the box * * <a href="terms.html" rel="facebox">Terms</a> * Loads the terms.html page in the box * * <a href="terms.png" rel="facebox">Terms</a> * Loads the terms.png image in the box * * * You can also use it programmatically: * * jQuery.facebox('some html') * * The above will open a facebox with "some html" as the content. * * jQuery.facebox(function($) { * $.get('blah.html', function(data) { $.facebox(data) }) * }) * * The above will show a loading screen before the passed function is called, * allowing for a better ajaxy experience. * * The facebox function can also display an ajax page or image: * * jQuery.facebox({ ajax: 'remote.html' }) * jQuery.facebox({ image: 'dude.jpg' }) * * Want to close the facebox? Trigger the 'close.facebox' document event: * * jQuery(document).trigger('close.facebox') * * Facebox also has a bunch of other hooks: * * loading.facebox * beforeReveal.facebox * reveal.facebox (aliased as 'afterReveal.facebox') * init.facebox * * Simply bind a function to any of these hooks: * * $(document).bind('reveal.facebox', function() { ...stuff to do after the facebox and contents are revealed... }) * */ (function($) { $.facebox = function(data, klass) { $.facebox.loading() if (data.ajax) fillFaceboxFromAjax(data.ajax) else if (data.image) fillFaceboxFromImage(data.image) else if (data.div) fillFaceboxFromHref(data.div) else if ($.isFunction(data)) data.call($) else $.facebox.reveal(data, klass) } /* * Public, $.facebox methods */ $.extend($.facebox, { settings: { opacity : 0, overlay : true, loadingImage : '/ae/images/loading.gif', closeImage : '/ae/images/closelabel.gif', imageTypes : [ 'png', 'jpg', 'jpeg', 'gif' ], faceboxHtml : '\ <div id="facebox" style="display:none;"> \ <div class="popup"> \ <table> \ <tbody> \ <tr> \ <td class="tl"/><td class="b"/><td class="tr"/> \ </tr> \ <tr> \ <td class="b"/> \ <td class="body"> \ <div class="content"> \ </div> \ <div class="footer"> \ <a href="#" class="close"> \ <img src="/ae/images/closelabel.gif" title="close" class="close_image" /> \ </a> \ </div> \ </td> \ <td class="b"/> \ </tr> \ <tr> \ <td class="bl"/><td class="b"/><td class="br"/> \ </tr> \ </tbody> \ </table> \ </div> \ </div>' }, loading: function() { init() if ($('#facebox .loading').length == 1) return true showOverlay() $('#facebox .content').empty() $('#facebox .body').children().hide().end(). append('<div class="loading"><img src="'+$.facebox.settings.loadingImage+'"/></div>') $('#facebox').css({ top: getPageScroll()[1] + (getPageHeight() / 10), left: 385.5 }).show() $(document).bind('keydown.facebox', function(e) { if (e.keyCode == 27) $.facebox.close() return true }) $(document).trigger('loading.facebox') }, reveal: function(data, klass) { $(document).trigger('beforeReveal.facebox') if (klass) $('#facebox .content').addClass(klass) $('#facebox .content').append(data) $('#facebox .loading').remove() $('#facebox .body').children().fadeIn('normal') $('#facebox').css('left', $(window).width() / 2 - ($('#facebox table').width() / 2)) $(document).trigger('reveal.facebox').trigger('afterReveal.facebox') }, close: function() { $(document).trigger('close.facebox') return false } }) /* * Public, $.fn methods */ $.fn.facebox = function(settings) { init(settings) function clickHandler() { $.facebox.loading(true) // support for rel="facebox.inline_popup" syntax, to add a class // also supports deprecated "facebox[.inline_popup]" syntax var klass = this.rel.match(/facebox\[?\.(\w+)\]?/) if (klass) klass = klass[1] fillFaceboxFromHref(this.href, klass) return false } return this.click(clickHandler) } /* * Private methods */ // called one time to setup facebox on this page function init(settings) { if ($.facebox.settings.inited) return true else $.facebox.settings.inited = true $(document).trigger('init.facebox') makeCompatible() var imageTypes = $.facebox.settings.imageTypes.join('|') $.facebox.settings.imageTypesRegexp = new RegExp('\.' + imageTypes + '$', 'i') if (settings) $.extend($.facebox.settings, settings) $('body').append($.facebox.settings.faceboxHtml) var preload = [ new Image(), new Image() ] preload[0].src = $.facebox.settings.closeImage preload[1].src = $.facebox.settings.loadingImage $('#facebox').find('.b:first, .bl, .br, .tl, .tr').each(function() { preload.push(new Image()) preload.slice(-1).src = $(this).css('background-image').replace(/url\((.+)\)/, '$1') }) $('#facebox .close').click($.facebox.close) $('#facebox .close_image').attr('src', $.facebox.settings.closeImage) } // getPageScroll() by quirksmode.com function getPageScroll() { var xScroll, yScroll; if (self.pageYOffset) { yScroll = self.pageYOffset; xScroll = self.pageXOffset; } else if (document.documentElement && document.documentElement.scrollTop) { // Explorer 6 Strict yScroll = document.documentElement.scrollTop; xScroll = document.documentElement.scrollLeft; } else if (document.body) {// all other Explorers yScroll = document.body.scrollTop; xScroll = document.body.scrollLeft; } return new Array(xScroll,yScroll) } // Adapted from getPageSize() by quirksmode.com function getPageHeight() { var windowHeight if (self.innerHeight) { // all except Explorer windowHeight = self.innerHeight; } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode windowHeight = document.documentElement.clientHeight; } else if (document.body) { // other Explorers windowHeight = document.body.clientHeight; } return windowHeight } // Backwards compatibility function makeCompatible() { var $s = $.facebox.settings $s.loadingImage = $s.loading_image || $s.loadingImage $s.closeImage = $s.close_image || $s.closeImage $s.imageTypes = $s.image_types || $s.imageTypes $s.faceboxHtml = $s.facebox_html || $s.faceboxHtml } // Figures out what you want to display and displays it // formats are: // div: #id // image: blah.extension // ajax: anything else function fillFaceboxFromHref(href, klass) { // div if (href.match(/#/)) { var url = window.location.href.split('#')[0] var target = href.replace(url,'') $.facebox.reveal($(target).clone().show(), klass) // image } else if (href.match($.facebox.settings.imageTypesRegexp)) { fillFaceboxFromImage(href, klass) // ajax } else { fillFaceboxFromAjax(href, klass) } } function fillFaceboxFromImage(href, klass) { var image = new Image() image.onload = function() { $.facebox.reveal('<div class="image"><img src="' + image.src + '" /></div>', klass) } image.src = href } function fillFaceboxFromAjax(href, klass) { $.get(href, function(data) { $.facebox.reveal(data, klass) }) } function skipOverlay() { return $.facebox.settings.overlay == false || $.facebox.settings.opacity === null } function showOverlay() { if (skipOverlay()) return if ($('facebox_overlay').length == 0) $("body").append('<div id="facebox_overlay" class="facebox_hide"></div>') $('#facebox_overlay').hide().addClass("facebox_overlayBG") .css('opacity', $.facebox.settings.opacity) .click(function() { $(document).trigger('close.facebox') }) .fadeIn(200) return false } function hideOverlay() { if (skipOverlay()) return $('#facebox_overlay').fadeOut(200, function(){ $("#facebox_overlay").removeClass("facebox_overlayBG") $("#facebox_overlay").addClass("facebox_hide") $("#facebox_overlay").remove() }) return false } /* * Bindings */ $(document).bind('close.facebox', function() { $(document).unbind('keydown.facebox') $('#facebox').fadeOut(function() { $('#facebox .content').removeClass().addClass('content') hideOverlay() $('#facebox .loading').remove() }) }) })(jQuery);
JavaScript
//by zhanyi function uParse(selector,opt){ var ie = !!window.ActiveXObject, cssRule = ie ? function(key,style,doc){ var indexList,index; doc = doc || document; if(doc.indexList){ indexList = doc.indexList; }else{ indexList = doc.indexList = {}; } var sheetStyle; if(!indexList[key]){ if(style === undefined){ return '' } sheetStyle = doc.createStyleSheet('',index = doc.styleSheets.length); indexList[key] = index; }else{ sheetStyle = doc.styleSheets[indexList[key]]; } if(style === undefined){ return sheetStyle.cssText } sheetStyle.cssText = sheetStyle.cssText + '\n' + (style || '') } : function(key,style,doc){ doc = doc || document; var head = doc.getElementsByTagName('head')[0],node; if(!(node = doc.getElementById(key))){ if(style === undefined){ return '' } node = doc.createElement('style'); node.id = key; head.appendChild(node) } if(style === undefined){ return node.innerHTML } if(style !== ''){ node.innerHTML = node.innerHTML + '\n' + style; }else{ head.removeChild(node) } }, domReady = function (onready) { var doc = window.document; if (doc.readyState === "complete") { onready(); }else{ if (ie) { (function () { if (doc.isReady) return; try { doc.documentElement.doScroll("left"); } catch (error) { setTimeout(arguments.callee, 0); return; } onready(); })(); window.attachEvent('onload', function(){ onready() }); } else { doc.addEventListener("DOMContentLoaded", function () { doc.removeEventListener("DOMContentLoaded", arguments.callee, false); onready(); }, false); window.addEventListener('load', function(){onready()}, false); } } }, _each = function(obj, iterator, context) { if (obj == null) return; if (obj.length === +obj.length) { for (var i = 0, l = obj.length; i < l; i++) { if(iterator.call(context, obj[i], i, obj) === false) return false; } } else { for (var key in obj) { if (obj.hasOwnProperty(key)) { if(iterator.call(context, obj[key], key, obj) === false) return false; } } } }, inArray = function(arr,item){ var index = -1; _each(arr,function(v,i){ if(v === item){ index = i; return false; } }); return index; }, pushItem = function(arr,item){ if(inArray(arr,item)==-1){ arr.push(item) } }, loadFile = function () { var tmpList = []; function getItem(doc,obj){ try{ for(var i= 0,ci;ci=tmpList[i++];){ if(ci.doc === doc && ci.url == (obj.src || obj.href)){ return ci; } } }catch(e){ return null; } } return function (doc, obj, fn) { var item = getItem(doc,obj); if (item) { if(item.ready){ fn && fn(); }else{ item.funs.push(fn) } return; } tmpList.push({ doc:doc, url:obj.src||obj.href, funs:[fn] }); if (!doc.body) { var html = []; for(var p in obj){ if(p == 'tag')continue; html.push(p + '="' + obj[p] + '"') } doc.write('<' + obj.tag + ' ' + html.join(' ') + ' ></'+obj.tag+'>'); return; } if (obj.id && doc.getElementById(obj.id)) { return; } var element = doc.createElement(obj.tag); delete obj.tag; for (var p in obj) { element.setAttribute(p, obj[p]); } element.onload = element.onreadystatechange = function () { if (!this.readyState || /loaded|complete/.test(this.readyState)) { item = getItem(doc,obj); if (item.funs.length > 0) { item.ready = 1; for (var fi; fi = item.funs.pop();) { fi(); } } element.onload = element.onreadystatechange = null; } }; element.onerror = function(){ throw Error('The load '+(obj.href||obj.src)+' fails,check the url') }; doc.getElementsByTagName("head")[0].appendChild(element); } }(); var defaultOption ={ liiconpath : 'http://bs.baidu.com/listicon/', listDefaultPaddingLeft : '20', 'highlightJsUrl':'', 'highlightCssUrl':'', customRule:function(){} }; if(opt){ for(var p in opt){ defaultOption[p] = opt[p] } } domReady(function(){ var contents; if(document.querySelectorAll){ contents = document.querySelectorAll(selector) }else{ if(/^#/.test(selector)){ contents = [document.getElementById(selector.replace(/^#/,''))] }else if(/^\./.test(selector)){ var contents = []; _each(document.getElementsByTagName('*'),function(node){ if(node.className && new RegExp('\\b' + selector.replace(/^\./,'') + '\\b','i').test(node.className)){ contents.push(node) } }) }else{ contents = document.getElementsByTagName(selector) } } _each(contents,function(content){ if(content.tagName.toLowerCase() == 'textarea'){ var tmpNode = document.createElement('div'); if(/^#/.test(selector)){ tmpNode.id = selector.replace(/^#/,'') }else if(/^\./.test(selector)){ tmpNode.className = selector.replace(/^\./,'') } content.parentNode.insertBefore(tmpNode,content); tmpNode.innerHTML = content.value; content.parentNode.removeChild(content); content = tmpNode; } function fillNode(nodes){ _each(nodes,function(node){ if(!node.firstChild){ node.innerHTML = '&nbsp;' } }) } function checkList(nodes){ var customCss = [], customStyle = { 'cn' : 'cn-1-', 'cn1' : 'cn-2-', 'cn2' : 'cn-3-', 'num' : 'num-1-', 'num1' : 'num-2-', 'num2' : 'num-3-', 'dash' : 'dash', 'dot' : 'dot' }; _each(nodes,function(list){ if(list.className && /custom_/i.test(list.className)){ var listStyle = list.className.match(/custom_(\w+)/)[1]; if(listStyle == 'dash' || listStyle == 'dot'){ pushItem(customCss,selector +' li.list-' + customStyle[listStyle] + '{background-image:url(' + defaultOption.liiconpath +customStyle[listStyle]+'.gif)}'); pushItem(customCss,selector +' ul.custom_'+listStyle+'{list-style:none;} '+ selector +' ul.custom_'+listStyle+' li{background-position:0 3px;background-repeat:no-repeat}'); }else{ var index = 1; _each(list.childNodes,function(li){ if(li.tagName == 'LI'){ pushItem(customCss,selector + ' li.list-' + customStyle[listStyle] + index + '{background-image:url(' + defaultOption.liiconpath + 'list-'+customStyle[listStyle] +index + '.gif)}'); index++; } }); pushItem(customCss,selector + ' ol.custom_'+listStyle+'{list-style:none;}'+selector+' ol.custom_'+listStyle+' li{background-position:0 3px;background-repeat:no-repeat}'); } switch(listStyle){ case 'cn': pushItem(customCss,selector + ' li.list-'+listStyle+'-paddingleft-1{padding-left:25px}'); pushItem(customCss,selector + ' li.list-'+listStyle+'-paddingleft-2{padding-left:40px}'); pushItem(customCss,selector + ' li.list-'+listStyle+'-paddingleft-3{padding-left:55px}'); break; case 'cn1': pushItem(customCss,selector + ' li.list-'+listStyle+'-paddingleft-1{padding-left:30px}'); pushItem(customCss,selector + ' li.list-'+listStyle+'-paddingleft-2{padding-left:40px}'); pushItem(customCss,selector + ' li.list-'+listStyle+'-paddingleft-3{padding-left:55px}'); break; case 'cn2': pushItem(customCss,selector + ' li.list-'+listStyle+'-paddingleft-1{padding-left:40px}'); pushItem(customCss,selector + ' li.list-'+listStyle+'-paddingleft-2{padding-left:55px}'); pushItem(customCss,selector + ' li.list-'+listStyle+'-paddingleft-3{padding-left:68px}'); break; case 'num': case 'num1': pushItem(customCss,selector + ' li.list-'+listStyle+'-paddingleft-1{padding-left:25px}'); break; case 'num2': pushItem(customCss,selector + ' li.list-'+listStyle+'-paddingleft-1{padding-left:35px}'); pushItem(customCss,selector + ' li.list-'+listStyle+'-paddingleft-2{padding-left:40px}'); break; case 'dash': pushItem(customCss,selector + ' li.list-'+listStyle+'-paddingleft{padding-left:35px}'); break; case 'dot': pushItem(customCss,selector + ' li.list-'+listStyle+'-paddingleft{padding-left:20px}'); } } }); customCss.push(selector +' .list-paddingleft-1{padding-left:0}'); customCss.push(selector +' .list-paddingleft-2{padding-left:'+defaultOption.listDefaultPaddingLeft+'px}'); customCss.push(selector +' .list-paddingleft-3{padding-left:'+defaultOption.listDefaultPaddingLeft*2+'px}'); cssRule('list', selector +' ol,'+selector +' ul{margin:0;padding:0;}li{clear:both;}'+customCss.join('\n'), document); } var needParseTagName = { 'table' : function(){ cssRule('table', selector +' table.noBorderTable td,'+selector+' table.noBorderTable th,'+selector+' table.noBorderTable caption{border:1px dashed #ddd !important}' + selector +' table{margin-bottom:10px;border-collapse:collapse;display:table;}' + selector +' td,'+selector+' th{ background:white; padding: 5px 10px;border: 1px solid #DDD;}' + selector +' caption{border:1px dashed #DDD;border-bottom:0;padding:3px;text-align:center;}' + selector +' th{border-top:2px solid #BBB;background:#F7F7F7;}' + selector +' td p{margin:0;padding:0;}', document); }, 'ol' : checkList, 'ul' : checkList, 'pre': function(nodes){ if(typeof XRegExp == "undefined"){ loadFile(document,{ id : "syntaxhighlighter_js", src : defaultOption.highlightJsUrl, tag : "script", type : "text/javascript", defer : "defer" },function(){ _each(nodes,function(pi){ if(pi && /brush/i.test(pi.className)){ SyntaxHighlighter.highlight(pi); // var tables = document.getElementsByTagName('table'); // for(var t= 0,ti;ti=tables[t++];){ // if(/SyntaxHighlighter/i.test(ti.className)){ // var tds = ti.getElementsByTagName('td'); // for(var i=0,li,ri;li=tds[0].childNodes[i];i++){ // ri = tds[1].firstChild.childNodes[i]; // if(ri){ // ri.style.height = li.style.height = ri.offsetHeight + 'px'; // } // } // } // } } }); }); } if(!document.getElementById("syntaxhighlighter_css")){ loadFile(document,{ id : "syntaxhighlighter_css", tag : "link", rel : "stylesheet", type : "text/css", href : defaultOption.highlightCssUrl }); } }, 'td':fillNode, 'th':fillNode, 'caption':fillNode }; for(var tag in needParseTagName){ var nodes = content.getElementsByTagName(tag); if(nodes.length){ needParseTagName[tag](nodes) } } defaultOption.customRule(content); }); }) }
JavaScript
(function(){ UEDITOR_CONFIG = window.UEDITOR_CONFIG || {}; var baidu = window.baidu || {}; window.baidu = baidu; window.UE = baidu.editor = {}; UE.plugins = {}; UE.commands = {}; UE.instants = {}; UE.I18N = {}; UE.version = "1.2.6.1"; var dom = UE.dom = {};/** * @file * @name UE.browser * @short Browser * @desc UEditor中采用的浏览器判断模块 */ var browser = UE.browser = function(){ var agent = navigator.userAgent.toLowerCase(), opera = window.opera, browser = { /** * 检测浏览器是否为IE * @name ie * @grammar UE.browser.ie => true|false */ ie : !!window.ActiveXObject, /** * 检测浏览器是否为Opera * @name opera * @grammar UE.browser.opera => true|false */ opera : ( !!opera && opera.version ), /** * 检测浏览器是否为webkit内核 * @name webkit * @grammar UE.browser.webkit => true|false */ webkit : ( agent.indexOf( ' applewebkit/' ) > -1 ), /** * 检测浏览器是否为mac系统下的浏览器 * @name mac * @grammar UE.browser.mac => true|false */ mac : ( agent.indexOf( 'macintosh' ) > -1 ), /** * 检测浏览器是否处于怪异模式 * @name quirks * @grammar UE.browser.quirks => true|false */ quirks : ( document.compatMode == 'BackCompat' ) }; /** * 检测浏览器是否处为gecko内核 * @name gecko * @grammar UE.browser.gecko => true|false */ browser.gecko =( navigator.product == 'Gecko' && !browser.webkit && !browser.opera ); var version = 0; // Internet Explorer 6.0+ if ( browser.ie ){ version = parseFloat( agent.match( /msie (\d+)/ )[1] ); /** * 检测浏览器是否为 IE9 模式 * @name ie9Compat * @grammar UE.browser.ie9Compat => true|false */ browser.ie9Compat = document.documentMode == 9; /** * 检测浏览器是否为 IE8 浏览器 * @name ie8 * @grammar UE.browser.ie8 => true|false */ browser.ie8 = !!document.documentMode; /** * 检测浏览器是否为 IE8 模式 * @name ie8Compat * @grammar UE.browser.ie8Compat => true|false */ browser.ie8Compat = document.documentMode == 8; /** * 检测浏览器是否运行在 兼容IE7模式 * @name ie7Compat * @grammar UE.browser.ie7Compat => true|false */ browser.ie7Compat = ( ( version == 7 && !document.documentMode ) || document.documentMode == 7 ); /** * 检测浏览器是否IE6模式或怪异模式 * @name ie6Compat * @grammar UE.browser.ie6Compat => true|false */ browser.ie6Compat = ( version < 7 || browser.quirks ); } // Gecko. if ( browser.gecko ){ var geckoRelease = agent.match( /rv:([\d\.]+)/ ); if ( geckoRelease ) { geckoRelease = geckoRelease[1].split( '.' ); version = geckoRelease[0] * 10000 + ( geckoRelease[1] || 0 ) * 100 + ( geckoRelease[2] || 0 ) * 1; } } /** * 检测浏览器是否为chrome * @name chrome * @grammar UE.browser.chrome => true|false */ if (/chrome\/(\d+\.\d)/i.test(agent)) { browser.chrome = + RegExp['\x241']; } /** * 检测浏览器是否为safari * @name safari * @grammar UE.browser.safari => true|false */ if(/(\d+\.\d)?(?:\.\d)?\s+safari\/?(\d+\.\d+)?/i.test(agent) && !/chrome/i.test(agent)){ browser.safari = + (RegExp['\x241'] || RegExp['\x242']); } // Opera 9.50+ if ( browser.opera ) version = parseFloat( opera.version() ); // WebKit 522+ (Safari 3+) if ( browser.webkit ) version = parseFloat( agent.match( / applewebkit\/(\d+)/ )[1] ); /** * 浏览器版本判断 * IE系列返回值为5,6,7,8,9,10等 * gecko系列会返回10900,158900等. * webkit系列会返回其build号 (如 522等). * @name version * @grammar UE.browser.version => number * @example * if ( UE.browser.ie && UE.browser.version == 6 ){ * alert( "Ouch!居然是万恶的IE6!" ); * } */ browser.version = version; /** * 是否是兼容模式的浏览器 * @name isCompatible * @grammar UE.browser.isCompatible => true|false * @example * if ( UE.browser.isCompatible ){ * alert( "你的浏览器相当不错哦!" ); * } */ browser.isCompatible = !browser.mobile && ( ( browser.ie && version >= 6 ) || ( browser.gecko && version >= 10801 ) || ( browser.opera && version >= 9.5 ) || ( browser.air && version >= 1 ) || ( browser.webkit && version >= 522 ) || false ); return browser; }(); //快捷方式 var ie = browser.ie, webkit = browser.webkit, gecko = browser.gecko, opera = browser.opera;/** * @file * @name UE.Utils * @short Utils * @desc UEditor封装使用的静态工具函数 * @import editor.js */ var utils = UE.utils = { /** * 遍历数组,对象,nodeList * @name each * @grammar UE.utils.each(obj,iterator,[context]) * @since 1.2.4+ * @desc * * obj 要遍历的对象 * * iterator 遍历的方法,方法的第一个是遍历的值,第二个是索引,第三个是obj * * context iterator的上下文 * @example * UE.utils.each([1,2],function(v,i){ * console.log(v)//值 * console.log(i)//索引 * }) * UE.utils.each(document.getElementsByTagName('*'),function(n){ * console.log(n.tagName) * }) */ each : function(obj, iterator, context) { if (obj == null) return; if (obj.length === +obj.length) { for (var i = 0, l = obj.length; i < l; i++) { if(iterator.call(context, obj[i], i, obj) === false) return false; } } else { for (var key in obj) { if (obj.hasOwnProperty(key)) { if(iterator.call(context, obj[key], key, obj) === false) return false; } } } }, makeInstance:function (obj) { var noop = new Function(); noop.prototype = obj; obj = new noop; noop.prototype = null; return obj; }, /** * 将source对象中的属性扩展到target对象上 * @name extend * @grammar UE.utils.extend(target,source) => Object //覆盖扩展 * @grammar UE.utils.extend(target,source,true) ==> Object //保留扩展 */ extend:function (t, s, b) { if (s) { for (var k in s) { if (!b || !t.hasOwnProperty(k)) { t[k] = s[k]; } } } return t; }, extend2:function (t) { var a = arguments; for (var i = 1; i < a.length; i++) { var x = a[i]; for (var k in x) { if (!t.hasOwnProperty(k)) { t[k] = x[k]; } } } return t; }, /** * 模拟继承机制,subClass继承superClass * @name inherits * @grammar UE.utils.inherits(subClass,superClass) => subClass * @example * function SuperClass(){ * this.name = "小李"; * } * SuperClass.prototype = { * hello:function(str){ * console.log(this.name + str); * } * } * function SubClass(){ * this.name = "小张"; * } * UE.utils.inherits(SubClass,SuperClass); * var sub = new SubClass(); * sub.hello("早上好!"); ==> "小张早上好!" */ inherits:function (subClass, superClass) { var oldP = subClass.prototype, newP = utils.makeInstance(superClass.prototype); utils.extend(newP, oldP, true); subClass.prototype = newP; return (newP.constructor = subClass); }, /** * 用指定的context作为fn上下文,也就是this * @name bind * @grammar UE.utils.bind(fn,context) => fn */ bind:function (fn, context) { return function () { return fn.apply(context, arguments); }; }, /** * 创建延迟delay执行的函数fn * @name defer * @grammar UE.utils.defer(fn,delay) =>fn //延迟delay毫秒执行fn,返回fn * @grammar UE.utils.defer(fn,delay,exclusion) =>fn //延迟delay毫秒执行fn,若exclusion为真,则互斥执行fn * @example * function test(){ * console.log("延迟输出!"); * } * //非互斥延迟执行 * var testDefer = UE.utils.defer(test,1000); * testDefer(); => "延迟输出!"; * testDefer(); => "延迟输出!"; * //互斥延迟执行 * var testDefer1 = UE.utils.defer(test,1000,true); * testDefer1(); => //本次不执行 * testDefer1(); => "延迟输出!"; */ defer:function (fn, delay, exclusion) { var timerID; return function () { if (exclusion) { clearTimeout(timerID); } timerID = setTimeout(fn, delay); }; }, /** * 查找元素item在数组array中的索引, 若找不到返回-1 * @name indexOf * @grammar UE.utils.indexOf(array,item) => index|-1 //默认从数组开头部开始搜索 * @grammar UE.utils.indexOf(array,item,start) => index|-1 //start指定开始查找的位置 */ indexOf:function (array, item, start) { var index = -1; start = this.isNumber(start) ? start : 0; this.each(array, function (v, i) { if (i >= start && v === item) { index = i; return false; } }); return index; }, /** * 移除数组array中的元素item * @name removeItem * @grammar UE.utils.removeItem(array,item) */ removeItem:function (array, item) { for (var i = 0, l = array.length; i < l; i++) { if (array[i] === item) { array.splice(i, 1); i--; } } }, /** * 删除字符串str的首尾空格 * @name trim * @grammar UE.utils.trim(str) => String */ trim:function (str) { return str.replace(/(^[ \t\n\r]+)|([ \t\n\r]+$)/g, ''); }, /** * 将字符串list(以','分隔)或者数组list转成哈希对象 * @name listToMap * @grammar UE.utils.listToMap(list) => Object //Object形如{test:1,br:1,textarea:1} */ listToMap:function (list) { if (!list)return {}; list = utils.isArray(list) ? list : list.split(','); for (var i = 0, ci, obj = {}; ci = list[i++];) { obj[ci.toUpperCase()] = obj[ci] = 1; } return obj; }, /** * 将str中的html符号转义,默认将转义''&<">''四个字符,可自定义reg来确定需要转义的字符 * @name unhtml * @grammar UE.utils.unhtml(str); => String * @grammar UE.utils.unhtml(str,reg) => String * @example * var html = '<body>You say:"你好!Baidu & UEditor!"</body>'; * UE.utils.unhtml(html); ==> &lt;body&gt;You say:&quot;你好!Baidu &amp; UEditor!&quot;&lt;/body&gt; * UE.utils.unhtml(html,/[<>]/g) ==> &lt;body&gt;You say:"你好!Baidu & UEditor!"&lt;/body&gt; */ unhtml:function (str, reg) { return str ? str.replace(reg || /[&<">'](?:(amp|lt|quot|gt|#39|nbsp);)?/g, function (a, b) { if (b) { return a; } else { return { '<':'&lt;', '&':'&amp;', '"':'&quot;', '>':'&gt;', "'":'&#39;' }[a] } }) : ''; }, /** * 将str中的转义字符还原成html字符 * @name html * @grammar UE.utils.html(str) => String //详细参见<code><a href = '#unhtml'>unhtml</a></code> */ html:function (str) { return str ? str.replace(/&((g|l|quo)t|amp|#39);/g, function (m) { return { '&lt;':'<', '&amp;':'&', '&quot;':'"', '&gt;':'>', '&#39;':"'" }[m] }) : ''; }, /** * 将css样式转换为驼峰的形式。如font-size => fontSize * @name cssStyleToDomStyle * @grammar UE.utils.cssStyleToDomStyle(cssName) => String */ cssStyleToDomStyle:function () { var test = document.createElement('div').style, cache = { 'float':test.cssFloat != undefined ? 'cssFloat' : test.styleFloat != undefined ? 'styleFloat' : 'float' }; return function (cssName) { return cache[cssName] || (cache[cssName] = cssName.toLowerCase().replace(/-./g, function (match) { return match.charAt(1).toUpperCase(); })); }; }(), /** * 动态加载文件到doc中,并依据obj来设置属性,加载成功后执行回调函数fn * @name loadFile * @grammar UE.utils.loadFile(doc,obj) * @grammar UE.utils.loadFile(doc,obj,fn) * @example * //指定加载到当前document中一个script文件,加载成功后执行function * utils.loadFile( document, { * src:"test.js", * tag:"script", * type:"text/javascript", * defer:"defer" * }, function () { * console.log('加载成功!') * }); */ loadFile:function () { var tmpList = []; function getItem(doc, obj) { try { for (var i = 0, ci; ci = tmpList[i++];) { if (ci.doc === doc && ci.url == (obj.src || obj.href)) { return ci; } } } catch (e) { return null; } } return function (doc, obj, fn) { var item = getItem(doc, obj); if (item) { if (item.ready) { fn && fn(); } else { item.funs.push(fn) } return; } tmpList.push({ doc:doc, url:obj.src || obj.href, funs:[fn] }); if (!doc.body) { var html = []; for (var p in obj) { if (p == 'tag')continue; html.push(p + '="' + obj[p] + '"') } doc.write('<' + obj.tag + ' ' + html.join(' ') + ' ></' + obj.tag + '>'); return; } if (obj.id && doc.getElementById(obj.id)) { return; } var element = doc.createElement(obj.tag); delete obj.tag; for (var p in obj) { element.setAttribute(p, obj[p]); } element.onload = element.onreadystatechange = function () { if (!this.readyState || /loaded|complete/.test(this.readyState)) { item = getItem(doc, obj); if (item.funs.length > 0) { item.ready = 1; for (var fi; fi = item.funs.pop();) { fi(); } } element.onload = element.onreadystatechange = null; } }; element.onerror = function () { throw Error('The load ' + (obj.href || obj.src) + ' fails,check the url settings of file ueditor.config.js ') }; doc.getElementsByTagName("head")[0].appendChild(element); } }(), /** * 判断obj对象是否为空 * @name isEmptyObject * @grammar UE.utils.isEmptyObject(obj) => true|false * @example * UE.utils.isEmptyObject({}) ==>true * UE.utils.isEmptyObject([]) ==>true * UE.utils.isEmptyObject("") ==>true */ isEmptyObject:function (obj) { if (obj == null) return true; if (this.isArray(obj) || this.isString(obj)) return obj.length === 0; for (var key in obj) if (obj.hasOwnProperty(key)) return false; return true; }, /** * 统一将颜色值使用16进制形式表示 * @name fixColor * @grammar UE.utils.fixColor(name,value) => value * @example * rgb(255,255,255) => "#ffffff" */ fixColor:function (name, value) { if (/color/i.test(name) && /rgba?/.test(value)) { var array = value.split(","); if (array.length > 3) return ""; value = "#"; for (var i = 0, color; color = array[i++];) { color = parseInt(color.replace(/[^\d]/gi, ''), 10).toString(16); value += color.length == 1 ? "0" + color : color; } value = value.toUpperCase(); } return value; }, /** * 只针对border,padding,margin做了处理,因为性能问题 * @public * @function * @param {String} val style字符串 */ optCss:function (val) { var padding, margin, border; val = val.replace(/(padding|margin|border)\-([^:]+):([^;]+);?/gi, function (str, key, name, val) { if (val.split(' ').length == 1) { switch (key) { case 'padding': !padding && (padding = {}); padding[name] = val; return ''; case 'margin': !margin && (margin = {}); margin[name] = val; return ''; case 'border': return val == 'initial' ? '' : str; } } return str; }); function opt(obj, name) { if (!obj) { return ''; } var t = obj.top , b = obj.bottom, l = obj.left, r = obj.right, val = ''; if (!t || !l || !b || !r) { for (var p in obj) { val += ';' + name + '-' + p + ':' + obj[p] + ';'; } } else { val += ';' + name + ':' + (t == b && b == l && l == r ? t : t == b && l == r ? (t + ' ' + l) : l == r ? (t + ' ' + l + ' ' + b) : (t + ' ' + r + ' ' + b + ' ' + l)) + ';' } return val; } val += opt(padding, 'padding') + opt(margin, 'margin'); return val.replace(/^[ \n\r\t;]*|[ \n\r\t]*$/, '').replace(/;([ \n\r\t]+)|\1;/g, ';') .replace(/(&((l|g)t|quot|#39))?;{2,}/g, function (a, b) { return b ? b + ";;" : ';' }); }, /** * 深度克隆对象,从source到target * @name clone * @grammar UE.utils.clone(source) => anthorObj 新的对象是完整的source的副本 * @grammar UE.utils.clone(source,target) => target包含了source的所有内容,重名会覆盖 */ clone:function (source, target) { var tmp; target = target || {}; for (var i in source) { if (source.hasOwnProperty(i)) { tmp = source[i]; if (typeof tmp == 'object') { target[i] = utils.isArray(tmp) ? [] : {}; utils.clone(source[i], target[i]) } else { target[i] = tmp; } } } return target; }, /** * 转换cm/pt到px * @name transUnitToPx * @grammar UE.utils.transUnitToPx('20pt') => '27px' * @grammar UE.utils.transUnitToPx('0pt') => '0' */ transUnitToPx:function (val) { if (!/(pt|cm)/.test(val)) { return val } var unit; val.replace(/([\d.]+)(\w+)/, function (str, v, u) { val = v; unit = u; }); switch (unit) { case 'cm': val = parseFloat(val) * 25; break; case 'pt': val = Math.round(parseFloat(val) * 96 / 72); } return val + (val ? 'px' : ''); }, /** * DomReady方法,回调函数将在dom树ready完成后执行 * @name domReady * @grammar UE.utils.domReady(fn) => fn //返回一个延迟执行的方法 */ domReady:function () { var fnArr = []; function doReady(doc) { //确保onready只执行一次 doc.isReady = true; for (var ci; ci = fnArr.pop(); ci()) { } } return function (onready, win) { win = win || window; var doc = win.document; onready && fnArr.push(onready); if (doc.readyState === "complete") { doReady(doc); } else { doc.isReady && doReady(doc); if (browser.ie) { (function () { if (doc.isReady) return; try { doc.documentElement.doScroll("left"); } catch (error) { setTimeout(arguments.callee, 0); return; } doReady(doc); })(); win.attachEvent('onload', function () { doReady(doc) }); } else { doc.addEventListener("DOMContentLoaded", function () { doc.removeEventListener("DOMContentLoaded", arguments.callee, false); doReady(doc); }, false); win.addEventListener('load', function () { doReady(doc) }, false); } } } }(), /** * 动态添加css样式 * @name cssRule * @grammar UE.utils.cssRule('添加的样式的节点名称',['样式','放到哪个document上']) * @grammar UE.utils.cssRule('body','body{background:#ccc}') => null //给body添加背景颜色 * @grammar UE.utils.cssRule('body') =>样式的字符串 //取得key值为body的样式的内容,如果没有找到key值先关的样式将返回空,例如刚才那个背景颜色,将返回 body{background:#ccc} * @grammar UE.utils.cssRule('body','') =>null //清空给定的key值的背景颜色 */ cssRule:browser.ie ? function (key, style, doc) { var indexList, index; doc = doc || document; if (doc.indexList) { indexList = doc.indexList; } else { indexList = doc.indexList = {}; } var sheetStyle; if (!indexList[key]) { if (style === undefined) { return '' } sheetStyle = doc.createStyleSheet('', index = doc.styleSheets.length); indexList[key] = index; } else { sheetStyle = doc.styleSheets[indexList[key]]; } if (style === undefined) { return sheetStyle.cssText } sheetStyle.cssText = style || '' } : function (key, style, doc) { doc = doc || document; var head = doc.getElementsByTagName('head')[0], node; if (!(node = doc.getElementById(key))) { if (style === undefined) { return '' } node = doc.createElement('style'); node.id = key; head.appendChild(node) } if (style === undefined) { return node.innerHTML } if (style !== '') { node.innerHTML = style; } else { head.removeChild(node) } }, sort:function(array,compareFn){ compareFn = compareFn || function(item1, item2){ return item1.localeCompare(item2);}; for(var i= 0,len = array.length; i<len; i++){ for(var j = i,length = array.length; j<length; j++){ if(compareFn(array[i], array[j]) > 0){ var t = array[i]; array[i] = array[j]; array[j] = t; } } } return array; } }; /** * 判断str是否为字符串 * @name isString * @grammar UE.utils.isString(str) => true|false */ /** * 判断array是否为数组 * @name isArray * @grammar UE.utils.isArray(obj) => true|false */ /** * 判断obj对象是否为方法 * @name isFunction * @grammar UE.utils.isFunction(obj) => true|false */ /** * 判断obj对象是否为数字 * @name isNumber * @grammar UE.utils.isNumber(obj) => true|false */ utils.each(['String', 'Function', 'Array', 'Number', 'RegExp', 'Object'], function (v) { UE.utils['is' + v] = function (obj) { return Object.prototype.toString.apply(obj) == '[object ' + v + ']'; } });/** * @file * @name UE.EventBase * @short EventBase * @import editor.js,core/utils.js * @desc UE采用的事件基类,继承此类的对应类将获取addListener,removeListener,fireEvent方法。 * 在UE中,Editor以及所有ui实例都继承了该类,故可以在对应的ui对象以及editor对象上使用上述方法。 */ var EventBase = UE.EventBase = function () {}; EventBase.prototype = { /** * 注册事件监听器 * @name addListener * @grammar editor.addListener(types,fn) //types为事件名称,多个可用空格分隔 * @example * editor.addListener('selectionchange',function(){ * console.log("选区已经变化!"); * }) * editor.addListener('beforegetcontent aftergetcontent',function(type){ * if(type == 'beforegetcontent'){ * //do something * }else{ * //do something * } * console.log(this.getContent) // this是注册的事件的编辑器实例 * }) */ addListener:function (types, listener) { types = utils.trim(types).split(' '); for (var i = 0, ti; ti = types[i++];) { getListener(this, ti, true).push(listener); } }, /** * 移除事件监听器 * @name removeListener * @grammar editor.removeListener(types,fn) //types为事件名称,多个可用空格分隔 * @example * //changeCallback为方法体 * editor.removeListener("selectionchange",changeCallback); */ removeListener:function (types, listener) { types = utils.trim(types).split(' '); for (var i = 0, ti; ti = types[i++];) { utils.removeItem(getListener(this, ti) || [], listener); } }, /** * 触发事件 * @name fireEvent * @grammar editor.fireEvent(types) //types为事件名称,多个可用空格分隔 * @example * editor.fireEvent("selectionchange"); */ fireEvent:function () { var types = arguments[0]; types = utils.trim(types).split(' '); for (var i = 0, ti; ti = types[i++];) { var listeners = getListener(this, ti), r, t, k; if (listeners) { k = listeners.length; while (k--) { if(!listeners[k])continue; t = listeners[k].apply(this, arguments); if(t === true){ return t; } if (t !== undefined) { r = t; } } } if (t = this['on' + ti.toLowerCase()]) { r = t.apply(this, arguments); } } return r; } }; /** * 获得对象所拥有监听类型的所有监听器 * @public * @function * @param {Object} obj 查询监听器的对象 * @param {String} type 事件类型 * @param {Boolean} force 为true且当前所有type类型的侦听器不存在时,创建一个空监听器数组 * @returns {Array} 监听器数组 */ function getListener(obj, type, force) { var allListeners; type = type.toLowerCase(); return ( ( allListeners = ( obj.__allListeners || force && ( obj.__allListeners = {} ) ) ) && ( allListeners[type] || force && ( allListeners[type] = [] ) ) ); } ///import editor.js ///import core/dom/dom.js ///import core/utils.js /** * dtd html语义化的体现类 * @constructor * @namespace dtd */ var dtd = dom.dtd = (function() { function _( s ) { for (var k in s) { s[k.toUpperCase()] = s[k]; } return s; } var X = utils.extend2; var A = _({isindex:1,fieldset:1}), B = _({input:1,button:1,select:1,textarea:1,label:1}), C = X( _({a:1}), B ), D = X( {iframe:1}, C ), E = _({hr:1,ul:1,menu:1,div:1,blockquote:1,noscript:1,table:1,center:1,address:1,dir:1,pre:1,h5:1,dl:1,h4:1,noframes:1,h6:1,ol:1,h1:1,h3:1,h2:1}), F = _({ins:1,del:1,script:1,style:1}), G = X( _({b:1,acronym:1,bdo:1,'var':1,'#':1,abbr:1,code:1,br:1,i:1,cite:1,kbd:1,u:1,strike:1,s:1,tt:1,strong:1,q:1,samp:1,em:1,dfn:1,span:1}), F ), H = X( _({sub:1,img:1,embed:1,object:1,sup:1,basefont:1,map:1,applet:1,font:1,big:1,small:1}), G ), I = X( _({p:1}), H ), J = X( _({iframe:1}), H, B ), K = _({img:1,embed:1,noscript:1,br:1,kbd:1,center:1,button:1,basefont:1,h5:1,h4:1,samp:1,h6:1,ol:1,h1:1,h3:1,h2:1,form:1,font:1,'#':1,select:1,menu:1,ins:1,abbr:1,label:1,code:1,table:1,script:1,cite:1,input:1,iframe:1,strong:1,textarea:1,noframes:1,big:1,small:1,span:1,hr:1,sub:1,bdo:1,'var':1,div:1,object:1,sup:1,strike:1,dir:1,map:1,dl:1,applet:1,del:1,isindex:1,fieldset:1,ul:1,b:1,acronym:1,a:1,blockquote:1,i:1,u:1,s:1,tt:1,address:1,q:1,pre:1,p:1,em:1,dfn:1}), L = X( _({a:0}), J ),//a不能被切开,所以把他 M = _({tr:1}), N = _({'#':1}), O = X( _({param:1}), K ), P = X( _({form:1}), A, D, E, I ), Q = _({li:1,ol:1,ul:1}), R = _({style:1,script:1}), S = _({base:1,link:1,meta:1,title:1}), T = X( S, R ), U = _({head:1,body:1}), V = _({html:1}); var block = _({address:1,blockquote:1,center:1,dir:1,div:1,dl:1,fieldset:1,form:1,h1:1,h2:1,h3:1,h4:1,h5:1,h6:1,hr:1,isindex:1,menu:1,noframes:1,ol:1,p:1,pre:1,table:1,ul:1}), empty = _({area:1,base:1,basefont:1,br:1,col:1,command:1,dialog:1,embed:1,hr:1,img:1,input:1,isindex:1,keygen:1,link:1,meta:1,param:1,source:1,track:1,wbr:1}); return _({ // $ 表示自定的属性 // body外的元素列表. $nonBodyContent: X( V, U, S ), //块结构元素列表 $block : block, //内联元素列表 $inline : L, $inlineWithA : X(_({a:1}),L), $body : X( _({script:1,style:1}), block ), $cdata : _({script:1,style:1}), //自闭和元素 $empty : empty, //不是自闭合,但不能让range选中里边 $nonChild : _({iframe:1,textarea:1}), //列表元素列表 $listItem : _({dd:1,dt:1,li:1}), //列表根元素列表 $list: _({ul:1,ol:1,dl:1}), //不能认为是空的元素 $isNotEmpty : _({table:1,ul:1,ol:1,dl:1,iframe:1,area:1,base:1,col:1,hr:1,img:1,embed:1,input:1,link:1,meta:1,param:1,h1:1,h2:1,h3:1,h4:1,h5:1,h6:1}), //如果没有子节点就可以删除的元素列表,像span,a $removeEmpty : _({a:1,abbr:1,acronym:1,address:1,b:1,bdo:1,big:1,cite:1,code:1,del:1,dfn:1,em:1,font:1,i:1,ins:1,label:1,kbd:1,q:1,s:1,samp:1,small:1,span:1,strike:1,strong:1,sub:1,sup:1,tt:1,u:1,'var':1}), $removeEmptyBlock : _({'p':1,'div':1}), //在table元素里的元素列表 $tableContent : _({caption:1,col:1,colgroup:1,tbody:1,td:1,tfoot:1,th:1,thead:1,tr:1,table:1}), //不转换的标签 $notTransContent : _({pre:1,script:1,style:1,textarea:1}), html: U, head: T, style: N, script: N, body: P, base: {}, link: {}, meta: {}, title: N, col : {}, tr : _({td:1,th:1}), img : {}, embed: {}, colgroup : _({thead:1,col:1,tbody:1,tr:1,tfoot:1}), noscript : P, td : P, br : {}, th : P, center : P, kbd : L, button : X( I, E ), basefont : {}, h5 : L, h4 : L, samp : L, h6 : L, ol : Q, h1 : L, h3 : L, option : N, h2 : L, form : X( A, D, E, I ), select : _({optgroup:1,option:1}), font : L, ins : L, menu : Q, abbr : L, label : L, table : _({thead:1,col:1,tbody:1,tr:1,colgroup:1,caption:1,tfoot:1}), code : L, tfoot : M, cite : L, li : P, input : {}, iframe : P, strong : L, textarea : N, noframes : P, big : L, small : L, //trace: span :_({'#':1,br:1,b:1,strong:1,u:1,i:1,em:1,sub:1,sup:1,strike:1,span:1}), hr : L, dt : L, sub : L, optgroup : _({option:1}), param : {}, bdo : L, 'var' : L, div : P, object : O, sup : L, dd : P, strike : L, area : {}, dir : Q, map : X( _({area:1,form:1,p:1}), A, F, E ), applet : O, dl : _({dt:1,dd:1}), del : L, isindex : {}, fieldset : X( _({legend:1}), K ), thead : M, ul : Q, acronym : L, b : L, a : X( _({a:1}), J ), blockquote :X(_({td:1,tr:1,tbody:1,li:1}),P), caption : L, i : L, u : L, tbody : M, s : L, address : X( D, I ), tt : L, legend : L, q : L, pre : X( G, C ), p : X(_({'a':1}),L), em :L, dfn : L }); })(); /** * @file * @name UE.dom.domUtils * @short DomUtils * @import editor.js, core/utils.js,core/browser.js,core/dom/dtd.js * @desc UEditor封装的底层dom操作库 */ function getDomNode(node, start, ltr, startFromChild, fn, guard) { var tmpNode = startFromChild && node[start], parent; !tmpNode && (tmpNode = node[ltr]); while (!tmpNode && (parent = (parent || node).parentNode)) { if (parent.tagName == 'BODY' || guard && !guard(parent)) { return null; } tmpNode = parent[ltr]; } if (tmpNode && fn && !fn(tmpNode)) { return getDomNode(tmpNode, start, ltr, false, fn); } return tmpNode; } var attrFix = ie && browser.version < 9 ? { tabindex:"tabIndex", readonly:"readOnly", "for":"htmlFor", "class":"className", maxlength:"maxLength", cellspacing:"cellSpacing", cellpadding:"cellPadding", rowspan:"rowSpan", colspan:"colSpan", usemap:"useMap", frameborder:"frameBorder" } : { tabindex:"tabIndex", readonly:"readOnly" }, styleBlock = utils.listToMap([ '-webkit-box', '-moz-box', 'block' , 'list-item' , 'table' , 'table-row-group' , 'table-header-group', 'table-footer-group' , 'table-row' , 'table-column-group' , 'table-column' , 'table-cell' , 'table-caption' ]); var domUtils = dom.domUtils = { //节点常量 NODE_ELEMENT:1, NODE_DOCUMENT:9, NODE_TEXT:3, NODE_COMMENT:8, NODE_DOCUMENT_FRAGMENT:11, //位置关系 POSITION_IDENTICAL:0, POSITION_DISCONNECTED:1, POSITION_FOLLOWING:2, POSITION_PRECEDING:4, POSITION_IS_CONTAINED:8, POSITION_CONTAINS:16, //ie6使用其他的会有一段空白出现 fillChar:ie && browser.version == '6' ? '\ufeff' : '\u200B', //-------------------------Node部分-------------------------------- keys:{ /*Backspace*/ 8:1, /*Delete*/ 46:1, /*Shift*/ 16:1, /*Ctrl*/ 17:1, /*Alt*/ 18:1, 37:1, 38:1, 39:1, 40:1, 13:1 /*enter*/ }, /** * 获取节点A相对于节点B的位置关系 * @name getPosition * @grammar UE.dom.domUtils.getPosition(nodeA,nodeB) => Number * @example * switch (returnValue) { * case 0: //相等,同一节点 * case 1: //无关,节点不相连 * case 2: //跟随,即节点A头部位于节点B头部的后面 * case 4: //前置,即节点A头部位于节点B头部的前面 * case 8: //被包含,即节点A被节点B包含 * case 10://组合类型,即节点A满足跟随节点B且被节点B包含。实际上,如果被包含,必定跟随,所以returnValue事实上不会存在8的情况。 * case 16://包含,即节点A包含节点B * case 20://组合类型,即节点A满足前置节点A且包含节点B。同样,如果包含,必定前置,所以returnValue事实上也不会存在16的情况 * } */ getPosition:function (nodeA, nodeB) { // 如果两个节点是同一个节点 if (nodeA === nodeB) { // domUtils.POSITION_IDENTICAL return 0; } var node, parentsA = [nodeA], parentsB = [nodeB]; node = nodeA; while (node = node.parentNode) { // 如果nodeB是nodeA的祖先节点 if (node === nodeB) { // domUtils.POSITION_IS_CONTAINED + domUtils.POSITION_FOLLOWING return 10; } parentsA.push(node); } node = nodeB; while (node = node.parentNode) { // 如果nodeA是nodeB的祖先节点 if (node === nodeA) { // domUtils.POSITION_CONTAINS + domUtils.POSITION_PRECEDING return 20; } parentsB.push(node); } parentsA.reverse(); parentsB.reverse(); if (parentsA[0] !== parentsB[0]) { // domUtils.POSITION_DISCONNECTED return 1; } var i = -1; while (i++, parentsA[i] === parentsB[i]) { } nodeA = parentsA[i]; nodeB = parentsB[i]; while (nodeA = nodeA.nextSibling) { if (nodeA === nodeB) { // domUtils.POSITION_PRECEDING return 4 } } // domUtils.POSITION_FOLLOWING return 2; }, /** * 返回节点node在父节点中的索引位置 * @name getNodeIndex * @grammar UE.dom.domUtils.getNodeIndex(node) => Number //索引值从0开始 */ getNodeIndex:function (node, ignoreTextNode) { var preNode = node, i = 0; while (preNode = preNode.previousSibling) { if (ignoreTextNode && preNode.nodeType == 3) { if(preNode.nodeType != preNode.nextSibling.nodeType ){ i++; } continue; } i++; } return i; }, /** * 检测节点node是否在节点doc的树上,实质上是检测是否被doc包含 * @name inDoc * @grammar UE.dom.domUtils.inDoc(node,doc) => true|false */ inDoc:function (node, doc) { return domUtils.getPosition(node, doc) == 10; }, /** * 查找node节点的祖先节点 * @name findParent * @grammar UE.dom.domUtils.findParent(node) => Element // 直接返回node节点的父节点 * @grammar UE.dom.domUtils.findParent(node,filterFn) => Element //filterFn为过滤函数,node作为参数,返回true时才会将node作为符合要求的节点返回 * @grammar UE.dom.domUtils.findParent(node,filterFn,includeSelf) => Element //includeSelf指定是否包含自身 */ findParent:function (node, filterFn, includeSelf) { if (node && !domUtils.isBody(node)) { node = includeSelf ? node : node.parentNode; while (node) { if (!filterFn || filterFn(node) || domUtils.isBody(node)) { return filterFn && !filterFn(node) && domUtils.isBody(node) ? null : node; } node = node.parentNode; } } return null; }, /** * 通过tagName查找node节点的祖先节点 * @name findParentByTagName * @grammar UE.dom.domUtils.findParentByTagName(node,tagNames) => Element //tagNames支持数组,区分大小写 * @grammar UE.dom.domUtils.findParentByTagName(node,tagNames,includeSelf) => Element //includeSelf指定是否包含自身 * @grammar UE.dom.domUtils.findParentByTagName(node,tagNames,includeSelf,excludeFn) => Element //excludeFn指定例外过滤条件,返回true时忽略该节点 */ findParentByTagName:function (node, tagNames, includeSelf, excludeFn) { tagNames = utils.listToMap(utils.isArray(tagNames) ? tagNames : [tagNames]); return domUtils.findParent(node, function (node) { return tagNames[node.tagName] && !(excludeFn && excludeFn(node)); }, includeSelf); }, /** * 查找节点node的祖先节点集合 * @name findParents * @grammar UE.dom.domUtils.findParents(node) => Array //返回一个祖先节点数组集合,不包含自身 * @grammar UE.dom.domUtils.findParents(node,includeSelf) => Array //返回一个祖先节点数组集合,includeSelf指定是否包含自身 * @grammar UE.dom.domUtils.findParents(node,includeSelf,filterFn) => Array //返回一个祖先节点数组集合,filterFn指定过滤条件,返回true的node将被选取 * @grammar UE.dom.domUtils.findParents(node,includeSelf,filterFn,closerFirst) => Array //返回一个祖先节点数组集合,closerFirst为true的话,node的直接父亲节点是数组的第0个 */ findParents:function (node, includeSelf, filterFn, closerFirst) { var parents = includeSelf && ( filterFn && filterFn(node) || !filterFn ) ? [node] : []; while (node = domUtils.findParent(node, filterFn)) { parents.push(node); } return closerFirst ? parents : parents.reverse(); }, /** * 在节点node后面插入新节点newNode * @name insertAfter * @grammar UE.dom.domUtils.insertAfter(node,newNode) => newNode */ insertAfter:function (node, newNode) { return node.parentNode.insertBefore(newNode, node.nextSibling); }, /** * 删除节点node,并根据keepChildren指定是否保留子节点 * @name remove * @grammar UE.dom.domUtils.remove(node) => node * @grammar UE.dom.domUtils.remove(node,keepChildren) => node */ remove:function (node, keepChildren) { var parent = node.parentNode, child; if (parent) { if (keepChildren && node.hasChildNodes()) { while (child = node.firstChild) { parent.insertBefore(child, node); } } parent.removeChild(node); } return node; }, /** * 取得node节点在dom树上的下一个节点,即多叉树遍历 * @name getNextDomNode * @grammar UE.dom.domUtils.getNextDomNode(node) => Element * @example */ getNextDomNode:function (node, startFromChild, filterFn, guard) { return getDomNode(node, 'firstChild', 'nextSibling', startFromChild, filterFn, guard); }, /** * 检测节点node是否属于bookmark节点 * @name isBookmarkNode * @grammar UE.dom.domUtils.isBookmarkNode(node) => true|false */ isBookmarkNode:function (node) { return node.nodeType == 1 && node.id && /^_baidu_bookmark_/i.test(node.id); }, /** * 获取节点node所在的window对象 * @name getWindow * @grammar UE.dom.domUtils.getWindow(node) => window对象 */ getWindow:function (node) { var doc = node.ownerDocument || node; return doc.defaultView || doc.parentWindow; }, /** * 得到nodeA与nodeB公共的祖先节点 * @name getCommonAncestor * @grammar UE.dom.domUtils.getCommonAncestor(nodeA,nodeB) => Element */ getCommonAncestor:function (nodeA, nodeB) { if (nodeA === nodeB) return nodeA; var parentsA = [nodeA] , parentsB = [nodeB], parent = nodeA, i = -1; while (parent = parent.parentNode) { if (parent === nodeB) { return parent; } parentsA.push(parent); } parent = nodeB; while (parent = parent.parentNode) { if (parent === nodeA) return parent; parentsB.push(parent); } parentsA.reverse(); parentsB.reverse(); while (i++, parentsA[i] === parentsB[i]) { } return i == 0 ? null : parentsA[i - 1]; }, /** * 清除node节点左右兄弟为空的inline节点 * @name clearEmptySibling * @grammar UE.dom.domUtils.clearEmptySibling(node) * @grammar UE.dom.domUtils.clearEmptySibling(node,ignoreNext) //ignoreNext指定是否忽略右边空节点 * @grammar UE.dom.domUtils.clearEmptySibling(node,ignoreNext,ignorePre) //ignorePre指定是否忽略左边空节点 * @example * <b></b><i></i>xxxx<b>bb</b> --> xxxx<b>bb</b> */ clearEmptySibling:function (node, ignoreNext, ignorePre) { function clear(next, dir) { var tmpNode; while (next && !domUtils.isBookmarkNode(next) && (domUtils.isEmptyInlineElement(next) //这里不能把空格算进来会吧空格干掉,出现文字间的空格丢掉了 || !new RegExp('[^\t\n\r' + domUtils.fillChar + ']').test(next.nodeValue) )) { tmpNode = next[dir]; domUtils.remove(next); next = tmpNode; } } !ignoreNext && clear(node.nextSibling, 'nextSibling'); !ignorePre && clear(node.previousSibling, 'previousSibling'); }, /** * 将一个文本节点node拆分成两个文本节点,offset指定拆分位置 * @name split * @grammar UE.dom.domUtils.split(node,offset) => TextNode //返回从切分位置开始的后一个文本节点 */ split:function (node, offset) { var doc = node.ownerDocument; if (browser.ie && offset == node.nodeValue.length) { var next = doc.createTextNode(''); return domUtils.insertAfter(node, next); } var retval = node.splitText(offset); //ie8下splitText不会跟新childNodes,我们手动触发他的更新 if (browser.ie8) { var tmpNode = doc.createTextNode(''); domUtils.insertAfter(retval, tmpNode); domUtils.remove(tmpNode); } return retval; }, /** * 检测节点node是否为空节点(包括空格、换行、占位符等字符) * @name isWhitespace * @grammar UE.dom.domUtils.isWhitespace(node) => true|false */ isWhitespace:function (node) { return !new RegExp('[^ \t\n\r' + domUtils.fillChar + ']').test(node.nodeValue); }, /** * 获取元素element相对于viewport的位置坐标 * @name getXY * @grammar UE.dom.domUtils.getXY(element) => Object //返回坐标对象{x:left,y:top} */ getXY:function (element) { var x = 0, y = 0; while (element.offsetParent) { y += element.offsetTop; x += element.offsetLeft; element = element.offsetParent; } return { 'x':x, 'y':y}; }, /** * 为元素element绑定原生DOM事件,type为事件类型,handler为处理函数 * @name on * @grammar UE.dom.domUtils.on(element,type,handler) //type支持数组传入 * @example * UE.dom.domUtils.on(document.body,"click",function(e){ * //e为事件对象,this为被点击元素对戏那个 * }) * @example * UE.dom.domUtils.on(document.body,["click","mousedown"],function(evt){ * //evt为事件对象,this为被点击元素对象 * }) */ on:function (element, type, handler) { var types = utils.isArray(type) ? type : [type], k = types.length; if (k) while (k--) { type = types[k]; if (element.addEventListener) { element.addEventListener(type, handler, false); } else { if (!handler._d) { handler._d = { els : [] }; } var key = type + handler.toString(),index = utils.indexOf(handler._d.els,element); if (!handler._d[key] || index == -1) { if(index == -1){ handler._d.els.push(element); } if(!handler._d[key]){ handler._d[key] = function (evt) { return handler.call(evt.srcElement, evt || window.event); }; } element.attachEvent('on' + type, handler._d[key]); } } } element = null; }, /** * 解除原生DOM事件绑定 * @name un * @grammar UE.dom.donUtils.un(element,type,handler) //参见<code><a href="#on">on</a></code> */ un:function (element, type, handler) { var types = utils.isArray(type) ? type : [type], k = types.length; if (k) while (k--) { type = types[k]; if (element.removeEventListener) { element.removeEventListener(type, handler, false); } else { var key = type + handler.toString(); try{ element.detachEvent('on' + type, handler._d ? handler._d[key] : handler); }catch(e){} if (handler._d && handler._d[key]) { var index = utils.indexOf(handler._d.els,element); if(index!=-1){ handler._d.els.splice(index,1); } handler._d.els.length == 0 && delete handler._d[key]; } } } }, /** * 比较节点nodeA与节点nodeB是否具有相同的标签名、属性名以及属性值 * @name isSameElement * @grammar UE.dom.domUtils.isSameElement(nodeA,nodeB) => true|false * @example * <span style="font-size:12px">ssss</span> and <span style="font-size:12px">bbbbb</span> => true * <span style="font-size:13px">ssss</span> and <span style="font-size:12px">bbbbb</span> => false */ isSameElement:function (nodeA, nodeB) { if (nodeA.tagName != nodeB.tagName) { return false; } var thisAttrs = nodeA.attributes, otherAttrs = nodeB.attributes; if (!ie && thisAttrs.length != otherAttrs.length) { return false; } var attrA, attrB, al = 0, bl = 0; for (var i = 0; attrA = thisAttrs[i++];) { if (attrA.nodeName == 'style') { if (attrA.specified) { al++; } if (domUtils.isSameStyle(nodeA, nodeB)) { continue; } else { return false; } } if (ie) { if (attrA.specified) { al++; attrB = otherAttrs.getNamedItem(attrA.nodeName); } else { continue; } } else { attrB = nodeB.attributes[attrA.nodeName]; } if (!attrB.specified || attrA.nodeValue != attrB.nodeValue) { return false; } } // 有可能attrB的属性包含了attrA的属性之外还有自己的属性 if (ie) { for (i = 0; attrB = otherAttrs[i++];) { if (attrB.specified) { bl++; } } if (al != bl) { return false; } } return true; }, /** * 判断节点nodeA与节点nodeB的元素属性是否一致 * @name isSameStyle * @grammar UE.dom.domUtils.isSameStyle(nodeA,nodeB) => true|false */ isSameStyle:function (nodeA, nodeB) { var styleA = nodeA.style.cssText.replace(/( ?; ?)/g, ';').replace(/( ?: ?)/g, ':'), styleB = nodeB.style.cssText.replace(/( ?; ?)/g, ';').replace(/( ?: ?)/g, ':'); if (browser.opera) { styleA = nodeA.style; styleB = nodeB.style; if (styleA.length != styleB.length) return false; for (var p in styleA) { if (/^(\d+|csstext)$/i.test(p)) { continue; } if (styleA[p] != styleB[p]) { return false; } } return true; } if (!styleA || !styleB) { return styleA == styleB; } styleA = styleA.split(';'); styleB = styleB.split(';'); if (styleA.length != styleB.length) { return false; } for (var i = 0, ci; ci = styleA[i++];) { if (utils.indexOf(styleB, ci) == -1) { return false; } } return true; }, /** * 检查节点node是否为块元素 * @name isBlockElm * @grammar UE.dom.domUtils.isBlockElm(node) => true|false */ isBlockElm:function (node) { return node.nodeType == 1 && (dtd.$block[node.tagName] || styleBlock[domUtils.getComputedStyle(node, 'display')]) && !dtd.$nonChild[node.tagName]; }, /** * 检测node节点是否为body节点 * @name isBody * @grammar UE.dom.domUtils.isBody(node) => true|false */ isBody:function (node) { return node && node.nodeType == 1 && node.tagName.toLowerCase() == 'body'; }, /** * 以node节点为中心,将该节点的指定祖先节点parent拆分成2块 * @name breakParent * @grammar UE.dom.domUtils.breakParent(node,parent) => node * @desc * <code type="html"><b>ooo</b>是node节点 * <p>xxxx<b>ooo</b>xxx</p> ==> <p>xxx</p><b>ooo</b><p>xxx</p> * <p>xxxxx<span>xxxx<b>ooo</b>xxxxxx</span></p> => <p>xxxxx<span>xxxx</span></p><b>ooo</b><p><span>xxxxxx</span></p></code> */ breakParent:function (node, parent) { var tmpNode, parentClone = node, clone = node, leftNodes, rightNodes; do { parentClone = parentClone.parentNode; if (leftNodes) { tmpNode = parentClone.cloneNode(false); tmpNode.appendChild(leftNodes); leftNodes = tmpNode; tmpNode = parentClone.cloneNode(false); tmpNode.appendChild(rightNodes); rightNodes = tmpNode; } else { leftNodes = parentClone.cloneNode(false); rightNodes = leftNodes.cloneNode(false); } while (tmpNode = clone.previousSibling) { leftNodes.insertBefore(tmpNode, leftNodes.firstChild); } while (tmpNode = clone.nextSibling) { rightNodes.appendChild(tmpNode); } clone = parentClone; } while (parent !== parentClone); tmpNode = parent.parentNode; tmpNode.insertBefore(leftNodes, parent); tmpNode.insertBefore(rightNodes, parent); tmpNode.insertBefore(node, rightNodes); domUtils.remove(parent); return node; }, /** * 检查节点node是否是空inline节点 * @name isEmptyInlineElement * @grammar UE.dom.domUtils.isEmptyInlineElement(node) => 1|0 * @example * <b><i></i></b> => 1 * <b><i></i><u></u></b> => 1 * <b></b> => 1 * <b>xx<i></i></b> => 0 */ isEmptyInlineElement:function (node) { if (node.nodeType != 1 || !dtd.$removeEmpty[ node.tagName ]) { return 0; } node = node.firstChild; while (node) { //如果是创建的bookmark就跳过 if (domUtils.isBookmarkNode(node)) { return 0; } if (node.nodeType == 1 && !domUtils.isEmptyInlineElement(node) || node.nodeType == 3 && !domUtils.isWhitespace(node) ) { return 0; } node = node.nextSibling; } return 1; }, /** * 删除node节点下的左右空白文本子节点 * @name trimWhiteTextNode * @grammar UE.dom.domUtils.trimWhiteTextNode(node) */ trimWhiteTextNode:function (node) { function remove(dir) { var child; while ((child = node[dir]) && child.nodeType == 3 && domUtils.isWhitespace(child)) { node.removeChild(child); } } remove('firstChild'); remove('lastChild'); }, /** * 合并node节点下相同的子节点 * @name mergeChild * @desc * UE.dom.domUtils.mergeChild(node,tagName) //tagName要合并的子节点的标签 * @example * <p><span style="font-size:12px;">xx<span style="font-size:12px;">aa</span>xx</span></p> * ==> UE.dom.domUtils.mergeChild(node,'span') * <p><span style="font-size:12px;">xxaaxx</span></p> */ mergeChild:function (node, tagName, attrs) { var list = domUtils.getElementsByTagName(node, node.tagName.toLowerCase()); for (var i = 0, ci; ci = list[i++];) { if (!ci.parentNode || domUtils.isBookmarkNode(ci)) { continue; } //span单独处理 if (ci.tagName.toLowerCase() == 'span') { if (node === ci.parentNode) { domUtils.trimWhiteTextNode(node); if (node.childNodes.length == 1) { node.style.cssText = ci.style.cssText + ";" + node.style.cssText; domUtils.remove(ci, true); continue; } } ci.style.cssText = node.style.cssText + ';' + ci.style.cssText; if (attrs) { var style = attrs.style; if (style) { style = style.split(';'); for (var j = 0, s; s = style[j++];) { ci.style[utils.cssStyleToDomStyle(s.split(':')[0])] = s.split(':')[1]; } } } if (domUtils.isSameStyle(ci, node)) { domUtils.remove(ci, true); } continue; } if (domUtils.isSameElement(node, ci)) { domUtils.remove(ci, true); } } }, /** * 原生方法getElementsByTagName的封装 * @name getElementsByTagName * @grammar UE.dom.domUtils.getElementsByTagName(node,tagName) => Array //节点集合数组 */ getElementsByTagName:function (node, name,filter) { if(filter && utils.isString(filter)){ var className = filter; filter = function(node){return domUtils.hasClass(node,className)} } name = utils.trim(name).replace(/[ ]{2,}/g,' ').split(' '); var arr = []; for(var n = 0,ni;ni=name[n++];){ var list = node.getElementsByTagName(ni); for (var i = 0, ci; ci = list[i++];) { if(!filter || filter(ci)) arr.push(ci); } } return arr; }, /** * 将节点node合并到父节点上 * @name mergeToParent * @grammar UE.dom.domUtils.mergeToParent(node) * @example * <span style="color:#fff"><span style="font-size:12px">xxx</span></span> ==> <span style="color:#fff;font-size:12px">xxx</span> */ mergeToParent:function (node) { var parent = node.parentNode; while (parent && dtd.$removeEmpty[parent.tagName]) { if (parent.tagName == node.tagName || parent.tagName == 'A') {//针对a标签单独处理 domUtils.trimWhiteTextNode(parent); //span需要特殊处理 不处理这样的情况 <span stlye="color:#fff">xxx<span style="color:#ccc">xxx</span>xxx</span> if (parent.tagName == 'SPAN' && !domUtils.isSameStyle(parent, node) || (parent.tagName == 'A' && node.tagName == 'SPAN')) { if (parent.childNodes.length > 1 || parent !== node.parentNode) { node.style.cssText = parent.style.cssText + ";" + node.style.cssText; parent = parent.parentNode; continue; } else { parent.style.cssText += ";" + node.style.cssText; //trace:952 a标签要保持下划线 if (parent.tagName == 'A') { parent.style.textDecoration = 'underline'; } } } if (parent.tagName != 'A') { parent === node.parentNode && domUtils.remove(node, true); break; } } parent = parent.parentNode; } }, /** * 合并节点node的左右兄弟节点 * @name mergeSibling * @grammar UE.dom.domUtils.mergeSibling(node) * @grammar UE.dom.domUtils.mergeSibling(node,ignorePre) //ignorePre指定是否忽略左兄弟 * @grammar UE.dom.domUtils.mergeSibling(node,ignorePre,ignoreNext) //ignoreNext指定是否忽略右兄弟 * @example * <b>xxxx</b><b>ooo</b><b>xxxx</b> ==> <b>xxxxoooxxxx</b> */ mergeSibling:function (node, ignorePre, ignoreNext) { function merge(rtl, start, node) { var next; if ((next = node[rtl]) && !domUtils.isBookmarkNode(next) && next.nodeType == 1 && domUtils.isSameElement(node, next)) { while (next.firstChild) { if (start == 'firstChild') { node.insertBefore(next.lastChild, node.firstChild); } else { node.appendChild(next.firstChild); } } domUtils.remove(next); } } !ignorePre && merge('previousSibling', 'firstChild', node); !ignoreNext && merge('nextSibling', 'lastChild', node); }, /** * 设置节点node及其子节点不会被选中 * @name unSelectable * @grammar UE.dom.domUtils.unSelectable(node) */ unSelectable:ie || browser.opera ? function (node) { //for ie9 node.onselectstart = function () { return false; }; node.onclick = node.onkeyup = node.onkeydown = function () { return false; }; node.unselectable = 'on'; node.setAttribute("unselectable", "on"); for (var i = 0, ci; ci = node.all[i++];) { switch (ci.tagName.toLowerCase()) { case 'iframe' : case 'textarea' : case 'input' : case 'select' : break; default : ci.unselectable = 'on'; node.setAttribute("unselectable", "on"); } } } : function (node) { node.style.MozUserSelect = node.style.webkitUserSelect = node.style.KhtmlUserSelect = 'none'; }, /** * 删除节点node上的属性attrNames,attrNames为属性名称数组 * @name removeAttributes * @grammar UE.dom.domUtils.removeAttributes(node,attrNames) * @example * //Before remove * <span style="font-size:14px;" id="test" name="followMe">xxxxx</span> * //Remove * UE.dom.domUtils.removeAttributes(node,["id","name"]); * //After remove * <span style="font-size:14px;">xxxxx</span> */ removeAttributes:function (node, attrNames) { attrNames = utils.isArray(attrNames) ? attrNames : utils.trim(attrNames).replace(/[ ]{2,}/g,' ').split(' '); for (var i = 0, ci; ci = attrNames[i++];) { ci = attrFix[ci] || ci; switch (ci) { case 'className': node[ci] = ''; break; case 'style': node.style.cssText = ''; !browser.ie && node.removeAttributeNode(node.getAttributeNode('style')) } node.removeAttribute(ci); } }, /** * 在doc下创建一个标签名为tag,属性为attrs的元素 * @name createElement * @grammar UE.dom.domUtils.createElement(doc,tag,attrs) => Node //返回创建的节点 */ createElement:function (doc, tag, attrs) { return domUtils.setAttributes(doc.createElement(tag), attrs) }, /** * 为节点node添加属性attrs,attrs为属性键值对 * @name setAttributes * @grammar UE.dom.domUtils.setAttributes(node,attrs) => node */ setAttributes:function (node, attrs) { for (var attr in attrs) { if(attrs.hasOwnProperty(attr)){ var value = attrs[attr]; switch (attr) { case 'class': //ie下要这样赋值,setAttribute不起作用 node.className = value; break; case 'style' : node.style.cssText = node.style.cssText + ";" + value; break; case 'innerHTML': node[attr] = value; break; case 'value': node.value = value; break; default: node.setAttribute(attrFix[attr] || attr, value); } } } return node; }, /** * 获取元素element的计算样式 * @name getComputedStyle * @grammar UE.dom.domUtils.getComputedStyle(element,styleName) => String //返回对应样式名称的样式值 * @example * getComputedStyle(document.body,"font-size") => "15px" * getComputedStyle(form,"color") => "#ffccdd" */ getComputedStyle:function (element, styleName) { //一下的属性单独处理 var pros = 'width height top left'; if(pros.indexOf(styleName) > -1){ return element['offset' + styleName.replace(/^\w/,function(s){return s.toUpperCase()})] + 'px'; } //忽略文本节点 if (element.nodeType == 3) { element = element.parentNode; } //ie下font-size若body下定义了font-size,则从currentStyle里会取到这个font-size. 取不到实际值,故此修改. if (browser.ie && browser.version < 9 && styleName == 'font-size' && !element.style.fontSize && !dtd.$empty[element.tagName] && !dtd.$nonChild[element.tagName]) { var span = element.ownerDocument.createElement('span'); span.style.cssText = 'padding:0;border:0;font-family:simsun;'; span.innerHTML = '.'; element.appendChild(span); var result = span.offsetHeight; element.removeChild(span); span = null; return result + 'px'; } try { var value = domUtils.getStyle(element, styleName) || (window.getComputedStyle ? domUtils.getWindow(element).getComputedStyle(element, '').getPropertyValue(styleName) : ( element.currentStyle || element.style )[utils.cssStyleToDomStyle(styleName)]); } catch (e) { return ""; } return utils.transUnitToPx(utils.fixColor(styleName, value)); }, /** * 在元素element上删除classNames,支持同时删除多个 * @name removeClasses * @grammar UE.dom.domUtils.removeClasses(element,classNames) * @example * //执行方法前的dom结构 * <span class="test1 test2 test3">xxx</span> * //执行方法 * UE.dom.domUtils.removeClasses(element,["test1","test3"]) * //执行方法后的dom结构 * <span class="test2">xxx</span> */ removeClasses:function (elm, classNames) { classNames = utils.isArray(classNames) ? classNames : utils.trim(classNames).replace(/[ ]{2,}/g,' ').split(' '); for(var i = 0,ci,cls = elm.className;ci=classNames[i++];){ cls = cls.replace(new RegExp('\\b' + ci + '\\b'),'') } cls = utils.trim(cls).replace(/[ ]{2,}/g,' '); if(cls){ elm.className = cls; }else{ domUtils.removeAttributes(elm,['class']); } }, /** * 在元素element上增加一个样式类className,支持以空格分开的多个类名 * 如果相同的类名将不会添加 * @name addClass * @grammar UE.dom.domUtils.addClass(element,classNames) */ addClass:function (elm, classNames) { if(!elm)return; classNames = utils.trim(classNames).replace(/[ ]{2,}/g,' ').split(' '); for(var i = 0,ci,cls = elm.className;ci=classNames[i++];){ if(!new RegExp('\\b' + ci + '\\b').test(cls)){ elm.className += ' ' + ci; } } }, /** * 判断元素element是否包含样式类名className,支持以空格分开的多个类名,多个类名顺序不同也可以比较 * @name hasClass * @grammar UE.dom.domUtils.hasClass(element,className) =>true|false */ hasClass:function (element, className) { if(utils.isRegExp(className)){ return className.test(element.className) } className = utils.trim(className).replace(/[ ]{2,}/g,' ').split(' '); for(var i = 0,ci,cls = element.className;ci=className[i++];){ if(!new RegExp('\\b' + ci + '\\b','i').test(cls)){ return false; } } return i - 1 == className.length; }, /** * 阻止事件默认行为 * @param {Event} evt 需要组织的事件对象 */ preventDefault:function (evt) { evt.preventDefault ? evt.preventDefault() : (evt.returnValue = false); }, /** * 删除元素element的样式 * @grammar UE.dom.domUtils.removeStyle(element,name) 删除的样式名称 */ removeStyle:function (element, name) { if(browser.ie ){ //针对color先单独处理一下 if(name == 'color'){ name = '(^|;)' + name; } element.style.cssText = element.style.cssText.replace(new RegExp(name + '[^:]*:[^;]+;?','ig'),'') }else{ if (element.style.removeProperty) { element.style.removeProperty (name); }else { element.style.removeAttribute (utils.cssStyleToDomStyle(name)); } } if (!element.style.cssText) { domUtils.removeAttributes(element, ['style']); } }, /** * 获取元素element的某个样式值 * @name getStyle * @grammar UE.dom.domUtils.getStyle(element,name) => String */ getStyle:function (element, name) { var value = element.style[ utils.cssStyleToDomStyle(name) ]; return utils.fixColor(name, value); }, /** * 为元素element设置样式属性值 * @name setStyle * @grammar UE.dom.domUtils.setStyle(element,name,value) */ setStyle:function (element, name, value) { element.style[utils.cssStyleToDomStyle(name)] = value; if(!utils.trim(element.style.cssText)){ this.removeAttributes(element,'style') } }, /** * 为元素element设置样式属性值 * @name setStyles * @grammar UE.dom.domUtils.setStyle(element,styles) //styles为样式键值对 */ setStyles:function (element, styles) { for (var name in styles) { if (styles.hasOwnProperty(name)) { domUtils.setStyle(element, name, styles[name]); } } }, /** * 删除_moz_dirty属性 * @function */ removeDirtyAttr:function (node) { for (var i = 0, ci, nodes = node.getElementsByTagName('*'); ci = nodes[i++];) { ci.removeAttribute('_moz_dirty'); } node.removeAttribute('_moz_dirty'); }, /** * 返回子节点的数量 * @function * @param {Node} node 父节点 * @param {Function} fn 过滤子节点的规则,若为空,则得到所有子节点的数量 * @return {Number} 符合条件子节点的数量 */ getChildCount:function (node, fn) { var count = 0, first = node.firstChild; fn = fn || function () { return 1; }; while (first) { if (fn(first)) { count++; } first = first.nextSibling; } return count; }, /** * 判断是否为空节点 * @function * @param {Node} node 节点 * @return {Boolean} 是否为空节点 */ isEmptyNode:function (node) { return !node.firstChild || domUtils.getChildCount(node, function (node) { return !domUtils.isBr(node) && !domUtils.isBookmarkNode(node) && !domUtils.isWhitespace(node) }) == 0 }, /** * 清空节点所有的className * @function * @param {Array} nodes 节点数组 */ clearSelectedArr:function (nodes) { var node; while (node = nodes.pop()) { domUtils.removeAttributes(node, ['class']); } }, /** * 将显示区域滚动到显示节点的位置 * @function * @param {Node} node 节点 * @param {window} win window对象 * @param {Number} offsetTop 距离上方的偏移量 */ scrollToView:function (node, win, offsetTop) { var getViewPaneSize = function () { var doc = win.document, mode = doc.compatMode == 'CSS1Compat'; return { width:( mode ? doc.documentElement.clientWidth : doc.body.clientWidth ) || 0, height:( mode ? doc.documentElement.clientHeight : doc.body.clientHeight ) || 0 }; }, getScrollPosition = function (win) { if ('pageXOffset' in win) { return { x:win.pageXOffset || 0, y:win.pageYOffset || 0 }; } else { var doc = win.document; return { x:doc.documentElement.scrollLeft || doc.body.scrollLeft || 0, y:doc.documentElement.scrollTop || doc.body.scrollTop || 0 }; } }; var winHeight = getViewPaneSize().height, offset = winHeight * -1 + offsetTop; offset += (node.offsetHeight || 0); var elementPosition = domUtils.getXY(node); offset += elementPosition.y; var currentScroll = getScrollPosition(win).y; // offset += 50; if (offset > currentScroll || offset < currentScroll - winHeight) { win.scrollTo(0, offset + (offset < 0 ? -20 : 20)); } }, /** * 判断节点是否为br * @function * @param {Node} node 节点 */ isBr:function (node) { return node.nodeType == 1 && node.tagName == 'BR'; }, isFillChar:function (node,isInStart) { return node.nodeType == 3 && !node.nodeValue.replace(new RegExp((isInStart ? '^' : '' ) + domUtils.fillChar), '').length }, isStartInblock:function (range) { var tmpRange = range.cloneRange(), flag = 0, start = tmpRange.startContainer, tmp; if(start.nodeType == 1 && start.childNodes[tmpRange.startOffset]){ start = start.childNodes[tmpRange.startOffset]; var pre = start.previousSibling; while(pre && domUtils.isFillChar(pre)){ start = pre; pre = pre.previousSibling; } } if(this.isFillChar(start,true) && tmpRange.startOffset == 1){ tmpRange.setStartBefore(start); start = tmpRange.startContainer; } while (start && domUtils.isFillChar(start)) { tmp = start; start = start.previousSibling } if (tmp) { tmpRange.setStartBefore(tmp); start = tmpRange.startContainer; } if (start.nodeType == 1 && domUtils.isEmptyNode(start) && tmpRange.startOffset == 1) { tmpRange.setStart(start, 0).collapse(true); } while (!tmpRange.startOffset) { start = tmpRange.startContainer; if (domUtils.isBlockElm(start) || domUtils.isBody(start)) { flag = 1; break; } var pre = tmpRange.startContainer.previousSibling, tmpNode; if (!pre) { tmpRange.setStartBefore(tmpRange.startContainer); } else { while (pre && domUtils.isFillChar(pre)) { tmpNode = pre; pre = pre.previousSibling; } if (tmpNode) { tmpRange.setStartBefore(tmpNode); } else { tmpRange.setStartBefore(tmpRange.startContainer); } } } return flag && !domUtils.isBody(tmpRange.startContainer) ? 1 : 0; }, isEmptyBlock:function (node,reg) { if(node.nodeType != 1) return 0; reg = reg || new RegExp('[ \t\r\n' + domUtils.fillChar + ']', 'g'); if (node[browser.ie ? 'innerText' : 'textContent'].replace(reg, '').length > 0) { return 0; } for (var n in dtd.$isNotEmpty) { if (node.getElementsByTagName(n).length) { return 0; } } return 1; }, setViewportOffset:function (element, offset) { var left = parseInt(element.style.left) | 0; var top = parseInt(element.style.top) | 0; var rect = element.getBoundingClientRect(); var offsetLeft = offset.left - rect.left; var offsetTop = offset.top - rect.top; if (offsetLeft) { element.style.left = left + offsetLeft + 'px'; } if (offsetTop) { element.style.top = top + offsetTop + 'px'; } }, fillNode:function (doc, node) { var tmpNode = browser.ie ? doc.createTextNode(domUtils.fillChar) : doc.createElement('br'); node.innerHTML = ''; node.appendChild(tmpNode); }, moveChild:function (src, tag, dir) { while (src.firstChild) { if (dir && tag.firstChild) { tag.insertBefore(src.lastChild, tag.firstChild); } else { tag.appendChild(src.firstChild); } } }, //判断是否有额外属性 hasNoAttributes:function (node) { return browser.ie ? /^<\w+\s*?>/.test(node.outerHTML) : node.attributes.length == 0; }, //判断是否是编辑器自定义的参数 isCustomeNode:function (node) { return node.nodeType == 1 && node.getAttribute('_ue_custom_node_'); }, isTagNode:function (node, tagName) { return node.nodeType == 1 && new RegExp('^' + node.tagName + '$','i').test(tagName) }, /** * 对于nodelist用filter进行过滤 * @name filterNodeList * @since 1.2.4+ * @grammar UE.dom.domUtils.filterNodeList(nodelist,filter,onlyFirst) => 节点 * @example * UE.dom.domUtils.filterNodeList(document.getElementsByTagName('*'),'div p') //返回第一个是div或者p的节点 * UE.dom.domUtils.filterNodeList(document.getElementsByTagName('*'),function(n){return n.getAttribute('src')}) * //返回第一个带src属性的节点 * UE.dom.domUtils.filterNodeList(document.getElementsByTagName('*'),'i',true) //返回数组,里边都是i节点 */ filterNodeList : function(nodelist,filter,forAll){ var results = []; if(!utils .isFunction(filter)){ var str = filter; filter = function(n){ return utils.indexOf(utils.isArray(str) ? str:str.split(' '), n.tagName.toLowerCase()) != -1 }; } utils.each(nodelist,function(n){ filter(n) && results.push(n) }); return results.length == 0 ? null : results.length == 1 || !forAll ? results[0] : results }, isInNodeEndBoundary : function (rng,node){ var start = rng.startContainer; if(start.nodeType == 3 && rng.startOffset != start.nodeValue.length){ return 0; } if(start.nodeType == 1 && rng.startOffset != start.childNodes.length){ return 0; } while(start !== node){ if(start.nextSibling){ return 0 }; start = start.parentNode; } return 1; }, isBoundaryNode : function (node,dir){ var tmp; while(!domUtils.isBody(node)){ tmp = node; node = node.parentNode; if(tmp !== node[dir]){ return false; } } return true; } }; var fillCharReg = new RegExp(domUtils.fillChar, 'g');///import editor.js ///import core/utils.js ///import core/browser.js ///import core/dom/dom.js ///import core/dom/dtd.js ///import core/dom/domUtils.js /** * @file * @name UE.dom.Range * @anthor zhanyi * @short Range * @import editor.js,core/utils.js,core/browser.js,core/dom/domUtils.js,core/dom/dtd.js * @desc Range范围实现类,本类是UEditor底层核心类,统一w3cRange和ieRange之间的差异,包括接口和属性 */ (function () { var guid = 0, fillChar = domUtils.fillChar, fillData; /** * 更新range的collapse状态 * @param {Range} range range对象 */ function updateCollapse(range) { range.collapsed = range.startContainer && range.endContainer && range.startContainer === range.endContainer && range.startOffset == range.endOffset; } function selectOneNode(rng){ return !rng.collapsed && rng.startContainer.nodeType == 1 && rng.startContainer === rng.endContainer && rng.endOffset - rng.startOffset == 1 } function setEndPoint(toStart, node, offset, range) { //如果node是自闭合标签要处理 if (node.nodeType == 1 && (dtd.$empty[node.tagName] || dtd.$nonChild[node.tagName])) { offset = domUtils.getNodeIndex(node) + (toStart ? 0 : 1); node = node.parentNode; } if (toStart) { range.startContainer = node; range.startOffset = offset; if (!range.endContainer) { range.collapse(true); } } else { range.endContainer = node; range.endOffset = offset; if (!range.startContainer) { range.collapse(false); } } updateCollapse(range); return range; } function execContentsAction(range, action) { //调整边界 //range.includeBookmark(); var start = range.startContainer, end = range.endContainer, startOffset = range.startOffset, endOffset = range.endOffset, doc = range.document, frag = doc.createDocumentFragment(), tmpStart, tmpEnd; if (start.nodeType == 1) { start = start.childNodes[startOffset] || (tmpStart = start.appendChild(doc.createTextNode(''))); } if (end.nodeType == 1) { end = end.childNodes[endOffset] || (tmpEnd = end.appendChild(doc.createTextNode(''))); } if (start === end && start.nodeType == 3) { frag.appendChild(doc.createTextNode(start.substringData(startOffset, endOffset - startOffset))); //is not clone if (action) { start.deleteData(startOffset, endOffset - startOffset); range.collapse(true); } return frag; } var current, currentLevel, clone = frag, startParents = domUtils.findParents(start, true), endParents = domUtils.findParents(end, true); for (var i = 0; startParents[i] == endParents[i];) { i++; } for (var j = i, si; si = startParents[j]; j++) { current = si.nextSibling; if (si == start) { if (!tmpStart) { if (range.startContainer.nodeType == 3) { clone.appendChild(doc.createTextNode(start.nodeValue.slice(startOffset))); //is not clone if (action) { start.deleteData(startOffset, start.nodeValue.length - startOffset); } } else { clone.appendChild(!action ? start.cloneNode(true) : start); } } } else { currentLevel = si.cloneNode(false); clone.appendChild(currentLevel); } while (current) { if (current === end || current === endParents[j]) { break; } si = current.nextSibling; clone.appendChild(!action ? current.cloneNode(true) : current); current = si; } clone = currentLevel; } clone = frag; if (!startParents[i]) { clone.appendChild(startParents[i - 1].cloneNode(false)); clone = clone.firstChild; } for (var j = i, ei; ei = endParents[j]; j++) { current = ei.previousSibling; if (ei == end) { if (!tmpEnd && range.endContainer.nodeType == 3) { clone.appendChild(doc.createTextNode(end.substringData(0, endOffset))); //is not clone if (action) { end.deleteData(0, endOffset); } } } else { currentLevel = ei.cloneNode(false); clone.appendChild(currentLevel); } //如果两端同级,右边第一次已经被开始做了 if (j != i || !startParents[i]) { while (current) { if (current === start) { break; } ei = current.previousSibling; clone.insertBefore(!action ? current.cloneNode(true) : current, clone.firstChild); current = ei; } } clone = currentLevel; } if (action) { range.setStartBefore(!endParents[i] ? endParents[i - 1] : !startParents[i] ? startParents[i - 1] : endParents[i]).collapse(true); } tmpStart && domUtils.remove(tmpStart); tmpEnd && domUtils.remove(tmpEnd); return frag; } /** * @name Range * @grammar new UE.dom.Range(document) => Range 实例 * @desc 创建一个跟document绑定的空的Range实例 * - ***startContainer*** 开始边界的容器节点,可以是elementNode或者是textNode * - ***startOffset*** 容器节点中的偏移量,如果是elementNode就是childNodes中的第几个,如果是textNode就是nodeValue的第几个字符 * - ***endContainer*** 结束边界的容器节点,可以是elementNode或者是textNode * - ***endOffset*** 容器节点中的偏移量,如果是elementNode就是childNodes中的第几个,如果是textNode就是nodeValue的第几个字符 * - ***document*** 跟range关联的document对象 * - ***collapsed*** 是否是闭合状态 */ var Range = dom.Range = function (document) { var me = this; me.startContainer = me.startOffset = me.endContainer = me.endOffset = null; me.document = document; me.collapsed = true; }; /** * 删除fillData * @param doc * @param excludeNode */ function removeFillData(doc, excludeNode) { try { if (fillData && domUtils.inDoc(fillData, doc)) { if (!fillData.nodeValue.replace(fillCharReg, '').length) { var tmpNode = fillData.parentNode; domUtils.remove(fillData); while (tmpNode && domUtils.isEmptyInlineElement(tmpNode) && //safari的contains有bug (browser.safari ? !(domUtils.getPosition(tmpNode,excludeNode) & domUtils.POSITION_CONTAINS) : !tmpNode.contains(excludeNode)) ) { fillData = tmpNode.parentNode; domUtils.remove(tmpNode); tmpNode = fillData; } } else { fillData.nodeValue = fillData.nodeValue.replace(fillCharReg, ''); } } } catch (e) { } } /** * * @param node * @param dir */ function mergeSibling(node, dir) { var tmpNode; node = node[dir]; while (node && domUtils.isFillChar(node)) { tmpNode = node[dir]; domUtils.remove(node); node = tmpNode; } } Range.prototype = { /** * @name cloneContents * @grammar range.cloneContents() => DocumentFragment * @desc 克隆选中的内容到一个fragment里,如果选区是空的将返回null */ cloneContents:function () { return this.collapsed ? null : execContentsAction(this, 0); }, /** * @name deleteContents * @grammar range.deleteContents() => Range * @desc 删除当前选区范围中的所有内容并返回range实例,这时的range已经变成了闭合状态 * @example * DOM Element : * <b>x<i>x[x<i>xx]x</b> * //执行方法后 * <b>x<i>x<i>|x</b> * 注意range改变了 * range.startContainer => b * range.startOffset => 2 * range.endContainer => b * range.endOffset => 2 * range.collapsed => true */ deleteContents:function () { var txt; if (!this.collapsed) { execContentsAction(this, 1); } if (browser.webkit) { txt = this.startContainer; if (txt.nodeType == 3 && !txt.nodeValue.length) { this.setStartBefore(txt).collapse(true); domUtils.remove(txt); } } return this; }, /** * @name extractContents * @grammar range.extractContents() => DocumentFragment * @desc 将当前的内容放到一个fragment里并返回这个fragment,这时的range已经变成了闭合状态 * @example * DOM Element : * <b>x<i>x[x<i>xx]x</b> * //执行方法后 * 返回的fragment里的 dom结构是 * <i>x<i>xx * dom树上的结构是 * <b>x<i>x<i>|x</b> * 注意range改变了 * range.startContainer => b * range.startOffset => 2 * range.endContainer => b * range.endOffset => 2 * range.collapsed => true */ extractContents:function () { return this.collapsed ? null : execContentsAction(this, 2); }, /** * @name setStart * @grammar range.setStart(node,offset) => Range * @desc 设置range的开始位置位于node节点内,偏移量为offset * 如果node是elementNode那offset指的是childNodes中的第几个,如果是textNode那offset指的是nodeValue的第几个字符 */ setStart:function (node, offset) { return setEndPoint(true, node, offset, this); }, /** * 设置range的结束位置位于node节点,偏移量为offset * 如果node是elementNode那offset指的是childNodes中的第几个,如果是textNode那offset指的是nodeValue的第几个字符 * @name setEnd * @grammar range.setEnd(node,offset) => Range */ setEnd:function (node, offset) { return setEndPoint(false, node, offset, this); }, /** * 将Range开始位置设置到node节点之后 * @name setStartAfter * @grammar range.setStartAfter(node) => Range * @example * <b>xx<i>x|x</i>x</b> * 执行setStartAfter(i)后 * range.startContainer =>b * range.startOffset =>2 */ setStartAfter:function (node) { return this.setStart(node.parentNode, domUtils.getNodeIndex(node) + 1); }, /** * 将Range开始位置设置到node节点之前 * @name setStartBefore * @grammar range.setStartBefore(node) => Range * @example * <b>xx<i>x|x</i>x</b> * 执行setStartBefore(i)后 * range.startContainer =>b * range.startOffset =>1 */ setStartBefore:function (node) { return this.setStart(node.parentNode, domUtils.getNodeIndex(node)); }, /** * 将Range结束位置设置到node节点之后 * @name setEndAfter * @grammar range.setEndAfter(node) => Range * @example * <b>xx<i>x|x</i>x</b> * setEndAfter(i)后 * range.endContainer =>b * range.endtOffset =>2 */ setEndAfter:function (node) { return this.setEnd(node.parentNode, domUtils.getNodeIndex(node) + 1); }, /** * 将Range结束位置设置到node节点之前 * @name setEndBefore * @grammar range.setEndBefore(node) => Range * @example * <b>xx<i>x|x</i>x</b> * 执行setEndBefore(i)后 * range.endContainer =>b * range.endtOffset =>1 */ setEndBefore:function (node) { return this.setEnd(node.parentNode, domUtils.getNodeIndex(node)); }, /** * 将Range开始位置设置到node节点内的开始位置 * @name setStartAtFirst * @grammar range.setStartAtFirst(node) => Range */ setStartAtFirst:function (node) { return this.setStart(node, 0); }, /** * 将Range开始位置设置到node节点内的结束位置 * @name setStartAtLast * @grammar range.setStartAtLast(node) => Range */ setStartAtLast:function (node) { return this.setStart(node, node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length); }, /** * 将Range结束位置设置到node节点内的开始位置 * @name setEndAtFirst * @grammar range.setEndAtFirst(node) => Range */ setEndAtFirst:function (node) { return this.setEnd(node, 0); }, /** * 将Range结束位置设置到node节点内的结束位置 * @name setEndAtLast * @grammar range.setEndAtLast(node) => Range */ setEndAtLast:function (node) { return this.setEnd(node, node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length); }, /** * 选中完整的指定节点,并返回包含该节点的range * @name selectNode * @grammar range.selectNode(node) => Range */ selectNode:function (node) { return this.setStartBefore(node).setEndAfter(node); }, /** * 选中node内部的所有节点,并返回对应的range * @name selectNodeContents * @grammar range.selectNodeContents(node) => Range * @example * <b>xx[x<i>xxx</i>]xxx</b> * 执行后 * <b>[xxx<i>xxx</i>xxx]</b> * range.startContainer =>b * range.startOffset =>0 * range.endContainer =>b * range.endOffset =>3 */ selectNodeContents:function (node) { return this.setStart(node, 0).setEndAtLast(node); }, /** * 克隆一个新的range对象 * @name cloneRange * @grammar range.cloneRange() => Range */ cloneRange:function () { var me = this; return new Range(me.document).setStart(me.startContainer, me.startOffset).setEnd(me.endContainer, me.endOffset); }, /** * 让选区闭合到尾部,若toStart为真,则闭合到头部 * @name collapse * @grammar range.collapse() => Range * @grammar range.collapse(true) => Range //闭合选区到头部 */ collapse:function (toStart) { var me = this; if (toStart) { me.endContainer = me.startContainer; me.endOffset = me.startOffset; } else { me.startContainer = me.endContainer; me.startOffset = me.endOffset; } me.collapsed = true; return me; }, /** * 调整range的边界,使其"收缩"到最小的位置 * @name shrinkBoundary * @grammar range.shrinkBoundary() => Range //range开始位置和结束位置都调整,参见<code><a href="#adjustmentboundary">adjustmentBoundary</a></code> * @grammar range.shrinkBoundary(true) => Range //仅调整开始位置,忽略结束位置 * @example * <b>xx[</b>xxxxx] ==> <b>xx</b>[xxxxx] * <b>x[xx</b><i>]xxx</i> ==> <b>x[xx]</b><i>xxx</i> * [<b><i>xxxx</i>xxxxxxx</b>] ==> <b><i>[xxxx</i>xxxxxxx]</b> */ shrinkBoundary:function (ignoreEnd) { var me = this, child, collapsed = me.collapsed; function check(node){ return node.nodeType == 1 && !domUtils.isBookmarkNode(node) && !dtd.$empty[node.tagName] && !dtd.$nonChild[node.tagName] } while (me.startContainer.nodeType == 1 //是element && (child = me.startContainer.childNodes[me.startOffset]) //子节点也是element && check(child)) { me.setStart(child, 0); } if (collapsed) { return me.collapse(true); } if (!ignoreEnd) { while (me.endContainer.nodeType == 1//是element && me.endOffset > 0 //如果是空元素就退出 endOffset=0那么endOffst-1为负值,childNodes[endOffset]报错 && (child = me.endContainer.childNodes[me.endOffset - 1]) //子节点也是element && check(child)) { me.setEnd(child, child.childNodes.length); } } return me; }, /** * 获取当前range所在位置的公共祖先节点,当前range位置可以位于文本节点内,也可以包含整个元素节点,也可以位于两个节点之间 * @name getCommonAncestor * @grammar range.getCommonAncestor([includeSelf, ignoreTextNode]) => Element * @example * <b>xx[xx<i>xx]x</i>xxx</b> ==>getCommonAncestor() ==> b * <b>[<img/>]</b> * range.startContainer ==> b * range.startOffset ==> 0 * range.endContainer ==> b * range.endOffset ==> 1 * range.getCommonAncestor() ==> b * range.getCommonAncestor(true) ==> img * <b>xxx|xx</b> * range.startContainer ==> textNode * range.startOffset ==> 3 * range.endContainer ==> textNode * range.endOffset ==> 3 * range.getCommonAncestor() ==> textNode * range.getCommonAncestor(null,true) ==> b */ getCommonAncestor:function (includeSelf, ignoreTextNode) { var me = this, start = me.startContainer, end = me.endContainer; if (start === end) { if (includeSelf && selectOneNode(this)) { start = start.childNodes[me.startOffset]; if(start.nodeType == 1) return start; } //只有在上来就相等的情况下才会出现是文本的情况 return ignoreTextNode && start.nodeType == 3 ? start.parentNode : start; } return domUtils.getCommonAncestor(start, end); }, /** * 调整边界容器,如果是textNode,就调整到elementNode上 * @name trimBoundary * @grammar range.trimBoundary([ignoreEnd]) => Range //true忽略结束边界 * @example * DOM Element : * <b>|xxx</b> * startContainer = xxx; startOffset = 0 * //执行后本方法后 * startContainer = <b>; startOffset = 0 * @example * Dom Element : * <b>xx|x</b> * startContainer = xxx; startOffset = 2 * //执行本方法后,xxx被实实在在地切分成两个TextNode * startContainer = <b>; startOffset = 1 */ trimBoundary:function (ignoreEnd) { this.txtToElmBoundary(); var start = this.startContainer, offset = this.startOffset, collapsed = this.collapsed, end = this.endContainer; if (start.nodeType == 3) { if (offset == 0) { this.setStartBefore(start); } else { if (offset >= start.nodeValue.length) { this.setStartAfter(start); } else { var textNode = domUtils.split(start, offset); //跟新结束边界 if (start === end) { this.setEnd(textNode, this.endOffset - offset); } else if (start.parentNode === end) { this.endOffset += 1; } this.setStartBefore(textNode); } } if (collapsed) { return this.collapse(true); } } if (!ignoreEnd) { offset = this.endOffset; end = this.endContainer; if (end.nodeType == 3) { if (offset == 0) { this.setEndBefore(end); } else { offset < end.nodeValue.length && domUtils.split(end, offset); this.setEndAfter(end); } } } return this; }, /** * 如果选区在文本的边界上,就扩展选区到文本的父节点上 * @name txtToElmBoundary * @example * Dom Element : * <b> |xxx</b> * startContainer = xxx; startOffset = 0 * //本方法执行后 * startContainer = <b>; startOffset = 0 * @example * Dom Element : * <b> xxx| </b> * startContainer = xxx; startOffset = 3 * //本方法执行后 * startContainer = <b>; startOffset = 1 */ txtToElmBoundary:function (ignoreCollapsed) { function adjust(r, c) { var container = r[c + 'Container'], offset = r[c + 'Offset']; if (container.nodeType == 3) { if (!offset) { r['set' + c.replace(/(\w)/, function (a) { return a.toUpperCase(); }) + 'Before'](container); } else if (offset >= container.nodeValue.length) { r['set' + c.replace(/(\w)/, function (a) { return a.toUpperCase(); }) + 'After' ](container); } } } if (ignoreCollapsed || !this.collapsed) { adjust(this, 'start'); adjust(this, 'end'); } return this; }, /** * 在当前选区的开始位置前插入一个节点或者fragment,range的开始位置会在插入节点的前边 * @name insertNode * @grammar range.insertNode(node) => Range //node可以是textNode,elementNode,fragment * @example * Range : * xxx[x<p>xxxx</p>xxxx]x<p>sdfsdf</p> * 待插入Node : * <p>ssss</p> * 执行本方法后的Range : * xxx[<p>ssss</p>x<p>xxxx</p>xxxx]x<p>sdfsdf</p> */ insertNode:function (node) { var first = node, length = 1; if (node.nodeType == 11) { first = node.firstChild; length = node.childNodes.length; } this.trimBoundary(true); var start = this.startContainer, offset = this.startOffset; var nextNode = start.childNodes[ offset ]; if (nextNode) { start.insertBefore(node, nextNode); } else { start.appendChild(node); } if (first.parentNode === this.endContainer) { this.endOffset = this.endOffset + length; } return this.setStartBefore(first); }, /** * 设置光标闭合位置,toEnd设置为true时光标将闭合到选区的结尾 * @name setCursor * @grammar range.setCursor([toEnd]) => Range //toEnd为true时,光标闭合到选区的末尾 */ setCursor:function (toEnd, noFillData) { return this.collapse(!toEnd).select(noFillData); }, /** * 创建当前range的一个书签,记录下当前range的位置,方便当dom树改变时,还能找回原来的选区位置 * @name createBookmark * @grammar range.createBookmark([serialize]) => Object //{start:开始标记,end:结束标记,id:serialize} serialize为真时,开始结束标记是插入节点的id,否则是插入节点的引用 */ createBookmark:function (serialize, same) { var endNode, startNode = this.document.createElement('span'); startNode.style.cssText = 'display:none;line-height:0px;'; startNode.appendChild(this.document.createTextNode('\u200D')); startNode.id = '_baidu_bookmark_start_' + (same ? '' : guid++); if (!this.collapsed) { endNode = startNode.cloneNode(true); endNode.id = '_baidu_bookmark_end_' + (same ? '' : guid++); } this.insertNode(startNode); if (endNode) { this.collapse().insertNode(endNode).setEndBefore(endNode); } this.setStartAfter(startNode); return { start:serialize ? startNode.id : startNode, end:endNode ? serialize ? endNode.id : endNode : null, id:serialize } }, /** * 移动边界到书签位置,并删除插入的书签节点 * @name moveToBookmark * @grammar range.moveToBookmark(bookmark) => Range //让当前的range选到给定bookmark的位置,bookmark对象是由range.createBookmark创建的 */ moveToBookmark:function (bookmark) { var start = bookmark.id ? this.document.getElementById(bookmark.start) : bookmark.start, end = bookmark.end && bookmark.id ? this.document.getElementById(bookmark.end) : bookmark.end; this.setStartBefore(start); domUtils.remove(start); if (end) { this.setEndBefore(end); domUtils.remove(end); } else { this.collapse(true); } return this; }, /** * 调整range的边界,使其"放大"到最近的父block节点 * @name enlarge * @grammar range.enlarge() => Range * @example * <p><span>xxx</span><b>x[x</b>xxxxx]</p><p>xxx</p> ==> [<p><span>xxx</span><b>xx</b>xxxxx</p>]<p>xxx</p> */ enlarge:function (toBlock, stopFn) { var isBody = domUtils.isBody, pre, node, tmp = this.document.createTextNode(''); if (toBlock) { node = this.startContainer; if (node.nodeType == 1) { if (node.childNodes[this.startOffset]) { pre = node = node.childNodes[this.startOffset] } else { node.appendChild(tmp); pre = node = tmp; } } else { pre = node; } while (1) { if (domUtils.isBlockElm(node)) { node = pre; while ((pre = node.previousSibling) && !domUtils.isBlockElm(pre)) { node = pre; } this.setStartBefore(node); break; } pre = node; node = node.parentNode; } node = this.endContainer; if (node.nodeType == 1) { if (pre = node.childNodes[this.endOffset]) { node.insertBefore(tmp, pre); } else { node.appendChild(tmp); } pre = node = tmp; } else { pre = node; } while (1) { if (domUtils.isBlockElm(node)) { node = pre; while ((pre = node.nextSibling) && !domUtils.isBlockElm(pre)) { node = pre; } this.setEndAfter(node); break; } pre = node; node = node.parentNode; } if (tmp.parentNode === this.endContainer) { this.endOffset--; } domUtils.remove(tmp); } // 扩展边界到最大 if (!this.collapsed) { while (this.startOffset == 0) { if (stopFn && stopFn(this.startContainer)) { break; } if (isBody(this.startContainer)) { break; } this.setStartBefore(this.startContainer); } while (this.endOffset == (this.endContainer.nodeType == 1 ? this.endContainer.childNodes.length : this.endContainer.nodeValue.length)) { if (stopFn && stopFn(this.endContainer)) { break; } if (isBody(this.endContainer)) { break; } this.setEndAfter(this.endContainer); } } return this; }, /** * 调整Range的边界,使其"缩小"到最合适的位置 * @name adjustmentBoundary * @grammar range.adjustmentBoundary() => Range //参见<code><a href="#shrinkboundary">shrinkBoundary</a></code> * @example * <b>xx[</b>xxxxx] ==> <b>xx</b>[xxxxx] * <b>x[xx</b><i>]xxx</i> ==> <b>x[xx</b>]<i>xxx</i> */ adjustmentBoundary:function () { if (!this.collapsed) { while (!domUtils.isBody(this.startContainer) && this.startOffset == this.startContainer[this.startContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length && this.startContainer[this.startContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length ) { this.setStartAfter(this.startContainer); } while (!domUtils.isBody(this.endContainer) && !this.endOffset && this.endContainer[this.endContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length ) { this.setEndBefore(this.endContainer); } } return this; }, /** * 给range选区中的内容添加给定的标签,主要用于inline标签 * @name applyInlineStyle * @grammar range.applyInlineStyle(tagName) => Range //tagName为需要添加的样式标签名 * @grammar range.applyInlineStyle(tagName,attrs) => Range //attrs为属性json对象 * @desc * <code type="html"><p>xxxx[xxxx]x</p> ==> range.applyInlineStyle("strong") ==> <p>xxxx[<strong>xxxx</strong>]x</p> * <p>xx[dd<strong>yyyy</strong>]x</p> ==> range.applyInlineStyle("strong") ==> <p>xx[<strong>ddyyyy</strong>]x</p> * <p>xxxx[xxxx]x</p> ==> range.applyInlineStyle("strong",{"style":"font-size:12px"}) ==> <p>xxxx[<strong style="font-size:12px">xxxx</strong>]x</p></code> */ applyInlineStyle:function (tagName, attrs, list) { if (this.collapsed)return this; this.trimBoundary().enlarge(false, function (node) { return node.nodeType == 1 && domUtils.isBlockElm(node) }).adjustmentBoundary(); var bookmark = this.createBookmark(), end = bookmark.end, filterFn = function (node) { return node.nodeType == 1 ? node.tagName.toLowerCase() != 'br' : !domUtils.isWhitespace(node); }, current = domUtils.getNextDomNode(bookmark.start, false, filterFn), node, pre, range = this.cloneRange(); while (current && (domUtils.getPosition(current, end) & domUtils.POSITION_PRECEDING)) { if (current.nodeType == 3 || dtd[tagName][current.tagName]) { range.setStartBefore(current); node = current; while (node && (node.nodeType == 3 || dtd[tagName][node.tagName]) && node !== end) { pre = node; node = domUtils.getNextDomNode(node, node.nodeType == 1, null, function (parent) { return dtd[tagName][parent.tagName]; }); } var frag = range.setEndAfter(pre).extractContents(), elm; if (list && list.length > 0) { var level, top; top = level = list[0].cloneNode(false); for (var i = 1, ci; ci = list[i++];) { level.appendChild(ci.cloneNode(false)); level = level.firstChild; } elm = level; } else { elm = range.document.createElement(tagName); } if (attrs) { domUtils.setAttributes(elm, attrs); } elm.appendChild(frag); range.insertNode(list ? top : elm); //处理下滑线在a上的情况 var aNode; if (tagName == 'span' && attrs.style && /text\-decoration/.test(attrs.style) && (aNode = domUtils.findParentByTagName(elm, 'a', true))) { domUtils.setAttributes(aNode, attrs); domUtils.remove(elm, true); elm = aNode; } else { domUtils.mergeSibling(elm); domUtils.clearEmptySibling(elm); } //去除子节点相同的 domUtils.mergeChild(elm, attrs); current = domUtils.getNextDomNode(elm, false, filterFn); domUtils.mergeToParent(elm); if (node === end) { break; } } else { current = domUtils.getNextDomNode(current, true, filterFn); } } return this.moveToBookmark(bookmark); }, /** * 对当前range选中的节点,去掉给定的标签节点,但标签中的内容保留,主要用于处理inline元素 * @name removeInlineStyle * @grammar range.removeInlineStyle(tagNames) => Range //tagNames 为需要去掉的样式标签名,支持"b"或者["b","i","u"] * @desc * <code type="html">xx[x<span>xxx<em>yyy</em>zz]z</span> => range.removeInlineStyle(["em"]) => xx[x<span>xxxyyyzz]z</span></code> */ removeInlineStyle:function (tagNames) { if (this.collapsed)return this; tagNames = utils.isArray(tagNames) ? tagNames : [tagNames]; this.shrinkBoundary().adjustmentBoundary(); var start = this.startContainer, end = this.endContainer; while (1) { if (start.nodeType == 1) { if (utils.indexOf(tagNames, start.tagName.toLowerCase()) > -1) { break; } if (start.tagName.toLowerCase() == 'body') { start = null; break; } } start = start.parentNode; } while (1) { if (end.nodeType == 1) { if (utils.indexOf(tagNames, end.tagName.toLowerCase()) > -1) { break; } if (end.tagName.toLowerCase() == 'body') { end = null; break; } } end = end.parentNode; } var bookmark = this.createBookmark(), frag, tmpRange; if (start) { tmpRange = this.cloneRange().setEndBefore(bookmark.start).setStartBefore(start); frag = tmpRange.extractContents(); tmpRange.insertNode(frag); domUtils.clearEmptySibling(start, true); start.parentNode.insertBefore(bookmark.start, start); } if (end) { tmpRange = this.cloneRange().setStartAfter(bookmark.end).setEndAfter(end); frag = tmpRange.extractContents(); tmpRange.insertNode(frag); domUtils.clearEmptySibling(end, false, true); end.parentNode.insertBefore(bookmark.end, end.nextSibling); } var current = domUtils.getNextDomNode(bookmark.start, false, function (node) { return node.nodeType == 1; }), next; while (current && current !== bookmark.end) { next = domUtils.getNextDomNode(current, true, function (node) { return node.nodeType == 1; }); if (utils.indexOf(tagNames, current.tagName.toLowerCase()) > -1) { domUtils.remove(current, true); } current = next; } return this.moveToBookmark(bookmark); }, /** * 得到一个自闭合的节点,常用于获取自闭和的节点,例如图片节点 * @name getClosedNode * @grammar range.getClosedNode() => node|null * @example * <b>xxxx[<img />]xxx</b> */ getClosedNode:function () { var node; if (!this.collapsed) { var range = this.cloneRange().adjustmentBoundary().shrinkBoundary(); if (selectOneNode(range)) { var child = range.startContainer.childNodes[range.startOffset]; if (child && child.nodeType == 1 && (dtd.$empty[child.tagName] || dtd.$nonChild[child.tagName])) { node = child; } } } return node; }, /** * 根据当前range选中内容节点(在页面上表现为反白显示) * @name select * @grammar range.select(); => Range */ select:browser.ie ? function (noFillData, textRange) { var nativeRange; if (!this.collapsed) this.shrinkBoundary(); var node = this.getClosedNode(); if (node && !textRange) { try { nativeRange = this.document.body.createControlRange(); nativeRange.addElement(node); nativeRange.select(); } catch (e) {} return this; } var bookmark = this.createBookmark(), start = bookmark.start, end; nativeRange = this.document.body.createTextRange(); nativeRange.moveToElementText(start); nativeRange.moveStart('character', 1); if (!this.collapsed) { var nativeRangeEnd = this.document.body.createTextRange(); end = bookmark.end; nativeRangeEnd.moveToElementText(end); nativeRange.setEndPoint('EndToEnd', nativeRangeEnd); } else { if (!noFillData && this.startContainer.nodeType != 3) { //使用<span>|x<span>固定住光标 var tmpText = this.document.createTextNode(fillChar), tmp = this.document.createElement('span'); tmp.appendChild(this.document.createTextNode(fillChar)); start.parentNode.insertBefore(tmp, start); start.parentNode.insertBefore(tmpText, start); //当点b,i,u时,不能清除i上边的b removeFillData(this.document, tmpText); fillData = tmpText; mergeSibling(tmp, 'previousSibling'); mergeSibling(start, 'nextSibling'); nativeRange.moveStart('character', -1); nativeRange.collapse(true); } } this.moveToBookmark(bookmark); tmp && domUtils.remove(tmp); //IE在隐藏状态下不支持range操作,catch一下 try { nativeRange.select(); } catch (e) { } return this; } : function (notInsertFillData) { function checkOffset(rng){ function check(node,offset,dir){ if(node.nodeType == 3 && node.nodeValue.length < offset){ rng[dir + 'Offset'] = node.nodeValue.length } } check(rng.startContainer,rng.startOffset,'start'); check(rng.endContainer,rng.endOffset,'end'); } var win = domUtils.getWindow(this.document), sel = win.getSelection(), txtNode; //FF下关闭自动长高时滚动条在关闭dialog时会跳 //ff下如果不body.focus将不能定位闭合光标到编辑器内 browser.gecko ? this.document.body.focus() : win.focus(); if (sel) { sel.removeAllRanges(); // trace:870 chrome/safari后边是br对于闭合得range不能定位 所以去掉了判断 // this.startContainer.nodeType != 3 &&! ((child = this.startContainer.childNodes[this.startOffset]) && child.nodeType == 1 && child.tagName == 'BR' if (this.collapsed && !notInsertFillData) { // //opear如果没有节点接着,原生的不能够定位,不能在body的第一级插入空白节点 // if (notInsertFillData && browser.opera && !domUtils.isBody(this.startContainer) && this.startContainer.nodeType == 1) { // var tmp = this.document.createTextNode(''); // this.insertNode(tmp).setStart(tmp, 0).collapse(true); // } // //处理光标落在文本节点的情况 //处理以下的情况 //<b>|xxxx</b> //<b>xxxx</b>|xxxx //xxxx<b>|</b> var start = this.startContainer,child = start; if(start.nodeType == 1){ child = start.childNodes[this.startOffset]; } if( !(start.nodeType == 3 && this.startOffset) && (child ? (!child.previousSibling || child.previousSibling.nodeType != 3) : (!start.lastChild || start.lastChild.nodeType != 3) ) ){ txtNode = this.document.createTextNode(fillChar); //跟着前边走 this.insertNode(txtNode); removeFillData(this.document, txtNode); mergeSibling(txtNode, 'previousSibling'); mergeSibling(txtNode, 'nextSibling'); fillData = txtNode; this.setStart(txtNode, browser.webkit ? 1 : 0).collapse(true); } } var nativeRange = this.document.createRange(); if(this.collapsed && browser.opera && this.startContainer.nodeType == 1){ var child = this.startContainer.childNodes[this.startOffset]; if(!child){ //往前靠拢 child = this.startContainer.lastChild; if( child && domUtils.isBr(child)){ this.setStartBefore(child).collapse(true); } }else{ //向后靠拢 while(child && domUtils.isBlockElm(child)){ if(child.nodeType == 1 && child.childNodes[0]){ child = child.childNodes[0] }else{ break; } } child && this.setStartBefore(child).collapse(true) } } //是createAddress最后一位算的不准,现在这里进行微调 checkOffset(this); nativeRange.setStart(this.startContainer, this.startOffset); nativeRange.setEnd(this.endContainer, this.endOffset); sel.addRange(nativeRange); } return this; }, /** * 滚动条跳到当然range开始的位置 * @name scrollToView * @grammar range.scrollToView([win,offset]) => Range //针对window对象,若不指定,将以编辑区域的窗口为准,offset偏移量 */ scrollToView:function (win, offset) { win = win ? window : domUtils.getWindow(this.document); var me = this, span = me.document.createElement('span'); //trace:717 span.innerHTML = '&nbsp;'; me.cloneRange().insertNode(span); domUtils.scrollToView(span, win, offset); domUtils.remove(span); return me; }, inFillChar : function(){ var start = this.startContainer; if(this.collapsed && start.nodeType == 3 && start.nodeValue.replace(new RegExp('^' + domUtils.fillChar),'').length + 1 == start.nodeValue.length ){ return true; } return false; }, createAddress : function(ignoreEnd,ignoreTxt){ var addr = {},me = this; function getAddress(isStart){ var node = isStart ? me.startContainer : me.endContainer; var parents = domUtils.findParents(node,true,function(node){return !domUtils.isBody(node)}), addrs = []; for(var i = 0,ci;ci = parents[i++];){ addrs.push(domUtils.getNodeIndex(ci,ignoreTxt)); } var firstIndex = 0; if(ignoreTxt){ if(node.nodeType == 3){ var tmpNode = node.previousSibling; while(tmpNode && tmpNode.nodeType == 3){ firstIndex += tmpNode.nodeValue.replace(fillCharReg,'').length; tmpNode = tmpNode.previousSibling; } firstIndex += (isStart ? me.startOffset : me.endOffset)// - (fillCharReg.test(node.nodeValue) ? 1 : 0 ) }else{ node = node.childNodes[ isStart ? me.startOffset : me.endOffset]; if(node){ firstIndex = domUtils.getNodeIndex(node,ignoreTxt); }else{ node = isStart ? me.startContainer : me.endContainer; var first = node.firstChild; while(first){ if(domUtils.isFillChar(first)){ first = first.nextSibling; continue; } firstIndex++; if(first.nodeType == 3){ while( first && first.nodeType == 3){ first = first.nextSibling; } }else{ first = first.nextSibling; } } } } }else{ firstIndex = isStart ? domUtils.isFillChar(node) ? 0 : me.startOffset : me.endOffset } if(firstIndex < 0){ firstIndex = 0; } addrs.push(firstIndex); return addrs; } addr.startAddress = getAddress(true); if(!ignoreEnd){ addr.endAddress = me.collapsed ? [].concat(addr.startAddress) : getAddress(); } return addr; }, moveToAddress : function(addr,ignoreEnd){ var me = this; function getNode(address,isStart){ var tmpNode = me.document.body, parentNode,offset; for(var i= 0,ci,l=address.length;i<l;i++){ ci = address[i]; parentNode = tmpNode; tmpNode = tmpNode.childNodes[ci]; if(!tmpNode){ offset = ci; break; } } if(isStart){ if(tmpNode){ me.setStartBefore(tmpNode) }else{ me.setStart(parentNode,offset) } }else{ if(tmpNode){ me.setEndBefore(tmpNode) }else{ me.setEnd(parentNode,offset) } } } getNode(addr.startAddress,true); !ignoreEnd && addr.endAddress && getNode(addr.endAddress); return me; }, equals : function(rng){ for(var p in this){ if(this.hasOwnProperty(p)){ if(this[p] !== rng[p]) return false } } return true; }, traversal:function(doFn,filterFn){ if (this.collapsed) return this; var bookmark = this.createBookmark(), end = bookmark.end, current = domUtils.getNextDomNode(bookmark.start, false, filterFn); while (current && current !== end && (domUtils.getPosition(current, end) & domUtils.POSITION_PRECEDING)) { var tmpNode = domUtils.getNextDomNode(current,false,filterFn); doFn(current); current = tmpNode; } return this.moveToBookmark(bookmark); } }; })();///import editor.js ///import core/browser.js ///import core/dom/dom.js ///import core/dom/dtd.js ///import core/dom/domUtils.js ///import core/dom/Range.js /** * @class baidu.editor.dom.Selection Selection类 */ (function () { function getBoundaryInformation( range, start ) { var getIndex = domUtils.getNodeIndex; range = range.duplicate(); range.collapse( start ); var parent = range.parentElement(); //如果节点里没有子节点,直接退出 if ( !parent.hasChildNodes() ) { return {container:parent, offset:0}; } var siblings = parent.children, child, testRange = range.duplicate(), startIndex = 0, endIndex = siblings.length - 1, index = -1, distance; while ( startIndex <= endIndex ) { index = Math.floor( (startIndex + endIndex) / 2 ); child = siblings[index]; testRange.moveToElementText( child ); var position = testRange.compareEndPoints( 'StartToStart', range ); if ( position > 0 ) { endIndex = index - 1; } else if ( position < 0 ) { startIndex = index + 1; } else { //trace:1043 return {container:parent, offset:getIndex( child )}; } } if ( index == -1 ) { testRange.moveToElementText( parent ); testRange.setEndPoint( 'StartToStart', range ); distance = testRange.text.replace( /(\r\n|\r)/g, '\n' ).length; siblings = parent.childNodes; if ( !distance ) { child = siblings[siblings.length - 1]; return {container:child, offset:child.nodeValue.length}; } var i = siblings.length; while ( distance > 0 ){ distance -= siblings[ --i ].nodeValue.length; } return {container:siblings[i], offset:-distance}; } testRange.collapse( position > 0 ); testRange.setEndPoint( position > 0 ? 'StartToStart' : 'EndToStart', range ); distance = testRange.text.replace( /(\r\n|\r)/g, '\n' ).length; if ( !distance ) { return dtd.$empty[child.tagName] || dtd.$nonChild[child.tagName] ? {container:parent, offset:getIndex( child ) + (position > 0 ? 0 : 1)} : {container:child, offset:position > 0 ? 0 : child.childNodes.length} } while ( distance > 0 ) { try { var pre = child; child = child[position > 0 ? 'previousSibling' : 'nextSibling']; distance -= child.nodeValue.length; } catch ( e ) { return {container:parent, offset:getIndex( pre )}; } } return {container:child, offset:position > 0 ? -distance : child.nodeValue.length + distance} } /** * 将ieRange转换为Range对象 * @param {Range} ieRange ieRange对象 * @param {Range} range Range对象 * @return {Range} range 返回转换后的Range对象 */ function transformIERangeToRange( ieRange, range ) { if ( ieRange.item ) { range.selectNode( ieRange.item( 0 ) ); } else { var bi = getBoundaryInformation( ieRange, true ); range.setStart( bi.container, bi.offset ); if ( ieRange.compareEndPoints( 'StartToEnd', ieRange ) != 0 ) { bi = getBoundaryInformation( ieRange, false ); range.setEnd( bi.container, bi.offset ); } } return range; } /** * 获得ieRange * @param {Selection} sel Selection对象 * @return {ieRange} 得到ieRange */ function _getIERange( sel ) { var ieRange; //ie下有可能报错 try { ieRange = sel.getNative().createRange(); } catch ( e ) { return null; } var el = ieRange.item ? ieRange.item( 0 ) : ieRange.parentElement(); if ( ( el.ownerDocument || el ) === sel.document ) { return ieRange; } return null; } var Selection = dom.Selection = function ( doc ) { var me = this, iframe; me.document = doc; if ( ie ) { iframe = domUtils.getWindow( doc ).frameElement; domUtils.on( iframe, 'beforedeactivate', function () { me._bakIERange = me.getIERange(); } ); domUtils.on( iframe, 'activate', function () { try { if ( !_getIERange( me ) && me._bakIERange ) { me._bakIERange.select(); } } catch ( ex ) { } me._bakIERange = null; } ); } iframe = doc = null; }; Selection.prototype = { /** * 获取原生seleciton对象 * @public * @function * @name baidu.editor.dom.Selection.getNative * @return {Selection} 获得selection对象 */ getNative:function () { var doc = this.document; try { return !doc ? null : ie && browser.ie < 9 ? doc.selection : domUtils.getWindow( doc ).getSelection(); } catch ( e ) { return null; } }, /** * 获得ieRange * @public * @function * @name baidu.editor.dom.Selection.getIERange * @return {ieRange} 返回ie原生的Range */ getIERange:function () { var ieRange = _getIERange( this ); if ( !ieRange ) { if ( this._bakIERange ) { return this._bakIERange; } } return ieRange; }, /** * 缓存当前选区的range和选区的开始节点 * @public * @function * @name baidu.editor.dom.Selection.cache */ cache:function () { this.clear(); this._cachedRange = this.getRange(); this._cachedStartElement = this.getStart(); this._cachedStartElementPath = this.getStartElementPath(); }, getStartElementPath:function () { if ( this._cachedStartElementPath ) { return this._cachedStartElementPath; } var start = this.getStart(); if ( start ) { return domUtils.findParents( start, true, null, true ) } return []; }, /** * 清空缓存 * @public * @function * @name baidu.editor.dom.Selection.clear */ clear:function () { this._cachedStartElementPath = this._cachedRange = this._cachedStartElement = null; }, /** * 编辑器是否得到了选区 */ isFocus:function () { try { return browser.ie && _getIERange( this ) || !browser.ie && this.getNative().rangeCount ? true : false; } catch ( e ) { return false; } }, /** * 获取选区对应的Range * @public * @function * @name baidu.editor.dom.Selection.getRange * @returns {baidu.editor.dom.Range} 得到Range对象 */ getRange:function () { var me = this; function optimze( range ) { var child = me.document.body.firstChild, collapsed = range.collapsed; while ( child && child.firstChild ) { range.setStart( child, 0 ); child = child.firstChild; } if ( !range.startContainer ) { range.setStart( me.document.body, 0 ) } if ( collapsed ) { range.collapse( true ); } } if ( me._cachedRange != null ) { return this._cachedRange; } var range = new baidu.editor.dom.Range( me.document ); if ( ie && browser.ie < 9 ) { var nativeRange = me.getIERange(); if ( nativeRange ) { //备份的_bakIERange可能已经实效了,dom树发生了变化比如从源码模式切回来,所以try一下,实效就放到body开始位置 try{ transformIERangeToRange( nativeRange, range ); }catch(e){ optimze( range ); } } else { optimze( range ); } } else { var sel = me.getNative(); if ( sel && sel.rangeCount ) { var firstRange = sel.getRangeAt( 0 ); var lastRange = sel.getRangeAt( sel.rangeCount - 1 ); range.setStart( firstRange.startContainer, firstRange.startOffset ).setEnd( lastRange.endContainer, lastRange.endOffset ); if ( range.collapsed && domUtils.isBody( range.startContainer ) && !range.startOffset ) { optimze( range ); } } else { //trace:1734 有可能已经不在dom树上了,标识的节点 if ( this._bakRange && domUtils.inDoc( this._bakRange.startContainer, this.document ) ){ return this._bakRange; } optimze( range ); } } return this._bakRange = range; }, /** * 获取开始元素,用于状态反射 * @public * @function * @name baidu.editor.dom.Selection.getStart * @return {Element} 获得开始元素 */ getStart:function () { if ( this._cachedStartElement ) { return this._cachedStartElement; } var range = ie ? this.getIERange() : this.getRange(), tmpRange, start, tmp, parent; if ( ie ) { if ( !range ) { //todo 给第一个值可能会有问题 return this.document.body.firstChild; } //control元素 if ( range.item ){ return range.item( 0 ); } tmpRange = range.duplicate(); //修正ie下<b>x</b>[xx] 闭合后 <b>x|</b>xx tmpRange.text.length > 0 && tmpRange.moveStart( 'character', 1 ); tmpRange.collapse( 1 ); start = tmpRange.parentElement(); parent = tmp = range.parentElement(); while ( tmp = tmp.parentNode ) { if ( tmp == start ) { start = parent; break; } } } else { range.shrinkBoundary(); start = range.startContainer; if ( start.nodeType == 1 && start.hasChildNodes() ){ start = start.childNodes[Math.min( start.childNodes.length - 1, range.startOffset )]; } if ( start.nodeType == 3 ){ return start.parentNode; } } return start; }, /** * 得到选区中的文本 * @public * @function * @name baidu.editor.dom.Selection.getText * @return {String} 选区中包含的文本 */ getText:function () { var nativeSel, nativeRange; if ( this.isFocus() && (nativeSel = this.getNative()) ) { nativeRange = browser.ie ? nativeSel.createRange() : nativeSel.getRangeAt( 0 ); return browser.ie ? nativeRange.text : nativeRange.toString(); } return ''; }, clearRange : function(){ this.getNative()[browser.ie ? 'empty' : 'removeAllRanges'](); } }; })();/** * @file * @name UE.Editor * @short Editor * @import editor.js,core/utils.js,core/EventBase.js,core/browser.js,core/dom/dtd.js,core/dom/domUtils.js,core/dom/Range.js,core/dom/Selection.js,plugins/serialize.js * @desc 编辑器主类,包含编辑器提供的大部分公用接口 */ (function () { var uid = 0, _selectionChangeTimer; /** * @private * @ignore * @param form 编辑器所在的form元素 * @param editor 编辑器实例对象 */ function setValue(form, editor) { var textarea; if (editor.textarea) { if (utils.isString(editor.textarea)) { for (var i = 0, ti, tis = domUtils.getElementsByTagName(form, 'textarea'); ti = tis[i++];) { if (ti.id == 'ueditor_textarea_' + editor.options.textarea) { textarea = ti; break; } } } else { textarea = editor.textarea; } } if (!textarea) { form.appendChild(textarea = domUtils.createElement(document, 'textarea', { 'name': editor.options.textarea, 'id': 'ueditor_textarea_' + editor.options.textarea, 'style': "display:none" })); //不要产生多个textarea editor.textarea = textarea; } textarea.value = editor.hasContents() ? (editor.options.allHtmlEnabled ? editor.getAllHtml() : editor.getContent(null, null, true)) : '' } function loadPlugins(me){ //初始化插件 for (var pi in UE.plugins) { UE.plugins[pi].call(me); } me.langIsReady = true; me.fireEvent("langReady"); } function checkCurLang(I18N){ for(var lang in I18N){ return lang } } /** * UEditor编辑器类 * @name Editor * @desc 创建一个跟编辑器实例 * - ***container*** 编辑器容器对象 * - ***iframe*** 编辑区域所在的iframe对象 * - ***window*** 编辑区域所在的window * - ***document*** 编辑区域所在的document对象 * - ***body*** 编辑区域所在的body对象 * - ***selection*** 编辑区域的选区对象 */ var Editor = UE.Editor = function (options) { var me = this; me.uid = uid++; EventBase.call(me); me.commands = {}; me.options = utils.extend(utils.clone(options || {}), UEDITOR_CONFIG, true); me.shortcutkeys = {}; me.inputRules = []; me.outputRules = []; //设置默认的常用属性 me.setOpt({ isShow: true, initialContent: '', initialStyle:'', autoClearinitialContent: false, iframeCssUrl: me.options.UEDITOR_HOME_URL + 'themes/iframe.css', textarea: 'editorValue', focus: false, focusInEnd: true, autoClearEmptyNode: true, fullscreen: false, readonly: false, zIndex: 999, imagePopup: true, enterTag: 'p', customDomain: false, lang: 'zh-cn', langPath: me.options.UEDITOR_HOME_URL + 'lang/', theme: 'default', themePath: me.options.UEDITOR_HOME_URL + 'themes/', allHtmlEnabled: false, scaleEnabled: false, tableNativeEditInFF: false, autoSyncData : true }); if(!utils.isEmptyObject(UE.I18N)){ //修改默认的语言类型 me.options.lang = checkCurLang(UE.I18N); loadPlugins(me) }else{ utils.loadFile(document, { src: me.options.langPath + me.options.lang + "/" + me.options.lang + ".js", tag: "script", type: "text/javascript", defer: "defer" }, function () { loadPlugins(me) }); } UE.instants['ueditorInstant' + me.uid] = me; }; Editor.prototype = { /** * 当编辑器ready后执行传入的fn,如果编辑器已经完成ready,就马上执行fn,fn的中的this是编辑器实例。 * 大部分的实例接口都需要放在该方法内部执行,否则在IE下可能会报错。 * @name ready * @grammar editor.ready(fn) fn是当编辑器渲染好后执行的function * @example * var editor = new UE.ui.Editor(); * editor.render("myEditor"); * editor.ready(function(){ * editor.setContent("欢迎使用UEditor!"); * }) */ ready: function (fn) { var me = this; if (fn) { me.isReady ? fn.apply(me) : me.addListener('ready', fn); } }, /** * 为编辑器设置默认参数值。若用户配置为空,则以默认配置为准 * @grammar editor.setOpt(key,value); //传入一个键、值对 * @grammar editor.setOpt({ key:value}); //传入一个json对象 */ setOpt: function (key, val) { var obj = {}; if (utils.isString(key)) { obj[key] = val } else { obj = key; } utils.extend(this.options, obj, true); }, /** * 销毁编辑器实例对象 * @name destroy * @grammar editor.destroy(); */ destroy: function () { var me = this; me.fireEvent('destroy'); var container = me.container.parentNode; var textarea = me.textarea; if (!textarea) { textarea = document.createElement('textarea'); container.parentNode.insertBefore(textarea, container); } else { textarea.style.display = '' } textarea.style.width = me.iframe.offsetWidth + 'px'; textarea.style.height = me.iframe.offsetHeight + 'px'; textarea.value = me.getContent(); textarea.id = me.key; container.innerHTML = ''; domUtils.remove(container); var key = me.key; //trace:2004 for (var p in me) { if (me.hasOwnProperty(p)) { delete this[p]; } } UE.delEditor(key); }, /** * 渲染编辑器的DOM到指定容器,必须且只能调用一次 * @name render * @grammar editor.render(containerId); //可以指定一个容器ID * @grammar editor.render(containerDom); //也可以直接指定容器对象 */ render: function (container) { var me = this, options = me.options, getStyleValue=function(attr){ return parseInt(domUtils.getComputedStyle(container,attr)); }; if (utils.isString(container)) { container = document.getElementById(container); } if (container) { if(options.initialFrameWidth){ options.minFrameWidth = options.initialFrameWidth }else{ options.minFrameWidth = options.initialFrameWidth = container.offsetWidth; } if(options.initialFrameHeight){ options.minFrameHeight = options.initialFrameHeight }else{ options.initialFrameHeight = options.minFrameHeight = container.offsetHeight; } container.style.width = /%$/.test(options.initialFrameWidth) ? '100%' : options.initialFrameWidth- getStyleValue("padding-left")- getStyleValue("padding-right") +'px'; container.style.height = /%$/.test(options.initialFrameHeight) ? '100%' : options.initialFrameHeight - getStyleValue("padding-top")- getStyleValue("padding-bottom") +'px'; container.style.zIndex = options.zIndex; var html = ( ie && browser.version < 9 ? '' : '<!DOCTYPE html>') + '<html xmlns=\'http://www.w3.org/1999/xhtml\' class=\'view\' ><head>' + '<style type=\'text/css\'>' + //设置四周的留边 '.view{padding:0;word-wrap:break-word;cursor:text;height:90%;}\n' + //设置默认字体和字号 //font-family不能呢随便改,在safari下fillchar会有解析问题 'body{margin:8px;font-family:sans-serif;font-size:16px;}' + //设置段落间距 'p{margin:5px 0;}</style>' + ( options.iframeCssUrl ? '<link rel=\'stylesheet\' type=\'text/css\' href=\'' + utils.unhtml(options.iframeCssUrl) + '\'/>' : '' ) + (options.initialStyle ? '<style>' + options.initialStyle + '</style>' : '') + '</head><body class=\'view\' ></body>' + '<script type=\'text/javascript\' ' + (ie ? 'defer=\'defer\'' : '' ) +' id=\'_initialScript\'>' + 'setTimeout(function(){window.parent.UE.instants[\'ueditorInstant' + me.uid + '\']._setup(document);},0);' + 'var _tmpScript = document.getElementById(\'_initialScript\');_tmpScript.parentNode.removeChild(_tmpScript);</script></html>'; container.appendChild(domUtils.createElement(document, 'iframe', { id: 'ueditor_' + me.uid, width: "100%", height: "100%", frameborder: "0", src: 'javascript:void(function(){document.open();' + (options.customDomain && document.domain != location.hostname ? 'document.domain="' + document.domain + '";' : '') + 'document.write("' + html + '");document.close();}())' })); container.style.overflow = 'hidden'; //解决如果是给定的百分比,会导致高度算不对的问题 setTimeout(function(){ if( /%$/.test(options.initialFrameWidth)){ options.minFrameWidth = options.initialFrameWidth = container.offsetWidth; container.style.width = options.initialFrameWidth + 'px'; } if(/%$/.test(options.initialFrameHeight)){ options.minFrameHeight = options.initialFrameHeight = container.offsetHeight; container.style.height = options.initialFrameHeight + 'px'; } }) } }, /** * 编辑器初始化 * @private * @ignore * @param {Element} doc 编辑器Iframe中的文档对象 */ _setup: function (doc) { var me = this, options = me.options; if (ie) { doc.body.disabled = true; doc.body.contentEditable = true; doc.body.disabled = false; } else { doc.body.contentEditable = true; } doc.body.spellcheck = false; me.document = doc; me.window = doc.defaultView || doc.parentWindow; me.iframe = me.window.frameElement; me.body = doc.body; me.selection = new dom.Selection(doc); //gecko初始化就能得到range,无法判断isFocus了 var geckoSel; if (browser.gecko && (geckoSel = this.selection.getNative())) { geckoSel.removeAllRanges(); } this._initEvents(); //为form提交提供一个隐藏的textarea for (var form = this.iframe.parentNode; !domUtils.isBody(form); form = form.parentNode) { if (form.tagName == 'FORM') { me.form = form; if(me.options.autoSyncData){ domUtils.on(me.window,'blur',function(){ setValue(form,me); }); }else{ domUtils.on(form, 'submit', function () { setValue(this, me); }); } break; } } if (options.initialContent) { if (options.autoClearinitialContent) { var oldExecCommand = me.execCommand; me.execCommand = function () { me.fireEvent('firstBeforeExecCommand'); return oldExecCommand.apply(me, arguments); }; this._setDefaultContent(options.initialContent); } else this.setContent(options.initialContent, false, true); } //编辑器不能为空内容 if (domUtils.isEmptyNode(me.body)) { me.body.innerHTML = '<p>' + (browser.ie ? '' : '<br/>') + '</p>'; } //如果要求focus, 就把光标定位到内容开始 if (options.focus) { setTimeout(function () { me.focus(me.options.focusInEnd); //如果自动清除开着,就不需要做selectionchange; !me.options.autoClearinitialContent && me._selectionChange(); }, 0); } if (!me.container) { me.container = this.iframe.parentNode; } if (options.fullscreen && me.ui) { me.ui.setFullScreen(true); } try { me.document.execCommand('2D-position', false, false); } catch (e) { } try { me.document.execCommand('enableInlineTableEditing', false, false); } catch (e) { } try { me.document.execCommand('enableObjectResizing', false, false); } catch (e) { // domUtils.on(me.body,browser.ie ? 'resizestart' : 'resize', function( evt ) { // domUtils.preventDefault(evt) // }); } me._bindshortcutKeys(); me.isReady = 1; me.fireEvent('ready'); options.onready && options.onready.call(me); if (!browser.ie) { domUtils.on(me.window, ['blur', 'focus'], function (e) { //chrome下会出现alt+tab切换时,导致选区位置不对 if (e.type == 'blur') { me._bakRange = me.selection.getRange(); try { me._bakNativeRange = me.selection.getNative().getRangeAt(0); me.selection.getNative().removeAllRanges(); } catch (e) { me._bakNativeRange = null; } } else { try { me._bakRange && me._bakRange.select(); } catch (e) { } } }); } //trace:1518 ff3.6body不够寛,会导致点击空白处无法获得焦点 if (browser.gecko && browser.version <= 10902) { //修复ff3.6初始化进来,不能点击获得焦点 me.body.contentEditable = false; setTimeout(function () { me.body.contentEditable = true; }, 100); setInterval(function () { me.body.style.height = me.iframe.offsetHeight - 20 + 'px' }, 100) } !options.isShow && me.setHide(); options.readonly && me.setDisabled(); }, /** * 同步编辑器的数据,为提交数据做准备,主要用于你是手动提交的情况 * @name sync * @grammar editor.sync(); //从编辑器的容器向上查找,如果找到就同步数据 * @grammar editor.sync(formID); //formID制定一个要同步数据的form的id,编辑器的数据会同步到你指定form下 * @desc * 后台取得数据得键值使用你容器上得''name''属性,如果没有就使用参数传入的''textarea'' * @example * editor.sync(); * form.sumbit(); //form变量已经指向了form元素 * */ sync: function (formId) { var me = this, form = formId ? document.getElementById(formId) : domUtils.findParent(me.iframe.parentNode, function (node) { return node.tagName == 'FORM' }, true); form && setValue(form, me); }, /** * 设置编辑器高度 * @name setHeight * @grammar editor.setHeight(number); //纯数值,不带单位 */ setHeight: function (height,notSetHeight) { if (height !== parseInt(this.iframe.parentNode.style.height)) { this.iframe.parentNode.style.height = height + 'px'; } !notSetHeight && (this.options.minFrameHeight = this.options.initialFrameHeight = height); this.body.style.height = height + 'px'; }, addshortcutkey: function (cmd, keys) { var obj = {}; if (keys) { obj[cmd] = keys } else { obj = cmd; } utils.extend(this.shortcutkeys, obj) }, _bindshortcutKeys: function () { var me = this, shortcutkeys = this.shortcutkeys; me.addListener('keydown', function (type, e) { var keyCode = e.keyCode || e.which; for (var i in shortcutkeys) { var tmp = shortcutkeys[i].split(','); for (var t = 0, ti; ti = tmp[t++];) { ti = ti.split(':'); var key = ti[0], param = ti[1]; if (/^(ctrl)(\+shift)?\+(\d+)$/.test(key.toLowerCase()) || /^(\d+)$/.test(key)) { if (( (RegExp.$1 == 'ctrl' ? (e.ctrlKey || e.metaKey) : 0) && (RegExp.$2 != "" ? e[RegExp.$2.slice(1) + "Key"] : 1) && keyCode == RegExp.$3 ) || keyCode == RegExp.$1 ) { if (me.queryCommandState(i,param) != -1) me.execCommand(i, param); domUtils.preventDefault(e); } } } } }); }, /** * 获取编辑器内容 * @name getContent * @grammar editor.getContent() => String //若编辑器中只包含字符"&lt;p&gt;&lt;br /&gt;&lt;/p/&gt;"会返回空。 * @grammar editor.getContent(fn) => String * @example * getContent默认是会现调用hasContents来判断编辑器是否为空,如果是,就直接返回空字符串 * 你也可以传入一个fn来接替hasContents的工作,定制判断的规则 * editor.getContent(function(){ * return false //编辑器没有内容 ,getContent直接返回空 * }) */ getContent: function (cmd, fn,notSetCursor,ignoreBlank,formatter) { var me = this; if (cmd && utils.isFunction(cmd)) { fn = cmd; cmd = ''; } if (fn ? !fn() : !this.hasContents()) { return ''; } me.fireEvent('beforegetcontent'); var root = UE.htmlparser(me.body.innerHTML,ignoreBlank); me.filterOutputRule(root); me.fireEvent('aftergetcontent', cmd); return root.toHtml(formatter); }, /** * 取得完整的html代码,可以直接显示成完整的html文档 * @name getAllHtml * @grammar editor.getAllHtml() => String */ getAllHtml: function () { var me = this, headHtml = [], html = ''; me.fireEvent('getAllHtml', headHtml); if (browser.ie && browser.version > 8) { var headHtmlForIE9 = ''; utils.each(me.document.styleSheets, function (si) { headHtmlForIE9 += ( si.href ? '<link rel="stylesheet" type="text/css" href="' + si.href + '" />' : '<style>' + si.cssText + '</style>'); }); utils.each(me.document.getElementsByTagName('script'), function (si) { headHtmlForIE9 += si.outerHTML; }); } return '<html><head>' + (me.options.charset ? '<meta http-equiv="Content-Type" content="text/html; charset=' + me.options.charset + '"/>' : '') + (headHtmlForIE9 || me.document.getElementsByTagName('head')[0].innerHTML) + headHtml.join('\n') + '</head>' + '<body ' + (ie && browser.version < 9 ? 'class="view"' : '') + '>' + me.getContent(null, null, true) + '</body></html>'; }, /** * 得到编辑器的纯文本内容,但会保留段落格式 * @name getPlainTxt * @grammar editor.getPlainTxt() => String */ getPlainTxt: function () { var reg = new RegExp(domUtils.fillChar, 'g'), html = this.body.innerHTML.replace(/[\n\r]/g, '');//ie要先去了\n在处理 html = html.replace(/<(p|div)[^>]*>(<br\/?>|&nbsp;)<\/\1>/gi, '\n') .replace(/<br\/?>/gi, '\n') .replace(/<[^>/]+>/g, '') .replace(/(\n)?<\/([^>]+)>/g, function (a, b, c) { return dtd.$block[c] ? '\n' : b ? b : ''; }); //取出来的空格会有c2a0会变成乱码,处理这种情况\u00a0 return html.replace(reg, '').replace(/\u00a0/g, ' ').replace(/&nbsp;/g, ' '); }, /** * 获取编辑器中的纯文本内容,没有段落格式 * @name getContentTxt * @grammar editor.getContentTxt() => String */ getContentTxt: function () { var reg = new RegExp(domUtils.fillChar, 'g'); //取出来的空格会有c2a0会变成乱码,处理这种情况\u00a0 return this.body[browser.ie ? 'innerText' : 'textContent'].replace(reg, '').replace(/\u00a0/g, ' '); }, /** * 将html设置到编辑器中, 如果是用于初始化时给编辑器赋初值,则必须放在ready方法内部执行 * @name setContent * @grammar editor.setContent(html) * @example * var editor = new UE.ui.Editor() * editor.ready(function(){ * //需要ready后执行,否则可能报错 * editor.setContent("欢迎使用UEditor!"); * }) */ setContent: function (html, isAppendTo, notFireSelectionchange) { var me = this; me.fireEvent('beforesetcontent', html); var root = UE.htmlparser(html); me.filterInputRule(root); html = root.toHtml(); me.body.innerHTML = (isAppendTo ? me.body.innerHTML : '') + html; function isCdataDiv(node){ return node.tagName == 'DIV' && node.getAttribute('cdata_tag'); } //给文本或者inline节点套p标签 if (me.options.enterTag == 'p') { var child = this.body.firstChild, tmpNode; if (!child || child.nodeType == 1 && (dtd.$cdata[child.tagName] || isCdataDiv(child) || domUtils.isCustomeNode(child) ) && child === this.body.lastChild) { this.body.innerHTML = '<p>' + (browser.ie ? '&nbsp;' : '<br/>') + '</p>' + this.body.innerHTML; } else { var p = me.document.createElement('p'); while (child) { while (child && (child.nodeType == 3 || child.nodeType == 1 && dtd.p[child.tagName] && !dtd.$cdata[child.tagName])) { tmpNode = child.nextSibling; p.appendChild(child); child = tmpNode; } if (p.firstChild) { if (!child) { me.body.appendChild(p); break; } else { child.parentNode.insertBefore(p, child); p = me.document.createElement('p'); } } child = child.nextSibling; } } } me.fireEvent('aftersetcontent'); me.fireEvent('contentchange'); !notFireSelectionchange && me._selectionChange(); //清除保存的选区 me._bakRange = me._bakIERange = me._bakNativeRange = null; //trace:1742 setContent后gecko能得到焦点问题 var geckoSel; if (browser.gecko && (geckoSel = this.selection.getNative())) { geckoSel.removeAllRanges(); } if(me.options.autoSyncData){ me.form && setValue(me.form,me); } }, /** * 让编辑器获得焦点,toEnd确定focus位置 * @name focus * @grammar editor.focus([toEnd]) //默认focus到编辑器头部,toEnd为true时focus到内容尾部 */ focus: function (toEnd) { try { var me = this, rng = me.selection.getRange(); if (toEnd) { rng.setStartAtLast(me.body.lastChild).setCursor(false, true); } else { rng.select(true); } this.fireEvent('focus'); } catch (e) { } }, /** * 初始化UE事件及部分事件代理 * @private * @ignore */ _initEvents: function () { var me = this, doc = me.document, win = me.window; me._proxyDomEvent = utils.bind(me._proxyDomEvent, me); domUtils.on(doc, ['click', 'contextmenu', 'mousedown', 'keydown', 'keyup', 'keypress', 'mouseup', 'mouseover', 'mouseout', 'selectstart'], me._proxyDomEvent); domUtils.on(win, ['focus', 'blur'], me._proxyDomEvent); domUtils.on(doc, ['mouseup', 'keydown'], function (evt) { //特殊键不触发selectionchange if (evt.type == 'keydown' && (evt.ctrlKey || evt.metaKey || evt.shiftKey || evt.altKey)) { return; } if (evt.button == 2)return; me._selectionChange(250, evt); }); // //处理拖拽 // //ie ff不能从外边拖入 // //chrome只针对从外边拖入的内容过滤 // var innerDrag = 0, source = browser.ie ? me.body : me.document, dragoverHandler; // domUtils.on(source, 'dragstart', function () { // innerDrag = 1; // }); // domUtils.on(source, browser.webkit ? 'dragover' : 'drop', function () { // return browser.webkit ? // function () { // clearTimeout(dragoverHandler); // dragoverHandler = setTimeout(function () { // if (!innerDrag) { // var sel = me.selection, // range = sel.getRange(); // if (range) { // var common = range.getCommonAncestor(); // if (common && me.serialize) { // var f = me.serialize, // node = // f.filter( // f.transformInput( // f.parseHTML( // f.word(common.innerHTML) // ) // ) // ); // common.innerHTML = f.toHTML(node); // } // } // } // innerDrag = 0; // }, 200); // } : // function (e) { // if (!innerDrag) { // e.preventDefault ? e.preventDefault() : (e.returnValue = false); // } // innerDrag = 0; // } // }()); }, /** * 触发事件代理 * @private * @ignore */ _proxyDomEvent: function (evt) { return this.fireEvent(evt.type.replace(/^on/, ''), evt); }, /** * 变化选区 * @private * @ignore */ _selectionChange: function (delay, evt) { var me = this; //有光标才做selectionchange 为了解决未focus时点击source不能触发更改工具栏状态的问题(source命令notNeedUndo=1) // if ( !me.selection.isFocus() ){ // return; // } var hackForMouseUp = false; var mouseX, mouseY; if (browser.ie && browser.version < 9 && evt && evt.type == 'mouseup') { var range = this.selection.getRange(); if (!range.collapsed) { hackForMouseUp = true; mouseX = evt.clientX; mouseY = evt.clientY; } } clearTimeout(_selectionChangeTimer); _selectionChangeTimer = setTimeout(function () { if (!me.selection.getNative()) { return; } //修复一个IE下的bug: 鼠标点击一段已选择的文本中间时,可能在mouseup后的一段时间内取到的range是在selection的type为None下的错误值. //IE下如果用户是拖拽一段已选择文本,则不会触发mouseup事件,所以这里的特殊处理不会对其有影响 var ieRange; if (hackForMouseUp && me.selection.getNative().type == 'None') { ieRange = me.document.body.createTextRange(); try { ieRange.moveToPoint(mouseX, mouseY); } catch (ex) { ieRange = null; } } var bakGetIERange; if (ieRange) { bakGetIERange = me.selection.getIERange; me.selection.getIERange = function () { return ieRange; }; } me.selection.cache(); if (bakGetIERange) { me.selection.getIERange = bakGetIERange; } if (me.selection._cachedRange && me.selection._cachedStartElement) { me.fireEvent('beforeselectionchange'); // 第二个参数causeByUi为true代表由用户交互造成的selectionchange. me.fireEvent('selectionchange', !!evt); me.fireEvent('afterselectionchange'); me.selection.clear(); } }, delay || 50); }, _callCmdFn: function (fnName, args) { var cmdName = args[0].toLowerCase(), cmd, cmdFn; cmd = this.commands[cmdName] || UE.commands[cmdName]; cmdFn = cmd && cmd[fnName]; //没有querycommandstate或者没有command的都默认返回0 if ((!cmd || !cmdFn) && fnName == 'queryCommandState') { return 0; } else if (cmdFn) { return cmdFn.apply(this, args); } }, /** * 执行编辑命令cmdName,完成富文本编辑效果 * @name execCommand * @grammar editor.execCommand(cmdName) => {*} */ execCommand: function (cmdName) { cmdName = cmdName.toLowerCase(); var me = this, result, cmd = me.commands[cmdName] || UE.commands[cmdName]; if (!cmd || !cmd.execCommand) { return null; } if (!cmd.notNeedUndo && !me.__hasEnterExecCommand) { me.__hasEnterExecCommand = true; if (me.queryCommandState.apply(me,arguments) != -1) { me.fireEvent('beforeexeccommand', cmdName); result = this._callCmdFn('execCommand', arguments); !me._ignoreContentChange && me.fireEvent('contentchange'); me.fireEvent('afterexeccommand', cmdName); } me.__hasEnterExecCommand = false; } else { result = this._callCmdFn('execCommand', arguments); !me._ignoreContentChange && me.fireEvent('contentchange') } !me._ignoreContentChange && me._selectionChange(); return result; }, /** * 根据传入的command命令,查选编辑器当前的选区,返回命令的状态 * @name queryCommandState * @grammar editor.queryCommandState(cmdName) => (-1|0|1) * @desc * * ''-1'' 当前命令不可用 * * ''0'' 当前命令可用 * * ''1'' 当前命令已经执行过了 */ queryCommandState: function (cmdName) { return this._callCmdFn('queryCommandState', arguments); }, /** * 根据传入的command命令,查选编辑器当前的选区,根据命令返回相关的值 * @name queryCommandValue * @grammar editor.queryCommandValue(cmdName) => {*} */ queryCommandValue: function (cmdName) { return this._callCmdFn('queryCommandValue', arguments); }, /** * 检查编辑区域中是否有内容,若包含tags中的节点类型,直接返回true * @name hasContents * @desc * 默认有文本内容,或者有以下节点都不认为是空 * <code>{table:1,ul:1,ol:1,dl:1,iframe:1,area:1,base:1,col:1,hr:1,img:1,embed:1,input:1,link:1,meta:1,param:1}</code> * @grammar editor.hasContents() => (true|false) * @grammar editor.hasContents(tags) => (true|false) //若文档中包含tags数组里对应的tag,直接返回true * @example * editor.hasContents(['span']) //如果编辑器里有这些,不认为是空 */ hasContents: function (tags) { if (tags) { for (var i = 0, ci; ci = tags[i++];) { if (this.document.getElementsByTagName(ci).length > 0) { return true; } } } if (!domUtils.isEmptyBlock(this.body)) { return true } //随时添加,定义的特殊标签如果存在,不能认为是空 tags = ['div']; for (i = 0; ci = tags[i++];) { var nodes = domUtils.getElementsByTagName(this.document, ci); for (var n = 0, cn; cn = nodes[n++];) { if (domUtils.isCustomeNode(cn)) { return true; } } } return false; }, /** * 重置编辑器,可用来做多个tab使用同一个编辑器实例 * @name reset * @desc * * 清空编辑器内容 * * 清空回退列表 * @grammar editor.reset() */ reset: function () { this.fireEvent('reset'); }, setEnabled: function () { var me = this, range; if (me.body.contentEditable == 'false') { me.body.contentEditable = true; range = me.selection.getRange(); //有可能内容丢失了 try { range.moveToBookmark(me.lastBk); delete me.lastBk } catch (e) { range.setStartAtFirst(me.body).collapse(true) } range.select(true); if (me.bkqueryCommandState) { me.queryCommandState = me.bkqueryCommandState; delete me.bkqueryCommandState; } me.fireEvent('selectionchange'); } }, /** * 设置当前编辑区域可以编辑 * @name enable * @grammar editor.enable() */ enable: function () { return this.setEnabled(); }, setDisabled: function (except) { var me = this; except = except ? utils.isArray(except) ? except : [except] : []; if (me.body.contentEditable == 'true') { if (!me.lastBk) { me.lastBk = me.selection.getRange().createBookmark(true); } me.body.contentEditable = false; me.bkqueryCommandState = me.queryCommandState; me.queryCommandState = function (type) { if (utils.indexOf(except, type) != -1) { return me.bkqueryCommandState.apply(me, arguments); } return -1; }; me.fireEvent('selectionchange'); } }, /** 设置当前编辑区域不可编辑,except中的命令除外 * @name disable * @grammar editor.disable() * @grammar editor.disable(except) //例外的命令,也即即使设置了disable,此处配置的命令仍然可以执行 * @example * //禁用工具栏中除加粗和插入图片之外的所有功能 * editor.disable(['bold','insertimage']);//可以是单一的String,也可以是Array */ disable: function (except) { return this.setDisabled(except); }, /** * 设置默认内容 * @ignore * @private * @param {String} cont 要存入的内容 */ _setDefaultContent: function () { function clear() { var me = this; if (me.document.getElementById('initContent')) { me.body.innerHTML = '<p>' + (ie ? '' : '<br/>') + '</p>'; me.removeListener('firstBeforeExecCommand focus', clear); setTimeout(function () { me.focus(); me._selectionChange(); }, 0) } } return function (cont) { var me = this; me.body.innerHTML = '<p id="initContent">' + cont + '</p>'; me.addListener('firstBeforeExecCommand focus', clear); } }(), /** * show方法的兼容版本 * @private * @ignore */ setShow: function () { var me = this, range = me.selection.getRange(); if (me.container.style.display == 'none') { //有可能内容丢失了 try { range.moveToBookmark(me.lastBk); delete me.lastBk } catch (e) { range.setStartAtFirst(me.body).collapse(true) } //ie下focus实效,所以做了个延迟 setTimeout(function () { range.select(true); }, 100); me.container.style.display = ''; } }, /** * 显示编辑器 * @name show * @grammar editor.show() */ show: function () { return this.setShow(); }, /** * hide方法的兼容版本 * @private * @ignore */ setHide: function () { var me = this; if (!me.lastBk) { me.lastBk = me.selection.getRange().createBookmark(true); } me.container.style.display = 'none' }, /** * 隐藏编辑器 * @name hide * @grammar editor.hide() */ hide: function () { return this.setHide(); }, /** * 根据制定的路径,获取对应的语言资源 * @name getLang * @grammar editor.getLang(path) => (JSON|String) 路径根据的是lang目录下的语言文件的路径结构 * @example * editor.getLang('contextMenu.delete') //如果当前是中文,那返回是的是删除 */ getLang: function (path) { var lang = UE.I18N[this.options.lang]; if (!lang) { throw Error("not import language file"); } path = (path || "").split("."); for (var i = 0, ci; ci = path[i++];) { lang = lang[ci]; if (!lang)break; } return lang; }, /** * 计算编辑器当前内容的长度 * @name getContentLength * @grammar editor.getContentLength(ingoneHtml,tagNames) => * @example * editor.getLang(true) */ getContentLength: function (ingoneHtml, tagNames) { var count = this.getContent(false,false,true).length; if (ingoneHtml) { tagNames = (tagNames || []).concat([ 'hr', 'img', 'iframe']); count = this.getContentTxt().replace(/[\t\r\n]+/g, '').length; for (var i = 0, ci; ci = tagNames[i++];) { count += this.document.getElementsByTagName(ci).length; } } return count; }, addInputRule: function (rule) { this.inputRules.push(rule); }, filterInputRule: function (root) { for (var i = 0, ci; ci = this.inputRules[i++];) { ci.call(this, root) } }, addOutputRule: function (rule) { this.outputRules.push(rule) }, filterOutputRule: function (root) { for (var i = 0, ci; ci = this.outputRules[i++];) { ci.call(this, root) } } /** * 得到dialog实例对象 * @name getDialog * @grammar editor.getDialog(dialogName) => Object * @example * var dialog = editor.getDialog("insertimage"); * dialog.open(); //打开dialog * dialog.close(); //关闭dialog */ }; utils.inherits(Editor, EventBase); })(); /** * @file * @name UE.ajax * @short Ajax * @desc UEditor内置的ajax请求模块 * @import core/utils.js * @user: taoqili * @date: 11-8-18 * @time: 下午3:18 */ UE.ajax = function() { /** * 创建一个ajaxRequest对象 */ var fnStr = 'XMLHttpRequest()'; try { new ActiveXObject("Msxml2.XMLHTTP"); fnStr = 'ActiveXObject(\'Msxml2.XMLHTTP\')'; } catch (e) { try { new ActiveXObject("Microsoft.XMLHTTP"); fnStr = 'ActiveXObject(\'Microsoft.XMLHTTP\')' } catch (e) { } } var creatAjaxRequest = new Function('return new ' + fnStr); /** * 将json参数转化成适合ajax提交的参数列表 * @param json */ function json2str(json) { var strArr = []; for (var i in json) { //忽略默认的几个参数 if(i=="method" || i=="timeout" || i=="async") continue; //传递过来的对象和函数不在提交之列 if (!((typeof json[i]).toLowerCase() == "function" || (typeof json[i]).toLowerCase() == "object")) { strArr.push( encodeURIComponent(i) + "="+encodeURIComponent(json[i]) ); } } return strArr.join("&"); } return { /** * @name request * @desc 发出ajax请求,ajaxOpt中默认包含method,timeout,async,data,onsuccess以及onerror等六个,支持自定义添加参数 * @grammar UE.ajax.request(url,ajaxOpt); * @example * UE.ajax.request('http://www.xxxx.com/test.php',{ * //可省略,默认POST * method:'POST', * //可以自定义参数 * content:'这里是提交的内容', * //也可以直接传json,但是只能命名为data,否则当做一般字符串处理 * data:{ * name:'UEditor', * age:'1' * } * onsuccess:function(xhr){ * console.log(xhr.responseText); * }, * onerror:function(xhr){ * console.log(xhr.responseText); * } * }) * @param ajaxOptions */ request:function(url, ajaxOptions) { var ajaxRequest = creatAjaxRequest(), //是否超时 timeIsOut = false, //默认参数 defaultAjaxOptions = { method:"POST", timeout:5000, async:true, data:{},//需要传递对象的话只能覆盖 onsuccess:function() { }, onerror:function() { } }; if (typeof url === "object") { ajaxOptions = url; url = ajaxOptions.url; } if (!ajaxRequest || !url) return; var ajaxOpts = ajaxOptions ? utils.extend(defaultAjaxOptions,ajaxOptions) : defaultAjaxOptions; var submitStr = json2str(ajaxOpts); // { name:"Jim",city:"Beijing" } --> "name=Jim&city=Beijing" //如果用户直接通过data参数传递json对象过来,则也要将此json对象转化为字符串 if (!utils.isEmptyObject(ajaxOpts.data)){ submitStr += (submitStr? "&":"") + json2str(ajaxOpts.data); } //超时检测 var timerID = setTimeout(function() { if (ajaxRequest.readyState != 4) { timeIsOut = true; ajaxRequest.abort(); clearTimeout(timerID); } }, ajaxOpts.timeout); var method = ajaxOpts.method.toUpperCase(); var str = url + (url.indexOf("?")==-1?"?":"&") + (method=="POST"?"":submitStr+ "&noCache=" + +new Date); ajaxRequest.open(method, str, ajaxOpts.async); ajaxRequest.onreadystatechange = function() { if (ajaxRequest.readyState == 4) { if (!timeIsOut && ajaxRequest.status == 200) { ajaxOpts.onsuccess(ajaxRequest); } else { ajaxOpts.onerror(ajaxRequest); } } }; if (method == "POST") { ajaxRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); ajaxRequest.send(submitStr); } else { ajaxRequest.send(null); } } }; }(); /** * @file * @name UE.filterWord * @short filterWord * @desc 用来过滤word粘贴过来的字符串 * @import editor.js,core/utils.js * @anthor zhanyi */ var filterWord = UE.filterWord = function () { //是否是word过来的内容 function isWordDocument( str ) { return /(class="?Mso|style="[^"]*\bmso\-|w:WordDocument|<v:)/ig.test( str ); } //去掉小数 function transUnit( v ) { v = v.replace( /[\d.]+\w+/g, function ( m ) { return utils.transUnitToPx(m); } ); return v; } function filterPasteWord( str ) { return str.replace( /[\t\r\n]+/g, "" ) .replace( /<!--[\s\S]*?-->/ig, "" ) //转换图片 .replace(/<v:shape [^>]*>[\s\S]*?.<\/v:shape>/gi,function(str){ //opera能自己解析出image所这里直接返回空 if(browser.opera){ return ''; } try{ var width = str.match(/width:([ \d.]*p[tx])/i)[1], height = str.match(/height:([ \d.]*p[tx])/i)[1], src = str.match(/src=\s*"([^"]*)"/i)[1]; return '<img width="'+ transUnit(width) +'" height="'+transUnit(height) +'" src="' + src + '" />'; } catch(e){ return ''; } }) //针对wps添加的多余标签处理 .replace(/<\/?div[^>]*>/g,'') //去掉多余的属性 .replace( /v:\w+=(["']?)[^'"]+\1/g, '' ) .replace( /<(!|script[^>]*>.*?<\/script(?=[>\s])|\/?(\?xml(:\w+)?|xml|meta|link|style|\w+:\w+)(?=[\s\/>]))[^>]*>/gi, "" ) .replace( /<p [^>]*class="?MsoHeading"?[^>]*>(.*?)<\/p>/gi, "<p><strong>$1</strong></p>" ) //去掉多余的属性 .replace( /\s+(class|lang|align)\s*=\s*(['"]?)([\w-]+)\2/ig, function(str,name,marks,val){ //保留list的标示 return name == 'class' && val == 'MsoListParagraph' ? str : '' }) //清除多余的font/span不能匹配&nbsp;有可能是空格 .replace( /<(font|span)[^>]*>\s*<\/\1>/gi, '' ) //处理style的问题 .replace( /(<[a-z][^>]*)\sstyle=(["'])([^\2]*?)\2/gi, function( str, tag, tmp, style ) { var n = [], s = style.replace( /^\s+|\s+$/, '' ) .replace(/&#39;/g,'\'') .replace( /&quot;/gi, "'" ) .split( /;\s*/g ); for ( var i = 0,v; v = s[i];i++ ) { var name, value, parts = v.split( ":" ); if ( parts.length == 2 ) { name = parts[0].toLowerCase(); value = parts[1].toLowerCase(); if(/^(background)\w*/.test(name) && value.replace(/(initial|\s)/g,'').length == 0 || /^(margin)\w*/.test(name) && /^0\w+$/.test(value) ){ continue; } switch ( name ) { case "mso-padding-alt": case "mso-padding-top-alt": case "mso-padding-right-alt": case "mso-padding-bottom-alt": case "mso-padding-left-alt": case "mso-margin-alt": case "mso-margin-top-alt": case "mso-margin-right-alt": case "mso-margin-bottom-alt": case "mso-margin-left-alt": //ie下会出现挤到一起的情况 //case "mso-table-layout-alt": case "mso-height": case "mso-width": case "mso-vertical-align-alt": //trace:1819 ff下会解析出padding在table上 if(!/<table/.test(tag)) n[i] = name.replace( /^mso-|-alt$/g, "" ) + ":" + transUnit( value ); continue; case "horiz-align": n[i] = "text-align:" + value; continue; case "vert-align": n[i] = "vertical-align:" + value; continue; case "font-color": case "mso-foreground": n[i] = "color:" + value; continue; case "mso-background": case "mso-highlight": n[i] = "background:" + value; continue; case "mso-default-height": n[i] = "min-height:" + transUnit( value ); continue; case "mso-default-width": n[i] = "min-width:" + transUnit( value ); continue; case "mso-padding-between-alt": n[i] = "border-collapse:separate;border-spacing:" + transUnit( value ); continue; case "text-line-through": if ( (value == "single") || (value == "double") ) { n[i] = "text-decoration:line-through"; } continue; case "mso-zero-height": if ( value == "yes" ) { n[i] = "display:none"; } continue; case 'background': break; case 'margin': if ( !/[1-9]/.test( value ) ) { continue; } } if ( /^(mso|column|font-emph|lang|layout|line-break|list-image|nav|panose|punct|row|ruby|sep|size|src|tab-|table-border|text-(?:decor|trans)|top-bar|version|vnd|word-break)/.test( name ) || /text\-indent|padding|margin/.test(name) && /\-[\d.]+/.test(value) ) { continue; } n[i] = name + ":" + parts[1]; } } return tag + (n.length ? ' style="' + n.join( ';').replace(/;{2,}/g,';') + '"' : ''); }) .replace(/[\d.]+(cm|pt)/g,function(str){ return utils.transUnitToPx(str) }) } return function ( html ) { return (isWordDocument( html ) ? filterPasteWord( html ) : html); }; }();///import editor.js ///import core/utils.js ///import core/dom/dom.js ///import core/dom/dtd.js ///import core/htmlparser.js //模拟的节点类 //by zhanyi (function () { var uNode = UE.uNode = function (obj) { this.type = obj.type; this.data = obj.data; this.tagName = obj.tagName; this.parentNode = obj.parentNode; this.attrs = obj.attrs || {}; this.children = obj.children; }; var indentChar = ' ', breakChar = '\n'; function insertLine(arr, current, begin) { arr.push(breakChar); return current + (begin ? 1 : -1); } function insertIndent(arr, current) { //插入缩进 for (var i = 0; i < current; i++) { arr.push(indentChar); } } //创建uNode的静态方法 //支持标签和html uNode.createElement = function (html) { if (/[<>]/.test(html)) { return UE.htmlparser(html).children[0] } else { return new uNode({ type:'element', children:[], tagName:html }) } }; uNode.createText = function (data) { return new UE.uNode({ type:'text', 'data':utils.unhtml(data || '') }) }; function nodeToHtml(node, arr, formatter, current) { switch (node.type) { case 'root': for (var i = 0, ci; ci = node.children[i++];) { //插入新行 if (formatter && ci.type == 'element' && !dtd.$inlineWithA[ci.tagName] && i > 1) { insertLine(arr, current, true); insertIndent(arr, current) } nodeToHtml(ci, arr, formatter, current) } break; case 'text': isText(node, arr); break; case 'element': isElement(node, arr, formatter, current); break; case 'comment': isComment(node, arr, formatter); } return arr; } function isText(node, arr) { arr.push(node.parentNode.tagName == 'pre' ? node.data : node.data.replace(/[ ]{2}/g,' &nbsp;')) } function isElement(node, arr, formatter, current) { var attrhtml = ''; if (node.attrs) { attrhtml = []; var attrs = node.attrs; for (var a in attrs) { attrhtml.push(a + (attrs[a] !== undefined ? '="' + utils.unhtml(attrs[a]) + '"' : '')) } attrhtml = attrhtml.join(' '); } arr.push('<' + node.tagName + (attrhtml ? ' ' + attrhtml : '') + (dtd.$empty[node.tagName] ? '\/' : '' ) + '>' ); //插入新行 if (formatter && !dtd.$inlineWithA[node.tagName] && node.tagName != 'pre') { if(node.children && node.children.length){ current = insertLine(arr, current, true); insertIndent(arr, current) } } if (node.children && node.children.length) { for (var i = 0, ci; ci = node.children[i++];) { if (formatter && ci.type == 'element' && !dtd.$inlineWithA[ci.tagName] && i > 1) { insertLine(arr, current); insertIndent(arr, current) } nodeToHtml(ci, arr, formatter, current) } } if (!dtd.$empty[node.tagName]) { if (formatter && !dtd.$inlineWithA[node.tagName] && node.tagName != 'pre') { if(node.children && node.children.length){ current = insertLine(arr, current); insertIndent(arr, current) } } arr.push('<\/' + node.tagName + '>'); } } function isComment(node, arr) { arr.push('<!--' + node.data + '-->'); } function getNodeById(root, id) { var node; if (root.type == 'element' && root.getAttr('id') == id) { return root; } if (root.children && root.children.length) { for (var i = 0, ci; ci = root.children[i++];) { if (node = getNodeById(ci, id)) { return node; } } } } function getNodesByTagName(node, tagName, arr) { if (node.type == 'element' && node.tagName == tagName) { arr.push(node); } if (node.children && node.children.length) { for (var i = 0, ci; ci = node.children[i++];) { getNodesByTagName(ci, tagName, arr) } } } function nodeTraversal(root,fn){ if(root.children && root.children.length){ for(var i= 0,ci;ci=root.children[i];){ nodeTraversal(ci,fn); //ci被替换的情况,这里就不再走 fn了 if(ci.parentNode ){ if(ci.children && ci.children.length){ fn(ci) } if(ci.parentNode) i++ } } }else{ fn(root) } } uNode.prototype = { toHtml:function (formatter) { var arr = []; nodeToHtml(this, arr, formatter, 0); return arr.join('') }, innerHTML:function (htmlstr) { if (this.type != 'element' || dtd.$empty[this.tagName]) { return this; } if (utils.isString(htmlstr)) { if(this.children){ for (var i = 0, ci; ci = this.children[i++];) { ci.parentNode = null; } } this.children = []; var tmpRoot = UE.htmlparser(htmlstr); for (var i = 0, ci; ci = tmpRoot.children[i++];) { this.children.push(ci); ci.parentNode = this; } return this; } else { var tmpRoot = new UE.uNode({ type:'root', children:this.children }); return tmpRoot.toHtml(); } }, innerText:function (textStr) { if (this.type != 'element' || dtd.$empty[this.tagName]) { return this; } if (textStr) { if(this.children){ for (var i = 0, ci; ci = this.children[i++];) { ci.parentNode = null; } } this.children = []; this.appendChild(uNode.createText(textStr)); return this; } else { return this.toHtml().replace(/<[^>]+>/g, ''); } }, getData:function () { if (this.type == 'element') return ''; return this.data }, firstChild:function () { // if (this.type != 'element' || dtd.$empty[this.tagName]) { // return this; // } return this.children ? this.children[0] : null; }, lastChild:function () { // if (this.type != 'element' || dtd.$empty[this.tagName] ) { // return this; // } return this.children ? this.children[this.children.length - 1] : null; }, previousSibling : function(){ var parent = this.parentNode; for (var i = 0, ci; ci = parent.children[i]; i++) { if (ci === this) { return i == 0 ? null : parent.children[i-1]; } } }, nextSibling : function(){ var parent = this.parentNode; for (var i = 0, ci; ci = parent.children[i++];) { if (ci === this) { return parent.children[i]; } } }, replaceChild:function (target, source) { if (this.children) { if(target.parentNode){ target.parentNode.removeChild(target); } for (var i = 0, ci; ci = this.children[i]; i++) { if (ci === source) { this.children.splice(i, 1, target); source.parentNode = null; target.parentNode = this; return target; } } } }, appendChild:function (node) { if (this.type == 'root' || (this.type == 'element' && !dtd.$empty[this.tagName])) { if (!this.children) { this.children = [] } if(node.parentNode){ node.parentNode.removeChild(node); } for (var i = 0, ci; ci = this.children[i]; i++) { if (ci === node) { this.children.splice(i, 1); break; } } this.children.push(node); node.parentNode = this; return node; } }, insertBefore:function (target, source) { if (this.children) { if(target.parentNode){ target.parentNode.removeChild(target); } for (var i = 0, ci; ci = this.children[i]; i++) { if (ci === source) { this.children.splice(i, 0, target); target.parentNode = this; return target; } } } }, insertAfter:function (target, source) { if (this.children) { if(target.parentNode){ target.parentNode.removeChild(target); } for (var i = 0, ci; ci = this.children[i]; i++) { if (ci === source) { this.children.splice(i + 1, 0, target); target.parentNode = this; return target; } } } }, removeChild:function (node,keepChildren) { if (this.children) { for (var i = 0, ci; ci = this.children[i]; i++) { if (ci === node) { this.children.splice(i, 1); ci.parentNode = null; if(keepChildren && ci.children && ci.children.length){ for(var j= 0,cj;cj=ci.children[j];j++){ this.children.splice(i+j,0,cj); cj.parentNode = this; } } return ci; } } } }, getAttr:function (attrName) { return this.attrs && this.attrs[attrName.toLowerCase()] }, setAttr:function (attrName, attrVal) { if (!attrName) { delete this.attrs; return; } if(!this.attrs){ this.attrs = {}; } if (utils.isObject(attrName)) { for (var a in attrName) { if (!attrName[a]) { delete this.attrs[a] } else { this.attrs[a.toLowerCase()] = attrName[a]; } } } else { if (!attrVal) { delete this.attrs[attrName] } else { this.attrs[attrName.toLowerCase()] = attrVal; } } }, getIndex:function(){ var parent = this.parentNode; for(var i= 0,ci;ci=parent.children[i];i++){ if(ci === this){ return i; } } return -1; }, getNodeById:function (id) { var node; if (this.children && this.children.length) { for (var i = 0, ci; ci = this.children[i++];) { if (node = getNodeById(ci, id)) { return node; } } } }, getNodesByTagName:function (tagNames) { tagNames = utils.trim(tagNames).replace(/[ ]{2,}/g, ' ').split(' '); var arr = [], me = this; utils.each(tagNames, function (tagName) { if (me.children && me.children.length) { for (var i = 0, ci; ci = me.children[i++];) { getNodesByTagName(ci, tagName, arr) } } }); return arr; }, getStyle:function (name) { var cssStyle = this.getAttr('style'); if (!cssStyle) { return '' } var reg = new RegExp(name + ':([^;]+)','i'); var match = cssStyle.match(reg); if (match && match[0]) { return match[1] } return ''; }, setStyle:function (name, val) { function exec(name, val) { var reg = new RegExp(name + ':([^;]+;?)', 'gi'); cssStyle = cssStyle.replace(reg, ''); if (val) { cssStyle = name + ':' + utils.unhtml(val) + ';' + cssStyle } } var cssStyle = this.getAttr('style'); if (!cssStyle) { cssStyle = ''; } if (utils.isObject(name)) { for (var a in name) { exec(a, name[a]) } } else { exec(name, val) } this.setAttr('style', utils.trim(cssStyle)) }, traversal:function(fn){ if(this.children && this.children.length){ nodeTraversal(this,fn); } return this; } } })(); //html字符串转换成uNode节点 //by zhanyi var htmlparser = UE.htmlparser = function (htmlstr,ignoreBlank) { var re_tag = /<(?:(?:\/([^>]+)>)|(?:!--([\S|\s]*?)-->)|(?:([^\s\/>]+)\s*((?:(?:"[^"]*")|(?:'[^']*')|[^"'<>])*)\/?>))/g, re_attr = /([\w\-:.]+)(?:(?:\s*=\s*(?:(?:"([^"]*)")|(?:'([^']*)')|([^\s>]+)))|(?=\s|$))/g; //ie下取得的html可能会有\n存在,要去掉,在处理replace(/[\t\r\n]*/g,'');代码高量的\n不能去除 var allowEmptyTags = { b:1,code:1,i:1,u:1,strike:1,s:1,tt:1,strong:1,q:1,samp:1,em:1,span:1, sub:1,img:1,sup:1,font:1,big:1,small:1,iframe:1,a:1,br:1,pre:1 }; htmlstr = htmlstr.replace(new RegExp(domUtils.fillChar, 'g'), ''); if(!ignoreBlank){ htmlstr = htmlstr.replace(new RegExp('[\\r\\t\\n'+(ignoreBlank?'':' ')+']*<\/?(\\w+)\\s*(?:[^>]*)>[\\r\\t\\n'+(ignoreBlank?'':' ')+']*','g'), function(a,b){ //br暂时单独处理 if(b && allowEmptyTags[b.toLowerCase()]){ return a.replace(/(^[\n\r]+)|([\n\r]+$)/g,''); } return a.replace(new RegExp('^[\\r\\n'+(ignoreBlank?'':' ')+']+'),'').replace(new RegExp('[\\r\\n'+(ignoreBlank?'':' ')+']+$'),''); }); } var uNode = UE.uNode, needParentNode = { 'td':'tr', 'tr':['tbody','thead','tfoot'], 'tbody':'table', 'th':'tr', 'thead':'table', 'tfoot':'table', 'caption':'table', 'li':['ul', 'ol'], 'dt':'dl', 'dd':'dl', 'option':'select' }, needChild = { 'ol':'li', 'ul':'li' }; function text(parent, data) { if(needChild[parent.tagName]){ var tmpNode = uNode.createElement(needChild[parent.tagName]); parent.appendChild(tmpNode); tmpNode.appendChild(uNode.createText(data)); parent = tmpNode; }else{ parent.appendChild(uNode.createText(data)); } } function element(parent, tagName, htmlattr) { var needParentTag; if (needParentTag = needParentNode[tagName]) { var tmpParent = parent,hasParent; while(tmpParent.type != 'root'){ if(utils.isArray(needParentTag) ? utils.indexOf(needParentTag, tmpParent.tagName) != -1 : needParentTag == tmpParent.tagName){ parent = tmpParent; hasParent = true; break; } tmpParent = tmpParent.parentNode; } if(!hasParent){ parent = element(parent, utils.isArray(needParentTag) ? needParentTag[0] : needParentTag) } } //按dtd处理嵌套 // if(parent.type != 'root' && !dtd[parent.tagName][tagName]) // parent = parent.parentNode; var elm = new uNode({ parentNode:parent, type:'element', tagName:tagName.toLowerCase(), //是自闭合的处理一下 children:dtd.$empty[tagName] ? null : [] }); //如果属性存在,处理属性 if (htmlattr) { var attrs = {}, match; while (match = re_attr.exec(htmlattr)) { attrs[match[1].toLowerCase()] = utils.unhtml(match[2] || match[3] || match[4]) } elm.attrs = attrs; } parent.children.push(elm); //如果是自闭合节点返回父亲节点 return dtd.$empty[tagName] ? parent : elm } function comment(parent, data) { parent.children.push(new uNode({ type:'comment', data:data, parentNode:parent })); } var match, currentIndex = 0, nextIndex = 0; //设置根节点 var root = new uNode({ type:'root', children:[] }); var currentParent = root; while (match = re_tag.exec(htmlstr)) { currentIndex = match.index; try{ if (currentIndex > nextIndex) { //text node text(currentParent, htmlstr.slice(nextIndex, currentIndex)); } if (match[3]) { //start tag currentParent = element(currentParent, match[3].toLowerCase(), match[4]); } else if (match[1]) { if(currentParent.type != 'root'){ var tmpParent = currentParent; while(currentParent.type == 'element' && currentParent.tagName != match[1].toLowerCase()){ currentParent = currentParent.parentNode; if(currentParent.type == 'root'){ currentParent = tmpParent; throw 'break' } } //end tag currentParent = currentParent.parentNode; } } else if (match[2]) { //comment comment(currentParent, match[2]) } }catch(e){} nextIndex = re_tag.lastIndex; } //如果结束是文本,就有可能丢掉,所以这里手动判断一下 //例如 <li>sdfsdfsdf<li>sdfsdfsdfsdf if (nextIndex < htmlstr.length) { text(currentParent, htmlstr.slice(nextIndex)); } return root; };/** * @file * @name UE.filterNode * @short filterNode * @desc 根据给定的规则过滤节点 * @import editor.js,core/utils.js * @anthor zhanyi */ var filterNode = UE.filterNode = function () { function filterNode(node,rules){ switch (node.type) { case 'text': break; case 'element': var val; if(val = rules[node.tagName]){ if(val === '-'){ node.parentNode.removeChild(node) }else if(utils.isFunction(val)){ var parentNode = node.parentNode, index = node.getIndex(); val(node); if(node.parentNode){ if(node.children){ for(var i = 0,ci;ci=node.children[i];){ filterNode(ci,rules); if(ci.parentNode){ i++; } } } }else{ for(var i = index,ci;ci=parentNode.children[i];){ filterNode(ci,rules); if(ci.parentNode){ i++; } } } }else{ var attrs = val['$']; if(attrs && node.attrs){ var tmpAttrs = {},tmpVal; for(var a in attrs){ tmpVal = node.getAttr(a); //todo 只先对style单独处理 if(a == 'style' && utils.isArray(attrs[a])){ var tmpCssStyle = []; utils.each(attrs[a],function(v){ var tmp; if(tmp = node.getStyle(v)){ tmpCssStyle.push(v + ':' + tmp); } }); tmpVal = tmpCssStyle.join(';') } if(tmpVal){ tmpAttrs[a] = tmpVal; } } node.attrs = tmpAttrs; } if(node.children){ for(var i = 0,ci;ci=node.children[i];){ filterNode(ci,rules); if(ci.parentNode){ i++; } } } } }else{ //如果不在名单里扣出子节点并删除该节点,cdata除外 if(dtd.$cdata[node.tagName]){ node.parentNode.removeChild(node) }else{ var parentNode = node.parentNode, index = node.getIndex(); node.parentNode.removeChild(node,true); for(var i = index,ci;ci=parentNode.children[i];){ filterNode(ci,rules); if(ci.parentNode){ i++; } } } } break; case 'comment': node.parentNode.removeChild(node) } } return function(root,rules){ if(utils.isEmptyObject(rules)){ return root; } var val; if(val = rules['-']){ utils.each(val.split(' '),function(k){ rules[k] = '-' }) } for(var i= 0,ci;ci=root.children[i];){ filterNode(ci,rules); if(ci.parentNode){ i++; } } return root; } }();///import core ///plugin 编辑器默认的过滤转换机制 UE.plugins['defaultfilter'] = function () { var me = this; me.setOpt('allowDivTransToP',true); //默认的过滤处理 //进入编辑器的内容处理 me.addInputRule(function (root) { var allowDivTransToP = this.options.allowDivTransToP; var val; //进行默认的处理 root.traversal(function (node) { if (node.type == 'element') { if (!dtd.$cdata[node.tagName] && me.options.autoClearEmptyNode && dtd.$inline[node.tagName] && !dtd.$empty[node.tagName] && (!node.attrs || utils.isEmptyObject(node.attrs))) { if (!node.firstChild()) node.parentNode.removeChild(node); else if (node.tagName == 'span' && (!node.attrs || utils.isEmptyObject(node.attrs))) { node.parentNode.removeChild(node, true) } return; } switch (node.tagName) { case 'style': case 'script': node.setAttr({ cdata_tag: node.tagName, cdata_data: encodeURIComponent(node.innerText() || '') }); node.tagName = 'div'; node.removeChild(node.firstChild()); break; case 'a': if (val = node.getAttr('href')) { node.setAttr('_href', val) } break; case 'img': //todo base64暂时去掉,后边做远程图片上传后,干掉这个 if (val = node.getAttr('src')) { if (/^data:/.test(val)) { node.parentNode.removeChild(node); break; } } node.setAttr('_src', node.getAttr('src')); break; case 'span': if (browser.webkit && (val = node.getStyle('white-space'))) { if (/nowrap|normal/.test(val)) { node.setStyle('white-space', ''); if (me.options.autoClearEmptyNode && utils.isEmptyObject(node.attrs)) { node.parentNode.removeChild(node, true) } } } break; case 'p': if (val = node.getAttr('align')) { node.setAttr('align'); node.setStyle('text-align', val) } //trace:3431 // var cssStyle = node.getAttr('style'); // if (cssStyle) { // cssStyle = cssStyle.replace(/(margin|padding)[^;]+/g, ''); // node.setAttr('style', cssStyle) // // } if (!node.firstChild()) { node.innerHTML(browser.ie ? '&nbsp;' : '<br/>') } break; case 'div': if(node.getAttr('cdata_tag')){ break; } //针对代码这里不处理插入代码的div val = node.getAttr('class'); if(val && /^line number\d+/.test(val)){ break; } if(!allowDivTransToP){ break; } var tmpNode, p = UE.uNode.createElement('p'); while (tmpNode = node.firstChild()) { if (tmpNode.type == 'text' || !UE.dom.dtd.$block[tmpNode.tagName]) { p.appendChild(tmpNode); } else { if (p.firstChild()) { node.parentNode.insertBefore(p, node); p = UE.uNode.createElement('p'); } else { node.parentNode.insertBefore(tmpNode, node); } } } if (p.firstChild()) { node.parentNode.insertBefore(p, node); } node.parentNode.removeChild(node); break; case 'dl': node.tagName = 'ul'; break; case 'dt': case 'dd': node.tagName = 'li'; break; case 'li': var className = node.getAttr('class'); if (!className || !/list\-/.test(className)) { node.setAttr() } var tmpNodes = node.getNodesByTagName('ol ul'); UE.utils.each(tmpNodes, function (n) { node.parentNode.insertAfter(n, node); }); break; case 'td': case 'th': case 'caption': if(!node.children || !node.children.length){ node.appendChild(browser.ie ? UE.uNode.createText(' ') : UE.uNode.createElement('br')) } } } if(node.type == 'comment'){ node.parentNode.removeChild(node); } }) }); //从编辑器出去的内容处理 me.addOutputRule(function (root) { var val; root.traversal(function (node) { if (node.type == 'element') { if (me.options.autoClearEmptyNode && dtd.$inline[node.tagName] && !dtd.$empty[node.tagName] && (!node.attrs || utils.isEmptyObject(node.attrs))) { if (!node.firstChild()) node.parentNode.removeChild(node); else if (node.tagName == 'span' && (!node.attrs || utils.isEmptyObject(node.attrs))) { node.parentNode.removeChild(node, true) } return; } switch (node.tagName) { case 'div': if (val = node.getAttr('cdata_tag')) { node.tagName = val; node.appendChild(UE.uNode.createText(node.getAttr('cdata_data'))); node.setAttr({cdata_tag: '', cdata_data: ''}); } break; case 'a': if (val = node.getAttr('_href')) { node.setAttr({ 'href': val, '_href': '' }) } break; case 'img': if (val = node.getAttr('_src')) { node.setAttr({ 'src': node.getAttr('_src'), '_src': '' }) } } } }) }); }; ///import core /** * @description 插入内容 * @name baidu.editor.execCommand * @param {String} cmdName inserthtml插入内容的命令 * @param {String} html 要插入的内容 * @author zhanyi */ UE.commands['inserthtml'] = { execCommand: function (command,html,notNeedFilter){ var me = this, range, div; if(!html){ return; } if(me.fireEvent('beforeinserthtml',html) === true){ return; } range = me.selection.getRange(); div = range.document.createElement( 'div' ); div.style.display = 'inline'; if (!notNeedFilter) { var root = UE.htmlparser(html); //如果给了过滤规则就先进行过滤 if(me.options.filterRules){ UE.filterNode(root,me.options.filterRules); } //执行默认的处理 me.filterInputRule(root); html = root.toHtml() } div.innerHTML = utils.trim( html ); if ( !range.collapsed ) { var tmpNode = range.startContainer; if(domUtils.isFillChar(tmpNode)){ range.setStartBefore(tmpNode) } tmpNode = range.endContainer; if(domUtils.isFillChar(tmpNode)){ range.setEndAfter(tmpNode) } range.txtToElmBoundary(); //结束边界可能放到了br的前边,要把br包含进来 // x[xxx]<br/> if(range.endContainer && range.endContainer.nodeType == 1){ tmpNode = range.endContainer.childNodes[range.endOffset]; if(tmpNode && domUtils.isBr(tmpNode)){ range.setEndAfter(tmpNode); } } if(range.startOffset == 0){ tmpNode = range.startContainer; if(domUtils.isBoundaryNode(tmpNode,'firstChild') ){ tmpNode = range.endContainer; if(range.endOffset == (tmpNode.nodeType == 3 ? tmpNode.nodeValue.length : tmpNode.childNodes.length) && domUtils.isBoundaryNode(tmpNode,'lastChild')){ me.body.innerHTML = '<p>'+(browser.ie ? '' : '<br/>')+'</p>'; range.setStart(me.body.firstChild,0).collapse(true) } } } !range.collapsed && range.deleteContents(); if(range.startContainer.nodeType == 1){ var child = range.startContainer.childNodes[range.startOffset],pre; if(child && domUtils.isBlockElm(child) && (pre = child.previousSibling) && domUtils.isBlockElm(pre)){ range.setEnd(pre,pre.childNodes.length).collapse(); while(child.firstChild){ pre.appendChild(child.firstChild); } domUtils.remove(child); } } } var child,parent,pre,tmp,hadBreak = 0, nextNode; //如果当前位置选中了fillchar要干掉,要不会产生空行 if(range.inFillChar()){ child = range.startContainer; if(domUtils.isFillChar(child)){ range.setStartBefore(child).collapse(true); domUtils.remove(child); }else if(domUtils.isFillChar(child,true)){ child.nodeValue = child.nodeValue.replace(fillCharReg,''); range.startOffset--; range.collapsed && range.collapse(true) } } //列表单独处理 var li = domUtils.findParentByTagName(range.startContainer,'li',true); if(li){ var next,last; while(child = div.firstChild){ //针对hr单独处理一下先 while(child && (child.nodeType == 3 || !domUtils.isBlockElm(child) || child.tagName=='HR' )){ next = child.nextSibling; range.insertNode( child).collapse(); last = child; child = next; } if(child){ if(/^(ol|ul)$/i.test(child.tagName)){ while(child.firstChild){ last = child.firstChild; domUtils.insertAfter(li,child.firstChild); li = li.nextSibling; } domUtils.remove(child) }else{ var tmpLi; next = child.nextSibling; tmpLi = me.document.createElement('li'); domUtils.insertAfter(li,tmpLi); tmpLi.appendChild(child); last = child; child = next; li = tmpLi; } } } li = domUtils.findParentByTagName(range.startContainer,'li',true); if(domUtils.isEmptyBlock(li)){ domUtils.remove(li) } if(last){ range.setStartAfter(last).collapse(true).select(true) } }else{ while ( child = div.firstChild ) { if(hadBreak){ var p = me.document.createElement('p'); while(child && (child.nodeType == 3 || !dtd.$block[child.tagName])){ nextNode = child.nextSibling; p.appendChild(child); child = nextNode; } if(p.firstChild){ child = p } } range.insertNode( child ); nextNode = child.nextSibling; if ( !hadBreak && child.nodeType == domUtils.NODE_ELEMENT && domUtils.isBlockElm( child ) ){ parent = domUtils.findParent( child,function ( node ){ return domUtils.isBlockElm( node ); } ); if ( parent && parent.tagName.toLowerCase() != 'body' && !(dtd[parent.tagName][child.nodeName] && child.parentNode === parent)){ if(!dtd[parent.tagName][child.nodeName]){ pre = parent; }else{ tmp = child.parentNode; while (tmp !== parent){ pre = tmp; tmp = tmp.parentNode; } } domUtils.breakParent( child, pre || tmp ); //去掉break后前一个多余的节点 <p>|<[p> ==> <p></p><div></div><p>|</p> var pre = child.previousSibling; domUtils.trimWhiteTextNode(pre); if(!pre.childNodes.length){ domUtils.remove(pre); } //trace:2012,在非ie的情况,切开后剩下的节点有可能不能点入光标添加br占位 if(!browser.ie && (next = child.nextSibling) && domUtils.isBlockElm(next) && next.lastChild && !domUtils.isBr(next.lastChild)){ next.appendChild(me.document.createElement('br')); } hadBreak = 1; } } var next = child.nextSibling; if(!div.firstChild && next && domUtils.isBlockElm(next)){ range.setStart(next,0).collapse(true); break; } range.setEndAfter( child ).collapse(); } child = range.startContainer; if(nextNode && domUtils.isBr(nextNode)){ domUtils.remove(nextNode) } //用chrome可能有空白展位符 if(domUtils.isBlockElm(child) && domUtils.isEmptyNode(child)){ if(nextNode = child.nextSibling){ domUtils.remove(child); if(nextNode.nodeType == 1 && dtd.$block[nextNode.tagName]){ range.setStart(nextNode,0).collapse(true).shrinkBoundary() } }else{ try{ child.innerHTML = browser.ie ? domUtils.fillChar : '<br/>'; }catch(e){ range.setStartBefore(child); domUtils.remove(child) } } } //加上true因为在删除表情等时会删两次,第一次是删的fillData try{ range.select(true); }catch(e){} } setTimeout(function(){ range = me.selection.getRange(); range.scrollToView(me.autoHeightEnabled,me.autoHeightEnabled ? domUtils.getXY(me.iframe).y:0); me.fireEvent('afterinserthtml'); },200); } }; ///import core ///commands 自动提交 ///commandsName autosubmit ///commandsTitle 自动提交 UE.plugins['autosubmit'] = function(){ var me = this; me.commands['autosubmit'] = { execCommand:function () { var me=this, form = domUtils.findParentByTagName(me.iframe,"form", false); if (form) { if(me.fireEvent("beforesubmit")===false){ return; } me.sync(); form.submit(); } } }; //快捷键 me.addshortcutkey({ "autosubmit" : "ctrl+13" //手动提交 }); }; ///import core ///import plugins\inserthtml.js ///commands 插入图片,操作图片的对齐方式 ///commandsName InsertImage,ImageNone,ImageLeft,ImageRight,ImageCenter ///commandsTitle 图片,默认,居左,居右,居中 ///commandsDialog dialogs\image /** * Created by . * User: zhanyi * for image */ UE.commands['imagefloat'] = { execCommand:function (cmd, align) { var me = this, range = me.selection.getRange(); if (!range.collapsed) { var img = range.getClosedNode(); if (img && img.tagName == 'IMG') { switch (align) { case 'left': case 'right': case 'none': var pN = img.parentNode, tmpNode, pre, next; while (dtd.$inline[pN.tagName] || pN.tagName == 'A') { pN = pN.parentNode; } tmpNode = pN; if (tmpNode.tagName == 'P' && domUtils.getStyle(tmpNode, 'text-align') == 'center') { if (!domUtils.isBody(tmpNode) && domUtils.getChildCount(tmpNode, function (node) { return !domUtils.isBr(node) && !domUtils.isWhitespace(node); }) == 1) { pre = tmpNode.previousSibling; next = tmpNode.nextSibling; if (pre && next && pre.nodeType == 1 && next.nodeType == 1 && pre.tagName == next.tagName && domUtils.isBlockElm(pre)) { pre.appendChild(tmpNode.firstChild); while (next.firstChild) { pre.appendChild(next.firstChild); } domUtils.remove(tmpNode); domUtils.remove(next); } else { domUtils.setStyle(tmpNode, 'text-align', ''); } } range.selectNode(img).select(); } domUtils.setStyle(img, 'float', align == 'none' ? '' : align); if(align == 'none'){ domUtils.removeAttributes(img,'align'); } break; case 'center': if (me.queryCommandValue('imagefloat') != 'center') { pN = img.parentNode; domUtils.setStyle(img, 'float', ''); domUtils.removeAttributes(img,'align'); tmpNode = img; while (pN && domUtils.getChildCount(pN, function (node) { return !domUtils.isBr(node) && !domUtils.isWhitespace(node); }) == 1 && (dtd.$inline[pN.tagName] || pN.tagName == 'A')) { tmpNode = pN; pN = pN.parentNode; } range.setStartBefore(tmpNode).setCursor(false); pN = me.document.createElement('div'); pN.appendChild(tmpNode); domUtils.setStyle(tmpNode, 'float', ''); me.execCommand('insertHtml', '<p id="_img_parent_tmp" style="text-align:center">' + pN.innerHTML + '</p>'); tmpNode = me.document.getElementById('_img_parent_tmp'); tmpNode.removeAttribute('id'); tmpNode = tmpNode.firstChild; range.selectNode(tmpNode).select(); //去掉后边多余的元素 next = tmpNode.parentNode.nextSibling; if (next && domUtils.isEmptyNode(next)) { domUtils.remove(next); } } break; } } } }, queryCommandValue:function () { var range = this.selection.getRange(), startNode, floatStyle; if (range.collapsed) { return 'none'; } startNode = range.getClosedNode(); if (startNode && startNode.nodeType == 1 && startNode.tagName == 'IMG') { floatStyle = startNode.getAttribute('align')||domUtils.getComputedStyle(startNode, 'float'); if (floatStyle == 'none') { floatStyle = domUtils.getComputedStyle(startNode.parentNode, 'text-align') == 'center' ? 'center' : floatStyle; } return { left:1, right:1, center:1 }[floatStyle] ? floatStyle : 'none'; } return 'none'; }, queryCommandState:function () { var range = this.selection.getRange(), startNode; if (range.collapsed) return -1; startNode = range.getClosedNode(); if (startNode && startNode.nodeType == 1 && startNode.tagName == 'IMG') { return 0; } return -1; } }; UE.commands['insertimage'] = { execCommand:function (cmd, opt) { opt = utils.isArray(opt) ? opt : [opt]; if (!opt.length) { return; } var me = this, range = me.selection.getRange(), img = range.getClosedNode(); if (img && /img/i.test(img.tagName) && img.className != "edui-faked-video" && !img.getAttribute("word_img")) { var first = opt.shift(); var floatStyle = first['floatStyle']; delete first['floatStyle']; //// img.style.border = (first.border||0) +"px solid #000"; //// img.style.margin = (first.margin||0) +"px"; // img.style.cssText += ';margin:' + (first.margin||0) +"px;" + 'border:' + (first.border||0) +"px solid #000"; domUtils.setAttributes(img, first); me.execCommand('imagefloat', floatStyle); if (opt.length > 0) { range.setStartAfter(img).setCursor(false, true); me.execCommand('insertimage', opt); } } else { var html = [], str = '', ci; ci = opt[0]; if (opt.length == 1) { str = '<img src="' + ci.src + '" ' + (ci._src ? ' _src="' + ci._src + '" ' : '') + (ci.width ? 'width="' + ci.width + '" ' : '') + (ci.height ? ' height="' + ci.height + '" ' : '') + (ci['floatStyle'] == 'left' || ci['floatStyle'] == 'right' ? ' style="float:' + ci['floatStyle'] + ';"' : '') + (ci.title && ci.title != "" ? ' title="' + ci.title + '"' : '') + (ci.border && ci.border != "0" ? ' border="' + ci.border + '"' : '') + (ci.alt && ci.alt != "" ? ' alt="' + ci.alt + '"' : '') + (ci.hspace && ci.hspace != "0" ? ' hspace = "' + ci.hspace + '"' : '') + (ci.vspace && ci.vspace != "0" ? ' vspace = "' + ci.vspace + '"' : '') + '/>'; if (ci['floatStyle'] == 'center') { str = '<p style="text-align: center">' + str + '</p>'; } html.push(str); } else { for (var i = 0; ci = opt[i++];) { str = '<p ' + (ci['floatStyle'] == 'center' ? 'style="text-align: center" ' : '') + '><img src="' + ci.src + '" ' + (ci.width ? 'width="' + ci.width + '" ' : '') + (ci._src ? ' _src="' + ci._src + '" ' : '') + (ci.height ? ' height="' + ci.height + '" ' : '') + ' style="' + (ci['floatStyle'] && ci['floatStyle'] != 'center' ? 'float:' + ci['floatStyle'] + ';' : '') + (ci.border || '') + '" ' + (ci.title ? ' title="' + ci.title + '"' : '') + ' /></p>'; html.push(str); } } me.execCommand('insertHtml', html.join('')); } } };///import core ///commands 段落格式,居左,居右,居中,两端对齐 ///commandsName JustifyLeft,JustifyCenter,JustifyRight,JustifyJustify ///commandsTitle 居左对齐,居中对齐,居右对齐,两端对齐 /** * @description 居左右中 * @name baidu.editor.execCommand * @param {String} cmdName justify执行对齐方式的命令 * @param {String} align 对齐方式:left居左,right居右,center居中,justify两端对齐 * @author zhanyi */ UE.plugins['justify']=function(){ var me=this, block = domUtils.isBlockElm, defaultValue = { left:1, right:1, center:1, justify:1 }, doJustify = function (range, style) { var bookmark = range.createBookmark(), filterFn = function (node) { return node.nodeType == 1 ? node.tagName.toLowerCase() != 'br' && !domUtils.isBookmarkNode(node) : !domUtils.isWhitespace(node); }; range.enlarge(true); var bookmark2 = range.createBookmark(), current = domUtils.getNextDomNode(bookmark2.start, false, filterFn), tmpRange = range.cloneRange(), tmpNode; while (current && !(domUtils.getPosition(current, bookmark2.end) & domUtils.POSITION_FOLLOWING)) { if (current.nodeType == 3 || !block(current)) { tmpRange.setStartBefore(current); while (current && current !== bookmark2.end && !block(current)) { tmpNode = current; current = domUtils.getNextDomNode(current, false, null, function (node) { return !block(node); }); } tmpRange.setEndAfter(tmpNode); var common = tmpRange.getCommonAncestor(); if (!domUtils.isBody(common) && block(common)) { domUtils.setStyles(common, utils.isString(style) ? {'text-align':style} : style); current = common; } else { var p = range.document.createElement('p'); domUtils.setStyles(p, utils.isString(style) ? {'text-align':style} : style); var frag = tmpRange.extractContents(); p.appendChild(frag); tmpRange.insertNode(p); current = p; } current = domUtils.getNextDomNode(current, false, filterFn); } else { current = domUtils.getNextDomNode(current, true, filterFn); } } return range.moveToBookmark(bookmark2).moveToBookmark(bookmark); }; UE.commands['justify'] = { execCommand:function (cmdName, align) { var range = this.selection.getRange(), txt; //闭合时单独处理 if (range.collapsed) { txt = this.document.createTextNode('p'); range.insertNode(txt); } doJustify(range, align); if (txt) { range.setStartBefore(txt).collapse(true); domUtils.remove(txt); } range.select(); return true; }, queryCommandValue:function () { var startNode = this.selection.getStart(), value = domUtils.getComputedStyle(startNode, 'text-align'); return defaultValue[value] ? value : 'left'; }, queryCommandState:function () { var start = this.selection.getStart(), cell = start && domUtils.findParentByTagName(start, ["td", "th","caption"], true); return cell? -1:0; } }; }; ///import core ///import plugins\removeformat.js ///commands 字体颜色,背景色,字号,字体,下划线,删除线 ///commandsName ForeColor,BackColor,FontSize,FontFamily,Underline,StrikeThrough ///commandsTitle 字体颜色,背景色,字号,字体,下划线,删除线 /** * @description 字体 * @name baidu.editor.execCommand * @param {String} cmdName 执行的功能名称 * @param {String} value 传入的值 */ UE.plugins['font'] = function () { var me = this, fonts = { 'forecolor': 'color', 'backcolor': 'background-color', 'fontsize': 'font-size', 'fontfamily': 'font-family', 'underline': 'text-decoration', 'strikethrough': 'text-decoration', 'fontborder': 'border' }, needCmd = {'underline': 1, 'strikethrough': 1, 'fontborder': 1}, needSetChild = { 'forecolor': 'color', 'backcolor': 'background-color', 'fontsize': 'font-size', 'fontfamily': 'font-family' }; me.setOpt({ 'fontfamily': [ { name: 'songti', val: '宋体,SimSun'}, { name: 'yahei', val: '微软雅黑,Microsoft YaHei'}, { name: 'kaiti', val: '楷体,楷体_GB2312, SimKai'}, { name: 'heiti', val: '黑体, SimHei'}, { name: 'lishu', val: '隶书, SimLi'}, { name: 'andaleMono', val: 'andale mono'}, { name: 'arial', val: 'arial, helvetica,sans-serif'}, { name: 'arialBlack', val: 'arial black,avant garde'}, { name: 'comicSansMs', val: 'comic sans ms'}, { name: 'impact', val: 'impact,chicago'}, { name: 'timesNewRoman', val: 'times new roman'} ], 'fontsize': [10, 11, 12, 14, 16, 18, 20, 24, 36] }); function mergeWithParent(node){ var parent; while(parent = node.parentNode){ if(parent.tagName == 'SPAN' && domUtils.getChildCount(parent,function(child){ return !domUtils.isBookmarkNode(child) && !domUtils.isBr(child) }) == 1) { parent.style.cssText += node.style.cssText; domUtils.remove(node,true); node = parent; }else{ break; } } } function mergeChild(rng,cmdName,value){ if(needSetChild[cmdName]){ rng.adjustmentBoundary(); if(!rng.collapsed && rng.startContainer.nodeType == 1){ var start = rng.startContainer.childNodes[rng.startOffset]; if(start && domUtils.isTagNode(start,'span')){ var bk = rng.createBookmark(); utils.each(domUtils.getElementsByTagName(start, 'span'), function (span) { if (!span.parentNode || domUtils.isBookmarkNode(span))return; if(cmdName == 'backcolor' && domUtils.getComputedStyle(span,'background-color').toLowerCase() === value){ return; } domUtils.removeStyle(span,needSetChild[cmdName]); if(span.style.cssText.replace(/^\s+$/,'').length == 0){ domUtils.remove(span,true) } }); rng.moveToBookmark(bk) } } } } function mergesibling(rng,cmdName,value) { var collapsed = rng.collapsed, bk = rng.createBookmark(), common; if (collapsed) { common = bk.start.parentNode; while (dtd.$inline[common.tagName]) { common = common.parentNode; } } else { common = domUtils.getCommonAncestor(bk.start, bk.end); } utils.each(domUtils.getElementsByTagName(common, 'span'), function (span) { if (!span.parentNode || domUtils.isBookmarkNode(span))return; if (/\s*border\s*:\s*none;?\s*/i.test(span.style.cssText)) { if(/^\s*border\s*:\s*none;?\s*$/.test(span.style.cssText)){ domUtils.remove(span, true); }else{ domUtils.removeStyle(span,'border'); } return } if (/border/i.test(span.style.cssText) && span.parentNode.tagName == 'SPAN' && /border/i.test(span.parentNode.style.cssText)) { span.style.cssText = span.style.cssText.replace(/border[^:]*:[^;]+;?/gi, ''); } if(!(cmdName=='fontborder' && value=='none')){ var next = span.nextSibling; while (next && next.nodeType == 1 && next.tagName == 'SPAN' ) { if(domUtils.isBookmarkNode(next) && cmdName == 'fontborder') { span.appendChild(next); next = span.nextSibling; continue; } if (next.style.cssText == span.style.cssText) { domUtils.moveChild(next, span); domUtils.remove(next); } if (span.nextSibling === next) break; next = span.nextSibling; } } mergeWithParent(span); if(browser.ie && browser.version > 8 ){ //拷贝父亲们的特别的属性,这里只做背景颜色的处理 var parent = domUtils.findParent(span,function(n){return n.tagName == 'SPAN' && /background-color/.test(n.style.cssText)}); if(parent && !/background-color/.test(span.style.cssText)){ span.style.backgroundColor = parent.style.backgroundColor; } } }); rng.moveToBookmark(bk); mergeChild(rng,cmdName,value) } me.addInputRule(function (root) { utils.each(root.getNodesByTagName('u s del font strike'), function (node) { if (node.tagName == 'font') { var cssStyle = []; for (var p in node.attrs) { switch (p) { case 'size': cssStyle.push('font-size:' + node.attrs[p] + 'px'); break; case 'color': cssStyle.push('color:' + node.attrs[p]); break; case 'face': cssStyle.push('font-family:' + node.attrs[p]); break; case 'style': cssStyle.push(node.attrs[p]); } } node.attrs = { 'style': cssStyle.join(';') }; } else { var val = node.tagName == 'u' ? 'underline' : 'line-through'; node.attrs = { 'style': (node.getAttr('style') || '') + 'text-decoration:' + val + ';' } } node.tagName = 'span'; }); // utils.each(root.getNodesByTagName('span'), function (node) { // var val; // if(val = node.getAttr('class')){ // if(/fontstrikethrough/.test(val)){ // node.setStyle('text-decoration','line-through'); // if(node.attrs['class']){ // node.attrs['class'] = node.attrs['class'].replace(/fontstrikethrough/,''); // }else{ // node.setAttr('class') // } // } // if(/fontborder/.test(val)){ // node.setStyle('border','1px solid #000'); // if(node.attrs['class']){ // node.attrs['class'] = node.attrs['class'].replace(/fontborder/,''); // }else{ // node.setAttr('class') // } // } // } // }); }); // me.addOutputRule(function(root){ // utils.each(root.getNodesByTagName('span'), function (node) { // var val; // if(val = node.getStyle('text-decoration')){ // if(/line-through/.test(val)){ // if(node.attrs['class']){ // node.attrs['class'] += ' fontstrikethrough'; // }else{ // node.setAttr('class','fontstrikethrough') // } // } // // node.setStyle('text-decoration') // } // if(val = node.getStyle('border')){ // if(/1px/.test(val) && /solid/.test(val)){ // if(node.attrs['class']){ // node.attrs['class'] += ' fontborder'; // // }else{ // node.setAttr('class','fontborder') // } // } // node.setStyle('border') // // } // }); // }); for (var p in fonts) { (function (cmd, style) { UE.commands[cmd] = { execCommand: function (cmdName, value) { value = value || (this.queryCommandState(cmdName) ? 'none' : cmdName == 'underline' ? 'underline' : cmdName == 'fontborder' ? '1px solid #000' : 'line-through'); var me = this, range = this.selection.getRange(), text; if (value == 'default') { if (range.collapsed) { text = me.document.createTextNode('font'); range.insertNode(text).select(); } me.execCommand('removeFormat', 'span,a', style); if (text) { range.setStartBefore(text).collapse(true); domUtils.remove(text); } mergesibling(range,cmdName,value); range.select() } else { if (!range.collapsed) { if (needCmd[cmd] && me.queryCommandValue(cmd)) { me.execCommand('removeFormat', 'span,a', style); } range = me.selection.getRange(); range.applyInlineStyle('span', {'style': style + ':' + value}); mergesibling(range, cmdName,value); range.select(); } else { var span = domUtils.findParentByTagName(range.startContainer, 'span', true); text = me.document.createTextNode('font'); if (span && !span.children.length && !span[browser.ie ? 'innerText' : 'textContent'].replace(fillCharReg, '').length) { //for ie hack when enter range.insertNode(text); if (needCmd[cmd]) { range.selectNode(text).select(); me.execCommand('removeFormat', 'span,a', style, null); span = domUtils.findParentByTagName(text, 'span', true); range.setStartBefore(text); } span && (span.style.cssText += ';' + style + ':' + value); range.collapse(true).select(); } else { range.insertNode(text); range.selectNode(text).select(); span = range.document.createElement('span'); if (needCmd[cmd]) { //a标签内的不处理跳过 if (domUtils.findParentByTagName(text, 'a', true)) { range.setStartBefore(text).setCursor(); domUtils.remove(text); return; } me.execCommand('removeFormat', 'span,a', style); } span.style.cssText = style + ':' + value; text.parentNode.insertBefore(span, text); //修复,span套span 但样式不继承的问题 if (!browser.ie || browser.ie && browser.version == 9) { var spanParent = span.parentNode; while (!domUtils.isBlockElm(spanParent)) { if (spanParent.tagName == 'SPAN') { //opera合并style不会加入";" span.style.cssText = spanParent.style.cssText + ";" + span.style.cssText; } spanParent = spanParent.parentNode; } } if (opera) { setTimeout(function () { range.setStart(span, 0).collapse(true); mergesibling(range, cmdName,value); range.select(); }); } else { range.setStart(span, 0).collapse(true); mergesibling(range,cmdName,value); range.select(); } //trace:981 //domUtils.mergeToParent(span) } domUtils.remove(text); } } return true; }, queryCommandValue: function (cmdName) { var startNode = this.selection.getStart(); //trace:946 if (cmdName == 'underline' || cmdName == 'strikethrough') { var tmpNode = startNode, value; while (tmpNode && !domUtils.isBlockElm(tmpNode) && !domUtils.isBody(tmpNode)) { if (tmpNode.nodeType == 1) { value = domUtils.getComputedStyle(tmpNode, style); if (value != 'none') { return value; } } tmpNode = tmpNode.parentNode; } return 'none'; } if (cmdName == 'fontborder') { var tmp = startNode, val; while (tmp && dtd.$inline[tmp.tagName]) { if (val = domUtils.getComputedStyle(tmp, 'border')) { if (/1px/.test(val) && /solid/.test(val)) { return val; } } tmp = tmp.parentNode; } return '' } if( cmdName == 'FontSize' ) { var styleVal = domUtils.getComputedStyle(startNode, style), tmp = /^([\d\.]+)(\w+)$/.exec( styleVal ); if( tmp ) { return Math.floor( tmp[1] ) + tmp[2]; } return styleVal; } return domUtils.getComputedStyle(startNode, style); }, queryCommandState: function (cmdName) { if (!needCmd[cmdName]) return 0; var val = this.queryCommandValue(cmdName); if (cmdName == 'fontborder') { return /1px/.test(val) && /solid/.test(val) } else { return val == (cmdName == 'underline' ? 'underline' : 'line-through'); } } }; })(p, fonts[p]); } };///import core ///commands 超链接,取消链接 ///commandsName Link,Unlink ///commandsTitle 超链接,取消链接 ///commandsDialog dialogs\link /** * 超链接 * @function * @name baidu.editor.execCommand * @param {String} cmdName link插入超链接 * @param {Object} options url地址,title标题,target是否打开新页 * @author zhanyi */ /** * 取消链接 * @function * @name baidu.editor.execCommand * @param {String} cmdName unlink取消链接 * @author zhanyi */ UE.plugins['link'] = function(){ function optimize( range ) { var start = range.startContainer,end = range.endContainer; if ( start = domUtils.findParentByTagName( start, 'a', true ) ) { range.setStartBefore( start ); } if ( end = domUtils.findParentByTagName( end, 'a', true ) ) { range.setEndAfter( end ); } } UE.commands['unlink'] = { execCommand : function() { var range = this.selection.getRange(), bookmark; if(range.collapsed && !domUtils.findParentByTagName( range.startContainer, 'a', true )){ return; } bookmark = range.createBookmark(); optimize( range ); range.removeInlineStyle( 'a' ).moveToBookmark( bookmark ).select(); }, queryCommandState : function(){ return !this.highlight && this.queryCommandValue('link') ? 0 : -1; } }; function doLink(range,opt,me){ var rngClone = range.cloneRange(), link = me.queryCommandValue('link'); optimize( range = range.adjustmentBoundary() ); var start = range.startContainer; if(start.nodeType == 1 && link){ start = start.childNodes[range.startOffset]; if(start && start.nodeType == 1 && start.tagName == 'A' && /^(?:https?|ftp|file)\s*:\s*\/\//.test(start[browser.ie?'innerText':'textContent'])){ start[browser.ie ? 'innerText' : 'textContent'] = utils.html(opt.textValue||opt.href); } } if( !rngClone.collapsed || link){ range.removeInlineStyle( 'a' ); rngClone = range.cloneRange(); } if ( rngClone.collapsed ) { var a = range.document.createElement( 'a'), text = ''; if(opt.textValue){ text = utils.html(opt.textValue); delete opt.textValue; }else{ text = utils.html(opt.href); } domUtils.setAttributes( a, opt ); start = domUtils.findParentByTagName( rngClone.startContainer, 'a', true ); if(start && domUtils.isInNodeEndBoundary(rngClone,start)){ range.setStartAfter(start).collapse(true); } a[browser.ie ? 'innerText' : 'textContent'] = text; range.insertNode(a).selectNode( a ); } else { range.applyInlineStyle( 'a', opt ); } } UE.commands['link'] = { execCommand : function( cmdName, opt ) { var range; opt._href && (opt._href = utils.unhtml(opt._href,/[<">]/g)); opt.href && (opt.href = utils.unhtml(opt.href,/[<">]/g)); opt.textValue && (opt.textValue = utils.unhtml(opt.textValue,/[<">]/g)); doLink(range=this.selection.getRange(),opt,this); //闭合都不加占位符,如果加了会在a后边多个占位符节点,导致a是图片背景组成的列表,出现空白问题 range.collapse().select(true); }, queryCommandValue : function() { var range = this.selection.getRange(), node; if ( range.collapsed ) { // node = this.selection.getStart(); //在ie下getstart()取值偏上了 node = range.startContainer; node = node.nodeType == 1 ? node : node.parentNode; if ( node && (node = domUtils.findParentByTagName( node, 'a', true )) && ! domUtils.isInNodeEndBoundary(range,node)) { return node; } } else { //trace:1111 如果是<p><a>xx</a></p> startContainer是p就会找不到a range.shrinkBoundary(); var start = range.startContainer.nodeType == 3 || !range.startContainer.childNodes[range.startOffset] ? range.startContainer : range.startContainer.childNodes[range.startOffset], end = range.endContainer.nodeType == 3 || range.endOffset == 0 ? range.endContainer : range.endContainer.childNodes[range.endOffset-1], common = range.getCommonAncestor(); node = domUtils.findParentByTagName( common, 'a', true ); if ( !node && common.nodeType == 1){ var as = common.getElementsByTagName( 'a' ), ps,pe; for ( var i = 0,ci; ci = as[i++]; ) { ps = domUtils.getPosition( ci, start ),pe = domUtils.getPosition( ci,end); if ( (ps & domUtils.POSITION_FOLLOWING || ps & domUtils.POSITION_CONTAINS) && (pe & domUtils.POSITION_PRECEDING || pe & domUtils.POSITION_CONTAINS) ) { node = ci; break; } } } return node; } }, queryCommandState : function() { //判断如果是视频的话连接不可用 //fix 853 var img = this.selection.getRange().getClosedNode(), flag = img && (img.className == "edui-faked-video"); return flag ? -1 : 0; } }; };///import core ///commands 清除格式 ///commandsName RemoveFormat ///commandsTitle 清除格式 /** * @description 清除格式 * @name baidu.editor.execCommand * @param {String} cmdName removeformat清除格式命令 * @param {String} tags 以逗号隔开的标签。如:span,a * @param {String} style 样式 * @param {String} attrs 属性 * @param {String} notIncluedA 是否把a标签切开 * @author zhanyi */ UE.plugins['removeformat'] = function(){ var me = this; me.setOpt({ 'removeFormatTags': 'b,big,code,del,dfn,em,font,i,ins,kbd,q,samp,small,span,strike,strong,sub,sup,tt,u,var', 'removeFormatAttributes':'class,style,lang,width,height,align,hspace,valign' }); me.commands['removeformat'] = { execCommand : function( cmdName, tags, style, attrs,notIncludeA ) { var tagReg = new RegExp( '^(?:' + (tags || this.options.removeFormatTags).replace( /,/g, '|' ) + ')$', 'i' ) , removeFormatAttributes = style ? [] : (attrs || this.options.removeFormatAttributes).split( ',' ), range = new dom.Range( this.document ), bookmark,node,parent, filter = function( node ) { return node.nodeType == 1; }; function isRedundantSpan (node) { if (node.nodeType == 3 || node.tagName.toLowerCase() != 'span'){ return 0; } if (browser.ie) { //ie 下判断实效,所以只能简单用style来判断 //return node.style.cssText == '' ? 1 : 0; var attrs = node.attributes; if ( attrs.length ) { for ( var i = 0,l = attrs.length; i<l; i++ ) { if ( attrs[i].specified ) { return 0; } } return 1; } } return !node.attributes.length; } function doRemove( range ) { var bookmark1 = range.createBookmark(); if ( range.collapsed ) { range.enlarge( true ); } //不能把a标签切了 if(!notIncludeA){ var aNode = domUtils.findParentByTagName(range.startContainer,'a',true); if(aNode){ range.setStartBefore(aNode); } aNode = domUtils.findParentByTagName(range.endContainer,'a',true); if(aNode){ range.setEndAfter(aNode); } } bookmark = range.createBookmark(); node = bookmark.start; //切开始 while ( (parent = node.parentNode) && !domUtils.isBlockElm( parent ) ) { domUtils.breakParent( node, parent ); domUtils.clearEmptySibling( node ); } if ( bookmark.end ) { //切结束 node = bookmark.end; while ( (parent = node.parentNode) && !domUtils.isBlockElm( parent ) ) { domUtils.breakParent( node, parent ); domUtils.clearEmptySibling( node ); } //开始去除样式 var current = domUtils.getNextDomNode( bookmark.start, false, filter ), next; while ( current ) { if ( current == bookmark.end ) { break; } next = domUtils.getNextDomNode( current, true, filter ); if ( !dtd.$empty[current.tagName.toLowerCase()] && !domUtils.isBookmarkNode( current ) ) { if ( tagReg.test( current.tagName ) ) { if ( style ) { domUtils.removeStyle( current, style ); if ( isRedundantSpan( current ) && style != 'text-decoration'){ domUtils.remove( current, true ); } } else { domUtils.remove( current, true ); } } else { //trace:939 不能把list上的样式去掉 if(!dtd.$tableContent[current.tagName] && !dtd.$list[current.tagName]){ domUtils.removeAttributes( current, removeFormatAttributes ); if ( isRedundantSpan( current ) ){ domUtils.remove( current, true ); } } } } current = next; } } //trace:1035 //trace:1096 不能把td上的样式去掉,比如边框 var pN = bookmark.start.parentNode; if(domUtils.isBlockElm(pN) && !dtd.$tableContent[pN.tagName] && !dtd.$list[pN.tagName]){ domUtils.removeAttributes( pN,removeFormatAttributes ); } pN = bookmark.end.parentNode; if(bookmark.end && domUtils.isBlockElm(pN) && !dtd.$tableContent[pN.tagName]&& !dtd.$list[pN.tagName]){ domUtils.removeAttributes( pN,removeFormatAttributes ); } range.moveToBookmark( bookmark ).moveToBookmark(bookmark1); //清除冗余的代码 <b><bookmark></b> var node = range.startContainer, tmp, collapsed = range.collapsed; while(node.nodeType == 1 && domUtils.isEmptyNode(node) && dtd.$removeEmpty[node.tagName]){ tmp = node.parentNode; range.setStartBefore(node); //trace:937 //更新结束边界 if(range.startContainer === range.endContainer){ range.endOffset--; } domUtils.remove(node); node = tmp; } if(!collapsed){ node = range.endContainer; while(node.nodeType == 1 && domUtils.isEmptyNode(node) && dtd.$removeEmpty[node.tagName]){ tmp = node.parentNode; range.setEndBefore(node); domUtils.remove(node); node = tmp; } } } range = this.selection.getRange(); doRemove( range ); range.select(); } }; }; ///import core ///commands 预览 ///commandsName Preview ///commandsTitle 预览 /** * 预览 * @function * @name baidu.editor.execCommand * @param {String} cmdName preview预览编辑器内容 */ UE.commands['preview'] = { execCommand : function(){ var w = window.open('', '_blank', ''), d = w.document; d.open(); d.write('<html><head><script src="'+this.options.UEDITOR_HOME_URL+'ueditor.parse.js"></script><script>' + "setTimeout(function(){uParse('div',{" + " 'highlightJsUrl':'"+this.options.UEDITOR_HOME_URL+"third-party/SyntaxHighlighter/shCore.js'," + " 'highlightCssUrl':'"+this.options.UEDITOR_HOME_URL+"third-party/SyntaxHighlighter/shCoreDefault.css'" + "})},300)" + '</script></head><body><div>'+this.getContent(null,null,true)+'</div></body></html>'); d.close(); }, notNeedUndo : 1 }; ///import core ///import plugins/inserthtml.js ///commands 插入代码 ///commandsName code ///commandsTitle 插入代码 UE.plugins['insertcode'] = function() { var me = this; me.ready(function(){ utils.cssRule('pre','pre{margin:.5em 0;padding:.4em .6em;border-radius:8px;background:#f8f8f8;}', me.document) }); me.setOpt('insertcode',{ 'as3':'ActionScript3', 'bash':'Bash/Shell', 'cpp':'C/C++', 'css':'Css', 'cf':'CodeFunction', 'c#':'C#', 'delphi':'Delphi', 'diff':'Diff', 'erlang':'Erlang', 'groovy':'Groovy', 'html':'Html', 'java':'Java', 'jfx':'JavaFx', 'js':'Javascript', 'pl':'Perl', 'php':'Php', 'plain':'Plain Text', 'ps':'PowerShell', 'python':'Python', 'ruby':'Ruby', 'scala':'Scala', 'sql':'Sql', 'vb':'Vb', 'xml':'Xml' }); me.commands['insertcode'] = { execCommand : function(cmd,lang){ var me = this, rng = me.selection.getRange(), pre = domUtils.findParentByTagName(rng.startContainer,'pre',true); if(pre){ pre.className = 'brush:'+lang+';toolbar:false;'; }else{ var code = ''; if(rng.collapsed){ code = browser.ie? (browser.version > 8 ? '' : '&nbsp;'):'<br/>'; }else{ var frag = rng.extractContents(); var div = me.document.createElement('div'); div.appendChild(frag); utils.each(UE.filterNode(UE.htmlparser(div.innerHTML.replace(/[\r\t]/g,'')),me.options.filterTxtRules).children,function(node){ if(browser.ie && browser.version > 8){ if(node.type =='element'){ if(node.tagName == 'br'){ code += '\n' }else if(!dtd.$empty[node.tagName]){ utils.each(node.children,function(cn){ if(cn.type =='element'){ if(cn.tagName == 'br'){ code += '\n' }else if(!dtd.$empty[node.tagName]){ code += cn.innerText(); } }else{ code += cn.data } }) if(!/\n$/.test(code)){ code += '\n'; } } }else{ code += node.data + '\n' } if(!node.nextSibling() && /\n$/.test(code)){ code = code.replace(/\n$/,''); } }else{ if(browser.ie){ if(node.type =='element'){ if(node.tagName == 'br'){ code += '<br>' }else if(!dtd.$empty[node.tagName]){ utils.each(node.children,function(cn){ if(cn.type =='element'){ if(cn.tagName == 'br'){ code += '<br>' }else if(!dtd.$empty[node.tagName]){ code += cn.innerText(); } }else{ code += cn.data } }); if(!/br>$/.test(code)){ code += '<br>'; } } }else{ code += node.data + '<br>' } if(!node.nextSibling() && /<br>$/.test(code)){ code = code.replace(/<br>$/,''); } }else{ code += (node.type == 'element' ? (dtd.$empty[node.tagName] ? '' : node.innerText()) : node.data); if(!/br\/?\s*>$/.test(code)){ if(!node.nextSibling()) return; code += '<br>' } } } }); } me.execCommand('inserthtml','<pre id="coder"class="brush:'+lang+';toolbar:false">'+code+'</pre>',true); pre = me.document.getElementById('coder'); domUtils.removeAttributes(pre,'id'); var tmpNode = pre.previousSibling; if(tmpNode && (tmpNode.nodeType == 3 && tmpNode.nodeValue.length == 1 && browser.ie && browser.version == 6 || domUtils.isEmptyBlock(tmpNode))){ domUtils.remove(tmpNode) } var rng = me.selection.getRange(); if(domUtils.isEmptyBlock(pre)){ rng.setStart(pre,0).setCursor(false,true) }else{ rng.selectNodeContents(pre).select() } } }, queryCommandValue : function(){ var path = this.selection.getStartElementPath(); var lang = ''; utils.each(path,function(node){ if(node.nodeName =='PRE'){ var match = node.className.match(/brush:([^;]+)/); lang = match && match[1] ? match[1] : ''; return false; } }); return lang; } }; me.addInputRule(function(root){ utils.each(root.getNodesByTagName('pre'),function(pre){ var brs = pre.getNodesByTagName('br'); if(brs.length){ browser.ie && browser.version > 8 && utils.each(brs,function(br){ var txt = UE.uNode.createText('\n'); br.parentNode.insertBefore(txt,br); br.parentNode.removeChild(br); }); return; } if(browser.ie && browser.version > 8) return; var code = pre.innerText().split(/\n/); pre.innerHTML(''); utils.each(code,function(c){ if(c.length){ pre.appendChild(UE.uNode.createText(c)); } pre.appendChild(UE.uNode.createElement('br')) }) }) }); me.addOutputRule(function(root){ utils.each(root.getNodesByTagName('pre'),function(pre){ var code = ''; utils.each(pre.children,function(n){ if(n.type == 'text'){ //在ie下文本内容有可能末尾带有\n要去掉 //trace:3396 code += n.data.replace(/[ ]/g,'&nbsp;').replace(/\n$/,''); }else{ if(n.tagName == 'br'){ code += '\n' }else{ code += (!dtd.$empty[n.tagName] ? '' : n.innerText()); } } }); pre.innerText(code.replace(/(&nbsp;|\n)+$/,'')) }) }); //不需要判断highlight的command列表 me.notNeedCodeQuery ={ help:1, undo:1, redo:1, source:1, print:1, searchreplace:1, fullscreen:1, preview:1, insertparagraph:1, elementpath:1, highlightcode:1, insertcode:1, inserthtml:1, selectall:1 }; //将queyCommamndState重置 var orgQuery = me.queryCommandState; me.queryCommandState = function(cmd){ var me = this; if(!me.notNeedCodeQuery[cmd.toLowerCase()] && me.selection && me.queryCommandValue('insertcode')){ return -1; } return UE.Editor.prototype.queryCommandState.apply(this,arguments) }; me.addListener('beforeenterkeydown',function(){ var rng = me.selection.getRange(); var pre = domUtils.findParentByTagName(rng.startContainer,'pre',true); if(pre){ me.fireEvent('saveScene'); if(!rng.collapsed){ rng.deleteContents(); } if(!browser.ie ){ var tmpNode = me.document.createElement('br'),pre; rng.insertNode(tmpNode).setStartAfter(tmpNode).collapse(true); var next = tmpNode.nextSibling; if(!next){ rng.insertNode(tmpNode.cloneNode(false)); }else{ rng.setStartAfter(tmpNode); } pre = tmpNode.previousSibling; var tmp; while(pre ){ tmp = pre; pre = pre.previousSibling; if(!pre || pre.nodeName == 'BR'){ pre = tmp; break; } } if(pre){ var str = ''; while(pre && pre.nodeName != 'BR' && new RegExp('^[\\s'+domUtils.fillChar+']*$').test(pre.nodeValue)){ str += pre.nodeValue; pre = pre.nextSibling; } if(pre.nodeName != 'BR'){ var match = pre.nodeValue.match(new RegExp('^([\\s'+domUtils.fillChar+']+)')); if(match && match[1]){ str += match[1] } } if(str){ str = me.document.createTextNode(str); rng.insertNode(str).setStartAfter(str); } } rng.collapse(true).select(true); }else{ if(browser.version > 8){ var txt = me.document.createTextNode('\n'); var start = rng.startContainer; if(rng.startOffset == 0){ var preNode = start.previousSibling; if(preNode){ rng.insertNode(txt); var fillchar = me.document.createTextNode(' '); rng.setStartAfter(txt).insertNode(fillchar).setStart(fillchar,0).collapse(true).select(true) } }else{ rng.insertNode(txt).setStartAfter(txt); var fillchar = me.document.createTextNode(' '); start = rng.startContainer.childNodes[rng.startOffset]; if(start && !/^\n/.test(start.nodeValue)){ rng.setStartBefore(txt) } rng.insertNode(fillchar).setStart(fillchar,0).collapse(true).select(true) } }else{ var tmpNode = me.document.createElement('br'); rng.insertNode(tmpNode); rng.insertNode(me.document.createTextNode(domUtils.fillChar)); rng.setStartAfter(tmpNode); pre = tmpNode.previousSibling; var tmp; while(pre ){ tmp = pre; pre = pre.previousSibling; if(!pre || pre.nodeName == 'BR'){ pre = tmp; break; } } if(pre){ var str = ''; while(pre && pre.nodeName != 'BR' && new RegExp('^[ '+domUtils.fillChar+']*$').test(pre.nodeValue)){ str += pre.nodeValue; pre = pre.nextSibling; } if(pre.nodeName != 'BR'){ var match = pre.nodeValue.match(new RegExp('^([ '+domUtils.fillChar+']+)')); if(match && match[1]){ str += match[1] } } str = me.document.createTextNode(str); rng.insertNode(str).setStartAfter(str); } rng.collapse(true).select(); } } me.fireEvent('saveScene'); return true; } }); me.addListener('tabkeydown',function(cmd,evt){ var rng = me.selection.getRange(); var pre = domUtils.findParentByTagName(rng.startContainer,'pre',true); if(pre){ me.fireEvent('saveScene'); if(evt.shiftKey){ // if(!rng.collapsed){ // var bk = rng.createBookmark(); // var start = bk.start.previousSibling; // if(start === pre.firstChild){ // start.nodeValue = start.nodeValue.replace(/^\s{4}/,''); // }else{ // while(start){ // if(domUtils.isBr(start)){ // start = start.nextSibling; // start.nodeValue = start.nodeValue.replace(/^\s{4}/,''); // break; // } // while(start.previousSibling && start.previousSibling.nodeType == 3){ // start.nodeValue = start.previousSibling.nodeValue + start.nodeValue; // domUtils.remove(start.previousSibling) // } // start = start.previousSibling; // } // } // // var end = bk.end; // start = bk.start.nextSibling; // // while(start && start !== end){ // if(domUtils.isBr(start) && start.nextSibling){ // if(start.nextSibling === end){ // break; // } // start = start.nextSibling; // while(start.nextSibling && start.nextSibling.nodeType == 3){ // start.nodeValue += start.nextSibling.nodeValue; // domUtils.remove(start.nextSibling) // } // // start.nodeValue = start.nodeValue.replace(/^\s{4}/,''); // } // // start = start.nextSibling; // } // rng.moveToBookmark(bk).select(); // }else{ // var bk = rng.createBookmark(); // var start = bk.start.previousSibling; // if(start === pre.firstChild){ // start.nodeValue = start.nodeValue.replace(/^\s{4}/,''); // }else{ // while(start){ // if(domUtils.isBr(start)){ // start = start.nextSibling; // start.nodeValue = start.nodeValue.replace(/^\s{4}/,''); // break; // } // while(start.previousSibling && start.previousSibling.nodeType == 3){ // start.nodeValue = start.previousSibling.nodeValue + start.nodeValue; // domUtils.remove(start.previousSibling) // } // start = start.previousSibling; // } // } // } }else{ if(!rng.collapsed){ var bk = rng.createBookmark(); var start = bk.start.previousSibling; while(start){ if(pre.firstChild === start && !domUtils.isBr(start)){ pre.insertBefore(me.document.createTextNode(' '),start); break; } if(domUtils.isBr(start)){ pre.insertBefore(me.document.createTextNode(' '),start.nextSibling); break; } start = start.previousSibling; } var end = bk.end; start = bk.start.nextSibling; if(pre.firstChild === bk.start){ pre.insertBefore(me.document.createTextNode(' '),start.nextSibling) } while(start && start !== end){ if(domUtils.isBr(start) && start.nextSibling){ if(start.nextSibling === end){ break; } pre.insertBefore(me.document.createTextNode(' '),start.nextSibling) } start = start.nextSibling; } rng.moveToBookmark(bk).select(); }else{ var tmpNode = me.document.createTextNode(' '); rng.insertNode(tmpNode).setStartAfter(tmpNode).collapse(true).select(true); } } me.fireEvent('saveScene'); return true; } }); me.addListener('beforeinserthtml',function(evtName,html){ var me = this, rng = me.selection.getRange(), pre = domUtils.findParentByTagName(rng.startContainer,'pre',true); if(pre){ if(!rng.collapsed){ rng.deleteContents() } var htmlstr = ''; if(browser.ie && browser.version > 8){ utils.each(UE.filterNode(UE.htmlparser(html),me.options.filterTxtRules).children,function(node){ if(node.type =='element'){ if(node.tagName == 'br'){ htmlstr += '\n' }else if(!dtd.$empty[node.tagName]){ utils.each(node.children,function(cn){ if(cn.type =='element'){ if(cn.tagName == 'br'){ htmlstr += '\n' }else if(!dtd.$empty[node.tagName]){ htmlstr += cn.innerText(); } }else{ htmlstr += cn.data } }) if(!/\n$/.test(htmlstr)){ htmlstr += '\n'; } } }else{ htmlstr += node.data + '\n' } if(!node.nextSibling() && /\n$/.test(htmlstr)){ htmlstr = htmlstr.replace(/\n$/,''); } }); var tmpNode = me.document.createTextNode(utils.html(htmlstr.replace(/&nbsp;/g,' '))); rng.insertNode(tmpNode).selectNode(tmpNode).select(); }else{ var frag = me.document.createDocumentFragment(); utils.each(UE.filterNode(UE.htmlparser(html),me.options.filterTxtRules).children,function(node){ if(node.type =='element'){ if(node.tagName == 'br'){ frag.appendChild(me.document.createElement('br')) }else if(!dtd.$empty[node.tagName]){ utils.each(node.children,function(cn){ if(cn.type =='element'){ if(cn.tagName == 'br'){ frag.appendChild(me.document.createElement('br')) }else if(!dtd.$empty[node.tagName]){ frag.appendChild(me.document.createTextNode(utils.html(cn.innerText().replace(/&nbsp;/g,' ')))); } }else{ frag.appendChild(me.document.createTextNode(utils.html( cn.data.replace(/&nbsp;/g,' ')))); } }) if(frag.lastChild.nodeName != 'BR'){ frag.appendChild(me.document.createElement('br')) } } }else{ frag.appendChild(me.document.createTextNode(utils.html( node.data.replace(/&nbsp;/g,' ')))); } if(!node.nextSibling() && frag.lastChild.nodeName == 'BR'){ frag.removeChild(frag.lastChild) } }); rng.insertNode(frag).select(); } return true; } }); //方向键的处理 me.addListener('keydown',function(cmd,evt){ var me = this,keyCode = evt.keyCode || evt.which; if(keyCode == 40){ var rng = me.selection.getRange(),pre,start = rng.startContainer; if(rng.collapsed && (pre = domUtils.findParentByTagName(rng.startContainer,'pre',true)) && !pre.nextSibling){ var last = pre.lastChild while(last && last.nodeName == 'BR'){ last = last.previousSibling; } if(last === start || rng.startContainer === pre && rng.startOffset == pre.childNodes.length){ me.execCommand('insertparagraph'); domUtils.preventDefault(evt) } } } }); //trace:3395 me.addListener('delkeydown',function(type,evt){ var rng = this.selection.getRange(); rng.txtToElmBoundary(true); var start = rng.startContainer; if(domUtils.isTagNode(start,'pre') && rng.collapsed && domUtils.isStartInblock(rng)){ var p = me.document.createElement('p'); domUtils.fillNode(me.document,p); start.parentNode.insertBefore(p,start); domUtils.remove(start); rng.setStart(p,0).setCursor(false,true); domUtils.preventDefault(evt); return true; } }) }; ///import core ///commands 字数统计 ///commandsName WordCount,wordCount ///commandsTitle 字数统计 /** * Created by JetBrains WebStorm. * User: taoqili * Date: 11-9-7 * Time: 下午8:18 * To change this template use File | Settings | File Templates. */ UE.plugins['wordcount'] = function(){ var me = this; me.addListener('contentchange',function(){ me.fireEvent('wordcount'); }); var timer; me.addListener('ready',function(){ var me = this; domUtils.on(me.body,"keyup",function(evt){ var code = evt.keyCode||evt.which, //忽略的按键,ctr,alt,shift,方向键 ignores = {"16":1,"18":1,"20":1,"37":1,"38":1,"39":1,"40":1}; if(code in ignores) return; clearTimeout(timer); timer = setTimeout(function(){ me.fireEvent('wordcount'); },200) }) }); }; UE.plugins['dragdrop'] = function (){ var me = this; me.ready(function(){ domUtils.on(this.body,'dragend',function(){ var rng = me.selection.getRange(); var node = rng.getClosedNode()||me.selection.getStart(); if(node && node.tagName == 'IMG'){ var pre = node.previousSibling,next; while(next = node.nextSibling){ if(next.nodeType == 1 && next.tagName == 'SPAN' && !next.firstChild){ domUtils.remove(next) }else{ break; } } if((pre && pre.nodeType == 1 && !domUtils.isEmptyBlock(pre) || !pre) && (!next || next && !domUtils.isEmptyBlock(next))){ if(pre && pre.tagName == 'P' && !domUtils.isEmptyBlock(pre)){ pre.appendChild(node); domUtils.moveChild(next,pre); domUtils.remove(next); }else if(next && next.tagName == 'P' && !domUtils.isEmptyBlock(next)){ next.insertBefore(node,next.firstChild); } if(pre && pre.tagName == 'P' && domUtils.isEmptyBlock(pre)){ domUtils.remove(pre) } if(next && next.tagName == 'P' && domUtils.isEmptyBlock(next)){ domUtils.remove(next) } rng.selectNode(node).select(); me.fireEvent('saveScene'); } } }) }); me.addListener('keyup', function(type, evt) { var keyCode = evt.keyCode || evt.which; if (keyCode == 13) { var rng = me.selection.getRange(),node; if(node = domUtils.findParentByTagName(rng.startContainer,'p',true)){ if(domUtils.getComputedStyle(node,'text-align') == 'center'){ domUtils.removeStyle(node,'text-align') } } } }) }; ///import core ///import plugins/inserthtml.js ///import plugins/undo.js ///import plugins/serialize.js ///commands 粘贴 ///commandsName PastePlain ///commandsTitle 纯文本粘贴模式 /* ** @description 粘贴 * @author zhanyi */ UE.plugins['paste'] = function () { function getClipboardData(callback) { var doc = this.document; if (doc.getElementById('baidu_pastebin')) { return; } var range = this.selection.getRange(), bk = range.createBookmark(), //创建剪贴的容器div pastebin = doc.createElement('div'); pastebin.id = 'baidu_pastebin'; // Safari 要求div必须有内容,才能粘贴内容进来 browser.webkit && pastebin.appendChild(doc.createTextNode(domUtils.fillChar + domUtils.fillChar)); doc.body.appendChild(pastebin); //trace:717 隐藏的span不能得到top //bk.start.innerHTML = '&nbsp;'; bk.start.style.display = ''; pastebin.style.cssText = "position:absolute;width:1px;height:1px;overflow:hidden;left:-1000px;white-space:nowrap;top:" + //要在现在光标平行的位置加入,否则会出现跳动的问题 domUtils.getXY(bk.start).y + 'px'; range.selectNodeContents(pastebin).select(true); setTimeout(function () { if (browser.webkit) { for (var i = 0, pastebins = doc.querySelectorAll('#baidu_pastebin'), pi; pi = pastebins[i++];) { if (domUtils.isEmptyNode(pi)) { domUtils.remove(pi); } else { pastebin = pi; break; } } } try { pastebin.parentNode.removeChild(pastebin); } catch (e) { } range.moveToBookmark(bk).select(true); callback(pastebin); }, 0); } var me = this; var txtContent, htmlContent, address; function filter(div) { var html; if (div.firstChild) { //去掉cut中添加的边界值 var nodes = domUtils.getElementsByTagName(div, 'span'); for (var i = 0, ni; ni = nodes[i++];) { if (ni.id == '_baidu_cut_start' || ni.id == '_baidu_cut_end') { domUtils.remove(ni); } } if (browser.webkit) { var brs = div.querySelectorAll('div br'); for (var i = 0, bi; bi = brs[i++];) { var pN = bi.parentNode; if (pN.tagName == 'DIV' && pN.childNodes.length == 1) { pN.innerHTML = '<p><br/></p>'; domUtils.remove(pN); } } var divs = div.querySelectorAll('#baidu_pastebin'); for (var i = 0, di; di = divs[i++];) { var tmpP = me.document.createElement('p'); di.parentNode.insertBefore(tmpP, di); while (di.firstChild) { tmpP.appendChild(di.firstChild); } domUtils.remove(di); } var metas = div.querySelectorAll('meta'); for (var i = 0, ci; ci = metas[i++];) { domUtils.remove(ci); } var brs = div.querySelectorAll('br'); for (i = 0; ci = brs[i++];) { if (/^apple-/i.test(ci.className)) { domUtils.remove(ci); } } } if (browser.gecko) { var dirtyNodes = div.querySelectorAll('[_moz_dirty]'); for (i = 0; ci = dirtyNodes[i++];) { ci.removeAttribute('_moz_dirty'); } } if (!browser.ie) { var spans = div.querySelectorAll('span.Apple-style-span'); for (var i = 0, ci; ci = spans[i++];) { domUtils.remove(ci, true); } } //ie下使用innerHTML会产生多余的\r\n字符,也会产生&nbsp;这里过滤掉 html = div.innerHTML;//.replace(/>(?:(\s|&nbsp;)*?)</g,'><'); //过滤word粘贴过来的冗余属性 html = UE.filterWord(html); //取消了忽略空白的第二个参数,粘贴过来的有些是有空白的,会被套上相关的标签 var root = UE.htmlparser(html); //如果给了过滤规则就先进行过滤 if (me.options.filterRules) { UE.filterNode(root, me.options.filterRules); } //执行默认的处理 me.filterInputRule(root); //针对chrome的处理 if (browser.webkit) { var br = root.lastChild(); if (br && br.type == 'element' && br.tagName == 'br') { root.removeChild(br) } utils.each(me.body.querySelectorAll('div'), function (node) { if (domUtils.isEmptyBlock(node)) { domUtils.remove(node) } }) } html = {'html': root.toHtml()}; me.fireEvent('beforepaste', html, root); //抢了默认的粘贴,那后边的内容就不执行了,比如表格粘贴 if(!html.html){ return; } root = UE.htmlparser(html.html,true); //如果开启了纯文本模式 if (me.queryCommandState('pasteplain') === 1) { me.execCommand('insertHtml', UE.filterNode(root, me.options.filterTxtRules).toHtml(), true); } else { //文本模式 UE.filterNode(root, me.options.filterTxtRules); txtContent = root.toHtml(); //完全模式 htmlContent = html.html; address = me.selection.getRange().createAddress(true); me.execCommand('insertHtml', htmlContent, true); } me.fireEvent("afterpaste", html); } } me.addListener('pasteTransfer', function (cmd, plainType) { if (address && txtContent && htmlContent && txtContent != htmlContent) { var range = me.selection.getRange(); range.moveToAddress(address, true); if (!range.collapsed) { while (!domUtils.isBody(range.startContainer) ) { var start = range.startContainer; if(start.nodeType == 1){ start = start.childNodes[range.startOffset]; if(!start){ range.setStartBefore(range.startContainer); continue; } var pre = start.previousSibling; if(pre && pre.nodeType == 3 && new RegExp('^[\n\r\t '+domUtils.fillChar+']*$').test(pre.nodeValue)){ range.setStartBefore(pre) } } if(range.startOffset == 0){ range.setStartBefore(range.startContainer); }else{ break; } } while (!domUtils.isBody(range.endContainer) ) { var end = range.endContainer; if(end.nodeType == 1){ end = end.childNodes[range.endOffset]; if(!end){ range.setEndAfter(range.endContainer); continue; } var next = end.nextSibling; if(next && next.nodeType == 3 && new RegExp('^[\n\r\t'+domUtils.fillChar+']*$').test(next.nodeValue)){ range.setEndAfter(next) } } if(range.endOffset == range.endContainer[range.endContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length){ range.setEndAfter(range.endContainer); }else{ break; } } } range.deleteContents(); range.select(true); me.__hasEnterExecCommand = true; var html = htmlContent; if (plainType === 2) { html = html.replace(/<(\/?)([\w\-]+)([^>]*)>/gi, function (a, b, tagName, attrs) { tagName = tagName.toLowerCase(); if ({img: 1}[tagName]) { return a; } attrs = attrs.replace(/([\w\-]*?)\s*=\s*(("([^"]*)")|('([^']*)')|([^\s>]+))/gi, function (str, atr, val) { if ({ 'src': 1, 'href': 1, 'name': 1 }[atr.toLowerCase()]) { return atr + '=' + val + ' ' } return '' }); if ({ 'span': 1, 'div': 1 }[tagName]) { return '' } else { return '<' + b + tagName + ' ' + utils.trim(attrs) + '>' } }); } else if (plainType) { html = txtContent; } me.execCommand('inserthtml', html, true); me.__hasEnterExecCommand = false; var rng = me.selection.getRange(); while (!domUtils.isBody(rng.startContainer) && !rng.startOffset && rng.startContainer[rng.startContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length ) { rng.setStartBefore(rng.startContainer); } var tmpAddress = rng.createAddress(true); address.endAddress = tmpAddress.startAddress; } }); me.addListener('ready', function () { domUtils.on(me.body, 'cut', function () { var range = me.selection.getRange(); if (!range.collapsed && me.undoManger) { me.undoManger.save(); } }); //ie下beforepaste在点击右键时也会触发,所以用监控键盘才处理 domUtils.on(me.body, browser.ie || browser.opera ? 'keydown' : 'paste', function (e) { if ((browser.ie || browser.opera) && ((!e.ctrlKey && !e.metaKey) || e.keyCode != '86')) { return; } getClipboardData.call(me, function (div) { filter(div); }); }); }); }; ///import core ///commands 有序列表,无序列表 ///commandsName InsertOrderedList,InsertUnorderedList ///commandsTitle 有序列表,无序列表 /** * 有序列表 * @function * @name baidu.editor.execCommand * @param {String} cmdName insertorderlist插入有序列表 * @param {String} style 值为:decimal,lower-alpha,lower-roman,upper-alpha,upper-roman * @author zhanyi */ /** * 无序链接 * @function * @name baidu.editor.execCommand * @param {String} cmdName insertunorderlist插入无序列表 * * @param {String} style 值为:circle,disc,square * @author zhanyi */ UE.plugins['list'] = function () { var me = this, notExchange = { 'TD':1, 'PRE':1, 'BLOCKQUOTE':1 }; var customStyle = { 'cn' : 'cn-1-', 'cn1' : 'cn-2-', 'cn2' : 'cn-3-', 'num': 'num-1-', 'num1' : 'num-2-', 'num2' : 'num-3-', 'dash' : 'dash', 'dot':'dot' }; me.setOpt( { 'insertorderedlist':{ 'num':'', 'num1':'', 'num2':'', 'cn':'', 'cn1':'', 'cn2':'', 'decimal':'', 'lower-alpha':'', 'lower-roman':'', 'upper-alpha':'', 'upper-roman':'' }, 'insertunorderedlist':{ 'circle':'', 'disc':'', 'square':'', 'dash' : '', 'dot':'' }, listDefaultPaddingLeft : '30', listiconpath : 'http://bs.baidu.com/listicon/', maxListLevel : -1//-1不限制 } ); function listToArray(list){ var arr = []; for(var p in list){ arr.push(p) } return arr; } var listStyle = { 'OL':listToArray(me.options.insertorderedlist), 'UL':listToArray(me.options.insertunorderedlist) }; var liiconpath = me.options.listiconpath; //根据用户配置,调整customStyle for(var s in customStyle){ if(!me.options.insertorderedlist.hasOwnProperty(s) && !me.options.insertunorderedlist.hasOwnProperty(s)){ delete customStyle[s]; } } me.ready(function () { var customCss = []; for(var p in customStyle){ if(p == 'dash' || p == 'dot'){ customCss.push('li.list-' + customStyle[p] + '{background-image:url(' + liiconpath +customStyle[p]+'.gif)}'); customCss.push('ul.custom_'+p+'{list-style:none;}ul.custom_'+p+' li{background-position:0 3px;background-repeat:no-repeat}'); }else{ for(var i= 0;i<99;i++){ customCss.push('li.list-' + customStyle[p] + i + '{background-image:url(' + liiconpath + 'list-'+customStyle[p] + i + '.gif)}') } customCss.push('ol.custom_'+p+'{list-style:none;}ol.custom_'+p+' li{background-position:0 3px;background-repeat:no-repeat}'); } switch(p){ case 'cn': customCss.push('li.list-'+p+'-paddingleft-1{padding-left:25px}'); customCss.push('li.list-'+p+'-paddingleft-2{padding-left:40px}'); customCss.push('li.list-'+p+'-paddingleft-3{padding-left:55px}'); break; case 'cn1': customCss.push('li.list-'+p+'-paddingleft-1{padding-left:30px}'); customCss.push('li.list-'+p+'-paddingleft-2{padding-left:40px}'); customCss.push('li.list-'+p+'-paddingleft-3{padding-left:55px}'); break; case 'cn2': customCss.push('li.list-'+p+'-paddingleft-1{padding-left:40px}'); customCss.push('li.list-'+p+'-paddingleft-2{padding-left:55px}'); customCss.push('li.list-'+p+'-paddingleft-3{padding-left:68px}'); break; case 'num': case 'num1': customCss.push('li.list-'+p+'-paddingleft-1{padding-left:25px}'); break; case 'num2': customCss.push('li.list-'+p+'-paddingleft-1{padding-left:35px}'); customCss.push('li.list-'+p+'-paddingleft-2{padding-left:40px}'); break; case 'dash': customCss.push('li.list-'+p+'-paddingleft{padding-left:35px}'); break; case 'dot': customCss.push('li.list-'+p+'-paddingleft{padding-left:20px}'); } } customCss.push('.list-paddingleft-1{padding-left:0}'); customCss.push('.list-paddingleft-2{padding-left:'+me.options.listDefaultPaddingLeft+'px}'); customCss.push('.list-paddingleft-3{padding-left:'+me.options.listDefaultPaddingLeft*2+'px}'); //如果不给宽度会在自定应样式里出现滚动条 utils.cssRule('list', 'ol,ul{margin:0;pading:0;'+(browser.ie ? '' : 'width:95%')+'}li{clear:both;}'+customCss.join('\n'), me.document); }); //单独处理剪切的问题 me.ready(function(){ domUtils.on(me.body,'cut',function(){ setTimeout(function(){ var rng = me.selection.getRange(),li; //trace:3416 if(!rng.collapsed){ if(li = domUtils.findParentByTagName(rng.startContainer,'li',true)){ if(!li.nextSibling && domUtils.isEmptyBlock(li)){ var pn = li.parentNode,node; if(node = pn.previousSibling){ domUtils.remove(pn); rng.setStartAtLast(node).collapse(true); rng.select(true); }else if(node = pn.nextSibling){ domUtils.remove(pn); rng.setStartAtFirst(node).collapse(true); rng.select(true); }else{ var tmpNode = me.document.createElement('p'); domUtils.fillNode(me.document,tmpNode); pn.parentNode.insertBefore(tmpNode,pn); domUtils.remove(pn); rng.setStart(tmpNode,0).collapse(true); rng.select(true); } } } } }) }) }); function getStyle(node){ var cls = node.className; if(domUtils.hasClass(node,/custom_/)){ return cls.match(/custom_(\w+)/)[1] } return domUtils.getStyle(node, 'list-style-type') } me.addListener('beforepaste',function(type,html){ var me = this, rng = me.selection.getRange(),li; var root = UE.htmlparser(html.html,true); if(li = domUtils.findParentByTagName(rng.startContainer,'li',true)){ var list = li.parentNode,tagName = list.tagName == 'OL' ? 'ul':'ol'; utils.each(root.getNodesByTagName(tagName),function(n){ n.tagName = list.tagName; n.setAttr(); if(n.parentNode === root){ type = getStyle(list) || (list.tagName == 'OL' ? 'decimal' : 'disc') }else{ var className = n.parentNode.getAttr('class'); if(className && /custom_/.test(className)){ type = className.match(/custom_(\w+)/)[1] }else{ type = n.parentNode.getStyle('list-style-type'); } if(!type){ type = list.tagName == 'OL' ? 'decimal' : 'disc'; } } var index = utils.indexOf(listStyle[list.tagName], type); if(n.parentNode !== root) index = index + 1 == listStyle[list.tagName].length ? 0 : index + 1; var currentStyle = listStyle[list.tagName][index]; if(customStyle[currentStyle]){ n.setAttr('class', 'custom_' + currentStyle) }else{ n.setStyle('list-style-type',currentStyle) } }) } html.html = root.toHtml(); }); //进入编辑器的li要套p标签 me.addInputRule(function(root){ utils.each(root.getNodesByTagName('li'),function(li){ var tmpP = UE.uNode.createElement('p'); for(var i= 0,ci;ci=li.children[i];){ if(ci.type == 'text' || dtd.p[ci.tagName]){ tmpP.appendChild(ci); }else{ if(tmpP.firstChild()){ li.insertBefore(tmpP,ci); tmpP = UE.uNode.createElement('p'); i = i + 2; }else{ i++; } } } if(tmpP.firstChild() && !tmpP.parentNode || !li.firstChild()){ li.appendChild(tmpP); } //trace:3357 //p不能为空 if (!tmpP.firstChild()) { tmpP.innerHTML(browser.ie ? '&nbsp;' : '<br/>') } //去掉末尾的空白 var p = li.firstChild(); var lastChild = p.lastChild(); if(lastChild && lastChild.type == 'text' && /^\s*$/.test(lastChild.data)){ p.removeChild(lastChild) } }); var orderlisttype = { 'num1':/^\d+\)/, 'decimal':/^\d+\./, 'lower-alpha':/^[a-z]+\)/, 'upper-alpha':/^[A-Z]+\./, 'cn':/^[\u4E00\u4E8C\u4E09\u56DB\u516d\u4e94\u4e03\u516b\u4e5d]+[\u3001]/, 'cn2':/^\([\u4E00\u4E8C\u4E09\u56DB\u516d\u4e94\u4e03\u516b\u4e5d]+\)/ }, unorderlisttype = { 'square':'n' }; function checkListType(content,container){ var span = container.firstChild(); if(span && span.type == 'element' && span.tagName == 'span' && /Wingdings|Symbol/.test(span.getStyle('font-family'))){ for(var p in unorderlisttype){ if(unorderlisttype[p] == span.data){ return p } } return 'disc' } for(var p in orderlisttype){ if(orderlisttype[p].test(content)){ return p; } } } utils.each(root.getNodesByTagName('p'),function(node){ if(node.getAttr('class') != 'MsoListParagraph'){ return } //word粘贴过来的会带有margin要去掉,但这样也可能会误命中一些央视 node.setStyle('margin',''); node.setStyle('margin-left',''); node.setAttr('class',''); function appendLi(list,p,type){ if(list.tagName == 'ol'){ if(browser.ie){ var first = p.firstChild(); if(first.type =='element' && first.tagName == 'span' && orderlisttype[type].test(first.innerText())){ p.removeChild(first); } }else{ p.innerHTML(p.innerHTML().replace(orderlisttype[type],'')); } }else{ p.removeChild(p.firstChild()) } var li = UE.uNode.createElement('li'); li.appendChild(p); list.appendChild(li); } var tmp = node,type,cacheNode = node; if(node.parentNode.tagName != 'li' && (type = checkListType(node.innerText(),node))){ var list = UE.uNode.createElement(me.options.insertorderedlist.hasOwnProperty(type) ? 'ol' : 'ul'); if(customStyle[type]){ list.setAttr('class','custom_'+type) }else{ list.setStyle('list-style-type',type) } while(node && node.parentNode.tagName != 'li' && checkListType(node.innerText(),node)){ tmp = node.nextSibling(); if(!tmp){ node.parentNode.insertBefore(list,node) } appendLi(list,node,type); node = tmp; } if(!list.parentNode && node && node.parentNode){ node.parentNode.insertBefore(list,node) } } var span = cacheNode.firstChild(); if(span && span.type == 'element' && span.tagName == 'span' && /^\s*(&nbsp;)+\s*$/.test(span.innerText())){ span.parentNode.removeChild(span) } }) }); //调整索引标签 me.addListener('contentchange',function(){ adjustListStyle(me.document) }); function adjustListStyle(doc,ignore){ utils.each(domUtils.getElementsByTagName(doc,'ol ul'),function(node){ if(!domUtils.inDoc(node,doc)) return; var parent = node.parentNode; if(parent.tagName == node.tagName){ var nodeStyleType = getStyle(node) || (node.tagName == 'OL' ? 'decimal' : 'disc'), parentStyleType = getStyle(parent) || (parent.tagName == 'OL' ? 'decimal' : 'disc'); if(nodeStyleType == parentStyleType){ var styleIndex = utils.indexOf(listStyle[node.tagName], nodeStyleType); styleIndex = styleIndex + 1 == listStyle[node.tagName].length ? 0 : styleIndex + 1; setListStyle(node,listStyle[node.tagName][styleIndex]) } } var index = 0,type = 2; if( domUtils.hasClass(node,/custom_/)){ if(!(/[ou]l/i.test(parent.tagName) && domUtils.hasClass(parent,/custom_/))){ type = 1; } }else{ if(/[ou]l/i.test(parent.tagName) && domUtils.hasClass(parent,/custom_/)){ type = 3; } } var style = domUtils.getStyle(node, 'list-style-type'); style && (node.style.cssText = 'list-style-type:' + style); node.className = utils.trim(node.className.replace(/list-paddingleft-\w+/,'')) + ' list-paddingleft-' + type; utils.each(domUtils.getElementsByTagName(node,'li'),function(li){ li.style.cssText && (li.style.cssText = ''); if(!li.firstChild){ domUtils.remove(li); return; } if(li.parentNode !== node){ return; } index++; if(domUtils.hasClass(node,/custom_/) ){ var paddingLeft = 1,currentStyle = getStyle(node); if(node.tagName == 'OL'){ if(currentStyle){ switch(currentStyle){ case 'cn' : case 'cn1': case 'cn2': if(index > 10 && (index % 10 == 0 || index > 10 && index < 20)){ paddingLeft = 2 }else if(index > 20){ paddingLeft = 3 } break; case 'num2' : if(index > 9){ paddingLeft = 2 } } } li.className = 'list-'+customStyle[currentStyle]+ index + ' ' + 'list-'+currentStyle+'-paddingleft-' + paddingLeft; }else{ li.className = 'list-'+customStyle[currentStyle] + ' ' + 'list-'+currentStyle+'-paddingleft'; } }else{ li.className = li.className.replace(/list-[\w\-]+/gi,''); } var className = li.getAttribute('class'); if(className !== null && !className.replace(/\s/g,'')){ domUtils.removeAttributes(li,'class') } }); !ignore && adjustList(node,node.tagName.toLowerCase(),getStyle(node)||domUtils.getStyle(node, 'list-style-type'),true); }) } function adjustList(list, tag, style,ignoreEmpty) { var nextList = list.nextSibling; if (nextList && nextList.nodeType == 1 && nextList.tagName.toLowerCase() == tag && (getStyle(nextList) || domUtils.getStyle(nextList, 'list-style-type') || (tag == 'ol' ? 'decimal' : 'disc')) == style) { domUtils.moveChild(nextList, list); if (nextList.childNodes.length == 0) { domUtils.remove(nextList); } } if(nextList && domUtils.isFillChar(nextList)){ domUtils.remove(nextList); } var preList = list.previousSibling; if (preList && preList.nodeType == 1 && preList.tagName.toLowerCase() == tag && (getStyle(preList) || domUtils.getStyle(preList, 'list-style-type') || (tag == 'ol' ? 'decimal' : 'disc')) == style) { domUtils.moveChild(list, preList); } if(preList && domUtils.isFillChar(preList)){ domUtils.remove(preList); } !ignoreEmpty && domUtils.isEmptyBlock(list) && domUtils.remove(list); if(getStyle(list)){ adjustListStyle(list.ownerDocument,true) } } function setListStyle(list,style){ if(customStyle[style]){ list.className = 'custom_' + style; } try{ domUtils.setStyle(list, 'list-style-type', style); }catch(e){} } function clearEmptySibling(node) { var tmpNode = node.previousSibling; if (tmpNode && domUtils.isEmptyBlock(tmpNode)) { domUtils.remove(tmpNode); } tmpNode = node.nextSibling; if (tmpNode && domUtils.isEmptyBlock(tmpNode)) { domUtils.remove(tmpNode); } } me.addListener('keydown', function (type, evt) { function preventAndSave() { evt.preventDefault ? evt.preventDefault() : (evt.returnValue = false); me.fireEvent('contentchange'); me.undoManger && me.undoManger.save(); } function findList(node,filterFn){ while(node && !domUtils.isBody(node)){ if(filterFn(node)){ return null } if(node.nodeType == 1 && /[ou]l/i.test(node.tagName)){ return node; } node = node.parentNode; } return null; } var keyCode = evt.keyCode || evt.which; if (keyCode == 13 && !evt.shiftKey) {//回车 var rng = me.selection.getRange(), parent = domUtils.findParent(rng.startContainer,function(node){return domUtils.isBlockElm(node)},true), li = domUtils.findParentByTagName(rng.startContainer,'li',true); if(parent && parent.tagName != 'PRE' && !li){ var html = parent.innerHTML.replace(new RegExp(domUtils.fillChar, 'g'),''); if(/^\s*1\s*\.[^\d]/.test(html)){ parent.innerHTML = html.replace(/^\s*1\s*\./,''); rng.setStartAtLast(parent).collapse(true).select(); me.__hasEnterExecCommand = true; me.execCommand('insertorderedlist'); me.__hasEnterExecCommand = false; } } var range = me.selection.getRange(), start = findList(range.startContainer,function (node) { return node.tagName == 'TABLE'; }), end = range.collapsed ? start : findList(range.endContainer,function (node) { return node.tagName == 'TABLE'; }); if (start && end && start === end) { if (!range.collapsed) { start = domUtils.findParentByTagName(range.startContainer, 'li', true); end = domUtils.findParentByTagName(range.endContainer, 'li', true); if (start && end && start === end) { range.deleteContents(); li = domUtils.findParentByTagName(range.startContainer, 'li', true); if (li && domUtils.isEmptyBlock(li)) { pre = li.previousSibling; next = li.nextSibling; p = me.document.createElement('p'); domUtils.fillNode(me.document, p); parentList = li.parentNode; if (pre && next) { range.setStart(next, 0).collapse(true).select(true); domUtils.remove(li); } else { if (!pre && !next || !pre) { parentList.parentNode.insertBefore(p, parentList); } else { li.parentNode.parentNode.insertBefore(p, parentList.nextSibling); } domUtils.remove(li); if (!parentList.firstChild) { domUtils.remove(parentList); } range.setStart(p, 0).setCursor(); } preventAndSave(); return; } } else { var tmpRange = range.cloneRange(), bk = tmpRange.collapse(false).createBookmark(); range.deleteContents(); tmpRange.moveToBookmark(bk); var li = domUtils.findParentByTagName(tmpRange.startContainer, 'li', true); clearEmptySibling(li); tmpRange.select(); preventAndSave(); return; } } li = domUtils.findParentByTagName(range.startContainer, 'li', true); if (li) { if (domUtils.isEmptyBlock(li)) { bk = range.createBookmark(); var parentList = li.parentNode; if (li !== parentList.lastChild) { domUtils.breakParent(li, parentList); clearEmptySibling(li); } else { parentList.parentNode.insertBefore(li, parentList.nextSibling); if (domUtils.isEmptyNode(parentList)) { domUtils.remove(parentList); } } //嵌套不处理 if (!dtd.$list[li.parentNode.tagName]) { if (!domUtils.isBlockElm(li.firstChild)) { p = me.document.createElement('p'); li.parentNode.insertBefore(p, li); while (li.firstChild) { p.appendChild(li.firstChild); } domUtils.remove(li); } else { domUtils.remove(li, true); } } range.moveToBookmark(bk).select(); } else { var first = li.firstChild; if (!first || !domUtils.isBlockElm(first)) { var p = me.document.createElement('p'); !li.firstChild && domUtils.fillNode(me.document, p); while (li.firstChild) { p.appendChild(li.firstChild); } li.appendChild(p); first = p; } var span = me.document.createElement('span'); range.insertNode(span); domUtils.breakParent(span, li); var nextLi = span.nextSibling; first = nextLi.firstChild; if (!first) { p = me.document.createElement('p'); domUtils.fillNode(me.document, p); nextLi.appendChild(p); first = p; } if (domUtils.isEmptyNode(first)) { first.innerHTML = ''; domUtils.fillNode(me.document, first); } range.setStart(first, 0).collapse(true).shrinkBoundary().select(); domUtils.remove(span); var pre = nextLi.previousSibling; if (pre && domUtils.isEmptyBlock(pre)) { pre.innerHTML = '<p></p>'; domUtils.fillNode(me.document, pre.firstChild); } } // } preventAndSave(); } } } if (keyCode == 8) { //修中ie中li下的问题 range = me.selection.getRange(); if (range.collapsed && domUtils.isStartInblock(range)) { tmpRange = range.cloneRange().trimBoundary(); li = domUtils.findParentByTagName(range.startContainer, 'li', true); //要在li的最左边,才能处理 if (li && domUtils.isStartInblock(tmpRange)) { start = domUtils.findParentByTagName(range.startContainer, 'p', true); if (start && start !== li.firstChild) { var parentList = domUtils.findParentByTagName(start,['ol','ul']); domUtils.breakParent(start,parentList); clearEmptySibling(start); me.fireEvent('contentchange'); range.setStart(start,0).setCursor(false,true); me.fireEvent('saveScene'); domUtils.preventDefault(evt); return; } if (li && (pre = li.previousSibling)) { if (keyCode == 46 && li.childNodes.length) { return; } //有可能上边的兄弟节点是个2级菜单,要追加到2级菜单的最后的li if (dtd.$list[pre.tagName]) { pre = pre.lastChild; } me.undoManger && me.undoManger.save(); first = li.firstChild; if (domUtils.isBlockElm(first)) { if (domUtils.isEmptyNode(first)) { // range.setEnd(pre, pre.childNodes.length).shrinkBoundary().collapse().select(true); pre.appendChild(first); range.setStart(first, 0).setCursor(false, true); //first不是唯一的节点 while (li.firstChild) { pre.appendChild(li.firstChild); } } else { span = me.document.createElement('span'); range.insertNode(span); //判断pre是否是空的节点,如果是<p><br/></p>类型的空节点,干掉p标签防止它占位 if (domUtils.isEmptyBlock(pre)) { pre.innerHTML = ''; } domUtils.moveChild(li, pre); range.setStartBefore(span).collapse(true).select(true); domUtils.remove(span); } } else { if (domUtils.isEmptyNode(li)) { var p = me.document.createElement('p'); pre.appendChild(p); range.setStart(p, 0).setCursor(); // range.setEnd(pre, pre.childNodes.length).shrinkBoundary().collapse().select(true); } else { range.setEnd(pre, pre.childNodes.length).collapse().select(true); while (li.firstChild) { pre.appendChild(li.firstChild); } } } domUtils.remove(li); me.fireEvent('contentchange'); me.fireEvent('saveScene'); domUtils.preventDefault(evt); return; } //trace:980 if (li && !li.previousSibling) { var parentList = li.parentNode; var bk = range.createBookmark(); if(domUtils.isTagNode(parentList.parentNode,'ol ul')){ parentList.parentNode.insertBefore(li,parentList); if(domUtils.isEmptyNode(parentList)){ domUtils.remove(parentList) } }else{ while(li.firstChild){ parentList.parentNode.insertBefore(li.firstChild,parentList); } domUtils.remove(li); if(domUtils.isEmptyNode(parentList)){ domUtils.remove(parentList) } } range.moveToBookmark(bk).setCursor(false,true); me.fireEvent('contentchange'); me.fireEvent('saveScene'); domUtils.preventDefault(evt); return; } } } } }); me.addListener('keyup',function(type, evt){ var keyCode = evt.keyCode || evt.which; if (keyCode == 8) { var rng = me.selection.getRange(),list; if(list = domUtils.findParentByTagName(rng.startContainer,['ol', 'ul'],true)){ adjustList(list,list.tagName.toLowerCase(),getStyle(list)||domUtils.getComputedStyle(list,'list-style-type'),true) } } }); //处理tab键 me.addListener('tabkeydown',function(){ var range = me.selection.getRange(); //控制级数 function checkLevel(li){ if(me.options.maxListLevel != -1){ var level = li.parentNode,levelNum = 0; while(/[ou]l/i.test(level.tagName)){ levelNum++; level = level.parentNode; } if(levelNum >= me.options.maxListLevel){ return true; } } } //只以开始为准 //todo 后续改进 var li = domUtils.findParentByTagName(range.startContainer, 'li', true); if(li){ var bk; if(range.collapsed){ if(checkLevel(li)) return true; var parentLi = li.parentNode, list = me.document.createElement(parentLi.tagName), index = utils.indexOf(listStyle[list.tagName], getStyle(parentLi)||domUtils.getComputedStyle(parentLi, 'list-style-type')); index = index + 1 == listStyle[list.tagName].length ? 0 : index + 1; var currentStyle = listStyle[list.tagName][index]; setListStyle(list,currentStyle); if(domUtils.isStartInblock(range)){ me.fireEvent('saveScene'); bk = range.createBookmark(); parentLi.insertBefore(list, li); list.appendChild(li); adjustList(list,list.tagName.toLowerCase(),currentStyle); me.fireEvent('contentchange'); range.moveToBookmark(bk).select(true); return true; } }else{ me.fireEvent('saveScene'); bk = range.createBookmark(); for(var i= 0,closeList,parents = domUtils.findParents(li),ci;ci=parents[i++];){ if(domUtils.isTagNode(ci,'ol ul')){ closeList = ci; break; } } var current = li; if(bk.end){ while(current && !(domUtils.getPosition(current, bk.end) & domUtils.POSITION_FOLLOWING)){ if(checkLevel(current)){ current = domUtils.getNextDomNode(current,false,null,function(node){return node !== closeList}); continue; } var parentLi = current.parentNode, list = me.document.createElement(parentLi.tagName), index = utils.indexOf(listStyle[list.tagName], getStyle(parentLi)||domUtils.getComputedStyle(parentLi, 'list-style-type')); var currentIndex = index + 1 == listStyle[list.tagName].length ? 0 : index + 1; var currentStyle = listStyle[list.tagName][currentIndex]; setListStyle(list,currentStyle); parentLi.insertBefore(list, current); while(current && !(domUtils.getPosition(current, bk.end) & domUtils.POSITION_FOLLOWING)){ li = current.nextSibling; list.appendChild(current); if(!li || domUtils.isTagNode(li,'ol ul')){ if(li){ while(li = li.firstChild){ if(li.tagName == 'LI'){ break; } } }else{ li = domUtils.getNextDomNode(current,false,null,function(node){return node !== closeList}); } break; } current = li; } adjustList(list,list.tagName.toLowerCase(),currentStyle); current = li; } } me.fireEvent('contentchange'); range.moveToBookmark(bk).select(); return true; } } }); function getLi(start){ while(start && !domUtils.isBody(start)){ if(start.nodeName == 'TABLE'){ return null; } if(start.nodeName == 'LI'){ return start } start = start.parentNode; } } me.commands['insertorderedlist'] = me.commands['insertunorderedlist'] = { execCommand:function (command, style) { if (!style) { style = command.toLowerCase() == 'insertorderedlist' ? 'decimal' : 'disc'; } var me = this, range = this.selection.getRange(), filterFn = function (node) { return node.nodeType == 1 ? node.tagName.toLowerCase() != 'br' : !domUtils.isWhitespace(node); }, tag = command.toLowerCase() == 'insertorderedlist' ? 'ol' : 'ul', frag = me.document.createDocumentFragment(); //去掉是因为会出现选到末尾,导致adjustmentBoundary缩到ol/ul的位置 //range.shrinkBoundary();//.adjustmentBoundary(); range.adjustmentBoundary().shrinkBoundary(); var bko = range.createBookmark(true), start = getLi(me.document.getElementById(bko.start)), modifyStart = 0, end = getLi(me.document.getElementById(bko.end)), modifyEnd = 0, startParent, endParent, list, tmp; if (start || end) { start && (startParent = start.parentNode); if (!bko.end) { end = start; } end && (endParent = end.parentNode); if (startParent === endParent) { while (start !== end) { tmp = start; start = start.nextSibling; if (!domUtils.isBlockElm(tmp.firstChild)) { var p = me.document.createElement('p'); while (tmp.firstChild) { p.appendChild(tmp.firstChild); } tmp.appendChild(p); } frag.appendChild(tmp); } tmp = me.document.createElement('span'); startParent.insertBefore(tmp, end); if (!domUtils.isBlockElm(end.firstChild)) { p = me.document.createElement('p'); while (end.firstChild) { p.appendChild(end.firstChild); } end.appendChild(p); } frag.appendChild(end); domUtils.breakParent(tmp, startParent); if (domUtils.isEmptyNode(tmp.previousSibling)) { domUtils.remove(tmp.previousSibling); } if (domUtils.isEmptyNode(tmp.nextSibling)) { domUtils.remove(tmp.nextSibling) } var nodeStyle = getStyle(startParent) || domUtils.getComputedStyle(startParent, 'list-style-type') || (command.toLowerCase() == 'insertorderedlist' ? 'decimal' : 'disc'); if (startParent.tagName.toLowerCase() == tag && nodeStyle == style) { for (var i = 0, ci, tmpFrag = me.document.createDocumentFragment(); ci = frag.childNodes[i++];) { if(domUtils.isTagNode(ci,'ol ul')){ utils.each(domUtils.getElementsByTagName(ci,'li'),function(li){ while(li.firstChild){ tmpFrag.appendChild(li.firstChild); } }); }else{ while (ci.firstChild) { tmpFrag.appendChild(ci.firstChild); } } } tmp.parentNode.insertBefore(tmpFrag, tmp); } else { list = me.document.createElement(tag); setListStyle(list,style); list.appendChild(frag); tmp.parentNode.insertBefore(list, tmp); } domUtils.remove(tmp); list && adjustList(list, tag, style); range.moveToBookmark(bko).select(); return; } //开始 if (start) { while (start) { tmp = start.nextSibling; if (domUtils.isTagNode(start, 'ol ul')) { frag.appendChild(start); } else { var tmpfrag = me.document.createDocumentFragment(), hasBlock = 0; while (start.firstChild) { if (domUtils.isBlockElm(start.firstChild)) { hasBlock = 1; } tmpfrag.appendChild(start.firstChild); } if (!hasBlock) { var tmpP = me.document.createElement('p'); tmpP.appendChild(tmpfrag); frag.appendChild(tmpP); } else { frag.appendChild(tmpfrag); } domUtils.remove(start); } start = tmp; } startParent.parentNode.insertBefore(frag, startParent.nextSibling); if (domUtils.isEmptyNode(startParent)) { range.setStartBefore(startParent); domUtils.remove(startParent); } else { range.setStartAfter(startParent); } modifyStart = 1; } if (end && domUtils.inDoc(endParent, me.document)) { //结束 start = endParent.firstChild; while (start && start !== end) { tmp = start.nextSibling; if (domUtils.isTagNode(start, 'ol ul')) { frag.appendChild(start); } else { tmpfrag = me.document.createDocumentFragment(); hasBlock = 0; while (start.firstChild) { if (domUtils.isBlockElm(start.firstChild)) { hasBlock = 1; } tmpfrag.appendChild(start.firstChild); } if (!hasBlock) { tmpP = me.document.createElement('p'); tmpP.appendChild(tmpfrag); frag.appendChild(tmpP); } else { frag.appendChild(tmpfrag); } domUtils.remove(start); } start = tmp; } var tmpDiv = domUtils.createElement(me.document, 'div', { 'tmpDiv':1 }); domUtils.moveChild(end, tmpDiv); frag.appendChild(tmpDiv); domUtils.remove(end); endParent.parentNode.insertBefore(frag, endParent); range.setEndBefore(endParent); if (domUtils.isEmptyNode(endParent)) { domUtils.remove(endParent); } modifyEnd = 1; } } if (!modifyStart) { range.setStartBefore(me.document.getElementById(bko.start)); } if (bko.end && !modifyEnd) { range.setEndAfter(me.document.getElementById(bko.end)); } range.enlarge(true, function (node) { return notExchange[node.tagName]; }); frag = me.document.createDocumentFragment(); var bk = range.createBookmark(), current = domUtils.getNextDomNode(bk.start, false, filterFn), tmpRange = range.cloneRange(), tmpNode, block = domUtils.isBlockElm; while (current && current !== bk.end && (domUtils.getPosition(current, bk.end) & domUtils.POSITION_PRECEDING)) { if (current.nodeType == 3 || dtd.li[current.tagName]) { if (current.nodeType == 1 && dtd.$list[current.tagName]) { while (current.firstChild) { frag.appendChild(current.firstChild); } tmpNode = domUtils.getNextDomNode(current, false, filterFn); domUtils.remove(current); current = tmpNode; continue; } tmpNode = current; tmpRange.setStartBefore(current); while (current && current !== bk.end && (!block(current) || domUtils.isBookmarkNode(current) )) { tmpNode = current; current = domUtils.getNextDomNode(current, false, null, function (node) { return !notExchange[node.tagName]; }); } if (current && block(current)) { tmp = domUtils.getNextDomNode(tmpNode, false, filterFn); if (tmp && domUtils.isBookmarkNode(tmp)) { current = domUtils.getNextDomNode(tmp, false, filterFn); tmpNode = tmp; } } tmpRange.setEndAfter(tmpNode); current = domUtils.getNextDomNode(tmpNode, false, filterFn); var li = range.document.createElement('li'); li.appendChild(tmpRange.extractContents()); if(domUtils.isEmptyNode(li)){ var tmpNode = range.document.createElement('p'); while(li.firstChild){ tmpNode.appendChild(li.firstChild) } li.appendChild(tmpNode); } frag.appendChild(li); } else { current = domUtils.getNextDomNode(current, true, filterFn); } } range.moveToBookmark(bk).collapse(true); list = me.document.createElement(tag); setListStyle(list,style); list.appendChild(frag); range.insertNode(list); //当前list上下看能否合并 adjustList(list, tag, style); //去掉冗余的tmpDiv for (var i = 0, ci, tmpDivs = domUtils.getElementsByTagName(list, 'div'); ci = tmpDivs[i++];) { if (ci.getAttribute('tmpDiv')) { domUtils.remove(ci, true) } } range.moveToBookmark(bko).select(); }, queryCommandState:function (command) { var tag = command.toLowerCase() == 'insertorderedlist' ? 'ol' : 'ul'; var path = this.selection.getStartElementPath(); for(var i= 0,ci;ci = path[i++];){ if(ci.nodeName == 'TABLE'){ return 0 } if(tag == ci.nodeName.toLowerCase()){ return 1 }; } return 0; }, queryCommandValue:function (command) { var tag = command.toLowerCase() == 'insertorderedlist' ? 'ol' : 'ul'; var path = this.selection.getStartElementPath(), node; for(var i= 0,ci;ci = path[i++];){ if(ci.nodeName == 'TABLE'){ node = null; break; } if(tag == ci.nodeName.toLowerCase()){ node = ci; break; }; } return node ? getStyle(node) || domUtils.getComputedStyle(node, 'list-style-type') : null; } }; }; ///import core ///import plugins/serialize.js ///import plugins/undo.js ///commands 查看源码 ///commandsName Source ///commandsTitle 查看源码 (function (){ var sourceEditors = { textarea: function (editor, holder){ var textarea = holder.ownerDocument.createElement('textarea'); textarea.style.cssText = 'position:absolute;resize:none;width:100%;height:100%;border:0;padding:0;margin:0;overflow-y:auto;'; // todo: IE下只有onresize属性可用... 很纠结 if (browser.ie && browser.version < 8) { textarea.style.width = holder.offsetWidth + 'px'; textarea.style.height = holder.offsetHeight + 'px'; holder.onresize = function (){ textarea.style.width = holder.offsetWidth + 'px'; textarea.style.height = holder.offsetHeight + 'px'; }; } holder.appendChild(textarea); return { setContent: function (content){ textarea.value = content; }, getContent: function (){ return textarea.value; }, select: function (){ var range; if (browser.ie) { range = textarea.createTextRange(); range.collapse(true); range.select(); } else { //todo: chrome下无法设置焦点 textarea.setSelectionRange(0, 0); textarea.focus(); } }, dispose: function (){ holder.removeChild(textarea); // todo holder.onresize = null; textarea = null; holder = null; } }; }, codemirror: function (editor, holder){ var codeEditor = window.CodeMirror(holder, { mode: "text/html", tabMode: "indent", lineNumbers: true, lineWrapping:true }); var dom = codeEditor.getWrapperElement(); dom.style.cssText = 'position:absolute;left:0;top:0;width:100%;height:100%;font-family:consolas,"Courier new",monospace;font-size:13px;'; codeEditor.getScrollerElement().style.cssText = 'position:absolute;left:0;top:0;width:100%;height:100%;'; codeEditor.refresh(); return { getCodeMirror:function(){ return codeEditor; }, setContent: function (content){ codeEditor.setValue(content); }, getContent: function (){ return codeEditor.getValue(); }, select: function (){ codeEditor.focus(); }, dispose: function (){ holder.removeChild(dom); dom = null; codeEditor = null; } }; } }; UE.plugins['source'] = function (){ var me = this; var opt = this.options; var sourceMode = false; var sourceEditor; opt.sourceEditor = browser.ie ? 'textarea' : (opt.sourceEditor || 'codemirror'); me.setOpt({ sourceEditorFirst:false }); function createSourceEditor(holder){ return sourceEditors[opt.sourceEditor == 'codemirror' && window.CodeMirror ? 'codemirror' : 'textarea'](me, holder); } var bakCssText; //解决在源码模式下getContent不能得到最新的内容问题 var oldGetContent = me.getContent, bakAddress; me.commands['source'] = { execCommand: function (){ sourceMode = !sourceMode; if (sourceMode) { bakAddress = me.selection.getRange().createAddress(false,true); me.undoManger && me.undoManger.save(true); if(browser.gecko){ me.body.contentEditable = false; } bakCssText = me.iframe.style.cssText; me.iframe.style.cssText += 'position:absolute;left:-32768px;top:-32768px;'; me.fireEvent('beforegetcontent'); var root = UE.htmlparser(me.body.innerHTML); me.filterOutputRule(root); root.traversal(function (node) { if (node.type == 'element') { switch (node.tagName) { case 'td': case 'th': case 'caption': if(node.children && node.children.length == 1){ if(node.firstChild().tagName == 'br' ){ node.removeChild(node.firstChild()) } }; break; case 'pre': node.innerText(node.innerText().replace(/&nbsp;/g,' ')) } } }); me.fireEvent('aftergetcontent'); var content = root.toHtml(true); sourceEditor = createSourceEditor(me.iframe.parentNode); sourceEditor.setContent(content); setTimeout(function (){ sourceEditor.select(); me.addListener('fullscreenchanged', function(){ try{ sourceEditor.getCodeMirror().refresh() }catch(e){} }); }); //重置getContent,源码模式下取值也能是最新的数据 me.getContent = function (){ return sourceEditor.getContent() || '<p>' + (browser.ie ? '' : '<br/>')+'</p>'; }; } else { me.iframe.style.cssText = bakCssText; var cont = sourceEditor.getContent() || '<p>' + (browser.ie ? '' : '<br/>')+'</p>'; //处理掉block节点前后的空格,有可能会误命中,暂时不考虑 cont = cont.replace(new RegExp('[\\r\\t\\n ]*<\/?(\\w+)\\s*(?:[^>]*)>','g'), function(a,b){ if(b && !dtd.$inlineWithA[b.toLowerCase()]){ return a.replace(/(^[\n\r\t ]*)|([\n\r\t ]*$)/g,''); } return a.replace(/(^[\n\r\t]*)|([\n\r\t]*$)/g,'') }); me.setContent(cont); sourceEditor.dispose(); sourceEditor = null; //还原getContent方法 me.getContent = oldGetContent; var first = me.body.firstChild; //trace:1106 都删除空了,下边会报错,所以补充一个p占位 if(!first){ me.body.innerHTML = '<p>'+(browser.ie?'':'<br/>')+'</p>'; first = me.body.firstChild; } //要在ifm为显示时ff才能取到selection,否则报错 //这里不能比较位置了 me.undoManger && me.undoManger.save(true); if(browser.gecko){ var input = document.createElement('input'); input.style.cssText = 'position:absolute;left:0;top:-32768px'; document.body.appendChild(input); me.body.contentEditable = false; setTimeout(function(){ domUtils.setViewportOffset(input, { left: -32768, top: 0 }); input.focus(); setTimeout(function(){ me.body.contentEditable = true; me.selection.getRange().moveToAddress(bakAddress).select(true); domUtils.remove(input); }); }); }else{ //ie下有可能报错,比如在代码顶头的情况 try{ me.selection.getRange().moveToAddress(bakAddress).select(true); }catch(e){} } } this.fireEvent('sourcemodechanged', sourceMode); }, queryCommandState: function (){ return sourceMode|0; }, notNeedUndo : 1 }; var oldQueryCommandState = me.queryCommandState; me.queryCommandState = function (cmdName){ cmdName = cmdName.toLowerCase(); if (sourceMode) { //源码模式下可以开启的命令 return cmdName in { 'source' : 1, 'fullscreen' : 1 } ? 1 : -1 } return oldQueryCommandState.apply(this, arguments); }; if(opt.sourceEditor == "codemirror"){ me.addListener("ready",function(){ utils.loadFile(document,{ src : opt.codeMirrorJsUrl || opt.UEDITOR_HOME_URL + "third-party/codemirror/codemirror.js", tag : "script", type : "text/javascript", defer : "defer" },function(){ if(opt.sourceEditorFirst){ setTimeout(function(){ me.execCommand("source"); },0); } }); utils.loadFile(document,{ tag : "link", rel : "stylesheet", type : "text/css", href : opt.codeMirrorCssUrl || opt.UEDITOR_HOME_URL + "third-party/codemirror/codemirror.css" }); }); } }; })();///import core ///import plugins/undo.js ///commands 设置回车标签p或br ///commandsName EnterKey ///commandsTitle 设置回车标签p或br /** * @description 处理回车 * @author zhanyi */ UE.plugins['enterkey'] = function() { var hTag, me = this, tag = me.options.enterTag; me.addListener('keyup', function(type, evt) { var keyCode = evt.keyCode || evt.which; if (keyCode == 13) { var range = me.selection.getRange(), start = range.startContainer, doSave; //修正在h1-h6里边回车后不能嵌套p的问题 if (!browser.ie) { if (/h\d/i.test(hTag)) { if (browser.gecko) { var h = domUtils.findParentByTagName(start, [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6','blockquote','caption','table'], true); if (!h) { me.document.execCommand('formatBlock', false, '<p>'); doSave = 1; } } else { //chrome remove div if (start.nodeType == 1) { var tmp = me.document.createTextNode(''),div; range.insertNode(tmp); div = domUtils.findParentByTagName(tmp, 'div', true); if (div) { var p = me.document.createElement('p'); while (div.firstChild) { p.appendChild(div.firstChild); } div.parentNode.insertBefore(p, div); domUtils.remove(div); range.setStartBefore(tmp).setCursor(); doSave = 1; } domUtils.remove(tmp); } } if (me.undoManger && doSave) { me.undoManger.save(); } } //没有站位符,会出现多行的问题 browser.opera && range.select(); }else{ me.fireEvent('saveScene',true,true) } } }); me.addListener('keydown', function(type, evt) { var keyCode = evt.keyCode || evt.which; if (keyCode == 13) {//回车 if(me.fireEvent('beforeenterkeydown')){ domUtils.preventDefault(evt); return; } me.fireEvent('saveScene',true,true); hTag = ''; var range = me.selection.getRange(); if (!range.collapsed) { //跨td不能删 var start = range.startContainer, end = range.endContainer, startTd = domUtils.findParentByTagName(start, 'td', true), endTd = domUtils.findParentByTagName(end, 'td', true); if (startTd && endTd && startTd !== endTd || !startTd && endTd || startTd && !endTd) { evt.preventDefault ? evt.preventDefault() : ( evt.returnValue = false); return; } } if (tag == 'p') { if (!browser.ie) { start = domUtils.findParentByTagName(range.startContainer, ['ol','ul','p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6','blockquote','caption'], true); //opera下执行formatblock会在table的场景下有问题,回车在opera原生支持很好,所以暂时在opera去掉调用这个原生的command //trace:2431 if (!start && !browser.opera) { me.document.execCommand('formatBlock', false, '<p>'); if (browser.gecko) { range = me.selection.getRange(); start = domUtils.findParentByTagName(range.startContainer, 'p', true); start && domUtils.removeDirtyAttr(start); } } else { hTag = start.tagName; start.tagName.toLowerCase() == 'p' && browser.gecko && domUtils.removeDirtyAttr(start); } } } else { evt.preventDefault ? evt.preventDefault() : ( evt.returnValue = false); if (!range.collapsed) { range.deleteContents(); start = range.startContainer; if (start.nodeType == 1 && (start = start.childNodes[range.startOffset])) { while (start.nodeType == 1) { if (dtd.$empty[start.tagName]) { range.setStartBefore(start).setCursor(); if (me.undoManger) { me.undoManger.save(); } return false; } if (!start.firstChild) { var br = range.document.createElement('br'); start.appendChild(br); range.setStart(start, 0).setCursor(); if (me.undoManger) { me.undoManger.save(); } return false; } start = start.firstChild; } if (start === range.startContainer.childNodes[range.startOffset]) { br = range.document.createElement('br'); range.insertNode(br).setCursor(); } else { range.setStart(start, 0).setCursor(); } } else { br = range.document.createElement('br'); range.insertNode(br).setStartAfter(br).setCursor(); } } else { br = range.document.createElement('br'); range.insertNode(br); var parent = br.parentNode; if (parent.lastChild === br) { br.parentNode.insertBefore(br.cloneNode(true), br); range.setStartBefore(br); } else { range.setStartAfter(br); } range.setCursor(); } } } }); }; /* * 处理特殊键的兼容性问题 */ UE.plugins['keystrokes'] = function() { var me = this; var collapsed = true; me.addListener('keydown', function(type, evt) { var keyCode = evt.keyCode || evt.which, rng = me.selection.getRange(); //处理全选的情况 if(!rng.collapsed && !(evt.ctrlKey || evt.shiftKey || evt.altKey || evt.metaKey) && (keyCode >= 65 && keyCode <=90 || keyCode >= 48 && keyCode <= 57 || keyCode >= 96 && keyCode <= 111 || { 13:1, 8:1, 46:1 }[keyCode]) ){ var tmpNode = rng.startContainer; if(domUtils.isFillChar(tmpNode)){ rng.setStartBefore(tmpNode) } tmpNode = rng.endContainer; if(domUtils.isFillChar(tmpNode)){ rng.setEndAfter(tmpNode) } rng.txtToElmBoundary(); //结束边界可能放到了br的前边,要把br包含进来 // x[xxx]<br/> if(rng.endContainer && rng.endContainer.nodeType == 1){ tmpNode = rng.endContainer.childNodes[rng.endOffset]; if(tmpNode && domUtils.isBr(tmpNode)){ rng.setEndAfter(tmpNode); } } if(rng.startOffset == 0){ tmpNode = rng.startContainer; if(domUtils.isBoundaryNode(tmpNode,'firstChild') ){ tmpNode = rng.endContainer; if(rng.endOffset == (tmpNode.nodeType == 3 ? tmpNode.nodeValue.length : tmpNode.childNodes.length) && domUtils.isBoundaryNode(tmpNode,'lastChild')){ me.fireEvent('saveScene'); me.body.innerHTML = '<p>'+(browser.ie ? '' : '<br/>')+'</p>'; rng.setStart(me.body.firstChild,0).setCursor(false,true); me._selectionChange(); return; } } } } //处理backspace if (keyCode == 8) { rng = me.selection.getRange(); collapsed = rng.collapsed; if(me.fireEvent('delkeydown',evt)){ return; } var start,end; //避免按两次删除才能生效的问题 if(rng.collapsed && rng.inFillChar()){ start = rng.startContainer; if(domUtils.isFillChar(start)){ rng.setStartBefore(start).shrinkBoundary(true).collapse(true); domUtils.remove(start) }else{ start.nodeValue = start.nodeValue.replace(new RegExp('^' + domUtils.fillChar ),''); rng.startOffset--; rng.collapse(true).select(true) } } //解决选中control元素不能删除的问题 if (start = rng.getClosedNode()) { me.fireEvent('saveScene'); rng.setStartBefore(start); domUtils.remove(start); rng.setCursor(); me.fireEvent('saveScene'); domUtils.preventDefault(evt); return; } //阻止在table上的删除 if (!browser.ie) { start = domUtils.findParentByTagName(rng.startContainer, 'table', true); end = domUtils.findParentByTagName(rng.endContainer, 'table', true); if (start && !end || !start && end || start !== end) { evt.preventDefault(); return; } } } //处理tab键的逻辑 if (keyCode == 9) { //不处理以下标签 var excludeTagNameForTabKey = { 'ol' : 1, 'ul' : 1, 'table':1 }; //处理组件里的tab按下事件 if(me.fireEvent('tabkeydown',evt)){ domUtils.preventDefault(evt); return; } var range = me.selection.getRange(); me.fireEvent('saveScene'); for (var i = 0,txt = '',tabSize = me.options.tabSize|| 4,tabNode = me.options.tabNode || '&nbsp;'; i < tabSize; i++) { txt += tabNode; } var span = me.document.createElement('span'); span.innerHTML = txt + domUtils.fillChar; if (range.collapsed) { range.insertNode(span.cloneNode(true).firstChild).setCursor(true); } else { //普通的情况 start = domUtils.findParent(range.startContainer, filterFn); end = domUtils.findParent(range.endContainer, filterFn); if (start && end && start === end) { range.deleteContents(); range.insertNode(span.cloneNode(true).firstChild).setCursor(true); } else { var bookmark = range.createBookmark(), filterFn = function(node) { return domUtils.isBlockElm(node) && !excludeTagNameForTabKey[node.tagName.toLowerCase()] }; range.enlarge(true); var bookmark2 = range.createBookmark(), current = domUtils.getNextDomNode(bookmark2.start, false, filterFn); while (current && !(domUtils.getPosition(current, bookmark2.end) & domUtils.POSITION_FOLLOWING)) { current.insertBefore(span.cloneNode(true).firstChild, current.firstChild); current = domUtils.getNextDomNode(current, false, filterFn); } range.moveToBookmark(bookmark2).moveToBookmark(bookmark).select(); } } domUtils.preventDefault(evt) } //trace:1634 //ff的del键在容器空的时候,也会删除 if(browser.gecko && keyCode == 46){ range = me.selection.getRange(); if(range.collapsed){ start = range.startContainer; if(domUtils.isEmptyBlock(start)){ var parent = start.parentNode; while(domUtils.getChildCount(parent) == 1 && !domUtils.isBody(parent)){ start = parent; parent = parent.parentNode; } if(start === parent.lastChild) evt.preventDefault(); return; } } } }); me.addListener('keyup', function(type, evt) { var keyCode = evt.keyCode || evt.which, rng,me = this; if(keyCode == 8){ if(me.fireEvent('delkeyup')){ return; } rng = me.selection.getRange(); if(rng.collapsed){ var tmpNode, autoClearTagName = ['h1','h2','h3','h4','h5','h6']; if(tmpNode = domUtils.findParentByTagName(rng.startContainer,autoClearTagName,true)){ if(domUtils.isEmptyBlock(tmpNode)){ var pre = tmpNode.previousSibling; if(pre && pre.nodeName != 'TABLE'){ domUtils.remove(tmpNode); rng.setStartAtLast(pre).setCursor(false,true); return; }else{ var next = tmpNode.nextSibling; if(next && next.nodeName != 'TABLE'){ domUtils.remove(tmpNode); rng.setStartAtFirst(next).setCursor(false,true); return; } } } } //处理当删除到body时,要重新给p标签展位 if(domUtils.isBody(rng.startContainer)){ var tmpNode = domUtils.createElement(me.document,'p',{ 'innerHTML' : browser.ie ? domUtils.fillChar : '<br/>' }); rng.insertNode(tmpNode).setStart(tmpNode,0).setCursor(false,true); } } //chrome下如果删除了inline标签,浏览器会有记忆,在输入文字还是会套上刚才删除的标签,所以这里再选一次就不会了 if( !collapsed && (rng.startContainer.nodeType == 3 || rng.startContainer.nodeType == 1 && domUtils.isEmptyBlock(rng.startContainer))){ if(browser.ie){ var span = rng.document.createElement('span'); rng.insertNode(span).setStartBefore(span).collapse(true); rng.select(); domUtils.remove(span) }else{ rng.select() } } } }) };///import core ///commands 修复chrome下图片不能点击的问题 ///commandsName FixImgClick ///commandsTitle 修复chrome下图片不能点击的问题 //修复chrome下图片不能点击的问题 //todo 可以改大小 UE.plugins['fiximgclick'] = function() { var me = this; if ( browser.webkit ) { me.addListener( 'click', function( type, e ) { if ( e.target.tagName == 'IMG' ) { var range = new dom.Range( me.document ); range.selectNode( e.target ).select(); } } ); } };/** * @description 纯文本粘贴 * @name puretxtpaste * @author zhanyi */ UE.plugins['pasteplain'] = function(){ var me = this; me.setOpt({ 'pasteplain':false, 'filterTxtRules' : function(){ function transP(node){ node.tagName = 'p'; node.setStyle(); } function removeNode(node){ node.parentNode.removeChild(node,true) } return { //直接删除及其字节点内容 '-' : 'script style object iframe embed input select', 'p': {$:{}}, 'br':{$:{}}, div: function (node) { var tmpNode, p = UE.uNode.createElement('p'); while (tmpNode = node.firstChild()) { if (tmpNode.type == 'text' || !UE.dom.dtd.$block[tmpNode.tagName]) { p.appendChild(tmpNode); } else { if (p.firstChild()) { node.parentNode.insertBefore(p, node); p = UE.uNode.createElement('p'); } else { node.parentNode.insertBefore(tmpNode, node); } } } if (p.firstChild()) { node.parentNode.insertBefore(p, node); } node.parentNode.removeChild(node); }, ol: removeNode, ul: removeNode, dl:removeNode, dt:removeNode, dd:removeNode, 'li':removeNode, 'caption':transP, 'th':transP, 'tr':transP, 'h1':transP,'h2':transP,'h3':transP,'h4':transP,'h5':transP,'h6':transP, 'td':function(node){ //没有内容的td直接删掉 var txt = !!node.innerText(); if(txt){ node.parentNode.insertAfter(UE.uNode.createText(' &nbsp; &nbsp;'),node); } node.parentNode.removeChild(node,node.innerText()) } } }() }); //暂时这里支持一下老版本的属性 var pasteplain = me.options.pasteplain; me.commands['pasteplain'] = { queryCommandState: function (){ return pasteplain ? 1 : 0; }, execCommand: function (){ pasteplain = !pasteplain|0; }, notNeedUndo : 1 }; };///import core ///import plugins/inserthtml.js ///commands 视频 ///commandsName InsertVideo ///commandsTitle 插入视频 ///commandsDialog dialogs\video UE.plugins['video'] = function (){ var me =this, div; /** * 创建插入视频字符窜 * @param url 视频地址 * @param width 视频宽度 * @param height 视频高度 * @param align 视频对齐 * @param toEmbed 是否以flash代替显示 * @param addParagraph 是否需要添加P 标签 */ function creatInsertStr(url,width,height,id,align,toEmbed){ return !toEmbed ? '<img ' + (id ? 'id="' + id+'"' : '') + ' width="'+ width +'" height="' + height + '" _url="'+url+'" class="edui-faked-video"' + ' src="' + me.options.UEDITOR_HOME_URL+'themes/default/images/spacer.gif" style="background:url('+me.options.UEDITOR_HOME_URL+'themes/default/images/videologo.gif) no-repeat center center; border:1px solid gray;'+(align ? 'float:' + align + ';': '')+'" />' : '<embed type="application/x-shockwave-flash" class="edui-faked-video" pluginspage="http://www.macromedia.com/go/getflashplayer"' + ' src="' + url + '" width="' + width + '" height="' + height + '"' + (align ? ' style="float:' + align + '"': '') + ' wmode="transparent" play="true" loop="false" menu="false" allowscriptaccess="never" allowfullscreen="true" >'; } function switchImgAndEmbed(root,img2embed){ utils.each(root.getNodesByTagName(img2embed ? 'img' : 'embed'),function(node){ if(node.getAttr('class') == 'edui-faked-video'){ var html = creatInsertStr( img2embed ? node.getAttr('_url') : node.getAttr('src'),node.getAttr('width'),node.getAttr('height'),null,node.getStyle('float') || '',img2embed); node.parentNode.replaceChild(UE.uNode.createElement(html),node) } }) } me.addOutputRule(function(root){ switchImgAndEmbed(root,true) }); me.addInputRule(function(root){ switchImgAndEmbed(root) }); me.commands["insertvideo"] = { execCommand: function (cmd, videoObjs){ videoObjs = utils.isArray(videoObjs)?videoObjs:[videoObjs]; var html = [],id = 'tmpVedio'; for(var i=0,vi,len = videoObjs.length;i<len;i++){ vi = videoObjs[i]; html.push(creatInsertStr( vi.url, vi.width || 420, vi.height || 280, id + i,null,false)); } me.execCommand("inserthtml",html.join(""),true); var rng = this.selection.getRange(); for(var i= 0,len=videoObjs.length;i<len;i++){ var img = this.document.getElementById('tmpVedio'+i); domUtils.removeAttributes(img,'id'); rng.selectNode(img).select(); me.execCommand('imagefloat',videoObjs[i].align) } }, queryCommandState : function(){ var img = me.selection.getRange().getClosedNode(), flag = img && (img.className == "edui-faked-video"); return flag ? 1 : 0; } }; };/** * Created with JetBrains WebStorm. * User: taoqili * Date: 13-1-18 * Time: 上午11:09 * To change this template use File | Settings | File Templates. */ /** * UE表格操作类 * @param table * @constructor */ (function () { var UETable = UE.UETable = function (table) { this.table = table; this.indexTable = []; this.selectedTds = []; this.cellsRange = {}; this.update(table); }; //===以下为静态工具方法=== UETable.removeSelectedClass = function (cells) { utils.each(cells, function (cell) { domUtils.removeClasses(cell, "selectTdClass"); }) }; UETable.addSelectedClass = function (cells) { utils.each(cells, function (cell) { domUtils.addClass(cell, "selectTdClass"); }) }; UETable.isEmptyBlock = function (node) { var reg = new RegExp(domUtils.fillChar, 'g'); if (node[browser.ie ? 'innerText' : 'textContent'].replace(/^\s*$/, '').replace(reg, '').length > 0) { return 0; } for (var i in dtd.$isNotEmpty) if (dtd.$isNotEmpty.hasOwnProperty(i)) { if (node.getElementsByTagName(i).length) { return 0; } } return 1; }; UETable.getWidth = function (cell) { if (!cell)return 0; return parseInt(domUtils.getComputedStyle(cell, "width"), 10); }; /** * 获取单元格或者单元格组的“对齐”状态。 如果当前的检测对象是一个单元格组, 只有在满足所有单元格的 水平和竖直 对齐属性都相同的 * 条件时才会返回其状态值,否则将返回null; 如果当前只检测了一个单元格, 则直接返回当前单元格的对齐状态; * @param table cell or table cells , 支持单个单元格dom对象 或者 单元格dom对象数组 * @return { align: 'left' || 'right' || 'center', valign: 'top' || 'middle' || 'bottom' } 或者 null */ UETable.getTableCellAlignState = function ( cells ) { !utils.isArray( cells ) && ( cells = [cells] ); var result = {}, status = ['align', 'valign'], tempStatus = null, isSame = true;//状态是否相同 utils.each( cells, function( cellNode ){ utils.each( status, function( currentState ){ tempStatus = cellNode.getAttribute( currentState ); if( !result[ currentState ] && tempStatus ) { result[ currentState ] = tempStatus; } else if( !result[ currentState ] || ( tempStatus !== result[ currentState ] ) ) { isSame = false; return false; } } ); return isSame; }); return isSame ? result : null; }; /** * 根据当前选区获取相关的table信息 * @return {Object} */ UETable.getTableItemsByRange = function (editor) { var start = editor.selection.getStart(); //ff下会选中bookmark if( start && start.id && start.id.indexOf('_baidu_bookmark_start_') === 0 ) { start = start.nextSibling; } //在table或者td边缘有可能存在选中tr的情况 var cell = start && domUtils.findParentByTagName(start, ["td", "th"], true), tr = cell && cell.parentNode, caption = start && domUtils.findParentByTagName(start, 'caption', true), table = caption ? caption.parentNode : tr && tr.parentNode.parentNode; return { cell:cell, tr:tr, table:table, caption:caption } }; UETable.getUETableBySelected = function (editor) { var table = UETable.getTableItemsByRange(editor).table; if (table && table.ueTable && table.ueTable.selectedTds.length) { return table.ueTable; } return null; }; UETable.getDefaultValue = function (editor, table) { var borderMap = { thin:'0px', medium:'1px', thick:'2px' }, tableBorder, tdPadding, tdBorder, tmpValue; if (!table) { table = editor.document.createElement('table'); table.insertRow(0).insertCell(0).innerHTML = 'xxx'; editor.body.appendChild(table); var td = table.getElementsByTagName('td')[0]; tmpValue = domUtils.getComputedStyle(table, 'border-left-width'); tableBorder = parseInt(borderMap[tmpValue] || tmpValue, 10); tmpValue = domUtils.getComputedStyle(td, 'padding-left'); tdPadding = parseInt(borderMap[tmpValue] || tmpValue, 10); tmpValue = domUtils.getComputedStyle(td, 'border-left-width'); tdBorder = parseInt(borderMap[tmpValue] || tmpValue, 10); domUtils.remove(table); return { tableBorder:tableBorder, tdPadding:tdPadding, tdBorder:tdBorder }; } else { td = table.getElementsByTagName('td')[0]; tmpValue = domUtils.getComputedStyle(table, 'border-left-width'); tableBorder = parseInt(borderMap[tmpValue] || tmpValue, 10); tmpValue = domUtils.getComputedStyle(td, 'padding-left'); tdPadding = parseInt(borderMap[tmpValue] || tmpValue, 10); tmpValue = domUtils.getComputedStyle(td, 'border-left-width'); tdBorder = parseInt(borderMap[tmpValue] || tmpValue, 10); return { tableBorder:tableBorder, tdPadding:tdPadding, tdBorder:tdBorder }; } }; /** * 根据当前点击的td或者table获取索引对象 * @param tdOrTable */ UETable.getUETable = function (tdOrTable) { var tag = tdOrTable.tagName.toLowerCase(); tdOrTable = (tag == "td" || tag == "th" || tag == 'caption') ? domUtils.findParentByTagName(tdOrTable, "table", true) : tdOrTable; if (!tdOrTable.ueTable) { tdOrTable.ueTable = new UETable(tdOrTable); } return tdOrTable.ueTable; }; UETable.cloneCell = function(cell,ignoreMerge,keepPro){ if (!cell || utils.isString(cell)) { return this.table.ownerDocument.createElement(cell || 'td'); } var flag = domUtils.hasClass(cell, "selectTdClass"); flag && domUtils.removeClasses(cell, "selectTdClass"); var tmpCell = cell.cloneNode(true); if (ignoreMerge) { tmpCell.rowSpan = tmpCell.colSpan = 1; } //去掉宽高 !keepPro && domUtils.removeAttributes(tmpCell,'width height'); !keepPro && domUtils.removeAttributes(tmpCell,'style'); tmpCell.style.borderLeftStyle = ""; tmpCell.style.borderTopStyle = ""; tmpCell.style.borderLeftColor = cell.style.borderRightColor; tmpCell.style.borderLeftWidth = cell.style.borderRightWidth; tmpCell.style.borderTopColor = cell.style.borderBottomColor; tmpCell.style.borderTopWidth = cell.style.borderBottomWidth; flag && domUtils.addClass(cell, "selectTdClass"); return tmpCell; } UETable.prototype = { getMaxRows:function () { var rows = this.table.rows, maxLen = 1; for (var i = 0, row; row = rows[i]; i++) { var currentMax = 1; for (var j = 0, cj; cj = row.cells[j++];) { currentMax = Math.max(cj.rowSpan || 1, currentMax); } maxLen = Math.max(currentMax + i, maxLen); } return maxLen; }, /** * 获取当前表格的最大列数 */ getMaxCols:function () { var rows = this.table.rows, maxLen = 0, cellRows = {}; for (var i = 0, row; row = rows[i]; i++) { var cellsNum = 0; for (var j = 0, cj; cj = row.cells[j++];) { cellsNum += (cj.colSpan || 1); if (cj.rowSpan && cj.rowSpan > 1) { for (var k = 1; k < cj.rowSpan; k++) { if (!cellRows['row_' + (i + k)]) { cellRows['row_' + (i + k)] = (cj.colSpan || 1); } else { cellRows['row_' + (i + k)]++ } } } } cellsNum += cellRows['row_' + i] || 0; maxLen = Math.max(cellsNum, maxLen); } return maxLen; }, getCellColIndex:function (cell) { }, /** * 获取当前cell旁边的单元格, * @param cell * @param right */ getHSideCell:function (cell, right) { try { var cellInfo = this.getCellInfo(cell), previewRowIndex, previewColIndex; var len = this.selectedTds.length, range = this.cellsRange; //首行或者首列没有前置单元格 if ((!right && (!len ? !cellInfo.colIndex : !range.beginColIndex)) || (right && (!len ? (cellInfo.colIndex == (this.colsNum - 1)) : (range.endColIndex == this.colsNum - 1)))) return null; previewRowIndex = !len ? cellInfo.rowIndex : range.beginRowIndex; previewColIndex = !right ? ( !len ? (cellInfo.colIndex < 1 ? 0 : (cellInfo.colIndex - 1)) : range.beginColIndex - 1) : ( !len ? cellInfo.colIndex + 1 : range.endColIndex + 1); return this.getCell(this.indexTable[previewRowIndex][previewColIndex].rowIndex, this.indexTable[previewRowIndex][previewColIndex].cellIndex); } catch (e) { showError(e); } }, getTabNextCell:function (cell, preRowIndex) { var cellInfo = this.getCellInfo(cell), rowIndex = preRowIndex || cellInfo.rowIndex, colIndex = cellInfo.colIndex + 1 + (cellInfo.colSpan - 1), nextCell; try { nextCell = this.getCell(this.indexTable[rowIndex][colIndex].rowIndex, this.indexTable[rowIndex][colIndex].cellIndex); } catch (e) { try { rowIndex = rowIndex * 1 + 1; colIndex = 0; nextCell = this.getCell(this.indexTable[rowIndex][colIndex].rowIndex, this.indexTable[rowIndex][colIndex].cellIndex); } catch (e) { } } return nextCell; }, /** * 获取视觉上的后置单元格 * @param cell * @param bottom */ getVSideCell:function (cell, bottom, ignoreRange) { try { var cellInfo = this.getCellInfo(cell), nextRowIndex, nextColIndex; var len = this.selectedTds.length && !ignoreRange, range = this.cellsRange; //末行或者末列没有后置单元格 if ((!bottom && (cellInfo.rowIndex == 0)) || (bottom && (!len ? (cellInfo.rowIndex + cellInfo.rowSpan > this.rowsNum - 1) : (range.endRowIndex == this.rowsNum - 1)))) return null; nextRowIndex = !bottom ? ( !len ? cellInfo.rowIndex - 1 : range.beginRowIndex - 1) : ( !len ? (cellInfo.rowIndex + cellInfo.rowSpan) : range.endRowIndex + 1); nextColIndex = !len ? cellInfo.colIndex : range.beginColIndex; return this.getCell(this.indexTable[nextRowIndex][nextColIndex].rowIndex, this.indexTable[nextRowIndex][nextColIndex].cellIndex); } catch (e) { showError(e); } }, /** * 获取相同结束位置的单元格,xOrY指代了是获取x轴相同还是y轴相同 */ getSameEndPosCells:function (cell, xOrY) { try { var flag = (xOrY.toLowerCase() === "x"), end = domUtils.getXY(cell)[flag ? 'x' : 'y'] + cell["offset" + (flag ? 'Width' : 'Height')], rows = this.table.rows, cells = null, returns = []; for (var i = 0; i < this.rowsNum; i++) { cells = rows[i].cells; for (var j = 0, tmpCell; tmpCell = cells[j++];) { var tmpEnd = domUtils.getXY(tmpCell)[flag ? 'x' : 'y'] + tmpCell["offset" + (flag ? 'Width' : 'Height')]; //对应行的td已经被上面行rowSpan了 if (tmpEnd > end && flag) break; if (cell == tmpCell || end == tmpEnd) { //只获取单一的单元格 //todo 仅获取单一单元格在特定情况下会造成returns为空,从而影响后续的拖拽实现,修正这个。需考虑性能 if (tmpCell[flag ? "colSpan" : "rowSpan"] == 1) { returns.push(tmpCell); } if (flag) break; } } } return returns; } catch (e) { showError(e); } }, setCellContent:function (cell, content) { cell.innerHTML = content || (browser.ie ? domUtils.fillChar : "<br />"); }, cloneCell:UETable.cloneCell, /** * 获取跟当前单元格的右边竖线为左边的所有未合并单元格 */ getSameStartPosXCells:function (cell) { try { var start = domUtils.getXY(cell).x + cell.offsetWidth, rows = this.table.rows, cells , returns = []; for (var i = 0; i < this.rowsNum; i++) { cells = rows[i].cells; for (var j = 0, tmpCell; tmpCell = cells[j++];) { var tmpStart = domUtils.getXY(tmpCell).x; if (tmpStart > start) break; if (tmpStart == start && tmpCell.colSpan == 1) { returns.push(tmpCell); break; } } } return returns; } catch (e) { showError(e); } }, /** * 更新table对应的索引表 */ update:function (table) { this.table = table || this.table; this.selectedTds = []; this.cellsRange = {}; this.indexTable = []; var rows = this.table.rows, rowsNum = this.getMaxRows(), dNum = rowsNum - rows.length, colsNum = this.getMaxCols(); while (dNum--) { this.table.insertRow(rows.length); } this.rowsNum = rowsNum; this.colsNum = colsNum; for (var i = 0, len = rows.length; i < len; i++) { this.indexTable[i] = new Array(colsNum); } //填充索引表 for (var rowIndex = 0, row; row = rows[rowIndex]; rowIndex++) { for (var cellIndex = 0, cell, cells = row.cells; cell = cells[cellIndex]; cellIndex++) { //修正整行被rowSpan时导致的行数计算错误 if (cell.rowSpan > rowsNum) { cell.rowSpan = rowsNum; } var colIndex = cellIndex, rowSpan = cell.rowSpan || 1, colSpan = cell.colSpan || 1; //当已经被上一行rowSpan或者被前一列colSpan了,则跳到下一个单元格进行 while (this.indexTable[rowIndex][colIndex]) colIndex++; for (var j = 0; j < rowSpan; j++) { for (var k = 0; k < colSpan; k++) { this.indexTable[rowIndex + j][colIndex + k] = { rowIndex:rowIndex, cellIndex:cellIndex, colIndex:colIndex, rowSpan:rowSpan, colSpan:colSpan } } } } } //修复残缺td for (j = 0; j < rowsNum; j++) { for (k = 0; k < colsNum; k++) { if (this.indexTable[j][k] === undefined) { row = rows[j]; cell = row.cells[row.cells.length - 1]; cell = cell ? cell.cloneNode(true) : this.table.ownerDocument.createElement("td"); this.setCellContent(cell); if (cell.colSpan !== 1)cell.colSpan = 1; if (cell.rowSpan !== 1)cell.rowSpan = 1; row.appendChild(cell); this.indexTable[j][k] = { rowIndex:j, cellIndex:cell.cellIndex, colIndex:k, rowSpan:1, colSpan:1 } } } } //当框选后删除行或者列后撤销,需要重建选区。 var tds = domUtils.getElementsByTagName(this.table, "td"), selectTds = []; utils.each(tds, function (td) { if (domUtils.hasClass(td, "selectTdClass")) { selectTds.push(td); } }); if (selectTds.length) { var start = selectTds[0], end = selectTds[selectTds.length - 1], startInfo = this.getCellInfo(start), endInfo = this.getCellInfo(end); this.selectedTds = selectTds; this.cellsRange = { beginRowIndex:startInfo.rowIndex, beginColIndex:startInfo.colIndex, endRowIndex:endInfo.rowIndex + endInfo.rowSpan - 1, endColIndex:endInfo.colIndex + endInfo.colSpan - 1 }; } }, /** * 获取单元格的索引信息 */ getCellInfo:function (cell) { if (!cell) return; var cellIndex = cell.cellIndex, rowIndex = cell.parentNode.rowIndex, rowInfo = this.indexTable[rowIndex], numCols = this.colsNum; for (var colIndex = cellIndex; colIndex < numCols; colIndex++) { var cellInfo = rowInfo[colIndex]; if (cellInfo.rowIndex === rowIndex && cellInfo.cellIndex === cellIndex) { return cellInfo; } } }, /** * 根据行列号获取单元格 */ getCell:function (rowIndex, cellIndex) { return rowIndex < this.rowsNum && this.table.rows[rowIndex].cells[cellIndex] || null; }, /** * 删除单元格 */ deleteCell:function (cell, rowIndex) { rowIndex = typeof rowIndex == 'number' ? rowIndex : cell.parentNode.rowIndex; var row = this.table.rows[rowIndex]; row.deleteCell(cell.cellIndex); }, /** * 根据始末两个单元格获取被框选的所有单元格范围 */ getCellsRange:function (cellA, cellB) { function checkRange(beginRowIndex, beginColIndex, endRowIndex, endColIndex) { var tmpBeginRowIndex = beginRowIndex, tmpBeginColIndex = beginColIndex, tmpEndRowIndex = endRowIndex, tmpEndColIndex = endColIndex, cellInfo, colIndex, rowIndex; // 通过indexTable检查是否存在超出TableRange上边界的情况 if (beginRowIndex > 0) { for (colIndex = beginColIndex; colIndex < endColIndex; colIndex++) { cellInfo = me.indexTable[beginRowIndex][colIndex]; rowIndex = cellInfo.rowIndex; if (rowIndex < beginRowIndex) { tmpBeginRowIndex = Math.min(rowIndex, tmpBeginRowIndex); } } } // 通过indexTable检查是否存在超出TableRange右边界的情况 if (endColIndex < me.colsNum) { for (rowIndex = beginRowIndex; rowIndex < endRowIndex; rowIndex++) { cellInfo = me.indexTable[rowIndex][endColIndex]; colIndex = cellInfo.colIndex + cellInfo.colSpan - 1; if (colIndex > endColIndex) { tmpEndColIndex = Math.max(colIndex, tmpEndColIndex); } } } // 检查是否有超出TableRange下边界的情况 if (endRowIndex < me.rowsNum) { for (colIndex = beginColIndex; colIndex < endColIndex; colIndex++) { cellInfo = me.indexTable[endRowIndex][colIndex]; rowIndex = cellInfo.rowIndex + cellInfo.rowSpan - 1; if (rowIndex > endRowIndex) { tmpEndRowIndex = Math.max(rowIndex, tmpEndRowIndex); } } } // 检查是否有超出TableRange左边界的情况 if (beginColIndex > 0) { for (rowIndex = beginRowIndex; rowIndex < endRowIndex; rowIndex++) { cellInfo = me.indexTable[rowIndex][beginColIndex]; colIndex = cellInfo.colIndex; if (colIndex < beginColIndex) { tmpBeginColIndex = Math.min(cellInfo.colIndex, tmpBeginColIndex); } } } //递归调用直至所有完成所有框选单元格的扩展 if (tmpBeginRowIndex != beginRowIndex || tmpBeginColIndex != beginColIndex || tmpEndRowIndex != endRowIndex || tmpEndColIndex != endColIndex) { return checkRange(tmpBeginRowIndex, tmpBeginColIndex, tmpEndRowIndex, tmpEndColIndex); } else { // 不需要扩展TableRange的情况 return { beginRowIndex:beginRowIndex, beginColIndex:beginColIndex, endRowIndex:endRowIndex, endColIndex:endColIndex }; } } try { var me = this, cellAInfo = me.getCellInfo(cellA); if (cellA === cellB) { return { beginRowIndex:cellAInfo.rowIndex, beginColIndex:cellAInfo.colIndex, endRowIndex:cellAInfo.rowIndex + cellAInfo.rowSpan - 1, endColIndex:cellAInfo.colIndex + cellAInfo.colSpan - 1 }; } var cellBInfo = me.getCellInfo(cellB); // 计算TableRange的四个边 var beginRowIndex = Math.min(cellAInfo.rowIndex, cellBInfo.rowIndex), beginColIndex = Math.min(cellAInfo.colIndex, cellBInfo.colIndex), endRowIndex = Math.max(cellAInfo.rowIndex + cellAInfo.rowSpan - 1, cellBInfo.rowIndex + cellBInfo.rowSpan - 1), endColIndex = Math.max(cellAInfo.colIndex + cellAInfo.colSpan - 1, cellBInfo.colIndex + cellBInfo.colSpan - 1); return checkRange(beginRowIndex, beginColIndex, endRowIndex, endColIndex); } catch (e) { //throw e; } }, /** * 依据cellsRange获取对应的单元格集合 */ getCells:function (range) { //每次获取cells之前必须先清除上次的选择,否则会对后续获取操作造成影响 this.clearSelected(); var beginRowIndex = range.beginRowIndex, beginColIndex = range.beginColIndex, endRowIndex = range.endRowIndex, endColIndex = range.endColIndex, cellInfo, rowIndex, colIndex, tdHash = {}, returnTds = []; for (var i = beginRowIndex; i <= endRowIndex; i++) { for (var j = beginColIndex; j <= endColIndex; j++) { cellInfo = this.indexTable[i][j]; rowIndex = cellInfo.rowIndex; colIndex = cellInfo.colIndex; // 如果Cells里已经包含了此Cell则跳过 var key = rowIndex + '|' + colIndex; if (tdHash[key]) continue; tdHash[key] = 1; if (rowIndex < i || colIndex < j || rowIndex + cellInfo.rowSpan - 1 > endRowIndex || colIndex + cellInfo.colSpan - 1 > endColIndex) { return null; } returnTds.push(this.getCell(rowIndex, cellInfo.cellIndex)); } } return returnTds; }, /** * 清理已经选中的单元格 */ clearSelected:function () { UETable.removeSelectedClass(this.selectedTds); this.selectedTds = []; this.cellsRange = {}; }, /** * 根据range设置已经选中的单元格 */ setSelected:function (range) { var cells = this.getCells(range); UETable.addSelectedClass(cells); this.selectedTds = cells; this.cellsRange = range; }, isFullRow:function () { var range = this.cellsRange; return (range.endColIndex - range.beginColIndex + 1) == this.colsNum; }, isFullCol:function () { var range = this.cellsRange, table = this.table, ths = table.getElementsByTagName("th"), rows = range.endRowIndex - range.beginRowIndex + 1; return !ths.length ? rows == this.rowsNum : rows == this.rowsNum || (rows == this.rowsNum - 1); }, /** * 获取视觉上的前置单元格,默认是左边,top传入时 * @param cell * @param top */ getNextCell:function (cell, bottom, ignoreRange) { try { var cellInfo = this.getCellInfo(cell), nextRowIndex, nextColIndex; var len = this.selectedTds.length && !ignoreRange, range = this.cellsRange; //末行或者末列没有后置单元格 if ((!bottom && (cellInfo.rowIndex == 0)) || (bottom && (!len ? (cellInfo.rowIndex + cellInfo.rowSpan > this.rowsNum - 1) : (range.endRowIndex == this.rowsNum - 1)))) return null; nextRowIndex = !bottom ? ( !len ? cellInfo.rowIndex - 1 : range.beginRowIndex - 1) : ( !len ? (cellInfo.rowIndex + cellInfo.rowSpan) : range.endRowIndex + 1); nextColIndex = !len ? cellInfo.colIndex : range.beginColIndex; return this.getCell(this.indexTable[nextRowIndex][nextColIndex].rowIndex, this.indexTable[nextRowIndex][nextColIndex].cellIndex); } catch (e) { showError(e); } }, getPreviewCell:function (cell, top) { try { var cellInfo = this.getCellInfo(cell), previewRowIndex, previewColIndex; var len = this.selectedTds.length, range = this.cellsRange; //首行或者首列没有前置单元格 if ((!top && (!len ? !cellInfo.colIndex : !range.beginColIndex)) || (top && (!len ? (cellInfo.rowIndex > (this.colsNum - 1)) : (range.endColIndex == this.colsNum - 1)))) return null; previewRowIndex = !top ? ( !len ? cellInfo.rowIndex : range.beginRowIndex ) : ( !len ? (cellInfo.rowIndex < 1 ? 0 : (cellInfo.rowIndex - 1)) : range.beginRowIndex); previewColIndex = !top ? ( !len ? (cellInfo.colIndex < 1 ? 0 : (cellInfo.colIndex - 1)) : range.beginColIndex - 1) : ( !len ? cellInfo.colIndex : range.endColIndex + 1); return this.getCell(this.indexTable[previewRowIndex][previewColIndex].rowIndex, this.indexTable[previewRowIndex][previewColIndex].cellIndex); } catch (e) { showError(e); } }, /** * 移动单元格中的内容 */ moveContent:function (cellTo, cellFrom) { if (UETable.isEmptyBlock(cellFrom)) return; if (UETable.isEmptyBlock(cellTo)) { cellTo.innerHTML = cellFrom.innerHTML; return; } var child = cellTo.lastChild; if (child.nodeType == 3 || !dtd.$block[child.tagName]) { cellTo.appendChild(cellTo.ownerDocument.createElement('br')) } while (child = cellFrom.firstChild) { cellTo.appendChild(child); } }, /** * 向右合并单元格 */ mergeRight:function (cell) { var cellInfo = this.getCellInfo(cell), rightColIndex = cellInfo.colIndex + cellInfo.colSpan, rightCellInfo = this.indexTable[cellInfo.rowIndex][rightColIndex], rightCell = this.getCell(rightCellInfo.rowIndex, rightCellInfo.cellIndex); //合并 cell.colSpan = cellInfo.colSpan + rightCellInfo.colSpan; //被合并的单元格不应存在宽度属性 cell.removeAttribute("width"); //移动内容 this.moveContent(cell, rightCell); //删掉被合并的Cell this.deleteCell(rightCell, rightCellInfo.rowIndex); this.update(); }, /** * 向下合并单元格 */ mergeDown:function (cell) { var cellInfo = this.getCellInfo(cell), downRowIndex = cellInfo.rowIndex + cellInfo.rowSpan, downCellInfo = this.indexTable[downRowIndex][cellInfo.colIndex], downCell = this.getCell(downCellInfo.rowIndex, downCellInfo.cellIndex); cell.rowSpan = cellInfo.rowSpan + downCellInfo.rowSpan; cell.removeAttribute("height"); this.moveContent(cell, downCell); this.deleteCell(downCell, downCellInfo.rowIndex); this.update(); }, /** * 合并整个range中的内容 */ mergeRange:function () { //由于合并操作可以在任意时刻进行,所以无法通过鼠标位置等信息实时生成range,只能通过缓存实例中的cellsRange对象来访问 var range = this.cellsRange, leftTopCell = this.getCell(range.beginRowIndex, this.indexTable[range.beginRowIndex][range.beginColIndex].cellIndex); if (leftTopCell.tagName == "TH" && range.endRowIndex !== range.beginRowIndex) { var index = this.indexTable, info = this.getCellInfo(leftTopCell); leftTopCell = this.getCell(1, index[1][info.colIndex].cellIndex); range = this.getCellsRange(leftTopCell, this.getCell(index[this.rowsNum - 1][info.colIndex].rowIndex, index[this.rowsNum - 1][info.colIndex].cellIndex)); } // 删除剩余的Cells var cells = this.getCells(range); for(var i= 0,ci;ci=cells[i++];){ if (ci !== leftTopCell) { this.moveContent(leftTopCell, ci); this.deleteCell(ci); } } // 修改左上角Cell的rowSpan和colSpan,并调整宽度属性设置 leftTopCell.rowSpan = range.endRowIndex - range.beginRowIndex + 1; leftTopCell.rowSpan > 1 && leftTopCell.removeAttribute("height"); leftTopCell.colSpan = range.endColIndex - range.beginColIndex + 1; leftTopCell.colSpan > 1 && leftTopCell.removeAttribute("width"); if (leftTopCell.rowSpan == this.rowsNum && leftTopCell.colSpan != 1) { leftTopCell.colSpan = 1; } if (leftTopCell.colSpan == this.colsNum && leftTopCell.rowSpan != 1) { var rowIndex = leftTopCell.parentNode.rowIndex; //解决IE下的表格操作问题 if( this.table.deleteRow ) { for (var i = rowIndex+ 1, curIndex=rowIndex+ 1, len=leftTopCell.rowSpan; i < len; i++) { this.table.deleteRow(curIndex); } } else { for (var i = 0, len=leftTopCell.rowSpan - 1; i < len; i++) { var row = this.table.rows[rowIndex + 1]; row.parentNode.removeChild(row); } } leftTopCell.rowSpan = 1; } this.update(); }, /** * 插入一行单元格 */ insertRow:function (rowIndex, sourceCell) { var numCols = this.colsNum, table = this.table, row = table.insertRow(rowIndex), cell, width = parseInt((table.offsetWidth - numCols * 20 - numCols - 1) / numCols, 10); //首行直接插入,无需考虑部分单元格被rowspan的情况 if (rowIndex == 0 || rowIndex == this.rowsNum) { for (var colIndex = 0; colIndex < numCols; colIndex++) { cell = this.cloneCell(sourceCell, true); this.setCellContent(cell); cell.getAttribute('vAlign') && cell.setAttribute('vAlign', cell.getAttribute('vAlign')); row.appendChild(cell); } } else { var infoRow = this.indexTable[rowIndex], cellIndex = 0; for (colIndex = 0; colIndex < numCols; colIndex++) { var cellInfo = infoRow[colIndex]; //如果存在某个单元格的rowspan穿过待插入行的位置,则修改该单元格的rowspan即可,无需插入单元格 if (cellInfo.rowIndex < rowIndex) { cell = this.getCell(cellInfo.rowIndex, cellInfo.cellIndex); cell.rowSpan = cellInfo.rowSpan + 1; } else { cell = this.cloneCell(sourceCell, true); this.setCellContent(cell); row.appendChild(cell); } } } //框选时插入不触发contentchange,需要手动更新索引。 this.update(); return row; }, /** * 删除一行单元格 * @param rowIndex */ deleteRow:function (rowIndex) { var row = this.table.rows[rowIndex], infoRow = this.indexTable[rowIndex], colsNum = this.colsNum, count = 0; //处理计数 for (var colIndex = 0; colIndex < colsNum;) { var cellInfo = infoRow[colIndex], cell = this.getCell(cellInfo.rowIndex, cellInfo.cellIndex); if (cell.rowSpan > 1) { if (cellInfo.rowIndex == rowIndex) { var clone = cell.cloneNode(true); clone.rowSpan = cell.rowSpan - 1; clone.innerHTML = ""; cell.rowSpan = 1; var nextRowIndex = rowIndex + 1, nextRow = this.table.rows[nextRowIndex], insertCellIndex, preMerged = this.getPreviewMergedCellsNum(nextRowIndex, colIndex) - count; if (preMerged < colIndex) { insertCellIndex = colIndex - preMerged - 1; //nextRow.insertCell(insertCellIndex); domUtils.insertAfter(nextRow.cells[insertCellIndex], clone); } else { if (nextRow.cells.length) nextRow.insertBefore(clone, nextRow.cells[0]) } count += 1; //cell.parentNode.removeChild(cell); } } colIndex += cell.colSpan || 1; } var deleteTds = [], cacheMap = {}; for (colIndex = 0; colIndex < colsNum; colIndex++) { var tmpRowIndex = infoRow[colIndex].rowIndex, tmpCellIndex = infoRow[colIndex].cellIndex, key = tmpRowIndex + "_" + tmpCellIndex; if (cacheMap[key])continue; cacheMap[key] = 1; cell = this.getCell(tmpRowIndex, tmpCellIndex); deleteTds.push(cell); } var mergeTds = []; utils.each(deleteTds, function (td) { if (td.rowSpan == 1) { td.parentNode.removeChild(td); } else { mergeTds.push(td); } }); utils.each(mergeTds, function (td) { td.rowSpan--; }); row.parentNode.removeChild(row); //浏览器方法本身存在bug,采用自定义方法删除 //this.table.deleteRow(rowIndex); this.update(); }, insertCol:function (colIndex, sourceCell, defaultValue) { var rowsNum = this.rowsNum, rowIndex = 0, tableRow, cell, backWidth = parseInt((this.table.offsetWidth - (this.colsNum + 1) * 20 - (this.colsNum + 1)) / (this.colsNum + 1), 10); function replaceTdToTh(rowIndex, cell, tableRow) { if (rowIndex == 0) { var th = cell.nextSibling || cell.previousSibling; if (th.tagName == 'TH') { th = cell.ownerDocument.createElement("th"); th.appendChild(cell.firstChild); tableRow.insertBefore(th, cell); domUtils.remove(cell) } }else{ if (cell.tagName == 'TH') { var td = cell.ownerDocument.createElement("td"); td.appendChild(cell.firstChild); tableRow.insertBefore(td, cell); domUtils.remove(cell) } } } var preCell; if (colIndex == 0 || colIndex == this.colsNum) { for (; rowIndex < rowsNum; rowIndex++) { tableRow = this.table.rows[rowIndex]; preCell = tableRow.cells[colIndex == 0 ? colIndex : tableRow.cells.length]; cell = this.cloneCell(sourceCell, true); //tableRow.insertCell(colIndex == 0 ? colIndex : tableRow.cells.length); this.setCellContent(cell); cell.setAttribute('vAlign', cell.getAttribute('vAlign')); preCell && cell.setAttribute('width', preCell.getAttribute('width')); if (!colIndex) { tableRow.insertBefore(cell, tableRow.cells[0]); } else { domUtils.insertAfter(tableRow.cells[tableRow.cells.length - 1], cell); } replaceTdToTh(rowIndex, cell, tableRow) } } else { for (; rowIndex < rowsNum; rowIndex++) { var cellInfo = this.indexTable[rowIndex][colIndex]; if (cellInfo.colIndex < colIndex) { cell = this.getCell(cellInfo.rowIndex, cellInfo.cellIndex); cell.colSpan = cellInfo.colSpan + 1; } else { tableRow = this.table.rows[rowIndex]; preCell = tableRow.cells[cellInfo.cellIndex]; cell = this.cloneCell(sourceCell, true);//tableRow.insertCell(cellInfo.cellIndex); this.setCellContent(cell); cell.setAttribute('vAlign', cell.getAttribute('vAlign')); preCell && cell.setAttribute('width', preCell.getAttribute('width')); //防止IE下报错 preCell ? tableRow.insertBefore(cell, preCell) : tableRow.appendChild(cell); } replaceTdToTh(rowIndex, cell, tableRow); } } //框选时插入不触发contentchange,需要手动更新索引 this.update(); this.updateWidth(backWidth, defaultValue || {tdPadding:10, tdBorder:1}); }, updateWidth:function (width, defaultValue) { var table = this.table, tmpWidth = UETable.getWidth(table) - defaultValue.tdPadding * 2 - defaultValue.tdBorder + width; if (tmpWidth < table.ownerDocument.body.offsetWidth) { table.setAttribute("width", tmpWidth); return; } var tds = domUtils.getElementsByTagName(this.table, "td"); utils.each(tds, function (td) { td.setAttribute("width", width); }) }, deleteCol:function (colIndex) { var indexTable = this.indexTable, tableRows = this.table.rows, backTableWidth = this.table.getAttribute("width"), backTdWidth = 0, rowsNum = this.rowsNum, cacheMap = {}; for (var rowIndex = 0; rowIndex < rowsNum;) { var infoRow = indexTable[rowIndex], cellInfo = infoRow[colIndex], key = cellInfo.rowIndex + '_' + cellInfo.colIndex; // 跳过已经处理过的Cell if (cacheMap[key])continue; cacheMap[key] = 1; var cell = this.getCell(cellInfo.rowIndex, cellInfo.cellIndex); if (!backTdWidth) backTdWidth = cell && parseInt(cell.offsetWidth / cell.colSpan, 10).toFixed(0); // 如果Cell的colSpan大于1, 就修改colSpan, 否则就删掉这个Cell if (cell.colSpan > 1) { cell.colSpan--; } else { tableRows[rowIndex].deleteCell(cellInfo.cellIndex); } rowIndex += cellInfo.rowSpan || 1; } this.table.setAttribute("width", backTableWidth - backTdWidth); this.update(); }, splitToCells:function (cell) { var me = this, cells = this.splitToRows(cell); utils.each(cells, function (cell) { me.splitToCols(cell); }) }, splitToRows:function (cell) { var cellInfo = this.getCellInfo(cell), rowIndex = cellInfo.rowIndex, colIndex = cellInfo.colIndex, results = []; // 修改Cell的rowSpan cell.rowSpan = 1; results.push(cell); // 补齐单元格 for (var i = rowIndex, endRow = rowIndex + cellInfo.rowSpan; i < endRow; i++) { if (i == rowIndex)continue; var tableRow = this.table.rows[i], tmpCell = tableRow.insertCell(colIndex - this.getPreviewMergedCellsNum(i, colIndex)); tmpCell.colSpan = cellInfo.colSpan; this.setCellContent(tmpCell); tmpCell.setAttribute('vAlign', cell.getAttribute('vAlign')); tmpCell.setAttribute('align', cell.getAttribute('align')); if (cell.style.cssText) { tmpCell.style.cssText = cell.style.cssText; } results.push(tmpCell); } this.update(); return results; }, getPreviewMergedCellsNum:function (rowIndex, colIndex) { var indexRow = this.indexTable[rowIndex], num = 0; for (var i = 0; i < colIndex;) { var colSpan = indexRow[i].colSpan, tmpRowIndex = indexRow[i].rowIndex; num += (colSpan - (tmpRowIndex == rowIndex ? 1 : 0)); i += colSpan; } return num; }, splitToCols:function (cell) { var backWidth = (cell.offsetWidth / cell.colSpan - 22).toFixed(0), cellInfo = this.getCellInfo(cell), rowIndex = cellInfo.rowIndex, colIndex = cellInfo.colIndex, results = []; // 修改Cell的rowSpan cell.colSpan = 1; cell.setAttribute("width", backWidth); results.push(cell); // 补齐单元格 for (var j = colIndex, endCol = colIndex + cellInfo.colSpan; j < endCol; j++) { if (j == colIndex)continue; var tableRow = this.table.rows[rowIndex], tmpCell = tableRow.insertCell(this.indexTable[rowIndex][j].cellIndex + 1); tmpCell.rowSpan = cellInfo.rowSpan; this.setCellContent(tmpCell); tmpCell.setAttribute('vAlign', cell.getAttribute('vAlign')); tmpCell.setAttribute('align', cell.getAttribute('align')); tmpCell.setAttribute('width', backWidth); if (cell.style.cssText) { tmpCell.style.cssText = cell.style.cssText; } //处理th的情况 if (cell.tagName == 'TH') { var th = cell.ownerDocument.createElement('th'); th.appendChild(tmpCell.firstChild); th.setAttribute('vAlign', cell.getAttribute('vAlign')); th.rowSpan = tmpCell.rowSpan; tableRow.insertBefore(th, tmpCell); domUtils.remove(tmpCell); } results.push(tmpCell); } this.update(); return results; }, isLastCell:function (cell, rowsNum, colsNum) { rowsNum = rowsNum || this.rowsNum; colsNum = colsNum || this.colsNum; var cellInfo = this.getCellInfo(cell); return ((cellInfo.rowIndex + cellInfo.rowSpan) == rowsNum) && ((cellInfo.colIndex + cellInfo.colSpan) == colsNum); }, getLastCell:function (cells) { cells = cells || this.table.getElementsByTagName("td"); var firstInfo = this.getCellInfo(cells[0]); var me = this, last = cells[0], tr = last.parentNode, cellsNum = 0, cols = 0, rows; utils.each(cells, function (cell) { if (cell.parentNode == tr)cols += cell.colSpan || 1; cellsNum += cell.rowSpan * cell.colSpan || 1; }); rows = cellsNum / cols; utils.each(cells, function (cell) { if (me.isLastCell(cell, rows, cols)) { last = cell; return false; } }); return last; }, selectRow:function (rowIndex) { var indexRow = this.indexTable[rowIndex], start = this.getCell(indexRow[0].rowIndex, indexRow[0].cellIndex), end = this.getCell(indexRow[this.colsNum - 1].rowIndex, indexRow[this.colsNum - 1].cellIndex), range = this.getCellsRange(start, end); this.setSelected(range); }, selectTable:function () { var tds = this.table.getElementsByTagName("td"), range = this.getCellsRange(tds[0], tds[tds.length - 1]); this.setSelected(range); }, sortTable:function (sortByCellIndex, compareFn) { var table = this.table, rows = table.rows, trArray = [], flag = rows[0].cells[0].tagName === "TH", lastRowIndex = 0; if(this.selectedTds.length){ var range = this.cellsRange, len = range.endRowIndex + 1; for (var i = range.beginRowIndex; i < len; i++) { trArray[i] = rows[i]; } trArray.splice(0,range.beginRowIndex); lastRowIndex = (range.endRowIndex +1) === this.rowsNum ? 0 : range.endRowIndex +1; }else{ for (var i = 0,len = rows.length; i < len; i++) { trArray[i] = rows[i]; } } //th不参与排序 flag && trArray.splice(0, 1); trArray = utils.sort(trArray,function (tr1, tr2) { var txt = function(node){ return node.innerText||node.textContent; }; return compareFn ? (typeof compareFn === "number" ? compareFn : compareFn.call(this, tr1.cells[sortByCellIndex], tr2.cells[sortByCellIndex])) : function () { var value1 = txt(tr1.cells[sortByCellIndex]), value2 = txt(tr2.cells[sortByCellIndex]); return value1.localeCompare(value2); }(); }); var fragment = table.ownerDocument.createDocumentFragment(); for (var j = 0, len = trArray.length; j < len; j++) { fragment.appendChild(trArray[j]); } var tbody = table.getElementsByTagName("tbody")[0]; if(!lastRowIndex){ tbody.appendChild(fragment); }else{ tbody.insertBefore(fragment,rows[lastRowIndex- range.endRowIndex + range.beginRowIndex - 1]) } }, setBackground:function (cells, value) { if (typeof value === "string") { utils.each(cells, function (cell) { cell.style.backgroundColor = value; }) } else if (typeof value === "object") { value = utils.extend({ repeat:true, colorList:["#ddd", "#fff"] }, value); var rowIndex = this.getCellInfo(cells[0]).rowIndex, count = 0, colors = value.colorList, getColor = function (list, index, repeat) { return list[index] ? list[index] : repeat ? list[index % list.length] : ""; }; for (var i = 0, cell; cell = cells[i++];) { var cellInfo = this.getCellInfo(cell); cell.style.backgroundColor = getColor(colors, ((rowIndex + count) == cellInfo.rowIndex) ? count : ++count, value.repeat); } } }, removeBackground:function (cells) { utils.each(cells, function (cell) { cell.style.backgroundColor = ""; }) } }; function showError(e) { } })();/** * Created with JetBrains PhpStorm. * User: taoqili * Date: 13-2-20 * Time: 下午6:25 * To change this template use File | Settings | File Templates. */ ; (function () { var UT = UE.UETable, getTableItemsByRange = function (editor) { return UT.getTableItemsByRange(editor); }, getUETableBySelected = function (editor) { return UT.getUETableBySelected(editor) }, getDefaultValue = function (editor, table) { return UT.getDefaultValue(editor, table); }, getUETable = function (tdOrTable) { return UT.getUETable(tdOrTable); }; UE.commands['inserttable'] = { queryCommandState: function () { return getTableItemsByRange(this).table ? -1 : 0; }, execCommand: function (cmd, opt) { function createTable(opt, tdWidth) { var html = [], rowsNum = opt.numRows, colsNum = opt.numCols; for (var r = 0; r < rowsNum; r++) { html.push('<tr>'); for (var c = 0; c < colsNum; c++) { html.push('<td width="' + tdWidth + '" vAlign="' + opt.tdvalign + '" >' + (browser.ie ? domUtils.fillChar : '<br/>') + '</td>') } html.push('</tr>') } //禁止指定table-width return '<table><tbody>' + html.join('') + '</tbody></table>' } if (!opt) { opt = utils.extend({}, { numCols: this.options.defaultCols, numRows: this.options.defaultRows, tdvalign: this.options.tdvalign }) } var me = this; var range = this.selection.getRange(), start = range.startContainer, firstParentBlock = domUtils.findParent(start, function (node) { return domUtils.isBlockElm(node); }, true) || me.body; var defaultValue = getDefaultValue(me), tableWidth = firstParentBlock.offsetWidth, tdWidth = Math.floor(tableWidth / opt.numCols - defaultValue.tdPadding * 2 - defaultValue.tdBorder); //todo其他属性 !opt.tdvalign && (opt.tdvalign = me.options.tdvalign); me.execCommand("inserthtml", createTable(opt, tdWidth)); } }; UE.commands['insertparagraphbeforetable'] = { queryCommandState: function () { return getTableItemsByRange(this).cell ? 0 : -1; }, execCommand: function () { var table = getTableItemsByRange(this).table; if (table) { var p = this.document.createElement("p"); p.innerHTML = browser.ie ? '&nbsp;' : '<br />'; table.parentNode.insertBefore(p, table); this.selection.getRange().setStart(p, 0).setCursor(); } } }; UE.commands['deletetable'] = { queryCommandState: function () { var rng = this.selection.getRange(); return domUtils.findParentByTagName(rng.startContainer, 'table', true) ? 0 : -1; }, execCommand: function (cmd, table) { var rng = this.selection.getRange(); table = table || domUtils.findParentByTagName(rng.startContainer, 'table', true); if (table) { var next = table.nextSibling; if (!next) { next = domUtils.createElement(this.document, 'p', { 'innerHTML': browser.ie ? domUtils.fillChar : '<br/>' }); table.parentNode.insertBefore(next, table); } domUtils.remove(table); rng = this.selection.getRange(); if (next.nodeType == 3) { rng.setStartBefore(next) } else { rng.setStart(next, 0) } rng.setCursor(false, true) this.fireEvent("tablehasdeleted") } } }; UE.commands['cellalign'] = { queryCommandState: function () { return getSelectedArr(this).length ? 0 : -1 }, execCommand: function (cmd, align) { var selectedTds = getSelectedArr(this); if (selectedTds.length) { for (var i = 0, ci; ci = selectedTds[i++];) { ci.setAttribute('align', align); } } } }; UE.commands['cellvalign'] = { queryCommandState: function () { return getSelectedArr(this).length ? 0 : -1; }, execCommand: function (cmd, valign) { var selectedTds = getSelectedArr(this); if (selectedTds.length) { for (var i = 0, ci; ci = selectedTds[i++];) { ci.setAttribute('vAlign', valign); } } } }; UE.commands['insertcaption'] = { queryCommandState: function () { var table = getTableItemsByRange(this).table; if (table) { return table.getElementsByTagName('caption').length == 0 ? 1 : -1; } return -1; }, execCommand: function () { var table = getTableItemsByRange(this).table; if (table) { var caption = this.document.createElement('caption'); caption.innerHTML = browser.ie ? domUtils.fillChar : '<br/>'; table.insertBefore(caption, table.firstChild); var range = this.selection.getRange(); range.setStart(caption, 0).setCursor(); } } }; UE.commands['deletecaption'] = { queryCommandState: function () { var rng = this.selection.getRange(), table = domUtils.findParentByTagName(rng.startContainer, 'table'); if (table) { return table.getElementsByTagName('caption').length == 0 ? -1 : 1; } return -1; }, execCommand: function () { var rng = this.selection.getRange(), table = domUtils.findParentByTagName(rng.startContainer, 'table'); if (table) { domUtils.remove(table.getElementsByTagName('caption')[0]); var range = this.selection.getRange(); range.setStart(table.rows[0].cells[0], 0).setCursor(); } } }; UE.commands['inserttitle'] = { queryCommandState: function () { var table = getTableItemsByRange(this).table; if (table) { var firstRow = table.rows[0]; return firstRow.getElementsByTagName('th').length == 0 ? 0 : -1 } return -1; }, execCommand: function () { var table = getTableItemsByRange(this).table; if (table) { getUETable(table).insertRow(0, 'th'); } var th = table.getElementsByTagName('th')[0]; this.selection.getRange().setStart(th, 0).setCursor(false, true); } }; UE.commands['deletetitle'] = { queryCommandState: function () { var table = getTableItemsByRange(this).table; if (table) { var firstRow = table.rows[0]; return firstRow.getElementsByTagName('th').length ? 0 : -1 } return -1; }, execCommand: function () { var table = getTableItemsByRange(this).table; if (table) { domUtils.remove(table.rows[0]) } var td = table.getElementsByTagName('td')[0]; this.selection.getRange().setStart(td, 0).setCursor(false, true); } }; UE.commands["mergeright"] = { queryCommandState: function (cmd) { var tableItems = getTableItemsByRange(this); if (!tableItems.cell) return -1; var ut = getUETable(tableItems.table); if (ut.selectedTds.length) return -1; var cellInfo = ut.getCellInfo(tableItems.cell), rightColIndex = cellInfo.colIndex + cellInfo.colSpan; if (rightColIndex >= ut.colsNum) return -1; var rightCellInfo = ut.indexTable[cellInfo.rowIndex][rightColIndex]; return (rightCellInfo.rowIndex == cellInfo.rowIndex && rightCellInfo.rowSpan == cellInfo.rowSpan) ? 0 : -1; }, execCommand: function (cmd) { var rng = this.selection.getRange(), bk = rng.createBookmark(true); var cell = getTableItemsByRange(this).cell, ut = getUETable(cell); ut.mergeRight(cell); rng.moveToBookmark(bk).select(); } }; UE.commands["mergedown"] = { queryCommandState: function (cmd) { var tableItems = getTableItemsByRange(this), cell = tableItems.cell; if (!cell || cell.tagName == "TH") return -1; var ut = getUETable(tableItems.table); if (ut.selectedTds.length)return -1; var cellInfo = ut.getCellInfo(tableItems.cell), downRowIndex = cellInfo.rowIndex + cellInfo.rowSpan; // 如果处于最下边则不能f向右合并 if (downRowIndex >= ut.rowsNum) return -1; var downCellInfo = ut.indexTable[downRowIndex][cellInfo.colIndex]; // 当且仅当两个Cell的开始列号和结束列号一致时能进行合并 return (downCellInfo.colIndex == cellInfo.colIndex && downCellInfo.colSpan == cellInfo.colSpan) && tableItems.cell.tagName !== 'TH' ? 0 : -1; }, execCommand: function () { var rng = this.selection.getRange(), bk = rng.createBookmark(true); var cell = getTableItemsByRange(this).cell, ut = getUETable(cell); ut.mergeDown(cell); rng.moveToBookmark(bk).select(); } }; UE.commands["mergecells"] = { queryCommandState: function () { return getUETableBySelected(this) ? 0 : -1; }, execCommand: function () { var ut = getUETableBySelected(this); if (ut && ut.selectedTds.length) { var cell = ut.selectedTds[0]; ut.mergeRange(); var rng = this.selection.getRange(); if (domUtils.isEmptyBlock(cell)) { rng.setStart(cell, 0).collapse(true) } else { rng.selectNodeContents(cell) } rng.select(); } } }; UE.commands["insertrow"] = { queryCommandState: function () { var tableItems = getTableItemsByRange(this), cell = tableItems.cell; return cell && cell.tagName == "TD" && getUETable(tableItems.table).rowsNum < this.options.maxRowNum ? 0 : -1; }, execCommand: function () { var rng = this.selection.getRange(), bk = rng.createBookmark(true); var tableItems = getTableItemsByRange(this), cell = tableItems.cell, table = tableItems.table, ut = getUETable(table), cellInfo = ut.getCellInfo(cell); //ut.insertRow(!ut.selectedTds.length ? cellInfo.rowIndex:ut.cellsRange.beginRowIndex,''); if (!ut.selectedTds.length) { ut.insertRow(cellInfo.rowIndex, cell); } else { var range = ut.cellsRange; for (var i = 0, len = range.endRowIndex - range.beginRowIndex + 1; i < len; i++) { ut.insertRow(range.beginRowIndex, cell); } } rng.moveToBookmark(bk).select(); if (table.getAttribute("interlaced") === "enabled")this.fireEvent("interlacetable", table); } }; //后插入行 UE.commands["insertrownext"] = { queryCommandState: function () { var tableItems = getTableItemsByRange(this), cell = tableItems.cell; return cell && (cell.tagName == "TD") && getUETable(tableItems.table).rowsNum < this.options.maxRowNum ? 0 : -1; }, execCommand: function () { var rng = this.selection.getRange(), bk = rng.createBookmark(true); var tableItems = getTableItemsByRange(this), cell = tableItems.cell, table = tableItems.table, ut = getUETable(table), cellInfo = ut.getCellInfo(cell); //ut.insertRow(!ut.selectedTds.length? cellInfo.rowIndex + cellInfo.rowSpan : ut.cellsRange.endRowIndex + 1,''); if (!ut.selectedTds.length) { ut.insertRow(cellInfo.rowIndex + cellInfo.rowSpan, cell); } else { var range = ut.cellsRange; for (var i = 0, len = range.endRowIndex - range.beginRowIndex + 1; i < len; i++) { ut.insertRow(range.endRowIndex + 1, cell); } } rng.moveToBookmark(bk).select(); if (table.getAttribute("interlaced") === "enabled")this.fireEvent("interlacetable", table); } }; UE.commands["deleterow"] = { queryCommandState: function () { var tableItems = getTableItemsByRange(this); if (!tableItems.cell) { return -1; } }, execCommand: function () { var cell = getTableItemsByRange(this).cell, ut = getUETable(cell), cellsRange = ut.cellsRange, cellInfo = ut.getCellInfo(cell), preCell = ut.getVSideCell(cell), nextCell = ut.getVSideCell(cell, true), rng = this.selection.getRange(); if (utils.isEmptyObject(cellsRange)) { ut.deleteRow(cellInfo.rowIndex); } else { for (var i = cellsRange.beginRowIndex; i < cellsRange.endRowIndex + 1; i++) { ut.deleteRow(cellsRange.beginRowIndex); } } var table = ut.table; if (!table.getElementsByTagName('td').length) { var nextSibling = table.nextSibling; domUtils.remove(table); if (nextSibling) { rng.setStart(nextSibling, 0).setCursor(false, true); } } else { if (cellInfo.rowSpan == 1 || cellInfo.rowSpan == cellsRange.endRowIndex - cellsRange.beginRowIndex + 1) { if (nextCell || preCell) rng.selectNodeContents(nextCell || preCell).setCursor(false, true); } else { var newCell = ut.getCell(cellInfo.rowIndex, ut.indexTable[cellInfo.rowIndex][cellInfo.colIndex].cellIndex); if (newCell) rng.selectNodeContents(newCell).setCursor(false, true); } } if (table.getAttribute("interlaced") === "enabled")this.fireEvent("interlacetable", table); } }; UE.commands["insertcol"] = { queryCommandState: function (cmd) { var tableItems = getTableItemsByRange(this), cell = tableItems.cell; return cell && (cell.tagName == "TD" || cell.tagName == 'TH') && getUETable(tableItems.table).colsNum < this.options.maxColNum ? 0 : -1; }, execCommand: function (cmd) { var rng = this.selection.getRange(), bk = rng.createBookmark(true); if (this.queryCommandState(cmd) == -1)return; var cell = getTableItemsByRange(this).cell, ut = getUETable(cell), cellInfo = ut.getCellInfo(cell); //ut.insertCol(!ut.selectedTds.length ? cellInfo.colIndex:ut.cellsRange.beginColIndex); if (!ut.selectedTds.length) { ut.insertCol(cellInfo.colIndex, cell); } else { var range = ut.cellsRange; for (var i = 0, len = range.endColIndex - range.beginColIndex + 1; i < len; i++) { ut.insertCol(range.beginColIndex, cell); } } rng.moveToBookmark(bk).select(true); } }; UE.commands["insertcolnext"] = { queryCommandState: function () { var tableItems = getTableItemsByRange(this), cell = tableItems.cell; return cell && getUETable(tableItems.table).colsNum < this.options.maxColNum ? 0 : -1; }, execCommand: function () { var rng = this.selection.getRange(), bk = rng.createBookmark(true); var cell = getTableItemsByRange(this).cell, ut = getUETable(cell), cellInfo = ut.getCellInfo(cell); //ut.insertCol(!ut.selectedTds.length ? cellInfo.colIndex + cellInfo.colSpan:ut.cellsRange.endColIndex +1); if (!ut.selectedTds.length) { ut.insertCol(cellInfo.colIndex + cellInfo.colSpan, cell); } else { var range = ut.cellsRange; for (var i = 0, len = range.endColIndex - range.beginColIndex + 1; i < len; i++) { ut.insertCol(range.endColIndex + 1, cell); } } rng.moveToBookmark(bk).select(); } }; UE.commands["deletecol"] = { queryCommandState: function () { var tableItems = getTableItemsByRange(this); if (!tableItems.cell) return -1; }, execCommand: function () { var cell = getTableItemsByRange(this).cell, ut = getUETable(cell), range = ut.cellsRange, cellInfo = ut.getCellInfo(cell), preCell = ut.getHSideCell(cell), nextCell = ut.getHSideCell(cell, true); if (utils.isEmptyObject(range)) { ut.deleteCol(cellInfo.colIndex); } else { for (var i = range.beginColIndex; i < range.endColIndex + 1; i++) { ut.deleteCol(range.beginColIndex); } } var table = ut.table, rng = this.selection.getRange(); if (!table.getElementsByTagName('td').length) { var nextSibling = table.nextSibling; domUtils.remove(table); if (nextSibling) { rng.setStart(nextSibling, 0).setCursor(false, true); } } else { if (domUtils.inDoc(cell, this.document)) { rng.setStart(cell, 0).setCursor(false, true); } else { if (nextCell && domUtils.inDoc(nextCell, this.document)) { rng.selectNodeContents(nextCell).setCursor(false, true); } else { if (preCell && domUtils.inDoc(preCell, this.document)) { rng.selectNodeContents(preCell).setCursor(true, true); } } } } } }; UE.commands["splittocells"] = { queryCommandState: function () { var tableItems = getTableItemsByRange(this), cell = tableItems.cell; if (!cell) return -1; var ut = getUETable(tableItems.table); if (ut.selectedTds.length > 0) return -1; return cell && (cell.colSpan > 1 || cell.rowSpan > 1) ? 0 : -1; }, execCommand: function () { var rng = this.selection.getRange(), bk = rng.createBookmark(true); var cell = getTableItemsByRange(this).cell, ut = getUETable(cell); ut.splitToCells(cell); rng.moveToBookmark(bk).select(); } }; UE.commands["splittorows"] = { queryCommandState: function () { var tableItems = getTableItemsByRange(this), cell = tableItems.cell; if (!cell) return -1; var ut = getUETable(tableItems.table); if (ut.selectedTds.length > 0) return -1; return cell && cell.rowSpan > 1 ? 0 : -1; }, execCommand: function () { var rng = this.selection.getRange(), bk = rng.createBookmark(true); var cell = getTableItemsByRange(this).cell, ut = getUETable(cell); ut.splitToRows(cell); rng.moveToBookmark(bk).select(); } }; UE.commands["splittocols"] = { queryCommandState: function () { var tableItems = getTableItemsByRange(this), cell = tableItems.cell; if (!cell) return -1; var ut = getUETable(tableItems.table); if (ut.selectedTds.length > 0) return -1; return cell && cell.colSpan > 1 ? 0 : -1; }, execCommand: function () { var rng = this.selection.getRange(), bk = rng.createBookmark(true); var cell = getTableItemsByRange(this).cell, ut = getUETable(cell); ut.splitToCols(cell); rng.moveToBookmark(bk).select(); } }; UE.commands["adaptbytext"] = UE.commands["adaptbywindow"] = { queryCommandState: function () { return getTableItemsByRange(this).table ? 0 : -1 }, execCommand: function (cmd) { var tableItems = getTableItemsByRange(this), table = tableItems.table; if (table) { if (cmd == 'adaptbywindow') { resetTdWidth(table, this); } else { var cells = domUtils.getElementsByTagName(table, "td th"); utils.each(cells, function (cell) { cell.removeAttribute("width"); }); table.removeAttribute("width"); } } } }; //平均分配各列 UE.commands['averagedistributecol'] = { queryCommandState: function () { var ut = getUETableBySelected(this); if (!ut) return -1; return ut.isFullRow() || ut.isFullCol() ? 0 : -1; }, execCommand: function (cmd) { var me = this, ut = getUETableBySelected(me); function getAverageWidth() { var tb = ut.table, averageWidth, sumWidth = 0, colsNum = 0, tbAttr = getDefaultValue(me, tb); if (ut.isFullRow()) { sumWidth = tb.offsetWidth; colsNum = ut.colsNum; } else { var begin = ut.cellsRange.beginColIndex, end = ut.cellsRange.endColIndex, node; for (var i = begin; i <= end;) { node = ut.selectedTds[i]; sumWidth += node.offsetWidth; i += node.colSpan; colsNum += 1; } } averageWidth = Math.ceil(sumWidth / colsNum) - tbAttr.tdBorder * 2 - tbAttr.tdPadding * 2; return averageWidth; } function setAverageWidth(averageWidth) { utils.each(domUtils.getElementsByTagName(ut.table, "th"), function (node) { node.setAttribute("width", ""); }); var cells = ut.isFullRow() ? domUtils.getElementsByTagName(ut.table, "td") : ut.selectedTds; utils.each(cells, function (node) { if (node.colSpan == 1) { node.setAttribute("width", averageWidth); } }); } if (ut && ut.selectedTds.length) { setAverageWidth(getAverageWidth()); } } }; //平均分配各行 UE.commands['averagedistributerow'] = { queryCommandState: function () { var ut = getUETableBySelected(this); if (!ut) return -1; if (ut.selectedTds && /th/ig.test(ut.selectedTds[0].tagName)) return -1; return ut.isFullRow() || ut.isFullCol() ? 0 : -1; }, execCommand: function (cmd) { var me = this, ut = getUETableBySelected(me); function getAverageHeight() { var averageHeight, rowNum, sumHeight = 0, tb = ut.table, tbAttr = getDefaultValue(me, tb), tdpadding = parseInt(domUtils.getComputedStyle(tb.getElementsByTagName('td')[0], "padding-top")); if (ut.isFullCol()) { var captionArr = domUtils.getElementsByTagName(tb, "caption"), thArr = domUtils.getElementsByTagName(tb, "th"), captionHeight, thHeight; if (captionArr.length > 0) { captionHeight = captionArr[0].offsetHeight; } if (thArr.length > 0) { thHeight = thArr[0].offsetHeight; } sumHeight = tb.offsetHeight - (captionHeight || 0) - (thHeight || 0); rowNum = thArr.length == 0 ? ut.rowsNum : (ut.rowsNum - 1); } else { var begin = ut.cellsRange.beginRowIndex, end = ut.cellsRange.endRowIndex, count = 0, trs = domUtils.getElementsByTagName(tb, "tr"); for (var i = begin; i <= end; i++) { sumHeight += trs[i].offsetHeight; count += 1; } rowNum = count; } //ie8下是混杂模式 if (browser.ie && browser.version < 9) { averageHeight = Math.ceil(sumHeight / rowNum); } else { averageHeight = Math.ceil(sumHeight / rowNum) - tbAttr.tdBorder * 2 - tdpadding * 2; } return averageHeight; } function setAverageHeight(averageHeight) { var cells = ut.isFullCol() ? domUtils.getElementsByTagName(ut.table, "td") : ut.selectedTds; utils.each(cells, function (node) { if (node.rowSpan == 1) { node.setAttribute("height", averageHeight); } }); } if (ut && ut.selectedTds.length) { setAverageHeight(getAverageHeight()); } } }; //单元格对齐方式 UE.commands['cellalignment'] = { queryCommandState: function () { return getTableItemsByRange(this).table ? 0 : -1 }, execCommand: function (cmd, data) { var me = this, ut = getUETableBySelected(me); if (!ut) { var start = me.selection.getStart(), cell = start && domUtils.findParentByTagName(start, ["td", "th", "caption"], true); if (!/caption/ig.test(cell.tagName)) { domUtils.setAttributes(cell, data); } else { cell.style.textAlign = data.align; cell.style.verticalAlign = data.vAlign; } me.selection.getRange().setCursor(true); } else { utils.each(ut.selectedTds, function (cell) { domUtils.setAttributes(cell, data); }); } }, /** * 查询当前点击的单元格的对齐状态, 如果当前已经选择了多个单元格, 则会返回所有单元格经过统一协调过后的状态 * @see UE.UETable.getTableCellAlignState */ queryCommandValue: function (cmd) { var activeMenuCell = getTableItemsByRange( this).cell; if( !activeMenuCell ) { activeMenuCell = getSelectedArr(this)[0]; } if (!activeMenuCell) { return null; } else { //获取同时选中的其他单元格 var cells = UE.UETable.getUETable(activeMenuCell).selectedTds; !cells.length && ( cells = activeMenuCell ); return UE.UETable.getTableCellAlignState(cells); } } }; //表格对齐方式 UE.commands['tablealignment'] = { queryCommandState: function () { if (browser.ie && browser.version < 8) { return -1; } return getTableItemsByRange(this).table ? 0 : -1 }, execCommand: function (cmd, value) { var me = this, start = me.selection.getStart(), table = start && domUtils.findParentByTagName(start, ["table"], true); if (table) { table.setAttribute("align",value); } } }; //表格属性 UE.commands['edittable'] = { queryCommandState: function () { return getTableItemsByRange(this).table ? 0 : -1 }, execCommand: function (cmd, color) { var rng = this.selection.getRange(), table = domUtils.findParentByTagName(rng.startContainer, 'table'); if (table) { var arr = domUtils.getElementsByTagName(table, "td").concat( domUtils.getElementsByTagName(table, "th"), domUtils.getElementsByTagName(table, "caption") ); utils.each(arr, function (node) { node.style.borderColor = color; }); } } }; //单元格属性 UE.commands['edittd'] = { queryCommandState: function () { return getTableItemsByRange(this).table ? 0 : -1 }, execCommand: function (cmd, bkColor) { var me = this, ut = getUETableBySelected(me); if (!ut) { var start = me.selection.getStart(), cell = start && domUtils.findParentByTagName(start, ["td", "th", "caption"], true); if (cell) { cell.style.backgroundColor = bkColor; } } else { utils.each(ut.selectedTds, function (cell) { cell.style.backgroundColor = bkColor; }); } } }; UE.commands['sorttable'] = { queryCommandState: function () { var me = this, tableItems = getTableItemsByRange(me); if (!tableItems.cell) return -1; var table = tableItems.table, cells = table.getElementsByTagName("td"); for (var i = 0, cell; cell = cells[i++];) { if (cell.rowSpan != 1 || cell.colSpan != 1) return -1; } return 0; }, execCommand: function (cmd, fn) { var me = this, range = me.selection.getRange(), bk = range.createBookmark(true), tableItems = getTableItemsByRange(me), cell = tableItems.cell, ut = getUETable(tableItems.table), cellInfo = ut.getCellInfo(cell); ut.sortTable(cellInfo.cellIndex, fn); range.moveToBookmark(bk).select(); } }; UE.commands["enablesort"] = UE.commands["disablesort"] = { queryCommandState: function () { return getTableItemsByRange(this).table ? 0 : -1; }, execCommand: function (cmd) { var table = getTableItemsByRange(this).table; table.setAttribute("data-sort", cmd == "enablesort" ? "sortEnabled" : "sortDisabled"); } }; UE.commands["settablebackground"] = { queryCommandState: function () { return getSelectedArr(this).length > 1 ? 0 : -1; }, execCommand: function (cmd, value) { var table, cells, ut; cells = getSelectedArr(this); ut = getUETable(cells[0]); ut.setBackground(cells, value); } }; UE.commands["cleartablebackground"] = { queryCommandState: function () { var cells = getSelectedArr(this); if (!cells.length)return -1; for (var i = 0, cell; cell = cells[i++];) { if (cell.style.backgroundColor !== "") return 0; } return -1; }, execCommand: function () { var cells = getSelectedArr(this), ut = getUETable(cells[0]); ut.removeBackground(cells); } }; UE.commands["interlacetable"] = UE.commands["uninterlacetable"] = { queryCommandState: function (cmd) { var table = getTableItemsByRange(this).table; if (!table) return -1; var interlaced = table.getAttribute("interlaced"); if (cmd == "interlacetable") { //TODO 待定 //是否需要待定,如果设置,则命令只能单次执行成功,但反射具备toggle效果;否则可以覆盖前次命令,但反射将不存在toggle效果 return (interlaced === "enabled") ? -1 : 0; } else { return (!interlaced || interlaced === "disabled") ? -1 : 0; } }, execCommand: function (cmd, classList) { var table = getTableItemsByRange(this).table; if (cmd == "interlacetable") { table.setAttribute("interlaced", "enabled"); this.fireEvent("interlacetable", table, classList); } else { table.setAttribute("interlaced", "disabled"); this.fireEvent("uninterlacetable", table); } } }; function resetTdWidth(table, editor) { var tds = table.getElementsByTagName("td"); utils.each(tds, function (td) { td.removeAttribute("width"); }); table.setAttribute('width', getTableWidth(editor, true, getDefaultValue(editor, table))); setTimeout(function () { utils.each(tds, function (td) { (td.colSpan == 1) && td.setAttribute("width", td.offsetWidth + ""); }) }, 0); } function getTableWidth(editor, needIEHack, defaultValue) { var body = editor.body; return body.offsetWidth - (needIEHack ? parseInt(domUtils.getComputedStyle(body, 'margin-left'), 10) * 2 : 0) - defaultValue.tableBorder * 2 - (editor.options.offsetWidth || 0); } function getSelectedArr(editor) { var cell = getTableItemsByRange(editor).cell; if (cell) { var ut = getUETable(cell); return ut.selectedTds.length ? ut.selectedTds : [cell]; } else { return []; } } })();/** * Created with JetBrains PhpStorm. * User: taoqili * Date: 12-10-12 * Time: 上午10:05 * To change this template use File | Settings | File Templates. */ UE.plugins['table'] = function () { var me = this, tabTimer = null, //拖动计时器 tableDragTimer = null, //双击计时器 tableResizeTimer = null, //单元格最小宽度 cellMinWidth = 5, isInResizeBuffer = false, //单元格边框大小 cellBorderWidth = 5, //鼠标偏移距离 offsetOfTableCell = 10, //记录在有限时间内的点击状态, 共有3个取值, 0, 1, 2。 0代表未初始化, 1代表单击了1次,2代表2次 singleClickState = 0, userActionStatus = null, //双击允许的时间范围 dblclickTime = 360, UT = UE.UETable, getUETable = function (tdOrTable) { return UT.getUETable(tdOrTable); }, getUETableBySelected = function (editor) { return UT.getUETableBySelected(editor); }, getDefaultValue = function (editor, table) { return UT.getDefaultValue(editor, table); }, removeSelectedClass = function (cells) { return UT.removeSelectedClass(cells); }; function showError(e) { // throw e; } me.ready(function(){ var me = this; var orgGetText = me.selection.getText; me.selection.getText = function(){ var table = getUETableBySelected(me); if(table){ var str = ''; utils.each(table.selectedTds,function(td){ str += td[browser.ie?'innerText':'textContent']; }) return str; }else{ return orgGetText.call(me.selection) } } }) //处理拖动及框选相关方法 var startTd = null, //鼠标按下时的锚点td currentTd = null, //当前鼠标经过时的td onDrag = "", //指示当前拖动状态,其值可为"","h","v" ,分别表示未拖动状态,横向拖动状态,纵向拖动状态,用于鼠标移动过程中的判断 onBorder = false, //检测鼠标按下时是否处在单元格边缘位置 dragButton = null, dragOver = false, dragLine = null, //模拟的拖动线 dragTd = null; //发生拖动的目标td var mousedown = false, //todo 判断混乱模式 needIEHack = true; me.setOpt({ 'maxColNum':20, 'maxRowNum':100, 'defaultCols':5, 'defaultRows':5, 'tdvalign':'top', 'cursorpath':me.options.UEDITOR_HOME_URL + "themes/default/images/cursor_", 'tableDragable':false, 'classList':["ue-table-interlace-color-single","ue-table-interlace-color-double"] }); me.getUETable = getUETable; var commands = { 'deletetable':1, 'inserttable':1, 'cellvalign':1, 'insertcaption':1, 'deletecaption':1, 'inserttitle':1, 'deletetitle':1, "mergeright":1, "mergedown":1, "mergecells":1, "insertrow":1, "insertrownext":1, "deleterow":1, "insertcol":1, "insertcolnext":1, "deletecol":1, "splittocells":1, "splittorows":1, "splittocols":1, "adaptbytext":1, "adaptbywindow":1, "adaptbycustomer":1, "insertparagraph":1, "insertparagraphbeforetable":1, "averagedistributecol":1, "averagedistributerow":1 }; me.ready(function () { utils.cssRule('table', //选中的td上的样式 '.selectTdClass{background-color:#edf5fa !important}' + 'table.noBorderTable td,table.noBorderTable th,table.noBorderTable caption{border:1px dashed #ddd !important}' + //插入的表格的默认样式 'table{margin-bottom:10px;border-collapse:collapse;display:table;}' + 'td,th{padding: 5px 10px;border: 1px solid #DDD;}' + 'caption{border:1px dashed #DDD;border-bottom:0;padding:3px;text-align:center;}' + 'th{border-top:2px solid #BBB;background:#F7F7F7;}' + '.ue-table-interlace-color-single{ background-color: #fcfcfc; } .ue-table-interlace-color-double{ background-color: #f7faff; }' + 'td p{margin:0;padding:0;}', me.document); var tableCopyList, isFullCol, isFullRow; //注册del/backspace事件 me.addListener('keydown', function (cmd, evt) { var me = this; var keyCode = evt.keyCode || evt.which; if (keyCode == 8) { var ut = getUETableBySelected(me); if (ut && ut.selectedTds.length) { if (ut.isFullCol()) { me.execCommand('deletecol') } else if (ut.isFullRow()) { me.execCommand('deleterow') } else { me.fireEvent('delcells'); } domUtils.preventDefault(evt); } var caption = domUtils.findParentByTagName(me.selection.getStart(), 'caption', true), range = me.selection.getRange(); if (range.collapsed && caption && isEmptyBlock(caption)) { me.fireEvent('saveScene'); var table = caption.parentNode; domUtils.remove(caption); if (table) { range.setStart(table.rows[0].cells[0], 0).setCursor(false, true); } me.fireEvent('saveScene'); } } if (keyCode == 46) { ut = getUETableBySelected(me); if (ut) { me.fireEvent('saveScene'); for (var i = 0, ci; ci = ut.selectedTds[i++];) { domUtils.fillNode(me.document, ci) } me.fireEvent('saveScene'); domUtils.preventDefault(evt); } } if (keyCode == 13) { var rng = me.selection.getRange(), caption = domUtils.findParentByTagName(rng.startContainer, 'caption', true); if (caption) { var table = domUtils.findParentByTagName(caption, 'table'); if (!rng.collapsed) { rng.deleteContents(); me.fireEvent('saveScene'); } else { if (caption) { rng.setStart(table.rows[0].cells[0], 0).setCursor(false, true); } } domUtils.preventDefault(evt); return; } if (rng.collapsed) { var table = domUtils.findParentByTagName(rng.startContainer, 'table'); if (table) { var cell = table.rows[0].cells[0], start = domUtils.findParentByTagName(me.selection.getStart(), ['td', 'th'], true), preNode = table.previousSibling; if (cell === start && (!preNode || preNode.nodeType == 1 && preNode.tagName == 'TABLE' ) && domUtils.isStartInblock(rng)) { var first = domUtils.findParent(me.selection.getStart(), function(n){return domUtils.isBlockElm(n)}, true); if(first && ( /t(h|d)/i.test(first.tagName) || first === start.firstChild )){ me.execCommand('insertparagraphbeforetable'); domUtils.preventDefault(evt); } } } } } if ((evt.ctrlKey || evt.metaKey) && evt.keyCode == '67') { tableCopyList = null; var ut = getUETableBySelected(me); if (ut) { var tds = ut.selectedTds; isFullCol = ut.isFullCol(); isFullRow = ut.isFullRow(); tableCopyList = [ [ut.cloneCell(tds[0],null,true)] ]; for (var i = 1, ci; ci = tds[i]; i++) { if (ci.parentNode !== tds[i - 1].parentNode) { tableCopyList.push([ut.cloneCell(ci,null,true)]); } else { tableCopyList[tableCopyList.length - 1].push(ut.cloneCell(ci,null,true)); } } } } }); me.addListener("tablehasdeleted",function(){ toggleDraggableState(this, false, "", null); if (dragButton)domUtils.remove(dragButton); }); me.addListener('beforepaste', function (cmd, html) { var me = this; var rng = me.selection.getRange(); if (domUtils.findParentByTagName(rng.startContainer, 'caption', true)) { var div = me.document.createElement("div"); div.innerHTML = html.html; html.html = div[browser.ie ? 'innerText' : 'textContent']; return; } var table = getUETableBySelected(me); if (tableCopyList) { me.fireEvent('saveScene'); var rng = me.selection.getRange(); var td = domUtils.findParentByTagName(rng.startContainer, ['td', 'th'], true), tmpNode, preNode; if (td) { var ut = getUETable(td); if (isFullRow) { var rowIndex = ut.getCellInfo(td).rowIndex; if (td.tagName == 'TH') { rowIndex++; } for (var i = 0, ci; ci = tableCopyList[i++];) { var tr = ut.insertRow(rowIndex++, "td"); for (var j = 0, cj; cj = ci[j]; j++) { var cell = tr.cells[j]; if (!cell) { cell = tr.insertCell(j) } cell.innerHTML = cj.innerHTML; cj.getAttribute('width') && cell.setAttribute('width', cj.getAttribute('width')); cj.getAttribute('vAlign') && cell.setAttribute('vAlign', cj.getAttribute('vAlign')); cj.getAttribute('align') && cell.setAttribute('align', cj.getAttribute('align')); cj.style.cssText && (cell.style.cssText = cj.style.cssText) } for (var j = 0, cj; cj = tr.cells[j]; j++) { if (!ci[j]) break; cj.innerHTML = ci[j].innerHTML; ci[j].getAttribute('width') && cj.setAttribute('width', ci[j].getAttribute('width')); ci[j].getAttribute('vAlign') && cj.setAttribute('vAlign', ci[j].getAttribute('vAlign')); ci[j].getAttribute('align') && cj.setAttribute('align', ci[j].getAttribute('align')); ci[j].style.cssText && (cj.style.cssText = ci[j].style.cssText) } } } else { if (isFullCol) { cellInfo = ut.getCellInfo(td); var maxColNum = 0; for (var j = 0, ci = tableCopyList[0], cj; cj = ci[j++];) { maxColNum += cj.colSpan || 1; } me.__hasEnterExecCommand = true; for (i = 0; i < maxColNum; i++) { me.execCommand('insertcol'); } me.__hasEnterExecCommand = false; td = ut.table.rows[0].cells[cellInfo.cellIndex]; if (td.tagName == 'TH') { td = ut.table.rows[1].cells[cellInfo.cellIndex]; } } for (var i = 0, ci; ci = tableCopyList[i++];) { tmpNode = td; for (var j = 0, cj; cj = ci[j++];) { if (td) { td.innerHTML = cj.innerHTML; //todo 定制处理 cj.getAttribute('width') && td.setAttribute('width', cj.getAttribute('width')); cj.getAttribute('vAlign') && td.setAttribute('vAlign', cj.getAttribute('vAlign')); cj.getAttribute('align') && td.setAttribute('align', cj.getAttribute('align')); cj.style.cssText && (td.style.cssText = cj.style.cssText); preNode = td; td = td.nextSibling; } else { var cloneTd = cj.cloneNode(true); domUtils.removeAttributes(cloneTd, ['class', 'rowSpan', 'colSpan']); preNode.parentNode.appendChild(cloneTd) } } td = ut.getNextCell(tmpNode, true, true); if (!tableCopyList[i]) break; if (!td) { var cellInfo = ut.getCellInfo(tmpNode); ut.table.insertRow(ut.table.rows.length); ut.update(); td = ut.getVSideCell(tmpNode, true); } } } ut.update(); } else { table = me.document.createElement('table'); for (var i = 0, ci; ci = tableCopyList[i++];) { var tr = table.insertRow(table.rows.length); for (var j = 0, cj; cj = ci[j++];) { cloneTd = UT.cloneCell(cj,null,true); domUtils.removeAttributes(cloneTd, ['class']); tr.appendChild(cloneTd) } if (j == 2 && cloneTd.rowSpan > 1) { cloneTd.rowSpan = 1; } } var defaultValue = getDefaultValue(me), width = me.body.offsetWidth - (needIEHack ? parseInt(domUtils.getComputedStyle(me.body, 'margin-left'), 10) * 2 : 0) - defaultValue.tableBorder * 2 - (me.options.offsetWidth || 0); me.execCommand('insertHTML', '<table ' + ( isFullCol && isFullRow ? 'width="' + width + '"' : '') + '>' + table.innerHTML.replace(/>\s*</g, '><').replace(/\bth\b/gi, "td") + '</table>') } me.fireEvent('contentchange'); me.fireEvent('saveScene'); html.html = ''; return true; } else { var div = me.document.createElement("div"), tables; div.innerHTML = html.html; tables = div.getElementsByTagName("table"); if (domUtils.findParentByTagName(me.selection.getStart(), 'table')) { utils.each(tables, function (t) { domUtils.remove(t) }); if (domUtils.findParentByTagName(me.selection.getStart(), 'caption', true)) { div.innerHTML = div[browser.ie ? 'innerText' : 'textContent']; } } else { utils.each(tables, function (table) { removeStyleSize(table, true); domUtils.removeAttributes(table, ['style', 'border']); utils.each(domUtils.getElementsByTagName(table, "td"), function (td) { if (isEmptyBlock(td)) { domUtils.fillNode(me.document, td); } removeStyleSize(td, true); // domUtils.removeAttributes(td, ['style']) }); }); } html.html = div.innerHTML; } }); me.addListener('afterpaste', function () { utils.each(domUtils.getElementsByTagName(me.body, "table"), function (table) { if (table.offsetWidth > me.body.offsetWidth) { var defaultValue = getDefaultValue(me, table); table.style.width = me.body.offsetWidth - (needIEHack ? parseInt(domUtils.getComputedStyle(me.body, 'margin-left'), 10) * 2 : 0) - defaultValue.tableBorder * 2 - (me.options.offsetWidth || 0) + 'px' } }) }); me.addListener('blur', function () { tableCopyList = null; }); var timer; me.addListener('keydown', function () { clearTimeout(timer); timer = setTimeout(function () { var rng = me.selection.getRange(), cell = domUtils.findParentByTagName(rng.startContainer, ['th', 'td'], true); if (cell) { var table = cell.parentNode.parentNode.parentNode; if (table.offsetWidth > table.getAttribute("width")) { cell.style.wordBreak = "break-all"; } } }, 100); }); me.addListener("selectionchange", function () { toggleDraggableState(me, false, "", null); }); //内容变化时触发索引更新 //todo 可否考虑标记检测,如果不涉及表格的变化就不进行索引重建和更新 me.addListener("contentchange", function () { var me = this; //尽可能排除一些不需要更新的状况 hideDragLine(me); if (getUETableBySelected(me))return; var rng = me.selection.getRange(); var start = rng.startContainer; start = domUtils.findParentByTagName(start, ['td', 'th'], true); utils.each(domUtils.getElementsByTagName(me.document, 'table'), function (table) { if (me.fireEvent("excludetable", table) === true) return; table.ueTable = new UT(table); utils.each(domUtils.getElementsByTagName(me.document, 'td'), function (td) { if (domUtils.isEmptyBlock(td) && td !== start) { domUtils.fillNode(me.document, td); if (browser.ie && browser.version == 6) { td.innerHTML = '&nbsp;' } } }); utils.each(domUtils.getElementsByTagName(me.document, 'th'), function (th) { if (domUtils.isEmptyBlock(th) && th !== start) { domUtils.fillNode(me.document, th); if (browser.ie && browser.version == 6) { th.innerHTML = '&nbsp;' } } }); table.onmouseover = function () { me.fireEvent('tablemouseover', table); }; table.onmousemove = function () { me.fireEvent('tablemousemove', table); me.options.tableDragable && toggleDragButton(true, this, me); }; table.onmouseout = function () { me.fireEvent('tablemouseout', table); toggleDraggableState(me, false, "", null); hideDragLine(me); }; table.onclick = function (evt) { evt = me.window.event || evt; var target = getParentTdOrTh(evt.target || evt.srcElement); if (!target)return; var ut = getUETable(target), table = ut.table, cellInfo = ut.getCellInfo(target), cellsRange, rng = me.selection.getRange(); // if ("topLeft" == inPosition(table, mouseCoords(evt))) { // cellsRange = ut.getCellsRange(ut.table.rows[0].cells[0], ut.getLastCell()); // ut.setSelected(cellsRange); // return; // } // if ("bottomRight" == inPosition(table, mouseCoords(evt))) { // // return; // } if (inTableSide(table, target, evt, true)) { var endTdCol = ut.getCell(ut.indexTable[ut.rowsNum - 1][cellInfo.colIndex].rowIndex, ut.indexTable[ut.rowsNum - 1][cellInfo.colIndex].cellIndex); if (evt.shiftKey && ut.selectedTds.length) { if (ut.selectedTds[0] !== endTdCol) { cellsRange = ut.getCellsRange(ut.selectedTds[0], endTdCol); ut.setSelected(cellsRange); } else { rng && rng.selectNodeContents(endTdCol).select(); } } else { if (target !== endTdCol) { cellsRange = ut.getCellsRange(target, endTdCol); ut.setSelected(cellsRange); } else { rng && rng.selectNodeContents(endTdCol).select(); } } return; } if (inTableSide(table, target, evt)) { var endTdRow = ut.getCell(ut.indexTable[cellInfo.rowIndex][ut.colsNum - 1].rowIndex, ut.indexTable[cellInfo.rowIndex][ut.colsNum - 1].cellIndex); if (evt.shiftKey && ut.selectedTds.length) { if (ut.selectedTds[0] !== endTdRow) { cellsRange = ut.getCellsRange(ut.selectedTds[0], endTdRow); ut.setSelected(cellsRange); } else { rng && rng.selectNodeContents(endTdRow).select(); } } else { if (target !== endTdRow) { cellsRange = ut.getCellsRange(target, endTdRow); ut.setSelected(cellsRange); } else { rng && rng.selectNodeContents(endTdRow).select(); } } } }; }); switchBorderColor(me, true); }); domUtils.on(me.document, "mousemove", mouseMoveEvent); domUtils.on(me.document, "mouseout", function (evt) { var target = evt.target || evt.srcElement; if (target.tagName == "TABLE") { toggleDraggableState(me, false, "", null); } }); /** * 表格隔行变色 */ me.addListener("interlacetable",function(type,table,classList){ if(!table) return; var me = this, rows = table.rows, len = rows.length, getClass = function(list,index,repeat){ return list[index] ? list[index] : repeat ? list[index % list.length]: ""; }; for(var i = 0;i<len;i++){ rows[i].className = getClass( classList|| me.options.classList,i,true); } }); me.addListener("uninterlacetable",function(type,table){ if(!table) return; var me = this, rows = table.rows, classList = me.options.classList, len = rows.length; for(var i = 0;i<len;i++){ domUtils.removeClasses( rows[i], classList ); } }); me.addListener("mousedown", mouseDownEvent); me.addListener("mouseup", mouseUpEvent); //拖动的时候不出发mouseup domUtils.on( me.body, 'dragstart', function( evt ){ mouseUpEvent.call( me, 'dragstart', evt ); }); var currentRowIndex = 0; me.addListener("mousedown", function () { currentRowIndex = 0; }); me.addListener('tabkeydown', function () { var range = this.selection.getRange(), common = range.getCommonAncestor(true, true), table = domUtils.findParentByTagName(common, 'table'); if (table) { if (domUtils.findParentByTagName(common, 'caption', true)) { var cell = domUtils.getElementsByTagName(table, 'th td'); if (cell && cell.length) { range.setStart(cell[0], 0).setCursor(false, true) } } else { var cell = domUtils.findParentByTagName(common, ['td', 'th'], true), ua = getUETable(cell); currentRowIndex = cell.rowSpan > 1 ? currentRowIndex : ua.getCellInfo(cell).rowIndex; var nextCell = ua.getTabNextCell(cell, currentRowIndex); if (nextCell) { if (isEmptyBlock(nextCell)) { range.setStart(nextCell, 0).setCursor(false, true) } else { range.selectNodeContents(nextCell).select() } } else { me.fireEvent('saveScene'); me.__hasEnterExecCommand = true; this.execCommand('insertrownext'); me.__hasEnterExecCommand = false; range = this.selection.getRange(); range.setStart(table.rows[table.rows.length - 1].cells[0], 0).setCursor(); me.fireEvent('saveScene'); } } return true; } }); browser.ie && me.addListener('selectionchange', function () { toggleDraggableState(this, false, "", null); }); me.addListener("keydown", function (type, evt) { var me = this; //处理在表格的最后一个输入tab产生新的表格 var keyCode = evt.keyCode || evt.which; if (keyCode == 8 || keyCode == 46) { return; } var notCtrlKey = !evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey; notCtrlKey && removeSelectedClass(domUtils.getElementsByTagName(me.body, "td")); var ut = getUETableBySelected(me); if (!ut) return; notCtrlKey && ut.clearSelected(); }); me.addListener("beforegetcontent", function () { switchBorderColor(this, false); browser.ie && utils.each(this.document.getElementsByTagName('caption'), function (ci) { if (domUtils.isEmptyNode(ci)) { ci.innerHTML = '&nbsp;' } }); }); me.addListener("aftergetcontent", function () { switchBorderColor(this, true); }); me.addListener("getAllHtml", function () { removeSelectedClass(me.document.getElementsByTagName("td")); }); //修正全屏状态下插入的表格宽度在非全屏状态下撑开编辑器的情况 me.addListener("fullscreenchanged", function (type, fullscreen) { if (!fullscreen) { var ratio = this.body.offsetWidth / document.body.offsetWidth, tables = domUtils.getElementsByTagName(this.body, "table"); utils.each(tables, function (table) { if (table.offsetWidth < me.body.offsetWidth) return false; var tds = domUtils.getElementsByTagName(table, "td"), backWidths = []; utils.each(tds, function (td) { backWidths.push(td.offsetWidth); }); for (var i = 0, td; td = tds[i]; i++) { td.setAttribute("width", Math.floor(backWidths[i] * ratio)); } table.setAttribute("width", Math.floor(getTableWidth(me, needIEHack, getDefaultValue(me)))) }); } }); //重写execCommand命令,用于处理框选时的处理 var oldExecCommand = me.execCommand; me.execCommand = function (cmd, datatat) { var me = this, args = arguments; cmd = cmd.toLowerCase(); var ut = getUETableBySelected(me), tds, range = new dom.Range(me.document), cmdFun = me.commands[cmd] || UE.commands[cmd], result; if (!cmdFun) return; if (ut && !commands[cmd] && !cmdFun.notNeedUndo && !me.__hasEnterExecCommand) { me.__hasEnterExecCommand = true; me.fireEvent("beforeexeccommand", cmd); tds = ut.selectedTds; var lastState = -2, lastValue = -2, value, state; for (var i = 0, td; td = tds[i]; i++) { if (isEmptyBlock(td)) { range.setStart(td, 0).setCursor(false, true) } else { range.selectNode(td).select(true); } state = me.queryCommandState(cmd); value = me.queryCommandValue(cmd); if (state != -1) { if (lastState !== state || lastValue !== value) { me._ignoreContentChange = true; result = oldExecCommand.apply(me, arguments); me._ignoreContentChange = false; } lastState = me.queryCommandState(cmd); lastValue = me.queryCommandValue(cmd); if (domUtils.isEmptyBlock(td)) { domUtils.fillNode(me.document, td) } } } range.setStart(tds[0], 0).shrinkBoundary(true).setCursor(false, true); me.fireEvent('contentchange'); me.fireEvent("afterexeccommand", cmd); me.__hasEnterExecCommand = false; me._selectionChange(); } else { result = oldExecCommand.apply(me, arguments); } return result; }; }); /** * 删除obj的宽高style,改成属性宽高 * @param obj * @param replaceToProperty */ function removeStyleSize(obj, replaceToProperty) { removeStyle(obj, "width", true); removeStyle(obj, "height", true); } function removeStyle(obj, styleName, replaceToProperty) { if (obj.style[styleName]) { replaceToProperty && obj.setAttribute(styleName, parseInt(obj.style[styleName], 10)); obj.style[styleName] = ""; } } function getParentTdOrTh(ele) { if (ele.tagName == "TD" || ele.tagName == "TH") return ele; var td; if (td = domUtils.findParentByTagName(ele, "td", true) || domUtils.findParentByTagName(ele, "th", true)) return td; return null; } function isEmptyBlock(node) { var reg = new RegExp(domUtils.fillChar, 'g'); if (node[browser.ie ? 'innerText' : 'textContent'].replace(/^\s*$/, '').replace(reg, '').length > 0) { return 0; } for (var n in dtd.$isNotEmpty) { if (node.getElementsByTagName(n).length) { return 0; } } return 1; } function mouseCoords(evt) { if (evt.pageX || evt.pageY) { return { x:evt.pageX, y:evt.pageY }; } return { x:evt.clientX + me.document.body.scrollLeft - me.document.body.clientLeft, y:evt.clientY + me.document.body.scrollTop - me.document.body.clientTop }; } function mouseMoveEvent(evt) { if( isEditorDisabled() ) { return; } try { //普通状态下鼠标移动 var target = getParentTdOrTh(evt.target || evt.srcElement), pos; //区分用户的行为是拖动还是双击 if( isInResizeBuffer ) { me.body.style.webkitUserSelect = 'none'; if( Math.abs( userActionStatus.x - evt.clientX ) > offsetOfTableCell || Math.abs( userActionStatus.y - evt.clientY ) > offsetOfTableCell ) { clearTableDragTimer(); isInResizeBuffer = false; singleClickState = 0; //drag action tableBorderDrag(evt); } } //修改单元格大小时的鼠标移动 if (onDrag && dragTd) { singleClickState = 0; me.body.style.webkitUserSelect = 'none'; me.selection.getNative()[browser.ie ? 'empty' : 'removeAllRanges'](); pos = mouseCoords(evt); toggleDraggableState(me, true, onDrag, pos, target); if (onDrag == "h") { dragLine.style.left = getPermissionX(dragTd, evt) + "px"; } else if (onDrag == "v") { dragLine.style.top = getPermissionY(dragTd, evt) + "px"; } return; } //当鼠标处于table上时,修改移动过程中的光标状态 if (target) { //针对使用table作为容器的组件不触发拖拽效果 if (me.fireEvent('excludetable', target) === true) return; pos = mouseCoords(evt); var state = getRelation(target, pos), table = domUtils.findParentByTagName(target, "table", true); if (inTableSide(table, target, evt, true)) { if (me.fireEvent("excludetable", table) === true) return; me.body.style.cursor = "url(" + me.options.cursorpath + "h.png),pointer"; } else if (inTableSide(table, target, evt)) { if (me.fireEvent("excludetable", table) === true) return; me.body.style.cursor = "url(" + me.options.cursorpath + "v.png),pointer"; } else { me.body.style.cursor = "text"; var curCell = target; if (/\d/.test(state)) { state = state.replace(/\d/, ''); target = getUETable(target).getPreviewCell(target, state == "v"); } //位于第一行的顶部或者第一列的左边时不可拖动 toggleDraggableState(me, target ? !!state : false, target ? state : '', pos, target); } } else { toggleDragButton(false, table, me); } } catch (e) { showError(e); } } var dragButtonTimer; function toggleDragButton(show, table, editor) { if (!show) { if (dragOver)return; dragButtonTimer = setTimeout(function () { !dragOver && dragButton && dragButton.parentNode && dragButton.parentNode.removeChild(dragButton); }, 2000); } else { createDragButton(table, editor); } } function createDragButton(table, editor) { var pos = domUtils.getXY(table), doc = table.ownerDocument; if (dragButton && dragButton.parentNode)return dragButton; dragButton = doc.createElement("div"); dragButton.contentEditable = false; dragButton.innerHTML = ""; dragButton.style.cssText = "width:15px;height:15px;background-image:url(" + editor.options.UEDITOR_HOME_URL + "dialogs/table/dragicon.png);position: absolute;cursor:move;top:" + (pos.y - 15) + "px;left:" + (pos.x) + "px;"; domUtils.unSelectable(dragButton); dragButton.onmouseover = function (evt) { dragOver = true; }; dragButton.onmouseout = function (evt) { dragOver = false; }; domUtils.on(dragButton, 'click', function (type, evt) { doClick(evt, this); }); domUtils.on(dragButton, 'dblclick', function (type, evt) { doDblClick(evt); }); domUtils.on(dragButton, 'dragstart', function (type, evt) { domUtils.preventDefault(evt); }); var timer; function doClick(evt, button) { // 部分浏览器下需要清理 clearTimeout(timer); timer = setTimeout(function () { editor.fireEvent("tableClicked", table, button); }, 300); } function doDblClick(evt) { clearTimeout(timer); var ut = getUETable(table), start = table.rows[0].cells[0], end = ut.getLastCell(), range = ut.getCellsRange(start, end); editor.selection.getRange().setStart(start, 0).setCursor(false, true); ut.setSelected(range); } doc.body.appendChild(dragButton); } // function inPosition(table, pos) { // var tablePos = domUtils.getXY(table), // width = table.offsetWidth, // height = table.offsetHeight; // if (pos.x - tablePos.x < 5 && pos.y - tablePos.y < 5) { // return "topLeft"; // } else if (tablePos.x + width - pos.x < 5 && tablePos.y + height - pos.y < 5) { // return "bottomRight"; // } // } function inTableSide(table, cell, evt, top) { var pos = mouseCoords(evt), state = getRelation(cell, pos); if (top) { var caption = table.getElementsByTagName("caption")[0], capHeight = caption ? caption.offsetHeight : 0; return (state == "v1") && ((pos.y - domUtils.getXY(table).y - capHeight) < 8); } else { return (state == "h1") && ((pos.x - domUtils.getXY(table).x) < 8); } } /** * 获取拖动时允许的X轴坐标 * @param dragTd * @param evt */ function getPermissionX(dragTd, evt) { var ut = getUETable(dragTd); if (ut) { var preTd = ut.getSameEndPosCells(dragTd, "x")[0], nextTd = ut.getSameStartPosXCells(dragTd)[0], mouseX = mouseCoords(evt).x, left = (preTd ? domUtils.getXY(preTd).x : domUtils.getXY(ut.table).x) + 20 , right = nextTd ? domUtils.getXY(nextTd).x + nextTd.offsetWidth - 20 : (me.body.offsetWidth + 5 || parseInt(domUtils.getComputedStyle(me.body, "width"), 10)); left += cellMinWidth; right -= cellMinWidth; return mouseX < left ? left : mouseX > right ? right : mouseX; } } /** * 获取拖动时允许的Y轴坐标 */ function getPermissionY(dragTd, evt) { try { var top = domUtils.getXY(dragTd).y, mousePosY = mouseCoords(evt).y; return mousePosY < top ? top : mousePosY; } catch (e) { showError(e); } } /** * 移动状态切换 */ function toggleDraggableState(editor, draggable, dir, mousePos, cell) { try { editor.body.style.cursor = dir == "h" ? "col-resize" : dir == "v" ? "row-resize" : "text"; if (browser.ie) { if (dir && !mousedown && !getUETableBySelected(editor)) { getDragLine(editor, editor.document); showDragLineAt(dir, cell); } else { hideDragLine(editor) } } onBorder = draggable; } catch (e) { showError(e); } } /** * 获取与UETable相关的resize line * @param uetable UETable对象 */ function getResizeLineByUETable() { var lineId = '_UETableResizeLine', line = this.document.getElementById( lineId ); if( !line ) { line = this.document.createElement("div"); line.id = lineId; line.contnetEditable = false; line.setAttribute("unselectable", "on"); var styles = { width: 2*cellBorderWidth + 1 + 'px', position: 'absolute', 'z-index': 100000, cursor: 'col-resize', background: 'red', display: 'none' }; //切换状态 line.onmouseout = function(){ this.style.display = 'none'; }; utils.extend( line.style, styles ); this.document.body.appendChild( line ); } return line; } /** * 更新resize-line */ function updateResizeLine( cell, uetable ) { var line = getResizeLineByUETable.call( this ), table = uetable.table, styles = { top: domUtils.getXY( table ).y + 'px', left: domUtils.getXY( cell).x + cell.offsetWidth - cellBorderWidth + 'px', display: 'block', height: table.offsetHeight + 'px' }; utils.extend( line.style, styles ); } /** * 显示resize-line */ function showResizeLine( cell ) { var uetable = getUETable( cell ); updateResizeLine.call( this, cell, uetable ); } /** * 获取鼠标与当前单元格的相对位置 * @param ele * @param mousePos */ function getRelation(ele, mousePos) { var elePos = domUtils.getXY(ele); if( !elePos ) { return ''; } if (elePos.x + ele.offsetWidth - mousePos.x < cellBorderWidth) { return "h"; } if (mousePos.x - elePos.x < cellBorderWidth) { return 'h1' } if (elePos.y + ele.offsetHeight - mousePos.y < cellBorderWidth) { return "v"; } if (mousePos.y - elePos.y < cellBorderWidth) { return 'v1' } return ''; } function mouseDownEvent(type, evt) { if( isEditorDisabled() ) { return ; } userActionStatus = { x: evt.clientX, y: evt.clientY }; //右键菜单单独处理 if (evt.button == 2) { var ut = getUETableBySelected(me), flag = false; if (ut) { var td = getTargetTd(me, evt); utils.each(ut.selectedTds, function (ti) { if (ti === td) { flag = true; } }); if (!flag) { removeSelectedClass(domUtils.getElementsByTagName(me.body, "th td")); ut.clearSelected() } else { td = ut.selectedTds[0]; setTimeout(function () { me.selection.getRange().setStart(td, 0).setCursor(false, true); }, 0); } } } else { tableClickHander( evt ); } } //清除表格的计时器 function clearTableTimer() { tabTimer && clearTimeout( tabTimer ); tabTimer = null; } //双击收缩 function tableDbclickHandler(evt) { singleClickState = 0; evt = evt || me.window.event; var target = getParentTdOrTh(evt.target || evt.srcElement); if (target) { var h; if (h = getRelation(target, mouseCoords(evt))) { hideDragLine( me ); if (h == 'h1') { h = 'h'; if (inTableSide(domUtils.findParentByTagName(target, "table"), target, evt)) { me.execCommand('adaptbywindow'); } else { target = getUETable(target).getPreviewCell(target); if (target) { var rng = me.selection.getRange(); rng.selectNodeContents(target).setCursor(true, true) } } } if (h == 'h') { var ut = getUETable(target), table = ut.table, cells = getCellsByMoveBorder( target, table, true ); cells = extractArray( cells, 'left' ); ut.width = ut.offsetWidth; var oldWidth = [], newWidth = []; utils.each( cells, function( cell ){ oldWidth.push( cell.offsetWidth ); } ); utils.each( cells, function( cell ){ cell.removeAttribute("width"); } ); window.setTimeout( function(){ //是否允许改变 var changeable = true; utils.each( cells, function( cell, index ){ var width = cell.offsetWidth; if( width > oldWidth[index] ) { changeable = false; return false; } newWidth.push( width ); } ); var change = changeable ? newWidth : oldWidth; utils.each( cells, function( cell, index ){ cell.width = change[index] - getTabcellSpace(); } ); }, 0 ); // minWidth -= cellMinWidth; // // table.removeAttribute("width"); // utils.each(cells, function (cell) { // cell.style.width = ""; // cell.width -= minWidth; // }); } } } } function tableClickHander( evt ) { removeSelectedClass(domUtils.getElementsByTagName(me.body, "td th")); //trace:3113 //选中单元格,点击table外部,不会清掉table上挂的ueTable,会引起getUETableBySelected方法返回值 utils.each(me.document.getElementsByTagName('table'), function (t) { t.ueTable = null; }); startTd = getTargetTd(me, evt); if( !startTd ) return; var table = domUtils.findParentByTagName(startTd, "table", true); ut = getUETable(table); ut && ut.clearSelected(); //判断当前鼠标状态 if (!onBorder) { me.document.body.style.webkitUserSelect = ''; mousedown = true; me.addListener('mouseover', mouseOverEvent); } else { //边框上的动作处理 borderActionHandler( evt ); } } //处理表格边框上的动作, 这里做延时处理,避免两种动作互相影响 function borderActionHandler( evt ) { if ( browser.ie ) { evt = reconstruct(evt ); } clearTableDragTimer(); //是否正在等待resize的缓冲中 isInResizeBuffer = true; tableDragTimer = setTimeout(function(){ tableBorderDrag( evt ); }, dblclickTime); } function extractArray( originArr, key ) { var result = [], tmp = null; for( var i = 0, len = originArr.length; i<len; i++ ) { tmp = originArr[ i ][ key ]; if( tmp ) { result.push( tmp ); } } return result; } function clearTableDragTimer() { tableDragTimer && clearTimeout(tableDragTimer); tableDragTimer = null; } function reconstruct( obj ) { var attrs = ['pageX', 'pageY', 'clientX', 'clientY', 'srcElement', 'target'], newObj = {}; if( obj ) { for( var i = 0, key, val; key = attrs[i]; i++ ) { val=obj[ key ]; val && (newObj[ key ] = val); } } return newObj; } //边框拖动 function tableBorderDrag( evt ) { isInResizeBuffer = false; if( !startTd ) return; var state = Math.abs( userActionStatus.x - evt.clientX ) >= Math.abs( userActionStatus.y - evt.clientY ) ? 'h' : 'v'; // var state = getRelation(startTd, mouseCoords(evt)); if (/\d/.test(state)) { state = state.replace(/\d/, ''); startTd = getUETable(startTd).getPreviewCell(startTd, state == 'v'); } hideDragLine(me); getDragLine(me, me.document); me.fireEvent('saveScene'); showDragLineAt(state, startTd); mousedown = true; //拖动开始 onDrag = state; dragTd = startTd; } function mouseUpEvent(type, evt) { if( isEditorDisabled() ) { return ; } clearTableDragTimer(); isInResizeBuffer = false; if( onBorder ) { singleClickState = ++singleClickState % 3; userActionStatus = { x: evt.clientX, y: evt.clientY }; tableResizeTimer = setTimeout(function(){ singleClickState > 0 && singleClickState--; }, dblclickTime ); if( singleClickState === 2 ) { singleClickState = 0; tableDbclickHandler(evt); return; } } if (evt.button == 2)return; var me = this; //清除表格上原生跨选问题 var range = me.selection.getRange(), start = domUtils.findParentByTagName(range.startContainer, 'table', true), end = domUtils.findParentByTagName(range.endContainer, 'table', true); if (start || end) { if (start === end) { start = domUtils.findParentByTagName(range.startContainer, ['td', 'th', 'caption'], true); end = domUtils.findParentByTagName(range.endContainer, ['td', 'th', 'caption'], true); if (start !== end) { me.selection.clearRange() } } else { me.selection.clearRange() } } mousedown = false; me.document.body.style.webkitUserSelect = ''; //拖拽状态下的mouseUP if ( onDrag && dragTd ) { me.selection.getNative()[browser.ie ? 'empty' : 'removeAllRanges'](); singleClickState = 0; dragLine = me.document.getElementById('ue_tableDragLine'); var dragTdPos = domUtils.getXY(dragTd), dragLinePos = domUtils.getXY(dragLine); switch (onDrag) { case "h": changeColWidth(dragTd, dragLinePos.x - dragTdPos.x); break; case "v": changeRowHeight(dragTd, dragLinePos.y - dragTdPos.y - dragTd.offsetHeight); break; default: } onDrag = ""; dragTd = null; hideDragLine(me); me.fireEvent('saveScene'); return; } //正常状态下的mouseup if (!startTd) { var target = domUtils.findParentByTagName(evt.target || evt.srcElement, "td", true); if (!target) target = domUtils.findParentByTagName(evt.target || evt.srcElement, "th", true); if (target && (target.tagName == "TD" || target.tagName == "TH")) { if (me.fireEvent("excludetable", target) === true) return; range = new dom.Range(me.document); range.setStart(target, 0).setCursor(false, true); } } else { var ut = getUETable(startTd), cell = ut ? ut.selectedTds[0] : null; if (cell) { range = new dom.Range(me.document); if (domUtils.isEmptyBlock(cell)) { range.setStart(cell, 0).setCursor(false, true); } else { range.selectNodeContents(cell).shrinkBoundary().setCursor(false, true); } } else { range = me.selection.getRange().shrinkBoundary(); if (!range.collapsed) { var start = domUtils.findParentByTagName(range.startContainer, ['td', 'th'], true), end = domUtils.findParentByTagName(range.endContainer, ['td', 'th'], true); //在table里边的不能清除 if (start && !end || !start && end || start && end && start !== end) { range.setCursor(false, true); } } } startTd = null; me.removeListener('mouseover', mouseOverEvent); } me._selectionChange(250, evt); } function mouseOverEvent(type, evt) { if( isEditorDisabled() ) { return; } var me = this, tar = evt.target || evt.srcElement; currentTd = domUtils.findParentByTagName(tar, "td", true) || domUtils.findParentByTagName(tar, "th", true); //需要判断两个TD是否位于同一个表格内 if (startTd && currentTd && ((startTd.tagName == "TD" && currentTd.tagName == "TD") || (startTd.tagName == "TH" && currentTd.tagName == "TH")) && domUtils.findParentByTagName(startTd, 'table') == domUtils.findParentByTagName(currentTd, 'table')) { var ut = getUETable(currentTd); if (startTd != currentTd) { me.document.body.style.webkitUserSelect = 'none'; me.selection.getNative()[browser.ie ? 'empty' : 'removeAllRanges'](); var range = ut.getCellsRange(startTd, currentTd); ut.setSelected(range); } else { me.document.body.style.webkitUserSelect = ''; ut.clearSelected(); } } evt.preventDefault ? evt.preventDefault() : (evt.returnValue = false); } function setCellHeight(cell, height, backHeight) { var lineHight = parseInt(domUtils.getComputedStyle(cell, "line-height"), 10), tmpHeight = backHeight + height; height = tmpHeight < lineHight ? lineHight : tmpHeight; if (cell.style.height) cell.style.height = ""; cell.rowSpan == 1 ? cell.setAttribute("height", height) : (cell.removeAttribute && cell.removeAttribute("height")); } function getWidth(cell) { if (!cell)return 0; return parseInt(domUtils.getComputedStyle(cell, "width"), 10); } function changeColWidth(cell, changeValue) { var ut = getUETable(cell); if (ut) { //根据当前移动的边框获取相关的单元格 var table = ut.table, cells = getCellsByMoveBorder( cell, table ); table.style.width = ""; table.removeAttribute("width"); //修正改变量 changeValue = correctChangeValue( changeValue, cell, cells ); if (cell.nextSibling) { var i=0; utils.each( cells, function( cellGroup ){ cellGroup.left.width = (+cellGroup.left.width)+changeValue; cellGroup.right && ( cellGroup.right.width = (+cellGroup.right.width)-changeValue ); } ); } else { utils.each( cells, function( cellGroup ){ cellGroup.left.width -= -changeValue; } ); } } } function isEditorDisabled() { return me.body.contentEditable === "false"; } function changeRowHeight(td, changeValue) { if (Math.abs(changeValue) < 10) return; var ut = getUETable(td); if (ut) { var cells = ut.getSameEndPosCells(td, "y"), //备份需要连带变化的td的原始高度,否则后期无法获取正确的值 backHeight = cells[0] ? cells[0].offsetHeight : 0; for (var i = 0, cell; cell = cells[i++];) { setCellHeight(cell, changeValue, backHeight); } } } /** * 获取调整单元格大小的相关单元格 * @isContainMergeCell 返回的结果中是否包含发生合并后的单元格 */ function getCellsByMoveBorder( cell, table, isContainMergeCell ) { if( !table ) { table = domUtils.findParentByTagName( cell, 'table' ); } if( !table ) { return null; } //获取到该单元格所在行的序列号 var index = domUtils.getNodeIndex( cell ), temp = cell, rows = table.rows, colIndex = 0; while( temp ) { //获取到当前单元格在未发生单元格合并时的序列 if( temp.nodeType === 1 ) { colIndex += (temp.colSpan || 1); } temp = temp.previousSibling; } temp = null; //记录想关的单元格 var borderCells = []; utils.each(rows, function( tabRow ){ var cells = tabRow.cells, currIndex = 0; utils.each( cells, function( tabCell ){ currIndex += (tabCell.colSpan || 1); if( currIndex === colIndex ) { borderCells.push({ left: tabCell, right: tabCell.nextSibling || null }); return false; } else if( currIndex > colIndex ) { if( isContainMergeCell ) { borderCells.push({ left: tabCell }); } return false; } } ); }); return borderCells; } /** * 通过给定的单元格集合获取最小的单元格width */ function getMinWidthByTableCells( cells ) { var minWidth = Number.MAX_VALUE; for( var i = 0, curCell; curCell = cells[ i ] ; i++ ) { minWidth = Math.min( minWidth, curCell.width || getTableCellWidth( curCell ) ); } return minWidth; } function correctChangeValue( changeValue, relatedCell, cells ) { //为单元格的paading预留空间 changeValue -= getTabcellSpace(); if( changeValue < 0 ) { return 0; } changeValue -= getTableCellWidth( relatedCell ); //确定方向 var direction = changeValue < 0 ? 'left':'right'; changeValue = Math.abs(changeValue); //只关心非最后一个单元格就可以 utils.each( cells, function( cellGroup ){ var curCell = cellGroup[direction]; //为单元格保留最小空间 if( curCell ) { changeValue = Math.min( changeValue, getTableCellWidth( curCell )-cellMinWidth ); } } ); //修正越界 changeValue = changeValue < 0 ? 0 : changeValue; return direction === 'left' ? -changeValue : changeValue; } function getTableCellWidth( cell ) { var width = 0, //偏移纠正量 offset = 0, width = cell.offsetWidth - getTabcellSpace(); //最后一个节点纠正一下 if( !cell.nextSibling ) { width -= getTableCellOffset( cell ); } width = width < 0 ? 0 : width; try { cell.width = width; } catch(e) { } return width; } /** * 获取单元格所在表格的最末单元格的偏移量 */ function getTableCellOffset( cell ) { tab = domUtils.findParentByTagName( cell, "table", false); if( tab.offsetVal === undefined ) { var prev = cell.previousSibling; if( prev ) { //最后一个单元格和前一个单元格的width diff结果 如果恰好为一个border width, 则条件成立 tab.offsetVal = cell.offsetWidth - prev.offsetWidth === UT.borderWidth ? UT.borderWidth : 0; } else { tab.offsetVal = 0; } } return tab.offsetVal; } function getTabcellSpace() { if( UT.tabcellSpace === undefined ) { var cell = null, tab = me.document.createElement("table"), tbody = me.document.createElement("tbody"), trow = me.document.createElement("tr"), tabcell = me.document.createElement("td"), mirror = null; tabcell.style.cssText = 'border: 0;'; tabcell.width = 1; trow.appendChild( tabcell ); trow.appendChild( mirror = tabcell.cloneNode( false ) ); tbody.appendChild( trow ); tab.appendChild( tbody ); tab.style.cssText = "visibility: hidden;"; me.body.appendChild( tab ); UT.paddingSpace = tabcell.offsetWidth - 1; var tmpTabWidth = tab.offsetWidth; tabcell.style.cssText = ''; mirror.style.cssText = ''; UT.borderWidth = ( tab.offsetWidth - tmpTabWidth ) / 3; UT.tabcellSpace = UT.paddingSpace + UT.borderWidth; me.body.removeChild( tab ); } getTabcellSpace = function(){ return UT.tabcellSpace; }; return UT.tabcellSpace; } function getDragLine(editor, doc) { if (mousedown)return; dragLine = editor.document.createElement("div"); domUtils.setAttributes(dragLine, { id:"ue_tableDragLine", unselectable:'on', contenteditable:false, 'onresizestart':'return false', 'ondragstart':'return false', 'onselectstart':'return false', style:"background-color:blue;position:absolute;padding:0;margin:0;background-image:none;border:0px none;opacity:0;filter:alpha(opacity=0)" }); editor.body.appendChild(dragLine); } function hideDragLine(editor) { if (mousedown)return; var line; while (line = editor.document.getElementById('ue_tableDragLine')) { domUtils.remove(line) } } /** * 依据state(v|h)在cell位置显示横线 * @param state * @param cell */ function showDragLineAt(state, cell) { if (!cell) return; var table = domUtils.findParentByTagName(cell, "table"), caption = table.getElementsByTagName('caption'), width = table.offsetWidth, height = table.offsetHeight - (caption.length > 0 ? caption[0].offsetHeight : 0), tablePos = domUtils.getXY(table), cellPos = domUtils.getXY(cell), css; switch (state) { case "h": css = 'height:' + height + 'px;top:' + (tablePos.y + (caption.length > 0 ? caption[0].offsetHeight : 0)) + 'px;left:' + (cellPos.x + cell.offsetWidth); dragLine.style.cssText = css + 'px;position: absolute;display:block;background-color:blue;width:1px;border:0; color:blue;opacity:.3;filter:alpha(opacity=30)'; break; case "v": css = 'width:' + width + 'px;left:' + tablePos.x + 'px;top:' + (cellPos.y + cell.offsetHeight ); //必须加上border:0和color:blue,否则低版ie不支持背景色显示 dragLine.style.cssText = css + 'px;overflow:hidden;position: absolute;display:block;background-color:blue;height:1px;border:0;color:blue;opacity:.2;filter:alpha(opacity=20)'; break; default: } } /** * 当表格边框颜色为白色时设置为虚线,true为添加虚线 * @param editor * @param flag */ function switchBorderColor(editor, flag) { var tableArr = domUtils.getElementsByTagName(editor.body, "table"), color; for (var i = 0, node; node = tableArr[i++];) { var td = domUtils.getElementsByTagName(node, "td"); if (td[0]) { if (flag) { color = (td[0].style.borderColor).replace(/\s/g, ""); if (/(#ffffff)|(rgb\(255,f55,255\))/ig.test(color)) domUtils.addClass(node, "noBorderTable") } else { domUtils.removeClasses(node, "noBorderTable") } } } } function getTableWidth(editor, needIEHack, defaultValue) { var body = editor.body; return body.offsetWidth - (needIEHack ? parseInt(domUtils.getComputedStyle(body, 'margin-left'), 10) * 2 : 0) - defaultValue.tableBorder * 2 - (editor.options.offsetWidth || 0); } /** * 获取当前拖动的单元格 */ function getTargetTd(editor, evt) { var target = domUtils.findParentByTagName(evt.target || evt.srcElement, ["td", "th"], true), dir = null; if( !target ) { return null; } dir = getRelation( target, mouseCoords( evt ) ); //如果有前一个节点, 需要做一个修正, 否则可能会得到一个错误的td if( !target ) { return null; } if( dir === 'h1' && target.previousSibling ) { var position = domUtils.getXY( target), cellWidth = target.offsetWidth; if( Math.abs( position.x + cellWidth - evt.clientX ) > cellWidth / 3 ) { target = target.previousSibling; } } else if( dir === 'v1' && target.parentNode.previousSibling ) { var position = domUtils.getXY( target), cellHeight = target.offsetHeight; if( Math.abs( position.y + cellHeight - evt.clientY ) > cellHeight / 3 ) { target = target.parentNode.previousSibling.firstChild; } } //排除了非td内部以及用于代码高亮部分的td return target && !(editor.fireEvent("excludetable", target) === true) ? target : null; } }; ///import core ///commands 右键菜单 ///commandsName ContextMenu ///commandsTitle 右键菜单 /** * 右键菜单 * @function * @name baidu.editor.plugins.contextmenu * @author zhanyi */ UE.plugins['contextmenu'] = function () { var me = this, lang = me.getLang( "contextMenu" ), menu, items = me.options.contextMenu || [ {label:lang['selectall'], cmdName:'selectall'}, { label:lang.deletecode, cmdName:'highlightcode', icon:'deletehighlightcode' }, { label:lang.cleardoc, cmdName:'cleardoc', exec:function () { if ( confirm( lang.confirmclear ) ) { this.execCommand( 'cleardoc' ); } } }, '-', { label:lang.unlink, cmdName:'unlink' }, '-', { group:lang.paragraph, icon:'justifyjustify', subMenu:[ { label:lang.justifyleft, cmdName:'justify', value:'left' }, { label:lang.justifyright, cmdName:'justify', value:'right' }, { label:lang.justifycenter, cmdName:'justify', value:'center' }, { label:lang.justifyjustify, cmdName:'justify', value:'justify' } ] }, '-', { group:lang.table, icon:'table', subMenu:[ { label:lang.inserttable, cmdName:'inserttable' }, { label:lang.deletetable, cmdName:'deletetable' }, '-', { label:lang.deleterow, cmdName:'deleterow' }, { label:lang.deletecol, cmdName:'deletecol' }, { label:lang.insertcol, cmdName:'insertcol' }, { label:lang.insertcolnext, cmdName:'insertcolnext' }, { label:lang.insertrow, cmdName:'insertrow' }, { label:lang.insertrownext, cmdName:'insertrownext' }, '-', { label:lang.insertcaption, cmdName:'insertcaption' }, { label:lang.deletecaption, cmdName:'deletecaption' }, { label:lang.inserttitle, cmdName:'inserttitle' }, { label:lang.deletetitle, cmdName:'deletetitle' }, '-', { label:lang.mergecells, cmdName:'mergecells' }, { label:lang.mergeright, cmdName:'mergeright' }, { label:lang.mergedown, cmdName:'mergedown' }, '-', { label:lang.splittorows, cmdName:'splittorows' }, { label:lang.splittocols, cmdName:'splittocols' }, { label:lang.splittocells, cmdName:'splittocells' }, '-', { label:lang.averageDiseRow, cmdName:'averagedistributerow' }, { label:lang.averageDisCol, cmdName:'averagedistributecol' }, '-', { label:lang.edittd, cmdName:'edittd', exec:function () { if ( UE.ui['edittd'] ) { new UE.ui['edittd']( this ); } this.getDialog('edittd').open(); } }, { label:lang.edittable, cmdName:'edittable', exec:function () { if ( UE.ui['edittable'] ) { new UE.ui['edittable']( this ); } this.getDialog('edittable').open(); } } ] }, { group:lang.tablesort, icon:'tablesort', subMenu:[ { label:lang.reversecurrent, cmdName:'sorttable', value:1 }, { label:lang.orderbyasc, cmdName:'sorttable' }, { label:lang.reversebyasc, cmdName:'sorttable', exec:function(){ this.execCommand("sorttable",function(td1,td2){ var value1 = td1.innerHTML, value2 = td2.innerHTML; return value2.localeCompare(value1); }); } }, { label:lang.orderbynum, cmdName:'sorttable', exec:function(){ this.execCommand("sorttable",function(td1,td2){ var value1 = td1[browser.ie ? 'innerText':'textContent'].match(/\d+/), value2 = td2[browser.ie ? 'innerText':'textContent'].match(/\d+/); if(value1) value1 = +value1[0]; if(value2) value2 = +value2[0]; return (value1||0) - (value2||0); }); } }, { label:lang.reversebynum, cmdName:'sorttable', exec:function(){ this.execCommand("sorttable",function(td1,td2){ var value1 = td1[browser.ie ? 'innerText':'textContent'].match(/\d+/), value2 = td2[browser.ie ? 'innerText':'textContent'].match(/\d+/); if(value1) value1 = +value1[0]; if(value2) value2 = +value2[0]; return (value2||0) - (value1||0); }); } } ] }, { group:lang.borderbk, icon:'borderBack', subMenu:[ { label:lang.setcolor, cmdName:"interlacetable", exec:function(){ this.execCommand("interlacetable"); } }, { label:lang.unsetcolor, cmdName:"uninterlacetable", exec:function(){ this.execCommand("uninterlacetable"); } }, { label:lang.setbackground, cmdName:"settablebackground", exec:function(){ this.execCommand("settablebackground",{repeat:true,colorList:["#bbb","#ccc"]}); } }, { label:lang.unsetbackground, cmdName:"cleartablebackground", exec:function(){ this.execCommand("cleartablebackground"); } }, { label:lang.redandblue, cmdName:"settablebackground", exec:function(){ this.execCommand("settablebackground",{repeat:true,colorList:["red","blue"]}); } }, { label:lang.threecolorgradient, cmdName:"settablebackground", exec:function(){ this.execCommand("settablebackground",{repeat:true,colorList:["#aaa","#bbb","#ccc"]}); } } ] }, { group:lang.aligntd, icon:'aligntd', subMenu:[ { cmdName:'cellalignment', value:{align:'left',vAlign:'top'} }, { cmdName:'cellalignment', value:{align:'center',vAlign:'top'} }, { cmdName:'cellalignment', value:{align:'right',vAlign:'top'} }, { cmdName:'cellalignment', value:{align:'left',vAlign:'middle'} }, { cmdName:'cellalignment', value:{align:'center',vAlign:'middle'} }, { cmdName:'cellalignment', value:{align:'right',vAlign:'middle'} }, { cmdName:'cellalignment', value:{align:'left',vAlign:'bottom'} }, { cmdName:'cellalignment', value:{align:'center',vAlign:'bottom'} }, { cmdName:'cellalignment', value:{align:'right',vAlign:'bottom'} } ] }, { group:lang.aligntable, icon:'aligntable', subMenu:[ { cmdName:'tablealignment', className: 'left', label:lang.tableleft, value:"left" }, { cmdName:'tablealignment', className: 'center', label:lang.tablecenter, value:"center" }, { cmdName:'tablealignment', className: 'right', label:lang.tableright, value:"right" } ] }, '-', { label:lang.insertparagraphbefore, cmdName:'insertparagraph', value:true }, { label:lang.insertparagraphafter, cmdName:'insertparagraph' }, { label:lang['copy'], cmdName:'copy', exec:function () { alert( lang.copymsg ); }, query:function () { return 0; } }, { label:lang['paste'], cmdName:'paste', exec:function () { alert( lang.pastemsg ); }, query:function () { return 0; } },{ label:lang['highlightcode'], cmdName:'highlightcode', exec:function () { if ( UE.ui['highlightcode'] ) { new UE.ui['highlightcode']( this ); } this.ui._dialogs['highlightcodeDialog'].open(); } } ]; if ( !items.length ) { return; } var uiUtils = UE.ui.uiUtils; me.addListener( 'contextmenu', function ( type, evt ) { var offset = uiUtils.getViewportOffsetByEvent( evt ); me.fireEvent( 'beforeselectionchange' ); if ( menu ) { menu.destroy(); } for ( var i = 0, ti, contextItems = []; ti = items[i]; i++ ) { var last; (function ( item ) { if ( item == '-' ) { if ( (last = contextItems[contextItems.length - 1 ] ) && last !== '-' ) { contextItems.push( '-' ); } } else if ( item.hasOwnProperty( "group" ) ) { for ( var j = 0, cj, subMenu = []; cj = item.subMenu[j]; j++ ) { (function ( subItem ) { if ( subItem == '-' ) { if ( (last = subMenu[subMenu.length - 1 ] ) && last !== '-' ) { subMenu.push( '-' ); }else{ subMenu.splice(subMenu.length-1); } } else { if ( (me.commands[subItem.cmdName] || UE.commands[subItem.cmdName] || subItem.query) && (subItem.query ? subItem.query() : me.queryCommandState( subItem.cmdName )) > -1 ) { subMenu.push( { 'label':subItem.label || me.getLang( "contextMenu." + subItem.cmdName + (subItem.value || '') )||"", 'className':'edui-for-' +subItem.cmdName + ( subItem.className ? ( ' edui-for-' + subItem.cmdName + '-' + subItem.className ) : '' ), onclick:subItem.exec ? function () { subItem.exec.call( me ); } : function () { me.execCommand( subItem.cmdName, subItem.value ); } } ); } } })( cj ); } if ( subMenu.length ) { function getLabel(){ switch (item.icon){ case "table": return me.getLang( "contextMenu.table" ); case "justifyjustify": return me.getLang( "contextMenu.paragraph" ); case "aligntd": return me.getLang("contextMenu.aligntd"); case "aligntable": return me.getLang("contextMenu.aligntable"); case "tablesort": return lang.tablesort; case "borderBack": return lang.borderbk; default : return ''; } } contextItems.push( { //todo 修正成自动获取方式 'label':getLabel(), className:'edui-for-' + item.icon, 'subMenu':{ items:subMenu, editor:me } } ); } } else { //有可能commmand没有加载右键不能出来,或者没有command也想能展示出来添加query方法 if ( (me.commands[item.cmdName] || UE.commands[item.cmdName] || item.query) && (item.query ? item.query.call(me) : me.queryCommandState( item.cmdName )) > -1 ) { //highlight todo if ( item.cmdName == 'highlightcode' ) { if(me.queryCommandState( item.cmdName ) == 1 && item.icon != 'deletehighlightcode'){ return; } if(me.queryCommandState( item.cmdName ) != 1 && item.icon == 'deletehighlightcode'){ return; } } contextItems.push( { 'label':item.label || me.getLang( "contextMenu." + item.cmdName ), className:'edui-for-' + (item.icon ? item.icon : item.cmdName + (item.value || '')), onclick:item.exec ? function () { item.exec.call( me ); } : function () { me.execCommand( item.cmdName, item.value ); } } ); } } })( ti ); } if ( contextItems[contextItems.length - 1] == '-' ) { contextItems.pop(); } menu = new UE.ui.Menu( { items:contextItems, className:"edui-contextmenu", editor:me } ); menu.render(); menu.showAt( offset ); me.fireEvent("aftershowcontextmenu",menu); domUtils.preventDefault( evt ); if ( browser.ie ) { var ieRange; try { ieRange = me.selection.getNative().createRange(); } catch ( e ) { return; } if ( ieRange.item ) { var range = new dom.Range( me.document ); range.selectNode( ieRange.item( 0 ) ).select( true, true ); } } } ); }; ///import core ///commands 加粗,斜体,上标,下标 ///commandsName Bold,Italic,Subscript,Superscript ///commandsTitle 加粗,加斜,下标,上标 /** * b u i等基础功能实现 * @function * @name baidu.editor.execCommands * @param {String} cmdName bold加粗。italic斜体。subscript上标。superscript下标。 */ UE.plugins['basestyle'] = function(){ var basestyles = { 'bold':['strong','b'], 'italic':['em','i'], 'subscript':['sub'], 'superscript':['sup'] }, getObj = function(editor,tagNames){ return domUtils.filterNodeList(editor.selection.getStartElementPath(),tagNames); }, me = this; //添加快捷键 me.addshortcutkey({ "Bold" : "ctrl+66",//^B "Italic" : "ctrl+73", //^I "Underline" : "ctrl+85"//^U }); me.addInputRule(function(root){ utils.each(root.getNodesByTagName('b i'),function(node){ switch (node.tagName){ case 'b': node.tagName = 'strong'; break; case 'i': node.tagName = 'em'; } }); }); for ( var style in basestyles ) { (function( cmd, tagNames ) { me.commands[cmd] = { execCommand : function( cmdName ) { var range = me.selection.getRange(),obj = getObj(this,tagNames); if ( range.collapsed ) { if ( obj ) { var tmpText = me.document.createTextNode(''); range.insertNode( tmpText ).removeInlineStyle( tagNames ); range.setStartBefore(tmpText); domUtils.remove(tmpText); } else { var tmpNode = range.document.createElement( tagNames[0] ); if(cmdName == 'superscript' || cmdName == 'subscript'){ tmpText = me.document.createTextNode(''); range.insertNode(tmpText) .removeInlineStyle(['sub','sup']) .setStartBefore(tmpText) .collapse(true); } range.insertNode( tmpNode ).setStart( tmpNode, 0 ); } range.collapse( true ); } else { if(cmdName == 'superscript' || cmdName == 'subscript'){ if(!obj || obj.tagName.toLowerCase() != cmdName){ range.removeInlineStyle(['sub','sup']); } } obj ? range.removeInlineStyle( tagNames ) : range.applyInlineStyle( tagNames[0] ); } range.select(); }, queryCommandState : function() { return getObj(this,tagNames) ? 1 : 0; } }; })( style, basestyles[style] ); } }; ///import core ///import plugins/inserthtml.js ///commands 音乐 ///commandsName Music ///commandsTitle 插入音乐 ///commandsDialog dialogs\music UE.plugins['music'] = function () { var me = this, div; /** * 创建插入音乐字符窜 * @param url 音乐地址 * @param width 音乐宽度 * @param height 音乐高度 * @param align 阴雨对齐 * @param toEmbed 是否以flash代替显示 * @param addParagraph 是否需要添加P标签 */ function creatInsertStr(url,width,height,align,toEmbed,addParagraph){ return !toEmbed ? (addParagraph? ('<p '+ (align !="none" ? ( align == "center"? ' style="text-align:center;" ':' style="float:"'+ align ) : '') + '>'): '') + '<img align="'+align+'" width="'+ width +'" height="' + height + '" _url="'+url+'" class="edui-faked-music"' + ' src="'+me.options.langPath+me.options.lang+'/images/music.png" />' + (addParagraph?'</p>':'') : '<embed type="application/x-shockwave-flash" class="edui-faked-music" pluginspage="http://www.macromedia.com/go/getflashplayer"' + ' src="' + url + '" width="' + width + '" height="' + height + '" align="' + align + '"' + ( align !="none" ? ' style= "'+ ( align == "center"? "display:block;":" float: "+ align ) + '"' :'' ) + ' wmode="transparent" play="true" loop="false" menu="false" allowscriptaccess="never" allowfullscreen="true" >'; } function switchImgAndEmbed(img2embed) { var tmpdiv, nodes = domUtils.getElementsByTagName(me.document, !img2embed ? "embed" : "img"); for (var i = 0, node; node = nodes[i++];) { if (node.className != "edui-faked-music") { continue; } tmpdiv = me.document.createElement("div"); //先看float在看align,浮动有的是时候是在float上定义的 var align = domUtils.getComputedStyle(node,'float'); align = align == 'none' ? (node.getAttribute('align') || '') : align; tmpdiv.innerHTML = creatInsertStr(img2embed ? node.getAttribute("_url") : node.getAttribute("src"), node.width, node.height, align, img2embed); node.parentNode.replaceChild(tmpdiv.firstChild, node); } } me.addListener("beforegetcontent", function () { switchImgAndEmbed(true); }); me.addListener('aftersetcontent', function () { switchImgAndEmbed(false); }); me.addListener('aftergetcontent', function (cmdName) { if (cmdName == 'aftergetcontent' && me.queryCommandState('source')) { return; } switchImgAndEmbed(false); }); me.commands["music"] = { execCommand:function (cmd, musicObj) { var me = this, str = creatInsertStr(musicObj.url, musicObj.width || 400, musicObj.height || 95, "none", false, true); me.execCommand("inserthtml",str); }, queryCommandState:function () { var me = this, img = me.selection.getRange().getClosedNode(), flag = img && (img.className == "edui-faked-music"); return flag ? 1 : 0; } }; };var baidu = baidu || {}; baidu.editor = baidu.editor || {}; baidu.editor.ui = {};(function (){ var browser = baidu.editor.browser, domUtils = baidu.editor.dom.domUtils; var magic = '$EDITORUI'; var root = window[magic] = {}; var uidMagic = 'ID' + magic; var uidCount = 0; var uiUtils = baidu.editor.ui.uiUtils = { uid: function (obj){ return (obj ? obj[uidMagic] || (obj[uidMagic] = ++ uidCount) : ++ uidCount); }, hook: function ( fn, callback ) { var dg; if (fn && fn._callbacks) { dg = fn; } else { dg = function (){ var q; if (fn) { q = fn.apply(this, arguments); } var callbacks = dg._callbacks; var k = callbacks.length; while (k --) { var r = callbacks[k].apply(this, arguments); if (q === undefined) { q = r; } } return q; }; dg._callbacks = []; } dg._callbacks.push(callback); return dg; }, createElementByHtml: function (html){ var el = document.createElement('div'); el.innerHTML = html; el = el.firstChild; el.parentNode.removeChild(el); return el; }, getViewportElement: function (){ return (browser.ie && browser.quirks) ? document.body : document.documentElement; }, getClientRect: function (element){ var bcr; //trace IE6下在控制编辑器显隐时可能会报错,catch一下 try{ bcr = element.getBoundingClientRect(); }catch(e){ bcr={left:0,top:0,height:0,width:0} } var rect = { left: Math.round(bcr.left), top: Math.round(bcr.top), height: Math.round(bcr.bottom - bcr.top), width: Math.round(bcr.right - bcr.left) }; var doc; while ((doc = element.ownerDocument) !== document && (element = domUtils.getWindow(doc).frameElement)) { bcr = element.getBoundingClientRect(); rect.left += bcr.left; rect.top += bcr.top; } rect.bottom = rect.top + rect.height; rect.right = rect.left + rect.width; return rect; }, getViewportRect: function (){ var viewportEl = uiUtils.getViewportElement(); var width = (window.innerWidth || viewportEl.clientWidth) | 0; var height = (window.innerHeight ||viewportEl.clientHeight) | 0; return { left: 0, top: 0, height: height, width: width, bottom: height, right: width }; }, setViewportOffset: function (element, offset){ var rect; var fixedLayer = uiUtils.getFixedLayer(); if (element.parentNode === fixedLayer) { element.style.left = offset.left + 'px'; element.style.top = offset.top + 'px'; } else { domUtils.setViewportOffset(element, offset); } }, getEventOffset: function (evt){ var el = evt.target || evt.srcElement; var rect = uiUtils.getClientRect(el); var offset = uiUtils.getViewportOffsetByEvent(evt); return { left: offset.left - rect.left, top: offset.top - rect.top }; }, getViewportOffsetByEvent: function (evt){ var el = evt.target || evt.srcElement; var frameEl = domUtils.getWindow(el).frameElement; var offset = { left: evt.clientX, top: evt.clientY }; if (frameEl && el.ownerDocument !== document) { var rect = uiUtils.getClientRect(frameEl); offset.left += rect.left; offset.top += rect.top; } return offset; }, setGlobal: function (id, obj){ root[id] = obj; return magic + '["' + id + '"]'; }, unsetGlobal: function (id){ delete root[id]; }, copyAttributes: function (tgt, src){ var attributes = src.attributes; var k = attributes.length; while (k --) { var attrNode = attributes[k]; if ( attrNode.nodeName != 'style' && attrNode.nodeName != 'class' && (!browser.ie || attrNode.specified) ) { tgt.setAttribute(attrNode.nodeName, attrNode.nodeValue); } } if (src.className) { domUtils.addClass(tgt,src.className); } if (src.style.cssText) { tgt.style.cssText += ';' + src.style.cssText; } }, removeStyle: function (el, styleName){ if (el.style.removeProperty) { el.style.removeProperty(styleName); } else if (el.style.removeAttribute) { el.style.removeAttribute(styleName); } else throw ''; }, contains: function (elA, elB){ return elA && elB && (elA === elB ? false : ( elA.contains ? elA.contains(elB) : elA.compareDocumentPosition(elB) & 16 )); }, startDrag: function (evt, callbacks,doc){ var doc = doc || document; var startX = evt.clientX; var startY = evt.clientY; function handleMouseMove(evt){ var x = evt.clientX - startX; var y = evt.clientY - startY; callbacks.ondragmove(x, y,evt); if (evt.stopPropagation) { evt.stopPropagation(); } else { evt.cancelBubble = true; } } if (doc.addEventListener) { function handleMouseUp(evt){ doc.removeEventListener('mousemove', handleMouseMove, true); doc.removeEventListener('mouseup', handleMouseUp, true); window.removeEventListener('mouseup', handleMouseUp, true); callbacks.ondragstop(); } doc.addEventListener('mousemove', handleMouseMove, true); doc.addEventListener('mouseup', handleMouseUp, true); window.addEventListener('mouseup', handleMouseUp, true); evt.preventDefault(); } else { var elm = evt.srcElement; elm.setCapture(); function releaseCaptrue(){ elm.releaseCapture(); elm.detachEvent('onmousemove', handleMouseMove); elm.detachEvent('onmouseup', releaseCaptrue); elm.detachEvent('onlosecaptrue', releaseCaptrue); callbacks.ondragstop(); } elm.attachEvent('onmousemove', handleMouseMove); elm.attachEvent('onmouseup', releaseCaptrue); elm.attachEvent('onlosecaptrue', releaseCaptrue); evt.returnValue = false; } callbacks.ondragstart(); }, getFixedLayer: function (){ var layer = document.getElementById('edui_fixedlayer'); if (layer == null) { layer = document.createElement('div'); layer.id = 'edui_fixedlayer'; document.body.appendChild(layer); if (browser.ie && browser.version <= 8) { layer.style.position = 'absolute'; bindFixedLayer(); setTimeout(updateFixedOffset); } else { layer.style.position = 'fixed'; } layer.style.left = '0'; layer.style.top = '0'; layer.style.width = '0'; layer.style.height = '0'; } return layer; }, makeUnselectable: function (element){ if (browser.opera || (browser.ie && browser.version < 9)) { element.unselectable = 'on'; if (element.hasChildNodes()) { for (var i=0; i<element.childNodes.length; i++) { if (element.childNodes[i].nodeType == 1) { uiUtils.makeUnselectable(element.childNodes[i]); } } } } else { if (element.style.MozUserSelect !== undefined) { element.style.MozUserSelect = 'none'; } else if (element.style.WebkitUserSelect !== undefined) { element.style.WebkitUserSelect = 'none'; } else if (element.style.KhtmlUserSelect !== undefined) { element.style.KhtmlUserSelect = 'none'; } } } }; function updateFixedOffset(){ var layer = document.getElementById('edui_fixedlayer'); uiUtils.setViewportOffset(layer, { left: 0, top: 0 }); // layer.style.display = 'none'; // layer.style.display = 'block'; //#trace: 1354 // setTimeout(updateFixedOffset); } function bindFixedLayer(adjOffset){ domUtils.on(window, 'scroll', updateFixedOffset); domUtils.on(window, 'resize', baidu.editor.utils.defer(updateFixedOffset, 0, true)); } })(); (function () { var utils = baidu.editor.utils, uiUtils = baidu.editor.ui.uiUtils, EventBase = baidu.editor.EventBase, UIBase = baidu.editor.ui.UIBase = function () { }; UIBase.prototype = { className:'', uiName:'', initOptions:function (options) { var me = this; for (var k in options) { me[k] = options[k]; } this.id = this.id || 'edui' + uiUtils.uid(); }, initUIBase:function () { this._globalKey = utils.unhtml(uiUtils.setGlobal(this.id, this)); }, render:function (holder) { var html = this.renderHtml(); var el = uiUtils.createElementByHtml(html); //by xuheng 给每个node添加class var list = domUtils.getElementsByTagName(el, "*"); var theme = "edui-" + (this.theme || this.editor.options.theme); var layer = document.getElementById('edui_fixedlayer'); for (var i = 0, node; node = list[i++];) { domUtils.addClass(node, theme); } domUtils.addClass(el, theme); if(layer){ layer.className=""; domUtils.addClass(layer,theme); } var seatEl = this.getDom(); if (seatEl != null) { seatEl.parentNode.replaceChild(el, seatEl); uiUtils.copyAttributes(el, seatEl); } else { if (typeof holder == 'string') { holder = document.getElementById(holder); } holder = holder || uiUtils.getFixedLayer(); domUtils.addClass(holder, theme); holder.appendChild(el); } this.postRender(); }, getDom:function (name) { if (!name) { return document.getElementById(this.id); } else { return document.getElementById(this.id + '_' + name); } }, postRender:function () { this.fireEvent('postrender'); }, getHtmlTpl:function () { return ''; }, formatHtml:function (tpl) { var prefix = 'edui-' + this.uiName; return (tpl .replace(/##/g, this.id) .replace(/%%-/g, this.uiName ? prefix + '-' : '') .replace(/%%/g, (this.uiName ? prefix : '') + ' ' + this.className) .replace(/\$\$/g, this._globalKey)); }, renderHtml:function () { return this.formatHtml(this.getHtmlTpl()); }, dispose:function () { var box = this.getDom(); if (box) baidu.editor.dom.domUtils.remove(box); uiUtils.unsetGlobal(this.id); } }; utils.inherits(UIBase, EventBase); })(); (function (){ var utils = baidu.editor.utils, UIBase = baidu.editor.ui.UIBase, Separator = baidu.editor.ui.Separator = function (options){ this.initOptions(options); this.initSeparator(); }; Separator.prototype = { uiName: 'separator', initSeparator: function (){ this.initUIBase(); }, getHtmlTpl: function (){ return '<div id="##" class="edui-box %%"></div>'; } }; utils.inherits(Separator, UIBase); })(); ///import core ///import uicore (function (){ var utils = baidu.editor.utils, domUtils = baidu.editor.dom.domUtils, UIBase = baidu.editor.ui.UIBase, uiUtils = baidu.editor.ui.uiUtils; var Mask = baidu.editor.ui.Mask = function (options){ this.initOptions(options); this.initUIBase(); }; Mask.prototype = { getHtmlTpl: function (){ return '<div id="##" class="edui-mask %%" onmousedown="return $$._onMouseDown(event, this);"></div>'; }, postRender: function (){ var me = this; domUtils.on(window, 'resize', function (){ setTimeout(function (){ if (!me.isHidden()) { me._fill(); } }); }); }, show: function (zIndex){ this._fill(); this.getDom().style.display = ''; this.getDom().style.zIndex = zIndex; }, hide: function (){ this.getDom().style.display = 'none'; this.getDom().style.zIndex = ''; }, isHidden: function (){ return this.getDom().style.display == 'none'; }, _onMouseDown: function (){ return false; }, _fill: function (){ var el = this.getDom(); var vpRect = uiUtils.getViewportRect(); el.style.width = vpRect.width + 'px'; el.style.height = vpRect.height + 'px'; } }; utils.inherits(Mask, UIBase); })(); ///import core ///import uicore (function () { var utils = baidu.editor.utils, uiUtils = baidu.editor.ui.uiUtils, domUtils = baidu.editor.dom.domUtils, UIBase = baidu.editor.ui.UIBase, Popup = baidu.editor.ui.Popup = function (options){ this.initOptions(options); this.initPopup(); }; var allPopups = []; function closeAllPopup( evt,el ){ for ( var i = 0; i < allPopups.length; i++ ) { var pop = allPopups[i]; if (!pop.isHidden()) { if (pop.queryAutoHide(el) !== false) { if(evt&&/scroll/ig.test(evt.type)&&pop.className=="edui-wordpastepop") return; pop.hide(); } } } if(allPopups.length) pop.editor.fireEvent("afterhidepop"); } Popup.postHide = closeAllPopup; var ANCHOR_CLASSES = ['edui-anchor-topleft','edui-anchor-topright', 'edui-anchor-bottomleft','edui-anchor-bottomright']; Popup.prototype = { SHADOW_RADIUS: 5, content: null, _hidden: false, autoRender: true, canSideLeft: true, canSideUp: true, initPopup: function (){ this.initUIBase(); allPopups.push( this ); }, getHtmlTpl: function (){ return '<div id="##" class="edui-popup %%" onmousedown="return false;">' + ' <div id="##_body" class="edui-popup-body">' + ' <iframe style="position:absolute;z-index:-1;left:0;top:0;background-color: transparent;" frameborder="0" width="100%" height="100%" src="javascript:"></iframe>' + ' <div class="edui-shadow"></div>' + ' <div id="##_content" class="edui-popup-content">' + this.getContentHtmlTpl() + ' </div>' + ' </div>' + '</div>'; }, getContentHtmlTpl: function (){ if(this.content){ if (typeof this.content == 'string') { return this.content; } return this.content.renderHtml(); }else{ return '' } }, _UIBase_postRender: UIBase.prototype.postRender, postRender: function (){ if (this.content instanceof UIBase) { this.content.postRender(); } //捕获鼠标滚轮 if( this.captureWheel && !this.captured ) { this.captured = true; var winHeight = ( document.documentElement.clientHeight || document.body.clientHeight ) - 80, _height = this.getDom().offsetHeight, _top = domUtils.getXY( this.combox.getDom() ).y, content = this.getDom('content'), me = this; while( _top + _height > winHeight ) { _height -= 30; content.style.height = _height + 'px'; } //阻止在combox上的鼠标滚轮事件, 防止用户的正常操作被误解 if( window.XMLHttpRequest ) { domUtils.on( content, ( 'onmousewheel' in document.body ) ? 'mousewheel' :'DOMMouseScroll' , function(e){ if(e.preventDefault) { e.preventDefault(); } else { e.returnValue = false; } if( e.wheelDelta ) { content.scrollTop -= ( e.wheelDelta / 120 )*60; } else { content.scrollTop -= ( e.detail / -3 )*60; } }); } else { //ie6 domUtils.on( this.getDom(), 'mousewheel' , function(e){ e.returnValue = false; me.getDom('content').scrollTop -= ( e.wheelDelta / 120 )*60; }); } } this.fireEvent('postRenderAfter'); this.hide(true); this._UIBase_postRender(); }, _doAutoRender: function (){ if (!this.getDom() && this.autoRender) { this.render(); } }, mesureSize: function (){ var box = this.getDom('content'); return uiUtils.getClientRect(box); }, fitSize: function (){ if( this.captureWheel && this.sized ) { return this.__size; } this.sized = true; var popBodyEl = this.getDom('body'); popBodyEl.style.width = ''; popBodyEl.style.height = ''; var size = this.mesureSize(); if( this.captureWheel ) { popBodyEl.style.width = -(-20 -size.width) + 'px'; } else { popBodyEl.style.width = size.width + 'px'; } popBodyEl.style.height = size.height + 'px'; this.__size = size; this.captureWheel && (this.getDom('content').style.overflow = 'auto'); return size; }, showAnchor: function ( element, hoz ){ this.showAnchorRect( uiUtils.getClientRect( element ), hoz ); }, showAnchorRect: function ( rect, hoz, adj ){ this._doAutoRender(); var vpRect = uiUtils.getViewportRect(); this._show(); var popSize = this.fitSize(); var sideLeft, sideUp, left, top; if (hoz) { sideLeft = this.canSideLeft && (rect.right + popSize.width > vpRect.right && rect.left > popSize.width); sideUp = this.canSideUp && (rect.top + popSize.height > vpRect.bottom && rect.bottom > popSize.height); left = (sideLeft ? rect.left - popSize.width : rect.right); top = (sideUp ? rect.bottom - popSize.height : rect.top); } else { sideLeft = this.canSideLeft && (rect.right + popSize.width > vpRect.right && rect.left > popSize.width); sideUp = this.canSideUp && (rect.top + popSize.height > vpRect.bottom && rect.bottom > popSize.height); left = (sideLeft ? rect.right - popSize.width : rect.left); top = (sideUp ? rect.top - popSize.height : rect.bottom); } var popEl = this.getDom(); uiUtils.setViewportOffset(popEl, { left: left, top: top }); domUtils.removeClasses(popEl, ANCHOR_CLASSES); popEl.className += ' ' + ANCHOR_CLASSES[(sideUp ? 1 : 0) * 2 + (sideLeft ? 1 : 0)]; if(this.editor){ popEl.style.zIndex = this.editor.container.style.zIndex * 1 + 10; baidu.editor.ui.uiUtils.getFixedLayer().style.zIndex = popEl.style.zIndex - 1; } }, showAt: function (offset) { var left = offset.left; var top = offset.top; var rect = { left: left, top: top, right: left, bottom: top, height: 0, width: 0 }; this.showAnchorRect(rect, false, true); }, _show: function (){ if (this._hidden) { var box = this.getDom(); box.style.display = ''; this._hidden = false; // if (box.setActive) { // box.setActive(); // } this.fireEvent('show'); } }, isHidden: function (){ return this._hidden; }, show: function (){ this._doAutoRender(); this._show(); }, hide: function (notNofity){ if (!this._hidden && this.getDom()) { this.getDom().style.display = 'none'; this._hidden = true; if (!notNofity) { this.fireEvent('hide'); } } }, queryAutoHide: function (el){ return !el || !uiUtils.contains(this.getDom(), el); } }; utils.inherits(Popup, UIBase); domUtils.on( document, 'mousedown', function ( evt ) { var el = evt.target || evt.srcElement; closeAllPopup( evt,el ); } ); domUtils.on( window, 'scroll', function (evt,el) { closeAllPopup( evt,el ); } ); })(); ///import core ///import uicore (function (){ var utils = baidu.editor.utils, UIBase = baidu.editor.ui.UIBase, ColorPicker = baidu.editor.ui.ColorPicker = function (options){ this.initOptions(options); this.noColorText = this.noColorText || this.editor.getLang("clearColor"); this.initUIBase(); }; ColorPicker.prototype = { getHtmlTpl: function (){ return genColorPicker(this.noColorText,this.editor); }, _onTableClick: function (evt){ var tgt = evt.target || evt.srcElement; var color = tgt.getAttribute('data-color'); if (color) { this.fireEvent('pickcolor', color); } }, _onTableOver: function (evt){ var tgt = evt.target || evt.srcElement; var color = tgt.getAttribute('data-color'); if (color) { this.getDom('preview').style.backgroundColor = color; } }, _onTableOut: function (){ this.getDom('preview').style.backgroundColor = ''; }, _onPickNoColor: function (){ this.fireEvent('picknocolor'); } }; utils.inherits(ColorPicker, UIBase); var COLORS = ( 'ffffff,000000,eeece1,1f497d,4f81bd,c0504d,9bbb59,8064a2,4bacc6,f79646,' + 'f2f2f2,7f7f7f,ddd9c3,c6d9f0,dbe5f1,f2dcdb,ebf1dd,e5e0ec,dbeef3,fdeada,' + 'd8d8d8,595959,c4bd97,8db3e2,b8cce4,e5b9b7,d7e3bc,ccc1d9,b7dde8,fbd5b5,' + 'bfbfbf,3f3f3f,938953,548dd4,95b3d7,d99694,c3d69b,b2a2c7,92cddc,fac08f,' + 'a5a5a5,262626,494429,17365d,366092,953734,76923c,5f497a,31859b,e36c09,' + '7f7f7f,0c0c0c,1d1b10,0f243e,244061,632423,4f6128,3f3151,205867,974806,' + 'c00000,ff0000,ffc000,ffff00,92d050,00b050,00b0f0,0070c0,002060,7030a0,').split(','); function genColorPicker(noColorText,editor){ var html = '<div id="##" class="edui-colorpicker %%">' + '<div class="edui-colorpicker-topbar edui-clearfix">' + '<div unselectable="on" id="##_preview" class="edui-colorpicker-preview"></div>' + '<div unselectable="on" class="edui-colorpicker-nocolor" onclick="$$._onPickNoColor(event, this);">'+ noColorText +'</div>' + '</div>' + '<table class="edui-box" style="border-collapse: collapse;" onmouseover="$$._onTableOver(event, this);" onmouseout="$$._onTableOut(event, this);" onclick="return $$._onTableClick(event, this);" cellspacing="0" cellpadding="0">' + '<tr style="border-bottom: 1px solid #ddd;font-size: 13px;line-height: 25px;color:#39C;padding-top: 2px"><td colspan="10">'+editor.getLang("themeColor")+'</td> </tr>'+ '<tr class="edui-colorpicker-tablefirstrow" >'; for (var i=0; i<COLORS.length; i++) { if (i && i%10 === 0) { html += '</tr>'+(i==60?'<tr style="border-bottom: 1px solid #ddd;font-size: 13px;line-height: 25px;color:#39C;"><td colspan="10">'+editor.getLang("standardColor")+'</td></tr>':'')+'<tr'+(i==60?' class="edui-colorpicker-tablefirstrow"':'')+'>'; } html += i<70 ? '<td style="padding: 0 2px;"><a hidefocus title="'+COLORS[i]+'" onclick="return false;" href="javascript:" unselectable="on" class="edui-box edui-colorpicker-colorcell"' + ' data-color="#'+ COLORS[i] +'"'+ ' style="background-color:#'+ COLORS[i] +';border:solid #ccc;'+ (i<10 || i>=60?'border-width:1px;': i>=10&&i<20?'border-width:1px 1px 0 1px;': 'border-width:0 1px 0 1px;')+ '"' + '></a></td>':''; } html += '</tr></table></div>'; return html; } })(); ///import core ///import uicore (function (){ var utils = baidu.editor.utils, uiUtils = baidu.editor.ui.uiUtils, UIBase = baidu.editor.ui.UIBase; var TablePicker = baidu.editor.ui.TablePicker = function (options){ this.initOptions(options); this.initTablePicker(); }; TablePicker.prototype = { defaultNumRows: 10, defaultNumCols: 10, maxNumRows: 20, maxNumCols: 20, numRows: 10, numCols: 10, lengthOfCellSide: 22, initTablePicker: function (){ this.initUIBase(); }, getHtmlTpl: function (){ var me = this; return '<div id="##" class="edui-tablepicker %%">' + '<div class="edui-tablepicker-body">' + '<div class="edui-infoarea">' + '<span id="##_label" class="edui-label"></span>' + '</div>' + '<div class="edui-pickarea"' + ' onmousemove="$$._onMouseMove(event, this);"' + ' onmouseover="$$._onMouseOver(event, this);"' + ' onmouseout="$$._onMouseOut(event, this);"' + ' onclick="$$._onClick(event, this);"' + '>' + '<div id="##_overlay" class="edui-overlay"></div>' + '</div>' + '</div>' + '</div>'; }, _UIBase_render: UIBase.prototype.render, render: function (holder){ this._UIBase_render(holder); this.getDom('label').innerHTML = '0'+this.editor.getLang("t_row")+' x 0'+this.editor.getLang("t_col"); }, _track: function (numCols, numRows){ var style = this.getDom('overlay').style; var sideLen = this.lengthOfCellSide; style.width = numCols * sideLen + 'px'; style.height = numRows * sideLen + 'px'; var label = this.getDom('label'); label.innerHTML = numCols +this.editor.getLang("t_col")+' x ' + numRows + this.editor.getLang("t_row"); this.numCols = numCols; this.numRows = numRows; }, _onMouseOver: function (evt, el){ var rel = evt.relatedTarget || evt.fromElement; if (!uiUtils.contains(el, rel) && el !== rel) { this.getDom('label').innerHTML = '0'+this.editor.getLang("t_col")+' x 0'+this.editor.getLang("t_row"); this.getDom('overlay').style.visibility = ''; } }, _onMouseOut: function (evt, el){ var rel = evt.relatedTarget || evt.toElement; if (!uiUtils.contains(el, rel) && el !== rel) { this.getDom('label').innerHTML = '0'+this.editor.getLang("t_col")+' x 0'+this.editor.getLang("t_row"); this.getDom('overlay').style.visibility = 'hidden'; } }, _onMouseMove: function (evt, el){ var style = this.getDom('overlay').style; var offset = uiUtils.getEventOffset(evt); var sideLen = this.lengthOfCellSide; var numCols = Math.ceil(offset.left / sideLen); var numRows = Math.ceil(offset.top / sideLen); this._track(numCols, numRows); }, _onClick: function (){ this.fireEvent('picktable', this.numCols, this.numRows); } }; utils.inherits(TablePicker, UIBase); })(); (function (){ var browser = baidu.editor.browser, domUtils = baidu.editor.dom.domUtils, uiUtils = baidu.editor.ui.uiUtils; var TPL_STATEFUL = 'onmousedown="$$.Stateful_onMouseDown(event, this);"' + ' onmouseup="$$.Stateful_onMouseUp(event, this);"' + ( browser.ie ? ( ' onmouseenter="$$.Stateful_onMouseEnter(event, this);"' + ' onmouseleave="$$.Stateful_onMouseLeave(event, this);"' ) : ( ' onmouseover="$$.Stateful_onMouseOver(event, this);"' + ' onmouseout="$$.Stateful_onMouseOut(event, this);"' )); baidu.editor.ui.Stateful = { alwalysHoverable: false, target:null,//目标元素和this指向dom不一样 Stateful_init: function (){ this._Stateful_dGetHtmlTpl = this.getHtmlTpl; this.getHtmlTpl = this.Stateful_getHtmlTpl; }, Stateful_getHtmlTpl: function (){ var tpl = this._Stateful_dGetHtmlTpl(); // 使用function避免$转义 return tpl.replace(/stateful/g, function (){ return TPL_STATEFUL; }); }, Stateful_onMouseEnter: function (evt, el){ this.target=el; if (!this.isDisabled() || this.alwalysHoverable) { this.addState('hover'); this.fireEvent('over'); } }, Stateful_onMouseLeave: function (evt, el){ if (!this.isDisabled() || this.alwalysHoverable) { this.removeState('hover'); this.removeState('active'); this.fireEvent('out'); } }, Stateful_onMouseOver: function (evt, el){ var rel = evt.relatedTarget; if (!uiUtils.contains(el, rel) && el !== rel) { this.Stateful_onMouseEnter(evt, el); } }, Stateful_onMouseOut: function (evt, el){ var rel = evt.relatedTarget; if (!uiUtils.contains(el, rel) && el !== rel) { this.Stateful_onMouseLeave(evt, el); } }, Stateful_onMouseDown: function (evt, el){ if (!this.isDisabled()) { this.addState('active'); } }, Stateful_onMouseUp: function (evt, el){ if (!this.isDisabled()) { this.removeState('active'); } }, Stateful_postRender: function (){ if (this.disabled && !this.hasState('disabled')) { this.addState('disabled'); } }, hasState: function (state){ return domUtils.hasClass(this.getStateDom(), 'edui-state-' + state); }, addState: function (state){ if (!this.hasState(state)) { this.getStateDom().className += ' edui-state-' + state; } }, removeState: function (state){ if (this.hasState(state)) { domUtils.removeClasses(this.getStateDom(), ['edui-state-' + state]); } }, getStateDom: function (){ return this.getDom('state'); }, isChecked: function (){ return this.hasState('checked'); }, setChecked: function (checked){ if (!this.isDisabled() && checked) { this.addState('checked'); } else { this.removeState('checked'); } }, isDisabled: function (){ return this.hasState('disabled'); }, setDisabled: function (disabled){ if (disabled) { this.removeState('hover'); this.removeState('checked'); this.removeState('active'); this.addState('disabled'); } else { this.removeState('disabled'); } } }; })(); ///import core ///import uicore ///import ui/stateful.js (function (){ var utils = baidu.editor.utils, UIBase = baidu.editor.ui.UIBase, Stateful = baidu.editor.ui.Stateful, Button = baidu.editor.ui.Button = function (options){ this.initOptions(options); this.initButton(); }; Button.prototype = { uiName: 'button', label: '', title: '', showIcon: true, showText: true, initButton: function (){ this.initUIBase(); this.Stateful_init(); }, getHtmlTpl: function (){ return '<div id="##" class="edui-box %%">' + '<div id="##_state" stateful>' + '<div class="%%-wrap"><div id="##_body" unselectable="on" ' + (this.title ? 'title="' + this.title + '"' : '') + ' class="%%-body" onmousedown="return false;" onclick="return $$._onClick();">' + (this.showIcon ? '<div class="edui-box edui-icon"></div>' : '') + (this.showText ? '<div class="edui-box edui-label">' + this.label + '</div>' : '') + '</div>' + '</div>' + '</div></div>'; }, postRender: function (){ this.Stateful_postRender(); this.setDisabled(this.disabled) }, _onClick: function (){ if (!this.isDisabled()) { this.fireEvent('click'); } } }; utils.inherits(Button, UIBase); utils.extend(Button.prototype, Stateful); })(); ///import core ///import uicore ///import ui/stateful.js (function (){ var utils = baidu.editor.utils, uiUtils = baidu.editor.ui.uiUtils, domUtils = baidu.editor.dom.domUtils, UIBase = baidu.editor.ui.UIBase, Stateful = baidu.editor.ui.Stateful, SplitButton = baidu.editor.ui.SplitButton = function (options){ this.initOptions(options); this.initSplitButton(); }; SplitButton.prototype = { popup: null, uiName: 'splitbutton', title: '', initSplitButton: function (){ this.initUIBase(); this.Stateful_init(); var me = this; if (this.popup != null) { var popup = this.popup; this.popup = null; this.setPopup(popup); } }, _UIBase_postRender: UIBase.prototype.postRender, postRender: function (){ this.Stateful_postRender(); this._UIBase_postRender(); }, setPopup: function (popup){ if (this.popup === popup) return; if (this.popup != null) { this.popup.dispose(); } popup.addListener('show', utils.bind(this._onPopupShow, this)); popup.addListener('hide', utils.bind(this._onPopupHide, this)); popup.addListener('postrender', utils.bind(function (){ popup.getDom('body').appendChild( uiUtils.createElementByHtml('<div id="' + this.popup.id + '_bordereraser" class="edui-bordereraser edui-background" style="width:' + (uiUtils.getClientRect(this.getDom()).width + 20) + 'px"></div>') ); popup.getDom().className += ' ' + this.className; }, this)); this.popup = popup; }, _onPopupShow: function (){ this.addState('opened'); }, _onPopupHide: function (){ this.removeState('opened'); }, getHtmlTpl: function (){ return '<div id="##" class="edui-box %%">' + '<div '+ (this.title ? 'title="' + this.title + '"' : '') +' id="##_state" stateful><div class="%%-body">' + '<div id="##_button_body" class="edui-box edui-button-body" onclick="$$._onButtonClick(event, this);">' + '<div class="edui-box edui-icon"></div>' + '</div>' + '<div class="edui-box edui-splitborder"></div>' + '<div class="edui-box edui-arrow" onclick="$$._onArrowClick();"></div>' + '</div></div></div>'; }, showPopup: function (){ // 当popup往上弹出的时候,做特殊处理 var rect = uiUtils.getClientRect(this.getDom()); rect.top -= this.popup.SHADOW_RADIUS; rect.height += this.popup.SHADOW_RADIUS; this.popup.showAnchorRect(rect); }, _onArrowClick: function (event, el){ if (!this.isDisabled()) { this.showPopup(); } }, _onButtonClick: function (){ if (!this.isDisabled()) { this.fireEvent('buttonclick'); } } }; utils.inherits(SplitButton, UIBase); utils.extend(SplitButton.prototype, Stateful, true); })(); ///import core ///import uicore ///import ui/colorpicker.js ///import ui/popup.js ///import ui/splitbutton.js (function (){ var utils = baidu.editor.utils, uiUtils = baidu.editor.ui.uiUtils, ColorPicker = baidu.editor.ui.ColorPicker, Popup = baidu.editor.ui.Popup, SplitButton = baidu.editor.ui.SplitButton, ColorButton = baidu.editor.ui.ColorButton = function (options){ this.initOptions(options); this.initColorButton(); }; ColorButton.prototype = { initColorButton: function (){ var me = this; this.popup = new Popup({ content: new ColorPicker({ noColorText: me.editor.getLang("clearColor"), editor:me.editor, onpickcolor: function (t, color){ me._onPickColor(color); }, onpicknocolor: function (t, color){ me._onPickNoColor(color); } }), editor:me.editor }); this.initSplitButton(); }, _SplitButton_postRender: SplitButton.prototype.postRender, postRender: function (){ this._SplitButton_postRender(); this.getDom('button_body').appendChild( uiUtils.createElementByHtml('<div id="' + this.id + '_colorlump" class="edui-colorlump"></div>') ); this.getDom().className += ' edui-colorbutton'; }, setColor: function (color){ this.getDom('colorlump').style.backgroundColor = color; this.color = color; }, _onPickColor: function (color){ if (this.fireEvent('pickcolor', color) !== false) { this.setColor(color); this.popup.hide(); } }, _onPickNoColor: function (color){ if (this.fireEvent('picknocolor') !== false) { this.popup.hide(); } } }; utils.inherits(ColorButton, SplitButton); })(); ///import core ///import uicore ///import ui/popup.js ///import ui/tablepicker.js ///import ui/splitbutton.js (function (){ var utils = baidu.editor.utils, Popup = baidu.editor.ui.Popup, TablePicker = baidu.editor.ui.TablePicker, SplitButton = baidu.editor.ui.SplitButton, TableButton = baidu.editor.ui.TableButton = function (options){ this.initOptions(options); this.initTableButton(); }; TableButton.prototype = { initTableButton: function (){ var me = this; this.popup = new Popup({ content: new TablePicker({ editor:me.editor, onpicktable: function (t, numCols, numRows){ me._onPickTable(numCols, numRows); } }), 'editor':me.editor }); this.initSplitButton(); }, _onPickTable: function (numCols, numRows){ if (this.fireEvent('picktable', numCols, numRows) !== false) { this.popup.hide(); } } }; utils.inherits(TableButton, SplitButton); })(); ///import core ///import uicore (function () { var utils = baidu.editor.utils, UIBase = baidu.editor.ui.UIBase; var AutoTypeSetPicker = baidu.editor.ui.AutoTypeSetPicker = function (options) { this.initOptions(options); this.initAutoTypeSetPicker(); }; AutoTypeSetPicker.prototype = { initAutoTypeSetPicker:function () { this.initUIBase(); }, getHtmlTpl:function () { var me = this.editor, opt = me.options.autotypeset, lang = me.getLang("autoTypeSet"); var textAlignInputName = 'textAlignValue' + me.uid, imageBlockInputName = 'imageBlockLineValue' + me.uid; return '<div id="##" class="edui-autotypesetpicker %%">' + '<div class="edui-autotypesetpicker-body">' + '<table >' + '<tr><td nowrap colspan="2"><input type="checkbox" name="mergeEmptyline" ' + (opt["mergeEmptyline"] ? "checked" : "" ) + '>' + lang.mergeLine + '</td><td colspan="2"><input type="checkbox" name="removeEmptyline" ' + (opt["removeEmptyline"] ? "checked" : "" ) + '>' + lang.delLine + '</td></tr>' + '<tr><td nowrap colspan="2"><input type="checkbox" name="removeClass" ' + (opt["removeClass"] ? "checked" : "" ) + '>' + lang.removeFormat + '</td><td colspan="2"><input type="checkbox" name="indent" ' + (opt["indent"] ? "checked" : "" ) + '>' + lang.indent + '</td></tr>' + '<tr><td nowrap colspan="2"><input type="checkbox" name="textAlign" ' + (opt["textAlign"] ? "checked" : "" ) + '>' + lang.alignment + '</td><td colspan="2" id="' + textAlignInputName + '"><input type="radio" name="'+ textAlignInputName +'" value="left" ' + ((opt["textAlign"] && opt["textAlign"] == "left") ? "checked" : "") + '>' + me.getLang("justifyleft") + '<input type="radio" name="'+ textAlignInputName +'" value="center" ' + ((opt["textAlign"] && opt["textAlign"] == "center") ? "checked" : "") + '>' + me.getLang("justifycenter") + '<input type="radio" name="'+ textAlignInputName +'" value="right" ' + ((opt["textAlign"] && opt["textAlign"] == "right") ? "checked" : "") + '>' + me.getLang("justifyright") + ' </tr>' + '<tr><td nowrap colspan="2"><input type="checkbox" name="imageBlockLine" ' + (opt["imageBlockLine"] ? "checked" : "" ) + '>' + lang.imageFloat + '</td>' + '<td nowrap colspan="2" id="'+ imageBlockInputName +'">' + '<input type="radio" name="'+ imageBlockInputName +'" value="none" ' + ((opt["imageBlockLine"] && opt["imageBlockLine"] == "none") ? "checked" : "") + '>' + me.getLang("default") + '<input type="radio" name="'+ imageBlockInputName +'" value="left" ' + ((opt["imageBlockLine"] && opt["imageBlockLine"] == "left") ? "checked" : "") + '>' + me.getLang("justifyleft") + '<input type="radio" name="'+ imageBlockInputName +'" value="center" ' + ((opt["imageBlockLine"] && opt["imageBlockLine"] == "center") ? "checked" : "") + '>' + me.getLang("justifycenter") + '<input type="radio" name="'+ imageBlockInputName +'" value="right" ' + ((opt["imageBlockLine"] && opt["imageBlockLine"] == "right") ? "checked" : "") + '>' + me.getLang("justifyright") + '</tr>' + '<tr><td nowrap colspan="2"><input type="checkbox" name="clearFontSize" ' + (opt["clearFontSize"] ? "checked" : "" ) + '>' + lang.removeFontsize + '</td><td colspan="2"><input type="checkbox" name="clearFontFamily" ' + (opt["clearFontFamily"] ? "checked" : "" ) + '>' + lang.removeFontFamily + '</td></tr>' + '<tr><td nowrap colspan="4"><input type="checkbox" name="removeEmptyNode" ' + (opt["removeEmptyNode"] ? "checked" : "" ) + '>' + lang.removeHtml + '</td></tr>' + '<tr><td nowrap colspan="4"><input type="checkbox" name="pasteFilter" ' + (opt["pasteFilter"] ? "checked" : "" ) + '>' + lang.pasteFilter + '</td></tr>' + '<tr><td nowrap colspan="4" align="right"><button >' + lang.run + '</button></td></tr>' + '</table>' + '</div>' + '</div>'; }, _UIBase_render:UIBase.prototype.render }; utils.inherits(AutoTypeSetPicker, UIBase); })(); ///import core ///import uicore ///import ui/popup.js ///import ui/autotypesetpicker.js ///import ui/splitbutton.js (function (){ var utils = baidu.editor.utils, Popup = baidu.editor.ui.Popup, AutoTypeSetPicker = baidu.editor.ui.AutoTypeSetPicker, SplitButton = baidu.editor.ui.SplitButton, AutoTypeSetButton = baidu.editor.ui.AutoTypeSetButton = function (options){ this.initOptions(options); this.initAutoTypeSetButton(); }; function getPara(me){ var opt = me.editor.options.autotypeset, cont = me.getDom(), editorId = me.editor.uid, inputType = null, attrName = null, ipts = domUtils.getElementsByTagName(cont,"input"); for(var i=ipts.length-1,ipt;ipt=ipts[i--];){ inputType = ipt.getAttribute("type"); if(inputType=="checkbox"){ attrName = ipt.getAttribute("name"); opt[attrName] && delete opt[attrName]; if(ipt.checked){ var attrValue = document.getElementById( attrName+"Value" + editorId ); if(attrValue){ if(/input/ig.test(attrValue.tagName)){ opt[attrName] = attrValue.value; }else{ var iptChilds = attrValue.getElementsByTagName("input"); for(var j=iptChilds.length-1,iptchild;iptchild=iptChilds[j--];){ if(iptchild.checked){ opt[attrName] = iptchild.value; break; } } } }else{ opt[attrName] = true; } } } } var selects = domUtils.getElementsByTagName(cont,"select"); for(var i=0,si;si=selects[i++];){ var attr = si.getAttribute('name'); opt[attr] = opt[attr] ? si.value : ''; } me.editor.options.autotypeset = opt; } AutoTypeSetButton.prototype = { initAutoTypeSetButton: function (){ var me = this; this.popup = new Popup({ //传入配置参数 content: new AutoTypeSetPicker({editor:me.editor}), 'editor':me.editor, hide : function(){ if (!this._hidden && this.getDom()) { getPara(this); this.getDom().style.display = 'none'; this._hidden = true; this.fireEvent('hide'); } } }); var flag = 0; this.popup.addListener('postRenderAfter',function(){ var popupUI = this; if(flag)return; var cont = this.getDom(), btn = cont.getElementsByTagName('button')[0]; btn.onclick = function(){ getPara(popupUI); me.editor.execCommand('autotypeset'); popupUI.hide() }; flag = 1; }); this.initSplitButton(); } }; utils.inherits(AutoTypeSetButton, SplitButton); })(); ///import core ///import uicore (function () { var utils = baidu.editor.utils, Popup = baidu.editor.ui.Popup, Stateful = baidu.editor.ui.Stateful, UIBase = baidu.editor.ui.UIBase; /** * 该参数将新增一个参数: selected, 参数类型为一个Object, 形如{ 'align': 'center', 'valign': 'top' }, 表示单元格的初始 * 对齐状态为: 竖直居上,水平居中; 其中 align的取值为:'center', 'left', 'right'; valign的取值为: 'top', 'middle', 'bottom' * @update 2013/4/2 hancong03@baidu.com */ var CellAlignPicker = baidu.editor.ui.CellAlignPicker = function (options) { this.initOptions(options); this.initSelected(); this.initCellAlignPicker(); }; CellAlignPicker.prototype = { //初始化选中状态, 该方法将根据传递进来的参数获取到应该选中的对齐方式图标的索引 initSelected: function(){ var status = { valign: { top: 0, middle: 1, bottom: 2 }, align: { left: 0, center: 1, right: 2 }, count: 3 }, result = -1; if( this.selected ) { this.selectedIndex = status.valign[ this.selected.valign ] * status.count + status.align[ this.selected.align ]; } }, initCellAlignPicker:function () { this.initUIBase(); this.Stateful_init(); }, getHtmlTpl:function () { var alignType = [ 'left', 'center', 'right' ], COUNT = 9, tempClassName = null, tempIndex = -1, tmpl = []; for( var i= 0; i<COUNT; i++ ) { tempClassName = this.selectedIndex === i ? ' class="edui-cellalign-selected" ' : ''; tempIndex = i % 3; tempIndex === 0 && tmpl.push('<tr>'); tmpl.push( '<td index="'+ i +'" ' + tempClassName + ' stateful><div class="edui-icon edui-'+ alignType[ tempIndex ] +'"></div></td>' ); tempIndex === 2 && tmpl.push('</tr>'); } return '<div id="##" class="edui-cellalignpicker %%">' + '<div class="edui-cellalignpicker-body">' + '<table onclick="$$._onClick(event);">' + tmpl.join('') + '</table>' + '</div>' + '</div>'; }, getStateDom: function (){ return this.target; }, _onClick: function (evt){ var target= evt.target || evt.srcElement; if(/icon/.test(target.className)){ this.items[target.parentNode.getAttribute("index")].onclick(); Popup.postHide(evt); } }, _UIBase_render:UIBase.prototype.render }; utils.inherits(CellAlignPicker, UIBase); utils.extend(CellAlignPicker.prototype, Stateful,true); })(); ///import core ///import uicore (function () { var utils = baidu.editor.utils, Stateful = baidu.editor.ui.Stateful, uiUtils = baidu.editor.ui.uiUtils, UIBase = baidu.editor.ui.UIBase; var PastePicker = baidu.editor.ui.PastePicker = function (options) { this.initOptions(options); this.initPastePicker(); }; PastePicker.prototype = { initPastePicker:function () { this.initUIBase(); this.Stateful_init(); }, getHtmlTpl:function () { return '<div class="edui-pasteicon" onclick="$$._onClick(this)"></div>' + '<div class="edui-pastecontainer">' + '<div class="edui-title">' + this.editor.getLang("pasteOpt") + '</div>' + '<div class="edui-button">' + '<div title="' + this.editor.getLang("pasteSourceFormat") + '" onclick="$$.format(false)" stateful>' + '<div class="edui-richtxticon"></div></div>' + '<div title="' + this.editor.getLang("tagFormat") + '" onclick="$$.format(2)" stateful>' + '<div class="edui-tagicon"></div></div>' + '<div title="' + this.editor.getLang("pasteTextFormat") + '" onclick="$$.format(true)" stateful>' + '<div class="edui-plaintxticon"></div></div>' + '</div>' + '</div>' + '</div>' }, getStateDom:function () { return this.target; }, format:function (param) { this.editor.ui._isTransfer = true; this.editor.fireEvent('pasteTransfer', param); }, _onClick:function (cur) { var node = domUtils.getNextDomNode(cur), screenHt = uiUtils.getViewportRect().height, subPop = uiUtils.getClientRect(node); if ((subPop.top + subPop.height) > screenHt) node.style.top = (-subPop.height - cur.offsetHeight) + "px"; else node.style.top = ""; if (/hidden/ig.test(domUtils.getComputedStyle(node, "visibility"))) { node.style.visibility = "visible"; domUtils.addClass(cur, "edui-state-opened"); } else { node.style.visibility = "hidden"; domUtils.removeClasses(cur, "edui-state-opened") } }, _UIBase_render:UIBase.prototype.render }; utils.inherits(PastePicker, UIBase); utils.extend(PastePicker.prototype, Stateful, true); })(); (function (){ var utils = baidu.editor.utils, uiUtils = baidu.editor.ui.uiUtils, UIBase = baidu.editor.ui.UIBase, Toolbar = baidu.editor.ui.Toolbar = function (options){ this.initOptions(options); this.initToolbar(); }; Toolbar.prototype = { items: null, initToolbar: function (){ this.items = this.items || []; this.initUIBase(); }, add: function (item){ this.items.push(item); }, getHtmlTpl: function (){ var buff = []; for (var i=0; i<this.items.length; i++) { buff[i] = this.items[i].renderHtml(); } return '<div id="##" class="edui-toolbar %%" onselectstart="return false;" onmousedown="return $$._onMouseDown(event, this);">' + buff.join('') + '</div>' }, postRender: function (){ var box = this.getDom(); for (var i=0; i<this.items.length; i++) { this.items[i].postRender(); } uiUtils.makeUnselectable(box); }, _onMouseDown: function (){ return false; } }; utils.inherits(Toolbar, UIBase); })(); ///import core ///import uicore ///import ui\popup.js ///import ui\stateful.js (function () { var utils = baidu.editor.utils, domUtils = baidu.editor.dom.domUtils, uiUtils = baidu.editor.ui.uiUtils, UIBase = baidu.editor.ui.UIBase, Popup = baidu.editor.ui.Popup, Stateful = baidu.editor.ui.Stateful, CellAlignPicker = baidu.editor.ui.CellAlignPicker, Menu = baidu.editor.ui.Menu = function (options) { this.initOptions(options); this.initMenu(); }; var menuSeparator = { renderHtml:function () { return '<div class="edui-menuitem edui-menuseparator"><div class="edui-menuseparator-inner"></div></div>'; }, postRender:function () { }, queryAutoHide:function () { return true; } }; Menu.prototype = { items:null, uiName:'menu', initMenu:function () { this.items = this.items || []; this.initPopup(); this.initItems(); }, initItems:function () { for (var i = 0; i < this.items.length; i++) { var item = this.items[i]; if (item == '-') { this.items[i] = this.getSeparator(); } else if (!(item instanceof MenuItem)) { item.editor = this.editor; item.theme = this.editor.options.theme; this.items[i] = this.createItem(item); } } }, getSeparator:function () { return menuSeparator; }, createItem:function (item) { //新增一个参数menu, 该参数存储了menuItem所对应的menu引用 item.menu = this; return new MenuItem(item); }, _Popup_getContentHtmlTpl:Popup.prototype.getContentHtmlTpl, getContentHtmlTpl:function () { if (this.items.length == 0) { return this._Popup_getContentHtmlTpl(); } var buff = []; for (var i = 0; i < this.items.length; i++) { var item = this.items[i]; buff[i] = item.renderHtml(); } return ('<div class="%%-body">' + buff.join('') + '</div>'); }, _Popup_postRender:Popup.prototype.postRender, postRender:function () { var me = this; for (var i = 0; i < this.items.length; i++) { var item = this.items[i]; item.ownerMenu = this; item.postRender(); } domUtils.on(this.getDom(), 'mouseover', function (evt) { evt = evt || event; var rel = evt.relatedTarget || evt.fromElement; var el = me.getDom(); if (!uiUtils.contains(el, rel) && el !== rel) { me.fireEvent('over'); } }); this._Popup_postRender(); }, queryAutoHide:function (el) { if (el) { if (uiUtils.contains(this.getDom(), el)) { return false; } for (var i = 0; i < this.items.length; i++) { var item = this.items[i]; if (item.queryAutoHide(el) === false) { return false; } } } }, clearItems:function () { for (var i = 0; i < this.items.length; i++) { var item = this.items[i]; clearTimeout(item._showingTimer); clearTimeout(item._closingTimer); if (item.subMenu) { item.subMenu.destroy(); } } this.items = []; }, destroy:function () { if (this.getDom()) { domUtils.remove(this.getDom()); } this.clearItems(); }, dispose:function () { this.destroy(); } }; utils.inherits(Menu, Popup); /** * @update 2013/04/03 hancong03 新增一个参数menu, 该参数存储了menuItem所对应的menu引用 * @type {Function} */ var MenuItem = baidu.editor.ui.MenuItem = function (options) { this.initOptions(options); this.initUIBase(); this.Stateful_init(); if (this.subMenu && !(this.subMenu instanceof Menu)) { if (options.className && options.className.indexOf("aligntd") != -1) { var me = this; //获取单元格对齐初始状态 this.subMenu.selected = this.editor.queryCommandValue( 'cellalignment' ); this.subMenu = new Popup({ content:new CellAlignPicker(this.subMenu), parentMenu:me, editor:me.editor, destroy:function () { if (this.getDom()) { domUtils.remove(this.getDom()); } } }); this.subMenu.addListener("postRenderAfter", function () { domUtils.on(this.getDom(), "mouseover", function () { me.addState('opened'); }); }); } else { this.subMenu = new Menu(this.subMenu); } } }; MenuItem.prototype = { label:'', subMenu:null, ownerMenu:null, uiName:'menuitem', alwalysHoverable:true, getHtmlTpl:function () { return '<div id="##" class="%%" stateful onclick="$$._onClick(event, this);">' + '<div class="%%-body">' + this.renderLabelHtml() + '</div>' + '</div>'; }, postRender:function () { var me = this; this.addListener('over', function () { me.ownerMenu.fireEvent('submenuover', me); if (me.subMenu) { me.delayShowSubMenu(); } }); if (this.subMenu) { this.getDom().className += ' edui-hassubmenu'; this.subMenu.render(); this.addListener('out', function () { me.delayHideSubMenu(); }); this.subMenu.addListener('over', function () { clearTimeout(me._closingTimer); me._closingTimer = null; me.addState('opened'); }); this.ownerMenu.addListener('hide', function () { me.hideSubMenu(); }); this.ownerMenu.addListener('submenuover', function (t, subMenu) { if (subMenu !== me) { me.delayHideSubMenu(); } }); this.subMenu._bakQueryAutoHide = this.subMenu.queryAutoHide; this.subMenu.queryAutoHide = function (el) { if (el && uiUtils.contains(me.getDom(), el)) { return false; } return this._bakQueryAutoHide(el); }; } this.getDom().style.tabIndex = '-1'; uiUtils.makeUnselectable(this.getDom()); this.Stateful_postRender(); }, delayShowSubMenu:function () { var me = this; if (!me.isDisabled()) { me.addState('opened'); clearTimeout(me._showingTimer); clearTimeout(me._closingTimer); me._closingTimer = null; me._showingTimer = setTimeout(function () { me.showSubMenu(); }, 250); } }, delayHideSubMenu:function () { var me = this; if (!me.isDisabled()) { me.removeState('opened'); clearTimeout(me._showingTimer); if (!me._closingTimer) { me._closingTimer = setTimeout(function () { if (!me.hasState('opened')) { me.hideSubMenu(); } me._closingTimer = null; }, 400); } } }, renderLabelHtml:function () { return '<div class="edui-arrow"></div>' + '<div class="edui-box edui-icon"></div>' + '<div class="edui-box edui-label %%-label">' + (this.label || '') + '</div>'; }, getStateDom:function () { return this.getDom(); }, queryAutoHide:function (el) { if (this.subMenu && this.hasState('opened')) { return this.subMenu.queryAutoHide(el); } }, _onClick:function (event, this_) { if (this.hasState('disabled')) return; if (this.fireEvent('click', event, this_) !== false) { if (this.subMenu) { this.showSubMenu(); } else { Popup.postHide(event); } } }, showSubMenu:function () { var rect = uiUtils.getClientRect(this.getDom()); rect.right -= 5; rect.left += 2; rect.width -= 7; rect.top -= 4; rect.bottom += 4; rect.height += 8; this.subMenu.showAnchorRect(rect, true, true); }, hideSubMenu:function () { this.subMenu.hide(); } }; utils.inherits(MenuItem, UIBase); utils.extend(MenuItem.prototype, Stateful, true); })(); ///import core ///import uicore ///import ui/menu.js ///import ui/splitbutton.js (function (){ // todo: menu和item提成通用list var utils = baidu.editor.utils, uiUtils = baidu.editor.ui.uiUtils, Menu = baidu.editor.ui.Menu, SplitButton = baidu.editor.ui.SplitButton, Combox = baidu.editor.ui.Combox = function (options){ this.initOptions(options); this.initCombox(); }; Combox.prototype = { uiName: 'combox', initCombox: function (){ var me = this; this.items = this.items || []; for (var i=0; i<this.items.length; i++) { var item = this.items[i]; item.uiName = 'listitem'; item.index = i; item.onclick = function (){ me.selectByIndex(this.index); }; } this.popup = new Menu({ items: this.items, uiName: 'list', editor:this.editor, captureWheel: true, combox: this }); this.initSplitButton(); }, _SplitButton_postRender: SplitButton.prototype.postRender, postRender: function (){ this._SplitButton_postRender(); this.setLabel(this.label || ''); this.setValue(this.initValue || ''); }, showPopup: function (){ var rect = uiUtils.getClientRect(this.getDom()); rect.top += 1; rect.bottom -= 1; rect.height -= 2; this.popup.showAnchorRect(rect); }, getValue: function (){ return this.value; }, setValue: function (value){ var index = this.indexByValue(value); if (index != -1) { this.selectedIndex = index; this.setLabel(this.items[index].label); this.value = this.items[index].value; } else { this.selectedIndex = -1; this.setLabel(this.getLabelForUnknowValue(value)); this.value = value; } }, setLabel: function (label){ this.getDom('button_body').innerHTML = label; this.label = label; }, getLabelForUnknowValue: function (value){ return value; }, indexByValue: function (value){ for (var i=0; i<this.items.length; i++) { if (value == this.items[i].value) { return i; } } return -1; }, getItem: function (index){ return this.items[index]; }, selectByIndex: function (index){ if (index < this.items.length && this.fireEvent('select', index) !== false) { this.selectedIndex = index; this.value = this.items[index].value; this.setLabel(this.items[index].label); } } }; utils.inherits(Combox, SplitButton); })(); ///import core ///import uicore ///import ui/mask.js ///import ui/button.js (function (){ var utils = baidu.editor.utils, domUtils = baidu.editor.dom.domUtils, uiUtils = baidu.editor.ui.uiUtils, Mask = baidu.editor.ui.Mask, UIBase = baidu.editor.ui.UIBase, Button = baidu.editor.ui.Button, Dialog = baidu.editor.ui.Dialog = function (options){ this.initOptions(utils.extend({ autoReset: true, draggable: true, onok: function (){}, oncancel: function (){}, onclose: function (t, ok){ return ok ? this.onok() : this.oncancel(); }, //是否控制dialog中的scroll事件, 默认为不阻止 holdScroll: false },options)); this.initDialog(); }; var modalMask; var dragMask; Dialog.prototype = { draggable: false, uiName: 'dialog', initDialog: function (){ var me = this, theme=this.editor.options.theme; this.initUIBase(); this.modalMask = (modalMask || (modalMask = new Mask({ className: 'edui-dialog-modalmask', theme:theme }))); this.dragMask = (dragMask || (dragMask = new Mask({ className: 'edui-dialog-dragmask', theme:theme }))); this.closeButton = new Button({ className: 'edui-dialog-closebutton', title: me.closeDialog, theme:theme, onclick: function (){ me.close(false); } }); if (this.buttons) { for (var i=0; i<this.buttons.length; i++) { if (!(this.buttons[i] instanceof Button)) { this.buttons[i] = new Button(this.buttons[i]); } } } }, fitSize: function (){ var popBodyEl = this.getDom('body'); // if (!(baidu.editor.browser.ie && baidu.editor.browser.version == 7)) { // uiUtils.removeStyle(popBodyEl, 'width'); // uiUtils.removeStyle(popBodyEl, 'height'); // } var size = this.mesureSize(); popBodyEl.style.width = size.width + 'px'; popBodyEl.style.height = size.height + 'px'; return size; }, safeSetOffset: function (offset){ var me = this; var el = me.getDom(); var vpRect = uiUtils.getViewportRect(); var rect = uiUtils.getClientRect(el); var left = offset.left; if (left + rect.width > vpRect.right) { left = vpRect.right - rect.width; } var top = offset.top; if (top + rect.height > vpRect.bottom) { top = vpRect.bottom - rect.height; } el.style.left = Math.max(left, 0) + 'px'; el.style.top = Math.max(top, 0) + 'px'; }, showAtCenter: function (){ this.getDom().style.display = ''; var vpRect = uiUtils.getViewportRect(); var popSize = this.fitSize(); var titleHeight = this.getDom('titlebar').offsetHeight | 0; var left = vpRect.width / 2 - popSize.width / 2; var top = vpRect.height / 2 - (popSize.height - titleHeight) / 2 - titleHeight; var popEl = this.getDom(); this.safeSetOffset({ left: Math.max(left | 0, 0), top: Math.max(top | 0, 0) }); if (!domUtils.hasClass(popEl, 'edui-state-centered')) { popEl.className += ' edui-state-centered'; } this._show(); }, getContentHtml: function (){ var contentHtml = ''; if (typeof this.content == 'string') { contentHtml = this.content; } else if (this.iframeUrl) { contentHtml = '<span id="'+ this.id +'_contmask" class="dialogcontmask"></span><iframe id="'+ this.id + '_iframe" class="%%-iframe" height="100%" width="100%" frameborder="0" src="'+ this.iframeUrl +'"></iframe>'; } return contentHtml; }, getHtmlTpl: function (){ var footHtml = ''; if (this.buttons) { var buff = []; for (var i=0; i<this.buttons.length; i++) { buff[i] = this.buttons[i].renderHtml(); } footHtml = '<div class="%%-foot">' + '<div id="##_buttons" class="%%-buttons">' + buff.join('') + '</div>' + '</div>'; } return '<div id="##" class="%%"><div class="%%-wrap"><div id="##_body" class="%%-body">' + '<div class="%%-shadow"></div>' + '<div id="##_titlebar" class="%%-titlebar">' + '<div class="%%-draghandle" onmousedown="$$._onTitlebarMouseDown(event, this);">' + '<span class="%%-caption">' + (this.title || '') + '</span>' + '</div>' + this.closeButton.renderHtml() + '</div>' + '<div id="##_content" class="%%-content">'+ ( this.autoReset ? '' : this.getContentHtml()) +'</div>' + footHtml + '</div></div></div>'; }, postRender: function (){ // todo: 保持居中/记住上次关闭位置选项 if (!this.modalMask.getDom()) { this.modalMask.render(); this.modalMask.hide(); } if (!this.dragMask.getDom()) { this.dragMask.render(); this.dragMask.hide(); } var me = this; this.addListener('show', function (){ me.modalMask.show(this.getDom().style.zIndex - 2); }); this.addListener('hide', function (){ me.modalMask.hide(); }); if (this.buttons) { for (var i=0; i<this.buttons.length; i++) { this.buttons[i].postRender(); } } domUtils.on(window, 'resize', function (){ setTimeout(function (){ if (!me.isHidden()) { me.safeSetOffset(uiUtils.getClientRect(me.getDom())); } }); }); //hold住scroll事件,防止dialog的滚动影响页面 if( this.holdScroll ) { if( !me.iframeUrl ) { domUtils.on( document.getElementById( me.id + "_iframe"), !browser.gecko ? "mousewheel" : "DOMMouseScroll", function(e){ domUtils.preventDefault(e); } ); } else { me.addListener('dialogafterreset', function(){ window.setTimeout(function(){ var iframeWindow = document.getElementById( me.id + "_iframe").contentWindow; if( browser.ie ) { var timer = window.setInterval(function(){ if( iframeWindow.document && iframeWindow.document.body ) { window.clearInterval( timer ); timer = null; domUtils.on( iframeWindow.document.body, !browser.gecko ? "mousewheel" : "DOMMouseScroll", function(e){ domUtils.preventDefault(e); } ); } }, 100); } else { domUtils.on( iframeWindow, !browser.gecko ? "mousewheel" : "DOMMouseScroll", function(e){ domUtils.preventDefault(e); } ); } }, 1); }); } } this._hide(); }, mesureSize: function (){ var body = this.getDom('body'); var width = uiUtils.getClientRect(this.getDom('content')).width; var dialogBodyStyle = body.style; dialogBodyStyle.width = width; return uiUtils.getClientRect(body); }, _onTitlebarMouseDown: function (evt, el){ if (this.draggable) { var rect; var vpRect = uiUtils.getViewportRect(); var me = this; uiUtils.startDrag(evt, { ondragstart: function (){ rect = uiUtils.getClientRect(me.getDom()); me.getDom('contmask').style.visibility = 'visible'; me.dragMask.show(me.getDom().style.zIndex - 1); }, ondragmove: function (x, y){ var left = rect.left + x; var top = rect.top + y; me.safeSetOffset({ left: left, top: top }); }, ondragstop: function (){ me.getDom('contmask').style.visibility = 'hidden'; domUtils.removeClasses(me.getDom(), ['edui-state-centered']); me.dragMask.hide(); } }); } }, reset: function (){ this.getDom('content').innerHTML = this.getContentHtml(); this.fireEvent('dialogafterreset'); }, _show: function (){ if (this._hidden) { this.getDom().style.display = ''; //要高过编辑器的zindxe this.editor.container.style.zIndex && (this.getDom().style.zIndex = this.editor.container.style.zIndex * 1 + 10); this._hidden = false; this.fireEvent('show'); baidu.editor.ui.uiUtils.getFixedLayer().style.zIndex = this.getDom().style.zIndex - 4; } }, isHidden: function (){ return this._hidden; }, _hide: function (){ if (!this._hidden) { this.getDom().style.display = 'none'; this.getDom().style.zIndex = ''; this._hidden = true; this.fireEvent('hide'); } }, open: function (){ if (this.autoReset) { //有可能还没有渲染 try{ this.reset(); }catch(e){ this.render(); this.open() } } this.showAtCenter(); if (this.iframeUrl) { try { this.getDom('iframe').focus(); } catch(ex){} } }, _onCloseButtonClick: function (evt, el){ this.close(false); }, close: function (ok){ if (this.fireEvent('close', ok) !== false) { this._hide(); } } }; utils.inherits(Dialog, UIBase); })(); ///import core ///import uicore ///import ui/menu.js ///import ui/splitbutton.js (function (){ var utils = baidu.editor.utils, Menu = baidu.editor.ui.Menu, SplitButton = baidu.editor.ui.SplitButton, MenuButton = baidu.editor.ui.MenuButton = function (options){ this.initOptions(options); this.initMenuButton(); }; MenuButton.prototype = { initMenuButton: function (){ var me = this; this.uiName = "menubutton"; this.popup = new Menu({ items: me.items, className: me.className, editor:me.editor }); this.popup.addListener('show', function (){ var list = this; for (var i=0; i<list.items.length; i++) { list.items[i].removeState('checked'); if (list.items[i].value == me._value) { list.items[i].addState('checked'); this.value = me._value; } } }); this.initSplitButton(); }, setValue : function(value){ this._value = value; } }; utils.inherits(MenuButton, SplitButton); })();//ui跟编辑器的适配層 //那个按钮弹出是dialog,是下拉筐等都是在这个js中配置 //自己写的ui也要在这里配置,放到baidu.editor.ui下边,当编辑器实例化的时候会根据ueditor.config中的toolbars找到相应的进行实例化 (function () { var utils = baidu.editor.utils; var editorui = baidu.editor.ui; var _Dialog = editorui.Dialog; editorui.buttons = {}; editorui.Dialog = function (options) { var dialog = new _Dialog(options); dialog.addListener('hide', function () { if (dialog.editor) { var editor = dialog.editor; try { if (browser.gecko) { var y = editor.window.scrollY, x = editor.window.scrollX; editor.body.focus(); editor.window.scrollTo(x, y); } else { editor.focus(); } } catch (ex) { } } }); return dialog; }; var iframeUrlMap = { 'anchor':'~/dialogs/anchor/anchor.html', 'insertimage':'~/dialogs/image/image.html', 'link':'~/dialogs/link/link.html', 'spechars':'~/dialogs/spechars/spechars.html', 'searchreplace':'~/dialogs/searchreplace/searchreplace.html', 'map':'~/dialogs/map/map.html', 'gmap':'~/dialogs/gmap/gmap.html', 'insertvideo':'~/dialogs/video/video.html', 'help':'~/dialogs/help/help.html', //'highlightcode':'~/dialogs/highlightcode/highlightcode.html', 'emotion':'~/dialogs/emotion/emotion.html', 'wordimage':'~/dialogs/wordimage/wordimage.html', 'attachment':'~/dialogs/attachment/attachment.html', 'insertframe':'~/dialogs/insertframe/insertframe.html', 'edittip':'~/dialogs/table/edittip.html', 'edittable':'~/dialogs/table/edittable.html', 'edittd':'~/dialogs/table/edittd.html', 'webapp':'~/dialogs/webapp/webapp.html', 'snapscreen':'~/dialogs/snapscreen/snapscreen.html', 'scrawl':'~/dialogs/scrawl/scrawl.html', 'music':'~/dialogs/music/music.html', 'template':'~/dialogs/template/template.html', 'background':'~/dialogs/background/background.html' }; //为工具栏添加按钮,以下都是统一的按钮触发命令,所以写在一起 var btnCmds = ['undo', 'redo', 'formatmatch', 'bold', 'italic', 'underline', 'fontborder', 'touppercase', 'tolowercase', 'strikethrough', 'subscript', 'superscript', 'source', 'indent', 'outdent', 'blockquote', 'pasteplain', 'pagebreak', 'selectall', 'print', 'preview', 'horizontal', 'removeformat', 'time', 'date', 'unlink', 'insertparagraphbeforetable', 'insertrow', 'insertcol', 'mergeright', 'mergedown', 'deleterow', 'deletecol', 'splittorows', 'splittocols', 'splittocells', 'mergecells', 'deletetable']; for (var i = 0, ci; ci = btnCmds[i++];) { ci = ci.toLowerCase(); editorui[ci] = function (cmd) { return function (editor) { var ui = new editorui.Button({ className:'edui-for-' + cmd, title:editor.options.labelMap[cmd] || editor.getLang("labelMap." + cmd) || '', onclick:function () { editor.execCommand(cmd); }, theme:editor.options.theme, showText:false }); editorui.buttons[cmd] = ui; editor.addListener('selectionchange', function (type, causeByUi, uiReady) { var state = editor.queryCommandState(cmd); if (state == -1) { ui.setDisabled(true); ui.setChecked(false); } else { if (!uiReady) { ui.setDisabled(false); ui.setChecked(state); } } }); return ui; }; }(ci); } //清除文档 editorui.cleardoc = function (editor) { var ui = new editorui.Button({ className:'edui-for-cleardoc', title:editor.options.labelMap.cleardoc || editor.getLang("labelMap.cleardoc") || '', theme:editor.options.theme, onclick:function () { if (confirm(editor.getLang("confirmClear"))) { editor.execCommand('cleardoc'); } } }); editorui.buttons["cleardoc"] = ui; editor.addListener('selectionchange', function () { ui.setDisabled(editor.queryCommandState('cleardoc') == -1); }); return ui; }; //排版,图片排版,文字方向 var typeset = { 'justify':['left', 'right', 'center', 'justify'], 'imagefloat':['none', 'left', 'center', 'right'], 'directionality':['ltr', 'rtl'] }; for (var p in typeset) { (function (cmd, val) { for (var i = 0, ci; ci = val[i++];) { (function (cmd2) { editorui[cmd.replace('float', '') + cmd2] = function (editor) { var ui = new editorui.Button({ className:'edui-for-' + cmd.replace('float', '') + cmd2, title:editor.options.labelMap[cmd.replace('float', '') + cmd2] || editor.getLang("labelMap." + cmd.replace('float', '') + cmd2) || '', theme:editor.options.theme, onclick:function () { editor.execCommand(cmd, cmd2); } }); editorui.buttons[cmd] = ui; editor.addListener('selectionchange', function (type, causeByUi, uiReady) { ui.setDisabled(editor.queryCommandState(cmd) == -1); ui.setChecked(editor.queryCommandValue(cmd) == cmd2 && !uiReady); }); return ui; }; })(ci) } })(p, typeset[p]) } //字体颜色和背景颜色 for (var i = 0, ci; ci = ['backcolor', 'forecolor'][i++];) { editorui[ci] = function (cmd) { return function (editor) { var ui = new editorui.ColorButton({ className:'edui-for-' + cmd, color:'default', title:editor.options.labelMap[cmd] || editor.getLang("labelMap." + cmd) || '', editor:editor, onpickcolor:function (t, color) { editor.execCommand(cmd, color); }, onpicknocolor:function () { editor.execCommand(cmd, 'default'); this.setColor('transparent'); this.color = 'default'; }, onbuttonclick:function () { editor.execCommand(cmd, this.color); } }); editorui.buttons[cmd] = ui; editor.addListener('selectionchange', function () { ui.setDisabled(editor.queryCommandState(cmd) == -1); }); return ui; }; }(ci); } var dialogBtns = { noOk:['searchreplace', 'help', 'spechars', 'webapp'], ok:['attachment', 'anchor', 'link', 'insertimage', 'map', 'gmap', 'insertframe', 'wordimage', 'insertvideo', 'insertframe', 'edittip', 'edittable', 'edittd', 'scrawl', 'template', 'music', 'background'] }; for (var p in dialogBtns) { (function (type, vals) { for (var i = 0, ci; ci = vals[i++];) { //todo opera下存在问题 if (browser.opera && ci === "searchreplace") { continue; } (function (cmd) { editorui[cmd] = function (editor, iframeUrl, title) { iframeUrl = iframeUrl || (editor.options.iframeUrlMap || {})[cmd] || iframeUrlMap[cmd]; title = editor.options.labelMap[cmd] || editor.getLang("labelMap." + cmd) || ''; var dialog; //没有iframeUrl不创建dialog if (iframeUrl) { dialog = new editorui.Dialog(utils.extend({ iframeUrl:editor.ui.mapUrl(iframeUrl), editor:editor, className:'edui-for-' + cmd, title:title, holdScroll: cmd === 'insertimage', closeDialog:editor.getLang("closeDialog") }, type == 'ok' ? { buttons:[ { className:'edui-okbutton', label:editor.getLang("ok"), editor:editor, onclick:function () { dialog.close(true); } }, { className:'edui-cancelbutton', label:editor.getLang("cancel"), editor:editor, onclick:function () { dialog.close(false); } } ] } : {})); editor.ui._dialogs[cmd + "Dialog"] = dialog; } var ui = new editorui.Button({ className:'edui-for-' + cmd, title:title, onclick:function () { if (dialog) { switch (cmd) { case "wordimage": editor.execCommand("wordimage", "word_img"); if (editor.word_img) { dialog.render(); dialog.open(); } break; case "scrawl": if (editor.queryCommandState("scrawl") != -1) { dialog.render(); dialog.open(); } break; default: dialog.render(); dialog.open(); } } }, theme:editor.options.theme, disabled:cmd == 'scrawl' && editor.queryCommandState("scrawl") == -1 }); editorui.buttons[cmd] = ui; editor.addListener('selectionchange', function () { //只存在于右键菜单而无工具栏按钮的ui不需要检测状态 var unNeedCheckState = {'edittable':1}; if (cmd in unNeedCheckState)return; var state = editor.queryCommandState(cmd); if (ui.getDom()) { ui.setDisabled(state == -1); ui.setChecked(state); } }); return ui; }; })(ci.toLowerCase()) } })(p, dialogBtns[p]) } editorui.snapscreen = function (editor, iframeUrl, title) { title = editor.options.labelMap['snapscreen'] || editor.getLang("labelMap.snapscreen") || ''; var ui = new editorui.Button({ className:'edui-for-snapscreen', title:title, onclick:function () { editor.execCommand("snapscreen"); }, theme:editor.options.theme }); editorui.buttons['snapscreen'] = ui; iframeUrl = iframeUrl || (editor.options.iframeUrlMap || {})["snapscreen"] || iframeUrlMap["snapscreen"]; if (iframeUrl) { var dialog = new editorui.Dialog({ iframeUrl:editor.ui.mapUrl(iframeUrl), editor:editor, className:'edui-for-snapscreen', title:title, buttons:[ { className:'edui-okbutton', label:editor.getLang("ok"), editor:editor, onclick:function () { dialog.close(true); } }, { className:'edui-cancelbutton', label:editor.getLang("cancel"), editor:editor, onclick:function () { dialog.close(false); } } ] }); dialog.render(); editor.ui._dialogs["snapscreenDialog"] = dialog; } editor.addListener('selectionchange', function () { ui.setDisabled(editor.queryCommandState('snapscreen') == -1); }); return ui; }; editorui.insertcode = function (editor, list, title) { list = editor.options['insertcode'] || []; title = editor.options.labelMap['insertcode'] || editor.getLang("labelMap.insertcode") || ''; // if (!list.length) return; var items = []; utils.each(list,function(key,val){ items.push({ label:key, value:val, theme:editor.options.theme, renderLabelHtml:function () { return '<div class="edui-label %%-label" >' + (this.label || '') + '</div>'; } }); }); var ui = new editorui.Combox({ editor:editor, items:items, onselect:function (t, index) { editor.execCommand('insertcode', this.items[index].value); }, onbuttonclick:function () { this.showPopup(); }, title:title, initValue:title, className:'edui-for-insertcode', indexByValue:function (value) { if (value) { for (var i = 0, ci; ci = this.items[i]; i++) { if (ci.value.indexOf(value) != -1) return i; } } return -1; } }); editorui.buttons['insertcode'] = ui; editor.addListener('selectionchange', function (type, causeByUi, uiReady) { if (!uiReady) { var state = editor.queryCommandState('insertcode'); if (state == -1) { ui.setDisabled(true); } else { ui.setDisabled(false); var value = editor.queryCommandValue('insertcode'); if(!value){ ui.setValue(title); return; } //trace:1871 ie下从源码模式切换回来时,字体会带单引号,而且会有逗号 value && (value = value.replace(/['"]/g, '').split(',')[0]); ui.setValue(value); } } }); return ui; }; editorui.fontfamily = function (editor, list, title) { list = editor.options['fontfamily'] || []; title = editor.options.labelMap['fontfamily'] || editor.getLang("labelMap.fontfamily") || ''; if (!list.length) return; for (var i = 0, ci, items = []; ci = list[i]; i++) { var langLabel = editor.getLang('fontfamily')[ci.name] || ""; (function (key, val) { items.push({ label:key, value:val, theme:editor.options.theme, renderLabelHtml:function () { return '<div class="edui-label %%-label" style="font-family:' + utils.unhtml(this.value) + '">' + (this.label || '') + '</div>'; } }); })(ci.label || langLabel, ci.val) } var ui = new editorui.Combox({ editor:editor, items:items, onselect:function (t, index) { editor.execCommand('FontFamily', this.items[index].value); }, onbuttonclick:function () { this.showPopup(); }, title:title, initValue:title, className:'edui-for-fontfamily', indexByValue:function (value) { if (value) { for (var i = 0, ci; ci = this.items[i]; i++) { if (ci.value.indexOf(value) != -1) return i; } } return -1; } }); editorui.buttons['fontfamily'] = ui; editor.addListener('selectionchange', function (type, causeByUi, uiReady) { if (!uiReady) { var state = editor.queryCommandState('FontFamily'); if (state == -1) { ui.setDisabled(true); } else { ui.setDisabled(false); var value = editor.queryCommandValue('FontFamily'); //trace:1871 ie下从源码模式切换回来时,字体会带单引号,而且会有逗号 value && (value = value.replace(/['"]/g, '').split(',')[0]); ui.setValue(value); } } }); return ui; }; editorui.fontsize = function (editor, list, title) { title = editor.options.labelMap['fontsize'] || editor.getLang("labelMap.fontsize") || ''; list = list || editor.options['fontsize'] || []; if (!list.length) return; var items = []; for (var i = 0; i < list.length; i++) { var size = list[i] + 'px'; items.push({ label:size, value:size, theme:editor.options.theme, renderLabelHtml:function () { return '<div class="edui-label %%-label" style="line-height:1;font-size:' + this.value + '">' + (this.label || '') + '</div>'; } }); } var ui = new editorui.Combox({ editor:editor, items:items, title:title, initValue:title, onselect:function (t, index) { editor.execCommand('FontSize', this.items[index].value); }, onbuttonclick:function () { this.showPopup(); }, className:'edui-for-fontsize' }); editorui.buttons['fontsize'] = ui; editor.addListener('selectionchange', function (type, causeByUi, uiReady) { if (!uiReady) { var state = editor.queryCommandState('FontSize'); if (state == -1) { ui.setDisabled(true); } else { ui.setDisabled(false); ui.setValue(editor.queryCommandValue('FontSize')); } } }); return ui; }; editorui.paragraph = function (editor, list, title) { title = editor.options.labelMap['paragraph'] || editor.getLang("labelMap.paragraph") || ''; list = editor.options['paragraph'] || []; if (utils.isEmptyObject(list)) return; var items = []; for (var i in list) { items.push({ value:i, label:list[i] || editor.getLang("paragraph")[i], theme:editor.options.theme, renderLabelHtml:function () { return '<div class="edui-label %%-label"><span class="edui-for-' + this.value + '">' + (this.label || '') + '</span></div>'; } }) } var ui = new editorui.Combox({ editor:editor, items:items, title:title, initValue:title, className:'edui-for-paragraph', onselect:function (t, index) { editor.execCommand('Paragraph', this.items[index].value); }, onbuttonclick:function () { this.showPopup(); } }); editorui.buttons['paragraph'] = ui; editor.addListener('selectionchange', function (type, causeByUi, uiReady) { if (!uiReady) { var state = editor.queryCommandState('Paragraph'); if (state == -1) { ui.setDisabled(true); } else { ui.setDisabled(false); var value = editor.queryCommandValue('Paragraph'); var index = ui.indexByValue(value); if (index != -1) { ui.setValue(value); } else { ui.setValue(ui.initValue); } } } }); return ui; }; //自定义标题 editorui.customstyle = function (editor) { var list = editor.options['customstyle'] || [], title = editor.options.labelMap['customstyle'] || editor.getLang("labelMap.customstyle") || ''; if (!list.length)return; var langCs = editor.getLang('customstyle'); for (var i = 0, items = [], t; t = list[i++];) { (function (t) { var ck = {}; ck.label = t.label ? t.label : langCs[t.name]; ck.style = t.style; ck.className = t.className; ck.tag = t.tag; items.push({ label:ck.label, value:ck, theme:editor.options.theme, renderLabelHtml:function () { return '<div class="edui-label %%-label">' + '<' + ck.tag + ' ' + (ck.className ? ' class="' + ck.className + '"' : "") + (ck.style ? ' style="' + ck.style + '"' : "") + '>' + ck.label + "<\/" + ck.tag + ">" + '</div>'; } }); })(t); } var ui = new editorui.Combox({ editor:editor, items:items, title:title, initValue:title, className:'edui-for-customstyle', onselect:function (t, index) { editor.execCommand('customstyle', this.items[index].value); }, onbuttonclick:function () { this.showPopup(); }, indexByValue:function (value) { for (var i = 0, ti; ti = this.items[i++];) { if (ti.label == value) { return i - 1 } } return -1; } }); editorui.buttons['customstyle'] = ui; editor.addListener('selectionchange', function (type, causeByUi, uiReady) { if (!uiReady) { var state = editor.queryCommandState('customstyle'); if (state == -1) { ui.setDisabled(true); } else { ui.setDisabled(false); var value = editor.queryCommandValue('customstyle'); var index = ui.indexByValue(value); if (index != -1) { ui.setValue(value); } else { ui.setValue(ui.initValue); } } } }); return ui; }; editorui.inserttable = function (editor, iframeUrl, title) { title = editor.options.labelMap['inserttable'] || editor.getLang("labelMap.inserttable") || ''; var ui = new editorui.TableButton({ editor:editor, title:title, className:'edui-for-inserttable', onpicktable:function (t, numCols, numRows) { editor.execCommand('InsertTable', {numRows:numRows, numCols:numCols, border:1}); }, onbuttonclick:function () { this.showPopup(); } }); editorui.buttons['inserttable'] = ui; editor.addListener('selectionchange', function () { ui.setDisabled(editor.queryCommandState('inserttable') == -1); }); return ui; }; editorui.lineheight = function (editor) { var val = editor.options.lineheight || []; if (!val.length)return; for (var i = 0, ci, items = []; ci = val[i++];) { items.push({ //todo:写死了 label:ci, value:ci, theme:editor.options.theme, onclick:function () { editor.execCommand("lineheight", this.value); } }) } var ui = new editorui.MenuButton({ editor:editor, className:'edui-for-lineheight', title:editor.options.labelMap['lineheight'] || editor.getLang("labelMap.lineheight") || '', items:items, onbuttonclick:function () { var value = editor.queryCommandValue('LineHeight') || this.value; editor.execCommand("LineHeight", value); } }); editorui.buttons['lineheight'] = ui; editor.addListener('selectionchange', function () { var state = editor.queryCommandState('LineHeight'); if (state == -1) { ui.setDisabled(true); } else { ui.setDisabled(false); var value = editor.queryCommandValue('LineHeight'); value && ui.setValue((value + '').replace(/cm/, '')); ui.setChecked(state) } }); return ui; }; var rowspacings = ['top', 'bottom']; for (var r = 0, ri; ri = rowspacings[r++];) { (function (cmd) { editorui['rowspacing' + cmd] = function (editor) { var val = editor.options['rowspacing' + cmd] || []; if (!val.length) return null; for (var i = 0, ci, items = []; ci = val[i++];) { items.push({ label:ci, value:ci, theme:editor.options.theme, onclick:function () { editor.execCommand("rowspacing", this.value, cmd); } }) } var ui = new editorui.MenuButton({ editor:editor, className:'edui-for-rowspacing' + cmd, title:editor.options.labelMap['rowspacing' + cmd] || editor.getLang("labelMap.rowspacing" + cmd) || '', items:items, onbuttonclick:function () { var value = editor.queryCommandValue('rowspacing', cmd) || this.value; editor.execCommand("rowspacing", value, cmd); } }); editorui.buttons[cmd] = ui; editor.addListener('selectionchange', function () { var state = editor.queryCommandState('rowspacing', cmd); if (state == -1) { ui.setDisabled(true); } else { ui.setDisabled(false); var value = editor.queryCommandValue('rowspacing', cmd); value && ui.setValue((value + '').replace(/%/, '')); ui.setChecked(state) } }); return ui; } })(ri) } //有序,无序列表 var lists = ['insertorderedlist', 'insertunorderedlist']; for (var l = 0, cl; cl = lists[l++];) { (function (cmd) { editorui[cmd] = function (editor) { var vals = editor.options[cmd], _onMenuClick = function () { editor.execCommand(cmd, this.value); }, items = []; for (var i in vals) { items.push({ label:vals[i] || editor.getLang()[cmd][i] || "", value:i, theme:editor.options.theme, onclick:_onMenuClick }) } var ui = new editorui.MenuButton({ editor:editor, className:'edui-for-' + cmd, title:editor.getLang("labelMap." + cmd) || '', 'items':items, onbuttonclick:function () { var value = editor.queryCommandValue(cmd) || this.value; editor.execCommand(cmd, value); } }); editorui.buttons[cmd] = ui; editor.addListener('selectionchange', function () { var state = editor.queryCommandState(cmd); if (state == -1) { ui.setDisabled(true); } else { ui.setDisabled(false); var value = editor.queryCommandValue(cmd); ui.setValue(value); ui.setChecked(state) } }); return ui; }; })(cl) } editorui.fullscreen = function (editor, title) { title = editor.options.labelMap['fullscreen'] || editor.getLang("labelMap.fullscreen") || ''; var ui = new editorui.Button({ className:'edui-for-fullscreen', title:title, theme:editor.options.theme, onclick:function () { if (editor.ui) { editor.ui.setFullScreen(!editor.ui.isFullScreen()); } this.setChecked(editor.ui.isFullScreen()); } }); editorui.buttons['fullscreen'] = ui; editor.addListener('selectionchange', function () { var state = editor.queryCommandState('fullscreen'); ui.setDisabled(state == -1); ui.setChecked(editor.ui.isFullScreen()); }); return ui; }; // 表情 editorui["emotion"] = function (editor, iframeUrl) { var cmd = "emotion"; var ui = new editorui.MultiMenuPop({ title:editor.options.labelMap[cmd] || editor.getLang("labelMap." + cmd + "") || '', editor:editor, className:'edui-for-' + cmd, iframeUrl:editor.ui.mapUrl(iframeUrl || (editor.options.iframeUrlMap || {})[cmd] || iframeUrlMap[cmd]) }); editorui.buttons[cmd] = ui; editor.addListener('selectionchange', function () { ui.setDisabled(editor.queryCommandState(cmd) == -1) }); return ui; }; editorui.autotypeset = function (editor) { var ui = new editorui.AutoTypeSetButton({ editor:editor, title:editor.options.labelMap['autotypeset'] || editor.getLang("labelMap.autotypeset") || '', className:'edui-for-autotypeset', onbuttonclick:function () { editor.execCommand('autotypeset') } }); editorui.buttons['autotypeset'] = ui; editor.addListener('selectionchange', function () { ui.setDisabled(editor.queryCommandState('autotypeset') == -1); }); return ui; }; })(); ///import core ///commands 全屏 ///commandsName FullScreen ///commandsTitle 全屏 (function () { var utils = baidu.editor.utils, uiUtils = baidu.editor.ui.uiUtils, UIBase = baidu.editor.ui.UIBase, domUtils = baidu.editor.dom.domUtils; var nodeStack = []; function EditorUI(options) { this.initOptions(options); this.initEditorUI(); } EditorUI.prototype = { uiName:'editor', initEditorUI:function () { this.editor.ui = this; this._dialogs = {}; this.initUIBase(); this._initToolbars(); var editor = this.editor, me = this; editor.addListener('ready', function () { //提供getDialog方法 editor.getDialog = function (name) { return editor.ui._dialogs[name + "Dialog"]; }; domUtils.on(editor.window, 'scroll', function (evt) { baidu.editor.ui.Popup.postHide(evt); }); //提供编辑器实时宽高(全屏时宽高不变化) editor.ui._actualFrameWidth = editor.options.initialFrameWidth; //display bottom-bar label based on config if (editor.options.elementPathEnabled) { editor.ui.getDom('elementpath').innerHTML = '<div class="edui-editor-breadcrumb">' + editor.getLang("elementPathTip") + ':</div>'; } if (editor.options.wordCount) { function countFn() { setCount(editor,me); domUtils.un(editor.document, "click", arguments.callee); } domUtils.on(editor.document, "click", countFn); editor.ui.getDom('wordcount').innerHTML = editor.getLang("wordCountTip"); } editor.ui._scale(); if (editor.options.scaleEnabled) { if (editor.autoHeightEnabled) { editor.disableAutoHeight(); } me.enableScale(); } else { me.disableScale(); } if (!editor.options.elementPathEnabled && !editor.options.wordCount && !editor.options.scaleEnabled) { editor.ui.getDom('elementpath').style.display = "none"; editor.ui.getDom('wordcount').style.display = "none"; editor.ui.getDom('scale').style.display = "none"; } if (!editor.selection.isFocus())return; editor.fireEvent('selectionchange', false, true); }); editor.addListener('mousedown', function (t, evt) { var el = evt.target || evt.srcElement; baidu.editor.ui.Popup.postHide(evt, el); baidu.editor.ui.ShortCutMenu.postHide(evt); }); editor.addListener("delcells", function () { if (UE.ui['edittip']) { new UE.ui['edittip'](editor); } editor.getDialog('edittip').open(); }); var pastePop, isPaste = false, timer; editor.addListener("afterpaste", function () { if(editor.queryCommandState('pasteplain')) return; if(baidu.editor.ui.PastePicker){ pastePop = new baidu.editor.ui.Popup({ content:new baidu.editor.ui.PastePicker({editor:editor}), editor:editor, className:'edui-wordpastepop' }); pastePop.render(); } isPaste = true; }); editor.addListener("afterinserthtml", function () { clearTimeout(timer); timer = setTimeout(function () { if (pastePop && (isPaste || editor.ui._isTransfer)) { if(pastePop.isHidden()){ var span = domUtils.createElement(editor.document, 'span', { 'style':"line-height:0px;", 'innerHTML':'\ufeff' }), range = editor.selection.getRange(); range.insertNode(span); var tmp= getDomNode(span, 'firstChild', 'previousSibling'); pastePop.showAnchor(tmp.nodeType == 3 ? tmp.parentNode : tmp); domUtils.remove(span); }else{ pastePop.show(); } delete editor.ui._isTransfer; isPaste = false; } }, 200) }); editor.addListener('contextmenu', function (t, evt) { baidu.editor.ui.Popup.postHide(evt); }); editor.addListener('keydown', function (t, evt) { if (pastePop) pastePop.dispose(evt); var keyCode = evt.keyCode || evt.which; if(evt.altKey&&keyCode==90){ UE.ui.buttons['fullscreen'].onclick(); } }); editor.addListener('wordcount', function (type) { setCount(this,me); }); function setCount(editor,ui) { editor.setOpt({ wordCount:true, maximumWords:10000, wordCountMsg:editor.options.wordCountMsg || editor.getLang("wordCountMsg"), wordOverFlowMsg:editor.options.wordOverFlowMsg || editor.getLang("wordOverFlowMsg") }); var opt = editor.options, max = opt.maximumWords, msg = opt.wordCountMsg , errMsg = opt.wordOverFlowMsg, countDom = ui.getDom('wordcount'); if (!opt.wordCount) { return; } var count = editor.getContentLength(true); if (count > max) { countDom.innerHTML = errMsg; editor.fireEvent("wordcountoverflow"); } else { countDom.innerHTML = msg.replace("{#leave}", max - count).replace("{#count}", count); } } editor.addListener('selectionchange', function () { if (editor.options.elementPathEnabled) { me[(editor.queryCommandState('elementpath') == -1 ? 'dis' : 'en') + 'ableElementPath']() } if (editor.options.scaleEnabled) { me[(editor.queryCommandState('scale') == -1 ? 'dis' : 'en') + 'ableScale'](); } }); var popup = new baidu.editor.ui.Popup({ editor:editor, content:'', className:'edui-bubble', _onEditButtonClick:function () { this.hide(); editor.ui._dialogs.linkDialog.open(); }, _onImgEditButtonClick:function (name) { this.hide(); editor.ui._dialogs[name] && editor.ui._dialogs[name].open(); }, _onImgSetFloat:function (value) { this.hide(); editor.execCommand("imagefloat", value); }, _setIframeAlign:function (value) { var frame = popup.anchorEl; var newFrame = frame.cloneNode(true); switch (value) { case -2: newFrame.setAttribute("align", ""); break; case -1: newFrame.setAttribute("align", "left"); break; case 1: newFrame.setAttribute("align", "right"); break; } frame.parentNode.insertBefore(newFrame, frame); domUtils.remove(frame); popup.anchorEl = newFrame; popup.showAnchor(popup.anchorEl); }, _updateIframe:function () { editor._iframe = popup.anchorEl; editor.ui._dialogs.insertframeDialog.open(); popup.hide(); }, _onRemoveButtonClick:function (cmdName) { editor.execCommand(cmdName); this.hide(); }, queryAutoHide:function (el) { if (el && el.ownerDocument == editor.document) { if (el.tagName.toLowerCase() == 'img' || domUtils.findParentByTagName(el, 'a', true)) { return el !== popup.anchorEl; } } return baidu.editor.ui.Popup.prototype.queryAutoHide.call(this, el); } }); popup.render(); if (editor.options.imagePopup) { editor.addListener('mouseover', function (t, evt) { evt = evt || window.event; var el = evt.target || evt.srcElement; if (editor.ui._dialogs.insertframeDialog && /iframe/ig.test(el.tagName)) { var html = popup.formatHtml( '<nobr>' + editor.getLang("property") + ': <span onclick=$$._setIframeAlign(-2) class="edui-clickable">' + editor.getLang("default") + '</span>&nbsp;&nbsp;<span onclick=$$._setIframeAlign(-1) class="edui-clickable">' + editor.getLang("justifyleft") + '</span>&nbsp;&nbsp;<span onclick=$$._setIframeAlign(1) class="edui-clickable">' + editor.getLang("justifyright") + '</span>&nbsp;&nbsp;' + ' <span onclick="$$._updateIframe( this);" class="edui-clickable">' + editor.getLang("modify") + '</span></nobr>'); if (html) { popup.getDom('content').innerHTML = html; popup.anchorEl = el; popup.showAnchor(popup.anchorEl); } else { popup.hide(); } } }); editor.addListener('selectionchange', function (t, causeByUi) { if (!causeByUi) return; var html = '', str = "", img = editor.selection.getRange().getClosedNode(), dialogs = editor.ui._dialogs; if (img && img.tagName == 'IMG') { var dialogName = 'insertimageDialog'; if (img.className.indexOf("edui-faked-video") != -1) { dialogName = "insertvideoDialog" } if (img.className.indexOf("edui-faked-webapp") != -1) { dialogName = "webappDialog" } if (img.src.indexOf("http://api.map.baidu.com") != -1) { dialogName = "mapDialog" } if (img.className.indexOf("edui-faked-music") != -1) { dialogName = "musicDialog" } if (img.src.indexOf("http://maps.google.com/maps/api/staticmap") != -1) { dialogName = "gmapDialog" } if (img.getAttribute("anchorname")) { dialogName = "anchorDialog"; html = popup.formatHtml( '<nobr>' + editor.getLang("property") + ': <span onclick=$$._onImgEditButtonClick("anchorDialog") class="edui-clickable">' + editor.getLang("modify") + '</span>&nbsp;&nbsp;' + '<span onclick=$$._onRemoveButtonClick(\'anchor\') class="edui-clickable">' + editor.getLang("delete") + '</span></nobr>'); } if (img.getAttribute("word_img")) { //todo 放到dialog去做查询 editor.word_img = [img.getAttribute("word_img")]; dialogName = "wordimageDialog" } if (!dialogs[dialogName]) { return; } str = '<nobr>' + editor.getLang("property") + ': '+ '<span onclick=$$._onImgSetFloat("none") class="edui-clickable">' + editor.getLang("default") + '</span>&nbsp;&nbsp;' + '<span onclick=$$._onImgSetFloat("left") class="edui-clickable">' + editor.getLang("justifyleft") + '</span>&nbsp;&nbsp;' + '<span onclick=$$._onImgSetFloat("right") class="edui-clickable">' + editor.getLang("justifyright") + '</span>&nbsp;&nbsp;' + '<span onclick=$$._onImgSetFloat("center") class="edui-clickable">' + editor.getLang("justifycenter") + '</span>&nbsp;&nbsp;'+ '<span onclick="$$._onImgEditButtonClick(\'' + dialogName + '\');" class="edui-clickable">' + editor.getLang("modify") + '</span></nobr>'; !html && (html = popup.formatHtml(str)) } if (editor.ui._dialogs.linkDialog) { var link = editor.queryCommandValue('link'); var url; if (link && (url = (link.getAttribute('_href') || link.getAttribute('href', 2)))) { var txt = url; if (url.length > 30) { txt = url.substring(0, 20) + "..."; } if (html) { html += '<div style="height:5px;"></div>' } html += popup.formatHtml( '<nobr>' + editor.getLang("anthorMsg") + ': <a target="_blank" href="' + url + '" title="' + url + '" >' + txt + '</a>' + ' <span class="edui-clickable" onclick="$$._onEditButtonClick();">' + editor.getLang("modify") + '</span>' + ' <span class="edui-clickable" onclick="$$._onRemoveButtonClick(\'unlink\');"> ' + editor.getLang("clear") + '</span></nobr>'); popup.showAnchor(link); } } if (html) { popup.getDom('content').innerHTML = html; popup.anchorEl = img || link; popup.showAnchor(popup.anchorEl); } else { popup.hide(); } }); } }, _initToolbars:function () { var editor = this.editor; var toolbars = this.toolbars || []; var toolbarUis = []; for (var i = 0; i < toolbars.length; i++) { var toolbar = toolbars[i]; var toolbarUi = new baidu.editor.ui.Toolbar({theme:editor.options.theme}); for (var j = 0; j < toolbar.length; j++) { var toolbarItem = toolbar[j]; var toolbarItemUi = null; if (typeof toolbarItem == 'string') { toolbarItem = toolbarItem.toLowerCase(); if (toolbarItem == '|') { toolbarItem = 'Separator'; } if(toolbarItem == '||'){ toolbarItem = 'Breakline'; } if (baidu.editor.ui[toolbarItem]) { toolbarItemUi = new baidu.editor.ui[toolbarItem](editor); } //fullscreen这里单独处理一下,放到首行去 if (toolbarItem == 'fullscreen') { if (toolbarUis && toolbarUis[0]) { toolbarUis[0].items.splice(0, 0, toolbarItemUi); } else { toolbarItemUi && toolbarUi.items.splice(0, 0, toolbarItemUi); } continue; } } else { toolbarItemUi = toolbarItem; } if (toolbarItemUi && toolbarItemUi.id) { toolbarUi.add(toolbarItemUi); } } toolbarUis[i] = toolbarUi; } this.toolbars = toolbarUis; }, getHtmlTpl:function () { return '<div id="##" class="%%">' + '<div id="##_toolbarbox" class="%%-toolbarbox">' + (this.toolbars.length ? '<div id="##_toolbarboxouter" class="%%-toolbarboxouter"><div class="%%-toolbarboxinner">' + this.renderToolbarBoxHtml() + '</div></div>' : '') + '<div id="##_toolbarmsg" class="%%-toolbarmsg" style="display:none;">' + '<div id = "##_upload_dialog" class="%%-toolbarmsg-upload" onclick="$$.showWordImageDialog();">' + this.editor.getLang("clickToUpload") + '</div>' + '<div class="%%-toolbarmsg-close" onclick="$$.hideToolbarMsg();">x</div>' + '<div id="##_toolbarmsg_label" class="%%-toolbarmsg-label"></div>' + '<div style="height:0;overflow:hidden;clear:both;"></div>' + '</div>' + '</div>' + '<div id="##_iframeholder" class="%%-iframeholder"></div>' + //modify wdcount by matao '<div id="##_bottombar" class="%%-bottomContainer"><table><tr>' + '<td id="##_elementpath" class="%%-bottombar"></td>' + '<td id="##_wordcount" class="%%-wordcount"></td>' + '<td id="##_scale" class="%%-scale"><div class="%%-icon"></div></td>' + '</tr></table></div>' + '<div id="##_scalelayer"></div>' + '</div>'; }, showWordImageDialog:function () { this.editor.execCommand("wordimage", "word_img"); this._dialogs['wordimageDialog'].open(); }, renderToolbarBoxHtml:function () { var buff = []; for (var i = 0; i < this.toolbars.length; i++) { buff.push(this.toolbars[i].renderHtml()); } return buff.join(''); }, setFullScreen:function (fullscreen) { var editor = this.editor, container = editor.container.parentNode.parentNode; if (this._fullscreen != fullscreen) { this._fullscreen = fullscreen; this.editor.fireEvent('beforefullscreenchange', fullscreen); if (baidu.editor.browser.gecko) { var bk = editor.selection.getRange().createBookmark(); } if (fullscreen) { while (container.tagName != "BODY") { var position = baidu.editor.dom.domUtils.getComputedStyle(container, "position"); nodeStack.push(position); container.style.position = "static"; container = container.parentNode; } this._bakHtmlOverflow = document.documentElement.style.overflow; this._bakBodyOverflow = document.body.style.overflow; this._bakAutoHeight = this.editor.autoHeightEnabled; this._bakScrollTop = Math.max(document.documentElement.scrollTop, document.body.scrollTop); this._bakEditorContaninerWidth = editor.iframe.parentNode.offsetWidth; if (this._bakAutoHeight) { //当全屏时不能执行自动长高 editor.autoHeightEnabled = false; this.editor.disableAutoHeight(); } document.documentElement.style.overflow = 'hidden'; document.body.style.overflow = 'hidden'; this._bakCssText = this.getDom().style.cssText; this._bakCssText1 = this.getDom('iframeholder').style.cssText; editor.iframe.parentNode.style.width = ''; this._updateFullScreen(); } else { while (container.tagName != "BODY") { container.style.position = nodeStack.shift(); container = container.parentNode; } this.getDom().style.cssText = this._bakCssText; this.getDom('iframeholder').style.cssText = this._bakCssText1; if (this._bakAutoHeight) { editor.autoHeightEnabled = true; this.editor.enableAutoHeight(); } document.documentElement.style.overflow = this._bakHtmlOverflow; document.body.style.overflow = this._bakBodyOverflow; editor.iframe.parentNode.style.width = this._bakEditorContaninerWidth + 'px'; window.scrollTo(0, this._bakScrollTop); } if (browser.gecko && editor.body.contentEditable === 'true') { var input = document.createElement('input'); document.body.appendChild(input); editor.body.contentEditable = false; setTimeout(function () { input.focus(); setTimeout(function () { editor.body.contentEditable = true; editor.fireEvent('fullscreenchanged', fullscreen); editor.selection.getRange().moveToBookmark(bk).select(true); baidu.editor.dom.domUtils.remove(input); fullscreen && window.scroll(0, 0); }, 0) }, 0) } if(editor.body.contentEditable === 'true'){ this.editor.fireEvent('fullscreenchanged', fullscreen); this.triggerLayout(); } } }, _updateFullScreen:function () { if (this._fullscreen) { var vpRect = uiUtils.getViewportRect(); this.getDom().style.cssText = 'border:0;position:absolute;left:0;top:' + (this.editor.options.topOffset || 0) + 'px;width:' + vpRect.width + 'px;height:' + vpRect.height + 'px;z-index:' + (this.getDom().style.zIndex * 1 + 100); uiUtils.setViewportOffset(this.getDom(), { left:0, top:this.editor.options.topOffset || 0 }); this.editor.setHeight(vpRect.height - this.getDom('toolbarbox').offsetHeight - this.getDom('bottombar').offsetHeight - (this.editor.options.topOffset || 0)); //不手动调一下,会导致全屏失效 if(browser.gecko){ try{ window.onresize(); }catch(e){ } } } }, _updateElementPath:function () { var bottom = this.getDom('elementpath'), list; if (this.elementPathEnabled && (list = this.editor.queryCommandValue('elementpath'))) { var buff = []; for (var i = 0, ci; ci = list[i]; i++) { buff[i] = this.formatHtml('<span unselectable="on" onclick="$$.editor.execCommand(&quot;elementpath&quot;, &quot;' + i + '&quot;);">' + ci + '</span>'); } bottom.innerHTML = '<div class="edui-editor-breadcrumb" onmousedown="return false;">' + this.editor.getLang("elementPathTip") + ': ' + buff.join(' &gt; ') + '</div>'; } else { bottom.style.display = 'none' } }, disableElementPath:function () { var bottom = this.getDom('elementpath'); bottom.innerHTML = ''; bottom.style.display = 'none'; this.elementPathEnabled = false; }, enableElementPath:function () { var bottom = this.getDom('elementpath'); bottom.style.display = ''; this.elementPathEnabled = true; this._updateElementPath(); }, _scale:function () { var doc = document, editor = this.editor, editorHolder = editor.container, editorDocument = editor.document, toolbarBox = this.getDom("toolbarbox"), bottombar = this.getDom("bottombar"), scale = this.getDom("scale"), scalelayer = this.getDom("scalelayer"); var isMouseMove = false, position = null, minEditorHeight = 0, minEditorWidth = editor.options.minFrameWidth, pageX = 0, pageY = 0, scaleWidth = 0, scaleHeight = 0; function down() { position = domUtils.getXY(editorHolder); if (!minEditorHeight) { minEditorHeight = editor.options.minFrameHeight + toolbarBox.offsetHeight + bottombar.offsetHeight; } scalelayer.style.cssText = "position:absolute;left:0;display:;top:0;background-color:#41ABFF;opacity:0.4;filter: Alpha(opacity=40);width:" + editorHolder.offsetWidth + "px;height:" + editorHolder.offsetHeight + "px;z-index:" + (editor.options.zIndex + 1); domUtils.on(doc, "mousemove", move); domUtils.on(editorDocument, "mouseup", up); domUtils.on(doc, "mouseup", up); } var me = this; //by xuheng 全屏时关掉缩放 this.editor.addListener('fullscreenchanged', function (e, fullScreen) { if (fullScreen) { me.disableScale(); } else { if (me.editor.options.scaleEnabled) { me.enableScale(); var tmpNode = me.editor.document.createElement('span'); me.editor.body.appendChild(tmpNode); me.editor.body.style.height = Math.max(domUtils.getXY(tmpNode).y, me.editor.iframe.offsetHeight - 20) + 'px'; domUtils.remove(tmpNode) } } }); function move(event) { clearSelection(); var e = event || window.event; pageX = e.pageX || (doc.documentElement.scrollLeft + e.clientX); pageY = e.pageY || (doc.documentElement.scrollTop + e.clientY); scaleWidth = pageX - position.x; scaleHeight = pageY - position.y; if (scaleWidth >= minEditorWidth) { isMouseMove = true; scalelayer.style.width = scaleWidth + 'px'; } if (scaleHeight >= minEditorHeight) { isMouseMove = true; scalelayer.style.height = scaleHeight + "px"; } } function up() { if (isMouseMove) { isMouseMove = false; editor.ui._actualFrameWidth = scalelayer.offsetWidth - 2; editorHolder.style.width = editor.ui._actualFrameWidth + 'px'; editor.setHeight(scalelayer.offsetHeight - bottombar.offsetHeight - toolbarBox.offsetHeight - 2); } if (scalelayer) { scalelayer.style.display = "none"; } clearSelection(); domUtils.un(doc, "mousemove", move); domUtils.un(editorDocument, "mouseup", up); domUtils.un(doc, "mouseup", up); } function clearSelection() { if (browser.ie) doc.selection.clear(); else window.getSelection().removeAllRanges(); } this.enableScale = function () { //trace:2868 if (editor.queryCommandState("source") == 1) return; scale.style.display = ""; this.scaleEnabled = true; domUtils.on(scale, "mousedown", down); }; this.disableScale = function () { scale.style.display = "none"; this.scaleEnabled = false; domUtils.un(scale, "mousedown", down); }; }, isFullScreen:function () { return this._fullscreen; }, postRender:function () { UIBase.prototype.postRender.call(this); for (var i = 0; i < this.toolbars.length; i++) { this.toolbars[i].postRender(); } var me = this; var timerId, domUtils = baidu.editor.dom.domUtils, updateFullScreenTime = function () { clearTimeout(timerId); timerId = setTimeout(function () { me._updateFullScreen(); }); }; domUtils.on(window, 'resize', updateFullScreenTime); me.addListener('destroy', function () { domUtils.un(window, 'resize', updateFullScreenTime); clearTimeout(timerId); }) }, showToolbarMsg:function (msg, flag) { this.getDom('toolbarmsg_label').innerHTML = msg; this.getDom('toolbarmsg').style.display = ''; // if (!flag) { var w = this.getDom('upload_dialog'); w.style.display = 'none'; } }, hideToolbarMsg:function () { this.getDom('toolbarmsg').style.display = 'none'; }, mapUrl:function (url) { return url ? url.replace('~/', this.editor.options.UEDITOR_HOME_URL || '') : '' }, triggerLayout:function () { var dom = this.getDom(); if (dom.style.zoom == '1') { dom.style.zoom = '100%'; } else { dom.style.zoom = '1'; } } }; utils.inherits(EditorUI, baidu.editor.ui.UIBase); var instances = {}; UE.ui.Editor = function (options) { var editor = new UE.Editor(options); editor.options.editor = editor; utils.loadFile(document, { href:editor.options.themePath + editor.options.theme + "/css/ueditor.css", tag:"link", type:"text/css", rel:"stylesheet" }); var oldRender = editor.render; editor.render = function (holder) { if (holder.constructor === String) { editor.key = holder; instances[holder] = editor; } utils.domReady(function () { editor.langIsReady ? renderUI() : editor.addListener("langReady", renderUI); function renderUI() { editor.setOpt({ labelMap:editor.options.labelMap || editor.getLang('labelMap') }); new EditorUI(editor.options); if (holder) { if (holder.constructor === String) { holder = document.getElementById(holder); } holder && holder.getAttribute('name') && ( editor.options.textarea = holder.getAttribute('name')); if (holder && /script|textarea/ig.test(holder.tagName)) { var newDiv = document.createElement('div'); holder.parentNode.insertBefore(newDiv, holder); var cont = holder.value || holder.innerHTML; editor.options.initialContent = /^[\t\r\n ]*$/.test(cont) ? editor.options.initialContent : cont.replace(/>[\n\r\t]+([ ]{4})+/g, '>') .replace(/[\n\r\t]+([ ]{4})+</g, '<') .replace(/>[\n\r\t]+</g, '><'); holder.className && (newDiv.className = holder.className); holder.style.cssText && (newDiv.style.cssText = holder.style.cssText); if (/textarea/i.test(holder.tagName)) { editor.textarea = holder; editor.textarea.style.display = 'none'; } else { holder.parentNode.removeChild(holder); holder.id && (newDiv.id = holder.id); } holder = newDiv; holder.innerHTML = ''; } } domUtils.addClass(holder, "edui-" + editor.options.theme); editor.ui.render(holder); var opt = editor.options; //给实例添加一个编辑器的容器引用 editor.container = editor.ui.getDom(); var parents = domUtils.findParents(holder,true); var displays = []; for(var i = 0 ,ci;ci=parents[i];i++){ displays[i] = ci.style.display; ci.style.display = 'block' } if (opt.initialFrameWidth) { opt.minFrameWidth = opt.initialFrameWidth; } else { opt.minFrameWidth = opt.initialFrameWidth = holder.offsetWidth; } if (opt.initialFrameHeight) { opt.minFrameHeight = opt.initialFrameHeight; } else { opt.initialFrameHeight = opt.minFrameHeight = holder.offsetHeight; } for(var i = 0 ,ci;ci=parents[i];i++){ ci.style.display = displays[i] } //编辑器最外容器设置了高度,会导致,编辑器不占位 //todo 先去掉,没有找到原因 if(holder.style.height){ holder.style.height = '' } editor.container.style.width = opt.initialFrameWidth + (/%$/.test(opt.initialFrameWidth) ? '' : 'px'); editor.container.style.zIndex = opt.zIndex; oldRender.call(editor, editor.ui.getDom('iframeholder')); } }) }; return editor; }; /** * @file * @name UE * @short UE * @desc UEditor的顶部命名空间 */ /** * @name getEditor * @since 1.2.4+ * @grammar UE.getEditor(id,[opt]) => Editor实例 * @desc 提供一个全局的方法得到编辑器实例 * * * ''id'' 放置编辑器的容器id, 如果容器下的编辑器已经存在,就直接返回 * * ''opt'' 编辑器的可选参数 * @example * UE.getEditor('containerId',{onready:function(){//创建一个编辑器实例 * this.setContent('hello') * }}); * UE.getEditor('containerId'); //返回刚创建的实例 * */ UE.getEditor = function (id, opt) { var editor = instances[id]; if (!editor) { editor = instances[id] = new UE.ui.Editor(opt); editor.render(id); } return editor; }; UE.delEditor = function (id) { var editor; if (editor = instances[id]) { editor.key && editor.destroy(); delete instances[id] } } })();///import core ///import uicore ///commands 表情 (function(){ var utils = baidu.editor.utils, Popup = baidu.editor.ui.Popup, SplitButton = baidu.editor.ui.SplitButton, MultiMenuPop = baidu.editor.ui.MultiMenuPop = function(options){ this.initOptions(options); this.initMultiMenu(); }; MultiMenuPop.prototype = { initMultiMenu: function (){ var me = this; this.popup = new Popup({ content: '', editor : me.editor, iframe_rendered: false, onshow: function (){ if (!this.iframe_rendered) { this.iframe_rendered = true; this.getDom('content').innerHTML = '<iframe id="'+me.id+'_iframe" src="'+ me.iframeUrl +'" frameborder="0"></iframe>'; me.editor.container.style.zIndex && (this.getDom().style.zIndex = me.editor.container.style.zIndex * 1 + 1); } } // canSideUp:false, // canSideLeft:false }); this.onbuttonclick = function(){ this.showPopup(); }; this.initSplitButton(); } }; utils.inherits(MultiMenuPop, SplitButton); })(); (function () { var UI = baidu.editor.ui, UIBase = UI.UIBase, uiUtils = UI.uiUtils, utils = baidu.editor.utils, domUtils = baidu.editor.dom.domUtils; var allMenus = [],//存储所有快捷菜单 timeID, isSubMenuShow = false;//是否有子pop显示 var ShortCutMenu = UI.ShortCutMenu = function (options) { this.initOptions (options); this.initShortCutMenu (); }; ShortCutMenu.postHide = hideAllMenu; ShortCutMenu.prototype = { isHidden : true , SPACE : 5 , initShortCutMenu : function () { this.items = this.items || []; this.initUIBase (); this.initItems (); this.initEvent (); allMenus.push (this); } , initEvent : function () { var me = this, doc = me.editor.document; domUtils.on (doc , "mousemove" , function (e) { if (me.isHidden === false) { //有pop显示就不隐藏快捷菜单 if (me.getSubMenuMark () || me.eventType == "contextmenu") return; var flag = true, el = me.getDom (), wt = el.offsetWidth, ht = el.offsetHeight, distanceX = wt / 2 + me.SPACE,//距离中心X标准 distanceY = ht / 2,//距离中心Y标准 x = Math.abs (e.screenX - me.left),//离中心距离横坐标 y = Math.abs (e.screenY - me.top);//离中心距离纵坐标 clearTimeout (timeID); timeID = setTimeout (function () { if (y > 0 && y < distanceY) { me.setOpacity (el , "1"); } else if (y > distanceY && y < distanceY + 70) { me.setOpacity (el , "0.5"); flag = false; } else if (y > distanceY + 70 && y < distanceY + 140) { me.hide (); } if (flag && x > 0 && x < distanceX) { me.setOpacity (el , "1") } else if (x > distanceX && x < distanceX + 70) { me.setOpacity (el , "0.5") } else if (x > distanceX + 70 && x < distanceX + 140) { me.hide (); } }); } }); //ie\ff下 mouseout不准 if (browser.chrome) { domUtils.on (doc , "mouseout" , function (e) { var relatedTgt = e.relatedTarget || e.toElement; if (relatedTgt == null || relatedTgt.tagName == "HTML") { me.hide (); } }); } me.editor.addListener ("afterhidepop" , function () { if (!me.isHidden) { isSubMenuShow = true; } }); } , initItems : function () { if (utils.isArray (this.items)) { for (var i = 0, len = this.items.length ; i < len ; i++) { var item = this.items[i].toLowerCase (); if (UI[item]) { this.items[i] = new UI[item] (this.editor); this.items[i].className += " edui-shortcutsubmenu "; } } } } , setOpacity : function (el , value) { if (browser.ie && browser.version < 9) { el.style.filter = "alpha(opacity = " + parseFloat (value) * 100 + ");" } else { el.style.opacity = value; } } , getSubMenuMark : function () { isSubMenuShow = false; var layerEle = uiUtils.getFixedLayer (); var list = domUtils.getElementsByTagName (layerEle , "div" , function (node) { return domUtils.hasClass (node , "edui-shortcutsubmenu edui-popup") }); for (var i = 0, node ; node = list[i++] ;) { if (node.style.display != "none") { isSubMenuShow = true; } } return isSubMenuShow; } , show : function (e , hasContextmenu) { var me = this, offset = {}, el = this.getDom (), fixedlayer = uiUtils.getFixedLayer (); function setPos (offset) { if (offset.left < 0) { offset.left = 0; } if (offset.top < 0) { offset.top = 0; } el.style.cssText = "position:absolute;left:" + offset.left + "px;top:" + offset.top + "px;"; } function setPosByCxtMenu (menu) { if (!menu.tagName) { menu = menu.getDom (); } offset.left = parseInt (menu.style.left); offset.top = parseInt (menu.style.top); offset.top -= el.offsetHeight + 15; setPos (offset); } me.eventType = e.type; el.style.cssText = "display:block;left:-9999px"; if (e.type == "contextmenu" && hasContextmenu) { var menu = domUtils.getElementsByTagName (fixedlayer , "div" , "edui-contextmenu")[0]; if (menu) { setPosByCxtMenu (menu) } else { me.editor.addListener ("aftershowcontextmenu" , function (type , menu) { setPosByCxtMenu (menu); }); } } else { offset = uiUtils.getViewportOffsetByEvent (e); offset.top -= el.offsetHeight + me.SPACE; offset.left += me.SPACE + 20; setPos (offset); me.setOpacity (el , 0.2); } me.isHidden = false; me.left = e.screenX + el.offsetWidth / 2 - me.SPACE; me.top = e.screenY - (el.offsetHeight / 2) - me.SPACE; if (me.editor) { el.style.zIndex = me.editor.container.style.zIndex * 1 + 10; fixedlayer.style.zIndex = el.style.zIndex - 1; } } , hide : function () { if (this.getDom ()) { this.getDom ().style.display = "none"; } this.isHidden = true; } , postRender : function () { if (utils.isArray (this.items)) { for (var i = 0, item ; item = this.items[i++] ;) { item.postRender (); } } } , getHtmlTpl : function () { var buff; if (utils.isArray (this.items)) { buff = []; for (var i = 0 ; i < this.items.length ; i++) { buff[i] = this.items[i].renderHtml (); } buff = buff.join (""); } else { buff = this.items; } return '<div id="##" class="%% edui-toolbar" data-src="shortcutmenu" onmousedown="return false;" onselectstart="return false;" >' + buff + '</div>'; } }; utils.inherits (ShortCutMenu , UIBase); function hideAllMenu (e) { var tgt = e.target || e.srcElement, cur = domUtils.findParent (tgt , function (node) { return domUtils.hasClass (node , "edui-shortcutmenu") || domUtils.hasClass (node , "edui-popup"); } , true); if (!cur) { for (var i = 0, menu ; menu = allMenus[i++] ;) { menu.hide () } } } domUtils.on (document , 'mousedown' , function (e) { hideAllMenu (e); }); domUtils.on (window , 'scroll' , function (e) { hideAllMenu (e); }); }) (); (function (){ var utils = baidu.editor.utils, UIBase = baidu.editor.ui.UIBase, Breakline = baidu.editor.ui.Breakline = function (options){ this.initOptions(options); this.initSeparator(); }; Breakline.prototype = { uiName: 'Breakline', initSeparator: function (){ this.initUIBase(); }, getHtmlTpl: function (){ return '<br/>'; } }; utils.inherits(Breakline, UIBase); })(); })();
JavaScript
/** * Created with JetBrains PhpStorm. * User: taoqili * Date: 12-6-12 * Time: 下午5:02 * To change this template use File | Settings | File Templates. */ UE.I18N['zh-cn'] = { 'labelMap':{ 'anchor':'锚点', 'undo':'撤销', 'redo':'重做', 'bold':'加粗', 'indent':'首行缩进', 'snapscreen':'截图', 'italic':'斜体', 'underline':'下划线', 'strikethrough':'删除线', 'subscript':'下标','fontborder':'字符边框', 'superscript':'上标', 'formatmatch':'格式刷', 'source':'源代码', 'blockquote':'引用', 'pasteplain':'纯文本粘贴模式', 'selectall':'全选', 'print':'打印', 'preview':'预览', 'horizontal':'分隔线', 'removeformat':'清除格式', 'time':'时间', 'date':'日期', 'unlink':'取消链接', 'insertrow':'前插入行', 'insertcol':'前插入列', 'mergeright':'右合并单元格', 'mergedown':'下合并单元格', 'deleterow':'删除行', 'deletecol':'删除列', 'splittorows':'拆分成行', 'splittocols':'拆分成列', 'splittocells':'完全拆分单元格', 'mergecells':'合并多个单元格', 'deletetable':'删除表格', 'cleardoc':'清空文档','insertparagraphbeforetable':"表格前插入行",'insertcode':'代码语言','fontfamily':'字体', 'fontsize':'字号', 'paragraph':'段落格式', 'insertimage':'图片', 'edittable':'表格属性','edittd':'单元格属性', 'link':'超链接','emotion':'表情', 'spechars':'特殊字符', 'searchreplace':'查询替换', 'map':'Baidu地图', 'gmap':'Google地图', 'insertvideo':'视频', 'help':'帮助', 'justifyleft':'居左对齐', 'justifyright':'居右对齐', 'justifycenter':'居中对齐', 'justifyjustify':'两端对齐', 'forecolor':'字体颜色', 'backcolor':'背景色', 'insertorderedlist':'有序列表', 'insertunorderedlist':'无序列表', 'fullscreen':'全屏', 'directionalityltr':'从左向右输入', 'directionalityrtl':'从右向左输入', 'rowspacingtop':'段前距', 'rowspacingbottom':'段后距', 'highlightcode':'插入代码', 'pagebreak':'分页', 'insertframe':'插入Iframe', 'imagenone':'默认', 'imageleft':'左浮动', 'imageright':'右浮动', 'attachment':'附件', 'imagecenter':'居中', 'wordimage':'图片转存', 'lineheight':'行间距','edittip' :'编辑提示','customstyle':'自定义标题', 'autotypeset':'自动排版', 'webapp':'百度应用', 'touppercase':'字母大写', 'tolowercase':'字母小写','background':'背景','template':'模板','scrawl':'涂鸦','music':'音乐',inserttable:'插入表格' }, 'insertorderedlist':{ 'num':'1,2,3...', 'num1':'1),2),3)...', 'num2':'(1),(2),(3)...', 'cn':'一,二,三....', 'cn1':'一),二),三)....', 'cn2':'(一),(二),(三)....', 'decimal':'1,2,3...', 'lower-alpha':'a,b,c...', 'lower-roman':'i,ii,iii...', 'upper-alpha':'A,B,C...', 'upper-roman':'I,II,III...' }, 'insertunorderedlist':{ 'circle':'○ 大圆圈', 'disc':'● 小黑点', 'square':'■ 小方块 ', 'dash' :'— 破折号', 'dot':' 。 小圆圈' }, 'paragraph':{'p':'段落', 'h1':'标题 1', 'h2':'标题 2', 'h3':'标题 3', 'h4':'标题 4', 'h5':'标题 5', 'h6':'标题 6'}, 'fontfamily':{ 'songti':'宋体', 'kaiti':'楷体', 'heiti':'黑体', 'lishu':'隶书', 'yahei':'微软雅黑', 'andaleMono':'andale mono', 'arial': 'arial', 'arialBlack':'arial black', 'comicSansMs':'comic sans ms', 'impact':'impact', 'timesNewRoman':'times new roman' }, 'insertcode':{ 'as3':'ActionScript3', 'bash':'Bash/Shell', 'cpp':'C/C++', 'css':'Css', 'cf':'CodeFunction', 'c#':'C#', 'delphi':'Delphi', 'diff':'Diff', 'erlang':'Erlang', 'groovy':'Groovy', 'html':'Html', 'java':'Java', 'jfx':'JavaFx', 'js':'Javascript', 'pl':'Perl', 'php':'Php', 'plain':'Plain Text', 'ps':'PowerShell', 'python':'Python', 'ruby':'Ruby', 'scala':'Scala', 'sql':'Sql', 'vb':'Vb', 'xml':'Xml' }, 'customstyle':{ 'tc':'标题居中', 'tl':'标题居左', 'im':'强调', 'hi':'明显强调' }, elementPathTip:"元素路径", 'wordCountTip':"字数统计", 'wordCountMsg':'当前已输入{#count}个字符, 您还可以输入{#leave}个字符。 ', 'wordOverFlowMsg':'<span style="color:red;">字数超出最大允许值,服务器可能拒绝保存!</span>', 'ok':"确认", 'cancel':"取消", 'closeDialog':"关闭对话框", 'tableDrag':"表格拖动必须引入uiUtils.js文件!", 'autofloatMsg':"工具栏浮动依赖编辑器UI,您首先需要引入UI文件!", 'snapScreen_plugin':{ 'browserMsg':"仅支持IE浏览器!", 'callBackErrorMsg':"服务器返回数据有误,请检查配置项之后重试。", 'uploadErrorMsg':"截图上传失败,请检查服务器端环境! " }, 'confirmClear':"确定清空当前文档么?", 'contextMenu':{ 'delete':"删除", 'selectall':"全选", 'deletecode':"删除代码", 'cleardoc':"清空文档", 'confirmclear':"确定清空当前文档么?", 'unlink':"删除超链接", 'paragraph':"段落格式", 'edittable':"表格属性", 'aligntd':"单元格对齐方式", 'aligntable':'表格对齐方式', 'tableleft':'左浮动', 'tablecenter':'居中显示', 'tableright':'右浮动', 'edittd':"单元格属性", 'justifyleft':'左对齐', 'justifyright':'右对齐', 'justifycenter':'居中对齐', 'justifyjustify':'两端对齐', 'table':"表格", 'inserttable':'插入表格', 'deletetable':"删除表格", 'insertparagraphbefore':"前插入段落", 'insertparagraphafter':'后插入段落', 'deleterow':"删除当前行", 'deletecol':"删除当前列", 'insertrow':"前插入行", 'insertcol':"左插入列", 'insertrownext':'后插入行', 'insertcolnext':'右插入列', 'insertcaption':'插入表格名称', 'deletecaption':'删除表格名称', 'inserttitle':'插入表格标题行', 'deletetitle':'删除表格标题行', 'averageDiseRow':'平均分布各行', 'averageDisCol':'平均分布各列', 'mergeright':"向右合并", 'mergeleft':"向左合并", 'mergedown':"向下合并", 'mergecells':"合并单元格", 'splittocells':"完全拆分单元格", 'splittocols':"拆分成列", 'splittorows':"拆分成行", 'tablesort':'表格排序', 'reversecurrent':'逆序当前', 'orderbyasc':'按ASCII字符升序', 'reversebyasc':'按ASCII字符降序', 'orderbynum':'按数值大小升序', 'reversebynum':'按数值大小降序', 'borderbk':'边框底纹', 'setcolor':'表格隔行变色', 'unsetcolor':'取消表格隔行变色', 'setbackground':'选区背景隔行', 'unsetbackground':'取消选区背景', 'redandblue':'红蓝相间', 'threecolorgradient':'三色渐变', 'copy':"复制(Ctrl + c)", 'copymsg':"请使用 'Ctrl + c'执行复制操作", 'paste':"粘贴(Ctrl + v)", 'pastemsg':"请使用 'Ctrl + v'执行复制操作", 'highlightcode':'插入代码' }, 'anthorMsg':"链接", 'clearColor':'清空颜色', 'standardColor':'标准颜色', 'themeColor':'主题颜色', 'property':'属性', 'default':'默认', 'modify':'修改', 'justifyleft':'左对齐', 'justifyright':'右对齐', 'justifycenter':'居中', 'justify':'默认', 'clear':'清除', 'anchorMsg':'锚点', 'delete':'删除', 'clickToUpload':"点击上传", 'unset':'尚未设置语言文件', 't_row':'行', 't_col':'列', 'more':'更多', 'pasteOpt':'粘贴选项', 'pasteSourceFormat':"保留源格式", 'tagFormat':'只保留标签', 'pasteTextFormat':'只保留文本', 'autoTypeSet':{ mergeLine:"合并空行", delLine:"清除空行", removeFormat:"清除格式", indent:"首行缩进", alignment:"对齐方式", imageFloat:"图片浮动", removeFontsize:"清除字号", removeFontFamily:"清除字体", removeHtml:"清除冗余HTML代码", pasteFilter:"粘贴过滤", run:"执行" }, 'background':{ 'static':{ 'lang_background_normal':'背景设置', 'lang_background_local':'本地图片', 'lang_background_set':'选项', 'lang_background_none':'无', 'lang_background_color':'颜色设置', 'lang_background_netimg':'网络图片', 'lang_background_align':'对齐方式', 'lang_background_position':'精确定位', 'repeatType':{options:["居中", "横向重复", "纵向重复", "平铺","自定义"]} }, 'noUploadImage':"当前未上传过任何图片!", 'toggleSelect':"单击可切换选中状态\n原图尺寸: " }, //===============dialog i18N======================= 'insertimage':{ 'static':{ lang_tab_remote:"远程图片", //节点 lang_tab_local:"本地上传", lang_tab_imgManager:"在线管理", lang_tab_imgSearch:"图片搜索", lang_input_url:"地 址:", lang_input_width:"宽 度:", lang_input_height:"高 度:", lang_input_border:"边 框:", lang_input_vhspace:"边 距:", lang_input_title:"描 述:", lang_input_remoteAlign:'对 齐:', lang_imgLoading:" 图片加载中……", 'lock':{title:"锁定宽高比例"}, //属性 'imgType':{title:"图片类型", options:["新闻", "壁纸", "表情", "头像"]}, //select的option 'imgSearchTxt':{value:"请输入搜索关键词"}, 'imgSearchBtn':{value:"百度一下"}, 'imgSearchReset':{value:"清空搜索"}, 'upload':{style:'background: url(upload.png);'}, 'duiqi':{style:'background: url(imglabel.png) -12px 2px no-repeat;'}, 'lang_savePath':'选择保存目录' }, 'netError':"网络链接错误,请检查配置后重试!", 'noUploadImage':"当前未上传过任何图片!", 'imageLoading':"图片加载中,请稍后……", 'tryAgain':" :( ,抱歉,没有找到图片!请重试一次!", 'toggleSelect':"单击可切换选中状态\n原图尺寸: ", 'searchInitInfo':"请输入搜索关键词", 'numError':"请输入正确的长度或者宽度值!例如:123,400", 'fileType':"图片", 'imageUrlError':"不允许的图片格式或者图片域!", 'imageLoadError':"图片加载失败!请检查链接地址或网络状态!", 'flashError':'Flash插件初始化失败,请更新您的FlashPlayer版本之后重试!', 'floatDefault':"默认", 'floatLeft':"左浮动", 'floatRight':"右浮动", 'floatCenter':"居中", 'flashI18n':{} //留空默认中文 }, 'webapp':{ tip1:"本功能由百度APP提供,如看到此页面,请各位站长首先申请百度APPKey!", tip2:"申请完成之后请至ueditor.config.js中配置获得的appkey! ", applyFor:"点此申请", anthorApi:"百度API" }, template:{ 'static':{ 'lang_template_bkcolor':'背景颜色', 'lang_template_clear' : '保留原有内容', 'lang_template_select' : '选择模板' }, 'blank':"空白文档", 'blog':"博客文章", 'resume':"个人简历", 'richText':"图文混排", 'sciPapers':"科技论文" }, 'scrawl':{ 'static':{ 'lang_input_previousStep':"上一步", 'lang_input_nextsStep':"下一步", 'lang_input_clear':'清空', 'lang_input_addPic':'添加背景', 'lang_input_ScalePic':'缩放背景', 'lang_input_removePic':'删除背景', 'J_imgTxt':{title:'添加背景图片'} }, 'noScarwl':"尚未作画,白纸一张~", 'scrawlUpLoading':"涂鸦上传中,别急哦~", 'continueBtn':"继续", 'imageError':"糟糕,图片读取失败了!", 'backgroundUploading':'背景图片上传中,别急哦~' }, 'music':{ 'static':{ 'lang_input_tips':"输入歌手/歌曲/专辑,搜索您感兴趣的音乐!", 'J_searchBtn':{value:'搜索歌曲'} }, 'emptyTxt':'未搜索到相关音乐结果,请换一个关键词试试。', 'chapter':'歌曲', 'singer':'歌手', 'special':'专辑', 'listenTest':'试听' }, 'anchor':{ 'static':{ 'lang_input_anchorName':'锚点名字:' } }, 'attachment':{ 'static':{ 'lang_input_fileStatus':' 当前未上传文件', 'startUpload':{style:"background:url(upload.png) no-repeat;"} }, 'browseFiles':'文件浏览…', 'uploadSuccess':'上传成功!', 'delSuccessFile':'从成功队列中移除', 'delFailSaveFile':'移除保存失败文件', 'statusPrompt':' 个文件已上传! ', 'flashVersionError':'当前Flash版本过低,请更新FlashPlayer后重试!', 'flashLoadingError':'Flash加载失败!请检查路径或网络状态', 'fileUploadReady':'等待上传……', 'delUploadQueue':'从上传队列中移除', 'limitPrompt1':'单次不能选择超过', 'limitPrompt2':'个文件!请重新选择!', 'delFailFile':'移除失败文件', 'fileSizeLimit':'文件大小超出限制!', 'emptyFile':'空文件无法上传!', 'fileTypeError':'文件类型错误!', 'unknownError':'未知错误!', 'fileUploading':'上传中,请等待……', 'cancelUpload':'取消上传', 'netError':'网络错误', 'failUpload':'上传失败!', 'serverIOError':'服务器IO错误!', 'noAuthority':'无权限!', 'fileNumLimit':'上传个数限制', 'failCheck':'验证失败,本次上传被跳过!', 'fileCanceling':'取消中,请等待……', 'stopUploading':'上传已停止……' }, 'highlightcode':{ 'static':{ 'lang_input_selectLang':'选择语言' }, importCode:'请输入代码' }, 'emotion':{ 'static':{ 'lang_input_choice':'精选', 'lang_input_Tuzki':'兔斯基', 'lang_input_BOBO':'BOBO', 'lang_input_lvdouwa':'绿豆蛙', 'lang_input_babyCat':'baby猫', 'lang_input_bubble':'泡泡', 'lang_input_youa':'有啊' } }, 'gmap':{ 'static':{ 'lang_input_address':'地址', 'lang_input_search':'搜索', 'address':{value:"北京"} }, searchError:'无法定位到该地址!' }, 'help':{ 'static':{ 'lang_input_about':'关于UEditor', 'lang_input_shortcuts':'快捷键', 'lang_input_version':'版本:1.2.6', 'lang_input_introduction':'UEditor是由百度web前端研发部开发的所见即所得富文本web编辑器,具有轻量,可定制,注重用户体验等特点。开源基于BSD协议,允许自由使用和修改代码。', 'lang_Txt_shortcuts':'快捷键', 'lang_Txt_func':'功能', 'lang_Txt_bold':'给选中字设置为加粗', 'lang_Txt_copy':'复制选中内容', 'lang_Txt_cut':'剪切选中内容', 'lang_Txt_Paste':'粘贴', 'lang_Txt_undo':'重新执行上次操作', 'lang_Txt_redo':'撤销上一次操作', 'lang_Txt_italic':'给选中字设置为斜体', 'lang_Txt_underline':'给选中字加下划线', 'lang_Txt_selectAll':'全部选中', 'lang_Txt_visualEnter':'软回车', 'lang_Txt_fullscreen':'全屏' } }, 'insertframe':{ 'static':{ 'lang_input_address':'地址:', 'lang_input_width':'宽度:', 'lang_input_height':'高度:', 'lang_input_isScroll':'允许滚动条:', 'lang_input_frameborder':'显示框架边框:', 'lang_input_alignMode':'对齐方式:', 'align':{title:"对齐方式", options:["默认", "左对齐", "右对齐", "居中"]} }, 'enterAddress':'请输入地址!' }, 'link':{ 'static':{ 'lang_input_text':'文本内容:', 'lang_input_url':'链接地址:', 'lang_input_title':'标题:', 'lang_input_target':'是否在新窗口打开:' }, 'validLink':'只支持选中一个链接时生效', 'httpPrompt':'您输入的超链接中不包含http等协议名称,默认将为您添加http://前缀' }, 'map':{ 'static':{ lang_city:"城市", lang_address:"地址", city:{value:"北京"}, lang_search:"搜索" }, cityMsg:"请选择城市", errorMsg:"抱歉,找不到该位置!" }, 'searchreplace':{ 'static':{ lang_tab_search:"查找", lang_tab_replace:"替换", lang_search1:"查找", lang_search2:"查找", lang_replace:"替换", lang_searchReg:'支持正则表达式,添加前后斜杠标示为正则表达式,例如“/表达式/”', lang_searchReg1:'支持正则表达式,添加前后斜杠标示为正则表达式,例如“/表达式/”', lang_case_sensitive1:"区分大小写", lang_case_sensitive2:"区分大小写", nextFindBtn:{value:"下一个"}, preFindBtn:{value:"上一个"}, nextReplaceBtn:{value:"下一个"}, preReplaceBtn:{value:"上一个"}, repalceBtn:{value:"替换"}, repalceAllBtn:{value:"全部替换"} }, getEnd:"已经搜索到文章末尾!", getStart:"已经搜索到文章头部", countMsg:"总共替换了{#count}处!" }, 'snapscreen':{ 'static':{ lang_showMsg:"截图功能需要首先安装UEditor截图插件! ", lang_download:"点此下载", lang_step1:"第一步,下载UEditor截图插件并运行安装。", lang_step2:"第二不,插件安装完成后即可使用,如不生效,请重启浏览器后再试!" } }, 'insertvideo':{ 'static':{ lang_tab_insertV:"插入视频", // lang_tab_searchV:"搜索视频", lang_video_url:"视频网址", lang_video_size:"视频尺寸", lang_videoW:"宽度", lang_videoH:"高度", lang_alignment:"对齐方式", videoSearchTxt:{value:"请输入搜索关键字!"}, videoType:{options:["全部", "热门", "娱乐", "搞笑", "体育", "科技", "综艺"]}, videoSearchBtn:{value:"百度一下"}, videoSearchReset:{value:"清空结果"} }, numError:"请输入正确的数值,如123,400", floatLeft:"左浮动", floatRight:"右浮动", "default":"默认", block:"独占一行", urlError:"输入的视频地址有误,请检查后再试!", loading:" &nbsp;视频加载中,请等待……", clickToSelect:"点击选中", goToSource:'访问源视频', noVideo:" &nbsp; &nbsp;抱歉,找不到对应的视频,请重试!" }, 'spechars':{ 'static':{}, tsfh:"特殊字符", lmsz:"罗马字符", szfh:"数学字符", rwfh:"日文字符", xlzm:"希腊字母", ewzm:"俄文字符", pyzm:"拼音字母", zyzf:"注音及其他" }, 'edittable':{ 'static':{ 'lang_tableStyle':'表格样式', 'lang_insertCaption':'添加表格标题行', 'lang_insertTitle':'添加表格名称行', 'lang_orderbycontent':"使表格内容可排序", 'lang_tableSize':'自动调整表格尺寸', 'lang_autoSizeContent':'按表格文字自适应', 'lang_autoSizePage':'按页面宽度自适应', 'lang_example':'示例', 'lang_borderStyle':'表格边框', 'lang_color':'颜色:' }, captionName:'表格名称', titleName:'标题', cellsName:'内容' }, 'edittip':{ 'static':{ lang_delRow:'删除整行', lang_delCol:'删除整列' } }, 'edittd':{ 'static':{ lang_tdBkColor:'背景颜色:' } }, 'formula':{ 'static':{ } }, 'wordimage':{ 'static':{ lang_resave:"转存步骤", uploadBtn:{src:"upload.png",alt:"上传"}, clipboard:{style:"background: url(copy.png) -153px -1px no-repeat;"}, lang_step:"1、点击顶部复制按钮,将地址复制到剪贴板;2、点击添加照片按钮,在弹出的对话框中使用Ctrl+V粘贴地址;3、点击打开后选择图片上传流程。" }, 'fileType':"图片", 'flashError':"FLASH初始化失败,请检查FLASH插件是否正确安装!", 'netError':"网络连接错误,请重试!", 'copySuccess':"图片地址已经复制!", 'flashI18n':{} //留空默认中文 } };
JavaScript
/** * ueditor完整配置项 * 可以在这里配置整个编辑器的特性 */ /**************************提示******************************** * 所有被注释的配置项均为UEditor默认值。 * 修改默认配置请首先确保已经完全明确该参数的真实用途。 * 主要有两种修改方案,一种是取消此处注释,然后修改成对应参数;另一种是在实例化编辑器时传入对应参数。 * 当升级编辑器时,可直接使用旧版配置文件替换新版配置文件,不用担心旧版配置文件中因缺少新功能所需的参数而导致脚本报错。 **************************提示********************************/ window.UEDITOR_HOME_URL = "/ueditor/"; (function () { /** * 编辑器资源文件根路径。它所表示的含义是:以编辑器实例化页面为当前路径,指向编辑器资源文件(即dialog等文件夹)的路径。 * 鉴于很多同学在使用编辑器的时候出现的种种路径问题,此处强烈建议大家使用"相对于网站根目录的相对路径"进行配置。 * "相对于网站根目录的相对路径"也就是以斜杠开头的形如"/myProject/ueditor/"这样的路径。 * 如果站点中有多个不在同一层级的页面需要实例化编辑器,且引用了同一UEditor的时候,此处的URL可能不适用于每个页面的编辑器。 * 因此,UEditor提供了针对不同页面的编辑器可单独配置的根路径,具体来说,在需要实例化编辑器的页面最顶部写上如下代码即可。当然,需要令此处的URL等于对应的配置。 * window.UEDITOR_HOME_URL = "/xxxx/xxxx/"; */ var URL = window.UEDITOR_HOME_URL; /** * 配置项主体。注意,此处所有涉及到路径的配置别遗漏URL变量。 */ window.UEDITOR_CONFIG = { //为编辑器实例添加一个路径,这个不能被注释 UEDITOR_HOME_URL : URL //图片上传配置区 ,imageUrl:URL+"php/imageUp.php" //图片上传提交地址 ,imagePath:"" //图片修正地址,引用了fixedImagePath,如有特殊需求,可自行配置 //,imageFieldName:"upfile" //图片数据的key,若此处修改,需要在后台对应文件修改对应参数 ,compressSide:1 //等比压缩的基准,确定maxImageSideLength参数的参照对象。0为按照最长边,1为按照宽度,2为按照高度 ,maxImageSideLength:550 //上传图片最大允许的边长,超过会自动等比缩放,不缩放就设置一个比较大的值,更多设置在image.html中 //涂鸦图片配置区 ,scrawlUrl:URL+"php/scrawlUp.php" //涂鸦上传地址 ,scrawlPath:URL+"php/" //图片修正地址,同imagePath //附件上传配置区 ,fileUrl:URL+"php/fileUp.php" //附件上传提交地址 ,filePath:"" //附件修正地址,同imagePath //,fileFieldName:"upfile" //附件提交的表单名,若此处修改,需要在后台对应文件修改对应参数 //远程抓取配置区 //,catchRemoteImageEnable:true //是否开启远程图片抓取,默认开启 ,catcherUrl:URL +"php/getRemoteImage.php" //处理远程图片抓取的地址 ,catcherPath:URL + "php/" //图片修正地址,同imagePath //,catchFieldName:"upfile" //提交到后台远程图片uri合集,若此处修改,需要在后台对应文件修改对应参数 //,separater:'ue_separate_ue' //提交至后台的远程图片地址字符串分隔符 //,localDomain:[] //本地顶级域名,当开启远程图片抓取时,除此之外的所有其它域名下的图片都将被抓取到本地,默认不抓取127.0.0.1和localhost //图片在线管理配置区 ,imageManagerUrl:URL + "php/imageManager.php" //图片在线管理的处理地址 ,imageManagerPath:"" //图片修正地址,同imagePath //屏幕截图配置区 ,snapscreenHost: location.hostname //屏幕截图的server端文件所在的网站地址或者ip,请不要加http:// ,snapscreenServerUrl: URL +"php/imageUp.php" //屏幕截图的server端保存程序,UEditor的范例代码为“URL +"server/upload/php/snapImgUp.php"” ,snapscreenPath: URL + "php/" ,snapscreenServerPort: location.port //屏幕截图的server端端口 //,snapscreenImgAlign: '' //截图的图片默认的排版方式 //word转存配置区 ,wordImageUrl:URL + "php/imageUp.php" //word转存提交地址 ,wordImagePath:URL + "php/" // //,wordImageFieldName:"upfile" //word转存表单名若此处修改,需要在后台对应文件修改对应参数 //获取视频数据的地址 ,getMovieUrl:URL+"php/getMovie.php" //视频数据获取地址 //工具栏上的所有的功能按钮和下拉框,可以在new编辑器的实例时选择自己需要的从新定义 , toolbars: [["source","bold","italic","underline","strikethrough","forecolor","backcolor","fontfamily","fontsize","insertunorderedlist","insertorderedlist","link","unlink","insertimage","music","insertvideo","inserttable","attachment","emotion","justifyleft","justifycenter","justifyright","justifyjustify","map","preview","insertcode","removeformat"]] //当鼠标放在工具栏上时显示的tooltip提示,留空支持自动多语言配置,否则以配置值为准 // ,labelMap:{ // 'anchor':'', 'undo':'' // } //webAppKey //百度应用的APIkey,每个站长必须首先去百度官网注册一个key后方能正常使用app功能 //,webAppKey:"" //语言配置项,默认是zh-cn。有需要的话也可以使用如下这样的方式来自动多语言切换,当然,前提条件是lang文件夹下存在对应的语言文件: //lang值也可以通过自动获取 (navigator.language||navigator.browserLanguage ||navigator.userLanguage).toLowerCase() ,lang:"zh-cn" //,langPath:URL +"lang/" //主题配置项,默认是default。有需要的话也可以使用如下这样的方式来自动多主题切换,当然,前提条件是themes文件夹下存在对应的主题文件: //现有如下皮肤:default //,theme:'default' //,themePath:URL +"themes/" //若实例化编辑器的页面手动修改的domain,此处需要设置为true //,customDomain:false //针对getAllHtml方法,会在对应的head标签中增加该编码设置。 //,charset:"utf-8" //常用配置项目 //,isShow : true //默认显示编辑器 //,initialContent:'欢迎使用ueditor!' //初始化编辑器的内容,也可以通过textarea/script给值,看官网例子 //,initialFrameWidth:1000 //初始化编辑器宽度,默认1000 ,initialFrameHeight:500 //初始化编辑器高度,默认320 //,autoClearinitialContent:true //是否自动清除编辑器初始内容,注意:如果focus属性设置为true,这个也为真,那么编辑器一上来就会触发导致初始化的内容看不到了 //,iframeCssUrl: URL + '/themes/iframe.css' //给编辑器内部引入一个css文件 //,textarea:'editorValue' // 提交表单时,服务器获取编辑器提交内容的所用的参数,多实例时可以给容器name属性,会将name给定的值最为每个实例的键值,不用每次实例化的时候都设置这个值 //,focus:false //初始化时,是否让编辑器获得焦点true或false //,autoClearEmptyNode : true //getContent时,是否删除空的inlineElement节点(包括嵌套的情况) //,fullscreen : false //是否开启初始化时即全屏,默认关闭 //,readonly : false //编辑器初始化结束后,编辑区域是否是只读的,默认是false //,zIndex : 900 //编辑器层级的基数,默认是900 //,imagePopup:true //图片操作的浮层开关,默认打开 //如果自定义,最好给p标签如下的行高,要不输入中文时,会有跳动感 //,initialStyle:'p{line-height:1em}'//编辑器层级的基数,可以用来改变字体等 //,autoSyncData:true //自动同步编辑器要提交的数据 //,emotionLocalization:false //是否开启表情本地化,默认关闭。若要开启请确保emotion文件夹下包含官网提供的images表情文件夹 ,pasteplain:true //是否默认为纯文本粘贴。false为不使用纯文本粘贴,true为使用纯文本粘贴 //纯文本粘贴模式下的过滤规则 // 'filterTxtRules' : function(){ // function transP(node){ // node.tagName = 'p'; // node.setStyle(); // } // return { // //直接删除及其字节点内容 // '-' : 'script style object iframe embed input select', // 'p': {$:{}}, // 'br':{$:{}}, // 'div':{'$':{}}, // 'li':{'$':{}}, // 'caption':transP, // 'th':transP, // 'tr':transP, // 'h1':transP,'h2':transP,'h3':transP,'h4':transP,'h5':transP,'h6':transP, // 'td':function(node){ // //没有内容的td直接删掉 // var txt = !!node.innerText(); // if(txt){ // node.parentNode.insertAfter(UE.uNode.createText(' &nbsp; &nbsp;'),node); // } // node.parentNode.removeChild(node,node.innerText()) // } // } // }() //,allHtmlEnabled:false //提交到后台的数据是否包含整个html字符串 //iframeUrlMap //dialog内容的路径 ~会被替换成URL,垓属性一旦打开,将覆盖所有的dialog的默认路径 //,iframeUrlMap:{ // 'anchor':'~/dialogs/anchor/anchor.html', // } //insertorderedlist //有序列表的下拉配置,值留空时支持多语言自动识别,若配置值,则以此值为准 // ,'insertorderedlist':{ // //自定的样式 // 'num':'1,2,3...', // 'num1':'1),2),3)...', // 'num2':'(1),(2),(3)...', // 'cn':'一,二,三....', // 'cn1':'一),二),三)....', // 'cn2':'(一),(二),(三)....', // //系统自带 // 'decimal' : '' , //'1,2,3...' // 'lower-alpha' : '' , // 'a,b,c...' // 'lower-roman' : '' , //'i,ii,iii...' // 'upper-alpha' : '' , lang //'A,B,C' // 'upper-roman' : '' //'I,II,III...' // } //insertunorderedlist //无序列表的下拉配置,值留空时支持多语言自动识别,若配置值,则以此值为准 //,insertunorderedlist : { // //自定的样式 // 'dash' :'— 破折号', // 'dot':' 。 小圆圈' // //系统自带 // 'circle' : '', // '○ 小圆圈' // 'disc' : '', // '● 小圆点' // 'square' : '' //'■ 小方块' //} // ,listDefaultPaddingLeft : '30'//默认的左边缩进的基数倍 // ,listiconpath : 'http://bs.baidu.com/listicon/'//自定义标号的路径 // ,maxListLevel : 3 //限制可以tab的级数-1不限制 //fontfamily //字体设置 label留空支持多语言自动切换,若配置,则以配置值为准 // ,'fontfamily':[ // { label:'',name:'songti',val:'宋体,SimSun'}, // { label:'',name:'kaiti',val:'楷体,楷体_GB2312, SimKai'}, // { label:'',name:'yahei',val:'微软雅黑,Microsoft YaHei'}, // { label:'',name:'heiti',val:'黑体, SimHei'}, // { label:'',name:'lishu',val:'隶书, SimLi'}, // { label:'',name:'andaleMono',val:'andale mono'}, // { label:'',name:'arial',val:'arial, helvetica,sans-serif'}, // { label:'',name:'arialBlack',val:'arial black,avant garde'}, // { label:'',name:'comicSansMs',val:'comic sans ms'}, // { label:'',name:'impact',val:'impact,chicago'}, // { label:'',name:'timesNewRoman',val:'times new roman'} // ] //fontsize //字号 //,'fontsize':[10, 11, 12, 14, 16, 18, 20, 24, 36] //paragraph //段落格式 值留空时支持多语言自动识别,若配置,则以配置值为准 //,'paragraph':{'p':'', 'h1':'', 'h2':'', 'h3':'', 'h4':'', 'h5':'', 'h6':''} //rowspacingtop //段间距 值和显示的名字相同 //,'rowspacingtop':['5', '10', '15', '20', '25'] //rowspacingBottom //段间距 值和显示的名字相同 //,'rowspacingbottom':['5', '10', '15', '20', '25'] //lineheight //行内间距 值和显示的名字相同 //,'lineheight':['1', '1.5','1.75','2', '3', '4', '5'] //customstyle //自定义样式,不支持国际化,此处配置值即可最后显示值 //block的元素是依据设置段落的逻辑设置的,inline的元素依据BIU的逻辑设置 //尽量使用一些常用的标签 //参数说明 //tag 使用的标签名字 //label 显示的名字也是用来标识不同类型的标识符,注意这个值每个要不同, //style 添加的样式 //每一个对象就是一个自定义的样式 //,'customstyle':[ // {tag:'h1', name:'tc', label:'', style:'border-bottom:#ccc 2px solid;padding:0 4px 0 0;text-align:center;margin:0 0 20px 0;'}, // {tag:'h1', name:'tl',label:'', style:'border-bottom:#ccc 2px solid;padding:0 4px 0 0;margin:0 0 10px 0;'}, // {tag:'span',name:'im', label:'', style:'font-style:italic;font-weight:bold'}, // {tag:'span',name:'hi', label:'', style:'font-style:italic;font-weight:bold;color:rgb(51, 153, 204)'} // ] //右键菜单的内容,可以参考plugins/contextmenu.js里边的默认菜单的例子,label留空支持国际化,否则以此配置为准 // ,contextMenu:[ // { // label:'', //显示的名称 // cmdName:'selectall',//执行的command命令,当点击这个右键菜单时 // //exec可选,有了exec就会在点击时执行这个function,优先级高于cmdName // exec:function () { // //this是当前编辑器的实例 // //this.ui._dialogs['inserttableDialog'].open(); // } // } // ] //快捷菜单 //,shortcutMenu:["fontfamily","fontsize","bold","italic","underline","forecolor","backcolor","insertorderedlist","insertunorderedlist"] //wordCount ,wordCount:true //是否开启字数统计 //,maximumWords:10000 //允许的最大字符数 //字数统计提示,{#count}代表当前字数,{#leave}代表还可以输入多少字符数,留空支持多语言自动切换,否则按此配置显示 //,wordCountMsg:'' //当前已输入 {#count} 个字符,您还可以输入{#leave} 个字符 //超出字数限制提示 留空支持多语言自动切换,否则按此配置显示 //,wordOverFlowMsg:'' //<span style="color:red;">你输入的字符个数已经超出最大允许值,服务器可能会拒绝保存!</span> //highlightcode // 代码高亮时需要加载的第三方插件的路径 // ,highlightJsUrl:URL + "third-party/SyntaxHighlighter/shCore.js" // ,highlightCssUrl:URL + "third-party/SyntaxHighlighter/shCoreDefault.css" //tab //点击tab键时移动的距离,tabSize倍数,tabNode什么字符做为单位 //,tabSize:4 //,tabNode:'&nbsp;' //elementPathEnabled //是否启用元素路径,默认是显示 //,elementPathEnabled : true //removeFormat //清除格式时可以删除的标签和属性 //removeForamtTags标签 //,removeFormatTags:'b,big,code,del,dfn,em,font,i,ins,kbd,q,samp,small,span,strike,strong,sub,sup,tt,u,var' //removeFormatAttributes属性 //,removeFormatAttributes:'class,style,lang,width,height,align,hspace,valign' //undo //可以最多回退的次数,默认20 //,maxUndoCount:20 //当输入的字符数超过该值时,保存一次现场 //,maxInputCount:1 //autoHeightEnabled // 是否自动长高,默认true //,autoHeightEnabled:true //scaleEnabled //是否可以拉伸长高,默认true(当开启时,自动长高失效) //,scaleEnabled:false //,minFrameWidth:800 //编辑器拖动时最小宽度,默认800 //,minFrameHeight:220 //编辑器拖动时最小高度,默认220 //autoFloatEnabled //是否保持toolbar的位置不动,默认true //,autoFloatEnabled:true //浮动时工具栏距离浏览器顶部的高度,用于某些具有固定头部的页面 //,topOffset:30 //编辑器底部距离工具栏高度(如果参数大于等于编辑器高度,则设置无效) //,toolbarTopOffset:400 //indentValue //首行缩进距离,默认是2em //,indentValue:'2em' //pageBreakTag //分页标识符,默认是_ueditor_page_break_tag_ //,pageBreakTag:'_ueditor_page_break_tag_' //sourceEditor //源码的查看方式,codemirror 是代码高亮,textarea是文本框,默认是codemirror //注意默认codemirror只能在ie8+和非ie中使用 //,sourceEditor:"codemirror" //如果sourceEditor是codemirror,还用配置一下两个参数 //codeMirrorJsUrl js加载的路径,默认是 URL + "third-party/codemirror/codemirror.js" //,codeMirrorJsUrl:URL + "third-party/codemirror/codemirror.js" //codeMirrorCssUrl css加载的路径,默认是 URL + "third-party/codemirror/codemirror.css" //,codeMirrorCssUrl:URL + "third-party/codemirror/codemirror.css" //编辑器初始化完成后是否进入源码模式,默认为否。 //,sourceEditorFirst:false //autotypeset // //自动排版参数 // ,autotypeset:{ // mergeEmptyline : true, //合并空行 // removeClass : true, //去掉冗余的class // removeEmptyline : false, //去掉空行 // textAlign : "left" , //段落的排版方式,可以是 left,right,center,justify 去掉这个属性表示不执行排版 // imageBlockLine : 'center', //图片的浮动方式,独占一行剧中,左右浮动,默认: center,left,right,none 去掉这个属性表示不执行排版 // pasteFilter : false, //根据规则过滤没事粘贴进来的内容 // clearFontSize : false, //去掉所有的内嵌字号,使用编辑器默认的字号 // clearFontFamily : false, //去掉所有的内嵌字体,使用编辑器默认的字体 // removeEmptyNode : false , // 去掉空节点 // //可以去掉的标签 // removeTagNames : {标签名字:1}, // indent : false, // 行首缩进 // indentValue : '2em' //行首缩进的大小 // }, //填写过滤规则 //filterRules : {} }; })();
JavaScript
/** * Created by JetBrains PhpStorm. * User: taoqili * Date: 12-2-20 * Time: 上午11:19 * To change this template use File | Settings | File Templates. */ var video = {}; (function(){ video.init = function(){ // switchTab("videoTab"); createAlignButton( ["videoFloat"] ); addUrlChangeListener($G("videoUrl")); addOkListener(); //编辑视频时初始化相关信息 (function(){ var img = editor.selection.getRange().getClosedNode(),url; if(img && img.className == "edui-faked-video"){ $G("videoUrl").value = url = img.getAttribute("_url"); $G("videoWidth").value = img.width; $G("videoHeight").value = img.height; var align = domUtils.getComputedStyle(img,"float"), parentAlign = domUtils.getComputedStyle(img.parentNode,"text-align"); updateAlignButton(parentAlign==="center"?"center":align); } createPreviewVideo(url); })(); }; /** * 监听确认和取消两个按钮事件,用户执行插入或者清空正在播放的视频实例操作 */ function addOkListener(){ dialog.onok = function(){ $G("preview").innerHTML = ""; var currentTab = findFocus("tabHeads","tabSrc"); switch(currentTab){ case "video": return insertSingle(); break; // case "videoSearch": // return insertSearch("searchList"); // break; } }; dialog.oncancel = function(){ $G("preview").innerHTML = ""; }; } function selectTxt(node){ if(node.select){ node.select(); }else{ var r = node.createTextRange && node.createTextRange(); r.select(); } } /** * 依据传入的align值更新按钮信息 * @param align */ function updateAlignButton( align ) { var aligns = $G( "videoFloat" ).children; for ( var i = 0, ci; ci = aligns[i++]; ) { if ( ci.getAttribute( "name" ) == align ) { if ( ci.className !="focus" ) { ci.className = "focus"; } } else { if ( ci.className =="focus" ) { ci.className = ""; } } } } /** * 将单个视频信息插入编辑器中 */ function insertSingle(){ var width = $G("videoWidth"), height = $G("videoHeight"), url=$G('videoUrl').value, align = findFocus("videoFloat","name"); if(!url) return false; if ( !checkNum( [width, height] ) ) return false; editor.execCommand('insertvideo', { url: convert_url(url), width: width.value, height: height.value, align: align }); } /** * 将元素id下的所有代表视频的图片插入编辑器中 * @param id */ function insertSearch(id){ var imgs = domUtils.getElementsByTagName($G(id),"img"), videoObjs=[]; for(var i=0,img; img=imgs[i++];){ if(img.getAttribute("selected")){ videoObjs.push({ url:img.getAttribute("ue_video_url"), width:420, height:280, align:"none" }); } } editor.execCommand('insertvideo',videoObjs); } /** * 找到id下具有focus类的节点并返回该节点下的某个属性 * @param id * @param returnProperty */ function findFocus( id, returnProperty ) { var tabs = $G( id ).children, property; for ( var i = 0, ci; ci = tabs[i++]; ) { if ( ci.className=="focus" ) { property = ci.getAttribute( returnProperty ); break; } } return property; } function convert_url(s){ return s.replace(/http:\/\/www\.tudou\.com\/programs\/view\/([\w\-]+)\/?/i,"http://www.tudou.com/v/$1") .replace(/http:\/\/www\.youtube\.com\/watch\?v=([\w\-]+)/i,"http://www.youtube.com/v/$1") .replace(/http:\/\/v\.youku\.com\/v_show\/id_([\w\-=]+)\.html/i,"http://player.youku.com/player.php/sid/$1") .replace(/http:\/\/www\.56\.com\/u\d+\/v_([\w\-]+)\.html/i, "http://player.56.com/v_$1.swf") .replace(/http:\/\/www.56.com\/w\d+\/play_album\-aid\-\d+_vid\-([^.]+)\.html/i, "http://player.56.com/v_$1.swf") .replace(/http:\/\/v\.ku6\.com\/.+\/([^.]+)\.html/i, "http://player.ku6.com/refer/$1/v.swf"); } /** * 检测传入的所有input框中输入的长宽是否是正数 * @param nodes input框集合, */ function checkNum( nodes ) { for ( var i = 0, ci; ci = nodes[i++]; ) { var value = ci.value; if ( !isNumber( value ) && value) { alert( lang.numError ); ci.value = ""; ci.focus(); return false; } } return true; } /** * 数字判断 * @param value */ function isNumber( value ) { return /(0|^[1-9]\d*$)/.test( value ); } /** * tab切换 * @param tabParentId * @param keepFocus 当此值为真时,切换按钮上会保留focus的样式 */ function switchTab( tabParentId,keepFocus ) { var tabElements = $G( tabParentId ).children, tabHeads = tabElements[0].children, tabBodys = tabElements[1].children; for ( var i = 0, length = tabHeads.length; i < length; i++ ) { var head = tabHeads[i]; domUtils.on( head, "click", function () { //head样式更改 for ( var k = 0, len = tabHeads.length; k < len; k++ ) { if(!keepFocus)tabHeads[k].className = ""; } this.className = "focus"; //body显隐 var tabSrc = this.getAttribute( "tabSrc" ); for ( var j = 0, length = tabBodys.length; j < length; j++ ) { var body = tabBodys[j], id = body.getAttribute( "id" ); if ( id == tabSrc ) { body.style.display = ""; if(id=="videoSearch"){ selectTxt($G("videoSearchTxt")); } if(id=="video"){ selectTxt($G("videoUrl")); } } else { body.style.display = "none"; } } } ); } } /** * 创建图片浮动选择按钮 * @param ids */ function createAlignButton( ids ) { for ( var i = 0, ci; ci = ids[i++]; ) { var floatContainer = $G( ci ), nameMaps = {"none":lang['default'], "left":lang.floatLeft, "right":lang.floatRight, "center":lang.block}; for ( var j in nameMaps ) { var div = document.createElement( "div" ); div.setAttribute( "name", j ); if ( j == "none" ) div.className="focus"; div.style.cssText = "background:url(images/" + j + "_focus.jpg);"; div.setAttribute( "title", nameMaps[j] ); floatContainer.appendChild( div ); } switchSelect( ci ); } } /** * 选择切换 * @param selectParentId */ function switchSelect( selectParentId ) { var selects = $G( selectParentId ).children; for ( var i = 0, ci; ci = selects[i++]; ) { domUtils.on( ci, "click", function () { for ( var j = 0, cj; cj = selects[j++]; ) { cj.className = ""; cj.removeAttribute && cj.removeAttribute( "class" ); } this.className = "focus"; } ) } } /** * 监听url改变事件 * @param url */ function addUrlChangeListener(url){ if (browser.ie) { url.onpropertychange = function () { createPreviewVideo( this.value ); } } else { url.addEventListener( "input", function () { createPreviewVideo( this.value ); }, false ); } } /** * 根据url生成视频预览 * @param url */ function createPreviewVideo(url){ if ( !url )return; var matches = url.match(/youtu.be\/(\w+)$/) || url.match(/youtube\.com\/watch\?v=(\w+)/) || url.match(/youtube.com\/v\/(\w+)/), youku = url.match(/youku\.com\/v_show\/id_(\w+)/), youkuPlay = /player\.youku\.com/ig.test(url); if(!youkuPlay){ if (matches){ url = "https://www.youtube.com/v/" + matches[1] + "?version=3&feature=player_embedded"; }else if(youku){ url = "http://player.youku.com/player.php/sid/"+youku[1]+"/v.swf" }else if(!endWith(url,[".swf",".flv",".wmv"])){ $G("preview").innerHTML = lang.urlError; return; } }else{ url = url.replace(/\?f=.*/,""); } $G("preview").innerHTML = '<embed type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer"' + ' src="' + url + '"' + ' width="' + 420 + '"' + ' height="' + 280 + '"' + ' wmode="transparent" play="true" loop="false" menu="false" allowscriptaccess="never" allowfullscreen="true" ></embed>'; } /** * 末尾字符检测 * @param str * @param endStrArr */ function endWith(str,endStrArr){ for(var i=0,len = endStrArr.length;i<len;i++){ var tmp = endStrArr[i]; if(str.length - tmp.length<0) return false; if(str.substring(str.length-tmp.length)==tmp){ return true; } } return false; } /** * ajax获取视频信息 */ function getMovie(){ var keywordInput = $G("videoSearchTxt"); if(!keywordInput.getAttribute("hasClick") ||!keywordInput.value){ selectTxt(keywordInput); return; } $G( "searchList" ).innerHTML = lang.loading; var keyword = keywordInput.value, type = $G("videoType").value, str=""; ajax.request(editor.options.getMovieUrl,{ searchKey:keyword, videoType:type, onsuccess:function(xhr){ try{ var info = eval("("+xhr.responseText+")"); }catch(e){ return; } var videos = info.multiPageResult.results; var html=["<table width='530'>"]; for(var i=0,ci;ci = videos[i++];){ html.push( "<tr>" + "<td><img title='"+lang.clickToSelect+"' ue_video_url='"+ci.outerPlayerUrl+"' alt='"+ci.tags+"' width='106' height='80' src='"+ci.picUrl+"' /> </td>" + "<td>" + "<p><a target='_blank' title='"+lang.goToSource+"' href='"+ci.itemUrl+"'>"+ci.title.substr(0,30)+"</a></p>" + "<p style='height: 62px;line-height: 20px' title='"+ci.description+"'> "+ ci.description.substr(0,95) +" </p>" + "</td>" + "</tr>" ); } html.push("</table>"); $G("searchList").innerHTML = str = html.length ==2 ?lang.noVideo : html.join(""); var imgs = domUtils.getElementsByTagName($G("searchList"),"img"); if(!imgs)return; for(var i=0,img;img = imgs[i++];){ domUtils.on(img,"click",function(){ changeSelected(this); }) } } }); } /** * 改变对象o的选中状态 * @param o */ function changeSelected(o){ if ( o.getAttribute( "selected" ) ) { o.removeAttribute( "selected" ); o.style.cssText = "filter:alpha(Opacity=100);-moz-opacity:1;opacity: 1;border: 2px solid #fff"; } else { o.setAttribute( "selected", "true" ); o.style.cssText = "filter:alpha(Opacity=50);-moz-opacity:0.5;opacity: 0.5;border:2px solid blue;"; } } })();
JavaScript
// Copyright (c) 2009, Baidu Inc. All rights reserved. // // Licensed under the BSD License // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http:// tangram.baidu.com/license.html // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @namespace T Tangram七巧板 * @name T * @version 1.6.0 */ /** * 声明baidu包 * @author: allstar, erik, meizz, berg */ var T, baidu = T = baidu || {version: "1.5.0"}; baidu.guid = "$BAIDU$"; baidu.$$ = window[baidu.guid] = window[baidu.guid] || {global:{}}; /** * 使用flash资源封装的一些功能 * @namespace baidu.flash */ baidu.flash = baidu.flash || {}; /** * 操作dom的方法 * @namespace baidu.dom */ baidu.dom = baidu.dom || {}; /** * 从文档中获取指定的DOM元素 * @name baidu.dom.g * @function * @grammar baidu.dom.g(id) * @param {string|HTMLElement} id 元素的id或DOM元素. * @shortcut g,T.G * @meta standard * @see baidu.dom.q * * @return {HTMLElement|null} 获取的元素,查找不到时返回null,如果参数不合法,直接返回参数. */ baidu.dom.g = function(id) { if (!id) return null; if ('string' == typeof id || id instanceof String) { return document.getElementById(id); } else if (id.nodeName && (id.nodeType == 1 || id.nodeType == 9)) { return id; } return null; }; baidu.g = baidu.G = baidu.dom.g; /** * 操作数组的方法 * @namespace baidu.array */ baidu.array = baidu.array || {}; /** * 遍历数组中所有元素 * @name baidu.array.each * @function * @grammar baidu.array.each(source, iterator[, thisObject]) * @param {Array} source 需要遍历的数组 * @param {Function} iterator 对每个数组元素进行调用的函数,该函数有两个参数,第一个为数组元素,第二个为数组索引值,function (item, index)。 * @param {Object} [thisObject] 函数调用时的this指针,如果没有此参数,默认是当前遍历的数组 * @remark * each方法不支持对Object的遍历,对Object的遍历使用baidu.object.each 。 * @shortcut each * @meta standard * * @returns {Array} 遍历的数组 */ baidu.each = baidu.array.forEach = baidu.array.each = function (source, iterator, thisObject) { var returnValue, item, i, len = source.length; if ('function' == typeof iterator) { for (i = 0; i < len; i++) { item = source[i]; returnValue = iterator.call(thisObject || source, item, i); if (returnValue === false) { break; } } } return source; }; /** * 对语言层面的封装,包括类型判断、模块扩展、继承基类以及对象自定义事件的支持。 * @namespace baidu.lang */ baidu.lang = baidu.lang || {}; /** * 判断目标参数是否为function或Function实例 * @name baidu.lang.isFunction * @function * @grammar baidu.lang.isFunction(source) * @param {Any} source 目标参数 * @version 1.2 * @see baidu.lang.isString,baidu.lang.isObject,baidu.lang.isNumber,baidu.lang.isArray,baidu.lang.isElement,baidu.lang.isBoolean,baidu.lang.isDate * @meta standard * @returns {boolean} 类型判断结果 */ baidu.lang.isFunction = function (source) { return '[object Function]' == Object.prototype.toString.call(source); }; /** * 判断目标参数是否string类型或String对象 * @name baidu.lang.isString * @function * @grammar baidu.lang.isString(source) * @param {Any} source 目标参数 * @shortcut isString * @meta standard * @see baidu.lang.isObject,baidu.lang.isNumber,baidu.lang.isArray,baidu.lang.isElement,baidu.lang.isBoolean,baidu.lang.isDate * * @returns {boolean} 类型判断结果 */ baidu.lang.isString = function (source) { return '[object String]' == Object.prototype.toString.call(source); }; baidu.isString = baidu.lang.isString; /** * 判断浏览器类型和特性的属性 * @namespace baidu.browser */ baidu.browser = baidu.browser || {}; /** * 判断是否为opera浏览器 * @property opera opera版本号 * @grammar baidu.browser.opera * @meta standard * @see baidu.browser.ie,baidu.browser.firefox,baidu.browser.safari,baidu.browser.chrome * @returns {Number} opera版本号 */ /** * opera 从10开始不是用opera后面的字符串进行版本的判断 * 在Browser identification最后添加Version + 数字进行版本标识 * opera后面的数字保持在9.80不变 */ baidu.browser.opera = /opera(\/| )(\d+(\.\d+)?)(.+?(version\/(\d+(\.\d+)?)))?/i.test(navigator.userAgent) ? + ( RegExp["\x246"] || RegExp["\x242"] ) : undefined; /** * 在目标元素的指定位置插入HTML代码 * @name baidu.dom.insertHTML * @function * @grammar baidu.dom.insertHTML(element, position, html) * @param {HTMLElement|string} element 目标元素或目标元素的id * @param {string} position 插入html的位置信息,取值为beforeBegin,afterBegin,beforeEnd,afterEnd * @param {string} html 要插入的html * @remark * * 对于position参数,大小写不敏感<br> * 参数的意思:beforeBegin&lt;span&gt;afterBegin this is span! beforeEnd&lt;/span&gt; afterEnd <br /> * 此外,如果使用本函数插入带有script标签的HTML字符串,script标签对应的脚本将不会被执行。 * * @shortcut insertHTML * @meta standard * * @returns {HTMLElement} 目标元素 */ baidu.dom.insertHTML = function (element, position, html) { element = baidu.dom.g(element); var range,begin; if (element.insertAdjacentHTML && !baidu.browser.opera) { element.insertAdjacentHTML(position, html); } else { range = element.ownerDocument.createRange(); position = position.toUpperCase(); if (position == 'AFTERBEGIN' || position == 'BEFOREEND') { range.selectNodeContents(element); range.collapse(position == 'AFTERBEGIN'); } else { begin = position == 'BEFOREBEGIN'; range[begin ? 'setStartBefore' : 'setEndAfter'](element); range.collapse(begin); } range.insertNode(range.createContextualFragment(html)); } return element; }; baidu.insertHTML = baidu.dom.insertHTML; /** * 操作flash对象的方法,包括创建flash对象、获取flash对象以及判断flash插件的版本号 * @namespace baidu.swf */ baidu.swf = baidu.swf || {}; /** * 浏览器支持的flash插件版本 * @property version 浏览器支持的flash插件版本 * @grammar baidu.swf.version * @return {String} 版本号 * @meta standard */ baidu.swf.version = (function () { var n = navigator; if (n.plugins && n.mimeTypes.length) { var plugin = n.plugins["Shockwave Flash"]; if (plugin && plugin.description) { return plugin.description .replace(/([a-zA-Z]|\s)+/, "") .replace(/(\s)+r/, ".") + ".0"; } } else if (window.ActiveXObject && !window.opera) { for (var i = 12; i >= 2; i--) { try { var c = new ActiveXObject('ShockwaveFlash.ShockwaveFlash.' + i); if (c) { var version = c.GetVariable("$version"); return version.replace(/WIN/g,'').replace(/,/g,'.'); } } catch(e) {} } } })(); /** * 操作字符串的方法 * @namespace baidu.string */ baidu.string = baidu.string || {}; /** * 对目标字符串进行html编码 * @name baidu.string.encodeHTML * @function * @grammar baidu.string.encodeHTML(source) * @param {string} source 目标字符串 * @remark * 编码字符有5个:&<>"' * @shortcut encodeHTML * @meta standard * @see baidu.string.decodeHTML * * @returns {string} html编码后的字符串 */ baidu.string.encodeHTML = function (source) { return String(source) .replace(/&/g,'&amp;') .replace(/</g,'&lt;') .replace(/>/g,'&gt;') .replace(/"/g, "&quot;") .replace(/'/g, "&#39;"); }; baidu.encodeHTML = baidu.string.encodeHTML; /** * 创建flash对象的html字符串 * @name baidu.swf.createHTML * @function * @grammar baidu.swf.createHTML(options) * * @param {Object} options 创建flash的选项参数 * @param {string} options.id 要创建的flash的标识 * @param {string} options.url flash文件的url * @param {String} options.errorMessage 未安装flash player或flash player版本号过低时的提示 * @param {string} options.ver 最低需要的flash player版本号 * @param {string} options.width flash的宽度 * @param {string} options.height flash的高度 * @param {string} options.align flash的对齐方式,允许值:middle/left/right/top/bottom * @param {string} options.base 设置用于解析swf文件中的所有相对路径语句的基本目录或URL * @param {string} options.bgcolor swf文件的背景色 * @param {string} options.salign 设置缩放的swf文件在由width和height设置定义的区域内的位置。允许值:l/r/t/b/tl/tr/bl/br * @param {boolean} options.menu 是否显示右键菜单,允许值:true/false * @param {boolean} options.loop 播放到最后一帧时是否重新播放,允许值: true/false * @param {boolean} options.play flash是否在浏览器加载时就开始播放。允许值:true/false * @param {string} options.quality 设置flash播放的画质,允许值:low/medium/high/autolow/autohigh/best * @param {string} options.scale 设置flash内容如何缩放来适应设置的宽高。允许值:showall/noborder/exactfit * @param {string} options.wmode 设置flash的显示模式。允许值:window/opaque/transparent * @param {string} options.allowscriptaccess 设置flash与页面的通信权限。允许值:always/never/sameDomain * @param {string} options.allownetworking 设置swf文件中允许使用的网络API。允许值:all/internal/none * @param {boolean} options.allowfullscreen 是否允许flash全屏。允许值:true/false * @param {boolean} options.seamlesstabbing 允许设置执行无缝跳格,从而使用户能跳出flash应用程序。该参数只能在安装Flash7及更高版本的Windows中使用。允许值:true/false * @param {boolean} options.devicefont 设置静态文本对象是否以设备字体呈现。允许值:true/false * @param {boolean} options.swliveconnect 第一次加载flash时浏览器是否应启动Java。允许值:true/false * @param {Object} options.vars 要传递给flash的参数,支持JSON或string类型。 * * @see baidu.swf.create * @meta standard * @returns {string} flash对象的html字符串 */ baidu.swf.createHTML = function (options) { options = options || {}; var version = baidu.swf.version, needVersion = options['ver'] || '6.0.0', vUnit1, vUnit2, i, k, len, item, tmpOpt = {}, encodeHTML = baidu.string.encodeHTML; for (k in options) { tmpOpt[k] = options[k]; } options = tmpOpt; if (version) { version = version.split('.'); needVersion = needVersion.split('.'); for (i = 0; i < 3; i++) { vUnit1 = parseInt(version[i], 10); vUnit2 = parseInt(needVersion[i], 10); if (vUnit2 < vUnit1) { break; } else if (vUnit2 > vUnit1) { return ''; } } } else { return ''; } var vars = options['vars'], objProperties = ['classid', 'codebase', 'id', 'width', 'height', 'align']; options['align'] = options['align'] || 'middle'; options['classid'] = 'clsid:d27cdb6e-ae6d-11cf-96b8-444553540000'; options['codebase'] = 'http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0'; options['movie'] = options['url'] || ''; delete options['vars']; delete options['url']; if ('string' == typeof vars) { options['flashvars'] = vars; } else { var fvars = []; for (k in vars) { item = vars[k]; fvars.push(k + "=" + encodeURIComponent(item)); } options['flashvars'] = fvars.join('&'); } var str = ['<object ']; for (i = 0, len = objProperties.length; i < len; i++) { item = objProperties[i]; str.push(' ', item, '="', encodeHTML(options[item]), '"'); } str.push('>'); var params = { 'wmode' : 1, 'scale' : 1, 'quality' : 1, 'play' : 1, 'loop' : 1, 'menu' : 1, 'salign' : 1, 'bgcolor' : 1, 'base' : 1, 'allowscriptaccess' : 1, 'allownetworking' : 1, 'allowfullscreen' : 1, 'seamlesstabbing' : 1, 'devicefont' : 1, 'swliveconnect' : 1, 'flashvars' : 1, 'movie' : 1 }; for (k in options) { item = options[k]; k = k.toLowerCase(); if (params[k] && (item || item === false || item === 0)) { str.push('<param name="' + k + '" value="' + encodeHTML(item) + '" />'); } } options['src'] = options['movie']; options['name'] = options['id']; delete options['id']; delete options['movie']; delete options['classid']; delete options['codebase']; options['type'] = 'application/x-shockwave-flash'; options['pluginspage'] = 'http://www.macromedia.com/go/getflashplayer'; str.push('<embed'); var salign; for (k in options) { item = options[k]; if (item || item === false || item === 0) { if ((new RegExp("^salign\x24", "i")).test(k)) { salign = item; continue; } str.push(' ', k, '="', encodeHTML(item), '"'); } } if (salign) { str.push(' salign="', encodeHTML(salign), '"'); } str.push('></embed></object>'); return str.join(''); }; /** * 在页面中创建一个flash对象 * @name baidu.swf.create * @function * @grammar baidu.swf.create(options[, container]) * * @param {Object} options 创建flash的选项参数 * @param {string} options.id 要创建的flash的标识 * @param {string} options.url flash文件的url * @param {String} options.errorMessage 未安装flash player或flash player版本号过低时的提示 * @param {string} options.ver 最低需要的flash player版本号 * @param {string} options.width flash的宽度 * @param {string} options.height flash的高度 * @param {string} options.align flash的对齐方式,允许值:middle/left/right/top/bottom * @param {string} options.base 设置用于解析swf文件中的所有相对路径语句的基本目录或URL * @param {string} options.bgcolor swf文件的背景色 * @param {string} options.salign 设置缩放的swf文件在由width和height设置定义的区域内的位置。允许值:l/r/t/b/tl/tr/bl/br * @param {boolean} options.menu 是否显示右键菜单,允许值:true/false * @param {boolean} options.loop 播放到最后一帧时是否重新播放,允许值: true/false * @param {boolean} options.play flash是否在浏览器加载时就开始播放。允许值:true/false * @param {string} options.quality 设置flash播放的画质,允许值:low/medium/high/autolow/autohigh/best * @param {string} options.scale 设置flash内容如何缩放来适应设置的宽高。允许值:showall/noborder/exactfit * @param {string} options.wmode 设置flash的显示模式。允许值:window/opaque/transparent * @param {string} options.allowscriptaccess 设置flash与页面的通信权限。允许值:always/never/sameDomain * @param {string} options.allownetworking 设置swf文件中允许使用的网络API。允许值:all/internal/none * @param {boolean} options.allowfullscreen 是否允许flash全屏。允许值:true/false * @param {boolean} options.seamlesstabbing 允许设置执行无缝跳格,从而使用户能跳出flash应用程序。该参数只能在安装Flash7及更高版本的Windows中使用。允许值:true/false * @param {boolean} options.devicefont 设置静态文本对象是否以设备字体呈现。允许值:true/false * @param {boolean} options.swliveconnect 第一次加载flash时浏览器是否应启动Java。允许值:true/false * @param {Object} options.vars 要传递给flash的参数,支持JSON或string类型。 * * @param {HTMLElement|string} [container] flash对象的父容器元素,不传递该参数时在当前代码位置创建flash对象。 * @meta standard * @see baidu.swf.createHTML,baidu.swf.getMovie */ baidu.swf.create = function (options, target) { options = options || {}; var html = baidu.swf.createHTML(options) || options['errorMessage'] || ''; if (target && 'string' == typeof target) { target = document.getElementById(target); } baidu.dom.insertHTML( target || document.body ,'beforeEnd',html ); }; /** * 判断是否为ie浏览器 * @name baidu.browser.ie * @field * @grammar baidu.browser.ie * @returns {Number} IE版本号 */ baidu.browser.ie = baidu.ie = /msie (\d+\.\d+)/i.test(navigator.userAgent) ? (document.documentMode || + RegExp['\x241']) : undefined; /** * 移除数组中的项 * @name baidu.array.remove * @function * @grammar baidu.array.remove(source, match) * @param {Array} source 需要移除项的数组 * @param {Any} match 要移除的项 * @meta standard * @see baidu.array.removeAt * * @returns {Array} 移除后的数组 */ baidu.array.remove = function (source, match) { var len = source.length; while (len--) { if (len in source && source[len] === match) { source.splice(len, 1); } } return source; }; /** * 判断目标参数是否Array对象 * @name baidu.lang.isArray * @function * @grammar baidu.lang.isArray(source) * @param {Any} source 目标参数 * @meta standard * @see baidu.lang.isString,baidu.lang.isObject,baidu.lang.isNumber,baidu.lang.isElement,baidu.lang.isBoolean,baidu.lang.isDate * * @returns {boolean} 类型判断结果 */ baidu.lang.isArray = function (source) { return '[object Array]' == Object.prototype.toString.call(source); }; /** * 将一个变量转换成array * @name baidu.lang.toArray * @function * @grammar baidu.lang.toArray(source) * @param {mix} source 需要转换成array的变量 * @version 1.3 * @meta standard * @returns {array} 转换后的array */ baidu.lang.toArray = function (source) { if (source === null || source === undefined) return []; if (baidu.lang.isArray(source)) return source; if (typeof source.length !== 'number' || typeof source === 'string' || baidu.lang.isFunction(source)) { return [source]; } if (source.item) { var l = source.length, array = new Array(l); while (l--) array[l] = source[l]; return array; } return [].slice.call(source); }; /** * 获得flash对象的实例 * @name baidu.swf.getMovie * @function * @grammar baidu.swf.getMovie(name) * @param {string} name flash对象的名称 * @see baidu.swf.create * @meta standard * @returns {HTMLElement} flash对象的实例 */ baidu.swf.getMovie = function (name) { var movie = document[name], ret; return baidu.browser.ie == 9 ? movie && movie.length ? (ret = baidu.array.remove(baidu.lang.toArray(movie),function(item){ return item.tagName.toLowerCase() != "embed"; })).length == 1 ? ret[0] : ret : movie : movie || window[name]; }; baidu.flash._Base = (function(){ var prefix = 'bd__flash__'; /** * 创建一个随机的字符串 * @private * @return {String} */ function _createString(){ return prefix + Math.floor(Math.random() * 2147483648).toString(36); }; /** * 检查flash状态 * @private * @param {Object} target flash对象 * @return {Boolean} */ function _checkReady(target){ if(typeof target !== 'undefined' && typeof target.flashInit !== 'undefined' && target.flashInit()){ return true; }else{ return false; } }; /** * 调用之前进行压栈的函数 * @private * @param {Array} callQueue 调用队列 * @param {Object} target flash对象 * @return {Null} */ function _callFn(callQueue, target){ var result = null; callQueue = callQueue.reverse(); baidu.each(callQueue, function(item){ result = target.call(item.fnName, item.params); item.callBack(result); }); }; /** * 为传入的匿名函数创建函数名 * @private * @param {String|Function} fun 传入的匿名函数或者函数名 * @return {String} */ function _createFunName(fun){ var name = ''; if(baidu.lang.isFunction(fun)){ name = _createString(); window[name] = function(){ fun.apply(window, arguments); }; return name; }else if(baidu.lang.isString){ return fun; } }; /** * 绘制flash * @private * @param {Object} options 创建参数 * @return {Object} */ function _render(options){ if(!options.id){ options.id = _createString(); } var container = options.container || ''; delete(options.container); baidu.swf.create(options, container); return baidu.swf.getMovie(options.id); }; return function(options, callBack){ var me = this, autoRender = (typeof options.autoRender !== 'undefined' ? options.autoRender : true), createOptions = options.createOptions || {}, target = null, isReady = false, callQueue = [], timeHandle = null, callBack = callBack || []; /** * 将flash文件绘制到页面上 * @public * @return {Null} */ me.render = function(){ target = _render(createOptions); if(callBack.length > 0){ baidu.each(callBack, function(funName, index){ callBack[index] = _createFunName(options[funName] || new Function()); }); } me.call('setJSFuncName', [callBack]); }; /** * 返回flash状态 * @return {Boolean} */ me.isReady = function(){ return isReady; }; /** * 调用flash接口的统一入口 * @param {String} fnName 调用的函数名 * @param {Array} params 传入的参数组成的数组,若不许要参数,需传入空数组 * @param {Function} [callBack] 异步调用后将返回值作为参数的调用回调函数,如无返回值,可以不传入此参数 * @return {Null} */ me.call = function(fnName, params, callBack){ if(!fnName) return null; callBack = callBack || new Function(); var result = null; if(isReady){ result = target.call(fnName, params); callBack(result); }else{ callQueue.push({ fnName: fnName, params: params, callBack: callBack }); (!timeHandle) && (timeHandle = setInterval(_check, 200)); } }; /** * 为传入的匿名函数创建函数名 * @public * @param {String|Function} fun 传入的匿名函数或者函数名 * @return {String} */ me.createFunName = function(fun){ return _createFunName(fun); }; /** * 检查flash是否ready, 并进行调用 * @private * @return {Null} */ function _check(){ if(_checkReady(target)){ clearInterval(timeHandle); timeHandle = null; _call(); isReady = true; } }; /** * 调用之前进行压栈的函数 * @private * @return {Null} */ function _call(){ _callFn(callQueue, target); callQueue = []; } autoRender && me.render(); }; })(); /** * 创建flash based imageUploader * @class * @grammar baidu.flash.imageUploader(options) * @param {Object} createOptions 创建flash时需要的参数,请参照baidu.swf.create文档 * @config {Object} vars 创建imageUploader时所需要的参数 * @config {Number} vars.gridWidth 每一个预览图片所占的宽度,应该为flash寛的整除 * @config {Number} vars.gridHeight 每一个预览图片所占的高度,应该为flash高的整除 * @config {Number} vars.picWidth 单张预览图片的宽度 * @config {Number} vars.picHeight 单张预览图片的高度 * @config {String} vars.uploadDataFieldName POST请求中图片数据的key,默认值'picdata' * @config {String} vars.picDescFieldName POST请求中图片描述的key,默认值'picDesc' * @config {Number} vars.maxSize 文件的最大体积,单位'MB' * @config {Number} vars.compressSize 上传前如果图片体积超过该值,会先压缩 * @config {Number} vars.maxNum:32 最大上传多少个文件 * @config {Number} vars.compressLength 能接受的最大边长,超过该值会等比压缩 * @config {String} vars.url 上传的url地址 * @config {Number} vars.mode mode == 0时,是使用滚动条,mode == 1时,拉伸flash, 默认值为0 * @see baidu.swf.createHTML * @param {String} backgroundUrl 背景图片路径 * @param {String} listBacgroundkUrl 布局控件背景 * @param {String} buttonUrl 按钮图片不背景 * @param {String|Function} selectFileCallback 选择文件的回调 * @param {String|Function} exceedFileCallback文件超出限制的最大体积时的回调 * @param {String|Function} deleteFileCallback 删除文件的回调 * @param {String|Function} startUploadCallback 开始上传某个文件时的回调 * @param {String|Function} uploadCompleteCallback 某个文件上传完成的回调 * @param {String|Function} uploadErrorCallback 某个文件上传失败的回调 * @param {String|Function} allCompleteCallback 全部上传完成时的回调 * @param {String|Function} changeFlashHeight 改变Flash的高度,mode==1的时候才有用 */ baidu.flash.imageUploader = baidu.flash.imageUploader || function(options){ var me = this, options = options || {}, _flash = new baidu.flash._Base(options, [ 'selectFileCallback', 'exceedFileCallback', 'deleteFileCallback', 'startUploadCallback', 'uploadCompleteCallback', 'uploadErrorCallback', 'allCompleteCallback', 'changeFlashHeight' ]); /** * 开始或回复上传图片 * @public * @return {Null} */ me.upload = function(){ _flash.call('upload'); }; /** * 暂停上传图片 * @public * @return {Null} */ me.pause = function(){ _flash.call('pause'); }; me.addCustomizedParams = function(index,obj){ _flash.call('addCustomizedParams',[index,obj]); } }; /** * 操作原生对象的方法 * @namespace baidu.object */ baidu.object = baidu.object || {}; /** * 将源对象的所有属性拷贝到目标对象中 * @author erik * @name baidu.object.extend * @function * @grammar baidu.object.extend(target, source) * @param {Object} target 目标对象 * @param {Object} source 源对象 * @see baidu.array.merge * @remark * 1.目标对象中,与源对象key相同的成员将会被覆盖。<br> 2.源对象的prototype成员不会拷贝。 * @shortcut extend * @meta standard * * @returns {Object} 目标对象 */ baidu.extend = baidu.object.extend = function (target, source) { for (var p in source) { if (source.hasOwnProperty(p)) { target[p] = source[p]; } } return target; }; /** * 创建flash based fileUploader * @class * @grammar baidu.flash.fileUploader(options) * @param {Object} options * @config {Object} createOptions 创建flash时需要的参数,请参照baidu.swf.create文档 * @config {String} createOptions.width * @config {String} createOptions.height * @config {Number} maxNum 最大可选文件数 * @config {Function|String} selectFile * @config {Function|String} exceedMaxSize * @config {Function|String} deleteFile * @config {Function|String} uploadStart * @config {Function|String} uploadComplete * @config {Function|String} uploadError * @config {Function|String} uploadProgress */ baidu.flash.fileUploader = baidu.flash.fileUploader || function(options){ var me = this, options = options || {}; options.createOptions = baidu.extend({ wmod: 'transparent' },options.createOptions || {}); var _flash = new baidu.flash._Base(options, [ 'selectFile', 'exceedMaxSize', 'deleteFile', 'uploadStart', 'uploadComplete', 'uploadError', 'uploadProgress' ]); _flash.call('setMaxNum', options.maxNum ? [options.maxNum] : [1]); /** * 设置当鼠标移动到flash上时,是否变成手型 * @public * @param {Boolean} isCursor * @return {Null} */ me.setHandCursor = function(isCursor){ _flash.call('setHandCursor', [isCursor || false]); }; /** * 设置鼠标相应函数名 * @param {String|Function} fun */ me.setMSFunName = function(fun){ _flash.call('setMSFunName',[_flash.createFunName(fun)]); }; /** * 执行上传操作 * @param {String} url 上传的url * @param {String} fieldName 上传的表单字段名 * @param {Object} postData 键值对,上传的POST数据 * @param {Number|Array|null|-1} [index]上传的文件序列 * Int值上传该文件 * Array一次串行上传该序列文件 * -1/null上传所有文件 * @return {Null} */ me.upload = function(url, fieldName, postData, index){ if(typeof url !== 'string' || typeof fieldName !== 'string') return null; if(typeof index === 'undefined') index = -1; _flash.call('upload', [url, fieldName, postData, index]); }; /** * 取消上传操作 * @public * @param {Number|-1} index */ me.cancel = function(index){ if(typeof index === 'undefined') index = -1; _flash.call('cancel', [index]); }; /** * 删除文件 * @public * @param {Number|Array} [index] 要删除的index,不传则全部删除 * @param {Function} callBack * @param * */ me.deleteFile = function(index, callBack){ var callBackAll = function(list){ callBack && callBack(list); }; if(typeof index === 'undefined'){ _flash.call('deleteFilesAll', [], callBackAll); return; }; if(typeof index === 'Number') index = [index]; index.sort(function(a,b){ return b-a; }); baidu.each(index, function(item){ _flash.call('deleteFileBy', item, callBackAll); }); }; /** * 添加文件类型,支持macType * @public * @param {Object|Array[Object]} type {description:String, extention:String} * @return {Null}; */ me.addFileType = function(type){ var type = type || [[]]; if(type instanceof Array) type = [type]; else type = [[type]]; _flash.call('addFileTypes', type); }; /** * 设置文件类型,支持macType * @public * @param {Object|Array[Object]} type {description:String, extention:String} * @return {Null}; */ me.setFileType = function(type){ var type = type || [[]]; if(type instanceof Array) type = [type]; else type = [[type]]; _flash.call('setFileTypes', type); }; /** * 设置可选文件的数量限制 * @public * @param {Number} num * @return {Null} */ me.setMaxNum = function(num){ _flash.call('setMaxNum', [num]); }; /** * 设置可选文件大小限制,以兆M为单位 * @public * @param {Number} num,0为无限制 * @return {Null} */ me.setMaxSize = function(num){ _flash.call('setMaxSize', [num]); }; /** * @public */ me.getFileAll = function(callBack){ _flash.call('getFileAll', [], callBack); }; /** * @public * @param {Number} index * @param {Function} [callBack] */ me.getFileByIndex = function(index, callBack){ _flash.call('getFileByIndex', [], callBack); }; /** * @public * @param {Number} index * @param {function} [callBack] */ me.getStatusByIndex = function(index, callBack){ _flash.call('getStatusByIndex', [], callBack); }; }; /** * 使用动态script标签请求服务器资源,包括由服务器端的回调和浏览器端的回调 * @namespace baidu.sio */ baidu.sio = baidu.sio || {}; /** * * @param {HTMLElement} src script节点 * @param {String} url script节点的地址 * @param {String} [charset] 编码 */ baidu.sio._createScriptTag = function(scr, url, charset){ scr.setAttribute('type', 'text/javascript'); charset && scr.setAttribute('charset', charset); scr.setAttribute('src', url); document.getElementsByTagName('head')[0].appendChild(scr); }; /** * 删除script的属性,再删除script标签,以解决修复内存泄漏的问题 * * @param {HTMLElement} src script节点 */ baidu.sio._removeScriptTag = function(scr){ if (scr.clearAttributes) { scr.clearAttributes(); } else { for (var attr in scr) { if (scr.hasOwnProperty(attr)) { delete scr[attr]; } } } if(scr && scr.parentNode){ scr.parentNode.removeChild(scr); } scr = null; }; /** * 通过script标签加载数据,加载完成由浏览器端触发回调 * @name baidu.sio.callByBrowser * @function * @grammar baidu.sio.callByBrowser(url, opt_callback, opt_options) * @param {string} url 加载数据的url * @param {Function|string} opt_callback 数据加载结束时调用的函数或函数名 * @param {Object} opt_options 其他可选项 * @config {String} [charset] script的字符集 * @config {Integer} [timeOut] 超时时间,超过这个时间将不再响应本请求,并触发onfailure函数 * @config {Function} [onfailure] timeOut设定后才生效,到达超时时间时触发本函数 * @remark * 1、与callByServer不同,callback参数只支持Function类型,不支持string。 * 2、如果请求了一个不存在的页面,callback函数在IE/opera下也会被调用,因此使用者需要在onsuccess函数中判断数据是否正确加载。 * @meta standard * @see baidu.sio.callByServer */ baidu.sio.callByBrowser = function (url, opt_callback, opt_options) { var scr = document.createElement("SCRIPT"), scriptLoaded = 0, options = opt_options || {}, charset = options['charset'], callback = opt_callback || function(){}, timeOut = options['timeOut'] || 0, timer; scr.onload = scr.onreadystatechange = function () { if (scriptLoaded) { return; } var readyState = scr.readyState; if ('undefined' == typeof readyState || readyState == "loaded" || readyState == "complete") { scriptLoaded = 1; try { callback(); clearTimeout(timer); } finally { scr.onload = scr.onreadystatechange = null; baidu.sio._removeScriptTag(scr); } } }; if( timeOut ){ timer = setTimeout(function(){ scr.onload = scr.onreadystatechange = null; baidu.sio._removeScriptTag(scr); options.onfailure && options.onfailure(); }, timeOut); } baidu.sio._createScriptTag(scr, url, charset); }; /** * 通过script标签加载数据,加载完成由服务器端触发回调 * @name baidu.sio.callByServer * @function * @grammar baidu.sio.callByServer(url, callback[, opt_options]) * @param {string} url 加载数据的url. * @param {Function|string} callback 服务器端调用的函数或函数名。如果没有指定本参数,将在URL中寻找options['queryField']做为callback的方法名. * @param {Object} opt_options 加载数据时的选项. * @config {string} [charset] script的字符集 * @config {string} [queryField] 服务器端callback请求字段名,默认为callback * @config {Integer} [timeOut] 超时时间(单位:ms),超过这个时间将不再响应本请求,并触发onfailure函数 * @config {Function} [onfailure] timeOut设定后才生效,到达超时时间时触发本函数 * @remark * 如果url中已经包含key为“options['queryField']”的query项,将会被替换成callback中参数传递或自动生成的函数名。 * @meta standard * @see baidu.sio.callByBrowser */ baidu.sio.callByServer = /**@function*/function(url, callback, opt_options) { var scr = document.createElement('SCRIPT'), prefix = 'bd__cbs__', callbackName, callbackImpl, options = opt_options || {}, charset = options['charset'], queryField = options['queryField'] || 'callback', timeOut = options['timeOut'] || 0, timer, reg = new RegExp('(\\?|&)' + queryField + '=([^&]*)'), matches; if (baidu.lang.isFunction(callback)) { callbackName = prefix + Math.floor(Math.random() * 2147483648).toString(36); window[callbackName] = getCallBack(0); } else if(baidu.lang.isString(callback)){ callbackName = callback; } else { if (matches = reg.exec(url)) { callbackName = matches[2]; } } if( timeOut ){ timer = setTimeout(getCallBack(1), timeOut); } url = url.replace(reg, '\x241' + queryField + '=' + callbackName); if (url.search(reg) < 0) { url += (url.indexOf('?') < 0 ? '?' : '&') + queryField + '=' + callbackName; } baidu.sio._createScriptTag(scr, url, charset); /* * 返回一个函数,用于立即(挂在window上)或者超时(挂在setTimeout中)时执行 */ function getCallBack(onTimeOut){ /*global callbackName, callback, scr, options;*/ return function(){ try { if( onTimeOut ){ options.onfailure && options.onfailure(); }else{ callback.apply(window, arguments); clearTimeout(timer); } window[callbackName] = null; delete window[callbackName]; } catch (exception) { } finally { baidu.sio._removeScriptTag(scr); } } } }; /** * 通过请求一个图片的方式令服务器存储一条日志 * @function * @grammar baidu.sio.log(url) * @param {string} url 要发送的地址. * @author: int08h,leeight */ baidu.sio.log = function(url) { var img = new Image(), key = 'tangram_sio_log_' + Math.floor(Math.random() * 2147483648).toString(36); window[key] = img; img.onload = img.onerror = img.onabort = function() { img.onload = img.onerror = img.onabort = null; window[key] = null; img = null; }; img.src = url; };
JavaScript
/** * Created by JetBrains PhpStorm. * User: taoqili * Date: 12-2-10 * Time: 下午3:50 * To change this template use File | Settings | File Templates. */ //文件类型图标索引 var fileTypeMaps = { ".rar":"icon_rar.gif", ".zip":"icon_rar.gif", ".doc":"icon_doc.gif", ".docx":"icon_doc.gif", ".pdf":"icon_pdf.gif", ".mp3":"icon_mp3.gif", ".xls":"icon_xls.gif", ".chm":"icon_chm.gif", ".ppt":"icon_ppt.gif", ".pptx":"icon_ppt.gif", ".avi":"icon_mv.gif", ".rmvb":"icon_mv.gif", ".wmv":"icon_mv.gif", ".flv":"icon_mv.gif", ".swf":"icon_mv.gif", ".rm":"icon_mv.gif", ".exe":"icon_exe.gif", ".psd":"icon_psd.gif", ".txt":"icon_txt.gif" };
JavaScript
/* Demo Note: This demo uses a FileProgress class that handles the UI for displaying the file name and percent complete. The FileProgress class is not part of SWFUpload. */ /* ********************** Event Handlers These are my custom event handlers to make my web application behave the way I went when SWFUpload completes different tasks. These aren't part of the SWFUpload package. They are part of my application. Without these none of the actions SWFUpload makes will show up in my application. ********************** */ function preLoad() { if (!this.support.loading) { alert(lang.flashVersionError); return false; } return true; } function loadFailed() { alert(lang.flashLoadingError); } function fileQueued(file) { try { var progress = new FileProgress(file, this.customSettings.progressTarget); progress.setStatus(lang.fileUploadReady); progress.toggleCancel(true, this,lang.delUploadQueue); } catch (ex) { this.debug(ex); } } function fileQueueError(file, errorCode, message) { try { if (errorCode === SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED) { alert(lang.limitPrompt1+ message + lang.limitPrompt2); return; } var progress = new FileProgress(file, this.customSettings.progressTarget); progress.setError(); progress.toggleCancel(true, this,lang.delFailFile); switch (errorCode) { case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT: progress.setStatus(lang.fileSizeLimit); this.debug("Error Code: File too big, File name: " + file.name + ", File size: " + file.size + ", Message: " + message); break; case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE: progress.setStatus(lang.emptyFile); this.debug("Error Code: Zero byte file, File name: " + file.name + ", File size: " + file.size + ", Message: " + message); break; case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE: progress.setStatus(lang.fileTypeError); this.debug("Error Code: Invalid File Type, File name: " + file.name + ", File size: " + file.size + ", Message: " + message); break; default: if (file !== null) { progress.setStatus(lang.unknownError); } this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message); break; } } catch (ex) { this.debug(ex); } } function uploadStart(file) { try { /* I don't want to do any file validation or anything, I'll just update the UI and return true to indicate that the upload should start. It's important to update the UI here because in Linux no uploadProgress events are called. The best we can do is say we are uploading. */ var progress = new FileProgress(file, this.customSettings.progressTarget); progress.setStatus(lang.fileUploading); progress.toggleCancel(true, this,lang.cancelUpload); }catch (ex) {} return true; } function uploadProgress(file, bytesLoaded, bytesTotal) { try { var percent = Math.ceil((bytesLoaded / bytesTotal) * 100); var progress = new FileProgress(file, this.customSettings.progressTarget); progress.setProgress(percent); progress.setStatus(lang.fileUploading); } catch (ex) { this.debug(ex); } } function uploadError(file, errorCode, message) { try { var progress = new FileProgress(file, this.customSettings.progressTarget); progress.setError(); //progress.toggleCancel(false); switch (errorCode) { case SWFUpload.UPLOAD_ERROR.HTTP_ERROR: progress.setStatus(lang.netError + message); this.debug("Error Code: HTTP Error, File name: " + file.name + ", Message: " + message); break; case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED: progress.setStatus(lang.failUpload); this.debug("Error Code: Upload Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message); break; case SWFUpload.UPLOAD_ERROR.IO_ERROR: progress.setStatus(lang.serverIOError); this.debug("Error Code: IO Error, File name: " + file.name + ", Message: " + message); break; case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR: progress.setStatus(lang.noAuthority); this.debug("Error Code: Security Error, File name: " + file.name + ", Message: " + message); break; case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED: progress.setStatus(lang.fileNumLimit); this.debug("Error Code: Upload Limit Exceeded, File name: " + file.name + ", File size: " + file.size + ", Message: " + message); break; case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED: progress.setStatus(lang.failCheck); this.debug("Error Code: File Validation Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message); break; case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED: // If there aren't any files left (they were all cancelled) disable the cancel button // if (this.getStats().files_queued === 0) { // document.getElementById(this.customSettings.cancelButtonId).disabled = true; // } progress.setStatus(lang.fileCanceling); progress.setCancelled(); break; case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED: progress.setStatus(lang.stopUploading); break; default: progress.setStatus(lang.unknownError + errorCode); this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message); break; } } catch (ex) { this.debug(ex); } } function uploadComplete(file) { //alert(file); // if (this.getStats().files_queued === 0) { // document.getElementById(this.customSettings.cancelButtonId).disabled = true; // } } // This event comes from the Queue Plugin function queueComplete(numFilesUploaded) { var status = document.getElementById("divStatus"); var num = status.innerHTML.match(/\d+/g); status.innerHTML = ((num && num[0] ?parseInt(num[0]):0) + numFilesUploaded) +lang.statusPrompt; }
JavaScript
(function () { var parent = window.parent; //dialog对象 dialog = parent.$EDITORUI[window.frameElement.id.replace( /_iframe$/, '' )]; //当前打开dialog的编辑器实例 editor = dialog.editor; UE = parent.UE; domUtils = UE.dom.domUtils; utils = UE.utils; browser = UE.browser; ajax = UE.ajax; $G = function ( id ) { return document.getElementById( id ) }; //focus元素 $focus = function ( node ) { setTimeout( function () { if ( browser.ie ) { var r = node.createTextRange(); r.collapse( false ); r.select(); } else { node.focus() } }, 0 ) }; utils.loadFile(document,{ href:editor.options.themePath + editor.options.theme + "/dialogbase.css?cache="+Math.random(), tag:"link", type:"text/css", rel:"stylesheet" }); lang = editor.getLang(dialog.className.split( "-" )[2]); domUtils.on(window,'load',function () { var langImgPath = editor.options.langPath + editor.options.lang + "/images/"; //针对静态资源 for ( var i in lang["static"] ) { var dom = $G( i ); if(!dom) continue; var tagName = dom.tagName, content = lang["static"][i]; if(content.src){ //clone content = utils.extend({},content,false); content.src = langImgPath + content.src; } if(content.style){ content = utils.extend({},content,false); content.style = content.style.replace(/url\s*\(/g,"url(" + langImgPath) } switch ( tagName.toLowerCase() ) { case "var": dom.parentNode.replaceChild( document.createTextNode( content ), dom ); break; case "select": var ops = dom.options; for ( var j = 0, oj; oj = ops[j]; ) { oj.innerHTML = content.options[j++]; } for ( var p in content ) { p != "options" && dom.setAttribute( p, content[p] ); } break; default : domUtils.setAttributes( dom, content); } } } ); })();
JavaScript
window.onload = function () { editor.setOpt({ emotionLocalization:false }); emotion.SmileyPath = editor.options.emotionLocalization === true ? 'images/' : "http://img.baidu.com/hi/"; emotion.SmileyBox = createTabList( emotion.tabNum ); emotion.tabExist = createArr( emotion.tabNum ); initImgName(); initEvtHandler( "tabHeads" ); }; function initImgName() { for ( var pro in emotion.SmilmgName ) { var tempName = emotion.SmilmgName[pro], tempBox = emotion.SmileyBox[pro], tempStr = ""; if ( tempBox.length ) return; for ( var i = 1; i <= tempName[1]; i++ ) { tempStr = tempName[0]; if ( i < 10 ) tempStr = tempStr + '0'; tempStr = tempStr + i + '.gif'; tempBox.push( tempStr ); } } } function initEvtHandler( conId ) { var tabHeads = $G( conId ); for ( var i = 0, j = 0; i < tabHeads.childNodes.length; i++ ) { var tabObj = tabHeads.childNodes[i]; if ( tabObj.nodeType == 1 ) { domUtils.on( tabObj, "click", (function ( index ) { return function () { switchTab( index ); }; })( j ) ); j++; } } switchTab( 0 ); $G( "tabIconReview" ).style.display = 'none'; } function InsertSmiley( url, evt ) { var obj = { src:editor.options.emotionLocalization ? editor.options.UEDITOR_HOME_URL + "dialogs/emotion/" + url : url }; obj._src = obj.src; editor.execCommand( 'insertimage', obj ); if ( !evt.ctrlKey ) { dialog.popup.hide(); } } function switchTab( index ) { autoHeight( index ); if ( emotion.tabExist[index] == 0 ) { emotion.tabExist[index] = 1; createTab( 'tab' + index ); } //获取呈现元素句柄数组 var tabHeads = $G( "tabHeads" ).getElementsByTagName( "span" ), tabBodys = $G( "tabBodys" ).getElementsByTagName( "div" ), i = 0, L = tabHeads.length; //隐藏所有呈现元素 for ( ; i < L; i++ ) { tabHeads[i].className = ""; tabBodys[i].style.display = "none"; } //显示对应呈现元素 tabHeads[index].className = "focus"; tabBodys[index].style.display = "block"; } function autoHeight( index ) { var iframe = dialog.getDom( "iframe" ), parent = iframe.parentNode.parentNode; switch ( index ) { case 0: iframe.style.height = "380px"; parent.style.height = "392px"; break; case 1: iframe.style.height = "220px"; parent.style.height = "232px"; break; case 2: iframe.style.height = "260px"; parent.style.height = "272px"; break; case 3: iframe.style.height = "300px"; parent.style.height = "312px"; break; case 4: iframe.style.height = "140px"; parent.style.height = "152px"; break; case 5: iframe.style.height = "260px"; parent.style.height = "272px"; break; case 6: iframe.style.height = "230px"; parent.style.height = "242px"; break; default: } } function createTab( tabName ) { var faceVersion = "?v=1.1", //版本号 tab = $G( tabName ), //获取将要生成的Div句柄 imagePath = emotion.SmileyPath + emotion.imageFolders[tabName], //获取显示表情和预览表情的路径 positionLine = 11 / 2, //中间数 iWidth = iHeight = 35, //图片长宽 iColWidth = 3, //表格剩余空间的显示比例 tableCss = emotion.imageCss[tabName], cssOffset = emotion.imageCssOffset[tabName], textHTML = ['<table class="smileytable">'], i = 0, imgNum = emotion.SmileyBox[tabName].length, imgColNum = 11, faceImage, sUrl, realUrl, posflag, offset, infor; for ( ; i < imgNum; ) { textHTML.push( '<tr>' ); for ( var j = 0; j < imgColNum; j++, i++ ) { faceImage = emotion.SmileyBox[tabName][i]; if ( faceImage ) { sUrl = imagePath + faceImage + faceVersion; realUrl = imagePath + faceImage; posflag = j < positionLine ? 0 : 1; offset = cssOffset * i * (-1) - 1; infor = emotion.SmileyInfor[tabName][i]; textHTML.push( '<td class="' + tableCss + '" border="1" width="' + iColWidth + '%" style="border-collapse:collapse;" align="center" bgcolor="transparent" onclick="InsertSmiley(\'' + realUrl.replace( /'/g, "\\'" ) + '\',event)" onmouseover="over(this,\'' + sUrl + '\',\'' + posflag + '\')" onmouseout="out(this)">' ); textHTML.push( '<span>' ); textHTML.push( '<img style="background-position:left ' + offset + 'px;" title="' + infor + '" src="' + emotion.SmileyPath + (editor.options.emotionLocalization ? '0.gif" width="' : 'default/0.gif" width="') + iWidth + '" height="' + iHeight + '"></img>' ); textHTML.push( '</span>' ); } else { textHTML.push( '<td width="' + iColWidth + '%" bgcolor="#FFFFFF">' ); } textHTML.push( '</td>' ); } textHTML.push( '</tr>' ); } textHTML.push( '</table>' ); textHTML = textHTML.join( "" ); tab.innerHTML = textHTML; } function over( td, srcPath, posFlag ) { td.style.backgroundColor = "#ACCD3C"; $G( 'faceReview' ).style.backgroundImage = "url(" + srcPath + ")"; if ( posFlag == 1 ) $G( "tabIconReview" ).className = "show"; $G( "tabIconReview" ).style.display = 'block'; } function out( td ) { td.style.backgroundColor = "transparent"; var tabIconRevew = $G( "tabIconReview" ); tabIconRevew.className = ""; tabIconRevew.style.display = 'none'; } function createTabList( tabNum ) { var obj = {}; for ( var i = 0; i < tabNum; i++ ) { obj["tab" + i] = []; } return obj; } function createArr( tabNum ) { var arr = []; for ( var i = 0; i < tabNum; i++ ) { arr[i] = 0; } return arr; }
JavaScript
/** * Created with JetBrains PhpStorm. * User: xuheng * Date: 12-12-19 * Time: 下午4:55 * To change this template use File | Settings | File Templates. */ (function () { var title = $G("J_title"), caption = $G("J_caption"), sorttable = $G("J_sorttable"), autoSizeContent = $G("J_autoSizeContent"), autoSizePage = $G("J_autoSizePage"), tone = $G("J_tone"), me, preview = $G("J_preview"); var editTable = function () { me = this; me.init(); }; editTable.prototype = { init:function () { var colorPiker = new UE.ui.ColorPicker({ editor:editor }), colorPop = new UE.ui.Popup({ editor:editor, content:colorPiker }); title.checked = editor.queryCommandState("inserttitle") == -1; caption.checked = editor.queryCommandState("insertcaption") == -1; me.createTable(title.checked, caption.checked); me.setAutoSize(); me.setColor(me.getColor()); domUtils.on(title, "click", me.titleHanler); domUtils.on(caption, "click", me.captionHanler); domUtils.on(sorttable, "click", me.sorttableHanler); domUtils.on(autoSizeContent, "click", me.autoSizeContentHanler); domUtils.on(autoSizePage, "click", me.autoSizePageHanler); domUtils.on(tone, "click", function () { colorPop.showAnchor(tone); }); domUtils.on(document, 'mousedown', function () { colorPop.hide(); }); colorPiker.addListener("pickcolor", function () { me.setColor(arguments[1]); colorPop.hide(); }); colorPiker.addListener("picknocolor", function () { me.setColor(""); colorPop.hide(); }); }, createTable:function (hasTitle, hasCaption) { var arr = []; arr.push("<table id='J_example'>"); if (hasCaption) { arr.push("<caption>" + lang.captionName + "</caption>") } if (hasTitle) { arr.push("<tr>"); for (var j = 0; j < 5; j++) { arr.push("<th>" + lang.titleName + "</th>") } arr.push("</tr>"); } for (var i = 0; i < 6; i++) { arr.push("<tr>"); for (var k = 0; k < 5; k++) { arr.push("<td>" + lang.cellsName + "</td>") } arr.push("</tr>"); } arr.push("</table>"); preview.innerHTML = arr.join(""); }, titleHanler:function () { var example = $G("J_example"), frg=document.createDocumentFragment(), color = domUtils.getComputedStyle(domUtils.getElementsByTagName(example, "td")[0], "border-color"); if (title.checked) { example.insertRow(0); for (var i = 0, node; i < 5; i++) { node = document.createElement("th"); node.innerHTML = lang.titleName; frg.appendChild(node); } example.rows[0].appendChild(frg); } else { domUtils.remove(example.rows[0]); } me.setColor(color); }, captionHanler:function () { var example = $G("J_example"); if (caption.checked) { var row = document.createElement('caption'); row.innerHTML = lang.captionName; example.insertBefore(row, example.firstChild); } else { domUtils.remove(domUtils.getElementsByTagName(example, 'caption')[0]); } }, sorttableHanler:function(){ var example = $G("J_example"), row = example.rows[0]; if (sorttable.checked) { for(var i = 0,cell;cell = row.cells[i++];){ var span = document.createElement("span"); span.innerHTML = "^"; cell.appendChild(span); } } else { var spans = domUtils.getElementsByTagName(example,"span"); utils.each(spans,function(span){ span.parentNode.removeChild(span); }) } }, autoSizeContentHanler:function () { var example = $G("J_example"); example.removeAttribute("width"); }, autoSizePageHanler:function () { var example = $G("J_example"); var tds = example.getElementsByTagName(example, "td"); utils.each(tds, function (td) { td.removeAttribute("width"); }); example.setAttribute('width', '100%'); }, getColor:function () { var start = editor.selection.getStart(), color, cell = domUtils.findParentByTagName(start, ["td", "th", "caption"], true); color = domUtils.getComputedStyle(cell, "border-color"); if (!color) color = "#DDDDDD"; return color; }, setColor:function (color) { var example = $G("J_example"), arr = domUtils.getElementsByTagName(example, "td").concat( domUtils.getElementsByTagName(example, "th"), domUtils.getElementsByTagName(example, "caption") ); tone.value = color; utils.each(arr, function (node) { node.style.borderColor = color; }); }, setAutoSize:function () { var me = this; autoSizePage.checked = true; me.autoSizePageHanler(); } }; new editTable; dialog.onok = function () { editor.__hasEnterExecCommand = true; var checks = { title:"inserttitle deletetitle", caption:"insertcaption deletecaption", sorttable:"enablesort disablesort" }; editor.fireEvent('saveScene'); for(var i in checks){ var cmds = checks[i].split(" "), input = $G("J_" + i); if(input["checked"]){ editor.queryCommandState(cmds[0])!=-1 &&editor.execCommand(cmds[0]); }else{ editor.queryCommandState(cmds[1])!=-1 &&editor.execCommand(cmds[1]); } } editor.execCommand("edittable", tone.value); autoSizeContent.checked ?editor.execCommand('adaptbytext') : ""; autoSizePage.checked ? editor.execCommand("adaptbywindow") : ""; editor.fireEvent('saveScene'); editor.__hasEnterExecCommand = false; }; })();
JavaScript
function Music() { this.init(); } (function () { var pages = [], panels = [], selectedItem = null; Music.prototype = { total:70, pageSize:10, dataUrl:"http://tingapi.ting.baidu.com/v1/restserver/ting?method=baidu.ting.search.common", playerUrl:"http://box.baidu.com/widget/flash/bdspacesong.swf", init:function () { var me = this; domUtils.on($G("J_searchName"), "keyup", function (event) { var e = window.event || event; if (e.keyCode == 13) { me.dosearch(); } }); domUtils.on($G("J_searchBtn"), "click", function () { me.dosearch(); }); }, callback:function (data) { var me = this; me.data = data.song_list; setTimeout(function () { $G('J_resultBar').innerHTML = me._renderTemplate(data.song_list); }, 300); }, dosearch:function () { var me = this; selectedItem = null; var key = $G('J_searchName').value; if (utils.trim(key) == "")return false; key = encodeURIComponent(key); me._sent(key); }, doselect:function (i) { var me = this; if (typeof i == 'object') { selectedItem = i; } else if (typeof i == 'number') { selectedItem = me.data[i]; } }, onpageclick:function (id) { var me = this; for (var i = 0; i < pages.length; i++) { $G(pages[i]).className = 'pageoff'; $G(panels[i]).className = 'paneloff'; } $G('page' + id).className = 'pageon'; $G('panel' + id).className = 'panelon'; }, listenTest:function (elem) { var me = this, view = $G('J_preview'), is_play_action = (elem.className == 'm-try'), old_trying = me._getTryingElem(); if (old_trying) { old_trying.className = 'm-try'; view.innerHTML = ''; } if (is_play_action) { elem.className = 'm-trying'; view.innerHTML = me._buildMusicHtml(me._getUrl(true)); } }, _sent:function (param) { var me = this; $G('J_resultBar').innerHTML = '<div class="loading"></div>'; utils.loadFile(document, { src:me.dataUrl + '&query=' + param + '&page_size=' + me.total + '&callback=music.callback()&.r=' + Math.random(), tag:"script", type:"text/javascript", defer:"defer" }); }, _removeHtml:function (str) { var reg = /<\s*\/?\s*[^>]*\s*>/gi; return str.replace(reg, ""); }, _getUrl:function (isTryListen) { var me = this; var param = 'from=tiebasongwidget&url=&name=' + encodeURIComponent(me._removeHtml(selectedItem.title)) + '&artist=' + encodeURIComponent(me._removeHtml(selectedItem.author)) + '&extra=' + encodeURIComponent(me._removeHtml(selectedItem.album_title)) + '&autoPlay='+isTryListen+'' + '&loop=true'; return me.playerUrl + "?" + param; }, _getTryingElem:function () { var s = $G('J_listPanel').getElementsByTagName('span'); for (var i = 0; i < s.length; i++) { if (s[i].className == 'm-trying') return s[i]; } return null; }, _buildMusicHtml:function (playerUrl) { var html = '<embed class="BDE_try_Music" allowfullscreen="false" pluginspage="http://www.macromedia.com/go/getflashplayer"'; html += ' src="' + playerUrl + '"'; html += ' width="1" height="1" style="position:absolute;left:-2000px;"'; html += ' type="application/x-shockwave-flash" wmode="transparent" play="true" loop="false"'; html += ' menu="false" allowscriptaccess="never" scale="noborder">'; return html; }, _byteLength:function (str) { return str.replace(/[^\u0000-\u007f]/g, "\u0061\u0061").length; }, _getMaxText:function (s) { var me = this; s = me._removeHtml(s); if (me._byteLength(s) > 12) return s.substring(0, 5) + '...'; if (!s) s = "&nbsp;"; return s; }, _rebuildData:function (data) { var me = this, newData = [], d = me.pageSize, itembox; for (var i = 0; i < data.length; i++) { if ((i + d) % d == 0) { itembox = []; newData.push(itembox) } itembox.push(data[i]); } return newData; }, _renderTemplate:function (data) { var me = this; if (data.length == 0)return '<div class="empty">' + lang.emptyTxt + '</div>'; data = me._rebuildData(data); var s = [], p = [], t = []; s.push('<div id="J_listPanel" class="listPanel">'); p.push('<div class="page">'); for (var i = 0, tmpList; tmpList = data[i++];) { panels.push('panel' + i); pages.push('page' + i); if (i == 1) { s.push('<div id="panel' + i + '" class="panelon">'); if (data.length != 1) { t.push('<div id="page' + i + '" onclick="music.onpageclick(' + i + ')" class="pageon">' + (i ) + '</div>'); } } else { s.push('<div id="panel' + i + '" class="paneloff">'); t.push('<div id="page' + i + '" onclick="music.onpageclick(' + i + ')" class="pageoff">' + (i ) + '</div>'); } s.push('<div class="m-box">'); s.push('<div class="m-h"><span class="m-t">' + lang.chapter + '</span><span class="m-s">' + lang.singer + '</span><span class="m-z">' + lang.special + '</span><span class="m-try-t">' + lang.listenTest + '</span></div>'); for (var j = 0, tmpObj; tmpObj = tmpList[j++];) { s.push('<label for="radio-' + i + '-' + j + '" class="m-m">'); s.push('<input type="radio" id="radio-' + i + '-' + j + '" name="musicId" class="m-l" onclick="music.doselect(' + (me.pageSize * (i-1) + (j-1)) + ')"/>'); s.push('<span class="m-t">' + me._getMaxText(tmpObj.title) + '</span>'); s.push('<span class="m-s">' + me._getMaxText(tmpObj.author) + '</span>'); s.push('<span class="m-z">' + me._getMaxText(tmpObj.album_title) + '</span>'); s.push('<span class="m-try" onclick="music.doselect(' + (me.pageSize * (i-1) + (j-1)) + ');music.listenTest(this)"></span>'); s.push('</label>'); } s.push('</div>'); s.push('</div>'); } t.reverse(); p.push(t.join('')); s.push('</div>'); p.push('</div>'); return s.join('') + p.join(''); }, exec:function () { var me = this; if (selectedItem == null) return; $G('J_preview').innerHTML = ""; editor.execCommand('music', { url:me._getUrl(false), width:400, height:95 }); } }; })();
JavaScript