code stringlengths 1 2.08M | language stringclasses 1 value |
|---|---|
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
(function()
{
function setupAdvParams( element )
{
var attrName = this.att;
var value = element && element.hasAttribute( attrName ) && element.getAttribute( attrName ) || '';
if ( value !== undefined )
this.setValue( value );
}
function commitAdvParams()
{
// Dialogs may use different parameters in the commit list, so, by
// definition, we take the first CKEDITOR.dom.element available.
var element;
for ( var i = 0 ; i < arguments.length ; i++ )
{
if ( arguments[ i ] instanceof CKEDITOR.dom.element )
{
element = arguments[ i ];
break;
}
}
if ( element )
{
var attrName = this.att,
value = this.getValue();
// Broadcast Lang Dir change
if ( attrName == 'dir' )
{
var dir = element.getAttribute( attrName );
if ( dir != value && element.getParent() )
this._.dialog._.editor.fire( 'dirChanged', { node : element, dir : value || element.getDirection( 1 ) } );
}
if ( value )
element.setAttribute( attrName, value );
else
element.removeAttribute( attrName, value );
}
}
CKEDITOR.plugins.add( 'dialogadvtab',
{
/**
*
* @param tabConfig
* id, dir, classes, styles
*/
createAdvancedTab : function( editor, tabConfig )
{
if ( !tabConfig )
tabConfig = { id:1, dir:1, classes:1, styles:1 };
var lang = editor.lang.common;
var result =
{
id : 'advanced',
label : lang.advancedTab,
title : lang.advancedTab,
elements :
[
{
type : 'vbox',
padding : 1,
children : []
}
]
};
var contents = [];
if ( tabConfig.id || tabConfig.dir )
{
if ( tabConfig.id )
{
contents.push(
{
id : 'advId',
att : 'id',
type : 'text',
label : lang.id,
setup : setupAdvParams,
commit : commitAdvParams
});
}
if ( tabConfig.dir )
{
contents.push(
{
id : 'advLangDir',
att : 'dir',
type : 'select',
label : lang.langDir,
'default' : '',
style : 'width:100%',
items :
[
[ lang.notSet, '' ],
[ lang.langDirLTR, 'ltr' ],
[ lang.langDirRTL, 'rtl' ]
],
setup : setupAdvParams,
commit : commitAdvParams
});
}
result.elements[ 0 ].children.push(
{
type : 'hbox',
widths : [ '50%', '50%' ],
children : [].concat( contents )
});
}
if ( tabConfig.styles || tabConfig.classes )
{
contents = [];
if ( tabConfig.styles )
{
contents.push(
{
id : 'advStyles',
att : 'style',
type : 'text',
label : lang.styles,
'default' : '',
getStyle : function( name, defaultValue )
{
var match = this.getValue().match( new RegExp( name + '\\s*:\s*([^;]*)', 'i') );
return match ? match[ 1 ] : defaultValue;
},
updateStyle : function( name, value )
{
var styles = this.getValue();
// Remove the current value.
if ( styles )
{
styles = styles
.replace( new RegExp( '\\s*' + name + '\s*:[^;]*(?:$|;\s*)', 'i' ), '' )
.replace( /^[;\s]+/, '' )
.replace( /\s+$/, '' );
}
if ( value )
{
styles && !(/;\s*$/).test( styles ) && ( styles += '; ' );
styles += name + ': ' + value;
}
this.setValue( styles, 1 );
},
setup : setupAdvParams,
commit : commitAdvParams
});
}
if ( tabConfig.classes )
{
contents.push(
{
type : 'hbox',
widths : [ '45%', '55%' ],
children :
[
{
id : 'advCSSClasses',
att : 'class',
type : 'text',
label : lang.cssClasses,
'default' : '',
setup : setupAdvParams,
commit : commitAdvParams
}
]
});
}
result.elements[ 0 ].children.push(
{
type : 'hbox',
widths : [ '50%', '50%' ],
children : [].concat( contents )
});
}
return result;
}
});
})();
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
(function()
{
var guardElements = { table:1, tbody: 1, ul:1, ol:1, blockquote:1, div:1, tr: 1 },
directSelectionGuardElements = {},
// All guard elements which can have a direction applied on them.
allGuardElements = {};
CKEDITOR.tools.extend( directSelectionGuardElements, guardElements, { tr:1, p:1, div:1, li:1 } );
CKEDITOR.tools.extend( allGuardElements, directSelectionGuardElements, { td:1 } );
function onSelectionChange( e )
{
setToolbarStates( e );
handleMixedDirContent( e );
}
function setToolbarStates( evt )
{
var editor = evt.editor,
path = evt.data.path;
var useComputedState = editor.config.useComputedState,
selectedElement;
useComputedState = useComputedState === undefined || useComputedState;
// We can use computedState provided by the browser or traverse parents manually.
if ( !useComputedState )
selectedElement = getElementForDirection( path.lastElement );
selectedElement = selectedElement || path.block || path.blockLimit;
if ( !selectedElement || selectedElement.getName() == 'body' )
return;
var selectionDir = useComputedState ?
selectedElement.getComputedStyle( 'direction' ) :
selectedElement.getStyle( 'direction' ) || selectedElement.getAttribute( 'dir' );
editor.getCommand( 'bidirtl' ).setState( selectionDir == 'rtl' ? CKEDITOR.TRISTATE_ON : CKEDITOR.TRISTATE_OFF );
editor.getCommand( 'bidiltr' ).setState( selectionDir == 'ltr' ? CKEDITOR.TRISTATE_ON : CKEDITOR.TRISTATE_OFF );
}
function handleMixedDirContent( evt )
{
var editor = evt.editor,
chromeRoot = editor.container.getChild( 1 ),
directionNode = evt.data.path.block || evt.data.path.blockLimit;
if ( directionNode && editor.lang.dir != directionNode.getComputedStyle( 'direction' ) )
chromeRoot.addClass( 'cke_mixed_dir_content' );
else
chromeRoot.removeClass( 'cke_mixed_dir_content' );
}
/**
* Returns element with possibility of applying the direction.
* @param node
*/
function getElementForDirection( node )
{
while ( node && !( node.getName() in allGuardElements || node.is( 'body' ) ) )
{
var parent = node.getParent();
if ( !parent )
break;
node = parent;
}
return node;
}
function switchDir( element, dir, editor, database )
{
// Mark this element as processed by switchDir.
CKEDITOR.dom.element.setMarker( database, element, 'bidi_processed', 1 );
// Check whether one of the ancestors has already been styled.
var parent = element;
while ( ( parent = parent.getParent() ) && !parent.is( 'body' ) )
{
if ( parent.getCustomData( 'bidi_processed' ) )
{
// Ancestor style must dominate.
element.removeStyle( 'direction' );
element.removeAttribute( 'dir' );
return null;
}
}
var useComputedState = ( 'useComputedState' in editor.config ) ? editor.config.useComputedState : 1;
var elementDir = useComputedState ? element.getComputedStyle( 'direction' )
: element.getStyle( 'direction' ) || element.hasAttribute( 'dir' );
// Stop if direction is same as present.
if ( elementDir == dir )
return null;
// Reuse computedState if we already have it.
var dirBefore = useComputedState ? elementDir : element.getComputedStyle( 'direction' );
// Clear direction on this element.
element.removeStyle( 'direction' );
// Do the second check when computed state is ON, to check
// if we need to apply explicit direction on this element.
if ( useComputedState )
{
element.removeAttribute( 'dir' );
if ( dir != element.getComputedStyle( 'direction' ) )
element.setAttribute( 'dir', dir );
}
else
// Set new direction for this element.
element.setAttribute( 'dir', dir );
// If the element direction changed, we need to switch the margins of
// the element and all its children, so it will get really reflected
// like a mirror. (#5910)
if ( dir != dirBefore )
{
editor.fire( 'dirChanged',
{
node : element,
dir : dir
} );
}
editor.forceNextSelectionCheck();
return null;
}
function getFullySelected( range, elements )
{
var ancestor = range.getCommonAncestor( false, true );
range.enlarge( CKEDITOR.ENLARGE_BLOCK_CONTENTS );
if ( range.checkBoundaryOfElement( ancestor, CKEDITOR.START )
&& range.checkBoundaryOfElement( ancestor, CKEDITOR.END ) )
{
var parent;
while ( ancestor && ancestor.type == CKEDITOR.NODE_ELEMENT
&& ( parent = ancestor.getParent() )
&& parent.getChildCount() == 1
&& ( !( ancestor.getName() in elements ) || ( parent.getName() in elements ) )
)
ancestor = parent;
return ancestor.type == CKEDITOR.NODE_ELEMENT
&& ( ancestor.getName() in elements )
&& ancestor;
}
}
function bidiCommand( dir )
{
return function( editor )
{
var selection = editor.getSelection(),
enterMode = editor.config.enterMode,
ranges = selection.getRanges();
if ( ranges && ranges.length )
{
var database = {};
// Creates bookmarks for selection, as we may split some blocks.
var bookmarks = selection.createBookmarks();
var rangeIterator = ranges.createIterator(),
range,
i = 0;
while ( ( range = rangeIterator.getNextRange( 1 ) ) )
{
// Apply do directly selected elements from guardElements.
var selectedElement = range.getEnclosedNode();
// If this is not our element of interest, apply to fully selected elements from guardElements.
if ( !selectedElement || selectedElement
&& !( selectedElement.type == CKEDITOR.NODE_ELEMENT && selectedElement.getName() in directSelectionGuardElements )
)
selectedElement = getFullySelected( range, guardElements );
if ( selectedElement && !selectedElement.isReadOnly() )
switchDir( selectedElement, dir, editor, database );
var iterator,
block;
// Walker searching for guardElements.
var walker = new CKEDITOR.dom.walker( range );
var start = bookmarks[ i ].startNode,
end = bookmarks[ i++ ].endNode;
walker.evaluator = function( node )
{
return !! ( node.type == CKEDITOR.NODE_ELEMENT
&& node.getName() in guardElements
&& !( node.getName() == ( enterMode == CKEDITOR.ENTER_P ) ? 'p' : 'div'
&& node.getParent().type == CKEDITOR.NODE_ELEMENT
&& node.getParent().getName() == 'blockquote' )
// Element must be fully included in the range as well. (#6485).
&& node.getPosition( start ) & CKEDITOR.POSITION_FOLLOWING
&& ( ( node.getPosition( end ) & CKEDITOR.POSITION_PRECEDING + CKEDITOR.POSITION_CONTAINS ) == CKEDITOR.POSITION_PRECEDING ) );
};
while ( ( block = walker.next() ) )
switchDir( block, dir, editor, database );
iterator = range.createIterator();
iterator.enlargeBr = enterMode != CKEDITOR.ENTER_BR;
while ( ( block = iterator.getNextParagraph( enterMode == CKEDITOR.ENTER_P ? 'p' : 'div' ) ) )
!block.isReadOnly() && switchDir( block, dir, editor, database );
}
CKEDITOR.dom.element.clearAllMarkers( database );
editor.forceNextSelectionCheck();
// Restore selection position.
selection.selectBookmarks( bookmarks );
editor.focus();
}
};
}
CKEDITOR.plugins.add( 'bidi',
{
requires : [ 'styles', 'button' ],
init : function( editor )
{
// All buttons use the same code to register. So, to avoid
// duplications, let's use this tool function.
var addButtonCommand = function( buttonName, buttonLabel, commandName, commandExec )
{
editor.addCommand( commandName, new CKEDITOR.command( editor, { exec : commandExec }) );
editor.ui.addButton( buttonName,
{
label : buttonLabel,
command : commandName
});
};
var lang = editor.lang.bidi;
addButtonCommand( 'BidiLtr', lang.ltr, 'bidiltr', bidiCommand( 'ltr' ) );
addButtonCommand( 'BidiRtl', lang.rtl, 'bidirtl', bidiCommand( 'rtl' ) );
editor.on( 'selectionChange', onSelectionChange );
}
});
})();
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @file Increse and decrease indent commands.
*/
(function()
{
var listNodeNames = { ol : 1, ul : 1 };
var isNotWhitespaces = CKEDITOR.dom.walker.whitespaces( true ),
isNotBookmark = CKEDITOR.dom.walker.bookmark( false, true );
function setState( editor, state )
{
editor.getCommand( this.name ).setState( state );
}
function onSelectionChange( evt )
{
var editor = evt.editor;
var elementPath = evt.data.path,
list = elementPath && elementPath.contains( listNodeNames );
if ( list )
return setState.call( this, editor, CKEDITOR.TRISTATE_OFF );
if ( !this.useIndentClasses && this.name == 'indent' )
return setState.call( this, editor, CKEDITOR.TRISTATE_OFF );
var path = evt.data.path,
firstBlock = path.block || path.blockLimit;
if ( !firstBlock )
return setState.call( this, editor, CKEDITOR.TRISTATE_DISABLED );
if ( this.useIndentClasses )
{
var indentClass = firstBlock.$.className.match( this.classNameRegex ),
indentStep = 0;
if ( indentClass )
{
indentClass = indentClass[1];
indentStep = this.indentClassMap[ indentClass ];
}
if ( ( this.name == 'outdent' && !indentStep ) ||
( this.name == 'indent' && indentStep == editor.config.indentClasses.length ) )
return setState.call( this, editor, CKEDITOR.TRISTATE_DISABLED );
return setState.call( this, editor, CKEDITOR.TRISTATE_OFF );
}
else
{
var indent = parseInt( firstBlock.getStyle( getIndentCssProperty( firstBlock ) ), 10 );
if ( isNaN( indent ) )
indent = 0;
if ( indent <= 0 )
return setState.call( this, editor, CKEDITOR.TRISTATE_DISABLED );
return setState.call( this, editor, CKEDITOR.TRISTATE_OFF );
}
}
function indentCommand( editor, name )
{
this.name = name;
this.useIndentClasses = editor.config.indentClasses && editor.config.indentClasses.length > 0;
if ( this.useIndentClasses )
{
this.classNameRegex = new RegExp( '(?:^|\\s+)(' + editor.config.indentClasses.join( '|' ) + ')(?=$|\\s)' );
this.indentClassMap = {};
for ( var i = 0 ; i < editor.config.indentClasses.length ; i++ )
this.indentClassMap[ editor.config.indentClasses[i] ] = i + 1;
}
this.startDisabled = name == 'outdent';
}
// Returns the CSS property to be used for identing a given element.
function getIndentCssProperty( element, dir )
{
return ( dir || element.getComputedStyle( 'direction' ) ) == 'ltr' ? 'margin-left' : 'margin-right';
}
function isListItem( node )
{
return node.type = CKEDITOR.NODE_ELEMENT && node.is( 'li' );
}
indentCommand.prototype = {
exec : function( editor )
{
var self = this, database = {};
function indentList( listNode )
{
// Our starting and ending points of the range might be inside some blocks under a list item...
// So before playing with the iterator, we need to expand the block to include the list items.
var startContainer = range.startContainer,
endContainer = range.endContainer;
while ( startContainer && !startContainer.getParent().equals( listNode ) )
startContainer = startContainer.getParent();
while ( endContainer && !endContainer.getParent().equals( listNode ) )
endContainer = endContainer.getParent();
if ( !startContainer || !endContainer )
return;
// Now we can iterate over the individual items on the same tree depth.
var block = startContainer,
itemsToMove = [],
stopFlag = false;
while ( !stopFlag )
{
if ( block.equals( endContainer ) )
stopFlag = true;
itemsToMove.push( block );
block = block.getNext();
}
if ( itemsToMove.length < 1 )
return;
// Do indent or outdent operations on the array model of the list, not the
// list's DOM tree itself. The array model demands that it knows as much as
// possible about the surrounding lists, we need to feed it the further
// ancestor node that is still a list.
var listParents = listNode.getParents( true );
for ( var i = 0 ; i < listParents.length ; i++ )
{
if ( listParents[i].getName && listNodeNames[ listParents[i].getName() ] )
{
listNode = listParents[i];
break;
}
}
var indentOffset = self.name == 'indent' ? 1 : -1,
startItem = itemsToMove[0],
lastItem = itemsToMove[ itemsToMove.length - 1 ];
// Convert the list DOM tree into a one dimensional array.
var listArray = CKEDITOR.plugins.list.listToArray( listNode, database );
// Apply indenting or outdenting on the array.
var baseIndent = listArray[ lastItem.getCustomData( 'listarray_index' ) ].indent;
for ( i = startItem.getCustomData( 'listarray_index' ); i <= lastItem.getCustomData( 'listarray_index' ); i++ )
{
listArray[ i ].indent += indentOffset;
// Make sure the newly created sublist get a brand-new element of the same type. (#5372)
var listRoot = listArray[ i ].parent;
listArray[ i ].parent = new CKEDITOR.dom.element( listRoot.getName(), listRoot.getDocument() );
}
for ( i = lastItem.getCustomData( 'listarray_index' ) + 1 ;
i < listArray.length && listArray[i].indent > baseIndent ; i++ )
listArray[i].indent += indentOffset;
// Convert the array back to a DOM forest (yes we might have a few subtrees now).
// And replace the old list with the new forest.
var newList = CKEDITOR.plugins.list.arrayToList( listArray, database, null, editor.config.enterMode, listNode.getDirection() );
// Avoid nested <li> after outdent even they're visually same,
// recording them for later refactoring.(#3982)
if ( self.name == 'outdent' )
{
var parentLiElement;
if ( ( parentLiElement = listNode.getParent() ) && parentLiElement.is( 'li' ) )
{
var children = newList.listNode.getChildren(),
pendingLis = [],
count = children.count(),
child;
for ( i = count - 1 ; i >= 0 ; i-- )
{
if ( ( child = children.getItem( i ) ) && child.is && child.is( 'li' ) )
pendingLis.push( child );
}
}
}
if ( newList )
newList.listNode.replace( listNode );
// Move the nested <li> to be appeared after the parent.
if ( pendingLis && pendingLis.length )
{
for ( i = 0; i < pendingLis.length ; i++ )
{
var li = pendingLis[ i ],
followingList = li;
// Nest preceding <ul>/<ol> inside current <li> if any.
while ( ( followingList = followingList.getNext() ) &&
followingList.is &&
followingList.getName() in listNodeNames )
{
// IE requires a filler NBSP for nested list inside empty list item,
// otherwise the list item will be inaccessiable. (#4476)
if ( CKEDITOR.env.ie && !li.getFirst( function( node ){ return isNotWhitespaces( node ) && isNotBookmark( node ); } ) )
li.append( range.document.createText( '\u00a0' ) );
li.append( followingList );
}
li.insertAfter( parentLiElement );
}
}
}
function indentBlock()
{
var iterator = range.createIterator(),
enterMode = editor.config.enterMode;
iterator.enforceRealBlocks = true;
iterator.enlargeBr = enterMode != CKEDITOR.ENTER_BR;
var block;
while ( ( block = iterator.getNextParagraph() ) )
indentElement( block );
}
function indentElement( element, dir )
{
if ( element.getCustomData( 'indent_processed' ) )
return false;
if ( self.useIndentClasses )
{
// Transform current class name to indent step index.
var indentClass = element.$.className.match( self.classNameRegex ),
indentStep = 0;
if ( indentClass )
{
indentClass = indentClass[1];
indentStep = self.indentClassMap[ indentClass ];
}
// Operate on indent step index, transform indent step index back to class
// name.
if ( self.name == 'outdent' )
indentStep--;
else
indentStep++;
if ( indentStep < 0 )
return false;
indentStep = Math.min( indentStep, editor.config.indentClasses.length );
indentStep = Math.max( indentStep, 0 );
element.$.className = CKEDITOR.tools.ltrim( element.$.className.replace( self.classNameRegex, '' ) );
if ( indentStep > 0 )
element.addClass( editor.config.indentClasses[ indentStep - 1 ] );
}
else
{
var indentCssProperty = getIndentCssProperty( element, dir ),
currentOffset = parseInt( element.getStyle( indentCssProperty ), 10 );
if ( isNaN( currentOffset ) )
currentOffset = 0;
var indentOffset = editor.config.indentOffset || 40;
currentOffset += ( self.name == 'indent' ? 1 : -1 ) * indentOffset;
if ( currentOffset < 0 )
return false;
currentOffset = Math.max( currentOffset, 0 );
currentOffset = Math.ceil( currentOffset / indentOffset ) * indentOffset;
element.setStyle( indentCssProperty, currentOffset ? currentOffset + ( editor.config.indentUnit || 'px' ) : '' );
if ( element.getAttribute( 'style' ) === '' )
element.removeAttribute( 'style' );
}
CKEDITOR.dom.element.setMarker( database, element, 'indent_processed', 1 );
return true;
}
var selection = editor.getSelection(),
bookmarks = selection.createBookmarks( 1 ),
ranges = selection && selection.getRanges( 1 ),
range;
var iterator = ranges.createIterator();
while ( ( range = iterator.getNextRange() ) )
{
var rangeRoot = range.getCommonAncestor(),
nearestListBlock = rangeRoot;
while ( nearestListBlock && !( nearestListBlock.type == CKEDITOR.NODE_ELEMENT &&
listNodeNames[ nearestListBlock.getName() ] ) )
nearestListBlock = nearestListBlock.getParent();
// Avoid having selection enclose the entire list. (#6138)
// [<ul><li>...</li></ul>] =><ul><li>[...]</li></ul>
if ( !nearestListBlock )
{
var selectedNode = range.getEnclosedNode();
if ( selectedNode
&& selectedNode.type == CKEDITOR.NODE_ELEMENT
&& selectedNode.getName() in listNodeNames)
{
range.setStartAt( selectedNode, CKEDITOR.POSITION_AFTER_START );
range.setEndAt( selectedNode, CKEDITOR.POSITION_BEFORE_END );
nearestListBlock = selectedNode;
}
}
// Avoid selection anchors under list root.
// <ul>[<li>...</li>]</ul> => <ul><li>[...]</li></ul>
if ( nearestListBlock && range.startContainer.type == CKEDITOR.NODE_ELEMENT
&& range.startContainer.getName() in listNodeNames )
{
var walker = new CKEDITOR.dom.walker( range );
walker.evaluator = isListItem;
range.startContainer = walker.next();
}
if ( nearestListBlock && range.endContainer.type == CKEDITOR.NODE_ELEMENT
&& range.endContainer.getName() in listNodeNames )
{
walker = new CKEDITOR.dom.walker( range );
walker.evaluator = isListItem;
range.endContainer = walker.previous();
}
if ( nearestListBlock )
{
var firstListItem = nearestListBlock.getFirst( isListItem ),
hasMultipleItems = !!firstListItem.getNext( isListItem ),
rangeStart = range.startContainer,
indentWholeList = firstListItem.equals( rangeStart ) || firstListItem.contains( rangeStart );
// Indent the entire list if cursor is inside the first list item. (#3893)
// Only do that for indenting or when using indent classes or when there is something to outdent. (#6141)
if ( !( indentWholeList &&
( self.name == 'indent' || self.useIndentClasses || parseInt( nearestListBlock.getStyle( getIndentCssProperty( nearestListBlock ) ), 10 ) ) &&
indentElement( nearestListBlock, !hasMultipleItems && firstListItem.getDirection() ) ) )
indentList( nearestListBlock );
}
else
indentBlock();
}
// Clean up the markers.
CKEDITOR.dom.element.clearAllMarkers( database );
editor.forceNextSelectionCheck();
selection.selectBookmarks( bookmarks );
}
};
CKEDITOR.plugins.add( 'indent',
{
init : function( editor )
{
// Register commands.
var indent = new indentCommand( editor, 'indent' ),
outdent = new indentCommand( editor, 'outdent' );
editor.addCommand( 'indent', indent );
editor.addCommand( 'outdent', outdent );
// Register the toolbar buttons.
editor.ui.addButton( 'Indent',
{
label : editor.lang.indent,
command : 'indent'
});
editor.ui.addButton( 'Outdent',
{
label : editor.lang.outdent,
command : 'outdent'
});
// Register the state changing handlers.
editor.on( 'selectionChange', CKEDITOR.tools.bind( onSelectionChange, indent ) );
editor.on( 'selectionChange', CKEDITOR.tools.bind( onSelectionChange, outdent ) );
// [IE6/7] Raw lists are using margin instead of padding for visual indentation in wysiwyg mode. (#3893)
if ( CKEDITOR.env.ie6Compat || CKEDITOR.env.ie7Compat )
{
editor.addCss(
"ul,ol" +
"{" +
" margin-left: 0px;" +
" padding-left: 40px;" +
"}" );
}
// Register dirChanged listener.
editor.on( 'dirChanged', function( e )
{
var range = new CKEDITOR.dom.range( editor.document );
range.setStartBefore( e.data.node );
range.setEndAfter( e.data.node );
var walker = new CKEDITOR.dom.walker( range ),
node;
while ( ( node = walker.next() ) )
{
if ( node.type == CKEDITOR.NODE_ELEMENT )
{
// A child with the defined dir is to be ignored.
if ( !node.equals( e.data.node ) && node.getDirection() )
{
range.setStartAfter( node );
walker = new CKEDITOR.dom.walker( range );
continue;
}
// Switch alignment classes.
var classes = editor.config.indentClasses;
if ( classes )
{
var suffix = ( e.data.dir == 'ltr' ) ? [ '_rtl', '' ] : [ '', '_rtl' ];
for ( var i = 0; i < classes.length; i++ )
{
if ( node.hasClass( classes[ i ] + suffix[ 0 ] ) )
{
node.removeClass( classes[ i ] + suffix[ 0 ] );
node.addClass( classes[ i ] + suffix[ 1 ] );
}
}
}
// Switch the margins.
var marginLeft = node.getStyle( 'margin-right' ),
marginRight = node.getStyle( 'margin-left' );
marginLeft ? node.setStyle( 'margin-left', marginLeft ) : node.removeStyle( 'margin-left' );
marginRight ? node.setStyle( 'margin-right', marginRight ) : node.removeStyle( 'margin-right' );
}
}
});
},
requires : [ 'domiterator', 'list' ]
} );
})();
/**
* Size of each indentation step
* @name CKEDITOR.config.indentOffset
* @type Number
* @default 40
* @example
* config.indentOffset = 4;
*/
/**
* Unit for the indentation style
* @name CKEDITOR.config.indentUnit
* @type String
* @default 'px'
* @example
* config.indentUnit = 'em';
*/
/**
* List of classes to use for indenting the contents. If it's null, no classes will be used
* and instead the {@link #indentUnit} and {@link #indentOffset} properties will be used.
* @name CKEDITOR.config.indentClasses
* @type Array
* default null
* @example
* // Use the classes 'Indent1', 'Indent2', 'Indent3'
* config.indentClasses = ['Indent1', 'Indent2', 'Indent3'];
*/
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
(function()
{
function protectFormStyles( formElement )
{
if ( !formElement || formElement.type != CKEDITOR.NODE_ELEMENT || formElement.getName() != 'form' )
return [];
var hijackRecord = [],
hijackNames = [ 'style', 'className' ];
for ( var i = 0 ; i < hijackNames.length ; i++ )
{
var name = hijackNames[i];
var $node = formElement.$.elements.namedItem( name );
if ( $node )
{
var hijackNode = new CKEDITOR.dom.element( $node );
hijackRecord.push( [ hijackNode, hijackNode.nextSibling ] );
hijackNode.remove();
}
}
return hijackRecord;
}
function restoreFormStyles( formElement, hijackRecord )
{
if ( !formElement || formElement.type != CKEDITOR.NODE_ELEMENT || formElement.getName() != 'form' )
return;
if ( hijackRecord.length > 0 )
{
for ( var i = hijackRecord.length - 1 ; i >= 0 ; i-- )
{
var node = hijackRecord[i][0];
var sibling = hijackRecord[i][1];
if ( sibling )
node.insertBefore( sibling );
else
node.appendTo( formElement );
}
}
}
function saveStyles( element, isInsideEditor )
{
var data = protectFormStyles( element );
var retval = {};
var $element = element.$;
if ( !isInsideEditor )
{
retval[ 'class' ] = $element.className || '';
$element.className = '';
}
retval.inline = $element.style.cssText || '';
if ( !isInsideEditor ) // Reset any external styles that might interfere. (#2474)
$element.style.cssText = 'position: static; overflow: visible';
restoreFormStyles( data );
return retval;
}
function restoreStyles( element, savedStyles )
{
var data = protectFormStyles( element );
var $element = element.$;
if ( 'class' in savedStyles )
$element.className = savedStyles[ 'class' ];
if ( 'inline' in savedStyles )
$element.style.cssText = savedStyles.inline;
restoreFormStyles( data );
}
function refreshCursor( editor )
{
// Refresh all editor instances on the page (#5724).
var all = CKEDITOR.instances;
for ( var i in all )
{
var one = all[ i ];
if ( one.mode == 'wysiwyg' )
{
var body = one.document.getBody();
// Refresh 'contentEditable' otherwise
// DOM lifting breaks design mode. (#5560)
body.setAttribute( 'contentEditable', false );
body.setAttribute( 'contentEditable', true );
}
}
if ( editor.focusManager.hasFocus )
{
editor.toolbox.focus();
editor.focus();
}
}
/**
* Adding an iframe shim to this element, OR removing the existing one if already applied.
* Note: This will only affect IE version below 7.
*/
function createIframeShim( element )
{
if ( !CKEDITOR.env.ie || CKEDITOR.env.version > 6 )
return null;
var shim = CKEDITOR.dom.element.createFromHtml( '<iframe frameborder="0" tabindex="-1"' +
' src="javascript:' +
'void((function(){' +
'document.open();' +
( CKEDITOR.env.isCustomDomain() ? 'document.domain=\'' + this.getDocument().$.domain + '\';' : '' ) +
'document.close();' +
'})())"' +
' style="display:block;position:absolute;z-index:-1;' +
'progid:DXImageTransform.Microsoft.Alpha(opacity=0);' +
'"></iframe>' );
return element.append( shim, true );
}
CKEDITOR.plugins.add( 'maximize',
{
init : function( editor )
{
var lang = editor.lang;
var mainDocument = CKEDITOR.document,
mainWindow = mainDocument.getWindow();
// Saved selection and scroll position for the editing area.
var savedSelection,
savedScroll;
// Saved scroll position for the outer window.
var outerScroll;
var shim;
// Saved resize handler function.
function resizeHandler()
{
var viewPaneSize = mainWindow.getViewPaneSize();
shim && shim.setStyles( { width : viewPaneSize.width + 'px', height : viewPaneSize.height + 'px' } );
editor.resize( viewPaneSize.width, viewPaneSize.height, null, true );
}
// Retain state after mode switches.
var savedState = CKEDITOR.TRISTATE_OFF;
editor.addCommand( 'maximize',
{
modes : { wysiwyg : 1, source : 1 },
editorFocus : false,
exec : function()
{
var container = editor.container.getChild( 1 );
var contents = editor.getThemeSpace( 'contents' );
// Save current selection and scroll position in editing area.
if ( editor.mode == 'wysiwyg' )
{
var selection = editor.getSelection();
savedSelection = selection && selection.getRanges();
savedScroll = mainWindow.getScrollPosition();
}
else
{
var $textarea = editor.textarea.$;
savedSelection = !CKEDITOR.env.ie && [ $textarea.selectionStart, $textarea.selectionEnd ];
savedScroll = [ $textarea.scrollLeft, $textarea.scrollTop ];
}
if ( this.state == CKEDITOR.TRISTATE_OFF ) // Go fullscreen if the state is off.
{
// Add event handler for resizing.
mainWindow.on( 'resize', resizeHandler );
// Save the scroll bar position.
outerScroll = mainWindow.getScrollPosition();
// Save and reset the styles for the entire node tree.
var currentNode = editor.container;
while ( ( currentNode = currentNode.getParent() ) )
{
currentNode.setCustomData( 'maximize_saved_styles', saveStyles( currentNode ) );
currentNode.setStyle( 'z-index', editor.config.baseFloatZIndex - 1 );
}
contents.setCustomData( 'maximize_saved_styles', saveStyles( contents, true ) );
container.setCustomData( 'maximize_saved_styles', saveStyles( container, true ) );
// Hide scroll bars.
var viewPaneSize = mainWindow.getViewPaneSize();
var styles =
{
overflow : 'hidden',
width : 0,
height : 0
};
mainDocument.getDocumentElement().setStyles( styles );
!CKEDITOR.env.gecko && mainDocument.getDocumentElement().setStyle( 'position', 'fixed' );
mainDocument.getBody().setStyles( styles );
// Scroll to the top left (IE needs some time for it - #4923).
CKEDITOR.env.ie ?
setTimeout( function() { mainWindow.$.scrollTo( 0, 0 ); }, 0 ) :
mainWindow.$.scrollTo( 0, 0 );
// Resize and move to top left.
container.setStyle( 'position', 'absolute' );
container.$.offsetLeft; // SAFARI BUG: See #2066.
container.setStyles(
{
'z-index' : editor.config.baseFloatZIndex - 1,
left : '0px',
top : '0px'
} );
shim = createIframeShim( container ); // IE6 select element penetration when maximized. (#4459)
// Add cke_maximized class before resize handle since that will change things sizes (#5580)
container.addClass( 'cke_maximized' );
resizeHandler();
// Still not top left? Fix it. (Bug #174)
var offset = container.getDocumentPosition();
container.setStyles(
{
left : ( -1 * offset.x ) + 'px',
top : ( -1 * offset.y ) + 'px'
} );
// Fixing positioning editor chrome in Firefox break design mode. (#5149)
CKEDITOR.env.gecko && refreshCursor( editor );
}
else if ( this.state == CKEDITOR.TRISTATE_ON ) // Restore from fullscreen if the state is on.
{
// Remove event handler for resizing.
mainWindow.removeListener( 'resize', resizeHandler );
// Restore CSS styles for the entire node tree.
var editorElements = [ contents, container ];
for ( var i = 0 ; i < editorElements.length ; i++ )
{
restoreStyles( editorElements[i], editorElements[i].getCustomData( 'maximize_saved_styles' ) );
editorElements[i].removeCustomData( 'maximize_saved_styles' );
}
currentNode = editor.container;
while ( ( currentNode = currentNode.getParent() ) )
{
restoreStyles( currentNode, currentNode.getCustomData( 'maximize_saved_styles' ) );
currentNode.removeCustomData( 'maximize_saved_styles' );
}
// Restore the window scroll position.
CKEDITOR.env.ie ?
setTimeout( function() { mainWindow.$.scrollTo( outerScroll.x, outerScroll.y ); }, 0 ) :
mainWindow.$.scrollTo( outerScroll.x, outerScroll.y );
// Remove cke_maximized class.
container.removeClass( 'cke_maximized' );
if ( shim )
{
shim.remove();
shim = null;
}
// Emit a resize event, because this time the size is modified in
// restoreStyles.
editor.fire( 'resize' );
}
this.toggleState();
// Toggle button label.
var button = this.uiItems[ 0 ];
var label = ( this.state == CKEDITOR.TRISTATE_OFF )
? lang.maximize : lang.minimize;
var buttonNode = editor.element.getDocument().getById( button._.id );
buttonNode.getChild( 1 ).setHtml( label );
buttonNode.setAttribute( 'title', label );
buttonNode.setAttribute( 'href', 'javascript:void("' + label + '");' );
// Restore selection and scroll position in editing area.
if ( editor.mode == 'wysiwyg' )
{
if ( savedSelection )
{
// Fixing positioning editor chrome in Firefox break design mode. (#5149)
CKEDITOR.env.gecko && refreshCursor( editor );
editor.getSelection().selectRanges(savedSelection);
var element = editor.getSelection().getStartElement();
element && element.scrollIntoView( true );
}
else
mainWindow.$.scrollTo( savedScroll.x, savedScroll.y );
}
else
{
if ( savedSelection )
{
$textarea.selectionStart = savedSelection[0];
$textarea.selectionEnd = savedSelection[1];
}
$textarea.scrollLeft = savedScroll[0];
$textarea.scrollTop = savedScroll[1];
}
savedSelection = savedScroll = null;
savedState = this.state;
},
canUndo : false
} );
editor.ui.addButton( 'Maximize',
{
label : lang.maximize,
command : 'maximize'
} );
// Restore the command state after mode change, unless it has been changed to disabled (#6467)
editor.on( 'mode', function()
{
var command = editor.getCommand( 'maximize' );
command.setState( command.state == CKEDITOR.TRISTATE_DISABLED ? CKEDITOR.TRISTATE_DISABLED : savedState );
}, null, null, 100 );
}
} );
})();
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.add( 'button',
{
beforeInit : function( editor )
{
editor.ui.addHandler( CKEDITOR.UI_BUTTON, CKEDITOR.ui.button.handler );
}
});
/**
* Button UI element.
* @constant
* @example
*/
CKEDITOR.UI_BUTTON = 1;
/**
* Represents a button UI element. This class should not be called directly. To
* create new buttons use {@link CKEDITOR.ui.prototype.addButton} instead.
* @constructor
* @param {Object} definition The button definition.
* @example
*/
CKEDITOR.ui.button = function( definition )
{
// Copy all definition properties to this object.
CKEDITOR.tools.extend( this, definition,
// Set defaults.
{
title : definition.label,
className : definition.className || ( definition.command && 'cke_button_' + definition.command ) || '',
click : definition.click || function( editor )
{
editor.execCommand( definition.command );
}
});
this._ = {};
};
/**
* Transforms a button definition in a {@link CKEDITOR.ui.button} instance.
* @type Object
* @example
*/
CKEDITOR.ui.button.handler =
{
create : function( definition )
{
return new CKEDITOR.ui.button( definition );
}
};
/**
* Handles a button click.
* @private
*/
CKEDITOR.ui.button._ =
{
instances : [],
keydown : function( index, ev )
{
var instance = CKEDITOR.ui.button._.instances[ index ];
if ( instance.onkey )
{
ev = new CKEDITOR.dom.event( ev );
return ( instance.onkey( instance, ev.getKeystroke() ) !== false );
}
},
focus : function( index, ev )
{
var instance = CKEDITOR.ui.button._.instances[ index ],
retVal;
if ( instance.onfocus )
retVal = ( instance.onfocus( instance, new CKEDITOR.dom.event( ev ) ) !== false );
// FF2: prevent focus event been bubbled up to editor container, which caused unexpected editor focus.
if ( CKEDITOR.env.gecko && CKEDITOR.env.version < 10900 )
ev.preventBubble();
return retVal;
}
};
( function()
{
var keydownFn = CKEDITOR.tools.addFunction( CKEDITOR.ui.button._.keydown, CKEDITOR.ui.button._ ),
focusFn = CKEDITOR.tools.addFunction( CKEDITOR.ui.button._.focus, CKEDITOR.ui.button._ );
CKEDITOR.ui.button.prototype =
{
canGroup : true,
/**
* Renders the button.
* @param {CKEDITOR.editor} editor The editor instance which this button is
* to be used by.
* @param {Array} output The output array to which append the HTML relative
* to this button.
* @example
*/
render : function( editor, output )
{
var env = CKEDITOR.env,
id = this._.id = CKEDITOR.tools.getNextId(),
classes = '',
command = this.command, // Get the command name.
clickFn,
index;
this._.editor = editor;
var instance =
{
id : id,
button : this,
editor : editor,
focus : function()
{
var element = CKEDITOR.document.getById( id );
element.focus();
},
execute : function()
{
this.button.click( editor );
}
};
instance.clickFn = clickFn = CKEDITOR.tools.addFunction( instance.execute, instance );
instance.index = index = CKEDITOR.ui.button._.instances.push( instance ) - 1;
// Indicate a mode sensitive button.
if ( this.modes )
{
var modeStates = {};
editor.on( 'beforeModeUnload', function()
{
modeStates[ editor.mode ] = this._.state;
}, this );
editor.on( 'mode', function()
{
var mode = editor.mode;
// Restore saved button state.
this.setState( this.modes[ mode ] ?
modeStates[ mode ] != undefined ? modeStates[ mode ] :
CKEDITOR.TRISTATE_OFF : CKEDITOR.TRISTATE_DISABLED );
}, this);
}
else if ( command )
{
// Get the command instance.
command = editor.getCommand( command );
if ( command )
{
command.on( 'state', function()
{
this.setState( command.state );
}, this);
classes += 'cke_' + (
command.state == CKEDITOR.TRISTATE_ON ? 'on' :
command.state == CKEDITOR.TRISTATE_DISABLED ? 'disabled' :
'off' );
}
}
if ( !command )
classes += 'cke_off';
if ( this.className )
classes += ' ' + this.className;
output.push(
'<span class="cke_button">',
'<a id="', id, '"' +
' class="', classes, '"',
env.gecko && env.version >= 10900 && !env.hc ? '' : '" href="javascript:void(\''+ ( this.title || '' ).replace( "'", '' )+ '\')"',
' title="', this.title, '"' +
' tabindex="-1"' +
' hidefocus="true"' +
' role="button"' +
' aria-labelledby="' + id + '_label"' +
( this.hasArrow ? ' aria-haspopup="true"' : '' ) );
// Some browsers don't cancel key events in the keydown but in the
// keypress.
// TODO: Check if really needed for Gecko+Mac.
if ( env.opera || ( env.gecko && env.mac ) )
{
output.push(
' onkeypress="return false;"' );
}
// With Firefox, we need to force the button to redraw, otherwise it
// will remain in the focus state.
if ( env.gecko )
{
output.push(
' onblur="this.style.cssText = this.style.cssText;"' );
}
output.push(
' onkeydown="return CKEDITOR.tools.callFunction(', keydownFn, ', ', index, ', event);"' +
' onfocus="return CKEDITOR.tools.callFunction(', focusFn,', ', index, ', event);"' +
' onclick="CKEDITOR.tools.callFunction(', clickFn, ', this); return false;">' +
'<span class="cke_icon"' );
if ( this.icon )
{
var offset = ( this.iconOffset || 0 ) * -16;
output.push( ' style="background-image:url(', CKEDITOR.getUrl( this.icon ), ');background-position:0 ' + offset + 'px;"' );
}
output.push(
'> </span>' +
'<span id="', id, '_label" class="cke_label">', this.label, '</span>' );
if ( this.hasArrow )
{
output.push(
'<span class="cke_buttonarrow">'
// BLACK DOWN-POINTING TRIANGLE
+ ( CKEDITOR.env.hc ? '▼' : ' ' )
+ '</span>' );
}
output.push(
'</a>',
'</span>' );
if ( this.onRender )
this.onRender();
return instance;
},
setState : function( state )
{
if ( this._.state == state )
return false;
this._.state = state;
var element = CKEDITOR.document.getById( this._.id );
if ( element )
{
element.setState( state );
state == CKEDITOR.TRISTATE_DISABLED ?
element.setAttribute( 'aria-disabled', true ) :
element.removeAttribute( 'aria-disabled' );
state == CKEDITOR.TRISTATE_ON ?
element.setAttribute( 'aria-pressed', true ) :
element.removeAttribute( 'aria-pressed' );
return true;
}
else
return false;
}
};
})();
/**
* Adds a button definition to the UI elements list.
* @param {String} The button name.
* @param {Object} The button definition.
* @example
* editorInstance.ui.addButton( 'MyBold',
* {
* label : 'My Bold',
* command : 'bold'
* });
*/
CKEDITOR.ui.prototype.addButton = function( name, definition )
{
this.add( name, CKEDITOR.UI_BUTTON, definition );
};
CKEDITOR.on( 'reset', function()
{
CKEDITOR.ui.button._.instances = [];
});
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @fileSave plugin.
*/
(function()
{
var saveCmd =
{
modes : { wysiwyg:1, source:1 },
exec : function( editor )
{
var $form = editor.element.$.form;
if ( $form )
{
try
{
$form.submit();
}
catch( e )
{
// If there's a button named "submit" then the form.submit
// function is masked and can't be called in IE/FF, so we
// call the click() method of that button.
if ( $form.submit.click )
$form.submit.click();
}
}
}
};
var pluginName = 'save';
// Register a plugin named "save".
CKEDITOR.plugins.add( pluginName,
{
init : function( editor )
{
var command = editor.addCommand( pluginName, saveCmd );
command.modes = { wysiwyg : !!( editor.element.$.form ) };
editor.ui.addButton( 'Save',
{
label : editor.lang.save,
command : pluginName
});
}
});
})();
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @fileOverview Plugin for making iframe based dialogs.
*/
CKEDITOR.plugins.add( 'iframedialog',
{
requires : [ 'dialog' ],
onLoad : function()
{
CKEDITOR.dialog.addIframe = function( name, title, src, width, height, onContentLoad )
{
var element =
{
type : 'iframe',
src : src,
width : '100%',
height : '100%'
};
if ( typeof( onContentLoad ) == 'function' )
element.onContentLoad = onContentLoad;
var definition =
{
title : title,
minWidth : width,
minHeight : height,
contents :
[
{
id : 'iframe',
label : title,
expand : true,
elements : [ element ]
}
]
};
return this.add( name, function(){ return definition; } );
};
(function()
{
/**
* An iframe element.
* @extends CKEDITOR.ui.dialog.uiElement
* @example
* @constructor
* @param {CKEDITOR.dialog} dialog
* Parent dialog object.
* @param {CKEDITOR.dialog.uiElementDefinition} elementDefinition
* The element definition. Accepted fields:
* <ul>
* <li><strong>src</strong> (Required) The src field of the iframe. </li>
* <li><strong>width</strong> (Required) The iframe's width.</li>
* <li><strong>height</strong> (Required) The iframe's height.</li>
* <li><strong>onContentLoad</strong> (Optional) A function to be executed
* after the iframe's contents has finished loading.</li>
* </ul>
* @param {Array} htmlList
* List of HTML code to output to.
*/
var iframeElement = function( dialog, elementDefinition, htmlList )
{
if ( arguments.length < 3 )
return;
var _ = ( this._ || ( this._ = {} ) ),
contentLoad = elementDefinition.onContentLoad && CKEDITOR.tools.bind( elementDefinition.onContentLoad, this ),
cssWidth = CKEDITOR.tools.cssLength( elementDefinition.width ),
cssHeight = CKEDITOR.tools.cssLength( elementDefinition.height );
_.frameId = CKEDITOR.tools.getNextId() + '_iframe';
// IE BUG: Parent container does not resize to contain the iframe automatically.
dialog.on( 'load', function()
{
var iframe = CKEDITOR.document.getById( _.frameId ),
parentContainer = iframe.getParent();
parentContainer.setStyles(
{
width : cssWidth,
height : cssHeight
} );
} );
var attributes =
{
src : '%2',
id : _.frameId,
frameborder : 0,
allowtransparency : true
};
var myHtml = [];
if ( typeof( elementDefinition.onContentLoad ) == 'function' )
attributes.onload = 'CKEDITOR.tools.callFunction(%1);';
CKEDITOR.ui.dialog.uiElement.call( this, dialog, elementDefinition, myHtml, 'iframe',
{
width : cssWidth,
height : cssHeight
}, attributes, '' );
// Put a placeholder for the first time.
htmlList.push( '<div style="width:' + cssWidth + ';height:' + cssHeight + ';" id="' + this.domId + '"></div>' );
// Iframe elements should be refreshed whenever it is shown.
myHtml = myHtml.join( '' );
dialog.on( 'show', function()
{
var iframe = CKEDITOR.document.getById( _.frameId ),
parentContainer = iframe.getParent(),
callIndex = CKEDITOR.tools.addFunction( contentLoad ),
html = myHtml.replace( '%1', callIndex ).replace( '%2', CKEDITOR.tools.htmlEncode( elementDefinition.src ) );
parentContainer.setHtml( html );
} );
};
iframeElement.prototype = new CKEDITOR.ui.dialog.uiElement;
CKEDITOR.dialog.addUIElement( 'iframe',
{
build : function( dialog, elementDefinition, output )
{
return new iframeElement( dialog, elementDefinition, output );
}
} );
})();
}
} );
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.add( 'panel',
{
beforeInit : function( editor )
{
editor.ui.addHandler( CKEDITOR.UI_PANEL, CKEDITOR.ui.panel.handler );
}
});
/**
* Panel UI element.
* @constant
* @example
*/
CKEDITOR.UI_PANEL = 2;
CKEDITOR.ui.panel = function( document, definition )
{
// Copy all definition properties to this object.
if ( definition )
CKEDITOR.tools.extend( this, definition );
// Set defaults.
CKEDITOR.tools.extend( this,
{
className : '',
css : []
});
this.id = CKEDITOR.tools.getNextId();
this.document = document;
this._ =
{
blocks : {}
};
};
/**
* Transforms a rich combo definition in a {@link CKEDITOR.ui.richCombo}
* instance.
* @type Object
* @example
*/
CKEDITOR.ui.panel.handler =
{
create : function( definition )
{
return new CKEDITOR.ui.panel( definition );
}
};
CKEDITOR.ui.panel.prototype =
{
renderHtml : function( editor )
{
var output = [];
this.render( editor, output );
return output.join( '' );
},
/**
* Renders the combo.
* @param {CKEDITOR.editor} editor The editor instance which this button is
* to be used by.
* @param {Array} output The output array to which append the HTML relative
* to this button.
* @example
*/
render : function( editor, output )
{
var id = this.id;
output.push(
'<div class="', editor.skinClass ,'"' +
' lang="', editor.langCode, '"' +
' role="presentation"' +
// iframe loading need sometime, keep the panel hidden(#4186).
' style="display:none;z-index:' + ( editor.config.baseFloatZIndex + 1 ) + '">' +
'<div' +
' id=', id,
' dir=', editor.lang.dir,
' role="presentation"' +
' class="cke_panel cke_', editor.lang.dir );
if ( this.className )
output.push( ' ', this.className );
output.push(
'">' );
if ( this.forceIFrame || this.css.length )
{
output.push(
'<iframe id="', id, '_frame"' +
' frameborder="0"' +
' role="application" src="javascript:void(' );
output.push(
// Support for custom document.domain in IE.
CKEDITOR.env.isCustomDomain() ?
'(function(){' +
'document.open();' +
'document.domain=\'' + document.domain + '\';' +
'document.close();' +
'})()'
:
'0' );
output.push(
')"></iframe>' );
}
output.push(
'</div>' +
'</div>' );
return id;
},
getHolderElement : function()
{
var holder = this._.holder;
if ( !holder )
{
if ( this.forceIFrame || this.css.length )
{
var iframe = this.document.getById( this.id + '_frame' ),
parentDiv = iframe.getParent(),
dir = parentDiv.getAttribute( 'dir' ),
className = parentDiv.getParent().getAttribute( 'class' ),
langCode = parentDiv.getParent().getAttribute( 'lang' ),
doc = iframe.getFrameDocument();
var onLoad = CKEDITOR.tools.addFunction( CKEDITOR.tools.bind( function( ev )
{
this.isLoaded = true;
if ( this.onLoad )
this.onLoad();
}, this ) );
var data =
'<!DOCTYPE html>' +
'<html dir="' + dir + '" class="' + className + '_container" lang="' + langCode + '">' +
'<head>' +
'<style>.' + className + '_container{visibility:hidden}</style>' +
'</head>' +
'<body class="cke_' + dir + ' cke_panel_frame ' + CKEDITOR.env.cssClass + '" style="margin:0;padding:0"' +
' onload="( window.CKEDITOR || window.parent.CKEDITOR ).tools.callFunction(' + onLoad + ');"></body>' +
// It looks strange, but for FF2, the styles must go
// after <body>, so it (body) becames immediatelly
// available. (#3031)
CKEDITOR.tools.buildStyleHtml( this.css ) +
'<\/html>';
doc.write( data );
var win = doc.getWindow();
// Register the CKEDITOR global.
win.$.CKEDITOR = CKEDITOR;
// Arrow keys for scrolling is only preventable with 'keypress' event in Opera (#4534).
doc.on( 'key' + ( CKEDITOR.env.opera? 'press':'down' ), function( evt )
{
var keystroke = evt.data.getKeystroke(),
dir = this.document.getById( this.id ).getAttribute( 'dir' );
// Delegate key processing to block.
if ( this._.onKeyDown && this._.onKeyDown( keystroke ) === false )
{
evt.data.preventDefault();
return;
}
// ESC/ARROW-LEFT(ltr) OR ARROW-RIGHT(rtl)
if ( keystroke == 27 || keystroke == ( dir == 'rtl' ? 39 : 37 ) )
{
if ( this.onEscape && this.onEscape( keystroke ) === false )
evt.data.preventDefault();
}
},
this );
holder = doc.getBody();
holder.unselectable();
CKEDITOR.env.air && CKEDITOR.tools.callFunction( onLoad );
}
else
holder = this.document.getById( this.id );
this._.holder = holder;
}
return holder;
},
addBlock : function( name, block )
{
block = this._.blocks[ name ] = block instanceof CKEDITOR.ui.panel.block ? block
: new CKEDITOR.ui.panel.block( this.getHolderElement(), block );
if ( !this._.currentBlock )
this.showBlock( name );
return block;
},
getBlock : function( name )
{
return this._.blocks[ name ];
},
showBlock : function( name )
{
var blocks = this._.blocks,
block = blocks[ name ],
current = this._.currentBlock,
holder = this.forceIFrame ?
this.document.getById( this.id + '_frame' )
: this._.holder;
// Disable context menu for block panel.
holder.getParent().getParent().disableContextMenu();
if ( current )
{
// Clean up the current block's effects on holder.
holder.removeAttributes( current.attributes );
current.hide();
}
this._.currentBlock = block;
holder.setAttributes( block.attributes );
CKEDITOR.fire( 'ariaWidget', holder );
// Reset the focus index, so it will always go into the first one.
block._.focusIndex = -1;
this._.onKeyDown = block.onKeyDown && CKEDITOR.tools.bind( block.onKeyDown, block );
block.onMark = function( item )
{
holder.setAttribute( 'aria-activedescendant', item.getId() + '_option' );
};
block.onUnmark = function()
{
holder.removeAttribute( 'aria-activedescendant' );
};
block.show();
return block;
},
destroy : function()
{
this.element && this.element.remove();
}
};
CKEDITOR.ui.panel.block = CKEDITOR.tools.createClass(
{
$ : function( blockHolder, blockDefinition )
{
this.element = blockHolder.append(
blockHolder.getDocument().createElement( 'div',
{
attributes :
{
'tabIndex' : -1,
'class' : 'cke_panel_block',
'role' : 'presentation'
},
styles :
{
display : 'none'
}
}) );
// Copy all definition properties to this object.
if ( blockDefinition )
CKEDITOR.tools.extend( this, blockDefinition );
if ( !this.attributes.title )
this.attributes.title = this.attributes[ 'aria-label' ];
this.keys = {};
this._.focusIndex = -1;
// Disable context menu for panels.
this.element.disableContextMenu();
},
_ : {
/**
* Mark the item specified by the index as current activated.
*/
markItem: function( index )
{
if ( index == -1 )
return;
var links = this.element.getElementsByTag( 'a' );
var item = links.getItem( this._.focusIndex = index );
// Safari need focus on the iframe window first(#3389), but we need
// lock the blur to avoid hiding the panel.
if ( CKEDITOR.env.webkit || CKEDITOR.env.opera )
item.getDocument().getWindow().focus();
item.focus();
this.onMark && this.onMark( item );
}
},
proto :
{
show : function()
{
this.element.setStyle( 'display', '' );
},
hide : function()
{
if ( !this.onHide || this.onHide.call( this ) !== true )
this.element.setStyle( 'display', 'none' );
},
onKeyDown : function( keystroke )
{
var keyAction = this.keys[ keystroke ];
switch ( keyAction )
{
// Move forward.
case 'next' :
var index = this._.focusIndex,
links = this.element.getElementsByTag( 'a' ),
link;
while ( ( link = links.getItem( ++index ) ) )
{
// Move the focus only if the element is marked with
// the _cke_focus and it it's visible (check if it has
// width).
if ( link.getAttribute( '_cke_focus' ) && link.$.offsetWidth )
{
this._.focusIndex = index;
link.focus();
break;
}
}
return false;
// Move backward.
case 'prev' :
index = this._.focusIndex;
links = this.element.getElementsByTag( 'a' );
while ( index > 0 && ( link = links.getItem( --index ) ) )
{
// Move the focus only if the element is marked with
// the _cke_focus and it it's visible (check if it has
// width).
if ( link.getAttribute( '_cke_focus' ) && link.$.offsetWidth )
{
this._.focusIndex = index;
link.focus();
break;
}
}
return false;
case 'click' :
index = this._.focusIndex;
link = index >= 0 && this.element.getElementsByTag( 'a' ).getItem( index );
if ( link )
link.$.click ? link.$.click() : link.$.onclick();
return false;
}
return true;
}
}
});
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
(function()
{
function createFakeElement( editor, realElement )
{
var fakeElement = editor.createFakeParserElement( realElement, 'cke_iframe', 'iframe', true ),
fakeStyle = fakeElement.attributes.style || '';
var width = realElement.attributes.width,
height = realElement.attributes.height;
if ( typeof width != 'undefined' )
fakeStyle += 'width:' + CKEDITOR.tools.cssLength( width ) + ';';
if ( typeof height != 'undefined' )
fakeStyle += 'height:' + CKEDITOR.tools.cssLength( height ) + ';';
fakeElement.attributes.style = fakeStyle;
return fakeElement;
}
CKEDITOR.plugins.add( 'iframe',
{
requires : [ 'dialog', 'fakeobjects' ],
init : function( editor )
{
var pluginName = 'iframe',
lang = editor.lang.iframe;
CKEDITOR.dialog.add( pluginName, this.path + 'dialogs/iframe.js' );
editor.addCommand( pluginName, new CKEDITOR.dialogCommand( pluginName ) );
editor.addCss(
'img.cke_iframe' +
'{' +
'background-image: url(' + CKEDITOR.getUrl( this.path + 'images/placeholder.png' ) + ');' +
'background-position: center center;' +
'background-repeat: no-repeat;' +
'border: 1px solid #a9a9a9;' +
'width: 80px;' +
'height: 80px;' +
'}'
);
editor.ui.addButton( 'Iframe',
{
label : lang.toolbar,
command : pluginName
});
editor.on( 'doubleclick', function( evt )
{
var element = evt.data.element;
if ( element.is( 'img' ) && element.data( 'cke-real-element-type' ) == 'iframe' )
evt.data.dialog = 'iframe';
});
if ( editor.addMenuItems )
{
editor.addMenuItems(
{
iframe :
{
label : lang.title,
command : 'iframe',
group : 'image'
}
});
}
// If the "contextmenu" plugin is loaded, register the listeners.
if ( editor.contextMenu )
{
editor.contextMenu.addListener( function( element, selection )
{
if ( element && element.is( 'img' ) && element.data( 'cke-real-element-type' ) == 'iframe' )
return { iframe : CKEDITOR.TRISTATE_OFF };
});
}
},
afterInit : function( editor )
{
var dataProcessor = editor.dataProcessor,
dataFilter = dataProcessor && dataProcessor.dataFilter;
if ( dataFilter )
{
dataFilter.addRules(
{
elements :
{
iframe : function( element )
{
return createFakeElement( editor, element );
}
}
});
}
}
});
})();
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
(function()
{
// Map 'true' and 'false' values to match W3C's specifications
// http://www.w3.org/TR/REC-html40/present/frames.html#h-16.5
var checkboxValues =
{
scrolling : { 'true' : 'yes', 'false' : 'no' },
frameborder : { 'true' : '1', 'false' : '0' }
};
function loadValue( iframeNode )
{
var isCheckbox = this instanceof CKEDITOR.ui.dialog.checkbox;
if ( iframeNode.hasAttribute( this.id ) )
{
var value = iframeNode.getAttribute( this.id );
if ( isCheckbox )
this.setValue( checkboxValues[ this.id ][ 'true' ] == value.toLowerCase() );
else
this.setValue( value );
}
}
function commitValue( iframeNode )
{
var isRemove = this.getValue() === '',
isCheckbox = this instanceof CKEDITOR.ui.dialog.checkbox,
value = this.getValue();
if ( isRemove )
iframeNode.removeAttribute( this.att || this.id );
else if ( isCheckbox )
iframeNode.setAttribute( this.id, checkboxValues[ this.id ][ value ] );
else
iframeNode.setAttribute( this.att || this.id, value );
}
CKEDITOR.dialog.add( 'iframe', function( editor )
{
var iframeLang = editor.lang.iframe,
commonLang = editor.lang.common,
dialogadvtab = editor.plugins.dialogadvtab;
return {
title : iframeLang.title,
minWidth : 350,
minHeight : 260,
onShow : function()
{
// Clear previously saved elements.
this.fakeImage = this.iframeNode = null;
var fakeImage = this.getSelectedElement();
if ( fakeImage && fakeImage.data( 'cke-real-element-type' ) && fakeImage.data( 'cke-real-element-type' ) == 'iframe' )
{
this.fakeImage = fakeImage;
var iframeNode = editor.restoreRealElement( fakeImage );
this.iframeNode = iframeNode;
this.setupContent( iframeNode, fakeImage );
}
},
onOk : function()
{
var iframeNode;
if ( !this.fakeImage )
iframeNode = new CKEDITOR.dom.element( 'iframe' );
else
iframeNode = this.iframeNode;
// A subset of the specified attributes/styles
// should also be applied on the fake element to
// have better visual effect. (#5240)
var extraStyles = {}, extraAttributes = {};
this.commitContent( iframeNode, extraStyles, extraAttributes );
// Refresh the fake image.
var newFakeImage = editor.createFakeElement( iframeNode, 'cke_iframe', 'iframe', true );
newFakeImage.setAttributes( extraAttributes );
newFakeImage.setStyles( extraStyles );
if ( this.fakeImage )
{
newFakeImage.replace( this.fakeImage );
editor.getSelection().selectElement( newFakeImage );
}
else
editor.insertElement( newFakeImage );
},
contents : [
{
id : 'info',
label : commonLang.generalTab,
accessKey : 'I',
elements :
[
{
type : 'vbox',
padding : 0,
children :
[
{
id : 'src',
type : 'text',
label : commonLang.url,
required : true,
validate : CKEDITOR.dialog.validate.notEmpty( iframeLang.noUrl ),
setup : loadValue,
commit : commitValue
}
]
},
{
type : 'hbox',
children :
[
{
id : 'width',
type : 'text',
style : 'width:100%',
labelLayout : 'vertical',
label : commonLang.width,
validate : CKEDITOR.dialog.validate.integer( commonLang.invalidWidth ),
setup : function( iframeNode, fakeImage )
{
loadValue.apply( this, arguments );
if ( fakeImage )
{
var fakeImageWidth = parseInt( fakeImage.$.style.width, 10 );
if ( !isNaN( fakeImageWidth ) )
this.setValue( fakeImageWidth );
}
},
commit : function( iframeNode, extraStyles )
{
commitValue.apply( this, arguments );
if ( this.getValue() )
extraStyles.width = this.getValue() + 'px';
}
},
{
id : 'height',
type : 'text',
style : 'width:100%',
labelLayout : 'vertical',
label : commonLang.height,
validate : CKEDITOR.dialog.validate.integer( commonLang.invalidHeight ),
setup : function( iframeNode, fakeImage )
{
loadValue.apply( this, arguments );
if ( fakeImage )
{
var fakeImageHeight = parseInt( fakeImage.$.style.height, 10 );
if ( !isNaN( fakeImageHeight ) )
this.setValue( fakeImageHeight );
}
},
commit : function( iframeNode, extraStyles )
{
commitValue.apply( this, arguments );
if ( this.getValue() )
extraStyles.height = this.getValue() + 'px';
}
},
{
id : 'align',
type : 'select',
'default' : '',
items :
[
[ commonLang.notSet , '' ],
[ commonLang.alignLeft , 'left' ],
[ commonLang.alignRight , 'right' ],
[ commonLang.alignTop , 'top' ],
[ commonLang.alignMiddle , 'middle' ],
[ commonLang.alignBottom , 'bottom' ]
],
style : 'width:100%',
labelLayout : 'vertical',
label : commonLang.align,
setup : function( iframeNode, fakeImage )
{
loadValue.apply( this, arguments );
if ( fakeImage )
{
var fakeImageAlign = fakeImage.getAttribute( 'align' );
this.setValue( fakeImageAlign && fakeImageAlign.toLowerCase() || '' );
}
},
commit : function( iframeNode, extraStyles, extraAttributes )
{
commitValue.apply( this, arguments );
if ( this.getValue() )
extraAttributes.align = this.getValue();
}
}
]
},
{
type : 'hbox',
widths : [ '50%', '50%' ],
children :
[
{
id : 'scrolling',
type : 'checkbox',
label : iframeLang.scrolling,
setup : loadValue,
commit : commitValue
},
{
id : 'frameborder',
type : 'checkbox',
label : iframeLang.border,
setup : loadValue,
commit : commitValue
}
]
},
{
type : 'hbox',
widths : [ '50%', '50%' ],
children :
[
{
id : 'name',
type : 'text',
label : commonLang.name,
setup : loadValue,
commit : commitValue
},
{
id : 'title',
type : 'text',
label : commonLang.advisoryTitle,
setup : loadValue,
commit : commitValue
}
]
},
{
id : 'longdesc',
type : 'text',
label : commonLang.longDescr,
setup : loadValue,
commit : commitValue
}
]
},
dialogadvtab && dialogadvtab.createAdvancedTab( editor, { id:1, classes:1, styles:1 })
]
};
});
})();
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
(function()
{
CKEDITOR.plugins.liststyle =
{
requires : [ 'dialog' ],
init : function( editor )
{
editor.addCommand( 'numberedListStyle', new CKEDITOR.dialogCommand( 'numberedListStyle' ) );
CKEDITOR.dialog.add( 'numberedListStyle', this.path + 'dialogs/liststyle.js' );
editor.addCommand( 'bulletedListStyle', new CKEDITOR.dialogCommand( 'bulletedListStyle' ) );
CKEDITOR.dialog.add( 'bulletedListStyle', this.path + 'dialogs/liststyle.js' );
// If the "menu" plugin is loaded, register the menu items.
if ( editor.addMenuItems )
{
//Register map group;
editor.addMenuGroup("list", 108);
editor.addMenuItems(
{
numberedlist :
{
label : editor.lang.list.numberedTitle,
group : 'list',
command: 'numberedListStyle'
},
bulletedlist :
{
label : editor.lang.list.bulletedTitle,
group : 'list',
command: 'bulletedListStyle'
}
});
}
// If the "contextmenu" plugin is loaded, register the listeners.
if ( editor.contextMenu )
{
editor.contextMenu.addListener( function( element, selection )
{
if ( !element || element.isReadOnly() )
return null;
while ( element )
{
var name = element.getName();
if ( name == 'ol' )
return { numberedlist: CKEDITOR.TRISTATE_OFF };
else if ( name == 'ul' )
return { bulletedlist: CKEDITOR.TRISTATE_OFF };
element = element.getParent();
}
return null;
});
}
}
};
CKEDITOR.plugins.add( 'liststyle', CKEDITOR.plugins.liststyle );
})();
| JavaScript |
/*
* Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.html or http://ckeditor.com/license
*/
(function()
{
function getListElement( editor, listTag )
{
var range;
try { range = editor.getSelection().getRanges()[ 0 ]; }
catch( e ) { return null; }
range.shrink( CKEDITOR.SHRINK_TEXT );
return range.getCommonAncestor().getAscendant( listTag, 1 );
}
var mapListStyle = {
'a' : 'lower-alpha',
'A' : 'upper-alpha',
'i' : 'lower-roman',
'I' : 'upper-roman',
'1' : 'decimal',
'disc' : 'disc',
'circle': 'circle',
'square' : 'square'
};
function listStyle( editor, startupPage )
{
var lang = editor.lang.list;
if ( startupPage == 'bulletedListStyle' )
{
return {
title : lang.bulletedTitle,
minWidth : 300,
minHeight : 50,
contents :
[
{
id : 'info',
accessKey : 'I',
elements :
[
{
type : 'select',
label : lang.type,
id : 'type',
style : 'width: 150px; margin: auto;',
items :
[
[ lang.notset, '' ],
[ lang.circle, 'circle' ],
[ lang.disc, 'disc' ],
[ lang.square, 'square' ]
],
setup : function( element )
{
var value = element.getStyle( 'list-style-type' )
|| mapListStyle[ element.getAttribute( 'type' ) ]
|| element.getAttribute( 'type' )
|| '';
this.setValue( value );
},
commit : function( element )
{
var value = this.getValue();
if ( value )
element.setStyle( 'list-style-type', value );
else
element.removeStyle( 'list-style-type' );
}
}
]
}
],
onShow: function()
{
var editor = this.getParentEditor(),
element = getListElement( editor, 'ul' );
element && this.setupContent( element );
},
onOk: function()
{
var editor = this.getParentEditor(),
element = getListElement( editor, 'ul' );
element && this.commitContent( element );
}
};
}
else if ( startupPage == 'numberedListStyle' )
{
var listStyleOptions =
[
[ lang.notset, '' ],
[ lang.lowerRoman, 'lower-roman' ],
[ lang.upperRoman, 'upper-roman' ],
[ lang.lowerAlpha, 'lower-alpha' ],
[ lang.upperAlpha, 'upper-alpha' ],
[ lang.decimal, 'decimal' ]
];
if ( !CKEDITOR.env.ie || CKEDITOR.env.version > 7 )
{
listStyleOptions.concat( [
[ lang.armenian, 'armenian' ],
[ lang.decimalLeadingZero, 'decimal-leading-zero' ],
[ lang.georgian, 'georgian' ],
[ lang.lowerGreek, 'lower-greek' ]
]);
}
return {
title : lang.numberedTitle,
minWidth : 300,
minHeight : 50,
contents :
[
{
id : 'info',
accessKey : 'I',
elements :
[
{
type : 'hbox',
widths : [ '25%', '75%' ],
children :
[
{
label : lang.start,
type : 'text',
id : 'start',
validate : CKEDITOR.dialog.validate.integer( lang.validateStartNumber ),
setup : function( element )
{
var value = element.getAttribute( 'start' ) || 1;
value && this.setValue( value );
},
commit : function( element )
{
element.setAttribute( 'start', this.getValue() );
}
},
{
type : 'select',
label : lang.type,
id : 'type',
style : 'width: 100%;',
items : listStyleOptions,
setup : function( element )
{
var value = element.getStyle( 'list-style-type' )
|| mapListStyle[ element.getAttribute( 'type' ) ]
|| element.getAttribute( 'type' )
|| '';
this.setValue( value );
},
commit : function( element )
{
var value = this.getValue();
if ( value )
element.setStyle( 'list-style-type', value );
else
element.removeStyle( 'list-style-type' );
}
}
]
}
]
}
],
onShow: function()
{
var editor = this.getParentEditor(),
element = getListElement( editor, 'ol' );
element && this.setupContent( element );
},
onOk: function()
{
var editor = this.getParentEditor(),
element = getListElement( editor, 'ol' );
element && this.commitContent( element );
}
};
}
}
CKEDITOR.dialog.add( 'numberedListStyle', function( editor )
{
return listStyle( editor, 'numberedListStyle' );
});
CKEDITOR.dialog.add( 'bulletedListStyle', function( editor )
{
return listStyle( editor, 'bulletedListStyle' );
});
})();
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
(function()
{
function removeRawAttribute( $node, attr )
{
if ( CKEDITOR.env.ie )
$node.removeAttribute( attr );
else
delete $node[ attr ];
}
var cellNodeRegex = /^(?:td|th)$/;
function getSelectedCells( selection )
{
// Walker will try to split text nodes, which will make the current selection
// invalid. So save bookmarks before doing anything.
var bookmarks = selection.createBookmarks();
var ranges = selection.getRanges();
var retval = [];
var database = {};
function moveOutOfCellGuard( node )
{
// Apply to the first cell only.
if ( retval.length > 0 )
return;
// If we are exiting from the first </td>, then the td should definitely be
// included.
if ( node.type == CKEDITOR.NODE_ELEMENT && cellNodeRegex.test( node.getName() )
&& !node.getCustomData( 'selected_cell' ) )
{
CKEDITOR.dom.element.setMarker( database, node, 'selected_cell', true );
retval.push( node );
}
}
for ( var i = 0 ; i < ranges.length ; i++ )
{
var range = ranges[ i ];
if ( range.collapsed )
{
// Walker does not handle collapsed ranges yet - fall back to old API.
var startNode = range.getCommonAncestor();
var nearestCell = startNode.getAscendant( 'td', true ) || startNode.getAscendant( 'th', true );
if ( nearestCell )
retval.push( nearestCell );
}
else
{
var walker = new CKEDITOR.dom.walker( range );
var node;
walker.guard = moveOutOfCellGuard;
while ( ( node = walker.next() ) )
{
// If may be possible for us to have a range like this:
// <td>^1</td><td>^2</td>
// The 2nd td shouldn't be included.
//
// So we have to take care to include a td we've entered only when we've
// walked into its children.
var parent = node.getParent();
if ( parent && cellNodeRegex.test( parent.getName() ) && !parent.getCustomData( 'selected_cell' ) )
{
CKEDITOR.dom.element.setMarker( database, parent, 'selected_cell', true );
retval.push( parent );
}
}
}
}
CKEDITOR.dom.element.clearAllMarkers( database );
// Restore selection position.
selection.selectBookmarks( bookmarks );
return retval;
}
function getFocusElementAfterDelCells( cellsToDelete ) {
var i = 0,
last = cellsToDelete.length - 1,
database = {},
cell,focusedCell,
tr;
while ( ( cell = cellsToDelete[ i++ ] ) )
CKEDITOR.dom.element.setMarker( database, cell, 'delete_cell', true );
// 1.first we check left or right side focusable cell row by row;
i = 0;
while ( ( cell = cellsToDelete[ i++ ] ) )
{
if ( ( focusedCell = cell.getPrevious() ) && !focusedCell.getCustomData( 'delete_cell' )
|| ( focusedCell = cell.getNext() ) && !focusedCell.getCustomData( 'delete_cell' ) )
{
CKEDITOR.dom.element.clearAllMarkers( database );
return focusedCell;
}
}
CKEDITOR.dom.element.clearAllMarkers( database );
// 2. then we check the toppest row (outside the selection area square) focusable cell
tr = cellsToDelete[ 0 ].getParent();
if ( ( tr = tr.getPrevious() ) )
return tr.getLast();
// 3. last we check the lowerest row focusable cell
tr = cellsToDelete[ last ].getParent();
if ( ( tr = tr.getNext() ) )
return tr.getChild( 0 );
return null;
}
function clearRow( $tr )
{
// Get the array of row's cells.
var $cells = $tr.cells;
// Empty all cells.
for ( var i = 0 ; i < $cells.length ; i++ )
{
$cells[ i ].innerHTML = '';
if ( !CKEDITOR.env.ie )
( new CKEDITOR.dom.element( $cells[ i ] ) ).appendBogus();
}
}
function insertRow( selection, insertBefore )
{
// Get the row where the selection is placed in.
var row = selection.getStartElement().getAscendant( 'tr' );
if ( !row )
return;
// Create a clone of the row.
var newRow = row.clone( 1 );
insertBefore ?
newRow.insertBefore( row ) :
newRow.insertAfter( row );
// Clean the new row.
clearRow( newRow.$ );
}
function deleteRows( selectionOrRow )
{
if ( selectionOrRow instanceof CKEDITOR.dom.selection )
{
var cells = getSelectedCells( selectionOrRow ),
cellsCount = cells.length,
rowsToDelete = [],
cursorPosition,
previousRowIndex,
nextRowIndex;
// Queue up the rows - it's possible and likely that we have duplicates.
for ( var i = 0 ; i < cellsCount ; i++ )
{
var row = cells[ i ].getParent(),
rowIndex = row.$.rowIndex;
!i && ( previousRowIndex = rowIndex - 1 );
rowsToDelete[ rowIndex ] = row;
i == cellsCount - 1 && ( nextRowIndex = rowIndex + 1 );
}
var table = row.getAscendant( 'table' ),
rows = table.$.rows,
rowCount = rows.length;
// Where to put the cursor after rows been deleted?
// 1. Into next sibling row if any;
// 2. Into previous sibling row if any;
// 3. Into table's parent element if it's the very last row.
cursorPosition = new CKEDITOR.dom.element(
nextRowIndex < rowCount && table.$.rows[ nextRowIndex ] ||
previousRowIndex > 0 && table.$.rows[ previousRowIndex ] ||
table.$.parentNode );
for ( i = rowsToDelete.length ; i >= 0 ; i-- )
{
if ( rowsToDelete[ i ] )
deleteRows( rowsToDelete[ i ] );
}
return cursorPosition;
}
else if ( selectionOrRow instanceof CKEDITOR.dom.element )
{
table = selectionOrRow.getAscendant( 'table' );
if ( table.$.rows.length == 1 )
table.remove();
else
selectionOrRow.remove();
}
return 0;
}
function insertColumn( selection, insertBefore )
{
// Get the cell where the selection is placed in.
var startElement = selection.getStartElement();
var cell = startElement.getAscendant( 'td', 1 ) || startElement.getAscendant( 'th', 1 );
if ( !cell )
return;
// Get the cell's table.
var table = cell.getAscendant( 'table' );
var cellIndex = cell.$.cellIndex;
// Loop through all rows available in the table.
for ( var i = 0 ; i < table.$.rows.length ; i++ )
{
var $row = table.$.rows[ i ];
// If the row doesn't have enough cells, ignore it.
if ( $row.cells.length < ( cellIndex + 1 ) )
continue;
cell = ( new CKEDITOR.dom.element( $row.cells[ cellIndex ] ) ).clone( 0 );
if ( !CKEDITOR.env.ie )
cell.appendBogus();
// Get back the currently selected cell.
var baseCell = new CKEDITOR.dom.element( $row.cells[ cellIndex ] );
if ( insertBefore )
cell.insertBefore( baseCell );
else
cell.insertAfter( baseCell );
}
}
function getFocusElementAfterDelCols( cells )
{
var cellIndexList = [],
table = cells[ 0 ] && cells[ 0 ].getAscendant( 'table' ),
i, length,
targetIndex, targetCell;
// get the cellIndex list of delete cells
for ( i = 0, length = cells.length; i < length; i++ )
cellIndexList.push( cells[i].$.cellIndex );
// get the focusable column index
cellIndexList.sort();
for ( i = 1, length = cellIndexList.length; i < length; i++ )
{
if ( cellIndexList[ i ] - cellIndexList[ i - 1 ] > 1 )
{
targetIndex = cellIndexList[ i - 1 ] + 1;
break;
}
}
if ( !targetIndex )
targetIndex = cellIndexList[ 0 ] > 0 ? ( cellIndexList[ 0 ] - 1 )
: ( cellIndexList[ cellIndexList.length - 1 ] + 1 );
// scan row by row to get the target cell
var rows = table.$.rows;
for ( i = 0, length = rows.length; i < length ; i++ )
{
targetCell = rows[ i ].cells[ targetIndex ];
if ( targetCell )
break;
}
return targetCell ? new CKEDITOR.dom.element( targetCell ) : table.getPrevious();
}
function deleteColumns( selectionOrCell )
{
if ( selectionOrCell instanceof CKEDITOR.dom.selection )
{
var colsToDelete = getSelectedCells( selectionOrCell ),
elementToFocus = getFocusElementAfterDelCols( colsToDelete );
for ( var i = colsToDelete.length - 1 ; i >= 0 ; i-- )
{
if ( colsToDelete[ i ] )
deleteColumns( colsToDelete[ i ] );
}
return elementToFocus;
}
else if ( selectionOrCell instanceof CKEDITOR.dom.element )
{
// Get the cell's table.
var table = selectionOrCell.getAscendant( 'table' );
if ( !table )
return null;
// Get the cell index.
var cellIndex = selectionOrCell.$.cellIndex;
/*
* Loop through all rows from down to up, coz it's possible that some rows
* will be deleted.
*/
for ( i = table.$.rows.length - 1 ; i >= 0 ; i-- )
{
// Get the row.
var row = new CKEDITOR.dom.element( table.$.rows[ i ] );
// If the cell to be removed is the first one and the row has just one cell.
if ( !cellIndex && row.$.cells.length == 1 )
{
deleteRows( row );
continue;
}
// Else, just delete the cell.
if ( row.$.cells[ cellIndex ] )
row.$.removeChild( row.$.cells[ cellIndex ] );
}
}
return null;
}
function insertCell( selection, insertBefore )
{
var startElement = selection.getStartElement();
var cell = startElement.getAscendant( 'td', 1 ) || startElement.getAscendant( 'th', 1 );
if ( !cell )
return;
// Create the new cell element to be added.
var newCell = cell.clone();
if ( !CKEDITOR.env.ie )
newCell.appendBogus();
if ( insertBefore )
newCell.insertBefore( cell );
else
newCell.insertAfter( cell );
}
function deleteCells( selectionOrCell )
{
if ( selectionOrCell instanceof CKEDITOR.dom.selection )
{
var cellsToDelete = getSelectedCells( selectionOrCell );
var table = cellsToDelete[ 0 ] && cellsToDelete[ 0 ].getAscendant( 'table' );
var cellToFocus = getFocusElementAfterDelCells( cellsToDelete );
for ( var i = cellsToDelete.length - 1 ; i >= 0 ; i-- )
deleteCells( cellsToDelete[ i ] );
if ( cellToFocus )
placeCursorInCell( cellToFocus, true );
else if ( table )
table.remove();
}
else if ( selectionOrCell instanceof CKEDITOR.dom.element )
{
var tr = selectionOrCell.getParent();
if ( tr.getChildCount() == 1 )
tr.remove();
else
selectionOrCell.remove();
}
}
// Remove filler at end and empty spaces around the cell content.
function trimCell( cell )
{
var bogus = cell.getBogus();
bogus && bogus.remove();
cell.trim();
}
function placeCursorInCell( cell, placeAtEnd )
{
var range = new CKEDITOR.dom.range( cell.getDocument() );
if ( !range[ 'moveToElementEdit' + ( placeAtEnd ? 'End' : 'Start' ) ]( cell ) )
{
range.selectNodeContents( cell );
range.collapse( placeAtEnd ? false : true );
}
range.select( true );
}
function cellInRow( tableMap, rowIndex, cell )
{
var oRow = tableMap[ rowIndex ];
if ( typeof cell == 'undefined' )
return oRow;
for ( var c = 0 ; oRow && c < oRow.length ; c++ )
{
if ( cell.is && oRow[c] == cell.$ )
return c;
else if ( c == cell )
return new CKEDITOR.dom.element( oRow[ c ] );
}
return cell.is ? -1 : null;
}
function cellInCol( tableMap, colIndex, cell )
{
var oCol = [];
for ( var r = 0; r < tableMap.length; r++ )
{
var row = tableMap[ r ];
if ( typeof cell == 'undefined' )
oCol.push( row[ colIndex ] );
else if ( cell.is && row[ colIndex ] == cell.$ )
return r;
else if ( r == cell )
return new CKEDITOR.dom.element( row[ colIndex ] );
}
return ( typeof cell == 'undefined' )? oCol : cell.is ? -1 : null;
}
function mergeCells( selection, mergeDirection, isDetect )
{
var cells = getSelectedCells( selection );
// Invalid merge request if:
// 1. In batch mode despite that less than two selected.
// 2. In solo mode while not exactly only one selected.
// 3. Cells distributed in different table groups (e.g. from both thead and tbody).
var commonAncestor;
if ( ( mergeDirection ? cells.length != 1 : cells.length < 2 )
|| ( commonAncestor = selection.getCommonAncestor() )
&& commonAncestor.type == CKEDITOR.NODE_ELEMENT
&& commonAncestor.is( 'table' ) )
{
return false;
}
var cell,
firstCell = cells[ 0 ],
table = firstCell.getAscendant( 'table' ),
map = CKEDITOR.tools.buildTableMap( table ),
mapHeight = map.length,
mapWidth = map[ 0 ].length,
startRow = firstCell.getParent().$.rowIndex,
startColumn = cellInRow( map, startRow, firstCell );
if ( mergeDirection )
{
var targetCell;
try
{
targetCell =
map[ mergeDirection == 'up' ?
( startRow - 1 ):
mergeDirection == 'down' ? ( startRow + 1 ) : startRow ] [
mergeDirection == 'left' ?
( startColumn - 1 ):
mergeDirection == 'right' ? ( startColumn + 1 ) : startColumn ];
}
catch( er )
{
return false;
}
// 1. No cell could be merged.
// 2. Same cell actually.
if ( !targetCell || firstCell.$ == targetCell )
return false;
// Sort in map order regardless of the DOM sequence.
cells[ ( mergeDirection == 'up' || mergeDirection == 'left' ) ?
'unshift' : 'push' ]( new CKEDITOR.dom.element( targetCell ) );
}
// Start from here are merging way ignorance (merge up/right, batch merge).
var doc = firstCell.getDocument(),
lastRowIndex = startRow,
totalRowSpan = 0,
totalColSpan = 0,
// Use a documentFragment as buffer when appending cell contents.
frag = !isDetect && new CKEDITOR.dom.documentFragment( doc ),
dimension = 0;
for ( var i = 0; i < cells.length; i++ )
{
cell = cells[ i ];
var tr = cell.getParent(),
cellFirstChild = cell.getFirst(),
colSpan = cell.$.colSpan,
rowSpan = cell.$.rowSpan,
rowIndex = tr.$.rowIndex,
colIndex = cellInRow( map, rowIndex, cell );
// Accumulated the actual places taken by all selected cells.
dimension += colSpan * rowSpan;
// Accumulated the maximum virtual spans from column and row.
totalColSpan = Math.max( totalColSpan, colIndex - startColumn + colSpan ) ;
totalRowSpan = Math.max( totalRowSpan, rowIndex - startRow + rowSpan );
if ( !isDetect )
{
// Trim all cell fillers and check to remove empty cells.
if ( trimCell( cell ), cell.getChildren().count() )
{
// Merge vertically cells as two separated paragraphs.
if ( rowIndex != lastRowIndex
&& cellFirstChild
&& !( cellFirstChild.isBlockBoundary
&& cellFirstChild.isBlockBoundary( { br : 1 } ) ) )
{
var last = frag.getLast( CKEDITOR.dom.walker.whitespaces( true ) );
if ( last && !( last.is && last.is( 'br' ) ) )
frag.append( new CKEDITOR.dom.element( 'br' ) );
}
cell.moveChildren( frag );
}
i ? cell.remove() : cell.setHtml( '' );
}
lastRowIndex = rowIndex;
}
if ( !isDetect )
{
frag.moveChildren( firstCell );
if ( !CKEDITOR.env.ie )
firstCell.appendBogus();
if ( totalColSpan >= mapWidth )
firstCell.removeAttribute( 'rowSpan' );
else
firstCell.$.rowSpan = totalRowSpan;
if ( totalRowSpan >= mapHeight )
firstCell.removeAttribute( 'colSpan' );
else
firstCell.$.colSpan = totalColSpan;
// Swip empty <tr> left at the end of table due to the merging.
var trs = new CKEDITOR.dom.nodeList( table.$.rows ),
count = trs.count();
for ( i = count - 1; i >= 0; i-- )
{
var tailTr = trs.getItem( i );
if ( !tailTr.$.cells.length )
{
tailTr.remove();
count++;
continue;
}
}
return firstCell;
}
// Be able to merge cells only if actual dimension of selected
// cells equals to the caculated rectangle.
else
return ( totalRowSpan * totalColSpan ) == dimension;
}
function verticalSplitCell ( selection, isDetect )
{
var cells = getSelectedCells( selection );
if ( cells.length > 1 )
return false;
else if ( isDetect )
return true;
var cell = cells[ 0 ],
tr = cell.getParent(),
table = tr.getAscendant( 'table' ),
map = CKEDITOR.tools.buildTableMap( table ),
rowIndex = tr.$.rowIndex,
colIndex = cellInRow( map, rowIndex, cell ),
rowSpan = cell.$.rowSpan,
newCell,
newRowSpan,
newCellRowSpan,
newRowIndex;
if ( rowSpan > 1 )
{
newRowSpan = Math.ceil( rowSpan / 2 );
newCellRowSpan = Math.floor( rowSpan / 2 );
newRowIndex = rowIndex + newRowSpan;
var newCellTr = new CKEDITOR.dom.element( table.$.rows[ newRowIndex ] ),
newCellRow = cellInRow( map, newRowIndex ),
candidateCell;
newCell = cell.clone();
// Figure out where to insert the new cell by checking the vitual row.
for ( var c = 0; c < newCellRow.length; c++ )
{
candidateCell = newCellRow[ c ];
// Catch first cell actually following the column.
if ( candidateCell.parentNode == newCellTr.$
&& c > colIndex )
{
newCell.insertBefore( new CKEDITOR.dom.element( candidateCell ) );
break;
}
else
candidateCell = null;
}
// The destination row is empty, append at will.
if ( !candidateCell )
newCellTr.append( newCell, true );
}
else
{
newCellRowSpan = newRowSpan = 1;
newCellTr = tr.clone();
newCellTr.insertAfter( tr );
newCellTr.append( newCell = cell.clone() );
var cellsInSameRow = cellInRow( map, rowIndex );
for ( var i = 0; i < cellsInSameRow.length; i++ )
cellsInSameRow[ i ].rowSpan++;
}
if ( !CKEDITOR.env.ie )
newCell.appendBogus();
cell.$.rowSpan = newRowSpan;
newCell.$.rowSpan = newCellRowSpan;
if ( newRowSpan == 1 )
cell.removeAttribute( 'rowSpan' );
if ( newCellRowSpan == 1 )
newCell.removeAttribute( 'rowSpan' );
return newCell;
}
function horizontalSplitCell( selection, isDetect )
{
var cells = getSelectedCells( selection );
if ( cells.length > 1 )
return false;
else if ( isDetect )
return true;
var cell = cells[ 0 ],
tr = cell.getParent(),
table = tr.getAscendant( 'table' ),
map = CKEDITOR.tools.buildTableMap( table ),
rowIndex = tr.$.rowIndex,
colIndex = cellInRow( map, rowIndex, cell ),
colSpan = cell.$.colSpan,
newCell,
newColSpan,
newCellColSpan;
if ( colSpan > 1 )
{
newColSpan = Math.ceil( colSpan / 2 );
newCellColSpan = Math.floor( colSpan / 2 );
}
else
{
newCellColSpan = newColSpan = 1;
var cellsInSameCol = cellInCol( map, colIndex );
for ( var i = 0; i < cellsInSameCol.length; i++ )
cellsInSameCol[ i ].colSpan++;
}
newCell = cell.clone();
newCell.insertAfter( cell );
if ( !CKEDITOR.env.ie )
newCell.appendBogus();
cell.$.colSpan = newColSpan;
newCell.$.colSpan = newCellColSpan;
if ( newColSpan == 1 )
cell.removeAttribute( 'colSpan' );
if ( newCellColSpan == 1 )
newCell.removeAttribute( 'colSpan' );
return newCell;
}
// Context menu on table caption incorrect (#3834)
var contextMenuTags = { thead : 1, tbody : 1, tfoot : 1, td : 1, tr : 1, th : 1 };
CKEDITOR.plugins.tabletools =
{
init : function( editor )
{
var lang = editor.lang.table;
editor.addCommand( 'cellProperties', new CKEDITOR.dialogCommand( 'cellProperties' ) );
CKEDITOR.dialog.add( 'cellProperties', this.path + 'dialogs/tableCell.js' );
editor.addCommand( 'tableDelete',
{
exec : function( editor )
{
var selection = editor.getSelection(),
startElement = selection && selection.getStartElement(),
table = startElement && startElement.getAscendant( 'table', 1 );
if ( !table )
return;
// Maintain the selection point at where the table was deleted.
selection.selectElement( table );
var range = selection.getRanges()[0];
range.collapse();
selection.selectRanges( [ range ] );
// If the table's parent has only one child remove it as well (unless it's the body or a table cell) (#5416, #6289)
var parent = table.getParent();
if ( parent.getChildCount() == 1 && !parent.is( 'body', 'td', 'th' ) )
parent.remove();
else
table.remove();
}
} );
editor.addCommand( 'rowDelete',
{
exec : function( editor )
{
var selection = editor.getSelection();
placeCursorInCell( deleteRows( selection ) );
}
} );
editor.addCommand( 'rowInsertBefore',
{
exec : function( editor )
{
var selection = editor.getSelection();
insertRow( selection, true );
}
} );
editor.addCommand( 'rowInsertAfter',
{
exec : function( editor )
{
var selection = editor.getSelection();
insertRow( selection );
}
} );
editor.addCommand( 'columnDelete',
{
exec : function( editor )
{
var selection = editor.getSelection();
var element = deleteColumns( selection );
element && placeCursorInCell( element, true );
}
} );
editor.addCommand( 'columnInsertBefore',
{
exec : function( editor )
{
var selection = editor.getSelection();
insertColumn( selection, true );
}
} );
editor.addCommand( 'columnInsertAfter',
{
exec : function( editor )
{
var selection = editor.getSelection();
insertColumn( selection );
}
} );
editor.addCommand( 'cellDelete',
{
exec : function( editor )
{
var selection = editor.getSelection();
deleteCells( selection );
}
} );
editor.addCommand( 'cellMerge',
{
exec : function( editor )
{
placeCursorInCell( mergeCells( editor.getSelection() ), true );
}
} );
editor.addCommand( 'cellMergeRight',
{
exec : function( editor )
{
placeCursorInCell( mergeCells( editor.getSelection(), 'right' ), true );
}
} );
editor.addCommand( 'cellMergeDown',
{
exec : function( editor )
{
placeCursorInCell( mergeCells( editor.getSelection(), 'down' ), true );
}
} );
editor.addCommand( 'cellVerticalSplit',
{
exec : function( editor )
{
placeCursorInCell( verticalSplitCell( editor.getSelection() ) );
}
} );
editor.addCommand( 'cellHorizontalSplit',
{
exec : function( editor )
{
placeCursorInCell( horizontalSplitCell( editor.getSelection() ) );
}
} );
editor.addCommand( 'cellInsertBefore',
{
exec : function( editor )
{
var selection = editor.getSelection();
insertCell( selection, true );
}
} );
editor.addCommand( 'cellInsertAfter',
{
exec : function( editor )
{
var selection = editor.getSelection();
insertCell( selection );
}
} );
// If the "menu" plugin is loaded, register the menu items.
if ( editor.addMenuItems )
{
editor.addMenuItems(
{
tablecell :
{
label : lang.cell.menu,
group : 'tablecell',
order : 1,
getItems : function()
{
var selection = editor.getSelection(),
cells = getSelectedCells( selection );
return {
tablecell_insertBefore : CKEDITOR.TRISTATE_OFF,
tablecell_insertAfter : CKEDITOR.TRISTATE_OFF,
tablecell_delete : CKEDITOR.TRISTATE_OFF,
tablecell_merge : mergeCells( selection, null, true ) ? CKEDITOR.TRISTATE_OFF : CKEDITOR.TRISTATE_DISABLED,
tablecell_merge_right : mergeCells( selection, 'right', true ) ? CKEDITOR.TRISTATE_OFF : CKEDITOR.TRISTATE_DISABLED,
tablecell_merge_down : mergeCells( selection, 'down', true ) ? CKEDITOR.TRISTATE_OFF : CKEDITOR.TRISTATE_DISABLED,
tablecell_split_vertical : verticalSplitCell( selection, true ) ? CKEDITOR.TRISTATE_OFF : CKEDITOR.TRISTATE_DISABLED,
tablecell_split_horizontal : horizontalSplitCell( selection, true ) ? CKEDITOR.TRISTATE_OFF : CKEDITOR.TRISTATE_DISABLED,
tablecell_properties : cells.length > 0 ? CKEDITOR.TRISTATE_OFF : CKEDITOR.TRISTATE_DISABLED
};
}
},
tablecell_insertBefore :
{
label : lang.cell.insertBefore,
group : 'tablecell',
command : 'cellInsertBefore',
order : 5
},
tablecell_insertAfter :
{
label : lang.cell.insertAfter,
group : 'tablecell',
command : 'cellInsertAfter',
order : 10
},
tablecell_delete :
{
label : lang.cell.deleteCell,
group : 'tablecell',
command : 'cellDelete',
order : 15
},
tablecell_merge :
{
label : lang.cell.merge,
group : 'tablecell',
command : 'cellMerge',
order : 16
},
tablecell_merge_right :
{
label : lang.cell.mergeRight,
group : 'tablecell',
command : 'cellMergeRight',
order : 17
},
tablecell_merge_down :
{
label : lang.cell.mergeDown,
group : 'tablecell',
command : 'cellMergeDown',
order : 18
},
tablecell_split_horizontal :
{
label : lang.cell.splitHorizontal,
group : 'tablecell',
command : 'cellHorizontalSplit',
order : 19
},
tablecell_split_vertical :
{
label : lang.cell.splitVertical,
group : 'tablecell',
command : 'cellVerticalSplit',
order : 20
},
tablecell_properties :
{
label : lang.cell.title,
group : 'tablecellproperties',
command : 'cellProperties',
order : 21
},
tablerow :
{
label : lang.row.menu,
group : 'tablerow',
order : 1,
getItems : function()
{
return {
tablerow_insertBefore : CKEDITOR.TRISTATE_OFF,
tablerow_insertAfter : CKEDITOR.TRISTATE_OFF,
tablerow_delete : CKEDITOR.TRISTATE_OFF
};
}
},
tablerow_insertBefore :
{
label : lang.row.insertBefore,
group : 'tablerow',
command : 'rowInsertBefore',
order : 5
},
tablerow_insertAfter :
{
label : lang.row.insertAfter,
group : 'tablerow',
command : 'rowInsertAfter',
order : 10
},
tablerow_delete :
{
label : lang.row.deleteRow,
group : 'tablerow',
command : 'rowDelete',
order : 15
},
tablecolumn :
{
label : lang.column.menu,
group : 'tablecolumn',
order : 1,
getItems : function()
{
return {
tablecolumn_insertBefore : CKEDITOR.TRISTATE_OFF,
tablecolumn_insertAfter : CKEDITOR.TRISTATE_OFF,
tablecolumn_delete : CKEDITOR.TRISTATE_OFF
};
}
},
tablecolumn_insertBefore :
{
label : lang.column.insertBefore,
group : 'tablecolumn',
command : 'columnInsertBefore',
order : 5
},
tablecolumn_insertAfter :
{
label : lang.column.insertAfter,
group : 'tablecolumn',
command : 'columnInsertAfter',
order : 10
},
tablecolumn_delete :
{
label : lang.column.deleteColumn,
group : 'tablecolumn',
command : 'columnDelete',
order : 15
}
});
}
// If the "contextmenu" plugin is laoded, register the listeners.
if ( editor.contextMenu )
{
editor.contextMenu.addListener( function( element, selection )
{
if ( !element || element.isReadOnly() )
return null;
while ( element )
{
if ( element.getName() in contextMenuTags )
{
return {
tablecell : CKEDITOR.TRISTATE_OFF,
tablerow : CKEDITOR.TRISTATE_OFF,
tablecolumn : CKEDITOR.TRISTATE_OFF
};
}
element = element.getParent();
}
return null;
} );
}
},
getSelectedCells : getSelectedCells
};
CKEDITOR.plugins.add( 'tabletools', CKEDITOR.plugins.tabletools );
})();
/**
* Create a two-dimension array that reflects the actual layout of table cells,
* with cell spans, with mappings to the original td elements.
* @param table {CKEDITOR.dom.element}
*/
CKEDITOR.tools.buildTableMap = function ( table )
{
var aRows = table.$.rows ;
// Row and Column counters.
var r = -1 ;
var aMap = [];
for ( var i = 0 ; i < aRows.length ; i++ )
{
r++ ;
!aMap[r] && ( aMap[r] = [] );
var c = -1 ;
for ( var j = 0 ; j < aRows[i].cells.length ; j++ )
{
var oCell = aRows[i].cells[j] ;
c++ ;
while ( aMap[r][c] )
c++ ;
var iColSpan = isNaN( oCell.colSpan ) ? 1 : oCell.colSpan ;
var iRowSpan = isNaN( oCell.rowSpan ) ? 1 : oCell.rowSpan ;
for ( var rs = 0 ; rs < iRowSpan ; rs++ )
{
if ( !aMap[r + rs] )
aMap[r + rs] = [];
for ( var cs = 0 ; cs < iColSpan ; cs++ )
{
aMap[r + rs][c + cs] = aRows[i].cells[j] ;
}
}
c += iColSpan - 1 ;
}
}
return aMap ;
};
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.dialog.add( 'cellProperties', function( editor )
{
var langTable = editor.lang.table,
langCell = langTable.cell,
langCommon = editor.lang.common,
validate = CKEDITOR.dialog.validate,
widthPattern = /^(\d+(?:\.\d+)?)(px|%)$/,
heightPattern = /^(\d+(?:\.\d+)?)px$/,
bind = CKEDITOR.tools.bind,
spacer = { type : 'html', html : ' ' },
rtl = editor.lang.dir == 'rtl';
/**
*
* @param dialogName
* @param callback [ childDialog ]
*/
function getDialogValue( dialogName, callback )
{
var onOk = function()
{
releaseHandlers( this );
callback( this, this._.parentDialog );
this._.parentDialog.changeFocus( true );
};
var onCancel = function()
{
releaseHandlers( this );
this._.parentDialog.changeFocus();
};
var releaseHandlers = function( dialog )
{
dialog.removeListener( 'ok', onOk );
dialog.removeListener( 'cancel', onCancel );
};
var bindToDialog = function( dialog )
{
dialog.on( 'ok', onOk );
dialog.on( 'cancel', onCancel );
};
editor.execCommand( dialogName );
if ( editor._.storedDialogs.colordialog )
bindToDialog( editor._.storedDialogs.colordialog );
else
{
CKEDITOR.on( 'dialogDefinition', function( e )
{
if ( e.data.name != dialogName )
return;
var definition = e.data.definition;
e.removeListener();
definition.onLoad = CKEDITOR.tools.override( definition.onLoad, function( orginal )
{
return function()
{
bindToDialog( this );
definition.onLoad = orginal;
if ( typeof orginal == 'function' )
orginal.call( this );
};
} );
});
}
}
return {
title : langCell.title,
minWidth : CKEDITOR.env.ie && CKEDITOR.env.quirks? 450 : 410,
minHeight : CKEDITOR.env.ie && CKEDITOR.env.quirks? 230 : 200,
contents : [
{
id : 'info',
label : langCell.title,
accessKey : 'I',
elements :
[
{
type : 'hbox',
widths : [ '40%', '5%', '40%' ],
children :
[
{
type : 'vbox',
padding : 0,
children :
[
{
type : 'hbox',
widths : [ '70%', '30%' ],
children :
[
{
type : 'text',
id : 'width',
width: '100px',
label : langCommon.width,
validate : validate[ 'number' ]( langCell.invalidWidth ),
// Extra labelling of width unit type.
onLoad : function()
{
var widthType = this.getDialog().getContentElement( 'info', 'widthType' ),
labelElement = widthType.getElement(),
inputElement = this.getInputElement(),
ariaLabelledByAttr = inputElement.getAttribute( 'aria-labelledby' );
inputElement.setAttribute( 'aria-labelledby', [ ariaLabelledByAttr, labelElement.$.id ].join( ' ' ) );
},
setup : function( element )
{
var widthAttr = parseInt( element.getAttribute( 'width' ), 10 ),
widthStyle = parseInt( element.getStyle( 'width' ), 10 );
!isNaN( widthAttr ) && this.setValue( widthAttr );
!isNaN( widthStyle ) && this.setValue( widthStyle );
},
commit : function( element )
{
var value = parseInt( this.getValue(), 10 ),
unit = this.getDialog().getValueOf( 'info', 'widthType' );
if ( !isNaN( value ) )
element.setStyle( 'width', value + unit );
else
element.removeStyle( 'width' );
element.removeAttribute( 'width' );
},
'default' : ''
},
{
type : 'select',
id : 'widthType',
label : editor.lang.table.widthUnit,
labelStyle: 'visibility:hidden',
'default' : 'px',
items :
[
[ langTable.widthPx, 'px' ],
[ langTable.widthPc, '%' ]
],
setup : function( selectedCell )
{
var widthMatch = widthPattern.exec( selectedCell.getStyle( 'width' ) || selectedCell.getAttribute( 'width' ) );
if ( widthMatch )
this.setValue( widthMatch[2] );
}
}
]
},
{
type : 'hbox',
widths : [ '70%', '30%' ],
children :
[
{
type : 'text',
id : 'height',
label : langCommon.height,
width: '100px',
'default' : '',
validate : validate[ 'number' ]( langCell.invalidHeight ),
// Extra labelling of height unit type.
onLoad : function()
{
var heightType = this.getDialog().getContentElement( 'info', 'htmlHeightType' ),
labelElement = heightType.getElement(),
inputElement = this.getInputElement(),
ariaLabelledByAttr = inputElement.getAttribute( 'aria-labelledby' );
inputElement.setAttribute( 'aria-labelledby', [ ariaLabelledByAttr, labelElement.$.id ].join( ' ' ) );
},
setup : function( element )
{
var heightAttr = parseInt( element.getAttribute( 'height' ), 10 ),
heightStyle = parseInt( element.getStyle( 'height' ), 10 );
!isNaN( heightAttr ) && this.setValue( heightAttr );
!isNaN( heightStyle ) && this.setValue( heightStyle );
},
commit : function( element )
{
var value = parseInt( this.getValue(), 10 );
if ( !isNaN( value ) )
element.setStyle( 'height', CKEDITOR.tools.cssLength( value ) );
else
element.removeStyle( 'height' );
element.removeAttribute( 'height' );
}
},
{
id : 'htmlHeightType',
type : 'html',
html : '<br />'+ langTable.widthPx
}
]
},
spacer,
{
type : 'select',
id : 'wordWrap',
label : langCell.wordWrap,
'default' : 'yes',
items :
[
[ langCell.yes, 'yes' ],
[ langCell.no, 'no' ]
],
setup : function( element )
{
var wordWrapAttr = element.getAttribute( 'noWrap' ),
wordWrapStyle = element.getStyle( 'white-space' );
if ( wordWrapStyle == 'nowrap' || wordWrapAttr )
this.setValue( 'no' );
},
commit : function( element )
{
if ( this.getValue() == 'no' )
element.setStyle( 'white-space', 'nowrap' );
else
element.removeStyle( 'white-space' );
element.removeAttribute( 'noWrap' );
}
},
spacer,
{
type : 'select',
id : 'hAlign',
label : langCell.hAlign,
'default' : '',
items :
[
[ langCommon.notSet, '' ],
[ langCommon.alignLeft, 'left' ],
[ langCommon.alignCenter, 'center' ],
[ langCommon.alignRight, 'right' ]
],
setup : function( element )
{
var alignAttr = element.getAttribute( 'align' ),
textAlignStyle = element.getStyle( 'text-align');
this.setValue( textAlignStyle || alignAttr || '' );
},
commit : function( selectedCell )
{
var value = this.getValue();
if ( value )
selectedCell.setStyle( 'text-align', value );
else
selectedCell.removeStyle( 'text-align' );
selectedCell.removeAttribute( 'align' );
}
},
{
type : 'select',
id : 'vAlign',
label : langCell.vAlign,
'default' : '',
items :
[
[ langCommon.notSet, '' ],
[ langCommon.alignTop, 'top' ],
[ langCommon.alignMiddle, 'middle' ],
[ langCommon.alignBottom, 'bottom' ],
[ langCell.alignBaseline, 'baseline' ]
],
setup : function( element )
{
var vAlignAttr = element.getAttribute( 'vAlign' ),
vAlignStyle = element.getStyle( 'vertical-align' );
switch( vAlignStyle )
{
// Ignore all other unrelated style values..
case 'top':
case 'middle':
case 'bottom':
case 'baseline':
break;
default:
vAlignStyle = '';
}
this.setValue( vAlignStyle || vAlignAttr || '' );
},
commit : function( element )
{
var value = this.getValue();
if ( value )
element.setStyle( 'vertical-align', value );
else
element.removeStyle( 'vertical-align' );
element.removeAttribute( 'vAlign' );
}
}
]
},
spacer,
{
type : 'vbox',
padding : 0,
children :
[
{
type : 'select',
id : 'cellType',
label : langCell.cellType,
'default' : 'td',
items :
[
[ langCell.data, 'td' ],
[ langCell.header, 'th' ]
],
setup : function( selectedCell )
{
this.setValue( selectedCell.getName() );
},
commit : function( selectedCell )
{
selectedCell.renameNode( this.getValue() );
}
},
spacer,
{
type : 'text',
id : 'rowSpan',
label : langCell.rowSpan,
'default' : '',
validate : validate.integer( langCell.invalidRowSpan ),
setup : function( selectedCell )
{
var attrVal = parseInt( selectedCell.getAttribute( 'rowSpan' ), 10 );
if ( attrVal && attrVal != 1 )
this.setValue( attrVal );
},
commit : function( selectedCell )
{
var value = parseInt( this.getValue(), 10 );
if ( value && value != 1 )
selectedCell.setAttribute( 'rowSpan', this.getValue() );
else
selectedCell.removeAttribute( 'rowSpan' );
}
},
{
type : 'text',
id : 'colSpan',
label : langCell.colSpan,
'default' : '',
validate : validate.integer( langCell.invalidColSpan ),
setup : function( element )
{
var attrVal = parseInt( element.getAttribute( 'colSpan' ), 10 );
if ( attrVal && attrVal != 1 )
this.setValue( attrVal );
},
commit : function( selectedCell )
{
var value = parseInt( this.getValue(), 10 );
if ( value && value != 1 )
selectedCell.setAttribute( 'colSpan', this.getValue() );
else
selectedCell.removeAttribute( 'colSpan' );
}
},
spacer,
{
type : 'hbox',
padding : 0,
widths : [ '60%', '40%' ],
children :
[
{
type : 'text',
id : 'bgColor',
label : langCell.bgColor,
'default' : '',
setup : function( element )
{
var bgColorAttr = element.getAttribute( 'bgColor' ),
bgColorStyle = element.getStyle( 'background-color' );
this.setValue( bgColorStyle || bgColorAttr );
},
commit : function( selectedCell )
{
var value = this.getValue();
if ( value )
selectedCell.setStyle( 'background-color', this.getValue() );
else
selectedCell.removeStyle( 'background-color' );
selectedCell.removeAttribute( 'bgColor');
}
},
{
type : 'button',
id : 'bgColorChoose',
"class" : 'colorChooser',
label : langCell.chooseColor,
onLoad : function()
{
// Stick the element to the bottom (#5587)
this.getElement().getParent().setStyle( 'vertical-align', 'bottom' );
},
onClick : function()
{
var self = this;
getDialogValue( 'colordialog', function( colorDialog )
{
self.getDialog().getContentElement( 'info', 'bgColor' ).setValue(
colorDialog.getContentElement( 'picker', 'selectedColor' ).getValue()
);
} );
}
}
]
},
spacer,
{
type : 'hbox',
padding : 0,
widths : [ '60%', '40%' ],
children :
[
{
type : 'text',
id : 'borderColor',
label : langCell.borderColor,
'default' : '',
setup : function( element )
{
var borderColorAttr = element.getAttribute( 'borderColor' ),
borderColorStyle = element.getStyle( 'border-color' );
this.setValue( borderColorStyle || borderColorAttr );
},
commit : function( selectedCell )
{
var value = this.getValue();
if ( value )
selectedCell.setStyle( 'border-color', this.getValue() );
else
selectedCell.removeStyle( 'border-color' );
selectedCell.removeAttribute( 'borderColor');
}
},
{
type : 'button',
id : 'borderColorChoose',
"class" : 'colorChooser',
label : langCell.chooseColor,
style : ( rtl ? 'margin-right' : 'margin-left' ) + ': 10px',
onLoad : function()
{
// Stick the element to the bottom (#5587)
this.getElement().getParent().setStyle( 'vertical-align', 'bottom' );
},
onClick : function()
{
var self = this;
getDialogValue( 'colordialog', function( colorDialog )
{
self.getDialog().getContentElement( 'info', 'borderColor' ).setValue(
colorDialog.getContentElement( 'picker', 'selectedColor' ).getValue()
);
} );
}
}
]
}
]
}
]
}
]
}
],
onShow : function()
{
this.cells = CKEDITOR.plugins.tabletools.getSelectedCells(
this._.editor.getSelection() );
this.setupContent( this.cells[ 0 ] );
},
onOk : function()
{
var selection = this._.editor.getSelection(),
bookmarks = selection.createBookmarks();
var cells = this.cells;
for ( var i = 0 ; i < cells.length ; i++ )
this.commitContent( cells[ i ] );
selection.selectBookmarks( bookmarks );
// Force selectionChange event because of alignment style.
var firstElement = selection.getStartElement();
var currentPath = new CKEDITOR.dom.elementPath( firstElement );
this._.editor._.selectionPreviousPath = currentPath;
this._.editor.fire( 'selectionChange', { selection : selection, path : currentPath, element : firstElement } );
}
};
} );
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @file Image plugin
*/
CKEDITOR.plugins.add( 'image',
{
init : function( editor )
{
var pluginName = 'image';
// Register the dialog.
CKEDITOR.dialog.add( pluginName, this.path + 'dialogs/image.js' );
// Register the command.
editor.addCommand( pluginName, new CKEDITOR.dialogCommand( pluginName ) );
// Register the toolbar button.
editor.ui.addButton( 'Image',
{
label : editor.lang.common.image,
command : pluginName
});
editor.on( 'doubleclick', function( evt )
{
var element = evt.data.element;
if ( element.is( 'img' ) && !element.data( 'cke-realelement' ) )
evt.data.dialog = 'image';
});
// If the "menu" plugin is loaded, register the menu items.
if ( editor.addMenuItems )
{
editor.addMenuItems(
{
image :
{
label : editor.lang.image.menu,
command : 'image',
group : 'image'
}
});
}
// If the "contextmenu" plugin is loaded, register the listeners.
if ( editor.contextMenu )
{
editor.contextMenu.addListener( function( element, selection )
{
if ( !element || !element.is( 'img' ) || element.data( 'cke-realelement' ) || element.isReadOnly() )
return null;
return { image : CKEDITOR.TRISTATE_OFF };
});
}
}
} );
/**
* Whether to remove links when emptying the link URL field in the image dialog.
* @type Boolean
* @default true
* @example
* config.image_removeLinkByEmptyURL = false;
*/
CKEDITOR.config.image_removeLinkByEmptyURL = true;
/**
* Padding text to set off the image in preview area.
* @name CKEDITOR.config.image_previewText
* @type String
* @default "Lorem ipsum dolor..." placehoder text.
* @example
* config.image_previewText = CKEDITOR.tools.repeat( '___ ', 100 );
*/
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
(function()
{
var imageDialog = function( editor, dialogType )
{
// Load image preview.
var IMAGE = 1,
LINK = 2,
PREVIEW = 4,
CLEANUP = 8,
regexGetSize = /^\s*(\d+)((px)|\%)?\s*$/i,
regexGetSizeOrEmpty = /(^\s*(\d+)((px)|\%)?\s*$)|^$/i,
pxLengthRegex = /^\d+px$/;
var onSizeChange = function()
{
var value = this.getValue(), // This = input element.
dialog = this.getDialog(),
aMatch = value.match( regexGetSize ); // Check value
if ( aMatch )
{
if ( aMatch[2] == '%' ) // % is allowed - > unlock ratio.
switchLockRatio( dialog, false ); // Unlock.
value = aMatch[1];
}
// Only if ratio is locked
if ( dialog.lockRatio )
{
var oImageOriginal = dialog.originalElement;
if ( oImageOriginal.getCustomData( 'isReady' ) == 'true' )
{
if ( this.id == 'txtHeight' )
{
if ( value && value != '0' )
value = Math.round( oImageOriginal.$.width * ( value / oImageOriginal.$.height ) );
if ( !isNaN( value ) )
dialog.setValueOf( 'info', 'txtWidth', value );
}
else //this.id = txtWidth.
{
if ( value && value != '0' )
value = Math.round( oImageOriginal.$.height * ( value / oImageOriginal.$.width ) );
if ( !isNaN( value ) )
dialog.setValueOf( 'info', 'txtHeight', value );
}
}
}
updatePreview( dialog );
};
var updatePreview = function( dialog )
{
//Don't load before onShow.
if ( !dialog.originalElement || !dialog.preview )
return 1;
// Read attributes and update imagePreview;
dialog.commitContent( PREVIEW, dialog.preview );
return 0;
};
// Custom commit dialog logic, where we're intended to give inline style
// field (txtdlgGenStyle) higher priority to avoid overwriting styles contribute
// by other fields.
function commitContent()
{
var args = arguments;
var inlineStyleField = this.getContentElement( 'advanced', 'txtdlgGenStyle' );
inlineStyleField && inlineStyleField.commit.apply( inlineStyleField, args );
this.foreach( function( widget )
{
if ( widget.commit && widget.id != 'txtdlgGenStyle' )
widget.commit.apply( widget, args );
});
}
// Avoid recursions.
var incommit;
// Synchronous field values to other impacted fields is required, e.g. border
// size change should alter inline-style text as well.
function commitInternally( targetFields )
{
if ( incommit )
return;
incommit = 1;
var dialog = this.getDialog(),
element = dialog.imageElement;
if ( element )
{
// Commit this field and broadcast to target fields.
this.commit( IMAGE, element );
targetFields = [].concat( targetFields );
var length = targetFields.length,
field;
for ( var i = 0; i < length; i++ )
{
field = dialog.getContentElement.apply( dialog, targetFields[ i ].split( ':' ) );
// May cause recursion.
field && field.setup( IMAGE, element );
}
}
incommit = 0;
}
var switchLockRatio = function( dialog, value )
{
var oImageOriginal = dialog.originalElement;
// Dialog may already closed. (#5505)
if( !oImageOriginal )
return null;
var ratioButton = CKEDITOR.document.getById( btnLockSizesId );
if ( oImageOriginal.getCustomData( 'isReady' ) == 'true' )
{
if ( value == 'check' ) // Check image ratio and original image ratio.
{
var width = dialog.getValueOf( 'info', 'txtWidth' ),
height = dialog.getValueOf( 'info', 'txtHeight' ),
originalRatio = oImageOriginal.$.width * 1000 / oImageOriginal.$.height,
thisRatio = width * 1000 / height;
dialog.lockRatio = false; // Default: unlock ratio
if ( !width && !height )
dialog.lockRatio = true;
else if ( !isNaN( originalRatio ) && !isNaN( thisRatio ) )
{
if ( Math.round( originalRatio ) == Math.round( thisRatio ) )
dialog.lockRatio = true;
}
}
else if ( value != undefined )
dialog.lockRatio = value;
else
dialog.lockRatio = !dialog.lockRatio;
}
else if ( value != 'check' ) // I can't lock ratio if ratio is unknown.
dialog.lockRatio = false;
if ( dialog.lockRatio )
ratioButton.removeClass( 'cke_btn_unlocked' );
else
ratioButton.addClass( 'cke_btn_unlocked' );
var lang = dialog._.editor.lang.image,
label = lang[ dialog.lockRatio ? 'unlockRatio' : 'lockRatio' ];
ratioButton.setAttribute( 'title', label );
ratioButton.getFirst().setText( label );
return dialog.lockRatio;
};
var resetSize = function( dialog )
{
var oImageOriginal = dialog.originalElement;
if ( oImageOriginal.getCustomData( 'isReady' ) == 'true' )
{
dialog.setValueOf( 'info', 'txtWidth', oImageOriginal.$.width );
dialog.setValueOf( 'info', 'txtHeight', oImageOriginal.$.height );
}
updatePreview( dialog );
};
var setupDimension = function( type, element )
{
if ( type != IMAGE )
return;
function checkDimension( size, defaultValue )
{
var aMatch = size.match( regexGetSize );
if ( aMatch )
{
if ( aMatch[2] == '%' ) // % is allowed.
{
aMatch[1] += '%';
switchLockRatio( dialog, false ); // Unlock ratio
}
return aMatch[1];
}
return defaultValue;
}
var dialog = this.getDialog(),
value = '',
dimension = (( this.id == 'txtWidth' )? 'width' : 'height' ),
size = element.getAttribute( dimension );
if ( size )
value = checkDimension( size, value );
value = checkDimension( element.getStyle( dimension ), value );
this.setValue( value );
};
var previewPreloader;
var onImgLoadEvent = function()
{
// Image is ready.
var original = this.originalElement;
original.setCustomData( 'isReady', 'true' );
original.removeListener( 'load', onImgLoadEvent );
original.removeListener( 'error', onImgLoadErrorEvent );
original.removeListener( 'abort', onImgLoadErrorEvent );
// Hide loader
CKEDITOR.document.getById( imagePreviewLoaderId ).setStyle( 'display', 'none' );
// New image -> new domensions
if ( !this.dontResetSize )
resetSize( this );
if ( this.firstLoad )
CKEDITOR.tools.setTimeout( function(){ switchLockRatio( this, 'check' ); }, 0, this );
this.firstLoad = false;
this.dontResetSize = false;
};
var onImgLoadErrorEvent = function()
{
// Error. Image is not loaded.
var original = this.originalElement;
original.removeListener( 'load', onImgLoadEvent );
original.removeListener( 'error', onImgLoadErrorEvent );
original.removeListener( 'abort', onImgLoadErrorEvent );
// Set Error image.
var noimage = CKEDITOR.getUrl( editor.skinPath + 'images/noimage.png' );
if ( this.preview )
this.preview.setAttribute( 'src', noimage );
// Hide loader
CKEDITOR.document.getById( imagePreviewLoaderId ).setStyle( 'display', 'none' );
switchLockRatio( this, false ); // Unlock.
};
var numbering = function( id )
{
return CKEDITOR.tools.getNextId() + '_' + id;
},
btnLockSizesId = numbering( 'btnLockSizes' ),
btnResetSizeId = numbering( 'btnResetSize' ),
imagePreviewLoaderId = numbering( 'ImagePreviewLoader' ),
imagePreviewBoxId = numbering( 'ImagePreviewBox' ),
previewLinkId = numbering( 'previewLink' ),
previewImageId = numbering( 'previewImage' );
return {
title : ( dialogType == 'image' ) ? editor.lang.image.title : editor.lang.image.titleButton,
minWidth : 420,
minHeight : CKEDITOR.env.ie && CKEDITOR.env.quirks? 360: 310,
onShow : function()
{
this.imageElement = false;
this.linkElement = false;
// Default: create a new element.
this.imageEditMode = false;
this.linkEditMode = false;
this.lockRatio = true;
this.dontResetSize = false;
this.firstLoad = true;
this.addLink = false;
var editor = this.getParentEditor(),
sel = this.getParentEditor().getSelection(),
element = sel.getSelectedElement(),
link = element && element.getAscendant( 'a' );
//Hide loader.
CKEDITOR.document.getById( imagePreviewLoaderId ).setStyle( 'display', 'none' );
// Create the preview before setup the dialog contents.
previewPreloader = new CKEDITOR.dom.element( 'img', editor.document );
this.preview = CKEDITOR.document.getById( previewImageId );
// Copy of the image
this.originalElement = editor.document.createElement( 'img' );
this.originalElement.setAttribute( 'alt', '' );
this.originalElement.setCustomData( 'isReady', 'false' );
if ( link )
{
this.linkElement = link;
this.linkEditMode = true;
// Look for Image element.
var linkChildren = link.getChildren();
if ( linkChildren.count() == 1 ) // 1 child.
{
var childTagName = linkChildren.getItem( 0 ).getName();
if ( childTagName == 'img' || childTagName == 'input' )
{
this.imageElement = linkChildren.getItem( 0 );
if ( this.imageElement.getName() == 'img' )
this.imageEditMode = 'img';
else if ( this.imageElement.getName() == 'input' )
this.imageEditMode = 'input';
}
}
// Fill out all fields.
if ( dialogType == 'image' )
this.setupContent( LINK, link );
}
if ( element && element.getName() == 'img' && !element.data( 'cke-realelement' )
|| element && element.getName() == 'input' && element.getAttribute( 'type' ) == 'image' )
{
this.imageEditMode = element.getName();
this.imageElement = element;
}
if ( this.imageEditMode )
{
// Use the original element as a buffer from since we don't want
// temporary changes to be committed, e.g. if the dialog is canceled.
this.cleanImageElement = this.imageElement;
this.imageElement = this.cleanImageElement.clone( true, true );
// Fill out all fields.
this.setupContent( IMAGE, this.imageElement );
// Refresh LockRatio button
switchLockRatio ( this, true );
}
else
this.imageElement = editor.document.createElement( 'img' );
// Dont show preview if no URL given.
if ( !CKEDITOR.tools.trim( this.getValueOf( 'info', 'txtUrl' ) ) )
{
this.preview.removeAttribute( 'src' );
this.preview.setStyle( 'display', 'none' );
}
},
onOk : function()
{
// Edit existing Image.
if ( this.imageEditMode )
{
var imgTagName = this.imageEditMode;
// Image dialog and Input element.
if ( dialogType == 'image' && imgTagName == 'input' && confirm( editor.lang.image.button2Img ) )
{
// Replace INPUT-> IMG
imgTagName = 'img';
this.imageElement = editor.document.createElement( 'img' );
this.imageElement.setAttribute( 'alt', '' );
editor.insertElement( this.imageElement );
}
// ImageButton dialog and Image element.
else if ( dialogType != 'image' && imgTagName == 'img' && confirm( editor.lang.image.img2Button ))
{
// Replace IMG -> INPUT
imgTagName = 'input';
this.imageElement = editor.document.createElement( 'input' );
this.imageElement.setAttributes(
{
type : 'image',
alt : ''
}
);
editor.insertElement( this.imageElement );
}
else
{
// Restore the original element before all commits.
this.imageElement = this.cleanImageElement;
delete this.cleanImageElement;
}
}
else // Create a new image.
{
// Image dialog -> create IMG element.
if ( dialogType == 'image' )
this.imageElement = editor.document.createElement( 'img' );
else
{
this.imageElement = editor.document.createElement( 'input' );
this.imageElement.setAttribute ( 'type' ,'image' );
}
this.imageElement.setAttribute( 'alt', '' );
}
// Create a new link.
if ( !this.linkEditMode )
this.linkElement = editor.document.createElement( 'a' );
// Set attributes.
this.commitContent( IMAGE, this.imageElement );
this.commitContent( LINK, this.linkElement );
// Remove empty style attribute.
if ( !this.imageElement.getAttribute( 'style' ) )
this.imageElement.removeAttribute( 'style' );
// Insert a new Image.
if ( !this.imageEditMode )
{
if ( this.addLink )
{
//Insert a new Link.
if ( !this.linkEditMode )
{
editor.insertElement(this.linkElement);
this.linkElement.append(this.imageElement, false);
}
else //Link already exists, image not.
editor.insertElement(this.imageElement );
}
else
editor.insertElement( this.imageElement );
}
else // Image already exists.
{
//Add a new link element.
if ( !this.linkEditMode && this.addLink )
{
editor.insertElement( this.linkElement );
this.imageElement.appendTo( this.linkElement );
}
//Remove Link, Image exists.
else if ( this.linkEditMode && !this.addLink )
{
editor.getSelection().selectElement( this.linkElement );
editor.insertElement( this.imageElement );
}
}
},
onLoad : function()
{
if ( dialogType != 'image' )
this.hidePage( 'Link' ); //Hide Link tab.
var doc = this._.element.getDocument();
this.addFocusable( doc.getById( btnResetSizeId ), 5 );
this.addFocusable( doc.getById( btnLockSizesId ), 5 );
this.commitContent = commitContent;
},
onHide : function()
{
if ( this.preview )
this.commitContent( CLEANUP, this.preview );
if ( this.originalElement )
{
this.originalElement.removeListener( 'load', onImgLoadEvent );
this.originalElement.removeListener( 'error', onImgLoadErrorEvent );
this.originalElement.removeListener( 'abort', onImgLoadErrorEvent );
this.originalElement.remove();
this.originalElement = false; // Dialog is closed.
}
delete this.imageElement;
},
contents : [
{
id : 'info',
label : editor.lang.image.infoTab,
accessKey : 'I',
elements :
[
{
type : 'vbox',
padding : 0,
children :
[
{
type : 'hbox',
widths : [ '280px', '110px' ],
align : 'right',
children :
[
{
id : 'txtUrl',
type : 'text',
label : editor.lang.common.url,
required: true,
onChange : function()
{
var dialog = this.getDialog(),
newUrl = this.getValue();
//Update original image
if ( newUrl.length > 0 ) //Prevent from load before onShow
{
dialog = this.getDialog();
var original = dialog.originalElement;
dialog.preview.removeStyle( 'display' );
original.setCustomData( 'isReady', 'false' );
// Show loader
var loader = CKEDITOR.document.getById( imagePreviewLoaderId );
if ( loader )
loader.setStyle( 'display', '' );
original.on( 'load', onImgLoadEvent, dialog );
original.on( 'error', onImgLoadErrorEvent, dialog );
original.on( 'abort', onImgLoadErrorEvent, dialog );
original.setAttribute( 'src', newUrl );
// Query the preloader to figure out the url impacted by based href.
previewPreloader.setAttribute( 'src', newUrl );
dialog.preview.setAttribute( 'src', previewPreloader.$.src );
updatePreview( dialog );
}
// Dont show preview if no URL given.
else if ( dialog.preview )
{
dialog.preview.removeAttribute( 'src' );
dialog.preview.setStyle( 'display', 'none' );
}
},
setup : function( type, element )
{
if ( type == IMAGE )
{
var url = element.data( 'cke-saved-src' ) || element.getAttribute( 'src' );
var field = this;
this.getDialog().dontResetSize = true;
field.setValue( url ); // And call this.onChange()
// Manually set the initial value.(#4191)
field.setInitValue();
}
},
commit : function( type, element )
{
if ( type == IMAGE && ( this.getValue() || this.isChanged() ) )
{
element.data( 'cke-saved-src', decodeURI( this.getValue() ) );
element.setAttribute( 'src', decodeURI( this.getValue() ) );
}
else if ( type == CLEANUP )
{
element.setAttribute( 'src', '' ); // If removeAttribute doesn't work.
element.removeAttribute( 'src' );
}
},
validate : CKEDITOR.dialog.validate.notEmpty( editor.lang.image.urlMissing )
},
{
type : 'button',
id : 'browse',
// v-align with the 'txtUrl' field.
// TODO: We need something better than a fixed size here.
style : 'display:inline-block;margin-top:10px;',
align : 'center',
label : editor.lang.common.browseServer,
hidden : true,
filebrowser : 'info:txtUrl'
}
]
}
]
},
{
id : 'txtAlt',
type : 'text',
label : editor.lang.image.alt,
accessKey : 'T',
'default' : '',
onChange : function()
{
updatePreview( this.getDialog() );
},
setup : function( type, element )
{
if ( type == IMAGE )
this.setValue( element.getAttribute( 'alt' ) );
},
commit : function( type, element )
{
if ( type == IMAGE )
{
if ( this.getValue() || this.isChanged() )
element.setAttribute( 'alt', this.getValue() );
}
else if ( type == PREVIEW )
{
element.setAttribute( 'alt', this.getValue() );
}
else if ( type == CLEANUP )
{
element.removeAttribute( 'alt' );
}
}
},
{
type : 'hbox',
children :
[
{
type : 'vbox',
children :
[
{
type : 'hbox',
widths : [ '50%', '50%' ],
children :
[
{
type : 'vbox',
padding : 1,
children :
[
{
type : 'text',
width: '40px',
id : 'txtWidth',
label : editor.lang.common.width,
onKeyUp : onSizeChange,
onChange : function()
{
commitInternally.call( this, 'advanced:txtdlgGenStyle' );
},
validate : function()
{
var aMatch = this.getValue().match( regexGetSizeOrEmpty );
if ( !aMatch )
alert( editor.lang.common.invalidWidth );
return !!aMatch;
},
setup : setupDimension,
commit : function( type, element, internalCommit )
{
var value = this.getValue();
if ( type == IMAGE )
{
if ( value )
element.setStyle( 'width', CKEDITOR.tools.cssLength( value ) );
else if ( !value && this.isChanged( ) )
element.removeStyle( 'width' );
!internalCommit && element.removeAttribute( 'width' );
}
else if ( type == PREVIEW )
{
var aMatch = value.match( regexGetSize );
if ( !aMatch )
{
var oImageOriginal = this.getDialog().originalElement;
if ( oImageOriginal.getCustomData( 'isReady' ) == 'true' )
element.setStyle( 'width', oImageOriginal.$.width + 'px');
}
else
element.setStyle( 'width', CKEDITOR.tools.cssLength( value ) );
}
else if ( type == CLEANUP )
{
element.removeAttribute( 'width' );
element.removeStyle( 'width' );
}
}
},
{
type : 'text',
id : 'txtHeight',
width: '40px',
label : editor.lang.common.height,
onKeyUp : onSizeChange,
onChange : function()
{
commitInternally.call( this, 'advanced:txtdlgGenStyle' );
},
validate : function()
{
var aMatch = this.getValue().match( regexGetSizeOrEmpty );
if ( !aMatch )
alert( editor.lang.common.invalidHeight );
return !!aMatch;
},
setup : setupDimension,
commit : function( type, element, internalCommit )
{
var value = this.getValue();
if ( type == IMAGE )
{
if ( value )
element.setStyle( 'height', CKEDITOR.tools.cssLength( value ) );
else if ( !value && this.isChanged( ) )
element.removeStyle( 'height' );
if ( !internalCommit && type == IMAGE )
element.removeAttribute( 'height' );
}
else if ( type == PREVIEW )
{
var aMatch = value.match( regexGetSize );
if ( !aMatch )
{
var oImageOriginal = this.getDialog().originalElement;
if ( oImageOriginal.getCustomData( 'isReady' ) == 'true' )
element.setStyle( 'height', oImageOriginal.$.height + 'px' );
}
else
element.setStyle( 'height', CKEDITOR.tools.cssLength( value ) );
}
else if ( type == CLEANUP )
{
element.removeAttribute( 'height' );
element.removeStyle( 'height' );
}
}
}
]
},
{
type : 'html',
style : 'margin-top:30px;width:40px;height:40px;',
onLoad : function()
{
// Activate Reset button
var resetButton = CKEDITOR.document.getById( btnResetSizeId ),
ratioButton = CKEDITOR.document.getById( btnLockSizesId );
if ( resetButton )
{
resetButton.on( 'click', function(evt)
{
resetSize( this );
evt.data.preventDefault();
}, this.getDialog() );
resetButton.on( 'mouseover', function()
{
this.addClass( 'cke_btn_over' );
}, resetButton );
resetButton.on( 'mouseout', function()
{
this.removeClass( 'cke_btn_over' );
}, resetButton );
}
// Activate (Un)LockRatio button
if ( ratioButton )
{
ratioButton.on( 'click', function(evt)
{
var locked = switchLockRatio( this ),
oImageOriginal = this.originalElement,
width = this.getValueOf( 'info', 'txtWidth' );
if ( oImageOriginal.getCustomData( 'isReady' ) == 'true' && width )
{
var height = oImageOriginal.$.height / oImageOriginal.$.width * width;
if ( !isNaN( height ) )
{
this.setValueOf( 'info', 'txtHeight', Math.round( height ) );
updatePreview( this );
}
}
evt.data.preventDefault();
}, this.getDialog() );
ratioButton.on( 'mouseover', function()
{
this.addClass( 'cke_btn_over' );
}, ratioButton );
ratioButton.on( 'mouseout', function()
{
this.removeClass( 'cke_btn_over' );
}, ratioButton );
}
},
html : '<div>'+
'<a href="javascript:void(0)" tabindex="-1" title="' + editor.lang.image.unlockRatio +
'" class="cke_btn_locked" id="' + btnLockSizesId + '" role="button"><span class="cke_label">' + editor.lang.image.unlockRatio + '</span></a>' +
'<a href="javascript:void(0)" tabindex="-1" title="' + editor.lang.image.resetSize +
'" class="cke_btn_reset" id="' + btnResetSizeId + '" role="button"><span class="cke_label">' + editor.lang.image.resetSize + '</span></a>'+
'</div>'
}
]
},
{
type : 'vbox',
padding : 1,
children :
[
{
type : 'text',
id : 'txtBorder',
width: '60px',
label : editor.lang.image.border,
'default' : '',
onKeyUp : function()
{
updatePreview( this.getDialog() );
},
onChange : function()
{
commitInternally.call( this, 'advanced:txtdlgGenStyle' );
},
validate : CKEDITOR.dialog.validate.integer( editor.lang.image.validateBorder ),
setup : function( type, element )
{
if ( type == IMAGE )
{
var value,
borderStyle = element.getStyle( 'border-width' );
borderStyle = borderStyle && borderStyle.match( /^(\d+px)(?: \1 \1 \1)?$/ );
value = borderStyle && parseInt( borderStyle[ 1 ], 10 );
isNaN ( parseInt( value, 10 ) ) && ( value = element.getAttribute( 'border' ) );
this.setValue( value );
}
},
commit : function( type, element, internalCommit )
{
var value = parseInt( this.getValue(), 10 );
if ( type == IMAGE || type == PREVIEW )
{
if ( !isNaN( value ) )
{
element.setStyle( 'border-width', CKEDITOR.tools.cssLength( value ) );
element.setStyle( 'border-style', 'solid' );
}
else if ( !value && this.isChanged() )
{
element.removeStyle( 'border-width' );
element.removeStyle( 'border-style' );
element.removeStyle( 'border-color' );
}
if ( !internalCommit && type == IMAGE )
element.removeAttribute( 'border' );
}
else if ( type == CLEANUP )
{
element.removeAttribute( 'border' );
element.removeStyle( 'border-width' );
element.removeStyle( 'border-style' );
element.removeStyle( 'border-color' );
}
}
},
{
type : 'text',
id : 'txtHSpace',
width: '60px',
label : editor.lang.image.hSpace,
'default' : '',
onKeyUp : function()
{
updatePreview( this.getDialog() );
},
onChange : function()
{
commitInternally.call( this, 'advanced:txtdlgGenStyle' );
},
validate : CKEDITOR.dialog.validate.integer( editor.lang.image.validateHSpace ),
setup : function( type, element )
{
if ( type == IMAGE )
{
var value,
marginLeftPx,
marginRightPx,
marginLeftStyle = element.getStyle( 'margin-left' ),
marginRightStyle = element.getStyle( 'margin-right' );
marginLeftStyle = marginLeftStyle && marginLeftStyle.match( pxLengthRegex );
marginRightStyle = marginRightStyle && marginRightStyle.match( pxLengthRegex );
marginLeftPx = parseInt( marginLeftStyle, 10 );
marginRightPx = parseInt( marginRightStyle, 10 );
value = ( marginLeftPx == marginRightPx ) && marginLeftPx;
isNaN( parseInt( value, 10 ) ) && ( value = element.getAttribute( 'hspace' ) );
this.setValue( value );
}
},
commit : function( type, element, internalCommit )
{
var value = parseInt( this.getValue(), 10 );
if ( type == IMAGE || type == PREVIEW )
{
if ( !isNaN( value ) )
{
element.setStyle( 'margin-left', CKEDITOR.tools.cssLength( value ) );
element.setStyle( 'margin-right', CKEDITOR.tools.cssLength( value ) );
}
else if ( !value && this.isChanged( ) )
{
element.removeStyle( 'margin-left' );
element.removeStyle( 'margin-right' );
}
if ( !internalCommit && type == IMAGE )
element.removeAttribute( 'hspace' );
}
else if ( type == CLEANUP )
{
element.removeAttribute( 'hspace' );
element.removeStyle( 'margin-left' );
element.removeStyle( 'margin-right' );
}
}
},
{
type : 'text',
id : 'txtVSpace',
width : '60px',
label : editor.lang.image.vSpace,
'default' : '',
onKeyUp : function()
{
updatePreview( this.getDialog() );
},
onChange : function()
{
commitInternally.call( this, 'advanced:txtdlgGenStyle' );
},
validate : CKEDITOR.dialog.validate.integer( editor.lang.image.validateVSpace ),
setup : function( type, element )
{
if ( type == IMAGE )
{
var value,
marginTopPx,
marginBottomPx,
marginTopStyle = element.getStyle( 'margin-top' ),
marginBottomStyle = element.getStyle( 'margin-bottom' );
marginTopStyle = marginTopStyle && marginTopStyle.match( pxLengthRegex );
marginBottomStyle = marginBottomStyle && marginBottomStyle.match( pxLengthRegex );
marginTopPx = parseInt( marginTopStyle, 10 );
marginBottomPx = parseInt( marginBottomStyle, 10 );
value = ( marginTopPx == marginBottomPx ) && marginTopPx;
isNaN ( parseInt( value, 10 ) ) && ( value = element.getAttribute( 'vspace' ) );
this.setValue( value );
}
},
commit : function( type, element, internalCommit )
{
var value = parseInt( this.getValue(), 10 );
if ( type == IMAGE || type == PREVIEW )
{
if ( !isNaN( value ) )
{
element.setStyle( 'margin-top', CKEDITOR.tools.cssLength( value ) );
element.setStyle( 'margin-bottom', CKEDITOR.tools.cssLength( value ) );
}
else if ( !value && this.isChanged( ) )
{
element.removeStyle( 'margin-top' );
element.removeStyle( 'margin-bottom' );
}
if ( !internalCommit && type == IMAGE )
element.removeAttribute( 'vspace' );
}
else if ( type == CLEANUP )
{
element.removeAttribute( 'vspace' );
element.removeStyle( 'margin-top' );
element.removeStyle( 'margin-bottom' );
}
}
},
{
id : 'cmbAlign',
type : 'select',
widths : [ '35%','65%' ],
style : 'width:90px',
label : editor.lang.common.align,
'default' : '',
items :
[
[ editor.lang.common.notSet , ''],
[ editor.lang.common.alignLeft , 'left'],
[ editor.lang.common.alignRight , 'right']
// Backward compatible with v2 on setup when specified as attribute value,
// while these values are no more available as select options.
// [ editor.lang.image.alignAbsBottom , 'absBottom'],
// [ editor.lang.image.alignAbsMiddle , 'absMiddle'],
// [ editor.lang.image.alignBaseline , 'baseline'],
// [ editor.lang.image.alignTextTop , 'text-top'],
// [ editor.lang.image.alignBottom , 'bottom'],
// [ editor.lang.image.alignMiddle , 'middle'],
// [ editor.lang.image.alignTop , 'top']
],
onChange : function()
{
updatePreview( this.getDialog() );
commitInternally.call( this, 'advanced:txtdlgGenStyle' );
},
setup : function( type, element )
{
if ( type == IMAGE )
{
var value = element.getStyle( 'float' );
switch( value )
{
// Ignore those unrelated values.
case 'inherit':
case 'none':
value = '';
}
!value && ( value = ( element.getAttribute( 'align' ) || '' ).toLowerCase() );
this.setValue( value );
}
},
commit : function( type, element, internalCommit )
{
var value = this.getValue();
if ( type == IMAGE || type == PREVIEW )
{
if ( value )
element.setStyle( 'float', value );
else
element.removeStyle( 'float' );
if ( !internalCommit && type == IMAGE )
{
value = ( element.getAttribute( 'align' ) || '' ).toLowerCase();
switch( value )
{
// we should remove it only if it matches "left" or "right",
// otherwise leave it intact.
case 'left':
case 'right':
element.removeAttribute( 'align' );
}
}
}
else if ( type == CLEANUP )
element.removeStyle( 'float' );
}
}
]
}
]
},
{
type : 'vbox',
height : '250px',
children :
[
{
type : 'html',
style : 'width:95%;',
html : '<div>' + CKEDITOR.tools.htmlEncode( editor.lang.common.preview ) +'<br>'+
'<div id="' + imagePreviewLoaderId + '" class="ImagePreviewLoader" style="display:none"><div class="loading"> </div></div>'+
'<div id="' + imagePreviewBoxId + '" class="ImagePreviewBox"><table><tr><td>'+
'<a href="javascript:void(0)" target="_blank" onclick="return false;" id="' + previewLinkId + '">'+
'<img id="' + previewImageId + '" alt="" /></a>' +
( editor.config.image_previewText ||
'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. '+
'Maecenas feugiat consequat diam. Maecenas metus. Vivamus diam purus, cursus a, commodo non, facilisis vitae, '+
'nulla. Aenean dictum lacinia tortor. Nunc iaculis, nibh non iaculis aliquam, orci felis euismod neque, sed ornare massa mauris sed velit. Nulla pretium mi et risus. Fusce mi pede, tempor id, cursus ac, ullamcorper nec, enim. Sed tortor. Curabitur molestie. Duis velit augue, condimentum at, ultrices a, luctus ut, orci. Donec pellentesque egestas eros. Integer cursus, augue in cursus faucibus, eros pede bibendum sem, in tempus tellus justo quis ligula. Etiam eget tortor. Vestibulum rutrum, est ut placerat elementum, lectus nisl aliquam velit, tempor aliquam eros nunc nonummy metus. In eros metus, gravida a, gravida sed, lobortis id, turpis. Ut ultrices, ipsum at venenatis fringilla, sem nulla lacinia tellus, eget aliquet turpis mauris non enim. Nam turpis. Suspendisse lacinia. Curabitur ac tortor ut ipsum egestas elementum. Nunc imperdiet gravida mauris.' ) +
'</td></tr></table></div></div>'
}
]
}
]
}
]
},
{
id : 'Link',
label : editor.lang.link.title,
padding : 0,
elements :
[
{
id : 'txtUrl',
type : 'text',
label : editor.lang.common.url,
style : 'width: 100%',
'default' : '',
setup : function( type, element )
{
if ( type == LINK )
{
var href = element.data( 'cke-saved-href' );
if ( !href )
href = element.getAttribute( 'href' );
this.setValue( href );
}
},
commit : function( type, element )
{
if ( type == LINK )
{
if ( this.getValue() || this.isChanged() )
{
element.data( 'cke-saved-href', decodeURI( this.getValue() ) );
element.setAttribute( 'href', 'javascript:void(0)/*' +
CKEDITOR.tools.getNextNumber() + '*/' );
if ( this.getValue() || !editor.config.image_removeLinkByEmptyURL )
this.getDialog().addLink = true;
}
}
}
},
{
type : 'button',
id : 'browse',
filebrowser :
{
action : 'Browse',
target: 'Link:txtUrl',
url: editor.config.filebrowserImageBrowseLinkUrl
},
style : 'float:right',
hidden : true,
label : editor.lang.common.browseServer
},
{
id : 'cmbTarget',
type : 'select',
label : editor.lang.common.target,
'default' : '',
items :
[
[ editor.lang.common.notSet , ''],
[ editor.lang.common.targetNew , '_blank'],
[ editor.lang.common.targetTop , '_top'],
[ editor.lang.common.targetSelf , '_self'],
[ editor.lang.common.targetParent , '_parent']
],
setup : function( type, element )
{
if ( type == LINK )
this.setValue( element.getAttribute( 'target' ) || '' );
},
commit : function( type, element )
{
if ( type == LINK )
{
if ( this.getValue() || this.isChanged() )
element.setAttribute( 'target', this.getValue() );
}
}
}
]
},
{
id : 'Upload',
hidden : true,
filebrowser : 'uploadButton',
label : editor.lang.image.upload,
elements :
[
{
type : 'file',
id : 'upload',
label : editor.lang.image.btnUpload,
style: 'height:40px',
size : 38
},
{
type : 'fileButton',
id : 'uploadButton',
filebrowser : 'info:txtUrl',
label : editor.lang.image.btnUpload,
'for' : [ 'Upload', 'upload' ]
}
]
},
{
id : 'advanced',
label : editor.lang.common.advancedTab,
elements :
[
{
type : 'hbox',
widths : [ '50%', '25%', '25%' ],
children :
[
{
type : 'text',
id : 'linkId',
label : editor.lang.common.id,
setup : function( type, element )
{
if ( type == IMAGE )
this.setValue( element.getAttribute( 'id' ) );
},
commit : function( type, element )
{
if ( type == IMAGE )
{
if ( this.getValue() || this.isChanged() )
element.setAttribute( 'id', this.getValue() );
}
}
},
{
id : 'cmbLangDir',
type : 'select',
style : 'width : 100px;',
label : editor.lang.common.langDir,
'default' : '',
items :
[
[ editor.lang.common.notSet, '' ],
[ editor.lang.common.langDirLtr, 'ltr' ],
[ editor.lang.common.langDirRtl, 'rtl' ]
],
setup : function( type, element )
{
if ( type == IMAGE )
this.setValue( element.getAttribute( 'dir' ) );
},
commit : function( type, element )
{
if ( type == IMAGE )
{
if ( this.getValue() || this.isChanged() )
element.setAttribute( 'dir', this.getValue() );
}
}
},
{
type : 'text',
id : 'txtLangCode',
label : editor.lang.common.langCode,
'default' : '',
setup : function( type, element )
{
if ( type == IMAGE )
this.setValue( element.getAttribute( 'lang' ) );
},
commit : function( type, element )
{
if ( type == IMAGE )
{
if ( this.getValue() || this.isChanged() )
element.setAttribute( 'lang', this.getValue() );
}
}
}
]
},
{
type : 'text',
id : 'txtGenLongDescr',
label : editor.lang.common.longDescr,
setup : function( type, element )
{
if ( type == IMAGE )
this.setValue( element.getAttribute( 'longDesc' ) );
},
commit : function( type, element )
{
if ( type == IMAGE )
{
if ( this.getValue() || this.isChanged() )
element.setAttribute( 'longDesc', this.getValue() );
}
}
},
{
type : 'hbox',
widths : [ '50%', '50%' ],
children :
[
{
type : 'text',
id : 'txtGenClass',
label : editor.lang.common.cssClass,
'default' : '',
setup : function( type, element )
{
if ( type == IMAGE )
this.setValue( element.getAttribute( 'class' ) );
},
commit : function( type, element )
{
if ( type == IMAGE )
{
if ( this.getValue() || this.isChanged() )
element.setAttribute( 'class', this.getValue() );
}
}
},
{
type : 'text',
id : 'txtGenTitle',
label : editor.lang.common.advisoryTitle,
'default' : '',
onChange : function()
{
updatePreview( this.getDialog() );
},
setup : function( type, element )
{
if ( type == IMAGE )
this.setValue( element.getAttribute( 'title' ) );
},
commit : function( type, element )
{
if ( type == IMAGE )
{
if ( this.getValue() || this.isChanged() )
element.setAttribute( 'title', this.getValue() );
}
else if ( type == PREVIEW )
{
element.setAttribute( 'title', this.getValue() );
}
else if ( type == CLEANUP )
{
element.removeAttribute( 'title' );
}
}
}
]
},
{
type : 'text',
id : 'txtdlgGenStyle',
label : editor.lang.common.cssStyle,
'default' : '',
setup : function( type, element )
{
if ( type == IMAGE )
{
var genStyle = element.getAttribute( 'style' );
if ( !genStyle && element.$.style.cssText )
genStyle = element.$.style.cssText;
this.setValue( genStyle );
var height = element.$.style.height,
width = element.$.style.width,
aMatchH = ( height ? height : '' ).match( regexGetSize ),
aMatchW = ( width ? width : '').match( regexGetSize );
this.attributesInStyle =
{
height : !!aMatchH,
width : !!aMatchW
};
}
},
onChange : function ()
{
commitInternally.call( this,
[ 'info:cmbFloat', 'info:cmbAlign',
'info:txtVSpace', 'info:txtHSpace',
'info:txtBorder',
'info:txtWidth', 'info:txtHeight' ] );
updatePreview( this );
},
commit : function( type, element )
{
if ( type == IMAGE && ( this.getValue() || this.isChanged() ) )
{
element.setAttribute( 'style', this.getValue() );
}
}
}
]
}
]
};
};
CKEDITOR.dialog.add( 'image', function( editor )
{
return imageDialog( editor, 'image' );
});
CKEDITOR.dialog.add( 'imagebutton', function( editor )
{
return imageDialog( editor, 'imagebutton' );
});
})();
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @file Insert and remove numbered and bulleted lists.
*/
(function()
{
var listNodeNames = { ol : 1, ul : 1 },
emptyTextRegex = /^[\n\r\t ]*$/;
var whitespaces = CKEDITOR.dom.walker.whitespaces(),
bookmarks = CKEDITOR.dom.walker.bookmark(),
nonEmpty = function( node ){ return !( whitespaces( node ) || bookmarks( node ) ); };
CKEDITOR.plugins.list = {
/*
* Convert a DOM list tree into a data structure that is easier to
* manipulate. This operation should be non-intrusive in the sense that it
* does not change the DOM tree, with the exception that it may add some
* markers to the list item nodes when database is specified.
*/
listToArray : function( listNode, database, baseArray, baseIndentLevel, grandparentNode )
{
if ( !listNodeNames[ listNode.getName() ] )
return [];
if ( !baseIndentLevel )
baseIndentLevel = 0;
if ( !baseArray )
baseArray = [];
// Iterate over all list items to and look for inner lists.
for ( var i = 0, count = listNode.getChildCount() ; i < count ; i++ )
{
var listItem = listNode.getChild( i );
// It may be a text node or some funny stuff.
if ( listItem.$.nodeName.toLowerCase() != 'li' )
continue;
var itemObj = { 'parent' : listNode, indent : baseIndentLevel, element : listItem, contents : [] };
if ( !grandparentNode )
{
itemObj.grandparent = listNode.getParent();
if ( itemObj.grandparent && itemObj.grandparent.$.nodeName.toLowerCase() == 'li' )
itemObj.grandparent = itemObj.grandparent.getParent();
}
else
itemObj.grandparent = grandparentNode;
if ( database )
CKEDITOR.dom.element.setMarker( database, listItem, 'listarray_index', baseArray.length );
baseArray.push( itemObj );
for ( var j = 0, itemChildCount = listItem.getChildCount(), child; j < itemChildCount ; j++ )
{
child = listItem.getChild( j );
if ( child.type == CKEDITOR.NODE_ELEMENT && listNodeNames[ child.getName() ] )
// Note the recursion here, it pushes inner list items with
// +1 indentation in the correct order.
CKEDITOR.plugins.list.listToArray( child, database, baseArray, baseIndentLevel + 1, itemObj.grandparent );
else
itemObj.contents.push( child );
}
}
return baseArray;
},
// Convert our internal representation of a list back to a DOM forest.
arrayToList : function( listArray, database, baseIndex, paragraphMode, dir )
{
if ( !baseIndex )
baseIndex = 0;
if ( !listArray || listArray.length < baseIndex + 1 )
return null;
var doc = listArray[ baseIndex ].parent.getDocument(),
retval = new CKEDITOR.dom.documentFragment( doc ),
rootNode = null,
currentIndex = baseIndex,
indentLevel = Math.max( listArray[ baseIndex ].indent, 0 ),
currentListItem = null,
paragraphName = ( paragraphMode == CKEDITOR.ENTER_P ? 'p' : 'div' );
while ( 1 )
{
var item = listArray[ currentIndex ];
if ( item.indent == indentLevel )
{
if ( !rootNode || listArray[ currentIndex ].parent.getName() != rootNode.getName() )
{
rootNode = listArray[ currentIndex ].parent.clone( false, 1 );
dir && rootNode.setAttribute( 'dir', dir );
retval.append( rootNode );
}
currentListItem = rootNode.append( item.element.clone( 0, 1 ) );
for ( var i = 0 ; i < item.contents.length ; i++ )
currentListItem.append( item.contents[i].clone( 1, 1 ) );
currentIndex++;
}
else if ( item.indent == Math.max( indentLevel, 0 ) + 1 )
{
var listData = CKEDITOR.plugins.list.arrayToList( listArray, null, currentIndex, paragraphMode );
currentListItem.append( listData.listNode );
currentIndex = listData.nextIndex;
}
else if ( item.indent == -1 && !baseIndex && item.grandparent )
{
currentListItem;
if ( listNodeNames[ item.grandparent.getName() ] )
currentListItem = item.element.clone( false, true );
else
{
// Create completely new blocks here.
if ( dir || item.element.hasAttributes() ||
( paragraphMode != CKEDITOR.ENTER_BR && item.grandparent.getName() != 'td' ) )
{
currentListItem = doc.createElement( paragraphName );
item.element.copyAttributes( currentListItem, { type:1, value:1 } );
dir && currentListItem.setAttribute( 'dir', dir );
// There might be a case where there are no attributes in the element after all
// (i.e. when "type" or "value" are the only attributes set). In this case, if enterMode = BR,
// the current item should be a fragment.
if ( !dir && paragraphMode == CKEDITOR.ENTER_BR && !currentListItem.hasAttributes() )
currentListItem = new CKEDITOR.dom.documentFragment( doc );
}
else
currentListItem = new CKEDITOR.dom.documentFragment( doc );
}
for ( i = 0 ; i < item.contents.length ; i++ )
currentListItem.append( item.contents[i].clone( 1, 1 ) );
if ( currentListItem.type == CKEDITOR.NODE_DOCUMENT_FRAGMENT
&& currentIndex != listArray.length - 1 )
{
var last = currentListItem.getLast();
if ( last && last.type == CKEDITOR.NODE_ELEMENT
&& last.getAttribute( 'type' ) == '_moz' )
{
last.remove();
}
if ( !( last = currentListItem.getLast( nonEmpty )
&& last.type == CKEDITOR.NODE_ELEMENT
&& last.getName() in CKEDITOR.dtd.$block ) )
{
currentListItem.append( doc.createElement( 'br' ) );
}
}
if ( currentListItem.type == CKEDITOR.NODE_ELEMENT &&
currentListItem.getName() == paragraphName &&
currentListItem.$.firstChild )
{
currentListItem.trim();
var firstChild = currentListItem.getFirst();
if ( firstChild.type == CKEDITOR.NODE_ELEMENT && firstChild.isBlockBoundary() )
{
var tmp = new CKEDITOR.dom.documentFragment( doc );
currentListItem.moveChildren( tmp );
currentListItem = tmp;
}
}
var currentListItemName = currentListItem.$.nodeName.toLowerCase();
if ( !CKEDITOR.env.ie && ( currentListItemName == 'div' || currentListItemName == 'p' ) )
currentListItem.appendBogus();
retval.append( currentListItem );
rootNode = null;
currentIndex++;
}
else
return null;
if ( listArray.length <= currentIndex || Math.max( listArray[ currentIndex ].indent, 0 ) < indentLevel )
break;
}
// Clear marker attributes for the new list tree made of cloned nodes, if any.
if ( database )
{
var currentNode = retval.getFirst();
while ( currentNode )
{
if ( currentNode.type == CKEDITOR.NODE_ELEMENT )
CKEDITOR.dom.element.clearMarkers( database, currentNode );
currentNode = currentNode.getNextSourceNode();
}
}
return { listNode : retval, nextIndex : currentIndex };
}
};
function setState( editor, state )
{
editor.getCommand( this.name ).setState( state );
}
function onSelectionChange( evt )
{
var path = evt.data.path,
blockLimit = path.blockLimit,
elements = path.elements,
element;
// Grouping should only happen under blockLimit.(#3940).
for ( var i = 0 ; i < elements.length && ( element = elements[ i ] )
&& !element.equals( blockLimit ); i++ )
{
if ( listNodeNames[ elements[i].getName() ] )
{
return setState.call( this, evt.editor,
this.type == elements[i].getName() ? CKEDITOR.TRISTATE_ON : CKEDITOR.TRISTATE_OFF );
}
}
return setState.call( this, evt.editor, CKEDITOR.TRISTATE_OFF );
}
function changeListType( editor, groupObj, database, listsCreated )
{
// This case is easy...
// 1. Convert the whole list into a one-dimensional array.
// 2. Change the list type by modifying the array.
// 3. Recreate the whole list by converting the array to a list.
// 4. Replace the original list with the recreated list.
var listArray = CKEDITOR.plugins.list.listToArray( groupObj.root, database ),
selectedListItems = [];
for ( var i = 0 ; i < groupObj.contents.length ; i++ )
{
var itemNode = groupObj.contents[i];
itemNode = itemNode.getAscendant( 'li', true );
if ( !itemNode || itemNode.getCustomData( 'list_item_processed' ) )
continue;
selectedListItems.push( itemNode );
CKEDITOR.dom.element.setMarker( database, itemNode, 'list_item_processed', true );
}
var root = groupObj.root,
fakeParent = root.getDocument().createElement( this.type );
// Copy all attributes, except from 'start' and 'type'.
root.copyAttributes( fakeParent, { start : 1, type : 1 } );
// The list-style-type property should be ignored.
fakeParent.removeStyle( 'list-style-type' );
for ( i = 0 ; i < selectedListItems.length ; i++ )
{
var listIndex = selectedListItems[i].getCustomData( 'listarray_index' );
listArray[listIndex].parent = fakeParent;
}
var newList = CKEDITOR.plugins.list.arrayToList( listArray, database, null, editor.config.enterMode );
var child, length = newList.listNode.getChildCount();
for ( i = 0 ; i < length && ( child = newList.listNode.getChild( i ) ) ; i++ )
{
if ( child.getName() == this.type )
listsCreated.push( child );
}
newList.listNode.replace( groupObj.root );
}
var headerTagRegex = /^h[1-6]$/;
function createList( editor, groupObj, listsCreated )
{
var contents = groupObj.contents,
doc = groupObj.root.getDocument(),
listContents = [];
// It is possible to have the contents returned by DomRangeIterator to be the same as the root.
// e.g. when we're running into table cells.
// In such a case, enclose the childNodes of contents[0] into a <div>.
if ( contents.length == 1 && contents[0].equals( groupObj.root ) )
{
var divBlock = doc.createElement( 'div' );
contents[0].moveChildren && contents[0].moveChildren( divBlock );
contents[0].append( divBlock );
contents[0] = divBlock;
}
// Calculate the common parent node of all content blocks.
var commonParent = groupObj.contents[0].getParent();
for ( var i = 0 ; i < contents.length ; i++ )
commonParent = commonParent.getCommonAncestor( contents[i].getParent() );
var useComputedState = editor.config.useComputedState,
listDir, explicitDirection;
useComputedState = useComputedState === undefined || useComputedState;
// We want to insert things that are in the same tree level only, so calculate the contents again
// by expanding the selected blocks to the same tree level.
for ( i = 0 ; i < contents.length ; i++ )
{
var contentNode = contents[i],
parentNode;
while ( ( parentNode = contentNode.getParent() ) )
{
if ( parentNode.equals( commonParent ) )
{
listContents.push( contentNode );
// Determine the lists's direction.
if ( !explicitDirection && contentNode.getDirection() )
explicitDirection = 1;
var itemDir = contentNode.getDirection( useComputedState );
if ( listDir !== null )
{
// If at least one LI have a different direction than current listDir, we can't have listDir.
if ( listDir && listDir != itemDir )
listDir = null;
else
listDir = itemDir;
}
break;
}
contentNode = parentNode;
}
}
if ( listContents.length < 1 )
return;
// Insert the list to the DOM tree.
var insertAnchor = listContents[ listContents.length - 1 ].getNext(),
listNode = doc.createElement( this.type );
listsCreated.push( listNode );
var contentBlock, listItem;
while ( listContents.length )
{
contentBlock = listContents.shift();
listItem = doc.createElement( 'li' );
// Preserve preformat block and heading structure when converting to list item. (#5335) (#5271)
if ( contentBlock.is( 'pre' ) || headerTagRegex.test( contentBlock.getName() ) )
contentBlock.appendTo( listItem );
else
{
// Remove DIR attribute if it was merged into list root.
if ( listDir && contentBlock.getDirection() )
{
contentBlock.removeStyle( 'direction' );
contentBlock.removeAttribute( 'dir' );
}
contentBlock.copyAttributes( listItem );
contentBlock.moveChildren( listItem );
contentBlock.remove();
}
listItem.appendTo( listNode );
}
// Apply list root dir only if it has been explicitly declared.
if ( listDir && explicitDirection )
listNode.setAttribute( 'dir', listDir );
if ( insertAnchor )
listNode.insertBefore( insertAnchor );
else
listNode.appendTo( commonParent );
}
function removeList( editor, groupObj, database )
{
// This is very much like the change list type operation.
// Except that we're changing the selected items' indent to -1 in the list array.
var listArray = CKEDITOR.plugins.list.listToArray( groupObj.root, database ),
selectedListItems = [];
for ( var i = 0 ; i < groupObj.contents.length ; i++ )
{
var itemNode = groupObj.contents[i];
itemNode = itemNode.getAscendant( 'li', true );
if ( !itemNode || itemNode.getCustomData( 'list_item_processed' ) )
continue;
selectedListItems.push( itemNode );
CKEDITOR.dom.element.setMarker( database, itemNode, 'list_item_processed', true );
}
var lastListIndex = null;
for ( i = 0 ; i < selectedListItems.length ; i++ )
{
var listIndex = selectedListItems[i].getCustomData( 'listarray_index' );
listArray[listIndex].indent = -1;
lastListIndex = listIndex;
}
// After cutting parts of the list out with indent=-1, we still have to maintain the array list
// model's nextItem.indent <= currentItem.indent + 1 invariant. Otherwise the array model of the
// list cannot be converted back to a real DOM list.
for ( i = lastListIndex + 1 ; i < listArray.length ; i++ )
{
if ( listArray[i].indent > listArray[i-1].indent + 1 )
{
var indentOffset = listArray[i-1].indent + 1 - listArray[i].indent;
var oldIndent = listArray[i].indent;
while ( listArray[i] && listArray[i].indent >= oldIndent )
{
listArray[i].indent += indentOffset;
i++;
}
i--;
}
}
var newList = CKEDITOR.plugins.list.arrayToList( listArray, database, null, editor.config.enterMode,
groupObj.root.getAttribute( 'dir' ) );
// Compensate <br> before/after the list node if the surrounds are non-blocks.(#3836)
var docFragment = newList.listNode, boundaryNode, siblingNode;
function compensateBrs( isStart )
{
if ( ( boundaryNode = docFragment[ isStart ? 'getFirst' : 'getLast' ]() )
&& !( boundaryNode.is && boundaryNode.isBlockBoundary() )
&& ( siblingNode = groupObj.root[ isStart ? 'getPrevious' : 'getNext' ]
( CKEDITOR.dom.walker.whitespaces( true ) ) )
&& !( siblingNode.is && siblingNode.isBlockBoundary( { br : 1 } ) ) )
editor.document.createElement( 'br' )[ isStart ? 'insertBefore' : 'insertAfter' ]( boundaryNode );
}
compensateBrs( true );
compensateBrs();
docFragment.replace( groupObj.root );
}
function listCommand( name, type )
{
this.name = name;
this.type = type;
}
listCommand.prototype = {
exec : function( editor )
{
editor.focus();
var doc = editor.document,
selection = editor.getSelection(),
ranges = selection && selection.getRanges( true );
// There should be at least one selected range.
if ( !ranges || ranges.length < 1 )
return;
// Midas lists rule #1 says we can create a list even in an empty document.
// But DOM iterator wouldn't run if the document is really empty.
// So create a paragraph if the document is empty and we're going to create a list.
if ( this.state == CKEDITOR.TRISTATE_OFF )
{
var body = doc.getBody();
body.trim();
if ( !body.getFirst() )
{
var paragraph = doc.createElement( editor.config.enterMode == CKEDITOR.ENTER_P ? 'p' :
( editor.config.enterMode == CKEDITOR.ENTER_DIV ? 'div' : 'br' ) );
paragraph.appendTo( body );
ranges = new CKEDITOR.dom.rangeList( [ new CKEDITOR.dom.range( doc ) ] );
// IE exception on inserting anything when anchor inside <br>.
if ( paragraph.is( 'br' ) )
{
ranges[ 0 ].setStartBefore( paragraph );
ranges[ 0 ].setEndAfter( paragraph );
}
else
ranges[ 0 ].selectNodeContents( paragraph );
selection.selectRanges( ranges );
}
// Maybe a single range there enclosing the whole list,
// turn on the list state manually(#4129).
else
{
var range = ranges.length == 1 && ranges[ 0 ],
enclosedNode = range && range.getEnclosedNode();
if ( enclosedNode && enclosedNode.is
&& this.type == enclosedNode.getName() )
setState.call( this, editor, CKEDITOR.TRISTATE_ON );
}
}
var bookmarks = selection.createBookmarks( true );
// Group the blocks up because there are many cases where multiple lists have to be created,
// or multiple lists have to be cancelled.
var listGroups = [],
database = {},
rangeIterator = ranges.createIterator(),
index = 0;
while ( ( range = rangeIterator.getNextRange() ) && ++index )
{
var boundaryNodes = range.getBoundaryNodes(),
startNode = boundaryNodes.startNode,
endNode = boundaryNodes.endNode;
if ( startNode.type == CKEDITOR.NODE_ELEMENT && startNode.getName() == 'td' )
range.setStartAt( boundaryNodes.startNode, CKEDITOR.POSITION_AFTER_START );
if ( endNode.type == CKEDITOR.NODE_ELEMENT && endNode.getName() == 'td' )
range.setEndAt( boundaryNodes.endNode, CKEDITOR.POSITION_BEFORE_END );
var iterator = range.createIterator(),
block;
iterator.forceBrBreak = ( this.state == CKEDITOR.TRISTATE_OFF );
while ( ( block = iterator.getNextParagraph() ) )
{
// Avoid duplicate blocks get processed across ranges.
if( block.getCustomData( 'list_block' ) )
continue;
else
CKEDITOR.dom.element.setMarker( database, block, 'list_block', 1 );
var path = new CKEDITOR.dom.elementPath( block ),
pathElements = path.elements,
pathElementsCount = pathElements.length,
listNode = null,
processedFlag = 0,
blockLimit = path.blockLimit,
element;
// First, try to group by a list ancestor.
for ( var i = pathElementsCount - 1; i >= 0 && ( element = pathElements[ i ] ); i-- )
{
if ( listNodeNames[ element.getName() ]
&& blockLimit.contains( element ) ) // Don't leak outside block limit (#3940).
{
// If we've encountered a list inside a block limit
// The last group object of the block limit element should
// no longer be valid. Since paragraphs after the list
// should belong to a different group of paragraphs before
// the list. (Bug #1309)
blockLimit.removeCustomData( 'list_group_object_' + index );
var groupObj = element.getCustomData( 'list_group_object' );
if ( groupObj )
groupObj.contents.push( block );
else
{
groupObj = { root : element, contents : [ block ] };
listGroups.push( groupObj );
CKEDITOR.dom.element.setMarker( database, element, 'list_group_object', groupObj );
}
processedFlag = 1;
break;
}
}
if ( processedFlag )
continue;
// No list ancestor? Group by block limit, but don't mix contents from different ranges.
var root = blockLimit;
if ( root.getCustomData( 'list_group_object_' + index ) )
root.getCustomData( 'list_group_object_' + index ).contents.push( block );
else
{
groupObj = { root : root, contents : [ block ] };
CKEDITOR.dom.element.setMarker( database, root, 'list_group_object_' + index, groupObj );
listGroups.push( groupObj );
}
}
}
// Now we have two kinds of list groups, groups rooted at a list, and groups rooted at a block limit element.
// We either have to build lists or remove lists, for removing a list does not makes sense when we are looking
// at the group that's not rooted at lists. So we have three cases to handle.
var listsCreated = [];
while ( listGroups.length > 0 )
{
groupObj = listGroups.shift();
if ( this.state == CKEDITOR.TRISTATE_OFF )
{
if ( listNodeNames[ groupObj.root.getName() ] )
changeListType.call( this, editor, groupObj, database, listsCreated );
else
createList.call( this, editor, groupObj, listsCreated );
}
else if ( this.state == CKEDITOR.TRISTATE_ON && listNodeNames[ groupObj.root.getName() ] )
removeList.call( this, editor, groupObj, database );
}
// For all new lists created, merge adjacent, same type lists.
for ( i = 0 ; i < listsCreated.length ; i++ )
{
listNode = listsCreated[i];
var mergeSibling, listCommand = this;
( mergeSibling = function( rtl ){
var sibling = listNode[ rtl ?
'getPrevious' : 'getNext' ]( CKEDITOR.dom.walker.whitespaces( true ) );
if ( sibling && sibling.getName &&
sibling.getName() == listCommand.type )
{
sibling.remove();
// Move children order by merge direction.(#3820)
sibling.moveChildren( listNode, rtl );
}
} )();
mergeSibling( 1 );
}
// Clean up, restore selection and update toolbar button states.
CKEDITOR.dom.element.clearAllMarkers( database );
selection.selectBookmarks( bookmarks );
editor.focus();
}
};
var dtd = CKEDITOR.dtd;
var tailNbspRegex = /[\t\r\n ]*(?: |\xa0)$/;
function indexOfFirstChildElement( element, tagNameList )
{
var child,
children = element.children,
length = children.length;
for ( var i = 0 ; i < length ; i++ )
{
child = children[ i ];
if ( child.name && ( child.name in tagNameList ) )
return i;
}
return length;
}
function getExtendNestedListFilter( isHtmlFilter )
{
// An element filter function that corrects nested list start in an empty
// list item for better displaying/outputting. (#3165)
return function( listItem )
{
var children = listItem.children,
firstNestedListIndex = indexOfFirstChildElement( listItem, dtd.$list ),
firstNestedList = children[ firstNestedListIndex ],
nodeBefore = firstNestedList && firstNestedList.previous,
tailNbspmatch;
if ( nodeBefore
&& ( nodeBefore.name && nodeBefore.name == 'br'
|| nodeBefore.value && ( tailNbspmatch = nodeBefore.value.match( tailNbspRegex ) ) ) )
{
var fillerNode = nodeBefore;
// Always use 'nbsp' as filler node if we found a nested list appear
// in front of a list item.
if ( !( tailNbspmatch && tailNbspmatch.index ) && fillerNode == children[ 0 ] )
children[ 0 ] = ( isHtmlFilter || CKEDITOR.env.ie ) ?
new CKEDITOR.htmlParser.text( '\xa0' ) :
new CKEDITOR.htmlParser.element( 'br', {} );
// Otherwise the filler is not needed anymore.
else if ( fillerNode.name == 'br' )
children.splice( firstNestedListIndex - 1, 1 );
else
fillerNode.value = fillerNode.value.replace( tailNbspRegex, '' );
}
};
}
var defaultListDataFilterRules = { elements : {} };
for ( var i in dtd.$listItem )
defaultListDataFilterRules.elements[ i ] = getExtendNestedListFilter();
var defaultListHtmlFilterRules = { elements : {} };
for ( i in dtd.$listItem )
defaultListHtmlFilterRules.elements[ i ] = getExtendNestedListFilter( true );
CKEDITOR.plugins.add( 'list',
{
init : function( editor )
{
// Register commands.
var numberedListCommand = new listCommand( 'numberedlist', 'ol' ),
bulletedListCommand = new listCommand( 'bulletedlist', 'ul' );
editor.addCommand( 'numberedlist', numberedListCommand );
editor.addCommand( 'bulletedlist', bulletedListCommand );
// Register the toolbar button.
editor.ui.addButton( 'NumberedList',
{
label : editor.lang.numberedlist,
command : 'numberedlist'
} );
editor.ui.addButton( 'BulletedList',
{
label : editor.lang.bulletedlist,
command : 'bulletedlist'
} );
// Register the state changing handlers.
editor.on( 'selectionChange', CKEDITOR.tools.bind( onSelectionChange, numberedListCommand ) );
editor.on( 'selectionChange', CKEDITOR.tools.bind( onSelectionChange, bulletedListCommand ) );
},
afterInit : function ( editor )
{
var dataProcessor = editor.dataProcessor;
if ( dataProcessor )
{
dataProcessor.dataFilter.addRules( defaultListDataFilterRules );
dataProcessor.htmlFilter.addRules( defaultListHtmlFilterRules );
}
},
requires : [ 'domiterator' ]
} );
})();
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @fileOverview The default editing block plugin, which holds the editing area
* and source view.
*/
(function()
{
var getMode = function( editor, mode )
{
return editor._.modes && editor._.modes[ mode || editor.mode ];
};
// This is a semaphore used to avoid recursive calls between
// the following data handling functions.
var isHandlingData;
CKEDITOR.plugins.add( 'editingblock',
{
init : function( editor )
{
if ( !editor.config.editingBlock )
return;
editor.on( 'themeSpace', function( event )
{
if ( event.data.space == 'contents' )
event.data.html += '<br>';
});
editor.on( 'themeLoaded', function()
{
editor.fireOnce( 'editingBlockReady' );
});
editor.on( 'uiReady', function()
{
editor.setMode( editor.config.startupMode );
});
editor.on( 'afterSetData', function()
{
if ( !isHandlingData )
{
function setData()
{
isHandlingData = true;
getMode( editor ).loadData( editor.getData() );
isHandlingData = false;
}
if ( editor.mode )
setData();
else
{
editor.on( 'mode', function()
{
setData();
editor.removeListener( 'mode', arguments.callee );
});
}
}
});
editor.on( 'beforeGetData', function()
{
if ( !isHandlingData && editor.mode )
{
isHandlingData = true;
editor.setData( getMode( editor ).getData() );
isHandlingData = false;
}
});
editor.on( 'getSnapshot', function( event )
{
if ( editor.mode )
event.data = getMode( editor ).getSnapshotData();
});
editor.on( 'loadSnapshot', function( event )
{
if ( editor.mode )
getMode( editor ).loadSnapshotData( event.data );
});
// For the first "mode" call, we'll also fire the "instanceReady"
// event.
editor.on( 'mode', function( event )
{
// Do that once only.
event.removeListener();
// Redirect the focus into editor for webkit. (#5713)
CKEDITOR.env.webkit && editor.container.on( 'focus', function()
{
editor.focus();
});
if ( editor.config.startupFocus )
editor.focus();
// Fire instanceReady for both the editor and CKEDITOR, but
// defer this until the whole execution has completed
// to guarantee the editor is fully responsible.
setTimeout( function(){
editor.fireOnce( 'instanceReady' );
CKEDITOR.fire( 'instanceReady', null, editor );
}, 0 );
});
}
});
/**
* The current editing mode. An editing mode is basically a viewport for
* editing or content viewing. By default the possible values for this
* property are "wysiwyg" and "source".
* @type String
* @example
* alert( CKEDITOR.instances.editor1.mode ); // "wysiwyg" (e.g.)
*/
CKEDITOR.editor.prototype.mode = '';
/**
* Registers an editing mode. This function is to be used mainly by plugins.
* @param {String} mode The mode name.
* @param {Object} modeEditor The mode editor definition.
* @example
*/
CKEDITOR.editor.prototype.addMode = function( mode, modeEditor )
{
modeEditor.name = mode;
( this._.modes || ( this._.modes = {} ) )[ mode ] = modeEditor;
};
/**
* Sets the current editing mode in this editor instance.
* @param {String} mode A registered mode name.
* @example
* // Switch to "source" view.
* CKEDITOR.instances.editor1.setMode( 'source' );
*/
CKEDITOR.editor.prototype.setMode = function( mode )
{
var data,
holderElement = this.getThemeSpace( 'contents' ),
isDirty = this.checkDirty();
// Unload the previous mode.
if ( this.mode )
{
if ( mode == this.mode )
return;
this.fire( 'beforeModeUnload' );
var currentMode = getMode( this );
data = currentMode.getData();
currentMode.unload( holderElement );
this.mode = '';
}
holderElement.setHtml( '' );
// Load required mode.
var modeEditor = getMode( this, mode );
if ( !modeEditor )
throw '[CKEDITOR.editor.setMode] Unknown mode "' + mode + '".';
if ( !isDirty )
{
this.on( 'mode', function()
{
this.resetDirty();
this.removeListener( 'mode', arguments.callee );
});
}
modeEditor.load( holderElement, ( typeof data ) != 'string' ? this.getData() : data);
};
/**
* Moves the selection focus to the editing are space in the editor.
*/
CKEDITOR.editor.prototype.focus = function()
{
var mode = getMode( this );
if ( mode )
mode.focus();
};
})();
/**
* The mode to load at the editor startup. It depends on the plugins
* loaded. By default, the "wysiwyg" and "source" modes are available.
* @type String
* @default 'wysiwyg'
* @example
* config.startupMode = 'source';
*/
CKEDITOR.config.startupMode = 'wysiwyg';
/**
* Sets whether the editor should have the focus when the page loads.
* @type Boolean
* @default false
* @example
* config.startupFocus = true;
*/
/**
* Whether to render or not the editing block area in the editor interface.
* @type Boolean
* @default true
* @example
* config.editingBlock = false;
*/
CKEDITOR.config.editingBlock = true;
/**
* Fired when a CKEDITOR instance is created, fully initialized and ready for interaction.
* @name CKEDITOR#instanceReady
* @event
* @param {CKEDITOR.editor} editor The editor instance that has been created.
*/
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @fileOverview Defines the "virtual" dialog, dialog content and dialog button
* definition classes.
*/
/**
* This class is not really part of the API. It just illustrates the properties
* that developers can use to define and create dialogs.
* @name CKEDITOR.dialog.dialogDefinition
* @constructor
* @example
* // There is no constructor for this class, the user just has to define an
* // object with the appropriate properties.
*
* CKEDITOR.dialog.add( 'testOnly', function( editor )
* {
* return {
* title : 'Test Dialog',
* resizable : CKEDITOR.DIALOG_RESIZE_BOTH,
* minWidth : 500,
* minHeight : 400,
* contents : [
* {
* id : 'tab1',
* label : 'First Tab',
* title : 'First Tab Title',
* accessKey : 'Q',
* elements : [
* {
* type : 'text',
* label : 'Test Text 1',
* id : 'testText1',
* 'default' : 'hello world!'
* }
* ]
* }
* ]
* };
* });
*/
/**
* The dialog title, displayed in the dialog's header. Required.
* @name CKEDITOR.dialog.dialogDefinition.prototype.title
* @field
* @type String
* @example
*/
/**
* How the dialog can be resized, must be one of the four contents defined below.
* <br /><br />
* <strong>CKEDITOR.DIALOG_RESIZE_NONE</strong><br />
* <strong>CKEDITOR.DIALOG_RESIZE_WIDTH</strong><br />
* <strong>CKEDITOR.DIALOG_RESIZE_HEIGHT</strong><br />
* <strong>CKEDITOR.DIALOG_RESIZE_BOTH</strong><br />
* @name CKEDITOR.dialog.dialogDefinition.prototype.resizable
* @field
* @type Number
* @default CKEDITOR.DIALOG_RESIZE_NONE
* @example
*/
/**
* The minimum width of the dialog, in pixels.
* @name CKEDITOR.dialog.dialogDefinition.prototype.minWidth
* @field
* @type Number
* @default 600
* @example
*/
/**
* The minimum height of the dialog, in pixels.
* @name CKEDITOR.dialog.dialogDefinition.prototype.minHeight
* @field
* @type Number
* @default 400
* @example
*/
/**
* The buttons in the dialog, defined as an array of
* {@link CKEDITOR.dialog.buttonDefinition} objects.
* @name CKEDITOR.dialog.dialogDefinition.prototype.buttons
* @field
* @type Array
* @default [ CKEDITOR.dialog.okButton, CKEDITOR.dialog.cancelButton ]
* @example
*/
/**
* The contents in the dialog, defined as an array of
* {@link CKEDITOR.dialog.contentDefinition} objects. Required.
* @name CKEDITOR.dialog.dialogDefinition.prototype.contents
* @field
* @type Array
* @example
*/
/**
* The function to execute when OK is pressed.
* @name CKEDITOR.dialog.dialogDefinition.prototype.onOk
* @field
* @type Function
* @example
*/
/**
* The function to execute when Cancel is pressed.
* @name CKEDITOR.dialog.dialogDefinition.prototype.onCancel
* @field
* @type Function
* @example
*/
/**
* The function to execute when the dialog is displayed for the first time.
* @name CKEDITOR.dialog.dialogDefinition.prototype.onLoad
* @field
* @type Function
* @example
*/
/**
* This class is not really part of the API. It just illustrates the properties
* that developers can use to define and create dialog content pages.
* @name CKEDITOR.dialog.contentDefinition
* @constructor
* @example
* // There is no constructor for this class, the user just has to define an
* // object with the appropriate properties.
*/
/**
* The id of the content page.
* @name CKEDITOR.dialog.contentDefinition.prototype.id
* @field
* @type String
* @example
*/
/**
* The tab label of the content page.
* @name CKEDITOR.dialog.contentDefinition.prototype.label
* @field
* @type String
* @example
*/
/**
* The popup message of the tab label.
* @name CKEDITOR.dialog.contentDefinition.prototype.title
* @field
* @type String
* @example
*/
/**
* The CTRL hotkey for switching to the tab.
* @name CKEDITOR.dialog.contentDefinition.prototype.accessKey
* @field
* @type String
* @example
* contentDefinition.accessKey = 'Q'; // Switch to this page when CTRL-Q is pressed.
*/
/**
* The UI elements contained in this content page, defined as an array of
* {@link CKEDITOR.dialog.uiElementDefinition} objects.
* @name CKEDITOR.dialog.contentDefinition.prototype.elements
* @field
* @type Array
* @example
*/
/**
* This class is not really part of the API. It just illustrates the properties
* that developers can use to define and create dialog buttons.
* @name CKEDITOR.dialog.buttonDefinition
* @constructor
* @example
* // There is no constructor for this class, the user just has to define an
* // object with the appropriate properties.
*/
/**
* The id of the dialog button. Required.
* @name CKEDITOR.dialog.buttonDefinition.prototype.id
* @type String
* @field
* @example
*/
/**
* The label of the dialog button. Required.
* @name CKEDITOR.dialog.buttonDefinition.prototype.label
* @type String
* @field
* @example
*/
/**
* The popup message of the dialog button.
* @name CKEDITOR.dialog.buttonDefinition.prototype.title
* @type String
* @field
* @example
*/
/**
* The CTRL hotkey for the button.
* @name CKEDITOR.dialog.buttonDefinition.prototype.accessKey
* @type String
* @field
* @example
* exitButton.accessKey = 'X'; // Button will be pressed when user presses CTRL-X
*/
/**
* Whether the button is disabled.
* @name CKEDITOR.dialog.buttonDefinition.prototype.disabled
* @type Boolean
* @field
* @default false
* @example
*/
/**
* The function to execute when the button is clicked.
* @name CKEDITOR.dialog.buttonDefinition.prototype.onClick
* @type Function
* @field
* @example
*/
/**
* This class is not really part of the API. It just illustrates the properties
* that developers can use to define and create dialog UI elements.
* @name CKEDITOR.dialog.uiElementDefinition
* @constructor
* @see CKEDITOR.ui.dialog.uiElement
* @example
* // There is no constructor for this class, the user just has to define an
* // object with the appropriate properties.
*/
/**
* The id of the UI element.
* @name CKEDITOR.dialog.uiElementDefinition.prototype.id
* @field
* @type String
* @example
*/
/**
* The type of the UI element. Required.
* @name CKEDITOR.dialog.uiElementDefinition.prototype.type
* @field
* @type String
* @example
*/
/**
* The popup label of the UI element.
* @name CKEDITOR.dialog.uiElementDefinition.prototype.title
* @field
* @type String
* @example
*/
/**
* CSS class names to append to the UI element.
* @name CKEDITOR.dialog.uiElementDefinition.prototype.className
* @field
* @type String
* @example
*/
/**
* Inline CSS classes to append to the UI element.
* @name CKEDITOR.dialog.uiElementDefinition.prototype.style
* @field
* @type String
* @example
*/
/**
* Function to execute the first time the UI element is displayed.
* @name CKEDITOR.dialog.uiElementDefinition.prototype.onLoad
* @field
* @type Function
* @example
*/
/**
* Function to execute whenever the UI element's parent dialog is displayed.
* @name CKEDITOR.dialog.uiElementDefinition.prototype.onShow
* @field
* @type Function
* @example
*/
/**
* Function to execute whenever the UI element's parent dialog is closed.
* @name CKEDITOR.dialog.uiElementDefinition.prototype.onHide
* @field
* @type Function
* @example
*/
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @fileOverview The floating dialog plugin.
*/
/**
* No resize for this dialog.
* @constant
*/
CKEDITOR.DIALOG_RESIZE_NONE = 0;
/**
* Only allow horizontal resizing for this dialog, disable vertical resizing.
* @constant
*/
CKEDITOR.DIALOG_RESIZE_WIDTH = 1;
/**
* Only allow vertical resizing for this dialog, disable horizontal resizing.
* @constant
*/
CKEDITOR.DIALOG_RESIZE_HEIGHT = 2;
/*
* Allow the dialog to be resized in both directions.
* @constant
*/
CKEDITOR.DIALOG_RESIZE_BOTH = 3;
(function()
{
var cssLength = CKEDITOR.tools.cssLength;
function isTabVisible( tabId )
{
return !!this._.tabs[ tabId ][ 0 ].$.offsetHeight;
}
function getPreviousVisibleTab()
{
var tabId = this._.currentTabId,
length = this._.tabIdList.length,
tabIndex = CKEDITOR.tools.indexOf( this._.tabIdList, tabId ) + length;
for ( var i = tabIndex - 1 ; i > tabIndex - length ; i-- )
{
if ( isTabVisible.call( this, this._.tabIdList[ i % length ] ) )
return this._.tabIdList[ i % length ];
}
return null;
}
function getNextVisibleTab()
{
var tabId = this._.currentTabId,
length = this._.tabIdList.length,
tabIndex = CKEDITOR.tools.indexOf( this._.tabIdList, tabId );
for ( var i = tabIndex + 1 ; i < tabIndex + length ; i++ )
{
if ( isTabVisible.call( this, this._.tabIdList[ i % length ] ) )
return this._.tabIdList[ i % length ];
}
return null;
}
function clearOrRecoverTextInputValue( container, isRecover )
{
var inputs = container.$.getElementsByTagName( 'input' );
for ( var i = 0, length = inputs.length; i < length ; i++ )
{
var item = new CKEDITOR.dom.element( inputs[ i ] );
if ( item.getAttribute( 'type' ).toLowerCase() == 'text' )
{
if ( isRecover )
{
item.setAttribute( 'value', item.getCustomData( 'fake_value' ) || '' );
item.removeCustomData( 'fake_value' );
}
else
{
item.setCustomData( 'fake_value', item.getAttribute( 'value' ) );
item.setAttribute( 'value', '' );
}
}
}
}
/**
* This is the base class for runtime dialog objects. An instance of this
* class represents a single named dialog for a single editor instance.
* @param {Object} editor The editor which created the dialog.
* @param {String} dialogName The dialog's registered name.
* @constructor
* @example
* var dialogObj = new CKEDITOR.dialog( editor, 'smiley' );
*/
CKEDITOR.dialog = function( editor, dialogName )
{
// Load the dialog definition.
var definition = CKEDITOR.dialog._.dialogDefinitions[ dialogName ],
defaultDefinition = CKEDITOR.tools.clone( defaultDialogDefinition ),
buttonsOrder = editor.config.dialog_buttonsOrder || 'OS',
dir = editor.lang.dir;
if ( ( buttonsOrder == 'OS' && CKEDITOR.env.mac ) || // The buttons in MacOS Apps are in reverse order (#4750)
( buttonsOrder == 'rtl' && dir == 'ltr' ) ||
( buttonsOrder == 'ltr' && dir == 'rtl' ) )
defaultDefinition.buttons.reverse();
// Completes the definition with the default values.
definition = CKEDITOR.tools.extend( definition( editor ), defaultDefinition );
// Clone a functionally independent copy for this dialog.
definition = CKEDITOR.tools.clone( definition );
// Create a complex definition object, extending it with the API
// functions.
definition = new definitionObject( this, definition );
var doc = CKEDITOR.document;
var themeBuilt = editor.theme.buildDialog( editor );
// Initialize some basic parameters.
this._ =
{
editor : editor,
element : themeBuilt.element,
name : dialogName,
contentSize : { width : 0, height : 0 },
size : { width : 0, height : 0 },
contents : {},
buttons : {},
accessKeyMap : {},
// Initialize the tab and page map.
tabs : {},
tabIdList : [],
currentTabId : null,
currentTabIndex : null,
pageCount : 0,
lastTab : null,
tabBarMode : false,
// Initialize the tab order array for input widgets.
focusList : [],
currentFocusIndex : 0,
hasFocus : false
};
this.parts = themeBuilt.parts;
CKEDITOR.tools.setTimeout( function()
{
editor.fire( 'ariaWidget', this.parts.contents );
},
0, this );
// Set the startup styles for the dialog, avoiding it enlarging the
// page size on the dialog creation.
this.parts.dialog.setStyles(
{
position : CKEDITOR.env.ie6Compat ? 'absolute' : 'fixed',
top : 0,
left: 0,
visibility : 'hidden'
});
// Call the CKEDITOR.event constructor to initialize this instance.
CKEDITOR.event.call( this );
// Fire the "dialogDefinition" event, making it possible to customize
// the dialog definition.
this.definition = definition = CKEDITOR.fire( 'dialogDefinition',
{
name : dialogName,
definition : definition
}
, editor ).definition;
var tabsToRemove = {};
// Cache tabs that should be removed.
if ( !( 'removeDialogTabs' in editor._ ) && editor.config.removeDialogTabs )
{
var removeContents = editor.config.removeDialogTabs.split( ';' );
for ( i = 0; i < removeContents.length; i++ )
{
var parts = removeContents[ i ].split( ':' );
if ( parts.length == 2 )
{
var removeDialogName = parts[ 0 ];
if ( !tabsToRemove[ removeDialogName ] )
tabsToRemove[ removeDialogName ] = [];
tabsToRemove[ removeDialogName ].push( parts[ 1 ] );
}
}
editor._.removeDialogTabs = tabsToRemove;
}
// Remove tabs of this dialog.
if ( editor._.removeDialogTabs && ( tabsToRemove = editor._.removeDialogTabs[ dialogName ] ) )
{
for ( i = 0; i < tabsToRemove.length; i++ )
definition.removeContents( tabsToRemove[ i ] );
}
// Initialize load, show, hide, ok and cancel events.
if ( definition.onLoad )
this.on( 'load', definition.onLoad );
if ( definition.onShow )
this.on( 'show', definition.onShow );
if ( definition.onHide )
this.on( 'hide', definition.onHide );
if ( definition.onOk )
{
this.on( 'ok', function( evt )
{
// Dialog confirm might probably introduce content changes (#5415).
editor.fire( 'saveSnapshot' );
setTimeout( function () { editor.fire( 'saveSnapshot' ); }, 0 );
if ( definition.onOk.call( this, evt ) === false )
evt.data.hide = false;
});
}
if ( definition.onCancel )
{
this.on( 'cancel', function( evt )
{
if ( definition.onCancel.call( this, evt ) === false )
evt.data.hide = false;
});
}
var me = this;
// Iterates over all items inside all content in the dialog, calling a
// function for each of them.
var iterContents = function( func )
{
var contents = me._.contents,
stop = false;
for ( var i in contents )
{
for ( var j in contents[i] )
{
stop = func.call( this, contents[i][j] );
if ( stop )
return;
}
}
};
this.on( 'ok', function( evt )
{
iterContents( function( item )
{
if ( item.validate )
{
var isValid = item.validate( this );
if ( typeof isValid == 'string' )
{
alert( isValid );
isValid = false;
}
if ( isValid === false )
{
if ( item.select )
item.select();
else
item.focus();
evt.data.hide = false;
evt.stop();
return true;
}
}
});
}, this, null, 0 );
this.on( 'cancel', function( evt )
{
iterContents( function( item )
{
if ( item.isChanged() )
{
if ( !confirm( editor.lang.common.confirmCancel ) )
evt.data.hide = false;
return true;
}
});
}, this, null, 0 );
this.parts.close.on( 'click', function( evt )
{
if ( this.fire( 'cancel', { hide : true } ).hide !== false )
this.hide();
evt.data.preventDefault();
}, this );
// Sort focus list according to tab order definitions.
function setupFocus()
{
var focusList = me._.focusList;
focusList.sort( function( a, b )
{
// Mimics browser tab order logics;
if ( a.tabIndex != b.tabIndex )
return b.tabIndex - a.tabIndex;
// Sort is not stable in some browsers,
// fall-back the comparator to 'focusIndex';
else
return a.focusIndex - b.focusIndex;
});
var size = focusList.length;
for ( var i = 0; i < size; i++ )
focusList[ i ].focusIndex = i;
}
function changeFocus( forward )
{
var focusList = me._.focusList,
offset = forward ? 1 : -1;
if ( focusList.length < 1 )
return;
var current = me._.currentFocusIndex;
// Trigger the 'blur' event of any input element before anything,
// since certain UI updates may depend on it.
try
{
focusList[ current ].getInputElement().$.blur();
}
catch( e ){}
var startIndex = ( current + offset + focusList.length ) % focusList.length,
currentIndex = startIndex;
while ( !focusList[ currentIndex ].isFocusable() )
{
currentIndex = ( currentIndex + offset + focusList.length ) % focusList.length;
if ( currentIndex == startIndex )
break;
}
focusList[ currentIndex ].focus();
// Select whole field content.
if ( focusList[ currentIndex ].type == 'text' )
focusList[ currentIndex ].select();
}
this.changeFocus = changeFocus;
var processed;
function focusKeydownHandler( evt )
{
// If I'm not the top dialog, ignore.
if ( me != CKEDITOR.dialog._.currentTop )
return;
var keystroke = evt.data.getKeystroke(),
rtl = editor.lang.dir == 'rtl';
processed = 0;
if ( keystroke == 9 || keystroke == CKEDITOR.SHIFT + 9 )
{
var shiftPressed = ( keystroke == CKEDITOR.SHIFT + 9 );
// Handling Tab and Shift-Tab.
if ( me._.tabBarMode )
{
// Change tabs.
var nextId = shiftPressed ? getPreviousVisibleTab.call( me ) : getNextVisibleTab.call( me );
me.selectPage( nextId );
me._.tabs[ nextId ][ 0 ].focus();
}
else
{
// Change the focus of inputs.
changeFocus( !shiftPressed );
}
processed = 1;
}
else if ( keystroke == CKEDITOR.ALT + 121 && !me._.tabBarMode && me.getPageCount() > 1 )
{
// Alt-F10 puts focus into the current tab item in the tab bar.
me._.tabBarMode = true;
me._.tabs[ me._.currentTabId ][ 0 ].focus();
processed = 1;
}
else if ( ( keystroke == 37 || keystroke == 39 ) && me._.tabBarMode )
{
// Arrow keys - used for changing tabs.
nextId = ( keystroke == ( rtl ? 39 : 37 ) ? getPreviousVisibleTab.call( me ) : getNextVisibleTab.call( me ) );
me.selectPage( nextId );
me._.tabs[ nextId ][ 0 ].focus();
processed = 1;
}
else if ( ( keystroke == 13 || keystroke == 32 ) && me._.tabBarMode )
{
this.selectPage( this._.currentTabId );
this._.tabBarMode = false;
this._.currentFocusIndex = -1;
changeFocus( true );
processed = 1;
}
if ( processed )
{
evt.stop();
evt.data.preventDefault();
}
}
function focusKeyPressHandler( evt )
{
processed && evt.data.preventDefault();
}
var dialogElement = this._.element;
// Add the dialog keyboard handlers.
this.on( 'show', function()
{
dialogElement.on( 'keydown', focusKeydownHandler, this, null, 0 );
// Some browsers instead, don't cancel key events in the keydown, but in the
// keypress. So we must do a longer trip in those cases. (#4531)
if ( CKEDITOR.env.opera || ( CKEDITOR.env.gecko && CKEDITOR.env.mac ) )
dialogElement.on( 'keypress', focusKeyPressHandler, this );
} );
this.on( 'hide', function()
{
dialogElement.removeListener( 'keydown', focusKeydownHandler );
if ( CKEDITOR.env.opera || ( CKEDITOR.env.gecko && CKEDITOR.env.mac ) )
dialogElement.removeListener( 'keypress', focusKeyPressHandler );
} );
this.on( 'iframeAdded', function( evt )
{
var doc = new CKEDITOR.dom.document( evt.data.iframe.$.contentWindow.document );
doc.on( 'keydown', focusKeydownHandler, this, null, 0 );
} );
// Auto-focus logic in dialog.
this.on( 'show', function()
{
// Setup tabIndex on showing the dialog instead of on loading
// to allow dynamic tab order happen in dialog definition.
setupFocus();
if ( editor.config.dialog_startupFocusTab
&& me._.pageCount > 1 )
{
me._.tabBarMode = true;
me._.tabs[ me._.currentTabId ][ 0 ].focus();
}
else if ( !this._.hasFocus )
{
this._.currentFocusIndex = -1;
// Decide where to put the initial focus.
if ( definition.onFocus )
{
var initialFocus = definition.onFocus.call( this );
// Focus the field that the user specified.
initialFocus && initialFocus.focus();
}
// Focus the first field in layout order.
else
changeFocus( true );
/*
* IE BUG: If the initial focus went into a non-text element (e.g. button),
* then IE would still leave the caret inside the editing area.
*/
if ( this._.editor.mode == 'wysiwyg' && CKEDITOR.env.ie )
{
var $selection = editor.document.$.selection,
$range = $selection.createRange();
if ( $range )
{
if ( $range.parentElement && $range.parentElement().ownerDocument == editor.document.$
|| $range.item && $range.item( 0 ).ownerDocument == editor.document.$ )
{
var $myRange = document.body.createTextRange();
$myRange.moveToElementText( this.getElement().getFirst().$ );
$myRange.collapse( true );
$myRange.select();
}
}
}
}
}, this, null, 0xffffffff );
// IE6 BUG: Text fields and text areas are only half-rendered the first time the dialog appears in IE6 (#2661).
// This is still needed after [2708] and [2709] because text fields in hidden TR tags are still broken.
if ( CKEDITOR.env.ie6Compat )
{
this.on( 'load', function( evt )
{
var outer = this.getElement(),
inner = outer.getFirst();
inner.remove();
inner.appendTo( outer );
}, this );
}
initDragAndDrop( this );
initResizeHandles( this );
// Insert the title.
( new CKEDITOR.dom.text( definition.title, CKEDITOR.document ) ).appendTo( this.parts.title );
// Insert the tabs and contents.
for ( var i = 0 ; i < definition.contents.length ; i++ )
{
var page = definition.contents[i];
page && this.addPage( page );
}
this.parts[ 'tabs' ].on( 'click', function( evt )
{
var target = evt.data.getTarget();
// If we aren't inside a tab, bail out.
if ( target.hasClass( 'cke_dialog_tab' ) )
{
// Get the ID of the tab, without the 'cke_' prefix and the unique number suffix.
var id = target.$.id;
this.selectPage( id.substring( 4, id.lastIndexOf( '_' ) ) );
if ( this._.tabBarMode )
{
this._.tabBarMode = false;
this._.currentFocusIndex = -1;
changeFocus( true );
}
evt.data.preventDefault();
}
}, this );
// Insert buttons.
var buttonsHtml = [],
buttons = CKEDITOR.dialog._.uiElementBuilders.hbox.build( this,
{
type : 'hbox',
className : 'cke_dialog_footer_buttons',
widths : [],
children : definition.buttons
}, buttonsHtml ).getChild();
this.parts.footer.setHtml( buttonsHtml.join( '' ) );
for ( i = 0 ; i < buttons.length ; i++ )
this._.buttons[ buttons[i].id ] = buttons[i];
};
// Focusable interface. Use it via dialog.addFocusable.
function Focusable( dialog, element, index )
{
this.element = element;
this.focusIndex = index;
// TODO: support tabIndex for focusables.
this.tabIndex = 0;
this.isFocusable = function()
{
return !element.getAttribute( 'disabled' ) && element.isVisible();
};
this.focus = function()
{
dialog._.currentFocusIndex = this.focusIndex;
this.element.focus();
};
// Bind events
element.on( 'keydown', function( e )
{
if ( e.data.getKeystroke() in { 32:1, 13:1 } )
this.fire( 'click' );
} );
element.on( 'focus', function()
{
this.fire( 'mouseover' );
} );
element.on( 'blur', function()
{
this.fire( 'mouseout' );
} );
}
CKEDITOR.dialog.prototype =
{
destroy : function()
{
this.hide();
this._.element.remove();
},
/**
* Resizes the dialog.
* @param {Number} width The width of the dialog in pixels.
* @param {Number} height The height of the dialog in pixels.
* @function
* @example
* dialogObj.resize( 800, 640 );
*/
resize : (function()
{
return function( width, height )
{
if ( this._.contentSize && this._.contentSize.width == width && this._.contentSize.height == height )
return;
CKEDITOR.dialog.fire( 'resize',
{
dialog : this,
skin : this._.editor.skinName,
width : width,
height : height
}, this._.editor );
this._.contentSize = { width : width, height : height };
};
})(),
/**
* Gets the current size of the dialog in pixels.
* @returns {Object} An object with "width" and "height" properties.
* @example
* var width = dialogObj.getSize().width;
*/
getSize : function()
{
var element = this._.element.getFirst();
return { width : element.$.offsetWidth || 0, height : element.$.offsetHeight || 0};
},
/**
* Moves the dialog to an (x, y) coordinate relative to the window.
* @function
* @param {Number} x The target x-coordinate.
* @param {Number} y The target y-coordinate.
* @param {Boolean} save Flag indicate whether the dialog position should be remembered on next open up.
* @example
* dialogObj.move( 10, 40 );
*/
move : (function()
{
var isFixed;
return function( x, y, save )
{
// The dialog may be fixed positioned or absolute positioned. Ask the
// browser what is the current situation first.
var element = this._.element.getFirst();
if ( isFixed === undefined )
isFixed = element.getComputedStyle( 'position' ) == 'fixed';
if ( isFixed && this._.position && this._.position.x == x && this._.position.y == y )
return;
// Save the current position.
this._.position = { x : x, y : y };
// If not fixed positioned, add scroll position to the coordinates.
if ( !isFixed )
{
var scrollPosition = CKEDITOR.document.getWindow().getScrollPosition();
x += scrollPosition.x;
y += scrollPosition.y;
}
element.setStyles(
{
'left' : ( x > 0 ? x : 0 ) + 'px',
'top' : ( y > 0 ? y : 0 ) + 'px'
});
save && ( this._.moved = 1 );
};
})(),
/**
* Gets the dialog's position in the window.
* @returns {Object} An object with "x" and "y" properties.
* @example
* var dialogX = dialogObj.getPosition().x;
*/
getPosition : function(){ return CKEDITOR.tools.extend( {}, this._.position ); },
/**
* Shows the dialog box.
* @example
* dialogObj.show();
*/
show : function()
{
var editor = this._.editor;
if ( editor.mode == 'wysiwyg' && CKEDITOR.env.ie )
{
var selection = editor.getSelection();
selection && selection.lock();
}
// Insert the dialog's element to the root document.
var element = this._.element;
var definition = this.definition;
if ( !( element.getParent() && element.getParent().equals( CKEDITOR.document.getBody() ) ) )
element.appendTo( CKEDITOR.document.getBody() );
else
element.setStyle( 'display', 'block' );
// FIREFOX BUG: Fix vanishing caret for Firefox 2 or Gecko 1.8.
if ( CKEDITOR.env.gecko && CKEDITOR.env.version < 10900 )
{
var dialogElement = this.parts.dialog;
dialogElement.setStyle( 'position', 'absolute' );
setTimeout( function()
{
dialogElement.setStyle( 'position', 'fixed' );
}, 0 );
}
// First, set the dialog to an appropriate size.
this.resize( this._.contentSize && this._.contentSize.width || definition.minWidth,
this._.contentSize && this._.contentSize.height || definition.minHeight );
// Reset all inputs back to their default value.
this.reset();
// Select the first tab by default.
this.selectPage( this.definition.contents[0].id );
// Set z-index.
if ( CKEDITOR.dialog._.currentZIndex === null )
CKEDITOR.dialog._.currentZIndex = this._.editor.config.baseFloatZIndex;
this._.element.getFirst().setStyle( 'z-index', CKEDITOR.dialog._.currentZIndex += 10 );
// Maintain the dialog ordering and dialog cover.
// Also register key handlers if first dialog.
if ( CKEDITOR.dialog._.currentTop === null )
{
CKEDITOR.dialog._.currentTop = this;
this._.parentDialog = null;
showCover( this._.editor );
element.on( 'keydown', accessKeyDownHandler );
element.on( CKEDITOR.env.opera ? 'keypress' : 'keyup', accessKeyUpHandler );
// Prevent some keys from bubbling up. (#4269)
for ( var event in { keyup :1, keydown :1, keypress :1 } )
element.on( event, preventKeyBubbling );
}
else
{
this._.parentDialog = CKEDITOR.dialog._.currentTop;
var parentElement = this._.parentDialog.getElement().getFirst();
parentElement.$.style.zIndex -= Math.floor( this._.editor.config.baseFloatZIndex / 2 );
CKEDITOR.dialog._.currentTop = this;
}
// Register the Esc hotkeys.
registerAccessKey( this, this, '\x1b', null, function()
{
this.getButton( 'cancel' ) && this.getButton( 'cancel' ).click();
} );
// Reset the hasFocus state.
this._.hasFocus = false;
CKEDITOR.tools.setTimeout( function()
{
this.layout();
this.parts.dialog.setStyle( 'visibility', '' );
// Execute onLoad for the first show.
this.fireOnce( 'load', {} );
CKEDITOR.ui.fire( 'ready', this );
this.fire( 'show', {} );
this._.editor.fire( 'dialogShow', this );
// Save the initial values of the dialog.
this.foreach( function( contentObj ) { contentObj.setInitValue && contentObj.setInitValue(); } );
},
100, this );
},
/**
* Rearrange the dialog to its previous position or the middle of the window.
* @since 3.5
*/
layout : function()
{
var viewSize = CKEDITOR.document.getWindow().getViewPaneSize(),
dialogSize = this.getSize();
this.move( this._.moved ? this._.position.x : ( viewSize.width - dialogSize.width ) / 2,
this._.moved ? this._.position.y : ( viewSize.height - dialogSize.height ) / 2 );
},
/**
* Executes a function for each UI element.
* @param {Function} fn Function to execute for each UI element.
* @returns {CKEDITOR.dialog} The current dialog object.
*/
foreach : function( fn )
{
for ( var i in this._.contents )
{
for ( var j in this._.contents[i] )
fn( this._.contents[i][j] );
}
return this;
},
/**
* Resets all input values in the dialog.
* @example
* dialogObj.reset();
* @returns {CKEDITOR.dialog} The current dialog object.
*/
reset : (function()
{
var fn = function( widget ){ if ( widget.reset ) widget.reset( 1 ); };
return function(){ this.foreach( fn ); return this; };
})(),
setupContent : function()
{
var args = arguments;
this.foreach( function( widget )
{
if ( widget.setup )
widget.setup.apply( widget, args );
});
},
commitContent : function()
{
var args = arguments;
this.foreach( function( widget )
{
if ( widget.commit )
widget.commit.apply( widget, args );
});
},
/**
* Hides the dialog box.
* @example
* dialogObj.hide();
*/
hide : function()
{
if ( !this.parts.dialog.isVisible() )
return;
this.fire( 'hide', {} );
this._.editor.fire( 'dialogHide', this );
var element = this._.element;
element.setStyle( 'display', 'none' );
this.parts.dialog.setStyle( 'visibility', 'hidden' );
// Unregister all access keys associated with this dialog.
unregisterAccessKey( this );
// Close any child(top) dialogs first.
while( CKEDITOR.dialog._.currentTop != this )
CKEDITOR.dialog._.currentTop.hide();
// Maintain dialog ordering and remove cover if needed.
if ( !this._.parentDialog )
hideCover();
else
{
var parentElement = this._.parentDialog.getElement().getFirst();
parentElement.setStyle( 'z-index', parseInt( parentElement.$.style.zIndex, 10 ) + Math.floor( this._.editor.config.baseFloatZIndex / 2 ) );
}
CKEDITOR.dialog._.currentTop = this._.parentDialog;
// Deduct or clear the z-index.
if ( !this._.parentDialog )
{
CKEDITOR.dialog._.currentZIndex = null;
// Remove access key handlers.
element.removeListener( 'keydown', accessKeyDownHandler );
element.removeListener( CKEDITOR.env.opera ? 'keypress' : 'keyup', accessKeyUpHandler );
// Remove bubbling-prevention handler. (#4269)
for ( var event in { keyup :1, keydown :1, keypress :1 } )
element.removeListener( event, preventKeyBubbling );
var editor = this._.editor;
editor.focus();
if ( editor.mode == 'wysiwyg' && CKEDITOR.env.ie )
{
var selection = editor.getSelection();
selection && selection.unlock( true );
}
}
else
CKEDITOR.dialog._.currentZIndex -= 10;
delete this._.parentDialog;
// Reset the initial values of the dialog.
this.foreach( function( contentObj ) { contentObj.resetInitValue && contentObj.resetInitValue(); } );
},
/**
* Adds a tabbed page into the dialog.
* @param {Object} contents Content definition.
* @example
*/
addPage : function( contents )
{
var pageHtml = [],
titleHtml = contents.label ? ' title="' + CKEDITOR.tools.htmlEncode( contents.label ) + '"' : '',
elements = contents.elements,
vbox = CKEDITOR.dialog._.uiElementBuilders.vbox.build( this,
{
type : 'vbox',
className : 'cke_dialog_page_contents',
children : contents.elements,
expand : !!contents.expand,
padding : contents.padding,
style : contents.style || 'width: 100%;'
}, pageHtml );
// Create the HTML for the tab and the content block.
var page = CKEDITOR.dom.element.createFromHtml( pageHtml.join( '' ) );
page.setAttribute( 'role', 'tabpanel' );
var env = CKEDITOR.env;
var tabId = 'cke_' + contents.id + '_' + CKEDITOR.tools.getNextNumber(),
tab = CKEDITOR.dom.element.createFromHtml( [
'<a class="cke_dialog_tab"',
( this._.pageCount > 0 ? ' cke_last' : 'cke_first' ),
titleHtml,
( !!contents.hidden ? ' style="display:none"' : '' ),
' id="', tabId, '"',
env.gecko && env.version >= 10900 && !env.hc ? '' : ' href="javascript:void(0)"',
' tabIndex="-1"',
' hidefocus="true"',
' role="tab">',
contents.label,
'</a>'
].join( '' ) );
page.setAttribute( 'aria-labelledby', tabId );
// Take records for the tabs and elements created.
this._.tabs[ contents.id ] = [ tab, page ];
this._.tabIdList.push( contents.id );
!contents.hidden && this._.pageCount++;
this._.lastTab = tab;
this.updateStyle();
var contentMap = this._.contents[ contents.id ] = {},
cursor,
children = vbox.getChild();
while ( ( cursor = children.shift() ) )
{
contentMap[ cursor.id ] = cursor;
if ( typeof( cursor.getChild ) == 'function' )
children.push.apply( children, cursor.getChild() );
}
// Attach the DOM nodes.
page.setAttribute( 'name', contents.id );
page.appendTo( this.parts.contents );
tab.unselectable();
this.parts.tabs.append( tab );
// Add access key handlers if access key is defined.
if ( contents.accessKey )
{
registerAccessKey( this, this, 'CTRL+' + contents.accessKey,
tabAccessKeyDown, tabAccessKeyUp );
this._.accessKeyMap[ 'CTRL+' + contents.accessKey ] = contents.id;
}
},
/**
* Activates a tab page in the dialog by its id.
* @param {String} id The id of the dialog tab to be activated.
* @example
* dialogObj.selectPage( 'tab_1' );
*/
selectPage : function( id )
{
if ( this._.currentTabId == id )
return;
// Returning true means that the event has been canceled
if ( this.fire( 'selectPage', { page : id, currentPage : this._.currentTabId } ) === true )
return;
// Hide the non-selected tabs and pages.
for ( var i in this._.tabs )
{
var tab = this._.tabs[i][0],
page = this._.tabs[i][1];
if ( i != id )
{
tab.removeClass( 'cke_dialog_tab_selected' );
page.hide();
}
page.setAttribute( 'aria-hidden', i != id );
}
var selected = this._.tabs[ id ];
selected[ 0 ].addClass( 'cke_dialog_tab_selected' );
// [IE] an invisible input[type='text'] will enlarge it's width
// if it's value is long when it shows, so we clear it's value
// before it shows and then recover it (#5649)
if ( CKEDITOR.env.ie6Compat || CKEDITOR.env.ie7Compat )
{
clearOrRecoverTextInputValue( selected[ 1 ] );
selected[ 1 ].show();
setTimeout( function()
{
clearOrRecoverTextInputValue( selected[ 1 ], 1 );
}, 0 );
}
else
selected[ 1 ].show();
this._.currentTabId = id;
this._.currentTabIndex = CKEDITOR.tools.indexOf( this._.tabIdList, id );
},
// Dialog state-specific style updates.
updateStyle : function()
{
// If only a single page shown, a different style is used in the central pane.
this.parts.dialog[ ( this._.pageCount === 1 ? 'add' : 'remove' ) + 'Class' ]( 'cke_single_page' );
},
/**
* Hides a page's tab away from the dialog.
* @param {String} id The page's Id.
* @example
* dialog.hidePage( 'tab_3' );
*/
hidePage : function( id )
{
var tab = this._.tabs[id] && this._.tabs[id][0];
if ( !tab || this._.pageCount == 1 || !tab.isVisible() )
return;
// Switch to other tab first when we're hiding the active tab.
else if ( id == this._.currentTabId )
this.selectPage( getPreviousVisibleTab.call( this ) );
tab.hide();
this._.pageCount--;
this.updateStyle();
},
/**
* Unhides a page's tab.
* @param {String} id The page's Id.
* @example
* dialog.showPage( 'tab_2' );
*/
showPage : function( id )
{
var tab = this._.tabs[id] && this._.tabs[id][0];
if ( !tab )
return;
tab.show();
this._.pageCount++;
this.updateStyle();
},
/**
* Gets the root DOM element of the dialog.
* @returns {CKEDITOR.dom.element} The <span> element containing this dialog.
* @example
* var dialogElement = dialogObj.getElement().getFirst();
* dialogElement.setStyle( 'padding', '5px' );
*/
getElement : function()
{
return this._.element;
},
/**
* Gets the name of the dialog.
* @returns {String} The name of this dialog.
* @example
* var dialogName = dialogObj.getName();
*/
getName : function()
{
return this._.name;
},
/**
* Gets a dialog UI element object from a dialog page.
* @param {String} pageId id of dialog page.
* @param {String} elementId id of UI element.
* @example
* @returns {CKEDITOR.ui.dialog.uiElement} The dialog UI element.
*/
getContentElement : function( pageId, elementId )
{
var page = this._.contents[ pageId ];
return page && page[ elementId ];
},
/**
* Gets the value of a dialog UI element.
* @param {String} pageId id of dialog page.
* @param {String} elementId id of UI element.
* @example
* @returns {Object} The value of the UI element.
*/
getValueOf : function( pageId, elementId )
{
return this.getContentElement( pageId, elementId ).getValue();
},
/**
* Sets the value of a dialog UI element.
* @param {String} pageId id of the dialog page.
* @param {String} elementId id of the UI element.
* @param {Object} value The new value of the UI element.
* @example
*/
setValueOf : function( pageId, elementId, value )
{
return this.getContentElement( pageId, elementId ).setValue( value );
},
/**
* Gets the UI element of a button in the dialog's button row.
* @param {String} id The id of the button.
* @example
* @returns {CKEDITOR.ui.dialog.button} The button object.
*/
getButton : function( id )
{
return this._.buttons[ id ];
},
/**
* Simulates a click to a dialog button in the dialog's button row.
* @param {String} id The id of the button.
* @example
* @returns The return value of the dialog's "click" event.
*/
click : function( id )
{
return this._.buttons[ id ].click();
},
/**
* Disables a dialog button.
* @param {String} id The id of the button.
* @example
*/
disableButton : function( id )
{
return this._.buttons[ id ].disable();
},
/**
* Enables a dialog button.
* @param {String} id The id of the button.
* @example
*/
enableButton : function( id )
{
return this._.buttons[ id ].enable();
},
/**
* Gets the number of pages in the dialog.
* @returns {Number} Page count.
*/
getPageCount : function()
{
return this._.pageCount;
},
/**
* Gets the editor instance which opened this dialog.
* @returns {CKEDITOR.editor} Parent editor instances.
*/
getParentEditor : function()
{
return this._.editor;
},
/**
* Gets the element that was selected when opening the dialog, if any.
* @returns {CKEDITOR.dom.element} The element that was selected, or null.
*/
getSelectedElement : function()
{
return this.getParentEditor().getSelection().getSelectedElement();
},
/**
* Adds element to dialog's focusable list.
*
* @param {CKEDITOR.dom.element} element
* @param {Number} [index]
*/
addFocusable: function( element, index ) {
if ( typeof index == 'undefined' )
{
index = this._.focusList.length;
this._.focusList.push( new Focusable( this, element, index ) );
}
else
{
this._.focusList.splice( index, 0, new Focusable( this, element, index ) );
for ( var i = index + 1 ; i < this._.focusList.length ; i++ )
this._.focusList[ i ].focusIndex++;
}
}
};
CKEDITOR.tools.extend( CKEDITOR.dialog,
/**
* @lends CKEDITOR.dialog
*/
{
/**
* Registers a dialog.
* @param {String} name The dialog's name.
* @param {Function|String} dialogDefinition
* A function returning the dialog's definition, or the URL to the .js file holding the function.
* The function should accept an argument "editor" which is the current editor instance, and
* return an object conforming to {@link CKEDITOR.dialog.dialogDefinition}.
* @example
* @see CKEDITOR.dialog.dialogDefinition
*/
add : function( name, dialogDefinition )
{
// Avoid path registration from multiple instances override definition.
if ( !this._.dialogDefinitions[name]
|| typeof dialogDefinition == 'function' )
this._.dialogDefinitions[name] = dialogDefinition;
},
exists : function( name )
{
return !!this._.dialogDefinitions[ name ];
},
getCurrent : function()
{
return CKEDITOR.dialog._.currentTop;
},
/**
* The default OK button for dialogs. Fires the "ok" event and closes the dialog if the event succeeds.
* @static
* @field
* @example
* @type Function
*/
okButton : (function()
{
var retval = function( editor, override )
{
override = override || {};
return CKEDITOR.tools.extend( {
id : 'ok',
type : 'button',
label : editor.lang.common.ok,
'class' : 'cke_dialog_ui_button_ok',
onClick : function( evt )
{
var dialog = evt.data.dialog;
if ( dialog.fire( 'ok', { hide : true } ).hide !== false )
dialog.hide();
}
}, override, true );
};
retval.type = 'button';
retval.override = function( override )
{
return CKEDITOR.tools.extend( function( editor ){ return retval( editor, override ); },
{ type : 'button' }, true );
};
return retval;
})(),
/**
* The default cancel button for dialogs. Fires the "cancel" event and closes the dialog if no UI element value changed.
* @static
* @field
* @example
* @type Function
*/
cancelButton : (function()
{
var retval = function( editor, override )
{
override = override || {};
return CKEDITOR.tools.extend( {
id : 'cancel',
type : 'button',
label : editor.lang.common.cancel,
'class' : 'cke_dialog_ui_button_cancel',
onClick : function( evt )
{
var dialog = evt.data.dialog;
if ( dialog.fire( 'cancel', { hide : true } ).hide !== false )
dialog.hide();
}
}, override, true );
};
retval.type = 'button';
retval.override = function( override )
{
return CKEDITOR.tools.extend( function( editor ){ return retval( editor, override ); },
{ type : 'button' }, true );
};
return retval;
})(),
/**
* Registers a dialog UI element.
* @param {String} typeName The name of the UI element.
* @param {Function} builder The function to build the UI element.
* @example
*/
addUIElement : function( typeName, builder )
{
this._.uiElementBuilders[ typeName ] = builder;
}
});
CKEDITOR.dialog._ =
{
uiElementBuilders : {},
dialogDefinitions : {},
currentTop : null,
currentZIndex : null
};
// "Inherit" (copy actually) from CKEDITOR.event.
CKEDITOR.event.implementOn( CKEDITOR.dialog );
CKEDITOR.event.implementOn( CKEDITOR.dialog.prototype, true );
var defaultDialogDefinition =
{
resizable : CKEDITOR.DIALOG_RESIZE_BOTH,
minWidth : 600,
minHeight : 400,
buttons : [ CKEDITOR.dialog.okButton, CKEDITOR.dialog.cancelButton ]
};
// Tool function used to return an item from an array based on its id
// property.
var getById = function( array, id, recurse )
{
for ( var i = 0, item ; ( item = array[ i ] ) ; i++ )
{
if ( item.id == id )
return item;
if ( recurse && item[ recurse ] )
{
var retval = getById( item[ recurse ], id, recurse ) ;
if ( retval )
return retval;
}
}
return null;
};
// Tool function used to add an item into an array.
var addById = function( array, newItem, nextSiblingId, recurse, nullIfNotFound )
{
if ( nextSiblingId )
{
for ( var i = 0, item ; ( item = array[ i ] ) ; i++ )
{
if ( item.id == nextSiblingId )
{
array.splice( i, 0, newItem );
return newItem;
}
if ( recurse && item[ recurse ] )
{
var retval = addById( item[ recurse ], newItem, nextSiblingId, recurse, true );
if ( retval )
return retval;
}
}
if ( nullIfNotFound )
return null;
}
array.push( newItem );
return newItem;
};
// Tool function used to remove an item from an array based on its id.
var removeById = function( array, id, recurse )
{
for ( var i = 0, item ; ( item = array[ i ] ) ; i++ )
{
if ( item.id == id )
return array.splice( i, 1 );
if ( recurse && item[ recurse ] )
{
var retval = removeById( item[ recurse ], id, recurse );
if ( retval )
return retval;
}
}
return null;
};
/**
* This class is not really part of the API. It is the "definition" property value
* passed to "dialogDefinition" event handlers.
* @constructor
* @name CKEDITOR.dialog.dialogDefinitionObject
* @extends CKEDITOR.dialog.dialogDefinition
* @example
* CKEDITOR.on( 'dialogDefinition', function( evt )
* {
* var definition = evt.data.definition;
* var content = definition.getContents( 'page1' );
* ...
* } );
*/
var definitionObject = function( dialog, dialogDefinition )
{
// TODO : Check if needed.
this.dialog = dialog;
// Transform the contents entries in contentObjects.
var contents = dialogDefinition.contents;
for ( var i = 0, content ; ( content = contents[i] ) ; i++ )
contents[ i ] = content && new contentObject( dialog, content );
CKEDITOR.tools.extend( this, dialogDefinition );
};
definitionObject.prototype =
/** @lends CKEDITOR.dialog.dialogDefinitionObject.prototype */
{
/**
* Gets a content definition.
* @param {String} id The id of the content definition.
* @returns {CKEDITOR.dialog.contentDefinition} The content definition
* matching id.
*/
getContents : function( id )
{
return getById( this.contents, id );
},
/**
* Gets a button definition.
* @param {String} id The id of the button definition.
* @returns {CKEDITOR.dialog.buttonDefinition} The button definition
* matching id.
*/
getButton : function( id )
{
return getById( this.buttons, id );
},
/**
* Adds a content definition object under this dialog definition.
* @param {CKEDITOR.dialog.contentDefinition} contentDefinition The
* content definition.
* @param {String} [nextSiblingId] The id of an existing content
* definition which the new content definition will be inserted
* before. Omit if the new content definition is to be inserted as
* the last item.
* @returns {CKEDITOR.dialog.contentDefinition} The inserted content
* definition.
*/
addContents : function( contentDefinition, nextSiblingId )
{
return addById( this.contents, contentDefinition, nextSiblingId );
},
/**
* Adds a button definition object under this dialog definition.
* @param {CKEDITOR.dialog.buttonDefinition} buttonDefinition The
* button definition.
* @param {String} [nextSiblingId] The id of an existing button
* definition which the new button definition will be inserted
* before. Omit if the new button definition is to be inserted as
* the last item.
* @returns {CKEDITOR.dialog.buttonDefinition} The inserted button
* definition.
*/
addButton : function( buttonDefinition, nextSiblingId )
{
return addById( this.buttons, buttonDefinition, nextSiblingId );
},
/**
* Removes a content definition from this dialog definition.
* @param {String} id The id of the content definition to be removed.
* @returns {CKEDITOR.dialog.contentDefinition} The removed content
* definition.
*/
removeContents : function( id )
{
removeById( this.contents, id );
},
/**
* Removes a button definition from the dialog definition.
* @param {String} id The id of the button definition to be removed.
* @returns {CKEDITOR.dialog.buttonDefinition} The removed button
* definition.
*/
removeButton : function( id )
{
removeById( this.buttons, id );
}
};
/**
* This class is not really part of the API. It is the template of the
* objects representing content pages inside the
* CKEDITOR.dialog.dialogDefinitionObject.
* @constructor
* @name CKEDITOR.dialog.contentDefinitionObject
* @example
* CKEDITOR.on( 'dialogDefinition', function( evt )
* {
* var definition = evt.data.definition;
* var content = definition.getContents( 'page1' );
* content.remove( 'textInput1' );
* ...
* } );
*/
function contentObject( dialog, contentDefinition )
{
this._ =
{
dialog : dialog
};
CKEDITOR.tools.extend( this, contentDefinition );
}
contentObject.prototype =
/** @lends CKEDITOR.dialog.contentDefinitionObject.prototype */
{
/**
* Gets a UI element definition under the content definition.
* @param {String} id The id of the UI element definition.
* @returns {CKEDITOR.dialog.uiElementDefinition}
*/
get : function( id )
{
return getById( this.elements, id, 'children' );
},
/**
* Adds a UI element definition to the content definition.
* @param {CKEDITOR.dialog.uiElementDefinition} elementDefinition The
* UI elemnet definition to be added.
* @param {String} nextSiblingId The id of an existing UI element
* definition which the new UI element definition will be inserted
* before. Omit if the new button definition is to be inserted as
* the last item.
* @returns {CKEDITOR.dialog.uiElementDefinition} The element
* definition inserted.
*/
add : function( elementDefinition, nextSiblingId )
{
return addById( this.elements, elementDefinition, nextSiblingId, 'children' );
},
/**
* Removes a UI element definition from the content definition.
* @param {String} id The id of the UI element definition to be
* removed.
* @returns {CKEDITOR.dialog.uiElementDefinition} The element
* definition removed.
* @example
*/
remove : function( id )
{
removeById( this.elements, id, 'children' );
}
};
function initDragAndDrop( dialog )
{
var lastCoords = null,
abstractDialogCoords = null,
element = dialog.getElement().getFirst(),
editor = dialog.getParentEditor(),
magnetDistance = editor.config.dialog_magnetDistance,
margins = editor.skin.margins || [ 0, 0, 0, 0 ];
if ( typeof magnetDistance == 'undefined' )
magnetDistance = 20;
function mouseMoveHandler( evt )
{
var dialogSize = dialog.getSize(),
viewPaneSize = CKEDITOR.document.getWindow().getViewPaneSize(),
x = evt.data.$.screenX,
y = evt.data.$.screenY,
dx = x - lastCoords.x,
dy = y - lastCoords.y,
realX, realY;
lastCoords = { x : x, y : y };
abstractDialogCoords.x += dx;
abstractDialogCoords.y += dy;
if ( abstractDialogCoords.x + margins[3] < magnetDistance )
realX = - margins[3];
else if ( abstractDialogCoords.x - margins[1] > viewPaneSize.width - dialogSize.width - magnetDistance )
realX = viewPaneSize.width - dialogSize.width + ( editor.lang.dir == 'rtl' ? 0 : margins[1] );
else
realX = abstractDialogCoords.x;
if ( abstractDialogCoords.y + margins[0] < magnetDistance )
realY = - margins[0];
else if ( abstractDialogCoords.y - margins[2] > viewPaneSize.height - dialogSize.height - magnetDistance )
realY = viewPaneSize.height - dialogSize.height + margins[2];
else
realY = abstractDialogCoords.y;
dialog.move( realX, realY, 1 );
evt.data.preventDefault();
}
function mouseUpHandler( evt )
{
CKEDITOR.document.removeListener( 'mousemove', mouseMoveHandler );
CKEDITOR.document.removeListener( 'mouseup', mouseUpHandler );
if ( CKEDITOR.env.ie6Compat )
{
var coverDoc = currentCover.getChild( 0 ).getFrameDocument();
coverDoc.removeListener( 'mousemove', mouseMoveHandler );
coverDoc.removeListener( 'mouseup', mouseUpHandler );
}
}
dialog.parts.title.on( 'mousedown', function( evt )
{
lastCoords = { x : evt.data.$.screenX, y : evt.data.$.screenY };
CKEDITOR.document.on( 'mousemove', mouseMoveHandler );
CKEDITOR.document.on( 'mouseup', mouseUpHandler );
abstractDialogCoords = dialog.getPosition();
if ( CKEDITOR.env.ie6Compat )
{
var coverDoc = currentCover.getChild( 0 ).getFrameDocument();
coverDoc.on( 'mousemove', mouseMoveHandler );
coverDoc.on( 'mouseup', mouseUpHandler );
}
evt.data.preventDefault();
}, dialog );
}
function initResizeHandles( dialog )
{
var def = dialog.definition,
resizable = def.resizable;
if ( resizable == CKEDITOR.DIALOG_RESIZE_NONE )
return;
var editor = dialog.getParentEditor();
var wrapperWidth, wrapperHeight, viewSize, origin, startSize;
function positionDialog( right )
{
// Maintain righthand sizing in RTL.
if ( dialog._.moved && editor.lang.dir == 'rtl' )
{
var element = dialog._.element.getFirst();
element.setStyle( 'right', right + "px" );
element.removeStyle( 'left' );
}
else if ( !dialog._.moved )
dialog.layout();
}
var mouseDownFn = CKEDITOR.tools.addFunction( function( $event )
{
startSize = dialog.getSize();
// Calculate the offset between content and chrome size.
wrapperHeight = startSize.height - dialog.parts.contents.getSize( 'height', ! ( CKEDITOR.env.gecko || CKEDITOR.env.opera || CKEDITOR.env.ie && CKEDITOR.env.quirks ) );
wrapperWidth = startSize.width - dialog.parts.contents.getSize( 'width', 1 );
origin = { x : $event.screenX, y : $event.screenY };
viewSize = CKEDITOR.document.getWindow().getViewPaneSize();
CKEDITOR.document.on( 'mousemove', mouseMoveHandler );
CKEDITOR.document.on( 'mouseup', mouseUpHandler );
if ( CKEDITOR.env.ie6Compat )
{
var coverDoc = currentCover.getChild( 0 ).getFrameDocument();
coverDoc.on( 'mousemove', mouseMoveHandler );
coverDoc.on( 'mouseup', mouseUpHandler );
}
$event.preventDefault && $event.preventDefault();
});
// Prepend the grip to the dialog.
dialog.on( 'load', function()
{
var direction = '';
if ( resizable == CKEDITOR.DIALOG_RESIZE_WIDTH )
direction = ' cke_resizer_horizontal';
else if ( resizable == CKEDITOR.DIALOG_RESIZE_HEIGHT )
direction = ' cke_resizer_vertical';
var resizer = CKEDITOR.dom.element.createFromHtml( '<div class="cke_resizer' + direction + '"' +
' title="' + CKEDITOR.tools.htmlEncode( editor.lang.resize ) + '"' +
' onmousedown="CKEDITOR.tools.callFunction(' + mouseDownFn + ', event )"></div>' );
dialog.parts.footer.append( resizer, 1 );
});
editor.on( 'destroy', function() { CKEDITOR.tools.removeFunction( mouseDownFn ); } );
function mouseMoveHandler( evt )
{
var rtl = editor.lang.dir == 'rtl',
dx = ( evt.data.$.screenX - origin.x ) * ( rtl ? -1 : 1 ),
dy = evt.data.$.screenY - origin.y,
width = startSize.width,
height = startSize.height,
internalWidth = width + dx * ( dialog._.moved ? 1 : 2 ),
internalHeight = height + dy * ( dialog._.moved ? 1 : 2 ),
element = dialog._.element.getFirst(),
right = rtl && element.getComputedStyle( 'right' ),
position = dialog.getPosition();
// IE might return "auto", we need exact position.
if ( right )
right = right == 'auto' ? viewSize.width - ( position.x || 0 ) - element.getSize( 'width' ) : parseInt( right, 10 );
if ( position.y + internalHeight > viewSize.height )
internalHeight = viewSize.height - position.y;
if ( ( rtl ? right : position.x ) + internalWidth > viewSize.width )
internalWidth = viewSize.width - ( rtl ? right : position.x );
// Make sure the dialog will not be resized to the wrong side when it's in the leftmost position for RTL.
if ( ( resizable == CKEDITOR.DIALOG_RESIZE_WIDTH || resizable == CKEDITOR.DIALOG_RESIZE_BOTH ) && !( rtl && dx > 0 && !position.x ) )
width = Math.max( def.minWidth || 0, internalWidth - wrapperWidth );
if ( resizable == CKEDITOR.DIALOG_RESIZE_HEIGHT || resizable == CKEDITOR.DIALOG_RESIZE_BOTH )
height = Math.max( def.minHeight || 0, internalHeight - wrapperHeight );
dialog.resize( width, height );
// The right property might get broken during resizing, so computing it before the resizing.
positionDialog( right );
evt.data.preventDefault();
}
function mouseUpHandler()
{
CKEDITOR.document.removeListener( 'mouseup', mouseUpHandler );
CKEDITOR.document.removeListener( 'mousemove', mouseMoveHandler );
if ( CKEDITOR.env.ie6Compat )
{
var coverDoc = currentCover.getChild( 0 ).getFrameDocument();
coverDoc.removeListener( 'mouseup', mouseUpHandler );
coverDoc.removeListener( 'mousemove', mouseMoveHandler );
}
// Switch back to use the left property, if RTL is used.
if ( editor.lang.dir == 'rtl' )
{
var element = dialog._.element.getFirst(),
left = element.getComputedStyle( 'left' );
// IE might return "auto", we need exact position.
if ( left == 'auto' )
left = viewSize.width - parseInt( element.getStyle( 'right' ), 10 ) - dialog.getSize().width;
else
left = parseInt( left, 10 );
element.removeStyle( 'right' );
// Make sure the left property gets applied, even if it is the same as previously.
dialog._.position.x += 1;
dialog.move( left, dialog._.position.y );
}
}
}
var resizeCover;
// Caching resuable covers and allowing only one cover
// on screen.
var covers = {},
currentCover;
function showCover( editor )
{
var win = CKEDITOR.document.getWindow();
var config = editor.config,
backgroundColorStyle = config.dialog_backgroundCoverColor || 'white',
backgroundCoverOpacity = config.dialog_backgroundCoverOpacity,
baseFloatZIndex = config.baseFloatZIndex,
coverKey = CKEDITOR.tools.genKey(
backgroundColorStyle,
backgroundCoverOpacity,
baseFloatZIndex ),
coverElement = covers[ coverKey ];
if ( !coverElement )
{
var html = [
'<div style="position: ', ( CKEDITOR.env.ie6Compat ? 'absolute' : 'fixed' ),
'; z-index: ', baseFloatZIndex,
'; top: 0px; left: 0px; ',
( !CKEDITOR.env.ie6Compat ? 'background-color: ' + backgroundColorStyle : '' ),
'" class="cke_dialog_background_cover">'
];
if ( CKEDITOR.env.ie6Compat )
{
// Support for custom document.domain in IE.
var isCustomDomain = CKEDITOR.env.isCustomDomain(),
iframeHtml = '<html><body style=\\\'background-color:' + backgroundColorStyle + ';\\\'></body></html>';
html.push(
'<iframe' +
' hidefocus="true"' +
' frameborder="0"' +
' id="cke_dialog_background_iframe"' +
' src="javascript:' );
html.push( 'void((function(){' +
'document.open();' +
( isCustomDomain ? 'document.domain=\'' + document.domain + '\';' : '' ) +
'document.write( \'' + iframeHtml + '\' );' +
'document.close();' +
'})())' );
html.push(
'"' +
' style="' +
'position:absolute;' +
'left:0;' +
'top:0;' +
'width:100%;' +
'height: 100%;' +
'progid:DXImageTransform.Microsoft.Alpha(opacity=0)">' +
'</iframe>' );
}
html.push( '</div>' );
coverElement = CKEDITOR.dom.element.createFromHtml( html.join( '' ) );
coverElement.setOpacity( backgroundCoverOpacity != undefined ? backgroundCoverOpacity : 0.5 );
coverElement.appendTo( CKEDITOR.document.getBody() );
covers[ coverKey ] = coverElement;
}
else
coverElement. show();
currentCover = coverElement;
var resizeFunc = function()
{
var size = win.getViewPaneSize();
coverElement.setStyles(
{
width : size.width + 'px',
height : size.height + 'px'
} );
};
var scrollFunc = function()
{
var pos = win.getScrollPosition(),
cursor = CKEDITOR.dialog._.currentTop;
coverElement.setStyles(
{
left : pos.x + 'px',
top : pos.y + 'px'
});
do
{
var dialogPos = cursor.getPosition();
cursor.move( dialogPos.x, dialogPos.y );
} while ( ( cursor = cursor._.parentDialog ) );
};
resizeCover = resizeFunc;
win.on( 'resize', resizeFunc );
resizeFunc();
if ( CKEDITOR.env.ie6Compat )
{
// IE BUG: win.$.onscroll assignment doesn't work.. it must be window.onscroll.
// So we need to invent a really funny way to make it work.
var myScrollHandler = function()
{
scrollFunc();
arguments.callee.prevScrollHandler.apply( this, arguments );
};
win.$.setTimeout( function()
{
myScrollHandler.prevScrollHandler = window.onscroll || function(){};
window.onscroll = myScrollHandler;
}, 0 );
scrollFunc();
}
}
function hideCover()
{
if ( !currentCover )
return;
var win = CKEDITOR.document.getWindow();
currentCover.hide();
win.removeListener( 'resize', resizeCover );
if ( CKEDITOR.env.ie6Compat )
{
win.$.setTimeout( function()
{
var prevScrollHandler = window.onscroll && window.onscroll.prevScrollHandler;
window.onscroll = prevScrollHandler || null;
}, 0 );
}
resizeCover = null;
}
function removeCovers()
{
for ( var coverId in covers )
covers[ coverId ].remove();
covers = {};
}
var accessKeyProcessors = {};
var accessKeyDownHandler = function( evt )
{
var ctrl = evt.data.$.ctrlKey || evt.data.$.metaKey,
alt = evt.data.$.altKey,
shift = evt.data.$.shiftKey,
key = String.fromCharCode( evt.data.$.keyCode ),
keyProcessor = accessKeyProcessors[( ctrl ? 'CTRL+' : '' ) + ( alt ? 'ALT+' : '') + ( shift ? 'SHIFT+' : '' ) + key];
if ( !keyProcessor || !keyProcessor.length )
return;
keyProcessor = keyProcessor[keyProcessor.length - 1];
keyProcessor.keydown && keyProcessor.keydown.call( keyProcessor.uiElement, keyProcessor.dialog, keyProcessor.key );
evt.data.preventDefault();
};
var accessKeyUpHandler = function( evt )
{
var ctrl = evt.data.$.ctrlKey || evt.data.$.metaKey,
alt = evt.data.$.altKey,
shift = evt.data.$.shiftKey,
key = String.fromCharCode( evt.data.$.keyCode ),
keyProcessor = accessKeyProcessors[( ctrl ? 'CTRL+' : '' ) + ( alt ? 'ALT+' : '') + ( shift ? 'SHIFT+' : '' ) + key];
if ( !keyProcessor || !keyProcessor.length )
return;
keyProcessor = keyProcessor[keyProcessor.length - 1];
if ( keyProcessor.keyup )
{
keyProcessor.keyup.call( keyProcessor.uiElement, keyProcessor.dialog, keyProcessor.key );
evt.data.preventDefault();
}
};
var registerAccessKey = function( uiElement, dialog, key, downFunc, upFunc )
{
var procList = accessKeyProcessors[key] || ( accessKeyProcessors[key] = [] );
procList.push( {
uiElement : uiElement,
dialog : dialog,
key : key,
keyup : upFunc || uiElement.accessKeyUp,
keydown : downFunc || uiElement.accessKeyDown
} );
};
var unregisterAccessKey = function( obj )
{
for ( var i in accessKeyProcessors )
{
var list = accessKeyProcessors[i];
for ( var j = list.length - 1 ; j >= 0 ; j-- )
{
if ( list[j].dialog == obj || list[j].uiElement == obj )
list.splice( j, 1 );
}
if ( list.length === 0 )
delete accessKeyProcessors[i];
}
};
var tabAccessKeyUp = function( dialog, key )
{
if ( dialog._.accessKeyMap[key] )
dialog.selectPage( dialog._.accessKeyMap[key] );
};
var tabAccessKeyDown = function( dialog, key )
{
};
// ESC, ENTER
var preventKeyBubblingKeys = { 27 :1, 13 :1 };
var preventKeyBubbling = function( e )
{
if ( e.data.getKeystroke() in preventKeyBubblingKeys )
e.data.stopPropagation();
};
(function()
{
CKEDITOR.ui.dialog =
{
/**
* The base class of all dialog UI elements.
* @constructor
* @param {CKEDITOR.dialog} dialog Parent dialog object.
* @param {CKEDITOR.dialog.uiElementDefinition} elementDefinition Element
* definition. Accepted fields:
* <ul>
* <li><strong>id</strong> (Required) The id of the UI element. See {@link
* CKEDITOR.dialog#getContentElement}</li>
* <li><strong>type</strong> (Required) The type of the UI element. The
* value to this field specifies which UI element class will be used to
* generate the final widget.</li>
* <li><strong>title</strong> (Optional) The popup tooltip for the UI
* element.</li>
* <li><strong>hidden</strong> (Optional) A flag that tells if the element
* should be initially visible.</li>
* <li><strong>className</strong> (Optional) Additional CSS class names
* to add to the UI element. Separated by space.</li>
* <li><strong>style</strong> (Optional) Additional CSS inline styles
* to add to the UI element. A semicolon (;) is required after the last
* style declaration.</li>
* <li><strong>accessKey</strong> (Optional) The alphanumeric access key
* for this element. Access keys are automatically prefixed by CTRL.</li>
* <li><strong>on*</strong> (Optional) Any UI element definition field that
* starts with <em>on</em> followed immediately by a capital letter and
* probably more letters is an event handler. Event handlers may be further
* divided into registered event handlers and DOM event handlers. Please
* refer to {@link CKEDITOR.ui.dialog.uiElement#registerEvents} and
* {@link CKEDITOR.ui.dialog.uiElement#eventProcessors} for more
* information.</li>
* </ul>
* @param {Array} htmlList
* List of HTML code to be added to the dialog's content area.
* @param {Function|String} nodeNameArg
* A function returning a string, or a simple string for the node name for
* the root DOM node. Default is 'div'.
* @param {Function|Object} stylesArg
* A function returning an object, or a simple object for CSS styles applied
* to the DOM node. Default is empty object.
* @param {Function|Object} attributesArg
* A fucntion returning an object, or a simple object for attributes applied
* to the DOM node. Default is empty object.
* @param {Function|String} contentsArg
* A function returning a string, or a simple string for the HTML code inside
* the root DOM node. Default is empty string.
* @example
*/
uiElement : function( dialog, elementDefinition, htmlList, nodeNameArg, stylesArg, attributesArg, contentsArg )
{
if ( arguments.length < 4 )
return;
var nodeName = ( nodeNameArg.call ? nodeNameArg( elementDefinition ) : nodeNameArg ) || 'div',
html = [ '<', nodeName, ' ' ],
styles = ( stylesArg && stylesArg.call ? stylesArg( elementDefinition ) : stylesArg ) || {},
attributes = ( attributesArg && attributesArg.call ? attributesArg( elementDefinition ) : attributesArg ) || {},
innerHTML = ( contentsArg && contentsArg.call ? contentsArg.call( this, dialog, elementDefinition ) : contentsArg ) || '',
domId = this.domId = attributes.id || CKEDITOR.tools.getNextId() + '_uiElement',
id = this.id = elementDefinition.id,
i;
// Set the id, a unique id is required for getElement() to work.
attributes.id = domId;
// Set the type and definition CSS class names.
var classes = {};
if ( elementDefinition.type )
classes[ 'cke_dialog_ui_' + elementDefinition.type ] = 1;
if ( elementDefinition.className )
classes[ elementDefinition.className ] = 1;
var attributeClasses = ( attributes['class'] && attributes['class'].split ) ? attributes['class'].split( ' ' ) : [];
for ( i = 0 ; i < attributeClasses.length ; i++ )
{
if ( attributeClasses[i] )
classes[ attributeClasses[i] ] = 1;
}
var finalClasses = [];
for ( i in classes )
finalClasses.push( i );
attributes['class'] = finalClasses.join( ' ' );
// Set the popup tooltop.
if ( elementDefinition.title )
attributes.title = elementDefinition.title;
// Write the inline CSS styles.
var styleStr = ( elementDefinition.style || '' ).split( ';' );
for ( i in styles )
styleStr.push( i + ':' + styles[i] );
if ( elementDefinition.hidden )
styleStr.push( 'display:none' );
for ( i = styleStr.length - 1 ; i >= 0 ; i-- )
{
if ( styleStr[i] === '' )
styleStr.splice( i, 1 );
}
if ( styleStr.length > 0 )
attributes.style = ( attributes.style ? ( attributes.style + '; ' ) : '' ) + styleStr.join( '; ' );
// Write the attributes.
for ( i in attributes )
html.push( i + '="' + CKEDITOR.tools.htmlEncode( attributes[i] ) + '" ');
// Write the content HTML.
html.push( '>', innerHTML, '</', nodeName, '>' );
// Add contents to the parent HTML array.
htmlList.push( html.join( '' ) );
( this._ || ( this._ = {} ) ).dialog = dialog;
// Override isChanged if it is defined in element definition.
if ( typeof( elementDefinition.isChanged ) == 'boolean' )
this.isChanged = function(){ return elementDefinition.isChanged; };
if ( typeof( elementDefinition.isChanged ) == 'function' )
this.isChanged = elementDefinition.isChanged;
// Add events.
CKEDITOR.event.implementOn( this );
this.registerEvents( elementDefinition );
if ( this.accessKeyUp && this.accessKeyDown && elementDefinition.accessKey )
registerAccessKey( this, dialog, 'CTRL+' + elementDefinition.accessKey );
var me = this;
dialog.on( 'load', function()
{
if ( me.getInputElement() )
{
me.getInputElement().on( 'focus', function()
{
dialog._.tabBarMode = false;
dialog._.hasFocus = true;
me.fire( 'focus' );
}, me );
}
} );
// Register the object as a tab focus if it can be included.
if ( this.keyboardFocusable )
{
this.tabIndex = elementDefinition.tabIndex || 0;
this.focusIndex = dialog._.focusList.push( this ) - 1;
this.on( 'focus', function()
{
dialog._.currentFocusIndex = me.focusIndex;
} );
}
// Completes this object with everything we have in the
// definition.
CKEDITOR.tools.extend( this, elementDefinition );
},
/**
* Horizontal layout box for dialog UI elements, auto-expends to available width of container.
* @constructor
* @extends CKEDITOR.ui.dialog.uiElement
* @param {CKEDITOR.dialog} dialog
* Parent dialog object.
* @param {Array} childObjList
* Array of {@link CKEDITOR.ui.dialog.uiElement} objects inside this
* container.
* @param {Array} childHtmlList
* Array of HTML code that correspond to the HTML output of all the
* objects in childObjList.
* @param {Array} htmlList
* Array of HTML code that this element will output to.
* @param {CKEDITOR.dialog.uiElementDefinition} elementDefinition
* The element definition. Accepted fields:
* <ul>
* <li><strong>widths</strong> (Optional) The widths of child cells.</li>
* <li><strong>height</strong> (Optional) The height of the layout.</li>
* <li><strong>padding</strong> (Optional) The padding width inside child
* cells.</li>
* <li><strong>align</strong> (Optional) The alignment of the whole layout
* </li>
* </ul>
* @example
*/
hbox : function( dialog, childObjList, childHtmlList, htmlList, elementDefinition )
{
if ( arguments.length < 4 )
return;
this._ || ( this._ = {} );
var children = this._.children = childObjList,
widths = elementDefinition && elementDefinition.widths || null,
height = elementDefinition && elementDefinition.height || null,
styles = {},
i;
/** @ignore */
var innerHTML = function()
{
var html = [ '<tbody><tr class="cke_dialog_ui_hbox">' ];
for ( i = 0 ; i < childHtmlList.length ; i++ )
{
var className = 'cke_dialog_ui_hbox_child',
styles = [];
if ( i === 0 )
className = 'cke_dialog_ui_hbox_first';
if ( i == childHtmlList.length - 1 )
className = 'cke_dialog_ui_hbox_last';
html.push( '<td class="', className, '" role="presentation" ' );
if ( widths )
{
if ( widths[i] )
styles.push( 'width:' + cssLength( widths[i] ) );
}
else
styles.push( 'width:' + Math.floor( 100 / childHtmlList.length ) + '%' );
if ( height )
styles.push( 'height:' + cssLength( height ) );
if ( elementDefinition && elementDefinition.padding != undefined )
styles.push( 'padding:' + cssLength( elementDefinition.padding ) );
if ( styles.length > 0 )
html.push( 'style="' + styles.join('; ') + '" ' );
html.push( '>', childHtmlList[i], '</td>' );
}
html.push( '</tr></tbody>' );
return html.join( '' );
};
var attribs = { role : 'presentation' };
elementDefinition && elementDefinition.align && ( attribs.align = elementDefinition.align );
CKEDITOR.ui.dialog.uiElement.call(
this,
dialog,
elementDefinition || { type : 'hbox' },
htmlList,
'table',
styles,
attribs,
innerHTML );
},
/**
* Vertical layout box for dialog UI elements.
* @constructor
* @extends CKEDITOR.ui.dialog.hbox
* @param {CKEDITOR.dialog} dialog
* Parent dialog object.
* @param {Array} childObjList
* Array of {@link CKEDITOR.ui.dialog.uiElement} objects inside this
* container.
* @param {Array} childHtmlList
* Array of HTML code that correspond to the HTML output of all the
* objects in childObjList.
* @param {Array} htmlList
* Array of HTML code that this element will output to.
* @param {CKEDITOR.dialog.uiElementDefinition} elementDefinition
* The element definition. Accepted fields:
* <ul>
* <li><strong>width</strong> (Optional) The width of the layout.</li>
* <li><strong>heights</strong> (Optional) The heights of individual cells.
* </li>
* <li><strong>align</strong> (Optional) The alignment of the layout.</li>
* <li><strong>padding</strong> (Optional) The padding width inside child
* cells.</li>
* <li><strong>expand</strong> (Optional) Whether the layout should expand
* vertically to fill its container.</li>
* </ul>
* @example
*/
vbox : function( dialog, childObjList, childHtmlList, htmlList, elementDefinition )
{
if ( arguments.length < 3 )
return;
this._ || ( this._ = {} );
var children = this._.children = childObjList,
width = elementDefinition && elementDefinition.width || null,
heights = elementDefinition && elementDefinition.heights || null;
/** @ignore */
var innerHTML = function()
{
var html = [ '<table role="presentation" cellspacing="0" border="0" ' ];
html.push( 'style="' );
if ( elementDefinition && elementDefinition.expand )
html.push( 'height:100%;' );
html.push( 'width:' + cssLength( width || '100%' ), ';' );
html.push( '"' );
html.push( 'align="', CKEDITOR.tools.htmlEncode(
( elementDefinition && elementDefinition.align ) || ( dialog.getParentEditor().lang.dir == 'ltr' ? 'left' : 'right' ) ), '" ' );
html.push( '><tbody>' );
for ( var i = 0 ; i < childHtmlList.length ; i++ )
{
var styles = [];
html.push( '<tr><td role="presentation" ' );
if ( width )
styles.push( 'width:' + cssLength( width || '100%' ) );
if ( heights )
styles.push( 'height:' + cssLength( heights[i] ) );
else if ( elementDefinition && elementDefinition.expand )
styles.push( 'height:' + Math.floor( 100 / childHtmlList.length ) + '%' );
if ( elementDefinition && elementDefinition.padding != undefined )
styles.push( 'padding:' + cssLength( elementDefinition.padding ) );
if ( styles.length > 0 )
html.push( 'style="', styles.join( '; ' ), '" ' );
html.push( ' class="cke_dialog_ui_vbox_child">', childHtmlList[i], '</td></tr>' );
}
html.push( '</tbody></table>' );
return html.join( '' );
};
CKEDITOR.ui.dialog.uiElement.call( this, dialog, elementDefinition || { type : 'vbox' }, htmlList, 'div', null, { role : 'presentation' }, innerHTML );
}
};
})();
CKEDITOR.ui.dialog.uiElement.prototype =
{
/**
* Gets the root DOM element of this dialog UI object.
* @returns {CKEDITOR.dom.element} Root DOM element of UI object.
* @example
* uiElement.getElement().hide();
*/
getElement : function()
{
return CKEDITOR.document.getById( this.domId );
},
/**
* Gets the DOM element that the user inputs values.
* This function is used by setValue(), getValue() and focus(). It should
* be overrided in child classes where the input element isn't the root
* element.
* @returns {CKEDITOR.dom.element} The element where the user input values.
* @example
* var rawValue = textInput.getInputElement().$.value;
*/
getInputElement : function()
{
return this.getElement();
},
/**
* Gets the parent dialog object containing this UI element.
* @returns {CKEDITOR.dialog} Parent dialog object.
* @example
* var dialog = uiElement.getDialog();
*/
getDialog : function()
{
return this._.dialog;
},
/**
* Sets the value of this dialog UI object.
* @param {Object} value The new value.
* @param {Boolean} noChangeEvent Internal commit, to supress 'change' event on this element.
* @returns {CKEDITOR.dialog.uiElement} The current UI element.
* @example
* uiElement.setValue( 'Dingo' );
*/
setValue : function( value, noChangeEvent )
{
this.getInputElement().setValue( value );
!noChangeEvent && this.fire( 'change', { value : value } );
return this;
},
/**
* Gets the current value of this dialog UI object.
* @returns {Object} The current value.
* @example
* var myValue = uiElement.getValue();
*/
getValue : function()
{
return this.getInputElement().getValue();
},
/**
* Tells whether the UI object's value has changed.
* @returns {Boolean} true if changed, false if not changed.
* @example
* if ( uiElement.isChanged() )
* confirm( 'Value changed! Continue?' );
*/
isChanged : function()
{
// Override in input classes.
return false;
},
/**
* Selects the parent tab of this element. Usually called by focus() or overridden focus() methods.
* @returns {CKEDITOR.dialog.uiElement} The current UI element.
* @example
* focus : function()
* {
* this.selectParentTab();
* // do something else.
* }
*/
selectParentTab : function()
{
var element = this.getInputElement(),
cursor = element,
tabId;
while ( ( cursor = cursor.getParent() ) && cursor.$.className.search( 'cke_dialog_page_contents' ) == -1 )
{ /*jsl:pass*/ }
// Some widgets don't have parent tabs (e.g. OK and Cancel buttons).
if ( !cursor )
return this;
tabId = cursor.getAttribute( 'name' );
// Avoid duplicate select.
if ( this._.dialog._.currentTabId != tabId )
this._.dialog.selectPage( tabId );
return this;
},
/**
* Puts the focus to the UI object. Switches tabs if the UI object isn't in the active tab page.
* @returns {CKEDITOR.dialog.uiElement} The current UI element.
* @example
* uiElement.focus();
*/
focus : function()
{
this.selectParentTab().getInputElement().focus();
return this;
},
/**
* Registers the on* event handlers defined in the element definition.
* The default behavior of this function is:
* <ol>
* <li>
* If the on* event is defined in the class's eventProcesors list,
* then the registration is delegated to the corresponding function
* in the eventProcessors list.
* </li>
* <li>
* If the on* event is not defined in the eventProcessors list, then
* register the event handler under the corresponding DOM event of
* the UI element's input DOM element (as defined by the return value
* of {@link CKEDITOR.ui.dialog.uiElement#getInputElement}).
* </li>
* </ol>
* This function is only called at UI element instantiation, but can
* be overridded in child classes if they require more flexibility.
* @param {CKEDITOR.dialog.uiElementDefinition} definition The UI element
* definition.
* @returns {CKEDITOR.dialog.uiElement} The current UI element.
* @example
*/
registerEvents : function( definition )
{
var regex = /^on([A-Z]\w+)/,
match;
var registerDomEvent = function( uiElement, dialog, eventName, func )
{
dialog.on( 'load', function()
{
uiElement.getInputElement().on( eventName, func, uiElement );
});
};
for ( var i in definition )
{
if ( !( match = i.match( regex ) ) )
continue;
if ( this.eventProcessors[i] )
this.eventProcessors[i].call( this, this._.dialog, definition[i] );
else
registerDomEvent( this, this._.dialog, match[1].toLowerCase(), definition[i] );
}
return this;
},
/**
* The event processor list used by
* {@link CKEDITOR.ui.dialog.uiElement#getInputElement} at UI element
* instantiation. The default list defines three on* events:
* <ol>
* <li>onLoad - Called when the element's parent dialog opens for the
* first time</li>
* <li>onShow - Called whenever the element's parent dialog opens.</li>
* <li>onHide - Called whenever the element's parent dialog closes.</li>
* </ol>
* @field
* @type Object
* @example
* // This connects the 'click' event in CKEDITOR.ui.dialog.button to onClick
* // handlers in the UI element's definitions.
* CKEDITOR.ui.dialog.button.eventProcessors = CKEDITOR.tools.extend( {},
* CKEDITOR.ui.dialog.uiElement.prototype.eventProcessors,
* { onClick : function( dialog, func ) { this.on( 'click', func ); } },
* true );
*/
eventProcessors :
{
onLoad : function( dialog, func )
{
dialog.on( 'load', func, this );
},
onShow : function( dialog, func )
{
dialog.on( 'show', func, this );
},
onHide : function( dialog, func )
{
dialog.on( 'hide', func, this );
}
},
/**
* The default handler for a UI element's access key down event, which
* tries to put focus to the UI element.<br />
* Can be overridded in child classes for more sophisticaed behavior.
* @param {CKEDITOR.dialog} dialog The parent dialog object.
* @param {String} key The key combination pressed. Since access keys
* are defined to always include the CTRL key, its value should always
* include a 'CTRL+' prefix.
* @example
*/
accessKeyDown : function( dialog, key )
{
this.focus();
},
/**
* The default handler for a UI element's access key up event, which
* does nothing.<br />
* Can be overridded in child classes for more sophisticated behavior.
* @param {CKEDITOR.dialog} dialog The parent dialog object.
* @param {String} key The key combination pressed. Since access keys
* are defined to always include the CTRL key, its value should always
* include a 'CTRL+' prefix.
* @example
*/
accessKeyUp : function( dialog, key )
{
},
/**
* Disables a UI element.
* @example
*/
disable : function()
{
var element = this.getInputElement();
element.setAttribute( 'disabled', 'true' );
element.addClass( 'cke_disabled' );
},
/**
* Enables a UI element.
* @example
*/
enable : function()
{
var element = this.getInputElement();
element.removeAttribute( 'disabled' );
element.removeClass( 'cke_disabled' );
},
/**
* Determines whether an UI element is enabled or not.
* @returns {Boolean} Whether the UI element is enabled.
* @example
*/
isEnabled : function()
{
return !this.getInputElement().getAttribute( 'disabled' );
},
/**
* Determines whether an UI element is visible or not.
* @returns {Boolean} Whether the UI element is visible.
* @example
*/
isVisible : function()
{
return this.getInputElement().isVisible();
},
/**
* Determines whether an UI element is focus-able or not.
* Focus-able is defined as being both visible and enabled.
* @returns {Boolean} Whether the UI element can be focused.
* @example
*/
isFocusable : function()
{
if ( !this.isEnabled() || !this.isVisible() )
return false;
return true;
}
};
CKEDITOR.ui.dialog.hbox.prototype = CKEDITOR.tools.extend( new CKEDITOR.ui.dialog.uiElement,
/**
* @lends CKEDITOR.ui.dialog.hbox.prototype
*/
{
/**
* Gets a child UI element inside this container.
* @param {Array|Number} indices An array or a single number to indicate the child's
* position in the container's descendant tree. Omit to get all the children in an array.
* @returns {Array|CKEDITOR.ui.dialog.uiElement} Array of all UI elements in the container
* if no argument given, or the specified UI element if indices is given.
* @example
* var checkbox = hbox.getChild( [0,1] );
* checkbox.setValue( true );
*/
getChild : function( indices )
{
// If no arguments, return a clone of the children array.
if ( arguments.length < 1 )
return this._.children.concat();
// If indices isn't array, make it one.
if ( !indices.splice )
indices = [ indices ];
// Retrieve the child element according to tree position.
if ( indices.length < 2 )
return this._.children[ indices[0] ];
else
return ( this._.children[ indices[0] ] && this._.children[ indices[0] ].getChild ) ?
this._.children[ indices[0] ].getChild( indices.slice( 1, indices.length ) ) :
null;
}
}, true );
CKEDITOR.ui.dialog.vbox.prototype = new CKEDITOR.ui.dialog.hbox();
(function()
{
var commonBuilder = {
build : function( dialog, elementDefinition, output )
{
var children = elementDefinition.children,
child,
childHtmlList = [],
childObjList = [];
for ( var i = 0 ; ( i < children.length && ( child = children[i] ) ) ; i++ )
{
var childHtml = [];
childHtmlList.push( childHtml );
childObjList.push( CKEDITOR.dialog._.uiElementBuilders[ child.type ].build( dialog, child, childHtml ) );
}
return new CKEDITOR.ui.dialog[elementDefinition.type]( dialog, childObjList, childHtmlList, output, elementDefinition );
}
};
CKEDITOR.dialog.addUIElement( 'hbox', commonBuilder );
CKEDITOR.dialog.addUIElement( 'vbox', commonBuilder );
})();
/**
* Generic dialog command. It opens a specific dialog when executed.
* @constructor
* @augments CKEDITOR.commandDefinition
* @param {string} dialogName The name of the dialog to open when executing
* this command.
* @example
* // Register the "link" command, which opens the "link" dialog.
* editor.addCommand( 'link', <b>new CKEDITOR.dialogCommand( 'link' )</b> );
*/
CKEDITOR.dialogCommand = function( dialogName )
{
this.dialogName = dialogName;
};
CKEDITOR.dialogCommand.prototype =
{
/** @ignore */
exec : function( editor )
{
editor.openDialog( this.dialogName );
},
// Dialog commands just open a dialog ui, thus require no undo logic,
// undo support should dedicate to specific dialog implementation.
canUndo: false,
editorFocus : CKEDITOR.env.ie || CKEDITOR.env.webkit
};
(function()
{
var notEmptyRegex = /^([a]|[^a])+$/,
integerRegex = /^\d*$/,
numberRegex = /^\d*(?:\.\d+)?$/;
CKEDITOR.VALIDATE_OR = 1;
CKEDITOR.VALIDATE_AND = 2;
CKEDITOR.dialog.validate =
{
functions : function()
{
return function()
{
/**
* It's important for validate functions to be able to accept the value
* as argument in addition to this.getValue(), so that it is possible to
* combine validate functions together to make more sophisticated
* validators.
*/
var value = this && this.getValue ? this.getValue() : arguments[0];
var msg = undefined,
relation = CKEDITOR.VALIDATE_AND,
functions = [], i;
for ( i = 0 ; i < arguments.length ; i++ )
{
if ( typeof( arguments[i] ) == 'function' )
functions.push( arguments[i] );
else
break;
}
if ( i < arguments.length && typeof( arguments[i] ) == 'string' )
{
msg = arguments[i];
i++;
}
if ( i < arguments.length && typeof( arguments[i]) == 'number' )
relation = arguments[i];
var passed = ( relation == CKEDITOR.VALIDATE_AND ? true : false );
for ( i = 0 ; i < functions.length ; i++ )
{
if ( relation == CKEDITOR.VALIDATE_AND )
passed = passed && functions[i]( value );
else
passed = passed || functions[i]( value );
}
if ( !passed )
{
if ( msg !== undefined )
alert( msg );
if ( this && ( this.select || this.focus ) )
( this.select || this.focus )();
return false;
}
return true;
};
},
regex : function( regex, msg )
{
/*
* Can be greatly shortened by deriving from functions validator if code size
* turns out to be more important than performance.
*/
return function()
{
var value = this && this.getValue ? this.getValue() : arguments[0];
if ( !regex.test( value ) )
{
if ( msg !== undefined )
alert( msg );
if ( this && ( this.select || this.focus ) )
{
if ( this.select )
this.select();
else
this.focus();
}
return false;
}
return true;
};
},
notEmpty : function( msg )
{
return this.regex( notEmptyRegex, msg );
},
integer : function( msg )
{
return this.regex( integerRegex, msg );
},
'number' : function( msg )
{
return this.regex( numberRegex, msg );
},
equals : function( value, msg )
{
return this.functions( function( val ){ return val == value; }, msg );
},
notEqual : function( value, msg )
{
return this.functions( function( val ){ return val != value; }, msg );
}
};
CKEDITOR.on( 'instanceDestroyed', function( evt )
{
// Remove dialog cover on last instance destroy.
if ( CKEDITOR.tools.isEmpty( CKEDITOR.instances ) )
{
var currentTopDialog;
while ( ( currentTopDialog = CKEDITOR.dialog._.currentTop ) )
currentTopDialog.hide();
removeCovers();
}
var dialogs = evt.editor._.storedDialogs;
for ( var name in dialogs )
dialogs[ name ].destroy();
});
})();
})();
// Extend the CKEDITOR.editor class with dialog specific functions.
CKEDITOR.tools.extend( CKEDITOR.editor.prototype,
/** @lends CKEDITOR.editor.prototype */
{
/**
* Loads and opens a registered dialog.
* @param {String} dialogName The registered name of the dialog.
* @param {Function} callback The function to be invoked after dialog instance created.
* @see CKEDITOR.dialog.add
* @example
* CKEDITOR.instances.editor1.openDialog( 'smiley' );
* @returns {CKEDITOR.dialog} The dialog object corresponding to the dialog displayed. null if the dialog name is not registered.
*/
openDialog : function( dialogName, callback )
{
var dialogDefinitions = CKEDITOR.dialog._.dialogDefinitions[ dialogName ],
dialogSkin = this.skin.dialog;
// If the dialogDefinition is already loaded, open it immediately.
if ( typeof dialogDefinitions == 'function' && dialogSkin._isLoaded )
{
var storedDialogs = this._.storedDialogs ||
( this._.storedDialogs = {} );
var dialog = storedDialogs[ dialogName ] ||
( storedDialogs[ dialogName ] = new CKEDITOR.dialog( this, dialogName ) );
callback && callback.call( dialog, dialog );
dialog.show();
return dialog;
}
else if ( dialogDefinitions == 'failed' )
throw new Error( '[CKEDITOR.dialog.openDialog] Dialog "' + dialogName + '" failed when loading definition.' );
// Not loaded? Load the .js file first.
var body = CKEDITOR.document.getBody(),
cursor = body.$.style.cursor,
me = this;
body.setStyle( 'cursor', 'wait' );
function onDialogFileLoaded( success )
{
var dialogDefinition = CKEDITOR.dialog._.dialogDefinitions[ dialogName ],
skin = me.skin.dialog;
// Check if both skin part and definition is loaded.
if ( !skin._isLoaded || loadDefinition && typeof success == 'undefined' )
return;
// In case of plugin error, mark it as loading failed.
if ( typeof dialogDefinition != 'function' )
CKEDITOR.dialog._.dialogDefinitions[ dialogName ] = 'failed';
me.openDialog( dialogName, callback );
body.setStyle( 'cursor', cursor );
}
if ( typeof dialogDefinitions == 'string' )
{
var loadDefinition = 1;
CKEDITOR.scriptLoader.load( CKEDITOR.getUrl( dialogDefinitions ), onDialogFileLoaded );
}
CKEDITOR.skins.load( this, 'dialog', onDialogFileLoaded );
return null;
}
});
CKEDITOR.plugins.add( 'dialog',
{
requires : [ 'dialogui' ]
});
// Dialog related configurations.
/**
* The color of the dialog background cover. It should be a valid CSS color
* string.
* @name CKEDITOR.config.dialog_backgroundCoverColor
* @type String
* @default 'white'
* @example
* config.dialog_backgroundCoverColor = 'rgb(255, 254, 253)';
*/
/**
* The opacity of the dialog background cover. It should be a number within the
* range [0.0, 1.0].
* @name CKEDITOR.config.dialog_backgroundCoverOpacity
* @type Number
* @default 0.5
* @example
* config.dialog_backgroundCoverOpacity = 0.7;
*/
/**
* If the dialog has more than one tab, put focus into the first tab as soon as dialog is opened.
* @name CKEDITOR.config.dialog_startupFocusTab
* @type Boolean
* @default false
* @example
* config.dialog_startupFocusTab = true;
*/
/**
* The distance of magnetic borders used in moving and resizing dialogs,
* measured in pixels.
* @name CKEDITOR.config.dialog_magnetDistance
* @type Number
* @default 20
* @example
* config.dialog_magnetDistance = 30;
*/
/**
* The guildeline to follow when generating the dialog buttons. There are 3 possible options:
* <ul>
* <li>'OS' - the buttons will be displayed in the default order of the user's OS;</li>
* <li>'ltr' - for Left-To-Right order;</li>
* <li>'rtl' - for Right-To-Left order.</li>
* </ul>
* @name CKEDITOR.config.dialog_buttonsOrder
* @type String
* @default 'OS'
* @since 3.5
* @example
* config.dialog_buttonsOrder = 'rtl';
*/
/**
* The dialog contents to removed. It's a string composed by dialog name and tab name with a colon between them.
* Separate each pair with semicolon (see example).
* <b>Note: All names are case-sensitive.</b>
* <b>Note: Be cautious when specifying dialog tabs that are mandatory, like "info", dialog functionality might be broken because of this!<b>
* @name CKEDITOR.config.removeDialogTabs
* @type String
* @since 3.5
* @default ''
* @example
* config.removeDialogTabs = 'flash:advanced;image:Link';
*/
/**
* Fired when a dialog definition is about to be used to create a dialog into
* an editor instance. This event makes it possible to customize the definition
* before creating it.
* <p>Note that this event is called only the first time a specific dialog is
* opened. Successive openings will use the cached dialog, and this event will
* not get fired.</p>
* @name CKEDITOR#dialogDefinition
* @event
* @param {CKEDITOR.dialog.dialogDefinition} data The dialog defination that
* is being loaded.
* @param {CKEDITOR.editor} editor The editor instance that will use the
* dialog.
*/
/**
* Fired when a tab is going to be selected in a dialog
* @name dialog#selectPage
* @event
* @param String page The id of the page that it's gonna be selected.
* @param String currentPage The id of the current page.
*/
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @fileOverview The "showblocks" plugin. Enable it will make all block level
* elements being decorated with a border and the element name
* displayed on the left-right corner.
*/
(function()
{
var cssTemplate = '.%2 p,'+
'.%2 div,'+
'.%2 pre,'+
'.%2 address,'+
'.%2 blockquote,'+
'.%2 h1,'+
'.%2 h2,'+
'.%2 h3,'+
'.%2 h4,'+
'.%2 h5,'+
'.%2 h6'+
'{'+
'background-repeat: no-repeat;'+
'background-position: top %3;'+
'border: 1px dotted gray;'+
'padding-top: 8px;'+
'padding-%3: 8px;'+
'}'+
'.%2 p'+
'{'+
'%1p.png);'+
'}'+
'.%2 div'+
'{'+
'%1div.png);'+
'}'+
'.%2 pre'+
'{'+
'%1pre.png);'+
'}'+
'.%2 address'+
'{'+
'%1address.png);'+
'}'+
'.%2 blockquote'+
'{'+
'%1blockquote.png);'+
'}'+
'.%2 h1'+
'{'+
'%1h1.png);'+
'}'+
'.%2 h2'+
'{'+
'%1h2.png);'+
'}'+
'.%2 h3'+
'{'+
'%1h3.png);'+
'}'+
'.%2 h4'+
'{'+
'%1h4.png);'+
'}'+
'.%2 h5'+
'{'+
'%1h5.png);'+
'}'+
'.%2 h6'+
'{'+
'%1h6.png);'+
'}';
var cssTemplateRegex = /%1/g, cssClassRegex = /%2/g, backgroundPositionRegex = /%3/g;
var commandDefinition =
{
preserveState : true,
editorFocus : false,
exec : function ( editor )
{
this.toggleState();
this.refresh( editor );
},
refresh : function( editor )
{
var funcName = ( this.state == CKEDITOR.TRISTATE_ON ) ? 'addClass' : 'removeClass';
editor.document.getBody()[ funcName ]( 'cke_show_blocks' );
}
};
CKEDITOR.plugins.add( 'showblocks',
{
requires : [ 'wysiwygarea' ],
init : function( editor )
{
var command = editor.addCommand( 'showblocks', commandDefinition );
command.canUndo = false;
if ( editor.config.startupOutlineBlocks )
command.setState( CKEDITOR.TRISTATE_ON );
editor.addCss( cssTemplate
.replace( cssTemplateRegex, 'background-image: url(' + CKEDITOR.getUrl( this.path ) + 'images/block_' )
.replace( cssClassRegex, 'cke_show_blocks ' )
.replace( backgroundPositionRegex, editor.lang.dir == 'rtl' ? 'right' : 'left' ) );
editor.ui.addButton( 'ShowBlocks',
{
label : editor.lang.showBlocks,
command : 'showblocks'
});
// Refresh the command on setData.
editor.on( 'mode', function()
{
if ( command.state != CKEDITOR.TRISTATE_DISABLED )
command.refresh( editor );
});
// Refresh the command on setData.
editor.on( 'contentDom', function()
{
if ( command.state != CKEDITOR.TRISTATE_DISABLED )
command.refresh( editor );
});
}
});
} )();
/**
* Whether to automaticaly enable the "show block" command when the editor
* loads. (StartupShowBlocks in FCKeditor)
* @name CKEDITOR.config.startupOutlineBlocks
* @type Boolean
* @default false
* @example
* config.startupOutlineBlocks = true;
*/
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/** @fileoverview The "dialogui" plugin. */
CKEDITOR.plugins.add( 'dialogui' );
(function()
{
var initPrivateObject = function( elementDefinition )
{
this._ || ( this._ = {} );
this._['default'] = this._.initValue = elementDefinition['default'] || '';
this._.required = elementDefinition[ 'required' ] || false;
var args = [ this._ ];
for ( var i = 1 ; i < arguments.length ; i++ )
args.push( arguments[i] );
args.push( true );
CKEDITOR.tools.extend.apply( CKEDITOR.tools, args );
return this._;
},
textBuilder =
{
build : function( dialog, elementDefinition, output )
{
return new CKEDITOR.ui.dialog.textInput( dialog, elementDefinition, output );
}
},
commonBuilder =
{
build : function( dialog, elementDefinition, output )
{
return new CKEDITOR.ui.dialog[elementDefinition.type]( dialog, elementDefinition, output );
}
},
containerBuilder =
{
build : function( dialog, elementDefinition, output )
{
var children = elementDefinition.children,
child,
childHtmlList = [],
childObjList = [];
for ( var i = 0 ; ( i < children.length && ( child = children[i] ) ) ; i++ )
{
var childHtml = [];
childHtmlList.push( childHtml );
childObjList.push( CKEDITOR.dialog._.uiElementBuilders[ child.type ].build( dialog, child, childHtml ) );
}
return new CKEDITOR.ui.dialog[ elementDefinition.type ]( dialog, childObjList, childHtmlList, output, elementDefinition );
}
},
commonPrototype =
{
isChanged : function()
{
return this.getValue() != this.getInitValue();
},
reset : function( noChangeEvent )
{
this.setValue( this.getInitValue(), noChangeEvent );
},
setInitValue : function()
{
this._.initValue = this.getValue();
},
resetInitValue : function()
{
this._.initValue = this._['default'];
},
getInitValue : function()
{
return this._.initValue;
}
},
commonEventProcessors = CKEDITOR.tools.extend( {}, CKEDITOR.ui.dialog.uiElement.prototype.eventProcessors,
{
onChange : function( dialog, func )
{
if ( !this._.domOnChangeRegistered )
{
dialog.on( 'load', function()
{
this.getInputElement().on( 'change', function()
{
// Make sure 'onchange' doesn't get fired after dialog closed. (#5719)
if ( !dialog.parts.dialog.isVisible() )
return;
this.fire( 'change', { value : this.getValue() } );
}, this );
}, this );
this._.domOnChangeRegistered = true;
}
this.on( 'change', func );
}
}, true ),
eventRegex = /^on([A-Z]\w+)/,
cleanInnerDefinition = function( def )
{
// An inner UI element should not have the parent's type, title or events.
for ( var i in def )
{
if ( eventRegex.test( i ) || i == 'title' || i == 'type' )
delete def[i];
}
return def;
};
CKEDITOR.tools.extend( CKEDITOR.ui.dialog,
/** @lends CKEDITOR.ui.dialog */
{
/**
* Base class for all dialog elements with a textual label on the left.
* @constructor
* @example
* @extends CKEDITOR.ui.dialog.uiElement
* @param {CKEDITOR.dialog} dialog
* Parent dialog object.
* @param {CKEDITOR.dialog.uiElementDefinition} elementDefinition
* The element definition. Accepted fields:
* <ul>
* <li><strong>label</strong> (Required) The label string.</li>
* <li><strong>labelLayout</strong> (Optional) Put 'horizontal' here if the
* label element is to be layed out horizontally. Otherwise a vertical
* layout will be used.</li>
* <li><strong>widths</strong> (Optional) This applies only for horizontal
* layouts - an 2-element array of lengths to specify the widths of the
* label and the content element.</li>
* </ul>
* @param {Array} htmlList
* List of HTML code to output to.
* @param {Function} contentHtml
* A function returning the HTML code string to be added inside the content
* cell.
*/
labeledElement : function( dialog, elementDefinition, htmlList, contentHtml )
{
if ( arguments.length < 4 )
return;
var _ = initPrivateObject.call( this, elementDefinition );
_.labelId = CKEDITOR.tools.getNextId() + '_label';
var children = this._.children = [];
/** @ignore */
var innerHTML = function()
{
var html = [],
requiredClass = elementDefinition.required ? ' cke_required' : '' ;
if ( elementDefinition.labelLayout != 'horizontal' )
html.push( '<label class="cke_dialog_ui_labeled_label' + requiredClass + '" ',
' id="'+ _.labelId + '"',
' for="' + _.inputId + '"',
' style="' + elementDefinition.labelStyle + '">',
elementDefinition.label,
'</label>',
'<div class="cke_dialog_ui_labeled_content" role="presentation">',
contentHtml.call( this, dialog, elementDefinition ),
'</div>' );
else
{
var hboxDefinition = {
type : 'hbox',
widths : elementDefinition.widths,
padding : 0,
children :
[
{
type : 'html',
html : '<label class="cke_dialog_ui_labeled_label' + requiredClass + '"' +
' id="' + _.labelId + '"' +
' for="' + _.inputId + '"' +
' style="' + elementDefinition.labelStyle + '">' +
CKEDITOR.tools.htmlEncode( elementDefinition.label ) +
'</span>'
},
{
type : 'html',
html : '<span class="cke_dialog_ui_labeled_content">' +
contentHtml.call( this, dialog, elementDefinition ) +
'</span>'
}
]
};
CKEDITOR.dialog._.uiElementBuilders.hbox.build( dialog, hboxDefinition, html );
}
return html.join( '' );
};
CKEDITOR.ui.dialog.uiElement.call( this, dialog, elementDefinition, htmlList, 'div', null, { role : 'presentation' }, innerHTML );
},
/**
* A text input with a label. This UI element class represents both the
* single-line text inputs and password inputs in dialog boxes.
* @constructor
* @example
* @extends CKEDITOR.ui.dialog.labeledElement
* @param {CKEDITOR.dialog} dialog
* Parent dialog object.
* @param {CKEDITOR.dialog.uiElementDefinition} elementDefinition
* The element definition. Accepted fields:
* <ul>
* <li><strong>default</strong> (Optional) The default value.</li>
* <li><strong>validate</strong> (Optional) The validation function. </li>
* <li><strong>maxLength</strong> (Optional) The maximum length of text box
* contents.</li>
* <li><strong>size</strong> (Optional) The size of the text box. This is
* usually overridden by the size defined by the skin, however.</li>
* </ul>
* @param {Array} htmlList
* List of HTML code to output to.
*/
textInput : function( dialog, elementDefinition, htmlList )
{
if ( arguments.length < 3 )
return;
initPrivateObject.call( this, elementDefinition );
var domId = this._.inputId = CKEDITOR.tools.getNextId() + '_textInput',
attributes = { 'class' : 'cke_dialog_ui_input_' + elementDefinition.type, id : domId, type : 'text' },
i;
// Set the validator, if any.
if ( elementDefinition.validate )
this.validate = elementDefinition.validate;
// Set the max length and size.
if ( elementDefinition.maxLength )
attributes.maxlength = elementDefinition.maxLength;
if ( elementDefinition.size )
attributes.size = elementDefinition.size;
if ( elementDefinition.controlStyle )
attributes.style = elementDefinition.controlStyle;
// If user presses Enter in a text box, it implies clicking OK for the dialog.
var me = this, keyPressedOnMe = false;
dialog.on( 'load', function()
{
me.getInputElement().on( 'keydown', function( evt )
{
if ( evt.data.getKeystroke() == 13 )
keyPressedOnMe = true;
} );
// Lower the priority this 'keyup' since 'ok' will close the dialog.(#3749)
me.getInputElement().on( 'keyup', function( evt )
{
if ( evt.data.getKeystroke() == 13 && keyPressedOnMe )
{
dialog.getButton( 'ok' ) && setTimeout( function ()
{
dialog.getButton( 'ok' ).click();
}, 0 );
keyPressedOnMe = false;
}
}, null, null, 1000 );
} );
/** @ignore */
var innerHTML = function()
{
// IE BUG: Text input fields in IE at 100% would exceed a <td> or inline
// container's width, so need to wrap it inside a <div>.
var html = [ '<div class="cke_dialog_ui_input_', elementDefinition.type, '" role="presentation"' ];
if ( elementDefinition.width )
html.push( 'style="width:'+ elementDefinition.width +'" ' );
html.push( '><input ' );
attributes[ 'aria-labelledby' ] = this._.labelId;
this._.required && ( attributes[ 'aria-required' ] = this._.required );
for ( var i in attributes )
html.push( i + '="' + attributes[i] + '" ' );
html.push( ' /></div>' );
return html.join( '' );
};
CKEDITOR.ui.dialog.labeledElement.call( this, dialog, elementDefinition, htmlList, innerHTML );
},
/**
* A text area with a label on the top or left.
* @constructor
* @extends CKEDITOR.ui.dialog.labeledElement
* @example
* @param {CKEDITOR.dialog} dialog
* Parent dialog object.
* @param {CKEDITOR.dialog.uiElementDefinition} elementDefinition
* The element definition. Accepted fields:
* <ul>
* <li><strong>rows</strong> (Optional) The number of rows displayed.
* Defaults to 5 if not defined.</li>
* <li><strong>cols</strong> (Optional) The number of cols displayed.
* Defaults to 20 if not defined. Usually overridden by skins.</li>
* <li><strong>default</strong> (Optional) The default value.</li>
* <li><strong>validate</strong> (Optional) The validation function. </li>
* </ul>
* @param {Array} htmlList
* List of HTML code to output to.
*/
textarea : function( dialog, elementDefinition, htmlList )
{
if ( arguments.length < 3 )
return;
initPrivateObject.call( this, elementDefinition );
var me = this,
domId = this._.inputId = CKEDITOR.tools.getNextId() + '_textarea',
attributes = {};
if ( elementDefinition.validate )
this.validate = elementDefinition.validate;
// Generates the essential attributes for the textarea tag.
attributes.rows = elementDefinition.rows || 5;
attributes.cols = elementDefinition.cols || 20;
/** @ignore */
var innerHTML = function()
{
attributes[ 'aria-labelledby' ] = this._.labelId;
this._.required && ( attributes[ 'aria-required' ] = this._.required );
var html = [ '<div class="cke_dialog_ui_input_textarea" role="presentation"><textarea class="cke_dialog_ui_input_textarea" id="', domId, '" ' ];
for ( var i in attributes )
html.push( i + '="' + CKEDITOR.tools.htmlEncode( attributes[i] ) + '" ' );
html.push( '>', CKEDITOR.tools.htmlEncode( me._['default'] ), '</textarea></div>' );
return html.join( '' );
};
CKEDITOR.ui.dialog.labeledElement.call( this, dialog, elementDefinition, htmlList, innerHTML );
},
/**
* A single checkbox with a label on the right.
* @constructor
* @extends CKEDITOR.ui.dialog.uiElement
* @example
* @param {CKEDITOR.dialog} dialog
* Parent dialog object.
* @param {CKEDITOR.dialog.uiElementDefinition} elementDefinition
* The element definition. Accepted fields:
* <ul>
* <li><strong>checked</strong> (Optional) Whether the checkbox is checked
* on instantiation. Defaults to false.</li>
* <li><strong>validate</strong> (Optional) The validation function.</li>
* <li><strong>label</strong> (Optional) The checkbox label.</li>
* </ul>
* @param {Array} htmlList
* List of HTML code to output to.
*/
checkbox : function( dialog, elementDefinition, htmlList )
{
if ( arguments.length < 3 )
return;
var _ = initPrivateObject.call( this, elementDefinition, { 'default' : !!elementDefinition[ 'default' ] } );
if ( elementDefinition.validate )
this.validate = elementDefinition.validate;
/** @ignore */
var innerHTML = function()
{
var myDefinition = CKEDITOR.tools.extend( {}, elementDefinition,
{
id : elementDefinition.id ? elementDefinition.id + '_checkbox' : CKEDITOR.tools.getNextId() + '_checkbox'
}, true ),
html = [];
var labelId = CKEDITOR.tools.getNextId() + '_label';
var attributes = { 'class' : 'cke_dialog_ui_checkbox_input', type : 'checkbox', 'aria-labelledby' : labelId };
cleanInnerDefinition( myDefinition );
if ( elementDefinition[ 'default' ] )
attributes.checked = 'checked';
if ( typeof myDefinition.controlStyle != 'undefined' )
myDefinition.style = myDefinition.controlStyle;
_.checkbox = new CKEDITOR.ui.dialog.uiElement( dialog, myDefinition, html, 'input', null, attributes );
html.push( ' <label id="', labelId, '" for="', attributes.id, '">',
CKEDITOR.tools.htmlEncode( elementDefinition.label ),
'</label>' );
return html.join( '' );
};
CKEDITOR.ui.dialog.uiElement.call( this, dialog, elementDefinition, htmlList, 'span', null, null, innerHTML );
},
/**
* A group of radio buttons.
* @constructor
* @example
* @extends CKEDITOR.ui.dialog.labeledElement
* @param {CKEDITOR.dialog} dialog
* Parent dialog object.
* @param {CKEDITOR.dialog.uiElementDefinition} elementDefinition
* The element definition. Accepted fields:
* <ul>
* <li><strong>default</strong> (Required) The default value.</li>
* <li><strong>validate</strong> (Optional) The validation function.</li>
* <li><strong>items</strong> (Required) An array of options. Each option
* is a 1- or 2-item array of format [ 'Description', 'Value' ]. If 'Value'
* is missing, then the value would be assumed to be the same as the
* description.</li>
* </ul>
* @param {Array} htmlList
* List of HTML code to output to.
*/
radio : function( dialog, elementDefinition, htmlList )
{
if ( arguments.length < 3)
return;
initPrivateObject.call( this, elementDefinition );
if ( !this._['default'] )
this._['default'] = this._.initValue = elementDefinition.items[0][1];
if ( elementDefinition.validate )
this.validate = elementDefinition.valdiate;
var children = [], me = this;
/** @ignore */
var innerHTML = function()
{
var inputHtmlList = [], html = [],
commonAttributes = { 'class' : 'cke_dialog_ui_radio_item', 'aria-labelledby' : this._.labelId },
commonName = elementDefinition.id ? elementDefinition.id + '_radio' : CKEDITOR.tools.getNextId() + '_radio';
for ( var i = 0 ; i < elementDefinition.items.length ; i++ )
{
var item = elementDefinition.items[i],
title = item[2] !== undefined ? item[2] : item[0],
value = item[1] !== undefined ? item[1] : item[0],
inputId = CKEDITOR.tools.getNextId() + '_radio_input',
labelId = inputId + '_label',
inputDefinition = CKEDITOR.tools.extend( {}, elementDefinition,
{
id : inputId,
title : null,
type : null
}, true ),
labelDefinition = CKEDITOR.tools.extend( {}, inputDefinition,
{
title : title
}, true ),
inputAttributes =
{
type : 'radio',
'class' : 'cke_dialog_ui_radio_input',
name : commonName,
value : value,
'aria-labelledby' : labelId
},
inputHtml = [];
if ( me._['default'] == value )
inputAttributes.checked = 'checked';
cleanInnerDefinition( inputDefinition );
cleanInnerDefinition( labelDefinition );
if ( typeof inputDefinition.controlStyle != 'undefined' )
inputDefinition.style = inputDefinition.controlStyle;
children.push( new CKEDITOR.ui.dialog.uiElement( dialog, inputDefinition, inputHtml, 'input', null, inputAttributes ) );
inputHtml.push( ' ' );
new CKEDITOR.ui.dialog.uiElement( dialog, labelDefinition, inputHtml, 'label', null, { id : labelId, 'for' : inputAttributes.id },
item[0] );
inputHtmlList.push( inputHtml.join( '' ) );
}
new CKEDITOR.ui.dialog.hbox( dialog, [], inputHtmlList, html );
return html.join( '' );
};
CKEDITOR.ui.dialog.labeledElement.call( this, dialog, elementDefinition, htmlList, innerHTML );
this._.children = children;
},
/**
* A button with a label inside.
* @constructor
* @example
* @extends CKEDITOR.ui.dialog.uiElement
* @param {CKEDITOR.dialog} dialog
* Parent dialog object.
* @param {CKEDITOR.dialog.uiElementDefinition} elementDefinition
* The element definition. Accepted fields:
* <ul>
* <li><strong>label</strong> (Required) The button label.</li>
* <li><strong>disabled</strong> (Optional) Set to true if you want the
* button to appear in disabled state.</li>
* </ul>
* @param {Array} htmlList
* List of HTML code to output to.
*/
button : function( dialog, elementDefinition, htmlList )
{
if ( !arguments.length )
return;
if ( typeof elementDefinition == 'function' )
elementDefinition = elementDefinition( dialog.getParentEditor() );
initPrivateObject.call( this, elementDefinition, { disabled : elementDefinition.disabled || false } );
// Add OnClick event to this input.
CKEDITOR.event.implementOn( this );
var me = this;
// Register an event handler for processing button clicks.
dialog.on( 'load', function( eventInfo )
{
var element = this.getElement();
(function()
{
element.on( 'click', function( evt )
{
me.fire( 'click', { dialog : me.getDialog() } );
evt.data.preventDefault();
} );
element.on( 'keydown', function( evt )
{
if ( evt.data.getKeystroke() in { 32:1 } )
{
me.click();
evt.data.preventDefault();
}
} );
})();
element.unselectable();
}, this );
var outerDefinition = CKEDITOR.tools.extend( {}, elementDefinition );
delete outerDefinition.style;
var labelId = CKEDITOR.tools.getNextId() + '_label';
CKEDITOR.ui.dialog.uiElement.call(
this,
dialog,
outerDefinition,
htmlList,
'a',
null,
{
style : elementDefinition.style,
href : 'javascript:void(0)',
title : elementDefinition.label,
hidefocus : 'true',
'class' : elementDefinition['class'],
role : 'button',
'aria-labelledby' : labelId
},
'<span id="' + labelId + '" class="cke_dialog_ui_button">' +
CKEDITOR.tools.htmlEncode( elementDefinition.label ) +
'</span>' );
},
/**
* A select box.
* @extends CKEDITOR.ui.dialog.uiElement
* @example
* @constructor
* @param {CKEDITOR.dialog} dialog
* Parent dialog object.
* @param {CKEDITOR.dialog.uiElementDefinition} elementDefinition
* The element definition. Accepted fields:
* <ul>
* <li><strong>default</strong> (Required) The default value.</li>
* <li><strong>validate</strong> (Optional) The validation function.</li>
* <li><strong>items</strong> (Required) An array of options. Each option
* is a 1- or 2-item array of format [ 'Description', 'Value' ]. If 'Value'
* is missing, then the value would be assumed to be the same as the
* description.</li>
* <li><strong>multiple</strong> (Optional) Set this to true if you'd like
* to have a multiple-choice select box.</li>
* <li><strong>size</strong> (Optional) The number of items to display in
* the select box.</li>
* </ul>
* @param {Array} htmlList
* List of HTML code to output to.
*/
select : function( dialog, elementDefinition, htmlList )
{
if ( arguments.length < 3 )
return;
var _ = initPrivateObject.call( this, elementDefinition );
if ( elementDefinition.validate )
this.validate = elementDefinition.validate;
_.inputId = CKEDITOR.tools.getNextId() + '_select';
/** @ignore */
var innerHTML = function()
{
var myDefinition = CKEDITOR.tools.extend( {}, elementDefinition,
{
id : elementDefinition.id ? elementDefinition.id + '_select' : CKEDITOR.tools.getNextId() + '_select'
}, true ),
html = [],
innerHTML = [],
attributes = { 'id' : _.inputId, 'class' : 'cke_dialog_ui_input_select', 'aria-labelledby' : this._.labelId };
// Add multiple and size attributes from element definition.
if ( elementDefinition.size != undefined )
attributes.size = elementDefinition.size;
if ( elementDefinition.multiple != undefined )
attributes.multiple = elementDefinition.multiple;
cleanInnerDefinition( myDefinition );
for ( var i = 0, item ; i < elementDefinition.items.length && ( item = elementDefinition.items[i] ) ; i++ )
{
innerHTML.push( '<option value="',
CKEDITOR.tools.htmlEncode( item[1] !== undefined ? item[1] : item[0] ), '" /> ',
CKEDITOR.tools.htmlEncode( item[0] ) );
}
if ( typeof myDefinition.controlStyle != 'undefined' )
myDefinition.style = myDefinition.controlStyle;
_.select = new CKEDITOR.ui.dialog.uiElement( dialog, myDefinition, html, 'select', null, attributes, innerHTML.join( '' ) );
return html.join( '' );
};
CKEDITOR.ui.dialog.labeledElement.call( this, dialog, elementDefinition, htmlList, innerHTML );
},
/**
* A file upload input.
* @extends CKEDITOR.ui.dialog.labeledElement
* @example
* @constructor
* @param {CKEDITOR.dialog} dialog
* Parent dialog object.
* @param {CKEDITOR.dialog.uiElementDefinition} elementDefinition
* The element definition. Accepted fields:
* <ul>
* <li><strong>validate</strong> (Optional) The validation function.</li>
* </ul>
* @param {Array} htmlList
* List of HTML code to output to.
*/
file : function( dialog, elementDefinition, htmlList )
{
if ( arguments.length < 3 )
return;
if ( elementDefinition['default'] === undefined )
elementDefinition['default'] = '';
var _ = CKEDITOR.tools.extend( initPrivateObject.call( this, elementDefinition ), { definition : elementDefinition, buttons : [] } );
if ( elementDefinition.validate )
this.validate = elementDefinition.validate;
/** @ignore */
var innerHTML = function()
{
_.frameId = CKEDITOR.tools.getNextId() + '_fileInput';
// Support for custom document.domain in IE.
var isCustomDomain = CKEDITOR.env.isCustomDomain();
var html = [
'<iframe' +
' frameborder="0"' +
' allowtransparency="0"' +
' class="cke_dialog_ui_input_file"' +
' id="', _.frameId, '"' +
' title="', elementDefinition.label, '"' +
' src="javascript:void(' ];
html.push(
isCustomDomain ?
'(function(){' +
'document.open();' +
'document.domain=\'' + document.domain + '\';' +
'document.close();' +
'})()'
:
'0' );
html.push(
')">' +
'</iframe>' );
return html.join( '' );
};
// IE BUG: Parent container does not resize to contain the iframe automatically.
dialog.on( 'load', function()
{
var iframe = CKEDITOR.document.getById( _.frameId ),
contentDiv = iframe.getParent();
contentDiv.addClass( 'cke_dialog_ui_input_file' );
} );
CKEDITOR.ui.dialog.labeledElement.call( this, dialog, elementDefinition, htmlList, innerHTML );
},
/**
* A button for submitting the file in a file upload input.
* @extends CKEDITOR.ui.dialog.button
* @example
* @constructor
* @param {CKEDITOR.dialog} dialog
* Parent dialog object.
* @param {CKEDITOR.dialog.uiElementDefinition} elementDefinition
* The element definition. Accepted fields:
* <ul>
* <li><strong>for</strong> (Required) The file input's page and element Id
* to associate to, in a 2-item array format: [ 'page_id', 'element_id' ].
* </li>
* <li><strong>validate</strong> (Optional) The validation function.</li>
* </ul>
* @param {Array} htmlList
* List of HTML code to output to.
*/
fileButton : function( dialog, elementDefinition, htmlList )
{
if ( arguments.length < 3 )
return;
var _ = initPrivateObject.call( this, elementDefinition ),
me = this;
if ( elementDefinition.validate )
this.validate = elementDefinition.validate;
var myDefinition = CKEDITOR.tools.extend( {}, elementDefinition );
var onClick = myDefinition.onClick;
myDefinition.className = ( myDefinition.className ? myDefinition.className + ' ' : '' ) + 'cke_dialog_ui_button';
myDefinition.onClick = function( evt )
{
var target = elementDefinition[ 'for' ]; // [ pageId, elementId ]
if ( !onClick || onClick.call( this, evt ) !== false )
{
dialog.getContentElement( target[0], target[1] ).submit();
this.disable();
}
};
dialog.on( 'load', function()
{
dialog.getContentElement( elementDefinition[ 'for' ][0], elementDefinition[ 'for' ][1] )._.buttons.push( me );
} );
CKEDITOR.ui.dialog.button.call( this, dialog, myDefinition, htmlList );
},
html : (function()
{
var myHtmlRe = /^\s*<[\w:]+\s+([^>]*)?>/,
theirHtmlRe = /^(\s*<[\w:]+(?:\s+[^>]*)?)((?:.|\r|\n)+)$/,
emptyTagRe = /\/$/;
/**
* A dialog element made from raw HTML code.
* @extends CKEDITOR.ui.dialog.uiElement
* @name CKEDITOR.ui.dialog.html
* @param {CKEDITOR.dialog} dialog Parent dialog object.
* @param {CKEDITOR.dialog.uiElementDefinition} elementDefinition Element definition.
* Accepted fields:
* <ul>
* <li><strong>html</strong> (Required) HTML code of this element.</li>
* </ul>
* @param {Array} htmlList List of HTML code to be added to the dialog's content area.
* @example
* @constructor
*/
return function( dialog, elementDefinition, htmlList )
{
if ( arguments.length < 3 )
return;
var myHtmlList = [],
myHtml,
theirHtml = elementDefinition.html,
myMatch, theirMatch;
// If the HTML input doesn't contain any tags at the beginning, add a <span> tag around it.
if ( theirHtml.charAt( 0 ) != '<' )
theirHtml = '<span>' + theirHtml + '</span>';
// Look for focus function in definition.
var focus = elementDefinition.focus;
if ( focus )
{
var oldFocus = this.focus;
this.focus = function()
{
oldFocus.call( this );
typeof focus == 'function' && focus.call( this );
this.fire( 'focus' );
};
if ( elementDefinition.isFocusable )
{
var oldIsFocusable = this.isFocusable;
this.isFocusable = oldIsFocusable;
}
this.keyboardFocusable = true;
}
CKEDITOR.ui.dialog.uiElement.call( this, dialog, elementDefinition, myHtmlList, 'span', null, null, '' );
// Append the attributes created by the uiElement call to the real HTML.
myHtml = myHtmlList.join( '' );
myMatch = myHtml.match( myHtmlRe );
theirMatch = theirHtml.match( theirHtmlRe ) || [ '', '', '' ];
if ( emptyTagRe.test( theirMatch[1] ) )
{
theirMatch[1] = theirMatch[1].slice( 0, -1 );
theirMatch[2] = '/' + theirMatch[2];
}
htmlList.push( [ theirMatch[1], ' ', myMatch[1] || '', theirMatch[2] ].join( '' ) );
};
})(),
/**
* Form fieldset for grouping dialog UI elements.
* @constructor
* @extends CKEDITOR.ui.dialog.uiElement
* @param {CKEDITOR.dialog} dialog Parent dialog object.
* @param {Array} childObjList
* Array of {@link CKEDITOR.ui.dialog.uiElement} objects inside this
* container.
* @param {Array} childHtmlList
* Array of HTML code that correspond to the HTML output of all the
* objects in childObjList.
* @param {Array} htmlList
* Array of HTML code that this element will output to.
* @param {CKEDITOR.dialog.uiElementDefinition} elementDefinition
* The element definition. Accepted fields:
* <ul>
* <li><strong>label</strong> (Optional) The legend of the this fieldset.</li>
* <li><strong>children</strong> (Required) An array of dialog field definitions which will be grouped inside this fieldset. </li>
* </ul>
*/
fieldset : function( dialog, childObjList, childHtmlList, htmlList, elementDefinition )
{
var legendLabel = elementDefinition.label;
/** @ignore */
var innerHTML = function()
{
var html = [];
legendLabel && html.push( '<legend>' + legendLabel + '</legend>' );
for ( var i = 0; i < childHtmlList.length; i++ )
html.push( childHtmlList[ i ] );
return html.join( '' );
};
this._ = { children : childObjList };
CKEDITOR.ui.dialog.uiElement.call( this, dialog, elementDefinition, htmlList, 'fieldset', null, null, innerHTML );
}
}, true );
CKEDITOR.ui.dialog.html.prototype = new CKEDITOR.ui.dialog.uiElement;
CKEDITOR.ui.dialog.labeledElement.prototype = CKEDITOR.tools.extend( new CKEDITOR.ui.dialog.uiElement,
/** @lends CKEDITOR.ui.dialog.labeledElement.prototype */
{
/**
* Sets the label text of the element.
* @param {String} label The new label text.
* @returns {CKEDITOR.ui.dialog.labeledElement} The current labeled element.
* @example
*/
setLabel : function( label )
{
var node = CKEDITOR.document.getById( this._.labelId );
if ( node.getChildCount() < 1 )
( new CKEDITOR.dom.text( label, CKEDITOR.document ) ).appendTo( node );
else
node.getChild( 0 ).$.nodeValue = label;
return this;
},
/**
* Retrieves the current label text of the elment.
* @returns {String} The current label text.
* @example
*/
getLabel : function()
{
var node = CKEDITOR.document.getById( this._.labelId );
if ( !node || node.getChildCount() < 1 )
return '';
else
return node.getChild( 0 ).getText();
},
/**
* Defines the onChange event for UI element definitions.
* @field
* @type Object
* @example
*/
eventProcessors : commonEventProcessors
}, true );
CKEDITOR.ui.dialog.button.prototype = CKEDITOR.tools.extend( new CKEDITOR.ui.dialog.uiElement,
/** @lends CKEDITOR.ui.dialog.button.prototype */
{
/**
* Simulates a click to the button.
* @example
* @returns {Object} Return value of the 'click' event.
*/
click : function()
{
if ( !this._.disabled )
return this.fire( 'click', { dialog : this._.dialog } );
this.getElement().$.blur();
return false;
},
/**
* Enables the button.
* @example
*/
enable : function()
{
this._.disabled = false;
var element = this.getElement();
element && element.removeClass( 'cke_disabled' );
},
/**
* Disables the button.
* @example
*/
disable : function()
{
this._.disabled = true;
this.getElement().addClass( 'cke_disabled' );
},
isVisible : function()
{
return this.getElement().getFirst().isVisible();
},
isEnabled : function()
{
return !this._.disabled;
},
/**
* Defines the onChange event and onClick for button element definitions.
* @field
* @type Object
* @example
*/
eventProcessors : CKEDITOR.tools.extend( {}, CKEDITOR.ui.dialog.uiElement.prototype.eventProcessors,
{
/** @ignore */
onClick : function( dialog, func )
{
this.on( 'click', func );
}
}, true ),
/**
* Handler for the element's access key up event. Simulates a click to
* the button.
* @example
*/
accessKeyUp : function()
{
this.click();
},
/**
* Handler for the element's access key down event. Simulates a mouse
* down to the button.
* @example
*/
accessKeyDown : function()
{
this.focus();
},
keyboardFocusable : true
}, true );
CKEDITOR.ui.dialog.textInput.prototype = CKEDITOR.tools.extend( new CKEDITOR.ui.dialog.labeledElement,
/** @lends CKEDITOR.ui.dialog.textInput.prototype */
{
/**
* Gets the text input DOM element under this UI object.
* @example
* @returns {CKEDITOR.dom.element} The DOM element of the text input.
*/
getInputElement : function()
{
return CKEDITOR.document.getById( this._.inputId );
},
/**
* Puts focus into the text input.
* @example
*/
focus : function()
{
var me = this.selectParentTab();
// GECKO BUG: setTimeout() is needed to workaround invisible selections.
setTimeout( function()
{
var element = me.getInputElement();
element && element.$.focus();
}, 0 );
},
/**
* Selects all the text in the text input.
* @example
*/
select : function()
{
var me = this.selectParentTab();
// GECKO BUG: setTimeout() is needed to workaround invisible selections.
setTimeout( function()
{
var e = me.getInputElement();
if ( e )
{
e.$.focus();
e.$.select();
}
}, 0 );
},
/**
* Handler for the text input's access key up event. Makes a select()
* call to the text input.
* @example
*/
accessKeyUp : function()
{
this.select();
},
/**
* Sets the value of this text input object.
* @param {Object} value The new value.
* @returns {CKEDITOR.ui.dialog.textInput} The current UI element.
* @example
* uiElement.setValue( 'Blamo' );
*/
setValue : function( value )
{
!value && ( value = '' );
return CKEDITOR.ui.dialog.uiElement.prototype.setValue.apply( this, arguments );
},
keyboardFocusable : true
}, commonPrototype, true );
CKEDITOR.ui.dialog.textarea.prototype = new CKEDITOR.ui.dialog.textInput();
CKEDITOR.ui.dialog.select.prototype = CKEDITOR.tools.extend( new CKEDITOR.ui.dialog.labeledElement,
/** @lends CKEDITOR.ui.dialog.select.prototype */
{
/**
* Gets the DOM element of the select box.
* @returns {CKEDITOR.dom.element} The <select> element of this UI
* element.
* @example
*/
getInputElement : function()
{
return this._.select.getElement();
},
/**
* Adds an option to the select box.
* @param {String} label Option label.
* @param {String} value (Optional) Option value, if not defined it'll be
* assumed to be the same as the label.
* @param {Number} index (Optional) Position of the option to be inserted
* to. If not defined the new option will be inserted to the end of list.
* @example
* @returns {CKEDITOR.ui.dialog.select} The current select UI element.
*/
add : function( label, value, index )
{
var option = new CKEDITOR.dom.element( 'option', this.getDialog().getParentEditor().document ),
selectElement = this.getInputElement().$;
option.$.text = label;
option.$.value = ( value === undefined || value === null ) ? label : value;
if ( index === undefined || index === null )
{
if ( CKEDITOR.env.ie )
selectElement.add( option.$ );
else
selectElement.add( option.$, null );
}
else
selectElement.add( option.$, index );
return this;
},
/**
* Removes an option from the selection list.
* @param {Number} index Index of the option to be removed.
* @example
* @returns {CKEDITOR.ui.dialog.select} The current select UI element.
*/
remove : function( index )
{
var selectElement = this.getInputElement().$;
selectElement.remove( index );
return this;
},
/**
* Clears all options out of the selection list.
* @returns {CKEDITOR.ui.dialog.select} The current select UI element.
*/
clear : function()
{
var selectElement = this.getInputElement().$;
while ( selectElement.length > 0 )
selectElement.remove( 0 );
return this;
},
keyboardFocusable : true
}, commonPrototype, true );
CKEDITOR.ui.dialog.checkbox.prototype = CKEDITOR.tools.extend( new CKEDITOR.ui.dialog.uiElement,
/** @lends CKEDITOR.ui.dialog.checkbox.prototype */
{
/**
* Gets the checkbox DOM element.
* @example
* @returns {CKEDITOR.dom.element} The DOM element of the checkbox.
*/
getInputElement : function()
{
return this._.checkbox.getElement();
},
/**
* Sets the state of the checkbox.
* @example
* @param {Boolean} true to tick the checkbox, false to untick it.
* @param {Boolean} noChangeEvent Internal commit, to supress 'change' event on this element.
*/
setValue : function( checked, noChangeEvent )
{
this.getInputElement().$.checked = checked;
!noChangeEvent && this.fire( 'change', { value : checked } );
},
/**
* Gets the state of the checkbox.
* @example
* @returns {Boolean} true means the checkbox is ticked, false means it's not ticked.
*/
getValue : function()
{
return this.getInputElement().$.checked;
},
/**
* Handler for the access key up event. Toggles the checkbox.
* @example
*/
accessKeyUp : function()
{
this.setValue( !this.getValue() );
},
/**
* Defines the onChange event for UI element definitions.
* @field
* @type Object
* @example
*/
eventProcessors :
{
onChange : function( dialog, func )
{
if ( !CKEDITOR.env.ie )
return commonEventProcessors.onChange.apply( this, arguments );
else
{
dialog.on( 'load', function()
{
var element = this._.checkbox.getElement();
element.on( 'propertychange', function( evt )
{
evt = evt.data.$;
if ( evt.propertyName == 'checked' )
this.fire( 'change', { value : element.$.checked } );
}, this );
}, this );
this.on( 'change', func );
}
return null;
}
},
keyboardFocusable : true
}, commonPrototype, true );
CKEDITOR.ui.dialog.radio.prototype = CKEDITOR.tools.extend( new CKEDITOR.ui.dialog.uiElement,
/** @lends CKEDITOR.ui.dialog.radio.prototype */
{
/**
* Checks one of the radio buttons in this button group.
* @example
* @param {String} value The value of the button to be chcked.
* @param {Boolean} noChangeEvent Internal commit, to supress 'change' event on this element.
*/
setValue : function( value, noChangeEvent )
{
var children = this._.children,
item;
for ( var i = 0 ; ( i < children.length ) && ( item = children[i] ) ; i++ )
item.getElement().$.checked = ( item.getValue() == value );
!noChangeEvent && this.fire( 'change', { value : value } );
},
/**
* Gets the value of the currently checked radio button.
* @example
* @returns {String} The currently checked button's value.
*/
getValue : function()
{
var children = this._.children;
for ( var i = 0 ; i < children.length ; i++ )
{
if ( children[i].getElement().$.checked )
return children[i].getValue();
}
return null;
},
/**
* Handler for the access key up event. Focuses the currently
* selected radio button, or the first radio button if none is
* selected.
* @example
*/
accessKeyUp : function()
{
var children = this._.children, i;
for ( i = 0 ; i < children.length ; i++ )
{
if ( children[i].getElement().$.checked )
{
children[i].getElement().focus();
return;
}
}
children[0].getElement().focus();
},
/**
* Defines the onChange event for UI element definitions.
* @field
* @type Object
* @example
*/
eventProcessors :
{
onChange : function( dialog, func )
{
if ( !CKEDITOR.env.ie )
return commonEventProcessors.onChange.apply( this, arguments );
else
{
dialog.on( 'load', function()
{
var children = this._.children, me = this;
for ( var i = 0 ; i < children.length ; i++ )
{
var element = children[i].getElement();
element.on( 'propertychange', function( evt )
{
evt = evt.data.$;
if ( evt.propertyName == 'checked' && this.$.checked )
me.fire( 'change', { value : this.getAttribute( 'value' ) } );
} );
}
}, this );
this.on( 'change', func );
}
return null;
}
},
keyboardFocusable : true
}, commonPrototype, true );
CKEDITOR.ui.dialog.file.prototype = CKEDITOR.tools.extend( new CKEDITOR.ui.dialog.labeledElement,
commonPrototype,
/** @lends CKEDITOR.ui.dialog.file.prototype */
{
/**
* Gets the <input> element of this file input.
* @returns {CKEDITOR.dom.element} The file input element.
* @example
*/
getInputElement : function()
{
var frameDocument = CKEDITOR.document.getById( this._.frameId ).getFrameDocument();
return frameDocument.$.forms.length > 0 ?
new CKEDITOR.dom.element( frameDocument.$.forms[0].elements[0] ) :
this.getElement();
},
/**
* Uploads the file in the file input.
* @returns {CKEDITOR.ui.dialog.file} This object.
* @example
*/
submit : function()
{
this.getInputElement().getParent().$.submit();
return this;
},
/**
* Get the action assigned to the form.
* @returns {String} The value of the action.
* @example
*/
getAction : function()
{
return this.getInputElement().getParent().$.action;
},
/**
* The events must be applied on the inner input element, and
* that must be done when the iframe & form has been loaded
*/
registerEvents : function( definition )
{
var regex = /^on([A-Z]\w+)/,
match;
var registerDomEvent = function( uiElement, dialog, eventName, func )
{
uiElement.on( 'formLoaded', function()
{
uiElement.getInputElement().on( eventName, func, uiElement );
});
};
for ( var i in definition )
{
if ( !( match = i.match( regex ) ) )
continue;
if ( this.eventProcessors[i] )
this.eventProcessors[i].call( this, this._.dialog, definition[i] );
else
registerDomEvent( this, this._.dialog, match[1].toLowerCase(), definition[i] );
}
return this;
},
/**
* Redraws the file input and resets the file path in the file input.
* The redraw logic is necessary because non-IE browsers tend to clear
* the <iframe> containing the file input after closing the dialog.
* @example
*/
reset : function()
{
var _ = this._,
frameElement = CKEDITOR.document.getById( _.frameId ),
frameDocument = frameElement.getFrameDocument(),
elementDefinition = _.definition,
buttons = _.buttons,
callNumber = this.formLoadedNumber,
unloadNumber = this.formUnloadNumber,
langDir = _.dialog._.editor.lang.dir,
langCode = _.dialog._.editor.langCode;
// The callback function for the iframe, but we must call tools.addFunction only once
// so we store the function number in this.formLoadedNumber
if ( !callNumber )
{
callNumber = this.formLoadedNumber = CKEDITOR.tools.addFunction(
function()
{
// Now we can apply the events to the input type=file
this.fire( 'formLoaded' ) ;
}, this ) ;
// Remove listeners attached to the content of the iframe (the file input)
unloadNumber = this.formUnloadNumber = CKEDITOR.tools.addFunction(
function()
{
this.getInputElement().clearCustomData();
}, this ) ;
this.getDialog()._.editor.on( 'destroy', function()
{
CKEDITOR.tools.removeFunction( callNumber );
CKEDITOR.tools.removeFunction( unloadNumber );
} );
}
function generateFormField()
{
frameDocument.$.open();
// Support for custom document.domain in IE.
if ( CKEDITOR.env.isCustomDomain() )
frameDocument.$.domain = document.domain;
var size = '';
if ( elementDefinition.size )
size = elementDefinition.size - ( CKEDITOR.env.ie ? 7 : 0 ); // "Browse" button is bigger in IE.
frameDocument.$.write( [ '<html dir="' + langDir + '" lang="' + langCode + '"><head><title></title></head><body style="margin: 0; overflow: hidden; background: transparent;">',
'<form enctype="multipart/form-data" method="POST" dir="' + langDir + '" lang="' + langCode + '" action="',
CKEDITOR.tools.htmlEncode( elementDefinition.action ),
'">',
'<input type="file" name="',
CKEDITOR.tools.htmlEncode( elementDefinition.id || 'cke_upload' ),
'" size="',
CKEDITOR.tools.htmlEncode( size > 0 ? size : "" ),
'" />',
'</form>',
'</body></html>',
'<script>window.parent.CKEDITOR.tools.callFunction(' + callNumber + ');',
'window.onbeforeunload = function() {window.parent.CKEDITOR.tools.callFunction(' + unloadNumber + ')}</script>' ].join( '' ) );
frameDocument.$.close();
for ( var i = 0 ; i < buttons.length ; i++ )
buttons[i].enable();
}
// #3465: Wait for the browser to finish rendering the dialog first.
if ( CKEDITOR.env.gecko )
setTimeout( generateFormField, 500 );
else
generateFormField();
},
getValue : function()
{
return this.getInputElement().$.value || '';
},
/***
* The default value of input type="file" is an empty string, but during initialization
* of this UI element, the iframe still isn't ready so it can't be read from that object
* Setting it manually prevents later issues about the current value ("") being different
* of the initial value (undefined as it asked for .value of a div)
*/
setInitValue : function()
{
this._.initValue = '';
},
/**
* Defines the onChange event for UI element definitions.
* @field
* @type Object
* @example
*/
eventProcessors :
{
onChange : function( dialog, func )
{
// If this method is called several times (I'm not sure about how this can happen but the default
// onChange processor includes this protection)
// In order to reapply to the new element, the property is deleted at the beggining of the registerEvents method
if ( !this._.domOnChangeRegistered )
{
// By listening for the formLoaded event, this handler will get reapplied when a new
// form is created
this.on( 'formLoaded', function()
{
this.getInputElement().on( 'change', function(){ this.fire( 'change', { value : this.getValue() } ); }, this );
}, this );
this._.domOnChangeRegistered = true;
}
this.on( 'change', func );
}
},
keyboardFocusable : true
}, true );
CKEDITOR.ui.dialog.fileButton.prototype = new CKEDITOR.ui.dialog.button;
CKEDITOR.ui.dialog.fieldset.prototype = CKEDITOR.tools.clone( CKEDITOR.ui.dialog.hbox.prototype );
CKEDITOR.dialog.addUIElement( 'text', textBuilder );
CKEDITOR.dialog.addUIElement( 'password', textBuilder );
CKEDITOR.dialog.addUIElement( 'textarea', commonBuilder );
CKEDITOR.dialog.addUIElement( 'checkbox', commonBuilder );
CKEDITOR.dialog.addUIElement( 'radio', commonBuilder );
CKEDITOR.dialog.addUIElement( 'button', commonBuilder );
CKEDITOR.dialog.addUIElement( 'select', commonBuilder );
CKEDITOR.dialog.addUIElement( 'file', commonBuilder );
CKEDITOR.dialog.addUIElement( 'fileButton', commonBuilder );
CKEDITOR.dialog.addUIElement( 'html', commonBuilder );
CKEDITOR.dialog.addUIElement( 'fieldset', containerBuilder );
})();
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
(function()
{
var htmlFilterRules =
{
elements :
{
$ : function( element )
{
var attributes = element.attributes,
realHtml = attributes && attributes[ 'data-cke-realelement' ],
realFragment = realHtml && new CKEDITOR.htmlParser.fragment.fromHtml( decodeURIComponent( realHtml ) ),
realElement = realFragment && realFragment.children[ 0 ];
// If we have width/height in the element, we must move it into
// the real element.
if ( realElement && element.attributes[ 'data-cke-resizable' ] )
{
var style = element.attributes.style;
if ( style )
{
// Get the width from the style.
var match = /(?:^|\s)width\s*:\s*(\d+)/i.exec( style ),
width = match && match[1];
// Get the height from the style.
match = /(?:^|\s)height\s*:\s*(\d+)/i.exec( style );
var height = match && match[1];
if ( width )
realElement.attributes.width = width;
if ( height )
realElement.attributes.height = height;
}
}
return realElement;
}
}
};
CKEDITOR.plugins.add( 'fakeobjects',
{
requires : [ 'htmlwriter' ],
afterInit : function( editor )
{
var dataProcessor = editor.dataProcessor,
htmlFilter = dataProcessor && dataProcessor.htmlFilter;
if ( htmlFilter )
htmlFilter.addRules( htmlFilterRules );
}
});
})();
CKEDITOR.editor.prototype.createFakeElement = function( realElement, className, realElementType, isResizable )
{
var lang = this.lang.fakeobjects,
label = lang[ realElementType ] || lang.unknown;
var attributes =
{
'class' : className,
src : CKEDITOR.getUrl( 'images/spacer.gif' ),
'data-cke-realelement' : encodeURIComponent( realElement.getOuterHtml() ),
'data-cke-real-node-type' : realElement.type,
alt : label,
title : label,
align : realElement.getAttribute( 'align' ) || ''
};
if ( realElementType )
attributes[ 'data-cke-real-element-type' ] = realElementType;
if ( isResizable )
attributes[ 'data-cke-resizable' ] = isResizable;
return this.document.createElement( 'img', { attributes : attributes } );
};
CKEDITOR.editor.prototype.createFakeParserElement = function( realElement, className, realElementType, isResizable )
{
var lang = this.lang.fakeobjects,
label = lang[ realElementType ] || lang.unknown,
html;
var writer = new CKEDITOR.htmlParser.basicWriter();
realElement.writeHtml( writer );
html = writer.getHtml();
var attributes =
{
'class' : className,
src : CKEDITOR.getUrl( 'images/spacer.gif' ),
'data-cke-realelement' : encodeURIComponent( html ),
'data-cke-real-node-type' : realElement.type,
alt : label,
title : label,
align : realElement.attributes.align || ''
};
if ( realElementType )
attributes[ 'data-cke-real-element-type' ] = realElementType;
if ( isResizable )
attributes[ 'data-cke-resizable' ] = isResizable;
return new CKEDITOR.htmlParser.element( 'img', attributes );
};
CKEDITOR.editor.prototype.restoreRealElement = function( fakeElement )
{
if ( fakeElement.data( 'cke-real-node-type' ) != CKEDITOR.NODE_ELEMENT )
return null;
return CKEDITOR.dom.element.createFromHtml(
decodeURIComponent( fakeElement.data( 'cke-realelement' ) ),
this.document );
};
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.add( 'floatpanel',
{
requires : [ 'panel' ]
});
(function()
{
var panels = {};
var isShowing = false;
function getPanel( editor, doc, parentElement, definition, level )
{
// Generates the panel key: docId-eleId-skinName-langDir[-uiColor][-CSSs][-level]
var key = CKEDITOR.tools.genKey( doc.getUniqueId(), parentElement.getUniqueId(), editor.skinName, editor.lang.dir,
editor.uiColor || '', definition.css || '', level || '' );
var panel = panels[ key ];
if ( !panel )
{
panel = panels[ key ] = new CKEDITOR.ui.panel( doc, definition );
panel.element = parentElement.append( CKEDITOR.dom.element.createFromHtml( panel.renderHtml( editor ), doc ) );
panel.element.setStyles(
{
display : 'none',
position : 'absolute'
});
}
return panel;
}
CKEDITOR.ui.floatPanel = CKEDITOR.tools.createClass(
{
$ : function( editor, parentElement, definition, level )
{
definition.forceIFrame = 1;
var doc = parentElement.getDocument(),
panel = getPanel( editor, doc, parentElement, definition, level || 0 ),
element = panel.element,
iframe = element.getFirst().getFirst();
this.element = element;
this._ =
{
// The panel that will be floating.
panel : panel,
parentElement : parentElement,
definition : definition,
document : doc,
iframe : iframe,
children : [],
dir : editor.lang.dir
};
editor.on( 'mode', function(){ this.hide(); }, this );
},
proto :
{
addBlock : function( name, block )
{
return this._.panel.addBlock( name, block );
},
addListBlock : function( name, multiSelect )
{
return this._.panel.addListBlock( name, multiSelect );
},
getBlock : function( name )
{
return this._.panel.getBlock( name );
},
/*
corner (LTR):
1 = top-left
2 = top-right
3 = bottom-right
4 = bottom-left
corner (RTL):
1 = top-right
2 = top-left
3 = bottom-left
4 = bottom-right
*/
showBlock : function( name, offsetParent, corner, offsetX, offsetY )
{
var panel = this._.panel,
block = panel.showBlock( name );
this.allowBlur( false );
isShowing = 1;
var element = this.element,
iframe = this._.iframe,
definition = this._.definition,
position = offsetParent.getDocumentPosition( element.getDocument() ),
rtl = this._.dir == 'rtl';
var left = position.x + ( offsetX || 0 ),
top = position.y + ( offsetY || 0 );
// Floating panels are off by (-1px, 0px) in RTL mode. (#3438)
if ( rtl && ( corner == 1 || corner == 4 ) )
left += offsetParent.$.offsetWidth;
else if ( !rtl && ( corner == 2 || corner == 3 ) )
left += offsetParent.$.offsetWidth - 1;
if ( corner == 3 || corner == 4 )
top += offsetParent.$.offsetHeight - 1;
// Memorize offsetParent by it's ID.
this._.panel._.offsetParentId = offsetParent.getId();
element.setStyles(
{
top : top + 'px',
left: 0,
display : ''
});
// Don't use display or visibility style because we need to
// calculate the rendering layout later and focus the element.
element.setOpacity( 0 );
// To allow the context menu to decrease back their width
element.getFirst().removeStyle( 'width' );
// Configure the IFrame blur event. Do that only once.
if ( !this._.blurSet )
{
// Non IE prefer the event into a window object.
var focused = CKEDITOR.env.ie ? iframe : new CKEDITOR.dom.window( iframe.$.contentWindow );
// With addEventListener compatible browsers, we must
// useCapture when registering the focus/blur events to
// guarantee they will be firing in all situations. (#3068, #3222 )
CKEDITOR.event.useCapture = true;
focused.on( 'blur', function( ev )
{
if ( !this.allowBlur() )
return;
// As we are using capture to register the listener,
// the blur event may get fired even when focusing
// inside the window itself, so we must ensure the
// target is out of it.
var target;
if ( CKEDITOR.env.ie && !this.allowBlur()
|| ( target = ev.data.getTarget() )
&& target.getName && target.getName() != 'iframe' )
return;
if ( this.visible && !this._.activeChild && !isShowing )
this.hide();
},
this );
focused.on( 'focus', function()
{
this._.focused = true;
this.hideChild();
this.allowBlur( true );
},
this );
CKEDITOR.event.useCapture = false;
this._.blurSet = 1;
}
panel.onEscape = CKEDITOR.tools.bind( function( keystroke )
{
if ( this.onEscape && this.onEscape( keystroke ) === false )
return false;
},
this );
CKEDITOR.tools.setTimeout( function()
{
if ( rtl )
left -= element.$.offsetWidth;
var panelLoad = CKEDITOR.tools.bind( function ()
{
var target = element.getFirst();
if ( block.autoSize )
{
// We must adjust first the width or IE6 could include extra lines in the height computation
var widthNode = block.element.$;
if ( CKEDITOR.env.gecko || CKEDITOR.env.opera )
widthNode = widthNode.parentNode;
if ( CKEDITOR.env.ie )
widthNode = widthNode.document.body;
var width = widthNode.scrollWidth;
// Account for extra height needed due to IE quirks box model bug:
// http://en.wikipedia.org/wiki/Internet_Explorer_box_model_bug
// (#3426)
if ( CKEDITOR.env.ie && CKEDITOR.env.quirks && width > 0 )
width += ( target.$.offsetWidth || 0 ) - ( target.$.clientWidth || 0 );
// A little extra at the end.
// If not present, IE6 might break into the next line, but also it looks better this way
width += 4 ;
target.setStyle( 'width', width + 'px' );
// IE doesn't compute the scrollWidth if a filter is applied previously
block.element.addClass( 'cke_frameLoaded' );
var height = block.element.$.scrollHeight;
// Account for extra height needed due to IE quirks box model bug:
// http://en.wikipedia.org/wiki/Internet_Explorer_box_model_bug
// (#3426)
if ( CKEDITOR.env.ie && CKEDITOR.env.quirks && height > 0 )
height += ( target.$.offsetHeight || 0 ) - ( target.$.clientHeight || 0 );
target.setStyle( 'height', height + 'px' );
// Fix IE < 8 visibility.
panel._.currentBlock.element.setStyle( 'display', 'none' ).removeStyle( 'display' );
}
else
target.removeStyle( 'height' );
var panelElement = panel.element,
panelWindow = panelElement.getWindow(),
windowScroll = panelWindow.getScrollPosition(),
viewportSize = panelWindow.getViewPaneSize(),
panelSize =
{
'height' : panelElement.$.offsetHeight,
'width' : panelElement.$.offsetWidth
};
// If the menu is horizontal off, shift it toward
// the opposite language direction.
if ( rtl ? left < 0 : left + panelSize.width > viewportSize.width + windowScroll.x )
left += ( panelSize.width * ( rtl ? 1 : -1 ) );
// Vertical off screen is simpler.
if ( top + panelSize.height > viewportSize.height + windowScroll.y )
top -= panelSize.height;
// If IE is in RTL, we have troubles with absolute
// position and horizontal scrolls. Here we have a
// series of hacks to workaround it. (#6146)
if ( CKEDITOR.env.ie )
{
var offsetParent = new CKEDITOR.dom.element( element.$.offsetParent ),
scrollParent = offsetParent;
// Quirks returns <body>, but standards returns <html>.
if ( scrollParent.getName() == 'html' )
scrollParent = scrollParent.getDocument().getBody();
if ( scrollParent.getComputedStyle( 'direction' ) == 'rtl' )
{
// For IE8, there is not much logic on this, but it works.
if ( CKEDITOR.env.ie8Compat )
left -= element.getDocument().getDocumentElement().$.scrollLeft * 2;
else
left -= ( offsetParent.$.scrollWidth - offsetParent.$.clientWidth );
}
}
// Trigger the onHide event of the previously active panel to prevent
// incorrect styles from being applied (#6170)
var innerElement = element.getFirst(),
activePanel;
if ( ( activePanel = innerElement.getCustomData( 'activePanel' ) ) )
activePanel.onHide && activePanel.onHide.call( this, 1 );
innerElement.setCustomData( 'activePanel', this );
element.setStyles(
{
top : top + 'px',
left : left + 'px'
} );
element.setOpacity( 1 );
} , this );
panel.isLoaded ? panelLoad() : panel.onLoad = panelLoad;
// Set the panel frame focus, so the blur event gets fired.
CKEDITOR.tools.setTimeout( function()
{
iframe.$.contentWindow.focus();
// We need this get fired manually because of unfired focus() function.
this.allowBlur( true );
}, 0, this);
}, CKEDITOR.env.air ? 200 : 0, this);
this.visible = 1;
if ( this.onShow )
this.onShow.call( this );
isShowing = 0;
},
hide : function()
{
if ( this.visible && ( !this.onHide || this.onHide.call( this ) !== true ) )
{
this.hideChild();
this.element.setStyle( 'display', 'none' );
this.visible = 0;
this.element.getFirst().removeCustomData( 'activePanel' );
}
},
allowBlur : function( allow ) // Prevent editor from hiding the panel. #3222.
{
var panel = this._.panel;
if ( allow != undefined )
panel.allowBlur = allow;
return panel.allowBlur;
},
showAsChild : function( panel, blockName, offsetParent, corner, offsetX, offsetY )
{
// Skip reshowing of child which is already visible.
if ( this._.activeChild == panel && panel._.panel._.offsetParentId == offsetParent.getId() )
return;
this.hideChild();
panel.onHide = CKEDITOR.tools.bind( function()
{
// Use a timeout, so we give time for this menu to get
// potentially focused.
CKEDITOR.tools.setTimeout( function()
{
if ( !this._.focused )
this.hide();
},
0, this );
},
this );
this._.activeChild = panel;
this._.focused = false;
panel.showBlock( blockName, offsetParent, corner, offsetX, offsetY );
/* #3767 IE: Second level menu may not have borders */
if ( CKEDITOR.env.ie7Compat || ( CKEDITOR.env.ie8 && CKEDITOR.env.ie6Compat ) )
{
setTimeout(function()
{
panel.element.getChild( 0 ).$.style.cssText += '';
}, 100);
}
},
hideChild : function()
{
var activeChild = this._.activeChild;
if ( activeChild )
{
delete activeChild.onHide;
delete this._.activeChild;
activeChild.hide();
}
}
}
});
CKEDITOR.on( 'instanceDestroyed', function()
{
var isLastInstance = CKEDITOR.tools.isEmpty( CKEDITOR.instances );
for ( var i in panels )
{
var panel = panels[ i ];
// Safe to destroy it since there're no more instances.(#4241)
if ( isLastInstance )
panel.destroy();
// Panel might be used by other instances, just hide them.(#4552)
else
panel.element.hide();
}
// Remove the registration.
isLastInstance && ( panels = {} );
} );
})();
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
(function()
{
CKEDITOR.plugins.add( 'pastefromword',
{
init : function( editor )
{
// Flag indicate this command is actually been asked instead of a generic
// pasting.
var forceFromWord = 0;
var resetFromWord = function()
{
setTimeout( function() { forceFromWord = 0; }, 0 );
};
// Features bring by this command beside the normal process:
// 1. No more bothering of user about the clean-up.
// 2. Perform the clean-up even if content is not from MS-Word.
// (e.g. from a MS-Word similar application.)
editor.addCommand( 'pastefromword',
{
canUndo : false,
exec : function()
{
forceFromWord = 1;
if ( editor.execCommand( 'paste' ) === false )
{
editor.on( 'dialogHide', function ( evt )
{
evt.removeListener();
resetFromWord();
});
}
else
resetFromWord();
}
});
// Register the toolbar button.
editor.ui.addButton( 'PasteFromWord',
{
label : editor.lang.pastefromword.toolbar,
command : 'pastefromword'
});
editor.on( 'paste', function( evt )
{
var data = evt.data,
mswordHtml;
// MS-WORD format sniffing.
if ( ( mswordHtml = data[ 'html' ] )
&& ( forceFromWord || ( /(class=\"?Mso|style=\"[^\"]*\bmso\-|w:WordDocument)/ ).test( mswordHtml ) ) )
{
var isLazyLoad = this.loadFilterRules( function()
{
// Event continuation with the original data.
if ( isLazyLoad )
editor.fire( 'paste', data );
else if ( !editor.config.pasteFromWordPromptCleanup
|| ( forceFromWord || confirm( editor.lang.pastefromword.confirmCleanup ) ) )
{
data[ 'html' ] = CKEDITOR.cleanWord( mswordHtml, editor );
}
});
// The cleanup rules are to be loaded, we should just cancel
// this event.
isLazyLoad && evt.cancel();
}
}, this );
},
loadFilterRules : function( callback )
{
var isLoaded = CKEDITOR.cleanWord;
if ( isLoaded )
callback();
else
{
var filterFilePath = CKEDITOR.getUrl(
CKEDITOR.config.pasteFromWordCleanupFile
|| ( this.path + 'filter/default.js' ) );
// Load with busy indicator.
CKEDITOR.scriptLoader.load( filterFilePath, callback, null, false, true );
}
return !isLoaded;
}
});
})();
/**
* Whether to prompt the user about the clean up of content being pasted from
* MS Word.
* @name CKEDITOR.config.pasteFromWordPromptCleanup
* @since 3.1
* @type Boolean
* @default undefined
* @example
* config.pasteFromWordPromptCleanup = true;
*/
/**
* The file that provides the MS Word cleanup function for pasting operations.
* Note: This is a global configuration shared by all editor instances present
* in the page.
* @name CKEDITOR.config.pasteFromWordCleanupFile
* @since 3.1
* @type String
* @default 'default'
* @example
* // Load from 'pastefromword' plugin 'filter' sub folder (custom.js file).
* CKEDITOR.config.pasteFromWordCleanupFile = 'custom';
*/
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
(function()
{
var fragmentPrototype = CKEDITOR.htmlParser.fragment.prototype,
elementPrototype = CKEDITOR.htmlParser.element.prototype;
fragmentPrototype.onlyChild = elementPrototype.onlyChild = function()
{
var children = this.children,
count = children.length,
firstChild = ( count == 1 ) && children[ 0 ];
return firstChild || null;
};
elementPrototype.removeAnyChildWithName = function( tagName )
{
var children = this.children,
childs = [],
child;
for ( var i = 0; i < children.length; i++ )
{
child = children[ i ];
if ( !child.name )
continue;
if ( child.name == tagName )
{
childs.push( child );
children.splice( i--, 1 );
}
childs = childs.concat( child.removeAnyChildWithName( tagName ) );
}
return childs;
};
elementPrototype.getAncestor = function( tagNameRegex )
{
var parent = this.parent;
while ( parent && !( parent.name && parent.name.match( tagNameRegex ) ) )
parent = parent.parent;
return parent;
};
fragmentPrototype.firstChild = elementPrototype.firstChild = function( evaluator )
{
var child;
for ( var i = 0 ; i < this.children.length ; i++ )
{
child = this.children[ i ];
if ( evaluator( child ) )
return child;
else if ( child.name )
{
child = child.firstChild( evaluator );
if ( child )
return child;
}
}
return null;
};
// Adding a (set) of styles to the element's 'style' attributes.
elementPrototype.addStyle = function( name, value, isPrepend )
{
var styleText, addingStyleText = '';
// name/value pair.
if ( typeof value == 'string' )
addingStyleText += name + ':' + value + ';';
else
{
// style literal.
if ( typeof name == 'object' )
{
for ( var style in name )
{
if ( name.hasOwnProperty( style ) )
addingStyleText += style + ':' + name[ style ] + ';';
}
}
// raw style text form.
else
addingStyleText += name;
isPrepend = value;
}
if ( !this.attributes )
this.attributes = {};
styleText = this.attributes.style || '';
styleText = ( isPrepend ?
[ addingStyleText, styleText ]
: [ styleText, addingStyleText ] ).join( ';' );
this.attributes.style = styleText.replace( /^;|;(?=;)/, '' );
};
/**
* Return the DTD-valid parent tag names of the specified one.
* @param tagName
*/
CKEDITOR.dtd.parentOf = function( tagName )
{
var result = {};
for ( var tag in this )
{
if ( tag.indexOf( '$' ) == -1 && this[ tag ][ tagName ] )
result[ tag ] = 1;
}
return result;
};
var cssLengthRelativeUnit = /^([.\d]*)+(em|ex|px|gd|rem|vw|vh|vm|ch|mm|cm|in|pt|pc|deg|rad|ms|s|hz|khz){1}?/i;
var emptyMarginRegex = /^(?:\b0[^\s]*\s*){1,4}$/; // e.g. 0px 0pt 0px
var romanLiternalPattern = '^m{0,4}(cm|cd|d?c{0,3})(xc|xl|l?x{0,3})(ix|iv|v?i{0,3})$',
lowerRomanLiteralRegex = new RegExp( romanLiternalPattern ),
upperRomanLiteralRegex = new RegExp( romanLiternalPattern.toUpperCase() );
var listBaseIndent = 0,
previousListItemMargin;
CKEDITOR.plugins.pastefromword =
{
utils :
{
// Create a <cke:listbullet> which indicate an list item type.
createListBulletMarker : function ( bulletStyle, bulletText )
{
var marker = new CKEDITOR.htmlParser.element( 'cke:listbullet' ),
listType;
// TODO: Support more list style type from MS-Word.
if ( !bulletStyle )
{
bulletStyle = 'decimal';
listType = 'ol';
}
else if ( bulletStyle[ 2 ] )
{
if ( !isNaN( bulletStyle[ 1 ] ) )
bulletStyle = 'decimal';
else if ( lowerRomanLiteralRegex.test( bulletStyle[ 1 ] ) )
bulletStyle = 'lower-roman';
else if ( upperRomanLiteralRegex.test( bulletStyle[ 1 ] ) )
bulletStyle = 'upper-roman';
else if ( /^[a-z]+$/.test( bulletStyle[ 1 ] ) )
bulletStyle = 'lower-alpha';
else if ( /^[A-Z]+$/.test( bulletStyle[ 1 ] ) )
bulletStyle = 'upper-alpha';
// Simply use decimal for the rest forms of unrepresentable
// numerals, e.g. Chinese...
else
bulletStyle = 'decimal';
listType = 'ol';
}
else
{
if ( /[l\u00B7\u2002]/.test( bulletStyle[ 1 ] ) )
bulletStyle = 'disc';
else if ( /[\u006F\u00D8]/.test( bulletStyle[ 1 ] ) )
bulletStyle = 'circle';
else if ( /[\u006E\u25C6]/.test( bulletStyle[ 1 ] ) )
bulletStyle = 'square';
else
bulletStyle = 'disc';
listType = 'ul';
}
// Represent list type as CSS style.
marker.attributes =
{
'cke:listtype' : listType,
'style' : 'list-style-type:' + bulletStyle + ';'
};
marker.add( new CKEDITOR.htmlParser.text( bulletText ) );
return marker;
},
isListBulletIndicator : function( element )
{
var styleText = element.attributes && element.attributes.style;
if ( /mso-list\s*:\s*Ignore/i.test( styleText ) )
return true;
},
isContainingOnlySpaces : function( element )
{
var text;
return ( ( text = element.onlyChild() )
&& ( /^(:?\s| )+$/ ).test( text.value ) );
},
resolveList : function( element )
{
// <cke:listbullet> indicate a list item.
var attrs = element.attributes,
listMarker;
if ( ( listMarker = element.removeAnyChildWithName( 'cke:listbullet' ) )
&& listMarker.length
&& ( listMarker = listMarker[ 0 ] ) )
{
element.name = 'cke:li';
if ( attrs.style )
{
attrs.style = CKEDITOR.plugins.pastefromword.filters.stylesFilter(
[
// Text-indent is not representing list item level any more.
[ 'text-indent' ],
[ 'line-height' ],
// Resolve indent level from 'margin-left' value.
[ ( /^margin(:?-left)?$/ ), null, function( margin )
{
// Be able to deal with component/short-hand form style.
var values = margin.split( ' ' );
margin = CKEDITOR.plugins.pastefromword.utils.convertToPx( values[ 3 ] || values[ 1 ] || values [ 0 ] );
margin = parseInt( margin, 10 );
// Figure out the indent unit by looking at the first increament.
if ( !listBaseIndent && previousListItemMargin && margin > previousListItemMargin )
listBaseIndent = margin - previousListItemMargin;
attrs[ 'cke:margin' ] = previousListItemMargin = margin;
} ]
] )( attrs.style, element ) || '' ;
}
// Inherit list-type-style from bullet.
var listBulletAttrs = listMarker.attributes,
listBulletStyle = listBulletAttrs.style;
element.addStyle( listBulletStyle );
CKEDITOR.tools.extend( attrs, listBulletAttrs );
return true;
}
return false;
},
// Convert various length units to 'px' in ignorance of DPI.
convertToPx : ( function ()
{
var calculator = CKEDITOR.dom.element.createFromHtml(
'<div style="position:absolute;left:-9999px;' +
'top:-9999px;margin:0px;padding:0px;border:0px;"' +
'></div>', CKEDITOR.document );
CKEDITOR.document.getBody().append( calculator );
return function( cssLength )
{
if ( cssLengthRelativeUnit.test( cssLength ) )
{
calculator.setStyle( 'width', cssLength );
return calculator.$.clientWidth + 'px';
}
return cssLength;
};
} )(),
// Providing a shorthand style then retrieve one or more style component values.
getStyleComponents : ( function()
{
var calculator = CKEDITOR.dom.element.createFromHtml(
'<div style="position:absolute;left:-9999px;top:-9999px;"></div>',
CKEDITOR.document );
CKEDITOR.document.getBody().append( calculator );
return function( name, styleValue, fetchList )
{
calculator.setStyle( name, styleValue );
var styles = {},
count = fetchList.length;
for ( var i = 0; i < count; i++ )
styles[ fetchList[ i ] ] = calculator.getStyle( fetchList[ i ] );
return styles;
};
} )(),
listDtdParents : CKEDITOR.dtd.parentOf( 'ol' )
},
filters :
{
// Transform a normal list into flat list items only presentation.
// E.g. <ul><li>level1<ol><li>level2</li></ol></li> =>
// <cke:li cke:listtype="ul" cke:indent="1">level1</cke:li>
// <cke:li cke:listtype="ol" cke:indent="2">level2</cke:li>
flattenList : function( element )
{
var attrs = element.attributes,
parent = element.parent;
var listStyleType,
indentLevel = 1;
// Resolve how many level nested.
while ( parent )
{
parent.attributes && parent.attributes[ 'cke:list'] && indentLevel++;
parent = parent.parent;
}
// All list items are of the same type.
switch ( attrs.type )
{
case 'a' :
listStyleType = 'lower-alpha';
break;
// TODO: Support more list style type from MS-Word.
}
var children = element.children,
child;
for ( var i = 0; i < children.length; i++ )
{
child = children[ i ];
var attributes = child.attributes;
if ( child.name in CKEDITOR.dtd.$listItem )
{
var listItemChildren = child.children,
count = listItemChildren.length,
last = listItemChildren[ count - 1 ];
// Move out nested list.
if ( last.name in CKEDITOR.dtd.$list )
{
children.splice( i + 1, 0, last );
last.parent = element;
// Remove the parent list item if it's just a holder.
if ( !--listItemChildren.length )
children.splice( i, 1 );
}
child.name = 'cke:li';
attributes[ 'cke:indent' ] = indentLevel;
previousListItemMargin = 0;
attributes[ 'cke:listtype' ] = element.name;
listStyleType && child.addStyle( 'list-style-type', listStyleType, true );
}
}
delete element.name;
// We're loosing tag name here, signalize this element as a list.
attrs[ 'cke:list' ] = 1;
},
/**
* Try to collect all list items among the children and establish one
* or more HTML list structures for them.
* @param element
*/
assembleList : function( element )
{
var children = element.children, child,
listItem, // The current processing cke:li element.
listItemAttrs,
listType, // Determine the root type of the list.
listItemIndent, // Indent level of current list item.
lastListItem, // The previous one just been added to the list.
list, parentList, // Current staging list and it's parent list if any.
indent;
for ( var i = 0; i < children.length; i++ )
{
child = children[ i ];
if ( 'cke:li' == child.name )
{
child.name = 'li';
listItem = child;
listItemAttrs = listItem.attributes;
listType = listItem.attributes[ 'cke:listtype' ];
// List item indent level might come from a real list indentation or
// been resolved from a pseudo list item's margin value, even get
// no indentation at all.
listItemIndent = parseInt( listItemAttrs[ 'cke:indent' ], 10 )
|| listBaseIndent && ( Math.ceil( listItemAttrs[ 'cke:margin' ] / listBaseIndent ) )
|| 1;
// Ignore the 'list-style-type' attribute if it's matched with
// the list root element's default style type.
listItemAttrs.style && ( listItemAttrs.style =
CKEDITOR.plugins.pastefromword.filters.stylesFilter(
[
[ 'list-style-type', listType == 'ol' ? 'decimal' : 'disc' ]
] )( listItemAttrs.style )
|| '' );
if ( !list )
{
list = new CKEDITOR.htmlParser.element( listType );
list.add( listItem );
children[ i ] = list;
}
else
{
if ( listItemIndent > indent )
{
list = new CKEDITOR.htmlParser.element( listType );
list.add( listItem );
lastListItem.add( list );
}
else if ( listItemIndent < indent )
{
// There might be a negative gap between two list levels. (#4944)
var diff = indent - listItemIndent,
parent;
while ( diff-- && ( parent = list.parent ) )
list = parent.parent;
list.add( listItem );
}
else
list.add( listItem );
children.splice( i--, 1 );
}
lastListItem = listItem;
indent = listItemIndent;
}
else
list = null;
}
listBaseIndent = 0;
},
/**
* A simple filter which always rejecting.
*/
falsyFilter : function( value )
{
return false;
},
/**
* A filter dedicated on the 'style' attribute filtering, e.g. dropping/replacing style properties.
* @param styles {Array} in form of [ styleNameRegexp, styleValueRegexp,
* newStyleValue/newStyleGenerator, newStyleName ] where only the first
* parameter is mandatory.
* @param whitelist {Boolean} Whether the {@param styles} will be considered as a white-list.
*/
stylesFilter : function( styles, whitelist )
{
return function( styleText, element )
{
var rules = [];
// html-encoded quote might be introduced by 'font-family'
// from MS-Word which confused the following regexp. e.g.
//'font-family: "Lucida, Console"'
styleText
.replace( /"/g, '"' )
.replace( /\s*([^ :;]+)\s*:\s*([^;]+)\s*(?=;|$)/g,
function( match, name, value )
{
name = name.toLowerCase();
name == 'font-family' && ( value = value.replace( /["']/g, '' ) );
var namePattern,
valuePattern,
newValue,
newName;
for ( var i = 0 ; i < styles.length; i++ )
{
if ( styles[ i ] )
{
namePattern = styles[ i ][ 0 ];
valuePattern = styles[ i ][ 1 ];
newValue = styles[ i ][ 2 ];
newName = styles[ i ][ 3 ];
if ( name.match( namePattern )
&& ( !valuePattern || value.match( valuePattern ) ) )
{
name = newName || name;
whitelist && ( newValue = newValue || value );
if ( typeof newValue == 'function' )
newValue = newValue( value, element, name );
// Return an couple indicate both name and value
// changed.
if ( newValue && newValue.push )
name = newValue[ 0 ], newValue = newValue[ 1 ];
if ( typeof newValue == 'string' )
rules.push( [ name, newValue ] );
return;
}
}
}
!whitelist && rules.push( [ name, value ] );
});
for ( var i = 0 ; i < rules.length ; i++ )
rules[ i ] = rules[ i ].join( ':' );
return rules.length ?
( rules.join( ';' ) + ';' ) : false;
};
},
/**
* Migrate the element by decorate styles on it.
* @param styleDefiniton
* @param variables
*/
elementMigrateFilter : function ( styleDefiniton, variables )
{
return function( element )
{
var styleDef =
variables ?
new CKEDITOR.style( styleDefiniton, variables )._.definition
: styleDefiniton;
element.name = styleDef.element;
CKEDITOR.tools.extend( element.attributes, CKEDITOR.tools.clone( styleDef.attributes ) );
element.addStyle( CKEDITOR.style.getStyleText( styleDef ) );
};
},
/**
* Migrate styles by creating a new nested stylish element.
* @param styleDefinition
*/
styleMigrateFilter : function( styleDefinition, variableName )
{
var elementMigrateFilter = this.elementMigrateFilter;
return function( value, element )
{
// Build an stylish element first.
var styleElement = new CKEDITOR.htmlParser.element( null ),
variables = {};
variables[ variableName ] = value;
elementMigrateFilter( styleDefinition, variables )( styleElement );
// Place the new element inside the existing span.
styleElement.children = element.children;
element.children = [ styleElement ];
};
},
/**
* A filter which remove cke-namespaced-attribute on
* all none-cke-namespaced elements.
* @param value
* @param element
*/
bogusAttrFilter : function( value, element )
{
if ( element.name.indexOf( 'cke:' ) == -1 )
return false;
},
/**
* A filter which will be used to apply inline css style according the stylesheet
* definition rules, is generated lazily when filtering.
*/
applyStyleFilter : null
},
getRules : function( editor )
{
var dtd = CKEDITOR.dtd,
blockLike = CKEDITOR.tools.extend( {}, dtd.$block, dtd.$listItem, dtd.$tableContent ),
config = editor.config,
filters = this.filters,
falsyFilter = filters.falsyFilter,
stylesFilter = filters.stylesFilter,
elementMigrateFilter = filters.elementMigrateFilter,
styleMigrateFilter = CKEDITOR.tools.bind( this.filters.styleMigrateFilter, this.filters ),
createListBulletMarker = this.utils.createListBulletMarker,
flattenList = filters.flattenList,
assembleList = filters.assembleList,
isListBulletIndicator = this.utils.isListBulletIndicator,
containsNothingButSpaces = this.utils.isContainingOnlySpaces,
resolveListItem = this.utils.resolveList,
convertToPx = this.utils.convertToPx,
getStyleComponents = this.utils.getStyleComponents,
listDtdParents = this.utils.listDtdParents,
removeFontStyles = config.pasteFromWordRemoveFontStyles !== false,
removeStyles = config.pasteFromWordRemoveStyles !== false;
return {
elementNames :
[
// Remove script, meta and link elements.
[ ( /meta|link|script/ ), '' ]
],
root : function( element )
{
element.filterChildren();
assembleList( element );
},
elements :
{
'^' : function( element )
{
// Transform CSS style declaration to inline style.
var applyStyleFilter;
if ( CKEDITOR.env.gecko && ( applyStyleFilter = filters.applyStyleFilter ) )
applyStyleFilter( element );
},
$ : function( element )
{
var tagName = element.name || '',
attrs = element.attributes;
// Convert length unit of width/height on blocks to
// a more editor-friendly way (px).
if ( tagName in blockLike
&& attrs.style )
{
attrs.style = stylesFilter(
[ [ ( /^(:?width|height)$/ ), null, convertToPx ] ] )( attrs.style ) || '';
}
// Processing headings.
if ( tagName.match( /h\d/ ) )
{
element.filterChildren();
// Is the heading actually a list item?
if ( resolveListItem( element ) )
return;
// Adapt heading styles to editor's convention.
elementMigrateFilter( config[ 'format_' + tagName ] )( element );
}
// Remove inline elements which contain only empty spaces.
else if ( tagName in dtd.$inline )
{
element.filterChildren();
if ( containsNothingButSpaces( element ) )
delete element.name;
}
// Remove element with ms-office namespace,
// with it's content preserved, e.g. 'o:p'.
else if ( tagName.indexOf( ':' ) != -1
&& tagName.indexOf( 'cke' ) == -1 )
{
element.filterChildren();
// Restore image real link from vml.
if ( tagName == 'v:imagedata' )
{
var href = element.attributes[ 'o:href' ];
if ( href )
element.attributes.src = href;
element.name = 'img';
return;
}
delete element.name;
}
// Assembling list items into a whole list.
if ( tagName in listDtdParents )
{
element.filterChildren();
assembleList( element );
}
},
// We'll drop any style sheet, but Firefox conclude
// certain styles in a single style element, which are
// required to be changed into inline ones.
'style' : function( element )
{
if ( CKEDITOR.env.gecko )
{
// Grab only the style definition section.
var styleDefSection = element.onlyChild().value.match( /\/\* Style Definitions \*\/([\s\S]*?)\/\*/ ),
styleDefText = styleDefSection && styleDefSection[ 1 ],
rules = {}; // Storing the parsed result.
if ( styleDefText )
{
styleDefText
// Remove line-breaks.
.replace(/[\n\r]/g,'')
// Extract selectors and style properties.
.replace( /(.+?)\{(.+?)\}/g,
function( rule, selectors, styleBlock )
{
selectors = selectors.split( ',' );
var length = selectors.length, selector;
for ( var i = 0; i < length; i++ )
{
// Assume MS-Word mostly generate only simple
// selector( [Type selector][Class selector]).
CKEDITOR.tools.trim( selectors[ i ] )
.replace( /^(\w+)(\.[\w-]+)?$/g,
function( match, tagName, className )
{
tagName = tagName || '*';
className = className.substring( 1, className.length );
// Reject MS-Word Normal styles.
if ( className.match( /MsoNormal/ ) )
return;
if ( !rules[ tagName ] )
rules[ tagName ] = {};
if ( className )
rules[ tagName ][ className ] = styleBlock;
else
rules[ tagName ] = styleBlock;
} );
}
});
filters.applyStyleFilter = function( element )
{
var name = rules[ '*' ] ? '*' : element.name,
className = element.attributes && element.attributes[ 'class' ],
style;
if ( name in rules )
{
style = rules[ name ];
if ( typeof style == 'object' )
style = style[ className ];
// Maintain style rules priorities.
style && element.addStyle( style, true );
}
};
}
}
return false;
},
'p' : function( element )
{
element.filterChildren();
// Is the paragraph actually a list item?
if ( resolveListItem( element ) )
return;
// Adapt paragraph formatting to editor's convention
// according to enter-mode.
if ( config.enterMode == CKEDITOR.ENTER_BR )
{
// We suffer from attribute/style lost in this situation.
delete element.name;
element.add( new CKEDITOR.htmlParser.element( 'br' ) );
}
else
elementMigrateFilter( config[ 'format_' + ( config.enterMode == CKEDITOR.ENTER_P ? 'p' : 'div' ) ] )( element );
},
'div' : function( element )
{
// Aligned table with no text surrounded is represented by a wrapper div, from which
// table cells inherit as text-align styles, which is wrong.
// Instead we use a clear-float div after the table to properly achieve the same layout.
var singleChild = element.onlyChild();
if ( singleChild && singleChild.name == 'table' )
{
var attrs = element.attributes;
singleChild.attributes = CKEDITOR.tools.extend( singleChild.attributes, attrs );
attrs.style && singleChild.addStyle( attrs.style );
var clearFloatDiv = new CKEDITOR.htmlParser.element( 'div' );
clearFloatDiv.addStyle( 'clear' ,'both' );
element.add( clearFloatDiv );
delete element.name;
}
},
'td' : function ( element )
{
// 'td' in 'thead' is actually <th>.
if ( element.getAncestor( 'thead') )
element.name = 'th';
},
// MS-Word sometimes present list as a mixing of normal list
// and pseudo-list, normalize the previous ones into pseudo form.
'ol' : flattenList,
'ul' : flattenList,
'dl' : flattenList,
'font' : function( element )
{
// IE/Safari: drop the font tag if it comes from list bullet text.
if ( !CKEDITOR.env.gecko && isListBulletIndicator( element.parent ) )
{
delete element.name;
return;
}
element.filterChildren();
var attrs = element.attributes,
styleText = attrs.style,
parent = element.parent;
if ( 'font' == parent.name ) // Merge nested <font> tags.
{
CKEDITOR.tools.extend( parent.attributes,
element.attributes );
styleText && parent.addStyle( styleText );
delete element.name;
}
// Convert the merged into a span with all attributes preserved.
else
{
styleText = styleText || '';
// IE's having those deprecated attributes, normalize them.
if ( attrs.color )
{
attrs.color != '#000000' && ( styleText += 'color:' + attrs.color + ';' );
delete attrs.color;
}
if ( attrs.face )
{
styleText += 'font-family:' + attrs.face + ';';
delete attrs.face;
}
// TODO: Mapping size in ranges of xx-small,
// x-small, small, medium, large, x-large, xx-large.
if ( attrs.size )
{
styleText += 'font-size:' +
( attrs.size > 3 ? 'large'
: ( attrs.size < 3 ? 'small' : 'medium' ) ) + ';';
delete attrs.size;
}
element.name = 'span';
element.addStyle( styleText );
}
},
'span' : function( element )
{
// IE/Safari: remove the span if it comes from list bullet text.
if ( !CKEDITOR.env.gecko && isListBulletIndicator( element.parent ) )
return false;
element.filterChildren();
if ( containsNothingButSpaces( element ) )
{
delete element.name;
return null;
}
// For IE/Safari: List item bullet type is supposed to be indicated by
// the text of a span with style 'mso-list : Ignore' or an image.
if ( !CKEDITOR.env.gecko && isListBulletIndicator( element ) )
{
var listSymbolNode = element.firstChild( function( node )
{
return node.value || node.name == 'img';
});
var listSymbol = listSymbolNode && ( listSymbolNode.value || 'l.' ),
listType = listSymbol.match( /^([^\s]+?)([.)]?)$/ );
return createListBulletMarker( listType, listSymbol );
}
// Update the src attribute of image element with href.
var children = element.children,
attrs = element.attributes,
styleText = attrs && attrs.style,
firstChild = children && children[ 0 ];
// Assume MS-Word mostly carry font related styles on <span>,
// adapting them to editor's convention.
if ( styleText )
{
attrs.style = stylesFilter(
[
// Drop 'inline-height' style which make lines overlapping.
[ 'line-height' ],
[ ( /^font-family$/ ), null, !removeFontStyles ? styleMigrateFilter( config[ 'font_style' ], 'family' ) : null ] ,
[ ( /^font-size$/ ), null, !removeFontStyles ? styleMigrateFilter( config[ 'fontSize_style' ], 'size' ) : null ] ,
[ ( /^color$/ ), null, !removeFontStyles ? styleMigrateFilter( config[ 'colorButton_foreStyle' ], 'color' ) : null ] ,
[ ( /^background-color$/ ), null, !removeFontStyles ? styleMigrateFilter( config[ 'colorButton_backStyle' ], 'color' ) : null ]
] )( styleText, element ) || '';
}
return null;
},
// Migrate basic style formats to editor configured ones.
'b' : elementMigrateFilter( config[ 'coreStyles_bold' ] ),
'i' : elementMigrateFilter( config[ 'coreStyles_italic' ] ),
'u' : elementMigrateFilter( config[ 'coreStyles_underline' ] ),
's' : elementMigrateFilter( config[ 'coreStyles_strike' ] ),
'sup' : elementMigrateFilter( config[ 'coreStyles_superscript' ] ),
'sub' : elementMigrateFilter( config[ 'coreStyles_subscript' ] ),
// Editor doesn't support anchor with content currently (#3582),
// drop such anchors with content preserved.
'a' : function( element )
{
var attrs = element.attributes;
if ( attrs && !attrs.href && attrs.name )
delete element.name;
},
'cke:listbullet' : function( element )
{
if ( element.getAncestor( /h\d/ ) && !config.pasteFromWordNumberedHeadingToList )
delete element.name;
}
},
attributeNames :
[
// Remove onmouseover and onmouseout events (from MS Word comments effect)
[ ( /^onmouse(:?out|over)/ ), '' ],
// Onload on image element.
[ ( /^onload$/ ), '' ],
// Remove office and vml attribute from elements.
[ ( /(?:v|o):\w+/ ), '' ],
// Remove lang/language attributes.
[ ( /^lang/ ), '' ]
],
attributes :
{
'style' : stylesFilter(
removeStyles ?
// Provide a white-list of styles that we preserve, those should
// be the ones that could later be altered with editor tools.
[
// Preserve margin-left/right which used as default indent style in the editor.
[ ( /^margin$|^margin-(?!bottom|top)/ ), null, function( value, element, name )
{
if ( element.name in { p : 1, div : 1 } )
{
var indentStyleName = config.contentsLangDirection == 'ltr' ?
'margin-left' : 'margin-right';
// Extract component value from 'margin' shorthand.
if ( name == 'margin' )
{
value = getStyleComponents( name, value,
[ indentStyleName ] )[ indentStyleName ];
}
else if ( name != indentStyleName )
return null;
if ( value && !emptyMarginRegex.test( value ) )
return [ indentStyleName, value ];
}
return null;
} ],
// Preserve clear float style.
[ ( /^clear$/ ) ],
[ ( /^border.*|margin.*|vertical-align|float$/ ), null,
function( value, element )
{
if ( element.name == 'img' )
return value;
} ],
[ (/^width|height$/ ), null,
function( value, element )
{
if ( element.name in { table : 1, td : 1, th : 1, img : 1 } )
return value;
} ]
] :
// Otherwise provide a black-list of styles that we remove.
[
[ ( /^mso-/ ) ],
// Fixing color values.
[ ( /-color$/ ), null, function( value )
{
if ( value == 'transparent' )
return false;
if ( CKEDITOR.env.gecko )
return value.replace( /-moz-use-text-color/g, 'transparent' );
} ],
// Remove empty margin values, e.g. 0.00001pt 0em 0pt
[ ( /^margin$/ ), emptyMarginRegex ],
[ 'text-indent', '0cm' ],
[ 'page-break-before' ],
[ 'tab-stops' ],
[ 'display', 'none' ],
removeFontStyles ? [ ( /font-?/ ) ] : null
], removeStyles ),
// Prefer width styles over 'width' attributes.
'width' : function( value, element )
{
if ( element.name in dtd.$tableContent )
return false;
},
// Prefer border styles over table 'border' attributes.
'border' : function( value, element )
{
if ( element.name in dtd.$tableContent )
return false;
},
// Only Firefox carry style sheet from MS-Word, which
// will be applied by us manually. For other browsers
// the css className is useless.
'class' : falsyFilter,
// MS-Word always generate 'background-color' along with 'bgcolor',
// simply drop the deprecated attributes.
'bgcolor' : falsyFilter,
// Deprecate 'valign' attribute in favor of 'vertical-align'.
'valign' : removeStyles ? falsyFilter : function( value, element )
{
element.addStyle( 'vertical-align', value );
return false;
}
},
// Fore none-IE, some useful data might be buried under these IE-conditional
// comments where RegExp were the right approach to dig them out where usual approach
// is transform it into a fake element node which hold the desired data.
comment :
!CKEDITOR.env.ie ?
function( value, node )
{
var imageInfo = value.match( /<img.*?>/ ),
listInfo = value.match( /^\[if !supportLists\]([\s\S]*?)\[endif\]$/ );
// Seek for list bullet indicator.
if ( listInfo )
{
// Bullet symbol could be either text or an image.
var listSymbol = listInfo[ 1 ] || ( imageInfo && 'l.' ),
listType = listSymbol && listSymbol.match( />([^\s]+?)([.)]?)</ );
return createListBulletMarker( listType, listSymbol );
}
// Reveal the <img> element in conditional comments for Firefox.
if ( CKEDITOR.env.gecko && imageInfo )
{
var img = CKEDITOR.htmlParser.fragment.fromHtml( imageInfo[ 0 ] ).children[ 0 ],
previousComment = node.previous,
// Try to dig the real image link from vml markup from previous comment text.
imgSrcInfo = previousComment && previousComment.value.match( /<v:imagedata[^>]*o:href=['"](.*?)['"]/ ),
imgSrc = imgSrcInfo && imgSrcInfo[ 1 ];
// Is there a real 'src' url to be used?
imgSrc && ( img.attributes.src = imgSrc );
return img;
}
return false;
}
: falsyFilter
};
}
};
// The paste processor here is just a reduced copy of html data processor.
var pasteProcessor = function()
{
this.dataFilter = new CKEDITOR.htmlParser.filter();
};
pasteProcessor.prototype =
{
toHtml : function( data )
{
var fragment = CKEDITOR.htmlParser.fragment.fromHtml( data, false ),
writer = new CKEDITOR.htmlParser.basicWriter();
fragment.writeHtml( writer, this.dataFilter );
return writer.getHtml( true );
}
};
CKEDITOR.cleanWord = function( data, editor )
{
// Firefox will be confused by those downlevel-revealed IE conditional
// comments, fixing them first( convert it to upperlevel-revealed one ).
// e.g. <![if !vml]>...<![endif]>
if ( CKEDITOR.env.gecko )
data = data.replace( /(<!--\[if[^<]*?\])-->([\S\s]*?)<!--(\[endif\]-->)/gi, '$1$2$3' );
var dataProcessor = new pasteProcessor(),
dataFilter = dataProcessor.dataFilter;
// These rules will have higher priorities than default ones.
dataFilter.addRules( CKEDITOR.plugins.pastefromword.getRules( editor ) );
// Allow extending data filter rules.
editor.fire( 'beforeCleanWord', { filter : dataFilter } );
try
{
data = dataProcessor.toHtml( data, false );
}
catch ( e )
{
alert( editor.lang.pastefromword.error );
}
/* Below post processing those things that are unable to delivered by filter rules. */
// Remove 'cke' namespaced attribute used in filter rules as marker.
data = data.replace( /cke:.*?".*?"/g, '' );
// Remove empty style attribute.
data = data.replace( /style=""/g, '' );
// Remove the dummy spans ( having no inline style ).
data = data.replace( /<span>/g, '' );
return data;
};
})();
/**
* Whether to ignore all font related formatting styles, including:
* <ul> <li>font size;</li>
* <li>font family;</li>
* <li>font foreground/background color.</li></ul>
* @name CKEDITOR.config.pasteFromWordRemoveFontStyles
* @since 3.1
* @type Boolean
* @default true
* @example
* config.pasteFromWordRemoveFontStyles = false;
*/
/**
* Whether to transform MS Word outline numbered headings into lists.
* @name CKEDITOR.config.pasteFromWordNumberedHeadingToList
* @since 3.1
* @type Boolean
* @default false
* @example
* config.pasteFromWordNumberedHeadingToList = true;
*/
/**
* Whether to remove element styles that can't be managed with the editor. Note
* that this doesn't handle the font specific styles, which depends on the
* {@link CKEDITOR.config.pasteFromWordRemoveFontStyles} setting instead.
* @name CKEDITOR.config.pasteFromWordRemoveStyles
* @since 3.1
* @type Boolean
* @default true
* @example
* config.pasteFromWordRemoveStyles = false;
*/
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @fileOverview The "wysiwygarea" plugin. It registers the "wysiwyg" editing
* mode, which handles the main editing area space.
*/
(function()
{
// List of elements in which has no way to move editing focus outside.
var nonExitableElementNames = { table:1,pre:1 };
// Matching an empty paragraph at the end of document.
var emptyParagraphRegexp = /(^|<body\b[^>]*>)\s*<(p|div|address|h\d|center)[^>]*>\s*(?:<br[^>]*>| |\u00A0| )?\s*(:?<\/\2>)?\s*(?=$|<\/body>)/gi;
var notWhitespaceEval = CKEDITOR.dom.walker.whitespaces( true );
// Elements that could have empty new line around, including table, pre-formatted block, hr, page-break. (#6554)
function nonExitable( element )
{
return ( element.getName() in nonExitableElementNames )
|| element.isBlockBoundary() && CKEDITOR.dtd.$empty[ element.getName() ];
}
function checkReadOnly( selection )
{
if ( selection.getType() == CKEDITOR.SELECTION_ELEMENT )
return selection.getSelectedElement().isReadOnly();
else
return selection.getCommonAncestor().isReadOnly();
}
function onInsert( insertFunc )
{
return function( evt )
{
if ( this.mode == 'wysiwyg' )
{
this.focus();
var selection = this.getSelection();
if ( checkReadOnly( selection ) )
return;
this.fire( 'saveSnapshot' );
insertFunc.call( this, evt.data );
// Save snaps after the whole execution completed.
// This's a workaround for make DOM modification's happened after
// 'insertElement' to be included either, e.g. Form-based dialogs' 'commitContents'
// call.
CKEDITOR.tools.setTimeout( function()
{
this.fire( 'saveSnapshot' );
}, 0, this );
}
};
}
function doInsertHtml( data )
{
if ( this.dataProcessor )
data = this.dataProcessor.toHtml( data );
var selection = this.getSelection();
if ( CKEDITOR.env.ie )
{
var selIsLocked = selection.isLocked;
if ( selIsLocked )
selection.unlock();
var $sel = selection.getNative();
// Delete control selections to avoid IE bugs on pasteHTML.
if ( $sel.type == 'Control' )
$sel.clear();
else if ( selection.getType() == CKEDITOR.SELECTION_TEXT )
{
// Due to IE bugs on handling contenteditable=false blocks
// (#6005), we need to make some checks and eventually
// delete the selection first.
var range = selection.getRanges()[0],
endContainer = range && range.endContainer;
if ( endContainer &&
endContainer.type == CKEDITOR.NODE_ELEMENT &&
endContainer.getAttribute( 'contenteditable' ) == 'false' &&
range.checkBoundaryOfElement( endContainer, CKEDITOR.END ) )
{
range.setEndAfter( range.endContainer );
range.deleteContents();
}
}
try
{
$sel.createRange().pasteHTML( data );
}
catch (e) {}
if ( selIsLocked )
this.getSelection().lock();
}
else
this.document.$.execCommand( 'inserthtml', false, data );
// Webkit does not scroll to the cursor position after pasting (#5558)
if ( CKEDITOR.env.webkit )
{
selection = this.getSelection();
selection.scrollIntoView();
}
}
function doInsertText( text )
{
var selection = this.getSelection(),
mode = selection.getStartElement().hasAscendant( 'pre', true ) ?
CKEDITOR.ENTER_BR : this.config.enterMode,
isEnterBrMode = mode == CKEDITOR.ENTER_BR;
var html = CKEDITOR.tools.htmlEncode( text.replace( /\r\n|\r/g, '\n' ) );
// Convert leading and trailing whitespaces into
html = html.replace( /^[ \t]+|[ \t]+$/g, function( match, offset, s )
{
if ( match.length == 1 ) // one space, preserve it
return ' ';
else if ( !offset ) // beginning of block
return CKEDITOR.tools.repeat( ' ', match.length - 1 ) + ' ';
else // end of block
return ' ' + CKEDITOR.tools.repeat( ' ', match.length - 1 );
} );
// Convert subsequent whitespaces into
html = html.replace( /[ \t]{2,}/g, function ( match )
{
return CKEDITOR.tools.repeat( ' ', match.length - 1 ) + ' ';
} );
var paragraphTag = mode == CKEDITOR.ENTER_P ? 'p' : 'div';
// Two line-breaks create one paragraph.
if ( !isEnterBrMode )
{
html = html.replace( /(\n{2})([\s\S]*?)(?:$|\1)/g,
function( match, group1, text )
{
return '<'+paragraphTag + '>' + text + '</' + paragraphTag + '>';
});
}
// One <br> per line-break.
html = html.replace( /\n/g, '<br>' );
// Compensate padding <br> for non-IE.
if ( !( isEnterBrMode || CKEDITOR.env.ie ) )
{
html = html.replace( new RegExp( '<br>(?=</' + paragraphTag + '>)' ), function( match )
{
return CKEDITOR.tools.repeat( match, 2 );
} );
}
// Inline styles have to be inherited in Firefox.
if ( CKEDITOR.env.gecko || CKEDITOR.env.webkit )
{
var path = new CKEDITOR.dom.elementPath( selection.getStartElement() ),
context = [];
for ( var i = 0; i < path.elements.length; i++ )
{
var tag = path.elements[ i ].getName();
if ( tag in CKEDITOR.dtd.$inline )
context.unshift( path.elements[ i ].getOuterHtml().match( /^<.*?>/) );
else if ( tag in CKEDITOR.dtd.$block )
break;
}
// Reproduce the context by preceding the pasted HTML with opening inline tags.
html = context.join( '' ) + html;
}
doInsertHtml.call( this, html );
}
function doInsertElement( element )
{
var selection = this.getSelection(),
ranges = selection.getRanges(),
elementName = element.getName(),
isBlock = CKEDITOR.dtd.$block[ elementName ];
var selIsLocked = selection.isLocked;
if ( selIsLocked )
selection.unlock();
var range, clone, lastElement, bookmark;
for ( var i = ranges.length - 1 ; i >= 0 ; i-- )
{
range = ranges[ i ];
// Remove the original contents.
range.deleteContents();
clone = !i && element || element.clone( 1 );
// If we're inserting a block at dtd-violated position, split
// the parent blocks until we reach blockLimit.
var current, dtd;
if ( isBlock )
{
while ( ( current = range.getCommonAncestor( 0, 1 ) )
&& ( dtd = CKEDITOR.dtd[ current.getName() ] )
&& !( dtd && dtd [ elementName ] ) )
{
// Split up inline elements.
if ( current.getName() in CKEDITOR.dtd.span )
range.splitElement( current );
// If we're in an empty block which indicate a new paragraph,
// simply replace it with the inserting block.(#3664)
else if ( range.checkStartOfBlock()
&& range.checkEndOfBlock() )
{
range.setStartBefore( current );
range.collapse( true );
current.remove();
}
else
range.splitBlock();
}
}
// Insert the new node.
range.insertNode( clone );
// Save the last element reference so we can make the
// selection later.
if ( !lastElement )
lastElement = clone;
}
range.moveToPosition( lastElement, CKEDITOR.POSITION_AFTER_END );
// If we're inserting a block element immediatelly followed by
// another block element, the selection must move there. (#3100,#5436)
if ( isBlock )
{
var next = lastElement.getNext( notWhitespaceEval ),
nextName = next && next.type == CKEDITOR.NODE_ELEMENT && next.getName();
// Check if it's a block element that accepts text.
if ( nextName && CKEDITOR.dtd.$block[ nextName ] && CKEDITOR.dtd[ nextName ]['#'] )
range.moveToElementEditStart( next );
}
selection.selectRanges( [ range ] );
if ( selIsLocked )
this.getSelection().lock();
}
// DOM modification here should not bother dirty flag.(#4385)
function restoreDirty( editor )
{
if ( !editor.checkDirty() )
setTimeout( function(){ editor.resetDirty(); }, 0 );
}
var isNotWhitespace = CKEDITOR.dom.walker.whitespaces( true ),
isNotBookmark = CKEDITOR.dom.walker.bookmark( false, true );
function isNotEmpty( node )
{
return isNotWhitespace( node ) && isNotBookmark( node );
}
function isNbsp( node )
{
return node.type == CKEDITOR.NODE_TEXT
&& CKEDITOR.tools.trim( node.getText() ).match( /^(?: |\xa0)$/ );
}
function restoreSelection( selection )
{
if ( selection.isLocked )
{
selection.unlock();
setTimeout( function() { selection.lock(); }, 0 );
}
}
function isBlankParagraph( block )
{
return block.getOuterHtml().match( emptyParagraphRegexp );
}
isNotWhitespace = CKEDITOR.dom.walker.whitespaces( true );
// Gecko need a key event to 'wake up' the editing
// ability when document is empty.(#3864, #5781)
function activateEditing( editor )
{
var win = editor.window,
doc = editor.document,
body = editor.document.getBody(),
bodyChildsNum = body.getChildren().count();
if ( !bodyChildsNum || ( bodyChildsNum == 1&& body.getFirst().hasAttribute( '_moz_editor_bogus_node' ) ) )
{
restoreDirty( editor );
// Memorize scroll position to restore it later (#4472).
var hostDocument = editor.element.getDocument();
var hostDocumentElement = hostDocument.getDocumentElement();
var scrollTop = hostDocumentElement.$.scrollTop;
var scrollLeft = hostDocumentElement.$.scrollLeft;
// Simulating keyboard character input by dispatching a keydown of white-space text.
var keyEventSimulate = doc.$.createEvent( "KeyEvents" );
keyEventSimulate.initKeyEvent( 'keypress', true, true, win.$, false,
false, false, false, 0, 32 );
doc.$.dispatchEvent( keyEventSimulate );
if ( scrollTop != hostDocumentElement.$.scrollTop || scrollLeft != hostDocumentElement.$.scrollLeft )
hostDocument.getWindow().$.scrollTo( scrollLeft, scrollTop );
// Restore the original document status by placing the cursor before a bogus br created (#5021).
bodyChildsNum && body.getFirst().remove();
doc.getBody().appendBogus();
var nativeRange = new CKEDITOR.dom.range( doc );
nativeRange.setStartAt( body , CKEDITOR.POSITION_AFTER_START );
nativeRange.select();
}
}
/**
* Auto-fixing block-less content by wrapping paragraph (#3190), prevent
* non-exitable-block by padding extra br.(#3189)
*/
function onSelectionChangeFixBody( evt )
{
var editor = evt.editor,
path = evt.data.path,
blockLimit = path.blockLimit,
selection = evt.data.selection,
range = selection.getRanges()[0],
body = editor.document.getBody(),
enterMode = editor.config.enterMode;
CKEDITOR.env.gecko && activateEditing( editor );
// When enterMode set to block, we'll establing new paragraph only if we're
// selecting inline contents right under body. (#3657)
if ( enterMode != CKEDITOR.ENTER_BR
&& range.collapsed
&& blockLimit.getName() == 'body'
&& !path.block )
{
editor.fire( 'updateSnapshot' );
restoreDirty( editor );
CKEDITOR.env.ie && restoreSelection( selection );
var fixedBlock = range.fixBlock( true,
editor.config.enterMode == CKEDITOR.ENTER_DIV ? 'div' : 'p' );
// For IE, we should remove any filler node which was introduced before.
if ( CKEDITOR.env.ie )
{
var first = fixedBlock.getFirst( isNotEmpty );
first && isNbsp( first ) && first.remove();
}
// If the fixed block is actually blank and is already followed by an exitable blank
// block, we should revert the fix and move into the existed one. (#3684)
if ( isBlankParagraph( fixedBlock ) )
{
var element = fixedBlock.getNext( isNotWhitespace );
if ( element &&
element.type == CKEDITOR.NODE_ELEMENT &&
!nonExitable( element ) )
{
range.moveToElementEditStart( element );
fixedBlock.remove();
}
else
{
element = fixedBlock.getPrevious( isNotWhitespace );
if ( element &&
element.type == CKEDITOR.NODE_ELEMENT &&
!nonExitable( element ) )
{
range.moveToElementEditEnd( element );
fixedBlock.remove();
}
}
}
range.select();
// Notify non-IE that selection has changed.
if ( !CKEDITOR.env.ie )
editor.selectionChange();
}
// All browsers are incapable to moving cursor out of certain non-exitable
// blocks (e.g. table, list, pre) at the end of document, make this happen by
// place a bogus node there, which would be later removed by dataprocessor.
var walkerRange = new CKEDITOR.dom.range( editor.document ),
walker = new CKEDITOR.dom.walker( walkerRange );
walkerRange.selectNodeContents( body );
walker.evaluator = function( node )
{
return node.type == CKEDITOR.NODE_ELEMENT && ( node.getName() in nonExitableElementNames );
};
walker.guard = function( node, isMoveout )
{
return !( ( node.type == CKEDITOR.NODE_TEXT && isNotWhitespace( node ) ) || isMoveout );
};
if ( walker.previous() )
{
editor.fire( 'updateSnapshot' );
restoreDirty( editor );
CKEDITOR.env.ie && restoreSelection( selection );
var paddingBlock;
if ( enterMode != CKEDITOR.ENTER_BR )
paddingBlock = body.append( new CKEDITOR.dom.element( enterMode == CKEDITOR.ENTER_P ? 'p' : 'div' ) );
else
paddingBlock = body;
if ( !CKEDITOR.env.ie )
paddingBlock.appendBogus();
}
}
CKEDITOR.plugins.add( 'wysiwygarea',
{
requires : [ 'editingblock' ],
init : function( editor )
{
var fixForBody = ( editor.config.enterMode != CKEDITOR.ENTER_BR )
? editor.config.enterMode == CKEDITOR.ENTER_DIV ? 'div' : 'p' : false;
var frameLabel = editor.lang.editorTitle.replace( '%1', editor.name );
var contentDomReadyHandler;
editor.on( 'editingBlockReady', function()
{
var mainElement,
iframe,
isLoadingData,
isPendingFocus,
frameLoaded,
fireMode;
// Support for custom document.domain in IE.
var isCustomDomain = CKEDITOR.env.isCustomDomain();
// Creates the iframe that holds the editable document.
var createIFrame = function( data )
{
if ( iframe )
iframe.remove();
var src =
'document.open();' +
// The document domain must be set any time we
// call document.open().
( isCustomDomain ? ( 'document.domain="' + document.domain + '";' ) : '' ) +
'document.close();';
// With IE, the custom domain has to be taken care at first,
// for other browers, the 'src' attribute should be left empty to
// trigger iframe's 'load' event.
src =
CKEDITOR.env.air ?
'javascript:void(0)' :
CKEDITOR.env.ie ?
'javascript:void(function(){' + encodeURIComponent( src ) + '}())'
:
'';
iframe = CKEDITOR.dom.element.createFromHtml( '<iframe' +
' style="width:100%;height:100%"' +
' frameBorder="0"' +
' title="' + frameLabel + '"' +
' src="' + src + '"' +
' tabIndex="' + ( CKEDITOR.env.webkit? -1 : editor.tabIndex ) + '"' +
' allowTransparency="true"' +
'></iframe>' );
// Running inside of Firefox chrome the load event doesn't bubble like in a normal page (#5689)
if ( document.location.protocol == 'chrome:' )
CKEDITOR.event.useCapture = true;
// With FF, it's better to load the data on iframe.load. (#3894,#4058)
iframe.on( 'load', function( ev )
{
frameLoaded = 1;
ev.removeListener();
var doc = iframe.getFrameDocument();
doc.write( data );
CKEDITOR.env.air && contentDomReady( doc.getWindow().$ );
});
// Reset adjustment back to default (#5689)
if ( document.location.protocol == 'chrome:' )
CKEDITOR.event.useCapture = false;
// The container must be visible when creating the iframe in FF (#5956)
var element = editor.element,
isHidden = CKEDITOR.env.gecko && !element.isVisible(),
previousStyles = {};
if ( isHidden )
{
element.show();
previousStyles = {
position : element.getStyle( 'position' ),
top : element.getStyle( 'top' )
};
element.setStyles( { position : 'absolute', top : '-3000px' } );
}
mainElement.append( iframe );
if ( isHidden )
{
setTimeout( function()
{
element.hide();
element.setStyles( previousStyles );
}, 1000 );
}
};
// The script that launches the bootstrap logic on 'domReady', so the document
// is fully editable even before the editing iframe is fully loaded (#4455).
contentDomReadyHandler = CKEDITOR.tools.addFunction( contentDomReady );
var activationScript =
'<script id="cke_actscrpt" type="text/javascript" data-cke-temp="1">' +
( isCustomDomain ? ( 'document.domain="' + document.domain + '";' ) : '' ) +
'window.parent.CKEDITOR.tools.callFunction( ' + contentDomReadyHandler + ', window );' +
'</script>';
// Editing area bootstrap code.
function contentDomReady( domWindow )
{
if ( !frameLoaded )
return;
frameLoaded = 0;
editor.fire( 'ariaWidget', iframe );
var domDocument = domWindow.document,
body = domDocument.body;
// Remove this script from the DOM.
var script = domDocument.getElementById( "cke_actscrpt" );
script && script.parentNode.removeChild( script );
body.spellcheck = !editor.config.disableNativeSpellChecker;
if ( CKEDITOR.env.ie )
{
// Don't display the focus border.
body.hideFocus = true;
// Disable and re-enable the body to avoid IE from
// taking the editing focus at startup. (#141 / #523)
body.disabled = true;
body.contentEditable = true;
body.removeAttribute( 'disabled' );
}
else
{
// Avoid opening design mode in a frame window thread,
// which will cause host page scrolling.(#4397)
setTimeout( function()
{
// Prefer 'contentEditable' instead of 'designMode'. (#3593)
if ( CKEDITOR.env.gecko && CKEDITOR.env.version >= 10900
|| CKEDITOR.env.opera )
domDocument.$.body.contentEditable = true;
else if ( CKEDITOR.env.webkit )
domDocument.$.body.parentNode.contentEditable = true;
else
domDocument.$.designMode = 'on';
}, 0 );
}
CKEDITOR.env.gecko && CKEDITOR.tools.setTimeout( activateEditing, 0, null, editor );
domWindow = editor.window = new CKEDITOR.dom.window( domWindow );
domDocument = editor.document = new CKEDITOR.dom.document( domDocument );
domDocument.on( 'dblclick', function( evt )
{
var element = evt.data.getTarget(),
data = { element : element, dialog : '' };
editor.fire( 'doubleclick', data );
data.dialog && editor.openDialog( data.dialog );
});
// Gecko/Webkit need some help when selecting control type elements. (#3448)
if ( !( CKEDITOR.env.ie || CKEDITOR.env.opera ) )
{
domDocument.on( 'mousedown', function( ev )
{
var control = ev.data.getTarget();
if ( control.is( 'img', 'hr', 'input', 'textarea', 'select' ) )
editor.getSelection().selectElement( control );
} );
}
if ( CKEDITOR.env.gecko )
{
domDocument.on( 'mouseup', function( ev )
{
if ( ev.data.$.button == 2 )
{
var target = ev.data.getTarget();
// Prevent right click from selecting an empty block even
// when selection is anchored inside it. (#5845)
if ( !target.getOuterHtml().replace( emptyParagraphRegexp, '' ) )
{
var range = new CKEDITOR.dom.range( domDocument );
range.moveToElementEditStart( target );
range.select( true );
}
}
} );
}
// Prevent the browser opening links in read-only blocks. (#6032)
domDocument.on( 'click', function( ev )
{
ev = ev.data;
if ( ev.getTarget().is( 'a' ) && ev.$.button != 2 )
ev.preventDefault();
});
// Webkit: avoid from editing form control elements content.
if ( CKEDITOR.env.webkit )
{
// Prevent from tick checkbox/radiobox/select
domDocument.on( 'click', function( ev )
{
if ( ev.data.getTarget().is( 'input', 'select' ) )
ev.data.preventDefault();
} );
// Prevent from editig textfield/textarea value.
domDocument.on( 'mouseup', function( ev )
{
if ( ev.data.getTarget().is( 'input', 'textarea' ) )
ev.data.preventDefault();
} );
}
// IE standard compliant in editing frame doesn't focus the editor when
// clicking outside actual content, manually apply the focus. (#1659)
if ( CKEDITOR.env.ie
&& domDocument.$.compatMode == 'CSS1Compat'
|| CKEDITOR.env.gecko
|| CKEDITOR.env.opera )
{
var htmlElement = domDocument.getDocumentElement();
htmlElement.on( 'mousedown', function( evt )
{
// Setting focus directly on editor doesn't work, we
// have to use here a temporary element to 'redirect'
// the focus.
if ( evt.data.getTarget().equals( htmlElement ) )
{
if ( CKEDITOR.env.gecko && CKEDITOR.env.version >= 10900 )
blinkCursor();
focusGrabber.focus();
}
} );
}
domWindow.on( 'blur', function()
{
editor.focusManager.blur();
});
var wasFocused;
domWindow.on( 'focus', function()
{
var doc = editor.document;
if ( CKEDITOR.env.gecko && CKEDITOR.env.version >= 10900 )
blinkCursor();
else if ( CKEDITOR.env.opera )
doc.getBody().focus();
// Webkit needs focus for the first time on the HTML element. (#6153)
else if ( CKEDITOR.env.webkit )
{
if ( !wasFocused )
{
editor.document.getDocumentElement().focus();
wasFocused = 1;
}
}
editor.focusManager.focus();
});
var keystrokeHandler = editor.keystrokeHandler;
if ( keystrokeHandler )
keystrokeHandler.attach( domDocument );
if ( CKEDITOR.env.ie )
{
domDocument.getDocumentElement().addClass( domDocument.$.compatMode );
// Override keystrokes which should have deletion behavior
// on control types in IE . (#4047)
domDocument.on( 'keydown', function( evt )
{
var keyCode = evt.data.getKeystroke();
// Backspace OR Delete.
if ( keyCode in { 8 : 1, 46 : 1 } )
{
var sel = editor.getSelection(),
control = sel.getSelectedElement();
if ( control )
{
// Make undo snapshot.
editor.fire( 'saveSnapshot' );
// Delete any element that 'hasLayout' (e.g. hr,table) in IE8 will
// break up the selection, safely manage it here. (#4795)
var bookmark = sel.getRanges()[ 0 ].createBookmark();
// Remove the control manually.
control.remove();
sel.selectBookmarks( [ bookmark ] );
editor.fire( 'saveSnapshot' );
evt.data.preventDefault();
}
}
} );
// PageUp/PageDown scrolling is broken in document
// with standard doctype, manually fix it. (#4736)
if ( domDocument.$.compatMode == 'CSS1Compat' )
{
var pageUpDownKeys = { 33 : 1, 34 : 1 };
domDocument.on( 'keydown', function( evt )
{
if ( evt.data.getKeystroke() in pageUpDownKeys )
{
setTimeout( function ()
{
editor.getSelection().scrollIntoView();
}, 0 );
}
} );
}
}
// Adds the document body as a context menu target.
if ( editor.contextMenu )
editor.contextMenu.addTarget( domDocument, editor.config.browserContextMenuOnCtrl !== false );
setTimeout( function()
{
editor.fire( 'contentDom' );
if ( fireMode )
{
editor.mode = 'wysiwyg';
editor.fire( 'mode' );
fireMode = false;
}
isLoadingData = false;
if ( isPendingFocus )
{
editor.focus();
isPendingFocus = false;
}
setTimeout( function()
{
editor.fire( 'dataReady' );
}, 0 );
// IE, Opera and Safari may not support it and throw errors.
try { editor.document.$.execCommand( 'enableObjectResizing', false, !editor.config.disableObjectResizing ) ; } catch(e) {}
try { editor.document.$.execCommand( 'enableInlineTableEditing', false, !editor.config.disableNativeTableHandles ) ; } catch(e) {}
/*
* IE BUG: IE might have rendered the iframe with invisible contents.
* (#3623). Push some inconsequential CSS style changes to force IE to
* refresh it.
*
* Also, for some unknown reasons, short timeouts (e.g. 100ms) do not
* fix the problem. :(
*/
if ( CKEDITOR.env.ie )
{
setTimeout( function()
{
if ( editor.document )
{
var $body = editor.document.$.body;
$body.runtimeStyle.marginBottom = '0px';
$body.runtimeStyle.marginBottom = '';
}
}, 1000 );
}
},
0 );
}
editor.addMode( 'wysiwyg',
{
load : function( holderElement, data, isSnapshot )
{
mainElement = holderElement;
if ( CKEDITOR.env.ie && CKEDITOR.env.quirks )
holderElement.setStyle( 'position', 'relative' );
// The editor data "may be dirty" after this
// point.
editor.mayBeDirty = true;
fireMode = true;
if ( isSnapshot )
this.loadSnapshotData( data );
else
this.loadData( data );
},
loadData : function( data )
{
isLoadingData = true;
var config = editor.config,
fullPage = config.fullPage,
docType = config.docType;
// Build the additional stuff to be included into <head>.
var headExtra =
'<style type="text/css" data-cke-temp="1">' +
editor._.styles.join( '\n' ) +
'</style>';
!fullPage && ( headExtra =
CKEDITOR.tools.buildStyleHtml( editor.config.contentsCss ) +
headExtra );
var baseTag = config.baseHref ? '<base href="' + config.baseHref + '" data-cke-temp="1" />' : '';
if ( fullPage )
{
// Search and sweep out the doctype declaration.
data = data.replace( /<!DOCTYPE[^>]*>/i, function( match )
{
editor.docType = docType = match;
return '';
});
}
// Get the HTML version of the data.
if ( editor.dataProcessor )
data = editor.dataProcessor.toHtml( data, fixForBody );
if ( fullPage )
{
// Check if the <body> tag is available.
if ( !(/<body[\s|>]/).test( data ) )
data = '<body>' + data;
// Check if the <html> tag is available.
if ( !(/<html[\s|>]/).test( data ) )
data = '<html>' + data + '</html>';
// Check if the <head> tag is available.
if ( !(/<head[\s|>]/).test( data ) )
data = data.replace( /<html[^>]*>/, '$&<head><title></title></head>' ) ;
else if ( !(/<title[\s|>]/).test( data ) )
data = data.replace( /<head[^>]*>/, '$&<title></title>' ) ;
// The base must be the first tag in the HEAD, e.g. to get relative
// links on styles.
baseTag && ( data = data.replace( /<head>/, '$&' + baseTag ) );
// Inject the extra stuff into <head>.
// Attention: do not change it before testing it well. (V2)
// This is tricky... if the head ends with <meta ... content type>,
// Firefox will break. But, it works if we place our extra stuff as
// the last elements in the HEAD.
data = data.replace( /<\/head\s*>/, headExtra + '$&' );
// Add the DOCTYPE back to it.
data = docType + data;
}
else
{
data =
config.docType +
'<html dir="' + config.contentsLangDirection + '"' +
' lang="' + ( config.contentsLanguage || editor.langCode ) + '">' +
'<head>' +
'<title>' + frameLabel + '</title>' +
baseTag +
headExtra +
'</head>' +
'<body' + ( config.bodyId ? ' id="' + config.bodyId + '"' : '' ) +
( config.bodyClass ? ' class="' + config.bodyClass + '"' : '' ) +
'>' +
data +
'</html>';
}
data += activationScript;
// The iframe is recreated on each call of setData, so we need to clear DOM objects
this.onDispose();
createIFrame( data );
},
getData : function()
{
var config = editor.config,
fullPage = config.fullPage,
docType = fullPage && editor.docType,
doc = iframe.getFrameDocument();
var data = fullPage
? doc.getDocumentElement().getOuterHtml()
: doc.getBody().getHtml();
if ( editor.dataProcessor )
data = editor.dataProcessor.toDataFormat( data, fixForBody );
// Reset empty if the document contains only one empty paragraph.
if ( config.ignoreEmptyParagraph )
data = data.replace( emptyParagraphRegexp, function( match, lookback ) { return lookback; } );
if ( docType )
data = docType + '\n' + data;
return data;
},
getSnapshotData : function()
{
return iframe.getFrameDocument().getBody().getHtml();
},
loadSnapshotData : function( data )
{
iframe.getFrameDocument().getBody().setHtml( data );
},
onDispose : function()
{
if ( !editor.document )
return;
editor.document.getDocumentElement().clearCustomData();
editor.document.getBody().clearCustomData();
editor.window.clearCustomData();
editor.document.clearCustomData();
iframe.clearCustomData();
/*
* IE BUG: When destroying editor DOM with the selection remains inside
* editing area would break IE7/8's selection system, we have to put the editing
* iframe offline first. (#3812 and #5441)
*/
iframe.remove();
},
unload : function( holderElement )
{
this.onDispose();
editor.window = editor.document = iframe = mainElement = isPendingFocus = null;
editor.fire( 'contentDomUnload' );
},
focus : function()
{
var win = editor.window;
if ( isLoadingData )
isPendingFocus = true;
// Temporary solution caused by #6025, supposed be unified by #6154.
else if ( CKEDITOR.env.opera && editor.document )
{
// Required for Opera when switching focus
// from another iframe, e.g. panels. (#6444)
var iframe = editor.window.$.frameElement;
iframe.blur(), iframe.focus();
editor.document.getBody().focus();
editor.selectionChange();
}
else if ( !CKEDITOR.env.opera && win )
{
// AIR needs a while to focus when moving from a link.
CKEDITOR.env.air ? setTimeout( function () { win.focus(); }, 0 ) : win.focus();
editor.selectionChange();
}
}
});
editor.on( 'insertHtml', onInsert( doInsertHtml ) , null, null, 20 );
editor.on( 'insertElement', onInsert( doInsertElement ), null, null, 20 );
editor.on( 'insertText', onInsert( doInsertText ), null, null, 20 );
// Auto fixing on some document structure weakness to enhance usabilities. (#3190 and #3189)
editor.on( 'selectionChange', onSelectionChangeFixBody, null, null, 1 );
});
var titleBackup;
// Setting voice label as window title, backup the original one
// and restore it before running into use.
editor.on( 'contentDom', function()
{
var title = editor.document.getElementsByTag( 'title' ).getItem( 0 );
title.data( 'cke-title', editor.document.$.title );
editor.document.$.title = frameLabel;
});
// IE8 stricts mode doesn't have 'contentEditable' in effect
// on element unless it has layout. (#5562)
if ( CKEDITOR.env.ie8Compat )
{
editor.addCss( 'html.CSS1Compat [contenteditable=false]{ min-height:0 !important;}' );
var selectors = [];
for ( var tag in CKEDITOR.dtd.$removeEmpty )
selectors.push( 'html.CSS1Compat ' + tag + '[contenteditable=false]' );
editor.addCss( selectors.join( ',' ) + '{ display:inline-block;}' );
}
// Set the HTML style to 100% to have the text cursor in affect (#6341)
else if ( CKEDITOR.env.gecko )
editor.addCss( 'html { height: 100% !important; }' );
// Switch on design mode for a short while and close it after then.
function blinkCursor( retry )
{
CKEDITOR.tools.tryThese(
function()
{
editor.document.$.designMode = 'on';
setTimeout( function()
{
editor.document.$.designMode = 'off';
if ( CKEDITOR.currentInstance == editor )
editor.document.getBody().focus();
}, 50 );
},
function()
{
// The above call is known to fail when parent DOM
// tree layout changes may break design mode. (#5782)
// Refresh the 'contentEditable' is a cue to this.
editor.document.$.designMode = 'off';
var body = editor.document.getBody();
body.setAttribute( 'contentEditable', false );
body.setAttribute( 'contentEditable', true );
// Try it again once..
!retry && blinkCursor( 1 );
});
}
// Create an invisible element to grab focus.
if ( CKEDITOR.env.gecko || CKEDITOR.env.ie || CKEDITOR.env.opera )
{
var focusGrabber;
editor.on( 'uiReady', function()
{
focusGrabber = editor.container.append( CKEDITOR.dom.element.createFromHtml(
// Use 'span' instead of anything else to fly under the screen-reader radar. (#5049)
'<span tabindex="-1" style="position:absolute;" role="presentation"></span>' ) );
focusGrabber.on( 'focus', function()
{
editor.focus();
} );
} );
editor.on( 'destroy', function()
{
CKEDITOR.tools.removeFunction( contentDomReadyHandler );
focusGrabber.clearCustomData();
} );
}
// Disable form elements editing mode provided by some browers. (#5746)
editor.on( 'insertElement', function ( evt )
{
var element = evt.data;
if ( element.type == CKEDITOR.NODE_ELEMENT
&& ( element.is( 'input' ) || element.is( 'textarea' ) ) )
{
if ( !element.isReadOnly() )
{
element.setAttribute( 'contentEditable', false );
// We should flag that the element was locked by our code so
// it'll be editable by the editor functions (#6046).
element.setCustomData( '_cke_notReadOnly', 1 );
}
}
});
}
});
// Fixing Firefox 'Back-Forward Cache' break design mode. (#4514)
if ( CKEDITOR.env.gecko )
{
(function()
{
var body = document.body;
if ( !body )
window.addEventListener( 'load', arguments.callee, false );
else
{
var currentHandler = body.getAttribute( 'onpageshow' );
body.setAttribute( 'onpageshow', ( currentHandler ? currentHandler + ';' : '') +
'event.persisted && (function(){' +
'var allInstances = CKEDITOR.instances, editor, doc;' +
'for ( var i in allInstances )' +
'{' +
' editor = allInstances[ i ];' +
' doc = editor.document;' +
' if ( doc )' +
' {' +
' doc.$.designMode = "off";' +
' doc.$.designMode = "on";' +
' }' +
'}' +
'})();' );
}
} )();
}
})();
/**
* Disables the ability of resize objects (image and tables) in the editing
* area.
* @type Boolean
* @default false
* @example
* config.disableObjectResizing = true;
*/
CKEDITOR.config.disableObjectResizing = false;
/**
* Disables the "table tools" offered natively by the browser (currently
* Firefox only) to make quick table editing operations, like adding or
* deleting rows and columns.
* @type Boolean
* @default true
* @example
* config.disableNativeTableHandles = false;
*/
CKEDITOR.config.disableNativeTableHandles = true;
/**
* Disables the built-in spell checker while typing natively available in the
* browser (currently Firefox and Safari only).<br /><br />
*
* Even if word suggestions will not appear in the CKEditor context menu, this
* feature is useful to help quickly identifying misspelled words.<br /><br />
*
* This setting is currently compatible with Firefox only due to limitations in
* other browsers.
* @type Boolean
* @default true
* @example
* config.disableNativeSpellChecker = false;
*/
CKEDITOR.config.disableNativeSpellChecker = true;
/**
* Whether the editor must output an empty value ("") if it's contents is made
* by an empty paragraph only.
* @type Boolean
* @default true
* @example
* config.ignoreEmptyParagraph = false;
*/
CKEDITOR.config.ignoreEmptyParagraph = true;
/**
* Fired when data is loaded and ready for retrieval in an editor instance.
* @name CKEDITOR.editor#dataReady
* @event
*/
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
(function()
{
CKEDITOR.plugins.add( 'stylescombo',
{
requires : [ 'richcombo', 'styles' ],
init : function( editor )
{
var config = editor.config,
lang = editor.lang.stylesCombo,
styles = {},
stylesList = [];
function loadStylesSet( callback )
{
editor.getStylesSet( function( stylesDefinitions )
{
if ( !stylesList.length )
{
var style,
styleName;
// Put all styles into an Array.
for ( var i = 0, count = stylesDefinitions.length ; i < count ; i++ )
{
var styleDefinition = stylesDefinitions[ i ];
styleName = styleDefinition.name;
style = styles[ styleName ] = new CKEDITOR.style( styleDefinition );
style._name = styleName;
style._.enterMode = config.enterMode;
stylesList.push( style );
}
// Sorts the Array, so the styles get grouped by type.
stylesList.sort( sortStyles );
}
callback && callback();
});
}
editor.ui.addRichCombo( 'Styles',
{
label : lang.label,
title : lang.panelTitle,
className : 'cke_styles',
panel :
{
css : editor.skin.editor.css.concat( config.contentsCss ),
multiSelect : true,
attributes : { 'aria-label' : lang.panelTitle }
},
init : function()
{
var combo = this;
loadStylesSet( function()
{
var style, styleName;
// Loop over the Array, adding all items to the
// combo.
var lastType;
for ( var i = 0, count = stylesList.length ; i < count ; i++ )
{
style = stylesList[ i ];
styleName = style._name;
var type = style.type;
if ( type != lastType )
{
combo.startGroup( lang[ 'panelTitle' + String( type ) ] );
lastType = type;
}
combo.add(
styleName,
style.type == CKEDITOR.STYLE_OBJECT ? styleName : style.buildPreview(),
styleName );
}
combo.commit();
combo.onOpen();
});
},
onClick : function( value )
{
editor.focus();
editor.fire( 'saveSnapshot' );
var style = styles[ value ],
selection = editor.getSelection();
var elementPath = new CKEDITOR.dom.elementPath( selection.getStartElement() );
if ( style.type == CKEDITOR.STYLE_INLINE && style.checkActive( elementPath ) )
style.remove( editor.document );
else if ( style.type == CKEDITOR.STYLE_OBJECT && style.checkActive( elementPath ) )
style.remove( editor.document );
else
style.apply( editor.document );
editor.fire( 'saveSnapshot' );
},
onRender : function()
{
editor.on( 'selectionChange', function( ev )
{
var currentValue = this.getValue();
var elementPath = ev.data.path,
elements = elementPath.elements;
// For each element into the elements path.
for ( var i = 0, count = elements.length, element ; i < count ; i++ )
{
element = elements[i];
// Check if the element is removable by any of
// the styles.
for ( var value in styles )
{
if ( styles[ value ].checkElementRemovable( element, true ) )
{
if ( value != currentValue )
this.setValue( value );
return;
}
}
}
// If no styles match, just empty it.
this.setValue( '' );
},
this);
},
onOpen : function()
{
if ( CKEDITOR.env.ie || CKEDITOR.env.webkit )
editor.focus();
var selection = editor.getSelection(),
element = selection.getSelectedElement(),
elementPath = new CKEDITOR.dom.elementPath( element || selection.getStartElement() );
var counter = [ 0, 0, 0, 0 ];
this.showAll();
this.unmarkAll();
for ( var name in styles )
{
var style = styles[ name ],
type = style.type;
if ( style.checkActive( elementPath ) )
this.mark( name );
else if ( type == CKEDITOR.STYLE_OBJECT && !style.checkApplicable( elementPath ) )
{
this.hideItem( name );
counter[ type ]--;
}
counter[ type ]++;
}
if ( !counter[ CKEDITOR.STYLE_BLOCK ] )
this.hideGroup( lang[ 'panelTitle' + String( CKEDITOR.STYLE_BLOCK ) ] );
if ( !counter[ CKEDITOR.STYLE_INLINE ] )
this.hideGroup( lang[ 'panelTitle' + String( CKEDITOR.STYLE_INLINE ) ] );
if ( !counter[ CKEDITOR.STYLE_OBJECT ] )
this.hideGroup( lang[ 'panelTitle' + String( CKEDITOR.STYLE_OBJECT ) ] );
}
});
editor.on( 'instanceReady', function() { loadStylesSet(); } );
}
});
function sortStyles( styleA, styleB )
{
var typeA = styleA.type,
typeB = styleB.type;
return typeA == typeB ? 0 :
typeA == CKEDITOR.STYLE_OBJECT ? -1 :
typeB == CKEDITOR.STYLE_OBJECT ? 1 :
typeB == CKEDITOR.STYLE_BLOCK ? 1 :
-1;
}
})();
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.add( 'find',
{
init : function( editor )
{
var forms = CKEDITOR.plugins.find;
editor.ui.addButton( 'Find',
{
label : editor.lang.findAndReplace.find,
command : 'find'
});
var findCommand = editor.addCommand( 'find', new CKEDITOR.dialogCommand( 'find' ) );
findCommand.canUndo = false;
editor.ui.addButton( 'Replace',
{
label : editor.lang.findAndReplace.replace,
command : 'replace'
});
var replaceCommand = editor.addCommand( 'replace', new CKEDITOR.dialogCommand( 'replace' ) );
replaceCommand.canUndo = false;
CKEDITOR.dialog.add( 'find', this.path + 'dialogs/find.js' );
CKEDITOR.dialog.add( 'replace', this.path + 'dialogs/find.js' );
},
requires : [ 'styles' ]
} );
/**
* Defines the style to be used to highlight results with the find dialog.
* @type Object
* @default { element : 'span', styles : { 'background-color' : '#004', 'color' : '#fff' } }
* @example
* // Highlight search results with blue on yellow.
* config.find_highlight =
* {
* element : 'span',
* styles : { 'background-color' : '#ff0', 'color' : '#00f' }
* };
*/
CKEDITOR.config.find_highlight = { element : 'span', styles : { 'background-color' : '#004', 'color' : '#fff' } };
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
(function()
{
var isReplace;
function findEvaluator( node )
{
return node.type == CKEDITOR.NODE_TEXT && node.getLength() > 0 && ( !isReplace || !node.isReadOnly() );
}
/**
* Elements which break characters been considered as sequence.
*/
function nonCharactersBoundary( node )
{
return !( node.type == CKEDITOR.NODE_ELEMENT && node.isBlockBoundary(
CKEDITOR.tools.extend( {}, CKEDITOR.dtd.$empty, CKEDITOR.dtd.$nonEditable ) ) );
}
/**
* Get the cursor object which represent both current character and it's dom
* position thing.
*/
var cursorStep = function()
{
return {
textNode : this.textNode,
offset : this.offset,
character : this.textNode ?
this.textNode.getText().charAt( this.offset ) : null,
hitMatchBoundary : this._.matchBoundary
};
};
var pages = [ 'find', 'replace' ],
fieldsMapping = [
[ 'txtFindFind', 'txtFindReplace' ],
[ 'txtFindCaseChk', 'txtReplaceCaseChk' ],
[ 'txtFindWordChk', 'txtReplaceWordChk' ],
[ 'txtFindCyclic', 'txtReplaceCyclic' ] ];
/**
* Synchronize corresponding filed values between 'replace' and 'find' pages.
* @param {String} currentPageId The page id which receive values.
*/
function syncFieldsBetweenTabs( currentPageId )
{
var sourceIndex, targetIndex,
sourceField, targetField;
sourceIndex = currentPageId === 'find' ? 1 : 0;
targetIndex = 1 - sourceIndex;
var i, l = fieldsMapping.length;
for ( i = 0 ; i < l ; i++ )
{
sourceField = this.getContentElement( pages[ sourceIndex ],
fieldsMapping[ i ][ sourceIndex ] );
targetField = this.getContentElement( pages[ targetIndex ],
fieldsMapping[ i ][ targetIndex ] );
targetField.setValue( sourceField.getValue() );
}
}
var findDialog = function( editor, startupPage )
{
// Style object for highlights: (#5018)
// 1. Defined as full match style to avoid compromising ordinary text color styles.
// 2. Must be apply onto inner-most text to avoid conflicting with ordinary text color styles visually.
var highlightStyle = new CKEDITOR.style( CKEDITOR.tools.extend( { fullMatch : true, childRule : function(){ return 0; } },
editor.config.find_highlight ) );
/**
* Iterator which walk through the specified range char by char. By
* default the walking will not stop at the character boundaries, until
* the end of the range is encountered.
* @param { CKEDITOR.dom.range } range
* @param {Boolean} matchWord Whether the walking will stop at character boundary.
*/
var characterWalker = function( range , matchWord )
{
var self = this;
var walker =
new CKEDITOR.dom.walker( range );
walker.guard = matchWord ? nonCharactersBoundary : function( node )
{
!nonCharactersBoundary( node ) && ( self._.matchBoundary = true );
};
walker[ 'evaluator' ] = findEvaluator;
walker.breakOnFalse = 1;
if ( range.startContainer.type == CKEDITOR.NODE_TEXT )
{
this.textNode = range.startContainer;
this.offset = range.startOffset - 1;
}
this._ = {
matchWord : matchWord,
walker : walker,
matchBoundary : false
};
};
characterWalker.prototype = {
next : function()
{
return this.move();
},
back : function()
{
return this.move( true );
},
move : function( rtl )
{
var currentTextNode = this.textNode;
// Already at the end of document, no more character available.
if ( currentTextNode === null )
return cursorStep.call( this );
this._.matchBoundary = false;
// There are more characters in the text node, step forward.
if ( currentTextNode
&& rtl
&& this.offset > 0 )
{
this.offset--;
return cursorStep.call( this );
}
else if ( currentTextNode
&& this.offset < currentTextNode.getLength() - 1 )
{
this.offset++;
return cursorStep.call( this );
}
else
{
currentTextNode = null;
// At the end of the text node, walking foward for the next.
while ( !currentTextNode )
{
currentTextNode =
this._.walker[ rtl ? 'previous' : 'next' ].call( this._.walker );
// Stop searching if we're need full word match OR
// already reach document end.
if ( this._.matchWord && !currentTextNode
|| this._.walker._.end )
break;
}
// Found a fresh text node.
this.textNode = currentTextNode;
if ( currentTextNode )
this.offset = rtl ? currentTextNode.getLength() - 1 : 0;
else
this.offset = 0;
}
return cursorStep.call( this );
}
};
/**
* A range of cursors which represent a trunk of characters which try to
* match, it has the same length as the pattern string.
*/
var characterRange = function( characterWalker, rangeLength )
{
this._ = {
walker : characterWalker,
cursors : [],
rangeLength : rangeLength,
highlightRange : null,
isMatched : 0
};
};
characterRange.prototype = {
/**
* Translate this range to {@link CKEDITOR.dom.range}
*/
toDomRange : function()
{
var range = new CKEDITOR.dom.range( editor.document );
var cursors = this._.cursors;
if ( cursors.length < 1 )
{
var textNode = this._.walker.textNode;
if ( textNode )
range.setStartAfter( textNode );
else
return null;
}
else
{
var first = cursors[0],
last = cursors[ cursors.length - 1 ];
range.setStart( first.textNode, first.offset );
range.setEnd( last.textNode, last.offset + 1 );
}
return range;
},
/**
* Reflect the latest changes from dom range.
*/
updateFromDomRange : function( domRange )
{
var cursor,
walker = new characterWalker( domRange );
this._.cursors = [];
do
{
cursor = walker.next();
if ( cursor.character )
this._.cursors.push( cursor );
}
while ( cursor.character );
this._.rangeLength = this._.cursors.length;
},
setMatched : function()
{
this._.isMatched = true;
},
clearMatched : function()
{
this._.isMatched = false;
},
isMatched : function()
{
return this._.isMatched;
},
/**
* Hightlight the current matched chunk of text.
*/
highlight : function()
{
// Do not apply if nothing is found.
if ( this._.cursors.length < 1 )
return;
// Remove the previous highlight if there's one.
if ( this._.highlightRange )
this.removeHighlight();
// Apply the highlight.
var range = this.toDomRange(),
bookmark = range.createBookmark();
highlightStyle.applyToRange( range );
range.moveToBookmark( bookmark );
this._.highlightRange = range;
// Scroll the editor to the highlighted area.
var element = range.startContainer;
if ( element.type != CKEDITOR.NODE_ELEMENT )
element = element.getParent();
element.scrollIntoView();
// Update the character cursors.
this.updateFromDomRange( range );
},
/**
* Remove highlighted find result.
*/
removeHighlight : function()
{
if ( !this._.highlightRange )
return;
var bookmark = this._.highlightRange.createBookmark();
highlightStyle.removeFromRange( this._.highlightRange );
this._.highlightRange.moveToBookmark( bookmark );
this.updateFromDomRange( this._.highlightRange );
this._.highlightRange = null;
},
isReadOnly : function()
{
if ( !this._.highlightRange )
return 0;
return this._.highlightRange.startContainer.isReadOnly();
},
moveBack : function()
{
var retval = this._.walker.back(),
cursors = this._.cursors;
if ( retval.hitMatchBoundary )
this._.cursors = cursors = [];
cursors.unshift( retval );
if ( cursors.length > this._.rangeLength )
cursors.pop();
return retval;
},
moveNext : function()
{
var retval = this._.walker.next(),
cursors = this._.cursors;
// Clear the cursors queue if we've crossed a match boundary.
if ( retval.hitMatchBoundary )
this._.cursors = cursors = [];
cursors.push( retval );
if ( cursors.length > this._.rangeLength )
cursors.shift();
return retval;
},
getEndCharacter : function()
{
var cursors = this._.cursors;
if ( cursors.length < 1 )
return null;
return cursors[ cursors.length - 1 ].character;
},
getNextCharacterRange : function( maxLength )
{
var lastCursor,
nextRangeWalker,
cursors = this._.cursors;
if ( ( lastCursor = cursors[ cursors.length - 1 ] ) && lastCursor.textNode )
nextRangeWalker = new characterWalker( getRangeAfterCursor( lastCursor ) );
// In case it's an empty range (no cursors), figure out next range from walker (#4951).
else
nextRangeWalker = this._.walker;
return new characterRange( nextRangeWalker, maxLength );
},
getCursors : function()
{
return this._.cursors;
}
};
// The remaining document range after the character cursor.
function getRangeAfterCursor( cursor , inclusive )
{
var range = new CKEDITOR.dom.range();
range.setStart( cursor.textNode,
( inclusive ? cursor.offset : cursor.offset + 1 ) );
range.setEndAt( editor.document.getBody(),
CKEDITOR.POSITION_BEFORE_END );
return range;
}
// The document range before the character cursor.
function getRangeBeforeCursor( cursor )
{
var range = new CKEDITOR.dom.range();
range.setStartAt( editor.document.getBody(),
CKEDITOR.POSITION_AFTER_START );
range.setEnd( cursor.textNode, cursor.offset );
return range;
}
var KMP_NOMATCH = 0,
KMP_ADVANCED = 1,
KMP_MATCHED = 2;
/**
* Examination the occurrence of a word which implement KMP algorithm.
*/
var kmpMatcher = function( pattern, ignoreCase )
{
var overlap = [ -1 ];
if ( ignoreCase )
pattern = pattern.toLowerCase();
for ( var i = 0 ; i < pattern.length ; i++ )
{
overlap.push( overlap[i] + 1 );
while ( overlap[ i + 1 ] > 0
&& pattern.charAt( i ) != pattern
.charAt( overlap[ i + 1 ] - 1 ) )
overlap[ i + 1 ] = overlap[ overlap[ i + 1 ] - 1 ] + 1;
}
this._ = {
overlap : overlap,
state : 0,
ignoreCase : !!ignoreCase,
pattern : pattern
};
};
kmpMatcher.prototype =
{
feedCharacter : function( c )
{
if ( this._.ignoreCase )
c = c.toLowerCase();
while ( true )
{
if ( c == this._.pattern.charAt( this._.state ) )
{
this._.state++;
if ( this._.state == this._.pattern.length )
{
this._.state = 0;
return KMP_MATCHED;
}
return KMP_ADVANCED;
}
else if ( !this._.state )
return KMP_NOMATCH;
else
this._.state = this._.overlap[ this._.state ];
}
return null;
},
reset : function()
{
this._.state = 0;
}
};
var wordSeparatorRegex =
/[.,"'?!;: \u0085\u00a0\u1680\u280e\u2028\u2029\u202f\u205f\u3000]/;
var isWordSeparator = function( c )
{
if ( !c )
return true;
var code = c.charCodeAt( 0 );
return ( code >= 9 && code <= 0xd )
|| ( code >= 0x2000 && code <= 0x200a )
|| wordSeparatorRegex.test( c );
};
var finder = {
searchRange : null,
matchRange : null,
find : function( pattern, matchCase, matchWord, matchCyclic, highlightMatched, cyclicRerun )
{
if ( !this.matchRange )
this.matchRange =
new characterRange(
new characterWalker( this.searchRange ),
pattern.length );
else
{
this.matchRange.removeHighlight();
this.matchRange = this.matchRange.getNextCharacterRange( pattern.length );
}
var matcher = new kmpMatcher( pattern, !matchCase ),
matchState = KMP_NOMATCH,
character = '%';
while ( character !== null )
{
this.matchRange.moveNext();
while ( ( character = this.matchRange.getEndCharacter() ) )
{
matchState = matcher.feedCharacter( character );
if ( matchState == KMP_MATCHED )
break;
if ( this.matchRange.moveNext().hitMatchBoundary )
matcher.reset();
}
if ( matchState == KMP_MATCHED )
{
if ( matchWord )
{
var cursors = this.matchRange.getCursors(),
tail = cursors[ cursors.length - 1 ],
head = cursors[ 0 ];
var headWalker = new characterWalker( getRangeBeforeCursor( head ), true ),
tailWalker = new characterWalker( getRangeAfterCursor( tail ), true );
if ( ! ( isWordSeparator( headWalker.back().character )
&& isWordSeparator( tailWalker.next().character ) ) )
continue;
}
this.matchRange.setMatched();
if ( highlightMatched !== false )
this.matchRange.highlight();
return true;
}
}
this.matchRange.clearMatched();
this.matchRange.removeHighlight();
// Clear current session and restart with the default search
// range.
// Re-run the finding once for cyclic.(#3517)
if ( matchCyclic && !cyclicRerun )
{
this.searchRange = getSearchRange( 1 );
this.matchRange = null;
return arguments.callee.apply( this,
Array.prototype.slice.call( arguments ).concat( [ true ] ) );
}
return false;
},
/**
* Record how much replacement occurred toward one replacing.
*/
replaceCounter : 0,
replace : function( dialog, pattern, newString, matchCase, matchWord,
matchCyclic , isReplaceAll )
{
isReplace = 1;
// Successiveness of current replace/find.
var result = 0;
// 1. Perform the replace when there's already a match here.
// 2. Otherwise perform the find but don't replace it immediately.
if ( this.matchRange && this.matchRange.isMatched()
&& !this.matchRange._.isReplaced && !this.matchRange.isReadOnly() )
{
// Turn off highlight for a while when saving snapshots.
this.matchRange.removeHighlight();
var domRange = this.matchRange.toDomRange();
var text = editor.document.createText( newString );
if ( !isReplaceAll )
{
// Save undo snaps before and after the replacement.
var selection = editor.getSelection();
selection.selectRanges( [ domRange ] );
editor.fire( 'saveSnapshot' );
}
domRange.deleteContents();
domRange.insertNode( text );
if ( !isReplaceAll )
{
selection.selectRanges( [ domRange ] );
editor.fire( 'saveSnapshot' );
}
this.matchRange.updateFromDomRange( domRange );
if ( !isReplaceAll )
this.matchRange.highlight();
this.matchRange._.isReplaced = true;
this.replaceCounter++;
result = 1;
}
else
result = this.find( pattern, matchCase, matchWord, matchCyclic, !isReplaceAll );
isReplace = 0;
return result;
}
};
/**
* The range in which find/replace happened, receive from user
* selection prior.
*/
function getSearchRange( isDefault )
{
var searchRange,
sel = editor.getSelection(),
body = editor.document.getBody();
if ( sel && !isDefault )
{
searchRange = sel.getRanges()[ 0 ].clone();
searchRange.collapse( true );
}
else
{
searchRange = new CKEDITOR.dom.range();
searchRange.setStartAt( body, CKEDITOR.POSITION_AFTER_START );
}
searchRange.setEndAt( body, CKEDITOR.POSITION_BEFORE_END );
return searchRange;
}
var lang = editor.lang.findAndReplace;
return {
title : lang.title,
resizable : CKEDITOR.DIALOG_RESIZE_NONE,
minWidth : 350,
minHeight : 165,
buttons : [ CKEDITOR.dialog.cancelButton ], // Cancel button only.
contents : [
{
id : 'find',
label : lang.find,
title : lang.find,
accessKey : '',
elements : [
{
type : 'hbox',
widths : [ '230px', '90px' ],
children :
[
{
type : 'text',
id : 'txtFindFind',
label : lang.findWhat,
isChanged : false,
labelLayout : 'horizontal',
accessKey : 'F'
},
{
type : 'button',
align : 'left',
style : 'width:100%',
label : lang.find,
onClick : function()
{
var dialog = this.getDialog();
if ( !finder.find( dialog.getValueOf( 'find', 'txtFindFind' ),
dialog.getValueOf( 'find', 'txtFindCaseChk' ),
dialog.getValueOf( 'find', 'txtFindWordChk' ),
dialog.getValueOf( 'find', 'txtFindCyclic' ) ) )
alert( lang
.notFoundMsg );
}
}
]
},
{
type : 'vbox',
padding : 0,
children :
[
{
type : 'checkbox',
id : 'txtFindCaseChk',
isChanged : false,
style : 'margin-top:28px',
label : lang.matchCase
},
{
type : 'checkbox',
id : 'txtFindWordChk',
isChanged : false,
label : lang.matchWord
},
{
type : 'checkbox',
id : 'txtFindCyclic',
isChanged : false,
'default' : true,
label : lang.matchCyclic
}
]
}
]
},
{
id : 'replace',
label : lang.replace,
accessKey : 'M',
elements : [
{
type : 'hbox',
widths : [ '230px', '90px' ],
children :
[
{
type : 'text',
id : 'txtFindReplace',
label : lang.findWhat,
isChanged : false,
labelLayout : 'horizontal',
accessKey : 'F'
},
{
type : 'button',
align : 'left',
style : 'width:100%',
label : lang.replace,
onClick : function()
{
var dialog = this.getDialog();
if ( !finder.replace( dialog,
dialog.getValueOf( 'replace', 'txtFindReplace' ),
dialog.getValueOf( 'replace', 'txtReplace' ),
dialog.getValueOf( 'replace', 'txtReplaceCaseChk' ),
dialog.getValueOf( 'replace', 'txtReplaceWordChk' ),
dialog.getValueOf( 'replace', 'txtReplaceCyclic' ) ) )
alert( lang
.notFoundMsg );
}
}
]
},
{
type : 'hbox',
widths : [ '230px', '90px' ],
children :
[
{
type : 'text',
id : 'txtReplace',
label : lang.replaceWith,
isChanged : false,
labelLayout : 'horizontal',
accessKey : 'R'
},
{
type : 'button',
align : 'left',
style : 'width:100%',
label : lang.replaceAll,
isChanged : false,
onClick : function()
{
var dialog = this.getDialog();
var replaceNums;
finder.replaceCounter = 0;
// Scope to full document.
finder.searchRange = getSearchRange( 1 );
if ( finder.matchRange )
{
finder.matchRange.removeHighlight();
finder.matchRange = null;
}
editor.fire( 'saveSnapshot' );
while ( finder.replace( dialog,
dialog.getValueOf( 'replace', 'txtFindReplace' ),
dialog.getValueOf( 'replace', 'txtReplace' ),
dialog.getValueOf( 'replace', 'txtReplaceCaseChk' ),
dialog.getValueOf( 'replace', 'txtReplaceWordChk' ),
false, true ) )
{ /*jsl:pass*/ }
if ( finder.replaceCounter )
{
alert( lang.replaceSuccessMsg.replace( /%1/, finder.replaceCounter ) );
editor.fire( 'saveSnapshot' );
}
else
alert( lang.notFoundMsg );
}
}
]
},
{
type : 'vbox',
padding : 0,
children :
[
{
type : 'checkbox',
id : 'txtReplaceCaseChk',
isChanged : false,
label : lang
.matchCase
},
{
type : 'checkbox',
id : 'txtReplaceWordChk',
isChanged : false,
label : lang
.matchWord
},
{
type : 'checkbox',
id : 'txtReplaceCyclic',
isChanged : false,
'default' : true,
label : lang
.matchCyclic
}
]
}
]
}
],
onLoad : function()
{
var dialog = this;
// Keep track of the current pattern field in use.
var patternField, wholeWordChkField;
// Ignore initial page select on dialog show
var isUserSelect = 0;
this.on( 'hide', function()
{
isUserSelect = 0;
});
this.on( 'show', function()
{
isUserSelect = 1;
});
this.selectPage = CKEDITOR.tools.override( this.selectPage, function( originalFunc )
{
return function( pageId )
{
originalFunc.call( dialog, pageId );
var currPage = dialog._.tabs[ pageId ];
var patternFieldInput, patternFieldId, wholeWordChkFieldId;
patternFieldId = pageId === 'find' ? 'txtFindFind' : 'txtFindReplace';
wholeWordChkFieldId = pageId === 'find' ? 'txtFindWordChk' : 'txtReplaceWordChk';
patternField = dialog.getContentElement( pageId,
patternFieldId );
wholeWordChkField = dialog.getContentElement( pageId,
wholeWordChkFieldId );
// Prepare for check pattern text filed 'keyup' event
if ( !currPage.initialized )
{
patternFieldInput = CKEDITOR.document
.getById( patternField._.inputId );
currPage.initialized = true;
}
// Synchronize fields on tab switch.
if ( isUserSelect )
syncFieldsBetweenTabs.call( this, pageId );
};
} );
},
onShow : function()
{
// Establish initial searching start position.
finder.searchRange = getSearchRange();
this.selectPage( startupPage );
},
onHide : function()
{
var range;
if ( finder.matchRange && finder.matchRange.isMatched() )
{
finder.matchRange.removeHighlight();
editor.focus();
range = finder.matchRange.toDomRange();
if ( range )
editor.getSelection().selectRanges( [ range ] );
}
// Clear current session before dialog close
delete finder.matchRange;
},
onFocus : function()
{
if ( startupPage == 'replace' )
return this.getContentElement( 'replace', 'txtFindReplace' );
else
return this.getContentElement( 'find', 'txtFindFind' );
}
};
};
CKEDITOR.dialog.add( 'find', function( editor )
{
return findDialog( editor, 'find' );
});
CKEDITOR.dialog.add( 'replace', function( editor )
{
return findDialog( editor, 'replace' );
});
})();
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.add( 'htmlwriter' );
/**
* Class used to write HTML data.
* @constructor
* @example
* var writer = new CKEDITOR.htmlWriter();
* writer.openTag( 'p' );
* writer.attribute( 'class', 'MyClass' );
* writer.openTagClose( 'p' );
* writer.text( 'Hello' );
* writer.closeTag( 'p' );
* alert( writer.getHtml() ); "<p class="MyClass">Hello</p>"
*/
CKEDITOR.htmlWriter = CKEDITOR.tools.createClass(
{
base : CKEDITOR.htmlParser.basicWriter,
$ : function()
{
// Call the base contructor.
this.base();
/**
* The characters to be used for each identation step.
* @type String
* @default "\t" (tab)
* @example
* // Use two spaces for indentation.
* editorInstance.dataProcessor.writer.indentationChars = ' ';
*/
this.indentationChars = '\t';
/**
* The characters to be used to close "self-closing" elements, like "br" or
* "img".
* @type String
* @default " />"
* @example
* // Use HTML4 notation for self-closing elements.
* editorInstance.dataProcessor.writer.selfClosingEnd = '>';
*/
this.selfClosingEnd = ' />';
/**
* The characters to be used for line breaks.
* @type String
* @default "\n" (LF)
* @example
* // Use CRLF for line breaks.
* editorInstance.dataProcessor.writer.lineBreakChars = '\r\n';
*/
this.lineBreakChars = '\n';
this.forceSimpleAmpersand = 0;
this.sortAttributes = 1;
this._.indent = 0;
this._.indentation = '';
// Indicate preformatted block context status. (#5789)
this._.inPre = 0;
this._.rules = {};
var dtd = CKEDITOR.dtd;
for ( var e in CKEDITOR.tools.extend( {}, dtd.$nonBodyContent, dtd.$block, dtd.$listItem, dtd.$tableContent ) )
{
this.setRules( e,
{
indent : 1,
breakBeforeOpen : 1,
breakAfterOpen : 1,
breakBeforeClose : !dtd[ e ][ '#' ],
breakAfterClose : 1
});
}
this.setRules( 'br',
{
breakAfterOpen : 1
});
this.setRules( 'title',
{
indent : 0,
breakAfterOpen : 0
});
this.setRules( 'style',
{
indent : 0,
breakBeforeClose : 1
});
// Disable indentation on <pre>.
this.setRules( 'pre',
{
indent : 0
});
},
proto :
{
/**
* Writes the tag opening part for a opener tag.
* @param {String} tagName The element name for this tag.
* @param {Object} attributes The attributes defined for this tag. The
* attributes could be used to inspect the tag.
* @example
* // Writes "<p".
* writer.openTag( 'p', { class : 'MyClass', id : 'MyId' } );
*/
openTag : function( tagName, attributes )
{
var rules = this._.rules[ tagName ];
if ( this._.indent )
this.indentation();
// Do not break if indenting.
else if ( rules && rules.breakBeforeOpen )
{
this.lineBreak();
this.indentation();
}
this._.output.push( '<', tagName );
},
/**
* Writes the tag closing part for a opener tag.
* @param {String} tagName The element name for this tag.
* @param {Boolean} isSelfClose Indicates that this is a self-closing tag,
* like "br" or "img".
* @example
* // Writes ">".
* writer.openTagClose( 'p', false );
* @example
* // Writes " />".
* writer.openTagClose( 'br', true );
*/
openTagClose : function( tagName, isSelfClose )
{
var rules = this._.rules[ tagName ];
if ( isSelfClose )
this._.output.push( this.selfClosingEnd );
else
{
this._.output.push( '>' );
if ( rules && rules.indent )
this._.indentation += this.indentationChars;
}
if ( rules && rules.breakAfterOpen )
this.lineBreak();
tagName == 'pre' && ( this._.inPre = 1 );
},
/**
* Writes an attribute. This function should be called after opening the
* tag with {@link #openTagClose}.
* @param {String} attName The attribute name.
* @param {String} attValue The attribute value.
* @example
* // Writes ' class="MyClass"'.
* writer.attribute( 'class', 'MyClass' );
*/
attribute : function( attName, attValue )
{
if ( typeof attValue == 'string' )
{
this.forceSimpleAmpersand && ( attValue = attValue.replace( /&/g, '&' ) );
// Browsers don't always escape special character in attribute values. (#4683, #4719).
attValue = CKEDITOR.tools.htmlEncodeAttr( attValue );
}
this._.output.push( ' ', attName, '="', attValue, '"' );
},
/**
* Writes a closer tag.
* @param {String} tagName The element name for this tag.
* @example
* // Writes "</p>".
* writer.closeTag( 'p' );
*/
closeTag : function( tagName )
{
var rules = this._.rules[ tagName ];
if ( rules && rules.indent )
this._.indentation = this._.indentation.substr( this.indentationChars.length );
if ( this._.indent )
this.indentation();
// Do not break if indenting.
else if ( rules && rules.breakBeforeClose )
{
this.lineBreak();
this.indentation();
}
this._.output.push( '</', tagName, '>' );
tagName == 'pre' && ( this._.inPre = 0 );
if ( rules && rules.breakAfterClose )
this.lineBreak();
},
/**
* Writes text.
* @param {String} text The text value
* @example
* // Writes "Hello Word".
* writer.text( 'Hello Word' );
*/
text : function( text )
{
if ( this._.indent )
{
this.indentation();
!this._.inPre && ( text = CKEDITOR.tools.ltrim( text ) );
}
this._.output.push( text );
},
/**
* Writes a comment.
* @param {String} comment The comment text.
* @example
* // Writes "<!-- My comment -->".
* writer.comment( ' My comment ' );
*/
comment : function( comment )
{
if ( this._.indent )
this.indentation();
this._.output.push( '<!--', comment, '-->' );
},
/**
* Writes a line break. It uses the {@link #lineBreakChars} property for it.
* @example
* // Writes "\n" (e.g.).
* writer.lineBreak();
*/
lineBreak : function()
{
if ( !this._.inPre && this._.output.length > 0 )
this._.output.push( this.lineBreakChars );
this._.indent = 1;
},
/**
* Writes the current indentation chars. It uses the
* {@link #indentationChars} property, repeating it for the current
* indentation steps.
* @example
* // Writes "\t" (e.g.).
* writer.indentation();
*/
indentation : function()
{
if( !this._.inPre )
this._.output.push( this._.indentation );
this._.indent = 0;
},
/**
* Sets formatting rules for a give element. The possible rules are:
* <ul>
* <li><b>indent</b>: indent the element contents.</li>
* <li><b>breakBeforeOpen</b>: break line before the opener tag for this element.</li>
* <li><b>breakAfterOpen</b>: break line after the opener tag for this element.</li>
* <li><b>breakBeforeClose</b>: break line before the closer tag for this element.</li>
* <li><b>breakAfterClose</b>: break line after the closer tag for this element.</li>
* </ul>
*
* All rules default to "false". Each call to the function overrides
* already present rules, leaving the undefined untouched.
*
* By default, all elements available in the {@link CKEDITOR.dtd.$block),
* {@link CKEDITOR.dtd.$listItem} and {@link CKEDITOR.dtd.$tableContent}
* lists have all the above rules set to "true". Additionaly, the "br"
* element has the "breakAfterOpen" set to "true".
* @param {String} tagName The element name to which set the rules.
* @param {Object} rules An object containing the element rules.
* @example
* // Break line before and after "img" tags.
* writer.setRules( 'img',
* {
* breakBeforeOpen : true
* breakAfterOpen : true
* });
* @example
* // Reset the rules for the "h1" tag.
* writer.setRules( 'h1', {} );
*/
setRules : function( tagName, rules )
{
var currentRules = this._.rules[ tagName ];
if ( currentRules )
CKEDITOR.tools.extend( currentRules, rules, true );
else
this._.rules[ tagName ] = rules;
}
}
});
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @fileOverview Undo/Redo system for saving shapshot for document modification
* and other recordable changes.
*/
(function()
{
CKEDITOR.plugins.add( 'undo',
{
requires : [ 'selection', 'wysiwygarea' ],
init : function( editor )
{
var undoManager = new UndoManager( editor );
var undoCommand = editor.addCommand( 'undo',
{
exec : function()
{
if ( undoManager.undo() )
{
editor.selectionChange();
this.fire( 'afterUndo' );
}
},
state : CKEDITOR.TRISTATE_DISABLED,
canUndo : false
});
var redoCommand = editor.addCommand( 'redo',
{
exec : function()
{
if ( undoManager.redo() )
{
editor.selectionChange();
this.fire( 'afterRedo' );
}
},
state : CKEDITOR.TRISTATE_DISABLED,
canUndo : false
});
undoManager.onChange = function()
{
undoCommand.setState( undoManager.undoable() ? CKEDITOR.TRISTATE_OFF : CKEDITOR.TRISTATE_DISABLED );
redoCommand.setState( undoManager.redoable() ? CKEDITOR.TRISTATE_OFF : CKEDITOR.TRISTATE_DISABLED );
};
function recordCommand( event )
{
// If the command hasn't been marked to not support undo.
if ( undoManager.enabled && event.data.command.canUndo !== false )
undoManager.save();
}
// We'll save snapshots before and after executing a command.
editor.on( 'beforeCommandExec', recordCommand );
editor.on( 'afterCommandExec', recordCommand );
// Save snapshots before doing custom changes.
editor.on( 'saveSnapshot', function()
{
undoManager.save();
});
// Registering keydown on every document recreation.(#3844)
editor.on( 'contentDom', function()
{
editor.document.on( 'keydown', function( event )
{
// Do not capture CTRL hotkeys.
if ( !event.data.$.ctrlKey && !event.data.$.metaKey )
undoManager.type( event );
});
});
// Always save an undo snapshot - the previous mode might have
// changed editor contents.
editor.on( 'beforeModeUnload', function()
{
editor.mode == 'wysiwyg' && undoManager.save( true );
});
// Make the undo manager available only in wysiwyg mode.
editor.on( 'mode', function()
{
undoManager.enabled = editor.mode == 'wysiwyg';
undoManager.onChange();
});
editor.ui.addButton( 'Undo',
{
label : editor.lang.undo,
command : 'undo'
});
editor.ui.addButton( 'Redo',
{
label : editor.lang.redo,
command : 'redo'
});
editor.resetUndo = function()
{
// Reset the undo stack.
undoManager.reset();
// Create the first image.
editor.fire( 'saveSnapshot' );
};
/**
* Update the undo stacks with any subsequent DOM changes after this call.
* @name CKEDITOR.editor#updateUndo
* @example
* function()
* {
* editor.fire( 'updateSnapshot' );
* ...
* // Ask to include subsequent (in this call stack) DOM changes to be
* // considered as part of the first snapshot.
* editor.fire( 'updateSnapshot' );
* editor.document.body.append(...);
* ...
* }
*/
editor.on( 'updateSnapshot', function()
{
if ( undoManager.currentImage && new Image( editor ).equals( undoManager.currentImage ) )
setTimeout( function() { undoManager.update(); }, 0 );
});
}
});
CKEDITOR.plugins.undo = {};
/**
* Undo snapshot which represents the current document status.
* @name CKEDITOR.plugins.undo.Image
* @param editor The editor instance on which the image is created.
*/
var Image = CKEDITOR.plugins.undo.Image = function( editor )
{
this.editor = editor;
var contents = editor.getSnapshot(),
selection = contents && editor.getSelection();
// In IE, we need to remove the expando attributes.
CKEDITOR.env.ie && contents && ( contents = contents.replace( /\s+data-cke-expando=".*?"/g, '' ) );
this.contents = contents;
this.bookmarks = selection && selection.createBookmarks2( true );
};
// Attributes that browser may changing them when setting via innerHTML.
var protectedAttrs = /\b(?:href|src|name)="[^"]*?"/gi;
Image.prototype =
{
equals : function( otherImage, contentOnly )
{
var thisContents = this.contents,
otherContents = otherImage.contents;
// For IE6/7 : Comparing only the protected attribute values but not the original ones.(#4522)
if ( CKEDITOR.env.ie && ( CKEDITOR.env.ie7Compat || CKEDITOR.env.ie6Compat ) )
{
thisContents = thisContents.replace( protectedAttrs, '' );
otherContents = otherContents.replace( protectedAttrs, '' );
}
if ( thisContents != otherContents )
return false;
if ( contentOnly )
return true;
var bookmarksA = this.bookmarks,
bookmarksB = otherImage.bookmarks;
if ( bookmarksA || bookmarksB )
{
if ( !bookmarksA || !bookmarksB || bookmarksA.length != bookmarksB.length )
return false;
for ( var i = 0 ; i < bookmarksA.length ; i++ )
{
var bookmarkA = bookmarksA[ i ],
bookmarkB = bookmarksB[ i ];
if (
bookmarkA.startOffset != bookmarkB.startOffset ||
bookmarkA.endOffset != bookmarkB.endOffset ||
!CKEDITOR.tools.arrayCompare( bookmarkA.start, bookmarkB.start ) ||
!CKEDITOR.tools.arrayCompare( bookmarkA.end, bookmarkB.end ) )
{
return false;
}
}
}
return true;
}
};
/**
* @constructor Main logic for Redo/Undo feature.
*/
function UndoManager( editor )
{
this.editor = editor;
// Reset the undo stack.
this.reset();
}
var editingKeyCodes = { /*Backspace*/ 8:1, /*Delete*/ 46:1 },
modifierKeyCodes = { /*Shift*/ 16:1, /*Ctrl*/ 17:1, /*Alt*/ 18:1 },
navigationKeyCodes = { 37:1, 38:1, 39:1, 40:1 }; // Arrows: L, T, R, B
UndoManager.prototype =
{
/**
* Process undo system regard keystrikes.
* @param {CKEDITOR.dom.event} event
*/
type : function( event )
{
var keystroke = event && event.data.getKey(),
isModifierKey = keystroke in modifierKeyCodes,
isEditingKey = keystroke in editingKeyCodes,
wasEditingKey = this.lastKeystroke in editingKeyCodes,
sameAsLastEditingKey = isEditingKey && keystroke == this.lastKeystroke,
// Keystrokes which navigation through contents.
isReset = keystroke in navigationKeyCodes,
wasReset = this.lastKeystroke in navigationKeyCodes,
// Keystrokes which just introduce new contents.
isContent = ( !isEditingKey && !isReset ),
// Create undo snap for every different modifier key.
modifierSnapshot = ( isEditingKey && !sameAsLastEditingKey ),
// Create undo snap on the following cases:
// 1. Just start to type .
// 2. Typing some content after a modifier.
// 3. Typing some content after make a visible selection.
startedTyping = !( isModifierKey || this.typing )
|| ( isContent && ( wasEditingKey || wasReset ) );
if ( startedTyping || modifierSnapshot )
{
var beforeTypeImage = new Image( this.editor );
// Use setTimeout, so we give the necessary time to the
// browser to insert the character into the DOM.
CKEDITOR.tools.setTimeout( function()
{
var currentSnapshot = this.editor.getSnapshot();
// In IE, we need to remove the expando attributes.
if ( CKEDITOR.env.ie )
currentSnapshot = currentSnapshot.replace( /\s+data-cke-expando=".*?"/g, '' );
if ( beforeTypeImage.contents != currentSnapshot )
{
// It's safe to now indicate typing state.
this.typing = true;
// This's a special save, with specified snapshot
// and without auto 'fireChange'.
if ( !this.save( false, beforeTypeImage, false ) )
// Drop future snapshots.
this.snapshots.splice( this.index + 1, this.snapshots.length - this.index - 1 );
this.hasUndo = true;
this.hasRedo = false;
this.typesCount = 1;
this.modifiersCount = 1;
this.onChange();
}
},
0, this
);
}
this.lastKeystroke = keystroke;
// Create undo snap after typed too much (over 25 times).
if ( isEditingKey )
{
this.typesCount = 0;
this.modifiersCount++;
if ( this.modifiersCount > 25 )
{
this.save( false, null, false );
this.modifiersCount = 1;
}
}
else if ( !isReset )
{
this.modifiersCount = 0;
this.typesCount++;
if ( this.typesCount > 25 )
{
this.save( false, null, false );
this.typesCount = 1;
}
}
},
reset : function() // Reset the undo stack.
{
/**
* Remember last pressed key.
*/
this.lastKeystroke = 0;
/**
* Stack for all the undo and redo snapshots, they're always created/removed
* in consistency.
*/
this.snapshots = [];
/**
* Current snapshot history index.
*/
this.index = -1;
this.limit = this.editor.config.undoStackSize || 20;
this.currentImage = null;
this.hasUndo = false;
this.hasRedo = false;
this.resetType();
},
/**
* Reset all states about typing.
* @see UndoManager.type
*/
resetType : function()
{
this.typing = false;
delete this.lastKeystroke;
this.typesCount = 0;
this.modifiersCount = 0;
},
fireChange : function()
{
this.hasUndo = !!this.getNextImage( true );
this.hasRedo = !!this.getNextImage( false );
// Reset typing
this.resetType();
this.onChange();
},
/**
* Save a snapshot of document image for later retrieve.
*/
save : function( onContentOnly, image, autoFireChange )
{
var snapshots = this.snapshots;
// Get a content image.
if ( !image )
image = new Image( this.editor );
// Do nothing if it was not possible to retrieve an image.
if ( image.contents === false )
return false;
// Check if this is a duplicate. In such case, do nothing.
if ( this.currentImage && image.equals( this.currentImage, onContentOnly ) )
return false;
// Drop future snapshots.
snapshots.splice( this.index + 1, snapshots.length - this.index - 1 );
// If we have reached the limit, remove the oldest one.
if ( snapshots.length == this.limit )
snapshots.shift();
// Add the new image, updating the current index.
this.index = snapshots.push( image ) - 1;
this.currentImage = image;
if ( autoFireChange !== false )
this.fireChange();
return true;
},
restoreImage : function( image )
{
this.editor.loadSnapshot( image.contents );
if ( image.bookmarks )
this.editor.getSelection().selectBookmarks( image.bookmarks );
else if ( CKEDITOR.env.ie )
{
// IE BUG: If I don't set the selection to *somewhere* after setting
// document contents, then IE would create an empty paragraph at the bottom
// the next time the document is modified.
var $range = this.editor.document.getBody().$.createTextRange();
$range.collapse( true );
$range.select();
}
this.index = image.index;
// Update current image with the actual editor
// content, since actualy content may differ from
// the original snapshot due to dom change. (#4622)
this.update();
this.fireChange();
},
// Get the closest available image.
getNextImage : function( isUndo )
{
var snapshots = this.snapshots,
currentImage = this.currentImage,
image, i;
if ( currentImage )
{
if ( isUndo )
{
for ( i = this.index - 1 ; i >= 0 ; i-- )
{
image = snapshots[ i ];
if ( !currentImage.equals( image, true ) )
{
image.index = i;
return image;
}
}
}
else
{
for ( i = this.index + 1 ; i < snapshots.length ; i++ )
{
image = snapshots[ i ];
if ( !currentImage.equals( image, true ) )
{
image.index = i;
return image;
}
}
}
}
return null;
},
/**
* Check the current redo state.
* @return {Boolean} Whether the document has previous state to
* retrieve.
*/
redoable : function()
{
return this.enabled && this.hasRedo;
},
/**
* Check the current undo state.
* @return {Boolean} Whether the document has future state to restore.
*/
undoable : function()
{
return this.enabled && this.hasUndo;
},
/**
* Perform undo on current index.
*/
undo : function()
{
if ( this.undoable() )
{
this.save( true );
var image = this.getNextImage( true );
if ( image )
return this.restoreImage( image ), true;
}
return false;
},
/**
* Perform redo on current index.
*/
redo : function()
{
if ( this.redoable() )
{
// Try to save. If no changes have been made, the redo stack
// will not change, so it will still be redoable.
this.save( true );
// If instead we had changes, we can't redo anymore.
if ( this.redoable() )
{
var image = this.getNextImage( false );
if ( image )
return this.restoreImage( image ), true;
}
}
return false;
},
/**
* Update the last snapshot of the undo stack with the current editor content.
*/
update : function()
{
this.snapshots.splice( this.index, 1, ( this.currentImage = new Image( this.editor ) ) );
}
};
})();
/**
* The number of undo steps to be saved. The higher this setting value the more
* memory is used for it.
* @type Number
* @default 20
* @example
* config.undoStackSize = 50;
*/
/**
* Fired when the editor is about to save an undo snapshot. This event can be
* fired by plugins and customizations to make the editor saving undo snapshots.
* @name CKEDITOR.editor#saveSnapshot
* @event
*/
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @file Forms Plugin
*/
CKEDITOR.plugins.add( 'forms',
{
init : function( editor )
{
var lang = editor.lang;
editor.addCss(
'form' +
'{' +
'border: 1px dotted #FF0000;' +
'padding: 2px;' +
'}\n' );
editor.addCss(
'img.cke_hidden' +
'{' +
'background-image: url(' + CKEDITOR.getUrl( this.path + 'images/hiddenfield.gif' ) + ');' +
'background-position: center center;' +
'background-repeat: no-repeat;' +
'border: 1px solid #a9a9a9;' +
'width: 16px !important;' +
'height: 16px !important;' +
'}' );
// All buttons use the same code to register. So, to avoid
// duplications, let's use this tool function.
var addButtonCommand = function( buttonName, commandName, dialogFile )
{
editor.addCommand( commandName, new CKEDITOR.dialogCommand( commandName ) );
editor.ui.addButton( buttonName,
{
label : lang.common[ buttonName.charAt(0).toLowerCase() + buttonName.slice(1) ],
command : commandName
});
CKEDITOR.dialog.add( commandName, dialogFile );
};
var dialogPath = this.path + 'dialogs/';
addButtonCommand( 'Form', 'form', dialogPath + 'form.js' );
addButtonCommand( 'Checkbox', 'checkbox', dialogPath + 'checkbox.js' );
addButtonCommand( 'Radio', 'radio', dialogPath + 'radio.js' );
addButtonCommand( 'TextField', 'textfield', dialogPath + 'textfield.js' );
addButtonCommand( 'Textarea', 'textarea', dialogPath + 'textarea.js' );
addButtonCommand( 'Select', 'select', dialogPath + 'select.js' );
addButtonCommand( 'Button', 'button', dialogPath + 'button.js' );
addButtonCommand( 'ImageButton', 'imagebutton', CKEDITOR.plugins.getPath('image') + 'dialogs/image.js' );
addButtonCommand( 'HiddenField', 'hiddenfield', dialogPath + 'hiddenfield.js' );
// If the "menu" plugin is loaded, register the menu items.
if ( editor.addMenuItems )
{
editor.addMenuItems(
{
form :
{
label : lang.form.menu,
command : 'form',
group : 'form'
},
checkbox :
{
label : lang.checkboxAndRadio.checkboxTitle,
command : 'checkbox',
group : 'checkbox'
},
radio :
{
label : lang.checkboxAndRadio.radioTitle,
command : 'radio',
group : 'radio'
},
textfield :
{
label : lang.textfield.title,
command : 'textfield',
group : 'textfield'
},
hiddenfield :
{
label : lang.hidden.title,
command : 'hiddenfield',
group : 'hiddenfield'
},
imagebutton :
{
label : lang.image.titleButton,
command : 'imagebutton',
group : 'imagebutton'
},
button :
{
label : lang.button.title,
command : 'button',
group : 'button'
},
select :
{
label : lang.select.title,
command : 'select',
group : 'select'
},
textarea :
{
label : lang.textarea.title,
command : 'textarea',
group : 'textarea'
}
});
}
// If the "contextmenu" plugin is loaded, register the listeners.
if ( editor.contextMenu )
{
editor.contextMenu.addListener( function( element )
{
if ( element && element.hasAscendant( 'form', true ) && !element.isReadOnly() )
return { form : CKEDITOR.TRISTATE_OFF };
});
editor.contextMenu.addListener( function( element )
{
if ( element && !element.isReadOnly() )
{
var name = element.getName();
if ( name == 'select' )
return { select : CKEDITOR.TRISTATE_OFF };
if ( name == 'textarea' )
return { textarea : CKEDITOR.TRISTATE_OFF };
if ( name == 'input' )
{
var type = element.getAttribute( 'type' );
if ( type == 'text' || type == 'password' )
return { textfield : CKEDITOR.TRISTATE_OFF };
if ( type == 'button' || type == 'submit' || type == 'reset' )
return { button : CKEDITOR.TRISTATE_OFF };
if ( type == 'checkbox' )
return { checkbox : CKEDITOR.TRISTATE_OFF };
if ( type == 'radio' )
return { radio : CKEDITOR.TRISTATE_OFF };
if ( type == 'image' )
return { imagebutton : CKEDITOR.TRISTATE_OFF };
}
if ( name == 'img' && element.data( 'cke-real-element-type' ) == 'hiddenfield' )
return { hiddenfield : CKEDITOR.TRISTATE_OFF };
}
});
}
editor.on( 'doubleclick', function( evt )
{
var element = evt.data.element;
if ( element.is( 'form' ) )
evt.data.dialog = 'form';
else if ( element.is( 'select' ) )
evt.data.dialog = 'select';
else if ( element.is( 'textarea' ) )
evt.data.dialog = 'textarea';
else if ( element.is( 'img' ) && element.data( 'cke-real-element-type' ) == 'hiddenfield' )
evt.data.dialog = 'hiddenfield';
else if ( element.is( 'input' ) )
{
var type = element.getAttribute( 'type' );
switch ( type )
{
case 'text' :
case 'password' :
evt.data.dialog = 'textfield';
break;
case 'button' :
case 'submit' :
case 'reset' :
evt.data.dialog = 'button';
break;
case 'checkbox' :
evt.data.dialog = 'checkbox';
break;
case 'radio' :
evt.data.dialog = 'radio';
break;
case 'image' :
evt.data.dialog = 'imagebutton';
break;
}
}
});
},
afterInit : function( editor )
{
var dataProcessor = editor.dataProcessor,
htmlFilter = dataProcessor && dataProcessor.htmlFilter,
dataFilter = dataProcessor && dataProcessor.dataFilter;
// Cleanup certain IE form elements default values.
if ( CKEDITOR.env.ie )
{
htmlFilter && htmlFilter.addRules(
{
elements :
{
input : function( input )
{
var attrs = input.attributes,
type = attrs.type;
if ( type == 'checkbox' || type == 'radio' )
attrs.value == 'on' && delete attrs.value;
}
}
} );
}
if ( dataFilter )
{
dataFilter.addRules(
{
elements :
{
input : function( element )
{
if ( element.attributes.type == 'hidden' )
return editor.createFakeParserElement( element, 'cke_hidden', 'hiddenfield' );
}
}
} );
}
},
requires : [ 'image', 'fakeobjects' ]
} );
if ( CKEDITOR.env.ie )
{
CKEDITOR.dom.element.prototype.hasAttribute = function( name )
{
var $attr = this.$.attributes.getNamedItem( name );
if ( this.getName() == 'input' )
{
switch ( name )
{
case 'class' :
return this.$.className.length > 0;
case 'checked' :
return !!this.$.checked;
case 'value' :
var type = this.getAttribute( 'type' );
if ( type == 'checkbox' || type == 'radio' )
return this.$.value != 'on';
break;
default:
}
}
return !!( $attr && $attr.specified );
};
}
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.dialog.add( 'select', function( editor )
{
// Add a new option to a SELECT object (combo or list).
function addOption( combo, optionText, optionValue, documentObject, index )
{
combo = getSelect( combo );
var oOption;
if ( documentObject )
oOption = documentObject.createElement( "OPTION" );
else
oOption = document.createElement( "OPTION" );
if ( combo && oOption && oOption.getName() == 'option' )
{
if ( CKEDITOR.env.ie ) {
if ( !isNaN( parseInt( index, 10) ) )
combo.$.options.add( oOption.$, index );
else
combo.$.options.add( oOption.$ );
oOption.$.innerHTML = optionText.length > 0 ? optionText : '';
oOption.$.value = optionValue;
}
else
{
if ( index !== null && index < combo.getChildCount() )
combo.getChild( index < 0 ? 0 : index ).insertBeforeMe( oOption );
else
combo.append( oOption );
oOption.setText( optionText.length > 0 ? optionText : '' );
oOption.setValue( optionValue );
}
}
else
return false;
return oOption;
}
// Remove all selected options from a SELECT object.
function removeSelectedOptions( combo )
{
combo = getSelect( combo );
// Save the selected index
var iSelectedIndex = getSelectedIndex( combo );
// Remove all selected options.
for ( var i = combo.getChildren().count() - 1 ; i >= 0 ; i-- )
{
if ( combo.getChild( i ).$.selected )
combo.getChild( i ).remove();
}
// Reset the selection based on the original selected index.
setSelectedIndex( combo, iSelectedIndex );
}
//Modify option from a SELECT object.
function modifyOption( combo, index, title, value )
{
combo = getSelect( combo );
if ( index < 0 )
return false;
var child = combo.getChild( index );
child.setText( title );
child.setValue( value );
return child;
}
function removeAllOptions( combo )
{
combo = getSelect( combo );
while ( combo.getChild( 0 ) && combo.getChild( 0 ).remove() )
{ /*jsl:pass*/ }
}
// Moves the selected option by a number of steps (also negative).
function changeOptionPosition( combo, steps, documentObject )
{
combo = getSelect( combo );
var iActualIndex = getSelectedIndex( combo );
if ( iActualIndex < 0 )
return false;
var iFinalIndex = iActualIndex + steps;
iFinalIndex = ( iFinalIndex < 0 ) ? 0 : iFinalIndex;
iFinalIndex = ( iFinalIndex >= combo.getChildCount() ) ? combo.getChildCount() - 1 : iFinalIndex;
if ( iActualIndex == iFinalIndex )
return false;
var oOption = combo.getChild( iActualIndex ),
sText = oOption.getText(),
sValue = oOption.getValue();
oOption.remove();
oOption = addOption( combo, sText, sValue, ( !documentObject ) ? null : documentObject, iFinalIndex );
setSelectedIndex( combo, iFinalIndex );
return oOption;
}
function getSelectedIndex( combo )
{
combo = getSelect( combo );
return combo ? combo.$.selectedIndex : -1;
}
function setSelectedIndex( combo, index )
{
combo = getSelect( combo );
if ( index < 0 )
return null;
var count = combo.getChildren().count();
combo.$.selectedIndex = ( index >= count ) ? ( count - 1 ) : index;
return combo;
}
function getOptions( combo )
{
combo = getSelect( combo );
return combo ? combo.getChildren() : false;
}
function getSelect( obj )
{
if ( obj && obj.domId && obj.getInputElement().$ ) // Dialog element.
return obj.getInputElement();
else if ( obj && obj.$ )
return obj;
return false;
}
return {
title : editor.lang.select.title,
minWidth : CKEDITOR.env.ie ? 460 : 395,
minHeight : CKEDITOR.env.ie ? 320 : 300,
onShow : function()
{
delete this.selectBox;
this.setupContent( 'clear' );
var element = this.getParentEditor().getSelection().getSelectedElement();
if ( element && element.getName() == "select" )
{
this.selectBox = element;
this.setupContent( element.getName(), element );
// Load Options into dialog.
var objOptions = getOptions( element );
for ( var i = 0 ; i < objOptions.count() ; i++ )
this.setupContent( 'option', objOptions.getItem( i ) );
}
},
onOk : function()
{
var editor = this.getParentEditor(),
element = this.selectBox,
isInsertMode = !element;
if ( isInsertMode )
element = editor.document.createElement( 'select' );
this.commitContent( element );
if ( isInsertMode )
{
editor.insertElement( element );
if ( CKEDITOR.env.ie )
{
var sel = editor.getSelection(),
bms = sel.createBookmarks();
setTimeout(function()
{
sel.selectBookmarks( bms );
}, 0 );
}
}
},
contents : [
{
id : 'info',
label : editor.lang.select.selectInfo,
title : editor.lang.select.selectInfo,
accessKey : '',
elements : [
{
id : 'txtName',
type : 'text',
widths : [ '25%','75%' ],
labelLayout : 'horizontal',
label : editor.lang.common.name,
'default' : '',
accessKey : 'N',
align : 'center',
style : 'width:350px',
setup : function( name, element )
{
if ( name == 'clear' )
this.setValue( this[ 'default' ] || '' );
else if ( name == 'select' )
{
this.setValue(
element.data( 'cke-saved-name' ) ||
element.getAttribute( 'name' ) ||
'' );
}
},
commit : function( element )
{
if ( this.getValue() )
element.data( 'cke-saved-name', this.getValue() );
else
{
element.data( 'cke-saved-name', false );
element.removeAttribute( 'name' );
}
}
},
{
id : 'txtValue',
type : 'text',
widths : [ '25%','75%' ],
labelLayout : 'horizontal',
label : editor.lang.select.value,
style : 'width:350px',
'default' : '',
className : 'cke_disabled',
onLoad : function()
{
this.getInputElement().setAttribute( 'readOnly', true );
},
setup : function( name, element )
{
if ( name == 'clear' )
this.setValue( '' );
else if ( name == 'option' && element.getAttribute( 'selected' ) )
this.setValue( element.$.value );
}
},
{
type : 'hbox',
widths : [ '175px', '170px' ],
align : 'center',
children :
[
{
id : 'txtSize',
type : 'text',
align : 'center',
labelLayout : 'horizontal',
label : editor.lang.select.size,
'default' : '',
accessKey : 'S',
style : 'width:175px',
validate: function()
{
var func = CKEDITOR.dialog.validate.integer( editor.lang.common.validateNumberFailed );
return ( ( this.getValue() === '' ) || func.apply( this ) );
},
setup : function( name, element )
{
if ( name == 'select' )
this.setValue( element.getAttribute( 'size' ) || '' );
if ( CKEDITOR.env.webkit )
this.getInputElement().setStyle( 'width', '86px' );
},
commit : function( element )
{
if ( this.getValue() )
element.setAttribute( 'size', this.getValue() );
else
element.removeAttribute( 'size' );
}
},
{
type : 'html',
html : '<span>' + CKEDITOR.tools.htmlEncode( editor.lang.select.lines ) + '</span>'
}
]
},
{
type : 'html',
html : '<span>' + CKEDITOR.tools.htmlEncode( editor.lang.select.opAvail ) + '</span>'
},
{
type : 'hbox',
widths : [ '115px', '115px' ,'100px' ],
align : 'top',
children :
[
{
type : 'vbox',
children :
[
{
id : 'txtOptName',
type : 'text',
label : editor.lang.select.opText,
style : 'width:115px',
setup : function( name, element )
{
if ( name == 'clear' )
this.setValue( "" );
}
},
{
type : 'select',
id : 'cmbName',
label : '',
title : '',
size : 5,
style : 'width:115px;height:75px',
items : [],
onChange : function()
{
var dialog = this.getDialog(),
values = dialog.getContentElement( 'info', 'cmbValue' ),
optName = dialog.getContentElement( 'info', 'txtOptName' ),
optValue = dialog.getContentElement( 'info', 'txtOptValue' ),
iIndex = getSelectedIndex( this );
setSelectedIndex( values, iIndex );
optName.setValue( this.getValue() );
optValue.setValue( values.getValue() );
},
setup : function( name, element )
{
if ( name == 'clear' )
removeAllOptions( this );
else if ( name == 'option' )
addOption( this, element.getText(), element.getText(),
this.getDialog().getParentEditor().document );
},
commit : function( element )
{
var dialog = this.getDialog(),
optionsNames = getOptions( this ),
optionsValues = getOptions( dialog.getContentElement( 'info', 'cmbValue' ) ),
selectValue = dialog.getContentElement( 'info', 'txtValue' ).getValue();
removeAllOptions( element );
for ( var i = 0 ; i < optionsNames.count() ; i++ )
{
var oOption = addOption( element, optionsNames.getItem( i ).getValue(),
optionsValues.getItem( i ).getValue(), dialog.getParentEditor().document );
if ( optionsValues.getItem( i ).getValue() == selectValue )
{
oOption.setAttribute( 'selected', 'selected' );
oOption.selected = true;
}
}
}
}
]
},
{
type : 'vbox',
children :
[
{
id : 'txtOptValue',
type : 'text',
label : editor.lang.select.opValue,
style : 'width:115px',
setup : function( name, element )
{
if ( name == 'clear' )
this.setValue( "" );
}
},
{
type : 'select',
id : 'cmbValue',
label : '',
size : 5,
style : 'width:115px;height:75px',
items : [],
onChange : function()
{
var dialog = this.getDialog(),
names = dialog.getContentElement( 'info', 'cmbName' ),
optName = dialog.getContentElement( 'info', 'txtOptName' ),
optValue = dialog.getContentElement( 'info', 'txtOptValue' ),
iIndex = getSelectedIndex( this );
setSelectedIndex( names, iIndex );
optName.setValue( names.getValue() );
optValue.setValue( this.getValue() );
},
setup : function( name, element )
{
if ( name == 'clear' )
removeAllOptions( this );
else if ( name == 'option' )
{
var oValue = element.getValue();
addOption( this, oValue, oValue,
this.getDialog().getParentEditor().document );
if ( element.getAttribute( 'selected' ) == 'selected' )
this.getDialog().getContentElement( 'info', 'txtValue' ).setValue( oValue );
}
}
}
]
},
{
type : 'vbox',
padding : 5,
children :
[
{
type : 'button',
style : '',
label : editor.lang.select.btnAdd,
title : editor.lang.select.btnAdd,
style : 'width:100%;',
onClick : function()
{
//Add new option.
var dialog = this.getDialog(),
parentEditor = dialog.getParentEditor(),
optName = dialog.getContentElement( 'info', 'txtOptName' ),
optValue = dialog.getContentElement( 'info', 'txtOptValue' ),
names = dialog.getContentElement( 'info', 'cmbName' ),
values = dialog.getContentElement( 'info', 'cmbValue' );
addOption(names, optName.getValue(), optName.getValue(), dialog.getParentEditor().document );
addOption(values, optValue.getValue(), optValue.getValue(), dialog.getParentEditor().document );
optName.setValue( "" );
optValue.setValue( "" );
}
},
{
type : 'button',
label : editor.lang.select.btnModify,
title : editor.lang.select.btnModify,
style : 'width:100%;',
onClick : function()
{
//Modify selected option.
var dialog = this.getDialog(),
optName = dialog.getContentElement( 'info', 'txtOptName' ),
optValue = dialog.getContentElement( 'info', 'txtOptValue' ),
names = dialog.getContentElement( 'info', 'cmbName' ),
values = dialog.getContentElement( 'info', 'cmbValue' ),
iIndex = getSelectedIndex( names );
if ( iIndex >= 0 )
{
modifyOption( names, iIndex, optName.getValue(), optName.getValue() );
modifyOption( values, iIndex, optValue.getValue(), optValue.getValue() );
}
}
},
{
type : 'button',
style : 'width:100%;',
label : editor.lang.select.btnUp,
title : editor.lang.select.btnUp,
onClick : function()
{
//Move up.
var dialog = this.getDialog(),
names = dialog.getContentElement( 'info', 'cmbName' ),
values = dialog.getContentElement( 'info', 'cmbValue' );
changeOptionPosition( names, -1, dialog.getParentEditor().document );
changeOptionPosition( values, -1, dialog.getParentEditor().document );
}
},
{
type : 'button',
style : 'width:100%;',
label : editor.lang.select.btnDown,
title : editor.lang.select.btnDown,
onClick : function()
{
//Move down.
var dialog = this.getDialog(),
names = dialog.getContentElement( 'info', 'cmbName' ),
values = dialog.getContentElement( 'info', 'cmbValue' );
changeOptionPosition( names, 1, dialog.getParentEditor().document );
changeOptionPosition( values, 1, dialog.getParentEditor().document );
}
}
]
}
]
},
{
type : 'hbox',
widths : [ '40%', '20%', '40%' ],
children :
[
{
type : 'button',
label : editor.lang.select.btnSetValue,
title : editor.lang.select.btnSetValue,
onClick : function()
{
//Set as default value.
var dialog = this.getDialog(),
values = dialog.getContentElement( 'info', 'cmbValue' ),
txtValue = dialog.getContentElement( 'info', 'txtValue' );
txtValue.setValue( values.getValue() );
}
},
{
type : 'button',
label : editor.lang.select.btnDelete,
title : editor.lang.select.btnDelete,
onClick : function()
{
// Delete option.
var dialog = this.getDialog(),
names = dialog.getContentElement( 'info', 'cmbName' ),
values = dialog.getContentElement( 'info', 'cmbValue' ),
optName = dialog.getContentElement( 'info', 'txtOptName' ),
optValue = dialog.getContentElement( 'info', 'txtOptValue' );
removeSelectedOptions( names );
removeSelectedOptions( values );
optName.setValue( "" );
optValue.setValue( "" );
}
},
{
id : 'chkMulti',
type : 'checkbox',
label : editor.lang.select.chkMulti,
'default' : '',
accessKey : 'M',
value : "checked",
setup : function( name, element )
{
if ( name == 'select' )
this.setValue( element.getAttribute( 'multiple' ) );
if ( CKEDITOR.env.webkit )
this.getElement().getParent().setStyle( 'vertical-align', 'middle' );
},
commit : function( element )
{
if ( this.getValue() )
element.setAttribute( 'multiple', this.getValue() );
else
element.removeAttribute( 'multiple' );
}
}
]
}
]
}
]
};
});
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.dialog.add( 'textfield', function( editor )
{
var autoAttributes =
{
value : 1,
size : 1,
maxLength : 1
};
var acceptedTypes =
{
text : 1,
password : 1
};
return {
title : editor.lang.textfield.title,
minWidth : 350,
minHeight : 150,
onShow : function()
{
delete this.textField;
var element = this.getParentEditor().getSelection().getSelectedElement();
if ( element && element.getName() == "input" &&
( acceptedTypes[ element.getAttribute( 'type' ) ] || !element.getAttribute( 'type' ) ) )
{
this.textField = element;
this.setupContent( element );
}
},
onOk : function()
{
var editor,
element = this.textField,
isInsertMode = !element;
if ( isInsertMode )
{
editor = this.getParentEditor();
element = editor.document.createElement( 'input' );
element.setAttribute( 'type', 'text' );
}
if ( isInsertMode )
editor.insertElement( element );
this.commitContent( { element : element } );
},
onLoad : function()
{
var autoSetup = function( element )
{
var value = element.hasAttribute( this.id ) && element.getAttribute( this.id );
this.setValue( value || '' );
};
var autoCommit = function( data )
{
var element = data.element;
var value = this.getValue();
if ( value )
element.setAttribute( this.id, value );
else
element.removeAttribute( this.id );
};
this.foreach( function( contentObj )
{
if ( autoAttributes[ contentObj.id ] )
{
contentObj.setup = autoSetup;
contentObj.commit = autoCommit;
}
} );
},
contents : [
{
id : 'info',
label : editor.lang.textfield.title,
title : editor.lang.textfield.title,
elements : [
{
type : 'hbox',
widths : [ '50%', '50%' ],
children :
[
{
id : '_cke_saved_name',
type : 'text',
label : editor.lang.textfield.name,
'default' : '',
accessKey : 'N',
setup : function( element )
{
this.setValue(
element.data( 'cke-saved-name' ) ||
element.getAttribute( 'name' ) ||
'' );
},
commit : function( data )
{
var element = data.element;
if ( this.getValue() )
element.data( 'cke-saved-name', this.getValue() );
else
{
element.data( 'cke-saved-name', false );
element.removeAttribute( 'name' );
}
}
},
{
id : 'value',
type : 'text',
label : editor.lang.textfield.value,
'default' : '',
accessKey : 'V'
}
]
},
{
type : 'hbox',
widths : [ '50%', '50%' ],
children :
[
{
id : 'size',
type : 'text',
label : editor.lang.textfield.charWidth,
'default' : '',
accessKey : 'C',
style : 'width:50px',
validate : CKEDITOR.dialog.validate.integer( editor.lang.common.validateNumberFailed )
},
{
id : 'maxLength',
type : 'text',
label : editor.lang.textfield.maxChars,
'default' : '',
accessKey : 'M',
style : 'width:50px',
validate : CKEDITOR.dialog.validate.integer( editor.lang.common.validateNumberFailed )
}
],
onLoad : function()
{
// Repaint the style for IE7 (#6068)
if ( CKEDITOR.env.ie7Compat )
this.getElement().setStyle( 'zoom', '100%' );
}
},
{
id : 'type',
type : 'select',
label : editor.lang.textfield.type,
'default' : 'text',
accessKey : 'M',
items :
[
[ editor.lang.textfield.typeText, 'text' ],
[ editor.lang.textfield.typePass, 'password' ]
],
setup : function( element )
{
this.setValue( element.getAttribute( 'type' ) );
},
commit : function( data )
{
var element = data.element;
if ( CKEDITOR.env.ie )
{
var elementType = element.getAttribute( 'type' );
var myType = this.getValue();
if ( elementType != myType )
{
var replace = CKEDITOR.dom.element.createFromHtml( '<input type="' + myType + '"></input>', editor.document );
element.copyAttributes( replace, { type : 1 } );
replace.replace( element );
editor.getSelection().selectElement( replace );
data.element = replace;
}
}
else
element.setAttribute( 'type', this.getValue() );
}
}
]
}
]
};
});
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.dialog.add( 'hiddenfield', function( editor )
{
return {
title : editor.lang.hidden.title,
hiddenField : null,
minWidth : 350,
minHeight : 110,
onShow : function()
{
delete this.hiddenField;
var editor = this.getParentEditor(),
selection = editor.getSelection(),
element = selection.getSelectedElement();
if ( element && element.data( 'cke-real-element-type' ) && element.data( 'cke-real-element-type' ) == 'hiddenfield' )
{
this.hiddenField = element;
element = editor.restoreRealElement( this.hiddenField );
this.setupContent( element );
selection.selectElement( this.hiddenField );
}
},
onOk : function()
{
var name = this.getValueOf( 'info', '_cke_saved_name' ),
value = this.getValueOf( 'info', 'value' ),
editor = this.getParentEditor(),
element = CKEDITOR.env.ie ? editor.document.createElement( '<input name="' + CKEDITOR.tools.htmlEncode( name ) + '">' ) : editor.document.createElement( 'input' );
element.setAttribute( 'type', 'hidden' );
this.commitContent( element );
var fakeElement = editor.createFakeElement( element, 'cke_hidden', 'hiddenfield' );
if ( !this.hiddenField )
editor.insertElement( fakeElement );
else
{
fakeElement.replace( this.hiddenField );
editor.getSelection().selectElement( fakeElement );
}
return true;
},
contents : [
{
id : 'info',
label : editor.lang.hidden.title,
title : editor.lang.hidden.title,
elements : [
{
id : '_cke_saved_name',
type : 'text',
label : editor.lang.hidden.name,
'default' : '',
accessKey : 'N',
setup : function( element )
{
this.setValue(
element.data( 'cke-saved-name' ) ||
element.getAttribute( 'name' ) ||
'' );
},
commit : function( element )
{
if ( this.getValue() )
element.setAttribute( 'name', this.getValue() );
else
{
element.removeAttribute( 'name' );
}
}
},
{
id : 'value',
type : 'text',
label : editor.lang.hidden.value,
'default' : '',
accessKey : 'V',
setup : function( element )
{
this.setValue( element.getAttribute( 'value' ) || '' );
},
commit : function( element )
{
if ( this.getValue() )
element.setAttribute( 'value', this.getValue() );
else
element.removeAttribute( 'value' );
}
}
]
}
]
};
});
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.dialog.add( 'button', function( editor )
{
return {
title : editor.lang.button.title,
minWidth : 350,
minHeight : 150,
onShow : function()
{
delete this.button;
var element = this.getParentEditor().getSelection().getSelectedElement();
if ( element && element.is( 'input' ) )
{
var type = element.getAttribute( 'type' );
if ( type in { button:1, reset:1, submit:1 } )
{
this.button = element;
this.setupContent( element );
}
}
},
onOk : function()
{
var editor,
element = this.button,
isInsertMode = !element;
if ( isInsertMode )
{
editor = this.getParentEditor();
element = editor.document.createElement( 'input' );
}
if ( isInsertMode )
editor.insertElement( element );
this.commitContent( { element : element } );
},
contents : [
{
id : 'info',
label : editor.lang.button.title,
title : editor.lang.button.title,
elements : [
{
id : '_cke_saved_name',
type : 'text',
label : editor.lang.common.name,
'default' : '',
setup : function( element )
{
this.setValue(
element.data( 'cke-saved-name' ) ||
element.getAttribute( 'name' ) ||
'' );
},
commit : function( data )
{
var element = data.element;
if ( this.getValue() )
element.data( 'cke-saved-name', this.getValue() );
else
{
element.data( 'cke-saved-name', false );
element.removeAttribute( 'name' );
}
}
},
{
id : 'value',
type : 'text',
label : editor.lang.button.text,
accessKey : 'V',
'default' : '',
setup : function( element )
{
this.setValue( element.getAttribute( 'value' ) || '' );
},
commit : function( data )
{
var element = data.element;
if ( this.getValue() )
element.setAttribute( 'value', this.getValue() );
else
element.removeAttribute( 'value' );
}
},
{
id : 'type',
type : 'select',
label : editor.lang.button.type,
'default' : 'button',
accessKey : 'T',
items :
[
[ editor.lang.button.typeBtn, 'button' ],
[ editor.lang.button.typeSbm, 'submit' ],
[ editor.lang.button.typeRst, 'reset' ]
],
setup : function( element )
{
this.setValue( element.getAttribute( 'type' ) || '' );
},
commit : function( data )
{
var element = data.element;
if ( CKEDITOR.env.ie )
{
var elementType = element.getAttribute( 'type' );
var currentType = this.getValue();
if ( currentType != elementType )
{
var replace = CKEDITOR.dom.element.createFromHtml( '<input type="' + currentType +
'"></input>', editor.document );
element.copyAttributes( replace, { type : 1 } );
replace.replace( element );
editor.getSelection().selectElement( replace );
data.element = replace;
}
}
else
element.setAttribute( 'type', this.getValue() );
}
}
]
}
]
};
});
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.dialog.add( 'form', function( editor )
{
var autoAttributes =
{
action : 1,
id : 1,
method : 1,
enctype : 1,
target : 1
};
return {
title : editor.lang.form.title,
minWidth : 350,
minHeight : 200,
onShow : function()
{
delete this.form;
var element = this.getParentEditor().getSelection().getStartElement();
var form = element && element.getAscendant( 'form', true );
if ( form )
{
this.form = form;
this.setupContent( form );
}
},
onOk : function()
{
var editor,
element = this.form,
isInsertMode = !element;
if ( isInsertMode )
{
editor = this.getParentEditor();
element = editor.document.createElement( 'form' );
element.append( editor.document.createElement( 'br' ) );
}
if ( isInsertMode )
editor.insertElement( element );
this.commitContent( element );
},
onLoad : function()
{
function autoSetup( element )
{
this.setValue( element.getAttribute( this.id ) || '' );
}
function autoCommit( element )
{
if ( this.getValue() )
element.setAttribute( this.id, this.getValue() );
else
element.removeAttribute( this.id );
}
this.foreach( function( contentObj )
{
if ( autoAttributes[ contentObj.id ] )
{
contentObj.setup = autoSetup;
contentObj.commit = autoCommit;
}
} );
},
contents : [
{
id : 'info',
label : editor.lang.form.title,
title : editor.lang.form.title,
elements : [
{
id : 'txtName',
type : 'text',
label : editor.lang.common.name,
'default' : '',
accessKey : 'N',
setup : function( element )
{
this.setValue( element.data( 'cke-saved-name' ) ||
element.getAttribute( 'name' ) ||
'' );
},
commit : function( element )
{
if ( this.getValue() )
element.data( 'cke-saved-name', this.getValue() );
else
{
element.data( 'cke-saved-name', false );
element.removeAttribute( 'name' );
}
}
},
{
id : 'action',
type : 'text',
label : editor.lang.form.action,
'default' : '',
accessKey : 'T'
},
{
type : 'hbox',
widths : [ '45%', '55%' ],
children :
[
{
id : 'id',
type : 'text',
label : editor.lang.common.id,
'default' : '',
accessKey : 'I'
},
{
id : 'enctype',
type : 'select',
label : editor.lang.form.encoding,
style : 'width:100%',
accessKey : 'E',
'default' : '',
items :
[
[ '' ],
[ 'text/plain' ],
[ 'multipart/form-data' ],
[ 'application/x-www-form-urlencoded' ]
]
}
]
},
{
type : 'hbox',
widths : [ '45%', '55%' ],
children :
[
{
id : 'target',
type : 'select',
label : editor.lang.common.target,
style : 'width:100%',
accessKey : 'M',
'default' : '',
items :
[
[ editor.lang.common.notSet, '' ],
[ editor.lang.common.targetNew, '_blank' ],
[ editor.lang.common.targetTop, '_top' ],
[ editor.lang.common.targetSelf, '_self' ],
[ editor.lang.common.targetParent, '_parent' ]
]
},
{
id : 'method',
type : 'select',
label : editor.lang.form.method,
accessKey : 'M',
'default' : 'GET',
items :
[
[ 'GET', 'get' ],
[ 'POST', 'post' ]
]
}
]
}
]
}
]
};
});
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.dialog.add( 'textarea', function( editor )
{
return {
title : editor.lang.textarea.title,
minWidth : 350,
minHeight : 150,
onShow : function()
{
delete this.textarea;
var element = this.getParentEditor().getSelection().getSelectedElement();
if ( element && element.getName() == "textarea" )
{
this.textarea = element;
this.setupContent( element );
}
},
onOk : function()
{
var editor,
element = this.textarea,
isInsertMode = !element;
if ( isInsertMode )
{
editor = this.getParentEditor();
element = editor.document.createElement( 'textarea' );
}
this.commitContent( element );
if ( isInsertMode )
editor.insertElement( element );
},
contents : [
{
id : 'info',
label : editor.lang.textarea.title,
title : editor.lang.textarea.title,
elements : [
{
id : '_cke_saved_name',
type : 'text',
label : editor.lang.common.name,
'default' : '',
accessKey : 'N',
setup : function( element )
{
this.setValue(
element.data( 'cke-saved-name' ) ||
element.getAttribute( 'name' ) ||
'' );
},
commit : function( element )
{
if ( this.getValue() )
element.data( 'cke-saved-name', this.getValue() );
else
{
element.data( 'cke-saved-name', false );
element.removeAttribute( 'name' );
}
}
},
{
id : 'cols',
type : 'text',
label : editor.lang.textarea.cols,
'default' : '',
accessKey : 'C',
style : 'width:50px',
validate : CKEDITOR.dialog.validate.integer( editor.lang.common.validateNumberFailed ),
setup : function( element )
{
var value = element.hasAttribute( 'cols' ) && element.getAttribute( 'cols' );
this.setValue( value || '' );
},
commit : function( element )
{
if ( this.getValue() )
element.setAttribute( 'cols', this.getValue() );
else
element.removeAttribute( 'cols' );
}
},
{
id : 'rows',
type : 'text',
label : editor.lang.textarea.rows,
'default' : '',
accessKey : 'R',
style : 'width:50px',
validate : CKEDITOR.dialog.validate.integer( editor.lang.common.validateNumberFailed ),
setup : function( element )
{
var value = element.hasAttribute( 'rows' ) && element.getAttribute( 'rows' );
this.setValue( value || '' );
},
commit : function( element )
{
if ( this.getValue() )
element.setAttribute( 'rows', this.getValue() );
else
element.removeAttribute( 'rows' );
}
}
]
}
]
};
});
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.dialog.add( 'radio', function( editor )
{
return {
title : editor.lang.checkboxAndRadio.radioTitle,
minWidth : 350,
minHeight : 140,
onShow : function()
{
delete this.radioButton;
var element = this.getParentEditor().getSelection().getSelectedElement();
if ( element && element.getName() == 'input' && element.getAttribute( 'type' ) == 'radio' )
{
this.radioButton = element;
this.setupContent( element );
}
},
onOk : function()
{
var editor,
element = this.radioButton,
isInsertMode = !element;
if ( isInsertMode )
{
editor = this.getParentEditor();
element = editor.document.createElement( 'input' );
element.setAttribute( 'type', 'radio' );
}
if ( isInsertMode )
editor.insertElement( element );
this.commitContent( { element : element } );
},
contents : [
{
id : 'info',
label : editor.lang.checkboxAndRadio.radioTitle,
title : editor.lang.checkboxAndRadio.radioTitle,
elements : [
{
id : 'name',
type : 'text',
label : editor.lang.common.name,
'default' : '',
accessKey : 'N',
setup : function( element )
{
this.setValue(
element.data( 'cke-saved-name' ) ||
element.getAttribute( 'name' ) ||
'' );
},
commit : function( data )
{
var element = data.element;
if ( this.getValue() )
element.data( 'cke-saved-name', this.getValue() );
else
{
element.data( 'cke-saved-name', false );
element.removeAttribute( 'name' );
}
}
},
{
id : 'value',
type : 'text',
label : editor.lang.checkboxAndRadio.value,
'default' : '',
accessKey : 'V',
setup : function( element )
{
this.setValue( element.getAttribute( 'value' ) || '' );
},
commit : function( data )
{
var element = data.element;
if ( this.getValue() )
element.setAttribute( 'value', this.getValue() );
else
element.removeAttribute( 'value' );
}
},
{
id : 'checked',
type : 'checkbox',
label : editor.lang.checkboxAndRadio.selected,
'default' : '',
accessKey : 'S',
value : "checked",
setup : function( element )
{
this.setValue( element.getAttribute( 'checked' ) );
},
commit : function( data )
{
var element = data.element;
if ( !CKEDITOR.env.ie )
{
if ( this.getValue() )
element.setAttribute( 'checked', 'checked' );
else
element.removeAttribute( 'checked' );
}
else
{
var isElementChecked = element.getAttribute( 'checked' );
var isChecked = !!this.getValue();
if ( isElementChecked != isChecked )
{
var replace = CKEDITOR.dom.element.createFromHtml( '<input type="radio"'
+ ( isChecked ? ' checked="checked"' : '' )
+ '></input>', editor.document );
element.copyAttributes( replace, { type : 1, checked : 1 } );
replace.replace( element );
editor.getSelection().selectElement( replace );
data.element = replace;
}
}
}
}
]
}
]
};
});
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.dialog.add( 'checkbox', function( editor )
{
return {
title : editor.lang.checkboxAndRadio.checkboxTitle,
minWidth : 350,
minHeight : 140,
onShow : function()
{
delete this.checkbox;
var element = this.getParentEditor().getSelection().getSelectedElement();
if ( element && element.getAttribute( 'type' ) == 'checkbox' )
{
this.checkbox = element;
this.setupContent( element );
}
},
onOk : function()
{
var editor,
element = this.checkbox,
isInsertMode = !element;
if ( isInsertMode )
{
editor = this.getParentEditor();
element = editor.document.createElement( 'input' );
element.setAttribute( 'type', 'checkbox' );
editor.insertElement( element );
}
this.commitContent( { element : element } );
},
contents : [
{
id : 'info',
label : editor.lang.checkboxAndRadio.checkboxTitle,
title : editor.lang.checkboxAndRadio.checkboxTitle,
startupFocus : 'txtName',
elements : [
{
id : 'txtName',
type : 'text',
label : editor.lang.common.name,
'default' : '',
accessKey : 'N',
setup : function( element )
{
this.setValue(
element.data( 'cke-saved-name' ) ||
element.getAttribute( 'name' ) ||
'' );
},
commit : function( data )
{
var element = data.element;
// IE failed to update 'name' property on input elements, protect it now.
if ( this.getValue() )
element.data( 'cke-saved-name', this.getValue() );
else
{
element.data( 'cke-saved-name', false );
element.removeAttribute( 'name' );
}
}
},
{
id : 'txtValue',
type : 'text',
label : editor.lang.checkboxAndRadio.value,
'default' : '',
accessKey : 'V',
setup : function( element )
{
var value = element.getAttribute( 'value' );
// IE Return 'on' as default attr value.
this.setValue( CKEDITOR.env.ie && value == 'on' ? '' : value );
},
commit : function( data )
{
var element = data.element,
value = this.getValue();
if ( value && !( CKEDITOR.env.ie && value == 'on' ) )
element.setAttribute( 'value', value );
else
{
if ( CKEDITOR.env.ie )
{
// Remove attribute 'value' of checkbox (#4721).
var checkbox = new CKEDITOR.dom.element( 'input', element.getDocument() );
element.copyAttributes( checkbox, { value: 1 } );
checkbox.replace( element );
editor.getSelection().selectElement( checkbox );
data.element = checkbox;
}
else
element.removeAttribute( 'value' );
}
}
},
{
id : 'cmbSelected',
type : 'checkbox',
label : editor.lang.checkboxAndRadio.selected,
'default' : '',
accessKey : 'S',
value : "checked",
setup : function( element )
{
this.setValue( element.getAttribute( 'checked' ) );
},
commit : function( data )
{
var element = data.element;
if ( CKEDITOR.env.ie )
{
var isElementChecked = !!element.getAttribute( 'checked' ),
isChecked = !!this.getValue();
if ( isElementChecked != isChecked )
{
var replace = CKEDITOR.dom.element.createFromHtml( '<input type="checkbox"'
+ ( isChecked ? ' checked="checked"' : '' )
+ '/>', editor.document );
element.copyAttributes( replace, { type : 1, checked : 1 } );
replace.replace( element );
editor.getSelection().selectElement( replace );
data.element = replace;
}
}
else
{
var value = this.getValue();
if ( value )
element.setAttribute( 'checked', 'checked' );
else
element.removeAttribute( 'checked' );
}
}
}
]
}
]
};
});
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
// Register a plugin named "sample".
CKEDITOR.plugins.add( 'keystrokes',
{
beforeInit : function( editor )
{
/**
* Controls keystrokes typing in this editor instance.
* @name CKEDITOR.editor.prototype.keystrokeHandler
* @type CKEDITOR.keystrokeHandler
* @example
*/
editor.keystrokeHandler = new CKEDITOR.keystrokeHandler( editor );
editor.specialKeys = {};
},
init : function( editor )
{
var keystrokesConfig = editor.config.keystrokes,
blockedConfig = editor.config.blockedKeystrokes;
var keystrokes = editor.keystrokeHandler.keystrokes,
blockedKeystrokes = editor.keystrokeHandler.blockedKeystrokes;
for ( var i = 0 ; i < keystrokesConfig.length ; i++ )
keystrokes[ keystrokesConfig[i][0] ] = keystrokesConfig[i][1];
for ( i = 0 ; i < blockedConfig.length ; i++ )
blockedKeystrokes[ blockedConfig[i] ] = 1;
}
});
/**
* Controls keystrokes typing in an editor instance.
* @constructor
* @param {CKEDITOR.editor} editor The editor instance.
* @example
*/
CKEDITOR.keystrokeHandler = function( editor )
{
if ( editor.keystrokeHandler )
return editor.keystrokeHandler;
/**
* List of keystrokes associated to commands. Each entry points to the
* command to be executed.
* @type Object
* @example
*/
this.keystrokes = {};
/**
* List of keystrokes that should be blocked if not defined at
* {@link keystrokes}. In this way it is possible to block the default
* browser behavior for those keystrokes.
* @type Object
* @example
*/
this.blockedKeystrokes = {};
this._ =
{
editor : editor
};
return this;
};
(function()
{
var cancel;
var onKeyDown = function( event )
{
// The DOM event object is passed by the "data" property.
event = event.data;
var keyCombination = event.getKeystroke();
var command = this.keystrokes[ keyCombination ];
var editor = this._.editor;
cancel = ( editor.fire( 'key', { keyCode : keyCombination } ) === true );
if ( !cancel )
{
if ( command )
{
var data = { from : 'keystrokeHandler' };
cancel = ( editor.execCommand( command, data ) !== false );
}
if ( !cancel )
{
var handler = editor.specialKeys[ keyCombination ];
cancel = ( handler && handler( editor ) === true );
if ( !cancel )
cancel = !!this.blockedKeystrokes[ keyCombination ];
}
}
if ( cancel )
event.preventDefault( true );
return !cancel;
};
var onKeyPress = function( event )
{
if ( cancel )
{
cancel = false;
event.data.preventDefault( true );
}
};
CKEDITOR.keystrokeHandler.prototype =
{
/**
* Attaches this keystroke handle to a DOM object. Keystrokes typed
** over this object will get handled by this keystrokeHandler.
* @param {CKEDITOR.dom.domObject} domObject The DOM object to attach
* to.
* @example
*/
attach : function( domObject )
{
// For most browsers, it is enough to listen to the keydown event
// only.
domObject.on( 'keydown', onKeyDown, this );
// Some browsers instead, don't cancel key events in the keydown, but in the
// keypress. So we must do a longer trip in those cases.
if ( CKEDITOR.env.opera || ( CKEDITOR.env.gecko && CKEDITOR.env.mac ) )
domObject.on( 'keypress', onKeyPress, this );
}
};
})();
/**
* A list of keystrokes to be blocked if not defined in the {@link CKEDITOR.config.keystrokes}
* setting. In this way it is possible to block the default browser behavior
* for those keystrokes.
* @type Array
* @default (see example)
* @example
* // This is actually the default value.
* config.blockedKeystrokes =
* [
* CKEDITOR.CTRL + 66 /*B*/,
* CKEDITOR.CTRL + 73 /*I*/,
* CKEDITOR.CTRL + 85 /*U*/
* ];
*/
CKEDITOR.config.blockedKeystrokes =
[
CKEDITOR.CTRL + 66 /*B*/,
CKEDITOR.CTRL + 73 /*I*/,
CKEDITOR.CTRL + 85 /*U*/
];
/**
* A list associating keystrokes to editor commands. Each element in the list
* is an array where the first item is the keystroke, and the second is the
* name of the command to be executed.
* @type Array
* @default (see example)
* @example
* // This is actually the default value.
* config.keystrokes =
* [
* [ CKEDITOR.ALT + 121 /*F10*/, 'toolbarFocus' ],
* [ CKEDITOR.ALT + 122 /*F11*/, 'elementsPathFocus' ],
*
* [ CKEDITOR.SHIFT + 121 /*F10*/, 'contextMenu' ],
*
* [ CKEDITOR.CTRL + 90 /*Z*/, 'undo' ],
* [ CKEDITOR.CTRL + 89 /*Y*/, 'redo' ],
* [ CKEDITOR.CTRL + CKEDITOR.SHIFT + 90 /*Z*/, 'redo' ],
*
* [ CKEDITOR.CTRL + 76 /*L*/, 'link' ],
*
* [ CKEDITOR.CTRL + 66 /*B*/, 'bold' ],
* [ CKEDITOR.CTRL + 73 /*I*/, 'italic' ],
* [ CKEDITOR.CTRL + 85 /*U*/, 'underline' ],
*
* [ CKEDITOR.ALT + 109 /*-*/, 'toolbarCollapse' ]
* ];
*/
CKEDITOR.config.keystrokes =
[
[ CKEDITOR.ALT + 121 /*F10*/, 'toolbarFocus' ],
[ CKEDITOR.ALT + 122 /*F11*/, 'elementsPathFocus' ],
[ CKEDITOR.SHIFT + 121 /*F10*/, 'contextMenu' ],
[ CKEDITOR.CTRL + CKEDITOR.SHIFT + 121 /*F10*/, 'contextMenu' ],
[ CKEDITOR.CTRL + 90 /*Z*/, 'undo' ],
[ CKEDITOR.CTRL + 89 /*Y*/, 'redo' ],
[ CKEDITOR.CTRL + CKEDITOR.SHIFT + 90 /*Z*/, 'redo' ],
[ CKEDITOR.CTRL + 76 /*L*/, 'link' ],
[ CKEDITOR.CTRL + 66 /*B*/, 'bold' ],
[ CKEDITOR.CTRL + 73 /*I*/, 'italic' ],
[ CKEDITOR.CTRL + 85 /*U*/, 'underline' ],
[ CKEDITOR.ALT + 109 /*-*/, 'toolbarCollapse' ],
[ CKEDITOR.ALT + 48 /*0*/, 'a11yHelp' ]
];
/**
* Fired when any keyboard key (or combination) is pressed into the editing area.
* @name CKEDITOR#key
* @event
* @param {Number} data.keyCode A number representing the key code (or
* combination). It is the sum of the current key code and the
* {@link CKEDITOR.CTRL}, {@link CKEDITOR.SHIFT} and {@link CKEDITOR.ALT}
* constants, if those are pressed.
*/
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @file DOM iterator, which iterates over list items, lines and paragraphs.
*/
CKEDITOR.plugins.add( 'domiterator' );
(function()
{
/**
* @name CKEDITOR.dom.iterator
*/
function iterator( range )
{
if ( arguments.length < 1 )
return;
this.range = range;
this.forceBrBreak = 0;
// Whether include <br>s into the enlarged range.(#3730).
this.enlargeBr = 1;
this.enforceRealBlocks = 0;
this._ || ( this._ = {} );
}
var beginWhitespaceRegex = /^[\r\n\t ]+$/,
isBookmark = CKEDITOR.dom.walker.bookmark();
iterator.prototype = {
getNextParagraph : function( blockTag )
{
// The block element to be returned.
var block;
// The range object used to identify the paragraph contents.
var range;
// Indicats that the current element in the loop is the last one.
var isLast;
// Indicate at least one of the range boundaries is inside a preformat block.
var touchPre;
// Instructs to cleanup remaining BRs.
var removePreviousBr, removeLastBr;
// This is the first iteration. Let's initialize it.
if ( !this._.lastNode )
{
range = this.range.clone();
// Shrink the range to exclude harmful "noises" (#4087, #4450, #5435).
range.shrink( CKEDITOR.NODE_ELEMENT, true );
touchPre = range.endContainer.hasAscendant( 'pre', true )
|| range.startContainer.hasAscendant( 'pre', true );
range.enlarge( this.forceBrBreak && !touchPre || !this.enlargeBr ?
CKEDITOR.ENLARGE_LIST_ITEM_CONTENTS : CKEDITOR.ENLARGE_BLOCK_CONTENTS );
var walker = new CKEDITOR.dom.walker( range ),
ignoreBookmarkTextEvaluator = CKEDITOR.dom.walker.bookmark( true, true );
// Avoid anchor inside bookmark inner text.
walker.evaluator = ignoreBookmarkTextEvaluator;
this._.nextNode = walker.next();
// TODO: It's better to have walker.reset() used here.
walker = new CKEDITOR.dom.walker( range );
walker.evaluator = ignoreBookmarkTextEvaluator;
var lastNode = walker.previous();
this._.lastNode = lastNode.getNextSourceNode( true );
// We may have an empty text node at the end of block due to [3770].
// If that node is the lastNode, it would cause our logic to leak to the
// next block.(#3887)
if ( this._.lastNode &&
this._.lastNode.type == CKEDITOR.NODE_TEXT &&
!CKEDITOR.tools.trim( this._.lastNode.getText() ) &&
this._.lastNode.getParent().isBlockBoundary() )
{
var testRange = new CKEDITOR.dom.range( range.document );
testRange.moveToPosition( this._.lastNode, CKEDITOR.POSITION_AFTER_END );
if ( testRange.checkEndOfBlock() )
{
var path = new CKEDITOR.dom.elementPath( testRange.endContainer );
var lastBlock = path.block || path.blockLimit;
this._.lastNode = lastBlock.getNextSourceNode( true );
}
}
// Probably the document end is reached, we need a marker node.
if ( !this._.lastNode )
{
this._.lastNode = this._.docEndMarker = range.document.createText( '' );
this._.lastNode.insertAfter( lastNode );
}
// Let's reuse this variable.
range = null;
}
var currentNode = this._.nextNode;
lastNode = this._.lastNode;
this._.nextNode = null;
while ( currentNode )
{
// closeRange indicates that a paragraph boundary has been found,
// so the range can be closed.
var closeRange = 0,
parentPre = currentNode.hasAscendant( 'pre' );
// includeNode indicates that the current node is good to be part
// of the range. By default, any non-element node is ok for it.
var includeNode = ( currentNode.type != CKEDITOR.NODE_ELEMENT ),
continueFromSibling = 0;
// If it is an element node, let's check if it can be part of the
// range.
if ( !includeNode )
{
var nodeName = currentNode.getName();
if ( currentNode.isBlockBoundary( this.forceBrBreak &&
!parentPre && { br : 1 } ) )
{
// <br> boundaries must be part of the range. It will
// happen only if ForceBrBreak.
if ( nodeName == 'br' )
includeNode = 1;
else if ( !range && !currentNode.getChildCount() && nodeName != 'hr' )
{
// If we have found an empty block, and haven't started
// the range yet, it means we must return this block.
block = currentNode;
isLast = currentNode.equals( lastNode );
break;
}
// The range must finish right before the boundary,
// including possibly skipped empty spaces. (#1603)
if ( range )
{
range.setEndAt( currentNode, CKEDITOR.POSITION_BEFORE_START );
// The found boundary must be set as the next one at this
// point. (#1717)
if ( nodeName != 'br' )
this._.nextNode = currentNode;
}
closeRange = 1;
}
else
{
// If we have child nodes, let's check them.
if ( currentNode.getFirst() )
{
// If we don't have a range yet, let's start it.
if ( !range )
{
range = new CKEDITOR.dom.range( this.range.document );
range.setStartAt( currentNode, CKEDITOR.POSITION_BEFORE_START );
}
currentNode = currentNode.getFirst();
continue;
}
includeNode = 1;
}
}
else if ( currentNode.type == CKEDITOR.NODE_TEXT )
{
// Ignore normal whitespaces (i.e. not including or
// other unicode whitespaces) before/after a block node.
if ( beginWhitespaceRegex.test( currentNode.getText() ) )
includeNode = 0;
}
// The current node is good to be part of the range and we are
// starting a new range, initialize it first.
if ( includeNode && !range )
{
range = new CKEDITOR.dom.range( this.range.document );
range.setStartAt( currentNode, CKEDITOR.POSITION_BEFORE_START );
}
// The last node has been found.
isLast = ( ( !closeRange || includeNode ) && currentNode.equals( lastNode ) );
// If we are in an element boundary, let's check if it is time
// to close the range, otherwise we include the parent within it.
if ( range && !closeRange )
{
while ( !currentNode.getNext() && !isLast )
{
var parentNode = currentNode.getParent();
if ( parentNode.isBlockBoundary( this.forceBrBreak
&& !parentPre && { br : 1 } ) )
{
closeRange = 1;
isLast = isLast || ( parentNode.equals( lastNode) );
break;
}
currentNode = parentNode;
includeNode = 1;
isLast = ( currentNode.equals( lastNode ) );
continueFromSibling = 1;
}
}
// Now finally include the node.
if ( includeNode )
range.setEndAt( currentNode, CKEDITOR.POSITION_AFTER_END );
currentNode = currentNode.getNextSourceNode( continueFromSibling, null, lastNode );
isLast = !currentNode;
// We have found a block boundary. Let's close the range and move out of the
// loop.
if ( isLast || ( closeRange && range ) )
break;
}
// Now, based on the processed range, look for (or create) the block to be returned.
if ( !block )
{
// If no range has been found, this is the end.
if ( !range )
{
this._.docEndMarker && this._.docEndMarker.remove();
this._.nextNode = null;
return null;
}
var startPath = new CKEDITOR.dom.elementPath( range.startContainer );
var startBlockLimit = startPath.blockLimit,
checkLimits = { div : 1, th : 1, td : 1 };
block = startPath.block;
if ( !block
&& !this.enforceRealBlocks
&& checkLimits[ startBlockLimit.getName() ]
&& range.checkStartOfBlock()
&& range.checkEndOfBlock() )
block = startBlockLimit;
else if ( !block || ( this.enforceRealBlocks && block.getName() == 'li' ) )
{
// Create the fixed block.
block = this.range.document.createElement( blockTag || 'p' );
// Move the contents of the temporary range to the fixed block.
range.extractContents().appendTo( block );
block.trim();
// Insert the fixed block into the DOM.
range.insertNode( block );
removePreviousBr = removeLastBr = true;
}
else if ( block.getName() != 'li' )
{
// If the range doesn't includes the entire contents of the
// block, we must split it, isolating the range in a dedicated
// block.
if ( !range.checkStartOfBlock() || !range.checkEndOfBlock() )
{
// The resulting block will be a clone of the current one.
block = block.clone( false );
// Extract the range contents, moving it to the new block.
range.extractContents().appendTo( block );
block.trim();
// Split the block. At this point, the range will be in the
// right position for our intents.
var splitInfo = range.splitBlock();
removePreviousBr = !splitInfo.wasStartOfBlock;
removeLastBr = !splitInfo.wasEndOfBlock;
// Insert the new block into the DOM.
range.insertNode( block );
}
}
else if ( !isLast )
{
// LIs are returned as is, with all their children (due to the
// nested lists). But, the next node is the node right after
// the current range, which could be an <li> child (nested
// lists) or the next sibling <li>.
this._.nextNode = ( block.equals( lastNode ) ? null :
range.getBoundaryNodes().endNode.getNextSourceNode( true, null, lastNode ) );
}
}
// Ignore bookmark nodes.(#3783)
var bookmarkGuard = CKEDITOR.dom.walker.bookmark( false, true );
if ( removePreviousBr )
{
var previousSibling = block.getPrevious();
if ( previousSibling && previousSibling.type == CKEDITOR.NODE_ELEMENT )
{
if ( previousSibling.getName() == 'br' )
previousSibling.remove();
else if ( previousSibling.getLast() && previousSibling.getLast().$.nodeName.toLowerCase() == 'br' )
previousSibling.getLast().remove();
}
}
if ( removeLastBr )
{
var lastChild = block.getLast();
if ( lastChild && lastChild.type == CKEDITOR.NODE_ELEMENT && lastChild.getName() == 'br' )
{
// Take care not to remove the block expanding <br> in non-IE browsers.
if ( CKEDITOR.env.ie
|| lastChild.getPrevious( bookmarkGuard )
|| lastChild.getNext( bookmarkGuard ) )
lastChild.remove();
}
}
// Get a reference for the next element. This is important because the
// above block can be removed or changed, so we can rely on it for the
// next interation.
if ( !this._.nextNode )
{
this._.nextNode = ( isLast || block.equals( lastNode ) ) ? null :
block.getNextSourceNode( true, null, lastNode );
}
if ( !bookmarkGuard( this._.nextNode ) )
{
this._.nextNode = this._.nextNode.getNextSourceNode( true, null, function( node )
{ return !node.equals( lastNode ) && bookmarkGuard( node ); } );
}
return block;
}
};
CKEDITOR.dom.range.prototype.createIterator = function()
{
return new iterator( this );
};
})();
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.add( 'table',
{
init : function( editor )
{
var table = CKEDITOR.plugins.table,
lang = editor.lang.table;
editor.addCommand( 'table', new CKEDITOR.dialogCommand( 'table' ) );
editor.addCommand( 'tableProperties', new CKEDITOR.dialogCommand( 'tableProperties' ) );
editor.ui.addButton( 'Table',
{
label : lang.toolbar,
command : 'table'
});
CKEDITOR.dialog.add( 'table', this.path + 'dialogs/table.js' );
CKEDITOR.dialog.add( 'tableProperties', this.path + 'dialogs/table.js' );
// If the "menu" plugin is loaded, register the menu items.
if ( editor.addMenuItems )
{
editor.addMenuItems(
{
table :
{
label : lang.menu,
command : 'tableProperties',
group : 'table',
order : 5
},
tabledelete :
{
label : lang.deleteTable,
command : 'tableDelete',
group : 'table',
order : 1
}
} );
}
editor.on( 'doubleclick', function( evt )
{
var element = evt.data.element;
if ( element.is( 'table' ) )
evt.data.dialog = 'tableProperties';
});
// If the "contextmenu" plugin is loaded, register the listeners.
if ( editor.contextMenu )
{
editor.contextMenu.addListener( function( element, selection )
{
if ( !element || element.isReadOnly() )
return null;
var isTable = element.hasAscendant( 'table', 1 );
if ( isTable )
{
return {
tabledelete : CKEDITOR.TRISTATE_OFF,
table : CKEDITOR.TRISTATE_OFF
};
}
return null;
} );
}
}
} );
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
(function()
{
var widthPattern = /^(\d+(?:\.\d+)?)(px|%)$/,
heightPattern = /^(\d+(?:\.\d+)?)px$/;
var commitValue = function( data )
{
var id = this.id;
if ( !data.info )
data.info = {};
data.info[id] = this.getValue();
};
function tableDialog( editor, command )
{
var makeElement = function( name )
{
return new CKEDITOR.dom.element( name, editor.document );
};
var dialogadvtab = editor.plugins.dialogadvtab;
return {
title : editor.lang.table.title,
minWidth : 310,
minHeight : CKEDITOR.env.ie ? 310 : 280,
onLoad : function()
{
var dialog = this;
var styles = dialog.getContentElement( 'advanced', 'advStyles' );
if ( styles )
{
styles.on( 'change', function( evt )
{
// Synchronize width value.
var width = this.getStyle( 'width', '' ),
txtWidth = dialog.getContentElement( 'info', 'txtWidth' ),
cmbWidthType = dialog.getContentElement( 'info', 'cmbWidthType' ),
isPx = 1;
if ( width )
{
isPx = ( width.length < 3 || width.substr( width.length - 1 ) != '%' );
width = parseInt( width, 10 );
}
txtWidth && txtWidth.setValue( width, true );
cmbWidthType && cmbWidthType.setValue( isPx ? 'pixels' : 'percents', true );
// Synchronize height value.
var height = this.getStyle( 'height', '' ),
txtHeight = dialog.getContentElement( 'info', 'txtHeight' );
height && ( height = parseInt( height, 10 ) );
txtHeight && txtHeight.setValue( height, true );
});
}
},
onShow : function()
{
// Detect if there's a selected table.
var selection = editor.getSelection(),
ranges = selection.getRanges(),
selectedTable = null;
var rowsInput = this.getContentElement( 'info', 'txtRows' ),
colsInput = this.getContentElement( 'info', 'txtCols' ),
widthInput = this.getContentElement( 'info', 'txtWidth' ),
heightInput = this.getContentElement( 'info', 'txtHeight' );
if ( command == 'tableProperties' )
{
if ( ( selectedTable = selection.getSelectedElement() ) )
selectedTable = selectedTable.getAscendant( 'table', true );
else if ( ranges.length > 0 )
{
// Webkit could report the following range on cell selection (#4948):
// <table><tr><td>[ </td></tr></table>]
if ( CKEDITOR.env.webkit )
ranges[ 0 ].shrink( CKEDITOR.NODE_ELEMENT );
var rangeRoot = ranges[0].getCommonAncestor( true );
selectedTable = rangeRoot.getAscendant( 'table', true );
}
// Save a reference to the selected table, and push a new set of default values.
this._.selectedElement = selectedTable;
}
// Enable or disable the row, cols, width fields.
if ( selectedTable )
{
this.setupContent( selectedTable );
rowsInput && rowsInput.disable();
colsInput && colsInput.disable();
}
else
{
rowsInput && rowsInput.enable();
colsInput && colsInput.enable();
}
// Call the onChange method for the widht and height fields so
// they get reflected into the Advanced tab.
widthInput && widthInput.onChange();
heightInput && heightInput.onChange();
},
onOk : function()
{
if ( this._.selectedElement )
{
var selection = editor.getSelection(),
bms = selection.createBookmarks();
}
var table = this._.selectedElement || makeElement( 'table' ),
me = this,
data = {};
this.commitContent( data, table );
if ( data.info )
{
var info = data.info;
// Generate the rows and cols.
if ( !this._.selectedElement )
{
var tbody = table.append( makeElement( 'tbody' ) ),
rows = parseInt( info.txtRows, 10 ) || 0,
cols = parseInt( info.txtCols, 10 ) || 0;
for ( var i = 0 ; i < rows ; i++ )
{
var row = tbody.append( makeElement( 'tr' ) );
for ( var j = 0 ; j < cols ; j++ )
{
var cell = row.append( makeElement( 'td' ) );
if ( !CKEDITOR.env.ie )
cell.append( makeElement( 'br' ) );
}
}
}
// Modify the table headers. Depends on having rows and cols generated
// correctly so it can't be done in commit functions.
// Should we make a <thead>?
var headers = info.selHeaders;
if ( !table.$.tHead && ( headers == 'row' || headers == 'both' ) )
{
var thead = new CKEDITOR.dom.element( table.$.createTHead() );
tbody = table.getElementsByTag( 'tbody' ).getItem( 0 );
var theRow = tbody.getElementsByTag( 'tr' ).getItem( 0 );
// Change TD to TH:
for ( i = 0 ; i < theRow.getChildCount() ; i++ )
{
var th = theRow.getChild( i );
// Skip bookmark nodes. (#6155)
if ( th.type == CKEDITOR.NODE_ELEMENT && !th.data( 'cke-bookmark' ) )
{
th.renameNode( 'th' );
th.setAttribute( 'scope', 'col' );
}
}
thead.append( theRow.remove() );
}
if ( table.$.tHead !== null && !( headers == 'row' || headers == 'both' ) )
{
// Move the row out of the THead and put it in the TBody:
thead = new CKEDITOR.dom.element( table.$.tHead );
tbody = table.getElementsByTag( 'tbody' ).getItem( 0 );
var previousFirstRow = tbody.getFirst();
while ( thead.getChildCount() > 0 )
{
theRow = thead.getFirst();
for ( i = 0; i < theRow.getChildCount() ; i++ )
{
var newCell = theRow.getChild( i );
if ( newCell.type == CKEDITOR.NODE_ELEMENT )
{
newCell.renameNode( 'td' );
newCell.removeAttribute( 'scope' );
}
}
theRow.insertBefore( previousFirstRow );
}
thead.remove();
}
// Should we make all first cells in a row TH?
if ( !this.hasColumnHeaders && ( headers == 'col' || headers == 'both' ) )
{
for ( row = 0 ; row < table.$.rows.length ; row++ )
{
newCell = new CKEDITOR.dom.element( table.$.rows[ row ].cells[ 0 ] );
newCell.renameNode( 'th' );
newCell.setAttribute( 'scope', 'row' );
}
}
// Should we make all first TH-cells in a row make TD? If 'yes' we do it the other way round :-)
if ( ( this.hasColumnHeaders ) && !( headers == 'col' || headers == 'both' ) )
{
for ( i = 0 ; i < table.$.rows.length ; i++ )
{
row = new CKEDITOR.dom.element( table.$.rows[i] );
if ( row.getParent().getName() == 'tbody' )
{
newCell = new CKEDITOR.dom.element( row.$.cells[0] );
newCell.renameNode( 'td' );
newCell.removeAttribute( 'scope' );
}
}
}
// Set the width and height.
var styles = [];
if ( info.txtHeight )
table.setStyle( 'height', CKEDITOR.tools.cssLength( info.txtHeight ) );
else
table.removeStyle( 'height' );
if ( info.txtWidth )
{
var type = info.cmbWidthType || 'pixels';
table.setStyle( 'width', info.txtWidth + ( type == 'pixels' ? 'px' : '%' ) );
}
else
table.removeStyle( 'width' );
if ( !table.getAttribute( 'style' ) )
table.removeAttribute( 'style' );
}
// Insert the table element if we're creating one.
if ( !this._.selectedElement )
editor.insertElement( table );
// Properly restore the selection inside table. (#4822)
else
selection.selectBookmarks( bms );
return true;
},
contents : [
{
id : 'info',
label : editor.lang.table.title,
elements :
[
{
type : 'hbox',
widths : [ null, null ],
styles : [ 'vertical-align:top' ],
children :
[
{
type : 'vbox',
padding : 0,
children :
[
{
type : 'text',
id : 'txtRows',
'default' : 3,
label : editor.lang.table.rows,
required : true,
style : 'width:5em',
validate : function()
{
var pass = true,
value = this.getValue();
pass = pass && CKEDITOR.dialog.validate.integer()( value )
&& value > 0;
if ( !pass )
{
alert( editor.lang.table.invalidRows );
this.select();
}
return pass;
},
setup : function( selectedElement )
{
this.setValue( selectedElement.$.rows.length );
},
commit : commitValue
},
{
type : 'text',
id : 'txtCols',
'default' : 2,
label : editor.lang.table.columns,
required : true,
style : 'width:5em',
validate : function()
{
var pass = true,
value = this.getValue();
pass = pass && CKEDITOR.dialog.validate.integer()( value )
&& value > 0;
if ( !pass )
{
alert( editor.lang.table.invalidCols );
this.select();
}
return pass;
},
setup : function( selectedTable )
{
this.setValue( selectedTable.$.rows[0].cells.length);
},
commit : commitValue
},
{
type : 'html',
html : ' '
},
{
type : 'select',
id : 'selHeaders',
'default' : '',
label : editor.lang.table.headers,
items :
[
[ editor.lang.table.headersNone, '' ],
[ editor.lang.table.headersRow, 'row' ],
[ editor.lang.table.headersColumn, 'col' ],
[ editor.lang.table.headersBoth, 'both' ]
],
setup : function( selectedTable )
{
// Fill in the headers field.
var dialog = this.getDialog();
dialog.hasColumnHeaders = true;
// Check if all the first cells in every row are TH
for ( var row = 0 ; row < selectedTable.$.rows.length ; row++ )
{
// If just one cell isn't a TH then it isn't a header column
if ( selectedTable.$.rows[row].cells[0].nodeName.toLowerCase() != 'th' )
{
dialog.hasColumnHeaders = false;
break;
}
}
// Check if the table contains <thead>.
if ( ( selectedTable.$.tHead !== null) )
this.setValue( dialog.hasColumnHeaders ? 'both' : 'row' );
else
this.setValue( dialog.hasColumnHeaders ? 'col' : '' );
},
commit : commitValue
},
{
type : 'text',
id : 'txtBorder',
'default' : 1,
label : editor.lang.table.border,
style : 'width:3em',
validate : CKEDITOR.dialog.validate['number']( editor.lang.table.invalidBorder ),
setup : function( selectedTable )
{
this.setValue( selectedTable.getAttribute( 'border' ) || '' );
},
commit : function( data, selectedTable )
{
if ( this.getValue() )
selectedTable.setAttribute( 'border', this.getValue() );
else
selectedTable.removeAttribute( 'border' );
}
},
{
id : 'cmbAlign',
type : 'select',
'default' : '',
label : editor.lang.common.align,
items :
[
[ editor.lang.common.notSet , ''],
[ editor.lang.common.alignLeft , 'left'],
[ editor.lang.common.alignCenter , 'center'],
[ editor.lang.common.alignRight , 'right']
],
setup : function( selectedTable )
{
this.setValue( selectedTable.getAttribute( 'align' ) || '' );
},
commit : function( data, selectedTable )
{
if ( this.getValue() )
selectedTable.setAttribute( 'align', this.getValue() );
else
selectedTable.removeAttribute( 'align' );
}
}
]
},
{
type : 'vbox',
padding : 0,
children :
[
{
type : 'hbox',
widths : [ '5em' ],
children :
[
{
type : 'text',
id : 'txtWidth',
style : 'width:5em',
label : editor.lang.common.width,
'default' : 500,
validate : CKEDITOR.dialog.validate['number']( editor.lang.table.invalidWidth ),
// Extra labelling of width unit type.
onLoad : function()
{
var widthType = this.getDialog().getContentElement( 'info', 'cmbWidthType' ),
labelElement = widthType.getElement(),
inputElement = this.getInputElement(),
ariaLabelledByAttr = inputElement.getAttribute( 'aria-labelledby' );
inputElement.setAttribute( 'aria-labelledby', [ ariaLabelledByAttr, labelElement.$.id ].join( ' ' ) );
},
onChange : function()
{
var styles = this.getDialog().getContentElement( 'advanced', 'advStyles' );
if ( styles )
{
var value = this.getValue();
if ( value )
value += this.getDialog().getContentElement( 'info', 'cmbWidthType' ).getValue() == 'percents' ? '%' : 'px';
styles.updateStyle( 'width', value );
}
},
setup : function( selectedTable )
{
var widthMatch = widthPattern.exec( selectedTable.$.style.width );
if ( widthMatch )
this.setValue( widthMatch[1] );
else
this.setValue( '' );
},
commit : commitValue
},
{
id : 'cmbWidthType',
type : 'select',
label : editor.lang.table.widthUnit,
labelStyle: 'visibility:hidden',
'default' : 'pixels',
items :
[
[ editor.lang.table.widthPx , 'pixels'],
[ editor.lang.table.widthPc , 'percents']
],
setup : function( selectedTable )
{
var widthMatch = widthPattern.exec( selectedTable.$.style.width );
if ( widthMatch )
this.setValue( widthMatch[2] == 'px' ? 'pixels' : 'percents' );
},
onChange : function()
{
this.getDialog().getContentElement( 'info', 'txtWidth' ).onChange();
},
commit : commitValue
}
]
},
{
type : 'hbox',
widths : [ '5em' ],
children :
[
{
type : 'text',
id : 'txtHeight',
style : 'width:5em',
label : editor.lang.common.height,
'default' : '',
validate : CKEDITOR.dialog.validate['number']( editor.lang.table.invalidHeight ),
// Extra labelling of height unit type.
onLoad : function()
{
var heightType = this.getDialog().getContentElement( 'info', 'htmlHeightType' ),
labelElement = heightType.getElement(),
inputElement = this.getInputElement(),
ariaLabelledByAttr = inputElement.getAttribute( 'aria-labelledby' );
inputElement.setAttribute( 'aria-labelledby', [ ariaLabelledByAttr, labelElement.$.id ].join( ' ' ) );
},
onChange : function()
{
var styles = this.getDialog().getContentElement( 'advanced', 'advStyles' );
if ( styles )
{
var value = this.getValue();
styles.updateStyle( 'height', value && ( value + 'px' ) );
}
},
setup : function( selectedTable )
{
var heightMatch = heightPattern.exec( selectedTable.$.style.height );
if ( heightMatch )
this.setValue( heightMatch[1] );
},
commit : commitValue
},
{
id : 'htmlHeightType',
type : 'html',
html : '<div><br />' + editor.lang.table.widthPx + '</div>'
}
]
},
{
type : 'html',
html : ' '
},
{
type : 'text',
id : 'txtCellSpace',
style : 'width:3em',
label : editor.lang.table.cellSpace,
'default' : 1,
validate : CKEDITOR.dialog.validate['number']( editor.lang.table.invalidCellSpacing ),
setup : function( selectedTable )
{
this.setValue( selectedTable.getAttribute( 'cellSpacing' ) || '' );
},
commit : function( data, selectedTable )
{
if ( this.getValue() )
selectedTable.setAttribute( 'cellSpacing', this.getValue() );
else
selectedTable.removeAttribute( 'cellSpacing' );
}
},
{
type : 'text',
id : 'txtCellPad',
style : 'width:3em',
label : editor.lang.table.cellPad,
'default' : 1,
validate : CKEDITOR.dialog.validate['number']( editor.lang.table.invalidCellPadding ),
setup : function( selectedTable )
{
this.setValue( selectedTable.getAttribute( 'cellPadding' ) || '' );
},
commit : function( data, selectedTable )
{
if ( this.getValue() )
selectedTable.setAttribute( 'cellPadding', this.getValue() );
else
selectedTable.removeAttribute( 'cellPadding' );
}
}
]
}
]
},
{
type : 'html',
align : 'right',
html : ''
},
{
type : 'vbox',
padding : 0,
children :
[
{
type : 'text',
id : 'txtCaption',
label : editor.lang.table.caption,
setup : function( selectedTable )
{
var nodeList = selectedTable.getElementsByTag( 'caption' );
if ( nodeList.count() > 0 )
{
var caption = nodeList.getItem( 0 );
caption = CKEDITOR.tools.trim( caption.getText() );
this.setValue( caption );
}
},
commit : function( data, table )
{
var caption = this.getValue(),
captionElement = table.getElementsByTag( 'caption' );
if ( caption )
{
if ( captionElement.count() > 0 )
{
captionElement = captionElement.getItem( 0 );
captionElement.setHtml( '' );
}
else
{
captionElement = new CKEDITOR.dom.element( 'caption', editor.document );
if ( table.getChildCount() )
captionElement.insertBefore( table.getFirst() );
else
captionElement.appendTo( table );
}
captionElement.append( new CKEDITOR.dom.text( caption, editor.document ) );
}
else if ( captionElement.count() > 0 )
{
for ( var i = captionElement.count() - 1 ; i >= 0 ; i-- )
captionElement.getItem( i ).remove();
}
}
},
{
type : 'text',
id : 'txtSummary',
label : editor.lang.table.summary,
setup : function( selectedTable )
{
this.setValue( selectedTable.getAttribute( 'summary' ) || '' );
},
commit : function( data, selectedTable )
{
if ( this.getValue() )
selectedTable.setAttribute( 'summary', this.getValue() );
else
selectedTable.removeAttribute( 'summary' );
}
}
]
}
]
},
dialogadvtab && dialogadvtab.createAdvancedTab( editor )
]
};
}
CKEDITOR.dialog.add( 'table', function( editor )
{
return tableDialog( editor, 'table' );
} );
CKEDITOR.dialog.add( 'tableProperties', function( editor )
{
return tableDialog( editor, 'tableProperties' );
} );
})();
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @file Horizontal Page Break
*/
// Register a plugin named "newpage".
CKEDITOR.plugins.add( 'newpage',
{
init : function( editor )
{
editor.addCommand( 'newpage',
{
modes : { wysiwyg:1, source:1 },
exec : function( editor )
{
var command = this;
editor.setData( editor.config.newpage_html || '', function()
{
// Save the undo snapshot after all document changes are affected. (#4889)
setTimeout( function ()
{
editor.fire( 'afterCommandExec',
{
name: command.name,
command: command
} );
}, 200 );
} );
editor.focus();
},
async : true
});
editor.ui.addButton( 'NewPage',
{
label : editor.lang.newPage,
command : 'newpage'
});
}
});
/**
* The HTML to load in the editor when the "new page" command is executed.
* @type String
* @default ''
* @example
* config.newpage_html = '<p>Type your text here.</p>';
*/
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.add( 'format',
{
requires : [ 'richcombo', 'styles' ],
init : function( editor )
{
var config = editor.config,
lang = editor.lang.format;
// Gets the list of tags from the settings.
var tags = config.format_tags.split( ';' );
// Create style objects for all defined styles.
var styles = {};
for ( var i = 0 ; i < tags.length ; i++ )
{
var tag = tags[ i ];
styles[ tag ] = new CKEDITOR.style( config[ 'format_' + tag ] );
styles[ tag ]._.enterMode = editor.config.enterMode;
}
editor.ui.addRichCombo( 'Format',
{
label : lang.label,
title : lang.panelTitle,
className : 'cke_format',
panel :
{
css : editor.skin.editor.css.concat( config.contentsCss ),
multiSelect : false,
attributes : { 'aria-label' : lang.panelTitle }
},
init : function()
{
this.startGroup( lang.panelTitle );
for ( var tag in styles )
{
var label = lang[ 'tag_' + tag ];
// Add the tag entry to the panel list.
this.add( tag, '<' + tag + '>' + label + '</' + tag + '>', label );
}
},
onClick : function( value )
{
editor.focus();
editor.fire( 'saveSnapshot' );
styles[ value ].apply( editor.document );
// Save the undo snapshot after all changes are affected. (#4899)
setTimeout( function()
{
editor.fire( 'saveSnapshot' );
}, 0 );
},
onRender : function()
{
editor.on( 'selectionChange', function( ev )
{
var currentTag = this.getValue();
var elementPath = ev.data.path;
for ( var tag in styles )
{
if ( styles[ tag ].checkActive( elementPath ) )
{
if ( tag != currentTag )
this.setValue( tag, editor.lang.format[ 'tag_' + tag ] );
return;
}
}
// If no styles match, just empty it.
this.setValue( '' );
},
this);
}
});
}
});
/**
* A list of semi colon separated style names (by default tags) representing
* the style definition for each entry to be displayed in the Format combo in
* the toolbar. Each entry must have its relative definition configuration in a
* setting named "format_(tagName)". For example, the "p" entry has its
* definition taken from config.format_p.
* @type String
* @default 'p;h1;h2;h3;h4;h5;h6;pre;address;div'
* @example
* config.format_tags = 'p;h2;h3;pre'
*/
CKEDITOR.config.format_tags = 'p;h1;h2;h3;h4;h5;h6;pre;address;div';
/**
* The style definition to be used to apply the "Normal" format.
* @type Object
* @default { element : 'p' }
* @example
* config.format_p = { element : 'p', attributes : { class : 'normalPara' } };
*/
CKEDITOR.config.format_p = { element : 'p' };
/**
* The style definition to be used to apply the "Normal (DIV)" format.
* @type Object
* @default { element : 'div' }
* @example
* config.format_div = { element : 'div', attributes : { class : 'normalDiv' } };
*/
CKEDITOR.config.format_div = { element : 'div' };
/**
* The style definition to be used to apply the "Formatted" format.
* @type Object
* @default { element : 'pre' }
* @example
* config.format_pre = { element : 'pre', attributes : { class : 'code' } };
*/
CKEDITOR.config.format_pre = { element : 'pre' };
/**
* The style definition to be used to apply the "Address" format.
* @type Object
* @default { element : 'address' }
* @example
* config.format_address = { element : 'address', attributes : { class : 'styledAddress' } };
*/
CKEDITOR.config.format_address = { element : 'address' };
/**
* The style definition to be used to apply the "Heading 1" format.
* @type Object
* @default { element : 'h1' }
* @example
* config.format_h1 = { element : 'h1', attributes : { class : 'contentTitle1' } };
*/
CKEDITOR.config.format_h1 = { element : 'h1' };
/**
* The style definition to be used to apply the "Heading 1" format.
* @type Object
* @default { element : 'h2' }
* @example
* config.format_h2 = { element : 'h2', attributes : { class : 'contentTitle2' } };
*/
CKEDITOR.config.format_h2 = { element : 'h2' };
/**
* The style definition to be used to apply the "Heading 1" format.
* @type Object
* @default { element : 'h3' }
* @example
* config.format_h3 = { element : 'h3', attributes : { class : 'contentTitle3' } };
*/
CKEDITOR.config.format_h3 = { element : 'h3' };
/**
* The style definition to be used to apply the "Heading 1" format.
* @type Object
* @default { element : 'h4' }
* @example
* config.format_h4 = { element : 'h4', attributes : { class : 'contentTitle4' } };
*/
CKEDITOR.config.format_h4 = { element : 'h4' };
/**
* The style definition to be used to apply the "Heading 1" format.
* @type Object
* @default { element : 'h5' }
* @example
* config.format_h5 = { element : 'h5', attributes : { class : 'contentTitle5' } };
*/
CKEDITOR.config.format_h5 = { element : 'h5' };
/**
* The style definition to be used to apply the "Heading 1" format.
* @type Object
* @default { element : 'h6' }
* @example
* config.format_h6 = { element : 'h6', attributes : { class : 'contentTitle6' } };
*/
CKEDITOR.config.format_h6 = { element : 'h6' };
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @file Special Character plugin
*/
CKEDITOR.plugins.add( 'specialchar',
{
// List of available localizations.
availableLangs : { en:1 },
init : function( editor )
{
var pluginName = 'specialchar',
plugin = this;
// Register the dialog.
CKEDITOR.dialog.add( pluginName, this.path + 'dialogs/specialchar.js' );
editor.addCommand( pluginName,
{
exec : function()
{
var langCode = editor.langCode;
langCode = plugin.availableLangs[ langCode ] ? langCode : 'en';
CKEDITOR.scriptLoader.load(
CKEDITOR.getUrl( plugin.path + 'lang/' + langCode + '.js' ),
function()
{
CKEDITOR.tools.extend( editor.lang.specialChar, plugin.lang[ langCode ] );
editor.openDialog( pluginName );
});
},
modes : { wysiwyg:1 },
canUndo : false
});
// Register the toolbar button.
editor.ui.addButton( 'SpecialChar',
{
label : editor.lang.specialChar.toolbar,
command : pluginName
});
}
} );
/**
* The list of special characters visible in Special Character dialog.
* @type Array
* @example
* config.specialChars = [ '"', '’', [ '&custom;', 'Custom label' ] ];
* config.specialChars = config.specialChars.concat( [ '"', [ '’', 'Custom label' ] ] );
*/
CKEDITOR.config.specialChars =
[
'!','"','#','$','%','&',"'",'(',')','*','+','-','.','/',
'0','1','2','3','4','5','6','7','8','9',':',';',
'<','=','>','?','@',
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O',
'P','Q','R','S','T','U','V','W','X','Y','Z',
'[',']','^','_','`',
'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p',
'q','r','s','t','u','v','w','x','y','z',
'{','|','}','~',
"€", "‘", "’", "“", "”", "–", "—", "¡", "¢", "£", "¤", "¥", "¦", "§", "¨", "©", "ª", "«", "¬", "®", "¯", "°", "&", "²", "³", "´", "µ", "¶", "·", "¸", "¹", "º", "&", "¼", "½", "¾", "¿", "À", "Á", "Â", "Ã", "Ä", "Å", "Æ", "Ç", "È", "É", "Ê", "Ë", "Ì", "Í", "Î", "Ï", "Ð", "Ñ", "Ò", "Ó", "Ô", "Õ", "Ö", "×", "Ø", "Ù", "Ú", "Û", "Ü", "Ý", "Þ", "ß", "à", "á", "â", "ã", "ä", "å", "æ", "ç", "è", "é", "ê", "ë", "ì", "í", "î", "ï", "ð", "ñ", "ò", "ó", "ô", "õ", "ö", "÷", "ø", "ù", "ú", "û", "ü", "ü", "ý", "þ", "ÿ", "Œ", "œ", "Ŵ", "Ŷ", "ŵ", "ŷ", "‚", "‛", "„", "…", "™", "►", "•", "→", "⇒", "⇔", "♦", "≈"
];
| JavaScript |
CKEDITOR.plugins.setLang( 'specialchar', 'en',
{
euro: "EURO SIGN",
lsquo: "LEFT SINGLE QUOTATION MARK",
rsquo: "RIGHT SINGLE QUOTATION MARK",
ldquo: "LEFT DOUBLE QUOTATION MARK",
rdquo: "RIGHT DOUBLE QUOTATION MARK",
ndash: "EN DASH",
mdash: "EM DASH",
iexcl: "INVERTED EXCLAMATION MARK",
cent: "CENT SIGN",
pound: "POUND SIGN",
curren: "CURRENCY SIGN",
yen: "YEN SIGN",
brvbar: "BROKEN BAR",
sect: "SECTION SIGN",
uml: "DIAERESIS",
copy: "COPYRIGHT SIGN",
ordf: "FEMININE ORDINAL INDICATOR",
laquo: "LEFT-POINTING DOUBLE ANGLE QUOTATION MARK",
not: "NOT SIGN",
reg: "REGISTERED SIGN",
macr: "MACRON",
deg: "DEGREE SIGN",
sup2: "SUPERSCRIPT TWO",
sup3: "SUPERSCRIPT THREE",
acute: "ACUTE ACCENT",
micro: "MICRO SIGN",
para: "PILCROW SIGN",
middot: "MIDDLE DOT",
cedil: "CEDILLA",
sup1: "SUPERSCRIPT ONE",
ordm: "MASCULINE ORDINAL INDICATOR",
frac14: "VULGAR FRACTION ONE QUARTER",
frac12: "VULGAR FRACTION ONE HALF",
frac34: "VULGAR FRACTION THREE QUARTERS",
iquest: "INVERTED QUESTION MARK",
agrave: "LATIN SMALL LETTER A WITH GRAVE",
aacute: "LATIN SMALL LETTER A WITH ACUTE",
acirc: "LATIN SMALL LETTER A WITH CIRCUMFLEX",
atilde: "LATIN SMALL LETTER A WITH TILDE",
auml: "LATIN SMALL LETTER A WITH DIAERESIS",
aring: "LATIN SMALL LETTER A WITH RING ABOVE",
aelig: "LATIN SMALL LETTER AE",
ccedil: "LATIN SMALL LETTER C WITH CEDILLA",
egrave: "LATIN SMALL LETTER E WITH GRAVE",
eacute: "LATIN SMALL LETTER E WITH ACUTE",
ecirc: "LATIN SMALL LETTER E WITH CIRCUMFLEX",
euml: "LATIN SMALL LETTER E WITH DIAERESIS",
igrave: "LATIN SMALL LETTER I WITH GRAVE",
iacute: "LATIN SMALL LETTER I WITH ACUTE",
icirc: "LATIN SMALL LETTER I WITH CIRCUMFLEX",
iuml: "LATIN SMALL LETTER I WITH DIAERESIS",
eth: "LATIN SMALL LETTER ETH",
ntilde: "LATIN SMALL LETTER N WITH TILDE",
ograve: "LATIN SMALL LETTER O WITH GRAVE",
oacute: "LATIN SMALL LETTER O WITH ACUTE",
ocirc: "LATIN SMALL LETTER O WITH CIRCUMFLEX",
otilde: "LATIN SMALL LETTER O WITH TILDE",
ouml: "LATIN SMALL LETTER O WITH DIAERESIS",
times: "MULTIPLICATION SIGN",
oslash: "LATIN SMALL LETTER O WITH STROKE",
ugrave: "LATIN SMALL LETTER U WITH GRAVE",
uacute: "LATIN SMALL LETTER U WITH ACUTE",
ucirc: "LATIN SMALL LETTER U WITH CIRCUMFLEX",
uuml: "LATIN SMALL LETTER U WITH DIAERESIS",
yacute: "LATIN SMALL LETTER Y WITH ACUTE",
thorn: "LATIN SMALL LETTER THORN",
szlig: "LATIN SMALL LETTER SHARP S",
divide: "DIVISION SIGN",
yuml: "LATIN SMALL LETTER Y WITH DIAERESIS",
oelig: "LATIN SMALL LIGATURE OE",
'372': "LATIN CAPITAL LETTER W WITH CIRCUMFLEX",
'374': "LATIN CAPITAL LETTER Y WITH CIRCUMFLEX",
'373': "LATIN SMALL LETTER W WITH CIRCUMFLEX",
'375': "LATIN SMALL LETTER Y WITH CIRCUMFLEX",
8219: "SINGLE HIGH-REVERSED-9 QUOTATION MARK",
bdquo: "DOUBLE LOW-9 QUOTATION MARK",
hellip: "HORIZONTAL ELLIPSIS",
trade: "TRADE MARK SIGN",
'9658': "BLACK RIGHT-POINTING POINTER",
bull: "BULLET",
rarr: "RIGHTWARDS DOUBLE ARROW",
harr: "LEFT RIGHT DOUBLE ARROW",
diams: "BLACK DIAMOND SUIT",
asymp: "ALMOST EQUAL TO",
sbquo: 'SINGLE LOW-9 QUOTATION MARK'
});
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.dialog.add( 'specialchar', function( editor )
{
/**
* Simulate "this" of a dialog for non-dialog events.
* @type {CKEDITOR.dialog}
*/
var dialog,
lang = editor.lang.specialChar;
var onChoice = function( evt )
{
var target, value;
if ( evt.data )
target = evt.data.getTarget();
else
target = new CKEDITOR.dom.element( evt );
if ( target.getName() == 'a' && ( value = target.getChild( 0 ).getHtml() ) )
{
target.removeClass( "cke_light_background" );
dialog.hide();
editor.insertHtml( value );
}
};
var onClick = CKEDITOR.tools.addFunction( onChoice );
var focusedNode;
var onFocus = function( evt, target )
{
var value;
target = target || evt.data.getTarget();
if ( target.getName() == 'span' )
target = target.getParent();
if ( target.getName() == 'a' && ( value = target.getChild( 0 ).getHtml() ) )
{
// Trigger blur manually if there is focused node.
if ( focusedNode )
onBlur( null, focusedNode );
var htmlPreview = dialog.getContentElement( 'info', 'htmlPreview' ).getElement();
dialog.getContentElement( 'info', 'charPreview' ).getElement().setHtml( value );
htmlPreview.setHtml( CKEDITOR.tools.htmlEncode( value ) );
target.getParent().addClass( "cke_light_background" );
// Memorize focused node.
focusedNode = target;
}
};
var onBlur = function( evt, target )
{
target = target || evt.data.getTarget();
if ( target.getName() == 'span' )
target = target.getParent();
if ( target.getName() == 'a' )
{
dialog.getContentElement( 'info', 'charPreview' ).getElement().setHtml( ' ' );
dialog.getContentElement( 'info', 'htmlPreview' ).getElement().setHtml( ' ' );
target.getParent().removeClass( "cke_light_background" );
focusedNode = undefined;
}
};
var onKeydown = CKEDITOR.tools.addFunction( function( ev )
{
ev = new CKEDITOR.dom.event( ev );
// Get an Anchor element.
var element = ev.getTarget();
var relative, nodeToMove;
var keystroke = ev.getKeystroke(),
rtl = editor.lang.dir == 'rtl';
switch ( keystroke )
{
// UP-ARROW
case 38 :
// relative is TR
if ( ( relative = element.getParent().getParent().getPrevious() ) )
{
nodeToMove = relative.getChild( [element.getParent().getIndex(), 0] );
nodeToMove.focus();
onBlur( null, element );
onFocus( null, nodeToMove );
}
ev.preventDefault();
break;
// DOWN-ARROW
case 40 :
// relative is TR
if ( ( relative = element.getParent().getParent().getNext() ) )
{
nodeToMove = relative.getChild( [ element.getParent().getIndex(), 0 ] );
if ( nodeToMove && nodeToMove.type == 1 )
{
nodeToMove.focus();
onBlur( null, element );
onFocus( null, nodeToMove );
}
}
ev.preventDefault();
break;
// SPACE
// ENTER is already handled as onClick
case 32 :
onChoice( { data: ev } );
ev.preventDefault();
break;
// RIGHT-ARROW
case rtl ? 37 : 39 :
// TAB
case 9 :
// relative is TD
if ( ( relative = element.getParent().getNext() ) )
{
nodeToMove = relative.getChild( 0 );
if ( nodeToMove.type == 1 )
{
nodeToMove.focus();
onBlur( null, element );
onFocus( null, nodeToMove );
ev.preventDefault( true );
}
else
onBlur( null, element );
}
// relative is TR
else if ( ( relative = element.getParent().getParent().getNext() ) )
{
nodeToMove = relative.getChild( [ 0, 0 ] );
if ( nodeToMove && nodeToMove.type == 1 )
{
nodeToMove.focus();
onBlur( null, element );
onFocus( null, nodeToMove );
ev.preventDefault( true );
}
else
onBlur( null, element );
}
break;
// LEFT-ARROW
case rtl ? 39 : 37 :
// SHIFT + TAB
case CKEDITOR.SHIFT + 9 :
// relative is TD
if ( ( relative = element.getParent().getPrevious() ) )
{
nodeToMove = relative.getChild( 0 );
nodeToMove.focus();
onBlur( null, element );
onFocus( null, nodeToMove );
ev.preventDefault( true );
}
// relative is TR
else if ( ( relative = element.getParent().getParent().getPrevious() ) )
{
nodeToMove = relative.getLast().getChild( 0 );
nodeToMove.focus();
onBlur( null, element );
onFocus( null, nodeToMove );
ev.preventDefault( true );
}
else
onBlur( null, element );
break;
default :
// Do not stop not handled events.
return;
}
});
return {
title : lang.title,
minWidth : 430,
minHeight : 280,
buttons : [ CKEDITOR.dialog.cancelButton ],
charColumns : 17,
onLoad : function()
{
var columns = this.definition.charColumns,
extraChars = editor.config.extraSpecialChars,
chars = editor.config.specialChars;
var charsTableLabel = CKEDITOR.tools.getNextId() + '_specialchar_table_label';
var html = [ '<table role="listbox" aria-labelledby="' + charsTableLabel + '"' +
' style="width: 320px; height: 100%; border-collapse: separate;"' +
' align="center" cellspacing="2" cellpadding="2" border="0">' ];
var i = 0,
size = chars.length,
character,
charDesc;
while ( i < size )
{
html.push( '<tr>' ) ;
for ( var j = 0 ; j < columns ; j++, i++ )
{
if ( ( character = chars[ i ] ) )
{
charDesc = '';
if ( character instanceof Array )
{
charDesc = character[ 1 ];
character = character[ 0 ];
}
else
{
var _tmpName = character.toLowerCase().replace( '&', '' ).replace( ';', '' ).replace( '#', '' );
// Use character in case description unavailable.
charDesc = lang[ _tmpName ] || character;
}
var charLabelId = 'cke_specialchar_label_' + i + '_' + CKEDITOR.tools.getNextNumber();
html.push(
'<td class="cke_dark_background" style="cursor: default" role="presentation">' +
'<a href="javascript: void(0);" role="option"' +
' aria-posinset="' + ( i +1 ) + '"',
' aria-setsize="' + size + '"',
' aria-labelledby="' + charLabelId + '"',
' style="cursor: inherit; display: block; height: 1.25em; margin-top: 0.25em; text-align: center;" title="', CKEDITOR.tools.htmlEncode( charDesc ), '"' +
' onkeydown="CKEDITOR.tools.callFunction( ' + onKeydown + ', event, this )"' +
' onclick="CKEDITOR.tools.callFunction(' + onClick + ', this); return false;"' +
' tabindex="-1">' +
'<span style="margin: 0 auto;cursor: inherit">' +
character +
'</span>' +
'<span class="cke_voice_label" id="' + charLabelId + '">' +
charDesc +
'</span></a>');
}
else
html.push( '<td class="cke_dark_background"> ' );
html.push( '</td>' );
}
html.push( '</tr>' );
}
html.push( '</tbody></table>', '<span id="' + charsTableLabel + '" class="cke_voice_label">' + lang.options +'</span>' );
this.getContentElement( 'info', 'charContainer' ).getElement().setHtml( html.join( '' ) );
},
contents : [
{
id : 'info',
label : editor.lang.common.generalTab,
title : editor.lang.common.generalTab,
padding : 0,
align : 'top',
elements : [
{
type : 'hbox',
align : 'top',
widths : [ '320px', '90px' ],
children :
[
{
type : 'html',
id : 'charContainer',
html : '',
onMouseover : onFocus,
onMouseout : onBlur,
focus : function()
{
var firstChar = this.getElement().getElementsByTag( 'a' ).getItem( 0 );
setTimeout( function()
{
firstChar.focus();
onFocus( null, firstChar );
}, 0 );
},
onShow : function()
{
var firstChar = this.getElement().getChild( [ 0, 0, 0, 0, 0 ] );
setTimeout( function()
{
firstChar.focus();
onFocus( null, firstChar );
}, 0 );
},
onLoad : function( event )
{
dialog = event.sender;
}
},
{
type : 'hbox',
align : 'top',
widths : [ '100%' ],
children :
[
{
type : 'vbox',
align : 'top',
children :
[
{
type : 'html',
html : '<div></div>'
},
{
type : 'html',
id : 'charPreview',
className : 'cke_dark_background',
style : 'border:1px solid #eeeeee;font-size:28px;height:40px;width:70px;padding-top:9px;font-family:\'Microsoft Sans Serif\',Arial,Helvetica,Verdana;text-align:center;',
html : '<div> </div>'
},
{
type : 'html',
id : 'htmlPreview',
className : 'cke_dark_background',
style : 'border:1px solid #eeeeee;font-size:14px;height:20px;width:70px;padding-top:2px;font-family:\'Microsoft Sans Serif\',Arial,Helvetica,Verdana;text-align:center;',
html : '<div> </div>'
}
]
}
]
}
]
}
]
}
]
};
} );
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @file Spell checker
*/
// Register a plugin named "wsc".
CKEDITOR.plugins.add( 'wsc',
{
requires : [ 'dialog' ],
init : function( editor )
{
var commandName = 'checkspell';
var command = editor.addCommand( commandName, new CKEDITOR.dialogCommand( commandName ) );
// SpellChecker doesn't work in Opera and with custom domain
command.modes = { wysiwyg : ( !CKEDITOR.env.opera && !CKEDITOR.env.air && document.domain == window.location.hostname ) };
editor.ui.addButton( 'SpellChecker',
{
label : editor.lang.spellCheck.toolbar,
command : commandName
});
CKEDITOR.dialog.add( commandName, this.path + 'dialogs/wsc.js' );
}
});
CKEDITOR.config.wsc_customerId = CKEDITOR.config.wsc_customerId || '1:ua3xw1-2XyGJ3-GWruD3-6OFNT1-oXcuB1-nR6Bp4-hgQHc-EcYng3-sdRXG3-NOfFk' ;
CKEDITOR.config.wsc_customLoaderScript = CKEDITOR.config.wsc_customLoaderScript || null;
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.dialog.add( 'checkspell', function( editor )
{
var number = CKEDITOR.tools.getNextNumber(),
iframeId = 'cke_frame_' + number,
textareaId = 'cke_data_' + number,
errorBoxId = 'cke_error_' + number,
interval,
protocol = document.location.protocol || 'http:',
errorMsg = editor.lang.spellCheck.notAvailable;
var pasteArea = '<textarea'+
' style="display: none"' +
' id="' + textareaId + '"' +
' rows="10"' +
' cols="40">' +
' </textarea><div' +
' id="' + errorBoxId + '"' +
' style="display:none;color:red;font-size:16px;font-weight:bold;padding-top:160px;text-align:center;z-index:11;">' +
'</div><iframe' +
' src=""' +
' style="width:100%;background-color:#f1f1e3;"' +
' frameborder="0"' +
' name="' + iframeId + '"' +
' id="' + iframeId + '"' +
' allowtransparency="1">' +
'</iframe>';
var wscCoreUrl = editor.config.wsc_customLoaderScript || ( protocol +
'//loader.spellchecker.net/sproxy_fck/sproxy.php'
+ '?plugin=fck2'
+ '&customerid=' + editor.config.wsc_customerId
+ '&cmd=script&doc=wsc&schema=22'
);
if ( editor.config.wsc_customLoaderScript )
errorMsg += '<p style="color:#000;font-size:11px;font-weight: normal;text-align:center;padding-top:10px">' +
editor.lang.spellCheck.errorLoading.replace( /%s/g, editor.config.wsc_customLoaderScript ) + '</p>';
function burnSpelling( dialog, errorMsg )
{
var i = 0;
return function ()
{
if ( typeof( window.doSpell ) == 'function' )
{
//Call from window.setInteval expected at once.
if ( typeof( interval ) != 'undefined' )
window.clearInterval( interval );
initAndSpell( dialog );
}
else if ( i++ == 180 ) // Timeout: 180 * 250ms = 45s.
window._cancelOnError( errorMsg );
};
}
window._cancelOnError = function( m )
{
if ( typeof( window.WSC_Error ) == 'undefined' )
{
CKEDITOR.document.getById( iframeId ).setStyle( 'display', 'none' );
var errorBox = CKEDITOR.document.getById( errorBoxId );
errorBox.setStyle( 'display', 'block' );
errorBox.setHtml( m || editor.lang.spellCheck.notAvailable );
}
};
function initAndSpell( dialog )
{
var LangComparer = new window._SP_FCK_LangCompare(), // Language abbr standarts comparer.
pluginPath = CKEDITOR.getUrl( editor.plugins.wsc.path + 'dialogs/' ), // Service paths corecting/preparing.
framesetPath = pluginPath + 'tmpFrameset.html';
// global var is used in FCK specific core
// change on equal var used in fckplugin.js
window.gFCKPluginName = 'wsc';
LangComparer.setDefaulLangCode( editor.config.defaultLanguage );
window.doSpell({
ctrl : textareaId,
lang : editor.config.wsc_lang || LangComparer.getSPLangCode(editor.langCode ),
intLang: editor.config.wsc_uiLang || LangComparer.getSPLangCode(editor.langCode ),
winType : iframeId, // If not defined app will run on winpopup.
// Callback binding section.
onCancel : function()
{
dialog.hide();
},
onFinish : function( dT )
{
editor.focus();
dialog.getParentEditor().setData( dT.value );
dialog.hide();
},
// Some manipulations with client static pages.
staticFrame : framesetPath,
framesetPath : framesetPath,
iframePath : pluginPath + 'ciframe.html',
// Styles defining.
schemaURI : pluginPath + 'wsc.css',
userDictionaryName: editor.config.wsc_userDictionaryName,
customDictionaryName: editor.config.wsc_customDictionaryIds && editor.config.wsc_customDictionaryIds.split(","),
domainName: editor.config.wsc_domainName
});
// Hide user message console (if application was loaded more then after timeout).
CKEDITOR.document.getById( errorBoxId ).setStyle( 'display', 'none' );
CKEDITOR.document.getById( iframeId ).setStyle( 'display', 'block' );
}
return {
title : editor.config.wsc_dialogTitle || editor.lang.spellCheck.title,
minWidth : 485,
minHeight : 380,
buttons : [ CKEDITOR.dialog.cancelButton ],
onShow : function()
{
var contentArea = this.getContentElement( 'general', 'content' ).getElement();
contentArea.setHtml( pasteArea );
contentArea.getChild( 2 ).setStyle( 'height', this._.contentSize.height + 'px' );
if ( typeof( window.doSpell ) != 'function' )
{
// Load script.
CKEDITOR.document.getHead().append(
CKEDITOR.document.createElement( 'script',
{
attributes :
{
type : 'text/javascript',
src : wscCoreUrl
}
})
);
}
var sData = editor.getData(); // Get the data to be checked.
CKEDITOR.document.getById( textareaId ).setValue( sData );
interval = window.setInterval( burnSpelling( this, errorMsg ), 250 );
},
onHide : function()
{
window.ooo = undefined;
window.int_framsetLoaded = undefined;
window.framesetLoaded = undefined;
window.is_window_opened = false;
},
contents : [
{
id : 'general',
label : editor.config.wsc_dialogTitle || editor.lang.spellCheck.title,
padding : 0,
elements : [
{
type : 'html',
id : 'content',
html : ''
}
]
}
]
};
});
// Expand the spell-check frame when dialog resized. (#6829)
CKEDITOR.dialog.on( 'resize', function( evt )
{
var data = evt.data,
dialog = data.dialog;
if ( dialog._.name == 'checkspell' )
{
var content = dialog.getContentElement( 'general', 'content' ).getElement(),
iframe = content && content.getChild( 2 );
iframe && iframe.setStyle( 'height', data.height + 'px' );
}
});
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @fileOverview The "filebrowser" plugin, it adds support for file uploads and
* browsing.
*
* When file is selected inside of the file browser or uploaded, its url is
* inserted automatically to a field, which is described in the 'filebrowser'
* attribute. To specify field that should be updated, pass the tab id and
* element id, separated with a colon.
*
* Example 1: (Browse)
*
* <pre>
* {
* type : 'button',
* id : 'browse',
* filebrowser : 'tabId:elementId',
* label : editor.lang.common.browseServer
* }
* </pre>
*
* If you set the 'filebrowser' attribute on any element other than
* 'fileButton', the 'Browse' action will be triggered.
*
* Example 2: (Quick Upload)
*
* <pre>
* {
* type : 'fileButton',
* id : 'uploadButton',
* filebrowser : 'tabId:elementId',
* label : editor.lang.common.uploadSubmit,
* 'for' : [ 'upload', 'upload' ]
* }
* </pre>
*
* If you set the 'filebrowser' attribute on a fileButton element, the
* 'QuickUpload' action will be executed.
*
* Filebrowser plugin also supports more advanced configuration (through
* javascript object).
*
* The following settings are supported:
*
* <pre>
* [action] - Browse or QuickUpload
* [target] - field to update, tabId:elementId
* [params] - additional arguments to be passed to the server connector (optional)
* [onSelect] - function to execute when file is selected/uploaded (optional)
* [url] - the URL to be called (optional)
* </pre>
*
* Example 3: (Quick Upload)
*
* <pre>
* {
* type : 'fileButton',
* label : editor.lang.common.uploadSubmit,
* id : 'buttonId',
* filebrowser :
* {
* action : 'QuickUpload', //required
* target : 'tab1:elementId', //required
* params : //optional
* {
* type : 'Files',
* currentFolder : '/folder/'
* },
* onSelect : function( fileUrl, errorMessage ) //optional
* {
* // Do not call the built-in selectFuntion
* // return false;
* }
* },
* 'for' : [ 'tab1', 'myFile' ]
* }
* </pre>
*
* Suppose we have a file element with id 'myFile', text field with id
* 'elementId' and a fileButton. If filebowser.url is not specified explicitly,
* form action will be set to 'filebrowser[DialogName]UploadUrl' or, if not
* specified, to 'filebrowserUploadUrl'. Additional parameters from 'params'
* object will be added to the query string. It is possible to create your own
* uploadHandler and cancel the built-in updateTargetElement command.
*
* Example 4: (Browse)
*
* <pre>
* {
* type : 'button',
* id : 'buttonId',
* label : editor.lang.common.browseServer,
* filebrowser :
* {
* action : 'Browse',
* url : '/ckfinder/ckfinder.html&type=Images',
* target : 'tab1:elementId'
* }
* }
* </pre>
*
* In this example, after pressing a button, file browser will be opened in a
* popup. If we don't specify filebrowser.url attribute,
* 'filebrowser[DialogName]BrowseUrl' or 'filebrowserBrowseUrl' will be used.
* After selecting a file in a file browser, an element with id 'elementId' will
* be updated. Just like in the third example, a custom 'onSelect' function may be
* defined.
*/
( function()
{
/**
* Adds (additional) arguments to given url.
*
* @param {String}
* url The url.
* @param {Object}
* params Additional parameters.
*/
function addQueryString( url, params )
{
var queryString = [];
if ( !params )
return url;
else
{
for ( var i in params )
queryString.push( i + "=" + encodeURIComponent( params[ i ] ) );
}
return url + ( ( url.indexOf( "?" ) != -1 ) ? "&" : "?" ) + queryString.join( "&" );
}
/**
* Make a string's first character uppercase.
*
* @param {String}
* str String.
*/
function ucFirst( str )
{
str += '';
var f = str.charAt( 0 ).toUpperCase();
return f + str.substr( 1 );
}
/**
* The onlick function assigned to the 'Browse Server' button. Opens the
* file browser and updates target field when file is selected.
*
* @param {CKEDITOR.event}
* evt The event object.
*/
function browseServer( evt )
{
var dialog = this.getDialog();
var editor = dialog.getParentEditor();
editor._.filebrowserSe = this;
var width = editor.config[ 'filebrowser' + ucFirst( dialog.getName() ) + 'WindowWidth' ]
|| editor.config.filebrowserWindowWidth || '80%';
var height = editor.config[ 'filebrowser' + ucFirst( dialog.getName() ) + 'WindowHeight' ]
|| editor.config.filebrowserWindowHeight || '70%';
var params = this.filebrowser.params || {};
params.CKEditor = editor.name;
params.CKEditorFuncNum = editor._.filebrowserFn;
if ( !params.langCode )
params.langCode = editor.langCode;
var url = addQueryString( this.filebrowser.url, params );
editor.popup( url, width, height, editor.config.fileBrowserWindowFeatures );
}
/**
* The onlick function assigned to the 'Upload' button. Makes the final
* decision whether form is really submitted and updates target field when
* file is uploaded.
*
* @param {CKEDITOR.event}
* evt The event object.
*/
function uploadFile( evt )
{
var dialog = this.getDialog();
var editor = dialog.getParentEditor();
editor._.filebrowserSe = this;
// If user didn't select the file, stop the upload.
if ( !dialog.getContentElement( this[ 'for' ][ 0 ], this[ 'for' ][ 1 ] ).getInputElement().$.value )
return false;
if ( !dialog.getContentElement( this[ 'for' ][ 0 ], this[ 'for' ][ 1 ] ).getAction() )
return false;
return true;
}
/**
* Setups the file element.
*
* @param {CKEDITOR.ui.dialog.file}
* fileInput The file element used during file upload.
* @param {Object}
* filebrowser Object containing filebrowser settings assigned to
* the fileButton associated with this file element.
*/
function setupFileElement( editor, fileInput, filebrowser )
{
var params = filebrowser.params || {};
params.CKEditor = editor.name;
params.CKEditorFuncNum = editor._.filebrowserFn;
if ( !params.langCode )
params.langCode = editor.langCode;
fileInput.action = addQueryString( filebrowser.url, params );
fileInput.filebrowser = filebrowser;
}
/**
* Traverse through the content definition and attach filebrowser to
* elements with 'filebrowser' attribute.
*
* @param String
* dialogName Dialog name.
* @param {CKEDITOR.dialog.dialogDefinitionObject}
* definition Dialog definition.
* @param {Array}
* elements Array of {@link CKEDITOR.dialog.contentDefinition}
* objects.
*/
function attachFileBrowser( editor, dialogName, definition, elements )
{
var element, fileInput;
for ( var i in elements )
{
element = elements[ i ];
if ( element.type == 'hbox' || element.type == 'vbox' )
attachFileBrowser( editor, dialogName, definition, element.children );
if ( !element.filebrowser )
continue;
if ( typeof element.filebrowser == 'string' )
{
var fb =
{
action : ( element.type == 'fileButton' ) ? 'QuickUpload' : 'Browse',
target : element.filebrowser
};
element.filebrowser = fb;
}
if ( element.filebrowser.action == 'Browse' )
{
var url = element.filebrowser.url;
if ( url === undefined )
{
url = editor.config[ 'filebrowser' + ucFirst( dialogName ) + 'BrowseUrl' ];
if ( url === undefined )
url = editor.config.filebrowserBrowseUrl;
}
if ( url )
{
element.onClick = browseServer;
element.filebrowser.url = url;
element.hidden = false;
}
}
else if ( element.filebrowser.action == 'QuickUpload' && element[ 'for' ] )
{
url = element.filebrowser.url;
if ( url === undefined )
{
url = editor.config[ 'filebrowser' + ucFirst( dialogName ) + 'UploadUrl' ];
if ( url === undefined )
url = editor.config.filebrowserUploadUrl;
}
if ( url )
{
var onClick = element.onClick;
element.onClick = function( evt )
{
// "element" here means the definition object, so we need to find the correct
// button to scope the event call
var sender = evt.sender;
if ( onClick && onClick.call( sender, evt ) === false )
return false;
return uploadFile.call( sender, evt );
};
element.filebrowser.url = url;
element.hidden = false;
setupFileElement( editor, definition.getContents( element[ 'for' ][ 0 ] ).get( element[ 'for' ][ 1 ] ), element.filebrowser );
}
}
}
}
/**
* Updates the target element with the url of uploaded/selected file.
*
* @param {String}
* url The url of a file.
*/
function updateTargetElement( url, sourceElement )
{
var dialog = sourceElement.getDialog();
var targetElement = sourceElement.filebrowser.target || null;
url = url.replace( /#/g, '%23' );
// If there is a reference to targetElement, update it.
if ( targetElement )
{
var target = targetElement.split( ':' );
var element = dialog.getContentElement( target[ 0 ], target[ 1 ] );
if ( element )
{
element.setValue( url );
dialog.selectPage( target[ 0 ] );
}
}
}
/**
* Returns true if filebrowser is configured in one of the elements.
*
* @param {CKEDITOR.dialog.dialogDefinitionObject}
* definition Dialog definition.
* @param String
* tabId The tab id where element(s) can be found.
* @param String
* elementId The element id (or ids, separated with a semicolon) to check.
*/
function isConfigured( definition, tabId, elementId )
{
if ( elementId.indexOf( ";" ) !== -1 )
{
var ids = elementId.split( ";" );
for ( var i = 0 ; i < ids.length ; i++ )
{
if ( isConfigured( definition, tabId, ids[i] ) )
return true;
}
return false;
}
var elementFileBrowser = definition.getContents( tabId ).get( elementId ).filebrowser;
return ( elementFileBrowser && elementFileBrowser.url );
}
function setUrl( fileUrl, data )
{
var dialog = this._.filebrowserSe.getDialog(),
targetInput = this._.filebrowserSe[ 'for' ],
onSelect = this._.filebrowserSe.filebrowser.onSelect;
if ( targetInput )
dialog.getContentElement( targetInput[ 0 ], targetInput[ 1 ] ).reset();
if ( typeof data == 'function' && data.call( this._.filebrowserSe ) === false )
return;
if ( onSelect && onSelect.call( this._.filebrowserSe, fileUrl, data ) === false )
return;
// The "data" argument may be used to pass the error message to the editor.
if ( typeof data == 'string' && data )
alert( data );
if ( fileUrl )
updateTargetElement( fileUrl, this._.filebrowserSe );
}
CKEDITOR.plugins.add( 'filebrowser',
{
init : function( editor, pluginPath )
{
editor._.filebrowserFn = CKEDITOR.tools.addFunction( setUrl, editor );
}
} );
CKEDITOR.on( 'dialogDefinition', function( evt )
{
var definition = evt.data.definition,
element;
// Associate filebrowser to elements with 'filebrowser' attribute.
for ( var i in definition.contents )
{
if ( ( element = definition.contents[ i ] ) )
{
attachFileBrowser( evt.editor, evt.data.name, definition, element.elements );
if ( element.hidden && element.filebrowser )
{
element.hidden = !isConfigured( definition, element[ 'id' ], element.filebrowser );
}
}
}
} );
} )();
/**
* The location of an external file browser, that should be launched when "Browse Server" button is pressed.
* If configured, the "Browse Server" button will appear in Link, Image and Flash dialogs.
* @see The <a href="http://docs.cksource.com/CKEditor_3.x/Developers_Guide/File_Browser_(Uploader)">File Browser/Uploader</a> documentation.
* @name CKEDITOR.config.filebrowserBrowseUrl
* @since 3.0
* @type String
* @default '' (empty string = disabled)
* @example
* config.filebrowserBrowseUrl = '/browser/browse.php';
*/
/**
* The location of a script that handles file uploads.
* If set, the "Upload" tab will appear in "Link", "Image" and "Flash" dialogs.
* @name CKEDITOR.config.filebrowserUploadUrl
* @see The <a href="http://docs.cksource.com/CKEditor_3.x/Developers_Guide/File_Browser_(Uploader)">File Browser/Uploader</a> documentation.
* @since 3.0
* @type String
* @default '' (empty string = disabled)
* @example
* config.filebrowserUploadUrl = '/uploader/upload.php';
*/
/**
* The location of an external file browser, that should be launched when "Browse Server" button is pressed in the Image dialog.
* If not set, CKEditor will use {@link CKEDITOR.config.filebrowserBrowseUrl}.
* @name CKEDITOR.config.filebrowserImageBrowseUrl
* @since 3.0
* @type String
* @default '' (empty string = disabled)
* @example
* config.filebrowserImageBrowseUrl = '/browser/browse.php?type=Images';
*/
/**
* The location of an external file browser, that should be launched when "Browse Server" button is pressed in the Flash dialog.
* If not set, CKEditor will use {@link CKEDITOR.config.filebrowserBrowseUrl}.
* @name CKEDITOR.config.filebrowserFlashBrowseUrl
* @since 3.0
* @type String
* @default '' (empty string = disabled)
* @example
* config.filebrowserFlashBrowseUrl = '/browser/browse.php?type=Flash';
*/
/**
* The location of a script that handles file uploads in the Image dialog.
* If not set, CKEditor will use {@link CKEDITOR.config.filebrowserUploadUrl}.
* @name CKEDITOR.config.filebrowserImageUploadUrl
* @since 3.0
* @type String
* @default '' (empty string = disabled)
* @example
* config.filebrowserImageUploadUrl = '/uploader/upload.php?type=Images';
*/
/**
* The location of a script that handles file uploads in the Flash dialog.
* If not set, CKEditor will use {@link CKEDITOR.config.filebrowserUploadUrl}.
* @name CKEDITOR.config.filebrowserFlashUploadUrl
* @since 3.0
* @type String
* @default '' (empty string = disabled)
* @example
* config.filebrowserFlashUploadUrl = '/uploader/upload.php?type=Flash';
*/
/**
* The location of an external file browser, that should be launched when "Browse Server" button is pressed in the Link tab of Image dialog.
* If not set, CKEditor will use {@link CKEDITOR.config.filebrowserBrowseUrl}.
* @name CKEDITOR.config.filebrowserImageBrowseLinkUrl
* @since 3.2
* @type String
* @default '' (empty string = disabled)
* @example
* config.filebrowserImageBrowseLinkUrl = '/browser/browse.php';
*/
/**
* The "features" to use in the file browser popup window.
* @name CKEDITOR.config.filebrowserWindowFeatures
* @since 3.4.1
* @type String
* @default 'location=no,menubar=no,toolbar=no,dependent=yes,minimizable=no,modal=yes,alwaysRaised=yes,resizable=yes,scrollbars=yes'
* @example
* config.filebrowserWindowFeatures = 'resizable=yes,scrollbars=no';
*/
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @fileOverview Spell Check As You Type (SCAYT).
* Button name : Scayt.
*/
(function()
{
var commandName = 'scaytcheck',
openPage = '';
// Checks if a value exists in an array
function in_array( needle, haystack )
{
var found = 0,
key;
for ( key in haystack )
{
if ( haystack[ key ] == needle )
{
found = 1;
break;
}
}
return found;
}
var onEngineLoad = function()
{
var editor = this;
var createInstance = function() // Create new instance every time Document is created.
{
var config = editor.config;
// Initialise Scayt instance.
var oParams = {};
// Get the iframe.
oParams.srcNodeRef = editor.document.getWindow().$.frameElement;
// syntax : AppName.AppVersion@AppRevision
oParams.assocApp = 'CKEDITOR.' + CKEDITOR.version + '@' + CKEDITOR.revision;
oParams.customerid = config.scayt_customerid || '1:WvF0D4-UtPqN1-43nkD4-NKvUm2-daQqk3-LmNiI-z7Ysb4-mwry24-T8YrS3-Q2tpq2';
oParams.customDictionaryIds = config.scayt_customDictionaryIds || '';
oParams.userDictionaryName = config.scayt_userDictionaryName || '';
oParams.sLang = config.scayt_sLang || 'en_US';
// Introduce SCAYT onLoad callback. (#5632)
oParams.onLoad = function()
{
// Draw down word marker to avoid being covered by background-color style.(#5466)
if ( !( CKEDITOR.env.ie && CKEDITOR.env.version < 8 ) )
this.addStyle( this.selectorCss(), 'padding-bottom: 2px !important;' );
// Call scayt_control.focus when SCAYT loaded
// and only if editor has focus and scayt control creates at first time (#5720)
if ( editor.focusManager.hasFocus && !plugin.isControlRestored( editor ) )
this.focus();
};
oParams.onBeforeChange = function()
{
if ( plugin.getScayt( editor ) && !editor.checkDirty() )
setTimeout( function(){ editor.resetDirty(); }, 0 );
};
var scayt_custom_params = window.scayt_custom_params;
if ( typeof scayt_custom_params == 'object' )
{
for ( var k in scayt_custom_params )
oParams[ k ] = scayt_custom_params[ k ];
}
// needs for restoring a specific scayt control settings
if ( plugin.getControlId( editor ) )
oParams.id = plugin.getControlId( editor );
var scayt_control = new window.scayt( oParams );
scayt_control.afterMarkupRemove.push( function( node )
{
( new CKEDITOR.dom.element( node, scayt_control.document ) ).mergeSiblings();
} );
// Copy config.
var lastInstance = plugin.instances[ editor.name ];
if ( lastInstance )
{
scayt_control.sLang = lastInstance.sLang;
scayt_control.option( lastInstance.option() );
scayt_control.paused = lastInstance.paused;
}
plugin.instances[ editor.name ] = scayt_control;
//window.scayt.uiTags
var menuGroup = 'scaytButton';
var uiTabs = window.scayt.uiTags;
var fTabs = [];
for ( var i = 0, l=4; i < l; i++ )
fTabs.push( uiTabs[i] && plugin.uiTabs[i] );
plugin.uiTabs = fTabs;
try {
scayt_control.setDisabled( plugin.isPaused( editor ) === false );
} catch (e) {}
editor.fire( 'showScaytState' );
};
editor.on( 'contentDom', createInstance );
editor.on( 'contentDomUnload', function()
{
// Remove scripts.
var scripts = CKEDITOR.document.getElementsByTag( 'script' ),
scaytIdRegex = /^dojoIoScript(\d+)$/i,
scaytSrcRegex = /^https?:\/\/svc\.spellchecker\.net\/spellcheck\/script\/ssrv\.cgi/i;
for ( var i=0; i < scripts.count(); i++ )
{
var script = scripts.getItem( i ),
id = script.getId(),
src = script.getAttribute( 'src' );
if ( id && src && id.match( scaytIdRegex ) && src.match( scaytSrcRegex ))
script.remove();
}
});
editor.on( 'beforeCommandExec', function( ev ) // Disable SCAYT before Source command execution.
{
if ( ( ev.data.name == 'source' || ev.data.name == 'newpage' ) && editor.mode == 'wysiwyg' )
{
var scayt_instance = plugin.getScayt( editor );
if ( scayt_instance )
{
plugin.setPaused( editor, !scayt_instance.disabled );
// store a control id for restore a specific scayt control settings
plugin.setControlId( editor, scayt_instance.id );
scayt_instance.destroy( true );
delete plugin.instances[ editor.name ];
}
}
// Catch on source mode switch off (#5720)
else if ( ev.data.name == 'source' && editor.mode == 'source' )
plugin.markControlRestore( editor );
});
editor.on( 'afterCommandExec', function( ev )
{
if ( !plugin.isScaytEnabled( editor ) )
return;
if ( editor.mode == 'wysiwyg' && ( ev.data.name == 'undo' || ev.data.name == 'redo' ) )
window.setTimeout( function() { plugin.getScayt( editor ).refresh(); }, 10 );
});
editor.on( 'destroy', function( ev )
{
var editor = ev.editor,
scayt_instance = plugin.getScayt( editor );
// SCAYT instance might already get destroyed by mode switch (#5744).
if ( !scayt_instance )
return;
delete plugin.instances[ editor.name ];
// store a control id for restore a specific scayt control settings
plugin.setControlId( editor, scayt_instance.id );
scayt_instance.destroy( true );
});
// Listen to data manipulation to reflect scayt markup.
editor.on( 'afterSetData', function()
{
if ( plugin.isScaytEnabled( editor ) ) {
window.setTimeout( function()
{
var instance = plugin.getScayt( editor );
instance && instance.refresh();
}, 10 );
}
});
// Reload spell-checking for current word after insertion completed.
editor.on( 'insertElement', function()
{
var scayt_instance = plugin.getScayt( editor );
if ( plugin.isScaytEnabled( editor ) )
{
// Unlock the selection before reload, SCAYT will take
// care selection update.
if ( CKEDITOR.env.ie )
editor.getSelection().unlock( true );
// Return focus to the editor and refresh SCAYT markup (#5573).
window.setTimeout( function()
{
scayt_instance.focus();
scayt_instance.refresh();
}, 10 );
}
}, this, null, 50 );
editor.on( 'insertHtml', function()
{
var scayt_instance = plugin.getScayt( editor );
if ( plugin.isScaytEnabled( editor ) )
{
// Unlock the selection before reload, SCAYT will take
// care selection update.
if ( CKEDITOR.env.ie )
editor.getSelection().unlock( true );
// Return focus to the editor (#5573)
// Refresh SCAYT markup
window.setTimeout( function()
{
scayt_instance.focus();
scayt_instance.refresh();
}, 10 );
}
}, this, null, 50 );
editor.on( 'scaytDialog', function( ev ) // Communication with dialog.
{
ev.data.djConfig = window.djConfig;
ev.data.scayt_control = plugin.getScayt( editor );
ev.data.tab = openPage;
ev.data.scayt = window.scayt;
});
var dataProcessor = editor.dataProcessor,
htmlFilter = dataProcessor && dataProcessor.htmlFilter;
if ( htmlFilter )
{
htmlFilter.addRules(
{
elements :
{
span : function( element )
{
if ( element.attributes[ 'data-scayt_word' ]
&& element.attributes[ 'data-scaytid' ] )
{
delete element.name; // Write children, but don't write this node.
return element;
}
}
}
}
);
}
// Override Image.equals method avoid CK snapshot module to add SCAYT markup to snapshots. (#5546)
var undoImagePrototype = CKEDITOR.plugins.undo.Image.prototype;
undoImagePrototype.equals = CKEDITOR.tools.override( undoImagePrototype.equals, function( org )
{
return function( otherImage )
{
var thisContents = this.contents,
otherContents = otherImage.contents;
var scayt_instance = plugin.getScayt( this.editor );
// Making the comparison based on content without SCAYT word markers.
if ( scayt_instance && plugin.isScaytReady( this.editor ) )
{
// scayt::reset might return value undefined. (#5742)
this.contents = scayt_instance.reset( thisContents ) || '';
otherImage.contents = scayt_instance.reset( otherContents ) || '';
}
var retval = org.apply( this, arguments );
this.contents = thisContents;
otherImage.contents = otherContents;
return retval;
};
});
if ( editor.document )
createInstance();
};
CKEDITOR.plugins.scayt =
{
engineLoaded : false,
instances : {},
// Data storage for SCAYT control, based on editor instances
controlInfo : {},
setControlInfo : function( editor, o )
{
if ( editor && editor.name && typeof ( this.controlInfo[ editor.name ] ) != 'object' )
this.controlInfo[ editor.name ] = {};
for ( var infoOpt in o )
this.controlInfo[ editor.name ][ infoOpt ] = o[ infoOpt ];
},
isControlRestored : function( editor )
{
if ( editor &&
editor.name &&
this.controlInfo[ editor.name ] )
{
return this.controlInfo[ editor.name ].restored ;
}
return false;
},
markControlRestore : function( editor )
{
this.setControlInfo( editor, { restored:true } );
},
setControlId: function( editor, id )
{
this.setControlInfo( editor, { id:id } );
},
getControlId: function( editor )
{
if ( editor &&
editor.name &&
this.controlInfo[ editor.name ] &&
this.controlInfo[ editor.name ].id )
{
return this.controlInfo[ editor.name ].id;
}
return null;
},
setPaused: function( editor , bool )
{
this.setControlInfo( editor, { paused:bool } );
},
isPaused: function( editor )
{
if ( editor &&
editor.name &&
this.controlInfo[editor.name] )
{
return this.controlInfo[editor.name].paused;
}
return undefined;
},
getScayt : function( editor )
{
return this.instances[ editor.name ];
},
isScaytReady : function( editor )
{
return this.engineLoaded === true &&
'undefined' !== typeof window.scayt && this.getScayt( editor );
},
isScaytEnabled : function( editor )
{
var scayt_instance = this.getScayt( editor );
return ( scayt_instance ) ? scayt_instance.disabled === false : false;
},
loadEngine : function( editor )
{
// SCAYT doesn't work with Firefox2, Opera and AIR.
if ( CKEDITOR.env.gecko && CKEDITOR.env.version < 10900 || CKEDITOR.env.opera || CKEDITOR.env.air )
return editor.fire( 'showScaytState' );
if ( this.engineLoaded === true )
return onEngineLoad.apply( editor ); // Add new instance.
else if ( this.engineLoaded == -1 ) // We are waiting.
return CKEDITOR.on( 'scaytReady', function(){ onEngineLoad.apply( editor ); } ); // Use function(){} to avoid rejection as duplicate.
CKEDITOR.on( 'scaytReady', onEngineLoad, editor );
CKEDITOR.on( 'scaytReady', function()
{
this.engineLoaded = true;
},
this,
null,
0
); // First to run.
this.engineLoaded = -1; // Loading in progress.
// compose scayt url
var protocol = document.location.protocol;
// Default to 'http' for unknown.
protocol = protocol.search( /https?:/) != -1? protocol : 'http:';
var baseUrl = 'svc.spellchecker.net/scayt26/loader__base.js';
var scaytUrl = editor.config.scayt_srcUrl || ( protocol + '//' + baseUrl );
var scaytConfigBaseUrl = plugin.parseUrl( scaytUrl ).path + '/';
if( window.scayt == undefined )
{
CKEDITOR._djScaytConfig =
{
baseUrl: scaytConfigBaseUrl,
addOnLoad:
[
function()
{
CKEDITOR.fireOnce( 'scaytReady' );
}
],
isDebug: false
};
// Append javascript code.
CKEDITOR.document.getHead().append(
CKEDITOR.document.createElement( 'script',
{
attributes :
{
type : 'text/javascript',
async : 'true',
src : scaytUrl
}
})
);
}
else
CKEDITOR.fireOnce( 'scaytReady' );
return null;
},
parseUrl : function ( data )
{
var match;
if ( data.match && ( match = data.match(/(.*)[\/\\](.*?\.\w+)$/) ) )
return { path: match[1], file: match[2] };
else
return data;
}
};
var plugin = CKEDITOR.plugins.scayt;
// Context menu constructing.
var addButtonCommand = function( editor, buttonName, buttonLabel, commandName, command, menugroup, menuOrder )
{
editor.addCommand( commandName, command );
// If the "menu" plugin is loaded, register the menu item.
editor.addMenuItem( commandName,
{
label : buttonLabel,
command : commandName,
group : menugroup,
order : menuOrder
});
};
var commandDefinition =
{
preserveState : true,
editorFocus : false,
canUndo : false,
exec: function( editor )
{
if ( plugin.isScaytReady( editor ) )
{
var isEnabled = plugin.isScaytEnabled( editor );
this.setState( isEnabled ? CKEDITOR.TRISTATE_OFF : CKEDITOR.TRISTATE_ON );
var scayt_control = plugin.getScayt( editor );
// the place where the status of editor focus should be restored
// after there will be ability to store its state before SCAYT button click
// if (storedFocusState is focused )
// scayt_control.focus();
//
// now focus is set certainly
scayt_control.focus();
scayt_control.setDisabled( isEnabled );
}
else if ( !editor.config.scayt_autoStartup && plugin.engineLoaded >= 0 ) // Load first time
{
this.setState( CKEDITOR.TRISTATE_DISABLED );
plugin.loadEngine( editor );
}
}
};
// Add scayt plugin.
CKEDITOR.plugins.add( 'scayt',
{
requires : [ 'menubutton' ],
beforeInit : function( editor )
{
var items_order = editor.config.scayt_contextMenuItemsOrder
|| 'suggest|moresuggest|control',
items_order_str = "";
items_order = items_order.split( '|' );
if ( items_order && items_order.length )
{
for ( var pos = 0 ; pos < items_order.length ; pos++ )
items_order_str += 'scayt_' + items_order[ pos ] + ( items_order.length != parseInt( pos, 10 ) + 1 ? ',' : '' );
}
// Put it on top of all context menu items (#5717)
editor.config.menu_groups = items_order_str + ',' + editor.config.menu_groups;
},
init : function( editor )
{
var moreSuggestions = {},
mainSuggestions = {};
// Scayt command.
var command = editor.addCommand( commandName, commandDefinition );
// Add Options dialog.
CKEDITOR.dialog.add( commandName, CKEDITOR.getUrl( this.path + 'dialogs/options.js' ) );
// read ui tags
var confuiTabs = editor.config.scayt_uiTabs || '1,1,1';
var uiTabs =[];
// string to array convert
confuiTabs = confuiTabs.split( ',' );
// check array length ! always must be 3 filled with 1 or 0
for ( var i=0, l=3; i < l; i++ )
{
var flag = parseInt( confuiTabs[i] || '1', 10 );
uiTabs.push( flag );
}
var menuGroup = 'scaytButton';
editor.addMenuGroup( menuGroup );
// combine menu items to render
var uiMuneItems = {};
var lang = editor.lang.scayt;
// always added
uiMuneItems.scaytToggle =
{
label : lang.enable,
command : commandName,
group : menuGroup
};
if ( uiTabs[0] == 1 )
uiMuneItems.scaytOptions =
{
label : lang.options,
group : menuGroup,
onClick : function()
{
openPage = 'options';
editor.openDialog( commandName );
}
};
if ( uiTabs[1] == 1 )
uiMuneItems.scaytLangs =
{
label : lang.langs,
group : menuGroup,
onClick : function()
{
openPage = 'langs';
editor.openDialog( commandName );
}
};
if ( uiTabs[2] == 1 )
uiMuneItems.scaytDict =
{
label : lang.dictionariesTab,
group : menuGroup,
onClick : function()
{
openPage = 'dictionaries';
editor.openDialog( commandName );
}
};
// always added
uiMuneItems.scaytAbout =
{
label : editor.lang.scayt.about,
group : menuGroup,
onClick : function()
{
openPage = 'about';
editor.openDialog( commandName );
}
};
uiTabs[3] = 1; // about us tab is always on
plugin.uiTabs = uiTabs;
editor.addMenuItems( uiMuneItems );
editor.ui.add( 'Scayt', CKEDITOR.UI_MENUBUTTON,
{
label : lang.title,
title : CKEDITOR.env.opera ? lang.opera_title : lang.title,
className : 'cke_button_scayt',
modes : { wysiwyg : 1 },
onRender: function()
{
command.on( 'state', function()
{
this.setState( command.state );
},
this);
},
onMenu : function()
{
var isEnabled = plugin.isScaytEnabled( editor );
editor.getMenuItem( 'scaytToggle' ).label = lang[ isEnabled ? 'disable' : 'enable' ];
return {
scaytToggle : CKEDITOR.TRISTATE_OFF,
scaytOptions : isEnabled && plugin.uiTabs[0] ? CKEDITOR.TRISTATE_OFF : CKEDITOR.TRISTATE_DISABLED,
scaytLangs : isEnabled && plugin.uiTabs[1] ? CKEDITOR.TRISTATE_OFF : CKEDITOR.TRISTATE_DISABLED,
scaytDict : isEnabled && plugin.uiTabs[2] ? CKEDITOR.TRISTATE_OFF : CKEDITOR.TRISTATE_DISABLED,
scaytAbout : isEnabled && plugin.uiTabs[3] ? CKEDITOR.TRISTATE_OFF : CKEDITOR.TRISTATE_DISABLED
};
}
});
// If the "contextmenu" plugin is loaded, register the listeners.
if ( editor.contextMenu && editor.addMenuItems )
{
editor.contextMenu.addListener( function( element, selection )
{
if ( !plugin.isScaytEnabled( editor )
|| selection.getCommonAncestor().isReadOnly() )
return null;
var scayt_control = plugin.getScayt( editor ),
node = scayt_control.getScaytNode();
if ( !node )
return null;
var word = scayt_control.getWord( node );
if ( !word )
return null;
var sLang = scayt_control.getLang(),
_r = {},
items_suggestion = window.scayt.getSuggestion( word, sLang );
if ( !items_suggestion || !items_suggestion.length )
return null;
// Remove unused commands and menuitems
for ( i in moreSuggestions )
{
delete editor._.menuItems[ i ];
delete editor._.commands[ i ];
}
for ( i in mainSuggestions )
{
delete editor._.menuItems[ i ];
delete editor._.commands[ i ];
}
moreSuggestions = {}; // Reset items.
mainSuggestions = {};
var moreSuggestionsUnable = editor.config.scayt_moreSuggestions || 'on';
var moreSuggestionsUnableAdded = false;
var maxSuggestions = editor.config.scayt_maxSuggestions;
( typeof maxSuggestions != 'number' ) && ( maxSuggestions = 5 );
!maxSuggestions && ( maxSuggestions = items_suggestion.length );
var contextCommands = editor.config.scayt_contextCommands || 'all';
contextCommands = contextCommands.split( '|' );
for ( var i = 0, l = items_suggestion.length; i < l; i += 1 )
{
var commandName = 'scayt_suggestion_' + items_suggestion[i].replace( ' ', '_' );
var exec = ( function( el, s )
{
return {
exec: function()
{
scayt_control.replace( el, s );
}
};
})( node, items_suggestion[i] );
if ( i < maxSuggestions )
{
addButtonCommand( editor, 'button_' + commandName, items_suggestion[i],
commandName, exec, 'scayt_suggest', i + 1 );
_r[ commandName ] = CKEDITOR.TRISTATE_OFF;
mainSuggestions[ commandName ] = CKEDITOR.TRISTATE_OFF;
}
else if ( moreSuggestionsUnable == 'on' )
{
addButtonCommand( editor, 'button_' + commandName, items_suggestion[i],
commandName, exec, 'scayt_moresuggest', i + 1 );
moreSuggestions[ commandName ] = CKEDITOR.TRISTATE_OFF;
moreSuggestionsUnableAdded = true;
}
}
if ( moreSuggestionsUnableAdded )
{
// Register the More suggestions group;
editor.addMenuItem( 'scayt_moresuggest',
{
label : lang.moreSuggestions,
group : 'scayt_moresuggest',
order : 10,
getItems : function()
{
return moreSuggestions;
}
});
mainSuggestions[ 'scayt_moresuggest' ] = CKEDITOR.TRISTATE_OFF;
}
if ( in_array( 'all', contextCommands ) || in_array( 'ignore', contextCommands) )
{
var ignore_command = {
exec: function(){
scayt_control.ignore( node );
}
};
addButtonCommand( editor, 'ignore', lang.ignore, 'scayt_ignore', ignore_command, 'scayt_control', 1 );
mainSuggestions[ 'scayt_ignore' ] = CKEDITOR.TRISTATE_OFF;
}
if ( in_array( 'all', contextCommands ) || in_array( 'ignoreall', contextCommands ) )
{
var ignore_all_command = {
exec: function(){
scayt_control.ignoreAll( node );
}
};
addButtonCommand(editor, 'ignore_all', lang.ignoreAll, 'scayt_ignore_all', ignore_all_command, 'scayt_control', 2);
mainSuggestions['scayt_ignore_all'] = CKEDITOR.TRISTATE_OFF;
}
if ( in_array( 'all', contextCommands ) || in_array( 'add', contextCommands ) )
{
var addword_command = {
exec: function(){
window.scayt.addWordToUserDictionary( node );
}
};
addButtonCommand(editor, 'add_word', lang.addWord, 'scayt_add_word', addword_command, 'scayt_control', 3);
mainSuggestions['scayt_add_word'] = CKEDITOR.TRISTATE_OFF;
}
if ( scayt_control.fireOnContextMenu )
scayt_control.fireOnContextMenu( editor );
return mainSuggestions;
});
}
var showInitialState = function()
{
editor.removeListener( 'showScaytState', showInitialState );
if ( !CKEDITOR.env.opera && !CKEDITOR.env.air )
command.setState( plugin.isScaytEnabled( editor ) ? CKEDITOR.TRISTATE_ON : CKEDITOR.TRISTATE_OFF );
else
command.setState( CKEDITOR.TRISTATE_DISABLED );
};
editor.on( 'showScaytState', showInitialState );
if ( CKEDITOR.env.opera || CKEDITOR.env.air )
{
editor.on( 'instanceReady', function()
{
showInitialState();
});
}
// Start plugin
if ( editor.config.scayt_autoStartup )
{
editor.on( 'instanceReady', function()
{
plugin.loadEngine( editor );
});
}
},
afterInit : function( editor )
{
// Prevent word marker line from displaying in elements path and been removed when cleaning format. (#3570) (#4125)
var elementsPathFilters,
scaytFilter = function( element )
{
if ( element.hasAttribute( 'data-scaytid' ) )
return false;
};
if ( editor._.elementsPath && ( elementsPathFilters = editor._.elementsPath.filters ) )
elementsPathFilters.push( scaytFilter );
editor.addRemoveFormatFilter && editor.addRemoveFormatFilter( scaytFilter );
}
});
})();
/**
* If enabled (true), turns on SCAYT automatically after loading the editor.
* @name CKEDITOR.config.scayt_autoStartup
* @type Boolean
* @default false
* @example
* config.scayt_autoStartup = true;
*/
/**
* Defines the number of SCAYT suggestions to show in the main context menu.
* The possible values are:
* <ul>
* <li>0 (zero): All suggestions are displayed in the main context menu.</li>
* <li>Positive number: The maximum number of suggestions to shown in context
* menu. Other entries will be shown in "More Suggestions" sub-menu.</li>
* <li>Negative number: No suggestions are shown in the main context menu. All
* entries will be listed in the "Suggestions" sub-menu.</li>
* </ul>
* @name CKEDITOR.config.scayt_maxSuggestions
* @type Number
* @default 5
* @example
* // Display only three suggestions in the main context menu.
* config.scayt_maxSuggestions = 3;
* @example
* // Do not show the suggestions directly.
* config.scayt_maxSuggestions = -1;
*/
/**
* Sets the customer ID for SCAYT. Required for migration from free version
* with banner to paid version.
* @name CKEDITOR.config.scayt_customerid
* @type String
* @default ''
* @example
* // Load SCAYT using my customer ID.
* config.scayt_customerid = 'your-encrypted-customer-id';
*/
/**
* Enables/disables the "More Suggestions" sub-menu in the context menu.
* The possible values are "on" or "off".
* @name CKEDITOR.config.scayt_moreSuggestions
* @type String
* @default 'on'
* @example
* // Disables the "More Suggestions" sub-menu.
* config.scayt_moreSuggestions = 'off';
*/
/**
* Customizes the display of SCAYT context menu commands ("Add Word", "Ignore"
* and "Ignore All"). It must be a string with one or more of the following
* words separated by a pipe ("|"):
* <ul>
* <li>"off": disables all options.</li>
* <li>"all": enables all options.</li>
* <li>"ignore": enables the "Ignore" option.</li>
* <li>"ignoreall": enables the "Ignore All" option.</li>
* <li>"add": enables the "Add Word" option.</li>
* </ul>
* @name CKEDITOR.config.scayt_contextCommands
* @type String
* @default 'all'
* @example
* // Show only "Add Word" and "Ignore All" in the context menu.
* config.scayt_contextCommands = 'add|ignoreall';
*/
/**
* Sets the default spellchecking language for SCAYT.
* @name CKEDITOR.config.scayt_sLang
* @type String
* @default 'en_US'
* @example
* // Sets SCAYT to German.
* config.scayt_sLang = 'de_DE';
*/
/**
* Sets the visibility of the SCAYT tabs in the settings dialog and toolbar
* button. The value must contain a "1" (enabled) or "0" (disabled) number for
* each of the following entries, in this precise order, separated by a
* comma (","): "Options", "Languages" and "Dictionary".
* @name CKEDITOR.config.scayt_uiTabs
* @type String
* @default '1,1,1'
* @example
* // Hide the "Languages" tab.
* config.scayt_uiTabs = '1,0,1';
*/
/**
* Set the URL to SCAYT core. Required to switch to licensed version of SCAYT application.
* Further details at http://wiki.spellchecker.net/doku.php?id=3rd:wysiwyg:fckeditor:wscckf3l .
* @name CKEDITOR.config.scayt_srcUrl
* @type String
* @default ''
* @example
* config.scayt_srcUrl = "http://my-host/spellcheck/lf/scayt/scayt.js";
*/
/**
* Links SCAYT to custom dictionaries. It's a string containing dictionary ids
* separared by commas (","). Available only for licensed version.
* Further details at http://wiki.spellchecker.net/doku.php?id=custom_dictionary_support .
* @name CKEDITOR.config.scayt_customDictionaryIds
* @type String
* @default ''
* @example
* config.scayt_customDictionaryIds = '3021,3456,3478"';
*/
/**
* Makes it possible to activate a custom dictionary on SCAYT. The user
* dictionary name must be used. Available only for licensed version.
* @name CKEDITOR.config.scayt_userDictionaryName
* @type String
* @default ''
* @example
* config.scayt_userDictionaryName = 'MyDictionary';
*/
/**
* Define order of placing of SCAYT context menu items by groups.
* It must be a string with one or more of the following
* words separated by a pipe ("|"):
* <ul>
* <li>'suggest' - main suggestion word list,</li>
* <li>'moresuggest' - more suggestions word list,</li>
* <li>'control' - SCAYT commands, such as 'Ignore' and 'Add Word'</li>
* </ul>
*
* @name CKEDITOR.config.scayt_contextMenuItemsOrder
* @type String
* @default 'suggest|moresuggest|control'
* @example
* config.scayt_contextMenuItemsOrder = 'moresuggest|control|suggest';
*/
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.dialog.add( 'scaytcheck', function( editor )
{
var firstLoad = true,
captions,
doc = CKEDITOR.document,
tags = [],
i,
contents = [],
userDicActive = 0,
dic_buttons = [
// [0] contains buttons for creating
"dic_create,dic_restore",
// [1] contains buton for manipulation
"dic_rename,dic_delete"
],
optionsIds = [ 'mixedCase', 'mixedWithDigits', 'allCaps', 'ignoreDomainNames' ];
// common operations
function getBOMAllOptions()
{
return document.forms.optionsbar["options"];
}
function getBOMAllLangs()
{
return document.forms.languagesbar["scayt_lang"];
}
function setCheckedValue( radioObj, newValue )
{
if ( !radioObj )
return;
var radioLength = radioObj.length;
if ( radioLength == undefined )
{
radioObj.checked = radioObj.value == newValue.toString();
return;
}
for ( var i = 0; i < radioLength; i++ )
{
radioObj[i].checked = false;
if ( radioObj[i].value == newValue.toString() )
radioObj[i].checked = true;
}
}
var lang = editor.lang.scayt;
var tags_contents = [
{
id : 'options',
label : lang.optionsTab,
elements : [
{
type : 'html',
id : 'options',
html : '<form name="optionsbar"><div class="inner_options">' +
' <div class="messagebox"></div>' +
' <div style="display:none;">' +
' <input type="checkbox" name="options" id="allCaps" />' +
' <label for="allCaps" id="label_allCaps"></label>' +
' </div>' +
' <div style="display:none;">' +
' <input name="options" type="checkbox" id="ignoreDomainNames" />' +
' <label for="ignoreDomainNames" id="label_ignoreDomainNames"></label>' +
' </div>' +
' <div style="display:none;">' +
' <input name="options" type="checkbox" id="mixedCase" />' +
' <label for="mixedCase" id="label_mixedCase"></label>' +
' </div>' +
' <div style="display:none;">' +
' <input name="options" type="checkbox" id="mixedWithDigits" />' +
' <label for="mixedWithDigits" id="label_mixedWithDigits"></label>' +
' </div>' +
'</div></form>'
}
]
},
{
id : 'langs',
label : lang.languagesTab,
elements : [
{
type : 'html',
id : 'langs',
html : '<form name="languagesbar"><div class="inner_langs">' +
' <div class="messagebox"></div> ' +
' <div style="float:left;width:45%;margin-left:5px;" id="scayt_lcol" ></div>' +
' <div style="float:left;width:45%;margin-left:15px;" id="scayt_rcol"></div>' +
'</div></form>'
}
]
},
{
id : 'dictionaries',
label : lang.dictionariesTab,
elements : [
{
type : 'html',
style: '',
id : 'dictionaries',
html : '<form name="dictionarybar"><div class="inner_dictionary" style="text-align:left; white-space:normal; width:320px; overflow: hidden;">' +
' <div style="margin:5px auto; width:80%;white-space:normal; overflow:hidden;" id="dic_message"> </div>' +
' <div style="margin:5px auto; width:80%;white-space:normal;"> ' +
' <span class="cke_dialog_ui_labeled_label" >Dictionary name</span><br>'+
' <span class="cke_dialog_ui_labeled_content" >'+
' <div class="cke_dialog_ui_input_text">'+
' <input id="dic_name" type="text" class="cke_dialog_ui_input_text"/>'+
' </div></span></div>'+
' <div style="margin:5px auto; width:80%;white-space:normal;">'+
' <a style="display:none;" class="cke_dialog_ui_button" href="javascript:void(0)" id="dic_create">'+
' </a>' +
' <a style="display:none;" class="cke_dialog_ui_button" href="javascript:void(0)" id="dic_delete">'+
' </a>' +
' <a style="display:none;" class="cke_dialog_ui_button" href="javascript:void(0)" id="dic_rename">'+
' </a>' +
' <a style="display:none;" class="cke_dialog_ui_button" href="javascript:void(0)" id="dic_restore">'+
' </a>' +
' </div>' +
' <div style="margin:5px auto; width:95%;white-space:normal;" id="dic_info"></div>' +
'</div></form>'
}
]
},
{
id : 'about',
label : lang.aboutTab,
elements : [
{
type : 'html',
id : 'about',
style : 'margin: 5px 5px;',
html : '<div id="scayt_about"></div>'
}
]
}
];
var dialogDefiniton = {
title : lang.title,
minWidth : 360,
minHeight : 220,
onShow : function()
{
var dialog = this;
dialog.data = editor.fire( 'scaytDialog', {} );
dialog.options = dialog.data.scayt_control.option();
dialog.sLang = dialog.data.scayt_control.sLang;
if ( !dialog.data || !dialog.data.scayt || !dialog.data.scayt_control )
{
alert( 'Error loading application service' );
dialog.hide();
return;
}
var stop = 0;
if ( firstLoad )
{
dialog.data.scayt.getCaption( editor.langCode || 'en', function( caps )
{
if ( stop++ > 0 ) // Once only
return;
captions = caps;
init_with_captions.apply( dialog );
reload.apply( dialog );
firstLoad = false;
});
}
else
reload.apply( dialog );
dialog.selectPage( dialog.data.tab );
},
onOk : function()
{
var scayt_control = this.data.scayt_control;
scayt_control.option( this.options );
// Setup languge if it was changed.
var csLang = this.chosed_lang;
scayt_control.setLang( csLang );
scayt_control.refresh();
},
onCancel: function()
{
var o = getBOMAllOptions();
for ( var i in o )
o[i].checked = false;
setCheckedValue( getBOMAllLangs(), "" );
},
contents : contents
};
var scayt_control = CKEDITOR.plugins.scayt.getScayt( editor );
tags = CKEDITOR.plugins.scayt.uiTabs;
for ( i in tags )
{
if ( tags[ i ] == 1 )
contents[ contents.length ] = tags_contents[ i ];
}
if ( tags[2] == 1 )
userDicActive = 1;
var init_with_captions = function()
{
var dialog = this,
lang_list = dialog.data.scayt.getLangList(),
buttons = [ 'dic_create', 'dic_delete', 'dic_rename', 'dic_restore' ],
labels = optionsIds,
i;
// Add buttons titles
if ( userDicActive )
{
for ( i = 0; i < buttons.length; i++ )
{
var button = buttons[ i ];
doc.getById( button ).setHtml( '<span class="cke_dialog_ui_button">' + captions[ 'button_' + button] +'</span>' );
}
doc.getById( 'dic_info' ).setHtml( captions[ 'dic_info' ] );
}
// Fill options and dictionary labels.
if ( tags[0] == 1 )
{
for ( i in labels )
{
var label = 'label_' + labels[ i ],
labelElement = doc.getById( label );
if ( 'undefined' != typeof labelElement
&& 'undefined' != typeof captions[ label ]
&& 'undefined' != typeof dialog.options[labels[ i ]] )
{
labelElement.setHtml( captions[ label ] );
var labelParent = labelElement.getParent();
labelParent.$.style.display = "block";
}
}
}
var about = '<p><img src="' + window.scayt.getAboutInfo().logoURL + '" /></p>' +
'<p>' + captions[ 'version' ] + window.scayt.getAboutInfo().version.toString() + '</p>' +
'<p>' + captions[ 'about_throwt_copy' ] + '</p>';
doc.getById( 'scayt_about' ).setHtml( about );
// Create languages tab.
var createOption = function( option, list )
{
var label = doc.createElement( 'label' );
label.setAttribute( 'for', 'cke_option' + option );
label.setHtml( list[ option ] );
if ( dialog.sLang == option ) // Current.
dialog.chosed_lang = option;
var div = doc.createElement( 'div' );
var radio = CKEDITOR.dom.element.createFromHtml( '<input id="cke_option' +
option + '" type="radio" ' +
( dialog.sLang == option ? 'checked="checked"' : '' ) +
' value="' + option + '" name="scayt_lang" />' );
radio.on( 'click', function()
{
this.$.checked = true;
dialog.chosed_lang = option;
});
div.append( radio );
div.append( label );
return {
lang : list[ option ],
code : option,
radio : div
};
};
var langList = [];
if ( tags[1] ==1 )
{
for ( i in lang_list.rtl )
langList[ langList.length ] = createOption( i, lang_list.ltr );
for ( i in lang_list.ltr )
langList[ langList.length ] = createOption( i, lang_list.ltr );
langList.sort( function( lang1, lang2 )
{
return ( lang2.lang > lang1.lang ) ? -1 : 1 ;
});
var fieldL = doc.getById( 'scayt_lcol' ),
fieldR = doc.getById( 'scayt_rcol' );
for ( i=0; i < langList.length; i++ )
{
var field = ( i < langList.length / 2 ) ? fieldL : fieldR;
field.append( langList[ i ].radio );
}
}
// user dictionary handlers
var dic = {};
dic.dic_create = function( el, dic_name , dic_buttons )
{
// comma separated button's ids include repeats if exists
var all_buttons = dic_buttons[0] + ',' + dic_buttons[1];
var err_massage = captions["err_dic_create"];
var suc_massage = captions["succ_dic_create"];
window.scayt.createUserDictionary( dic_name,
function( arg )
{
hide_dic_buttons ( all_buttons );
display_dic_buttons ( dic_buttons[1] );
suc_massage = suc_massage.replace("%s" , arg.dname );
dic_success_message (suc_massage);
},
function( arg )
{
err_massage = err_massage.replace("%s" ,arg.dname );
dic_error_message ( err_massage + "( "+ (arg.message || "") +")");
});
};
dic.dic_rename = function( el, dic_name )
{
//
// try to rename dictionary
var err_massage = captions["err_dic_rename"] || "";
var suc_massage = captions["succ_dic_rename"] || "";
window.scayt.renameUserDictionary( dic_name,
function( arg )
{
suc_massage = suc_massage.replace("%s" , arg.dname );
set_dic_name( dic_name );
dic_success_message ( suc_massage );
},
function( arg )
{
err_massage = err_massage.replace("%s" , arg.dname );
set_dic_name( dic_name );
dic_error_message( err_massage + "( " + ( arg.message || "" ) + " )" );
});
};
dic.dic_delete = function( el, dic_name , dic_buttons )
{
var all_buttons = dic_buttons[0] + ',' + dic_buttons[1];
var err_massage = captions["err_dic_delete"];
var suc_massage = captions["succ_dic_delete"];
// try to delete dictionary
window.scayt.deleteUserDictionary(
function( arg )
{
suc_massage = suc_massage.replace("%s" , arg.dname );
hide_dic_buttons ( all_buttons );
display_dic_buttons ( dic_buttons[0] );
set_dic_name( "" ); // empty input field
dic_success_message( suc_massage );
},
function( arg )
{
err_massage = err_massage.replace("%s" , arg.dname );
dic_error_message(err_massage);
});
};
dic.dic_restore = dialog.dic_restore || function( el, dic_name , dic_buttons )
{
// try to restore existing dictionary
var all_buttons = dic_buttons[0] + ',' + dic_buttons[1];
var err_massage = captions["err_dic_restore"];
var suc_massage = captions["succ_dic_restore"];
window.scayt.restoreUserDictionary(dic_name,
function( arg )
{
suc_massage = suc_massage.replace("%s" , arg.dname );
hide_dic_buttons ( all_buttons );
display_dic_buttons(dic_buttons[1]);
dic_success_message( suc_massage );
},
function( arg )
{
err_massage = err_massage.replace("%s" , arg.dname );
dic_error_message( err_massage );
});
};
function onDicButtonClick( ev )
{
var dic_name = doc.getById('dic_name').getValue();
if ( !dic_name )
{
dic_error_message(" Dictionary name should not be empty. ");
return false;
}
try{
var el = id = ev.data.getTarget().getParent();
var id = el.getId();
dic[ id ].apply( null, [ el, dic_name, dic_buttons ] );
}
catch(err)
{
dic_error_message(" Dictionary error. ");
}
return true;
}
// ** bind event listeners
var arr_buttons = ( dic_buttons[0] + ',' + dic_buttons[1] ).split( ',' ),
l;
for ( i = 0, l = arr_buttons.length ; i < l ; i += 1 )
{
var dic_button = doc.getById(arr_buttons[i]);
if ( dic_button )
dic_button.on( 'click', onDicButtonClick, this );
}
};
var reload = function()
{
var dialog = this;
// for enabled options tab
if ( tags[0] == 1 ){
var opto = getBOMAllOptions();
// Animate options.
for ( var k=0,l = opto.length; k<l;k++ )
{
var i = opto[k].id;
var checkbox = doc.getById( i );
if ( checkbox )
{
opto[k].checked = false;
//alert (opto[k].removeAttribute)
if ( dialog.options[ i ] == 1 )
{
opto[k].checked = true;
}
// Bind events. Do it only once.
if ( firstLoad )
{
checkbox.on( 'click', function()
{
dialog.options[ this.getId() ] = this.$.checked ? 1 : 0 ;
});
}
}
}
}
//for enabled languages tab
if ( tags[1] == 1 )
{
var domLang = doc.getById("cke_option" + dialog.sLang);
setCheckedValue( domLang.$,dialog.sLang );
}
// * user dictionary
if ( userDicActive )
{
window.scayt.getNameUserDictionary(
function( o )
{
var dic_name = o.dname;
hide_dic_buttons( dic_buttons[0] + ',' + dic_buttons[1] );
if ( dic_name )
{
doc.getById( 'dic_name' ).setValue(dic_name);
display_dic_buttons( dic_buttons[1] );
}
else
display_dic_buttons( dic_buttons[0] );
},
function()
{
doc.getById( 'dic_name' ).setValue("");
});
dic_success_message("");
}
};
function dic_error_message( m )
{
doc.getById('dic_message').setHtml('<span style="color:red;">' + m + '</span>' );
}
function dic_success_message( m )
{
doc.getById('dic_message').setHtml('<span style="color:blue;">' + m + '</span>') ;
}
function display_dic_buttons( sIds )
{
sIds = String( sIds );
var aIds = sIds.split(',');
for ( var i=0, l = aIds.length; i < l ; i+=1)
doc.getById( aIds[i] ).$.style.display = "inline";
}
function hide_dic_buttons( sIds )
{
sIds = String( sIds );
var aIds = sIds.split(',');
for ( var i = 0, l = aIds.length; i < l ; i += 1 )
doc.getById( aIds[i] ).$.style.display = "none";
}
function set_dic_name( dic_name )
{
doc.getById('dic_name').$.value= dic_name;
}
return dialogDefiniton;
});
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.add( 'listblock',
{
requires : [ 'panel' ],
onLoad : function()
{
CKEDITOR.ui.panel.prototype.addListBlock = function( name, definition )
{
return this.addBlock( name, new CKEDITOR.ui.listBlock( this.getHolderElement(), definition ) );
};
CKEDITOR.ui.listBlock = CKEDITOR.tools.createClass(
{
base : CKEDITOR.ui.panel.block,
$ : function( blockHolder, blockDefinition )
{
blockDefinition = blockDefinition || {};
var attribs = blockDefinition.attributes || ( blockDefinition.attributes = {} );
( this.multiSelect = !!blockDefinition.multiSelect ) &&
( attribs[ 'aria-multiselectable' ] = true );
// Provide default role of 'listbox'.
!attribs.role && ( attribs.role = 'listbox' );
// Call the base contructor.
this.base.apply( this, arguments );
var keys = this.keys;
keys[ 40 ] = 'next'; // ARROW-DOWN
keys[ 9 ] = 'next'; // TAB
keys[ 38 ] = 'prev'; // ARROW-UP
keys[ CKEDITOR.SHIFT + 9 ] = 'prev'; // SHIFT + TAB
keys[ 32 ] = 'click'; // SPACE
this._.pendingHtml = [];
this._.items = {};
this._.groups = {};
},
_ :
{
close : function()
{
if ( this._.started )
{
this._.pendingHtml.push( '</ul>' );
delete this._.started;
}
},
getClick : function()
{
if ( !this._.click )
{
this._.click = CKEDITOR.tools.addFunction( function( value )
{
var marked = true;
if ( this.multiSelect )
marked = this.toggle( value );
else
this.mark( value );
if ( this.onClick )
this.onClick( value, marked );
},
this );
}
return this._.click;
}
},
proto :
{
add : function( value, html, title )
{
var pendingHtml = this._.pendingHtml,
id = CKEDITOR.tools.getNextId();
if ( !this._.started )
{
pendingHtml.push( '<ul role="presentation" class=cke_panel_list>' );
this._.started = 1;
this._.size = this._.size || 0;
}
this._.items[ value ] = id;
pendingHtml.push(
'<li id=', id, ' class=cke_panel_listItem role=presentation>' +
'<a id="', id, '_option" _cke_focus=1 hidefocus=true' +
' title="', title || value, '"' +
' href="javascript:void(\'', value, '\')"' +
' onclick="CKEDITOR.tools.callFunction(', this._.getClick(), ',\'', value, '\'); return false;"',
' role="option"' +
' aria-posinset="' + ++this._.size + '">',
html || value,
'</a>' +
'</li>' );
},
startGroup : function( title )
{
this._.close();
var id = CKEDITOR.tools.getNextId();
this._.groups[ title ] = id;
this._.pendingHtml.push( '<h1 role="presentation" id=', id, ' class=cke_panel_grouptitle>', title, '</h1>' );
},
commit : function()
{
this._.close();
this.element.appendHtml( this._.pendingHtml.join( '' ) );
var items = this._.items,
doc = this.element.getDocument();
for ( var value in items )
doc.getById( items[ value ] + '_option' ).setAttribute( 'aria-setsize', this._.size );
delete this._.size;
this._.pendingHtml = [];
},
toggle : function( value )
{
var isMarked = this.isMarked( value );
if ( isMarked )
this.unmark( value );
else
this.mark( value );
return !isMarked;
},
hideGroup : function( groupTitle )
{
var group = this.element.getDocument().getById( this._.groups[ groupTitle ] ),
list = group && group.getNext();
if ( group )
{
group.setStyle( 'display', 'none' );
if ( list && list.getName() == 'ul' )
list.setStyle( 'display', 'none' );
}
},
hideItem : function( value )
{
this.element.getDocument().getById( this._.items[ value ] ).setStyle( 'display', 'none' );
},
showAll : function()
{
var items = this._.items,
groups = this._.groups,
doc = this.element.getDocument();
for ( var value in items )
{
doc.getById( items[ value ] ).setStyle( 'display', '' );
}
for ( var title in groups )
{
var group = doc.getById( groups[ title ] ),
list = group.getNext();
group.setStyle( 'display', '' );
if ( list && list.getName() == 'ul' )
list.setStyle( 'display', '' );
}
},
mark : function( value )
{
if ( !this.multiSelect )
this.unmarkAll();
var itemId = this._.items[ value ],
item = this.element.getDocument().getById( itemId );
item.addClass( 'cke_selected' );
this.element.getDocument().getById( itemId + '_option' ).setAttribute( 'aria-selected', true );
this.element.setAttribute( 'aria-activedescendant', itemId + '_option' );
this.onMark && this.onMark( item );
},
unmark : function( value )
{
this.element.getDocument().getById( this._.items[ value ] ).removeClass( 'cke_selected' );
this.onUnmark && this.onUnmark( this._.items[ value ] );
},
unmarkAll : function()
{
var items = this._.items,
doc = this.element.getDocument();
for ( var value in items )
{
doc.getById( items[ value ] ).removeClass( 'cke_selected' );
}
this.onUnmark && this.onUnmark();
},
isMarked : function( value )
{
return this.element.getDocument().getById( this._.items[ value ] ).hasClass( 'cke_selected' );
},
focus : function( value )
{
this._.focusIndex = -1;
if ( value )
{
var selected = this.element.getDocument().getById( this._.items[ value ] ).getFirst();
var links = this.element.getElementsByTag( 'a' ),
link,
i = -1;
while ( ( link = links.getItem( ++i ) ) )
{
if ( link.equals( selected ) )
{
this._.focusIndex = i;
break;
}
}
setTimeout( function()
{
selected.focus();
},
0 );
}
}
}
});
}
});
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @file Paste as plain text plugin
*/
(function()
{
// The pastetext command definition.
var pasteTextCmd =
{
exec : function( editor )
{
var clipboardText = CKEDITOR.tools.tryThese(
function()
{
var clipboardText = window.clipboardData.getData( 'Text' );
if ( !clipboardText )
throw 0;
return clipboardText;
}
// Any other approach that's working...
);
if ( !clipboardText ) // Clipboard access privilege is not granted.
{
editor.openDialog( 'pastetext' );
return false;
}
else
editor.fire( 'paste', { 'text' : clipboardText } );
return true;
}
};
// Register the plugin.
CKEDITOR.plugins.add( 'pastetext',
{
init : function( editor )
{
var commandName = 'pastetext',
command = editor.addCommand( commandName, pasteTextCmd );
editor.ui.addButton( 'PasteText',
{
label : editor.lang.pasteText.button,
command : commandName
});
CKEDITOR.dialog.add( commandName, CKEDITOR.getUrl( this.path + 'dialogs/pastetext.js' ) );
if ( editor.config.forcePasteAsPlainText )
{
// Intercept the default pasting process.
editor.on( 'beforeCommandExec', function ( evt )
{
if ( evt.data.name == 'paste' )
{
editor.execCommand( 'pastetext' );
evt.cancel();
}
}, null, null, 0 );
}
},
requires : [ 'clipboard' ]
});
})();
/**
* Whether to force all pasting operations to insert on plain text into the
* editor, loosing any formatting information possibly available in the source
* text.
* @name CKEDITOR.config.forcePasteAsPlainText
* @type Boolean
* @default false
* @example
* config.forcePasteAsPlainText = true;
*/
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
(function()
{
CKEDITOR.dialog.add( 'pastetext', function( editor )
{
return {
title : editor.lang.pasteText.title,
minWidth : CKEDITOR.env.ie && CKEDITOR.env.quirks ? 368 : 350,
minHeight : 240,
onShow : function()
{
// Reset the textarea value.
this.getContentElement( 'general', 'content' ).getInputElement().setValue( '' );
},
onOk : function()
{
// Get the textarea value.
var text = this.getContentElement( 'general', 'content' ).getInputElement().getValue(),
editor = this.getParentEditor();
setTimeout( function()
{
editor.fire( 'paste', { 'text' : text } );
}, 0 );
},
contents :
[
{
label : editor.lang.common.generalTab,
id : 'general',
elements :
[
{
type : 'html',
id : 'pasteMsg',
html : '<div style="white-space:normal;width:340px;">' + editor.lang.clipboard.pasteMsg + '</div>'
},
{
type : 'textarea',
id : 'content',
className : 'cke_pastetext',
onLoad : function()
{
var label = this.getDialog().getContentElement( 'general', 'pasteMsg' ).getElement(),
input = this.getElement().getElementsByTag( 'textarea' ).getItem( 0 );
input.setAttribute( 'aria-labelledby', label.$.id );
input.setStyle( 'direction', editor.config.contentsLangDirection );
},
focus : function()
{
this.getElement().focus();
}
}
]
}
]
};
});
})();
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
(function()
{
var pxUnit = CKEDITOR.tools.cssLength,
needsIEHacks = CKEDITOR.env.ie && ( CKEDITOR.env.ie7Compat || CKEDITOR.env.quirks || CKEDITOR.env.version < 7 );
function getWidth( el )
{
return CKEDITOR.env.ie ? el.$.clientWidth : parseInt( el.getComputedStyle( 'width' ), 10 );
}
function getBorderWidth( element, side )
{
var computed = element.getComputedStyle( 'border-' + side + '-width' ),
borderMap =
{
thin: '0px',
medium: '1px',
thick: '2px'
};
if ( computed.indexOf( 'px' ) < 0 )
{
// look up keywords
if ( computed in borderMap && element.getComputedStyle( 'border-style' ) != 'none' )
computed = borderMap[ computed ];
else
computed = 0;
}
return parseInt( computed, 10 );
}
// Gets the table row that contains the most columns.
function getMasterPillarRow( table )
{
var $rows = table.$.rows,
maxCells = 0, cellsCount,
$elected, $tr;
for ( var i = 0, len = $rows.length ; i < len; i++ )
{
$tr = $rows[ i ];
cellsCount = $tr.cells.length;
if ( cellsCount > maxCells )
{
maxCells = cellsCount;
$elected = $tr;
}
}
return $elected;
}
function buildTableColumnPillars( table )
{
var pillars = [],
pillarIndex = -1,
rtl = ( table.getComputedStyle( 'direction' ) == 'rtl' );
// Get the raw row element that cointains the most columns.
var $tr = getMasterPillarRow( table );
// Get the tbody element and position, which will be used to set the
// top and bottom boundaries.
var tbody = new CKEDITOR.dom.element( table.$.tBodies[ 0 ] ),
tbodyPosition = tbody.getDocumentPosition();
// Loop thorugh all cells, building pillars after each one of them.
for ( var i = 0, len = $tr.cells.length ; i < len ; i++ )
{
// Both the current cell and the successive one will be used in the
// pillar size calculation.
var td = new CKEDITOR.dom.element( $tr.cells[ i ] ),
nextTd = $tr.cells[ i + 1 ] && new CKEDITOR.dom.element( $tr.cells[ i + 1 ] );
pillarIndex += td.$.colSpan || 1;
// Calculate the pillar boundary positions.
var pillarLeft, pillarRight, pillarWidth, pillarPadding;
var x = td.getDocumentPosition().x;
// Calculate positions based on the current cell.
rtl ?
pillarRight = x + getBorderWidth( td, 'left' ) :
pillarLeft = x + td.$.offsetWidth - getBorderWidth( td, 'right' );
// Calculate positions based on the next cell, if available.
if ( nextTd )
{
x = nextTd.getDocumentPosition().x;
rtl ?
pillarLeft = x + nextTd.$.offsetWidth - getBorderWidth( nextTd, 'right' ) :
pillarRight = x + getBorderWidth( nextTd, 'left' );
}
// Otherwise calculate positions based on the table (for last cell).
else
{
x = table.getDocumentPosition().x;
rtl ?
pillarLeft = x :
pillarRight = x + table.$.offsetWidth;
}
pillarWidth = Math.max( pillarRight - pillarLeft, 3 );
// Make the pillar touch area at least 14 pixels wide, for easy to use.
pillarPadding = Math.max( Math.round( 7 - ( pillarWidth / 2 ) ), 0 );
// The pillar should reflects exactly the shape of the hovered
// column border line.
pillars.push( {
table : table,
index : pillarIndex,
x : pillarLeft,
y : tbodyPosition.y,
width : pillarWidth,
height: tbody.$.offsetHeight,
padding : pillarPadding,
rtl : rtl } );
}
return pillars;
}
function getPillarAtPosition( pillars, positionX )
{
for ( var i = 0, len = pillars.length ; i < len ; i++ )
{
var pillar = pillars[ i ],
pad = pillar.padding;
if ( positionX >= pillar.x - pad && positionX <= ( pillar.x + pillar.width + pad ) )
return pillar;
}
return null;
}
function cancel( evt )
{
( evt.data || evt ).preventDefault();
}
function columnResizer( editor )
{
var pillar,
document,
resizer,
isResizing,
startOffset,
currentShift;
var leftSideCells, rightSideCells, leftShiftBoundary, rightShiftBoundary;
function detach()
{
pillar = null;
currentShift = 0;
isResizing = 0;
document.removeListener( 'mouseup', onMouseUp );
resizer.removeListener( 'mousedown', onMouseDown );
resizer.removeListener( 'mousemove', onMouseMove );
document.getBody().setStyle( 'cursor', 'auto' );
// Hide the resizer (remove it on IE7 - #5890).
needsIEHacks ? resizer.remove() : resizer.hide();
}
function resizeStart()
{
// Before starting to resize, figure out which cells to change
// and the boundaries of this resizing shift.
var columnIndex = pillar.index,
map = CKEDITOR.tools.buildTableMap( pillar.table ),
leftColumnCells = [],
rightColumnCells = [],
leftMinSize = Number.MAX_VALUE,
rightMinSize = leftMinSize,
rtl = pillar.rtl;
for ( var i = 0, len = map.length ; i < len ; i++ )
{
var row = map[ i ],
leftCell = row[ columnIndex + ( rtl ? 1 : 0 ) ],
rightCell = row[ columnIndex + ( rtl ? 0 : 1 ) ];
leftCell = leftCell && new CKEDITOR.dom.element( leftCell );
rightCell = rightCell && new CKEDITOR.dom.element( rightCell );
if ( !leftCell || !rightCell || !leftCell.equals( rightCell ) )
{
leftCell && ( leftMinSize = Math.min( leftMinSize, getWidth( leftCell ) ) );
rightCell && ( rightMinSize = Math.min( rightMinSize, getWidth( rightCell ) ) );
leftColumnCells.push( leftCell );
rightColumnCells.push( rightCell );
}
}
// Cache the list of cells to be resized.
leftSideCells = leftColumnCells;
rightSideCells = rightColumnCells;
// Cache the resize limit boundaries.
leftShiftBoundary = pillar.x - leftMinSize;
rightShiftBoundary = pillar.x + rightMinSize;
resizer.setOpacity( 0.5 );
startOffset = parseInt( resizer.getStyle( 'left' ), 10 );
currentShift = 0;
isResizing = 1;
resizer.on( 'mousemove', onMouseMove );
// Prevent the native drag behavior otherwise 'mousemove' won't fire.
document.on( 'dragstart', cancel );
}
function resizeEnd()
{
isResizing = 0;
resizer.setOpacity( 0 );
currentShift && resizeColumn();
var table = pillar.table;
setTimeout( function () { table.removeCustomData( '_cke_table_pillars' ); }, 0 );
document.removeListener( 'dragstart', cancel );
}
function resizeColumn()
{
var rtl = pillar.rtl,
cellsCount = rtl ? rightSideCells.length : leftSideCells.length;
// Perform the actual resize to table cells, only for those by side of the pillar.
for ( var i = 0 ; i < cellsCount ; i++ )
{
var leftCell = leftSideCells[ i ],
rightCell = rightSideCells[ i ],
table = pillar.table;
// Defer the resizing to avoid any interference among cells.
CKEDITOR.tools.setTimeout(
function( leftCell, leftOldWidth, rightCell, rightOldWidth, tableWidth, sizeShift )
{
leftCell && leftCell.setStyle( 'width', pxUnit( Math.max( leftOldWidth + sizeShift, 0 ) ) );
rightCell && rightCell.setStyle( 'width', pxUnit( Math.max( rightOldWidth - sizeShift, 0 ) ) );
// If we're in the last cell, we need to resize the table as well
if ( tableWidth )
table.setStyle( 'width', pxUnit( tableWidth + sizeShift * ( rtl ? -1 : 1 ) ) );
}
, 0,
this, [
leftCell, leftCell && getWidth( leftCell ),
rightCell, rightCell && getWidth( rightCell ),
( !leftCell || !rightCell ) && ( getWidth( table ) + getBorderWidth( table, 'left' ) + getBorderWidth( table, 'right' ) ),
currentShift ] );
}
}
function onMouseDown( evt )
{
cancel( evt );
resizeStart();
document.on( 'mouseup', onMouseUp, this );
}
function onMouseUp( evt )
{
evt.removeListener();
resizeEnd();
}
function onMouseMove( evt )
{
move( evt.data.$.clientX );
}
document = editor.document;
resizer = CKEDITOR.dom.element.createFromHtml(
'<div data-cke-temp=1 contenteditable=false unselectable=on '+
'style="position:absolute;cursor:col-resize;filter:alpha(opacity=0);opacity:0;' +
'padding:0;background-color:#004;background-image:none;border:0px none;z-index:10"></div>', document );
// Except on IE6/7 (#5890), place the resizer after body to prevent it
// from being editable.
if ( !needsIEHacks )
document.getDocumentElement().append( resizer );
this.attachTo = function( targetPillar )
{
// Accept only one pillar at a time.
if ( isResizing )
return;
// On IE6/7, we append the resizer everytime we need it. (#5890)
if ( needsIEHacks )
{
document.getBody().append( resizer );
currentShift = 0;
}
pillar = targetPillar;
resizer.setStyles(
{
width: pxUnit( targetPillar.width ),
height : pxUnit( targetPillar.height ),
left : pxUnit( targetPillar.x ),
top : pxUnit( targetPillar.y )
});
// In IE6/7, it's not possible to have custom cursors for floating
// elements in an editable document. Show the resizer in that case,
// to give the user a visual clue.
needsIEHacks && resizer.setOpacity( 0.25 );
resizer.on( 'mousedown', onMouseDown, this );
document.getBody().setStyle( 'cursor', 'col-resize' );
// Display the resizer to receive events but don't show it,
// only change the cursor to resizable shape.
resizer.show();
};
var move = this.move = function( posX )
{
if ( !pillar )
return 0;
var pad = pillar.padding;
if ( !isResizing && ( posX < pillar.x - pad || posX > ( pillar.x + pillar.width + pad ) ) )
{
detach();
return 0;
}
var resizerNewPosition = posX - Math.round( resizer.$.offsetWidth / 2 );
if ( isResizing )
{
if ( resizerNewPosition == leftShiftBoundary || resizerNewPosition == rightShiftBoundary )
return 1;
resizerNewPosition = Math.max( resizerNewPosition, leftShiftBoundary );
resizerNewPosition = Math.min( resizerNewPosition, rightShiftBoundary );
currentShift = resizerNewPosition - startOffset;
}
resizer.setStyle( 'left', pxUnit( resizerNewPosition ) );
return 1;
};
}
function clearPillarsCache( evt )
{
var target = evt.data.getTarget();
if ( evt.name == 'mouseout' )
{
// Bypass interal mouse move.
if ( !target.is ( 'table' ) )
return;
var dest = new CKEDITOR.dom.element( evt.data.$.relatedTarget || evt.data.$.toElement );
while( dest && dest.$ && !dest.equals( target ) && !dest.is( 'body' ) )
dest = dest.getParent();
if ( !dest || dest.equals( target ) )
return;
}
target.getAscendant( 'table', 1 ).removeCustomData( '_cke_table_pillars' );
evt.removeListener();
}
CKEDITOR.plugins.add( 'tableresize',
{
requires : [ 'tabletools' ],
init : function( editor )
{
editor.on( 'contentDom', function()
{
var resizer;
editor.document.getBody().on( 'mousemove', function( evt )
{
evt = evt.data;
// If we're already attached to a pillar, simply move the
// resizer.
if ( resizer && resizer.move( evt.$.clientX ) )
{
cancel( evt );
return;
}
// Considering table, tr, td, tbody but nothing else.
var target = evt.getTarget(),
table,
pillars;
if ( !target.is( 'table' ) && !target.getAscendant( 'tbody', 1 ) )
return;
table = target.getAscendant( 'table', 1 );
if ( !( pillars = table.getCustomData( '_cke_table_pillars' ) ) )
{
// Cache table pillars calculation result.
table.setCustomData( '_cke_table_pillars', ( pillars = buildTableColumnPillars( table ) ) );
table.on( 'mouseout', clearPillarsCache );
table.on( 'mousedown', clearPillarsCache );
}
var pillar = getPillarAtPosition( pillars, evt.$.clientX );
if ( pillar )
{
!resizer && ( resizer = new columnResizer( editor ) );
resizer.attachTo( pillar );
}
});
});
}
});
})();
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.add( 'resize',
{
init : function( editor )
{
var config = editor.config;
!config.resize_dir && ( config.resize_dir = 'both' );
( config.resize_maxWidth == undefined ) && ( config.resize_maxWidth = 3000 );
( config.resize_maxHeight == undefined ) && ( config.resize_maxHeight = 3000 );
( config.resize_minWidth == undefined ) && ( config.resize_minWidth = 750 );
( config.resize_minHeight == undefined ) && ( config.resize_minHeight = 250 );
if ( config.resize_enabled !== false )
{
var container = null,
origin,
startSize,
resizeHorizontal = ( config.resize_dir == 'both' || config.resize_dir == 'horizontal' ) &&
( config.resize_minWidth != config.resize_maxWidth ),
resizeVertical = ( config.resize_dir == 'both' || config.resize_dir == 'vertical' ) &&
( config.resize_minHeight != config.resize_maxHeight );
function dragHandler( evt )
{
var dx = evt.data.$.screenX - origin.x,
dy = evt.data.$.screenY - origin.y,
width = startSize.width,
height = startSize.height,
internalWidth = width + dx * ( editor.lang.dir == 'rtl' ? -1 : 1 ),
internalHeight = height + dy;
if ( resizeHorizontal )
width = Math.max( config.resize_minWidth, Math.min( internalWidth, config.resize_maxWidth ) );
if ( resizeVertical )
height = Math.max( config.resize_minHeight, Math.min( internalHeight, config.resize_maxHeight ) );
editor.resize( width, height );
}
function dragEndHandler ( evt )
{
CKEDITOR.document.removeListener( 'mousemove', dragHandler );
CKEDITOR.document.removeListener( 'mouseup', dragEndHandler );
if ( editor.document )
{
editor.document.removeListener( 'mousemove', dragHandler );
editor.document.removeListener( 'mouseup', dragEndHandler );
}
}
var mouseDownFn = CKEDITOR.tools.addFunction( function( $event )
{
if ( !container )
container = editor.getResizable();
startSize = { width : container.$.offsetWidth || 0, height : container.$.offsetHeight || 0 };
origin = { x : $event.screenX, y : $event.screenY };
config.resize_minWidth > startSize.width && ( config.resize_minWidth = startSize.width );
config.resize_minHeight > startSize.height && ( config.resize_minHeight = startSize.height );
CKEDITOR.document.on( 'mousemove', dragHandler );
CKEDITOR.document.on( 'mouseup', dragEndHandler );
if ( editor.document )
{
editor.document.on( 'mousemove', dragHandler );
editor.document.on( 'mouseup', dragEndHandler );
}
});
editor.on( 'destroy', function() { CKEDITOR.tools.removeFunction( mouseDownFn ); } );
editor.on( 'themeSpace', function( event )
{
if ( event.data.space == 'bottom' )
{
var direction = '';
if ( resizeHorizontal && !resizeVertical )
direction = ' cke_resizer_horizontal';
if ( !resizeHorizontal && resizeVertical )
direction = ' cke_resizer_vertical';
event.data.html += '<div class="cke_resizer' + direction + '"' +
' title="' + CKEDITOR.tools.htmlEncode( editor.lang.resize ) + '"' +
' onmousedown="CKEDITOR.tools.callFunction(' + mouseDownFn + ', event)"' +
'></div>';
}
}, editor, null, 100 );
}
}
} );
/**
* The minimum editor width, in pixels, when resizing it with the resize handle.
* Note: It fallbacks to editor's actual width if that's smaller than the default value.
* @name CKEDITOR.config.resize_minWidth
* @type Number
* @default 750
* @example
* config.resize_minWidth = 500;
*/
/**
* The minimum editor height, in pixels, when resizing it with the resize handle.
* Note: It fallbacks to editor's actual height if that's smaller than the default value.
* @name CKEDITOR.config.resize_minHeight
* @type Number
* @default 250
* @example
* config.resize_minHeight = 600;
*/
/**
* The maximum editor width, in pixels, when resizing it with the resize handle.
* @name CKEDITOR.config.resize_maxWidth
* @type Number
* @default 3000
* @example
* config.resize_maxWidth = 750;
*/
/**
* The maximum editor height, in pixels, when resizing it with the resize handle.
* @name CKEDITOR.config.resize_maxHeight
* @type Number
* @default 3000
* @example
* config.resize_maxHeight = 600;
*/
/**
* Whether to enable the resizing feature. If disabled the resize handler will not be visible.
* @name CKEDITOR.config.resize_enabled
* @type Boolean
* @default true
* @example
* config.resize_enabled = false;
*/
/**
* The directions to which the editor resizing is enabled. Possible values
* are "both", "vertical" and "horizontal".
* @name CKEDITOR.config.resize_dir
* @type String
* @default 'both'
* @since 3.3
* @example
* config.resize_dir = 'vertical';
*/
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @fileOverview The "show border" plugin. The command display visible outline
* border line around all table elements if table doesn't have a none-zero 'border' attribute specified.
*/
(function()
{
var showBorderClassName = 'cke_show_border',
cssStyleText,
cssTemplate =
// TODO: For IE6, we don't have child selector support,
// where nested table cells could be incorrect.
( CKEDITOR.env.ie6Compat ?
[
'.%1 table.%2,',
'.%1 table.%2 td, .%1 table.%2 th,',
'{',
'border : #d3d3d3 1px dotted',
'}'
] :
[
'.%1 table.%2,',
'.%1 table.%2 > tr > td, .%1 table.%2 > tr > th,',
'.%1 table.%2 > tbody > tr > td, .%1 table.%2 > tbody > tr > th,',
'.%1 table.%2 > thead > tr > td, .%1 table.%2 > thead > tr > th,',
'.%1 table.%2 > tfoot > tr > td, .%1 table.%2 > tfoot > tr > th',
'{',
'border : #d3d3d3 1px dotted',
'}'
] ).join( '' );
cssStyleText = cssTemplate.replace( /%2/g, showBorderClassName ).replace( /%1/g, 'cke_show_borders ' );
var commandDefinition =
{
preserveState : true,
editorFocus : false,
exec : function ( editor )
{
this.toggleState();
this.refresh( editor );
},
refresh : function( editor )
{
var funcName = ( this.state == CKEDITOR.TRISTATE_ON ) ? 'addClass' : 'removeClass';
editor.document.getBody()[ funcName ]( 'cke_show_borders' );
}
};
CKEDITOR.plugins.add( 'showborders',
{
requires : [ 'wysiwygarea' ],
modes : { 'wysiwyg' : 1 },
init : function( editor )
{
var command = editor.addCommand( 'showborders', commandDefinition );
command.canUndo = false;
if ( editor.config.startupShowBorders !== false )
command.setState( CKEDITOR.TRISTATE_ON );
editor.addCss( cssStyleText );
// Refresh the command on setData.
editor.on( 'mode', function()
{
if ( command.state != CKEDITOR.TRISTATE_DISABLED )
command.refresh( editor );
}, null, null, 100 );
// Refresh the command on wysiwyg frame reloads.
editor.on( 'contentDom', function()
{
if ( command.state != CKEDITOR.TRISTATE_DISABLED )
command.refresh( editor );
});
editor.on( 'removeFormatCleanup', function( evt )
{
var element = evt.data;
if ( editor.getCommand( 'showborders' ).state == CKEDITOR.TRISTATE_ON &&
element.is( 'table' ) && ( !element.hasAttribute( 'border' ) || parseInt( element.getAttribute( 'border' ), 10 ) <= 0 ) )
element.addClass( showBorderClassName );
});
},
afterInit : function( editor )
{
var dataProcessor = editor.dataProcessor,
dataFilter = dataProcessor && dataProcessor.dataFilter,
htmlFilter = dataProcessor && dataProcessor.htmlFilter;
if ( dataFilter )
{
dataFilter.addRules(
{
elements :
{
'table' : function( element )
{
var attributes = element.attributes,
cssClass = attributes[ 'class' ],
border = parseInt( attributes.border, 10 );
if ( !border || border <= 0 )
attributes[ 'class' ] = ( cssClass || '' ) + ' ' + showBorderClassName;
}
}
} );
}
if ( htmlFilter )
{
htmlFilter.addRules(
{
elements :
{
'table' : function( table )
{
var attributes = table.attributes,
cssClass = attributes[ 'class' ];
cssClass && ( attributes[ 'class' ] =
cssClass.replace( showBorderClassName, '' )
.replace( /\s{2}/, ' ' )
.replace( /^\s+|\s+$/, '' ) );
}
}
} );
}
}
});
// Table dialog must be aware of it.
CKEDITOR.on( 'dialogDefinition', function( ev )
{
var dialogName = ev.data.name;
if ( dialogName == 'table' || dialogName == 'tableProperties' )
{
var dialogDefinition = ev.data.definition,
infoTab = dialogDefinition.getContents( 'info' ),
borderField = infoTab.get( 'txtBorder' ),
originalCommit = borderField.commit;
borderField.commit = CKEDITOR.tools.override( originalCommit, function( org )
{
return function( data, selectedTable )
{
org.apply( this, arguments );
var value = parseInt( this.getValue(), 10 );
selectedTable[ ( !value || value <= 0 ) ? 'addClass' : 'removeClass' ]( showBorderClassName );
};
} );
var advTab = dialogDefinition.getContents( 'advanced' ),
classField = advTab && advTab.get( 'advCSSClasses' );
if ( classField )
{
classField.setup = CKEDITOR.tools.override( classField.setup, function( originalSetup )
{
return function()
{
originalSetup.apply( this, arguments );
this.setValue( this.getValue().replace( /cke_show_border/, '' ) );
};
});
classField.commit = CKEDITOR.tools.override( classField.commit, function( originalCommit )
{
return function( data, element )
{
originalCommit.apply( this, arguments );
if ( !parseInt( element.getAttribute( 'border' ), 10 ) )
element.addClass( 'cke_show_border' );
};
});
}
}
});
} )();
/**
* Whether to automatically enable the "show borders" command when the editor loads.
* (ShowBorders in FCKeditor)
* @name CKEDITOR.config.startupShowBorders
* @type Boolean
* @default true
* @example
* config.startupShowBorders = false;
*/
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
(function()
{
// Base HTML entities.
var htmlbase = 'nbsp,gt,lt,quot';
var entities =
// Latin-1 Entities
'iexcl,cent,pound,curren,yen,brvbar,sect,uml,copy,ordf,laquo,' +
'not,shy,reg,macr,deg,plusmn,sup2,sup3,acute,micro,para,middot,' +
'cedil,sup1,ordm,raquo,frac14,frac12,frac34,iquest,times,divide,' +
// Symbols
'fnof,bull,hellip,prime,Prime,oline,frasl,weierp,image,real,trade,' +
'alefsym,larr,uarr,rarr,darr,harr,crarr,lArr,uArr,rArr,dArr,hArr,' +
'forall,part,exist,empty,nabla,isin,notin,ni,prod,sum,minus,lowast,' +
'radic,prop,infin,ang,and,or,cap,cup,int,there4,sim,cong,asymp,ne,' +
'equiv,le,ge,sub,sup,nsub,sube,supe,oplus,otimes,perp,sdot,lceil,' +
'rceil,lfloor,rfloor,lang,rang,loz,spades,clubs,hearts,diams,' +
// Other Special Characters
'circ,tilde,ensp,emsp,thinsp,zwnj,zwj,lrm,rlm,ndash,mdash,lsquo,' +
'rsquo,sbquo,ldquo,rdquo,bdquo,dagger,Dagger,permil,lsaquo,rsaquo,' +
'euro';
// Latin Letters Entities
var latin =
'Agrave,Aacute,Acirc,Atilde,Auml,Aring,AElig,Ccedil,Egrave,Eacute,' +
'Ecirc,Euml,Igrave,Iacute,Icirc,Iuml,ETH,Ntilde,Ograve,Oacute,Ocirc,' +
'Otilde,Ouml,Oslash,Ugrave,Uacute,Ucirc,Uuml,Yacute,THORN,szlig,' +
'agrave,aacute,acirc,atilde,auml,aring,aelig,ccedil,egrave,eacute,' +
'ecirc,euml,igrave,iacute,icirc,iuml,eth,ntilde,ograve,oacute,ocirc,' +
'otilde,ouml,oslash,ugrave,uacute,ucirc,uuml,yacute,thorn,yuml,' +
'OElig,oelig,Scaron,scaron,Yuml';
// Greek Letters Entities.
var greek =
'Alpha,Beta,Gamma,Delta,Epsilon,Zeta,Eta,Theta,Iota,Kappa,Lambda,Mu,' +
'Nu,Xi,Omicron,Pi,Rho,Sigma,Tau,Upsilon,Phi,Chi,Psi,Omega,alpha,' +
'beta,gamma,delta,epsilon,zeta,eta,theta,iota,kappa,lambda,mu,nu,xi,' +
'omicron,pi,rho,sigmaf,sigma,tau,upsilon,phi,chi,psi,omega,thetasym,' +
'upsih,piv';
/**
* Create a mapping table between one character and it's entity form from a list of entity names.
* @param reverse {Boolean} Whether create a reverse map from the entity string form to actual character.
*/
function buildTable( entities, reverse )
{
var table = {},
regex = [];
// Entities that the browsers DOM don't transform to the final char
// automatically.
var specialTable =
{
nbsp : '\u00A0', // IE | FF
shy : '\u00AD', // IE
gt : '\u003E', // IE | FF | -- | Opera
lt : '\u003C' // IE | FF | Safari | Opera
};
entities = entities.replace( /\b(nbsp|shy|gt|lt|amp)(?:,|$)/g, function( match, entity )
{
var org = reverse ? '&' + entity + ';' : specialTable[ entity ],
result = reverse ? specialTable[ entity ] : '&' + entity + ';';
table[ org ] = result;
regex.push( org );
return '';
});
if ( !reverse )
{
// Transforms the entities string into an array.
entities = entities.split( ',' );
// Put all entities inside a DOM element, transforming them to their
// final chars.
var div = document.createElement( 'div' ),
chars;
div.innerHTML = '&' + entities.join( ';&' ) + ';';
chars = div.innerHTML;
div = null;
// Add all chars to the table.
for ( var i = 0 ; i < chars.length ; i++ )
{
var charAt = chars.charAt( i );
table[ charAt ] = '&' + entities[ i ] + ';';
regex.push( charAt );
}
}
table.regex = regex.join( reverse ? '|' : '' );
return table;
}
CKEDITOR.plugins.add( 'entities',
{
afterInit : function( editor )
{
var config = editor.config;
var dataProcessor = editor.dataProcessor,
htmlFilter = dataProcessor && dataProcessor.htmlFilter;
if ( htmlFilter )
{
// Mandatory HTML base entities.
var selectedEntities = htmlbase;
if ( config.entities )
{
selectedEntities += ',' + entities;
if ( config.entities_latin )
selectedEntities += ',' + latin;
if ( config.entities_greek )
selectedEntities += ',' + greek;
if ( config.entities_additional )
selectedEntities += ',' + config.entities_additional;
}
var entitiesTable = buildTable( selectedEntities );
// Create the Regex used to find entities in the text.
var entitiesRegex = '[' + entitiesTable.regex + ']';
delete entitiesTable.regex;
if ( config.entities && config.entities_processNumerical )
entitiesRegex = '[^ -~]|' + entitiesRegex ;
entitiesRegex = new RegExp( entitiesRegex, 'g' );
function getEntity( character )
{
return config.entities_processNumerical == 'force' || !entitiesTable[ character ] ?
'&#' + character.charCodeAt(0) + ';'
: entitiesTable[ character ];
}
// Decode entities that the browsers has transformed
// at first place.
var baseEntitiesTable = buildTable( [ htmlbase, 'shy' ].join( ',' ) , true ),
baseEntitiesRegex = new RegExp( baseEntitiesTable.regex, 'g' );
function getChar( character )
{
return baseEntitiesTable[ character ];
}
htmlFilter.addRules(
{
text : function( text )
{
return text.replace( baseEntitiesRegex, getChar )
.replace( entitiesRegex, getEntity );
}
});
}
}
});
})();
/**
* Whether to use HTML entities in the output.
* @type Boolean
* @default true
* @example
* config.entities = false;
*/
CKEDITOR.config.entities = true;
/**
* Whether to convert some Latin characters (Latin alphabet No. 1, ISO 8859-1)
* to HTML entities. The list of entities can be found at the
* <a href="http://www.w3.org/TR/html4/sgml/entities.html#h-24.2.1">W3C HTML 4.01 Specification, section 24.2.1</a>.
* @type Boolean
* @default true
* @example
* config.entities_latin = false;
*/
CKEDITOR.config.entities_latin = true;
/**
* Whether to convert some symbols, mathematical symbols, and Greek letters to
* HTML entities. This may be more relevant for users typing text written in Greek.
* The list of entities can be found at the
* <a href="http://www.w3.org/TR/html4/sgml/entities.html#h-24.3.1">W3C HTML 4.01 Specification, section 24.3.1</a>.
* @type Boolean
* @default true
* @example
* config.entities_greek = false;
*/
CKEDITOR.config.entities_greek = true;
/**
* Whether to convert all remaining characters, not comprised in the ASCII
* character table, to their relative decimal numeric representation of HTML entity.
* When specified as the value 'force', it will simply convert all entities into the above form.
* For example, the phrase "This is Chinese: 汉语." is outputted
* as "This is Chinese: &#27721;&#35821;."
* @type Boolean
* @type Boolean|String
* @default false
* @example
* config.entities_processNumerical = true;
* config.entities_processNumerical = 'force'; //Convert from " " into " ";
*/
/**
* An additional list of entities to be used. It's a string containing each
* entry separated by a comma. Entities names or number must be used, exclusing
* the "&" preffix and the ";" termination.
* @default '#39' // The single quote (') character.
* @type String
* @example
*/
CKEDITOR.config.entities_additional = '#39';
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @fileOverview Plugin definition for the a11yhelp, which provides a dialog
* with accessibility related help.
*/
(function()
{
var pluginName = 'a11yhelp',
commandName = 'a11yHelp';
CKEDITOR.plugins.add( pluginName,
{
// List of available localizations.
availableLangs : { en:1, he:1 },
init : function( editor )
{
var plugin = this;
editor.addCommand( commandName,
{
exec : function()
{
var langCode = editor.langCode;
langCode = plugin.availableLangs[ langCode ] ? langCode : 'en';
CKEDITOR.scriptLoader.load(
CKEDITOR.getUrl( plugin.path + 'lang/' + langCode + '.js' ),
function()
{
CKEDITOR.tools.extend( editor.lang, plugin.lang[ langCode ] );
editor.openDialog( commandName );
});
},
modes : { wysiwyg:1, source:1 },
canUndo : false
});
CKEDITOR.dialog.add( commandName, this.path + 'dialogs/a11yhelp.js' );
}
});
})();
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'a11yhelp', 'en',
{
accessibilityHelp :
{
title : 'Accessibility Instructions',
contents : 'Help Contents. To close this dialog press ESC.',
legend :
[
{
name : 'General',
items :
[
{
name : 'Editor Toolbar',
legend:
'Press ${toolbarFocus} to navigate to the toolbar. ' +
'Move to next toolbar button with TAB or RIGHT ARROW. ' +
'Move to previous button with SHIFT+TAB or LEFT ARROW. ' +
'Press SPACE or ENTER to activate the toolbar button.'
},
{
name : 'Editor Dialog',
legend :
'Inside a dialog, press TAB to navigate to next dialog field, press SHIFT + TAB to move to previous field, press ENTER to submit dialog, press ESC to cancel dialog. ' +
'For dialogs that have multiple tab pages, press ALT + F10 to navigate to tab-list. ' +
'Then move to next tab with TAB OR RIGTH ARROW. ' +
'Move to previous tab with SHIFT + TAB or LEFT ARROW. ' +
'Press SPACE or ENTER to select the tab page.'
},
{
name : 'Editor Context Menu',
legend :
'Press ${contextMenu} or APPLICATION KEY to open context-menu. ' +
'Then move to next menu option with TAB or DOWN ARROW. ' +
'Move to previous option with SHIFT+TAB or UP ARROW. ' +
'Press SPACE or ENTER to select the menu option. ' +
'Open sub-menu of current option wtih SPACE or ENTER or RIGHT ARROW. ' +
'Go back to parent menu item with ESC or LEFT ARROW. ' +
'Close context menu with ESC.'
},
{
name : 'Editor List Box',
legend :
'Inside a list-box, move to next list item with TAB OR DOWN ARROW. ' +
'Move to previous list item with SHIFT + TAB or UP ARROW. ' +
'Press SPACE or ENTER to select the list option. ' +
'Press ESC to close the list-box.'
},
{
name : 'Editor Element Path Bar',
legend :
'Press ${elementsPathFocus} to navigate to the elements path bar. ' +
'Move to next element button with TAB or RIGHT ARROW. ' +
'Move to previous button with SHIFT+TAB or LEFT ARROW. ' +
'Press SPACE or ENTER to select the element in editor.'
}
]
},
{
name : 'Commands',
items :
[
{
name : ' Undo command',
legend : 'Press ${undo}'
},
{
name : ' Redo command',
legend : 'Press ${redo}'
},
{
name : ' Bold command',
legend : 'Press ${bold}'
},
{
name : ' Italic command',
legend : 'Press ${italic}'
},
{
name : ' Underline command',
legend : 'Press ${underline}'
},
{
name : ' Link command',
legend : 'Press ${link}'
},
{
name : ' Toolbar Collapse command',
legend : 'Press ${toolbarCollapse}'
},
{
name : ' Accessibility Help',
legend : 'Press ${a11yHelp}'
}
]
}
]
}
});
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'a11yhelp', 'he',
{
accessibilityHelp :
{
title : 'הוראות נגישות',
contents : 'הוראות נגישות. לסגירה לחץ אסקייפ (ESC).',
legend :
[
{
name : 'כללי',
items :
[
{
name : 'סרגל הכלים',
legend:
'לחץ על ${toolbarFocus} כדי לנווט לסרגל הכלים. ' +
'עבור לכפתור הבא עם מקש הטאב (TAB) או חץ שמאלי. ' +
'עבור לכפתור הקודם עם מקש השיפט (SHIFT) + טאב (TAB) או חץ ימני. ' +
'לחץ רווח או אנטר (ENTER) כדי להפעיל את הכפתור הנבחר.'
},
{
name : 'דיאלוגים (חלונות תשאול)',
legend :
'בתוך דיאלוג, לחץ טאב (TAB) כדי לנווט לשדה הבא, לחץ שיפט (SHIFT) + טאב (TAB) כדי לנווט לשדה הקודם, לחץ אנטר (ENTER) כדי לשלוח את הדיאלוג, לחץ אסקייפ (ESC) כדי לבטל. ' +
'בתוך דיאלוגים בעלי מספר טאבים (לשוניות), לחץ אלט (ALT) + F10 כדי לנווט לשורת הטאבים. ' +
'נווט לטאב הבא עם טאב (TAB) או חץ שמאלי. ' +
'עבור לטאב הקודם עם שיפט (SHIFT) + טאב (TAB) או חץ שמאלי. ' +
'לחץ רווח או אנטר (ENTER) כדי להיכנס לטאב.'
},
{
name : 'תפריט ההקשר (Context Menu)',
legend :
'לחץ ${contextMenu} או APPLICATION KEYכדי לפתוח את תפריט ההקשר. ' +
'עבור לאפשרות הבאה עם טאב (TAB) או חץ למטה. ' +
'עבור לאפשרות הקודמת עם שיפט (SHIFT) + טאב (TAB) או חץ למעלה. ' +
'לחץ רווח או אנטר (ENTER) כדי לבחור את האפשרות. ' +
'פתח את תת התפריט (Sub-menu) של האפשרות הנוכחית עם רווח או אנטר (ENTER) או חץ שמאלי. ' +
'חזור לתפריט האב עם אסקייפ (ESC) או חץ שמאלי. ' +
'סגור את תפריט ההקשר עם אסקייפ (ESC).'
},
{
name : 'תפריטים צפים (List boxes)',
legend :
'בתוך תפריט צף, עבור לפריט הבא עם טאב (TAB) או חץ למטה. ' +
'עבור לתפריט הקודם עם שיפט (SHIFT) + טאב (TAB) or חץ עליון. ' +
'Press SPACE or ENTER to select the list option. ' +
'Press ESC to close the list-box.'
},
{
name : 'עץ אלמנטים (Elements Path)',
legend :
'לחץ ${elementsPathFocus} כדי לנווט לעץ האלמנטים. ' +
'עבור לפריט הבא עם טאב (TAB) או חץ ימני. ' +
'עבור לפריט הקודם עם שיפט (SHIFT) + טאב (TAB) או חץ שמאלי. ' +
'לחץ רווח או אנטר (ENTER) כדי לבחור את האלמנט בעורך.'
}
]
},
{
name : 'פקודות',
items :
[
{
name : ' ביטול צעד אחרון',
legend : 'לחץ ${undo}'
},
{
name : ' חזרה על צעד אחרון',
legend : 'לחץ ${redo}'
},
{
name : ' הדגשה',
legend : 'לחץ ${bold}'
},
{
name : ' הטייה',
legend : 'לחץ ${italic}'
},
{
name : ' הוספת קו תחתון',
legend : 'לחץ ${underline}'
},
{
name : ' הוספת לינק',
legend : 'לחץ ${link}'
},
{
name : ' כיווץ סרגל הכלים',
legend : 'לחץ ${toolbarCollapse}'
},
{
name : ' הוראות נגישות',
legend : 'לחץ ${a11yHelp}'
}
]
}
]
}
});
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'a11yhelp', 'he',
{
accessibilityHelp :
{
title : 'הוראות נגישות',
contents : 'הוראות נגישות. לסגירה לחץ אסקייפ (ESC).',
legend :
[
{
name : 'כללי',
items :
[
{
name : 'סרגל הכלים',
legend:
'לחץ על ${toolbarFocus} כדי לנווט לסרגל הכלים. ' +
'עבור לכפתור הבא עם מקש הטאב (TAB) או חץ שמאלי. ' +
'עבור לכפתור הקודם עם מקש השיפט (SHIFT) + טאב (TAB) או חץ ימני. ' +
'לחץ רווח או אנטר (ENTER) כדי להפעיל את הכפתור הנבחר.'
},
{
name : 'דיאלוגים (חלונות תשאול)',
legend :
'בתוך דיאלוג, לחץ טאב (TAB) כדי לנווט לשדה הבא, לחץ שיפט (SHIFT) + טאב (TAB) כדי לנווט לשדה הקודם, לחץ אנטר (ENTER) כדי לשלוח את הדיאלוג, לחץ אסקייפ (ESC) כדי לבטל. ' +
'בתוך דיאלוגים בעלי מספר טאבים (לשוניות), לחץ אלט (ALT) + F10 כדי לנווט לשורת הטאבים. ' +
'נווט לטאב הבא עם טאב (TAB) או חץ שמאלי. ' +
'עבור לטאב הקודם עם שיפט (SHIFT) + טאב (TAB) או חץ שמאלי. ' +
'לחץ רווח או אנטר (ENTER) כדי להיכנס לטאב.'
},
{
name : 'תפריט ההקשר (Context Menu)',
legend :
'לחץ ${contextMenu} או APPLICATION KEYכדי לפתוח את תפריט ההקשר. ' +
'עבור לאפשרות הבאה עם טאב (TAB) או חץ למטה. ' +
'עבור לאפשרות הקודמת עם שיפט (SHIFT) + טאב (TAB) או חץ למעלה. ' +
'לחץ רווח או אנטר (ENTER) כדי לבחור את האפשרות. ' +
'פתח את תת התפריט (Sub-menu) של האפשרות הנוכחית עם רווח או אנטר (ENTER) או חץ שמאלי. ' +
'חזור לתפריט האב עם אסקייפ (ESC) או חץ שמאלי. ' +
'סגור את תפריט ההקשר עם אסקייפ (ESC).'
},
{
name : 'תפריטים צפים (List boxes)',
legend :
'בתוך תפריט צף, עבור לפריט הבא עם טאב (TAB) או חץ למטה. ' +
'עבור לתפריט הקודם עם שיפט (SHIFT) + טאב (TAB) or חץ עליון. ' +
'Press SPACE or ENTER to select the list option. ' +
'Press ESC to close the list-box.'
},
{
name : 'עץ אלמנטים (Elements Path)',
legend :
'לחץ ${elementsPathFocus} כדי לנווט לעץ האלמנטים. ' +
'עבור לפריט הבא עם טאב (TAB) או חץ ימני. ' +
'עבור לפריט הקודם עם שיפט (SHIFT) + טאב (TAB) או חץ שמאלי. ' +
'לחץ רווח או אנטר (ENTER) כדי לבחור את האלמנט בעורך.'
}
]
},
{
name : 'פקודות',
items :
[
{
name : ' ביטול צעד אחרון',
legend : 'לחץ ${undo}'
},
{
name : ' חזרה על צעד אחרון',
legend : 'לחץ ${redo}'
},
{
name : ' הדגשה',
legend : 'לחץ ${bold}'
},
{
name : ' הטייה',
legend : 'לחץ ${italic}'
},
{
name : ' הוספת קו תחתון',
legend : 'לחץ ${underline}'
},
{
name : ' הוספת לינק',
legend : 'לחץ ${link}'
},
{
name : ' כיווץ סרגל הכלים',
legend : 'לחץ ${toolbarCollapse}'
},
{
name : ' הוראות נגישות',
legend : 'לחץ ${a11yHelp}'
}
]
}
]
}
});
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.dialog.add( 'a11yHelp', function( editor )
{
var lang = editor.lang.accessibilityHelp,
id = CKEDITOR.tools.getNextId();
// CharCode <-> KeyChar.
var keyMap =
{
8 : "BACKSPACE",
9 : "TAB" ,
13 : "ENTER" ,
16 : "SHIFT" ,
17 : "CTRL" ,
18 : "ALT" ,
19 : "PAUSE" ,
20 : "CAPSLOCK" ,
27 : "ESCAPE" ,
33 : "PAGE UP" ,
34 : "PAGE DOWN" ,
35 : "END" ,
36 : "HOME" ,
37 : "LEFT ARROW" ,
38 : "UP ARROW" ,
39 : "RIGHT ARROW" ,
40 : "DOWN ARROW" ,
45 : "INSERT" ,
46 : "DELETE" ,
91 : "LEFT WINDOW KEY" ,
92 : "RIGHT WINDOW KEY" ,
93 : "SELECT KEY" ,
96 : "NUMPAD 0" ,
97 : "NUMPAD 1" ,
98 : "NUMPAD 2" ,
99 : "NUMPAD 3" ,
100 : "NUMPAD 4" ,
101 : "NUMPAD 5" ,
102 : "NUMPAD 6" ,
103 : "NUMPAD 7" ,
104 : "NUMPAD 8" ,
105 : "NUMPAD 9" ,
106 : "MULTIPLY" ,
107 : "ADD" ,
109 : "SUBTRACT" ,
110 : "DECIMAL POINT" ,
111 : "DIVIDE" ,
112 : "F1" ,
113 : "F2" ,
114 : "F3" ,
115 : "F4" ,
116 : "F5" ,
117 : "F6" ,
118 : "F7" ,
119 : "F8" ,
120 : "F9" ,
121 : "F10" ,
122 : "F11" ,
123 : "F12" ,
144 : "NUM LOCK" ,
145 : "SCROLL LOCK" ,
186 : "SEMI-COLON" ,
187 : "EQUAL SIGN" ,
188 : "COMMA" ,
189 : "DASH" ,
190 : "PERIOD" ,
191 : "FORWARD SLASH" ,
192 : "GRAVE ACCENT" ,
219 : "OPEN BRACKET" ,
220 : "BACK SLASH" ,
221 : "CLOSE BRAKET" ,
222 : "SINGLE QUOTE"
};
// Modifier keys override.
keyMap[ CKEDITOR.ALT ] = 'ALT';
keyMap[ CKEDITOR.SHIFT ] = 'SHIFT';
keyMap[ CKEDITOR.CTRL ] = 'CTRL';
// Sort in desc.
var modifiers = [ CKEDITOR.ALT, CKEDITOR.SHIFT, CKEDITOR.CTRL ];
function representKeyStroke( keystroke )
{
var quotient,
modifier,
presentation = [];
for ( var i = 0; i < modifiers.length; i++ )
{
modifier = modifiers[ i ];
quotient = keystroke / modifiers[ i ];
if ( quotient > 1 && quotient <= 2 )
{
keystroke -= modifier;
presentation.push( keyMap[ modifier ] );
}
}
presentation.push( keyMap[ keystroke ]
|| String.fromCharCode( keystroke ) );
return presentation.join( '+' );
}
var variablesPattern = /\$\{(.*?)\}/g;
function replaceVariables( match, name )
{
var keystrokes = editor.config.keystrokes,
definition,
length = keystrokes.length;
for ( var i = 0; i < length; i++ )
{
definition = keystrokes[ i ];
if ( definition[ 1 ] == name )
break;
}
return representKeyStroke( definition[ 0 ] );
}
// Create the help list directly from lang file entries.
function buildHelpContents()
{
var pageTpl = '<div class="cke_accessibility_legend" role="document" aria-labelledby="' + id + '_arialbl" tabIndex="-1">%1</div>' +
'<span id="' + id + '_arialbl" class="cke_voice_label">' + lang.contents + ' </span>',
sectionTpl = '<h1>%1</h1><dl>%2</dl>',
itemTpl = '<dt>%1</dt><dd>%2</dd>';
var pageHtml = [],
sections = lang.legend,
sectionLength = sections.length;
for ( var i = 0; i < sectionLength; i++ )
{
var section = sections[ i ],
sectionHtml = [],
items = section.items,
itemsLength = items.length;
for ( var j = 0; j < itemsLength; j++ )
{
var item = items[ j ],
itemHtml;
itemHtml = itemTpl.replace( '%1', item.name ).
replace( '%2', item.legend.replace( variablesPattern, replaceVariables ) );
sectionHtml.push( itemHtml );
}
pageHtml.push( sectionTpl.replace( '%1', section.name ).replace( '%2', sectionHtml.join( '' ) ) );
}
return pageTpl.replace( '%1', pageHtml.join( '' ) );
}
return {
title : lang.title,
minWidth : 600,
minHeight : 400,
contents : [
{
id : 'info',
label : editor.lang.common.generalTab,
expand : true,
elements :
[
{
type : 'html',
id : 'legends',
focus : function() {},
html : buildHelpContents() +
'<style type="text/css">' +
'.cke_accessibility_legend' +
'{' +
'width:600px;' +
'height:400px;' +
'padding-right:5px;' +
'overflow-y:auto;' +
'overflow-x:hidden;' +
'}' +
'.cke_accessibility_legend h1' +
'{' +
'font-size: 20px;' +
'border-bottom: 1px solid #AAA;' +
'margin: 5px 0px 15px;' +
'}' +
'.cke_accessibility_legend dl' +
'{' +
'margin-left: 5px;' +
'}' +
'.cke_accessibility_legend dt' +
'{' +
'font-size: 13px;' +
'font-weight: bold;' +
'}' +
'.cke_accessibility_legend dd' +
'{' +
'white-space:normal;' +
'margin:10px' +
'}' +
'</style>'
}
]
}
],
buttons : [ CKEDITOR.dialog.cancelButton ]
};
});
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.add( 'richcombo',
{
requires : [ 'floatpanel', 'listblock', 'button' ],
beforeInit : function( editor )
{
editor.ui.addHandler( CKEDITOR.UI_RICHCOMBO, CKEDITOR.ui.richCombo.handler );
}
});
/**
* Button UI element.
* @constant
* @example
*/
CKEDITOR.UI_RICHCOMBO = 3;
CKEDITOR.ui.richCombo = CKEDITOR.tools.createClass(
{
$ : function( definition )
{
// Copy all definition properties to this object.
CKEDITOR.tools.extend( this, definition,
// Set defaults.
{
title : definition.label,
modes : { wysiwyg : 1 }
});
// We don't want the panel definition in this object.
var panelDefinition = this.panel || {};
delete this.panel;
this.id = CKEDITOR.tools.getNextNumber();
this.document = ( panelDefinition
&& panelDefinition.parent
&& panelDefinition.parent.getDocument() )
|| CKEDITOR.document;
panelDefinition.className = ( panelDefinition.className || '' ) + ' cke_rcombopanel';
panelDefinition.block =
{
multiSelect : panelDefinition.multiSelect,
attributes : panelDefinition.attributes
};
this._ =
{
panelDefinition : panelDefinition,
items : {},
state : CKEDITOR.TRISTATE_OFF
};
},
statics :
{
handler :
{
create : function( definition )
{
return new CKEDITOR.ui.richCombo( definition );
}
}
},
proto :
{
renderHtml : function( editor )
{
var output = [];
this.render( editor, output );
return output.join( '' );
},
/**
* Renders the combo.
* @param {CKEDITOR.editor} editor The editor instance which this button is
* to be used by.
* @param {Array} output The output array to which append the HTML relative
* to this button.
* @example
*/
render : function( editor, output )
{
var env = CKEDITOR.env;
var id = 'cke_' + this.id;
var clickFn = CKEDITOR.tools.addFunction( function( $element )
{
var _ = this._;
if ( _.state == CKEDITOR.TRISTATE_DISABLED )
return;
this.createPanel( editor );
if ( _.on )
{
_.panel.hide();
return;
}
this.commit();
var value = this.getValue();
if ( value )
_.list.mark( value );
else
_.list.unmarkAll();
_.panel.showBlock( this.id, new CKEDITOR.dom.element( $element ), 4 );
},
this );
var instance = {
id : id,
combo : this,
focus : function()
{
var element = CKEDITOR.document.getById( id ).getChild( 1 );
element.focus();
},
clickFn : clickFn
};
editor.on( 'mode', function()
{
this.setState( this.modes[ editor.mode ] ? CKEDITOR.TRISTATE_OFF : CKEDITOR.TRISTATE_DISABLED );
},
this );
var keyDownFn = CKEDITOR.tools.addFunction( function( ev, element )
{
ev = new CKEDITOR.dom.event( ev );
var keystroke = ev.getKeystroke();
switch ( keystroke )
{
case 13 : // ENTER
case 32 : // SPACE
case 40 : // ARROW-DOWN
// Show panel
CKEDITOR.tools.callFunction( clickFn, element );
break;
default :
// Delegate the default behavior to toolbar button key handling.
instance.onkey( instance, keystroke );
}
// Avoid subsequent focus grab on editor document.
ev.preventDefault();
});
// For clean up
instance.keyDownFn = keyDownFn;
output.push(
'<span class="cke_rcombo">',
'<span id=', id );
if ( this.className )
output.push( ' class="', this.className, ' cke_off"');
output.push(
'>',
'<span id="' + id+ '_label" class=cke_label>', this.label, '</span>',
'<a hidefocus=true title="', this.title, '" tabindex="-1"',
env.gecko && env.version >= 10900 && !env.hc ? '' : ' href="javascript:void(\'' + this.label + '\')"',
' role="button" aria-labelledby="', id , '_label" aria-describedby="', id, '_text" aria-haspopup="true"' );
// Some browsers don't cancel key events in the keydown but in the
// keypress.
// TODO: Check if really needed for Gecko+Mac.
if ( CKEDITOR.env.opera || ( CKEDITOR.env.gecko && CKEDITOR.env.mac ) )
{
output.push(
' onkeypress="return false;"' );
}
// With Firefox, we need to force it to redraw, otherwise it
// will remain in the focus state.
if ( CKEDITOR.env.gecko )
{
output.push(
' onblur="this.style.cssText = this.style.cssText;"' );
}
output.push(
' onkeydown="CKEDITOR.tools.callFunction( ', keyDownFn, ', event, this );"' +
' onclick="CKEDITOR.tools.callFunction(', clickFn, ', this); return false;">' +
'<span>' +
'<span id="' + id + '_text" class="cke_text cke_inline_label">' + this.label + '</span>' +
'</span>' +
'<span class=cke_openbutton>' + ( CKEDITOR.env.hc ? '<span>▼</span>' : CKEDITOR.env.air ? ' ' : '' ) + '</span>' + // BLACK DOWN-POINTING TRIANGLE
'</a>' +
'</span>' +
'</span>' );
if ( this.onRender )
this.onRender();
return instance;
},
createPanel : function( editor )
{
if ( this._.panel )
return;
var panelDefinition = this._.panelDefinition,
panelBlockDefinition = this._.panelDefinition.block,
panelParentElement = panelDefinition.parent || CKEDITOR.document.getBody(),
panel = new CKEDITOR.ui.floatPanel( editor, panelParentElement, panelDefinition ),
list = panel.addListBlock( this.id, panelBlockDefinition ),
me = this;
panel.onShow = function()
{
if ( me.className )
this.element.getFirst().addClass( me.className + '_panel' );
me.setState( CKEDITOR.TRISTATE_ON );
list.focus( !me.multiSelect && me.getValue() );
me._.on = 1;
if ( me.onOpen )
me.onOpen();
};
panel.onHide = function( preventOnClose )
{
if ( me.className )
this.element.getFirst().removeClass( me.className + '_panel' );
me.setState( me.modes && me.modes[ editor.mode ] ? CKEDITOR.TRISTATE_OFF : CKEDITOR.TRISTATE_DISABLED );
me._.on = 0;
if ( !preventOnClose && me.onClose )
me.onClose();
};
panel.onEscape = function()
{
panel.hide();
me.document.getById( 'cke_' + me.id ).getFirst().getNext().focus();
};
list.onClick = function( value, marked )
{
// Move the focus to the main windows, otherwise it will stay
// into the floating panel, even if invisible, and Safari and
// Opera will go a bit crazy.
me.document.getWindow().focus();
if ( me.onClick )
me.onClick.call( me, value, marked );
if ( marked )
me.setValue( value, me._.items[ value ] );
else
me.setValue( '' );
panel.hide();
};
this._.panel = panel;
this._.list = list;
panel.getBlock( this.id ).onHide = function()
{
me._.on = 0;
me.setState( CKEDITOR.TRISTATE_OFF );
};
if ( this.init )
this.init();
},
setValue : function( value, text )
{
this._.value = value;
var textElement = this.document.getById( 'cke_' + this.id + '_text' );
if ( !( value || text ) )
{
text = this.label;
textElement.addClass( 'cke_inline_label' );
}
else
textElement.removeClass( 'cke_inline_label' );
textElement.setHtml( typeof text != 'undefined' ? text : value );
},
getValue : function()
{
return this._.value || '';
},
unmarkAll : function()
{
this._.list.unmarkAll();
},
mark : function( value )
{
this._.list.mark( value );
},
hideItem : function( value )
{
this._.list.hideItem( value );
},
hideGroup : function( groupTitle )
{
this._.list.hideGroup( groupTitle );
},
showAll : function()
{
this._.list.showAll();
},
add : function( value, html, text )
{
this._.items[ value ] = text || value;
this._.list.add( value, html, text );
},
startGroup : function( title )
{
this._.list.startGroup( title );
},
commit : function()
{
if ( !this._.committed )
{
this._.list.commit();
this._.committed = 1;
CKEDITOR.ui.fire( 'ready', this );
}
this._.committed = 1;
},
setState : function( state )
{
if ( this._.state == state )
return;
this.document.getById( 'cke_' + this.id ).setState( state );
this._.state = state;
}
}
});
CKEDITOR.ui.prototype.addRichCombo = function( name, definition )
{
this.add( name, CKEDITOR.UI_RICHCOMBO, definition );
};
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @file Print Plugin
*/
CKEDITOR.plugins.add( 'print',
{
init : function( editor )
{
var pluginName = 'print';
// Register the command.
var command = editor.addCommand( pluginName, CKEDITOR.plugins.print );
// Register the toolbar button.
editor.ui.addButton( 'Print',
{
label : editor.lang.print,
command : pluginName
});
}
} );
CKEDITOR.plugins.print =
{
exec : function( editor )
{
if ( CKEDITOR.env.opera )
return;
else if ( CKEDITOR.env.gecko )
editor.window.$.print();
else
editor.document.$.execCommand( "Print" );
},
canUndo : false,
modes : { wysiwyg : !( CKEDITOR.env.opera ) } // It is imposible to print the inner document in Opera.
};
| JavaScript |
( function()
{
CKEDITOR.plugins.colordialog =
{
init : function( editor )
{
editor.addCommand( 'colordialog', new CKEDITOR.dialogCommand( 'colordialog' ) );
CKEDITOR.dialog.add( 'colordialog', this.path + 'dialogs/colordialog.js' );
}
};
CKEDITOR.plugins.add( 'colordialog', CKEDITOR.plugins.colordialog );
} )();
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.dialog.add( 'colordialog', function( editor )
{
// Define some shorthands.
var $el = CKEDITOR.dom.element,
$doc = CKEDITOR.document,
$tools = CKEDITOR.tools,
lang = editor.lang.colordialog;
// Reference the dialog.
var dialog;
var spacer =
{
type : 'html',
html : ' '
};
function clearSelected()
{
$doc.getById( selHiColorId ).removeStyle( 'background-color' );
dialog.getContentElement( 'picker', 'selectedColor' ).setValue( '' );
}
function updateSelected( evt )
{
if ( ! ( evt instanceof CKEDITOR.dom.event ) )
evt = new CKEDITOR.dom.event( evt );
var target = evt.getTarget(),
color;
if ( target.getName() == 'a' && ( color = target.getChild( 0 ).getHtml() ) )
dialog.getContentElement( 'picker', 'selectedColor' ).setValue( color );
}
function updateHighlight( event )
{
if ( ! ( event instanceof CKEDITOR.dom.event ) )
event = event.data;
var target = event.getTarget(),
color;
if ( target.getName() == 'a' && ( color = target.getChild( 0 ).getHtml() ) )
{
$doc.getById( hicolorId ).setStyle( 'background-color', color );
$doc.getById( hicolorTextId ).setHtml( color );
}
}
function clearHighlight()
{
$doc.getById( hicolorId ).removeStyle( 'background-color' );
$doc.getById( hicolorTextId ).setHtml( ' ' );
}
var onMouseout = $tools.addFunction( clearHighlight ),
onClick = updateSelected,
onClickHandler = CKEDITOR.tools.addFunction( onClick ),
onFocus = updateHighlight,
onBlur = clearHighlight;
var onKeydownHandler = CKEDITOR.tools.addFunction( function( ev )
{
ev = new CKEDITOR.dom.event( ev );
var element = ev.getTarget();
var relative, nodeToMove;
var keystroke = ev.getKeystroke(),
rtl = editor.lang.dir == 'rtl';
switch ( keystroke )
{
// UP-ARROW
case 38 :
// relative is TR
if ( ( relative = element.getParent().getParent().getPrevious() ) )
{
nodeToMove = relative.getChild( [element.getParent().getIndex(), 0] );
nodeToMove.focus();
onBlur( ev, element );
onFocus( ev, nodeToMove );
}
ev.preventDefault();
break;
// DOWN-ARROW
case 40 :
// relative is TR
if ( ( relative = element.getParent().getParent().getNext() ) )
{
nodeToMove = relative.getChild( [ element.getParent().getIndex(), 0 ] );
if ( nodeToMove && nodeToMove.type == 1 )
{
nodeToMove.focus();
onBlur( ev, element );
onFocus( ev, nodeToMove );
}
}
ev.preventDefault();
break;
// SPACE
// ENTER is already handled as onClick
case 32 :
onClick( ev );
ev.preventDefault();
break;
// RIGHT-ARROW
case rtl ? 37 : 39 :
// relative is TD
if ( ( relative = element.getParent().getNext() ) )
{
nodeToMove = relative.getChild( 0 );
if ( nodeToMove.type == 1 )
{
nodeToMove.focus();
onBlur( ev, element );
onFocus( ev, nodeToMove );
ev.preventDefault( true );
}
else
onBlur( null, element );
}
// relative is TR
else if ( ( relative = element.getParent().getParent().getNext() ) )
{
nodeToMove = relative.getChild( [ 0, 0 ] );
if ( nodeToMove && nodeToMove.type == 1 )
{
nodeToMove.focus();
onBlur( ev, element );
onFocus( ev, nodeToMove );
ev.preventDefault( true );
}
else
onBlur( null, element );
}
break;
// LEFT-ARROW
case rtl ? 39 : 37 :
// relative is TD
if ( ( relative = element.getParent().getPrevious() ) )
{
nodeToMove = relative.getChild( 0 );
nodeToMove.focus();
onBlur( ev, element );
onFocus( ev, nodeToMove );
ev.preventDefault( true );
}
// relative is TR
else if ( ( relative = element.getParent().getParent().getPrevious() ) )
{
nodeToMove = relative.getLast().getChild( 0 );
nodeToMove.focus();
onBlur( ev, element );
onFocus( ev, nodeToMove );
ev.preventDefault( true );
}
else
onBlur( null, element );
break;
default :
// Do not stop not handled events.
return;
}
});
function createColorTable()
{
// Create the base colors array.
var aColors = [ '00', '33', '66', '99', 'cc', 'ff' ];
// This function combines two ranges of three values from the color array into a row.
function appendColorRow( rangeA, rangeB )
{
for ( var i = rangeA ; i < rangeA + 3 ; i++ )
{
var row = table.$.insertRow( -1 );
for ( var j = rangeB ; j < rangeB + 3 ; j++ )
{
for ( var n = 0 ; n < 6 ; n++ )
{
appendColorCell( row, '#' + aColors[j] + aColors[n] + aColors[i] );
}
}
}
}
// This function create a single color cell in the color table.
function appendColorCell( targetRow, color )
{
var cell = new $el( targetRow.insertCell( -1 ) );
cell.setAttribute( 'class', 'ColorCell' );
cell.setStyle( 'background-color', color );
cell.setStyle( 'width', '15px' );
cell.setStyle( 'height', '15px' );
var index = cell.$.cellIndex + 1 + 18 * targetRow.rowIndex;
cell.append( CKEDITOR.dom.element.createFromHtml(
'<a href="javascript: void(0);" role="option"' +
' aria-posinset="' + index + '"' +
' aria-setsize="' + 13 * 18 + '"' +
' style="cursor: pointer;display:block;width:100%;height:100% " title="'+ CKEDITOR.tools.htmlEncode( color )+ '"' +
' onkeydown="CKEDITOR.tools.callFunction( ' + onKeydownHandler + ', event, this )"' +
' onclick="CKEDITOR.tools.callFunction(' + onClickHandler + ', event, this ); return false;"' +
' tabindex="-1"><span class="cke_voice_label">' + color + '</span> </a>', CKEDITOR.document ) );
}
appendColorRow( 0, 0 );
appendColorRow( 3, 0 );
appendColorRow( 0, 3 );
appendColorRow( 3, 3 );
// Create the last row.
var oRow = table.$.insertRow(-1) ;
// Create the gray scale colors cells.
for ( var n = 0 ; n < 6 ; n++ )
{
appendColorCell( oRow, '#' + aColors[n] + aColors[n] + aColors[n] ) ;
}
// Fill the row with black cells.
for ( var i = 0 ; i < 12 ; i++ )
{
appendColorCell( oRow, '#000000' ) ;
}
}
var table = new $el( 'table' );
createColorTable();
var html = table.getHtml();
var numbering = function( id )
{
return CKEDITOR.tools.getNextId() + '_' + id;
},
hicolorId = numbering( 'hicolor' ),
hicolorTextId = numbering( 'hicolortext' ),
selHiColorId = numbering( 'selhicolor' ),
tableLabelId = numbering( 'color_table_label' );
return {
title : lang.title,
minWidth : 360,
minHeight : 220,
onLoad : function()
{
// Update reference.
dialog = this;
},
contents : [
{
id : 'picker',
label : lang.title,
accessKey : 'I',
elements :
[
{
type : 'hbox',
padding : 0,
widths : [ '70%', '10%', '30%' ],
children :
[
{
type : 'html',
html : '<table role="listbox" aria-labelledby="' + tableLabelId + '" onmouseout="CKEDITOR.tools.callFunction( ' + onMouseout + ' );">' +
( !CKEDITOR.env.webkit ? html : '' ) +
'</table><span id="' + tableLabelId + '" class="cke_voice_label">' + lang.options +'</span>',
onLoad : function()
{
var table = CKEDITOR.document.getById( this.domId );
table.on( 'mouseover', updateHighlight );
// In WebKit, the table content must be inserted after this event call (#6150)
CKEDITOR.env.webkit && table.setHtml( html );
},
focus: function()
{
var firstColor = this.getElement().getElementsByTag( 'a' ).getItem( 0 );
firstColor.focus();
}
},
spacer,
{
type : 'vbox',
padding : 0,
widths : [ '70%', '5%', '25%' ],
children :
[
{
type : 'html',
html : '<span>' + lang.highlight +'</span>\
<div id="' + hicolorId + '" style="border: 1px solid; height: 74px; width: 74px;"></div>\
<div id="' + hicolorTextId + '"> </div><span>' + lang.selected + '</span>\
<div id="' + selHiColorId + '" style="border: 1px solid; height: 20px; width: 74px;"></div>'
},
{
type : 'text',
label : lang.selected,
labelStyle: 'display:none',
id : 'selectedColor',
style : 'width: 74px',
onChange : function()
{
// Try to update color preview with new value. If fails, then set it no none.
try
{
$doc.getById( selHiColorId ).setStyle( 'background-color', this.getValue() );
}
catch ( e )
{
clearSelected();
}
}
},
spacer,
{
type : 'button',
id : 'clear',
style : 'margin-top: 5px',
label : lang.clear,
onClick : clearSelected
}
]
}
]
}
]
}
]
};
}
);
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @file Justify commands.
*/
(function()
{
function getState( editor, path )
{
var firstBlock = path.block || path.blockLimit;
if ( !firstBlock || firstBlock.getName() == 'body' )
return CKEDITOR.TRISTATE_OFF;
return ( getAlignment( firstBlock, editor.config.useComputedState ) == this.value ) ?
CKEDITOR.TRISTATE_ON :
CKEDITOR.TRISTATE_OFF;
}
function getAlignment( element, useComputedState )
{
useComputedState = useComputedState === undefined || useComputedState;
var align;
if ( useComputedState )
align = element.getComputedStyle( 'text-align' );
else
{
while ( !element.hasAttribute || !( element.hasAttribute( 'align' ) || element.getStyle( 'text-align' ) ) )
{
var parent = element.getParent();
if ( !parent )
break;
element = parent;
}
align = element.getStyle( 'text-align' ) || element.getAttribute( 'align' ) || '';
}
align && ( align = align.replace( /-moz-|-webkit-|start|auto/i, '' ) );
!align && useComputedState && ( align = element.getComputedStyle( 'direction' ) == 'rtl' ? 'right' : 'left' );
return align;
}
function onSelectionChange( evt )
{
var command = evt.editor.getCommand( this.name );
command.state = getState.call( this, evt.editor, evt.data.path );
command.fire( 'state' );
}
function justifyCommand( editor, name, value )
{
this.name = name;
this.value = value;
var classes = editor.config.justifyClasses;
if ( classes )
{
switch ( value )
{
case 'left' :
this.cssClassName = classes[0];
break;
case 'center' :
this.cssClassName = classes[1];
break;
case 'right' :
this.cssClassName = classes[2];
break;
case 'justify' :
this.cssClassName = classes[3];
break;
}
this.cssClassRegex = new RegExp( '(?:^|\\s+)(?:' + classes.join( '|' ) + ')(?=$|\\s)' );
}
}
function onDirChanged( e )
{
var editor = e.editor;
var range = new CKEDITOR.dom.range( editor.document );
range.setStartBefore( e.data.node );
range.setEndAfter( e.data.node );
var walker = new CKEDITOR.dom.walker( range ),
node;
while ( ( node = walker.next() ) )
{
if ( node.type == CKEDITOR.NODE_ELEMENT )
{
// A child with the defined dir is to be ignored.
if ( !node.equals( e.data.node ) && node.getDirection() )
{
range.setStartAfter( node );
walker = new CKEDITOR.dom.walker( range );
continue;
}
// Switch the alignment.
var classes = editor.config.justifyClasses;
if ( classes )
{
// The left align class.
if ( node.hasClass( classes[ 0 ] ) )
{
node.removeClass( classes[ 0 ] );
node.addClass( classes[ 2 ] );
}
// The right align class.
else if ( node.hasClass( classes[ 2 ] ) )
{
node.removeClass( classes[ 2 ] );
node.addClass( classes[ 0 ] );
}
}
// Always switch CSS margins.
var style = 'text-align';
var align = node.getStyle( style );
if ( align == 'left' )
node.setStyle( style, 'right' );
else if ( align == 'right' )
node.setStyle( style, 'left' );
}
}
}
justifyCommand.prototype = {
exec : function( editor )
{
var selection = editor.getSelection(),
enterMode = editor.config.enterMode;
if ( !selection )
return;
var bookmarks = selection.createBookmarks(),
ranges = selection.getRanges( true );
var cssClassName = this.cssClassName,
iterator,
block;
var useComputedState = editor.config.useComputedState;
useComputedState = useComputedState === undefined || useComputedState;
for ( var i = ranges.length - 1 ; i >= 0 ; i-- )
{
iterator = ranges[ i ].createIterator();
iterator.enlargeBr = enterMode != CKEDITOR.ENTER_BR;
while ( ( block = iterator.getNextParagraph() ) )
{
block.removeAttribute( 'align' );
block.removeStyle( 'text-align' );
// Remove any of the alignment classes from the className.
var className = cssClassName && ( block.$.className =
CKEDITOR.tools.ltrim( block.$.className.replace( this.cssClassRegex, '' ) ) );
var apply =
( this.state == CKEDITOR.TRISTATE_OFF ) &&
( !useComputedState || ( getAlignment( block, true ) != this.value ) );
if ( cssClassName )
{
// Append the desired class name.
if ( apply )
block.addClass( cssClassName );
else if ( !className )
block.removeAttribute( 'class' );
}
else if ( apply )
block.setStyle( 'text-align', this.value );
}
}
editor.focus();
editor.forceNextSelectionCheck();
selection.selectBookmarks( bookmarks );
}
};
CKEDITOR.plugins.add( 'justify',
{
init : function( editor )
{
var left = new justifyCommand( editor, 'justifyleft', 'left' ),
center = new justifyCommand( editor, 'justifycenter', 'center' ),
right = new justifyCommand( editor, 'justifyright', 'right' ),
justify = new justifyCommand( editor, 'justifyblock', 'justify' );
editor.addCommand( 'justifyleft', left );
editor.addCommand( 'justifycenter', center );
editor.addCommand( 'justifyright', right );
editor.addCommand( 'justifyblock', justify );
editor.ui.addButton( 'JustifyLeft',
{
label : editor.lang.justify.left,
command : 'justifyleft'
} );
editor.ui.addButton( 'JustifyCenter',
{
label : editor.lang.justify.center,
command : 'justifycenter'
} );
editor.ui.addButton( 'JustifyRight',
{
label : editor.lang.justify.right,
command : 'justifyright'
} );
editor.ui.addButton( 'JustifyBlock',
{
label : editor.lang.justify.block,
command : 'justifyblock'
} );
editor.on( 'selectionChange', CKEDITOR.tools.bind( onSelectionChange, left ) );
editor.on( 'selectionChange', CKEDITOR.tools.bind( onSelectionChange, right ) );
editor.on( 'selectionChange', CKEDITOR.tools.bind( onSelectionChange, center ) );
editor.on( 'selectionChange', CKEDITOR.tools.bind( onSelectionChange, justify ) );
editor.on( 'dirChanged', onDirChanged );
},
requires : [ 'domiterator' ]
});
})();
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @name CKEDITOR.theme
* @class
*/
CKEDITOR.themes.add( 'default', (function()
{
function checkSharedSpace( editor, spaceName )
{
var container,
element;
// Try to retrieve the target element from the sharedSpaces settings.
element = editor.config.sharedSpaces;
element = element && element[ spaceName ];
element = element && CKEDITOR.document.getById( element );
// If the element is available, we'll then create the container for
// the space.
if ( element )
{
// Creates an HTML structure that reproduces the editor class hierarchy.
var html =
'<span class="cke_shared">' +
'<span class="' + editor.skinClass + ' ' + editor.id + ' cke_editor_' + editor.name + '">' +
'<span class="' + CKEDITOR.env.cssClass + '">' +
'<span class="cke_wrapper cke_' + editor.lang.dir + '">' +
'<span class="cke_editor">' +
'<div class="cke_' + spaceName + '">' +
'</div></span></span></span></span></span>';
var mainContainer = element.append( CKEDITOR.dom.element.createFromHtml( html, element.getDocument() ) );
// Only the first container starts visible. Others get hidden.
if ( element.getCustomData( 'cke_hasshared' ) )
mainContainer.hide();
else
element.setCustomData( 'cke_hasshared', 1 );
// Get the deeper inner <div>.
container = mainContainer.getChild( [0,0,0,0] );
// Save a reference to the shared space container.
!editor.sharedSpaces && ( editor.sharedSpaces = {} );
editor.sharedSpaces[ spaceName ] = container;
// When the editor gets focus, we show the space container, hiding others.
editor.on( 'focus', function()
{
for ( var i = 0, sibling, children = element.getChildren() ; ( sibling = children.getItem( i ) ) ; i++ )
{
if ( sibling.type == CKEDITOR.NODE_ELEMENT
&& !sibling.equals( mainContainer )
&& sibling.hasClass( 'cke_shared' ) )
{
sibling.hide();
}
}
mainContainer.show();
});
editor.on( 'destroy', function()
{
mainContainer.remove();
});
}
return container;
}
return /** @lends CKEDITOR.theme */ {
build : function( editor, themePath )
{
var name = editor.name,
element = editor.element,
elementMode = editor.elementMode;
if ( !element || elementMode == CKEDITOR.ELEMENT_MODE_NONE )
return;
if ( elementMode == CKEDITOR.ELEMENT_MODE_REPLACE )
element.hide();
// Get the HTML for the predefined spaces.
var topHtml = editor.fire( 'themeSpace', { space : 'top', html : '' } ).html;
var contentsHtml = editor.fire( 'themeSpace', { space : 'contents', html : '' } ).html;
var bottomHtml = editor.fireOnce( 'themeSpace', { space : 'bottom', html : '' } ).html;
var height = contentsHtml && editor.config.height;
var tabIndex = editor.config.tabIndex || editor.element.getAttribute( 'tabindex' ) || 0;
// The editor height is considered only if the contents space got filled.
if ( !contentsHtml )
height = 'auto';
else if ( !isNaN( height ) )
height += 'px';
var style = '';
var width = editor.config.width;
if ( width )
{
if ( !isNaN( width ) )
width += 'px';
style += "width: " + width + ";";
}
var sharedTop = topHtml && checkSharedSpace( editor, 'top' ),
sharedBottoms = checkSharedSpace( editor, 'bottom' );
sharedTop && ( sharedTop.setHtml( topHtml ) , topHtml = '' );
sharedBottoms && ( sharedBottoms.setHtml( bottomHtml ), bottomHtml = '' );
var container = CKEDITOR.dom.element.createFromHtml( [
'<span' +
' id="cke_', name, '"' +
' class="', editor.skinClass, ' ', editor.id, ' cke_editor_', name, '"' +
' dir="', editor.lang.dir, '"' +
' title="', ( CKEDITOR.env.gecko ? ' ' : '' ), '"' +
' lang="', editor.langCode, '"' +
( CKEDITOR.env.webkit? ' tabindex="' + tabIndex + '"' : '' ) +
' role="application"' +
' aria-labelledby="cke_', name, '_arialbl"' +
( style ? ' style="' + style + '"' : '' ) +
'>' +
'<span id="cke_', name, '_arialbl" class="cke_voice_label">' + editor.lang.editor + '</span>' +
'<span class="' , CKEDITOR.env.cssClass, '" role="presentation">' +
'<span class="cke_wrapper cke_', editor.lang.dir, '" role="presentation">' +
'<table class="cke_editor" border="0" cellspacing="0" cellpadding="0" role="presentation"><tbody>' +
'<tr', topHtml ? '' : ' style="display:none"', ' role="presentation"><td id="cke_top_' , name, '" class="cke_top" role="presentation">' , topHtml , '</td></tr>' +
'<tr', contentsHtml ? '' : ' style="display:none"', ' role="presentation"><td id="cke_contents_', name, '" class="cke_contents" style="height:', height, '" role="presentation">', contentsHtml, '</td></tr>' +
'<tr', bottomHtml ? '' : ' style="display:none"', ' role="presentation"><td id="cke_bottom_' , name, '" class="cke_bottom" role="presentation">' , bottomHtml , '</td></tr>' +
'</tbody></table>' +
//Hide the container when loading skins, later restored by skin css.
'<style>.', editor.skinClass, '{visibility:hidden;}</style>' +
'</span>' +
'</span>' +
'</span>' ].join( '' ) );
container.getChild( [1, 0, 0, 0, 0] ).unselectable();
container.getChild( [1, 0, 0, 0, 2] ).unselectable();
if ( elementMode == CKEDITOR.ELEMENT_MODE_REPLACE )
container.insertAfter( element );
else
element.append( container );
/**
* The DOM element that holds the main editor interface.
* @name CKEDITOR.editor.prototype.container
* @type CKEDITOR.dom.element
* @example
* var editor = CKEDITOR.instances.editor1;
* alert( <b>editor.container</b>.getName() ); "span"
*/
editor.container = container;
// Disable browser context menu for editor's chrome.
container.disableContextMenu();
editor.fireOnce( 'themeLoaded' );
editor.fireOnce( 'uiReady' );
},
buildDialog : function( editor )
{
var baseIdNumber = CKEDITOR.tools.getNextNumber();
var element = CKEDITOR.dom.element.createFromHtml( [
'<div class="', editor.id, '_dialog cke_editor_', editor.name.replace('.', '\\.'), '_dialog cke_skin_', editor.skinName,
'" dir="', editor.lang.dir, '"' +
' lang="', editor.langCode, '"' +
' role="dialog"' +
' aria-labelledby="%title#"' +
'>' +
'<table class="cke_dialog', ' ' + CKEDITOR.env.cssClass,
' cke_', editor.lang.dir, '" style="position:absolute" role="presentation">' +
'<tr><td role="presentation">' +
'<div class="%body" role="presentation">' +
'<div id="%title#" class="%title" role="presentation"></div>' +
'<a id="%close_button#" class="%close_button" href="javascript:void(0)" title="' + editor.lang.common.close+'" role="button"><span class="cke_label">X</span></a>' +
'<div id="%tabs#" class="%tabs" role="tablist"></div>' +
'<table class="%contents" role="presentation">' +
'<tr>' +
'<td id="%contents#" class="%contents" role="presentation"></td>' +
'</tr>' +
'<tr>' +
'<td id="%footer#" class="%footer" role="presentation"></td>' +
'</tr>' +
'</table>' +
'</div>' +
'<div id="%tl#" class="%tl"></div>' +
'<div id="%tc#" class="%tc"></div>' +
'<div id="%tr#" class="%tr"></div>' +
'<div id="%ml#" class="%ml"></div>' +
'<div id="%mr#" class="%mr"></div>' +
'<div id="%bl#" class="%bl"></div>' +
'<div id="%bc#" class="%bc"></div>' +
'<div id="%br#" class="%br"></div>' +
'</td></tr>' +
'</table>',
//Hide the container when loading skins, later restored by skin css.
( CKEDITOR.env.ie ? '' : '<style>.cke_dialog{visibility:hidden;}</style>' ),
'</div>'
].join( '' )
.replace( /#/g, '_' + baseIdNumber )
.replace( /%/g, 'cke_dialog_' ) );
var body = element.getChild( [ 0, 0, 0, 0, 0 ] ),
title = body.getChild( 0 ),
close = body.getChild( 1 );
// Make the Title and Close Button unselectable.
title.unselectable();
close.unselectable();
return {
element : element,
parts :
{
dialog : element.getChild( 0 ),
title : title,
close : close,
tabs : body.getChild( 2 ),
contents : body.getChild( [ 3, 0, 0, 0 ] ),
footer : body.getChild( [ 3, 0, 1, 0 ] )
}
};
},
destroy : function( editor )
{
var container = editor.container;
container.clearCustomData();
editor.element.clearCustomData();
if ( container )
container.remove();
if ( editor.elementMode == CKEDITOR.ELEMENT_MODE_REPLACE )
editor.element.show();
delete editor.element;
}
};
})() );
/**
* Returns the DOM element that represents a theme space. The default theme defines
* three spaces, namely "top", "contents" and "bottom", representing the main
* blocks that compose the editor interface.
* @param {String} spaceName The space name.
* @returns {CKEDITOR.dom.element} The element that represents the space.
* @example
* // Hide the bottom space in the UI.
* var bottom = editor.getThemeSpace( 'bottom' );
* bottom.setStyle( 'display', 'none' );
*/
CKEDITOR.editor.prototype.getThemeSpace = function( spaceName )
{
var spacePrefix = 'cke_' + spaceName;
var space = this._[ spacePrefix ] ||
( this._[ spacePrefix ] = CKEDITOR.document.getById( spacePrefix + '_' + this.name ) );
return space;
};
/**
* Resizes the editor interface.
* @param {Number|String} width The new width. It can be an pixels integer or a
* CSS size value.
* @param {Number|String} height The new height. It can be an pixels integer or
* a CSS size value.
* @param {Boolean} [isContentHeight] Indicates that the provided height is to
* be applied to the editor contents space, not to the entire editor
* interface. Defaults to false.
* @param {Boolean} [resizeInner] Indicates that the first inner interface
* element must receive the size, not the outer element. The default theme
* defines the interface inside a pair of span elements
* (<span><span>...</span></span>). By default the
* first span element receives the sizes. If this parameter is set to
* true, the second span is sized instead.
* @example
* editor.resize( 900, 300 );
* @example
* editor.resize( '100%', 450, true );
*/
CKEDITOR.editor.prototype.resize = function( width, height, isContentHeight, resizeInner )
{
var container = this.container,
contents = CKEDITOR.document.getById( 'cke_contents_' + this.name ),
outer = resizeInner ? container.getChild( 1 ) : container;
// Resize the width first.
// WEBKIT BUG: Webkit requires that we put the editor off from display when we
// resize it. If we don't, the browser crashes!
CKEDITOR.env.webkit && outer.setStyle( 'display', 'none' );
// Set as border box width. (#5353)
outer.setSize( 'width', width, true );
if ( CKEDITOR.env.webkit )
{
outer.$.offsetWidth;
outer.setStyle( 'display', '' );
}
// Get the height delta between the outer table and the content area.
// If we're setting the content area's height, then we don't need the delta.
var delta = isContentHeight ? 0 : ( outer.$.offsetHeight || 0 ) - ( contents.$.clientHeight || 0 );
contents.setStyle( 'height', Math.max( height - delta, 0 ) + 'px' );
// Emit a resize event.
this.fire( 'resize' );
};
/**
* Gets the element that can be freely used to check the editor size. This method
* is mainly used by the resize plugin, which adds a UI handle that can be used
* to resize the editor.
* @returns {CKEDITOR.dom.element} The resizable element.
* @example
*/
CKEDITOR.editor.prototype.getResizable = function()
{
return this.container.getChild( 1 );
};
/**
* Makes it possible to place some of the editor UI blocks, like the toolbar
* and the elements path, into any element in the page.
* The elements used to hold the UI blocks can be shared among several editor
* instances. In that case, only the blocks of the active editor instance will
* display.
* @name CKEDITOR.config.sharedSpaces
* @type Object
* @default undefined
* @example
* // Place the toolbar inside the element with ID "someElementId" and the
* // elements path into the element with ID "anotherId".
* config.sharedSpaces =
* {
* top : 'someElementId',
* bottom : 'anotherId'
* };
* @example
* // Place the toolbar inside the element with ID "someElementId". The
* // elements path will remain attached to the editor UI.
* config.sharedSpaces =
* {
* top : 'someElementId'
* };
*/
/**
* Fired after the editor instance is resized through
* the {@link CKEDITOR.editor.prototype.resize} method.
* @name CKEDITOR#resize
* @event
*/
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
// Compressed version of core/ckeditor_base.js. See original for instructions.
/*jsl:ignore*/
if(!window.CKEDITOR)window.CKEDITOR=(function(){var a={timestamp:'',version:'3.5',revision:'6230',_:{},status:'unloaded',basePath:(function(){var d=window.CKEDITOR_BASEPATH||'';if(!d){var e=document.getElementsByTagName('script');for(var f=0;f<e.length;f++){var g=e[f].src.match(/(^|.*[\\\/])ckeditor(?:_basic)?(?:_source)?.js(?:\?.*)?$/i);if(g){d=g[1];break;}}}if(d.indexOf(':/')==-1)if(d.indexOf('/')===0)d=location.href.match(/^.*?:\/\/[^\/]*/)[0]+d;else d=location.href.match(/^[^\?]*\/(?:)/)[0]+d;return d;})(),getUrl:function(d){if(d.indexOf(':/')==-1&&d.indexOf('/')!==0)d=this.basePath+d;if(this.timestamp&&d.charAt(d.length-1)!='/')d+=(d.indexOf('?')>=0?'&':'?')+('t=')+this.timestamp;return d;}},b=window.CKEDITOR_GETURL;if(b){var c=a.getUrl;a.getUrl=function(d){return b.call(a,d)||c.call(a,d);};}return a;})();
/*jsl:end*/
// Uncomment the following line to have a new timestamp generated for each
// request, having clear cache load of the editor code.
// CKEDITOR.timestamp = ( new Date() ).valueOf();
if ( CKEDITOR.loader )
CKEDITOR.loader.load( 'core/ckeditor' );
else
{
// Set the script name to be loaded by the loader.
CKEDITOR._autoLoad = 'core/ckeditor';
// Include the loader script.
document.write(
'<script type="text/javascript" src="' + CKEDITOR.getUrl( '_source/core/loader.js' ) + '"></script>' );
}
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.editorConfig = function( config )
{
// Define changes to default configuration here. For example:
// config.language = 'fr';
// config.uiColor = '#AADC6E';
};
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','en',{placeholder:{title:'Placeholder Properties',toolbar:'Create Placeholder',text:'Placeholder Text',edit:'Edit Placeholder',textMissing:'The placeholder must contain text.'}});
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','en',{uicolor:{title:'UI Color Picker',preview:'Live preview',config:'Paste this string into your config.js file',predefined:'Predefined color sets'}});
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','he',{uicolor:{title:'בחירת צבע ממשק משתמש',preview:'תצוגה מקדימה',config:'הדבק את הטקסט הבא לתוך הקובץ config.js',predefined:'קבוצות צבעים מוגדרות מראש'}});
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
// Compressed version of core/ckeditor_base.js. See original for instructions.
/*jsl:ignore*/
if(!window.CKEDITOR)window.CKEDITOR=(function(){var a={timestamp:'',version:'3.5',revision:'6230',_:{},status:'unloaded',basePath:(function(){var d=window.CKEDITOR_BASEPATH||'';if(!d){var e=document.getElementsByTagName('script');for(var f=0;f<e.length;f++){var g=e[f].src.match(/(^|.*[\\\/])ckeditor(?:_basic)?(?:_source)?.js(?:\?.*)?$/i);if(g){d=g[1];break;}}}if(d.indexOf(':/')==-1)if(d.indexOf('/')===0)d=location.href.match(/^.*?:\/\/[^\/]*/)[0]+d;else d=location.href.match(/^[^\?]*\/(?:)/)[0]+d;return d;})(),getUrl:function(d){if(d.indexOf(':/')==-1&&d.indexOf('/')!==0)d=this.basePath+d;if(this.timestamp&&d.charAt(d.length-1)!='/')d+=(d.indexOf('?')>=0?'&':'?')+('t=')+this.timestamp;return d;}},b=window.CKEDITOR_GETURL;if(b){var c=a.getUrl;a.getUrl=function(d){return b.call(a,d)||c.call(a,d);};}return a;})();
/*jsl:end*/
// Uncomment the following line to have a new timestamp generated for each
// request, having clear cache load of the editor code.
// CKEDITOR.timestamp = ( new Date() ).valueOf();
// Set the script name to be loaded by the loader.
CKEDITOR._autoLoad = 'core/ckeditor_basic';
// Include the loader script.
document.write(
'<script type="text/javascript" src="' + CKEDITOR.getUrl( '_source/core/loader.js' ) + '"></script>' );
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.dialog.add( 'myDialog', function( editor )
{
return {
title : 'My Dialog',
minWidth : 400,
minHeight : 200,
contents : [
{
id : 'tab1',
label : 'First Tab',
title : 'First Tab',
elements :
[
{
id : 'input1',
type : 'text',
label : 'Input 1'
}
]
}
]
};
} );
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
// This file is not required by CKEditor and may be safely ignored.
// It is just a helper file that displays a red message about browser compatibility
// at the top of the samples (if incompatible browser is detected).
if ( window.CKEDITOR )
{
(function()
{
var showCompatibilityMsg = function()
{
var env = CKEDITOR.env;
var html = '<p><strong>Your browser is not compatible with CKEditor.</strong>';
var browsers =
{
gecko : 'Firefox 2.0',
ie : 'Internet Explorer 6.0',
opera : 'Opera 9.5',
webkit : 'Safari 3.0'
};
var alsoBrowsers = '';
for ( var key in env )
{
if ( browsers[ key ] )
{
if ( env[key] )
html += ' CKEditor is compatible with ' + browsers[ key ] + ' or higher.';
else
alsoBrowsers += browsers[ key ] + '+, ';
}
}
alsoBrowsers = alsoBrowsers.replace( /\+,([^,]+), $/, '+ and $1' );
html += ' It is also compatible with ' + alsoBrowsers + '.';
html += '</p><p>With non compatible browsers, you should still be able to see and edit the contents (HTML) in a plain text field.</p>';
var alertsEl = document.getElementById( 'alerts' );
alertsEl && ( alertsEl.innerHTML = html );
};
var onload = function()
{
// Show a friendly compatibility message as soon as the page is loaded,
// for those browsers that are not compatible with CKEditor.
if ( !CKEDITOR.env.isCompatible )
showCompatibilityMsg();
};
// Register the onload listener.
if ( window.addEventListener )
window.addEventListener( 'load', onload, false );
else if ( window.attachEvent )
window.attachEvent( 'onload', onload );
})();
}
| JavaScript |
/**
* SWFObject v1.5: Flash Player detection and embed - http://blog.deconcept.com/swfobject/
*
* SWFObject is (c) 2007 Geoff Stearns and is released under the MIT License:
* http://www.opensource.org/licenses/mit-license.php
*
*/
if(typeof deconcept == "undefined") var deconcept = new Object();
if(typeof deconcept.util == "undefined") deconcept.util = new Object();
if(typeof deconcept.SWFObjectUtil == "undefined") deconcept.SWFObjectUtil = new Object();
deconcept.SWFObject = function(swf, id, w, h, ver, c, quality, xiRedirectUrl, redirectUrl, detectKey) {
if (!document.getElementById) { return; }
this.DETECT_KEY = detectKey ? detectKey : 'detectflash';
this.skipDetect = deconcept.util.getRequestParameter(this.DETECT_KEY);
this.params = new Object();
this.variables = new Object();
this.attributes = new Array();
if(swf) { this.setAttribute('swf', swf); }
if(id) { this.setAttribute('id', id); }
if(w) { this.setAttribute('width', w); }
if(h) { this.setAttribute('height', h); }
if(ver) { this.setAttribute('version', new deconcept.PlayerVersion(ver.toString().split("."))); }
this.installedVer = deconcept.SWFObjectUtil.getPlayerVersion();
if (!window.opera && document.all && this.installedVer.major > 7) {
// only add the onunload cleanup if the Flash Player version supports External Interface and we are in IE
deconcept.SWFObject.doPrepUnload = true;
}
if(c) { this.addParam('bgcolor', c); }
var q = quality ? quality : 'high';
this.addParam('quality', q);
this.setAttribute('useExpressInstall', false);
this.setAttribute('doExpressInstall', false);
var xir = (xiRedirectUrl) ? xiRedirectUrl : window.location;
this.setAttribute('xiRedirectUrl', xir);
this.setAttribute('redirectUrl', '');
if(redirectUrl) { this.setAttribute('redirectUrl', redirectUrl); }
}
deconcept.SWFObject.prototype = {
useExpressInstall: function(path) {
this.xiSWFPath = !path ? "expressinstall.swf" : path;
this.setAttribute('useExpressInstall', true);
},
setAttribute: function(name, value){
this.attributes[name] = value;
},
getAttribute: function(name){
return this.attributes[name];
},
addParam: function(name, value){
this.params[name] = value;
},
getParams: function(){
return this.params;
},
addVariable: function(name, value){
this.variables[name] = value;
},
getVariable: function(name){
return this.variables[name];
},
getVariables: function(){
return this.variables;
},
getVariablePairs: function(){
var variablePairs = new Array();
var key;
var variables = this.getVariables();
for(key in variables){
variablePairs[variablePairs.length] = key +"="+ variables[key];
}
return variablePairs;
},
getSWFHTML: function() {
var swfNode = "";
if (navigator.plugins && navigator.mimeTypes && navigator.mimeTypes.length) { // netscape plugin architecture
if (this.getAttribute("doExpressInstall")) {
this.addVariable("MMplayerType", "PlugIn");
this.setAttribute('swf', this.xiSWFPath);
}
swfNode = '<embed type="application/x-shockwave-flash" src="'+ this.getAttribute('swf') +'" width="'+ this.getAttribute('width') +'" height="'+ this.getAttribute('height') +'" style="'+ this.getAttribute('style') +'"';
swfNode += ' id="'+ this.getAttribute('id') +'" name="'+ this.getAttribute('id') +'" ';
var params = this.getParams();
for(var key in params){ swfNode += [key] +'="'+ params[key] +'" '; }
var pairs = this.getVariablePairs().join("&");
if (pairs.length > 0){ swfNode += 'flashvars="'+ pairs +'"'; }
swfNode += '/>';
} else { // PC IE
if (this.getAttribute("doExpressInstall")) {
this.addVariable("MMplayerType", "ActiveX");
this.setAttribute('swf', this.xiSWFPath);
}
swfNode = '<object id="'+ this.getAttribute('id') +'" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="'+ this.getAttribute('width') +'" height="'+ this.getAttribute('height') +'" style="'+ this.getAttribute('style') +'">';
swfNode += '<param name="movie" value="'+ this.getAttribute('swf') +'" />';
var params = this.getParams();
for(var key in params) {
swfNode += '<param name="'+ key +'" value="'+ params[key] +'" />';
}
var pairs = this.getVariablePairs().join("&");
if(pairs.length > 0) {swfNode += '<param name="flashvars" value="'+ pairs +'" />';}
swfNode += "</object>";
}
return swfNode;
},
write: function(elementId){
if(this.getAttribute('useExpressInstall')) {
// check to see if we need to do an express install
var expressInstallReqVer = new deconcept.PlayerVersion([6,0,65]);
if (this.installedVer.versionIsValid(expressInstallReqVer) && !this.installedVer.versionIsValid(this.getAttribute('version'))) {
this.setAttribute('doExpressInstall', true);
this.addVariable("MMredirectURL", escape(this.getAttribute('xiRedirectUrl')));
document.title = document.title.slice(0, 47) + " - Flash Player Installation";
this.addVariable("MMdoctitle", document.title);
}
}
if(this.skipDetect || this.getAttribute('doExpressInstall') || this.installedVer.versionIsValid(this.getAttribute('version'))){
var n = (typeof elementId == 'string') ? document.getElementById(elementId) : elementId;
n.innerHTML = this.getSWFHTML();
return true;
}else{
if(this.getAttribute('redirectUrl') != "") {
document.location.replace(this.getAttribute('redirectUrl'));
}
}
return false;
}
}
/* ---- detection functions ---- */
deconcept.SWFObjectUtil.getPlayerVersion = function(){
var PlayerVersion = new deconcept.PlayerVersion([0,0,0]);
if(navigator.plugins && navigator.mimeTypes.length){
var x = navigator.plugins["Shockwave Flash"];
if(x && x.description) {
PlayerVersion = new deconcept.PlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/, "").replace(/(\s+r|\s+b[0-9]+)/, ".").split("."));
}
}else if (navigator.userAgent && navigator.userAgent.indexOf("Windows CE") >= 0){ // if Windows CE
var axo = 1;
var counter = 3;
while(axo) {
try {
counter++;
axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+ counter);
// document.write("player v: "+ counter);
PlayerVersion = new deconcept.PlayerVersion([counter,0,0]);
} catch (e) {
axo = null;
}
}
} else { // Win IE (non mobile)
// do minor version lookup in IE, but avoid fp6 crashing issues
// see http://blog.deconcept.com/2006/01/11/getvariable-setvariable-crash-internet-explorer-flash-6/
try{
var axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
}catch(e){
try {
var axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
PlayerVersion = new deconcept.PlayerVersion([6,0,21]);
axo.AllowScriptAccess = "always"; // error if player version < 6.0.47 (thanks to Michael Williams @ Adobe for this code)
} catch(e) {
if (PlayerVersion.major == 6) {
return PlayerVersion;
}
}
try {
axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
} catch(e) {}
}
if (axo != null) {
PlayerVersion = new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));
}
}
return PlayerVersion;
}
deconcept.PlayerVersion = function(arrVersion){
this.major = arrVersion[0] != null ? parseInt(arrVersion[0]) : 0;
this.minor = arrVersion[1] != null ? parseInt(arrVersion[1]) : 0;
this.rev = arrVersion[2] != null ? parseInt(arrVersion[2]) : 0;
}
deconcept.PlayerVersion.prototype.versionIsValid = function(fv){
if(this.major < fv.major) return false;
if(this.major > fv.major) return true;
if(this.minor < fv.minor) return false;
if(this.minor > fv.minor) return true;
if(this.rev < fv.rev) return false;
return true;
}
/* ---- get value of query string param ---- */
deconcept.util = {
getRequestParameter: function(param) {
var q = document.location.search || document.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 "";
}
}
/* fix for video streaming bug */
deconcept.SWFObjectUtil.cleanupSWFs = function() {
var objects = document.getElementsByTagName("OBJECT");
for (var i = objects.length - 1; i >= 0; i--) {
objects[i].style.display = 'none';
for (var x in objects[i]) {
if (typeof objects[i][x] == 'function') {
objects[i][x] = function(){};
}
}
}
}
// fixes bug in some fp9 versions see http://blog.deconcept.com/2006/07/28/swfobject-143-released/
if (deconcept.SWFObject.doPrepUnload) {
if (!deconcept.unloadSet) {
deconcept.SWFObjectUtil.prepUnload = function() {
__flash_unloadHandler = function(){};
__flash_savedUnloadHandler = function(){};
window.attachEvent("onunload", deconcept.SWFObjectUtil.cleanupSWFs);
}
window.attachEvent("onbeforeunload", deconcept.SWFObjectUtil.prepUnload);
deconcept.unloadSet = true;
}
}
/* add document.getElementById if needed (mobile IE < 5) */
if (!document.getElementById && document.all) { document.getElementById = function(id) { return document.all[id]; }}
/* add some aliases for ease of use/backwards compatibility */
var getQueryParamValue = deconcept.util.getRequestParameter;
var FlashObject = deconcept.SWFObject; // for legacy support
var SWFObject = deconcept.SWFObject;
| JavaScript |
/**
* @license Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* This file was added automatically by CKEditor builder.
* You may re-use it at any time at http://ckeditor.com/builder to build CKEditor again.
*
* NOTE:
* This file is not used by CKEditor, you may remove it.
* Changing this file will not change your CKEditor configuration.
*/
var CKBUILDER_CONFIG = {
skin: 'moono',
preset: 'standard',
ignore: [
'dev',
'.gitignore',
'.gitattributes',
'README.md',
'.mailmap'
],
plugins : {
'about' : 1,
'a11yhelp' : 1,
'basicstyles' : 1,
'blockquote' : 1,
'clipboard' : 1,
'contextmenu' : 1,
'resize' : 1,
'toolbar' : 1,
'elementspath' : 1,
'enterkey' : 1,
'entities' : 1,
'filebrowser' : 1,
'floatingspace' : 1,
'format' : 1,
'htmlwriter' : 1,
'horizontalrule' : 1,
'wysiwygarea' : 1,
'image' : 1,
'indent' : 1,
'link' : 1,
'list' : 1,
'magicline' : 1,
'maximize' : 1,
'pastetext' : 1,
'pastefromword' : 1,
'removeformat' : 1,
'sourcearea' : 1,
'specialchar' : 1,
'stylescombo' : 1,
'tab' : 1,
'table' : 1,
'tabletools' : 1,
'undo' : 1,
'dialog' : 1,
'dialogui' : 1,
'menu' : 1,
'floatpanel' : 1,
'panel' : 1,
'button' : 1,
'popup' : 1,
'richcombo' : 1,
'listblock' : 1,
'fakeobjects' : 1
},
languages : {
'af' : 1,
'ar' : 1,
'eu' : 1,
'bn' : 1,
'bs' : 1,
'bg' : 1,
'ca' : 1,
'zh-cn' : 1,
'zh' : 1,
'hr' : 1,
'cs' : 1,
'da' : 1,
'nl' : 1,
'en' : 1,
'en-au' : 1,
'en-ca' : 1,
'en-gb' : 1,
'eo' : 1,
'et' : 1,
'fo' : 1,
'fi' : 1,
'fr' : 1,
'fr-ca' : 1,
'gl' : 1,
'ka' : 1,
'de' : 1,
'el' : 1,
'gu' : 1,
'he' : 1,
'hi' : 1,
'hu' : 1,
'is' : 1,
'it' : 1,
'ja' : 1,
'km' : 1,
'ko' : 1,
'ku' : 1,
'lv' : 1,
'lt' : 1,
'mk' : 1,
'ms' : 1,
'mn' : 1,
'no' : 1,
'nb' : 1,
'fa' : 1,
'pl' : 1,
'pt-br' : 1,
'pt' : 1,
'ro' : 1,
'ru' : 1,
'sr' : 1,
'sr-latn' : 1,
'sk' : 1,
'sl' : 1,
'es' : 1,
'sv' : 1,
'th' : 1,
'tr' : 1,
'ug' : 1,
'uk' : 1,
'vi' : 1,
'cy' : 1,
}
}; | JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
| JavaScript |
/**
* @license Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.editorConfig = function( config ) {
// Define changes to default configuration here.
// For the complete reference:
// http://docs.ckeditor.com/#!/api/CKEDITOR.config
// The toolbar groups arrangement, optimized for two toolbar rows.
config.toolbarGroups = [
{ name: 'clipboard', groups: [ 'clipboard', 'undo' ] },
{ name: 'editing', groups: [ 'find', 'selection', 'spellchecker' ] },
{ name: 'links' },
{ name: 'insert' },
{ name: 'forms' },
{ name: 'tools' },
{ name: 'document', groups: [ 'mode', 'document', 'doctools' ] },
{ name: 'others' },
'/',
{ name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] },
{ name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align' ] },
{ name: 'styles' },
{ name: 'colors' },
{ name: 'about' }
];
// Remove some buttons, provided by the standard plugins, which we don't
// need to have in the Standard(s) toolbar.
config.removeButtons = 'Underline,Subscript,Superscript';
};
| JavaScript |
/**
* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.html or http://ckeditor.com/license
*/
// This file contains style definitions that can be used by CKEditor plugins.
//
// The most common use for it is the "stylescombo" plugin, which shows a combo
// in the editor toolbar, containing all styles. Other plugins instead, like
// the div plugin, use a subset of the styles on their feature.
//
// If you don't have plugins that depend on this file, you can simply ignore it.
// Otherwise it is strongly recommended to customize this file to match your
// website requirements and design properly.
CKEDITOR.stylesSet.add( 'default', [
/* Block Styles */
// These styles are already available in the "Format" combo ("format" plugin),
// so they are not needed here by default. You may enable them to avoid
// placing the "Format" combo in the toolbar, maintaining the same features.
/*
{ name: 'Paragraph', element: 'p' },
{ name: 'Heading 1', element: 'h1' },
{ name: 'Heading 2', element: 'h2' },
{ name: 'Heading 3', element: 'h3' },
{ name: 'Heading 4', element: 'h4' },
{ name: 'Heading 5', element: 'h5' },
{ name: 'Heading 6', element: 'h6' },
{ name: 'Preformatted Text',element: 'pre' },
{ name: 'Address', element: 'address' },
*/
{ name: 'Italic Title', element: 'h2', styles: { 'font-style': 'italic' } },
{ name: 'Subtitle', element: 'h3', styles: { 'color': '#aaa', 'font-style': 'italic' } },
{
name: 'Special Container',
element: 'div',
styles: {
padding: '5px 10px',
background: '#eee',
border: '1px solid #ccc'
}
},
/* Inline Styles */
// These are core styles available as toolbar buttons. You may opt enabling
// some of them in the Styles combo, removing them from the toolbar.
// (This requires the "stylescombo" plugin)
/*
{ name: 'Strong', element: 'strong', overrides: 'b' },
{ name: 'Emphasis', element: 'em' , overrides: 'i' },
{ name: 'Underline', element: 'u' },
{ name: 'Strikethrough', element: 'strike' },
{ name: 'Subscript', element: 'sub' },
{ name: 'Superscript', element: 'sup' },
*/
{ name: 'Marker: Yellow', element: 'span', styles: { 'background-color': 'Yellow' } },
{ name: 'Marker: Green', element: 'span', styles: { 'background-color': 'Lime' } },
{ name: 'Big', element: 'big' },
{ name: 'Small', element: 'small' },
{ name: 'Typewriter', element: 'tt' },
{ name: 'Computer Code', element: 'code' },
{ name: 'Keyboard Phrase', element: 'kbd' },
{ name: 'Sample Text', element: 'samp' },
{ name: 'Variable', element: 'var' },
{ name: 'Deleted Text', element: 'del' },
{ name: 'Inserted Text', element: 'ins' },
{ name: 'Cited Work', element: 'cite' },
{ name: 'Inline Quotation', element: 'q' },
{ name: 'Language: RTL', element: 'span', attributes: { 'dir': 'rtl' } },
{ name: 'Language: LTR', element: 'span', attributes: { 'dir': 'ltr' } },
/* Object Styles */
{
name: 'Styled image (left)',
element: 'img',
attributes: { 'class': 'left' }
},
{
name: 'Styled image (right)',
element: 'img',
attributes: { 'class': 'right' }
},
{
name: 'Compact table',
element: 'table',
attributes: {
cellpadding: '5',
cellspacing: '0',
border: '1',
bordercolor: '#ccc'
},
styles: {
'border-collapse': 'collapse'
}
},
{ name: 'Borderless Table', element: 'table', styles: { 'border-style': 'hidden', 'background-color': '#E6E6FA' } },
{ name: 'Square Bulleted List', element: 'ul', styles: { 'list-style-type': 'square' } }
]);
| 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 D="undefined",r="object",S="Shockwave Flash",W="ShockwaveFlash.ShockwaveFlash",q="application/x-shockwave-flash",R="SWFObjectExprInst",x="onreadystatechange",O=window,j=document,t=navigator,T=false,U=[h],o=[],N=[],I=[],l,Q,E,B,J=false,a=false,n,G,m=true,M=function(){var aa=typeof j.getElementById!=D&&typeof j.getElementsByTagName!=D&&typeof j.createElement!=D,ah=t.userAgent.toLowerCase(),Y=t.platform.toLowerCase(),ae=Y?/win/.test(Y):/win/.test(ah),ac=Y?/mac/.test(Y):/mac/.test(ah),af=/webkit/.test(ah)?parseFloat(ah.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,X=!+"\v1",ag=[0,0,0],ab=null;
if(typeof t.plugins!=D&&typeof t.plugins[S]==r){ab=t.plugins[S].description;if(ab&&!(typeof t.mimeTypes!=D&&t.mimeTypes[q]&&!t.mimeTypes[q].enabledPlugin)){T=true;
X=false;ab=ab.replace(/^.*\s+(\S+\s+\S+$)/,"$1");ag[0]=parseInt(ab.replace(/^(.*)\..*$/,"$1"),10);ag[1]=parseInt(ab.replace(/^.*\.(.*)\s.*$/,"$1"),10);
ag[2]=/[a-zA-Z]/.test(ab)?parseInt(ab.replace(/^.*[a-zA-Z]+(.*)$/,"$1"),10):0;}}else{if(typeof O.ActiveXObject!=D){try{var ad=new ActiveXObject(W);if(ad){ab=ad.GetVariable("$version");
if(ab){X=true;ab=ab.split(" ")[1].split(",");ag=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)];}}}catch(Z){}}}return{w3:aa,pv:ag,wk:af,ie:X,win:ae,mac:ac};
}(),k=function(){if(!M.w3){return;}if((typeof j.readyState!=D&&j.readyState=="complete")||(typeof j.readyState==D&&(j.getElementsByTagName("body")[0]||j.body))){f();
}if(!J){if(typeof j.addEventListener!=D){j.addEventListener("DOMContentLoaded",f,false);}if(M.ie&&M.win){j.attachEvent(x,function(){if(j.readyState=="complete"){j.detachEvent(x,arguments.callee);
f();}});if(O==top){(function(){if(J){return;}try{j.documentElement.doScroll("left");}catch(X){setTimeout(arguments.callee,0);return;}f();})();}}if(M.wk){(function(){if(J){return;
}if(!/loaded|complete/.test(j.readyState)){setTimeout(arguments.callee,0);return;}f();})();}s(f);}}();function f(){if(J){return;}try{var Z=j.getElementsByTagName("body")[0].appendChild(C("span"));
Z.parentNode.removeChild(Z);}catch(aa){return;}J=true;var X=U.length;for(var Y=0;Y<X;Y++){U[Y]();}}function K(X){if(J){X();}else{U[U.length]=X;}}function s(Y){if(typeof O.addEventListener!=D){O.addEventListener("load",Y,false);
}else{if(typeof j.addEventListener!=D){j.addEventListener("load",Y,false);}else{if(typeof O.attachEvent!=D){i(O,"onload",Y);}else{if(typeof O.onload=="function"){var X=O.onload;
O.onload=function(){X();Y();};}else{O.onload=Y;}}}}}function h(){if(T){V();}else{H();}}function V(){var X=j.getElementsByTagName("body")[0];var aa=C(r);
aa.setAttribute("type",q);var Z=X.appendChild(aa);if(Z){var Y=0;(function(){if(typeof Z.GetVariable!=D){var ab=Z.GetVariable("$version");if(ab){ab=ab.split(" ")[1].split(",");
M.pv=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)];}}else{if(Y<10){Y++;setTimeout(arguments.callee,10);return;}}X.removeChild(aa);Z=null;H();
})();}else{H();}}function H(){var ag=o.length;if(ag>0){for(var af=0;af<ag;af++){var Y=o[af].id;var ab=o[af].callbackFn;var aa={success:false,id:Y};if(M.pv[0]>0){var ae=c(Y);
if(ae){if(F(o[af].swfVersion)&&!(M.wk&&M.wk<312)){w(Y,true);if(ab){aa.success=true;aa.ref=z(Y);ab(aa);}}else{if(o[af].expressInstall&&A()){var ai={};ai.data=o[af].expressInstall;
ai.width=ae.getAttribute("width")||"0";ai.height=ae.getAttribute("height")||"0";if(ae.getAttribute("class")){ai.styleclass=ae.getAttribute("class");}if(ae.getAttribute("align")){ai.align=ae.getAttribute("align");
}var ah={};var X=ae.getElementsByTagName("param");var ac=X.length;for(var ad=0;ad<ac;ad++){if(X[ad].getAttribute("name").toLowerCase()!="movie"){ah[X[ad].getAttribute("name")]=X[ad].getAttribute("value");
}}P(ai,ah,Y,ab);}else{p(ae);if(ab){ab(aa);}}}}}else{w(Y,true);if(ab){var Z=z(Y);if(Z&&typeof Z.SetVariable!=D){aa.success=true;aa.ref=Z;}ab(aa);}}}}}function z(aa){var X=null;
var Y=c(aa);if(Y&&Y.nodeName=="OBJECT"){if(typeof Y.SetVariable!=D){X=Y;}else{var Z=Y.getElementsByTagName(r)[0];if(Z){X=Z;}}}return X;}function A(){return !a&&F("6.0.65")&&(M.win||M.mac)&&!(M.wk&&M.wk<312);
}function P(aa,ab,X,Z){a=true;E=Z||null;B={success:false,id:X};var ae=c(X);if(ae){if(ae.nodeName=="OBJECT"){l=g(ae);Q=null;}else{l=ae;Q=X;}aa.id=R;if(typeof aa.width==D||(!/%$/.test(aa.width)&&parseInt(aa.width,10)<310)){aa.width="310";
}if(typeof aa.height==D||(!/%$/.test(aa.height)&&parseInt(aa.height,10)<137)){aa.height="137";}j.title=j.title.slice(0,47)+" - Flash Player Installation";
var ad=M.ie&&M.win?"ActiveX":"PlugIn",ac="MMredirectURL="+O.location.toString().replace(/&/g,"%26")+"&MMplayerType="+ad+"&MMdoctitle="+j.title;if(typeof ab.flashvars!=D){ab.flashvars+="&"+ac;
}else{ab.flashvars=ac;}if(M.ie&&M.win&&ae.readyState!=4){var Y=C("div");X+="SWFObjectNew";Y.setAttribute("id",X);ae.parentNode.insertBefore(Y,ae);ae.style.display="none";
(function(){if(ae.readyState==4){ae.parentNode.removeChild(ae);}else{setTimeout(arguments.callee,10);}})();}u(aa,ab,X);}}function p(Y){if(M.ie&&M.win&&Y.readyState!=4){var X=C("div");
Y.parentNode.insertBefore(X,Y);X.parentNode.replaceChild(g(Y),X);Y.style.display="none";(function(){if(Y.readyState==4){Y.parentNode.removeChild(Y);}else{setTimeout(arguments.callee,10);
}})();}else{Y.parentNode.replaceChild(g(Y),Y);}}function g(ab){var aa=C("div");if(M.win&&M.ie){aa.innerHTML=ab.innerHTML;}else{var Y=ab.getElementsByTagName(r)[0];
if(Y){var ad=Y.childNodes;if(ad){var X=ad.length;for(var Z=0;Z<X;Z++){if(!(ad[Z].nodeType==1&&ad[Z].nodeName=="PARAM")&&!(ad[Z].nodeType==8)){aa.appendChild(ad[Z].cloneNode(true));
}}}}}return aa;}function u(ai,ag,Y){var X,aa=c(Y);if(M.wk&&M.wk<312){return X;}if(aa){if(typeof ai.id==D){ai.id=Y;}if(M.ie&&M.win){var ah="";for(var ae in ai){if(ai[ae]!=Object.prototype[ae]){if(ae.toLowerCase()=="data"){ag.movie=ai[ae];
}else{if(ae.toLowerCase()=="styleclass"){ah+=' class="'+ai[ae]+'"';}else{if(ae.toLowerCase()!="classid"){ah+=" "+ae+'="'+ai[ae]+'"';}}}}}var af="";for(var ad in ag){if(ag[ad]!=Object.prototype[ad]){af+='<param name="'+ad+'" value="'+ag[ad]+'" />';
}}aa.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+ah+">"+af+"</object>";N[N.length]=ai.id;X=c(ai.id);}else{var Z=C(r);Z.setAttribute("type",q);
for(var ac in ai){if(ai[ac]!=Object.prototype[ac]){if(ac.toLowerCase()=="styleclass"){Z.setAttribute("class",ai[ac]);}else{if(ac.toLowerCase()!="classid"){Z.setAttribute(ac,ai[ac]);
}}}}for(var ab in ag){if(ag[ab]!=Object.prototype[ab]&&ab.toLowerCase()!="movie"){e(Z,ab,ag[ab]);}}aa.parentNode.replaceChild(Z,aa);X=Z;}}return X;}function e(Z,X,Y){var aa=C("param");
aa.setAttribute("name",X);aa.setAttribute("value",Y);Z.appendChild(aa);}function y(Y){var X=c(Y);if(X&&X.nodeName=="OBJECT"){if(M.ie&&M.win){X.style.display="none";
(function(){if(X.readyState==4){b(Y);}else{setTimeout(arguments.callee,10);}})();}else{X.parentNode.removeChild(X);}}}function b(Z){var Y=c(Z);if(Y){for(var X in Y){if(typeof Y[X]=="function"){Y[X]=null;
}}Y.parentNode.removeChild(Y);}}function c(Z){var X=null;try{X=j.getElementById(Z);}catch(Y){}return X;}function C(X){return j.createElement(X);}function i(Z,X,Y){Z.attachEvent(X,Y);
I[I.length]=[Z,X,Y];}function F(Z){var Y=M.pv,X=Z.split(".");X[0]=parseInt(X[0],10);X[1]=parseInt(X[1],10)||0;X[2]=parseInt(X[2],10)||0;return(Y[0]>X[0]||(Y[0]==X[0]&&Y[1]>X[1])||(Y[0]==X[0]&&Y[1]==X[1]&&Y[2]>=X[2]))?true:false;
}function v(ac,Y,ad,ab){if(M.ie&&M.mac){return;}var aa=j.getElementsByTagName("head")[0];if(!aa){return;}var X=(ad&&typeof ad=="string")?ad:"screen";if(ab){n=null;
G=null;}if(!n||G!=X){var Z=C("style");Z.setAttribute("type","text/css");Z.setAttribute("media",X);n=aa.appendChild(Z);if(M.ie&&M.win&&typeof j.styleSheets!=D&&j.styleSheets.length>0){n=j.styleSheets[j.styleSheets.length-1];
}G=X;}if(M.ie&&M.win){if(n&&typeof n.addRule==r){n.addRule(ac,Y);}}else{if(n&&typeof j.createTextNode!=D){n.appendChild(j.createTextNode(ac+" {"+Y+"}"));
}}}function w(Z,X){if(!m){return;}var Y=X?"visible":"hidden";if(J&&c(Z)){c(Z).style.visibility=Y;}else{v("#"+Z,"visibility:"+Y);}}function L(Y){var Z=/[\\\"<>\.;]/;
var X=Z.exec(Y)!=null;return X&&typeof encodeURIComponent!=D?encodeURIComponent(Y):Y;}var d=function(){if(M.ie&&M.win){window.attachEvent("onunload",function(){var ac=I.length;
for(var ab=0;ab<ac;ab++){I[ab][0].detachEvent(I[ab][1],I[ab][2]);}var Z=N.length;for(var aa=0;aa<Z;aa++){y(N[aa]);}for(var Y in M){M[Y]=null;}M=null;for(var X in swfobject){swfobject[X]=null;
}swfobject=null;});}}();return{registerObject:function(ab,X,aa,Z){if(M.w3&&ab&&X){var Y={};Y.id=ab;Y.swfVersion=X;Y.expressInstall=aa;Y.callbackFn=Z;o[o.length]=Y;
w(ab,false);}else{if(Z){Z({success:false,id:ab});}}},getObjectById:function(X){if(M.w3){return z(X);}},embedSWF:function(ab,ah,ae,ag,Y,aa,Z,ad,af,ac){var X={success:false,id:ah};
if(M.w3&&!(M.wk&&M.wk<312)&&ab&&ah&&ae&&ag&&Y){w(ah,false);K(function(){ae+="";ag+="";var aj={};if(af&&typeof af===r){for(var al in af){aj[al]=af[al];}}aj.data=ab;
aj.width=ae;aj.height=ag;var am={};if(ad&&typeof ad===r){for(var ak in ad){am[ak]=ad[ak];}}if(Z&&typeof Z===r){for(var ai in Z){if(typeof am.flashvars!=D){am.flashvars+="&"+ai+"="+Z[ai];
}else{am.flashvars=ai+"="+Z[ai];}}}if(F(Y)){var an=u(aj,am,ah);if(aj.id==ah){w(ah,true);}X.success=true;X.ref=an;}else{if(aa&&A()){aj.data=aa;P(aj,am,ah,ac);
return;}else{w(ah,true);}}if(ac){ac(X);}});}else{if(ac){ac(X);}}},switchOffAutoHideShow:function(){m=false;},ua:M,getFlashPlayerVersion:function(){return{major:M.pv[0],minor:M.pv[1],release:M.pv[2]};
},hasFlashPlayerVersion:F,createSWF:function(Z,Y,X){if(M.w3){return u(Z,Y,X);}else{return undefined;}},showExpressInstall:function(Z,aa,X,Y){if(M.w3&&A()){P(Z,aa,X,Y);
}},removeSWF:function(X){if(M.w3){y(X);}},createCSS:function(aa,Z,Y,X){if(M.w3){v(aa,Z,Y,X);}},addDomLoadEvent:K,addLoadEvent:s,getQueryParamValue:function(aa){var Z=j.location.search||j.location.hash;
if(Z){if(/\?/.test(Z)){Z=Z.split("?")[1];}if(aa==null){return L(Z);}var Y=Z.split("&");for(var X=0;X<Y.length;X++){if(Y[X].substring(0,Y[X].indexOf("="))==aa){return L(Y[X].substring((Y[X].indexOf("=")+1)));
}}}return"";},expressInstallCallback:function(){if(a){var X=c(R);if(X&&l){X.parentNode.replaceChild(l,X);if(Q){w(Q,true);if(M.ie&&M.win){l.style.display="block";
}}if(E){E(B);}}a=false;}}};}();
/*
SWFUpload: http://www.swfupload.org, http://swfupload.googlecode.com
mmSWFUpload 1.0: Flash upload dialog - http://profandesign.se/swfupload/, http://www.vinterwebb.se/
SWFUpload is (c) 2006-2007 Lars Huring, Olov Nilzén and Mammon Media and is released under the MIT License:
http://www.opensource.org/licenses/mit-license.php
SWFUpload 2 is (c) 2007-2008 Jake Roberts and is released under the MIT License:
http://www.opensource.org/licenses/mit-license.php
*/
var SWFUpload;if(SWFUpload==undefined){SWFUpload=function(a){this.initSWFUpload(a)}}SWFUpload.prototype.initSWFUpload=function(b){try{this.customSettings={};this.settings=b;this.eventQueue=[];this.movieName="SWFUpload_"+SWFUpload.movieCount++;this.movieElement=null;SWFUpload.instances[this.movieName]=this;this.initSettings();this.loadFlash();this.displayDebugInfo()}catch(a){delete SWFUpload.instances[this.movieName];throw a}};SWFUpload.instances={};SWFUpload.movieCount=0;SWFUpload.version="2.2.0 2009-03-25";SWFUpload.QUEUE_ERROR={QUEUE_LIMIT_EXCEEDED:-100,FILE_EXCEEDS_SIZE_LIMIT:-110,ZERO_BYTE_FILE:-120,INVALID_FILETYPE:-130};SWFUpload.UPLOAD_ERROR={HTTP_ERROR:-200,MISSING_UPLOAD_URL:-210,IO_ERROR:-220,SECURITY_ERROR:-230,UPLOAD_LIMIT_EXCEEDED:-240,UPLOAD_FAILED:-250,SPECIFIED_FILE_ID_NOT_FOUND:-260,FILE_VALIDATION_FAILED:-270,FILE_CANCELLED:-280,UPLOAD_STOPPED:-290};SWFUpload.FILE_STATUS={QUEUED:-1,IN_PROGRESS:-2,ERROR:-3,COMPLETE:-4,CANCELLED:-5};SWFUpload.BUTTON_ACTION={SELECT_FILE:-100,SELECT_FILES:-110,START_UPLOAD:-120};SWFUpload.CURSOR={ARROW:-1,HAND:-2};SWFUpload.WINDOW_MODE={WINDOW:"window",TRANSPARENT:"transparent",OPAQUE:"opaque"};SWFUpload.completeURL=function(a){if(typeof(a)!=="string"||a.match(/^https?:\/\//i)||a.match(/^\//)){return a}var c=window.location.protocol+"//"+window.location.hostname+(window.location.port?":"+window.location.port:"");var b=window.location.pathname.lastIndexOf("/");if(b<=0){path="/"}else{path=window.location.pathname.substr(0,b)+"/"}return path+a};SWFUpload.prototype.initSettings=function(){this.ensureDefault=function(b,a){this.settings[b]=(this.settings[b]==undefined)?a:this.settings[b]};this.ensureDefault("upload_url","");this.ensureDefault("preserve_relative_urls",false);this.ensureDefault("file_post_name","Filedata");this.ensureDefault("post_params",{});this.ensureDefault("use_query_string",false);this.ensureDefault("requeue_on_error",false);this.ensureDefault("http_success",[]);this.ensureDefault("assume_success_timeout",0);this.ensureDefault("file_types","*.*");this.ensureDefault("file_types_description","All Files");this.ensureDefault("file_size_limit",0);this.ensureDefault("file_upload_limit",0);this.ensureDefault("file_queue_limit",0);this.ensureDefault("flash_url","swfupload.swf");this.ensureDefault("prevent_swf_caching",true);this.ensureDefault("button_image_url","");this.ensureDefault("button_width",1);this.ensureDefault("button_height",1);this.ensureDefault("button_text","");this.ensureDefault("button_text_style","color: #000000; font-size: 16pt;");this.ensureDefault("button_text_top_padding",0);this.ensureDefault("button_text_left_padding",0);this.ensureDefault("button_action",SWFUpload.BUTTON_ACTION.SELECT_FILES);this.ensureDefault("button_disabled",false);this.ensureDefault("button_placeholder_id","");this.ensureDefault("button_placeholder",null);this.ensureDefault("button_cursor",SWFUpload.CURSOR.ARROW);this.ensureDefault("button_window_mode",SWFUpload.WINDOW_MODE.WINDOW);this.ensureDefault("debug",false);this.settings.debug_enabled=this.settings.debug;this.settings.return_upload_start_handler=this.returnUploadStart;this.ensureDefault("swfupload_loaded_handler",null);this.ensureDefault("file_dialog_start_handler",null);this.ensureDefault("file_queued_handler",null);this.ensureDefault("file_queue_error_handler",null);this.ensureDefault("file_dialog_complete_handler",null);this.ensureDefault("upload_start_handler",null);this.ensureDefault("upload_progress_handler",null);this.ensureDefault("upload_error_handler",null);this.ensureDefault("upload_success_handler",null);this.ensureDefault("upload_complete_handler",null);this.ensureDefault("debug_handler",this.debugMessage);this.ensureDefault("custom_settings",{});this.customSettings=this.settings.custom_settings;if(!!this.settings.prevent_swf_caching){this.settings.flash_url=this.settings.flash_url+(this.settings.flash_url.indexOf("?")<0?"?":"&")+"preventswfcaching="+new Date().getTime()}if(!this.settings.preserve_relative_urls){this.settings.upload_url=SWFUpload.completeURL(this.settings.upload_url);this.settings.button_image_url=SWFUpload.completeURL(this.settings.button_image_url)}delete this.ensureDefault};SWFUpload.prototype.loadFlash=function(){var a,b;if(document.getElementById(this.movieName)!==null){throw"ID "+this.movieName+" is already in use. The Flash Object could not be added"}a=document.getElementById(this.settings.button_placeholder_id)||this.settings.button_placeholder;if(a==undefined){throw"Could not find the placeholder element: "+this.settings.button_placeholder_id}b=document.createElement("div");b.innerHTML=this.getFlashHTML();a.parentNode.replaceChild(b.firstChild,a);if(window[this.movieName]==undefined){window[this.movieName]=this.getMovieElement()}};SWFUpload.prototype.getFlashHTML=function(){return['<object id="',this.movieName,'" type="application/x-shockwave-flash" data="',this.settings.flash_url,'" width="',this.settings.button_width,'" height="',this.settings.button_height,'" class="swfupload">','<param name="wmode" value="',this.settings.button_window_mode,'" />','<param name="movie" value="',this.settings.flash_url,'" />','<param name="quality" value="high" />','<param name="menu" value="false" />','<param name="allowScriptAccess" value="always" />','<param name="flashvars" value="'+this.getFlashVars()+'" />',"</object>"].join("")};SWFUpload.prototype.getFlashVars=function(){var b=this.buildParamString();var a=this.settings.http_success.join(",");return["movieName=",encodeURIComponent(this.movieName),"&uploadURL=",encodeURIComponent(this.settings.upload_url),"&useQueryString=",encodeURIComponent(this.settings.use_query_string),"&requeueOnError=",encodeURIComponent(this.settings.requeue_on_error),"&httpSuccess=",encodeURIComponent(a),"&assumeSuccessTimeout=",encodeURIComponent(this.settings.assume_success_timeout),"&params=",encodeURIComponent(b),"&filePostName=",encodeURIComponent(this.settings.file_post_name),"&fileTypes=",encodeURIComponent(this.settings.file_types),"&fileTypesDescription=",encodeURIComponent(this.settings.file_types_description),"&fileSizeLimit=",encodeURIComponent(this.settings.file_size_limit),"&fileUploadLimit=",encodeURIComponent(this.settings.file_upload_limit),"&fileQueueLimit=",encodeURIComponent(this.settings.file_queue_limit),"&debugEnabled=",encodeURIComponent(this.settings.debug_enabled),"&buttonImageURL=",encodeURIComponent(this.settings.button_image_url),"&buttonWidth=",encodeURIComponent(this.settings.button_width),"&buttonHeight=",encodeURIComponent(this.settings.button_height),"&buttonText=",encodeURIComponent(this.settings.button_text),"&buttonTextTopPadding=",encodeURIComponent(this.settings.button_text_top_padding),"&buttonTextLeftPadding=",encodeURIComponent(this.settings.button_text_left_padding),"&buttonTextStyle=",encodeURIComponent(this.settings.button_text_style),"&buttonAction=",encodeURIComponent(this.settings.button_action),"&buttonDisabled=",encodeURIComponent(this.settings.button_disabled),"&buttonCursor=",encodeURIComponent(this.settings.button_cursor)].join("")};SWFUpload.prototype.getMovieElement=function(){if(this.movieElement==undefined){this.movieElement=document.getElementById(this.movieName)}if(this.movieElement===null){throw"Could not find Flash element"}return this.movieElement};SWFUpload.prototype.buildParamString=function(){var c=this.settings.post_params;var b=[];if(typeof(c)==="object"){for(var a in c){if(c.hasOwnProperty(a)){b.push(encodeURIComponent(a.toString())+"="+encodeURIComponent(c[a].toString()))}}}return b.join("&")};SWFUpload.prototype.destroy=function(){try{this.cancelUpload(null,false);var a=null;a=this.getMovieElement();if(a&&typeof(a.CallFunction)==="unknown"){for(var c in a){try{if(typeof(a[c])==="function"){a[c]=null}}catch(e){}}try{a.parentNode.removeChild(a)}catch(b){}}window[this.movieName]=null;SWFUpload.instances[this.movieName]=null;delete SWFUpload.instances[this.movieName];this.movieElement=null;this.settings=null;this.customSettings=null;this.eventQueue=null;this.movieName=null;return true}catch(d){return false}};SWFUpload.prototype.displayDebugInfo=function(){this.debug(["---SWFUpload Instance Info---\n","Version: ",SWFUpload.version,"\n","Movie Name: ",this.movieName,"\n","Settings:\n","\t","upload_url: ",this.settings.upload_url,"\n","\t","flash_url: ",this.settings.flash_url,"\n","\t","use_query_string: ",this.settings.use_query_string.toString(),"\n","\t","requeue_on_error: ",this.settings.requeue_on_error.toString(),"\n","\t","http_success: ",this.settings.http_success.join(", "),"\n","\t","assume_success_timeout: ",this.settings.assume_success_timeout,"\n","\t","file_post_name: ",this.settings.file_post_name,"\n","\t","post_params: ",this.settings.post_params.toString(),"\n","\t","file_types: ",this.settings.file_types,"\n","\t","file_types_description: ",this.settings.file_types_description,"\n","\t","file_size_limit: ",this.settings.file_size_limit,"\n","\t","file_upload_limit: ",this.settings.file_upload_limit,"\n","\t","file_queue_limit: ",this.settings.file_queue_limit,"\n","\t","debug: ",this.settings.debug.toString(),"\n","\t","prevent_swf_caching: ",this.settings.prevent_swf_caching.toString(),"\n","\t","button_placeholder_id: ",this.settings.button_placeholder_id.toString(),"\n","\t","button_placeholder: ",(this.settings.button_placeholder?"Set":"Not Set"),"\n","\t","button_image_url: ",this.settings.button_image_url.toString(),"\n","\t","button_width: ",this.settings.button_width.toString(),"\n","\t","button_height: ",this.settings.button_height.toString(),"\n","\t","button_text: ",this.settings.button_text.toString(),"\n","\t","button_text_style: ",this.settings.button_text_style.toString(),"\n","\t","button_text_top_padding: ",this.settings.button_text_top_padding.toString(),"\n","\t","button_text_left_padding: ",this.settings.button_text_left_padding.toString(),"\n","\t","button_action: ",this.settings.button_action.toString(),"\n","\t","button_disabled: ",this.settings.button_disabled.toString(),"\n","\t","custom_settings: ",this.settings.custom_settings.toString(),"\n","Event Handlers:\n","\t","swfupload_loaded_handler assigned: ",(typeof this.settings.swfupload_loaded_handler==="function").toString(),"\n","\t","file_dialog_start_handler assigned: ",(typeof this.settings.file_dialog_start_handler==="function").toString(),"\n","\t","file_queued_handler assigned: ",(typeof this.settings.file_queued_handler==="function").toString(),"\n","\t","file_queue_error_handler assigned: ",(typeof this.settings.file_queue_error_handler==="function").toString(),"\n","\t","upload_start_handler assigned: ",(typeof this.settings.upload_start_handler==="function").toString(),"\n","\t","upload_progress_handler assigned: ",(typeof this.settings.upload_progress_handler==="function").toString(),"\n","\t","upload_error_handler assigned: ",(typeof this.settings.upload_error_handler==="function").toString(),"\n","\t","upload_success_handler assigned: ",(typeof this.settings.upload_success_handler==="function").toString(),"\n","\t","upload_complete_handler assigned: ",(typeof this.settings.upload_complete_handler==="function").toString(),"\n","\t","debug_handler assigned: ",(typeof this.settings.debug_handler==="function").toString(),"\n"].join(""))};SWFUpload.prototype.addSetting=function(b,c,a){if(c==undefined){return(this.settings[b]=a)}else{return(this.settings[b]=c)}};SWFUpload.prototype.getSetting=function(a){if(this.settings[a]!=undefined){return this.settings[a]}return""};SWFUpload.prototype.callFlash=function(functionName,argumentArray){argumentArray=argumentArray||[];var movieElement=this.getMovieElement();var returnValue,returnString;try{returnString=movieElement.CallFunction('<invoke name="'+functionName+'" returntype="javascript">'+__flash__argumentsToXML(argumentArray,0)+"</invoke>");returnValue=eval(returnString)}catch(ex){throw"Call to "+functionName+" failed"}if(returnValue!=undefined&&typeof returnValue.post==="object"){returnValue=this.unescapeFilePostParams(returnValue)}return returnValue};SWFUpload.prototype.selectFile=function(){this.callFlash("SelectFile")};SWFUpload.prototype.selectFiles=function(){this.callFlash("SelectFiles")};SWFUpload.prototype.startUpload=function(a){this.callFlash("StartUpload",[a])};SWFUpload.prototype.cancelUpload=function(a,b){if(b!==false){b=true}this.callFlash("CancelUpload",[a,b])};SWFUpload.prototype.stopUpload=function(){this.callFlash("StopUpload")};SWFUpload.prototype.getStats=function(){return this.callFlash("GetStats")};SWFUpload.prototype.setStats=function(a){this.callFlash("SetStats",[a])};SWFUpload.prototype.getFile=function(a){if(typeof(a)==="number"){return this.callFlash("GetFileByIndex",[a])}else{return this.callFlash("GetFile",[a])}};SWFUpload.prototype.addFileParam=function(a,b,c){return this.callFlash("AddFileParam",[a,b,c])};SWFUpload.prototype.removeFileParam=function(a,b){this.callFlash("RemoveFileParam",[a,b])};SWFUpload.prototype.setUploadURL=function(a){this.settings.upload_url=a.toString();this.callFlash("SetUploadURL",[a])};SWFUpload.prototype.setPostParams=function(a){this.settings.post_params=a;this.callFlash("SetPostParams",[a])};SWFUpload.prototype.addPostParam=function(a,b){this.settings.post_params[a]=b;this.callFlash("SetPostParams",[this.settings.post_params])};SWFUpload.prototype.removePostParam=function(a){delete this.settings.post_params[a];this.callFlash("SetPostParams",[this.settings.post_params])};SWFUpload.prototype.setFileTypes=function(a,b){this.settings.file_types=a;this.settings.file_types_description=b;this.callFlash("SetFileTypes",[a,b])};SWFUpload.prototype.setFileSizeLimit=function(a){this.settings.file_size_limit=a;this.callFlash("SetFileSizeLimit",[a])};SWFUpload.prototype.setFileUploadLimit=function(a){this.settings.file_upload_limit=a;this.callFlash("SetFileUploadLimit",[a])};SWFUpload.prototype.setFileQueueLimit=function(a){this.settings.file_queue_limit=a;this.callFlash("SetFileQueueLimit",[a])};SWFUpload.prototype.setFilePostName=function(a){this.settings.file_post_name=a;this.callFlash("SetFilePostName",[a])};SWFUpload.prototype.setUseQueryString=function(a){this.settings.use_query_string=a;this.callFlash("SetUseQueryString",[a])};SWFUpload.prototype.setRequeueOnError=function(a){this.settings.requeue_on_error=a;this.callFlash("SetRequeueOnError",[a])};SWFUpload.prototype.setHTTPSuccess=function(a){if(typeof a==="string"){a=a.replace(" ","").split(",")}this.settings.http_success=a;this.callFlash("SetHTTPSuccess",[a])};SWFUpload.prototype.setAssumeSuccessTimeout=function(a){this.settings.assume_success_timeout=a;this.callFlash("SetAssumeSuccessTimeout",[a])};SWFUpload.prototype.setDebugEnabled=function(a){this.settings.debug_enabled=a;this.callFlash("SetDebugEnabled",[a])};SWFUpload.prototype.setButtonImageURL=function(a){if(a==undefined){a=""}this.settings.button_image_url=a;this.callFlash("SetButtonImageURL",[a])};SWFUpload.prototype.setButtonDimensions=function(c,a){this.settings.button_width=c;this.settings.button_height=a;var b=this.getMovieElement();if(b!=undefined){b.style.width=c+"px";b.style.height=a+"px"}this.callFlash("SetButtonDimensions",[c,a])};SWFUpload.prototype.setButtonText=function(a){this.settings.button_text=a;this.callFlash("SetButtonText",[a])};SWFUpload.prototype.setButtonTextPadding=function(b,a){this.settings.button_text_top_padding=a;this.settings.button_text_left_padding=b;this.callFlash("SetButtonTextPadding",[b,a])};SWFUpload.prototype.setButtonTextStyle=function(a){this.settings.button_text_style=a;this.callFlash("SetButtonTextStyle",[a])};SWFUpload.prototype.setButtonDisabled=function(a){this.settings.button_disabled=a;this.callFlash("SetButtonDisabled",[a])};SWFUpload.prototype.setButtonAction=function(a){this.settings.button_action=a;this.callFlash("SetButtonAction",[a])};SWFUpload.prototype.setButtonCursor=function(a){this.settings.button_cursor=a;this.callFlash("SetButtonCursor",[a])};SWFUpload.prototype.queueEvent=function(b,c){if(c==undefined){c=[]}else{if(!(c instanceof Array)){c=[c]}}var a=this;if(typeof this.settings[b]==="function"){this.eventQueue.push(function(){this.settings[b].apply(this,c)});setTimeout(function(){a.executeNextEvent()},0)}else{if(this.settings[b]!==null){throw"Event handler "+b+" is unknown or is not a function"}}};SWFUpload.prototype.executeNextEvent=function(){var a=this.eventQueue?this.eventQueue.shift():null;if(typeof(a)==="function"){a.apply(this)}};SWFUpload.prototype.unescapeFilePostParams=function(c){var e=/[$]([0-9a-f]{4})/i;var f={};var d;if(c!=undefined){for(var a in c.post){if(c.post.hasOwnProperty(a)){d=a;var b;while((b=e.exec(d))!==null){d=d.replace(b[0],String.fromCharCode(parseInt("0x"+b[1],16)))}f[d]=c.post[a]}}c.post=f}return c};SWFUpload.prototype.testExternalInterface=function(){try{return this.callFlash("TestExternalInterface")}catch(a){return false}};SWFUpload.prototype.flashReady=function(){var a=this.getMovieElement();if(!a){this.debug("Flash called back ready but the flash movie can't be found.");return}this.cleanUp(a);this.queueEvent("swfupload_loaded_handler")};SWFUpload.prototype.cleanUp=function(a){try{if(this.movieElement&&typeof(a.CallFunction)==="unknown"){this.debug("Removing Flash functions hooks (this should only run in IE and should prevent memory leaks)");for(var c in a){try{if(typeof(a[c])==="function"){a[c]=null}}catch(b){}}}}catch(d){}window.__flash__removeCallback=function(e,f){try{if(e){e[f]=null}}catch(g){}}};SWFUpload.prototype.fileDialogStart=function(){this.queueEvent("file_dialog_start_handler")};SWFUpload.prototype.fileQueued=function(a){a=this.unescapeFilePostParams(a);this.queueEvent("file_queued_handler",a)};SWFUpload.prototype.fileQueueError=function(a,c,b){a=this.unescapeFilePostParams(a);this.queueEvent("file_queue_error_handler",[a,c,b])};SWFUpload.prototype.fileDialogComplete=function(b,c,a){this.queueEvent("file_dialog_complete_handler",[b,c,a])};SWFUpload.prototype.uploadStart=function(a){a=this.unescapeFilePostParams(a);this.queueEvent("return_upload_start_handler",a)};SWFUpload.prototype.returnUploadStart=function(a){var b;if(typeof this.settings.upload_start_handler==="function"){a=this.unescapeFilePostParams(a);b=this.settings.upload_start_handler.call(this,a)}else{if(this.settings.upload_start_handler!=undefined){throw"upload_start_handler must be a function"}}if(b===undefined){b=true}b=!!b;this.callFlash("ReturnUploadStart",[b])};SWFUpload.prototype.uploadProgress=function(a,c,b){a=this.unescapeFilePostParams(a);this.queueEvent("upload_progress_handler",[a,c,b])};SWFUpload.prototype.uploadError=function(a,c,b){a=this.unescapeFilePostParams(a);this.queueEvent("upload_error_handler",[a,c,b])};SWFUpload.prototype.uploadSuccess=function(b,a,c){b=this.unescapeFilePostParams(b);this.queueEvent("upload_success_handler",[b,a,c])};SWFUpload.prototype.uploadComplete=function(a){a=this.unescapeFilePostParams(a);this.queueEvent("upload_complete_handler",a)};SWFUpload.prototype.debug=function(a){this.queueEvent("debug_handler",a)};SWFUpload.prototype.debugMessage=function(c){if(this.settings.debug){var a,d=[];if(typeof c==="object"&&typeof c.name==="string"&&typeof c.message==="string"){for(var b in c){if(c.hasOwnProperty(b)){d.push(b+": "+c[b])}}a=d.join("\n")||"";d=a.split("\n");a="EXCEPTION: "+d.join("\nEXCEPTION: ");SWFUpload.Console.writeLine(a)}else{SWFUpload.Console.writeLine(c)}}};SWFUpload.Console={};SWFUpload.Console.writeLine=function(d){var b,a;try{b=document.getElementById("SWFUpload_Console");if(!b){a=document.createElement("form");document.getElementsByTagName("body")[0].appendChild(a);b=document.createElement("textarea");b.id="SWFUpload_Console";b.style.fontFamily="monospace";b.setAttribute("wrap","off");b.wrap="off";b.style.overflow="auto";b.style.width="700px";b.style.height="350px";b.style.margin="5px";a.appendChild(b)}b.value+=d+"\n";b.scrollTop=b.scrollHeight-b.clientHeight}catch(c){alert("Exception: "+c.name+" Message: "+c.message)}};
/*
Uploadify v3.2
Copyright (c) 2012 Reactive Apps, Ronnie Garcia
Released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/
(function($) {
// These methods can be called by adding them as the first argument in the uploadify plugin call
var methods = {
init : function(options, swfUploadOptions) {
return this.each(function() {
// Create a reference to the jQuery DOM object
var $this = $(this);
// Clone the original DOM object
var $clone = $this.clone();
// Setup the default options
var settings = $.extend({
// Required Settings
id : $this.attr('id'), // The ID of the DOM object
swf : 'uploadify.swf', // The path to the uploadify SWF file
uploader : 'uploadify.php', // The path to the server-side upload script
// Options
auto : true, // Automatically upload files when added to the queue
buttonClass : '', // A class name to add to the browse button DOM object
buttonCursor : 'hand', // The cursor to use with the browse button
buttonImage : null, // (String or null) The path to an image to use for the Flash browse button if not using CSS to style the button
buttonText : 'SELECT FILES', // The text to use for the browse button
checkExisting : false, // The path to a server-side script that checks for existing files on the server
debug : false, // Turn on swfUpload debugging mode
fileObjName : 'Filedata', // The name of the file object to use in your server-side script
fileSizeLimit : 0, // The maximum size of an uploadable file in KB (Accepts units B KB MB GB if string, 0 for no limit)
fileTypeDesc : 'All Files', // The description for file types in the browse dialog
fileTypeExts : '*.*', // Allowed extensions in the browse dialog (server-side validation should also be used)
height : 30, // The height of the browse button
itemTemplate : false, // The template for the file item in the queue
method : 'post', // The method to use when sending files to the server-side upload script
multi : true, // Allow multiple file selection in the browse dialog
formData : {}, // An object with additional data to send to the server-side upload script with every file upload
preventCaching : true, // Adds a random value to the Flash URL to prevent caching of it (conflicts with existing parameters)
progressData : 'percentage', // ('percentage' or 'speed') Data to show in the queue item during a file upload
queueID : false, // The ID of the DOM object to use as a file queue (without the #)
queueSizeLimit : 999, // The maximum number of files that can be in the queue at one time
removeCompleted : true, // Remove queue items from the queue when they are done uploading
removeTimeout : 3, // The delay in seconds before removing a queue item if removeCompleted is set to true
requeueErrors : false, // Keep errored files in the queue and keep trying to upload them
successTimeout : 30, // The number of seconds to wait for Flash to detect the server's response after the file has finished uploading
uploadLimit : 0, // The maximum number of files you can upload
width : 120, // The width of the browse button
// Events
overrideEvents : [] // (Array) A list of default event handlers to skip
/*
onCancel // Triggered when a file is cancelled from the queue
onClearQueue // Triggered during the 'clear queue' method
onDestroy // Triggered when the uploadify object is destroyed
onDialogClose // Triggered when the browse dialog is closed
onDialogOpen // Triggered when the browse dialog is opened
onDisable // Triggered when the browse button gets disabled
onEnable // Triggered when the browse button gets enabled
onFallback // Triggered is Flash is not detected
onInit // Triggered when Uploadify is initialized
onQueueComplete // Triggered when all files in the queue have been uploaded
onSelectError // Triggered when an error occurs while selecting a file (file size, queue size limit, etc.)
onSelect // Triggered for each file that is selected
onSWFReady // Triggered when the SWF button is loaded
onUploadComplete // Triggered when a file upload completes (success or error)
onUploadError // Triggered when a file upload returns an error
onUploadSuccess // Triggered when a file is uploaded successfully
onUploadProgress // Triggered every time a file progress is updated
onUploadStart // Triggered immediately before a file upload starts
*/
}, options);
// Prepare settings for SWFUpload
var swfUploadSettings = {
assume_success_timeout : settings.successTimeout,
button_placeholder_id : settings.id,
button_width : settings.width,
button_height : settings.height,
button_text : null,
button_text_style : null,
button_text_top_padding : 0,
button_text_left_padding : 0,
button_action : (settings.multi ? SWFUpload.BUTTON_ACTION.SELECT_FILES : SWFUpload.BUTTON_ACTION.SELECT_FILE),
button_disabled : false,
button_cursor : (settings.buttonCursor == 'arrow' ? SWFUpload.CURSOR.ARROW : SWFUpload.CURSOR.HAND),
button_window_mode : SWFUpload.WINDOW_MODE.TRANSPARENT,
debug : settings.debug,
requeue_on_error : settings.requeueErrors,
file_post_name : settings.fileObjName,
file_size_limit : settings.fileSizeLimit,
file_types : settings.fileTypeExts,
file_types_description : settings.fileTypeDesc,
file_queue_limit : settings.queueSizeLimit,
file_upload_limit : settings.uploadLimit,
flash_url : settings.swf,
prevent_swf_caching : settings.preventCaching,
post_params : settings.formData,
upload_url : settings.uploader,
use_query_string : (settings.method == 'get'),
// Event Handlers
file_dialog_complete_handler : handlers.onDialogClose,
file_dialog_start_handler : handlers.onDialogOpen,
file_queued_handler : handlers.onSelect,
file_queue_error_handler : handlers.onSelectError,
swfupload_loaded_handler : settings.onSWFReady,
upload_complete_handler : handlers.onUploadComplete,
upload_error_handler : handlers.onUploadError,
upload_progress_handler : handlers.onUploadProgress,
upload_start_handler : handlers.onUploadStart,
upload_success_handler : handlers.onUploadSuccess
}
// Merge the user-defined options with the defaults
if (swfUploadOptions) {
swfUploadSettings = $.extend(swfUploadSettings, swfUploadOptions);
}
// Add the user-defined settings to the swfupload object
swfUploadSettings = $.extend(swfUploadSettings, settings);
// Detect if Flash is available
var playerVersion = swfobject.getFlashPlayerVersion();
var flashInstalled = (playerVersion.major >= 9);
if (flashInstalled) {
// Create the swfUpload instance
window['uploadify_' + settings.id] = new SWFUpload(swfUploadSettings);
var swfuploadify = window['uploadify_' + settings.id];
// Add the SWFUpload object to the elements data object
$this.data('uploadify', swfuploadify);
// Wrap the instance
var $wrapper = $('<div />', {
'id' : settings.id,
'class' : 'uploadify',
'css' : {
'height' : settings.height + 'px',
'width' : settings.width + 'px'
}
});
$('#' + swfuploadify.movieName).wrap($wrapper);
// Recreate the reference to wrapper
$wrapper = $('#' + settings.id);
// Add the data object to the wrapper
$wrapper.data('uploadify', swfuploadify);
// Create the button
var $button = $('<div />', {
'id' : settings.id + '-button',
'class' : 'uploadify-button ' + settings.buttonClass
});
if (settings.buttonImage) {
$button.css({
'background-image' : "url('" + settings.buttonImage + "')",
'text-indent' : '-9999px'
});
}
$button.html('<span class="uploadify-button-text">' + settings.buttonText + '</span>')
.css({
'height' : settings.height + 'px',
'line-height' : settings.height + 'px',
'width' : settings.width + 'px'
});
// Append the button to the wrapper
$wrapper.append($button);
// Adjust the styles of the movie
$('#' + swfuploadify.movieName).css({
'position' : 'absolute',
'z-index' : 1
});
// Create the file queue
if (!settings.queueID) {
var $queue = $('<div />', {
'id' : settings.id + '-queue',
'class' : 'uploadify-queue'
});
$wrapper.after($queue);
swfuploadify.settings.queueID = settings.id + '-queue';
swfuploadify.settings.defaultQueue = true;
}
// Create some queue related objects and variables
swfuploadify.queueData = {
files : {}, // The files in the queue
filesSelected : 0, // The number of files selected in the last select operation
filesQueued : 0, // The number of files added to the queue in the last select operation
filesReplaced : 0, // The number of files replaced in the last select operation
filesCancelled : 0, // The number of files that were cancelled instead of replaced
filesErrored : 0, // The number of files that caused error in the last select operation
uploadsSuccessful : 0, // The number of files that were successfully uploaded
uploadsErrored : 0, // The number of files that returned errors during upload
averageSpeed : 0, // The average speed of the uploads in KB
queueLength : 0, // The number of files in the queue
queueSize : 0, // The size in bytes of the entire queue
uploadSize : 0, // The size in bytes of the upload queue
queueBytesUploaded : 0, // The size in bytes that have been uploaded for the current upload queue
uploadQueue : [], // The files currently to be uploaded
errorMsg : 'Some files were not added to the queue:'
};
// Save references to all the objects
swfuploadify.original = $clone;
swfuploadify.wrapper = $wrapper;
swfuploadify.button = $button;
swfuploadify.queue = $queue;
// Call the user-defined init event handler
if (settings.onInit) settings.onInit.call($this, swfuploadify);
} else {
// Call the fallback function
if (settings.onFallback) settings.onFallback.call($this);
}
});
},
// Stop a file upload and remove it from the queue
cancel : function(fileID, supressEvent) {
var args = arguments;
this.each(function() {
// Create a reference to the jQuery DOM object
var $this = $(this),
swfuploadify = $this.data('uploadify'),
settings = swfuploadify.settings,
delay = -1;
if (args[0]) {
// Clear the queue
if (args[0] == '*') {
var queueItemCount = swfuploadify.queueData.queueLength;
$('#' + settings.queueID).find('.uploadify-queue-item').each(function() {
delay++;
if (args[1] === true) {
swfuploadify.cancelUpload($(this).attr('id'), false);
} else {
swfuploadify.cancelUpload($(this).attr('id'));
}
$(this).find('.data').removeClass('data').html(' - Cancelled');
$(this).find('.uploadify-progress-bar').remove();
$(this).delay(1000 + 100 * delay).fadeOut(500, function() {
$(this).remove();
});
});
swfuploadify.queueData.queueSize = 0;
swfuploadify.queueData.queueLength = 0;
// Trigger the onClearQueue event
if (settings.onClearQueue) settings.onClearQueue.call($this, queueItemCount);
} else {
for (var n = 0; n < args.length; n++) {
swfuploadify.cancelUpload(args[n]);
$('#' + args[n]).find('.data').removeClass('data').html(' - Cancelled');
$('#' + args[n]).find('.uploadify-progress-bar').remove();
$('#' + args[n]).delay(1000 + 100 * n).fadeOut(500, function() {
$(this).remove();
});
}
}
} else {
var item = $('#' + settings.queueID).find('.uploadify-queue-item').get(0);
$item = $(item);
swfuploadify.cancelUpload($item.attr('id'));
$item.find('.data').removeClass('data').html(' - Cancelled');
$item.find('.uploadify-progress-bar').remove();
$item.delay(1000).fadeOut(500, function() {
$(this).remove();
});
}
});
},
// Revert the DOM object back to its original state
destroy : function() {
this.each(function() {
// Create a reference to the jQuery DOM object
var $this = $(this),
swfuploadify = $this.data('uploadify'),
settings = swfuploadify.settings;
// Destroy the SWF object and
swfuploadify.destroy();
// Destroy the queue
if (settings.defaultQueue) {
$('#' + settings.queueID).remove();
}
// Reload the original DOM element
$('#' + settings.id).replaceWith(swfuploadify.original);
// Call the user-defined event handler
if (settings.onDestroy) settings.onDestroy.call(this);
delete swfuploadify;
});
},
// Disable the select button
disable : function(isDisabled) {
this.each(function() {
// Create a reference to the jQuery DOM object
var $this = $(this),
swfuploadify = $this.data('uploadify'),
settings = swfuploadify.settings;
// Call the user-defined event handlers
if (isDisabled) {
swfuploadify.button.addClass('disabled');
if (settings.onDisable) settings.onDisable.call(this);
} else {
swfuploadify.button.removeClass('disabled');
if (settings.onEnable) settings.onEnable.call(this);
}
// Enable/disable the browse button
swfuploadify.setButtonDisabled(isDisabled);
});
},
// Get or set the settings data
settings : function(name, value, resetObjects) {
var args = arguments;
var returnValue = value;
this.each(function() {
// Create a reference to the jQuery DOM object
var $this = $(this),
swfuploadify = $this.data('uploadify'),
settings = swfuploadify.settings;
if (typeof(args[0]) == 'object') {
for (var n in value) {
setData(n,value[n]);
}
}
if (args.length === 1) {
returnValue = settings[name];
} else {
switch (name) {
case 'uploader':
swfuploadify.setUploadURL(value);
break;
case 'formData':
if (!resetObjects) {
value = $.extend(settings.formData, value);
}
swfuploadify.setPostParams(settings.formData);
break;
case 'method':
if (value == 'get') {
swfuploadify.setUseQueryString(true);
} else {
swfuploadify.setUseQueryString(false);
}
break;
case 'fileObjName':
swfuploadify.setFilePostName(value);
break;
case 'fileTypeExts':
swfuploadify.setFileTypes(value, settings.fileTypeDesc);
break;
case 'fileTypeDesc':
swfuploadify.setFileTypes(settings.fileTypeExts, value);
break;
case 'fileSizeLimit':
swfuploadify.setFileSizeLimit(value);
break;
case 'uploadLimit':
swfuploadify.setFileUploadLimit(value);
break;
case 'queueSizeLimit':
swfuploadify.setFileQueueLimit(value);
break;
case 'buttonImage':
swfuploadify.button.css('background-image', settingValue);
break;
case 'buttonCursor':
if (value == 'arrow') {
swfuploadify.setButtonCursor(SWFUpload.CURSOR.ARROW);
} else {
swfuploadify.setButtonCursor(SWFUpload.CURSOR.HAND);
}
break;
case 'buttonText':
$('#' + settings.id + '-button').find('.uploadify-button-text').html(value);
break;
case 'width':
swfuploadify.setButtonDimensions(value, settings.height);
break;
case 'height':
swfuploadify.setButtonDimensions(settings.width, value);
break;
case 'multi':
if (value) {
swfuploadify.setButtonAction(SWFUpload.BUTTON_ACTION.SELECT_FILES);
} else {
swfuploadify.setButtonAction(SWFUpload.BUTTON_ACTION.SELECT_FILE);
}
break;
}
settings[name] = value;
}
});
if (args.length === 1) {
return returnValue;
}
},
// Stop the current uploads and requeue what is in progress
stop : function() {
this.each(function() {
// Create a reference to the jQuery DOM object
var $this = $(this),
swfuploadify = $this.data('uploadify');
// Reset the queue information
swfuploadify.queueData.averageSpeed = 0;
swfuploadify.queueData.uploadSize = 0;
swfuploadify.queueData.bytesUploaded = 0;
swfuploadify.queueData.uploadQueue = [];
swfuploadify.stopUpload();
});
},
// Start uploading files in the queue
upload : function() {
var args = arguments;
this.each(function() {
// Create a reference to the jQuery DOM object
var $this = $(this),
swfuploadify = $this.data('uploadify');
// Reset the queue information
swfuploadify.queueData.averageSpeed = 0;
swfuploadify.queueData.uploadSize = 0;
swfuploadify.queueData.bytesUploaded = 0;
swfuploadify.queueData.uploadQueue = [];
// Upload the files
if (args[0]) {
if (args[0] == '*') {
swfuploadify.queueData.uploadSize = swfuploadify.queueData.queueSize;
swfuploadify.queueData.uploadQueue.push('*');
swfuploadify.startUpload();
} else {
for (var n = 0; n < args.length; n++) {
swfuploadify.queueData.uploadSize += swfuploadify.queueData.files[args[n]].size;
swfuploadify.queueData.uploadQueue.push(args[n]);
}
swfuploadify.startUpload(swfuploadify.queueData.uploadQueue.shift());
}
} else {
swfuploadify.startUpload();
}
});
}
}
// These functions handle all the events that occur with the file uploader
var handlers = {
// Triggered when the file dialog is opened
onDialogOpen : function() {
// Load the swfupload settings
var settings = this.settings;
// Reset some queue info
this.queueData.errorMsg = 'Some files were not added to the queue:';
this.queueData.filesReplaced = 0;
this.queueData.filesCancelled = 0;
// Call the user-defined event handler
if (settings.onDialogOpen) settings.onDialogOpen.call(this);
},
// Triggered when the browse dialog is closed
onDialogClose : function(filesSelected, filesQueued, queueLength) {
// Load the swfupload settings
var settings = this.settings;
// Update the queue information
this.queueData.filesErrored = filesSelected - filesQueued;
this.queueData.filesSelected = filesSelected;
this.queueData.filesQueued = filesQueued - this.queueData.filesCancelled;
this.queueData.queueLength = queueLength;
// Run the default event handler
if ($.inArray('onDialogClose', settings.overrideEvents) < 0) {
if (this.queueData.filesErrored > 0) {
alert(this.queueData.errorMsg);
}
}
// Call the user-defined event handler
if (settings.onDialogClose) settings.onDialogClose.call(this, this.queueData);
// Upload the files if auto is true
if (settings.auto) $('#' + settings.id).uploadify('upload', '*');
},
// Triggered once for each file added to the queue
onSelect : function(file) {
// Load the swfupload settings
var settings = this.settings;
// Check if a file with the same name exists in the queue
var queuedFile = {};
for (var n in this.queueData.files) {
queuedFile = this.queueData.files[n];
if (queuedFile.uploaded != true && queuedFile.name == file.name) {
var replaceQueueItem = confirm('The file named "' + file.name + '" is already in the queue.\nDo you want to replace the existing item in the queue?');
if (!replaceQueueItem) {
this.cancelUpload(file.id);
this.queueData.filesCancelled++;
return false;
} else {
$('#' + queuedFile.id).remove();
this.cancelUpload(queuedFile.id);
this.queueData.filesReplaced++;
}
}
}
// Get the size of the file
var fileSize = Math.round(file.size / 1024);
var suffix = 'KB';
if (fileSize > 1000) {
fileSize = Math.round(fileSize / 1000);
suffix = 'MB';
}
var fileSizeParts = fileSize.toString().split('.');
fileSize = fileSizeParts[0];
if (fileSizeParts.length > 1) {
fileSize += '.' + fileSizeParts[1].substr(0,2);
}
fileSize += suffix;
// Truncate the filename if it's too long
var fileName = file.name;
if (fileName.length > 25) {
fileName = fileName.substr(0,25) + '...';
}
// Create the file data object
itemData = {
'fileID' : file.id,
'instanceID' : settings.id,
'fileName' : fileName,
'fileSize' : fileSize
}
// Create the file item template
if (settings.itemTemplate == false) {
settings.itemTemplate = '<div id="${fileID}" class="uploadify-queue-item">\
<div class="cancel">\
<a href="javascript:$(\'#${instanceID}\').uploadify(\'cancel\', \'${fileID}\')">X</a>\
</div>\
<span class="fileName">${fileName} (${fileSize})</span><span class="data"></span>\
<div class="uploadify-progress">\
<div class="uploadify-progress-bar"><!--Progress Bar--></div>\
</div>\
</div>';
}
// Run the default event handler
if ($.inArray('onSelect', settings.overrideEvents) < 0) {
// Replace the item data in the template
itemHTML = settings.itemTemplate;
for (var d in itemData) {
itemHTML = itemHTML.replace(new RegExp('\\$\\{' + d + '\\}', 'g'), itemData[d]);
}
// Add the file item to the queue
$('#' + settings.queueID).append(itemHTML);
}
this.queueData.queueSize += file.size;
this.queueData.files[file.id] = file;
// Call the user-defined event handler
if (settings.onSelect) settings.onSelect.apply(this, arguments);
},
// Triggered when a file is not added to the queue
onSelectError : function(file, errorCode, errorMsg) {
// Load the swfupload settings
var settings = this.settings;
// Run the default event handler
if ($.inArray('onSelectError', settings.overrideEvents) < 0) {
switch(errorCode) {
case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
if (settings.queueSizeLimit > errorMsg) {
this.queueData.errorMsg += '\nThe number of files selected exceeds the remaining upload limit (' + errorMsg + ').';
} else {
this.queueData.errorMsg += '\nThe number of files selected exceeds the queue size limit (' + settings.queueSizeLimit + ').';
}
break;
case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
this.queueData.errorMsg += '\nThe file "' + file.name + '" exceeds the size limit (' + settings.fileSizeLimit + ').';
break;
case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
this.queueData.errorMsg += '\nThe file "' + file.name + '" is empty.';
break;
case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
this.queueData.errorMsg += '\nThe file "' + file.name + '" is not an accepted file type (' + settings.fileTypeDesc + ').';
break;
}
}
if (errorCode != SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED) {
delete this.queueData.files[file.id];
}
// Call the user-defined event handler
if (settings.onSelectError) settings.onSelectError.apply(this, arguments);
},
// Triggered when all the files in the queue have been processed
onQueueComplete : function() {
if (this.settings.onQueueComplete) this.settings.onQueueComplete.call(this, this.settings.queueData);
},
// Triggered when a file upload successfully completes
onUploadComplete : function(file) {
// Load the swfupload settings
var settings = this.settings,
swfuploadify = this;
// Check if all the files have completed uploading
var stats = this.getStats();
this.queueData.queueLength = stats.files_queued;
if (this.queueData.uploadQueue[0] == '*') {
if (this.queueData.queueLength > 0) {
this.startUpload();
} else {
this.queueData.uploadQueue = [];
// Call the user-defined event handler for queue complete
if (settings.onQueueComplete) settings.onQueueComplete.call(this, this.queueData);
}
} else {
if (this.queueData.uploadQueue.length > 0) {
this.startUpload(this.queueData.uploadQueue.shift());
} else {
this.queueData.uploadQueue = [];
// Call the user-defined event handler for queue complete
if (settings.onQueueComplete) settings.onQueueComplete.call(this, this.queueData);
}
}
// Call the default event handler
if ($.inArray('onUploadComplete', settings.overrideEvents) < 0) {
if (settings.removeCompleted) {
switch (file.filestatus) {
case SWFUpload.FILE_STATUS.COMPLETE:
setTimeout(function() {
if ($('#' + file.id)) {
swfuploadify.queueData.queueSize -= file.size;
swfuploadify.queueData.queueLength -= 1;
delete swfuploadify.queueData.files[file.id]
$('#' + file.id).fadeOut(500, function() {
$(this).remove();
});
}
}, settings.removeTimeout * 1000);
break;
case SWFUpload.FILE_STATUS.ERROR:
if (!settings.requeueErrors) {
setTimeout(function() {
if ($('#' + file.id)) {
swfuploadify.queueData.queueSize -= file.size;
swfuploadify.queueData.queueLength -= 1;
delete swfuploadify.queueData.files[file.id];
$('#' + file.id).fadeOut(500, function() {
$(this).remove();
});
}
}, settings.removeTimeout * 1000);
}
break;
}
} else {
file.uploaded = true;
}
}
// Call the user-defined event handler
if (settings.onUploadComplete) settings.onUploadComplete.call(this, file);
},
// Triggered when a file upload returns an error
onUploadError : function(file, errorCode, errorMsg) {
// Load the swfupload settings
var settings = this.settings;
// Set the error string
var errorString = 'Error';
switch(errorCode) {
case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
errorString = 'HTTP Error (' + errorMsg + ')';
break;
case SWFUpload.UPLOAD_ERROR.MISSING_UPLOAD_URL:
errorString = 'Missing Upload URL';
break;
case SWFUpload.UPLOAD_ERROR.IO_ERROR:
errorString = 'IO Error';
break;
case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
errorString = 'Security Error';
break;
case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
alert('The upload limit has been reached (' + errorMsg + ').');
errorString = 'Exceeds Upload Limit';
break;
case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
errorString = 'Failed';
break;
case SWFUpload.UPLOAD_ERROR.SPECIFIED_FILE_ID_NOT_FOUND:
break;
case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED:
errorString = 'Validation Error';
break;
case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
errorString = 'Cancelled';
this.queueData.queueSize -= file.size;
this.queueData.queueLength -= 1;
if (file.status == SWFUpload.FILE_STATUS.IN_PROGRESS || $.inArray(file.id, this.queueData.uploadQueue) >= 0) {
this.queueData.uploadSize -= file.size;
}
// Trigger the onCancel event
if (settings.onCancel) settings.onCancel.call(this, file);
delete this.queueData.files[file.id];
break;
case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
errorString = 'Stopped';
break;
}
// Call the default event handler
if ($.inArray('onUploadError', settings.overrideEvents) < 0) {
if (errorCode != SWFUpload.UPLOAD_ERROR.FILE_CANCELLED && errorCode != SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED) {
$('#' + file.id).addClass('uploadify-error');
}
// Reset the progress bar
$('#' + file.id).find('.uploadify-progress-bar').css('width','1px');
// Add the error message to the queue item
if (errorCode != SWFUpload.UPLOAD_ERROR.SPECIFIED_FILE_ID_NOT_FOUND && file.status != SWFUpload.FILE_STATUS.COMPLETE) {
$('#' + file.id).find('.data').html(' - ' + errorString);
}
}
var stats = this.getStats();
this.queueData.uploadsErrored = stats.upload_errors;
// Call the user-defined event handler
if (settings.onUploadError) settings.onUploadError.call(this, file, errorCode, errorMsg, errorString);
},
// Triggered periodically during a file upload
onUploadProgress : function(file, fileBytesLoaded, fileTotalBytes) {
// Load the swfupload settings
var settings = this.settings;
// Setup all the variables
var timer = new Date();
var newTime = timer.getTime();
var lapsedTime = newTime - this.timer;
if (lapsedTime > 500) {
this.timer = newTime;
}
var lapsedBytes = fileBytesLoaded - this.bytesLoaded;
this.bytesLoaded = fileBytesLoaded;
var queueBytesLoaded = this.queueData.queueBytesUploaded + fileBytesLoaded;
var percentage = Math.round(fileBytesLoaded / fileTotalBytes * 100);
// Calculate the average speed
var suffix = 'KB/s';
var mbs = 0;
var kbs = (lapsedBytes / 1024) / (lapsedTime / 1000);
kbs = Math.floor(kbs * 10) / 10;
if (this.queueData.averageSpeed > 0) {
this.queueData.averageSpeed = Math.floor((this.queueData.averageSpeed + kbs) / 2);
} else {
this.queueData.averageSpeed = Math.floor(kbs);
}
if (kbs > 1000) {
mbs = (kbs * .001);
this.queueData.averageSpeed = Math.floor(mbs);
suffix = 'MB/s';
}
// Call the default event handler
if ($.inArray('onUploadProgress', settings.overrideEvents) < 0) {
if (settings.progressData == 'percentage') {
$('#' + file.id).find('.data').html(' - ' + percentage + '%');
} else if (settings.progressData == 'speed' && lapsedTime > 500) {
$('#' + file.id).find('.data').html(' - ' + this.queueData.averageSpeed + suffix);
}
$('#' + file.id).find('.uploadify-progress-bar').css('width', percentage + '%');
}
// Call the user-defined event handler
if (settings.onUploadProgress) settings.onUploadProgress.call(this, file, fileBytesLoaded, fileTotalBytes, queueBytesLoaded, this.queueData.uploadSize);
},
// Triggered right before a file is uploaded
onUploadStart : function(file) {
// Load the swfupload settings
var settings = this.settings;
var timer = new Date();
this.timer = timer.getTime();
this.bytesLoaded = 0;
if (this.queueData.uploadQueue.length == 0) {
this.queueData.uploadSize = file.size;
}
if (settings.checkExisting) {
$.ajax({
type : 'POST',
async : false,
url : settings.checkExisting,
data : {filename: file.name},
success : function(data) {
if (data == 1) {
var overwrite = confirm('A file with the name "' + file.name + '" already exists on the server.\nWould you like to replace the existing file?');
if (!overwrite) {
this.cancelUpload(file.id);
$('#' + file.id).remove();
if (this.queueData.uploadQueue.length > 0 && this.queueData.queueLength > 0) {
if (this.queueData.uploadQueue[0] == '*') {
this.startUpload();
} else {
this.startUpload(this.queueData.uploadQueue.shift());
}
}
}
}
}
});
}
// Call the user-defined event handler
if (settings.onUploadStart) settings.onUploadStart.call(this, file);
},
// Triggered when a file upload returns a successful code
onUploadSuccess : function(file, data, response) {
// Load the swfupload settings
var settings = this.settings;
var stats = this.getStats();
this.queueData.uploadsSuccessful = stats.successful_uploads;
this.queueData.queueBytesUploaded += file.size;
// Call the default event handler
if ($.inArray('onUploadSuccess', settings.overrideEvents) < 0) {
$('#' + file.id).find('.data').html(' - Complete');
}
// Call the user-defined event handler
if (settings.onUploadSuccess) settings.onUploadSuccess.call(this, file, data, response);
}
}
$.fn.uploadify = function(method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error('The method ' + method + ' does not exist in $.uploadify');
}
}
})($); | JavaScript |
/*
* jQuery selectbox plugin
*
* Copyright (c) 2007 Sadri Sahraoui (brainfault.com)
* Licensed under the GPL license and MIT:
* http://www.opensource.org/licenses/GPL-license.php
* http://www.opensource.org/licenses/mit-license.php
*
* The code is inspired from Autocomplete plugin (http://www.dyve.net/jquery/?autocomplete)
*
* Revision: $Id$
* Version: 0.5
*
* Changelog :
* Version 0.5
* - separate css style for current selected element and hover element which solve the highlight issue
* Version 0.4
* - Fix width when the select is in a hidden div @Pawel Maziarz
* - Add a unique id for generated li to avoid conflict with other selects and empty values @Pawel Maziarz
*/
jQuery.fn.extend({
selectbox: function(options) {
return this.each(function() {
new jQuery.SelectBox(this, options);
});
}
});
/* pawel maziarz: work around for ie logging */
if (!window.console) {
var console = {
log: function(msg) {
}
}
}
/* */
jQuery.SelectBox = function(selectobj, options) {
var opt = options || {};
opt.inputClass = opt.inputClass || "selectbox2";
opt.containerClass = opt.containerClass || "selectbox-wrapper2";
opt.hoverClass = opt.hoverClass || "current2";
opt.currentClass = opt.selectedClass || "selected2"
opt.debug = opt.debug || false;
var elm_id = selectobj.id;
var active = -1;
var inFocus = false;
var hasfocus = 0;
//jquery object for select element
var $select = $(selectobj);
// jquery container object
var $container = setupContainer(opt);
//jquery input object
var $input = setupInput(opt);
// hide select and append newly created elements
$select.hide().before($input).before($container);
init();
$input
.click(function(){
if (!inFocus) {
$container.toggle();
}
})
.focus(function(){
if ($container.not(':visible')) {
inFocus = true;
$container.show();
}
})
.keydown(function(event) {
switch(event.keyCode) {
case 38: // up
event.preventDefault();
moveSelect(-1);
break;
case 40: // down
event.preventDefault();
moveSelect(1);
break;
//case 9: // tab
case 13: // return
event.preventDefault(); // seems not working in mac !
$('li.'+opt.hoverClass).trigger('click');
break;
case 27: //escape
hideMe();
break;
}
})
.blur(function() {
if ($container.is(':visible') && hasfocus > 0 ) {
if(opt.debug) console.log('container visible and has focus')
} else {
hideMe();
}
});
function hideMe() {
hasfocus = 0;
$container.hide();
}
function init() {
$container.append(getSelectOptions($input.attr('id'))).hide();
var width = $input.css('width');
$container.width(width);
}
function setupContainer(options) {
var container = document.createElement("div");
$container = $(container);
$container.attr('id', elm_id+'_container');
$container.addClass(options.containerClass);
return $container;
}
function setupInput(options) {
var input = document.createElement("input");
var $input = $(input);
$input.attr("id", elm_id+"_input");
$input.attr("type", "text");
$input.addClass(options.inputClass);
$input.attr("autocomplete", "off");
$input.attr("readonly", "readonly");
$input.attr("tabIndex", $select.attr("tabindex")); // "I" capital is important for ie
return $input;
}
function moveSelect(step) {
var lis = $("li", $container);
if (!lis) return;
active += step;
if (active < 0) {
active = 0;
} else if (active >= lis.size()) {
active = lis.size() - 1;
}
lis.removeClass(opt.hoverClass);
$(lis[active]).addClass(opt.hoverClass);
}
function setCurrent() {
var li = $("li."+opt.currentClass, $container).get(0);
var ar = (''+li.id).split('_');
var el = ar[ar.length-1];
$select.val(el);
$input.val($(li).html());
return true;
}
// select value
function getCurrentSelected() {
return $select.val();
}
// input value
function getCurrentValue() {
return $input.val();
}
function getSelectOptions(parentid) {
var select_options = new Array();
var ul = document.createElement('ul');
$select.children('option').each(function() {
var li = document.createElement('li');
li.setAttribute('id', parentid + '_' + $(this).val());
li.innerHTML = $(this).html();
if ($(this).is(':selected')) {
$input.val($(this).html());
$(li).addClass(opt.currentClass);
}
ul.appendChild(li);
$(li)
.mouseover(function(event) {
hasfocus = 1;
if (opt.debug) console.log('over on : '+this.id);
jQuery(event.target, $container).addClass(opt.hoverClass);
})
.mouseout(function(event) {
hasfocus = -1;
if (opt.debug) console.log('out on : '+this.id);
jQuery(event.target, $container).removeClass(opt.hoverClass);
})
.click(function(event) {
var fl = $('li.'+opt.hoverClass, $container).get(0);
if (opt.debug) console.log('click on :'+this.id);
$('li.'+opt.currentClass).removeClass(opt.currentClass);
$(this).addClass(opt.currentClass);
setCurrent();
hideMe();
});
});
return ul;
}
};
| JavaScript |
/************************
jquery-timepicker
http://jonthornton.github.com/jquery-timepicker/
requires jQuery 1.7+
************************/
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery'], factory);
} else {
// Browser globals
factory(jQuery);
}
}(function ($) {
var _baseDate = _generateBaseDate();
var _ONE_DAY = 86400;
var _defaults = {
className: null,
minTime: null,
maxTime: null,
durationTime: null,
step: 30,
showDuration: false,
timeFormat: 'g:ia',
scrollDefaultNow: false,
scrollDefaultTime: false,
selectOnBlur: false,
forceRoundTime: false,
appendTo: 'body'
};
var _lang = {
decimal: '.',
mins: 'mins',
hr: 'hr',
hrs: 'hrs'
};
var methods =
{
init: function(options)
{
return this.each(function()
{
var self = $(this);
// convert dropdowns to text input
if (self[0].tagName == 'SELECT') {
var attrs = { 'type': 'text', 'value': self.val() };
var raw_attrs = self[0].attributes;
for (var i=0; i < raw_attrs.length; i++) {
attrs[raw_attrs[i].nodeName] = raw_attrs[i].nodeValue;
}
var input = $('<input />', attrs);
self.replaceWith(input);
self = input;
}
var settings = $.extend({}, _defaults);
if (options) {
settings = $.extend(settings, options);
}
if (settings.minTime) {
settings.minTime = _time2int(settings.minTime);
}
if (settings.maxTime) {
settings.maxTime = _time2int(settings.maxTime);
}
if (settings.durationTime) {
settings.durationTime = _time2int(settings.durationTime);
}
if (settings.lang) {
_lang = $.extend(_lang, settings.lang);
}
self.data('timepicker-settings', settings);
self.prop('autocomplete', 'off');
self.on('click.timepicker focus.timepicker', methods.show);
self.on('blur.timepicker', _formatValue);
self.on('keydown.timepicker', _keyhandler);
self.addClass('ui-timepicker-input');
_formatValue.call(self.get(0));
});
},
show: function(e)
{
var self = $(this);
if ('ontouchstart' in document) {
// block the keyboard on mobile devices
self.blur();
}
var list = self.data('timepicker-list');
// check if input is readonly
if (self.prop('readonly')) {
return;
}
// check if list needs to be rendered
if (!list || list.length === 0) {
_render(self);
list = self.data('timepicker-list');
}
// check if a flag was set to close this picker
if (self.hasClass('ui-timepicker-hideme')) {
self.removeClass('ui-timepicker-hideme');
list.hide();
return;
}
if (list.is(':visible')) {
return;
}
// make sure other pickers are hidden
methods.hide();
if ((self.offset().top + self.outerHeight(true) + list.outerHeight()) > $(window).height() + $(window).scrollTop()) {
// position the dropdown on top
list.css({ 'left':(self.offset().left), 'top': self.offset().top - list.outerHeight() });
} else {
// put it under the input
list.css({ 'left':(self.offset().left), 'top': self.offset().top + self.outerHeight() });
}
list.show();
var settings = self.data('timepicker-settings');
// position scrolling
var selected = list.find('.ui-timepicker-selected');
if (!selected.length) {
if (self.val()) {
selected = _findRow(self, list, _time2int(self.val()));
} else if (settings.scrollDefaultNow) {
selected = _findRow(self, list, _time2int(new Date()));
} else if (settings.scrollDefaultTime !== false) {
selected = _findRow(self, list, _time2int(settings.scrollDefaultTime));
}
}
if (selected && selected.length) {
var topOffset = list.scrollTop() + selected.position().top - selected.outerHeight();
list.scrollTop(topOffset);
} else {
list.scrollTop(0);
}
_attachCloseHandler();
self.trigger('showTimepicker');
},
hide: function(e)
{
$('.ui-timepicker-list:visible').each(function() {
var list = $(this);
var self = list.data('timepicker-input');
var settings = self.data('timepicker-settings');
if (settings && settings.selectOnBlur) {
_selectValue(self);
}
list.hide();
self.trigger('hideTimepicker');
});
},
option: function(key, value)
{
var self = $(this);
var settings = self.data('timepicker-settings');
var list = self.data('timepicker-list');
if (typeof key == 'object') {
settings = $.extend(settings, key);
} else if (typeof key == 'string' && typeof value != 'undefined') {
settings[key] = value;
} else if (typeof key == 'string') {
return settings[key];
}
if (settings.minTime) {
settings.minTime = _time2int(settings.minTime);
}
if (settings.maxTime) {
settings.maxTime = _time2int(settings.maxTime);
}
if (settings.durationTime) {
settings.durationTime = _time2int(settings.durationTime);
}
self.data('timepicker-settings', settings);
if (list) {
list.remove();
self.data('timepicker-list', false);
}
},
getSecondsFromMidnight: function()
{
return _time2int($(this).val());
},
getTime: function()
{
return new Date(_baseDate.valueOf() + (_time2int($(this).val())*1000));
},
setTime: function(value)
{
var self = $(this);
var prettyTime = _int2time(_time2int(value), self.data('timepicker-settings').timeFormat);
self.val(prettyTime);
},
remove: function()
{
var self = $(this);
// check if this element is a timepicker
if (!self.hasClass('ui-timepicker-input')) {
return;
}
self.removeAttr('autocomplete', 'off');
self.removeClass('ui-timepicker-input');
self.removeData('timepicker-settings');
self.off('.timepicker');
// timepicker-list won't be present unless the user has interacted with this timepicker
if (self.data('timepicker-list')) {
self.data('timepicker-list').remove();
}
self.removeData('timepicker-list');
}
};
// private methods
function _render(self)
{
var settings = self.data('timepicker-settings');
var list = self.data('timepicker-list');
if (list && list.length) {
list.remove();
self.data('timepicker-list', false);
}
list = $('<ul />', {
'tabindex': -1,
'class': 'ui-timepicker-list'
});
if (settings.className) {
list.addClass(settings.className);
}
list.css({'display':'none', 'position': 'absolute' });
if ((settings.minTime !== null || settings.durationTime !== null) && settings.showDuration) {
list.addClass('ui-timepicker-with-duration');
}
var durStart = (settings.durationTime !== null) ? settings.durationTime : settings.minTime;
var start = (settings.minTime !== null) ? settings.minTime : 0;
var end = (settings.maxTime !== null) ? settings.maxTime : (start + _ONE_DAY - 1);
if (end <= start) {
// make sure the end time is greater than start time, otherwise there will be no list to show
end += _ONE_DAY;
}
for (var i=start; i <= end; i += settings.step*60) {
var timeInt = i%_ONE_DAY;
var row = $('<li />');
row.data('time', timeInt);
row.text(_int2time(timeInt, settings.timeFormat));
if ((settings.minTime !== null || settings.durationTime !== null) && settings.showDuration) {
var duration = $('<span />');
duration.addClass('ui-timepicker-duration');
duration.text(' ('+_int2duration(i - durStart)+')');
row.append(duration);
}
list.append(row);
}
list.data('timepicker-input', self);
self.data('timepicker-list', list);
var appendTo = settings.appendTo;
if (typeof appendTo === 'string') {
appendTo = $(appendTo);
} else if (typeof appendTo === 'function') {
appendTo = appendTo(self);
}
appendTo.append(list);
_setSelected(self, list);
list.on('click', 'li', function(e) {
self.addClass('ui-timepicker-hideme');
self[0].focus();
// make sure only the clicked row is selected
list.find('li').removeClass('ui-timepicker-selected');
$(this).addClass('ui-timepicker-selected');
_selectValue(self);
list.hide();
});
}
function _generateBaseDate()
{
var _baseDate = new Date();
var _currentTimezoneOffset = _baseDate.getTimezoneOffset()*60000;
_baseDate.setHours(0); _baseDate.setMinutes(0); _baseDate.setSeconds(0);
var _baseDateTimezoneOffset = _baseDate.getTimezoneOffset()*60000;
return new Date(_baseDate.valueOf() - _baseDateTimezoneOffset + _currentTimezoneOffset);
}
function _attachCloseHandler()
{
if ('ontouchstart' in document) {
$('body').on('touchstart.ui-timepicker', _closeHandler);
} else {
$('body').on('mousedown.ui-timepicker', _closeHandler);
$(window).on('scroll.ui-timepicker', _closeHandler);
}
}
// event handler to decide whether to close timepicker
function _closeHandler(e)
{
var target = $(e.target);
var input = target.closest('.ui-timepicker-input');
if (input.length === 0 && target.closest('.ui-timepicker-list').length === 0) {
methods.hide();
}
$('body').unbind('.ui-timepicker');
$(window).unbind('.ui-timepicker');
}
function _findRow(self, list, value)
{
if (!value && value !== 0) {
return false;
}
var settings = self.data('timepicker-settings');
var out = false;
var halfStep = settings.step*30;
// loop through the menu items
list.find('li').each(function(i, obj) {
var jObj = $(obj);
var offset = jObj.data('time') - value;
// check if the value is less than half a step from each row
if (Math.abs(offset) < halfStep || offset == halfStep) {
out = jObj;
return false;
}
});
return out;
}
function _setSelected(self, list)
{
var timeValue = _time2int(self.val());
var selected = _findRow(self, list, timeValue);
if (selected) selected.addClass('ui-timepicker-selected');
}
function _formatValue()
{
if (this.value === '') {
return;
}
var self = $(this);
var seconds = _time2int(this.value);
if (seconds === null) {
self.trigger('timeFormatError');
return;
}
var settings = self.data('timepicker-settings');
if (settings.forceRoundTime) {
var offset = seconds % (settings.step*60); // step is in minutes
if (offset >= settings.step*30) {
// if offset is larger than a half step, round up
seconds += (settings.step*60) - offset;
} else {
// round down
seconds -= offset;
}
}
var prettyTime = _int2time(seconds, settings.timeFormat);
self.val(prettyTime);
}
function _keyhandler(e)
{
var self = $(this);
var list = self.data('timepicker-list');
if (!list.is(':visible')) {
if (e.keyCode == 40) {
self.focus();
} else {
return true;
}
}
switch (e.keyCode) {
case 13: // return
_selectValue(self);
methods.hide.apply(this);
e.preventDefault();
return false;
case 38: // up
var selected = list.find('.ui-timepicker-selected');
if (!selected.length) {
list.children().each(function(i, obj) {
if ($(obj).position().top > 0) {
selected = $(obj);
return false;
}
});
selected.addClass('ui-timepicker-selected');
} else if (!selected.is(':first-child')) {
selected.removeClass('ui-timepicker-selected');
selected.prev().addClass('ui-timepicker-selected');
if (selected.prev().position().top < selected.outerHeight()) {
list.scrollTop(list.scrollTop() - selected.outerHeight());
}
}
break;
case 40: // down
selected = list.find('.ui-timepicker-selected');
if (selected.length === 0) {
list.children().each(function(i, obj) {
if ($(obj).position().top > 0) {
selected = $(obj);
return false;
}
});
selected.addClass('ui-timepicker-selected');
} else if (!selected.is(':last-child')) {
selected.removeClass('ui-timepicker-selected');
selected.next().addClass('ui-timepicker-selected');
if (selected.next().position().top + 2*selected.outerHeight() > list.outerHeight()) {
list.scrollTop(list.scrollTop() + selected.outerHeight());
}
}
break;
case 27: // escape
list.find('li').removeClass('ui-timepicker-selected');
list.hide();
break;
case 9: //tab
methods.hide();
break;
case 16:
case 17:
case 18:
case 19:
case 20:
case 33:
case 34:
case 35:
case 36:
case 37:
case 39:
case 45:
return;
default:
list.find('li').removeClass('ui-timepicker-selected');
return;
}
}
function _selectValue(self)
{
var settings = self.data('timepicker-settings');
var list = self.data('timepicker-list');
var timeValue = null;
var cursor = list.find('.ui-timepicker-selected');
if (cursor.length) {
// selected value found
timeValue = cursor.data('time');
} else if (self.val()) {
// no selected value; fall back on input value
timeValue = _time2int(self.val());
_setSelected(self, list);
}
if (timeValue !== null) {
var timeString = _int2time(timeValue, settings.timeFormat);
self.val(timeString);
}
self.trigger('change').trigger('changeTime');
}
function _int2duration(seconds)
{
var minutes = Math.round(seconds/60);
var duration;
if (Math.abs(minutes) < 60) {
duration = [minutes, _lang.mins];
} else if (minutes == 60) {
duration = ['1', _lang.hr];
} else {
var hours = (minutes/60).toFixed(1);
if (_lang.decimal != '.') hours = hours.replace('.', _lang.decimal);
duration = [hours, _lang.hrs];
}
return duration.join(' ');
}
function _int2time(seconds, format)
{
if (seconds === null) {
return;
}
var time = new Date(_baseDate.valueOf() + (seconds*1000));
var output = '';
var hour, code;
for (var i=0; i<format.length; i++) {
code = format.charAt(i);
switch (code) {
case 'a':
output += (time.getHours() > 11) ? 'pm' : 'am';
break;
case 'A':
output += (time.getHours() > 11) ? 'PM' : 'AM';
break;
case 'g':
hour = time.getHours() % 12;
output += (hour === 0) ? '12' : hour;
break;
case 'G':
output += time.getHours();
break;
case 'h':
hour = time.getHours() % 12;
if (hour !== 0 && hour < 10) {
hour = '0'+hour;
}
output += (hour === 0) ? '12' : hour;
break;
case 'H':
hour = time.getHours();
output += (hour > 9) ? hour : '0'+hour;
break;
case 'i':
var minutes = time.getMinutes();
output += (minutes > 9) ? minutes : '0'+minutes;
break;
case 's':
seconds = time.getSeconds();
output += (seconds > 9) ? seconds : '0'+seconds;
break;
default:
output += code;
}
}
return output;
}
function _time2int(timeString)
{
if (timeString === '') return null;
if (timeString+0 == timeString) return timeString;
if (typeof(timeString) == 'object') {
timeString = timeString.getHours()+':'+timeString.getMinutes()+':'+timeString.getSeconds();
}
var d = new Date(0);
var time = timeString.toLowerCase().match(/(\d{1,2})(?::(\d{1,2}))?(?::(\d{2}))?\s*([pa]?)/);
if (!time) {
return null;
}
var hour = parseInt(time[1]*1, 10);
var hours;
if (time[4]) {
if (hour == 12) {
hours = (time[4] == 'p') ? 12 : 0;
} else {
hours = (hour + (time[4] == 'p' ? 12 : 0));
}
} else {
hours = hour;
}
var minutes = ( time[2]*1 || 0 );
var seconds = ( time[3]*1 || 0 );
return hours*3600 + minutes*60 + seconds;
}
// Plugin entry
$.fn.timepicker = function(method)
{
if(methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); }
else if(typeof method === "object" || !method) { return methods.init.apply(this, arguments); }
else { $.error("Method "+ method + " does not exist on jQuery.timepicker"); }
};
}));
| JavaScript |
/************************************************************************
*************************************************************************
@Name : jNotify - jQuery Plugin
@Revison : 2.1
@Date : 18/01/2011
@Author: ALPIXEL (www.myjqueryplugins.com - www.alpixel.fr)
@Support: FF, IE7, IE8, MAC Firefox, MAC Safari
@License : Open Source - MIT License : http://www.opensource.org/licenses/mit-license.php
**************************************************************************
*************************************************************************/
(function($) {
$.jNotify = {
defaults: {
/** VARS - OPTIONS **/
autoHide: true, // Notify box auto-close after 'TimeShown' ms ?
clickOverlay: false, // if 'clickOverlay' = false, close the notice box on the overlay click ?
MinWidth: 200, // min-width CSS property
TimeShown: 1500, // Box shown during 'TimeShown' ms
ShowTimeEffect: 200, // duration of the Show Effect
HideTimeEffect: 200, // duration of the Hide effect
LongTrip: 15, // in pixel, length of the move effect when show and hide
HorizontalPosition: 'center', // left, center, right
VerticalPosition: 'top', // top, center, bottom
ShowOverlay: true, // show overlay behind the notice ?
ColorOverlay: '#000', // color of the overlay
OpacityOverlay: 0.3, // opacity of the overlay
/** METHODS - OPTIONS **/
onClosed: null,
onCompleted: null
},
/*****************/
/** Init Method **/
/*****************/
init: function(msg, options, id) {
opts = $.extend({}, $.jNotify.defaults, options);
/** Box **/
if ($("#" + id).length == 0)
$Div = $.jNotify._construct(id, msg);
// Width of the Brower
WidthDoc = parseInt($(window).width());
HeightDoc = parseInt($(window).height());
// Scroll Position
ScrollTop = parseInt($(window).scrollTop());
ScrollLeft = parseInt($(window).scrollLeft());
// Position of the jNotify Box
posTop = $.jNotify.vPos(opts.VerticalPosition);
posLeft = $.jNotify.hPos(opts.HorizontalPosition);
// Show the jNotify Box
if (opts.ShowOverlay && $("#jOverlay").length == 0)
$.jNotify._showOverlay($Div);
$.jNotify._show(msg);
},
/*******************/
/** Construct DOM **/
/*******************/
_construct: function(id, msg) {
$Div =
$('<div id="' + id + '"/>')
.css({ opacity: 0, minWidth: opts.MinWidth })
.html(msg)
.appendTo('body');
return $Div;
},
/**********************/
/** Postions Methods **/
/**********************/
vPos: function(pos) {
switch (pos) {
case 'top':
var vPos = ScrollTop + parseInt($Div.outerHeight(true) / 2);
break;
case 'center':
var vPos = ScrollTop + (HeightDoc / 2) - (parseInt($Div.outerHeight(true)) / 2);
break;
case 'bottom':
var vPos = ScrollTop + HeightDoc - parseInt($Div.outerHeight(true));
break;
}
return vPos;
},
hPos: function(pos) {
switch (pos) {
case 'left':
var hPos = ScrollLeft;
break;
case 'center':
var hPos = ScrollLeft + (WidthDoc / 2) - (parseInt($Div.outerWidth(true)) / 2);
break;
case 'right':
var hPos = ScrollLeft + WidthDoc - parseInt($Div.outerWidth(true));
break;
}
return hPos;
},
/*********************/
/** Show Div Method **/
/*********************/
_show: function(msg) {
$Div
.css({
top: posTop,
left: posLeft
});
switch (opts.VerticalPosition) {
case 'top':
$Div.animate({
top: posTop + opts.LongTrip,
opacity: 1
}, opts.ShowTimeEffect, function() {
if (opts.onCompleted) opts.onCompleted();
});
if (opts.autoHide)
$.jNotify._close();
else
$Div.css('cursor', 'pointer').click(function(e) {
$.jNotify._close();
});
break;
case 'center':
$Div.animate({
opacity: 1
}, opts.ShowTimeEffect, function() {
if (opts.onCompleted) opts.onCompleted();
});
if (opts.autoHide)
$.jNotify._close();
else
$Div.css('cursor', 'pointer').click(function(e) {
$.jNotify._close();
});
break;
case 'bottom':
$Div.animate({
top: posTop - opts.LongTrip,
opacity: 1
}, opts.ShowTimeEffect, function() {
if (opts.onCompleted) opts.onCompleted();
});
if (opts.autoHide)
$.jNotify._close();
else
$Div.css('cursor', 'pointer').click(function(e) {
$.jNotify._close();
});
break;
}
},
_showOverlay: function(el) {
var overlay =
$('<div id="jOverlay" />')
.css({
backgroundColor: opts.ColorOverlay,
opacity: opts.OpacityOverlay
})
.appendTo('body')
.show();
if (opts.clickOverlay)
overlay.click(function(e) {
e.preventDefault();
opts.TimeShown = 0; // Thanks to Guillaume M.
$.jNotify._close();
});
},
_close: function() {
switch (opts.VerticalPosition) {
case 'top':
if (!opts.autoHide)
opts.TimeShown = 0;
$Div.stop(true, true).delay(opts.TimeShown).animate({ // Tanks to Guillaume M.
top: posTop - opts.LongTrip,
opacity: 0
}, opts.HideTimeEffect, function() {
$(this).remove();
if (opts.ShowOverlay && $("#jOverlay").length > 0)
$("#jOverlay").remove();
if (opts.onClosed) opts.onClosed();
});
break;
case 'center':
if (!opts.autoHide)
opts.TimeShown = 0;
$Div.stop(true, true).delay(opts.TimeShown).animate({ // Tanks to Guillaume M.
opacity: 0
}, opts.HideTimeEffect, function() {
$(this).remove();
if (opts.ShowOverlay && $("#jOverlay").length > 0)
$("#jOverlay").remove();
if (opts.onClosed) opts.onClosed();
});
break;
case 'bottom':
if (!opts.autoHide)
opts.TimeShown = 0;
$Div.stop(true, true).delay(opts.TimeShown).animate({ // Tanks to Guillaume M.
top: posTop + opts.LongTrip,
opacity: 0
}, opts.HideTimeEffect, function() {
$(this).remove();
if (opts.ShowOverlay && $("#jOverlay").length > 0)
$("#jOverlay").remove();
if (opts.onClosed) opts.onClosed();
});
break;
}
},
_isReadable: function(id) {
if ($('#' + id).length > 0)
return false;
else
return true;
}
};
/** Init method **/
jNotify = function(msg, options) {
if ($.jNotify._isReadable('jNotify'))
$.jNotify.init(msg, options, 'jNotify');
};
jSuccess = function(msg, options) {
if ($.jNotify._isReadable('jSuccess'))
$.jNotify.init(msg, options, 'jSuccess');
};
jError = function(msg, options) {
if ($.jNotify._isReadable('jError'))
$.jNotify.init(msg, options, 'jError');
};
})(jQuery); | JavaScript |
/*
* jQuery showLoading plugin v1.0
*
* Copyright (c) 2009 Jim Keller
* Context - http://www.contextllc.com
*
* Dual licensed under the MIT and GPL licenses.
*
*/
jQuery.fn.showLoading = function(options) {
var indicatorID;
var settings = {
'addClass': '',
'beforeShow': '',
'afterShow': '',
'hPos': 'center',
'vPos': 'center',
'indicatorZIndex' : 5001,
'overlayZIndex': 5000,
'parent': '',
'marginTop': 0,
'marginLeft': 0,
'overlayWidth': null,
'overlayHeight': null
};
jQuery.extend(settings, options);
var loadingDiv = jQuery('<div></div>');
var overlayDiv = jQuery('<div></div>');
//
// Set up ID and classes
//
if ( settings.indicatorID ) {
indicatorID = settings.indicatorID;
}
else {
indicatorID = jQuery(this).attr('id');
}
jQuery(loadingDiv).attr('id', 'loading-indicator-' + indicatorID );
jQuery(loadingDiv).addClass('loading-indicator');
if ( settings.addClass ){
jQuery(loadingDiv).addClass(settings.addClass);
}
//
// Create the overlay
//
jQuery(overlayDiv).css('display', 'none');
// Append to body, otherwise position() doesn't work on Webkit-based browsers
jQuery(document.body).append(overlayDiv);
//
// Set overlay classes
//
jQuery(overlayDiv).attr('id', 'loading-indicator-' + indicatorID + '-overlay');
jQuery(overlayDiv).addClass('loading-indicator-overlay');
if ( settings.addClass ){
jQuery(overlayDiv).addClass(settings.addClass + '-overlay');
}
//
// Set overlay position
//
var overlay_width;
var overlay_height;
var border_top_width = jQuery(this).css('border-top-width');
var border_left_width = jQuery(this).css('border-left-width');
//
// IE will return values like 'medium' as the default border,
// but we need a number
//
border_top_width = isNaN(parseInt(border_top_width)) ? 0 : border_top_width;
border_left_width = isNaN(parseInt(border_left_width)) ? 0 : border_left_width;
var overlay_left_pos = jQuery(this).offset().left + parseInt(border_left_width);
var overlay_top_pos = jQuery(this).offset().top + parseInt(border_top_width);
if ( settings.overlayWidth !== null ) {
overlay_width = settings.overlayWidth;
}
else {
overlay_width = parseInt(jQuery(this).width()) + parseInt(jQuery(this).css('padding-right')) + parseInt(jQuery(this).css('padding-left'));
}
if ( settings.overlayHeight !== null ) {
overlay_height = settings.overlayWidth;
}
else {
overlay_height = parseInt(jQuery(this).height()) + parseInt(jQuery(this).css('padding-top')) + parseInt(jQuery(this).css('padding-bottom'));
}
jQuery(overlayDiv).css('width', overlay_width.toString() + 'px');
jQuery(overlayDiv).css('height', overlay_height.toString() + 'px');
jQuery(overlayDiv).css('left', overlay_left_pos.toString() + 'px');
jQuery(overlayDiv).css('position', 'absolute');
jQuery(overlayDiv).css('top', overlay_top_pos.toString() + 'px' );
jQuery(overlayDiv).css('z-index', settings.overlayZIndex);
//
// Set any custom overlay CSS
//
if ( settings.overlayCSS ) {
jQuery(overlayDiv).css ( settings.overlayCSS );
}
//
// We have to append the element to the body first
// or .width() won't work in Webkit-based browsers (e.g. Chrome, Safari)
//
jQuery(loadingDiv).css('display', 'none');
jQuery(document.body).append(loadingDiv);
jQuery(loadingDiv).css('position', 'absolute');
jQuery(loadingDiv).css('z-index', settings.indicatorZIndex);
//
// Set top margin
//
var indicatorTop = overlay_top_pos;
if ( settings.marginTop ) {
indicatorTop += parseInt(settings.marginTop);
}
var indicatorLeft = overlay_left_pos;
if ( settings.marginLeft ) {
indicatorLeft += parseInt(settings.marginTop);
}
//
// set horizontal position
//
if ( settings.hPos.toString().toLowerCase() == 'center' ) {
jQuery(loadingDiv).css('left', (indicatorLeft + ((jQuery(overlayDiv).width() - parseInt(jQuery(loadingDiv).width())) / 2)).toString() + 'px');
}
else if ( settings.hPos.toString().toLowerCase() == 'left' ) {
jQuery(loadingDiv).css('left', (indicatorLeft + parseInt(jQuery(overlayDiv).css('margin-left'))).toString() + 'px');
}
else if ( settings.hPos.toString().toLowerCase() == 'right' ) {
jQuery(loadingDiv).css('left', (indicatorLeft + (jQuery(overlayDiv).width() - parseInt(jQuery(loadingDiv).width()))).toString() + 'px');
}
else {
jQuery(loadingDiv).css('left', (indicatorLeft + parseInt(settings.hPos)).toString() + 'px');
}
//
// set vertical position
//
if ( settings.vPos.toString().toLowerCase() == 'center' ) {
jQuery(loadingDiv).css('top', (indicatorTop + ((jQuery(overlayDiv).height() - parseInt(jQuery(loadingDiv).height())) / 2)).toString() + 'px');
}
else if ( settings.vPos.toString().toLowerCase() == 'top' ) {
jQuery(loadingDiv).css('top', indicatorTop.toString() + 'px');
}
else if ( settings.vPos.toString().toLowerCase() == 'bottom' ) {
jQuery(loadingDiv).css('top', (indicatorTop + (jQuery(overlayDiv).height() - parseInt(jQuery(loadingDiv).height()))).toString() + 'px');
}
else {
jQuery(loadingDiv).css('top', (indicatorTop + parseInt(settings.vPos)).toString() + 'px' );
}
//
// Set any custom css for loading indicator
//
if ( settings.css ) {
jQuery(loadingDiv).css ( settings.css );
}
//
// Set up callback options
//
var callback_options =
{
'overlay': overlayDiv,
'indicator': loadingDiv,
'element': this
};
//
// beforeShow callback
//
if ( typeof(settings.beforeShow) == 'function' ) {
settings.beforeShow( callback_options );
}
//
// Show the overlay
//
jQuery(overlayDiv).show();
//
// Show the loading indicator
//
jQuery(loadingDiv).show();
//
// afterShow callback
//
if ( typeof(settings.afterShow) == 'function' ) {
settings.afterShow( callback_options );
}
return this;
};
jQuery.fn.hideLoading = function(options) {
var settings = {};
jQuery.extend(settings, options);
if ( settings.indicatorID ) {
indicatorID = settings.indicatorID;
}
else {
indicatorID = jQuery(this).attr('id');
}
jQuery(document.body).find('#loading-indicator-' + indicatorID ).remove();
jQuery(document.body).find('#loading-indicator-' + indicatorID + '-overlay' ).remove();
return this;
};
| JavaScript |
//Menu
$(document).ready(function() {
$("ul.sf-menu").supersubs({
minWidth: 12, // minimum width of sub-menus in em units
maxWidth: 27, // maximum width of sub-menus in em units
extraWidth: 1 // extra width can ensure lines don't sometimes turn over
// due to slight rounding differences and font-family
}).superfish(); // call supersubs first, then superfish, so that subs are
// not display:none when measuring. Call before initialising
// containing tabs for same reason.
});
// Change language
function changeLanguage(value, to) {
var url = window.location.href;
if (url.indexOf('/' + value) > 0) {
url = url.replace('/' + value, '/' + to);
}
else {
url = url + to + '/';
}
window.location = url;
}
//// 3 - MESSAGE BOX FADING SCRIPTS ---------------------------------------------------------------------
$(document).ready(function() {
$(".close-yellow").click(function() {
$("#message-yellow").fadeOut("slow");
});
$(".close-red").click(function() {
$("#message-red").fadeOut("slow");
});
$(".close-blue").click(function() {
$("#message-blue").fadeOut("slow");
});
$(".close-green").click(function() {
$("#message-green").fadeOut("slow");
});
});
// END ----------------------------- 3
// 1 - START DROPDOWN SLIDER SCRIPTS ------------------------------------------------------------------------
$(document).ready(function() {
$(".showhide-account").click(function() {
$(".account-content").slideToggle("fast");
$(this).toggleClass("active");
return false;
});
});
$(document).ready(function() {
$(".action-slider").click(function() {
$("#actions-box-slider").slideToggle("fast");
$(this).toggleClass("activated");
return false;
});
});
// END ----------------------------- 1
$(function() {
$.ajaxSetup({ cache: false });
$('#toggle-all').click(function() {
//
if ($(this).attr('class') != "toggle-checked") {
$('#mainform input[type=checkbox]').attr('checked', false);
}
//alert($(this).attr('class'));
$('#mainform input').checkBox();
$('#toggle-all').toggleClass('toggle-checked');
$('#mainform input[type=checkbox]').checkBox('toggle');
return false;
});
$('#mainform input:checkbox:not(#toggle-all)').click(function() {
$('#toggle-all').removeClass('toggle-checked');
});
/* Custom javascripts for listing pages
============================================================*/
//prompt for delete button
$('.remove-btn').click(function(e) {
e.preventDefault(); //prevent default action for anchor
if (confirm("Confirm removed the selected records?")) {
window.location = this.href;
}
});
//prompt for reject button
$('.reject-btn').click(function(e) {
e.preventDefault(); //prevent default action for anchor
if (confirm("Confirm reject the selected Post Property Request?")) {
window.location = this.href;
}
});
//prompt for approve button
$('.approve-btn').click(function(e) {
e.preventDefault(); //prevent default action for anchor
if (confirm("Confirm approving the selected Post Property Request?")) {
window.location = this.href;
}
});
//bulk process action
$('.action-invoke').click(function(e) {
e.preventDefault(); //prevent default action for anchor
//ensure at least one item is checked
var fields = $("input[name='selected']").serializeArray();
if (fields.length == 0) {
alert('Please select at least one item.');
return false;
} else {
//submit form
$(".list_item_form").attr("action",this.href);
$(".list_item_form").submit();
}
});
//Sort by process action
$('.action-sort').click(function(e) {
e.preventDefault(); //prevent default action for anchor
//submit form
$(".list_item_form").attr("action", this.href);
$(".list_item_form").submit();
});
//bulk process action
$('.remove-sidecontent-btn').click(function(e) {
e.preventDefault(); //prevent default action for anchor
//submit form
$("#delete_sidecontent_hook").attr("action", this.href);
$("#delete_sidecontent_hook").submit();
});
//bulk process delete action
$('.action-invoke-removed').click(function(e) {
e.preventDefault(); //prevent default action for anchor
//ensure at least one item is checked
var fields = $("input[name='selected']").serializeArray();
if (fields.length == 0) {
alert('Please select at least one item.');
return false;
} else {
if (confirm("Confirm removed the selected records?")) {
$(".list_item_form").attr("action", this.href);
$(".list_item_form").submit();
}
}
});
//bulk process reject post property request action
$('.action-invoke-rejected').click(function(e) {
e.preventDefault(); //prevent default action for anchor
//ensure at least one item is checked
var fields = $("input[name='selected[]']").serializeArray();
if (fields.length == 0) {
alert('Please select at least one item.');
return false;
} else {
if (confirm("Confirm reject the selected Post Property Request(s)?")) {
$(".list_item_form").attr("action", this.href);
$(".list_item_form").submit();
}
}
});
//bulk process reject post property request action
$('.action-invoke-approved').click(function(e) {
e.preventDefault(); //prevent default action for anchor
//ensure at least one item is checked
var fields = $("input[name='selected[]']").serializeArray();
if (fields.length == 0) {
alert('Please select at least one item.');
return false;
} else {
if (confirm("Confirm approve the selected Post Property Request(s)?")) {
$(".list_item_form").attr("action", this.href);
$(".list_item_form").submit();
}
}
});
});
//Tooltips -->
$(function() {
$('a.info-tooltip ').tooltip({
track: true,
delay: 0,
fixPNG: true,
showURL: false,
showBody: " - ",
top: -35,
left: 5
});
});
function htmlspecialchars(str) {
if (typeof (str) == "string") {
str = str.replace(/&/g, "&");
str = str.replace(/"/g, """);
str = str.replace(/'/g, "’s");
str = str.replace(/</g, "<");
str = str.replace(/>/g, ">");
}
return str;
}
//set up
//Pretty Loader/
//styled select box script version 1
$(document).ready(function() {
$('.styledselect').selectbox({ inputClass: "selectbox_styled" });
//
$('.styledselect_form_2').selectbox({ inputClass: "styledselect_form_2" });
//
$('.styledselect_pages').selectbox({ inputClass: "styledselect_pages" });
}); | JavaScript |
/*
* jQuery Tooltip plugin 1.2
*
* http://bassistance.de/jquery-plugins/jquery-plugin-tooltip/
* http://docs.jquery.com/Plugins/Tooltip
*
* Copyright (c) 2006 - 2008 Jörn Zaefferer
*
* $Id: jquery.tooltip.js 4569 2008-01-31 19:36:35Z joern.zaefferer $
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*/
;(function($) {
// the tooltip element
var helper = {},
// the current tooltipped element
current,
// the title of the current element, used for restoring
title,
// timeout id for delayed tooltips
tID,
// IE 5.5 or 6
IE = $.browser.msie && /MSIE\s(5\.5|6\.)/.test(navigator.userAgent),
// flag for mouse tracking
track = false;
$.tooltip = {
blocked: false,
defaults: {
delay: 200,
showURL: true,
extraClass: "",
top: 15,
left: 15,
id: "tooltip"
},
block: function() {
$.tooltip.blocked = !$.tooltip.blocked;
}
};
$.fn.extend({
tooltip: function(settings) {
settings = $.extend({}, $.tooltip.defaults, settings);
createHelper(settings);
return this.each(function() {
$.data(this, "tooltip-settings", settings);
// copy tooltip into its own expando and remove the title
this.tooltipText = this.title;
$(this).removeAttr("title");
// also remove alt attribute to prevent default tooltip in IE
this.alt = "";
})
.hover(save, hide)
.click(hide);
},
fixPNG: IE ? function() {
return this.each(function () {
var image = $(this).css('backgroundImage');
if (image.match(/^url\(["']?(.*\.png)["']?\)$/i)) {
image = RegExp.$1;
$(this).css({
'backgroundImage': 'none',
'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=crop, src='" + image + "')"
}).each(function () {
var position = $(this).css('position');
if (position != 'absolute' && position != 'relative')
$(this).css('position', 'relative');
});
}
});
} : function() { return this; },
unfixPNG: IE ? function() {
return this.each(function () {
$(this).css({'filter': '', backgroundImage: ''});
});
} : function() { return this; },
hideWhenEmpty: function() {
return this.each(function() {
$(this)[ $(this).html() ? "show" : "hide" ]();
});
},
url: function() {
return this.attr('href') || this.attr('src');
}
});
function createHelper(settings) {
// there can be only one tooltip helper
if( helper.parent )
return;
// create the helper, h3 for title, div for url
helper.parent = $('<div id="' + settings.id + '"><h6></h6><div class="body"></div><div class="url"></div></div>')
// add to document
.appendTo(document.body)
// hide it at first
.hide();
// apply bgiframe if available
if ( $.fn.bgiframe )
helper.parent.bgiframe();
// save references to title and url elements
helper.title = $('h6', helper.parent);
helper.body = $('div.body', helper.parent);
helper.url = $('div.url', helper.parent);
}
function settings(element) {
return $.data(element, "tooltip-settings");
}
// main event handler to start showing tooltips
function handle(event) {
// show helper, either with timeout or on instant
if( settings(this).delay )
tID = setTimeout(show, settings(this).delay);
else
show();
// if selected, update the helper position when the mouse moves
track = !!settings(this).track;
$(document.body).bind('mousemove', update);
// update at least once
update(event);
}
// save elements title before the tooltip is displayed
function save() {
// if this is the current source, or it has no title (occurs with click event), stop
if ( $.tooltip.blocked || this == current || (!this.tooltipText && !settings(this).bodyHandler) )
return;
// save current
current = this;
title = this.tooltipText;
if ( settings(this).bodyHandler ) {
helper.title.hide();
var bodyContent = settings(this).bodyHandler.call(this);
if (bodyContent.nodeType || bodyContent.jquery) {
helper.body.empty().append(bodyContent)
} else {
helper.body.html( bodyContent );
}
helper.body.show();
} else if ( settings(this).showBody ) {
var parts = title.split(settings(this).showBody);
helper.title.html(parts.shift()).show();
helper.body.empty();
for(var i = 0, part; part = parts[i]; i++) {
if(i > 0)
helper.body.append("<br/>");
helper.body.append(part);
}
helper.body.hideWhenEmpty();
} else {
helper.title.html(title).show();
helper.body.hide();
}
// if element has href or src, add and show it, otherwise hide it
if( settings(this).showURL && $(this).url() )
helper.url.html( $(this).url().replace('http://', '') ).show();
else
helper.url.hide();
// add an optional class for this tip
helper.parent.addClass(settings(this).extraClass);
// fix PNG background for IE
if (settings(this).fixPNG )
helper.parent.fixPNG();
handle.apply(this, arguments);
}
// delete timeout and show helper
function show() {
tID = null;
helper.parent.show();
update();
}
/**
* callback for mousemove
* updates the helper position
* removes itself when no current element
*/
function update(event) {
if($.tooltip.blocked)
return;
// stop updating when tracking is disabled and the tooltip is visible
if ( !track && helper.parent.is(":visible")) {
$(document.body).unbind('mousemove', update)
}
// if no current element is available, remove this listener
if( current == null ) {
$(document.body).unbind('mousemove', update);
return;
}
// remove position helper classes
helper.parent.removeClass("viewport-right").removeClass("viewport-bottom");
var left = helper.parent[0].offsetLeft;
var top = helper.parent[0].offsetTop;
if(event) {
// position the helper 15 pixel to bottom right, starting from mouse position
left = event.pageX + settings(current).left;
top = event.pageY + settings(current).top;
helper.parent.css({
left: left + 'px',
top: top + 'px'
});
}
var v = viewport(),
h = helper.parent[0];
// check horizontal position
if(v.x + v.cx < h.offsetLeft + h.offsetWidth) {
left -= h.offsetWidth + 20 + settings(current).left;
helper.parent.css({left: left + 'px'}).addClass("viewport-right");
}
// check vertical position
if(v.y + v.cy < h.offsetTop + h.offsetHeight) {
top -= h.offsetHeight + 20 + settings(current).top;
helper.parent.css({top: top + 'px'}).addClass("viewport-bottom");
}
}
function viewport() {
return {
x: $(window).scrollLeft(),
y: $(window).scrollTop(),
cx: $(window).width(),
cy: $(window).height()
};
}
// hide helper and restore added classes and the title
function hide(event) {
if($.tooltip.blocked)
return;
// clear timeout if possible
if(tID)
clearTimeout(tID);
// no more current element
current = null;
helper.parent.hide().removeClass( settings(this).extraClass );
if( settings(this).fixPNG )
helper.parent.unfixPNG();
}
$.fn.Tooltip = $.fn.tooltip;
})(jQuery);
| JavaScript |
/*! Copyright (c) 2011 Brandon Aaron (http://brandonaaron.net)
* Licensed under the MIT License (LICENSE.txt).
*
* Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
* Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
* Thanks to: Seamus Leahy for adding deltaX and deltaY
*
* Version: 3.0.6
*
* Requires: 1.2.2+
*/
(function(d){function e(a){var b=a||window.event,c=[].slice.call(arguments,1),f=0,e=0,g=0,a=d.event.fix(b);a.type="mousewheel";b.wheelDelta&&(f=b.wheelDelta/120);b.detail&&(f=-b.detail/3);g=f;b.axis!==void 0&&b.axis===b.HORIZONTAL_AXIS&&(g=0,e=-1*f);b.wheelDeltaY!==void 0&&(g=b.wheelDeltaY/120);b.wheelDeltaX!==void 0&&(e=-1*b.wheelDeltaX/120);c.unshift(a,f,e,g);return(d.event.dispatch||d.event.handle).apply(this,c)}var c=["DOMMouseScroll","mousewheel"];if(d.event.fixHooks)for(var h=c.length;h;)d.event.fixHooks[c[--h]]=
d.event.mouseHooks;d.event.special.mousewheel={setup:function(){if(this.addEventListener)for(var a=c.length;a;)this.addEventListener(c[--a],e,false);else this.onmousewheel=e},teardown:function(){if(this.removeEventListener)for(var a=c.length;a;)this.removeEventListener(c[--a],e,false);else this.onmousewheel=null}};d.fn.extend({mousewheel:function(a){return a?this.bind("mousewheel",a):this.trigger("mousewheel")},unmousewheel:function(a){return this.unbind("mousewheel",a)}})})(jQuery); | JavaScript |
/*!
* jQuery Templates Plugin 1.0.0pre
* http://github.com/jquery/jquery-tmpl
* Requires jQuery 1.4.2
*
* Copyright Software Freedom Conservancy, Inc.
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*/
(function( jQuery, undefined ){
var oldManip = jQuery.fn.domManip, tmplItmAtt = "_tmplitem", htmlExpr = /^[^<]*(<[\w\W]+>)[^>]*$|\{\{\! /,
newTmplItems = {}, wrappedItems = {}, appendToTmplItems, topTmplItem = { key: 0, data: {} }, itemKey = 0, cloneIndex = 0, stack = [];
function newTmplItem( options, parentItem, fn, data ) {
// Returns a template item data structure for a new rendered instance of a template (a 'template item').
// The content field is a hierarchical array of strings and nested items (to be
// removed and replaced by nodes field of dom elements, once inserted in DOM).
var newItem = {
data: data || (data === 0 || data === false) ? data : (parentItem ? parentItem.data : {}),
_wrap: parentItem ? parentItem._wrap : null,
tmpl: null,
parent: parentItem || null,
nodes: [],
calls: tiCalls,
nest: tiNest,
wrap: tiWrap,
html: tiHtml,
update: tiUpdate
};
if ( options ) {
jQuery.extend( newItem, options, { nodes: [], parent: parentItem });
}
if ( fn ) {
// Build the hierarchical content to be used during insertion into DOM
newItem.tmpl = fn;
newItem._ctnt = newItem._ctnt || newItem.tmpl( jQuery, newItem );
newItem.key = ++itemKey;
// Keep track of new template item, until it is stored as jQuery Data on DOM element
(stack.length ? wrappedItems : newTmplItems)[itemKey] = newItem;
}
return newItem;
}
// Override appendTo etc., in order to provide support for targeting multiple elements. (This code would disappear if integrated in jquery core).
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var ret = [], insert = jQuery( selector ), elems, i, l, tmplItems,
parent = this.length === 1 && this[0].parentNode;
appendToTmplItems = newTmplItems || {};
if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) {
insert[ original ]( this[0] );
ret = this;
} else {
for ( i = 0, l = insert.length; i < l; i++ ) {
cloneIndex = i;
elems = (i > 0 ? this.clone(true) : this).get();
jQuery( insert[i] )[ original ]( elems );
ret = ret.concat( elems );
}
cloneIndex = 0;
ret = this.pushStack( ret, name, insert.selector );
}
tmplItems = appendToTmplItems;
appendToTmplItems = null;
jQuery.tmpl.complete( tmplItems );
return ret;
};
});
jQuery.fn.extend({
// Use first wrapped element as template markup.
// Return wrapped set of template items, obtained by rendering template against data.
tmpl: function( data, options, parentItem ) {
return jQuery.tmpl( this[0], data, options, parentItem );
},
// Find which rendered template item the first wrapped DOM element belongs to
tmplItem: function() {
return jQuery.tmplItem( this[0] );
},
// Consider the first wrapped element as a template declaration, and get the compiled template or store it as a named template.
template: function( name ) {
return jQuery.template( name, this[0] );
},
domManip: function( args, table, callback, options ) {
if ( args[0] && jQuery.isArray( args[0] )) {
var dmArgs = jQuery.makeArray( arguments ), elems = args[0], elemsLength = elems.length, i = 0, tmplItem;
while ( i < elemsLength && !(tmplItem = jQuery.data( elems[i++], "tmplItem" ))) {}
if ( tmplItem && cloneIndex ) {
dmArgs[2] = function( fragClone ) {
// Handler called by oldManip when rendered template has been inserted into DOM.
jQuery.tmpl.afterManip( this, fragClone, callback );
};
}
oldManip.apply( this, dmArgs );
} else {
oldManip.apply( this, arguments );
}
cloneIndex = 0;
if ( !appendToTmplItems ) {
jQuery.tmpl.complete( newTmplItems );
}
return this;
}
});
jQuery.extend({
// Return wrapped set of template items, obtained by rendering template against data.
tmpl: function( tmpl, data, options, parentItem ) {
var ret, topLevel = !parentItem;
if ( topLevel ) {
// This is a top-level tmpl call (not from a nested template using {{tmpl}})
parentItem = topTmplItem;
tmpl = jQuery.template[tmpl] || jQuery.template( null, tmpl );
wrappedItems = {}; // Any wrapped items will be rebuilt, since this is top level
} else if ( !tmpl ) {
// The template item is already associated with DOM - this is a refresh.
// Re-evaluate rendered template for the parentItem
tmpl = parentItem.tmpl;
newTmplItems[parentItem.key] = parentItem;
parentItem.nodes = [];
if ( parentItem.wrapped ) {
updateWrapped( parentItem, parentItem.wrapped );
}
// Rebuild, without creating a new template item
return jQuery( build( parentItem, null, parentItem.tmpl( jQuery, parentItem ) ));
}
if ( !tmpl ) {
return []; // Could throw...
}
if ( typeof data === "function" ) {
data = data.call( parentItem || {} );
}
if ( options && options.wrapped ) {
updateWrapped( options, options.wrapped );
}
ret = jQuery.isArray( data ) ?
jQuery.map( data, function( dataItem ) {
return dataItem ? newTmplItem( options, parentItem, tmpl, dataItem ) : null;
}) :
[ newTmplItem( options, parentItem, tmpl, data ) ];
return topLevel ? jQuery( build( parentItem, null, ret ) ) : ret;
},
// Return rendered template item for an element.
tmplItem: function( elem ) {
var tmplItem;
if ( elem instanceof jQuery ) {
elem = elem[0];
}
while ( elem && elem.nodeType === 1 && !(tmplItem = jQuery.data( elem, "tmplItem" )) && (elem = elem.parentNode) ) {}
return tmplItem || topTmplItem;
},
// Set:
// Use $.template( name, tmpl ) to cache a named template,
// where tmpl is a template string, a script element or a jQuery instance wrapping a script element, etc.
// Use $( "selector" ).template( name ) to provide access by name to a script block template declaration.
// Get:
// Use $.template( name ) to access a cached template.
// Also $( selectorToScriptBlock ).template(), or $.template( null, templateString )
// will return the compiled template, without adding a name reference.
// If templateString includes at least one HTML tag, $.template( templateString ) is equivalent
// to $.template( null, templateString )
template: function( name, tmpl ) {
if (tmpl) {
// Compile template and associate with name
if ( typeof tmpl === "string" ) {
// This is an HTML string being passed directly in.
tmpl = buildTmplFn( tmpl )
} else if ( tmpl instanceof jQuery ) {
tmpl = tmpl[0] || {};
}
if ( tmpl.nodeType ) {
// If this is a template block, use cached copy, or generate tmpl function and cache.
tmpl = jQuery.data( tmpl, "tmpl" ) || jQuery.data( tmpl, "tmpl", buildTmplFn( tmpl.innerHTML ));
// Issue: In IE, if the container element is not a script block, the innerHTML will remove quotes from attribute values whenever the value does not include white space.
// This means that foo="${x}" will not work if the value of x includes white space: foo="${x}" -> foo=value of x.
// To correct this, include space in tag: foo="${ x }" -> foo="value of x"
}
return typeof name === "string" ? (jQuery.template[name] = tmpl) : tmpl;
}
// Return named compiled template
return name ? (typeof name !== "string" ? jQuery.template( null, name ):
(jQuery.template[name] ||
// If not in map, and not containing at least on HTML tag, treat as a selector.
// (If integrated with core, use quickExpr.exec)
jQuery.template( null, htmlExpr.test( name ) ? name : jQuery( name )))) : null;
},
encode: function( text ) {
// Do HTML encoding replacing < > & and ' and " by corresponding entities.
return ("" + text).split("<").join("<").split(">").join(">").split('"').join(""").split("'").join("'");
}
});
jQuery.extend( jQuery.tmpl, {
tag: {
"tmpl": {
_default: { $2: "null" },
open: "if($notnull_1){__=__.concat($item.nest($1,$2));}"
// tmpl target parameter can be of type function, so use $1, not $1a (so not auto detection of functions)
// This means that {{tmpl foo}} treats foo as a template (which IS a function).
// Explicit parens can be used if foo is a function that returns a template: {{tmpl foo()}}.
},
"wrap": {
_default: { $2: "null" },
open: "$item.calls(__,$1,$2);__=[];",
close: "call=$item.calls();__=call._.concat($item.wrap(call,__));"
},
"each": {
_default: { $2: "$index, $value" },
open: "if($notnull_1){$.each($1a,function($2){with(this){",
close: "}});}"
},
"if": {
open: "if(($notnull_1) && $1a){",
close: "}"
},
"else": {
_default: { $1: "true" },
open: "}else if(($notnull_1) && $1a){"
},
"html": {
// Unecoded expression evaluation.
open: "if($notnull_1){__.push($1a);}"
},
"=": {
// Encoded expression evaluation. Abbreviated form is ${}.
_default: { $1: "$data" },
open: "if($notnull_1){__.push($.encode($1a));}"
},
"!": {
// Comment tag. Skipped by parser
open: ""
}
},
// This stub can be overridden, e.g. in jquery.tmplPlus for providing rendered events
complete: function( items ) {
newTmplItems = {};
},
// Call this from code which overrides domManip, or equivalent
// Manage cloning/storing template items etc.
afterManip: function afterManip( elem, fragClone, callback ) {
// Provides cloned fragment ready for fixup prior to and after insertion into DOM
var content = fragClone.nodeType === 11 ?
jQuery.makeArray(fragClone.childNodes) :
fragClone.nodeType === 1 ? [fragClone] : [];
// Return fragment to original caller (e.g. append) for DOM insertion
callback.call( elem, fragClone );
// Fragment has been inserted:- Add inserted nodes to tmplItem data structure. Replace inserted element annotations by jQuery.data.
storeTmplItems( content );
cloneIndex++;
}
});
//========================== Private helper functions, used by code above ==========================
function build( tmplItem, nested, content ) {
// Convert hierarchical content into flat string array
// and finally return array of fragments ready for DOM insertion
var frag, ret = content ? jQuery.map( content, function( item ) {
return (typeof item === "string") ?
// Insert template item annotations, to be converted to jQuery.data( "tmplItem" ) when elems are inserted into DOM.
(tmplItem.key ? item.replace( /(<\w+)(?=[\s>])(?![^>]*_tmplitem)([^>]*)/g, "$1 " + tmplItmAtt + "=\"" + tmplItem.key + "\" $2" ) : item) :
// This is a child template item. Build nested template.
build( item, tmplItem, item._ctnt );
}) :
// If content is not defined, insert tmplItem directly. Not a template item. May be a string, or a string array, e.g. from {{html $item.html()}}.
tmplItem;
if ( nested ) {
return ret;
}
// top-level template
ret = ret.join("");
// Support templates which have initial or final text nodes, or consist only of text
// Also support HTML entities within the HTML markup.
ret.replace( /^\s*([^<\s][^<]*)?(<[\w\W]+>)([^>]*[^>\s])?\s*$/, function( all, before, middle, after) {
frag = jQuery( middle ).get();
storeTmplItems( frag );
if ( before ) {
frag = unencode( before ).concat(frag);
}
if ( after ) {
frag = frag.concat(unencode( after ));
}
});
return frag ? frag : unencode( ret );
}
function unencode( text ) {
// Use createElement, since createTextNode will not render HTML entities correctly
var el = document.createElement( "div" );
el.innerHTML = text;
return jQuery.makeArray(el.childNodes);
}
// Generate a reusable function that will serve to render a template against data
function buildTmplFn( markup ) {
return new Function("jQuery","$item",
// Use the variable __ to hold a string array while building the compiled template. (See https://github.com/jquery/jquery-tmpl/issues#issue/10).
"var $=jQuery,call,__=[],$data=$item.data;" +
// Introduce the data as local variables using with(){}
"with($data){__.push('" +
// Convert the template into pure JavaScript
jQuery.trim(markup)
.replace( /([\\'])/g, "\\$1" )
.replace( /[\r\t\n]/g, " " )
.replace( /\$\{([^\}]*)\}/g, "{{= $1}}" )
.replace( /\{\{(\/?)(\w+|.)(?:\(((?:[^\}]|\}(?!\}))*?)?\))?(?:\s+(.*?)?)?(\(((?:[^\}]|\}(?!\}))*?)\))?\s*\}\}/g,
function( all, slash, type, fnargs, target, parens, args ) {
var tag = jQuery.tmpl.tag[ type ], def, expr, exprAutoFnDetect;
if ( !tag ) {
throw "Unknown template tag: " + type;
}
def = tag._default || [];
if ( parens && !/\w$/.test(target)) {
target += parens;
parens = "";
}
if ( target ) {
target = unescape( target );
args = args ? ("," + unescape( args ) + ")") : (parens ? ")" : "");
// Support for target being things like a.toLowerCase();
// In that case don't call with template item as 'this' pointer. Just evaluate...
expr = parens ? (target.indexOf(".") > -1 ? target + unescape( parens ) : ("(" + target + ").call($item" + args)) : target;
exprAutoFnDetect = parens ? expr : "(typeof(" + target + ")==='function'?(" + target + ").call($item):(" + target + "))";
} else {
exprAutoFnDetect = expr = def.$1 || "null";
}
fnargs = unescape( fnargs );
return "');" +
tag[ slash ? "close" : "open" ]
.split( "$notnull_1" ).join( target ? "typeof(" + target + ")!=='undefined' && (" + target + ")!=null" : "true" )
.split( "$1a" ).join( exprAutoFnDetect )
.split( "$1" ).join( expr )
.split( "$2" ).join( fnargs || def.$2 || "" ) +
"__.push('";
}) +
"');}return __;"
);
}
function updateWrapped( options, wrapped ) {
// Build the wrapped content.
options._wrap = build( options, true,
// Suport imperative scenario in which options.wrapped can be set to a selector or an HTML string.
jQuery.isArray( wrapped ) ? wrapped : [htmlExpr.test( wrapped ) ? wrapped : jQuery( wrapped ).html()]
).join("");
}
function unescape( args ) {
return args ? args.replace( /\\'/g, "'").replace(/\\\\/g, "\\" ) : null;
}
function outerHtml( elem ) {
var div = document.createElement("div");
div.appendChild( elem.cloneNode(true) );
return div.innerHTML;
}
// Store template items in jQuery.data(), ensuring a unique tmplItem data data structure for each rendered template instance.
function storeTmplItems( content ) {
var keySuffix = "_" + cloneIndex, elem, elems, newClonedItems = {}, i, l, m;
for ( i = 0, l = content.length; i < l; i++ ) {
if ( (elem = content[i]).nodeType !== 1 ) {
continue;
}
elems = elem.getElementsByTagName("*");
for ( m = elems.length - 1; m >= 0; m-- ) {
processItemKey( elems[m] );
}
processItemKey( elem );
}
function processItemKey( el ) {
var pntKey, pntNode = el, pntItem, tmplItem, key;
// Ensure that each rendered template inserted into the DOM has its own template item,
if ( (key = el.getAttribute( tmplItmAtt ))) {
while ( pntNode.parentNode && (pntNode = pntNode.parentNode).nodeType === 1 && !(pntKey = pntNode.getAttribute( tmplItmAtt ))) { }
if ( pntKey !== key ) {
// The next ancestor with a _tmplitem expando is on a different key than this one.
// So this is a top-level element within this template item
// Set pntNode to the key of the parentNode, or to 0 if pntNode.parentNode is null, or pntNode is a fragment.
pntNode = pntNode.parentNode ? (pntNode.nodeType === 11 ? 0 : (pntNode.getAttribute( tmplItmAtt ) || 0)) : 0;
if ( !(tmplItem = newTmplItems[key]) ) {
// The item is for wrapped content, and was copied from the temporary parent wrappedItem.
tmplItem = wrappedItems[key];
tmplItem = newTmplItem( tmplItem, newTmplItems[pntNode]||wrappedItems[pntNode] );
tmplItem.key = ++itemKey;
newTmplItems[itemKey] = tmplItem;
}
if ( cloneIndex ) {
cloneTmplItem( key );
}
}
el.removeAttribute( tmplItmAtt );
} else if ( cloneIndex && (tmplItem = jQuery.data( el, "tmplItem" )) ) {
// This was a rendered element, cloned during append or appendTo etc.
// TmplItem stored in jQuery data has already been cloned in cloneCopyEvent. We must replace it with a fresh cloned tmplItem.
cloneTmplItem( tmplItem.key );
newTmplItems[tmplItem.key] = tmplItem;
pntNode = jQuery.data( el.parentNode, "tmplItem" );
pntNode = pntNode ? pntNode.key : 0;
}
if ( tmplItem ) {
pntItem = tmplItem;
// Find the template item of the parent element.
// (Using !=, not !==, since pntItem.key is number, and pntNode may be a string)
while ( pntItem && pntItem.key != pntNode ) {
// Add this element as a top-level node for this rendered template item, as well as for any
// ancestor items between this item and the item of its parent element
pntItem.nodes.push( el );
pntItem = pntItem.parent;
}
// Delete content built during rendering - reduce API surface area and memory use, and avoid exposing of stale data after rendering...
delete tmplItem._ctnt;
delete tmplItem._wrap;
// Store template item as jQuery data on the element
jQuery.data( el, "tmplItem", tmplItem );
}
function cloneTmplItem( key ) {
key = key + keySuffix;
tmplItem = newClonedItems[key] =
(newClonedItems[key] || newTmplItem( tmplItem, newTmplItems[tmplItem.parent.key + keySuffix] || tmplItem.parent ));
}
}
}
//---- Helper functions for template item ----
function tiCalls( content, tmpl, data, options ) {
if ( !content ) {
return stack.pop();
}
stack.push({ _: content, tmpl: tmpl, item:this, data: data, options: options });
}
function tiNest( tmpl, data, options ) {
// nested template, using {{tmpl}} tag
return jQuery.tmpl( jQuery.template( tmpl ), data, options, this );
}
function tiWrap( call, wrapped ) {
// nested template, using {{wrap}} tag
var options = call.options || {};
options.wrapped = wrapped;
// Apply the template, which may incorporate wrapped content,
return jQuery.tmpl( jQuery.template( call.tmpl ), call.data, options, call.item );
}
function tiHtml( filter, textOnly ) {
var wrapped = this._wrap;
return jQuery.map(
jQuery( jQuery.isArray( wrapped ) ? wrapped.join("") : wrapped ).filter( filter || "*" ),
function(e) {
return textOnly ?
e.innerText || e.textContent :
e.outerHTML || outerHtml(e);
});
}
function tiUpdate() {
var coll = this.nodes;
jQuery.tmpl( null, null, null, this).insertBefore( coll[0] );
jQuery( coll ).remove();
}
})( jQuery );
| JavaScript |
/*
* Inline Form Validation Engine 2.6, jQuery plugin
*
* Copyright(c) 2010, Cedric Dugas
* http://www.position-absolute.com
*
* 2.0 Rewrite by Olivier Refalo
* http://www.crionics.com
*
* Form validation engine allowing custom regex rules to be added.
* Licensed under the MIT License
*/
(function($) {
"use strict";
var methods = {
/**
* Kind of the constructor, called before any action
* @param {Map} user options
*/
init: function(options) {
var form = this;
if (!form.data('jqv') || form.data('jqv') == null) {
options = methods._saveOptions(form, options);
// bind all formError elements to close on click
$(".formError").live("click", function() {
$(this).fadeOut(150, function() {
// remove prompt once invisible
$(this).parent('.formErrorOuter').remove();
$(this).remove();
});
});
}
return this;
},
/**
* Attachs jQuery.validationEngine to form.submit and field.blur events
* Takes an optional params: a list of options
* ie. jQuery("#formID1").validationEngine('attach', {promptPosition : "centerRight"});
*/
attach: function(userOptions) {
if (!$(this).is("form")) {
alert("Sorry, jqv.attach() only applies to a form");
return this;
}
var form = this;
var options;
if (userOptions)
options = methods._saveOptions(form, userOptions);
else
options = form.data('jqv');
options.validateAttribute = (form.find("[data-validation-engine*=validate]").length) ? "data-validation-engine" : "class";
if (options.binded) {
// bind fields
form.find("[" + options.validateAttribute + "*=validate]").not("[type=checkbox]").not("[type=radio]").not(".datepicker").bind(options.validationEventTrigger, methods._onFieldEvent);
form.find("[" + options.validateAttribute + "*=validate][type=checkbox],[" + options.validateAttribute + "*=validate][type=radio]").bind("click", methods._onFieldEvent);
form.find("[" + options.validateAttribute + "*=validate][class*=datepicker]").bind(options.validationEventTrigger, { "delay": 300 }, methods._onFieldEvent);
}
if (options.autoPositionUpdate) {
$(window).bind("resize", {
"noAnimation": true,
"formElem": form
}, methods.updatePromptsPosition);
}
// bind form.submit
form.bind("submit", methods._onSubmitEvent);
return this;
},
/**
* Unregisters any bindings that may point to jQuery.validaitonEngine
*/
detach: function() {
if (!$(this).is("form")) {
alert("Sorry, jqv.detach() only applies to a form");
return this;
}
var form = this;
var options = form.data('jqv');
// unbind fields
form.find("[" + options.validateAttribute + "*=validate]").not("[type=checkbox]").unbind(options.validationEventTrigger, methods._onFieldEvent);
form.find("[" + options.validateAttribute + "*=validate][type=checkbox],[class*=validate][type=radio]").unbind("click", methods._onFieldEvent);
// unbind form.submit
form.unbind("submit", methods.onAjaxFormComplete);
// unbind live fields (kill)
form.find("[" + options.validateAttribute + "*=validate]").not("[type=checkbox]").die(options.validationEventTrigger, methods._onFieldEvent);
form.find("[" + options.validateAttribute + "*=validate][type=checkbox]").die("click", methods._onFieldEvent);
// unbind form.submit
form.die("submit", methods.onAjaxFormComplete);
form.removeData('jqv');
if (options.autoPositionUpdate)
$(window).unbind("resize", methods.updatePromptsPosition);
return this;
},
/**
* Validates either a form or a list of fields, shows prompts accordingly.
* Note: There is no ajax form validation with this method, only field ajax validation are evaluated
*
* @return true if the form validates, false if it fails
*/
validate: function() {
var element = $(this);
var valid = null;
if (element.is("form") && !element.hasClass('validating')) {
element.addClass('validating');
var options = element.data('jqv');
valid = methods._validateFields(this);
// If the form doesn't validate, clear the 'validating' class before the user has a chance to submit again
setTimeout(function() {
element.removeClass('validating');
}, 100);
if (valid && options.onFormSuccess) {
options.onFormSuccess();
} else if (!valid && options.onFormFailure) {
options.onFormFailure();
}
} else if (element.is('form')) {
element.removeClass('validating');
} else {
// field validation
var form = element.closest('form');
var options = form.data('jqv');
valid = methods._validateField(element, options);
if (valid && options.onFieldSuccess)
options.onFieldSuccess();
else if (options.onFieldFailure && options.InvalidFields.length > 0) {
options.onFieldFailure();
}
}
return valid;
},
/**
* Redraw prompts position, useful when you change the DOM state when validating
*/
updatePromptsPosition: function(event) {
if (event && this == window) {
var form = event.data.formElem;
var noAnimation = event.data.noAnimation;
}
else
var form = $(this.closest('form'));
var options = form.data('jqv');
// No option, take default one
form.find('[' + options.validateAttribute + '*=validate]').not(":disabled").each(function() {
var field = $(this);
if (options.prettySelect && field.is(":hidden"))
field = form.find("#" + options.usePrefix + field.attr('id') + options.useSuffix);
var prompt = methods._getPrompt(field);
var promptText = $(prompt).find(".formErrorContent").html();
if (prompt)
methods._updatePrompt(field, $(prompt), promptText, undefined, false, options, noAnimation);
});
return this;
},
/**
* Displays a prompt on a element.
* Note that the element needs an id!
*
* @param {String} promptText html text to display type
* @param {String} type the type of bubble: 'pass' (green), 'load' (black) anything else (red)
* @param {String} possible values topLeft, topRight, bottomLeft, centerRight, bottomRight
*/
showPrompt: function(promptText, type, promptPosition, showArrow) {
var form = this.closest('form');
var options = form.data('jqv');
// No option, take default one
if (!options)
options = methods._saveOptions(this, options);
if (promptPosition)
options.promptPosition = promptPosition;
options.showArrow = showArrow == true;
methods._showPrompt(this, promptText, type, false, options);
return this;
},
/**
* Closes form error prompts, CAN be invidual
*/
hide: function() {
var form = $(this).closest('form');
var options = form.data('jqv');
var fadeDuration = (options && options.fadeDuration) ? options.fadeDuration : 0.3;
var closingtag;
if ($(this).is("form")) {
closingtag = "parentForm" + methods._getClassName($(this).attr("id"));
} else {
closingtag = methods._getClassName($(this).attr("id")) + "formError";
}
$('.' + closingtag).fadeTo(fadeDuration, 0.3, function() {
$(this).parent('.formErrorOuter').remove();
$(this).remove();
});
return this;
},
/**
* Closes all error prompts on the page
*/
hideAll: function() {
var form = this;
var options = form.data('jqv');
var duration = options ? options.fadeDuration : 0.3;
$('.formError').fadeTo(duration, 0.3, function() {
$(this).parent('.formErrorOuter').remove();
$(this).remove();
});
return this;
},
/**
* Typically called when user exists a field using tab or a mouse click, triggers a field
* validation
*/
_onFieldEvent: function(event) {
var field = $(this);
var form = field.closest('form');
var options = form.data('jqv');
options.eventTrigger = "field";
// validate the current field
window.setTimeout(function() {
methods._validateField(field, options);
if (options.InvalidFields.length == 0 && options.onFieldSuccess) {
options.onFieldSuccess();
} else if (options.InvalidFields.length > 0 && options.onFieldFailure) {
options.onFieldFailure();
}
}, (event.data) ? event.data.delay : 0);
},
/**
* Called when the form is submited, shows prompts accordingly
*
* @param {jqObject}
* form
* @return false if form submission needs to be cancelled
*/
_onSubmitEvent: function() {
var form = $(this);
var options = form.data('jqv');
options.eventTrigger = "submit";
// validate each field
// (- skip field ajax validation, not necessary IF we will perform an ajax form validation)
var r = methods._validateFields(form);
if (r && options.ajaxFormValidation) {
methods._validateFormWithAjax(form, options);
// cancel form auto-submission - process with async call onAjaxFormComplete
return false;
}
if (options.onValidationComplete) {
// !! ensures that an undefined return is interpreted as return false but allows a onValidationComplete() to possibly return true and have form continue processing
return !!options.onValidationComplete(form, r);
}
return r;
},
/**
* Return true if the ajax field validations passed so far
* @param {Object} options
* @return true, is all ajax validation passed so far (remember ajax is async)
*/
_checkAjaxStatus: function(options) {
var status = true;
$.each(options.ajaxValidCache, function(key, value) {
if (!value) {
status = false;
// break the each
return false;
}
});
return status;
},
/**
* Return true if the ajax field is validated
* @param {String} fieldid
* @param {Object} options
* @return true, if validation passed, false if false or doesn't exist
*/
_checkAjaxFieldStatus: function(fieldid, options) {
return options.ajaxValidCache[fieldid] == true;
},
/**
* Validates form fields, shows prompts accordingly
*
* @param {jqObject}
* form
* @param {skipAjaxFieldValidation}
* boolean - when set to true, ajax field validation is skipped, typically used when the submit button is clicked
*
* @return true if form is valid, false if not, undefined if ajax form validation is done
*/
_validateFields: function(form) {
var options = form.data('jqv');
// this variable is set to true if an error is found
var errorFound = false;
// Trigger hook, start validation
form.trigger("jqv.form.validating");
// first, evaluate status of non ajax fields
var first_err = null;
form.find('[' + options.validateAttribute + '*=validate]').not(":disabled").each(function() {
var field = $(this);
var names = [];
if ($.inArray(field.attr('name'), names) < 0) {
errorFound |= methods._validateField(field, options);
if (errorFound && first_err == null)
if (field.is(":hidden") && options.prettySelect)
first_err = field = form.find("#" + options.usePrefix + methods._jqSelector(field.attr('id')) + options.useSuffix);
else
first_err = field;
if (options.doNotShowAllErrosOnSubmit)
return false;
names.push(field.attr('name'));
//if option set, stop checking validation rules after one error is found
if (options.showOneMessage == true && errorFound) {
return false;
}
}
});
// second, check to see if all ajax calls completed ok
// errorFound |= !methods._checkAjaxStatus(options);
// third, check status and scroll the container accordingly
form.trigger("jqv.form.result", [errorFound]);
if (errorFound) {
if (options.scroll) {
var destination = first_err.offset().top;
var fixleft = first_err.offset().left;
//prompt positioning adjustment support. Usage: positionType:Xshift,Yshift (for ex.: bottomLeft:+20 or bottomLeft:-20,+10)
var positionType = options.promptPosition;
if (typeof (positionType) == 'string' && positionType.indexOf(":") != -1)
positionType = positionType.substring(0, positionType.indexOf(":"));
if (positionType != "bottomRight" && positionType != "bottomLeft") {
var prompt_err = methods._getPrompt(first_err);
if (prompt_err) {
destination = prompt_err.offset().top;
}
}
// get the position of the first error, there should be at least one, no need to check this
//var destination = form.find(".formError:not('.greenPopup'):first").offset().top;
if (options.isOverflown) {
var overflowDIV = $(options.overflownDIV);
if (!overflowDIV.length) return false;
var scrollContainerScroll = overflowDIV.scrollTop();
var scrollContainerPos = -parseInt(overflowDIV.offset().top);
destination += scrollContainerScroll + scrollContainerPos - 5;
var scrollContainer = $(options.overflownDIV + ":not(:animated)");
scrollContainer.animate({ scrollTop: destination }, 1100, function() {
if (options.focusFirstField) first_err.focus();
});
} else {
$("body,html").stop().animate({
scrollTop: destination,
scrollLeft: fixleft
}, 1100, function() {
if (options.focusFirstField) first_err.focus();
});
}
} else if (options.focusFirstField)
first_err.focus();
return false;
}
return true;
},
/**
* This method is called to perform an ajax form validation.
* During this process all the (field, value) pairs are sent to the server which returns a list of invalid fields or true
*
* @param {jqObject} form
* @param {Map} options
*/
_validateFormWithAjax: function(form, options) {
var data = form.serialize();
var type = (options.ajaxmethod) ? options.ajaxmethod : "GET";
var url = (options.ajaxFormValidationURL) ? options.ajaxFormValidationURL : form.attr("action");
var dataType = (options.dataType) ? options.dataType : "json";
$.ajax({
type: type,
url: url,
cache: false,
dataType: dataType,
data: data,
form: form,
methods: methods,
options: options,
beforeSend: function() {
return options.onBeforeAjaxFormValidation(form, options);
},
error: function(data, transport) {
methods._ajaxError(data, transport);
},
success: function(json) {
if ((dataType == "json") && (json !== true)) {
// getting to this case doesn't necessary means that the form is invalid
// the server may return green or closing prompt actions
// this flag helps figuring it out
var errorInForm = false;
for (var i = 0; i < json.length; i++) {
var value = json[i];
var errorFieldId = value[0];
var errorField = $($("#" + errorFieldId)[0]);
// make sure we found the element
if (errorField.length == 1) {
// promptText or selector
var msg = value[2];
// if the field is valid
if (value[1] == true) {
if (msg == "" || !msg) {
// if for some reason, status==true and error="", just close the prompt
methods._closePrompt(errorField);
} else {
// the field is valid, but we are displaying a green prompt
if (options.allrules[msg]) {
var txt = options.allrules[msg].alertTextOk;
if (txt)
msg = txt;
}
methods._showPrompt(errorField, msg, "pass", false, options, true);
}
} else {
// the field is invalid, show the red error prompt
errorInForm |= true;
if (options.allrules[msg]) {
var txt = options.allrules[msg].alertText;
if (txt)
msg = txt;
}
methods._showPrompt(errorField, msg, "", false, options, true);
}
}
}
options.onAjaxFormComplete(!errorInForm, form, json, options);
} else
options.onAjaxFormComplete(true, form, json, options);
}
});
},
/**
* Validates field, shows prompts accordingly
*
* @param {jqObject}
* field
* @param {Array[String]}
* field's validation rules
* @param {Map}
* user options
* @return false if field is valid (It is inversed for *fields*, it return false on validate and true on errors.)
*/
_validateField: function(field, options, skipAjaxValidation) {
if (!field.attr("id")) {
field.attr("id", "form-validation-field-" + $.validationEngine.fieldIdCounter);
++$.validationEngine.fieldIdCounter;
}
if (field.is(":hidden") && !options.prettySelect || field.parent().is(":hidden"))
return false;
var rulesParsing = field.attr(options.validateAttribute);
var getRules = /validate\[(.*)\]/.exec(rulesParsing);
if (!getRules)
return false;
var str = getRules[1];
var rules = str.split(/\[|,|\]/);
// true if we ran the ajax validation, tells the logic to stop messing with prompts
var isAjaxValidator = false;
var fieldName = field.attr("name");
var promptText = "";
var promptType = "";
var required = false;
var limitErrors = false;
options.isError = false;
options.showArrow = true;
// If the programmer wants to limit the amount of error messages per field,
if (options.maxErrorsPerField > 0) {
limitErrors = true;
}
var form = $(field.closest("form"));
// Fix for adding spaces in the rules
for (var i in rules) {
rules[i] = rules[i].replace(" ", "");
// Remove any parsing errors
if (rules[i] === '') {
delete rules[i];
}
}
for (var i = 0, field_errors = 0; i < rules.length; i++) {
// If we are limiting errors, and have hit the max, break
if (limitErrors && field_errors >= options.maxErrorsPerField) {
// If we haven't hit a required yet, check to see if there is one in the validation rules for this
// field and that it's index is greater or equal to our current index
if (!required) {
var have_required = $.inArray('required', rules);
required = (have_required != -1 && have_required >= i);
}
break;
}
var errorMsg = undefined;
switch (rules[i]) {
case "required":
required = true;
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._required);
break;
case "custom":
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._custom);
break;
case "groupRequired":
// Check is its the first of group, if not, reload validation with first field
// AND continue normal validation on present field
var classGroup = "[" + options.validateAttribute + "*=" + rules[i + 1] + "]";
var firstOfGroup = form.find(classGroup).eq(0);
if (firstOfGroup[0] != field[0]) {
methods._validateField(firstOfGroup, options, skipAjaxValidation);
options.showArrow = true;
continue;
}
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._groupRequired);
if (errorMsg) required = true;
options.showArrow = false;
break;
case "ajax":
// AJAX defaults to returning it's loading message
errorMsg = methods._ajax(field, rules, i, options);
if (errorMsg) {
promptType = "load";
}
break;
case "minSize":
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._minSize);
break;
case "maxSize":
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._maxSize);
break;
case "min":
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._min);
break;
case "max":
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._max);
break;
case "past":
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._past);
break;
case "future":
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._future);
break;
case "dateRange":
var classGroup = "[" + options.validateAttribute + "*=" + rules[i + 1] + "]";
options.firstOfGroup = form.find(classGroup).eq(0);
options.secondOfGroup = form.find(classGroup).eq(1);
//if one entry out of the pair has value then proceed to run through validation
if (options.firstOfGroup[0].value || options.secondOfGroup[0].value) {
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._dateRange);
}
if (errorMsg) required = true;
options.showArrow = false;
break;
case "dateTimeRange":
var classGroup = "[" + options.validateAttribute + "*=" + rules[i + 1] + "]";
options.firstOfGroup = form.find(classGroup).eq(0);
options.secondOfGroup = form.find(classGroup).eq(1);
//if one entry out of the pair has value then proceed to run through validation
if (options.firstOfGroup[0].value || options.secondOfGroup[0].value) {
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._dateTimeRange);
}
if (errorMsg) required = true;
options.showArrow = false;
break;
case "maxCheckbox":
field = $(form.find("input[name='" + fieldName + "']"));
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._maxCheckbox);
break;
case "minCheckbox":
field = $(form.find("input[name='" + fieldName + "']"));
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._minCheckbox);
break;
case "equals":
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._equals);
break;
case "funcCall":
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._funcCall);
break;
case "creditCard":
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._creditCard);
break;
case "condRequired":
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._condRequired);
if (errorMsg !== undefined) {
required = true;
}
break;
default:
}
var end_validation = false;
// If we were passed back an message object, check what the status was to determine what to do
if (typeof errorMsg == "object") {
switch (errorMsg.status) {
case "_break":
end_validation = true;
break;
// If we have an error message, set errorMsg to the error message
case "_error":
errorMsg = errorMsg.message;
break;
// If we want to throw an error, but not show a prompt, return early with true
case "_error_no_prompt":
return true;
break;
// Anything else we continue on
default:
break;
}
}
// If it has been specified that validation should end now, break
if (end_validation) {
break;
}
// If we have a string, that means that we have an error, so add it to the error message.
if (typeof errorMsg == 'string') {
promptText += errorMsg + "<br/>";
options.isError = true;
field_errors++;
}
}
// If the rules required is not added, an empty field is not validated
if (!required && field.val().length < 1) options.isError = false;
// Hack for radio/checkbox group button, the validation go into the
// first radio/checkbox of the group
var fieldType = field.prop("type");
if ((fieldType == "radio" || fieldType == "checkbox") && form.find("input[name='" + fieldName + "']").size() > 1) {
field = $(form.find("input[name='" + fieldName + "'][type!=hidden]:first"));
options.showArrow = false;
}
if (field.is(":hidden") && options.prettySelect) {
field = form.find("#" + options.usePrefix + methods._jqSelector(field.attr('id')) + options.useSuffix);
}
if (options.isError) {
methods._showPrompt(field, promptText, promptType, false, options);
} else {
if (!isAjaxValidator) methods._closePrompt(field);
}
if (!isAjaxValidator) {
field.trigger("jqv.field.result", [field, options.isError, promptText]);
}
/* Record error */
var errindex = $.inArray(field[0], options.InvalidFields);
if (errindex == -1) {
if (options.isError)
options.InvalidFields.push(field[0]);
} else if (!options.isError) {
options.InvalidFields.splice(errindex, 1);
}
methods._handleStatusCssClasses(field, options);
return options.isError;
},
/**
* Handling css classes of fields indicating result of validation
*
* @param {jqObject}
* field
* @param {Array[String]}
* field's validation rules
* @private
*/
_handleStatusCssClasses: function(field, options) {
/* remove all classes */
if (options.addSuccessCssClassToField)
field.removeClass(options.addSuccessCssClassToField);
if (options.addFailureCssClassToField)
field.removeClass(options.addFailureCssClassToField);
/* Add classes */
if (options.addSuccessCssClassToField && !options.isError)
field.addClass(options.addSuccessCssClassToField);
if (options.addFailureCssClassToField && options.isError)
field.addClass(options.addFailureCssClassToField);
},
/********************
* _getErrorMessage
*
* @param form
* @param field
* @param rule
* @param rules
* @param i
* @param options
* @param originalValidationMethod
* @return {*}
* @private
*/
_getErrorMessage: function(form, field, rule, rules, i, options, originalValidationMethod) {
// If we are using the custon validation type, build the index for the rule.
// Otherwise if we are doing a function call, make the call and return the object
// that is passed back.
var beforeChangeRule = rule;
if (rule == "custom") {
var custom_validation_type_index = jQuery.inArray(rule, rules) + 1;
var custom_validation_type = rules[custom_validation_type_index];
rule = "custom[" + custom_validation_type + "]";
}
var element_classes = (field.attr("data-validation-engine")) ? field.attr("data-validation-engine") : field.attr("class");
var element_classes_array = element_classes.split(" ");
// Call the original validation method. If we are dealing with dates or checkboxes, also pass the form
var errorMsg;
if (rule == "future" || rule == "past" || rule == "maxCheckbox" || rule == "minCheckbox") {
errorMsg = originalValidationMethod(form, field, rules, i, options);
} else {
errorMsg = originalValidationMethod(field, rules, i, options);
}
// If the original validation method returned an error and we have a custom error message,
// return the custom message instead. Otherwise return the original error message.
if (errorMsg != undefined) {
var custom_message = methods._getCustomErrorMessage($(field), element_classes_array, beforeChangeRule, options);
if (custom_message) errorMsg = custom_message;
}
return errorMsg;
},
_getCustomErrorMessage: function(field, classes, rule, options) {
var custom_message = false;
var validityProp = methods._validityProp[rule];
// If there is a validityProp for this rule, check to see if the field has an attribute for it
if (validityProp != undefined) {
custom_message = field.attr("data-errormessage-" + validityProp);
// If there was an error message for it, return the message
if (custom_message != undefined)
return custom_message;
}
custom_message = field.attr("data-errormessage");
// If there is an inline custom error message, return it
if (custom_message != undefined)
return custom_message;
var id = '#' + field.attr("id");
// If we have custom messages for the element's id, get the message for the rule from the id.
// Otherwise, if we have custom messages for the element's classes, use the first class message we find instead.
if (typeof options.custom_error_messages[id] != "undefined" &&
typeof options.custom_error_messages[id][rule] != "undefined") {
custom_message = options.custom_error_messages[id][rule]['message'];
} else if (classes.length > 0) {
for (var i = 0; i < classes.length && classes.length > 0; i++) {
var element_class = "." + classes[i];
if (typeof options.custom_error_messages[element_class] != "undefined" &&
typeof options.custom_error_messages[element_class][rule] != "undefined") {
custom_message = options.custom_error_messages[element_class][rule]['message'];
break;
}
}
}
if (!custom_message &&
typeof options.custom_error_messages[rule] != "undefined" &&
typeof options.custom_error_messages[rule]['message'] != "undefined") {
custom_message = options.custom_error_messages[rule]['message'];
}
return custom_message;
},
_validityProp: {
"required": "value-missing",
"custom": "custom-error",
"groupRequired": "value-missing",
"ajax": "custom-error",
"minSize": "range-underflow",
"maxSize": "range-overflow",
"min": "range-underflow",
"max": "range-overflow",
"past": "type-mismatch",
"future": "type-mismatch",
"dateRange": "type-mismatch",
"dateTimeRange": "type-mismatch",
"maxCheckbox": "range-overflow",
"minCheckbox": "range-underflow",
"equals": "pattern-mismatch",
"funcCall": "custom-error",
"creditCard": "pattern-mismatch",
"condRequired": "value-missing"
},
/**
* Required validation
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_required: function(field, rules, i, options) {
switch (field.prop("type")) {
case "text":
case "password":
case "textarea":
case "file":
case "select-one":
case "select-multiple":
default:
if (!$.trim(field.val()) || field.val() == field.attr("data-validation-placeholder") || field.val() == field.attr("placeholder"))
return options.allrules[rules[i]].alertText;
break;
case "radio":
case "checkbox":
var form = field.closest("form");
var name = field.attr("name");
if (form.find("input[name='" + name + "']:checked").size() == 0) {
if (form.find("input[name='" + name + "']:visible").size() == 1)
return options.allrules[rules[i]].alertTextCheckboxe;
else
return options.allrules[rules[i]].alertTextCheckboxMultiple;
}
break;
}
},
/**
* Validate that 1 from the group field is required
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_groupRequired: function(field, rules, i, options) {
var classGroup = "[" + options.validateAttribute + "*=" + rules[i + 1] + "]";
var isValid = false;
// Check all fields from the group
field.closest("form").find(classGroup).each(function() {
if (!methods._required($(this), rules, i, options)) {
isValid = true;
return false;
}
});
if (!isValid) {
return options.allrules[rules[i]].alertText;
}
},
/**
* Validate rules
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_custom: function(field, rules, i, options) {
var customRule = rules[i + 1];
var rule = options.allrules[customRule];
var fn;
if (!rule) {
alert("jqv:custom rule not found - " + customRule);
return;
}
if (rule["regex"]) {
var ex = rule.regex;
if (!ex) {
alert("jqv:custom regex not found - " + customRule);
return;
}
var pattern = new RegExp(ex);
if (!pattern.test(field.val())) return options.allrules[customRule].alertText;
} else if (rule["func"]) {
fn = rule["func"];
if (typeof (fn) !== "function") {
alert("jqv:custom parameter 'function' is no function - " + customRule);
return;
}
if (!fn(field, rules, i, options))
return options.allrules[customRule].alertText;
} else {
alert("jqv:custom type not allowed " + customRule);
return;
}
},
/**
* Validate custom function outside of the engine scope
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_funcCall: function(field, rules, i, options) {
var functionName = rules[i + 1];
var fn;
if (functionName.indexOf('.') > -1) {
var namespaces = functionName.split('.');
var scope = window;
while (namespaces.length) {
scope = scope[namespaces.shift()];
}
fn = scope;
}
else
fn = window[functionName] || options.customFunctions[functionName];
if (typeof (fn) == 'function')
return fn(field, rules, i, options);
},
/**
* Field match
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_equals: function(field, rules, i, options) {
var equalsField = rules[i + 1];
if (field.val() != $("#" + equalsField).val())
return options.allrules.equals.alertText;
},
/**
* Check the maximum size (in characters)
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_maxSize: function(field, rules, i, options) {
var max = rules[i + 1];
var len = field.val().length;
if (len > max) {
var rule = options.allrules.maxSize;
return rule.alertText + max + rule.alertText2;
}
},
/**
* Check the minimum size (in characters)
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_minSize: function(field, rules, i, options) {
var min = rules[i + 1];
var len = field.val().length;
if (len < min) {
var rule = options.allrules.minSize;
return rule.alertText + min + rule.alertText2;
}
},
/**
* Check number minimum value
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_min: function(field, rules, i, options) {
var min = parseFloat(rules[i + 1]);
var len = parseFloat(field.val());
if (len < min) {
var rule = options.allrules.min;
if (rule.alertText2) return rule.alertText + min + rule.alertText2;
return rule.alertText + min;
}
},
/**
* Check number maximum value
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_max: function(field, rules, i, options) {
var max = parseFloat(rules[i + 1]);
var len = parseFloat(field.val());
if (len > max) {
var rule = options.allrules.max;
if (rule.alertText2) return rule.alertText + max + rule.alertText2;
//orefalo: to review, also do the translations
return rule.alertText + max;
}
},
/**
* Checks date is in the past
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_past: function(form, field, rules, i, options) {
var p = rules[i + 1];
var fieldAlt = $(form.find("input[name='" + p.replace(/^#+/, '') + "']"));
var pdate;
if (p.toLowerCase() == "now") {
pdate = new Date();
} else if (undefined != fieldAlt.val()) {
if (fieldAlt.is(":disabled"))
return;
pdate = methods._parseDate(fieldAlt.val());
} else {
pdate = methods._parseDate(p);
}
var vdate = methods._parseDate(field.val());
if (vdate > pdate) {
var rule = options.allrules.past;
if (rule.alertText2) return rule.alertText + methods._dateToString(pdate) + rule.alertText2;
return rule.alertText + methods._dateToString(pdate);
}
},
/**
* Checks date is in the future
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_future: function(form, field, rules, i, options) {
var p = rules[i + 1];
var fieldAlt = $(form.find("input[name='" + p.replace(/^#+/, '') + "']"));
var pdate;
if (p.toLowerCase() == "now") {
pdate = new Date();
} else if (undefined != fieldAlt.val()) {
if (fieldAlt.is(":disabled"))
return;
pdate = methods._parseDate(fieldAlt.val());
} else {
pdate = methods._parseDate(p);
}
var vdate = methods._parseDate(field.val());
if (vdate < pdate) {
var rule = options.allrules.future;
if (rule.alertText2)
return rule.alertText + methods._dateToString(pdate) + rule.alertText2;
return rule.alertText + methods._dateToString(pdate);
}
},
/**
* Checks if valid date
*
* @param {string} date string
* @return a bool based on determination of valid date
*/
_isDate: function(value) {
var dateRegEx = new RegExp(/^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$|^(?:(?:(?:0?[13578]|1[02])(\/|-)31)|(?:(?:0?[1,3-9]|1[0-2])(\/|-)(?:29|30)))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^(?:(?:0?[1-9]|1[0-2])(\/|-)(?:0?[1-9]|1\d|2[0-8]))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^(0?2(\/|-)29)(\/|-)(?:(?:0[48]00|[13579][26]00|[2468][048]00)|(?:\d\d)?(?:0[48]|[2468][048]|[13579][26]))$/);
return dateRegEx.test(value);
},
/**
* Checks if valid date time
*
* @param {string} date string
* @return a bool based on determination of valid date time
*/
_isDateTime: function(value) {
var dateTimeRegEx = new RegExp(/^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])\s+(1[012]|0?[1-9]){1}:(0?[1-5]|[0-6][0-9]){1}:(0?[0-6]|[0-6][0-9]){1}\s+(am|pm|AM|PM){1}$|^(?:(?:(?:0?[13578]|1[02])(\/|-)31)|(?:(?:0?[1,3-9]|1[0-2])(\/|-)(?:29|30)))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^((1[012]|0?[1-9]){1}\/(0?[1-9]|[12][0-9]|3[01]){1}\/\d{2,4}\s+(1[012]|0?[1-9]){1}:(0?[1-5]|[0-6][0-9]){1}:(0?[0-6]|[0-6][0-9]){1}\s+(am|pm|AM|PM){1})$/);
return dateTimeRegEx.test(value);
},
//Checks if the start date is before the end date
//returns true if end is later than start
_dateCompare: function(start, end) {
return (new Date(start.toString()) < new Date(end.toString()));
},
/**
* Checks date range
*
* @param {jqObject} first field name
* @param {jqObject} second field name
* @return an error string if validation failed
*/
_dateRange: function(field, rules, i, options) {
//are not both populated
if ((!options.firstOfGroup[0].value && options.secondOfGroup[0].value) || (options.firstOfGroup[0].value && !options.secondOfGroup[0].value)) {
return options.allrules[rules[i]].alertText + options.allrules[rules[i]].alertText2;
}
//are not both dates
if (!methods._isDate(options.firstOfGroup[0].value) || !methods._isDate(options.secondOfGroup[0].value)) {
return options.allrules[rules[i]].alertText + options.allrules[rules[i]].alertText2;
}
//are both dates but range is off
if (!methods._dateCompare(options.firstOfGroup[0].value, options.secondOfGroup[0].value)) {
return options.allrules[rules[i]].alertText + options.allrules[rules[i]].alertText2;
}
},
/**
* Checks date time range
*
* @param {jqObject} first field name
* @param {jqObject} second field name
* @return an error string if validation failed
*/
_dateTimeRange: function(field, rules, i, options) {
//are not both populated
if ((!options.firstOfGroup[0].value && options.secondOfGroup[0].value) || (options.firstOfGroup[0].value && !options.secondOfGroup[0].value)) {
return options.allrules[rules[i]].alertText + options.allrules[rules[i]].alertText2;
}
//are not both dates
if (!methods._isDateTime(options.firstOfGroup[0].value) || !methods._isDateTime(options.secondOfGroup[0].value)) {
return options.allrules[rules[i]].alertText + options.allrules[rules[i]].alertText2;
}
//are both dates but range is off
if (!methods._dateCompare(options.firstOfGroup[0].value, options.secondOfGroup[0].value)) {
return options.allrules[rules[i]].alertText + options.allrules[rules[i]].alertText2;
}
},
/**
* Max number of checkbox selected
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_maxCheckbox: function(form, field, rules, i, options) {
var nbCheck = rules[i + 1];
var groupname = field.attr("name");
var groupSize = form.find("input[name='" + groupname + "']:checked").size();
if (groupSize > nbCheck) {
options.showArrow = false;
if (options.allrules.maxCheckbox.alertText2)
return options.allrules.maxCheckbox.alertText + " " + nbCheck + " " + options.allrules.maxCheckbox.alertText2;
return options.allrules.maxCheckbox.alertText;
}
},
/**
* Min number of checkbox selected
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_minCheckbox: function(form, field, rules, i, options) {
var nbCheck = rules[i + 1];
var groupname = field.attr("name");
var groupSize = form.find("input[name='" + groupname + "']:checked").size();
if (groupSize < nbCheck) {
options.showArrow = false;
return options.allrules.minCheckbox.alertText + " " + nbCheck + " " + options.allrules.minCheckbox.alertText2;
}
},
/**
* Checks that it is a valid credit card number according to the
* Luhn checksum algorithm.
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_creditCard: function(field, rules, i, options) {
//spaces and dashes may be valid characters, but must be stripped to calculate the checksum.
var valid = false, cardNumber = field.val().replace(/ +/g, '').replace(/-+/g, '');
var numDigits = cardNumber.length;
if (numDigits >= 14 && numDigits <= 16 && parseInt(cardNumber) > 0) {
var sum = 0, i = numDigits - 1, pos = 1, digit, luhn = new String();
do {
digit = parseInt(cardNumber.charAt(i));
luhn += (pos++ % 2 == 0) ? digit * 2 : digit;
} while (--i >= 0)
for (i = 0; i < luhn.length; i++) {
sum += parseInt(luhn.charAt(i));
}
valid = sum % 10 == 0;
}
if (!valid) return options.allrules.creditCard.alertText;
},
/**
* Ajax field validation
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return nothing! the ajax validator handles the prompts itself
*/
_ajax: function(field, rules, i, options) {
var errorSelector = rules[i + 1];
var rule = options.allrules[errorSelector];
var extraData = rule.extraData;
var extraDataDynamic = rule.extraDataDynamic;
var data = {
"fieldId": field.attr("id"),
"fieldValue": field.val()
};
if (typeof extraData === "object") {
$.extend(data, extraData);
} else if (typeof extraData === "string") {
var tempData = extraData.split("&");
for (var i = 0; i < tempData.length; i++) {
var values = tempData[i].split("=");
if (values[0] && values[0]) {
data[values[0]] = values[1];
}
}
}
if (extraDataDynamic) {
var tmpData = [];
var domIds = String(extraDataDynamic).split(",");
for (var i = 0; i < domIds.length; i++) {
var id = domIds[i];
if ($(id).length) {
var inputValue = field.closest("form").find(id).val();
var keyValue = id.replace('#', '') + '=' + escape(inputValue);
data[id.replace('#', '')] = inputValue;
}
}
}
// If a field change event triggered this we want to clear the cache for this ID
if (options.eventTrigger == "field") {
delete (options.ajaxValidCache[field.attr("id")]);
}
// If there is an error or if the the field is already validated, do not re-execute AJAX
if (!options.isError && !methods._checkAjaxFieldStatus(field.attr("id"), options)) {
$.ajax({
type: options.ajaxFormValidationMethod,
url: rule.url,
cache: false,
dataType: "json",
data: data,
field: field,
rule: rule,
methods: methods,
options: options,
beforeSend: function() { },
error: function(data, transport) {
methods._ajaxError(data, transport);
},
success: function(json) {
// asynchronously called on success, data is the json answer from the server
var errorFieldId = json[0];
//var errorField = $($("#" + errorFieldId)[0]);
var errorField = $("#" + errorFieldId + "']").eq(0);
// make sure we found the element
if (errorField.length == 1) {
var status = json[1];
// read the optional msg from the server
var msg = json[2];
if (!status) {
// Houston we got a problem - display an red prompt
options.ajaxValidCache[errorFieldId] = false;
options.isError = true;
// resolve the msg prompt
if (msg) {
if (options.allrules[msg]) {
var txt = options.allrules[msg].alertText;
if (txt) {
msg = txt;
}
}
}
else
msg = rule.alertText;
methods._showPrompt(errorField, msg, "", true, options);
} else {
options.ajaxValidCache[errorFieldId] = true;
// resolves the msg prompt
if (msg) {
if (options.allrules[msg]) {
var txt = options.allrules[msg].alertTextOk;
if (txt) {
msg = txt;
}
}
}
else
msg = rule.alertTextOk;
// see if we should display a green prompt
if (msg)
methods._showPrompt(errorField, msg, "pass", true, options);
else
methods._closePrompt(errorField);
// If a submit form triggered this, we want to re-submit the form
if (options.eventTrigger == "submit")
field.closest("form").submit();
}
}
errorField.trigger("jqv.field.result", [errorField, options.isError, msg]);
}
});
return rule.alertTextLoad;
}
},
/**
* Common method to handle ajax errors
*
* @param {Object} data
* @param {Object} transport
*/
_ajaxError: function(data, transport) {
if (data.status == 0 && transport == null)
alert("The page is not served from a server! ajax call failed");
else if (typeof console != "undefined")
console.log("Ajax error: " + data.status + " " + transport);
},
/**
* date -> string
*
* @param {Object} date
*/
_dateToString: function(date) {
return date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
},
/**
* Parses an ISO date
* @param {String} d
*/
_parseDate: function(d) {
var dateParts = d.split("-");
if (dateParts == d)
dateParts = d.split("/");
return new Date(dateParts[0], (dateParts[1] - 1), dateParts[2]);
},
/**
* Builds or updates a prompt with the given information
*
* @param {jqObject} field
* @param {String} promptText html text to display type
* @param {String} type the type of bubble: 'pass' (green), 'load' (black) anything else (red)
* @param {boolean} ajaxed - use to mark fields than being validated with ajax
* @param {Map} options user options
*/
_showPrompt: function(field, promptText, type, ajaxed, options, ajaxform) {
var prompt = methods._getPrompt(field);
// The ajax submit errors are not see has an error in the form,
// When the form errors are returned, the engine see 2 bubbles, but those are ebing closed by the engine at the same time
// Because no error was found befor submitting
if (ajaxform) prompt = false;
if (prompt)
methods._updatePrompt(field, prompt, promptText, type, ajaxed, options);
else
methods._buildPrompt(field, promptText, type, ajaxed, options);
},
/**
* Builds and shades a prompt for the given field.
*
* @param {jqObject} field
* @param {String} promptText html text to display type
* @param {String} type the type of bubble: 'pass' (green), 'load' (black) anything else (red)
* @param {boolean} ajaxed - use to mark fields than being validated with ajax
* @param {Map} options user options
*/
_buildPrompt: function(field, promptText, type, ajaxed, options) {
// create the prompt
var prompt = $('<div>');
prompt.addClass(methods._getClassName(field.attr("id")) + "formError");
// add a class name to identify the parent form of the prompt
prompt.addClass("parentForm" + methods._getClassName(field.parents('form').attr("id")));
prompt.addClass("formError");
switch (type) {
case "pass":
prompt.addClass("greenPopup");
break;
case "load":
prompt.addClass("blackPopup");
break;
default:
/* it has error */
//alert("unknown popup type:"+type);
}
if (ajaxed)
prompt.addClass("ajaxed");
// create the prompt content
var promptContent = $('<div>').addClass("formErrorContent").html(promptText).appendTo(prompt);
// create the css arrow pointing at the field
// note that there is no triangle on max-checkbox and radio
if (options.showArrow) {
var arrow = $('<div>').addClass("formErrorArrow");
//prompt positioning adjustment support. Usage: positionType:Xshift,Yshift (for ex.: bottomLeft:+20 or bottomLeft:-20,+10)
var positionType = field.data("promptPosition") || options.promptPosition;
if (typeof (positionType) == 'string') {
var pos = positionType.indexOf(":");
if (pos != -1)
positionType = positionType.substring(0, pos);
}
switch (positionType) {
case "bottomLeft":
case "bottomRight":
prompt.find(".formErrorContent").before(arrow);
arrow.addClass("formErrorArrowBottom").html('<div class="line1"><!-- --></div><div class="line2"><!-- --></div><div class="line3"><!-- --></div><div class="line4"><!-- --></div><div class="line5"><!-- --></div><div class="line6"><!-- --></div><div class="line7"><!-- --></div><div class="line8"><!-- --></div><div class="line9"><!-- --></div><div class="line10"><!-- --></div>');
break;
case "topLeft":
case "topRight":
arrow.html('<div class="line10"><!-- --></div><div class="line9"><!-- --></div><div class="line8"><!-- --></div><div class="line7"><!-- --></div><div class="line6"><!-- --></div><div class="line5"><!-- --></div><div class="line4"><!-- --></div><div class="line3"><!-- --></div><div class="line2"><!-- --></div><div class="line1"><!-- --></div>');
prompt.append(arrow);
break;
}
}
// Modify z-indexes for jquery ui
if (field.closest('.ui-dialog').length)
prompt.addClass('formErrorInsideDialog');
prompt.css({
"opacity": 0,
'position': 'absolute'
});
field.before(prompt);
var pos = methods._calculatePosition(field, prompt, options);
prompt.css({
"top": pos.callerTopPosition,
"left": pos.callerleftPosition,
"marginTop": pos.marginTopSize,
"opacity": 0
}).data("callerField", field);
if (options.autoHidePrompt) {
setTimeout(function() {
prompt.animate({
"opacity": 0
}, function() {
prompt.closest('.formErrorOuter').remove();
prompt.remove();
});
}, options.autoHideDelay);
}
return prompt.animate({
"opacity": 0.87
});
},
/**
* Updates the prompt text field - the field for which the prompt
* @param {jqObject} field
* @param {String} promptText html text to display type
* @param {String} type the type of bubble: 'pass' (green), 'load' (black) anything else (red)
* @param {boolean} ajaxed - use to mark fields than being validated with ajax
* @param {Map} options user options
*/
_updatePrompt: function(field, prompt, promptText, type, ajaxed, options, noAnimation) {
if (prompt) {
if (typeof type !== "undefined") {
if (type == "pass")
prompt.addClass("greenPopup");
else
prompt.removeClass("greenPopup");
if (type == "load")
prompt.addClass("blackPopup");
else
prompt.removeClass("blackPopup");
}
if (ajaxed)
prompt.addClass("ajaxed");
else
prompt.removeClass("ajaxed");
prompt.find(".formErrorContent").html(promptText);
var pos = methods._calculatePosition(field, prompt, options);
var css = { "top": pos.callerTopPosition,
"left": pos.callerleftPosition,
"marginTop": pos.marginTopSize
};
if (noAnimation)
prompt.css(css);
else
prompt.animate(css);
}
},
/**
* Closes the prompt associated with the given field
*
* @param {jqObject}
* field
*/
_closePrompt: function(field) {
var prompt = methods._getPrompt(field);
if (prompt)
prompt.fadeTo("fast", 0, function() {
prompt.parent('.formErrorOuter').remove();
prompt.remove();
});
},
closePrompt: function(field) {
return methods._closePrompt(field);
},
/**
* Returns the error prompt matching the field if any
*
* @param {jqObject}
* field
* @return undefined or the error prompt (jqObject)
*/
_getPrompt: function(field) {
var formId = $(field).closest('form').attr('id');
var className = methods._getClassName(field.attr("id")) + "formError";
var match = $("." + methods._escapeExpression(className) + '.parentForm' + formId)[0];
if (match)
return $(match);
},
/**
* Returns the escapade classname
*
* @param {selector}
* className
*/
_escapeExpression: function(selector) {
return selector.replace(/([#;&,\.\+\*\~':"\!\^$\[\]\(\)=>\|])/g, "\\$1");
},
/**
* returns true if we are in a RTLed document
*
* @param {jqObject} field
*/
isRTL: function(field) {
var $document = $(document);
var $body = $('body');
var rtl =
(field && field.hasClass('rtl')) ||
(field && (field.attr('dir') || '').toLowerCase() === 'rtl') ||
$document.hasClass('rtl') ||
($document.attr('dir') || '').toLowerCase() === 'rtl' ||
$body.hasClass('rtl') ||
($body.attr('dir') || '').toLowerCase() === 'rtl';
return Boolean(rtl);
},
/**
* Calculates prompt position
*
* @param {jqObject}
* field
* @param {jqObject}
* the prompt
* @param {Map}
* options
* @return positions
*/
_calculatePosition: function(field, promptElmt, options) {
var promptTopPosition, promptleftPosition, marginTopSize;
var fieldWidth = field.width();
var fieldLeft = field.position().left;
var fieldTop = field.position().top;
var fieldHeight = field.height();
var promptHeight = promptElmt.height();
// is the form contained in an overflown container?
promptTopPosition = promptleftPosition = 0;
// compensation for the arrow
marginTopSize = -promptHeight;
//prompt positioning adjustment support
//now you can adjust prompt position
//usage: positionType:Xshift,Yshift
//for example:
// bottomLeft:+20 means bottomLeft position shifted by 20 pixels right horizontally
// topRight:20, -15 means topRight position shifted by 20 pixels to right and 15 pixels to top
//You can use +pixels, - pixels. If no sign is provided than + is default.
var positionType = field.data("promptPosition") || options.promptPosition;
var shift1 = "";
var shift2 = "";
var shiftX = 0;
var shiftY = 0;
if (typeof (positionType) == 'string') {
//do we have any position adjustments ?
if (positionType.indexOf(":") != -1) {
shift1 = positionType.substring(positionType.indexOf(":") + 1);
positionType = positionType.substring(0, positionType.indexOf(":"));
//if any advanced positioning will be needed (percents or something else) - parser should be added here
//for now we use simple parseInt()
//do we have second parameter?
if (shift1.indexOf(",") != -1) {
shift2 = shift1.substring(shift1.indexOf(",") + 1);
shift1 = shift1.substring(0, shift1.indexOf(","));
shiftY = parseInt(shift2);
if (isNaN(shiftY)) shiftY = 0;
};
shiftX = parseInt(shift1);
if (isNaN(shift1)) shift1 = 0;
};
};
switch (positionType) {
default:
case "topRight":
promptleftPosition += fieldLeft + fieldWidth - 30;
promptTopPosition += fieldTop;
break;
case "topLeft":
promptTopPosition += fieldTop;
promptleftPosition += fieldLeft;
break;
case "centerRight":
promptTopPosition = fieldTop + 4;
marginTopSize = 0;
promptleftPosition = fieldLeft + field.outerWidth(true) + 5;
break;
case "centerLeft":
promptleftPosition = fieldLeft - (promptElmt.width() + 2);
promptTopPosition = fieldTop + 4;
marginTopSize = 0;
break;
case "bottomLeft":
promptTopPosition = fieldTop + field.height() + 5;
marginTopSize = 0;
promptleftPosition = fieldLeft;
break;
case "bottomRight":
promptleftPosition = fieldLeft + fieldWidth - 30;
promptTopPosition = fieldTop + field.height() + 5;
marginTopSize = 0;
};
//apply adjusments if any
promptleftPosition += shiftX;
promptTopPosition += shiftY;
return {
"callerTopPosition": promptTopPosition + "px",
"callerleftPosition": promptleftPosition + "px",
"marginTopSize": marginTopSize + "px"
};
},
/**
* Saves the user options and variables in the form.data
*
* @param {jqObject}
* form - the form where the user option should be saved
* @param {Map}
* options - the user options
* @return the user options (extended from the defaults)
*/
_saveOptions: function(form, options) {
// is there a language localisation ?
if ($.validationEngineLanguage)
var allRules = $.validationEngineLanguage.allRules;
else
$.error("jQuery.validationEngine rules are not loaded, plz add localization files to the page");
// --- Internals DO NOT TOUCH or OVERLOAD ---
// validation rules and i18
$.validationEngine.defaults.allrules = allRules;
var userOptions = $.extend(true, {}, $.validationEngine.defaults, options);
form.data('jqv', userOptions);
return userOptions;
},
/**
* Removes forbidden characters from class name
* @param {String} className
*/
_getClassName: function(className) {
if (className)
return className.replace(/:/g, "_").replace(/\./g, "_");
},
/**
* Escape special character for jQuery selector
* http://totaldev.com/content/escaping-characters-get-valid-jquery-id
* @param {String} selector
*/
_jqSelector: function(str) {
return str.replace(/([;&,\.\+\*\~':"\!\^#$%@\[\]\(\)=>\|])/g, '\\$1');
},
/**
* Conditionally required field
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_condRequired: function(field, rules, i, options) {
var idx, dependingField;
for (idx = (i + 1); idx < rules.length; idx++) {
dependingField = jQuery("#" + rules[idx]).first();
/* Use _required for determining wether dependingField has a value.
* There is logic there for handling all field types, and default value; so we won't replicate that here
*/
if (dependingField.length && methods._required(dependingField, ["required"], 0, options) == undefined) {
/* We now know any of the depending fields has a value,
* so we can validate this field as per normal required code
*/
return methods._required(field, ["required"], 0, options);
}
}
}
};
/**
* Plugin entry point.
* You may pass an action as a parameter or a list of options.
* if none, the init and attach methods are being called.
* Remember: if you pass options, the attached method is NOT called automatically
*
* @param {String}
* method (optional) action
*/
$.fn.validationEngine = function(method) {
var form = $(this);
if (!form[0]) return form; // stop here if the form does not exist
if (typeof (method) == 'string' && method.charAt(0) != '_' && methods[method]) {
// make sure init is called once
if (method != "showPrompt" && method != "hide" && method != "hideAll")
methods.init.apply(form);
return methods[method].apply(form, Array.prototype.slice.call(arguments, 1));
} else if (typeof method == 'object' || !method) {
// default constructor with or without arguments
methods.init.apply(form, arguments);
return methods.attach.apply(form);
} else {
$.error('Method ' + method + ' does not exist in jQuery.validationEngine');
}
};
// LEAK GLOBAL OPTIONS
$.validationEngine = { fieldIdCounter: 0, defaults: {
// Name of the event triggering field validation
validationEventTrigger: "blur",
// Automatically scroll viewport to the first error
scroll: true,
// Focus on the first input
focusFirstField: true,
// Opening box position, possible locations are: topLeft,
// topRight, bottomLeft, centerRight, bottomRight
promptPosition: "topRight",
bindMethod: "bind",
// internal, automatically set to true when it parse a _ajax rule
inlineAjax: false,
// if set to true, the form data is sent asynchronously via ajax to the form.action url (get)
ajaxFormValidation: false,
// The url to send the submit ajax validation (default to action)
ajaxFormValidationURL: false,
// HTTP method used for ajax validation
ajaxFormValidationMethod: 'get',
// Ajax form validation callback method: boolean onComplete(form, status, errors, options)
// retuns false if the form.submit event needs to be canceled.
onAjaxFormComplete: $.noop,
// called right before the ajax call, may return false to cancel
onBeforeAjaxFormValidation: $.noop,
// Stops form from submitting and execute function assiciated with it
onValidationComplete: false,
// Used when you have a form fields too close and the errors messages are on top of other disturbing viewing messages
doNotShowAllErrosOnSubmit: false,
// Object where you store custom messages to override the default error messages
custom_error_messages: {},
// true if you want to vind the input fields
binded: true,
// set to true, when the prompt arrow needs to be displayed
showArrow: true,
// did one of the validation fail ? kept global to stop further ajax validations
isError: false,
// Limit how many displayed errors a field can have
maxErrorsPerField: false,
// Caches field validation status, typically only bad status are created.
// the array is used during ajax form validation to detect issues early and prevent an expensive submit
ajaxValidCache: {},
// Auto update prompt position after window resize
autoPositionUpdate: false,
InvalidFields: [],
onFieldSuccess: false,
onFieldFailure: false,
onFormSuccess: false,
onFormFailure: false,
addSuccessCssClassToField: false,
addFailureCssClassToField: false,
// Auto-hide prompt
autoHidePrompt: false,
// Delay before auto-hide
autoHideDelay: 10000,
// Fade out duration while hiding the validations
fadeDuration: 0.3,
// Use Prettify select library
prettySelect: false,
// Custom ID uses prefix
usePrefix: "",
// Custom ID uses suffix
useSuffix: "",
// Only show one message per error prompt
showOneMessage: false
}
};
$(function() { $.validationEngine.defaults.promptPosition = methods.isRTL() ? 'topLeft' : "topRight" });
})(jQuery);
| JavaScript |
(function($){
$.fn.validationEngineLanguage = function(){
};
$.validationEngineLanguage = {
newLang: function(){
$.validationEngineLanguage.allRules = {
"required": { // Add your regex rules here, you can take telephone as an example
"regex": "none",
"alertText": "* This field is required",
"alertTextCheckboxMultiple": "* Please select an option",
"alertTextCheckboxe": "* This checkbox is required",
"alertTextDateRange": "* Both date range fields are required"
},
"requiredInFunction": {
"func": function(field, rules, i, options){
return (field.val() == "test") ? true : false;
},
"alertText": "* Field must equal test"
},
"dateRange": {
"regex": "none",
"alertText": "* Invalid ",
"alertText2": "Date Range"
},
"dateTimeRange": {
"regex": "none",
"alertText": "* Invalid ",
"alertText2": "Date Time Range"
},
"minSize": {
"regex": "none",
"alertText": "* Minimum ",
"alertText2": " characters required"
},
"maxSize": {
"regex": "none",
"alertText": "* Maximum ",
"alertText2": " characters allowed"
},
"groupRequired": {
"regex": "none",
"alertText": "* You must fill one of the following fields"
},
"min": {
"regex": "none",
"alertText": "* Minimum value is "
},
"max": {
"regex": "none",
"alertText": "* Maximum value is "
},
"past": {
"regex": "none",
"alertText": "* Date prior to "
},
"future": {
"regex": "none",
"alertText": "* Date past "
},
"maxCheckbox": {
"regex": "none",
"alertText": "* Maximum ",
"alertText2": " options allowed"
},
"minCheckbox": {
"regex": "none",
"alertText": "* Please select ",
"alertText2": " options"
},
"equals": {
"regex": "none",
"alertText": "* Fields do not match"
},
"creditCard": {
"regex": "none",
"alertText": "* Invalid credit card number"
},
"phone": {
// credit: jquery.h5validate.js / orefalo
"regex": /^([\+][0-9]{1,3}[\ \.\-])?([\(]{1}[0-9]{2,6}[\)])?([0-9\ \.\-\/]{3,20})((x|ext|extension)[\ ]?[0-9]{1,4})?$/,
"alertText": "* Invalid phone number"
},
"email": {
// HTML5 compatible email regex ( http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html# e-mail-state-%28type=email%29 )
"regex": /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
"alertText": "* Invalid email address"
},
"integer": {
"regex": /^[\-\+]?\d+$/,
"alertText": "* Not a valid integer"
},
"number": {
// Number, including positive, negative, and floating decimal. credit: orefalo
"regex": /^[\-\+]?((([0-9]{1,3})([,][0-9]{3})*)|([0-9]+))?([\.]([0-9]+))?$/,
"alertText": "* Invalid floating decimal number"
},
"date": {
// Check if date is valid by leap year
"func": function (field) {
var pattern = new RegExp(/^(\d{4})[\/\-\.](0?[1-9]|1[012])[\/\-\.](0?[1-9]|[12][0-9]|3[01])$/);
var match = pattern.exec(field.val());
if (match == null)
return false;
var year = match[1];
var month = match[2]*1;
var day = match[3]*1;
var date = new Date(year, month - 1, day); // because months starts from 0.
return (date.getFullYear() == year && date.getMonth() == (month - 1) && date.getDate() == day);
},
"alertText": "* Invalid date, must be in YYYY-MM-DD format"
},
"ipv4": {
"regex": /^((([01]?[0-9]{1,2})|(2[0-4][0-9])|(25[0-5]))[.]){3}(([0-1]?[0-9]{1,2})|(2[0-4][0-9])|(25[0-5]))$/,
"alertText": "* Invalid IP address"
},
"url": {
"regex": /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i,
"alertText": "* Invalid URL"
},
"onlyNumberSp": {
"regex": /^[0-9\ ]+$/,
"alertText": "* Numbers only"
},
"onlyLetterSp": {
"regex": /^[a-zA-Z\ \']+$/,
"alertText": "* Letters only"
},
"onlyLetterNumber": {
"regex": /^[0-9a-zA-Z]+$/,
"alertText": "* No special characters allowed"
},
// --- CUSTOM RULES -- Those are specific to the demos, they can be removed or changed to your likings
"ajaxUserCall": {
"url": "ajaxValidateFieldUser",
// you may want to pass extra data on the ajax call
"extraData": "name=eric",
"alertText": "* This user is already taken",
"alertTextLoad": "* Validating, please wait"
},
"ajaxUserCallPhp": {
"url": "phpajax/ajaxValidateFieldUser.php",
// you may want to pass extra data on the ajax call
"extraData": "name=eric",
// if you provide an "alertTextOk", it will show as a green prompt when the field validates
"alertTextOk": "* This username is available",
"alertText": "* This user is already taken",
"alertTextLoad": "* Validating, please wait"
},
"ajaxNameCall": {
// remote json service location
"url": "ajaxValidateFieldName",
// error
"alertText": "* This name is already taken",
// if you provide an "alertTextOk", it will show as a green prompt when the field validates
"alertTextOk": "* This name is available",
// speaks by itself
"alertTextLoad": "* Validating, please wait"
},
"ajaxNameCallPhp": {
// remote json service location
"url": "phpajax/ajaxValidateFieldName.php",
// error
"alertText": "* This name is already taken",
// speaks by itself
"alertTextLoad": "* Validating, please wait"
},
"validate2fields": {
"alertText": "* Please input HELLO"
},
//tls warning:homegrown not fielded
"dateFormat":{
"regex": /^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$|^(?:(?:(?:0?[13578]|1[02])(\/|-)31)|(?:(?:0?[1,3-9]|1[0-2])(\/|-)(?:29|30)))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^(?:(?:0?[1-9]|1[0-2])(\/|-)(?:0?[1-9]|1\d|2[0-8]))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^(0?2(\/|-)29)(\/|-)(?:(?:0[48]00|[13579][26]00|[2468][048]00)|(?:\d\d)?(?:0[48]|[2468][048]|[13579][26]))$/,
"alertText": "* Invalid Date"
},
//tls warning:homegrown not fielded
"dateTimeFormat": {
"regex": /^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])\s+(1[012]|0?[1-9]){1}:(0?[1-5]|[0-6][0-9]){1}:(0?[0-6]|[0-6][0-9]){1}\s+(am|pm|AM|PM){1}$|^(?:(?:(?:0?[13578]|1[02])(\/|-)31)|(?:(?:0?[1,3-9]|1[0-2])(\/|-)(?:29|30)))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^((1[012]|0?[1-9]){1}\/(0?[1-9]|[12][0-9]|3[01]){1}\/\d{2,4}\s+(1[012]|0?[1-9]){1}:(0?[1-5]|[0-6][0-9]){1}:(0?[0-6]|[0-6][0-9]){1}\s+(am|pm|AM|PM){1})$/,
"alertText": "* Invalid Date or Date Format",
"alertText2": "Expected Format: ",
"alertText3": "mm/dd/yyyy hh:mm:ss AM|PM or ",
"alertText4": "yyyy-mm-dd hh:mm:ss AM|PM"
}
};
}
};
$.validationEngineLanguage.newLang();
})(jQuery);
| JavaScript |
$(document).ready(function() {
// Our Confirm method
function Confirm(question, callback) {
// Content will consist of the question and ok/cancel buttons
var message = $('<p />', { text: question }),
ok = $('<button />', {
text: 'Ok',
click: function() { callback(true); }
}),
cancel = $('<button />', {
text: 'Cancel',
click: function() { callback(false); }
});
dialogue(message.add(ok).add(cancel), 'Do you agree?');
}
// Our Alert method
function Alert(message) {
// Content will consist of the message and an ok button
var message = $('<p />', { text: message }),
ok = $('<button />', { text: 'Ok', 'class': 'full' });
dialogue(message.add(ok), 'Alert!');
}
// Our Prompt method
function Prompt(question, initial, callback) {
// Content will consist of a question elem and input, with ok/cancel buttons
var message = $('<p />', { text: question }),
input = $('<input />', { val: initial }),
ok = $('<button />', {
text: 'Ok',
click: function() { callback(input.val()); }
}),
cancel = $('<button />', {
text: 'Cancel',
click: function() { callback(null); }
});
dialogue(message.add(input).add(ok).add(cancel), 'Attention!');
}
function dialogue(content, title) {
/*
* Since the dialogue isn't really a tooltip as such, we'll use a dummy
* out-of-DOM element as our target instead of an actual element like document.body
*/
$('<div />').qtip(
{
content: {
text: content,
title: title
},
position: {
my: 'center', at: 'center', // Center it...
target: $(window) // ... in the window
},
show: {
ready: true, // Show it straight away
modal: {
on: true, // Make it modal (darken the rest of the page)...
blur: false // ... but don't close the tooltip when clicked
}
},
hide: false, // We'll hide it maunally so disable hide events
style: 'qtip-light qtip-rounded qtip-dialogue', // Add a few styles
events: {
// Hide the tooltip when any buttons in the dialogue are clicked
render: function(event, api) {
$('button', api.elements.content).click(api.hide);
},
// Destroy the tooltip once it's hidden as we no longer need it!
hide: function(event, api) { api.destroy(); }
}
});
}
//Checked
$('#toggle-all-pending').click(function() {
//
if ($(this).attr('class') != "toggle-checked") {
$('#mainformpending input[type=checkbox]').attr('checked', false);
}
$('#mainformpending input').checkBox();
$('#toggle-all-pending').toggleClass('toggle-checked');
$('#mainformpending input[type=checkbox]').checkBox('toggle');
return false;
});
$('#mainformpending input:checkbox:not(#toggle-all-pending)').click(function() {
$('#toggle-all-pending').removeClass('toggle-checked');
});
//Checked
$('#toggle-all-rejected').click(function() {
//
if ($(this).attr('class') != "toggle-checked") {
$('#mainformrejected input[type=checkbox]').attr('checked', false);
}
$('#mainformrejected input').checkBox();
$('#toggle-all-rejected').toggleClass('toggle-checked');
$('#mainformrejected input[type=checkbox]').checkBox('toggle');
return false;
});
$('#mainformrejected input:checkbox:not(#toggle-all-rejected)').click(function() {
$('#toggle-all-rejected').removeClass('toggle-checked');
});
//
//prompt for delete button
$('.remove-btn').click(function(e) {
e.preventDefault(); //prevent default action for anchor
var self = this;
Confirm("Confirm removed the selected records?", function(yes) {
if (yes) {
window.location = self.href;
}
});
});
//bulk process action
$('.action-invoke').click(function(e) {
e.preventDefault(); //prevent default action for anchor
//ensure at least one item is checked
var fields = $("input[name='selected']").serializeArray();
if (fields.length == 0) {
Alert('Please select at least one item.');
return false;
} else {
//submit form
$(".list_item_form").attr("action", this.href);
$(".list_item_form").submit();
}
});
//bulk process delete action
$('.action-invoke-removed').click(function(e) {
e.preventDefault(); //prevent default action for anchor
//ensure at least one item is checked
var fields = $("input[name='selected']").serializeArray();
if (fields.length == 0) {
Alert('Please select at least one item.');
return false;
} else {
var self = this;
Confirm("Confirm removed the selected records?", function(yes) {
if (yes) {
$(".list_item_form").attr("action", self.href);
$(".list_item_form").submit();
}
});
}
});
// 1 - START DROPDOWN SLIDER SCRIPTS ------------------------------------------------------------------------
$(".action-slider").click(function() {
$("#actions-box-slider").slideToggle("fast");
$(this).toggleClass("activated");
return false;
});
$(".action-slider-reject").click(function() {
$("#actions-box-slider-reject").slideToggle("fast");
$(this).toggleClass("activated");
return false;
});
// END ----------------------------- 1
});
| JavaScript |
/*!
* Media helper for fancyBox
* version: 1.0.5 (Tue, 23 Oct 2012)
* @requires fancyBox v2.0 or later
*
* Usage:
* $(".fancybox").fancybox({
* helpers : {
* media: true
* }
* });
*
* Set custom URL parameters:
* $(".fancybox").fancybox({
* helpers : {
* media: {
* youtube : {
* params : {
* autoplay : 0
* }
* }
* }
* }
* });
*
* Or:
* $(".fancybox").fancybox({,
* helpers : {
* media: true
* },
* youtube : {
* autoplay: 0
* }
* });
*
* Supports:
*
* Youtube
* http://www.youtube.com/watch?v=opj24KnzrWo
* http://www.youtube.com/embed/opj24KnzrWo
* http://youtu.be/opj24KnzrWo
* Vimeo
* http://vimeo.com/40648169
* http://vimeo.com/channels/staffpicks/38843628
* http://vimeo.com/groups/surrealism/videos/36516384
* http://player.vimeo.com/video/45074303
* Metacafe
* http://www.metacafe.com/watch/7635964/dr_seuss_the_lorax_movie_trailer/
* http://www.metacafe.com/watch/7635964/
* Dailymotion
* http://www.dailymotion.com/video/xoytqh_dr-seuss-the-lorax-premiere_people
* Twitvid
* http://twitvid.com/QY7MD
* Twitpic
* http://twitpic.com/7p93st
* Instagram
* http://instagr.am/p/IejkuUGxQn/
* http://instagram.com/p/IejkuUGxQn/
* Google maps
* http://maps.google.com/maps?q=Eiffel+Tower,+Avenue+Gustave+Eiffel,+Paris,+France&t=h&z=17
* http://maps.google.com/?ll=48.857995,2.294297&spn=0.007666,0.021136&t=m&z=16
* http://maps.google.com/?ll=48.859463,2.292626&spn=0.000965,0.002642&t=m&z=19&layer=c&cbll=48.859524,2.292532&panoid=YJ0lq28OOy3VT2IqIuVY0g&cbp=12,151.58,,0,-15.56
*/
(function ($) {
"use strict";
//Shortcut for fancyBox object
var F = $.fancybox,
format = function( url, rez, params ) {
params = params || '';
if ( $.type( params ) === "object" ) {
params = $.param(params, true);
}
$.each(rez, function(key, value) {
url = url.replace( '$' + key, value || '' );
});
if (params.length) {
url += ( url.indexOf('?') > 0 ? '&' : '?' ) + params;
}
return url;
};
//Add helper object
F.helpers.media = {
defaults : {
youtube : {
matcher : /(youtube\.com|youtu\.be)\/(watch\?v=|v\/|u\/|embed\/?)?(videoseries\?list=(.*)|[\w-]{11}|\?listType=(.*)&list=(.*)).*/i,
params : {
autoplay : 1,
autohide : 1,
fs : 1,
rel : 0,
hd : 1,
wmode : 'opaque',
enablejsapi : 1
},
type : 'iframe',
url : '//www.youtube.com/embed/$3'
},
vimeo : {
matcher : /(?:vimeo(?:pro)?.com)\/(?:[^\d]+)?(\d+)(?:.*)/,
params : {
autoplay : 1,
hd : 1,
show_title : 1,
show_byline : 1,
show_portrait : 0,
fullscreen : 1
},
type : 'iframe',
url : '//player.vimeo.com/video/$1'
},
metacafe : {
matcher : /metacafe.com\/(?:watch|fplayer)\/([\w\-]{1,10})/,
params : {
autoPlay : 'yes'
},
type : 'swf',
url : function( rez, params, obj ) {
obj.swf.flashVars = 'playerVars=' + $.param( params, true );
return '//www.metacafe.com/fplayer/' + rez[1] + '/.swf';
}
},
dailymotion : {
matcher : /dailymotion.com\/video\/(.*)\/?(.*)/,
params : {
additionalInfos : 0,
autoStart : 1
},
type : 'swf',
url : '//www.dailymotion.com/swf/video/$1'
},
twitvid : {
matcher : /twitvid\.com\/([a-zA-Z0-9_\-\?\=]+)/i,
params : {
autoplay : 0
},
type : 'iframe',
url : '//www.twitvid.com/embed.php?guid=$1'
},
twitpic : {
matcher : /twitpic\.com\/(?!(?:place|photos|events)\/)([a-zA-Z0-9\?\=\-]+)/i,
type : 'image',
url : '//twitpic.com/show/full/$1/'
},
instagram : {
matcher : /(instagr\.am|instagram\.com)\/p\/([a-zA-Z0-9_\-]+)\/?/i,
type : 'image',
url : '//$1/p/$2/media/'
},
google_maps : {
matcher : /maps\.google\.([a-z]{2,3}(\.[a-z]{2})?)\/(\?ll=|maps\?)(.*)/i,
type : 'iframe',
url : function( rez ) {
return '//maps.google.' + rez[1] + '/' + rez[3] + '' + rez[4] + '&output=' + (rez[4].indexOf('layer=c') > 0 ? 'svembed' : 'embed');
}
}
},
beforeLoad : function(opts, obj) {
var url = obj.href || '',
type = false,
what,
item,
rez,
params;
for (what in opts) {
item = opts[ what ];
rez = url.match( item.matcher );
if (rez) {
type = item.type;
params = $.extend(true, {}, item.params, obj[ what ] || ($.isPlainObject(opts[ what ]) ? opts[ what ].params : null));
url = $.type( item.url ) === "function" ? item.url.call( this, rez, params, obj ) : format( item.url, rez, params );
break;
}
}
if (type) {
obj.href = url;
obj.type = type;
obj.autoHeight = false;
}
}
};
}(jQuery)); | JavaScript |
/*!
* Buttons helper for fancyBox
* version: 1.0.5 (Mon, 15 Oct 2012)
* @requires fancyBox v2.0 or later
*
* Usage:
* $(".fancybox").fancybox({
* helpers : {
* buttons: {
* position : 'top'
* }
* }
* });
*
*/
(function ($) {
//Shortcut for fancyBox object
var F = $.fancybox;
//Add helper object
F.helpers.buttons = {
defaults : {
skipSingle : false, // disables if gallery contains single image
position : 'top', // 'top' or 'bottom'
tpl : '<div id="fancybox-buttons"><ul><li><a class="btnPrev" title="Previous" href="javascript:;"></a></li><li><a class="btnPlay" title="Start slideshow" href="javascript:;"></a></li><li><a class="btnNext" title="Next" href="javascript:;"></a></li><li><a class="btnToggle" title="Toggle size" href="javascript:;"></a></li><li><a class="btnClose" title="Close" href="javascript:jQuery.fancybox.close();"></a></li></ul></div>'
},
list : null,
buttons: null,
beforeLoad: function (opts, obj) {
//Remove self if gallery do not have at least two items
if (opts.skipSingle && obj.group.length < 2) {
obj.helpers.buttons = false;
obj.closeBtn = true;
return;
}
//Increase top margin to give space for buttons
obj.margin[ opts.position === 'bottom' ? 2 : 0 ] += 30;
},
onPlayStart: function () {
if (this.buttons) {
this.buttons.play.attr('title', 'Pause slideshow').addClass('btnPlayOn');
}
},
onPlayEnd: function () {
if (this.buttons) {
this.buttons.play.attr('title', 'Start slideshow').removeClass('btnPlayOn');
}
},
afterShow: function (opts, obj) {
var buttons = this.buttons;
if (!buttons) {
this.list = $(opts.tpl).addClass(opts.position).appendTo('body');
buttons = {
prev : this.list.find('.btnPrev').click( F.prev ),
next : this.list.find('.btnNext').click( F.next ),
play : this.list.find('.btnPlay').click( F.play ),
toggle : this.list.find('.btnToggle').click( F.toggle )
}
}
//Prev
if (obj.index > 0 || obj.loop) {
buttons.prev.removeClass('btnDisabled');
} else {
buttons.prev.addClass('btnDisabled');
}
//Next / Play
if (obj.loop || obj.index < obj.group.length - 1) {
buttons.next.removeClass('btnDisabled');
buttons.play.removeClass('btnDisabled');
} else {
buttons.next.addClass('btnDisabled');
buttons.play.addClass('btnDisabled');
}
this.buttons = buttons;
this.onUpdate(opts, obj);
},
onUpdate: function (opts, obj) {
var toggle;
if (!this.buttons) {
return;
}
toggle = this.buttons.toggle.removeClass('btnDisabled btnToggleOn');
//Size toggle button
if (obj.canShrink) {
toggle.addClass('btnToggleOn');
} else if (!obj.canExpand) {
toggle.addClass('btnDisabled');
}
},
beforeClose: function () {
if (this.list) {
this.list.remove();
}
this.list = null;
this.buttons = null;
}
};
}(jQuery)); | JavaScript |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.