code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231 values | license stringclasses 13 values | size int64 1 2.01M |
|---|---|---|---|---|---|
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'uicolor', 'nl',
{
uicolor :
{
title : 'UI Kleurenkiezer',
preview : 'Live voorbeeld',
config : 'Plak deze tekst in jouw config.js bestand',
predefined : 'Voorgedefinieerde kleurensets'
}
});
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/uicolor/lang/nl.js | JavaScript | asf20 | 393 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'uicolor', 'ug',
{
uicolor :
{
title : 'ئىشلەتكۈچى ئارايۈزى رەڭ تاللىغۇچ',
preview : 'شۇئان ئالدىن كۆزىتىش',
config : 'بۇ ھەرپ تىزىقىنى config.js ھۆججەتكە چاپلايدۇ',
predefined : 'ئالدىن بەلگىلەنگەن رەڭلەر'
}
});
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/uicolor/lang/ug.js | JavaScript | asf20 | 514 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'uicolor', 'it',
{
uicolor :
{
title : 'Selettore Colore UI',
preview : 'Anteprima Live',
config : 'Incolla questa stringa nel tuo file config.js',
predefined : 'Set di colori predefiniti'
}
});
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/uicolor/lang/it.js | JavaScript | asf20 | 396 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'uicolor', 'de',
{
uicolor :
{
title : 'UI Pipette',
preview : 'Live-Vorschau',
config : 'Fügen Sie diese Zeichenfolge in die \'config.js\' Datei.',
predefined : 'Vordefinierte Farbsätze'
}
});
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/uicolor/lang/de.js | JavaScript | asf20 | 397 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'uicolor', 'pl',
{
uicolor :
{
title : 'Wybór koloru interfejsu',
preview : 'Podgląd na żywo',
config : 'Wklej poniższy łańcuch znaków do pliku config.js:',
predefined : 'Predefiniowane zestawy kolorów'
}
});
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/uicolor/lang/pl.js | JavaScript | asf20 | 418 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'uicolor', 'vi',
{
uicolor :
{
title : 'Giao diện người dùng Color Picker',
preview : 'Xem trước trực tiếp',
config : 'Dán chuỗi này vào tập tin config.js của bạn',
predefined : 'Tập màu định nghĩa sẵn'
}
});
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/uicolor/lang/vi.js | JavaScript | asf20 | 443 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'uicolor', 'hr',
{
uicolor :
{
title : 'UI odabir boja',
preview : 'Pregled uživo',
config : 'Zalijepite ovaj tekst u Vašu config.js datoteku.',
predefined : 'Već postavljeni setovi boja'
}
});
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/uicolor/lang/hr.js | JavaScript | asf20 | 398 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'uicolor', 'tr',
{
uicolor :
{
title : 'UI Renk Seçicisi',
preview : 'Canlı önizleme',
config : 'Bu dizeyi config.js dosyasının içine yapıştırın',
predefined : 'Önceden tanımlanmış renk kümeleri'
}
});
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/uicolor/lang/tr.js | JavaScript | asf20 | 418 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'uicolor', 'fr',
{
uicolor :
{
title : 'UI Sélecteur de couleur',
preview : 'Aperçu',
config : 'Collez cette chaîne de caractères dans votre fichier config.js',
predefined : 'Palettes de couleurs prédéfinies'
}
});
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/uicolor/lang/fr.js | JavaScript | asf20 | 422 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'uicolor', 'zh-cn',
{
uicolor :
{
title : '用户界面颜色选择器',
preview : '即时预览',
config : '粘贴此字符串到你的 config.js 文件',
predefined : '预定义颜色集'
}
});
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/uicolor/lang/zh-cn.js | JavaScript | asf20 | 397 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'uicolor', 'eo',
{
uicolor :
{
title : 'UI Kolorselektilo',
preview : 'Vidigi la aspekton',
config : 'Gluu tiun signoĉenon en vian dosieron config.js',
predefined : 'Antaŭdifinita koloraro'
}
});
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/uicolor/lang/eo.js | JavaScript | asf20 | 399 |
/*
Copyright (c) 2003-2012, 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'
}
});
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/uicolor/lang/en.js | JavaScript | asf20 | 383 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'uicolor', 'da',
{
uicolor :
{
title : 'Brugerflade på farvevælger',
preview : 'Vis liveeksempel',
config : 'Indsæt denne streng i din config.js fil',
predefined : 'Prædefinerede farveskemaer'
}
});
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/uicolor/lang/da.js | JavaScript | asf20 | 404 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'uicolor', 'nb',
{
uicolor :
{
title : 'Fargevelger for brukergrensesnitt',
preview : 'Forhåndsvisning i sanntid',
config : 'Lim inn følgende tekst i din config.js-fil',
predefined : 'Forhåndsdefinerte fargesett'
}
});
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/uicolor/lang/nb.js | JavaScript | asf20 | 423 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'uicolor', 'bg',
{
uicolor :
{
title : 'ПИ избор на цвят',
preview : 'Преглед',
config : 'Вмъкнете този низ във Вашия config.js fajl',
predefined : 'Предефинирани цветови палитри'
}
});
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/uicolor/lang/bg.js | JavaScript | asf20 | 457 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'uicolor', 'el',
{
uicolor :
{
title : 'Διεπαφή Επιλογέα Χρωμάτων',
preview : 'Ζωντανή Προεπισκόπηση',
config : 'Επικολλήστε αυτό το κείμενο στο αρχείο config.js',
predefined : 'Προκαθορισμένα σύνολα χρωμάτων'
}
});
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/uicolor/lang/el.js | JavaScript | asf20 | 521 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'uicolor', 'fi',
{
uicolor :
{
title : 'Käyttöliittymän värivalitsin',
preview : 'Esikatsele',
config : 'Liitä tämä merkkijono config.js tiedostoosi',
predefined : 'Esimääritellyt värijoukot'
}
});
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/uicolor/lang/fi.js | JavaScript | asf20 | 409 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'uicolor', 'cy',
{
uicolor :
{
title : 'Dewisydd Lliwiau\'r UI',
preview : 'Rhagolwg Byw',
config : 'Gludwch y llinyn hwn i\'ch ffeil config.js',
predefined : 'Setiau lliw wedi\'u cyn-ddiffinio'
}
});
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/uicolor/lang/cy.js | JavaScript | asf20 | 402 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'uicolor', 'no',
{
uicolor :
{
title : 'Fargevelger for brukergrensesnitt',
preview : 'Forhåndsvisning i sanntid',
config : 'Lim inn følgende tekst i din config.js-fil',
predefined : 'Forhåndsdefinerte fargesett'
}
});
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/uicolor/lang/no.js | JavaScript | asf20 | 423 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'uicolor', 'mk',
{
uicolor :
{
title : 'Палета со бои',
preview : 'Преглед',
config : 'Залепи го овој текст во config.js датотеката',
predefined : 'Предефинирани множества на бои'
}
});
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/uicolor/lang/mk.js | JavaScript | asf20 | 461 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'uicolor', 'fa',
{
uicolor :
{
title : 'انتخاب رنگ UI',
preview : 'پیشنمایش زنده',
config : 'این رشته را در فایل config.js خود بچسبانید.',
predefined : 'مجموعه رنگ از پیش تعریف شده'
}
});
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/uicolor/lang/fa.js | JavaScript | asf20 | 458 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'uicolor', 'et',
{
uicolor :
{
title : 'Värvivalija kasutajaliides',
preview : 'Automaatne eelvaade',
config : 'Aseta see sõne oma config.js faili.',
predefined : 'Eelmääratud värvikomplektid'
}
});
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/uicolor/lang/et.js | JavaScript | asf20 | 405 |
/*
Copyright (c) 2003-2012, 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 : 'קבוצות צבעים מוגדרות מראש'
}
});
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/uicolor/lang/he.js | JavaScript | asf20 | 461 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'uicolor', 'uk',
{
uicolor :
{
title : 'Color Picker Інтерфейс',
preview : 'Перегляд наживо',
config : 'Вставте цей рядок у файл config.js',
predefined : 'Стандартний набір кольорів'
}
});
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/uicolor/lang/uk.js | JavaScript | asf20 | 457 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'uicolor', 'cs',
{
uicolor :
{
title : 'Výběr barvy rozhraní',
preview : 'Živý náhled',
config : 'Vložte tento řetězec do Vašeho souboru config.js',
predefined : 'Přednastavené sady barev'
}
});
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/uicolor/lang/cs.js | JavaScript | asf20 | 408 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'uicolor', 'pt-br',
{
uicolor :
{
title : 'Paleta de Cores',
preview : 'Visualização ao vivo',
config : 'Cole o texto no seu arquivo config.js',
predefined : 'Conjuntos de cores predefinidos'
}
});
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/uicolor/lang/pt-br.js | JavaScript | asf20 | 401 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.dialog.add( 'uicolor', function( editor )
{
var dialog, picker, pickerContents,
// Actual UI color value.
uiColor = editor.getUiColor(),
pickerId = 'cke_uicolor_picker' + CKEDITOR.tools.getNextNumber();
function setNewPickerColor( color )
{
// Convert HEX representation to RGB, stripping # char.
if ( /^#/.test( color ) )
color = window.YAHOO.util.Color.hex2rgb( color.substr( 1 ) );
picker.setValue( color, true );
// Refresh picker UI.
picker.refresh( pickerId );
}
function setNewUiColor( color, force )
{
if ( force || dialog._.contents.tab1.livePeview.getValue() )
editor.setUiColor( color );
// Write new config string into textbox.
dialog._.contents.tab1.configBox.setValue(
'config.uiColor = "#' + picker.get( "hex" ) + '"'
);
}
pickerContents =
{
id : 'yuiColorPicker',
type : 'html',
html : "<div id='" + pickerId + "' class='cke_uicolor_picker' style='width: 360px; height: 200px; position: relative;'></div>",
onLoad : function( event )
{
var url = CKEDITOR.getUrl(
'_source/' + // @Packager.RemoveLine
'plugins/uicolor/yui/'
);
// Create new color picker widget.
picker = new window.YAHOO.widget.ColorPicker( pickerId,
{
showhsvcontrols : true,
showhexcontrols : true,
images :
{
PICKER_THUMB : url + "assets/picker_thumb.png",
HUE_THUMB : url + "assets/hue_thumb.png"
}
});
// Set actual UI color to the picker.
if ( uiColor )
setNewPickerColor( uiColor );
// Subscribe to the rgbChange event.
picker.on( "rgbChange", function()
{
// Reset predefined box.
dialog._.contents.tab1.predefined.setValue( '' );
setNewUiColor( '#' + picker.get( 'hex' ) );
});
// Fix input class names.
var inputs = new CKEDITOR.dom.nodeList( picker.getElementsByTagName( 'input' ) );
for ( var i = 0; i < inputs.count() ; i++ )
inputs.getItem( i ).addClass( 'cke_dialog_ui_input_text' );
}
};
var skipPreviewChange = true;
return {
title : editor.lang.uicolor.title,
minWidth : 360,
minHeight : 320,
onLoad : function()
{
dialog = this;
this.setupContent();
// #3808
if ( CKEDITOR.env.ie7Compat )
dialog.parts.contents.setStyle( 'overflow', 'hidden' );
},
contents : [
{
id : 'tab1',
label : '',
title : '',
expand : true,
padding : 0,
elements : [
pickerContents,
{
id : 'tab1',
type : 'vbox',
children :
[
{
id : 'livePeview',
type : 'checkbox',
label : editor.lang.uicolor.preview,
'default' : 1,
onLoad : function()
{
skipPreviewChange = true;
},
onChange : function()
{
if ( skipPreviewChange )
return;
var on = this.getValue(),
color = on ? '#' + picker.get( 'hex' ) : uiColor;
setNewUiColor( color, true );
}
},
{
type : 'hbox',
children :
[
{
id : 'predefined',
type : 'select',
'default' : '',
label : editor.lang.uicolor.predefined,
items :
[
[ '' ],
[ 'Light blue', '#9AB8F3' ],
[ 'Sand', '#D2B48C' ],
[ 'Metallic', '#949AAA' ],
[ 'Purple', '#C2A3C7' ],
[ 'Olive', '#A2C980' ],
[ 'Happy green', '#9BD446' ],
[ 'Jezebel Blue', '#14B8C4' ],
[ 'Burn', '#FF893A' ],
[ 'Easy red', '#FF6969' ],
[ 'Pisces 3', '#48B4F2' ],
[ 'Aquarius 5', '#487ED4' ],
[ 'Absinthe', '#A8CF76' ],
[ 'Scrambled Egg', '#C7A622' ],
[ 'Hello monday', '#8E8D80' ],
[ 'Lovely sunshine', '#F1E8B1' ],
[ 'Recycled air', '#B3C593' ],
[ 'Down', '#BCBCA4' ],
[ 'Mark Twain', '#CFE91D' ],
[ 'Specks of dust', '#D1B596' ],
[ 'Lollipop', '#F6CE23' ]
],
onChange : function()
{
var color = this.getValue();
if ( color )
{
setNewPickerColor( color );
setNewUiColor( color );
// Refresh predefined preview box.
CKEDITOR.document.getById( 'predefinedPreview' ).setStyle( 'background', color );
}
else
CKEDITOR.document.getById( 'predefinedPreview' ).setStyle( 'background', '' );
},
onShow : function()
{
var color = editor.getUiColor();
if ( color )
this.setValue( color );
}
},
{
id : 'predefinedPreview',
type : 'html',
html : '<div id="cke_uicolor_preview" style="border: 1px solid black; padding: 3px; width: 30px;">' +
'<div id="predefinedPreview" style="width: 30px; height: 30px;"> </div>' +
'</div>'
}
]
},
{
id : 'configBox',
type : 'text',
label : editor.lang.uicolor.config,
onShow : function()
{
var color = editor.getUiColor();
if ( color )
this.setValue(
'config.uiColor = "' + color + '"'
);
}
}
]
}
]
}
],
buttons : [ CKEDITOR.dialog.okButton ]
};
} );
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/uicolor/dialogs/uicolor.js | JavaScript | asf20 | 5,808 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @file Blockquote.
*/
(function()
{
function getState( editor, path )
{
var firstBlock = path.block || path.blockLimit;
if ( !firstBlock || firstBlock.getName() == 'body' )
return CKEDITOR.TRISTATE_OFF;
// See if the first block has a blockquote parent.
if ( firstBlock.getAscendant( 'blockquote', true ) )
return CKEDITOR.TRISTATE_ON;
return CKEDITOR.TRISTATE_OFF;
}
function onSelectionChange( evt )
{
var editor = evt.editor;
if ( editor.readOnly )
return;
var command = editor.getCommand( 'blockquote' );
command.state = getState( editor, evt.data.path );
command.fire( 'state' );
}
function noBlockLeft( bqBlock )
{
for ( var i = 0, length = bqBlock.getChildCount(), child ; i < length && ( child = bqBlock.getChild( i ) ) ; i++ )
{
if ( child.type == CKEDITOR.NODE_ELEMENT && child.isBlockBoundary() )
return false;
}
return true;
}
var commandObject =
{
exec : function( editor )
{
var state = editor.getCommand( 'blockquote' ).state,
selection = editor.getSelection(),
range = selection && selection.getRanges( true )[0];
if ( !range )
return;
var bookmarks = selection.createBookmarks();
// Kludge for #1592: if the bookmark nodes are in the beginning of
// blockquote, then move them to the nearest block element in the
// blockquote.
if ( CKEDITOR.env.ie )
{
var bookmarkStart = bookmarks[0].startNode,
bookmarkEnd = bookmarks[0].endNode,
cursor;
if ( bookmarkStart && bookmarkStart.getParent().getName() == 'blockquote' )
{
cursor = bookmarkStart;
while ( ( cursor = cursor.getNext() ) )
{
if ( cursor.type == CKEDITOR.NODE_ELEMENT &&
cursor.isBlockBoundary() )
{
bookmarkStart.move( cursor, true );
break;
}
}
}
if ( bookmarkEnd
&& bookmarkEnd.getParent().getName() == 'blockquote' )
{
cursor = bookmarkEnd;
while ( ( cursor = cursor.getPrevious() ) )
{
if ( cursor.type == CKEDITOR.NODE_ELEMENT &&
cursor.isBlockBoundary() )
{
bookmarkEnd.move( cursor );
break;
}
}
}
}
var iterator = range.createIterator(),
block;
iterator.enlargeBr = editor.config.enterMode != CKEDITOR.ENTER_BR;
if ( state == CKEDITOR.TRISTATE_OFF )
{
var paragraphs = [];
while ( ( block = iterator.getNextParagraph() ) )
paragraphs.push( block );
// If no paragraphs, create one from the current selection position.
if ( paragraphs.length < 1 )
{
var para = editor.document.createElement( editor.config.enterMode == CKEDITOR.ENTER_P ? 'p' : 'div' ),
firstBookmark = bookmarks.shift();
range.insertNode( para );
para.append( new CKEDITOR.dom.text( '\ufeff', editor.document ) );
range.moveToBookmark( firstBookmark );
range.selectNodeContents( para );
range.collapse( true );
firstBookmark = range.createBookmark();
paragraphs.push( para );
bookmarks.unshift( firstBookmark );
}
// Make sure all paragraphs have the same parent.
var commonParent = paragraphs[0].getParent(),
tmp = [];
for ( var i = 0 ; i < paragraphs.length ; i++ )
{
block = paragraphs[i];
commonParent = commonParent.getCommonAncestor( block.getParent() );
}
// The common parent must not be the following tags: table, tbody, tr, ol, ul.
var denyTags = { table : 1, tbody : 1, tr : 1, ol : 1, ul : 1 };
while ( denyTags[ commonParent.getName() ] )
commonParent = commonParent.getParent();
// Reconstruct the block list to be processed such that all resulting blocks
// satisfy parentNode.equals( commonParent ).
var lastBlock = null;
while ( paragraphs.length > 0 )
{
block = paragraphs.shift();
while ( !block.getParent().equals( commonParent ) )
block = block.getParent();
if ( !block.equals( lastBlock ) )
tmp.push( block );
lastBlock = block;
}
// If any of the selected blocks is a blockquote, remove it to prevent
// nested blockquotes.
while ( tmp.length > 0 )
{
block = tmp.shift();
if ( block.getName() == 'blockquote' )
{
var docFrag = new CKEDITOR.dom.documentFragment( editor.document );
while ( block.getFirst() )
{
docFrag.append( block.getFirst().remove() );
paragraphs.push( docFrag.getLast() );
}
docFrag.replace( block );
}
else
paragraphs.push( block );
}
// Now we have all the blocks to be included in a new blockquote node.
var bqBlock = editor.document.createElement( 'blockquote' );
bqBlock.insertBefore( paragraphs[0] );
while ( paragraphs.length > 0 )
{
block = paragraphs.shift();
bqBlock.append( block );
}
}
else if ( state == CKEDITOR.TRISTATE_ON )
{
var moveOutNodes = [],
database = {};
while ( ( block = iterator.getNextParagraph() ) )
{
var bqParent = null,
bqChild = null;
while ( block.getParent() )
{
if ( block.getParent().getName() == 'blockquote' )
{
bqParent = block.getParent();
bqChild = block;
break;
}
block = block.getParent();
}
// Remember the blocks that were recorded down in the moveOutNodes array
// to prevent duplicates.
if ( bqParent && bqChild && !bqChild.getCustomData( 'blockquote_moveout' ) )
{
moveOutNodes.push( bqChild );
CKEDITOR.dom.element.setMarker( database, bqChild, 'blockquote_moveout', true );
}
}
CKEDITOR.dom.element.clearAllMarkers( database );
var movedNodes = [],
processedBlockquoteBlocks = [];
database = {};
while ( moveOutNodes.length > 0 )
{
var node = moveOutNodes.shift();
bqBlock = node.getParent();
// If the node is located at the beginning or the end, just take it out
// without splitting. Otherwise, split the blockquote node and move the
// paragraph in between the two blockquote nodes.
if ( !node.getPrevious() )
node.remove().insertBefore( bqBlock );
else if ( !node.getNext() )
node.remove().insertAfter( bqBlock );
else
{
node.breakParent( node.getParent() );
processedBlockquoteBlocks.push( node.getNext() );
}
// Remember the blockquote node so we can clear it later (if it becomes empty).
if ( !bqBlock.getCustomData( 'blockquote_processed' ) )
{
processedBlockquoteBlocks.push( bqBlock );
CKEDITOR.dom.element.setMarker( database, bqBlock, 'blockquote_processed', true );
}
movedNodes.push( node );
}
CKEDITOR.dom.element.clearAllMarkers( database );
// Clear blockquote nodes that have become empty.
for ( i = processedBlockquoteBlocks.length - 1 ; i >= 0 ; i-- )
{
bqBlock = processedBlockquoteBlocks[i];
if ( noBlockLeft( bqBlock ) )
bqBlock.remove();
}
if ( editor.config.enterMode == CKEDITOR.ENTER_BR )
{
var firstTime = true;
while ( movedNodes.length )
{
node = movedNodes.shift();
if ( node.getName() == 'div' )
{
docFrag = new CKEDITOR.dom.documentFragment( editor.document );
var needBeginBr = firstTime && node.getPrevious() &&
!( node.getPrevious().type == CKEDITOR.NODE_ELEMENT && node.getPrevious().isBlockBoundary() );
if ( needBeginBr )
docFrag.append( editor.document.createElement( 'br' ) );
var needEndBr = node.getNext() &&
!( node.getNext().type == CKEDITOR.NODE_ELEMENT && node.getNext().isBlockBoundary() );
while ( node.getFirst() )
node.getFirst().remove().appendTo( docFrag );
if ( needEndBr )
docFrag.append( editor.document.createElement( 'br' ) );
docFrag.replace( node );
firstTime = false;
}
}
}
}
selection.selectBookmarks( bookmarks );
editor.focus();
}
};
CKEDITOR.plugins.add( 'blockquote',
{
init : function( editor )
{
editor.addCommand( 'blockquote', commandObject );
editor.ui.addButton( 'Blockquote',
{
label : editor.lang.blockquote,
command : 'blockquote'
} );
editor.on( 'selectionChange', onSelectionChange );
},
requires : [ 'domiterator' ]
} );
})();
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/blockquote/plugin.js | JavaScript | asf20 | 8,767 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
// Register a templates definition set named "default".
CKEDITOR.addTemplates( 'default',
{
// The name of sub folder which hold the shortcut preview images of the
// templates.
imagesPath : CKEDITOR.getUrl( CKEDITOR.plugins.getPath( 'templates' ) + 'templates/images/' ),
// The templates definitions.
templates :
[
{
title: 'Image and Title',
image: 'template1.gif',
description: 'One main image with a title and text that surround the image.',
html:
'<h3>' +
'<img style="margin-right: 10px" height="100" width="100" align="left"/>' +
'Type the title here'+
'</h3>' +
'<p>' +
'Type the text here' +
'</p>'
},
{
title: 'Strange Template',
image: 'template2.gif',
description: 'A template that defines two colums, each one with a title, and some text.',
html:
'<table cellspacing="0" cellpadding="0" style="width:100%" border="0">' +
'<tr>' +
'<td style="width:50%">' +
'<h3>Title 1</h3>' +
'</td>' +
'<td></td>' +
'<td style="width:50%">' +
'<h3>Title 2</h3>' +
'</td>' +
'</tr>' +
'<tr>' +
'<td>' +
'Text 1' +
'</td>' +
'<td></td>' +
'<td>' +
'Text 2' +
'</td>' +
'</tr>' +
'</table>' +
'<p>' +
'More text goes here.' +
'</p>'
},
{
title: 'Text and Table',
image: 'template3.gif',
description: 'A title with some text and a table.',
html:
'<div style="width: 80%">' +
'<h3>' +
'Title goes here' +
'</h3>' +
'<table style="width:150px;float: right" cellspacing="0" cellpadding="0" border="1">' +
'<caption style="border:solid 1px black">' +
'<strong>Table title</strong>' +
'</caption>' +
'</tr>' +
'<tr>' +
'<td> </td>' +
'<td> </td>' +
'<td> </td>' +
'</tr>' +
'<tr>' +
'<td> </td>' +
'<td> </td>' +
'<td> </td>' +
'</tr>' +
'<tr>' +
'<td> </td>' +
'<td> </td>' +
'<td> </td>' +
'</tr>' +
'</table>' +
'<p>' +
'Type the text here' +
'</p>' +
'</div>'
}
]
});
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/templates/templates/default.js | JavaScript | asf20 | 2,520 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
(function()
{
CKEDITOR.plugins.add( 'templates',
{
requires : [ 'dialog' ],
init : function( editor )
{
CKEDITOR.dialog.add( 'templates', CKEDITOR.getUrl( this.path + 'dialogs/templates.js' ) );
editor.addCommand( 'templates', new CKEDITOR.dialogCommand( 'templates' ) );
editor.ui.addButton( 'Templates',
{
label : editor.lang.templates.button,
command : 'templates'
});
}
});
var templates = {},
loadedTemplatesFiles = {};
CKEDITOR.addTemplates = function( name, definition )
{
templates[ name ] = definition;
};
CKEDITOR.getTemplates = function( name )
{
return templates[ name ];
};
CKEDITOR.loadTemplates = function( templateFiles, callback )
{
// Holds the templates files to be loaded.
var toLoad = [];
// Look for pending template files to get loaded.
for ( var i = 0, count = templateFiles.length ; i < count ; i++ )
{
if ( !loadedTemplatesFiles[ templateFiles[ i ] ] )
{
toLoad.push( templateFiles[ i ] );
loadedTemplatesFiles[ templateFiles[ i ] ] = 1;
}
}
if ( toLoad.length )
CKEDITOR.scriptLoader.load( toLoad, callback );
else
setTimeout( callback, 0 );
};
})();
/**
* The templates definition set to use. It accepts a list of names separated by
* comma. It must match definitions loaded with the templates_files setting.
* @type String
* @default 'default'
* @name CKEDITOR.config.templates
* @example
* config.templates = 'my_templates';
*/
/**
* The list of templates definition files to load.
* @type (String) Array
* @default [ 'plugins/templates/templates/default.js' ]
* @example
* config.templates_files =
* [
* '/editor_templates/site_default.js',
* 'http://www.example.com/user_templates.js
* ];
*
*/
CKEDITOR.config.templates_files =
[
CKEDITOR.getUrl(
'_source/' + // @Packager.RemoveLine
'plugins/templates/templates/default.js' )
];
/**
* Whether the "Replace actual contents" checkbox is checked by default in the
* Templates dialog.
* @type Boolean
* @default true
* @example
* config.templates_replaceContent = false;
*/
CKEDITOR.config.templates_replaceContent = true;
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/templates/plugin.js | JavaScript | asf20 | 2,431 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
(function()
{
var doc = CKEDITOR.document;
CKEDITOR.dialog.add( 'templates', function( editor )
{
// Constructs the HTML view of the specified templates data.
function renderTemplatesList( container, templatesDefinitions )
{
// clear loading wait text.
container.setHtml( '' );
for ( var i = 0, totalDefs = templatesDefinitions.length ; i < totalDefs ; i++ )
{
var definition = CKEDITOR.getTemplates( templatesDefinitions[ i ] ),
imagesPath = definition.imagesPath,
templates = definition.templates,
count = templates.length;
for ( var j = 0 ; j < count ; j++ )
{
var template = templates[ j ],
item = createTemplateItem( template, imagesPath );
item.setAttribute( 'aria-posinset', j + 1 );
item.setAttribute( 'aria-setsize', count );
container.append( item );
}
}
}
function createTemplateItem( template, imagesPath )
{
var item = CKEDITOR.dom.element.createFromHtml(
'<a href="javascript:void(0)" tabIndex="-1" role="option" >' +
'<div class="cke_tpl_item"></div>' +
'</a>' );
// Build the inner HTML of our new item DIV.
var html = '<table style="width:350px;" class="cke_tpl_preview" role="presentation"><tr>';
if ( template.image && imagesPath )
html += '<td class="cke_tpl_preview_img"><img src="' + CKEDITOR.getUrl( imagesPath + template.image ) + '"' + ( CKEDITOR.env.ie6Compat ? ' onload="this.width=this.width"' : '' ) + ' alt="" title=""></td>';
html += '<td style="white-space:normal;"><span class="cke_tpl_title">' + template.title + '</span><br/>';
if ( template.description )
html += '<span>' + template.description + '</span>';
html += '</td></tr></table>';
item.getFirst().setHtml( html );
item.on( 'click', function() { insertTemplate( template.html ); } );
return item;
}
/**
* Insert the specified template content into editor.
* @param {Number} index
*/
function insertTemplate( html )
{
var dialog = CKEDITOR.dialog.getCurrent(),
isInsert = dialog.getValueOf( 'selectTpl', 'chkInsertOpt' );
if ( isInsert )
{
// Everything should happen after the document is loaded (#4073).
editor.on( 'contentDom', function( evt )
{
evt.removeListener();
dialog.hide();
// Place the cursor at the first editable place.
var range = new CKEDITOR.dom.range( editor.document );
range.moveToElementEditStart( editor.document.getBody() );
range.select( 1 );
setTimeout( function()
{
editor.fire( 'saveSnapshot' );
}, 0 );
});
editor.fire( 'saveSnapshot' );
editor.setData( html );
}
else
{
editor.insertHtml( html );
dialog.hide();
}
}
function keyNavigation( evt )
{
var target = evt.data.getTarget(),
onList = listContainer.equals( target );
// Keyboard navigation for template list.
if ( onList || listContainer.contains( target ) )
{
var keystroke = evt.data.getKeystroke(),
items = listContainer.getElementsByTag( 'a' ),
focusItem;
if ( items )
{
// Focus not yet onto list items?
if ( onList )
focusItem = items.getItem( 0 );
else
{
switch ( keystroke )
{
case 40 : // ARROW-DOWN
focusItem = target.getNext();
break;
case 38 : // ARROW-UP
focusItem = target.getPrevious();
break;
case 13 : // ENTER
case 32 : // SPACE
target.fire( 'click' );
}
}
if ( focusItem )
{
focusItem.focus();
evt.data.preventDefault();
}
}
}
}
// Load skin at first.
CKEDITOR.skins.load( editor, 'templates' );
var listContainer;
var templateListLabelId = 'cke_tpl_list_label_' + CKEDITOR.tools.getNextNumber(),
lang = editor.lang.templates,
config = editor.config;
return {
title :editor.lang.templates.title,
minWidth : CKEDITOR.env.ie ? 440 : 400,
minHeight : 340,
contents :
[
{
id :'selectTpl',
label : lang.title,
elements :
[
{
type : 'vbox',
padding : 5,
children :
[
{
id : 'selectTplText',
type : 'html',
html :
'<span>' +
lang.selectPromptMsg +
'</span>'
},
{
id : 'templatesList',
type : 'html',
focus: true,
html :
'<div class="cke_tpl_list" tabIndex="-1" role="listbox" aria-labelledby="' + templateListLabelId+ '">' +
'<div class="cke_tpl_loading"><span></span></div>' +
'</div>' +
'<span class="cke_voice_label" id="' + templateListLabelId + '">' + lang.options+ '</span>'
},
{
id : 'chkInsertOpt',
type : 'checkbox',
label : lang.insertOption,
'default' : config.templates_replaceContent
}
]
}
]
}
],
buttons : [ CKEDITOR.dialog.cancelButton ],
onShow : function()
{
var templatesListField = this.getContentElement( 'selectTpl' , 'templatesList' );
listContainer = templatesListField.getElement();
CKEDITOR.loadTemplates( config.templates_files, function()
{
var templates = ( config.templates || 'default' ).split( ',' );
if ( templates.length )
{
renderTemplatesList( listContainer, templates );
templatesListField.focus();
}
else
{
listContainer.setHtml(
'<div class="cke_tpl_empty">' +
'<span>' + lang.emptyListMsg + '</span>' +
'</div>' );
}
});
this._.element.on( 'keydown', keyNavigation );
},
onHide : function()
{
this._.element.removeListener( 'keydown', keyNavigation );
}
};
});
})();
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/templates/dialogs/templates.js | JavaScript | asf20 | 6,361 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
(function()
{
// Regex to scan for at the end of blocks, which are actually placeholders.
// Safari transforms the to \xa0. (#4172)
var tailNbspRegex = /^[\t\r\n ]*(?: |\xa0)$/;
var protectedSourceMarker = '{cke_protected}';
// Return the last non-space child node of the block (#4344).
function lastNoneSpaceChild( block )
{
var lastIndex = block.children.length,
last = block.children[ lastIndex - 1 ];
while ( last && last.type == CKEDITOR.NODE_TEXT && !CKEDITOR.tools.trim( last.value ) )
last = block.children[ --lastIndex ];
return last;
}
function trimFillers( block, fromSource )
{
// If the current node is a block, and if we're converting from source or
// we're not in IE then search for and remove any tailing BR node.
//
// Also, any at the end of blocks are fillers, remove them as well.
// (#2886)
var children = block.children, lastChild = lastNoneSpaceChild( block );
if ( lastChild )
{
if ( ( fromSource || !CKEDITOR.env.ie ) && lastChild.type == CKEDITOR.NODE_ELEMENT && lastChild.name == 'br' )
children.pop();
if ( lastChild.type == CKEDITOR.NODE_TEXT && tailNbspRegex.test( lastChild.value ) )
children.pop();
}
}
function blockNeedsExtension( block, fromSource, extendEmptyBlock )
{
if( !fromSource && ( !extendEmptyBlock ||
typeof extendEmptyBlock == 'function' && ( extendEmptyBlock( block ) === false ) ) )
return false;
// 1. For IE version >=8, empty blocks are displayed correctly themself in wysiwiyg;
// 2. For the rest, at least table cell and list item need no filler space.
// (#6248)
if ( fromSource && CKEDITOR.env.ie &&
( document.documentMode > 7
|| block.name in CKEDITOR.dtd.tr
|| block.name in CKEDITOR.dtd.$listItem ) )
return false;
var lastChild = lastNoneSpaceChild( block );
return !lastChild || lastChild &&
( lastChild.type == CKEDITOR.NODE_ELEMENT && lastChild.name == 'br'
// Some of the controls in form needs extension too,
// to move cursor at the end of the form. (#4791)
|| block.name == 'form' && lastChild.name == 'input' );
}
function getBlockExtension( isOutput, emptyBlockFiller )
{
return function( node )
{
trimFillers( node, !isOutput );
if ( blockNeedsExtension( node, !isOutput, emptyBlockFiller ) )
{
if ( isOutput || CKEDITOR.env.ie )
node.add( new CKEDITOR.htmlParser.text( '\xa0' ) );
else
node.add( new CKEDITOR.htmlParser.element( 'br', {} ) );
}
};
}
var dtd = CKEDITOR.dtd;
// Define orders of table elements.
var tableOrder = [ 'caption', 'colgroup', 'col', 'thead', 'tfoot', 'tbody' ];
// Find out the list of block-like tags that can contain <br>.
var blockLikeTags = CKEDITOR.tools.extend( {}, dtd.$block, dtd.$listItem, dtd.$tableContent );
for ( var i in blockLikeTags )
{
if ( ! ( 'br' in dtd[i] ) )
delete blockLikeTags[i];
}
// We just avoid filler in <pre> right now.
// TODO: Support filler for <pre>, line break is also occupy line height.
delete blockLikeTags.pre;
var defaultDataFilterRules =
{
elements : {},
attributeNames :
[
// Event attributes (onXYZ) must not be directly set. They can become
// active in the editing area (IE|WebKit).
[ ( /^on/ ), 'data-cke-pa-on' ]
]
};
var defaultDataBlockFilterRules = { elements : {} };
for ( i in blockLikeTags )
defaultDataBlockFilterRules.elements[ i ] = getBlockExtension();
var defaultHtmlFilterRules =
{
elementNames :
[
// Remove the "cke:" namespace prefix.
[ ( /^cke:/ ), '' ],
// Ignore <?xml:namespace> tags.
[ ( /^\?xml:namespace$/ ), '' ]
],
attributeNames :
[
// Attributes saved for changes and protected attributes.
[ ( /^data-cke-(saved|pa)-/ ), '' ],
// All "data-cke-" attributes are to be ignored.
[ ( /^data-cke-.*/ ), '' ],
[ 'hidefocus', '' ]
],
elements :
{
$ : function( element )
{
var attribs = element.attributes;
if ( attribs )
{
// Elements marked as temporary are to be ignored.
if ( attribs[ 'data-cke-temp' ] )
return false;
// Remove duplicated attributes - #3789.
var attributeNames = [ 'name', 'href', 'src' ],
savedAttributeName;
for ( var i = 0 ; i < attributeNames.length ; i++ )
{
savedAttributeName = 'data-cke-saved-' + attributeNames[ i ];
savedAttributeName in attribs && ( delete attribs[ attributeNames[ i ] ] );
}
}
return element;
},
// The contents of table should be in correct order (#4809).
table : function( element )
{
var children = element.children;
children.sort( function ( node1, node2 )
{
return node1.type == CKEDITOR.NODE_ELEMENT && node2.type == node1.type ?
CKEDITOR.tools.indexOf( tableOrder, node1.name ) > CKEDITOR.tools.indexOf( tableOrder, node2.name ) ? 1 : -1 : 0;
} );
},
embed : function( element )
{
var parent = element.parent;
// If the <embed> is child of a <object>, copy the width
// and height attributes from it.
if ( parent && parent.name == 'object' )
{
var parentWidth = parent.attributes.width,
parentHeight = parent.attributes.height;
parentWidth && ( element.attributes.width = parentWidth );
parentHeight && ( element.attributes.height = parentHeight );
}
},
// Restore param elements into self-closing.
param : function( param )
{
param.children = [];
param.isEmpty = true;
return param;
},
// Remove empty link but not empty anchor.(#3829)
a : function( element )
{
if ( !( element.children.length ||
element.attributes.name ||
element.attributes[ 'data-cke-saved-name' ] ) )
{
return false;
}
},
// Remove dummy span in webkit.
span: function( element )
{
if ( element.attributes[ 'class' ] == 'Apple-style-span' )
delete element.name;
},
// Empty <pre> in IE is reported with filler node ( ).
pre : function( element ) { CKEDITOR.env.ie && trimFillers( element ); },
html : function( element )
{
delete element.attributes.contenteditable;
delete element.attributes[ 'class' ];
},
body : function( element )
{
delete element.attributes.spellcheck;
delete element.attributes.contenteditable;
},
style : function( element )
{
var child = element.children[ 0 ];
child && child.value && ( child.value = CKEDITOR.tools.trim( child.value ));
if ( !element.attributes.type )
element.attributes.type = 'text/css';
},
title : function( element )
{
var titleText = element.children[ 0 ];
titleText && ( titleText.value = element.attributes[ 'data-cke-title' ] || '' );
}
},
attributes :
{
'class' : function( value, element )
{
// Remove all class names starting with "cke_".
return CKEDITOR.tools.ltrim( value.replace( /(?:^|\s+)cke_[^\s]*/g, '' ) ) || false;
}
}
};
if ( CKEDITOR.env.ie )
{
// IE outputs style attribute in capital letters. We should convert
// them back to lower case, while not hurting the values (#5930)
defaultHtmlFilterRules.attributes.style = function( value, element )
{
return value.replace( /(^|;)([^\:]+)/g, function( match )
{
return match.toLowerCase();
});
};
}
function protectReadOnly( element )
{
var attrs = element.attributes;
// We should flag that the element was locked by our code so
// it'll be editable by the editor functions (#6046).
if ( attrs.contenteditable != "false" )
attrs[ 'data-cke-editable' ] = attrs.contenteditable ? 'true' : 1;
attrs.contenteditable = "false";
}
function unprotectReadyOnly( element )
{
var attrs = element.attributes;
switch( attrs[ 'data-cke-editable' ] )
{
case 'true': attrs.contenteditable = 'true'; break;
case '1': delete attrs.contenteditable; break;
}
}
// Disable form elements editing mode provided by some browers. (#5746)
for ( i in { input : 1, textarea : 1 } )
{
defaultDataFilterRules.elements[ i ] = protectReadOnly;
defaultHtmlFilterRules.elements[ i ] = unprotectReadyOnly;
}
var protectElementRegex = /<(a|area|img|input)\b([^>]*)>/gi,
protectAttributeRegex = /\b(on\w+|href|src|name)\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|(?:[^ "'>]+))/gi;
var protectElementsRegex = /(?:<style(?=[ >])[^>]*>[\s\S]*<\/style>)|(?:<(:?link|meta|base)[^>]*>)/gi,
encodedElementsRegex = /<cke:encoded>([^<]*)<\/cke:encoded>/gi;
var protectElementNamesRegex = /(<\/?)((?:object|embed|param|html|body|head|title)[^>]*>)/gi,
unprotectElementNamesRegex = /(<\/?)cke:((?:html|body|head|title)[^>]*>)/gi;
var protectSelfClosingRegex = /<cke:(param|embed)([^>]*?)\/?>(?!\s*<\/cke:\1)/gi;
function protectAttributes( html )
{
return html.replace( protectElementRegex, function( element, tag, attributes )
{
return '<' + tag + attributes.replace( protectAttributeRegex, function( fullAttr, attrName )
{
// Avoid corrupting the inline event attributes (#7243).
// We should not rewrite the existed protected attributes, e.g. clipboard content from editor. (#5218)
if ( !( /^on/ ).test( attrName ) && attributes.indexOf( 'data-cke-saved-' + attrName ) == -1 )
return ' data-cke-saved-' + fullAttr + ' data-cke-' + CKEDITOR.rnd + '-' + fullAttr;
return fullAttr;
}) + '>';
});
}
function protectElements( html )
{
return html.replace( protectElementsRegex, function( match )
{
return '<cke:encoded>' + encodeURIComponent( match ) + '</cke:encoded>';
});
}
function unprotectElements( html )
{
return html.replace( encodedElementsRegex, function( match, encoded )
{
return decodeURIComponent( encoded );
});
}
function protectElementsNames( html )
{
return html.replace( protectElementNamesRegex, '$1cke:$2');
}
function unprotectElementNames( html )
{
return html.replace( unprotectElementNamesRegex, '$1$2' );
}
function protectSelfClosingElements( html )
{
return html.replace( protectSelfClosingRegex, '<cke:$1$2></cke:$1>' );
}
function protectPreFormatted( html )
{
return html.replace( /(<pre\b[^>]*>)(\r\n|\n)/g, '$1$2$2' );
}
function protectRealComments( html )
{
return html.replace( /<!--(?!{cke_protected})[\s\S]+?-->/g, function( match )
{
return '<!--' + protectedSourceMarker +
'{C}' +
encodeURIComponent( match ).replace( /--/g, '%2D%2D' ) +
'-->';
});
}
function unprotectRealComments( html )
{
return html.replace( /<!--\{cke_protected\}\{C\}([\s\S]+?)-->/g, function( match, data )
{
return decodeURIComponent( data );
});
}
function unprotectSource( html, editor )
{
var store = editor._.dataStore;
return html.replace( /<!--\{cke_protected\}([\s\S]+?)-->/g, function( match, data )
{
return decodeURIComponent( data );
}).replace( /\{cke_protected_(\d+)\}/g, function( match, id )
{
return store && store[ id ] || '';
});
}
function protectSource( data, editor )
{
var protectedHtml = [],
protectRegexes = editor.config.protectedSource,
store = editor._.dataStore || ( editor._.dataStore = { id : 1 } ),
tempRegex = /<\!--\{cke_temp(comment)?\}(\d*?)-->/g;
var regexes =
[
// Script tags will also be forced to be protected, otherwise
// IE will execute them.
( /<script[\s\S]*?<\/script>/gi ),
// <noscript> tags (get lost in IE and messed up in FF).
/<noscript[\s\S]*?<\/noscript>/gi
]
.concat( protectRegexes );
// First of any other protection, we must protect all comments
// to avoid loosing them (of course, IE related).
// Note that we use a different tag for comments, as we need to
// transform them when applying filters.
data = data.replace( (/<!--[\s\S]*?-->/g), function( match )
{
return '<!--{cke_tempcomment}' + ( protectedHtml.push( match ) - 1 ) + '-->';
});
for ( var i = 0 ; i < regexes.length ; i++ )
{
data = data.replace( regexes[i], function( match )
{
match = match.replace( tempRegex, // There could be protected source inside another one. (#3869).
function( $, isComment, id )
{
return protectedHtml[ id ];
}
);
// Avoid protecting over protected, e.g. /\{.*?\}/
return ( /cke_temp(comment)?/ ).test( match ) ? match
: '<!--{cke_temp}' + ( protectedHtml.push( match ) - 1 ) + '-->';
});
}
data = data.replace( tempRegex, function( $, isComment, id )
{
return '<!--' + protectedSourceMarker +
( isComment ? '{C}' : '' ) +
encodeURIComponent( protectedHtml[ id ] ).replace( /--/g, '%2D%2D' ) +
'-->';
}
);
// Different protection pattern is used for those that
// live in attributes to avoid from being HTML encoded.
return data.replace( /(['"]).*?\1/g, function ( match )
{
return match.replace( /<!--\{cke_protected\}([\s\S]+?)-->/g, function( match, data )
{
store[ store.id ] = decodeURIComponent( data );
return '{cke_protected_'+ ( store.id++ ) + '}';
});
});
}
CKEDITOR.plugins.add( 'htmldataprocessor',
{
requires : [ 'htmlwriter' ],
init : function( editor )
{
var dataProcessor = editor.dataProcessor = new CKEDITOR.htmlDataProcessor( editor );
dataProcessor.writer.forceSimpleAmpersand = editor.config.forceSimpleAmpersand;
dataProcessor.dataFilter.addRules( defaultDataFilterRules );
dataProcessor.dataFilter.addRules( defaultDataBlockFilterRules );
dataProcessor.htmlFilter.addRules( defaultHtmlFilterRules );
var defaultHtmlBlockFilterRules = { elements : {} };
for ( i in blockLikeTags )
defaultHtmlBlockFilterRules.elements[ i ] = getBlockExtension( true, editor.config.fillEmptyBlocks );
dataProcessor.htmlFilter.addRules( defaultHtmlBlockFilterRules );
},
onLoad : function()
{
! ( 'fillEmptyBlocks' in CKEDITOR.config ) && ( CKEDITOR.config.fillEmptyBlocks = 1 );
}
});
CKEDITOR.htmlDataProcessor = function( editor )
{
this.editor = editor;
this.writer = new CKEDITOR.htmlWriter();
this.dataFilter = new CKEDITOR.htmlParser.filter();
this.htmlFilter = new CKEDITOR.htmlParser.filter();
};
CKEDITOR.htmlDataProcessor.prototype =
{
toHtml : function( data, fixForBody )
{
// The source data is already HTML, but we need to clean
// it up and apply the filter.
data = protectSource( data, this.editor );
// Before anything, we must protect the URL attributes as the
// browser may changing them when setting the innerHTML later in
// the code.
data = protectAttributes( data );
// Protect elements than can't be set inside a DIV. E.g. IE removes
// style tags from innerHTML. (#3710)
data = protectElements( data );
// Certain elements has problem to go through DOM operation, protect
// them by prefixing 'cke' namespace. (#3591)
data = protectElementsNames( data );
// All none-IE browsers ignore self-closed custom elements,
// protecting them into open-close. (#3591)
data = protectSelfClosingElements( data );
// Compensate one leading line break after <pre> open as browsers
// eat it up. (#5789)
data = protectPreFormatted( data );
// Call the browser to help us fixing a possibly invalid HTML
// structure.
var div = new CKEDITOR.dom.element( 'div' );
// Add fake character to workaround IE comments bug. (#3801)
div.setHtml( 'a' + data );
data = div.getHtml().substr( 1 );
// Restore shortly protected attribute names.
data = data.replace( new RegExp( ' data-cke-' + CKEDITOR.rnd + '-', 'ig' ), ' ' );
// Unprotect "some" of the protected elements at this point.
data = unprotectElementNames( data );
data = unprotectElements( data );
// Restore the comments that have been protected, in this way they
// can be properly filtered.
data = unprotectRealComments( data );
// Now use our parser to make further fixes to the structure, as
// well as apply the filter.
var fragment = CKEDITOR.htmlParser.fragment.fromHtml( data, fixForBody ),
writer = new CKEDITOR.htmlParser.basicWriter();
fragment.writeHtml( writer, this.dataFilter );
data = writer.getHtml( true );
// Protect the real comments again.
data = protectRealComments( data );
return data;
},
toDataFormat : function( html, fixForBody )
{
var writer = this.writer,
fragment = CKEDITOR.htmlParser.fragment.fromHtml( html, fixForBody );
writer.reset();
fragment.writeHtml( writer, this.htmlFilter );
var data = writer.getHtml( true );
// Restore those non-HTML protected source. (#4475,#4880)
data = unprotectRealComments( data );
data = unprotectSource( data, this.editor );
return data;
}
};
})();
/**
* Whether to force using "&" instead of "&amp;" in elements attributes
* values, it's not recommended to change this setting for compliance with the
* W3C XHTML 1.0 standards (<a href="http://www.w3.org/TR/xhtml1/#C_12">C.12, XHTML 1.0</a>).
* @name CKEDITOR.config.forceSimpleAmpersand
* @name CKEDITOR.config.forceSimpleAmpersand
* @type Boolean
* @default false
* @example
* config.forceSimpleAmpersand = false;
*/
/**
* Whether a filler text (non-breaking space entity - ) will be inserted into empty block elements in HTML output,
* this is used to render block elements properly with line-height; When a function is instead specified,
* it'll be passed a {@link CKEDITOR.htmlParser.element} to decide whether adding the filler text
* by expecting a boolean return value.
* @name CKEDITOR.config.fillEmptyBlocks
* @since 3.5
* @type Boolean
* @default true
* @example
* config.fillEmptyBlocks = false; // Prevent filler nodes in all empty blocks.
*
* // Prevent filler node only in float cleaners.
* config.fillEmptyBlocks = function( element )
* {
* if ( element.attributes[ 'class' ].indexOf ( 'clear-both' ) != -1 )
* return false;
* }
*/
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/htmldataprocessor/plugin.js | JavaScript | asf20 | 18,781 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @fileOverview Defines the {@link CKEDITOR.ajax} object, which holds ajax methods for
* data loading.
*/
(function()
{
CKEDITOR.plugins.add( 'ajax',
{
requires : [ 'xml' ]
});
/**
* Ajax methods for data loading.
* @namespace
* @example
*/
CKEDITOR.ajax = (function()
{
var createXMLHttpRequest = function()
{
// In IE, using the native XMLHttpRequest for local files may throw
// "Access is Denied" errors.
if ( !CKEDITOR.env.ie || location.protocol != 'file:' )
try { return new XMLHttpRequest(); } catch(e) {}
try { return new ActiveXObject( 'Msxml2.XMLHTTP' ); } catch (e) {}
try { return new ActiveXObject( 'Microsoft.XMLHTTP' ); } catch (e) {}
return null;
};
var checkStatus = function( xhr )
{
// HTTP Status Codes:
// 2xx : Success
// 304 : Not Modified
// 0 : Returned when running locally (file://)
// 1223 : IE may change 204 to 1223 (see http://dev.jquery.com/ticket/1450)
return ( xhr.readyState == 4 &&
( ( xhr.status >= 200 && xhr.status < 300 ) ||
xhr.status == 304 ||
xhr.status === 0 ||
xhr.status == 1223 ) );
};
var getResponseText = function( xhr )
{
if ( checkStatus( xhr ) )
return xhr.responseText;
return null;
};
var getResponseXml = function( xhr )
{
if ( checkStatus( xhr ) )
{
var xml = xhr.responseXML;
return new CKEDITOR.xml( xml && xml.firstChild ? xml : xhr.responseText );
}
return null;
};
var load = function( url, callback, getResponseFn )
{
var async = !!callback;
var xhr = createXMLHttpRequest();
if ( !xhr )
return null;
xhr.open( 'GET', url, async );
if ( async )
{
// TODO: perform leak checks on this closure.
/** @ignore */
xhr.onreadystatechange = function()
{
if ( xhr.readyState == 4 )
{
callback( getResponseFn( xhr ) );
xhr = null;
}
};
}
xhr.send(null);
return async ? '' : getResponseFn( xhr );
};
return /** @lends CKEDITOR.ajax */ {
/**
* Loads data from an URL as plain text.
* @param {String} url The URL from which load data.
* @param {Function} [callback] A callback function to be called on
* data load. If not provided, the data will be loaded
* synchronously.
* @returns {String} The loaded data. For asynchronous requests, an
* empty string. For invalid requests, null.
* @example
* // Load data synchronously.
* var data = CKEDITOR.ajax.load( 'somedata.txt' );
* alert( data );
* @example
* // Load data asynchronously.
* var data = CKEDITOR.ajax.load( 'somedata.txt', function( data )
* {
* alert( data );
* } );
*/
load : function( url, callback )
{
return load( url, callback, getResponseText );
},
/**
* Loads data from an URL as XML.
* @param {String} url The URL from which load data.
* @param {Function} [callback] A callback function to be called on
* data load. If not provided, the data will be loaded
* synchronously.
* @returns {CKEDITOR.xml} An XML object holding the loaded data. For asynchronous requests, an
* empty string. For invalid requests, null.
* @example
* // Load XML synchronously.
* var xml = CKEDITOR.ajax.loadXml( 'somedata.xml' );
* alert( xml.getInnerXml( '//' ) );
* @example
* // Load XML asynchronously.
* var data = CKEDITOR.ajax.loadXml( 'somedata.xml', function( xml )
* {
* alert( xml.getInnerXml( '//' ) );
* } );
*/
loadXml : function( url, callback )
{
return load( url, callback, getResponseXml );
}
};
})();
})();
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/ajax/plugin.js | JavaScript | asf20 | 3,996 |
<script>
var doc = document;
doc.open();
doc.write( window.opener._cke_htmlToLoad );
doc.close();
delete window.opener._cke_htmlToLoad;
</script>
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/preview/preview.html | HTML | asf20 | 159 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @file Preview plugin.
*/
(function()
{
var pluginPath;
var previewCmd =
{
modes : { wysiwyg:1, source:1 },
canUndo : false,
readOnly : 1,
exec : function( editor )
{
var sHTML,
config = editor.config,
baseTag = config.baseHref ? '<base href="' + config.baseHref + '"/>' : '',
isCustomDomain = CKEDITOR.env.isCustomDomain();
if ( config.fullPage )
{
sHTML = editor.getData()
.replace( /<head>/, '$&' + baseTag )
.replace( /[^>]*(?=<\/title>)/, '$& — ' + editor.lang.preview );
}
else
{
var bodyHtml = '<body ',
body = editor.document && editor.document.getBody();
if ( body )
{
if ( body.getAttribute( 'id' ) )
bodyHtml += 'id="' + body.getAttribute( 'id' ) + '" ';
if ( body.getAttribute( 'class' ) )
bodyHtml += 'class="' + body.getAttribute( 'class' ) + '" ';
}
bodyHtml += '>';
sHTML =
editor.config.docType +
'<html dir="' + editor.config.contentsLangDirection + '">' +
'<head>' +
baseTag +
'<title>' + editor.lang.preview + '</title>' +
CKEDITOR.tools.buildStyleHtml( editor.config.contentsCss ) +
'</head>' + bodyHtml +
editor.getData() +
'</body></html>';
}
var iWidth = 640, // 800 * 0.8,
iHeight = 420, // 600 * 0.7,
iLeft = 80; // (800 - 0.8 * 800) /2 = 800 * 0.1.
try
{
var screen = window.screen;
iWidth = Math.round( screen.width * 0.8 );
iHeight = Math.round( screen.height * 0.7 );
iLeft = Math.round( screen.width * 0.1 );
}
catch ( e ){}
var sOpenUrl = '';
if ( isCustomDomain )
{
window._cke_htmlToLoad = sHTML;
sOpenUrl = 'javascript:void( (function(){' +
'document.open();' +
'document.domain="' + document.domain + '";' +
'document.write( window.opener._cke_htmlToLoad );' +
'document.close();' +
'window.opener._cke_htmlToLoad = null;' +
'})() )';
}
// With Firefox only, we need to open a special preview page, so
// anchors will work properly on it. (#9047)
if ( CKEDITOR.env.gecko )
{
window._cke_htmlToLoad = sHTML;
sOpenUrl = pluginPath + 'preview.html';
}
var oWindow = window.open( sOpenUrl, null, 'toolbar=yes,location=no,status=yes,menubar=yes,scrollbars=yes,resizable=yes,width=' +
iWidth + ',height=' + iHeight + ',left=' + iLeft );
if ( !isCustomDomain && !CKEDITOR.env.gecko )
{
var doc = oWindow.document;
doc.open();
doc.write( sHTML );
doc.close();
// Chrome will need this to show the embedded. (#8016)
CKEDITOR.env.webkit && setTimeout( function() { doc.body.innerHTML += ''; }, 0 );
}
}
};
var pluginName = 'preview';
// Register a plugin named "preview".
CKEDITOR.plugins.add( pluginName,
{
init : function( editor )
{
pluginPath = this.path;
editor.addCommand( pluginName, previewCmd );
editor.ui.addButton( 'Preview',
{
label : editor.lang.preview,
command : pluginName
});
}
});
})();
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/preview/plugin.js | JavaScript | asf20 | 3,285 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
(function()
{
var meta =
{
editorFocus : false,
modes : { wysiwyg:1, source:1 }
};
var blurCommand =
{
exec : function( editor )
{
editor.container.focusNext( true, editor.tabIndex );
}
};
var blurBackCommand =
{
exec : function( editor )
{
editor.container.focusPrevious( true, editor.tabIndex );
}
};
function selectNextCellCommand( backward )
{
return {
editorFocus : false,
canUndo : false,
modes : { wysiwyg : 1 },
exec : function( editor )
{
if ( editor.focusManager.hasFocus )
{
var sel = editor.getSelection(),
ancestor = sel.getCommonAncestor(),
cell;
if ( ( cell = ( ancestor.getAscendant( 'td', true ) || ancestor.getAscendant( 'th', true ) ) ) )
{
var resultRange = new CKEDITOR.dom.range( editor.document ),
next = CKEDITOR.tools.tryThese( function()
{
var row = cell.getParent(),
next = row.$.cells[ cell.$.cellIndex + ( backward ? - 1 : 1 ) ];
// Invalid any empty value.
next.parentNode.parentNode;
return next;
},
function()
{
var row = cell.getParent(),
table = row.getAscendant( 'table' ),
nextRow = table.$.rows[ row.$.rowIndex + ( backward ? - 1 : 1 ) ];
return nextRow.cells[ backward? nextRow.cells.length -1 : 0 ];
});
// Clone one more row at the end of table and select the first newly established cell.
if ( ! ( next || backward ) )
{
var table = cell.getAscendant( 'table' ).$,
cells = cell.getParent().$.cells;
var newRow = new CKEDITOR.dom.element( table.insertRow( -1 ), editor.document );
for ( var i = 0, count = cells.length ; i < count; i++ )
{
var newCell = newRow.append( new CKEDITOR.dom.element(
cells[ i ], editor.document ).clone( false, false ) );
!CKEDITOR.env.ie && newCell.appendBogus();
}
resultRange.moveToElementEditStart( newRow );
}
else if ( next )
{
next = new CKEDITOR.dom.element( next );
resultRange.moveToElementEditStart( next );
// Avoid selecting empty block makes the cursor blind.
if ( !( resultRange.checkStartOfBlock() && resultRange.checkEndOfBlock() ) )
resultRange.selectNodeContents( next );
}
else
return true;
resultRange.select( true );
return true;
}
}
return false;
}
};
}
CKEDITOR.plugins.add( 'tab',
{
requires : [ 'keystrokes' ],
init : function( editor )
{
var tabTools = editor.config.enableTabKeyTools !== false,
tabSpaces = editor.config.tabSpaces || 0,
tabText = '';
while ( tabSpaces-- )
tabText += '\xa0';
if ( tabText )
{
editor.on( 'key', function( ev )
{
if ( ev.data.keyCode == 9 ) // TAB
{
editor.insertHtml( tabText );
ev.cancel();
}
});
}
if ( tabTools )
{
editor.on( 'key', function( ev )
{
if ( ev.data.keyCode == 9 && editor.execCommand( 'selectNextCell' ) || // TAB
ev.data.keyCode == ( CKEDITOR.SHIFT + 9 ) && editor.execCommand( 'selectPreviousCell' ) ) // SHIFT+TAB
ev.cancel();
});
}
if ( CKEDITOR.env.webkit || CKEDITOR.env.gecko )
{
editor.on( 'key', function( ev )
{
var keyCode = ev.data.keyCode;
if ( keyCode == 9 && !tabText ) // TAB
{
ev.cancel();
editor.execCommand( 'blur' );
}
if ( keyCode == ( CKEDITOR.SHIFT + 9 ) ) // SHIFT+TAB
{
editor.execCommand( 'blurBack' );
ev.cancel();
}
});
}
editor.addCommand( 'blur', CKEDITOR.tools.extend( blurCommand, meta ) );
editor.addCommand( 'blurBack', CKEDITOR.tools.extend( blurBackCommand, meta ) );
editor.addCommand( 'selectNextCell', selectNextCellCommand() );
editor.addCommand( 'selectPreviousCell', selectNextCellCommand( true ) );
}
});
})();
/**
* Moves the UI focus to the element following this element in the tabindex
* order.
* @example
* var element = CKEDITOR.document.getById( 'example' );
* element.focusNext();
*/
CKEDITOR.dom.element.prototype.focusNext = function( ignoreChildren, indexToUse )
{
var $ = this.$,
curTabIndex = ( indexToUse === undefined ? this.getTabIndex() : indexToUse ),
passedCurrent, enteredCurrent,
elected, electedTabIndex,
element, elementTabIndex;
if ( curTabIndex <= 0 )
{
// If this element has tabindex <= 0 then we must simply look for any
// element following it containing tabindex=0.
element = this.getNextSourceNode( ignoreChildren, CKEDITOR.NODE_ELEMENT );
while ( element )
{
if ( element.isVisible() && element.getTabIndex() === 0 )
{
elected = element;
break;
}
element = element.getNextSourceNode( false, CKEDITOR.NODE_ELEMENT );
}
}
else
{
// If this element has tabindex > 0 then we must look for:
// 1. An element following this element with the same tabindex.
// 2. The first element in source other with the lowest tabindex
// that is higher than this element tabindex.
// 3. The first element with tabindex=0.
element = this.getDocument().getBody().getFirst();
while ( ( element = element.getNextSourceNode( false, CKEDITOR.NODE_ELEMENT ) ) )
{
if ( !passedCurrent )
{
if ( !enteredCurrent && element.equals( this ) )
{
enteredCurrent = true;
// Ignore this element, if required.
if ( ignoreChildren )
{
if ( !( element = element.getNextSourceNode( true, CKEDITOR.NODE_ELEMENT ) ) )
break;
passedCurrent = 1;
}
}
else if ( enteredCurrent && !this.contains( element ) )
passedCurrent = 1;
}
if ( !element.isVisible() || ( elementTabIndex = element.getTabIndex() ) < 0 )
continue;
if ( passedCurrent && elementTabIndex == curTabIndex )
{
elected = element;
break;
}
if ( elementTabIndex > curTabIndex && ( !elected || !electedTabIndex || elementTabIndex < electedTabIndex ) )
{
elected = element;
electedTabIndex = elementTabIndex;
}
else if ( !elected && elementTabIndex === 0 )
{
elected = element;
electedTabIndex = elementTabIndex;
}
}
}
if ( elected )
elected.focus();
};
/**
* Moves the UI focus to the element before this element in the tabindex order.
* @example
* var element = CKEDITOR.document.getById( 'example' );
* element.focusPrevious();
*/
CKEDITOR.dom.element.prototype.focusPrevious = function( ignoreChildren, indexToUse )
{
var $ = this.$,
curTabIndex = ( indexToUse === undefined ? this.getTabIndex() : indexToUse ),
passedCurrent, enteredCurrent,
elected,
electedTabIndex = 0,
elementTabIndex;
var element = this.getDocument().getBody().getLast();
while ( ( element = element.getPreviousSourceNode( false, CKEDITOR.NODE_ELEMENT ) ) )
{
if ( !passedCurrent )
{
if ( !enteredCurrent && element.equals( this ) )
{
enteredCurrent = true;
// Ignore this element, if required.
if ( ignoreChildren )
{
if ( !( element = element.getPreviousSourceNode( true, CKEDITOR.NODE_ELEMENT ) ) )
break;
passedCurrent = 1;
}
}
else if ( enteredCurrent && !this.contains( element ) )
passedCurrent = 1;
}
if ( !element.isVisible() || ( elementTabIndex = element.getTabIndex() ) < 0 )
continue;
if ( curTabIndex <= 0 )
{
// If this element has tabindex <= 0 then we must look for:
// 1. An element before this one containing tabindex=0.
// 2. The last element with the highest tabindex.
if ( passedCurrent && elementTabIndex === 0 )
{
elected = element;
break;
}
if ( elementTabIndex > electedTabIndex )
{
elected = element;
electedTabIndex = elementTabIndex;
}
}
else
{
// If this element has tabindex > 0 we must look for:
// 1. An element preceeding this one, with the same tabindex.
// 2. The last element in source other with the highest tabindex
// that is lower than this element tabindex.
if ( passedCurrent && elementTabIndex == curTabIndex )
{
elected = element;
break;
}
if ( elementTabIndex < curTabIndex && ( !elected || elementTabIndex > electedTabIndex ) )
{
elected = element;
electedTabIndex = elementTabIndex;
}
}
}
if ( elected )
elected.focus();
};
/**
* Intructs the editor to add a number of spaces (&nbsp;) to the text when
* hitting the TAB key. If set to zero, the TAB key will be used to move the
* cursor focus to the next element in the page, out of the editor focus.
* @name CKEDITOR.config.tabSpaces
* @type Number
* @default 0
* @example
* config.tabSpaces = 4;
*/
/**
* Allow context-sensitive tab key behaviors, including the following scenarios:
* <h5>When selection is anchored inside <b>table cells</b>:</h5>
* <ul>
* <li>If TAB is pressed, select the contents of the "next" cell. If in the last cell in the table, add a new row to it and focus its first cell.</li>
* <li>If SHIFT+TAB is pressed, select the contents of the "previous" cell. Do nothing when it's in the first cell.</li>
* </ul>
* @name CKEDITOR.config.enableTabKeyTools
* @type Boolean
* @default true
* @example
* config.enableTabKeyTools = false;
*/
// If the TAB key is not supposed to be enabled for navigation, the following
// settings could be used alternatively:
// config.keystrokes.push(
// [ CKEDITOR.ALT + 38 /*Arrow Up*/, 'selectPreviousCell' ],
// [ CKEDITOR.ALT + 40 /*Arrow Down*/, 'selectNextCell' ]
// );
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/tab/plugin.js | JavaScript | asf20 | 10,104 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.add( 'menubutton',
{
requires : [ 'button', 'menu' ],
beforeInit : function( editor )
{
editor.ui.addHandler( CKEDITOR.UI_MENUBUTTON, CKEDITOR.ui.menuButton.handler );
}
});
/**
* Button UI element.
* @constant
* @example
*/
CKEDITOR.UI_MENUBUTTON = 'menubutton';
(function()
{
var clickFn = function( editor )
{
var _ = this._;
// Do nothing if this button is disabled.
if ( _.state === CKEDITOR.TRISTATE_DISABLED )
return;
_.previousState = _.state;
// Check if we already have a menu for it, otherwise just create it.
var menu = _.menu;
if ( !menu )
{
menu = _.menu = new CKEDITOR.menu( editor,
{
panel:
{
className : editor.skinClass + ' cke_contextmenu',
attributes : { 'aria-label' : editor.lang.common.options }
}
});
menu.onHide = CKEDITOR.tools.bind( function()
{
this.setState( this.modes && this.modes[ editor.mode ] ? _.previousState : CKEDITOR.TRISTATE_DISABLED );
},
this );
// Initialize the menu items at this point.
if ( this.onMenu )
menu.addListener( this.onMenu );
}
if ( _.on )
{
menu.hide();
return;
}
this.setState( CKEDITOR.TRISTATE_ON );
menu.show( CKEDITOR.document.getById( this._.id ), 4 );
};
CKEDITOR.ui.menuButton = CKEDITOR.tools.createClass(
{
base : CKEDITOR.ui.button,
$ : function( definition )
{
// We don't want the panel definition in this object.
var panelDefinition = definition.panel;
delete definition.panel;
this.base( definition );
this.hasArrow = true;
this.click = clickFn;
},
statics :
{
handler :
{
create : function( definition )
{
return new CKEDITOR.ui.menuButton( definition );
}
}
}
});
})();
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/menubutton/plugin.js | JavaScript | asf20 | 2,000 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
(function()
{
CKEDITOR.plugins.add( 'enterkey',
{
requires : [ 'keystrokes', 'indent' ],
init : function( editor )
{
editor.addCommand( 'enter', {
modes : { wysiwyg:1 },
editorFocus : false,
exec : function( editor ){ enter( editor ); }
});
editor.addCommand( 'shiftEnter', {
modes : { wysiwyg:1 },
editorFocus : false,
exec : function( editor ){ shiftEnter( editor ); }
});
var keystrokes = editor.keystrokeHandler.keystrokes;
keystrokes[ 13 ] = 'enter';
keystrokes[ CKEDITOR.SHIFT + 13 ] = 'shiftEnter';
}
});
CKEDITOR.plugins.enterkey =
{
enterBlock : function( editor, mode, range, forceMode )
{
// Get the range for the current selection.
range = range || getRange( editor );
// We may not have valid ranges to work on, like when inside a
// contenteditable=false element.
if ( !range )
return;
var doc = range.document;
var atBlockStart = range.checkStartOfBlock(),
atBlockEnd = range.checkEndOfBlock(),
path = new CKEDITOR.dom.elementPath( range.startContainer ),
block = path.block;
if ( atBlockStart && atBlockEnd )
{
// Exit the list when we're inside an empty list item block. (#5376)
if ( block && ( block.is( 'li' ) || block.getParent().is( 'li' ) ) )
{
editor.execCommand( 'outdent' );
return;
}
if ( block && block.getParent().is( 'blockquote' ) )
{
block.breakParent( block.getParent() );
// If we were at the start of <blockquote>, there will be an empty element before it now.
if ( !block.getPrevious().getFirst( CKEDITOR.dom.walker.invisible(1) ) )
block.getPrevious().remove();
// If we were at the end of <blockquote>, there will be an empty element after it now.
if ( !block.getNext().getFirst( CKEDITOR.dom.walker.invisible(1) ) )
block.getNext().remove();
range.moveToElementEditStart( block );
range.select();
return;
}
}
// Don't split <pre> if we're in the middle of it, act as shift enter key.
else if ( block && block.is( 'pre' ) )
{
if ( !atBlockEnd )
{
enterBr( editor, mode, range, forceMode );
return;
}
}
// Don't split caption blocks. (#7944)
else if ( block && CKEDITOR.dtd.$captionBlock[ block.getName() ] )
{
enterBr( editor, mode, range, forceMode );
return;
}
// Determine the block element to be used.
var blockTag = ( mode == CKEDITOR.ENTER_DIV ? 'div' : 'p' );
// Split the range.
var splitInfo = range.splitBlock( blockTag );
if ( !splitInfo )
return;
// Get the current blocks.
var previousBlock = splitInfo.previousBlock,
nextBlock = splitInfo.nextBlock;
var isStartOfBlock = splitInfo.wasStartOfBlock,
isEndOfBlock = splitInfo.wasEndOfBlock;
var node;
// If this is a block under a list item, split it as well. (#1647)
if ( nextBlock )
{
node = nextBlock.getParent();
if ( node.is( 'li' ) )
{
nextBlock.breakParent( node );
nextBlock.move( nextBlock.getNext(), 1 );
}
}
else if ( previousBlock && ( node = previousBlock.getParent() ) && node.is( 'li' ) )
{
previousBlock.breakParent( node );
node = previousBlock.getNext();
range.moveToElementEditStart( node );
previousBlock.move( previousBlock.getPrevious() );
}
// If we have both the previous and next blocks, it means that the
// boundaries were on separated blocks, or none of them where on the
// block limits (start/end).
if ( !isStartOfBlock && !isEndOfBlock )
{
// If the next block is an <li> with another list tree as the first
// child, we'll need to append a filler (<br>/NBSP) or the list item
// wouldn't be editable. (#1420)
if ( nextBlock.is( 'li' )
&& ( node = nextBlock.getFirst( CKEDITOR.dom.walker.invisible( true ) ) )
&& node.is && node.is( 'ul', 'ol' ) )
( CKEDITOR.env.ie ? doc.createText( '\xa0' ) : doc.createElement( 'br' ) ).insertBefore( node );
// Move the selection to the end block.
if ( nextBlock )
range.moveToElementEditStart( nextBlock );
}
else
{
var newBlock,
newBlockDir;
if ( previousBlock )
{
// Do not enter this block if it's a header tag, or we are in
// a Shift+Enter (#77). Create a new block element instead
// (later in the code).
if ( previousBlock.is( 'li' ) ||
! ( headerTagRegex.test( previousBlock.getName() ) || previousBlock.is( 'pre' ) ) )
{
// Otherwise, duplicate the previous block.
newBlock = previousBlock.clone();
}
}
else if ( nextBlock )
newBlock = nextBlock.clone();
if ( !newBlock )
{
// We have already created a new list item. (#6849)
if ( node && node.is( 'li' ) )
newBlock = node;
else
{
newBlock = doc.createElement( blockTag );
if ( previousBlock && ( newBlockDir = previousBlock.getDirection() ) )
newBlock.setAttribute( 'dir', newBlockDir );
}
}
// Force the enter block unless we're talking of a list item.
else if ( forceMode && !newBlock.is( 'li' ) )
newBlock.renameNode( blockTag );
// Recreate the inline elements tree, which was available
// before hitting enter, so the same styles will be available in
// the new block.
var elementPath = splitInfo.elementPath;
if ( elementPath )
{
for ( var i = 0, len = elementPath.elements.length ; i < len ; i++ )
{
var element = elementPath.elements[ i ];
if ( element.equals( elementPath.block ) || element.equals( elementPath.blockLimit ) )
break;
if ( CKEDITOR.dtd.$removeEmpty[ element.getName() ] )
{
element = element.clone();
newBlock.moveChildren( element );
newBlock.append( element );
}
}
}
if ( !CKEDITOR.env.ie )
newBlock.appendBogus();
if ( !newBlock.getParent() )
range.insertNode( newBlock );
// list item start number should not be duplicated (#7330), but we need
// to remove the attribute after it's onto the DOM tree because of old IEs (#7581).
newBlock.is( 'li' ) && newBlock.removeAttribute( 'value' );
// This is tricky, but to make the new block visible correctly
// we must select it.
// The previousBlock check has been included because it may be
// empty if we have fixed a block-less space (like ENTER into an
// empty table cell).
if ( CKEDITOR.env.ie && isStartOfBlock && ( !isEndOfBlock || !previousBlock.getChildCount() ) )
{
// Move the selection to the new block.
range.moveToElementEditStart( isEndOfBlock ? previousBlock : newBlock );
range.select();
}
// Move the selection to the new block.
range.moveToElementEditStart( isStartOfBlock && !isEndOfBlock ? nextBlock : newBlock );
}
if ( !CKEDITOR.env.ie )
{
if ( nextBlock )
{
// If we have split the block, adds a temporary span at the
// range position and scroll relatively to it.
var tmpNode = doc.createElement( 'span' );
// We need some content for Safari.
tmpNode.setHtml( ' ' );
range.insertNode( tmpNode );
tmpNode.scrollIntoView();
range.deleteContents();
}
else
{
// We may use the above scroll logic for the new block case
// too, but it gives some weird result with Opera.
newBlock.scrollIntoView();
}
}
range.select();
},
enterBr : function( editor, mode, range, forceMode )
{
// Get the range for the current selection.
range = range || getRange( editor );
// We may not have valid ranges to work on, like when inside a
// contenteditable=false element.
if ( !range )
return;
var doc = range.document;
// Determine the block element to be used.
var blockTag = ( mode == CKEDITOR.ENTER_DIV ? 'div' : 'p' );
var isEndOfBlock = range.checkEndOfBlock();
var elementPath = new CKEDITOR.dom.elementPath( editor.getSelection().getStartElement() );
var startBlock = elementPath.block,
startBlockTag = startBlock && elementPath.block.getName();
var isPre = false;
if ( !forceMode && startBlockTag == 'li' )
{
enterBlock( editor, mode, range, forceMode );
return;
}
// If we are at the end of a header block.
if ( !forceMode && isEndOfBlock && headerTagRegex.test( startBlockTag ) )
{
var newBlock,
newBlockDir;
if ( ( newBlockDir = startBlock.getDirection() ) )
{
newBlock = doc.createElement( 'div' );
newBlock.setAttribute( 'dir', newBlockDir );
newBlock.insertAfter( startBlock );
range.setStart( newBlock, 0 );
}
else
{
// Insert a <br> after the current paragraph.
doc.createElement( 'br' ).insertAfter( startBlock );
// A text node is required by Gecko only to make the cursor blink.
if ( CKEDITOR.env.gecko )
doc.createText( '' ).insertAfter( startBlock );
// IE has different behaviors regarding position.
range.setStartAt( startBlock.getNext(), CKEDITOR.env.ie ? CKEDITOR.POSITION_BEFORE_START : CKEDITOR.POSITION_AFTER_START );
}
}
else
{
var lineBreak;
isPre = ( startBlockTag == 'pre' );
// Gecko prefers <br> as line-break inside <pre> (#4711).
if ( isPre && !CKEDITOR.env.gecko )
lineBreak = doc.createText( CKEDITOR.env.ie ? '\r' : '\n' );
else
lineBreak = doc.createElement( 'br' );
range.deleteContents();
range.insertNode( lineBreak );
// IE has different behavior regarding position.
if ( CKEDITOR.env.ie )
range.setStartAt( lineBreak, CKEDITOR.POSITION_AFTER_END );
else
{
// A text node is required by Gecko only to make the cursor blink.
// We need some text inside of it, so the bogus <br> is properly
// created.
doc.createText( '\ufeff' ).insertAfter( lineBreak );
// If we are at the end of a block, we must be sure the bogus node is available in that block.
if ( isEndOfBlock )
lineBreak.getParent().appendBogus();
// Now we can remove the text node contents, so the caret doesn't
// stop on it.
lineBreak.getNext().$.nodeValue = '';
range.setStartAt( lineBreak.getNext(), CKEDITOR.POSITION_AFTER_START );
// Scroll into view, for non IE.
var dummy = null;
// BR is not positioned in Opera and Webkit.
if ( !CKEDITOR.env.gecko )
{
dummy = doc.createElement( 'span' );
// We need have some contents for Webkit to position it
// under parent node. ( #3681)
dummy.setHtml(' ');
}
else
dummy = doc.createElement( 'br' );
dummy.insertBefore( lineBreak.getNext() );
dummy.scrollIntoView();
dummy.remove();
}
}
// This collapse guarantees the cursor will be blinking.
range.collapse( true );
range.select( isPre );
}
};
var plugin = CKEDITOR.plugins.enterkey,
enterBr = plugin.enterBr,
enterBlock = plugin.enterBlock,
headerTagRegex = /^h[1-6]$/;
function shiftEnter( editor )
{
// Only effective within document.
if ( editor.mode != 'wysiwyg' )
return false;
// On SHIFT+ENTER:
// 1. We want to enforce the mode to be respected, instead
// of cloning the current block. (#77)
return enter( editor, editor.config.shiftEnterMode, 1 );
}
function enter( editor, mode, forceMode )
{
forceMode = editor.config.forceEnterMode || forceMode;
// Only effective within document.
if ( editor.mode != 'wysiwyg' )
return false;
if ( !mode )
mode = editor.config.enterMode;
// Use setTimout so the keys get cancelled immediatelly.
setTimeout( function()
{
editor.fire( 'saveSnapshot' ); // Save undo step.
if ( mode == CKEDITOR.ENTER_BR )
enterBr( editor, mode, null, forceMode );
else
enterBlock( editor, mode, null, forceMode );
editor.fire( 'saveSnapshot' );
}, 0 );
return true;
}
function getRange( editor )
{
// Get the selection ranges.
var ranges = editor.getSelection().getRanges( true );
// Delete the contents of all ranges except the first one.
for ( var i = ranges.length - 1 ; i > 0 ; i-- )
{
ranges[ i ].deleteContents();
}
// Return the first range.
return ranges[ 0 ];
}
})();
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/enterkey/plugin.js | JavaScript | asf20 | 12,826 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @fileOverview The "elementspath" plugin. It shows all elements in the DOM
* parent tree relative to the current selection in the editing area.
*/
(function()
{
var commands =
{
toolbarFocus :
{
editorFocus : false,
readOnly : 1,
exec : function( editor )
{
var idBase = editor._.elementsPath.idBase;
var element = CKEDITOR.document.getById( idBase + '0' );
// Make the first button focus accessible for IE. (#3417)
// Adobe AIR instead need while of delay.
element && element.focus( CKEDITOR.env.ie || CKEDITOR.env.air );
}
}
};
var emptyHtml = '<span class="cke_empty"> </span>';
CKEDITOR.plugins.add( 'elementspath',
{
requires : [ 'selection' ],
init : function( editor )
{
var spaceId = 'cke_path_' + editor.name;
var spaceElement;
var getSpaceElement = function()
{
if ( !spaceElement )
spaceElement = CKEDITOR.document.getById( spaceId );
return spaceElement;
};
var idBase = 'cke_elementspath_' + CKEDITOR.tools.getNextNumber() + '_';
editor._.elementsPath = { idBase : idBase, filters : [] };
editor.on( 'themeSpace', function( event )
{
if ( event.data.space == 'bottom' )
{
event.data.html +=
'<span id="' + spaceId + '_label" class="cke_voice_label">' + editor.lang.elementsPath.eleLabel + '</span>' +
'<div id="' + spaceId + '" class="cke_path" role="group" aria-labelledby="' + spaceId + '_label">' + emptyHtml + '</div>';
}
});
function onClick( elementIndex )
{
editor.focus();
var element = editor._.elementsPath.list[ elementIndex ];
if ( element.is( 'body' ) )
{
var range = new CKEDITOR.dom.range( editor.document );
range.selectNodeContents( element );
range.select();
}
else
editor.getSelection().selectElement( element );
}
var onClickHanlder = CKEDITOR.tools.addFunction( onClick );
var onKeyDownHandler = CKEDITOR.tools.addFunction( function( elementIndex, ev )
{
var idBase = editor._.elementsPath.idBase,
element;
ev = new CKEDITOR.dom.event( ev );
var rtl = editor.lang.dir == 'rtl';
switch ( ev.getKeystroke() )
{
case rtl ? 39 : 37 : // LEFT-ARROW
case 9 : // TAB
element = CKEDITOR.document.getById( idBase + ( elementIndex + 1 ) );
if ( !element )
element = CKEDITOR.document.getById( idBase + '0' );
element.focus();
return false;
case rtl ? 37 : 39 : // RIGHT-ARROW
case CKEDITOR.SHIFT + 9 : // SHIFT + TAB
element = CKEDITOR.document.getById( idBase + ( elementIndex - 1 ) );
if ( !element )
element = CKEDITOR.document.getById( idBase + ( editor._.elementsPath.list.length - 1 ) );
element.focus();
return false;
case 27 : // ESC
editor.focus();
return false;
case 13 : // ENTER // Opera
case 32 : // SPACE
onClick( elementIndex );
return false;
}
return true;
});
editor.on( 'selectionChange', function( ev )
{
var env = CKEDITOR.env,
selection = ev.data.selection,
element = selection.getStartElement(),
html = [],
editor = ev.editor,
elementsList = editor._.elementsPath.list = [],
filters = editor._.elementsPath.filters;
while ( element )
{
var ignore = 0,
name;
if ( element.data( 'cke-display-name' ) )
name = element.data( 'cke-display-name' );
else if ( element.data( 'cke-real-element-type' ) )
name = element.data( 'cke-real-element-type' );
else
name = element.getName();
for ( var i = 0; i < filters.length; i++ )
{
var ret = filters[ i ]( element, name );
if ( ret === false )
{
ignore = 1;
break;
}
name = ret || name;
}
if ( !ignore )
{
var index = elementsList.push( element ) - 1;
// Use this variable to add conditional stuff to the
// HTML (because we are doing it in reverse order... unshift).
var extra = '';
// 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 ) )
extra += ' onkeypress="return false;"';
// With Firefox, we need to force the button to redraw, otherwise it
// will remain in the focus state.
if ( env.gecko )
extra += ' onblur="this.style.cssText = this.style.cssText;"';
var label = editor.lang.elementsPath.eleTitle.replace( /%1/, name );
html.unshift(
'<a' +
' id="', idBase, index, '"' +
' href="javascript:void(\'', name, '\')"' +
' tabindex="-1"' +
' title="', label, '"' +
( ( CKEDITOR.env.gecko && CKEDITOR.env.version < 10900 ) ?
' onfocus="event.preventBubble();"' : '' ) +
' hidefocus="true" ' +
' onkeydown="return CKEDITOR.tools.callFunction(', onKeyDownHandler, ',', index, ', event );"' +
extra ,
' onclick="CKEDITOR.tools.callFunction('+ onClickHanlder, ',', index, '); return false;"',
' role="button" aria-labelledby="' + idBase + index + '_label">',
name,
'<span id="', idBase, index, '_label" class="cke_label">' + label + '</span>',
'</a>' );
}
if ( name == 'body' )
break;
element = element.getParent();
}
var space = getSpaceElement();
space.setHtml( html.join('') + emptyHtml );
editor.fire( 'elementsPathUpdate', { space : space } );
});
function empty()
{
spaceElement && spaceElement.setHtml( emptyHtml );
delete editor._.elementsPath.list;
}
editor.on( 'readOnly', empty );
editor.on( 'contentDomUnload', empty );
editor.addCommand( 'elementsPathFocus', commands.toolbarFocus );
}
});
})();
/**
* Fired when the contents of the elementsPath are changed
* @name CKEDITOR.editor#elementsPathUpdate
* @event
* @param {Object} eventData.space The elementsPath container
*/
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/elementspath/plugin.js | JavaScript | asf20 | 6,519 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.add( 'contextmenu',
{
requires : [ 'menu' ],
// Make sure the base class (CKEDITOR.menu) is loaded before it (#3318).
onLoad : function()
{
CKEDITOR.plugins.contextMenu = CKEDITOR.tools.createClass(
{
base : CKEDITOR.menu,
$ : function( editor )
{
this.base.call( this, editor,
{
panel:
{
className : editor.skinClass + ' cke_contextmenu',
attributes :
{
'aria-label' : editor.lang.contextmenu.options
}
}
});
},
proto :
{
addTarget : function( element, nativeContextMenuOnCtrl )
{
// Opera doesn't support 'contextmenu' event, we have duo approaches employed here:
// 1. Inherit the 'button override' hack we introduced in v2 (#4530), while this require the Opera browser
// option 'Allow script to detect context menu/right click events' to be always turned on.
// 2. Considering the fact that ctrl/meta key is not been occupied
// for multiple range selecting (like Gecko), we use this key
// combination as a fallback for triggering context-menu. (#4530)
if ( CKEDITOR.env.opera && !( 'oncontextmenu' in document.body ))
{
var contextMenuOverrideButton;
element.on( 'mousedown', function( evt )
{
evt = evt.data;
if ( evt.$.button != 2 )
{
if ( evt.getKeystroke() == CKEDITOR.CTRL + 1 )
element.fire( 'contextmenu', evt );
return;
}
if ( nativeContextMenuOnCtrl
&& ( CKEDITOR.env.mac ? evt.$.metaKey : evt.$.ctrlKey ) )
return;
var target = evt.getTarget();
if ( !contextMenuOverrideButton )
{
var ownerDoc = target.getDocument();
contextMenuOverrideButton = ownerDoc.createElement( 'input' ) ;
contextMenuOverrideButton.$.type = 'button' ;
ownerDoc.getBody().append( contextMenuOverrideButton ) ;
}
contextMenuOverrideButton.setAttribute( 'style', 'position:absolute;top:' + ( evt.$.clientY - 2 ) +
'px;left:' + ( evt.$.clientX - 2 ) +
'px;width:5px;height:5px;opacity:0.01' );
} );
element.on( 'mouseup', function ( evt )
{
if ( contextMenuOverrideButton )
{
contextMenuOverrideButton.remove();
contextMenuOverrideButton = undefined;
// Simulate 'contextmenu' event.
element.fire( 'contextmenu', evt.data );
}
} );
}
element.on( 'contextmenu', function( event )
{
var domEvent = event.data;
if ( nativeContextMenuOnCtrl &&
// Safari on Windows always show 'ctrlKey' as true in 'contextmenu' event,
// which make this property unreliable. (#4826)
( CKEDITOR.env.webkit ? holdCtrlKey : ( CKEDITOR.env.mac ? domEvent.$.metaKey : domEvent.$.ctrlKey ) ) )
return;
// Cancel the browser context menu.
domEvent.preventDefault();
var offsetParent = domEvent.getTarget().getDocument().getDocumentElement(),
offsetX = domEvent.$.clientX,
offsetY = domEvent.$.clientY;
CKEDITOR.tools.setTimeout( function()
{
this.open( offsetParent, null, offsetX, offsetY );
// IE needs a short while to allow selection change before opening menu. (#7908)
}, CKEDITOR.env.ie? 200 : 0, this );
},
this );
if ( CKEDITOR.env.opera )
{
// 'contextmenu' event triggered by Windows menu key is unpreventable,
// cancel the key event itself. (#6534)
element.on( 'keypress' , function ( evt )
{
var domEvent = evt.data;
if ( domEvent.$.keyCode === 0 )
domEvent.preventDefault();
});
}
if ( CKEDITOR.env.webkit )
{
var holdCtrlKey,
onKeyDown = function( event )
{
holdCtrlKey = CKEDITOR.env.mac ? event.data.$.metaKey : event.data.$.ctrlKey ;
},
resetOnKeyUp = function()
{
holdCtrlKey = 0;
};
element.on( 'keydown', onKeyDown );
element.on( 'keyup', resetOnKeyUp );
element.on( 'contextmenu', resetOnKeyUp );
}
},
open : function( offsetParent, corner, offsetX, offsetY )
{
this.editor.focus();
offsetParent = offsetParent || CKEDITOR.document.getDocumentElement();
this.show( offsetParent, corner, offsetX, offsetY );
}
}
});
},
beforeInit : function( editor )
{
editor.contextMenu = new CKEDITOR.plugins.contextMenu( editor );
editor.addCommand( 'contextMenu',
{
exec : function()
{
editor.contextMenu.open( editor.document.getBody() );
}
});
}
});
/**
* Whether to show the browser native context menu when the <em>Ctrl</em> or
* <em>Meta</em> (Mac) key is pressed on opening the context menu with the
* right mouse button click or the <em>Menu</em> key.
* @name CKEDITOR.config.browserContextMenuOnCtrl
* @since 3.0.2
* @type Boolean
* @default <code>true</code>
* @example
* config.browserContextMenuOnCtrl = false;
*/
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/contextmenu/plugin.js | JavaScript | asf20 | 5,353 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.add( 'link',
{
requires : [ 'fakeobjects', 'dialog' ],
init : function( editor )
{
// Add the link and unlink buttons.
editor.addCommand( 'link', new CKEDITOR.dialogCommand( 'link' ) );
editor.addCommand( 'anchor', new CKEDITOR.dialogCommand( 'anchor' ) );
editor.addCommand( 'unlink', new CKEDITOR.unlinkCommand() );
editor.addCommand( 'removeAnchor', new CKEDITOR.removeAnchorCommand() );
editor.ui.addButton( 'Link',
{
label : editor.lang.link.toolbar,
command : 'link'
} );
editor.ui.addButton( 'Unlink',
{
label : editor.lang.unlink,
command : 'unlink'
} );
editor.ui.addButton( 'Anchor',
{
label : editor.lang.anchor.toolbar,
command : 'anchor'
} );
CKEDITOR.dialog.add( 'link', this.path + 'dialogs/link.js' );
CKEDITOR.dialog.add( 'anchor', this.path + 'dialogs/anchor.js' );
// Add the CSS styles for anchor placeholders.
var side = ( editor.lang.dir == 'rtl' ? 'right' : 'left' );
var basicCss =
'background:url(' + CKEDITOR.getUrl( this.path + 'images/anchor.gif' ) + ') no-repeat ' + side + ' center;' +
'border:1px dotted #00f;';
editor.addCss(
'a.cke_anchor,a.cke_anchor_empty' +
// IE6 breaks with the following selectors.
( ( CKEDITOR.env.ie && CKEDITOR.env.version < 7 ) ? '' :
',a[name],a[data-cke-saved-name]' ) +
'{' +
basicCss +
'padding-' + side + ':18px;' +
// Show the arrow cursor for the anchor image (FF at least).
'cursor:auto;' +
'}' +
( CKEDITOR.env.ie ? (
'a.cke_anchor_empty' +
'{' +
// Make empty anchor selectable on IE.
'display:inline-block;' +
'}'
) : '' ) +
'img.cke_anchor' +
'{' +
basicCss +
'width:16px;' +
'min-height:15px;' +
// The default line-height on IE.
'height:1.15em;' +
// Opera works better with "middle" (even if not perfect)
'vertical-align:' + ( CKEDITOR.env.opera ? 'middle' : 'text-bottom' ) + ';' +
'}');
// Register selection change handler for the unlink button.
editor.on( 'selectionChange', function( evt )
{
if ( editor.readOnly )
return;
/*
* Despite our initial hope, document.queryCommandEnabled() does not work
* for this in Firefox. So we must detect the state by element paths.
*/
var command = editor.getCommand( 'unlink' ),
element = evt.data.path.lastElement && evt.data.path.lastElement.getAscendant( 'a', true );
if ( element && element.getName() == 'a' && element.getAttribute( 'href' ) && element.getChildCount() )
command.setState( CKEDITOR.TRISTATE_OFF );
else
command.setState( CKEDITOR.TRISTATE_DISABLED );
} );
editor.on( 'doubleclick', function( evt )
{
var element = CKEDITOR.plugins.link.getSelectedLink( editor ) || evt.data.element;
if ( !element.isReadOnly() )
{
if ( element.is( 'a' ) )
{
evt.data.dialog = ( element.getAttribute( 'name' ) && ( !element.getAttribute( 'href' ) || !element.getChildCount() ) ) ? 'anchor' : 'link';
editor.getSelection().selectElement( element );
}
else if ( CKEDITOR.plugins.link.tryRestoreFakeAnchor( editor, element ) )
evt.data.dialog = 'anchor';
}
});
// If the "menu" plugin is loaded, register the menu items.
if ( editor.addMenuItems )
{
editor.addMenuItems(
{
anchor :
{
label : editor.lang.anchor.menu,
command : 'anchor',
group : 'anchor',
order : 1
},
removeAnchor :
{
label : editor.lang.anchor.remove,
command : 'removeAnchor',
group : 'anchor',
order : 5
},
link :
{
label : editor.lang.link.menu,
command : 'link',
group : 'link',
order : 1
},
unlink :
{
label : editor.lang.unlink,
command : 'unlink',
group : 'link',
order : 5
}
});
}
// 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 anchor = CKEDITOR.plugins.link.tryRestoreFakeAnchor( editor, element );
if ( !anchor && !( anchor = CKEDITOR.plugins.link.getSelectedLink( editor ) ) )
return null;
var menu = {};
if ( anchor.getAttribute( 'href' ) && anchor.getChildCount() )
menu = { link : CKEDITOR.TRISTATE_OFF, unlink : CKEDITOR.TRISTATE_OFF };
if ( anchor && anchor.hasAttribute( 'name' ) )
menu.anchor = menu.removeAnchor = CKEDITOR.TRISTATE_OFF;
return menu;
});
}
},
afterInit : function( editor )
{
// Register a filter to displaying placeholders after mode change.
var dataProcessor = editor.dataProcessor,
dataFilter = dataProcessor && dataProcessor.dataFilter,
htmlFilter = dataProcessor && dataProcessor.htmlFilter,
pathFilters = editor._.elementsPath && editor._.elementsPath.filters;
if ( dataFilter )
{
dataFilter.addRules(
{
elements :
{
a : function( element )
{
var attributes = element.attributes;
if ( !attributes.name )
return null;
var isEmpty = !element.children.length;
if ( CKEDITOR.plugins.link.synAnchorSelector )
{
// IE needs a specific class name to be applied
// to the anchors, for appropriate styling.
var ieClass = isEmpty ? 'cke_anchor_empty' : 'cke_anchor';
var cls = attributes[ 'class' ];
if ( attributes.name && ( !cls || cls.indexOf( ieClass ) < 0 ) )
attributes[ 'class' ] = ( cls || '' ) + ' ' + ieClass;
if ( isEmpty && CKEDITOR.plugins.link.emptyAnchorFix )
{
attributes.contenteditable = 'false';
attributes[ 'data-cke-editable' ] = 1;
}
}
else if ( CKEDITOR.plugins.link.fakeAnchor && isEmpty )
return editor.createFakeParserElement( element, 'cke_anchor', 'anchor' );
return null;
}
}
});
}
if ( CKEDITOR.plugins.link.emptyAnchorFix && htmlFilter )
{
htmlFilter.addRules(
{
elements :
{
a : function( element )
{
delete element.attributes.contenteditable;
}
}
});
}
if ( pathFilters )
{
pathFilters.push( function( element, name )
{
if ( name == 'a' )
{
if ( CKEDITOR.plugins.link.tryRestoreFakeAnchor( editor, element ) ||
( element.getAttribute( 'name' ) && ( !element.getAttribute( 'href' ) || !element.getChildCount() ) ) )
{
return 'anchor';
}
}
});
}
}
} );
CKEDITOR.plugins.link =
{
/**
* Get the surrounding link element of current selection.
* @param editor
* @example CKEDITOR.plugins.link.getSelectedLink( editor );
* @since 3.2.1
* The following selection will all return the link element.
* <pre>
* <a href="#">li^nk</a>
* <a href="#">[link]</a>
* text[<a href="#">link]</a>
* <a href="#">li[nk</a>]
* [<b><a href="#">li]nk</a></b>]
* [<a href="#"><b>li]nk</b></a>
* </pre>
*/
getSelectedLink : function( editor )
{
try
{
var selection = editor.getSelection();
if ( selection.getType() == CKEDITOR.SELECTION_ELEMENT )
{
var selectedElement = selection.getSelectedElement();
if ( selectedElement.is( 'a' ) )
return selectedElement;
}
var range = selection.getRanges( true )[ 0 ];
range.shrink( CKEDITOR.SHRINK_TEXT );
var root = range.getCommonAncestor();
return root.getAscendant( 'a', true );
}
catch( e ) { return null; }
},
// Opera and WebKit don't make it possible to select empty anchors. Fake
// elements must be used for them.
fakeAnchor : CKEDITOR.env.opera || CKEDITOR.env.webkit,
// For browsers that don't support CSS3 a[name]:empty(), note IE9 is included because of #7783.
synAnchorSelector : CKEDITOR.env.ie,
// For browsers that have editing issue with empty anchor.
emptyAnchorFix : CKEDITOR.env.ie && CKEDITOR.env.version < 8,
tryRestoreFakeAnchor : function( editor, element )
{
if ( element && element.data( 'cke-real-element-type' ) && element.data( 'cke-real-element-type' ) == 'anchor' )
{
var link = editor.restoreRealElement( element );
if ( link.data( 'cke-saved-name' ) )
return link;
}
}
};
CKEDITOR.unlinkCommand = function(){};
CKEDITOR.unlinkCommand.prototype =
{
/** @ignore */
exec : function( editor )
{
/*
* execCommand( 'unlink', ... ) in Firefox leaves behind <span> tags at where
* the <a> was, so again we have to remove the link ourselves. (See #430)
*
* TODO: Use the style system when it's complete. Let's use execCommand()
* as a stopgap solution for now.
*/
var selection = editor.getSelection(),
bookmarks = selection.createBookmarks(),
ranges = selection.getRanges(),
rangeRoot,
element;
for ( var i = 0 ; i < ranges.length ; i++ )
{
rangeRoot = ranges[i].getCommonAncestor( true );
element = rangeRoot.getAscendant( 'a', true );
if ( !element )
continue;
ranges[i].selectNodeContents( element );
}
selection.selectRanges( ranges );
editor.document.$.execCommand( 'unlink', false, null );
selection.selectBookmarks( bookmarks );
},
startDisabled : true
};
CKEDITOR.removeAnchorCommand = function(){};
CKEDITOR.removeAnchorCommand.prototype =
{
/** @ignore */
exec : function( editor )
{
var sel = editor.getSelection(),
bms = sel.createBookmarks(),
anchor;
if ( sel && ( anchor = sel.getSelectedElement() ) && ( CKEDITOR.plugins.link.fakeAnchor && !anchor.getChildCount() ? CKEDITOR.plugins.link.tryRestoreFakeAnchor( editor, anchor ) : anchor.is( 'a' ) ) )
anchor.remove( 1 );
else
{
if ( ( anchor = CKEDITOR.plugins.link.getSelectedLink( editor ) ) )
{
if ( anchor.hasAttribute( 'href' ) )
{
anchor.removeAttributes( { name : 1, 'data-cke-saved-name' : 1 } );
anchor.removeClass( 'cke_anchor' );
}
else
anchor.remove( 1 );
}
}
sel.selectBookmarks( bms );
}
};
CKEDITOR.tools.extend( CKEDITOR.config,
{
linkShowAdvancedTab : true,
linkShowTargetTab : true
} );
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/link/plugin.js | JavaScript | asf20 | 10,662 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.dialog.add( 'anchor', function( editor )
{
// Function called in onShow to load selected element.
var loadElements = function( element )
{
this._.selectedElement = element;
var attributeValue = element.data( 'cke-saved-name' );
this.setValueOf( 'info','txtName', attributeValue || '' );
};
function createFakeAnchor( editor, anchor )
{
return editor.createFakeElement( anchor, 'cke_anchor', 'anchor' );
}
return {
title : editor.lang.anchor.title,
minWidth : 300,
minHeight : 60,
onOk : function()
{
var name = CKEDITOR.tools.trim( this.getValueOf( 'info', 'txtName' ) );
var attributes =
{
name : name,
'data-cke-saved-name' : name
};
if ( this._.selectedElement )
{
if ( this._.selectedElement.data( 'cke-realelement' ) )
{
var newFake = createFakeAnchor( editor, editor.document.createElement( 'a', { attributes: attributes } ) );
newFake.replace( this._.selectedElement );
}
else
this._.selectedElement.setAttributes( attributes );
}
else
{
var sel = editor.getSelection(),
range = sel && sel.getRanges()[ 0 ];
// Empty anchor
if ( range.collapsed )
{
if ( CKEDITOR.plugins.link.synAnchorSelector )
attributes[ 'class' ] = 'cke_anchor_empty';
if ( CKEDITOR.plugins.link.emptyAnchorFix )
{
attributes[ 'contenteditable' ] = 'false';
attributes[ 'data-cke-editable' ] = 1;
}
var anchor = editor.document.createElement( 'a', { attributes: attributes } );
// Transform the anchor into a fake element for browsers that need it.
if ( CKEDITOR.plugins.link.fakeAnchor )
anchor = createFakeAnchor( editor, anchor );
range.insertNode( anchor );
}
else
{
if ( CKEDITOR.env.ie && CKEDITOR.env.version < 9 )
attributes['class'] = 'cke_anchor';
// Apply style.
var style = new CKEDITOR.style( { element : 'a', attributes : attributes } );
style.type = CKEDITOR.STYLE_INLINE;
style.apply( editor.document );
}
}
},
onHide : function()
{
delete this._.selectedElement;
},
onShow : function()
{
var selection = editor.getSelection(),
fullySelected = selection.getSelectedElement(),
partialSelected;
// Detect the anchor under selection.
if ( fullySelected )
{
if ( CKEDITOR.plugins.link.fakeAnchor )
{
var realElement = CKEDITOR.plugins.link.tryRestoreFakeAnchor( editor, fullySelected );
realElement && loadElements.call( this, realElement );
this._.selectedElement = fullySelected;
}
else if ( fullySelected.is( 'a' ) && fullySelected.hasAttribute( 'name' ) )
loadElements.call( this, fullySelected );
}
else
{
partialSelected = CKEDITOR.plugins.link.getSelectedLink( editor );
if ( partialSelected )
{
loadElements.call( this, partialSelected );
selection.selectElement( partialSelected );
}
}
this.getContentElement( 'info', 'txtName' ).focus();
},
contents : [
{
id : 'info',
label : editor.lang.anchor.title,
accessKey : 'I',
elements :
[
{
type : 'text',
id : 'txtName',
label : editor.lang.anchor.name,
required: true,
validate : function()
{
if ( !this.getValue() )
{
alert( editor.lang.anchor.errorName );
return false;
}
return true;
}
}
]
}
]
};
} );
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/link/dialogs/anchor.js | JavaScript | asf20 | 3,740 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.dialog.add( 'link', function( editor )
{
var plugin = CKEDITOR.plugins.link;
// Handles the event when the "Target" selection box is changed.
var targetChanged = function()
{
var dialog = this.getDialog(),
popupFeatures = dialog.getContentElement( 'target', 'popupFeatures' ),
targetName = dialog.getContentElement( 'target', 'linkTargetName' ),
value = this.getValue();
if ( !popupFeatures || !targetName )
return;
popupFeatures = popupFeatures.getElement();
popupFeatures.hide();
targetName.setValue( '' );
switch ( value )
{
case 'frame' :
targetName.setLabel( editor.lang.link.targetFrameName );
targetName.getElement().show();
break;
case 'popup' :
popupFeatures.show();
targetName.setLabel( editor.lang.link.targetPopupName );
targetName.getElement().show();
break;
default :
targetName.setValue( value );
targetName.getElement().hide();
break;
}
};
// Handles the event when the "Type" selection box is changed.
var linkTypeChanged = function()
{
var dialog = this.getDialog(),
partIds = [ 'urlOptions', 'anchorOptions', 'emailOptions' ],
typeValue = this.getValue(),
uploadTab = dialog.definition.getContents( 'upload' ),
uploadInitiallyHidden = uploadTab && uploadTab.hidden;
if ( typeValue == 'url' )
{
if ( editor.config.linkShowTargetTab )
dialog.showPage( 'target' );
if ( !uploadInitiallyHidden )
dialog.showPage( 'upload' );
}
else
{
dialog.hidePage( 'target' );
if ( !uploadInitiallyHidden )
dialog.hidePage( 'upload' );
}
for ( var i = 0 ; i < partIds.length ; i++ )
{
var element = dialog.getContentElement( 'info', partIds[i] );
if ( !element )
continue;
element = element.getElement().getParent().getParent();
if ( partIds[i] == typeValue + 'Options' )
element.show();
else
element.hide();
}
dialog.layout();
};
// Loads the parameters in a selected link to the link dialog fields.
var javascriptProtocolRegex = /^javascript:/,
emailRegex = /^mailto:([^?]+)(?:\?(.+))?$/,
emailSubjectRegex = /subject=([^;?:@&=$,\/]*)/,
emailBodyRegex = /body=([^;?:@&=$,\/]*)/,
anchorRegex = /^#(.*)$/,
urlRegex = /^((?:http|https|ftp|news):\/\/)?(.*)$/,
selectableTargets = /^(_(?:self|top|parent|blank))$/,
encodedEmailLinkRegex = /^javascript:void\(location\.href='mailto:'\+String\.fromCharCode\(([^)]+)\)(?:\+'(.*)')?\)$/,
functionCallProtectedEmailLinkRegex = /^javascript:([^(]+)\(([^)]+)\)$/;
var popupRegex =
/\s*window.open\(\s*this\.href\s*,\s*(?:'([^']*)'|null)\s*,\s*'([^']*)'\s*\)\s*;\s*return\s*false;*\s*/;
var popupFeaturesRegex = /(?:^|,)([^=]+)=(\d+|yes|no)/gi;
var parseLink = function( editor, element )
{
var href = ( element && ( element.data( 'cke-saved-href' ) || element.getAttribute( 'href' ) ) ) || '',
javascriptMatch,
emailMatch,
anchorMatch,
urlMatch,
retval = {};
if ( ( javascriptMatch = href.match( javascriptProtocolRegex ) ) )
{
if ( emailProtection == 'encode' )
{
href = href.replace( encodedEmailLinkRegex,
function ( match, protectedAddress, rest )
{
return 'mailto:' +
String.fromCharCode.apply( String, protectedAddress.split( ',' ) ) +
( rest && unescapeSingleQuote( rest ) );
});
}
// Protected email link as function call.
else if ( emailProtection )
{
href.replace( functionCallProtectedEmailLinkRegex, function( match, funcName, funcArgs )
{
if ( funcName == compiledProtectionFunction.name )
{
retval.type = 'email';
var email = retval.email = {};
var paramRegex = /[^,\s]+/g,
paramQuoteRegex = /(^')|('$)/g,
paramsMatch = funcArgs.match( paramRegex ),
paramsMatchLength = paramsMatch.length,
paramName,
paramVal;
for ( var i = 0; i < paramsMatchLength; i++ )
{
paramVal = decodeURIComponent( unescapeSingleQuote( paramsMatch[ i ].replace( paramQuoteRegex, '' ) ) );
paramName = compiledProtectionFunction.params[ i ].toLowerCase();
email[ paramName ] = paramVal;
}
email.address = [ email.name, email.domain ].join( '@' );
}
} );
}
}
if ( !retval.type )
{
if ( ( anchorMatch = href.match( anchorRegex ) ) )
{
retval.type = 'anchor';
retval.anchor = {};
retval.anchor.name = retval.anchor.id = anchorMatch[1];
}
// Protected email link as encoded string.
else if ( ( emailMatch = href.match( emailRegex ) ) )
{
var subjectMatch = href.match( emailSubjectRegex ),
bodyMatch = href.match( emailBodyRegex );
retval.type = 'email';
var email = ( retval.email = {} );
email.address = emailMatch[ 1 ];
subjectMatch && ( email.subject = decodeURIComponent( subjectMatch[ 1 ] ) );
bodyMatch && ( email.body = decodeURIComponent( bodyMatch[ 1 ] ) );
}
// urlRegex matches empty strings, so need to check for href as well.
else if ( href && ( urlMatch = href.match( urlRegex ) ) )
{
retval.type = 'url';
retval.url = {};
retval.url.protocol = urlMatch[1];
retval.url.url = urlMatch[2];
}
else
retval.type = 'url';
}
// Load target and popup settings.
if ( element )
{
var target = element.getAttribute( 'target' );
retval.target = {};
retval.adv = {};
// IE BUG: target attribute is an empty string instead of null in IE if it's not set.
if ( !target )
{
var onclick = element.data( 'cke-pa-onclick' ) || element.getAttribute( 'onclick' ),
onclickMatch = onclick && onclick.match( popupRegex );
if ( onclickMatch )
{
retval.target.type = 'popup';
retval.target.name = onclickMatch[1];
var featureMatch;
while ( ( featureMatch = popupFeaturesRegex.exec( onclickMatch[2] ) ) )
{
// Some values should remain numbers (#7300)
if ( ( featureMatch[2] == 'yes' || featureMatch[2] == '1' ) && !( featureMatch[1] in { height:1, width:1, top:1, left:1 } ) )
retval.target[ featureMatch[1] ] = true;
else if ( isFinite( featureMatch[2] ) )
retval.target[ featureMatch[1] ] = featureMatch[2];
}
}
}
else
{
var targetMatch = target.match( selectableTargets );
if ( targetMatch )
retval.target.type = retval.target.name = target;
else
{
retval.target.type = 'frame';
retval.target.name = target;
}
}
var me = this;
var advAttr = function( inputName, attrName )
{
var value = element.getAttribute( attrName );
if ( value !== null )
retval.adv[ inputName ] = value || '';
};
advAttr( 'advId', 'id' );
advAttr( 'advLangDir', 'dir' );
advAttr( 'advAccessKey', 'accessKey' );
retval.adv.advName =
element.data( 'cke-saved-name' )
|| element.getAttribute( 'name' )
|| '';
advAttr( 'advLangCode', 'lang' );
advAttr( 'advTabIndex', 'tabindex' );
advAttr( 'advTitle', 'title' );
advAttr( 'advContentType', 'type' );
CKEDITOR.plugins.link.synAnchorSelector ?
retval.adv.advCSSClasses = getLinkClass( element )
: advAttr( 'advCSSClasses', 'class' );
advAttr( 'advCharset', 'charset' );
advAttr( 'advStyles', 'style' );
advAttr( 'advRel', 'rel' );
}
// Find out whether we have any anchors in the editor.
var anchors = retval.anchors = [],
i, count, item;
// For some browsers we set contenteditable="false" on anchors, making document.anchors not to include them, so we must traverse the links manually (#7893).
if ( CKEDITOR.plugins.link.emptyAnchorFix )
{
var links = editor.document.getElementsByTag( 'a' );
for ( i = 0, count = links.count(); i < count; i++ )
{
item = links.getItem( i );
if ( item.data( 'cke-saved-name' ) || item.hasAttribute( 'name' ) )
anchors.push( { name : item.data( 'cke-saved-name' ) || item.getAttribute( 'name' ), id : item.getAttribute( 'id' ) } );
}
}
else
{
var anchorList = new CKEDITOR.dom.nodeList( editor.document.$.anchors );
for ( i = 0, count = anchorList.count(); i < count; i++ )
{
item = anchorList.getItem( i );
anchors[ i ] = { name : item.getAttribute( 'name' ), id : item.getAttribute( 'id' ) };
}
}
if ( CKEDITOR.plugins.link.fakeAnchor )
{
var imgs = editor.document.getElementsByTag( 'img' );
for ( i = 0, count = imgs.count(); i < count; i++ )
{
if ( ( item = CKEDITOR.plugins.link.tryRestoreFakeAnchor( editor, imgs.getItem( i ) ) ) )
anchors.push( { name : item.getAttribute( 'name' ), id : item.getAttribute( 'id' ) } );
}
}
// Record down the selected element in the dialog.
this._.selectedElement = element;
return retval;
};
var setupParams = function( page, data )
{
if ( data[page] )
this.setValue( data[page][this.id] || '' );
};
var setupPopupParams = function( data )
{
return setupParams.call( this, 'target', data );
};
var setupAdvParams = function( data )
{
return setupParams.call( this, 'adv', data );
};
var commitParams = function( page, data )
{
if ( !data[page] )
data[page] = {};
data[page][this.id] = this.getValue() || '';
};
var commitPopupParams = function( data )
{
return commitParams.call( this, 'target', data );
};
var commitAdvParams = function( data )
{
return commitParams.call( this, 'adv', data );
};
function unescapeSingleQuote( str )
{
return str.replace( /\\'/g, '\'' );
}
function escapeSingleQuote( str )
{
return str.replace( /'/g, '\\$&' );
}
var emailProtection = editor.config.emailProtection || '';
// Compile the protection function pattern.
if ( emailProtection && emailProtection != 'encode' )
{
var compiledProtectionFunction = {};
emailProtection.replace( /^([^(]+)\(([^)]+)\)$/, function( match, funcName, params )
{
compiledProtectionFunction.name = funcName;
compiledProtectionFunction.params = [];
params.replace( /[^,\s]+/g, function( param )
{
compiledProtectionFunction.params.push( param );
} );
} );
}
function protectEmailLinkAsFunction( email )
{
var retval,
name = compiledProtectionFunction.name,
params = compiledProtectionFunction.params,
paramName,
paramValue;
retval = [ name, '(' ];
for ( var i = 0; i < params.length; i++ )
{
paramName = params[ i ].toLowerCase();
paramValue = email[ paramName ];
i > 0 && retval.push( ',' );
retval.push( '\'',
paramValue ?
escapeSingleQuote( encodeURIComponent( email[ paramName ] ) )
: '',
'\'');
}
retval.push( ')' );
return retval.join( '' );
}
function protectEmailAddressAsEncodedString( address )
{
var charCode,
length = address.length,
encodedChars = [];
for ( var i = 0; i < length; i++ )
{
charCode = address.charCodeAt( i );
encodedChars.push( charCode );
}
return 'String.fromCharCode(' + encodedChars.join( ',' ) + ')';
}
function getLinkClass( ele )
{
var className = ele.getAttribute( 'class' );
return className ? className.replace( /\s*(?:cke_anchor_empty|cke_anchor)(?:\s*$)?/g, '' ) : '';
}
var commonLang = editor.lang.common,
linkLang = editor.lang.link;
return {
title : linkLang.title,
minWidth : 350,
minHeight : 230,
contents : [
{
id : 'info',
label : linkLang.info,
title : linkLang.info,
elements :
[
{
id : 'linkType',
type : 'select',
label : linkLang.type,
'default' : 'url',
items :
[
[ linkLang.toUrl, 'url' ],
[ linkLang.toAnchor, 'anchor' ],
[ linkLang.toEmail, 'email' ]
],
onChange : linkTypeChanged,
setup : function( data )
{
if ( data.type )
this.setValue( data.type );
},
commit : function( data )
{
data.type = this.getValue();
}
},
{
type : 'vbox',
id : 'urlOptions',
children :
[
{
type : 'hbox',
widths : [ '25%', '75%' ],
children :
[
{
id : 'protocol',
type : 'select',
label : commonLang.protocol,
'default' : 'http://',
items :
[
// Force 'ltr' for protocol names in BIDI. (#5433)
[ 'http://\u200E', 'http://' ],
[ 'https://\u200E', 'https://' ],
[ 'ftp://\u200E', 'ftp://' ],
[ 'news://\u200E', 'news://' ],
[ linkLang.other , '' ]
],
setup : function( data )
{
if ( data.url )
this.setValue( data.url.protocol || '' );
},
commit : function( data )
{
if ( !data.url )
data.url = {};
data.url.protocol = this.getValue();
}
},
{
type : 'text',
id : 'url',
label : commonLang.url,
required: true,
onLoad : function ()
{
this.allowOnChange = true;
},
onKeyUp : function()
{
this.allowOnChange = false;
var protocolCmb = this.getDialog().getContentElement( 'info', 'protocol' ),
url = this.getValue(),
urlOnChangeProtocol = /^(http|https|ftp|news):\/\/(?=.)/i,
urlOnChangeTestOther = /^((javascript:)|[#\/\.\?])/i;
var protocol = urlOnChangeProtocol.exec( url );
if ( protocol )
{
this.setValue( url.substr( protocol[ 0 ].length ) );
protocolCmb.setValue( protocol[ 0 ].toLowerCase() );
}
else if ( urlOnChangeTestOther.test( url ) )
protocolCmb.setValue( '' );
this.allowOnChange = true;
},
onChange : function()
{
if ( this.allowOnChange ) // Dont't call on dialog load.
this.onKeyUp();
},
validate : function()
{
var dialog = this.getDialog();
if ( dialog.getContentElement( 'info', 'linkType' ) &&
dialog.getValueOf( 'info', 'linkType' ) != 'url' )
return true;
if ( this.getDialog().fakeObj ) // Edit Anchor.
return true;
var func = CKEDITOR.dialog.validate.notEmpty( linkLang.noUrl );
return func.apply( this );
},
setup : function( data )
{
this.allowOnChange = false;
if ( data.url )
this.setValue( data.url.url );
this.allowOnChange = true;
},
commit : function( data )
{
// IE will not trigger the onChange event if the mouse has been used
// to carry all the operations #4724
this.onChange();
if ( !data.url )
data.url = {};
data.url.url = this.getValue();
this.allowOnChange = false;
}
}
],
setup : function( data )
{
if ( !this.getDialog().getContentElement( 'info', 'linkType' ) )
this.getElement().show();
}
},
{
type : 'button',
id : 'browse',
hidden : 'true',
filebrowser : 'info:url',
label : commonLang.browseServer
}
]
},
{
type : 'vbox',
id : 'anchorOptions',
width : 260,
align : 'center',
padding : 0,
children :
[
{
type : 'fieldset',
id : 'selectAnchorText',
label : linkLang.selectAnchor,
setup : function( data )
{
if ( data.anchors.length > 0 )
this.getElement().show();
else
this.getElement().hide();
},
children :
[
{
type : 'hbox',
id : 'selectAnchor',
children :
[
{
type : 'select',
id : 'anchorName',
'default' : '',
label : linkLang.anchorName,
style : 'width: 100%;',
items :
[
[ '' ]
],
setup : function( data )
{
this.clear();
this.add( '' );
for ( var i = 0 ; i < data.anchors.length ; i++ )
{
if ( data.anchors[i].name )
this.add( data.anchors[i].name );
}
if ( data.anchor )
this.setValue( data.anchor.name );
var linkType = this.getDialog().getContentElement( 'info', 'linkType' );
if ( linkType && linkType.getValue() == 'email' )
this.focus();
},
commit : function( data )
{
if ( !data.anchor )
data.anchor = {};
data.anchor.name = this.getValue();
}
},
{
type : 'select',
id : 'anchorId',
'default' : '',
label : linkLang.anchorId,
style : 'width: 100%;',
items :
[
[ '' ]
],
setup : function( data )
{
this.clear();
this.add( '' );
for ( var i = 0 ; i < data.anchors.length ; i++ )
{
if ( data.anchors[i].id )
this.add( data.anchors[i].id );
}
if ( data.anchor )
this.setValue( data.anchor.id );
},
commit : function( data )
{
if ( !data.anchor )
data.anchor = {};
data.anchor.id = this.getValue();
}
}
],
setup : function( data )
{
if ( data.anchors.length > 0 )
this.getElement().show();
else
this.getElement().hide();
}
}
]
},
{
type : 'html',
id : 'noAnchors',
style : 'text-align: center;',
html : '<div role="note" tabIndex="-1">' + CKEDITOR.tools.htmlEncode( linkLang.noAnchors ) + '</div>',
// Focus the first element defined in above html.
focus : true,
setup : function( data )
{
if ( data.anchors.length < 1 )
this.getElement().show();
else
this.getElement().hide();
}
}
],
setup : function( data )
{
if ( !this.getDialog().getContentElement( 'info', 'linkType' ) )
this.getElement().hide();
}
},
{
type : 'vbox',
id : 'emailOptions',
padding : 1,
children :
[
{
type : 'text',
id : 'emailAddress',
label : linkLang.emailAddress,
required : true,
validate : function()
{
var dialog = this.getDialog();
if ( !dialog.getContentElement( 'info', 'linkType' ) ||
dialog.getValueOf( 'info', 'linkType' ) != 'email' )
return true;
var func = CKEDITOR.dialog.validate.notEmpty( linkLang.noEmail );
return func.apply( this );
},
setup : function( data )
{
if ( data.email )
this.setValue( data.email.address );
var linkType = this.getDialog().getContentElement( 'info', 'linkType' );
if ( linkType && linkType.getValue() == 'email' )
this.select();
},
commit : function( data )
{
if ( !data.email )
data.email = {};
data.email.address = this.getValue();
}
},
{
type : 'text',
id : 'emailSubject',
label : linkLang.emailSubject,
setup : function( data )
{
if ( data.email )
this.setValue( data.email.subject );
},
commit : function( data )
{
if ( !data.email )
data.email = {};
data.email.subject = this.getValue();
}
},
{
type : 'textarea',
id : 'emailBody',
label : linkLang.emailBody,
rows : 3,
'default' : '',
setup : function( data )
{
if ( data.email )
this.setValue( data.email.body );
},
commit : function( data )
{
if ( !data.email )
data.email = {};
data.email.body = this.getValue();
}
}
],
setup : function( data )
{
if ( !this.getDialog().getContentElement( 'info', 'linkType' ) )
this.getElement().hide();
}
}
]
},
{
id : 'target',
label : linkLang.target,
title : linkLang.target,
elements :
[
{
type : 'hbox',
widths : [ '50%', '50%' ],
children :
[
{
type : 'select',
id : 'linkTargetType',
label : commonLang.target,
'default' : 'notSet',
style : 'width : 100%;',
'items' :
[
[ commonLang.notSet, 'notSet' ],
[ linkLang.targetFrame, 'frame' ],
[ linkLang.targetPopup, 'popup' ],
[ commonLang.targetNew, '_blank' ],
[ commonLang.targetTop, '_top' ],
[ commonLang.targetSelf, '_self' ],
[ commonLang.targetParent, '_parent' ]
],
onChange : targetChanged,
setup : function( data )
{
if ( data.target )
this.setValue( data.target.type || 'notSet' );
targetChanged.call( this );
},
commit : function( data )
{
if ( !data.target )
data.target = {};
data.target.type = this.getValue();
}
},
{
type : 'text',
id : 'linkTargetName',
label : linkLang.targetFrameName,
'default' : '',
setup : function( data )
{
if ( data.target )
this.setValue( data.target.name );
},
commit : function( data )
{
if ( !data.target )
data.target = {};
data.target.name = this.getValue().replace(/\W/gi, '');
}
}
]
},
{
type : 'vbox',
width : '100%',
align : 'center',
padding : 2,
id : 'popupFeatures',
children :
[
{
type : 'fieldset',
label : linkLang.popupFeatures,
children :
[
{
type : 'hbox',
children :
[
{
type : 'checkbox',
id : 'resizable',
label : linkLang.popupResizable,
setup : setupPopupParams,
commit : commitPopupParams
},
{
type : 'checkbox',
id : 'status',
label : linkLang.popupStatusBar,
setup : setupPopupParams,
commit : commitPopupParams
}
]
},
{
type : 'hbox',
children :
[
{
type : 'checkbox',
id : 'location',
label : linkLang.popupLocationBar,
setup : setupPopupParams,
commit : commitPopupParams
},
{
type : 'checkbox',
id : 'toolbar',
label : linkLang.popupToolbar,
setup : setupPopupParams,
commit : commitPopupParams
}
]
},
{
type : 'hbox',
children :
[
{
type : 'checkbox',
id : 'menubar',
label : linkLang.popupMenuBar,
setup : setupPopupParams,
commit : commitPopupParams
},
{
type : 'checkbox',
id : 'fullscreen',
label : linkLang.popupFullScreen,
setup : setupPopupParams,
commit : commitPopupParams
}
]
},
{
type : 'hbox',
children :
[
{
type : 'checkbox',
id : 'scrollbars',
label : linkLang.popupScrollBars,
setup : setupPopupParams,
commit : commitPopupParams
},
{
type : 'checkbox',
id : 'dependent',
label : linkLang.popupDependent,
setup : setupPopupParams,
commit : commitPopupParams
}
]
},
{
type : 'hbox',
children :
[
{
type : 'text',
widths : [ '50%', '50%' ],
labelLayout : 'horizontal',
label : commonLang.width,
id : 'width',
setup : setupPopupParams,
commit : commitPopupParams
},
{
type : 'text',
labelLayout : 'horizontal',
widths : [ '50%', '50%' ],
label : linkLang.popupLeft,
id : 'left',
setup : setupPopupParams,
commit : commitPopupParams
}
]
},
{
type : 'hbox',
children :
[
{
type : 'text',
labelLayout : 'horizontal',
widths : [ '50%', '50%' ],
label : commonLang.height,
id : 'height',
setup : setupPopupParams,
commit : commitPopupParams
},
{
type : 'text',
labelLayout : 'horizontal',
label : linkLang.popupTop,
widths : [ '50%', '50%' ],
id : 'top',
setup : setupPopupParams,
commit : commitPopupParams
}
]
}
]
}
]
}
]
},
{
id : 'upload',
label : linkLang.upload,
title : linkLang.upload,
hidden : true,
filebrowser : 'uploadButton',
elements :
[
{
type : 'file',
id : 'upload',
label : commonLang.upload,
style: 'height:40px',
size : 29
},
{
type : 'fileButton',
id : 'uploadButton',
label : commonLang.uploadSubmit,
filebrowser : 'info:url',
'for' : [ 'upload', 'upload' ]
}
]
},
{
id : 'advanced',
label : linkLang.advanced,
title : linkLang.advanced,
elements :
[
{
type : 'vbox',
padding : 1,
children :
[
{
type : 'hbox',
widths : [ '45%', '35%', '20%' ],
children :
[
{
type : 'text',
id : 'advId',
label : linkLang.id,
setup : setupAdvParams,
commit : commitAdvParams
},
{
type : 'select',
id : 'advLangDir',
label : linkLang.langDir,
'default' : '',
style : 'width:110px',
items :
[
[ commonLang.notSet, '' ],
[ linkLang.langDirLTR, 'ltr' ],
[ linkLang.langDirRTL, 'rtl' ]
],
setup : setupAdvParams,
commit : commitAdvParams
},
{
type : 'text',
id : 'advAccessKey',
width : '80px',
label : linkLang.acccessKey,
maxLength : 1,
setup : setupAdvParams,
commit : commitAdvParams
}
]
},
{
type : 'hbox',
widths : [ '45%', '35%', '20%' ],
children :
[
{
type : 'text',
label : linkLang.name,
id : 'advName',
setup : setupAdvParams,
commit : commitAdvParams
},
{
type : 'text',
label : linkLang.langCode,
id : 'advLangCode',
width : '110px',
'default' : '',
setup : setupAdvParams,
commit : commitAdvParams
},
{
type : 'text',
label : linkLang.tabIndex,
id : 'advTabIndex',
width : '80px',
maxLength : 5,
setup : setupAdvParams,
commit : commitAdvParams
}
]
}
]
},
{
type : 'vbox',
padding : 1,
children :
[
{
type : 'hbox',
widths : [ '45%', '55%' ],
children :
[
{
type : 'text',
label : linkLang.advisoryTitle,
'default' : '',
id : 'advTitle',
setup : setupAdvParams,
commit : commitAdvParams
},
{
type : 'text',
label : linkLang.advisoryContentType,
'default' : '',
id : 'advContentType',
setup : setupAdvParams,
commit : commitAdvParams
}
]
},
{
type : 'hbox',
widths : [ '45%', '55%' ],
children :
[
{
type : 'text',
label : linkLang.cssClasses,
'default' : '',
id : 'advCSSClasses',
setup : setupAdvParams,
commit : commitAdvParams
},
{
type : 'text',
label : linkLang.charset,
'default' : '',
id : 'advCharset',
setup : setupAdvParams,
commit : commitAdvParams
}
]
},
{
type : 'hbox',
widths : [ '45%', '55%' ],
children :
[
{
type : 'text',
label : linkLang.rel,
'default' : '',
id : 'advRel',
setup : setupAdvParams,
commit : commitAdvParams
},
{
type : 'text',
label : linkLang.styles,
'default' : '',
id : 'advStyles',
validate : CKEDITOR.dialog.validate.inlineStyle( editor.lang.common.invalidInlineStyle ),
setup : setupAdvParams,
commit : commitAdvParams
}
]
}
]
}
]
}
],
onShow : function()
{
var editor = this.getParentEditor(),
selection = editor.getSelection(),
element = null;
// Fill in all the relevant fields if there's already one link selected.
if ( ( element = plugin.getSelectedLink( editor ) ) && element.hasAttribute( 'href' ) )
selection.selectElement( element );
else
element = null;
this.setupContent( parseLink.apply( this, [ editor, element ] ) );
},
onOk : function()
{
var attributes = {},
removeAttributes = [],
data = {},
me = this,
editor = this.getParentEditor();
this.commitContent( data );
// Compose the URL.
switch ( data.type || 'url' )
{
case 'url':
var protocol = ( data.url && data.url.protocol != undefined ) ? data.url.protocol : 'http://',
url = ( data.url && CKEDITOR.tools.trim( data.url.url ) ) || '';
attributes[ 'data-cke-saved-href' ] = ( url.indexOf( '/' ) === 0 ) ? url : protocol + url;
break;
case 'anchor':
var name = ( data.anchor && data.anchor.name ),
id = ( data.anchor && data.anchor.id );
attributes[ 'data-cke-saved-href' ] = '#' + ( name || id || '' );
break;
case 'email':
var linkHref,
email = data.email,
address = email.address;
switch( emailProtection )
{
case '' :
case 'encode' :
{
var subject = encodeURIComponent( email.subject || '' ),
body = encodeURIComponent( email.body || '' );
// Build the e-mail parameters first.
var argList = [];
subject && argList.push( 'subject=' + subject );
body && argList.push( 'body=' + body );
argList = argList.length ? '?' + argList.join( '&' ) : '';
if ( emailProtection == 'encode' )
{
linkHref = [ 'javascript:void(location.href=\'mailto:\'+',
protectEmailAddressAsEncodedString( address ) ];
// parameters are optional.
argList && linkHref.push( '+\'', escapeSingleQuote( argList ), '\'' );
linkHref.push( ')' );
}
else
linkHref = [ 'mailto:', address, argList ];
break;
}
default :
{
// Separating name and domain.
var nameAndDomain = address.split( '@', 2 );
email.name = nameAndDomain[ 0 ];
email.domain = nameAndDomain[ 1 ];
linkHref = [ 'javascript:', protectEmailLinkAsFunction( email ) ];
}
}
attributes[ 'data-cke-saved-href' ] = linkHref.join( '' );
break;
}
// Popups and target.
if ( data.target )
{
if ( data.target.type == 'popup' )
{
var onclickList = [ 'window.open(this.href, \'',
data.target.name || '', '\', \'' ];
var featureList = [ 'resizable', 'status', 'location', 'toolbar', 'menubar', 'fullscreen',
'scrollbars', 'dependent' ];
var featureLength = featureList.length;
var addFeature = function( featureName )
{
if ( data.target[ featureName ] )
featureList.push( featureName + '=' + data.target[ featureName ] );
};
for ( var i = 0 ; i < featureLength ; i++ )
featureList[i] = featureList[i] + ( data.target[ featureList[i] ] ? '=yes' : '=no' ) ;
addFeature( 'width' );
addFeature( 'left' );
addFeature( 'height' );
addFeature( 'top' );
onclickList.push( featureList.join( ',' ), '\'); return false;' );
attributes[ 'data-cke-pa-onclick' ] = onclickList.join( '' );
// Add the "target" attribute. (#5074)
removeAttributes.push( 'target' );
}
else
{
if ( data.target.type != 'notSet' && data.target.name )
attributes.target = data.target.name;
else
removeAttributes.push( 'target' );
removeAttributes.push( 'data-cke-pa-onclick', 'onclick' );
}
}
// Advanced attributes.
if ( data.adv )
{
var advAttr = function( inputName, attrName )
{
var value = data.adv[ inputName ];
if ( value )
attributes[attrName] = value;
else
removeAttributes.push( attrName );
};
advAttr( 'advId', 'id' );
advAttr( 'advLangDir', 'dir' );
advAttr( 'advAccessKey', 'accessKey' );
if ( data.adv[ 'advName' ] )
attributes[ 'name' ] = attributes[ 'data-cke-saved-name' ] = data.adv[ 'advName' ];
else
removeAttributes = removeAttributes.concat( [ 'data-cke-saved-name', 'name' ] );
advAttr( 'advLangCode', 'lang' );
advAttr( 'advTabIndex', 'tabindex' );
advAttr( 'advTitle', 'title' );
advAttr( 'advContentType', 'type' );
advAttr( 'advCSSClasses', 'class' );
advAttr( 'advCharset', 'charset' );
advAttr( 'advStyles', 'style' );
advAttr( 'advRel', 'rel' );
}
var selection = editor.getSelection();
// Browser need the "href" fro copy/paste link to work. (#6641)
attributes.href = attributes[ 'data-cke-saved-href' ];
if ( !this._.selectedElement )
{
// Create element if current selection is collapsed.
var ranges = selection.getRanges( true );
if ( ranges.length == 1 && ranges[0].collapsed )
{
// Short mailto link text view (#5736).
var text = new CKEDITOR.dom.text( data.type == 'email' ?
data.email.address : attributes[ 'data-cke-saved-href' ], editor.document );
ranges[0].insertNode( text );
ranges[0].selectNodeContents( text );
selection.selectRanges( ranges );
}
// Apply style.
var style = new CKEDITOR.style( { element : 'a', attributes : attributes } );
style.type = CKEDITOR.STYLE_INLINE; // need to override... dunno why.
style.apply( editor.document );
}
else
{
// We're only editing an existing link, so just overwrite the attributes.
var element = this._.selectedElement,
href = element.data( 'cke-saved-href' ),
textView = element.getHtml();
element.setAttributes( attributes );
element.removeAttributes( removeAttributes );
if ( data.adv && data.adv.advName && CKEDITOR.plugins.link.synAnchorSelector )
element.addClass( element.getChildCount() ? 'cke_anchor' : 'cke_anchor_empty' );
// Update text view when user changes protocol (#4612).
if ( href == textView || data.type == 'email' && textView.indexOf( '@' ) != -1 )
{
// Short mailto link text view (#5736).
element.setHtml( data.type == 'email' ?
data.email.address : attributes[ 'data-cke-saved-href' ] );
}
selection.selectElement( element );
delete this._.selectedElement;
}
},
onLoad : function()
{
if ( !editor.config.linkShowAdvancedTab )
this.hidePage( 'advanced' ); //Hide Advanded tab.
if ( !editor.config.linkShowTargetTab )
this.hidePage( 'target' ); //Hide Target tab.
},
// Inital focus on 'url' field if link is of type URL.
onFocus : function()
{
var linkType = this.getContentElement( 'info', 'linkType' ),
urlField;
if ( linkType && linkType.getValue() == 'url' )
{
urlField = this.getContentElement( 'info', 'url' );
urlField.select();
}
}
};
});
/**
* The e-mail address anti-spam protection option. The protection will be
* applied when creating or modifying e-mail links through the editor interface.<br>
* Two methods of protection can be choosed:
* <ol> <li>The e-mail parts (name, domain and any other query string) are
* assembled into a function call pattern. Such function must be
* provided by the developer in the pages that will use the contents.
* <li>Only the e-mail address is obfuscated into a special string that
* has no meaning for humans or spam bots, but which is properly
* rendered and accepted by the browser.</li></ol>
* Both approaches require JavaScript to be enabled.
* @name CKEDITOR.config.emailProtection
* @since 3.1
* @type String
* @default '' (empty string = disabled)
* @example
* // href="mailto:tester@ckeditor.com?subject=subject&body=body"
* config.emailProtection = '';
* @example
* // href="<a href=\"javascript:void(location.href=\'mailto:\'+String.fromCharCode(116,101,115,116,101,114,64,99,107,101,100,105,116,111,114,46,99,111,109)+\'?subject=subject&body=body\')\">e-mail</a>"
* config.emailProtection = 'encode';
* @example
* // href="javascript:mt('tester','ckeditor.com','subject','body')"
* config.emailProtection = 'mt(NAME,DOMAIN,SUBJECT,BODY)';
*/
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/link/dialogs/link.js | JavaScript | asf20 | 39,814 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @file Clipboard support
*/
(function()
{
// Tries to execute any of the paste, cut or copy commands in IE. Returns a
// boolean indicating that the operation succeeded.
var execIECommand = function( editor, command )
{
var doc = editor.document,
body = doc.getBody();
var enabled = false;
var onExec = function()
{
enabled = true;
};
// The following seems to be the only reliable way to detect that
// clipboard commands are enabled in IE. It will fire the
// onpaste/oncut/oncopy events only if the security settings allowed
// the command to execute.
body.on( command, onExec );
// IE6/7: document.execCommand has problem to paste into positioned element.
( CKEDITOR.env.version > 7 ? doc.$ : doc.$.selection.createRange() ) [ 'execCommand' ]( command );
body.removeListener( command, onExec );
return enabled;
};
// Attempts to execute the Cut and Copy operations.
var tryToCutCopy =
CKEDITOR.env.ie ?
function( editor, type )
{
return execIECommand( editor, type );
}
: // !IE.
function( editor, type )
{
try
{
// Other browsers throw an error if the command is disabled.
return editor.document.$.execCommand( type, false, null );
}
catch( e )
{
return false;
}
};
// A class that represents one of the cut or copy commands.
var cutCopyCmd = function( type )
{
this.type = type;
this.canUndo = this.type == 'cut'; // We can't undo copy to clipboard.
this.startDisabled = true;
};
cutCopyCmd.prototype =
{
exec : function( editor, data )
{
this.type == 'cut' && fixCut( editor );
var success = tryToCutCopy( editor, this.type );
if ( !success )
alert( editor.lang.clipboard[ this.type + 'Error' ] ); // Show cutError or copyError.
return success;
}
};
// Paste command.
var pasteCmd =
{
canUndo : false,
exec :
CKEDITOR.env.ie ?
function( editor )
{
// Prevent IE from pasting at the begining of the document.
editor.focus();
if ( !editor.document.getBody().fire( 'beforepaste' )
&& !execIECommand( editor, 'paste' ) )
{
editor.fire( 'pasteDialog' );
return false;
}
}
:
function( editor )
{
try
{
if ( !editor.document.getBody().fire( 'beforepaste' )
&& !editor.document.$.execCommand( 'Paste', false, null ) )
{
throw 0;
}
}
catch ( e )
{
setTimeout( function()
{
editor.fire( 'pasteDialog' );
}, 0 );
return false;
}
}
};
// Listens for some clipboard related keystrokes, so they get customized.
var onKey = function( event )
{
if ( this.mode != 'wysiwyg' )
return;
switch ( event.data.keyCode )
{
// Paste
case CKEDITOR.CTRL + 86 : // CTRL+V
case CKEDITOR.SHIFT + 45 : // SHIFT+INS
var body = this.document.getBody();
// 1. Opera just misses the "paste" event.
// 2. Firefox's "paste" event comes too late to have the plain
// text paste bin to work.
if ( CKEDITOR.env.opera || CKEDITOR.env.gecko )
body.fire( 'paste' );
return;
// Cut
case CKEDITOR.CTRL + 88 : // CTRL+X
case CKEDITOR.SHIFT + 46 : // SHIFT+DEL
// Save Undo snapshot.
var editor = this;
this.fire( 'saveSnapshot' ); // Save before paste
setTimeout( function()
{
editor.fire( 'saveSnapshot' ); // Save after paste
}, 0 );
}
};
function cancel( evt ) { evt.cancel(); }
// Allow to peek clipboard content by redirecting the
// pasting content into a temporary bin and grab the content of it.
function getClipboardData( evt, mode, callback )
{
var doc = this.document;
// Avoid recursions on 'paste' event or consequent paste too fast. (#5730)
if ( doc.getById( 'cke_pastebin' ) )
return;
// If the browser supports it, get the data directly
if ( mode == 'text' && evt.data && evt.data.$.clipboardData )
{
// evt.data.$.clipboardData.types contains all the flavours in Mac's Safari, but not on windows.
var plain = evt.data.$.clipboardData.getData( 'text/plain' );
if ( plain )
{
evt.data.preventDefault();
callback( plain );
return;
}
}
var sel = this.getSelection(),
range = new CKEDITOR.dom.range( doc );
// Create container to paste into
var pastebin = new CKEDITOR.dom.element( mode == 'text' ? 'textarea' : CKEDITOR.env.webkit ? 'body' : 'div', doc );
pastebin.setAttribute( 'id', 'cke_pastebin' );
// Safari requires a filler node inside the div to have the content pasted into it. (#4882)
CKEDITOR.env.webkit && pastebin.append( doc.createText( '\xa0' ) );
doc.getBody().append( pastebin );
pastebin.setStyles(
{
position : 'absolute',
// Position the bin exactly at the position of the selected element
// to avoid any subsequent document scroll.
top : sel.getStartElement().getDocumentPosition().y + 'px',
width : '1px',
height : '1px',
overflow : 'hidden'
});
// It's definitely a better user experience if we make the paste-bin pretty unnoticed
// by pulling it off the screen.
pastebin.setStyle( this.config.contentsLangDirection == 'ltr' ? 'left' : 'right', '-1000px' );
var bms = sel.createBookmarks();
this.on( 'selectionChange', cancel, null, null, 0 );
// Turn off design mode temporarily before give focus to the paste bin.
if ( mode == 'text' )
pastebin.$.focus();
else
{
range.setStartAt( pastebin, CKEDITOR.POSITION_AFTER_START );
range.setEndAt( pastebin, CKEDITOR.POSITION_BEFORE_END );
range.select( true );
}
var editor = this;
// Wait a while and grab the pasted contents
window.setTimeout( function()
{
// Restore properly the document focus. (#5684, #8849)
editor.document.getBody().focus();
editor.removeListener( 'selectionChange', cancel );
// IE7: selection must go before removing paste bin. (#8691)
if ( CKEDITOR.env.ie7Compat )
{
sel.selectBookmarks( bms );
pastebin.remove();
}
// Webkit: selection must go after removing paste bin. (#8921)
else
{
pastebin.remove();
sel.selectBookmarks( bms );
}
// Grab the HTML contents.
// We need to look for a apple style wrapper on webkit it also adds
// a div wrapper if you copy/paste the body of the editor.
// Remove hidden div and restore selection.
var bogusSpan;
pastebin = ( CKEDITOR.env.webkit
&& ( bogusSpan = pastebin.getFirst() )
&& ( bogusSpan.is && bogusSpan.hasClass( 'Apple-style-span' ) ) ?
bogusSpan : pastebin );
callback( pastebin[ 'get' + ( mode == 'text' ? 'Value' : 'Html' ) ]() );
}, 0 );
}
// Cutting off control type element in IE standards breaks the selection entirely. (#4881)
function fixCut( editor )
{
if ( !CKEDITOR.env.ie || CKEDITOR.env.quirks )
return;
var sel = editor.getSelection();
var control;
if( ( sel.getType() == CKEDITOR.SELECTION_ELEMENT ) && ( control = sel.getSelectedElement() ) )
{
var range = sel.getRanges()[ 0 ];
var dummy = editor.document.createText( '' );
dummy.insertBefore( control );
range.setStartBefore( dummy );
range.setEndAfter( control );
sel.selectRanges( [ range ] );
// Clear up the fix if the paste wasn't succeeded.
setTimeout( function()
{
// Element still online?
if ( control.getParent() )
{
dummy.remove();
sel.selectElement( control );
}
}, 0 );
}
}
var depressBeforeEvent,
inReadOnly;
function stateFromNamedCommand( command, editor )
{
var retval;
if ( inReadOnly && command in { Paste : 1, Cut : 1 } )
return CKEDITOR.TRISTATE_DISABLED;
if ( command == 'Paste' )
{
// IE Bug: queryCommandEnabled('paste') fires also 'beforepaste(copy/cut)',
// guard to distinguish from the ordinary sources (either
// keyboard paste or execCommand) (#4874).
CKEDITOR.env.ie && ( depressBeforeEvent = 1 );
try
{
// Always return true for Webkit (which always returns false).
retval = editor.document.$.queryCommandEnabled( command ) || CKEDITOR.env.webkit;
}
catch( er ) {}
depressBeforeEvent = 0;
}
// Cut, Copy - check if the selection is not empty
else
{
var sel = editor.getSelection(),
ranges = sel && sel.getRanges();
retval = sel && !( ranges.length == 1 && ranges[ 0 ].collapsed );
}
return retval ? CKEDITOR.TRISTATE_OFF : CKEDITOR.TRISTATE_DISABLED;
}
function setToolbarStates()
{
if ( this.mode != 'wysiwyg' )
return;
var pasteState = stateFromNamedCommand( 'Paste', this );
this.getCommand( 'cut' ).setState( stateFromNamedCommand( 'Cut', this ) );
this.getCommand( 'copy' ).setState( stateFromNamedCommand( 'Copy', this ) );
this.getCommand( 'paste' ).setState( pasteState );
this.fire( 'pasteState', pasteState );
}
// Register the plugin.
CKEDITOR.plugins.add( 'clipboard',
{
requires : [ 'dialog', 'htmldataprocessor' ],
init : function( editor )
{
// Inserts processed data into the editor at the end of the
// events chain.
editor.on( 'paste', function( evt )
{
var data = evt.data;
if ( data[ 'html' ] )
editor.insertHtml( data[ 'html' ] );
else if ( data[ 'text' ] )
editor.insertText( data[ 'text' ] );
setTimeout( function () { editor.fire( 'afterPaste' ); }, 0 );
}, null, null, 1000 );
editor.on( 'pasteDialog', function( evt )
{
setTimeout( function()
{
// Open default paste dialog.
editor.openDialog( 'paste' );
}, 0 );
});
editor.on( 'pasteState', function( evt )
{
editor.getCommand( 'paste' ).setState( evt.data );
});
function addButtonCommand( buttonName, commandName, command, ctxMenuOrder )
{
var lang = editor.lang[ commandName ];
editor.addCommand( commandName, command );
editor.ui.addButton( buttonName,
{
label : lang,
command : commandName
});
// If the "menu" plugin is loaded, register the menu item.
if ( editor.addMenuItems )
{
editor.addMenuItem( commandName,
{
label : lang,
command : commandName,
group : 'clipboard',
order : ctxMenuOrder
});
}
}
addButtonCommand( 'Cut', 'cut', new cutCopyCmd( 'cut' ), 1 );
addButtonCommand( 'Copy', 'copy', new cutCopyCmd( 'copy' ), 4 );
addButtonCommand( 'Paste', 'paste', pasteCmd, 8 );
CKEDITOR.dialog.add( 'paste', CKEDITOR.getUrl( this.path + 'dialogs/paste.js' ) );
editor.on( 'key', onKey, editor );
// We'll be catching all pasted content in one line, regardless of whether the
// it's introduced by a document command execution (e.g. toolbar buttons) or
// user paste behaviors. (e.g. Ctrl-V)
editor.on( 'contentDom', function()
{
var body = editor.document.getBody();
// Intercept the paste before it actually takes place.
body.on( !CKEDITOR.env.ie ? 'paste' : 'beforepaste', function( evt )
{
if ( depressBeforeEvent )
return;
// Dismiss the (wrong) 'beforepaste' event fired on toolbar menu open.
var domEvent = evt.data && evt.data.$;
if ( CKEDITOR.env.ie && domEvent && !domEvent.ctrlKey )
return;
// Fire 'beforePaste' event so clipboard flavor get customized
// by other plugins.
var eventData = { mode : 'html' };
editor.fire( 'beforePaste', eventData );
getClipboardData.call( editor, evt, eventData.mode, function ( data )
{
// The very last guard to make sure the
// paste has successfully happened.
if ( !( data = CKEDITOR.tools.trim( data.replace( /<span[^>]+data-cke-bookmark[^<]*?<\/span>/ig,'' ) ) ) )
return;
var dataTransfer = {};
dataTransfer[ eventData.mode ] = data;
editor.fire( 'paste', dataTransfer );
} );
});
if ( CKEDITOR.env.ie )
{
// Dismiss the (wrong) 'beforepaste' event fired on context menu open. (#7953)
body.on( 'contextmenu', function()
{
depressBeforeEvent = 1;
// Important: The following timeout will be called only after menu closed.
setTimeout( function() { depressBeforeEvent = 0; }, 0 );
} );
// Handle IE's late coming "paste" event when pasting from
// browser toolbar/context menu.
body.on( 'paste', function( evt )
{
if ( !editor.document.getById( 'cke_pastebin' ) )
{
// Prevent native paste.
evt.data.preventDefault();
depressBeforeEvent = 0;
// Resort to the paste command.
pasteCmd.exec( editor );
}
} );
}
body.on( 'beforecut', function() { !depressBeforeEvent && fixCut( editor ); } );
body.on( 'mouseup', function(){ setTimeout( function(){ setToolbarStates.call( editor ); }, 0 ); }, editor );
body.on( 'keyup', setToolbarStates, editor );
});
// For improved performance, we're checking the readOnly state on selectionChange instead of hooking a key event for that.
editor.on( 'selectionChange', function( evt )
{
inReadOnly = evt.data.selection.getRanges()[ 0 ].checkReadOnly();
setToolbarStates.call( editor );
});
// If the "contextmenu" plugin is loaded, register the listeners.
if ( editor.contextMenu )
{
editor.contextMenu.addListener( function( element, selection )
{
var readOnly = selection.getRanges()[ 0 ].checkReadOnly();
return {
cut : stateFromNamedCommand( 'Cut', editor ),
copy : stateFromNamedCommand( 'Copy', editor ),
paste : stateFromNamedCommand( 'Paste', editor )
};
});
}
}
});
})();
/**
* Fired when a clipboard operation is about to be taken into the editor.
* Listeners can manipulate the data to be pasted before having it effectively
* inserted into the document.
* @name CKEDITOR.editor#paste
* @since 3.1
* @event
* @param {String} [data.html] The HTML data to be pasted. If not available, e.data.text will be defined.
* @param {String} [data.text] The plain text data to be pasted, available when plain text operations are to used. If not available, e.data.html will be defined.
*/
/**
* Internal event to open the Paste dialog
* @name CKEDITOR.editor#pasteDialog
* @event
*/
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/clipboard/plugin.js | JavaScript | asf20 | 15,008 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.dialog.add( 'paste', function( editor )
{
var lang = editor.lang.clipboard;
var isCustomDomain = CKEDITOR.env.isCustomDomain();
function onPasteFrameLoad( win )
{
var doc = new CKEDITOR.dom.document( win.document ),
docElement = doc.$;
var script = doc.getById( 'cke_actscrpt' );
script && script.remove();
CKEDITOR.env.ie ?
docElement.body.contentEditable = "true" :
docElement.designMode = "on";
// IE before version 8 will leave cursor blinking inside the document after
// editor blurred unless we clean up the selection. (#4716)
if ( CKEDITOR.env.ie && CKEDITOR.env.version < 8 )
{
doc.getWindow().on( 'blur', function()
{
docElement.selection.empty();
} );
}
doc.on( "keydown", function( e )
{
var domEvent = e.data,
key = domEvent.getKeystroke(),
processed;
switch( key )
{
case 27 :
this.hide();
processed = 1;
break;
case 9 :
case CKEDITOR.SHIFT + 9 :
this.changeFocus( 1 );
processed = 1;
}
processed && domEvent.preventDefault();
}, this );
editor.fire( 'ariaWidget', new CKEDITOR.dom.element( win.frameElement ) );
}
return {
title : lang.title,
minWidth : CKEDITOR.env.ie && CKEDITOR.env.quirks ? 370 : 350,
minHeight : CKEDITOR.env.quirks ? 250 : 245,
onShow : function()
{
// FIREFOX BUG: Force the browser to render the dialog to make the to-be-
// inserted iframe editable. (#3366)
this.parts.dialog.$.offsetHeight;
this.setupContent();
},
onHide : function()
{
if ( CKEDITOR.env.ie )
this.getParentEditor().document.getBody().$.contentEditable = 'true';
},
onLoad : function()
{
if ( ( CKEDITOR.env.ie7Compat || CKEDITOR.env.ie6Compat ) && editor.lang.dir == 'rtl' )
this.parts.contents.setStyle( 'overflow', 'hidden' );
},
onOk : function()
{
this.commitContent();
},
contents : [
{
id : 'general',
label : editor.lang.common.generalTab,
elements : [
{
type : 'html',
id : 'securityMsg',
html : '<div style="white-space:normal;width:340px;">' + lang.securityMsg + '</div>'
},
{
type : 'html',
id : 'pasteMsg',
html : '<div style="white-space:normal;width:340px;">'+lang.pasteMsg +'</div>'
},
{
type : 'html',
id : 'editing_area',
style : 'width: 100%; height: 100%;',
html : '',
focus : function()
{
var win = this.getInputElement().$.contentWindow;
// #3291 : JAWS needs the 500ms delay to detect that the editor iframe
// iframe is no longer editable. So that it will put the focus into the
// Paste from Word dialog's editable area instead.
setTimeout( function()
{
win.focus();
}, 500 );
},
setup : function()
{
var dialog = this.getDialog();
var htmlToLoad =
'<html dir="' + editor.config.contentsLangDirection + '"' +
' lang="' + ( editor.config.contentsLanguage || editor.langCode ) + '">' +
'<head><style>body { margin: 3px; height: 95%; } </style></head><body>' +
'<script id="cke_actscrpt" type="text/javascript">' +
'window.parent.CKEDITOR.tools.callFunction( ' + CKEDITOR.tools.addFunction( onPasteFrameLoad, dialog ) + ', this );' +
'</script></body>' +
'</html>';
var src =
CKEDITOR.env.air ?
'javascript:void(0)' :
isCustomDomain ?
'javascript:void((function(){' +
'document.open();' +
'document.domain=\'' + document.domain + '\';' +
'document.close();' +
'})())"'
:
'';
var iframe = CKEDITOR.dom.element.createFromHtml(
'<iframe' +
' class="cke_pasteframe"' +
' frameborder="0" ' +
' allowTransparency="true"' +
' src="' + src + '"' +
' role="region"' +
' aria-label="' + lang.pasteArea + '"' +
' aria-describedby="' + dialog.getContentElement( 'general', 'pasteMsg' ).domId + '"' +
' aria-multiple="true"' +
'></iframe>' );
iframe.on( 'load', function( e )
{
e.removeListener();
var doc = iframe.getFrameDocument();
doc.write( htmlToLoad );
if ( CKEDITOR.env.air )
onPasteFrameLoad.call( this, doc.getWindow().$ );
}, dialog );
iframe.setCustomData( 'dialog', dialog );
var container = this.getElement();
container.setHtml( '' );
container.append( iframe );
// IE need a redirect on focus to make
// the cursor blinking inside iframe. (#5461)
if ( CKEDITOR.env.ie )
{
var focusGrabber = CKEDITOR.dom.element.createFromHtml( '<span tabindex="-1" style="position:absolute;" role="presentation"></span>' );
focusGrabber.on( 'focus', function()
{
iframe.$.contentWindow.focus();
});
container.append( focusGrabber );
// Override focus handler on field.
this.focus = function()
{
focusGrabber.focus();
this.fire( 'focus' );
};
}
this.getInputElement = function(){ return iframe; };
// Force container to scale in IE.
if ( CKEDITOR.env.ie )
{
container.setStyle( 'display', 'block' );
container.setStyle( 'height', ( iframe.$.offsetHeight + 2 ) + 'px' );
}
},
commit : function( data )
{
var container = this.getElement(),
editor = this.getDialog().getParentEditor(),
body = this.getInputElement().getFrameDocument().getBody(),
bogus = body.getBogus(),
html;
bogus && bogus.remove();
// Saving the contents so changes until paste is complete will not take place (#7500)
html = body.getHtml();
setTimeout( function(){
editor.fire( 'paste', { 'html' : html } );
}, 0 );
}
}
]
}
]
};
});
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/clipboard/dialogs/paste.js | JavaScript | asf20 | 6,348 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @fileOverview Defines the {@link CKEDITOR.xml} class, which represents a
* loaded XML document.
*/
(function()
{
CKEDITOR.plugins.add( 'xml', {});
/**
* Represents a loaded XML document.
* @constructor
* @param {object|string} xmlObjectOrData A native XML (DOM document) object or
* a string containing the XML definition to be loaded.
* @example
* var xml = <b>new CKEDITOR.xml( '<books><book title="My Book" /></books>' )</b>;
*/
CKEDITOR.xml = function( xmlObjectOrData )
{
var baseXml = null;
if ( typeof xmlObjectOrData == 'object' )
baseXml = xmlObjectOrData;
else
{
var data = ( xmlObjectOrData || '' ).replace( / /g, '\xA0' );
if ( window.DOMParser )
baseXml = (new DOMParser()).parseFromString( data, 'text/xml' );
else if ( window.ActiveXObject )
{
try { baseXml = new ActiveXObject( 'MSXML2.DOMDocument' ); }
catch(e)
{
try { baseXml = new ActiveXObject( 'Microsoft.XmlDom' ); } catch(e) {}
}
if ( baseXml )
{
baseXml.async = false;
baseXml.resolveExternals = false;
baseXml.validateOnParse = false;
baseXml.loadXML( data );
}
}
}
/**
* The native XML (DOM document) used by the class instance.
* @type object
* @example
*/
this.baseXml = baseXml;
};
CKEDITOR.xml.prototype =
{
/**
* Get a single node from the XML document, based on a XPath query.
* @param {String} xpath The XPath query to execute.
* @param {Object} [contextNode] The XML DOM node to be used as the context
* for the XPath query. The document root is used by default.
* @returns {Object} A XML node element or null if the query has no results.
* @example
* // Create the XML instance.
* var xml = new CKEDITOR.xml( '<list><item id="test1" /><item id="test2" /></list>' );
* // Get the first <item> node.
* var itemNode = <b>xml.selectSingleNode( 'list/item' )</b>;
* // Alert "item".
* alert( itemNode.nodeName );
*/
selectSingleNode : function( xpath, contextNode )
{
var baseXml = this.baseXml;
if ( contextNode || ( contextNode = baseXml ) )
{
if ( CKEDITOR.env.ie || contextNode.selectSingleNode ) // IE
return contextNode.selectSingleNode( xpath );
else if ( baseXml.evaluate ) // Others
{
var result = baseXml.evaluate( xpath, contextNode, null, 9, null);
return ( result && result.singleNodeValue ) || null;
}
}
return null;
},
/**
* Gets a list node from the XML document, based on a XPath query.
* @param {String} xpath The XPath query to execute.
* @param {Object} [contextNode] The XML DOM node to be used as the context
* for the XPath query. The document root is used by default.
* @returns {ArrayLike} An array containing all matched nodes. The array will
* be empty if the query has no results.
* @example
* // Create the XML instance.
* var xml = new CKEDITOR.xml( '<list><item id="test1" /><item id="test2" /></list>' );
* // Get the first <item> node.
* var itemNodes = xml.selectSingleNode( 'list/item' );
* // Alert "item" twice, one for each <item>.
* for ( var i = 0 ; i < itemNodes.length ; i++ )
* alert( itemNodes[i].nodeName );
*/
selectNodes : function( xpath, contextNode )
{
var baseXml = this.baseXml,
nodes = [];
if ( contextNode || ( contextNode = baseXml ) )
{
if ( CKEDITOR.env.ie || contextNode.selectNodes ) // IE
return contextNode.selectNodes( xpath );
else if ( baseXml.evaluate ) // Others
{
var result = baseXml.evaluate( xpath, contextNode, null, 5, null);
if ( result )
{
var node;
while ( ( node = result.iterateNext() ) )
nodes.push( node );
}
}
}
return nodes;
},
/**
* Gets the string representation of hte inner contents of a XML node,
* based on a XPath query.
* @param {String} xpath The XPath query to execute.
* @param {Object} [contextNode] The XML DOM node to be used as the context
* for the XPath query. The document root is used by default.
* @returns {String} The textual representation of the inner contents of
* the node or null if the query has no results.
* @example
* // Create the XML instance.
* var xml = new CKEDITOR.xml( '<list><item id="test1" /><item id="test2" /></list>' );
* // Alert "<item id="test1" /><item id="test2" />".
* alert( xml.getInnerXml( 'list' ) );
*/
getInnerXml : function( xpath, contextNode )
{
var node = this.selectSingleNode( xpath, contextNode ),
xml = [];
if ( node )
{
node = node.firstChild;
while ( node )
{
if ( node.xml ) // IE
xml.push( node.xml );
else if ( window.XMLSerializer ) // Others
xml.push( ( new XMLSerializer() ).serializeToString( node ) );
node = node.nextSibling;
}
}
return xml.length ? xml.join( '' ) : null;
}
};
})();
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/xml/plugin.js | JavaScript | asf20 | 5,253 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @file AutoGrow plugin
*/
(function(){
// Actual content height, figured out by appending check the last element's document position.
function contentHeight( scrollable )
{
var overflowY = scrollable.getStyle( 'overflow-y' );
var doc = scrollable.getDocument();
// Create a temporary marker element.
var marker = CKEDITOR.dom.element.createFromHtml( '<span style="margin:0;padding:0;border:0;clear:both;width:1px;height:1px;display:block;">' + ( CKEDITOR.env.webkit ? ' ' : '' ) + '</span>', doc );
doc[ CKEDITOR.env.ie? 'getBody' : 'getDocumentElement']().append( marker );
var height = marker.getDocumentPosition( doc ).y + marker.$.offsetHeight;
marker.remove();
scrollable.setStyle( 'overflow-y', overflowY );
return height;
}
var resizeEditor = function( editor )
{
if ( !editor.window )
return;
var doc = editor.document,
iframe = new CKEDITOR.dom.element( doc.getWindow().$.frameElement ),
body = doc.getBody(),
htmlElement = doc.getDocumentElement(),
currentHeight = editor.window.getViewPaneSize().height,
// Quirks mode overflows body, standards overflows document element
scrollable = doc.$.compatMode == 'BackCompat' ? body : htmlElement,
newHeight = contentHeight( scrollable );
// Additional space specified by user.
newHeight += ( editor.config.autoGrow_bottomSpace || 0 );
var min = editor.config.autoGrow_minHeight != undefined ? editor.config.autoGrow_minHeight : 200,
max = editor.config.autoGrow_maxHeight || Infinity;
newHeight = Math.max( newHeight, min );
newHeight = Math.min( newHeight, max );
if ( newHeight != currentHeight )
{
newHeight = editor.fire( 'autoGrow', { currentHeight : currentHeight, newHeight : newHeight } ).newHeight;
editor.resize( editor.container.getStyle( 'width' ), newHeight, true );
}
if ( scrollable.$.scrollHeight > scrollable.$.clientHeight && newHeight < max )
scrollable.setStyle( 'overflow-y', 'hidden' );
else
scrollable.removeStyle( 'overflow-y' );
};
CKEDITOR.plugins.add( 'autogrow',
{
init : function( editor )
{
editor.addCommand( 'autogrow', { exec : resizeEditor, modes : { wysiwyg:1 }, readOnly: 1, canUndo: false, editorFocus: false } );
var eventsList = { contentDom:1, key:1, selectionChange:1, insertElement:1, mode:1 };
editor.config.autoGrow_onStartup && ( eventsList[ 'instanceReady' ] = 1 );
for ( var eventName in eventsList )
{
editor.on( eventName, function( evt )
{
var maximize = editor.getCommand( 'maximize' );
// Some time is required for insertHtml, and it gives other events better performance as well.
if ( evt.editor.mode == 'wysiwyg' &&
// Disable autogrow when the editor is maximized .(#6339)
( !maximize || maximize.state != CKEDITOR.TRISTATE_ON ) )
{
setTimeout( function()
{
resizeEditor( evt.editor );
// Second pass to make correction upon
// the first resize, e.g. scrollbar.
resizeEditor( evt.editor );
}, 100 );
}
});
}
}
});
})();
/**
* The minimum height that the editor can reach using the AutoGrow feature.
* @name CKEDITOR.config.autoGrow_minHeight
* @type Number
* @default <code>200</code>
* @since 3.4
* @example
* config.autoGrow_minHeight = 300;
*/
/**
* The maximum height that the editor can reach using the AutoGrow feature. Zero means unlimited.
* @name CKEDITOR.config.autoGrow_maxHeight
* @type Number
* @default <code>0</code>
* @since 3.4
* @example
* config.autoGrow_maxHeight = 400;
*/
/**
* Whether to have the auto grow happen on editor creation.
* @name CKEDITOR.config.autoGrow_onStartup
* @type Boolean
* @default false
* @since 3.6.2
* @example
* config.autoGrow_onStartup = true;
*/
/**
* Fired when the AutoGrow plugin is about to change the size of the editor.
* @name CKEDITOR.editor#autogrow
* @event
* @param {Number} data.currentHeight The current height of the editor (before resizing).
* @param {Number} data.newHeight The new height of the editor (after resizing). It can be changed
* to determine a different height value to be used instead.
*/
/**
* Extra height in pixel to leave between the bottom boundary of content with document size when auto resizing.
* @name CKEDITOR.config.autoGrow_bottomSpace
* @type Number
* @default 0
* @since 3.6.2
*/
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/autogrow/plugin.js | JavaScript | asf20 | 4,658 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
(function()
{
var eventNameList = [ 'click', 'keydown', 'mousedown', 'keypress', 'mouseover', 'mouseout' ];
// Inline event callbacks assigned via innerHTML/outerHTML, such as
// onclick/onmouseover, are ignored in AIR.
// Use DOM2 event listeners to substitue inline handlers instead.
function convertInlineHandlers( container )
{
// TODO: document.querySelectorAll is not supported in AIR.
var children = container.getElementsByTag( '*' ),
count = children.count(),
child;
for ( var i = 0; i < count; i++ )
{
child = children.getItem( i );
(function( node )
{
for ( var j = 0; j < eventNameList.length; j++ )
{
(function( eventName )
{
var inlineEventHandler = node.getAttribute( 'on' + eventName );
if ( node.hasAttribute( 'on' + eventName ) )
{
node.removeAttribute( 'on' + eventName );
node.on( eventName, function( evt )
{
var callFunc = /(return\s*)?CKEDITOR\.tools\.callFunction\(([^)]+)\)/.exec( inlineEventHandler ),
hasReturn = callFunc && callFunc[ 1 ],
callFuncArgs = callFunc && callFunc[ 2 ].split( ',' ),
preventDefault = /return false;/.test( inlineEventHandler );
if ( callFuncArgs )
{
var nums = callFuncArgs.length,
argName;
for ( var i = 0; i < nums; i++ )
{
// Trim spaces around param.
callFuncArgs[ i ] = argName = CKEDITOR.tools.trim( callFuncArgs[ i ] );
// String form param.
var strPattern = argName.match( /^(["'])([^"']*?)\1$/ );
if ( strPattern )
{
callFuncArgs[ i ] = strPattern[ 2 ];
continue;
}
// Integer form param.
if ( argName.match( /\d+/ ) )
{
callFuncArgs[ i ] = parseInt( argName, 10 );
continue;
}
// Speical variables.
switch( argName )
{
case 'this' :
callFuncArgs[ i ] = node.$;
break;
case 'event' :
callFuncArgs[ i ] = evt.data.$;
break;
case 'null' :
callFuncArgs [ i ] = null;
break;
}
}
var retval = CKEDITOR.tools.callFunction.apply( window, callFuncArgs );
if ( hasReturn && retval === false )
preventDefault = 1;
}
if ( preventDefault )
evt.data.preventDefault();
});
}
})( eventNameList[ j ] );
}
})( child );
}
}
CKEDITOR.plugins.add( 'adobeair',
{
init : function( editor )
{
if ( !CKEDITOR.env.air )
return;
// Body doesn't get default margin on AIR.
editor.addCss( 'body { padding: 8px }' );
editor.on( 'uiReady', function()
{
convertInlineHandlers( editor.container );
if ( editor.sharedSpaces )
{
for ( var space in editor.sharedSpaces )
convertInlineHandlers( editor.sharedSpaces[ space ] );
}
editor.on( 'elementsPathUpdate', function( evt ) { convertInlineHandlers( evt.data.space ); } );
});
editor.on( 'contentDom', function()
{
// Hyperlinks are enabled in editable documents in Adobe
// AIR. Prevent their click behavior.
editor.document.on( 'click', function( ev )
{
ev.data.preventDefault( true );
});
});
}
});
CKEDITOR.ui.on( 'ready', function( evt )
{
var ui = evt.data;
// richcombo, panelbutton and menu
if ( ui._.panel )
{
var panel = ui._.panel._.panel,
holder;
( function()
{
// Adding dom event listeners off-line are not supported in AIR,
// waiting for panel iframe loaded.
if ( !panel.isLoaded )
{
setTimeout( arguments.callee, 30 );
return;
}
holder = panel._.holder;
convertInlineHandlers( holder );
})();
}
else if ( ui instanceof CKEDITOR.dialog )
convertInlineHandlers( ui._.element );
});
})();
CKEDITOR.dom.document.prototype.write = CKEDITOR.tools.override( CKEDITOR.dom.document.prototype.write,
function( original_write )
{
function appendElement( parent, tagName, fullTag, text )
{
var node = parent.append( tagName ),
attrs = CKEDITOR.htmlParser.fragment.fromHtml( fullTag ).children[ 0 ].attributes;
attrs && node.setAttributes( attrs );
text && node.append( parent.getDocument().createText( text ) );
}
return function( html, mode )
{
// document.write() or document.writeln() fail silently after
// the page load event in Adobe AIR.
// DOM manipulation could be used instead.
if ( this.getBody() )
{
// We're taking the below extra work only because innerHTML
// on <html> element doesn't work as expected.
var doc = this,
head = this.getHead();
// Create style nodes for inline css. ( <style> content doesn't applied when setting via innerHTML )
html = html.replace( /(<style[^>]*>)([\s\S]*?)<\/style>/gi,
function ( match, startTag, styleText )
{
appendElement( head, 'style', startTag, styleText );
return '';
});
html = html.replace( /<base\b[^>]*\/>/i,
function( match )
{
appendElement( head, 'base', match );
return '';
});
html = html.replace( /<title>([\s\S]*)<\/title>/i,
function( match, title )
{
doc.$.title = title;
return '';
});
// Move the rest of head stuff.
html = html.replace( /<head>([\s\S]*)<\/head>/i,
function( headHtml )
{
// Inject the <head> HTML inside a <div>.
// Do that before getDocumentHead because WebKit moves
// <link css> elements to the <head> at this point.
var div = new CKEDITOR.dom.element( 'div', doc );
div.setHtml( headHtml );
// Move the <div> nodes to <head>.
div.moveChildren( head );
return '';
});
html.replace( /(<body[^>]*>)([\s\S]*)(?=$|<\/body>)/i,
function( match, startTag, innerHTML )
{
doc.getBody().setHtml( innerHTML );
var attrs = CKEDITOR.htmlParser.fragment.fromHtml( startTag ).children[ 0 ].attributes;
attrs && doc.getBody().setAttributes( attrs );
});
}
else
original_write.apply( this, arguments );
};
});
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/adobeair/plugin.js | JavaScript | asf20 | 6,679 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @fileOverview The "div" plugin. It wraps the selected block level elements with a 'div' element with specified styles and attributes.
*
*/
(function()
{
CKEDITOR.plugins.add( 'div',
{
requires : [ 'editingblock', 'dialog', 'domiterator', 'styles' ],
init : function( editor )
{
var lang = editor.lang.div;
editor.addCommand( 'creatediv', new CKEDITOR.dialogCommand( 'creatediv' ) );
editor.addCommand( 'editdiv', new CKEDITOR.dialogCommand( 'editdiv' ) );
editor.addCommand( 'removediv',
{
exec : function( editor )
{
var selection = editor.getSelection(),
ranges = selection && selection.getRanges(),
range,
bookmarks = selection.createBookmarks(),
walker,
toRemove = [];
function findDiv( node )
{
var path = new CKEDITOR.dom.elementPath( node ),
blockLimit = path.blockLimit,
div = blockLimit.is( 'div' ) && blockLimit;
if ( div && !div.data( 'cke-div-added' ) )
{
toRemove.push( div );
div.data( 'cke-div-added' );
}
}
for ( var i = 0 ; i < ranges.length ; i++ )
{
range = ranges[ i ];
if ( range.collapsed )
findDiv( selection.getStartElement() );
else
{
walker = new CKEDITOR.dom.walker( range );
walker.evaluator = findDiv;
walker.lastForward();
}
}
for ( i = 0 ; i < toRemove.length ; i++ )
toRemove[ i ].remove( true );
selection.selectBookmarks( bookmarks );
}
} );
editor.ui.addButton( 'CreateDiv',
{
label : lang.toolbar,
command :'creatediv'
} );
if ( editor.addMenuItems )
{
editor.addMenuItems(
{
editdiv :
{
label : lang.edit,
command : 'editdiv',
group : 'div',
order : 1
},
removediv:
{
label : lang.remove,
command : 'removediv',
group : 'div',
order : 5
}
} );
if ( editor.contextMenu )
{
editor.contextMenu.addListener( function( element, selection )
{
if ( !element || element.isReadOnly() )
return null;
var elementPath = new CKEDITOR.dom.elementPath( element ),
blockLimit = elementPath.blockLimit;
if ( blockLimit && blockLimit.getAscendant( 'div', true ) )
{
return {
editdiv : CKEDITOR.TRISTATE_OFF,
removediv : CKEDITOR.TRISTATE_OFF
};
}
return null;
} );
}
}
CKEDITOR.dialog.add( 'creatediv', this.path + 'dialogs/div.js' );
CKEDITOR.dialog.add( 'editdiv', this.path + 'dialogs/div.js' );
}
} );
})();
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/div/plugin.js | JavaScript | asf20 | 2,954 |
/*
* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.html or http://ckeditor.com/license
*/
(function()
{
/**
* Add to collection with DUP examination.
* @param {Object} collection
* @param {Object} element
* @param {Object} database
*/
function addSafely( collection, element, database )
{
// 1. IE doesn't support customData on text nodes;
// 2. Text nodes never get chance to appear twice;
if ( !element.is || !element.getCustomData( 'block_processed' ) )
{
element.is && CKEDITOR.dom.element.setMarker( database, element, 'block_processed', true );
collection.push( element );
}
}
function getNonEmptyChildren( element )
{
var retval = [];
var children = element.getChildren();
for ( var i = 0 ; i < children.count() ; i++ )
{
var child = children.getItem( i );
if ( ! ( child.type === CKEDITOR.NODE_TEXT
&& ( /^[ \t\n\r]+$/ ).test( child.getText() ) ) )
retval.push( child );
}
return retval;
}
/**
* Dialog reused by both 'creatediv' and 'editdiv' commands.
* @param {Object} editor
* @param {String} command The command name which indicate what the current command is.
*/
function divDialog( editor, command )
{
// Definition of elements at which div operation should stopped.
var divLimitDefinition = ( function(){
// Customzie from specialize blockLimit elements
var definition = CKEDITOR.tools.extend( {}, CKEDITOR.dtd.$blockLimit );
// Exclude 'div' itself.
delete definition.div;
// Exclude 'td' and 'th' when 'wrapping table'
if ( editor.config.div_wrapTable )
{
delete definition.td;
delete definition.th;
}
return definition;
})();
// DTD of 'div' element
var dtd = CKEDITOR.dtd.div;
/**
* Get the first div limit element on the element's path.
* @param {Object} element
*/
function getDivLimitElement( element )
{
var pathElements = new CKEDITOR.dom.elementPath( element ).elements;
var divLimit;
for ( var i = 0; i < pathElements.length ; i++ )
{
if ( pathElements[ i ].getName() in divLimitDefinition )
{
divLimit = pathElements[ i ];
break;
}
}
return divLimit;
}
/**
* Init all fields' setup/commit function.
* @memberof divDialog
*/
function setupFields()
{
this.foreach( function( field )
{
// Exclude layout container elements
if ( /^(?!vbox|hbox)/.test( field.type ) )
{
if ( !field.setup )
{
// Read the dialog fields values from the specified
// element attributes.
field.setup = function( element )
{
field.setValue( element.getAttribute( field.id ) || '' );
};
}
if ( !field.commit )
{
// Set element attributes assigned by the dialog
// fields.
field.commit = function( element )
{
var fieldValue = this.getValue();
// ignore default element attribute values
if ( 'dir' == field.id && element.getComputedStyle( 'direction' ) == fieldValue )
return;
if ( fieldValue )
element.setAttribute( field.id, fieldValue );
else
element.removeAttribute( field.id );
};
}
}
} );
}
/**
* Wrapping 'div' element around appropriate blocks among the selected ranges.
* @param {Object} editor
*/
function createDiv( editor )
{
// new adding containers OR detected pre-existed containers.
var containers = [];
// node markers store.
var database = {};
// All block level elements which contained by the ranges.
var containedBlocks = [], block;
// Get all ranges from the selection.
var selection = editor.document.getSelection(),
ranges = selection.getRanges();
var bookmarks = selection.createBookmarks();
var i, iterator;
// Calcualte a default block tag if we need to create blocks.
var blockTag = editor.config.enterMode == CKEDITOR.ENTER_DIV ? 'div' : 'p';
// collect all included elements from dom-iterator
for ( i = 0 ; i < ranges.length ; i++ )
{
iterator = ranges[ i ].createIterator();
while ( ( block = iterator.getNextParagraph() ) )
{
// include contents of blockLimit elements.
if ( block.getName() in divLimitDefinition )
{
var j, childNodes = block.getChildren();
for ( j = 0 ; j < childNodes.count() ; j++ )
addSafely( containedBlocks, childNodes.getItem( j ) , database );
}
else
{
// Bypass dtd disallowed elements.
while ( !dtd[ block.getName() ] && block.getName() != 'body' )
block = block.getParent();
addSafely( containedBlocks, block, database );
}
}
}
CKEDITOR.dom.element.clearAllMarkers( database );
var blockGroups = groupByDivLimit( containedBlocks );
var ancestor, blockEl, divElement;
for ( i = 0 ; i < blockGroups.length ; i++ )
{
var currentNode = blockGroups[ i ][ 0 ];
// Calculate the common parent node of all contained elements.
ancestor = currentNode.getParent();
for ( j = 1 ; j < blockGroups[ i ].length; j++ )
ancestor = ancestor.getCommonAncestor( blockGroups[ i ][ j ] );
divElement = new CKEDITOR.dom.element( 'div', editor.document );
// Normalize the blocks in each group to a common parent.
for ( j = 0; j < blockGroups[ i ].length ; j++ )
{
currentNode = blockGroups[ i ][ j ];
while ( !currentNode.getParent().equals( ancestor ) )
currentNode = currentNode.getParent();
// This could introduce some duplicated elements in array.
blockGroups[ i ][ j ] = currentNode;
}
// Wrapped blocks counting
var fixedBlock = null;
for ( j = 0 ; j < blockGroups[ i ].length ; j++ )
{
currentNode = blockGroups[ i ][ j ];
// Avoid DUP elements introduced by grouping.
if ( !( currentNode.getCustomData && currentNode.getCustomData( 'block_processed' ) ) )
{
currentNode.is && CKEDITOR.dom.element.setMarker( database, currentNode, 'block_processed', true );
// Establish new container, wrapping all elements in this group.
if ( !j )
divElement.insertBefore( currentNode );
divElement.append( currentNode );
}
}
CKEDITOR.dom.element.clearAllMarkers( database );
containers.push( divElement );
}
selection.selectBookmarks( bookmarks );
return containers;
}
function getDiv( editor )
{
var path = new CKEDITOR.dom.elementPath( editor.getSelection().getStartElement() ),
blockLimit = path.blockLimit,
div = blockLimit && blockLimit.getAscendant( 'div', true );
return div;
}
/**
* Divide a set of nodes to different groups by their path's blocklimit element.
* Note: the specified nodes should be in source order naturally, which mean they are supposed to producea by following class:
* * CKEDITOR.dom.range.Iterator
* * CKEDITOR.dom.domWalker
* @return {Array []} the grouped nodes
*/
function groupByDivLimit( nodes )
{
var groups = [],
lastDivLimit = null,
path, block;
for ( var i = 0 ; i < nodes.length ; i++ )
{
block = nodes[i];
var limit = getDivLimitElement( block );
if ( !limit.equals( lastDivLimit ) )
{
lastDivLimit = limit ;
groups.push( [] ) ;
}
groups[ groups.length - 1 ].push( block ) ;
}
return groups;
}
// Synchronous field values to other impacted fields is required, e.g. div styles
// change should also alter inline-style text.
function commitInternally( targetFields )
{
var dialog = this.getDialog(),
element = dialog._element && dialog._element.clone()
|| new CKEDITOR.dom.element( 'div', editor.document );
// Commit this field and broadcast to target fields.
this.commit( element, true );
targetFields = [].concat( targetFields );
var length = targetFields.length, field;
for ( var i = 0; i < length; i++ )
{
field = dialog.getContentElement.apply( dialog, targetFields[ i ].split( ':' ) );
field && field.setup && field.setup( element, true );
}
}
// Registered 'CKEDITOR.style' instances.
var styles = {} ;
/**
* Hold a collection of created block container elements.
*/
var containers = [];
/**
* @type divDialog
*/
return {
title : editor.lang.div.title,
minWidth : 400,
minHeight : 165,
contents :
[
{
id :'info',
label :editor.lang.common.generalTab,
title :editor.lang.common.generalTab,
elements :
[
{
type :'hbox',
widths : [ '50%', '50%' ],
children :
[
{
id :'elementStyle',
type :'select',
style :'width: 100%;',
label :editor.lang.div.styleSelectLabel,
'default' : '',
// Options are loaded dynamically.
items :
[
[ editor.lang.common.notSet , '' ]
],
onChange : function()
{
commitInternally.call( this, [ 'info:class', 'advanced:dir', 'advanced:style' ] );
},
setup : function( element )
{
for ( var name in styles )
styles[ name ].checkElementRemovable( element, true ) && this.setValue( name );
},
commit: function( element )
{
var styleName;
if ( ( styleName = this.getValue() ) )
{
var style = styles[ styleName ];
var customData = element.getCustomData( 'elementStyle' ) || '';
style.applyToObject( element );
element.setCustomData( 'elementStyle', customData + style._.definition.attributes.style );
}
}
},
{
id :'class',
type :'text',
label :editor.lang.common.cssClass,
'default' : ''
}
]
}
]
},
{
id :'advanced',
label :editor.lang.common.advancedTab,
title :editor.lang.common.advancedTab,
elements :
[
{
type :'vbox',
padding :1,
children :
[
{
type :'hbox',
widths : [ '50%', '50%' ],
children :
[
{
type :'text',
id :'id',
label :editor.lang.common.id,
'default' : ''
},
{
type :'text',
id :'lang',
label :editor.lang.link.langCode,
'default' : ''
}
]
},
{
type :'hbox',
children :
[
{
type :'text',
id :'style',
style :'width: 100%;',
label :editor.lang.common.cssStyle,
'default' : '',
commit : function( element )
{
// Merge with 'elementStyle', which is of higher priority.
var merged = this.getValue() + ( element.getCustomData( 'elementStyle' ) || '' );
element.setAttribute( 'style', merged );
}
}
]
},
{
type :'hbox',
children :
[
{
type :'text',
id :'title',
style :'width: 100%;',
label :editor.lang.common.advisoryTitle,
'default' : ''
}
]
},
{
type :'select',
id :'dir',
style :'width: 100%;',
label :editor.lang.common.langDir,
'default' : '',
items :
[
[ editor.lang.common.notSet , '' ],
[
editor.lang.common.langDirLtr,
'ltr'
],
[
editor.lang.common.langDirRtl,
'rtl'
]
]
}
]
}
]
}
],
onLoad : function()
{
setupFields.call( this );
// Preparing for the 'elementStyle' field.
var dialog = this,
stylesField = this.getContentElement( 'info', 'elementStyle' );
// Reuse the 'stylescombo' plugin's styles definition.
editor.getStylesSet( function( stylesDefinitions )
{
var styleName;
if ( stylesDefinitions )
{
// Digg only those styles that apply to 'div'.
for ( var i = 0 ; i < stylesDefinitions.length ; i++ )
{
var styleDefinition = stylesDefinitions[ i ];
if ( styleDefinition.element && styleDefinition.element == 'div' )
{
styleName = styleDefinition.name;
styles[ styleName ] = new CKEDITOR.style( styleDefinition );
// Populate the styles field options with style name.
stylesField.items.push( [ styleName, styleName ] );
stylesField.add( styleName, styleName );
}
}
}
// We should disable the content element
// it if no options are available at all.
stylesField[ stylesField.items.length > 1 ? 'enable' : 'disable' ]();
// Now setup the field value manually.
setTimeout( function() { stylesField.setup( dialog._element ); }, 0 );
} );
},
onShow : function()
{
// Whether always create new container regardless of existed
// ones.
if ( command == 'editdiv' )
{
// Try to discover the containers that already existed in
// ranges
var div = getDiv( editor );
// update dialog field values
div && this.setupContent( this._element = div );
}
},
onOk : function()
{
if ( command == 'editdiv' )
containers = [ this._element ];
else
containers = createDiv( editor, true );
// Update elements attributes
var size = containers.length;
for ( var i = 0; i < size; i++ )
{
this.commitContent( containers[ i ] );
// Remove empty 'style' attribute.
!containers[ i ].getAttribute( 'style' ) && containers[ i ].removeAttribute( 'style' );
}
this.hide();
},
onHide : function()
{
// Remove style only when editing existing DIV. (#6315)
if ( command == 'editdiv' )
this._element.removeCustomData( 'elementStyle' );
delete this._element;
}
};
}
CKEDITOR.dialog.add( 'creatediv', function( editor )
{
return divDialog( editor, 'creatediv' );
} );
CKEDITOR.dialog.add( 'editdiv', function( editor )
{
return divDialog( editor, 'editdiv' );
} );
} )();
/*
* @name CKEDITOR.config.div_wrapTable
* Whether to wrap the whole table instead of indivisual cells when created 'div' in table cell.
* @type Boolean
* @default false
* @example config.div_wrapTable = true;
*/
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/div/dialogs/div.js | JavaScript | asf20 | 14,886 |
/*
Copyright (c) 2003-2012, 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();
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' : '',
validate : CKEDITOR.dialog.validate.inlineStyle( lang.invalidInlineStyle ),
onChange : function(){},
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;
}
});
})();
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/dialogadvtab/plugin.js | JavaScript | asf20 | 4,150 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
(function()
{
var guardElements = { table:1, ul:1, ol:1, blockquote:1, div: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;
if ( editor.readOnly )
return;
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 we're having BODY here, user probably done CTRL+A, let's try to get the enclosed node, if any.
if ( selectedElement.is( 'body' ) )
{
var enclosedNode = editor.getSelection().getRanges()[ 0 ].getEnclosedNode();
enclosedNode && enclosedNode.type == CKEDITOR.NODE_ELEMENT && ( selectedElement = enclosedNode );
}
if ( !selectedElement )
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,
directionNode = evt.data.path.block || evt.data.path.blockLimit;
editor.fire( 'contentDirChanged', directionNode ? directionNode.getComputedStyle( 'direction' ) : editor.lang.dir );
}
/**
* 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 )
{
if ( element.isReadOnly() )
return;
// 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;
}
}
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;
// 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 );
editor.forceNextSelectionCheck();
return;
}
function getFullySelected( range, elements, enterMode )
{
var ancestor = range.getCommonAncestor( false, true );
range = range.clone();
range.enlarge( enterMode == CKEDITOR.ENTER_BR ?
CKEDITOR.ENLARGE_LIST_ITEM_CONTENTS
: 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 ) )
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, enterMode );
selectedElement && 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' ) ) )
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 );
editor.on( 'contentDom', function()
{
editor.document.on( 'dirChanged', function( evt )
{
editor.fire( 'dirChanged',
{
node : evt.data,
dir : evt.data.getDirection( 1 )
} );
});
});
}
});
// 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)
function isOffline( el )
{
var html = el.getDocument().getBody().getParent();
while ( el )
{
if ( el.equals( html ) )
return false;
el = el.getParent();
}
return true;
}
function dirChangeNotifier( org )
{
var isAttribute = org == elementProto.setAttribute,
isRemoveAttribute = org == elementProto.removeAttribute,
dirStyleRegexp = /\bdirection\s*:\s*(.*?)\s*(:?$|;)/;
return function( name, val )
{
if ( !this.getDocument().equals( CKEDITOR.document ) )
{
var orgDir;
if ( ( name == ( isAttribute || isRemoveAttribute ? 'dir' : 'direction' ) ||
name == 'style' && ( isRemoveAttribute || dirStyleRegexp.test( val ) ) ) && !isOffline( this ) )
{
orgDir = this.getDirection( 1 );
var retval = org.apply( this, arguments );
if ( orgDir != this.getDirection( 1 ) )
{
this.getDocument().fire( 'dirChanged', this );
return retval;
}
}
}
return org.apply( this, arguments );
};
}
var elementProto = CKEDITOR.dom.element.prototype,
methods = [ 'setStyle', 'removeStyle', 'setAttribute', 'removeAttribute' ];
for ( var i = 0; i < methods.length; i++ )
elementProto[ methods[ i ] ] = CKEDITOR.tools.override( elementProto[ methods [ i ] ], dirChangeNotifier );
})();
/**
* Fired when the language direction of an element is changed
* @name CKEDITOR.editor#dirChanged
* @event
* @param {CKEDITOR.editor} editor This editor instance.
* @param {Object} eventData.node The element that is being changed.
* @param {String} eventData.dir The new direction.
*/
/**
* Fired when the language direction in the specific cursor position is changed
* @name CKEDITOR.editor#contentDirChanged
* @event
* @param {String} eventData The direction in the current position.
*/
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/bidi/plugin.js | JavaScript | asf20 | 10,441 |
/*
Copyright (c) 2003-2012, 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 },
isNotWhitespaces = CKEDITOR.dom.walker.whitespaces( true ),
isNotBookmark = CKEDITOR.dom.walker.bookmark( false, true );
function onSelectionChange( evt )
{
if ( evt.editor.readOnly )
return null;
var editor = evt.editor,
elementPath = evt.data.path,
list = elementPath && elementPath.contains( listNodeNames ),
firstBlock = elementPath.block || elementPath.blockLimit;
if ( list )
return this.setState( CKEDITOR.TRISTATE_OFF );
if ( !this.useIndentClasses && this.name == 'indent' )
return this.setState( CKEDITOR.TRISTATE_OFF );
if ( !firstBlock )
return this.setState( 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 this.setState( CKEDITOR.TRISTATE_DISABLED );
return this.setState( CKEDITOR.TRISTATE_OFF );
}
else
{
var indent = parseInt( firstBlock.getStyle( getIndentCssProperty( firstBlock ) ), 10 );
if ( isNaN( indent ) )
indent = 0;
if ( indent <= 0 )
return this.setState( CKEDITOR.TRISTATE_DISABLED );
return this.setState( 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)
if ( indentOffset > 0 )
{
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( enterMode == CKEDITOR.ENTER_P ? 'p' : 'div' ) ) )
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 = editor.addCommand( 'indent', new indentCommand( editor, 'indent' ) ),
outdent = editor.addCommand( 'outdent', new indentCommand( editor, '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'];
*/
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/indent/plugin.js | JavaScript | asf20 | 15,670 |
/*
Copyright (c) 2003-2012, 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' && !one.readOnly )
{
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',
{
// Disabled on iOS (#8307).
modes : { wysiwyg : !CKEDITOR.env.iOS, source : !CKEDITOR.env.iOS },
readOnly : 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 styles =
{
overflow : CKEDITOR.env.webkit ? '' : 'hidden', // #6896
width : 0,
height : 0
};
mainDocument.getDocumentElement().setStyles( styles );
!CKEDITOR.env.gecko && mainDocument.getDocumentElement().setStyle( 'position', 'fixed' );
!( CKEDITOR.env.gecko && CKEDITOR.env.quirks ) && 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.
// Special treatment for FF Quirks (#7284)
container.setStyle( 'position', CKEDITOR.env.gecko && CKEDITOR.env.quirks ? 'fixed' : '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' );
// Webkit requires a re-layout on editor chrome. (#6695)
if ( CKEDITOR.env.webkit )
{
container.setStyle( 'display', 'inline' );
setTimeout( function(){ container.setStyle( 'display', 'block' ); }, 0 );
}
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 ];
// Only try to change the button if it exists (#6166)
if( button )
{
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 );
}
} );
})();
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/maximize/plugin.js | JavaScript | asf20 | 11,442 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
(function()
{
CKEDITOR.on( 'dialogDefinition', function( ev )
{
var tab, name = ev.data.name,
definition = ev.data.definition;
if ( name == 'link' )
{
definition.removeContents( 'target' );
definition.removeContents( 'upload' );
definition.removeContents( 'advanced' );
tab = definition.getContents( 'info' );
tab.remove( 'emailSubject' );
tab.remove( 'emailBody' );
}
else if ( name == 'image' )
{
definition.removeContents( 'advanced' );
tab = definition.getContents( 'Link' );
tab.remove( 'cmbTarget' );
tab = definition.getContents( 'info' );
tab.remove( 'txtAlt' );
tab.remove( 'basic' );
}
});
var bbcodeMap = { 'b' : 'strong', 'u': 'u', 'i' : 'em', 'color' : 'span', 'size' : 'span', 'quote' : 'blockquote', 'code' : 'code', 'url' : 'a', 'email' : 'span', 'img' : 'span', '*' : 'li', 'list' : 'ol' },
convertMap = { 'strong' : 'b' , 'b' : 'b', 'u': 'u', 'em' : 'i', 'i': 'i', 'code' : 'code', 'li' : '*' },
tagnameMap = { 'strong' : 'b', 'em' : 'i', 'u' : 'u', 'li' : '*', 'ul' : 'list', 'ol' : 'list', 'code' : 'code', 'a' : 'link', 'img' : 'img', 'blockquote' : 'quote' },
stylesMap = { 'color' : 'color', 'size' : 'font-size' },
attributesMap = { 'url' : 'href', 'email' : 'mailhref', 'quote': 'cite', 'list' : 'listType' };
// List of block-like tags.
var dtd = CKEDITOR.dtd,
blockLikeTags = CKEDITOR.tools.extend( { table:1 }, dtd.$block, dtd.$listItem, dtd.$tableContent, dtd.$list );
var semicolonFixRegex = /\s*(?:;\s*|$)/;
function serializeStyleText( stylesObject )
{
var styleText = '';
for ( var style in stylesObject )
{
var styleVal = stylesObject[ style ],
text = ( style + ':' + styleVal ).replace( semicolonFixRegex, ';' );
styleText += text;
}
return styleText;
}
function parseStyleText( styleText )
{
var retval = {};
( styleText || '' )
.replace( /"/g, '"' )
.replace( /\s*([^ :;]+)\s*:\s*([^;]+)\s*(?=;|$)/g, function( match, name, value )
{
retval[ name.toLowerCase() ] = value;
} );
return retval;
}
function RGBToHex( cssStyle )
{
return cssStyle.replace( /(?:rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\))/gi, function( match, red, green, blue )
{
red = parseInt( red, 10 ).toString( 16 );
green = parseInt( green, 10 ).toString( 16 );
blue = parseInt( blue, 10 ).toString( 16 );
var color = [red, green, blue] ;
// Add padding zeros if the hex value is less than 0x10.
for ( var i = 0 ; i < color.length ; i++ )
color[i] = String( '0' + color[i] ).slice( -2 ) ;
return '#' + color.join( '' ) ;
});
}
// Maintain the map of smiley-to-description.
var smileyMap = {"smiley":":)","sad":":(","wink":";)","laugh":":D","cheeky":":P","blush":":*)","surprise":":-o","indecision":":|","angry":">:(","angel":"o:)","cool":"8-)","devil":">:-)","crying":";(","kiss":":-*" },
smileyReverseMap = {},
smileyRegExp = [];
// Build regexp for the list of smiley text.
for ( var i in smileyMap )
{
smileyReverseMap[ smileyMap[ i ] ] = i;
smileyRegExp.push( smileyMap[ i ].replace( /\(|\)|\:|\/|\*|\-|\|/g, function( match ) { return '\\' + match; } ) );
}
smileyRegExp = new RegExp( smileyRegExp.join( '|' ), 'g' );
var decodeHtml = ( function ()
{
var regex = [],
entities =
{
nbsp : '\u00A0', // IE | FF
shy : '\u00AD', // IE
gt : '\u003E', // IE | FF | -- | Opera
lt : '\u003C' // IE | FF | Safari | Opera
};
for ( var entity in entities )
regex.push( entity );
regex = new RegExp( '&(' + regex.join( '|' ) + ');', 'g' );
return function( html )
{
return html.replace( regex, function( match, entity )
{
return entities[ entity ];
});
};
})();
CKEDITOR.BBCodeParser = function()
{
this._ =
{
bbcPartsRegex : /(?:\[([^\/\]=]*?)(?:=([^\]]*?))?\])|(?:\[\/([a-z]{1,16})\])/ig
};
};
CKEDITOR.BBCodeParser.prototype =
{
parse : function( bbcode )
{
var parts,
part,
lastIndex = 0;
while ( ( parts = this._.bbcPartsRegex.exec( bbcode ) ) )
{
var tagIndex = parts.index;
if ( tagIndex > lastIndex )
{
var text = bbcode.substring( lastIndex, tagIndex );
this.onText( text, 1 );
}
lastIndex = this._.bbcPartsRegex.lastIndex;
/*
"parts" is an array with the following items:
0 : The entire match for opening/closing tags and line-break;
1 : line-break;
2 : open of tag excludes option;
3 : tag option;
4 : close of tag;
*/
part = ( parts[ 1 ] || parts[ 3 ] || '' ).toLowerCase();
// Unrecognized tags should be delivered as a simple text (#7860).
if ( part && !bbcodeMap[ part ] )
{
this.onText( parts[ 0 ] );
continue;
}
// Opening tag
if ( parts[ 1 ] )
{
var tagName = bbcodeMap[ part ],
attribs = {},
styles = {},
optionPart = parts[ 2 ];
if ( optionPart )
{
if ( part == 'list' )
{
if ( !isNaN( optionPart ) )
optionPart = 'decimal';
else if ( /^[a-z]+$/.test( optionPart ) )
optionPart = 'lower-alpha';
else if ( /^[A-Z]+$/.test( optionPart ) )
optionPart = 'upper-alpha';
}
if ( stylesMap[ part ] )
{
// Font size represents percentage.
if ( part == 'size' )
optionPart += '%';
styles[ stylesMap[ part ] ] = optionPart;
attribs.style = serializeStyleText( styles );
}
else if ( attributesMap[ part ] )
attribs[ attributesMap[ part ] ] = optionPart;
}
// Two special handling - image and email, protect them
// as "span" with an attribute marker.
if ( part == 'email' || part == 'img' )
attribs[ 'bbcode' ] = part;
this.onTagOpen( tagName, attribs, CKEDITOR.dtd.$empty[ tagName ] );
}
// Closing tag
else if ( parts[ 3 ] )
this.onTagClose( bbcodeMap[ part ] );
}
if ( bbcode.length > lastIndex )
this.onText( bbcode.substring( lastIndex, bbcode.length ), 1 );
}
};
/**
* Creates a {@link CKEDITOR.htmlParser.fragment} from an HTML string.
* @param {String} source The HTML to be parsed, filling the fragment.
* @param {Number} [fixForBody=false] Wrap body with specified element if needed.
* @returns CKEDITOR.htmlParser.fragment The fragment created.
* @example
* var fragment = CKEDITOR.htmlParser.fragment.fromHtml( '<b>Sample</b> Text' );
* alert( fragment.children[0].name ); "b"
* alert( fragment.children[1].value ); " Text"
*/
CKEDITOR.htmlParser.fragment.fromBBCode = function( source )
{
var parser = new CKEDITOR.BBCodeParser(),
fragment = new CKEDITOR.htmlParser.fragment(),
pendingInline = [],
pendingBrs = 0,
currentNode = fragment,
returnPoint;
function checkPending( newTagName )
{
if ( pendingInline.length > 0 )
{
for ( var i = 0 ; i < pendingInline.length ; i++ )
{
var pendingElement = pendingInline[ i ],
pendingName = pendingElement.name,
pendingDtd = CKEDITOR.dtd[ pendingName ],
currentDtd = currentNode.name && CKEDITOR.dtd[ currentNode.name ];
if ( ( !currentDtd || currentDtd[ pendingName ] ) && ( !newTagName || !pendingDtd || pendingDtd[ newTagName ] || !CKEDITOR.dtd[ newTagName ] ) )
{
// Get a clone for the pending element.
pendingElement = pendingElement.clone();
// Add it to the current node and make it the current,
// so the new element will be added inside of it.
pendingElement.parent = currentNode;
currentNode = pendingElement;
// Remove the pending element (back the index by one
// to properly process the next entry).
pendingInline.splice( i, 1 );
i--;
}
}
}
}
function checkPendingBrs( tagName, closing )
{
var len = currentNode.children.length,
previous = len > 0 && currentNode.children[ len - 1 ],
lineBreakParent = !previous && BBCodeWriter.getRule( tagnameMap[ currentNode.name ], 'breakAfterOpen' ),
lineBreakPrevious = previous && previous.type == CKEDITOR.NODE_ELEMENT && BBCodeWriter.getRule( tagnameMap[ previous.name ], 'breakAfterClose' ),
lineBreakCurrent = tagName && BBCodeWriter.getRule( tagnameMap[ tagName ], closing ? 'breakBeforeClose' : 'breakBeforeOpen' );
if ( pendingBrs && ( lineBreakParent || lineBreakPrevious || lineBreakCurrent ) )
pendingBrs--;
// 1. Either we're at the end of block, where it requires us to compensate the br filler
// removing logic (from htmldataprocessor).
// 2. Or we're at the end of pseudo block, where it requires us to compensate
// the bogus br effect.
if ( pendingBrs && tagName in blockLikeTags )
pendingBrs++;
while ( pendingBrs && pendingBrs-- )
currentNode.children.push( previous = new CKEDITOR.htmlParser.element( 'br' ) );
}
function addElement( node, target )
{
checkPendingBrs( node.name, 1 );
target = target || currentNode || fragment;
var len = target.children.length,
previous = len > 0 && target.children[ len - 1 ] || null;
node.previous = previous;
node.parent = target;
target.children.push( node );
if ( node.returnPoint )
{
currentNode = node.returnPoint;
delete node.returnPoint;
}
}
parser.onTagOpen = function( tagName, attributes, selfClosing )
{
var element = new CKEDITOR.htmlParser.element( tagName, attributes );
// This is a tag to be removed if empty, so do not add it immediately.
if ( CKEDITOR.dtd.$removeEmpty[ tagName ] )
{
pendingInline.push( element );
return;
}
var currentName = currentNode.name;
var currentDtd = currentName
&& ( CKEDITOR.dtd[ currentName ]
|| ( currentNode._.isBlockLike ? CKEDITOR.dtd.div : CKEDITOR.dtd.span ) );
// If the element cannot be child of the current element.
if ( currentDtd && !currentDtd[ tagName ] )
{
var reApply = false,
addPoint; // New position to start adding nodes.
// If the element name is the same as the current element name,
// then just close the current one and append the new one to the
// parent. This situation usually happens with <p>, <li>, <dt> and
// <dd>, specially in IE. Do not enter in this if block in this case.
if ( tagName == currentName )
addElement( currentNode, currentNode.parent );
else if ( tagName in CKEDITOR.dtd.$listItem )
{
parser.onTagOpen( 'ul', {} );
addPoint = currentNode;
reApply = true;
}
else
{
addElement( currentNode, currentNode.parent );
// The current element is an inline element, which
// cannot hold the new one. Put it in the pending list,
// and try adding the new one after it.
pendingInline.unshift( currentNode );
reApply = true;
}
if ( addPoint )
currentNode = addPoint;
// Try adding it to the return point, or the parent element.
else
currentNode = currentNode.returnPoint || currentNode.parent;
if ( reApply )
{
parser.onTagOpen.apply( this, arguments );
return;
}
}
checkPending( tagName );
checkPendingBrs( tagName );
element.parent = currentNode;
element.returnPoint = returnPoint;
returnPoint = 0;
if ( element.isEmpty )
addElement( element );
else
currentNode = element;
};
parser.onTagClose = function( tagName )
{
// Check if there is any pending tag to be closed.
for ( var i = pendingInline.length - 1 ; i >= 0 ; i-- )
{
// If found, just remove it from the list.
if ( tagName == pendingInline[ i ].name )
{
pendingInline.splice( i, 1 );
return;
}
}
var pendingAdd = [],
newPendingInline = [],
candidate = currentNode;
while ( candidate.type && candidate.name != tagName )
{
// If this is an inline element, add it to the pending list, if we're
// really closing one of the parents element later, they will continue
// after it.
if ( !candidate._.isBlockLike )
newPendingInline.unshift( candidate );
// This node should be added to it's parent at this point. But,
// it should happen only if the closing tag is really closing
// one of the nodes. So, for now, we just cache it.
pendingAdd.push( candidate );
candidate = candidate.parent;
}
if ( candidate.type )
{
// Add all elements that have been found in the above loop.
for ( i = 0 ; i < pendingAdd.length ; i++ )
{
var node = pendingAdd[ i ];
addElement( node, node.parent );
}
currentNode = candidate;
addElement( candidate, candidate.parent );
// The parent should start receiving new nodes now, except if
// addElement changed the currentNode.
if ( candidate == currentNode )
currentNode = currentNode.parent;
pendingInline = pendingInline.concat( newPendingInline );
}
};
parser.onText = function( text )
{
var currentDtd = CKEDITOR.dtd[ currentNode.name ];
if ( !currentDtd || currentDtd[ '#' ] )
{
checkPendingBrs();
checkPending();
text.replace(/([\r\n])|[^\r\n]*/g, function( piece, lineBreak )
{
if ( lineBreak !== undefined && lineBreak.length )
pendingBrs++;
else if ( piece.length )
{
var lastIndex = 0;
// Create smiley from text emotion.
piece.replace( smileyRegExp, function( match, index )
{
addElement( new CKEDITOR.htmlParser.text( piece.substring( lastIndex, index ) ), currentNode );
addElement( new CKEDITOR.htmlParser.element( 'smiley', { 'desc': smileyReverseMap[ match ] } ), currentNode );
lastIndex = index + match.length;
});
if ( lastIndex != piece.length )
addElement( new CKEDITOR.htmlParser.text( piece.substring( lastIndex, piece.length ) ), currentNode );
}
});
}
};
// Parse it.
parser.parse( CKEDITOR.tools.htmlEncode( source ) );
// Close all hanging nodes.
while ( currentNode.type )
{
var parent = currentNode.parent,
node = currentNode;
addElement( node, parent );
currentNode = parent;
}
return fragment;
};
CKEDITOR.htmlParser.BBCodeWriter = CKEDITOR.tools.createClass(
{
$ : function()
{
this._ =
{
output : [],
rules : []
};
// List and list item.
this.setRules( 'list',
{
breakBeforeOpen : 1,
breakAfterOpen : 1,
breakBeforeClose : 1,
breakAfterClose : 1
} );
this.setRules( '*',
{
breakBeforeOpen : 1,
breakAfterOpen : 0,
breakBeforeClose : 1,
breakAfterClose : 0
} );
this.setRules( 'quote',
{
breakBeforeOpen : 1,
breakAfterOpen : 0,
breakBeforeClose : 0,
breakAfterClose : 1
} );
},
proto :
{
/**
* Sets formatting rules for a given tag. The possible rules are:
* <ul>
* <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.
*
* @param {String} tagName The tag 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( 'list',
* {
* breakBeforeOpen : true
* breakAfterOpen : true
* });
*/
setRules : function( tagName, rules )
{
var currentRules = this._.rules[ tagName ];
if ( currentRules )
CKEDITOR.tools.extend( currentRules, rules, true );
else
this._.rules[ tagName ] = rules;
},
getRule : function( tagName, ruleName )
{
return this._.rules[ tagName ] && this._.rules[ tagName ][ ruleName ];
},
openTag : function( tag, attributes )
{
if ( tag in bbcodeMap )
{
if ( this.getRule( tag, 'breakBeforeOpen' ) )
this.lineBreak( 1 );
this.write( '[', tag );
var option = attributes.option;
option && this.write( '=', option );
this.write( ']' );
if ( this.getRule( tag, 'breakAfterOpen' ) )
this.lineBreak( 1 );
}
else if ( tag == 'br' )
this._.output.push( '\n' );
},
openTagClose : function() { },
attribute : function() { },
closeTag : function( tag )
{
if ( tag in bbcodeMap )
{
if ( this.getRule( tag, 'breakBeforeClose' ) )
this.lineBreak( 1 );
tag != '*' && this.write( '[/', tag, ']' );
if ( this.getRule( tag, 'breakAfterClose' ) )
this.lineBreak( 1 );
}
},
text : function( text )
{
this.write( text );
},
/**
* Writes a comment.
* @param {String} comment The comment text.
* @example
* // Writes "<!-- My comment -->".
* writer.comment( ' My comment ' );
*/
comment : function() {},
/*
* Output line-break for formatting.
*/
lineBreak : function()
{
// Avoid line break when:
// 1) Previous tag already put one.
// 2) We're at output start.
if ( !this._.hasLineBreak && this._.output.length )
{
this.write( '\n' );
this._.hasLineBreak = 1;
}
},
write : function()
{
this._.hasLineBreak = 0;
var data = Array.prototype.join.call( arguments, '' );
this._.output.push( data );
},
reset : function()
{
this._.output = [];
this._.hasLineBreak = 0;
},
getHtml : function( reset )
{
var bbcode = this._.output.join( '' );
if ( reset )
this.reset();
return decodeHtml ( bbcode );
}
}
});
var BBCodeWriter = new CKEDITOR.htmlParser.BBCodeWriter();
CKEDITOR.plugins.add( 'bbcode',
{
requires : [ 'htmldataprocessor', 'entities' ],
beforeInit : function( editor )
{
// Adapt some critical editor configuration for better support
// of BBCode environment.
var config = editor.config;
CKEDITOR.tools.extend( config,
{
enterMode : CKEDITOR.ENTER_BR,
basicEntities: false,
entities : false,
fillEmptyBlocks : false
}, true );
},
init : function( editor )
{
var config = editor.config;
function BBCodeToHtml( code )
{
var fragment = CKEDITOR.htmlParser.fragment.fromBBCode( code ),
writer = new CKEDITOR.htmlParser.basicWriter();
fragment.writeHtml( writer, dataFilter );
return writer.getHtml( true );
}
var dataFilter = new CKEDITOR.htmlParser.filter();
dataFilter.addRules(
{
elements :
{
'blockquote' : function( element )
{
var quoted = new CKEDITOR.htmlParser.element( 'div' );
quoted.children = element.children;
element.children = [ quoted ];
var citeText = element.attributes.cite;
if ( citeText )
{
var cite = new CKEDITOR.htmlParser.element( 'cite' );
cite.add( new CKEDITOR.htmlParser.text( citeText.replace( /^"|"$/g, '' ) ) );
delete element.attributes.cite;
element.children.unshift( cite );
}
},
'span' : function( element )
{
var bbcode;
if ( ( bbcode = element.attributes.bbcode ) )
{
if ( bbcode == 'img' )
{
element.name = 'img';
element.attributes.src = element.children[ 0 ].value;
element.children = [];
}
else if ( bbcode == 'email' )
{
element.name = 'a';
element.attributes.href = 'mailto:' + element.children[ 0 ].value;
}
delete element.attributes.bbcode;
}
},
'ol' : function ( element )
{
if ( element.attributes.listType )
{
if ( element.attributes.listType != 'decimal' )
element.attributes.style = 'list-style-type:' + element.attributes.listType;
}
else
element.name = 'ul';
delete element.attributes.listType;
},
a : function( element )
{
if ( !element.attributes.href )
element.attributes.href = element.children[ 0 ].value;
},
'smiley' : function( element )
{
element.name = 'img';
var description = element.attributes.desc,
image = config.smiley_images[ CKEDITOR.tools.indexOf( config.smiley_descriptions, description ) ],
src = CKEDITOR.tools.htmlEncode( config.smiley_path + image );
element.attributes =
{
src : src,
'data-cke-saved-src' : src,
title : description,
alt : description
};
}
}
} );
editor.dataProcessor.htmlFilter.addRules(
{
elements :
{
$ : function( element )
{
var attributes = element.attributes,
style = parseStyleText( attributes.style ),
value;
var tagName = element.name;
if ( tagName in convertMap )
tagName = convertMap[ tagName ];
else if ( tagName == 'span' )
{
if ( ( value = style.color ) )
{
tagName = 'color';
value = RGBToHex( value );
}
else if ( ( value = style[ 'font-size' ] ) )
{
var percentValue = value.match( /(\d+)%$/ );
if ( percentValue )
{
value = percentValue[ 1 ];
tagName = 'size';
}
}
}
else if ( tagName == 'ol' || tagName == 'ul' )
{
if ( ( value = style[ 'list-style-type'] ) )
{
switch ( value )
{
case 'lower-alpha':
value = 'a';
break;
case 'upper-alpha':
value = 'A';
break;
}
}
else if ( tagName == 'ol' )
value = 1;
tagName = 'list';
}
else if ( tagName == 'blockquote' )
{
try
{
var cite = element.children[ 0 ],
quoted = element.children[ 1 ],
citeText = cite.name == 'cite' && cite.children[ 0 ].value;
if ( citeText )
{
value = '"' + citeText + '"';
element.children = quoted.children;
}
}
catch( er )
{
}
tagName = 'quote';
}
else if ( tagName == 'a' )
{
if ( ( value = attributes.href ) )
{
if ( value.indexOf( 'mailto:' ) !== -1 )
{
tagName = 'email';
// [email] should have a single text child with email address.
element.children = [ new CKEDITOR.htmlParser.text( value.replace( 'mailto:', '' ) ) ];
value = '';
}
else
{
var singleton = element.children.length == 1 && element.children[ 0 ];
if ( singleton
&& singleton.type == CKEDITOR.NODE_TEXT
&& singleton.value == value )
value = '';
tagName = 'url';
}
}
}
else if ( tagName == 'img' )
{
element.isEmpty = 0;
// Translate smiley (image) to text emotion.
var src = attributes[ 'data-cke-saved-src' ];
if ( src && src.indexOf( editor.config.smiley_path ) != -1 )
return new CKEDITOR.htmlParser.text( smileyMap[ attributes.alt ] );
else
element.children = [ new CKEDITOR.htmlParser.text( src ) ];
}
element.name = tagName;
value && ( element.attributes.option = value );
return null;
},
// Remove any bogus br from the end of a pseudo block,
// e.g. <div>some text<br /><p>paragraph</p></div>
br : function( element )
{
var next = element.next;
if ( next && next.name in blockLikeTags )
return false;
}
}
}, 1 );
editor.dataProcessor.writer = BBCodeWriter;
editor.on( 'beforeSetMode', function( evt )
{
evt.removeListener();
var wysiwyg = editor._.modes[ 'wysiwyg' ];
wysiwyg.loadData = CKEDITOR.tools.override( wysiwyg.loadData, function( org )
{
return function( data )
{
return ( org.call( this, BBCodeToHtml( data ) ) );
};
} );
} );
},
afterInit : function( editor )
{
var filters;
if ( editor._.elementsPath )
{
// Eliminate irrelevant elements from displaying, e.g body and p.
if ( ( filters = editor._.elementsPath.filters ) )
filters.push( function( element )
{
var htmlName = element.getName(),
name = tagnameMap[ htmlName ] || false;
// Specialized anchor presents as email.
if ( name == 'link' && element.getAttribute( 'href' ).indexOf( 'mailto:' ) === 0 )
name = 'email';
// Styled span could be either size or color.
else if ( htmlName == 'span' )
{
if ( element.getStyle( 'font-size' ) )
name = 'size';
else if ( element.getStyle( 'color' ) )
name = 'color';
}
else if ( name == 'img' )
{
var src = element.data( 'cke-saved-src' );
if ( src && src.indexOf( editor.config.smiley_path ) === 0 )
name = 'smiley';
}
return name;
});
}
}
} );
})();
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/bbcode/plugin.js | JavaScript | asf20 | 26,446 |
/*
Copyright (c) 2003-2012, 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 = 'button';
/**
* 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 );
}
};
( function()
{
CKEDITOR.ui.button.prototype =
{
/**
* 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;
this._.editor = editor;
var instance =
{
id : id,
button : this,
editor : editor,
focus : function()
{
var element = CKEDITOR.document.getById( id );
element.focus();
},
execute : function()
{
// IE 6 needs some time before execution (#7922)
if ( CKEDITOR.env.ie && CKEDITOR.env.version < 7 )
CKEDITOR.tools.setTimeout( function(){ this.button.click( editor ); }, 0, this );
else
this.button.click( editor );
}
};
var keydownFn = CKEDITOR.tools.addFunction( function( ev )
{
if ( instance.onkey )
{
ev = new CKEDITOR.dom.event( ev );
return ( instance.onkey( instance, ev.getKeystroke() ) !== false );
}
});
var focusFn = CKEDITOR.tools.addFunction( function( ev )
{
var 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;
});
instance.clickFn = clickFn = CKEDITOR.tools.addFunction( instance.execute, instance );
// Indicate a mode sensitive button.
if ( this.modes )
{
var modeStates = {};
function updateState()
{
// "this" is a CKEDITOR.ui.button instance.
var mode = editor.mode;
if ( mode )
{
// Restore saved button state.
var state = this.modes[ mode ] ? modeStates[ mode ] != undefined ? modeStates[ mode ] :
CKEDITOR.TRISTATE_OFF : CKEDITOR.TRISTATE_DISABLED;
this.setState( editor.readOnly && !this.readOnly ? CKEDITOR.TRISTATE_DISABLED : state );
}
}
editor.on( 'beforeModeUnload', function()
{
if ( editor.mode && this._.state != CKEDITOR.TRISTATE_DISABLED )
modeStates[ editor.mode ] = this._.state;
}, this );
editor.on( 'mode', updateState, this);
// If this button is sensitive to readOnly state, update it accordingly.
!this.readOnly && editor.on( 'readOnly', updateState, 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' + ( this.icon && this.icon.indexOf( '.png' ) == -1 ? ' cke_noalphafix' : '' ) + '">',
'<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, ', event);"' +
' onfocus="return CKEDITOR.tools.callFunction(', focusFn,', event);" ' +
( CKEDITOR.env.ie ? 'onclick="return false;" onmouseup' : 'onclick' ) + // #188
'="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} name The button name.
* @param {Object} definition 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 );
};
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/button/plugin.js | JavaScript | asf20 | 7,612 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.add( 'devtools',
{
lang : [ 'en', 'bg', 'cs', 'cy', 'da', 'de', 'el', 'eo', 'et', 'fa', 'fi', 'fr', 'gu', 'he', 'hr', 'it', 'nb', 'nl', 'no', 'pl', 'pt-br', 'tr', 'ug', 'uk', 'vi', 'zh-cn' ],
init : function( editor )
{
editor._.showDialogDefinitionTooltips = 1;
},
onLoad : function()
{
CKEDITOR.document.appendStyleText( CKEDITOR.config.devtools_styles ||
'#cke_tooltip { padding: 5px; border: 2px solid #333; background: #ffffff }' +
'#cke_tooltip h2 { font-size: 1.1em; border-bottom: 1px solid; margin: 0; padding: 1px; }' +
'#cke_tooltip ul { padding: 0pt; list-style-type: none; }' );
}
});
(function()
{
function defaultCallback( editor, dialog, element, tabName )
{
var lang = editor.lang.devTools,
link = '<a href="http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.dialog.definition.' +
( element ? ( element.type == 'text' ? 'textInput' : element.type ) : 'content' ) +
'.html" target="_blank">' + ( element ? element.type : 'content' ) + '</a>',
str =
'<h2>' + lang.title + '</h2>' +
'<ul>' +
'<li><strong>' + lang.dialogName + '</strong> : ' + dialog.getName() + '</li>' +
'<li><strong>' + lang.tabName + '</strong> : ' + tabName + '</li>';
if ( element )
str += '<li><strong>' + lang.elementId + '</strong> : ' + element.id + '</li>';
str += '<li><strong>' + lang.elementType + '</strong> : ' + link + '</li>';
return str + '</ul>';
}
function showTooltip( callback, el, editor, dialog, obj, tabName )
{
var pos = el.getDocumentPosition(),
styles = { 'z-index' : CKEDITOR.dialog._.currentZIndex + 10, top : ( pos.y + el.getSize( 'height' ) ) + 'px' };
tooltip.setHtml( callback( editor, dialog, obj, tabName ) );
tooltip.show();
// Translate coordinate for RTL.
if ( editor.lang.dir == 'rtl' )
{
var viewPaneSize = CKEDITOR.document.getWindow().getViewPaneSize();
styles.right = ( viewPaneSize.width - pos.x - el.getSize( 'width' ) ) + 'px';
}
else
styles.left = pos.x + 'px';
tooltip.setStyles( styles );
}
var tooltip;
CKEDITOR.on( 'reset', function()
{
tooltip && tooltip.remove();
tooltip = null;
});
CKEDITOR.on( 'dialogDefinition', function( evt )
{
var editor = evt.editor;
if ( editor._.showDialogDefinitionTooltips )
{
if ( !tooltip )
{
tooltip = CKEDITOR.dom.element.createFromHtml( '<div id="cke_tooltip" tabindex="-1" style="position: absolute"></div>', CKEDITOR.document );
tooltip.hide();
tooltip.on( 'mouseover', function(){ this.show(); } );
tooltip.on( 'mouseout', function(){ this.hide(); } );
tooltip.appendTo( CKEDITOR.document.getBody() );
}
var dialog = evt.data.definition.dialog,
callback = editor.config.devtools_textCallback || defaultCallback;
dialog.on( 'load', function()
{
var tabs = dialog.parts.tabs.getChildren(), tab;
for ( var i = 0, len = tabs.count(); i < len; i++ )
{
tab = tabs.getItem( i );
tab.on( 'mouseover', function()
{
var id = this.$.id;
showTooltip( callback, this, editor, dialog, null, id.substring( 4, id.lastIndexOf( '_' ) ) );
});
tab.on( 'mouseout', function()
{
tooltip.hide();
});
}
dialog.foreach( function( obj )
{
if ( obj.type in { hbox : 1, vbox : 1 } )
return;
var el = obj.getElement();
if ( el )
{
el.on( 'mouseover', function()
{
showTooltip( callback, this, editor, dialog, obj, dialog._.currentTabId );
});
el.on( 'mouseout', function()
{
tooltip.hide();
});
}
});
});
}
});
})();
/**
* A function that returns the text to be displayed inside the Developer Tools tooltip when hovering over a dialog UI element.
* There are 4 parameters that are being passed into the function: editor, dialog window, element, tab name.
* @name editor.config.devtools_textCallback
* @since 3.6
* @type Function
* @default (see example)
* @example
* // This is actually the default value.
* // Show dialog window name, tab ID, and element ID.
* config.devtools_textCallback = function( editor, dialog, element, tabName )
* {
* var lang = editor.lang.devTools,
* link = '<a href="http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.dialog.definition.' +
* ( element ? ( element.type == 'text' ? 'textInput' : element.type ) : 'content' ) +
* '.html" target="_blank">' + ( element ? element.type : 'content' ) + '</a>',
* str =
* '<h2>' + lang.title + '</h2>' +
* '<ul>' +
* '<li><strong>' + lang.dialogName + '</strong> : ' + dialog.getName() + '</li>' +
* '<li><strong>' + lang.tabName + '</strong> : ' + tabName + '</li>';
*
* if ( element )
* str += '<li><strong>' + lang.elementId + '</strong> : ' + element.id + '</li>';
*
* str += '<li><strong>' + lang.elementType + '</strong> : ' + link + '</li>';
*
* return str + '</ul>';
* }
*/
/**
* A setting that stores CSS rules to be injected into the page with styles to be applied to the tooltip element.
* @name CKEDITOR.config.devtools_styles
* @since 3.6
* @type String
* @default (see example)
* @example
* // This is actually the default value.
* CKEDITOR.config.devtools_styles = "
* #cke_tooltip { padding: 5px; border: 2px solid #333; background: #ffffff }
* #cke_tooltip h2 { font-size: 1.1em; border-bottom: 1px solid; margin: 0; padding: 1px; }
* #cke_tooltip ul { padding: 0pt; list-style-type: none; }
* ";
*/
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/devtools/plugin.js | JavaScript | asf20 | 5,825 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'devtools', 'nl',
{
devTools :
{
title : 'Elementinformatie',
dialogName : 'Naam dialoogvenster',
tabName : 'Tabnaam',
elementId : 'Element ID',
elementType : 'Elementtype'
}
});
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/devtools/lang/nl.js | JavaScript | asf20 | 385 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'devtools', 'ug',
{
devTools :
{
title : 'ئېلېمېنت ئۇچۇرى',
dialogName : 'سۆزلەشكۈ كۆزنەك ئاتى',
tabName : 'Tab ئاتى',
elementId : 'ئېلېمېنت كىملىكى',
elementType : 'ئېلېمېنت تىپى'
}
});
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/devtools/lang/ug.js | JavaScript | asf20 | 456 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'devtools', 'it',
{
devTools :
{
title : 'Informazioni elemento',
dialogName : 'Nome finestra di dialogo',
tabName : 'Nome Tab',
elementId : 'ID Elemento',
elementType : 'Tipo elemento'
}
});
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/devtools/lang/it.js | JavaScript | asf20 | 398 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'devtools', 'de',
{
devTools :
{
title : 'Elementinformation',
dialogName : 'Dialogfenstername',
tabName : 'Reitername',
elementId : 'Element ID',
elementType : 'Elementtyp'
}
});
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/devtools/lang/de.js | JavaScript | asf20 | 386 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'devtools', 'pl',
{
devTools :
{
title : 'Informacja o elemencie',
dialogName : 'Nazwa okna dialogowego',
tabName : 'Nazwa zakładki',
elementId : 'ID elementu',
elementType : 'Typ elementu'
}
});
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/devtools/lang/pl.js | JavaScript | asf20 | 403 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'devtools', 'vi',
{
devTools :
{
title : 'Thông tin thành ph',
dialogName : 'Tên hộp tho',
tabName : 'Tên th',
elementId : 'Mã thành ph',
elementType : 'Loại thành ph'
}
});
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/devtools/lang/vi.js | JavaScript | asf20 | 391 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'devtools', 'hr',
{
devTools :
{
title : 'Informacije elementa',
dialogName : 'Naziv prozora za dijalog',
tabName : 'Naziva jahača',
elementId : 'ID elementa',
elementType : 'Vrsta elementa'
}
});
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/devtools/lang/hr.js | JavaScript | asf20 | 404 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'devtools', 'tr',
{
devTools :
{
title : 'Eleman Bilgisi',
dialogName : 'İletişim pencere ismi',
tabName : 'Sekme adı',
elementId : 'Eleman ID',
elementType : 'Eleman türü'
}
});
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/devtools/lang/tr.js | JavaScript | asf20 | 390 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'devtools', 'fr',
{
devTools :
{
title : 'Information sur l\'élément',
dialogName : 'Nom de la fenêtre de dialogue',
tabName : 'Nom de l\'onglet',
elementId : 'ID de l\'élément',
elementType : 'Type de l\'élément'
}
});
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/devtools/lang/fr.js | JavaScript | asf20 | 433 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'devtools', 'zh-cn',
{
devTools :
{
title : '元素信息',
dialogName : '对话框窗口名称',
tabName : 'Tab 名称',
elementId : '元素 ID',
elementType : '元素类型'
}
});
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/devtools/lang/zh-cn.js | JavaScript | asf20 | 388 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'devtools', 'eo',
{
devTools :
{
title : 'Informo pri la elemento',
dialogName : 'Nomo de la dialogfenestro',
tabName : 'Langetnomo',
elementId : 'ID de la elemento',
elementType : 'Tipo de la elemento'
}
});
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/devtools/lang/eo.js | JavaScript | asf20 | 415 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'devtools', 'en',
{
devTools :
{
title : 'Element Information',
dialogName : 'Dialog window name',
tabName : 'Tab name',
elementId : 'Element ID',
elementType : 'Element type'
}
});
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/devtools/lang/en.js | JavaScript | asf20 | 388 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'devtools', 'da',
{
devTools :
{
title : 'Information på elementet',
dialogName : 'Dialogboks',
tabName : 'Tab beskrivelse',
elementId : 'ID på element',
elementType : 'Type af element'
}
});
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/devtools/lang/da.js | JavaScript | asf20 | 400 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'devtools', 'nb',
{
devTools :
{
title : 'Elementinformasjon',
dialogName : 'Navn på dialogvindu',
tabName : 'Navn på fane',
elementId : 'Element-ID',
elementType : 'Elementtype'
}
});
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/devtools/lang/nb.js | JavaScript | asf20 | 393 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'devtools', 'bg',
{
devTools :
{
title : 'Информация за елемента',
dialogName : 'Име на диалоговия прозорец',
tabName : 'Име на таб',
elementId : 'ID на елемента',
elementType : 'Тип на елемента'
}
});
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/devtools/lang/bg.js | JavaScript | asf20 | 482 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'devtools', 'el',
{
devTools :
{
title : 'Πληροφορίες Στοιχείου',
dialogName : 'Όνομα παραθύρου διαλόγου',
tabName : 'Όνομα καρτέλας',
elementId : 'ID Στοιχείου',
elementType : 'Τύπος στοιχείου'
}
});
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/devtools/lang/el.js | JavaScript | asf20 | 485 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'devtools', 'fi',
{
devTools :
{
title : 'Elementin tiedot',
dialogName : 'Dialogi-ikkunan nimi',
tabName : 'Välilehden nimi',
elementId : 'Elementin ID',
elementType : 'Elementin tyyppi'
}
});
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/devtools/lang/fi.js | JavaScript | asf20 | 401 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'devtools', 'cy',
{
devTools :
{
title : 'Gwybodaeth am yr Elfen',
dialogName : 'Enw ffenestr y deialog',
tabName : 'Enw\'r tab',
elementId : 'ID yr Elfen',
elementType : 'Math yr elfen'
}
});
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/devtools/lang/cy.js | JavaScript | asf20 | 399 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'devtools', 'no',
{
devTools :
{
title : 'Elementinformasjon',
dialogName : 'Navn på dialogvindu',
tabName : 'Navn på fane',
elementId : 'Element-ID',
elementType : 'Elementtype'
}
});
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/devtools/lang/no.js | JavaScript | asf20 | 393 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'devtools', 'fa',
{
devTools :
{
title : 'اطلاعات عنصر',
dialogName : 'نام پنجره محاورهای',
tabName : 'نام برگه',
elementId : 'ID عنصر',
elementType : 'نوع عنصر'
}
});
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/devtools/lang/fa.js | JavaScript | asf20 | 419 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'devtools', 'et',
{
devTools :
{
title : 'Elemendi andmed',
dialogName : 'Dialoogiakna nimi',
tabName : 'Saki nimi',
elementId : 'Elemendi ID',
elementType : 'Elemendi liik'
}
});
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/devtools/lang/et.js | JavaScript | asf20 | 386 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'devtools', 'he',
{
devTools :
{
title : 'מידע על האלמנט',
dialogName : 'שם הדיאלוג',
tabName : 'שם הטאב',
elementId : 'ID של האלמנט',
elementType : 'סוג האלמנט'
}
});
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/devtools/lang/he.js | JavaScript | asf20 | 418 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'devtools', 'uk',
{
devTools :
{
title : 'Відомості про Елемент',
dialogName : 'Заголовок діалогового вікна',
tabName : 'Назва вкладки',
elementId : 'Ідентифікатор Елемента',
elementType : 'Тип Елемента'
}
});
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/devtools/lang/uk.js | JavaScript | asf20 | 504 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'devtools', 'cs',
{
devTools :
{
title : 'Informace o prvku',
dialogName : 'Název dialogového okna',
tabName : 'Název karty',
elementId : 'ID prvku',
elementType : 'Typ prvku'
}
});
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/devtools/lang/cs.js | JavaScript | asf20 | 391 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'devtools', 'pt-br',
{
devTools :
{
title : 'Informação do Elemento',
dialogName : 'Nome da janela de diálogo',
tabName : 'Nome da aba',
elementId : 'ID do elemento',
elementType : 'Tipo do elemento'
}
});
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/devtools/lang/pt-br.js | JavaScript | asf20 | 415 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'devtools', 'gu',
{
devTools :
{
title : 'પ્રાથમિક માહિતી',
dialogName : 'વિન્ડોનું નામ',
tabName : 'ટેબનું નામ',
elementId : 'પ્રાથમિક આઈડી',
elementType : 'પ્રાથમિક પ્રકાર'
}
});
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/devtools/lang/gu.js | JavaScript | asf20 | 509 |
/*
Copyright (c) 2003-2012, 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 },
readOnly : 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
});
}
});
})();
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/save/plugin.js | JavaScript | asf20 | 1,100 |
/*
Copyright (c) 2003-2012, 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()
{
/**
* An iframe base dialog.
* @param {String} name Name of the dialog
* @param {String} title Title of the dialog
* @param {Number} minWidth Minimum width of the dialog
* @param {Number} minHeight Minimum height of the dialog
* @param {Function} [onContentLoad] Function called when the iframe has been loaded.
* If it isn't specified, the inner frame is notified of the dialog events ('load',
* 'resize', 'ok' and 'cancel') on a function called 'onDialogEvent'
* @param {Object} [userDefinition] Additional properties for the dialog definition
* @example
*/
CKEDITOR.dialog.addIframe = function( name, title, src, minWidth, minHeight, onContentLoad, userDefinition )
{
var element =
{
type : 'iframe',
src : src,
width : '100%',
height : '100%'
};
if ( typeof( onContentLoad ) == 'function' )
element.onContentLoad = onContentLoad;
else
element.onContentLoad = function()
{
var element = this.getElement(),
childWindow = element.$.contentWindow;
// If the inner frame has defined a "onDialogEvent" function, setup listeners
if ( childWindow.onDialogEvent )
{
var dialog = this.getDialog(),
notifyEvent = function(e)
{
return childWindow.onDialogEvent(e);
};
dialog.on( 'ok', notifyEvent );
dialog.on( 'cancel', notifyEvent );
dialog.on( 'resize', notifyEvent );
// Clear listeners
dialog.on( 'hide', function(e)
{
dialog.removeListener( 'ok', notifyEvent );
dialog.removeListener( 'cancel', notifyEvent );
dialog.removeListener( 'resize', notifyEvent );
e.removeListener();
} );
// Notify child iframe of load:
childWindow.onDialogEvent( {
name : 'load',
sender : this,
editor : dialog._.editor
} );
}
};
var definition =
{
title : title,
minWidth : minWidth,
minHeight : minHeight,
contents :
[
{
id : 'iframe',
label : title,
expand : true,
elements : [ element ]
}
]
};
for ( var i in userDefinition )
definition[i] = userDefinition[i];
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.definition.uiElement} 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 );
}
} );
})();
}
} );
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/iframedialog/plugin.js | JavaScript | asf20 | 5,719 |
/*
Copyright (c) 2003-2012, 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 = 'panel';
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();
// Make it scrollable on iOS. (#8308)
CKEDITOR.env.iOS && parentDiv.setStyles(
{
'overflow' : 'scroll',
'-webkit-overflow-scrolling' : 'touch'
});
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>' +
CKEDITOR.tools.buildStyleHtml( this.css ) +
'</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>' +
'<\/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;
// ARIA role works better in IE on the body element, while on the iframe
// for FF. (#8864)
var holder = !this.forceIFrame || CKEDITOR.env.ie ?
this._.holder : this.document.getById( this.id + '_frame' );
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.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' :
case 'mouseup' :
index = this._.focusIndex;
link = index >= 0 && this.element.getElementsByTag( 'a' ).getItem( index );
if ( link )
link.$[ keyAction ] ? link.$[ keyAction ]() : link.$[ 'on' + keyAction ]();
return false;
}
return true;
}
}
});
/**
* Fired when a panel is added to the document
* @name CKEDITOR#ariaWidget
* @event
* @param {Object} holder The element wrapping the panel
*/
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/panel/plugin.js | JavaScript | asf20 | 9,711 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
(function()
{
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 editor.createFakeParserElement( element, 'cke_iframe', 'iframe', true );
}
}
});
}
}
});
})();
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/iframe/plugin.js | JavaScript | asf20 | 2,143 |
/*
Copyright (c) 2003-2012, 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 );
}
},
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.htmlLength( commonLang.invalidHtmlLength.replace( '%1', commonLang.width ) ),
setup : loadValue,
commit : commitValue
},
{
id : 'height',
type : 'text',
style : 'width:100%',
labelLayout : 'vertical',
label : commonLang.height,
validate : CKEDITOR.dialog.validate.htmlLength( commonLang.invalidHtmlLength.replace( '%1', commonLang.height ) ),
setup : loadValue,
commit : commitValue
},
{
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 })
]
};
});
})();
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/iframe/dialogs/iframe.js | JavaScript | asf20 | 6,454 |
/*
Copyright (c) 2003-2012, 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 );
})();
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/liststyle/plugin.js | JavaScript | asf20 | 1,822 |
/*
* Copyright (c) 2003-2012, 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 listItem = function( node ) { return node.type == CKEDITOR.NODE_ELEMENT && node.is( 'li' ); };
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',
align : 'center',
style : 'width:150px',
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 )
{
// List item start number dominates.
var value = element.getFirst( listItem ).getAttribute( 'value' ) || element.getAttribute( 'start' ) || 1;
value && this.setValue( value );
},
commit : function( element )
{
var firstItem = element.getFirst( listItem );
var oldStart = firstItem.getAttribute( 'value' ) || element.getAttribute( 'start' ) || 1;
// Force start number on list root.
element.getFirst( listItem ).removeAttribute( 'value' );
var val = parseInt( this.getValue(), 10 );
if ( isNaN( val ) )
element.removeAttribute( 'start' );
else
element.setAttribute( 'start', val );
// Update consequent list item numbering.
var nextItem = firstItem, conseq = oldStart, startNumber = isNaN( val ) ? 1 : val;
while ( ( nextItem = nextItem.getNext( listItem ) ) && conseq++ )
{
if ( nextItem.getAttribute( 'value' ) == conseq )
nextItem.setAttribute( 'value', startNumber + conseq - oldStart );
}
}
},
{
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' );
});
})();
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/liststyle/dialogs/liststyle.js | JavaScript | asf20 | 6,082 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
(function()
{
var cellNodeRegex = /^(?:td|th)$/;
function getSelectedCells( selection )
{
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.getAscendant( 'td' ) || node.getAscendant( 'th' );
if ( parent && !parent.getCustomData( 'selected_cell' ) )
{
CKEDITOR.dom.element.setMarker( database, parent, 'selected_cell', true );
retval.push( parent );
}
}
}
}
CKEDITOR.dom.element.clearAllMarkers( database );
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 insertRow( selection, insertBefore )
{
var cells = getSelectedCells( selection ),
firstCell = cells[ 0 ],
table = firstCell.getAscendant( 'table' ),
doc = firstCell.getDocument(),
startRow = cells[ 0 ].getParent(),
startRowIndex = startRow.$.rowIndex,
lastCell = cells[ cells.length - 1 ],
endRowIndex = lastCell.getParent().$.rowIndex + lastCell.$.rowSpan - 1,
endRow = new CKEDITOR.dom.element( table.$.rows[ endRowIndex ] ),
rowIndex = insertBefore ? startRowIndex : endRowIndex,
row = insertBefore ? startRow : endRow;
var map = CKEDITOR.tools.buildTableMap( table ),
cloneRow = map[ rowIndex ],
nextRow = insertBefore ? map[ rowIndex - 1 ] : map[ rowIndex + 1 ],
width = map[0].length;
var newRow = doc.createElement( 'tr' );
for ( var i = 0; cloneRow[ i ] && i < width; i++ )
{
var cell;
// Check whether there's a spanning row here, do not break it.
if ( cloneRow[ i ].rowSpan > 1 && nextRow && cloneRow[ i ] == nextRow[ i ] )
{
cell = cloneRow[ i ];
cell.rowSpan += 1;
}
else
{
cell = new CKEDITOR.dom.element( cloneRow[ i ] ).clone();
cell.removeAttribute( 'rowSpan' );
!CKEDITOR.env.ie && cell.appendBogus();
newRow.append( cell );
cell = cell.$;
}
i += cell.colSpan - 1;
}
insertBefore ?
newRow.insertBefore( row ) :
newRow.insertAfter( row );
}
function deleteRows( selectionOrRow )
{
if ( selectionOrRow instanceof CKEDITOR.dom.selection )
{
var cells = getSelectedCells( selectionOrRow ),
firstCell = cells[ 0 ],
table = firstCell.getAscendant( 'table' ),
map = CKEDITOR.tools.buildTableMap( table ),
startRow = cells[ 0 ].getParent(),
startRowIndex = startRow.$.rowIndex,
lastCell = cells[ cells.length - 1 ],
endRowIndex = lastCell.getParent().$.rowIndex + lastCell.$.rowSpan - 1,
rowsToDelete = [];
// Delete cell or reduce cell spans by checking through the table map.
for ( var i = startRowIndex; i <= endRowIndex; i++ )
{
var mapRow = map[ i ],
row = new CKEDITOR.dom.element( table.$.rows[ i ] );
for ( var j = 0; j < mapRow.length; j++ )
{
var cell = new CKEDITOR.dom.element( mapRow[ j ] ),
cellRowIndex = cell.getParent().$.rowIndex;
if ( cell.$.rowSpan == 1 )
cell.remove();
// Row spanned cell.
else
{
// Span row of the cell, reduce spanning.
cell.$.rowSpan -= 1;
// Root row of the cell, root cell to next row.
if ( cellRowIndex == i )
{
var nextMapRow = map[ i + 1 ];
nextMapRow[ j - 1 ] ?
cell.insertAfter( new CKEDITOR.dom.element( nextMapRow[ j - 1 ] ) )
: new CKEDITOR.dom.element( table.$.rows[ i + 1 ] ).append( cell, 1 );
}
}
j += cell.$.colSpan - 1;
}
rowsToDelete.push( row );
}
var rows = table.$.rows;
// 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.
var cursorPosition = new CKEDITOR.dom.element( rows[ endRowIndex + 1 ] || ( startRowIndex > 0 ? rows[ startRowIndex - 1 ] : null ) || table.$.parentNode );
for ( i = rowsToDelete.length ; i >= 0 ; 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 null;
}
function getCellColIndex( cell, isStart )
{
var row = cell.getParent(),
rowCells = row.$.cells;
var colIndex = 0;
for ( var i = 0; i < rowCells.length; i++ )
{
var mapCell = rowCells[ i ];
colIndex += isStart ? 1 : mapCell.colSpan;
if ( mapCell == cell.$ )
break;
}
return colIndex -1;
}
function getColumnsIndices( cells, isStart )
{
var retval = isStart ? Infinity : 0;
for ( var i = 0; i < cells.length; i++ )
{
var colIndex = getCellColIndex( cells[ i ], isStart );
if ( isStart ? colIndex < retval : colIndex > retval )
retval = colIndex;
}
return retval;
}
function insertColumn( selection, insertBefore )
{
var cells = getSelectedCells( selection ),
firstCell = cells[ 0 ],
table = firstCell.getAscendant( 'table' ),
startCol = getColumnsIndices( cells, 1 ),
lastCol = getColumnsIndices( cells ),
colIndex = insertBefore? startCol : lastCol;
var map = CKEDITOR.tools.buildTableMap( table ),
cloneCol = [],
nextCol = [],
height = map.length;
for ( var i = 0; i < height; i++ )
{
cloneCol.push( map[ i ][ colIndex ] );
var nextCell = insertBefore ? map[ i ][ colIndex - 1 ] : map[ i ][ colIndex + 1 ];
nextCell && nextCol.push( nextCell );
}
for ( i = 0; i < height; i++ )
{
var cell;
// Check whether there's a spanning column here, do not break it.
if ( cloneCol[ i ].colSpan > 1
&& nextCol.length
&& nextCol[ i ] == cloneCol[ i ] )
{
cell = cloneCol[ i ];
cell.colSpan += 1;
}
else
{
cell = new CKEDITOR.dom.element( cloneCol[ i ] ).clone();
cell.removeAttribute( 'colSpan' );
!CKEDITOR.env.ie && cell.appendBogus();
cell[ insertBefore? 'insertBefore' : 'insertAfter' ].call( cell, new CKEDITOR.dom.element ( cloneCol[ i ] ) );
cell = cell.$;
}
i += cell.rowSpan - 1;
}
}
function deleteColumns( selectionOrCell )
{
var cells = getSelectedCells( selectionOrCell ),
firstCell = cells[ 0 ],
lastCell = cells[ cells.length - 1 ],
table = firstCell.getAscendant( 'table' ),
map = CKEDITOR.tools.buildTableMap( table ),
startColIndex,
endColIndex,
rowsToDelete = [];
// Figure out selected cells' column indices.
for ( var i = 0, rows = map.length; i < rows; i++ )
{
for ( var j = 0, cols = map[ i ].length; j < cols; j++ )
{
if ( map[ i ][ j ] == firstCell.$ )
startColIndex = j;
if ( map[ i ][ j ] == lastCell.$ )
endColIndex = j;
}
}
// Delete cell or reduce cell spans by checking through the table map.
for ( i = startColIndex; i <= endColIndex; i++ )
{
for ( j = 0; j < map.length; j++ )
{
var mapRow = map[ j ],
row = new CKEDITOR.dom.element( table.$.rows[ j ] ),
cell = new CKEDITOR.dom.element( mapRow[ i ] );
if ( cell.$ )
{
if ( cell.$.colSpan == 1 )
cell.remove();
// Reduce the col spans.
else
cell.$.colSpan -= 1;
j += cell.$.rowSpan - 1;
if ( !row.$.cells.length )
rowsToDelete.push( row );
}
}
}
var firstRowCells = table.$.rows[ 0 ] && table.$.rows[ 0 ].cells;
// Where to put the cursor after columns been deleted?
// 1. Into next cell of the first row if any;
// 2. Into previous cell of the first row if any;
// 3. Into table's parent element;
var cursorPosition = new CKEDITOR.dom.element( firstRowCells[ startColIndex ] || ( startColIndex ? firstRowCells[ startColIndex - 1 ] : table.$.parentNode ) );
// Delete table rows only if all columns are gone (do not remove empty row).
if ( rowsToDelete.length == rows )
table.remove();
return cursorPosition;
}
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 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 )
{
var oCol = [];
for ( var r = 0; r < tableMap.length; r++ )
{
var row = tableMap[ r ];
oCol.push( row[ colIndex ] );
// Avoid adding duplicate cells.
if ( row[ colIndex ].rowSpan > 1 )
r += row[ colIndex ].rowSpan - 1;
}
return oCol;
}
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
{
var rowspan = parseInt( firstCell.getAttribute( 'rowspan' ), 10 ) || 1;
var colspan = parseInt( firstCell.getAttribute( 'colspan' ), 10 ) || 1;
targetCell =
map[ mergeDirection == 'up' ?
( startRow - rowspan ):
mergeDirection == 'down' ? ( startRow + rowspan ) : startRow ] [
mergeDirection == 'left' ?
( startColumn - colspan ):
mergeDirection == 'right' ? ( startColumn + colspan ) : 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( '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 =
{
requires : [ 'table', 'dialog', 'contextmenu' ],
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;
// 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' ) )
table = parent;
var range = new CKEDITOR.dom.range( editor.document );
range.moveToPosition( table, CKEDITOR.POSITION_BEFORE_START );
table.remove();
range.select();
}
} );
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 ;
};
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/tabletools/plugin.js | JavaScript | asf20 | 32,228 |
/*
Copyright (c) 2003-2012, 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();
};
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.ie7Compat || CKEDITOR.env.quirks )? 230 : 220,
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 ] );
this._.editor.forceNextSelectionCheck();
selection.selectBookmarks( bookmarks );
this._.editor.selectionChange();
}
};
} );
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/tabletools/dialogs/tableCell.js | JavaScript | asf20 | 16,433 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @file Image plugin
*/
(function()
{
CKEDITOR.plugins.add( 'image',
{
requires: [ 'dialog' ],
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' ) && !element.isReadOnly() )
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 ( getSelectedImage( editor, element ) )
return { image : CKEDITOR.TRISTATE_OFF };
});
}
},
afterInit : function( editor )
{
// Customize the behavior of the alignment commands. (#7430)
setupAlignCommand( 'left' );
setupAlignCommand( 'right' );
setupAlignCommand( 'center' );
setupAlignCommand( 'block' );
function setupAlignCommand( value )
{
var command = editor.getCommand( 'justify' + value );
if ( command )
{
if ( value == 'left' || value == 'right' )
{
command.on( 'exec', function( evt )
{
var img = getSelectedImage( editor ), align;
if ( img )
{
align = getImageAlignment( img );
if ( align == value )
{
img.removeStyle( 'float' );
// Remove "align" attribute when necessary.
if ( value == getImageAlignment( img ) )
img.removeAttribute( 'align' );
}
else
img.setStyle( 'float', value );
evt.cancel();
}
});
}
command.on( 'refresh', function( evt )
{
var img = getSelectedImage( editor ), align;
if ( img )
{
align = getImageAlignment( img );
this.setState(
( align == value ) ? CKEDITOR.TRISTATE_ON :
( value == 'right' || value == 'left' ) ? CKEDITOR.TRISTATE_OFF :
CKEDITOR.TRISTATE_DISABLED );
evt.cancel();
}
});
}
}
}
});
function getSelectedImage( editor, element )
{
if ( !element )
{
var sel = editor.getSelection();
element = ( sel.getType() == CKEDITOR.SELECTION_ELEMENT ) && sel.getSelectedElement();
}
if ( element && element.is( 'img' ) && !element.data( 'cke-realelement' ) && !element.isReadOnly() )
return element;
}
function getImageAlignment( element )
{
var align = element.getStyle( 'float' );
if ( align == 'inherit' || align == 'none' )
align = 0;
if ( !align )
align = element.getAttribute( 'align' );
return align;
}
})();
/**
* 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 );
*/
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/image/plugin.js | JavaScript | asf20 | 3,926 |
/*
Copyright (c) 2003-2012, 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 )
{
if ( !dialog.getContentElement( 'info', 'ratioLock' ) )
return null;
var oImageOriginal = dialog.originalElement;
// Dialog may already closed. (#5505)
if( !oImageOriginal )
return null;
// Check image ratio and original image ratio, but respecting user's preference.
if ( value == 'check' )
{
if ( !dialog.userlockRatio && oImageOriginal.getCustomData( 'isReady' ) == 'true' )
{
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.userlockRatio = 1;
dialog.lockRatio = !dialog.lockRatio;
}
var ratioButton = CKEDITOR.document.getById( btnLockSizesId );
if ( dialog.lockRatio )
ratioButton.removeClass( 'cke_btn_unlocked' );
else
ratioButton.addClass( 'cke_btn_unlocked' );
ratioButton.setAttribute( 'aria-checked', dialog.lockRatio );
// Ratio button hc presentation - WHITE SQUARE / BLACK SQUARE
if ( CKEDITOR.env.hc )
{
var icon = ratioButton.getChild( 0 );
icon.setHtml( dialog.lockRatio ? CKEDITOR.env.ie ? '\u25A0': '\u25A3' : CKEDITOR.env.ie ? '\u25A1' : '\u25A2' );
}
return dialog.lockRatio;
};
var resetSize = function( dialog )
{
var oImageOriginal = dialog.originalElement;
if ( oImageOriginal.getCustomData( 'isReady' ) == 'true' )
{
var widthField = dialog.getContentElement( 'info', 'txtWidth' ),
heightField = dialog.getContentElement( 'info', 'txtHeight' );
widthField && widthField.setValue( oImageOriginal.$.width );
heightField && heightField.setValue( 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' ),
previewLinkId = numbering( 'previewLink' ),
previewImageId = numbering( 'previewImage' );
return {
title : editor.lang.image[ dialogType == 'image' ? 'title' : 'titleButton' ],
minWidth : 420,
minHeight : 360,
onShow : function()
{
this.imageElement = false;
this.linkElement = false;
// Default: create a new element.
this.imageEditMode = false;
this.linkEditMode = false;
this.lockRatio = true;
this.userlockRatio = 0;
this.dontResetSize = false;
this.firstLoad = true;
this.addLink = false;
var editor = this.getParentEditor(),
sel = editor.getSelection(),
element = sel && 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 );
}
else
this.imageElement = editor.document.createElement( 'img' );
// Refresh LockRatio button
switchLockRatio ( this, true );
// 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();
if ( this.getContentElement( 'info', 'ratioLock' ) )
{
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', this.getValue() );
element.setAttribute( 'src', 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 :
[
{
id : 'basic',
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 ),
isValid = !!( aMatch && parseInt( aMatch[1], 10 ) !== 0 );
if ( !isValid )
alert( editor.lang.common.invalidWidth );
return isValid;
},
setup : setupDimension,
commit : function( type, element, internalCommit )
{
var value = this.getValue();
if ( type == IMAGE )
{
if ( value )
element.setStyle( 'width', CKEDITOR.tools.cssLength( value ) );
else
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 ),
isValid = !!( aMatch && parseInt( aMatch[1], 10 ) !== 0 );
if ( !isValid )
alert( editor.lang.common.invalidHeight );
return isValid;
},
setup : setupDimension,
commit : function( type, element, internalCommit )
{
var value = this.getValue();
if ( type == IMAGE )
{
if ( value )
element.setStyle( 'height', CKEDITOR.tools.cssLength( value ) );
else
element.removeStyle( 'height' );
!internalCommit && 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' );
}
}
}
]
},
{
id : 'ratioLock',
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 && 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 && 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.lockRatio +
'" class="cke_btn_locked" id="' + btnLockSizesId + '" role="checkbox"><span class="cke_icon"></span><span class="cke_label">' + editor.lang.image.lockRatio + '</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',
id : 'htmlPreview',
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 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() )
{
var url = decodeURI( this.getValue() );
element.data( 'cke-saved-href', url );
element.setAttribute( 'href', url );
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,
validate : CKEDITOR.dialog.validate.inlineStyle( editor.lang.common.invalidInlineStyle ),
'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' );
});
})();
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/image/dialogs/image.js | JavaScript | asf20 | 47,145 |
/*
Copyright (c) 2003-2012, 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 ) );},
blockBogus = CKEDITOR.dom.walker.bogus();
function cleanUpDirection( element )
{
var dir, parent, parentDir;
if ( ( dir = element.getDirection() ) )
{
parent = element.getParent();
while ( parent && !( parentDir = parent.getDirection() ) )
parent = parent.getParent();
if ( dir == parentDir )
element.removeAttribute( 'dir' );
}
}
// Inheirt inline styles from another element.
function inheirtInlineStyles( parent, el )
{
var style = parent.getAttribute( 'style' );
// Put parent styles before child styles.
style && el.setAttribute( 'style',
style.replace( /([^;])$/, '$1;' ) +
( el.getAttribute( 'style' ) || '' ) );
}
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 );
// Fixing malformed nested lists by moving it into a previous list item. (#6236)
if( listItem.type == CKEDITOR.NODE_ELEMENT && listItem.getName() in CKEDITOR.dtd.$list )
CKEDITOR.plugins.list.listToArray( listItem, database, baseArray, baseIndentLevel + 1 );
// 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 i,
doc = listArray[ baseIndex ].parent.getDocument(),
retval = new CKEDITOR.dom.documentFragment( doc ),
rootNode = null,
currentIndex = baseIndex,
indentLevel = Math.max( listArray[ baseIndex ].indent, 0 ),
currentListItem = null,
orgDir,
block,
paragraphName = ( paragraphMode == CKEDITOR.ENTER_P ? 'p' : 'div' );
while ( 1 )
{
var item = listArray[ currentIndex ],
itemGrandParent = item.grandparent;
orgDir = item.element.getDirection( 1 );
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 ) );
if ( orgDir != rootNode.getDirection( 1 ) )
currentListItem.setAttribute( 'dir', orgDir );
for ( 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 )
{
// Maintain original direction (#6861).
var currDir = listArray[ currentIndex - 1 ].element.getDirection( 1 ),
listData = CKEDITOR.plugins.list.arrayToList( listArray, null, currentIndex, paragraphMode,
currDir != orgDir ? orgDir: null );
// If the next block is an <li> with another list tree as the first
// child, we'll need to append a filler (<br>/NBSP) or the list item
// wouldn't be editable. (#6724)
if ( !currentListItem.getChildCount() && CKEDITOR.env.ie && !( doc.$.documentMode > 7 ))
currentListItem.append( doc.createText( '\xa0' ) );
currentListItem.append( listData.listNode );
currentIndex = listData.nextIndex;
}
else if ( item.indent == -1 && !baseIndex && itemGrandParent )
{
if ( listNodeNames[ itemGrandParent.getName() ] )
{
currentListItem = item.element.clone( false, true );
if ( orgDir != itemGrandParent.getDirection( 1 ) )
currentListItem.setAttribute( 'dir', orgDir );
}
else
currentListItem = new CKEDITOR.dom.documentFragment( doc );
// Migrate all children to the new container,
// apply the proper text direction.
var dirLoose = itemGrandParent.getDirection( 1 ) != orgDir,
li = item.element,
className = li.getAttribute( 'class' ),
style = li.getAttribute( 'style' );
var needsBlock = currentListItem.type ==
CKEDITOR.NODE_DOCUMENT_FRAGMENT &&
( paragraphMode != CKEDITOR.ENTER_BR || dirLoose ||
style || className );
var child, count = item.contents.length;
for ( i = 0 ; i < count; i++ )
{
child = item.contents[ i ];
if ( child.type == CKEDITOR.NODE_ELEMENT && child.isBlockBoundary() )
{
// Apply direction on content blocks.
if ( dirLoose && !child.getDirection() )
child.setAttribute( 'dir', orgDir );
inheirtInlineStyles( li, child );
className && child.addClass( className );
}
else if ( needsBlock )
{
// Establish new block to hold text direction and styles.
if ( !block )
{
block = doc.createElement( paragraphName );
dirLoose && block.setAttribute( 'dir', orgDir );
}
// Copy over styles to new block;
style && block.setAttribute( 'style', style );
className && block.setAttribute( 'class', className );
block.append( child.clone( 1, 1 ) );
}
currentListItem.append( block || child.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' ) );
}
}
var currentListItemName = currentListItem.$.nodeName.toLowerCase();
if ( !CKEDITOR.env.ie && ( currentListItemName == 'div' || currentListItemName == 'p' ) )
currentListItem.appendBogus();
retval.append( currentListItem );
rootNode = null;
currentIndex++;
}
else
return null;
block = null;
if ( listArray.length <= currentIndex || Math.max( listArray[ currentIndex ].indent, 0 ) < indentLevel )
break;
}
if ( database )
{
var currentNode = retval.getFirst(),
listRoot = listArray[ 0 ].parent;
while ( currentNode )
{
if ( currentNode.type == CKEDITOR.NODE_ELEMENT )
{
// Clear marker attributes for the new list tree made of cloned nodes, if any.
CKEDITOR.dom.element.clearMarkers( database, currentNode );
// Clear redundant direction attribute specified on list items.
if ( currentNode.getName() in CKEDITOR.dtd.$listItem )
cleanUpDirection( currentNode );
}
currentNode = currentNode.getNextSourceNode();
}
}
return { listNode : retval, nextIndex : currentIndex };
}
};
function onSelectionChange( evt )
{
if ( evt.editor.readOnly )
return null;
var path = evt.data.path,
blockLimit = path.blockLimit,
elements = path.elements,
element,
i;
// Grouping should only happen under blockLimit.(#3940).
for ( i = 0 ; i < elements.length && ( element = elements[ i ] )
&& !element.equals( blockLimit ); i++ )
{
if ( listNodeNames[ elements[ i ].getName() ] )
return this.setState( this.type == elements[ i ].getName() ? CKEDITOR.TRISTATE_ON : CKEDITOR.TRISTATE_OFF );
}
return this.setState( 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,
doc = root.getDocument(),
listNode,
newListNode;
for ( i = 0 ; i < selectedListItems.length ; i++ )
{
var listIndex = selectedListItems[i].getCustomData( 'listarray_index' );
listNode = listArray[ listIndex ].parent;
// Switch to new list node for this particular item.
if ( !listNode.is( this.type ) )
{
newListNode = doc.createElement( this.type );
// Copy all attributes, except from 'start' and 'type'.
listNode.copyAttributes( newListNode, { start : 1, type : 1 } );
// The list-style-type property should be ignored.
newListNode.removeStyle( 'list-style-type' );
listArray[ listIndex ].parent = newListNode;
}
}
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
{
contentBlock.copyAttributes( listItem );
// Remove direction attribute after it was merged into list root. (#7657)
if ( listDir && contentBlock.getDirection() )
{
listItem.removeStyle( 'direction' );
listItem.removeAttribute( 'dir' );
}
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;
}
var elementType = CKEDITOR.dom.walker.nodeType( CKEDITOR.NODE_ELEMENT );
// Merge child nodes with direction preserved. (#7448)
function mergeChildren( from, into, refNode, forward )
{
var child, itemDir;
while ( ( child = from[ forward ? 'getLast' : 'getFirst' ]( elementType ) ) )
{
if ( ( itemDir = child.getDirection( 1 ) ) !== into.getDirection( 1 ) )
child.setAttribute( 'dir', itemDir );
child.remove();
refNode ?
child[ forward ? 'insertBefore' : 'insertAfter' ]( refNode ) :
into.append( child, forward );
}
}
listCommand.prototype = {
exec : function( editor )
{
var doc = editor.document,
config = editor.config,
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();
if ( !body.getFirst( nonEmpty ) )
{
config.enterMode == CKEDITOR.ENTER_BR ?
body.appendBogus() :
ranges[ 0 ].fixBlock( 1, config.enterMode == CKEDITOR.ENTER_P ? 'p' : 'div' );
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() )
this.setState( 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 into adjacent, same type lists.
for ( i = 0 ; i < listsCreated.length ; i++ )
mergeListSiblings( listsCreated[ i ] );
// Clean up, restore selection and update toolbar button states.
CKEDITOR.dom.element.clearAllMarkers( database );
selection.selectBookmarks( bookmarks );
editor.focus();
}
};
// Merge list adjacent, of same type lists.
function mergeListSiblings( listNode )
{
var mergeSibling;
( mergeSibling = function( rtl )
{
var sibling = listNode[ rtl ? 'getPrevious' : 'getNext' ]( nonEmpty );
if ( sibling && sibling.type == CKEDITOR.NODE_ELEMENT &&
sibling.is( listNode.getName() ) )
{
// Move children order by merge direction.(#3820)
mergeChildren( listNode, sibling, null, !rtl );
listNode.remove();
listNode = sibling;
}
} )();
mergeSibling( 1 );
}
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 );
// Check if node is block element that recieves text.
function isTextBlock( node )
{
return node.type == CKEDITOR.NODE_ELEMENT &&
( node.getName() in CKEDITOR.dtd.$block ||
node.getName() in CKEDITOR.dtd.$listItem ) &&
CKEDITOR.dtd[ node.getName() ][ '#' ];
}
// Merge the visual line content at the cursor range into the block.
function joinNextLineToCursor( editor, cursor, nextCursor )
{
editor.fire( 'saveSnapshot' );
// Merge with previous block's content.
nextCursor.enlarge( CKEDITOR.ENLARGE_LIST_ITEM_CONTENTS );
var frag = nextCursor.extractContents();
cursor.trim( false, true );
var bm = cursor.createBookmark();
// Kill original bogus;
var currentPath = new CKEDITOR.dom.elementPath( cursor.startContainer );
var currentLi = currentPath.lastElement.getAscendant( 'li', 1 );
var bogus = currentPath.block.getBogus();
bogus && bogus.remove();
// Kill the tail br in extracted.
var last = frag.getLast();
if ( last && last.type == CKEDITOR.NODE_ELEMENT && last.is( 'br' ) )
last.remove();
// Insert fragment at the range position.
var nextNode = cursor.startContainer.getChild( cursor.startOffset );
if ( nextNode )
frag.insertBefore( nextNode );
else
cursor.startContainer.append( frag );
var nextPath = new CKEDITOR.dom.elementPath( nextCursor.startContainer );
var nextLi = nextCursor.startContainer.getAscendant( 'li', 1 );
// Move the sub list nested in the next list item.
if ( nextLi )
{
var sublist = getSubList( nextLi );
if ( sublist )
{
// If next line is in the sub list of the current list item.
if ( currentLi.contains( nextLi ) )
{
mergeChildren( sublist, nextLi.getParent(), nextLi );
sublist.remove();
}
// Migrate the sub list to current list item.
else
currentLi.append( sublist );
}
}
// Remove any remaining empty path blocks at next line after merging.
while ( nextCursor.checkStartOfBlock() &&
nextCursor.checkEndOfBlock() )
{
nextPath = new CKEDITOR.dom.elementPath( nextCursor.startContainer );
var nextBlock = nextPath.block, parent;
// Check if also to remove empty list.
if ( nextBlock.is( 'li' ) )
{
parent = nextBlock.getParent();
if ( nextBlock.equals( parent.getLast( nonEmpty ) )
&& nextBlock.equals( parent.getFirst( nonEmpty ) ) )
nextBlock = parent;
}
nextCursor.moveToPosition( nextBlock, CKEDITOR.POSITION_BEFORE_START );
nextBlock.remove();
}
// Check if need to further merge with the list resides after the merged block. (#9080)
var walkerRng = nextCursor.clone(), body = editor.document.getBody();
walkerRng.setEndAt( body, CKEDITOR.POSITION_BEFORE_END );
var walker = new CKEDITOR.dom.walker( walkerRng );
walker.evaluator = function( node ) { return nonEmpty( node ) && !blockBogus( node ); };
var next = walker.next();
if ( next && next.type == CKEDITOR.NODE_ELEMENT && next.getName() in CKEDITOR.dtd.$list )
mergeListSiblings( next );
cursor.moveToBookmark( bm );
// Make fresh selection.
cursor.select();
editor.selectionChange( 1 );
editor.fire( 'saveSnapshot' );
}
function getSubList( li )
{
var last = li.getLast( nonEmpty );
return last && last.type == CKEDITOR.NODE_ELEMENT && last.getName() in listNodeNames ? last : null;
}
CKEDITOR.plugins.add( 'list',
{
init : function( editor )
{
// Register commands.
var numberedListCommand = editor.addCommand( 'numberedlist', new listCommand( 'numberedlist', 'ol' ) ),
bulletedListCommand = editor.addCommand( 'bulletedlist', new listCommand( 'bulletedlist', 'ul' ) );
// 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 ) );
// Handled backspace/del key to join list items. (#8248,#9080)
editor.on( 'key', function( evt )
{
var key = evt.data.keyCode;
// DEl/BACKSPACE
if ( editor.mode == 'wysiwyg' && key in { 8 : 1, 46 : 1 } )
{
var sel = editor.getSelection(),
range = sel.getRanges()[ 0 ];
if ( !range.collapsed )
return;
var isBackspace = key == 8;
var body = editor.document.getBody();
var walker = new CKEDITOR.dom.walker( range.clone() );
walker.evaluator = function( node ) { return nonEmpty( node ) && !blockBogus( node ); };
var cursor = range.clone();
if ( isBackspace )
{
var previous, joinWith;
var path = new CKEDITOR.dom.elementPath( range.startContainer );
// Join a sub list's first line, with the previous visual line in parent.
if ( ( previous = path.contains( listNodeNames ) ) &&
range.checkBoundaryOfElement( previous, CKEDITOR.START ) &&
( previous = previous.getParent() ) && previous.is( 'li' ) &&
( previous = getSubList( previous ) ) )
{
joinWith = previous;
previous = previous.getPrevious( nonEmpty );
// Place cursor before the nested list.
cursor.moveToPosition(
previous && blockBogus( previous ) ? previous : joinWith,
CKEDITOR.POSITION_BEFORE_START );
}
// Join any line following a list, with the last visual line of the list.
else
{
walker.range.setStartAt( body, CKEDITOR.POSITION_AFTER_START );
walker.range.setEnd( range.startContainer, range.startOffset );
previous = walker.previous();
if ( previous && previous.type == CKEDITOR.NODE_ELEMENT &&
( previous.getName() in listNodeNames || previous.is( 'li' ) ) )
{
if ( !previous.is( 'li' ) )
{
walker.range.selectNodeContents( previous );
walker.reset();
walker.evaluator = isTextBlock;
previous = walker.previous();
}
joinWith = previous;
// Place cursor at the end of previous block.
cursor.moveToElementEditEnd( joinWith );
}
}
if ( joinWith )
{
joinNextLineToCursor( editor, cursor, range );
evt.cancel();
}
}
else
{
var li = range.startContainer.getAscendant( 'li', 1 );
if ( li )
{
walker.range.setEndAt( body, CKEDITOR.POSITION_BEFORE_END );
var last = li.getLast( nonEmpty );
var block = last && isTextBlock( last ) ? last : li;
// Indicate cursor at the visual end of an list item.
var isAtEnd = 0;
var next = walker.next();
// When list item contains a sub list.
if ( next && next.type == CKEDITOR.NODE_ELEMENT &&
next.getName() in listNodeNames
&& next.equals( last ) )
{
isAtEnd = 1;
// Move to the first item in sub list.
next = walker.next();
}
// Right at the end of list item.
else if ( range.checkBoundaryOfElement( block, CKEDITOR.END ) )
isAtEnd = 1;
if ( isAtEnd && next )
{
// Put cursor range there.
var nextLine = range.clone();
nextLine.moveToElementEditStart( next );
joinNextLineToCursor( editor, cursor, nextLine );
evt.cancel();
}
}
}
// The backspace/del could potentially put cursor at a bad position,
// being it handled or not, check immediately the selection to have it fixed.
setTimeout( function() { editor.selectionChange( 1 ); } );
}
} );
},
afterInit : function ( editor )
{
var dataProcessor = editor.dataProcessor;
if ( dataProcessor )
{
dataProcessor.dataFilter.addRules( defaultListDataFilterRules );
dataProcessor.htmlFilter.addRules( defaultListHtmlFilterRules );
}
},
requires : [ 'domiterator' ]
} );
})();
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/list/plugin.js | JavaScript | asf20 | 35,080 |
/*
Copyright (c) 2003-2012, 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()
{
// 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;
editor.getMode().loadData( editor.getData() );
isHandlingData = false;
}
if ( editor.mode )
setData();
else
{
editor.on( 'mode', function()
{
if ( editor.mode )
{
setData();
editor.removeListener( 'mode', arguments.callee );
}
});
}
}
});
editor.on( 'beforeGetData', function()
{
if ( !isHandlingData && editor.mode )
{
isHandlingData = true;
editor.setData( editor.getMode().getData(), null, 1 );
isHandlingData = false;
}
});
editor.on( 'getSnapshot', function( event )
{
if ( editor.mode )
event.data = editor.getMode().getSnapshotData();
});
editor.on( 'loadSnapshot', function( event )
{
if ( editor.mode )
editor.getMode().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 );
});
editor.on( 'destroy', function ()
{
// -> currentMode.unload( holderElement );
if ( this.mode )
this._.modes[ this.mode ].unload( this.getThemeSpace( 'contents' ) );
});
}
});
/**
* 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 )
{
this.fire( 'beforeSetMode', { newMode : mode } );
var data,
holderElement = this.getThemeSpace( 'contents' ),
isDirty = this.checkDirty();
// Unload the previous mode.
if ( this.mode )
{
if ( mode == this.mode )
return;
this._.previousMode = this.mode;
this.fire( 'beforeModeUnload' );
var currentMode = this.getMode();
data = currentMode.getData();
currentMode.unload( holderElement );
this.mode = '';
}
holderElement.setHtml( '' );
// Load required mode.
var modeEditor = this.getMode( 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 );
};
/**
* Gets the current or any of the objects that represent the editing
* area modes. The two most common editing modes are "wysiwyg" and "source".
* @param {String} [mode] The mode to be retrieved. If not specified, the
* current one is returned.
*/
CKEDITOR.editor.prototype.getMode = function( mode )
{
return this._.modes && this._.modes[ mode || this.mode ];
};
/**
* Moves the selection focus to the editing are space in the editor.
*/
CKEDITOR.editor.prototype.focus = function()
{
this.forceNextSelectionCheck();
var mode = this.getMode();
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.
* @name CKEDITOR.config.startupFocus
* @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.
*/
/**
* Fired when the CKEDITOR instance is created, fully initialized and ready for interaction.
* @name CKEDITOR.editor#instanceReady
* @event
*/
/**
* Fired before changing the editing mode. See also CKEDITOR.editor#beforeSetMode and CKEDITOR.editor#mode
* @name CKEDITOR.editor#beforeModeUnload
* @event
*/
/**
* Fired before the editor mode is set. See also CKEDITOR.editor#mode and CKEDITOR.editor#beforeModeUnload
* @name CKEDITOR.editor#beforeSetMode
* @event
* @since 3.5.3
* @param {String} newMode The name of the mode which is about to be set.
*/
/**
* Fired after setting the editing mode. See also CKEDITOR.editor#beforeSetMode and CKEDITOR.editor#beforeModeUnload
* @name CKEDITOR.editor#mode
* @event
* @param {String} previousMode The previous mode of the editor.
*/
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/editingblock/plugin.js | JavaScript | asf20 | 7,289 |
/*
Copyright (c) 2003-2012, 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.
*/
/**
* The definition of a dialog window.
* <div class="notapi">
* This class is not really part of the API. It just illustrates the properties
* that developers can use to define and create dialogs.
* </div>
* @name CKEDITOR.dialog.definition
* @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.definition.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.definition.prototype.resizable
* @field
* @type Number
* @default CKEDITOR.DIALOG_RESIZE_NONE
* @example
*/
/**
* The minimum width of the dialog, in pixels.
* @name CKEDITOR.dialog.definition.prototype.minWidth
* @field
* @type Number
* @default 600
* @example
*/
/**
* The minimum height of the dialog, in pixels.
* @name CKEDITOR.dialog.definition.prototype.minHeight
* @field
* @type Number
* @default 400
* @example
*/
/**
* The initial width of the dialog, in pixels.
* @name CKEDITOR.dialog.definition.prototype.width
* @field
* @type Number
* @default @CKEDITOR.dialog.definition.prototype.minWidth
* @since 3.5.3
* @example
*/
/**
* The initial height of the dialog, in pixels.
* @name CKEDITOR.dialog.definition.prototype.height
* @field
* @type Number
* @default @CKEDITOR.dialog.definition.prototype.minHeight
* @since 3.5.3
* @example
*/
/**
* The buttons in the dialog, defined as an array of
* {@link CKEDITOR.dialog.definition.button} objects.
* @name CKEDITOR.dialog.definition.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.definition.content} objects. Required.
* @name CKEDITOR.dialog.definition.prototype.contents
* @field
* @type Array
* @example
*/
/**
* The function to execute when OK is pressed.
* @name CKEDITOR.dialog.definition.prototype.onOk
* @field
* @type Function
* @example
*/
/**
* The function to execute when Cancel is pressed.
* @name CKEDITOR.dialog.definition.prototype.onCancel
* @field
* @type Function
* @example
*/
/**
* The function to execute when the dialog is displayed for the first time.
* @name CKEDITOR.dialog.definition.prototype.onLoad
* @field
* @type Function
* @example
*/
/**
* The function to execute when the dialog is loaded (executed every time the dialog is opened).
* @name CKEDITOR.dialog.definition.prototype.onShow
* @field
* @type Function
* @example
*/
/**
* <div class="notapi">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.</div>
* @name CKEDITOR.dialog.definition.content
* @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.definition.content.prototype.id
* @field
* @type String
* @example
*/
/**
* The tab label of the content page.
* @name CKEDITOR.dialog.definition.content.prototype.label
* @field
* @type String
* @example
*/
/**
* The popup message of the tab label.
* @name CKEDITOR.dialog.definition.content.prototype.title
* @field
* @type String
* @example
*/
/**
* The CTRL hotkey for switching to the tab.
* @name CKEDITOR.dialog.definition.content.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.definition.uiElement} objects.
* @name CKEDITOR.dialog.definition.content.prototype.elements
* @field
* @type Array
* @example
*/
/**
* The definition of user interface element (textarea, radio etc).
* <div class="notapi">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.</div>
* @name CKEDITOR.dialog.definition.uiElement
* @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.definition.uiElement.prototype.id
* @field
* @type String
* @example
*/
/**
* The type of the UI element. Required.
* @name CKEDITOR.dialog.definition.uiElement.prototype.type
* @field
* @type String
* @example
*/
/**
* The popup label of the UI element.
* @name CKEDITOR.dialog.definition.uiElement.prototype.title
* @field
* @type String
* @example
*/
/**
* CSS class names to append to the UI element.
* @name CKEDITOR.dialog.definition.uiElement.prototype.className
* @field
* @type String
* @example
*/
/**
* Inline CSS classes to append to the UI element.
* @name CKEDITOR.dialog.definition.uiElement.prototype.style
* @field
* @type String
* @example
*/
/**
* Horizontal alignment (in container) of the UI element.
* @name CKEDITOR.dialog.definition.uiElement.prototype.align
* @field
* @type String
* @example
*/
/**
* Function to execute the first time the UI element is displayed.
* @name CKEDITOR.dialog.definition.uiElement.prototype.onLoad
* @field
* @type Function
* @example
*/
/**
* Function to execute whenever the UI element's parent dialog is displayed.
* @name CKEDITOR.dialog.definition.uiElement.prototype.onShow
* @field
* @type Function
* @example
*/
/**
* Function to execute whenever the UI element's parent dialog is closed.
* @name CKEDITOR.dialog.definition.uiElement.prototype.onHide
* @field
* @type Function
* @example
*/
/**
* Function to execute whenever the UI element's parent dialog's {@link CKEDITOR.dialog.definition.setupContent} method is executed.
* It usually takes care of the respective UI element as a standalone element.
* @name CKEDITOR.dialog.definition.uiElement.prototype.setup
* @field
* @type Function
* @example
*/
/**
* Function to execute whenever the UI element's parent dialog's {@link CKEDITOR.dialog.definition.commitContent} method is executed.
* It usually takes care of the respective UI element as a standalone element.
* @name CKEDITOR.dialog.definition.uiElement.prototype.commit
* @field
* @type Function
* @example
*/
// ----- hbox -----
/**
* Horizontal layout box for dialog UI elements, auto-expends to available width of container.
* <div class="notapi">
* This class is not really part of the API. It just illustrates the properties
* that developers can use to define and create horizontal layouts.
* <br /><br />Once the dialog is opened, the created element becomes a {@link CKEDITOR.ui.dialog.hbox} object and can be accessed with {@link CKEDITOR.dialog#getContentElement}.
* </div>
* @name CKEDITOR.dialog.definition.hbox
* @extends CKEDITOR.dialog.definition.uiElement
* @constructor
* @example
* // There is no constructor for this class, the user just has to define an
* // object with the appropriate properties.
*
* // Example:
* {
* <b>type : 'hbox',</b>
* widths : [ '25%', '25%', '50%' ],
* children :
* [
* {
* type : 'text',
* id : 'id1',
* width : '40px',
* },
* {
* type : 'text',
* id : 'id2',
* width : '40px',
* },
* {
* type : 'text',
* id : 'id3'
* }
* ]
* }
*/
/**
* Array of {@link CKEDITOR.ui.dialog.uiElement} objects inside this container.
* @name CKEDITOR.dialog.definition.hbox.prototype.children
* @field
* @type Array
* @example
*/
/**
* (Optional) The widths of child cells.
* @name CKEDITOR.dialog.definition.hbox.prototype.widths
* @field
* @type Array
* @example
*/
/**
* (Optional) The height of the layout.
* @name CKEDITOR.dialog.definition.hbox.prototype.height
* @field
* @type Number
* @example
*/
/**
* The CSS styles to apply to this element.
* @name CKEDITOR.dialog.definition.hbox.prototype.styles
* @field
* @type String
* @example
*/
/**
* (Optional) The padding width inside child cells. Example: 0, 1.
* @name CKEDITOR.dialog.definition.hbox.prototype.padding
* @field
* @type Number
* @example
*/
/**
* (Optional) The alignment of the whole layout. Example: center, top.
* @name CKEDITOR.dialog.definition.hbox.prototype.align
* @field
* @type String
* @example
*/
// ----- vbox -----
/**
* Vertical layout box for dialog UI elements.
* <div class="notapi">
* This class is not really part of the API. It just illustrates the properties
* that developers can use to define and create vertical layouts.
* <br /><br />Once the dialog is opened, the created element becomes a {@link CKEDITOR.ui.dialog.vbox} object and can be accessed with {@link CKEDITOR.dialog#getContentElement}.
* </div>
* <style type="text/css">.details .detailList {display:none;} </style>
* @name CKEDITOR.dialog.definition.vbox
* @extends CKEDITOR.dialog.definition.uiElement
* @constructor
* @example
* // There is no constructor for this class, the user just has to define an
* // object with the appropriate properties.
*
* // Example:
* {
* <b>type : 'vbox',</b>
* align : 'right',
* width : '200px',
* children :
* [
* {
* type : 'text',
* id : 'age',
* label : 'Age'
* },
* {
* type : 'text',
* id : 'sex',
* label : 'Sex'
* },
* {
* type : 'text',
* id : 'nationality',
* label : 'Nationality'
* }
* ]
* }
*/
/**
* Array of {@link CKEDITOR.ui.dialog.uiElement} objects inside this container.
* @name CKEDITOR.dialog.definition.vbox.prototype.children
* @field
* @type Array
* @example
*/
/**
* (Optional) The width of the layout.
* @name CKEDITOR.dialog.definition.vbox.prototype.width
* @field
* @type Array
* @example
*/
/**
* (Optional) The heights of individual cells.
* @name CKEDITOR.dialog.definition.vbox.prototype.heights
* @field
* @type Number
* @example
*/
/**
* The CSS styles to apply to this element.
* @name CKEDITOR.dialog.definition.vbox.prototype.styles
* @field
* @type String
* @example
*/
/**
* (Optional) The padding width inside child cells. Example: 0, 1.
* @name CKEDITOR.dialog.definition.vbox.prototype.padding
* @field
* @type Number
* @example
*/
/**
* (Optional) The alignment of the whole layout. Example: center, top.
* @name CKEDITOR.dialog.definition.vbox.prototype.align
* @field
* @type String
* @example
*/
/**
* (Optional) Whether the layout should expand vertically to fill its container.
* @name CKEDITOR.dialog.definition.vbox.prototype.expand
* @field
* @type Boolean
* @example
*/
// ----- labeled element ------
/**
* The definition of labeled user interface element (textarea, textInput etc).
* <div class="notapi">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.</div>
* @name CKEDITOR.dialog.definition.labeledElement
* @extends CKEDITOR.dialog.definition.uiElement
* @constructor
* @see CKEDITOR.ui.dialog.labeledElement
* @example
* // There is no constructor for this class, the user just has to define an
* // object with the appropriate properties.
*/
/**
* The label of the UI element.
* @name CKEDITOR.dialog.definition.labeledElement.prototype.label
* @type String
* @field
* @example
* {
* type : 'text',
* label : 'My Label '
* }
*/
/**
* (Optional) Specify the layout of the label. Set to 'horizontal' for horizontal layout.
* The default layout is vertical.
* @name CKEDITOR.dialog.definition.labeledElement.prototype.labelLayout
* @type String
* @field
* @example
* {
* type : 'text',
* label : 'My Label ',
* <strong> labelLayout : 'horizontal',</strong>
* }
*/
/**
* (Optional) Applies only to horizontal layouts: a two elements array of lengths to specify the widths of the
* label and the content element. See also {@link CKEDITOR.dialog.definition.labeledElement#labelLayout}.
* @name CKEDITOR.dialog.definition.labeledElement.prototype.widths
* @type Array
* @field
* @example
* {
* type : 'text',
* label : 'My Label ',
* labelLayout : 'horizontal',
* <strong> widths : [100, 200],</strong>
* }
*/
/**
* Specify the inline style of the uiElement label.
* @name CKEDITOR.dialog.definition.labeledElement.prototype.labelStyle
* @type String
* @field
* @example
* {
* type : 'text',
* label : 'My Label ',
* <strong> labelStyle : 'color: red',</strong>
* }
*/
/**
* Specify the inline style of the input element.
* @name CKEDITOR.dialog.definition.labeledElement.prototype.inputStyle
* @type String
* @since 3.6.1
* @field
* @example
* {
* type : 'text',
* label : 'My Label ',
* <strong> inputStyle : 'text-align:center',</strong>
* }
*/
/**
* Specify the inline style of the input element container .
* @name CKEDITOR.dialog.definition.labeledElement.prototype.controlStyle
* @type String
* @since 3.6.1
* @field
* @example
* {
* type : 'text',
* label : 'My Label ',
* <strong> controlStyle : 'width:3em',</strong>
* }
*/
// ----- button ------
/**
* The definition of a button.
* <div class="notapi">
* This class is not really part of the API. It just illustrates the properties
* that developers can use to define and create buttons.
* <br /><br />Once the dialog is opened, the created element becomes a {@link CKEDITOR.ui.dialog.button} object and can be accessed with {@link CKEDITOR.dialog#getContentElement}.
* </div>
* For a complete example of dialog definition, please check {@link CKEDITOR.dialog.add}.
* @name CKEDITOR.dialog.definition.button
* @extends CKEDITOR.dialog.definition.uiElement
* @constructor
* @example
* // There is no constructor for this class, the user just has to define an
* // object with the appropriate properties.
*
* // Example:
* {
* <b>type : 'button',</b>
* id : 'buttonId',
* label : 'Click me',
* title : 'My title',
* onClick : function() {
* // this = CKEDITOR.ui.dialog.button
* alert( 'Clicked: ' + this.id );
* }
* }
*/
/**
* Whether the button is disabled.
* @name CKEDITOR.dialog.definition.button.prototype.disabled
* @type Boolean
* @field
* @example
*/
/**
* The label of the UI element.
* @name CKEDITOR.dialog.definition.button.prototype.label
* @type String
* @field
* @example
*/
// ----- checkbox ------
/**
* The definition of a checkbox element.
* <div class="notapi">
* This class is not really part of the API. It just illustrates the properties
* that developers can use to define and create groups of checkbox buttons.
* <br /><br />Once the dialog is opened, the created element becomes a {@link CKEDITOR.ui.dialog.checkbox} object and can be accessed with {@link CKEDITOR.dialog#getContentElement}.
* </div>
* For a complete example of dialog definition, please check {@link CKEDITOR.dialog.add}.
* @name CKEDITOR.dialog.definition.checkbox
* @extends CKEDITOR.dialog.definition.uiElement
* @constructor
* @example
* // There is no constructor for this class, the user just has to define an
* // object with the appropriate properties.
*
* // Example:
* {
* <b>type : 'checkbox',</b>
* id : 'agree',
* label : 'I agree',
* 'default' : 'checked',
* onClick : function() {
* // this = CKEDITOR.ui.dialog.checkbox
* alert( 'Checked: ' + this.getValue() );
* }
* }
*/
/**
* (Optional) The validation function.
* @name CKEDITOR.dialog.definition.checkbox.prototype.validate
* @field
* @type Function
* @example
*/
/**
* The label of the UI element.
* @name CKEDITOR.dialog.definition.checkbox.prototype.label
* @type String
* @field
* @example
*/
/**
* The default state.
* @name CKEDITOR.dialog.definition.checkbox.prototype.default
* @type String
* @field
* @default
* '' (unchecked)
* @example
*/
// ----- file -----
/**
* The definition of a file upload input.
* <div class="notapi">
* This class is not really part of the API. It just illustrates the properties
* that developers can use to define and create file upload elements.
* <br /><br />Once the dialog is opened, the created element becomes a {@link CKEDITOR.ui.dialog.file} object and can be accessed with {@link CKEDITOR.dialog#getContentElement}.
* </div>
* For a complete example of dialog definition, please check {@link CKEDITOR.dialog.add}.
* @name CKEDITOR.dialog.definition.file
* @extends CKEDITOR.dialog.definition.labeledElement
* @constructor
* @example
* // There is no constructor for this class, the user just has to define an
* // object with the appropriate properties.
*
* // Example:
* {
* <b>type : 'file'</b>,
* id : 'upload',
* label : 'Select file from your computer',
* size : 38
* },
* {
* type : 'fileButton',
* id : 'fileId',
* label : 'Upload file',
* 'for' : [ 'tab1', 'upload' ]
* filebrowser : {
* onSelect : function( fileUrl, data ) {
* alert( 'Successfully uploaded: ' + fileUrl );
* }
* }
* }
*/
/**
* (Optional) The validation function.
* @name CKEDITOR.dialog.definition.file.prototype.validate
* @field
* @type Function
* @example
*/
/**
* (Optional) The action attribute of the form element associated with this file upload input.
* If empty, CKEditor will use path to server connector for currently opened folder.
* @name CKEDITOR.dialog.definition.file.prototype.action
* @type String
* @field
* @example
*/
/**
* The size of the UI element.
* @name CKEDITOR.dialog.definition.file.prototype.size
* @type Number
* @field
* @example
*/
// ----- fileButton -----
/**
* The definition of a button for submitting the file in a file upload input.
* <div class="notapi">
* This class is not really part of the API. It just illustrates the properties
* that developers can use to define and create a button for submitting the file in a file upload input.
* <br /><br />Once the dialog is opened, the created element becomes a {@link CKEDITOR.ui.dialog.fileButton} object and can be accessed with {@link CKEDITOR.dialog#getContentElement}.
* </div>
* For a complete example of dialog definition, please check {@link CKEDITOR.dialog.add}.
* @name CKEDITOR.dialog.definition.fileButton
* @extends CKEDITOR.dialog.definition.uiElement
* @constructor
* @example
* // There is no constructor for this class, the user just has to define an
* // object with the appropriate properties.
*
* // Example:
* {
* type : 'file',
* id : 'upload',
* label : 'Select file from your computer',
* size : 38
* },
* {
* <b>type : 'fileButton'</b>,
* id : 'fileId',
* label : 'Upload file',
* 'for' : [ 'tab1', 'upload' ]
* filebrowser : {
* onSelect : function( fileUrl, data ) {
* alert( 'Successfully uploaded: ' + fileUrl );
* }
* }
* }
*/
/**
* (Optional) The validation function.
* @name CKEDITOR.dialog.definition.fileButton.prototype.validate
* @field
* @type Function
* @example
*/
/**
* The label of the UI element.
* @name CKEDITOR.dialog.definition.fileButton.prototype.label
* @type String
* @field
* @example
*/
/**
* The instruction for CKEditor how to deal with file upload.
* By default, the file and fileButton elements will not work "as expected" if this attribute is not set.
* @name CKEDITOR.dialog.definition.fileButton.prototype.filebrowser
* @type String|Object
* @field
* @example
* // Update field with id 'txtUrl' in the 'tab1' tab when file is uploaded.
* filebrowser : 'tab1:txtUrl'
*
* // Call custom onSelect function when file is successfully uploaded.
* filebrowser : {
* onSelect : function( fileUrl, data ) {
* alert( 'Successfully uploaded: ' + fileUrl );
* }
* }
*/
/**
* An array that contains pageId and elementId of the file upload input element for which this button is created.
* @name CKEDITOR.dialog.definition.fileButton.prototype.for
* @type String
* @field
* @example
* [ pageId, elementId ]
*/
// ----- html -----
/**
* The definition of a raw HTML element.
* <div class="notapi">
* This class is not really part of the API. It just illustrates the properties
* that developers can use to define and create elements made from raw HTML code.
* <br /><br />Once the dialog is opened, the created element becomes a {@link CKEDITOR.ui.dialog.html} object and can be accessed with {@link CKEDITOR.dialog#getContentElement}.
* </div>
* For a complete example of dialog definition, please check {@link CKEDITOR.dialog.add}.<br />
* To access HTML elements use {@link CKEDITOR.dom.document#getById}
* @name CKEDITOR.dialog.definition.html
* @extends CKEDITOR.dialog.definition.uiElement
* @constructor
* @example
* // There is no constructor for this class, the user just has to define an
* // object with the appropriate properties.
*
* // Example 1:
* {
* <b>type : 'html',</b>
* html : '<h3>This is some sample HTML content.</h3>'
* }
* @example
* // Example 2:
* // Complete sample with document.getById() call when the "Ok" button is clicked.
* var dialogDefinition =
* {
* title : 'Sample dialog',
* minWidth : 300,
* minHeight : 200,
* onOk : function() {
* // "this" is now a CKEDITOR.dialog object.
* var document = this.getElement().getDocument();
* // document = CKEDITOR.dom.document
* var element = <b>document.getById( 'myDiv' );</b>
* if ( element )
* alert( element.getHtml() );
* },
* contents : [
* {
* id : 'tab1',
* label : '',
* title : '',
* elements :
* [
* {
* <b>type : 'html',</b>
* html : '<b><div id="myDiv">Sample <b>text</b>.</div></b><div id="otherId">Another div.</div>'
* },
* ]
* }
* ],
* buttons : [ CKEDITOR.dialog.cancelButton, CKEDITOR.dialog.okButton ]
* };
*/
/**
* (Required) HTML code of this element.
* @name CKEDITOR.dialog.definition.html.prototype.html
* @type String
* @field
* @example
*/
// ----- radio ------
/**
* The definition of a radio group.
* <div class="notapi">
* This class is not really part of the API. It just illustrates the properties
* that developers can use to define and create groups of radio buttons.
* <br /><br />Once the dialog is opened, the created element becomes a {@link CKEDITOR.ui.dialog.radio} object and can be accessed with {@link CKEDITOR.dialog#getContentElement}.
* </div>
* For a complete example of dialog definition, please check {@link CKEDITOR.dialog.add}.
* @name CKEDITOR.dialog.definition.radio
* @extends CKEDITOR.dialog.definition.labeledElement
* @constructor
* @example
* // There is no constructor for this class, the user just has to define an
* // object with the appropriate properties.
*
* // Example:
* {
* <b>type : 'radio',</b>
* id : 'country',
* label : 'Which country is bigger',
* items : [ [ 'France', 'FR' ], [ 'Germany', 'DE' ] ] ,
* style : 'color:green',
* 'default' : 'DE',
* onClick : function() {
* // this = CKEDITOR.ui.dialog.radio
* alert( 'Current value: ' + this.getValue() );
* }
* }
*/
/**
* The default value.
* @name CKEDITOR.dialog.definition.radio.prototype.default
* @type String
* @field
* @example
*/
/**
* (Optional) The validation function.
* @name CKEDITOR.dialog.definition.radio.prototype.validate
* @field
* @type Function
* @example
*/
/**
* 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.
* @name CKEDITOR.dialog.definition.radio.prototype.items
* @field
* @type Array
* @example
*/
// ----- selectElement ------
/**
* The definition of a select element.
* <div class="notapi">
* This class is not really part of the API. It just illustrates the properties
* that developers can use to define and create select elements.
* <br /><br />Once the dialog is opened, the created element becomes a {@link CKEDITOR.ui.dialog.select} object and can be accessed with {@link CKEDITOR.dialog#getContentElement}.
* </div>
* For a complete example of dialog definition, please check {@link CKEDITOR.dialog.add}.
* @name CKEDITOR.dialog.definition.select
* @extends CKEDITOR.dialog.definition.labeledElement
* @constructor
* @example
* // There is no constructor for this class, the user just has to define an
* // object with the appropriate properties.
*
* // Example:
* {
* <b>type : 'select',</b>
* id : 'sport',
* label : 'Select your favourite sport',
* items : [ [ 'Basketball' ], [ 'Baseball' ], [ 'Hockey' ], [ 'Football' ] ],
* 'default' : 'Football',
* onChange : function( api ) {
* // this = CKEDITOR.ui.dialog.select
* alert( 'Current value: ' + this.getValue() );
* }
* }
*/
/**
* The default value.
* @name CKEDITOR.dialog.definition.select.prototype.default
* @type String
* @field
* @example
*/
/**
* (Optional) The validation function.
* @name CKEDITOR.dialog.definition.select.prototype.validate
* @field
* @type Function
* @example
*/
/**
* 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.
* @name CKEDITOR.dialog.definition.select.prototype.items
* @field
* @type Array
* @example
*/
/**
* (Optional) Set this to true if you'd like to have a multiple-choice select box.
* @name CKEDITOR.dialog.definition.select.prototype.multiple
* @type Boolean
* @field
* @example
* @default false
*/
/**
* (Optional) The number of items to display in the select box.
* @name CKEDITOR.dialog.definition.select.prototype.size
* @type Number
* @field
* @example
*/
// ----- textInput -----
/**
* The definition of a text field (single line).
* <div class="notapi">
* This class is not really part of the API. It just illustrates the properties
* that developers can use to define and create text fields.
* <br /><br />Once the dialog is opened, the created element becomes a {@link CKEDITOR.ui.dialog.textInput} object and can be accessed with {@link CKEDITOR.dialog#getContentElement}.
* </div>
* For a complete example of dialog definition, please check {@link CKEDITOR.dialog.add}.
* @name CKEDITOR.dialog.definition.textInput
* @extends CKEDITOR.dialog.definition.labeledElement
* @constructor
* @example
* // There is no constructor for this class, the user just has to define an
* // object with the appropriate properties.
*
* {
* <b>type : 'text',</b>
* id : 'name',
* label : 'Your name',
* 'default' : '',
* validate : function() {
* if ( !this.getValue() )
* {
* api.openMsgDialog( '', 'Name cannot be empty.' );
* return false;
* }
* }
* }
*/
/**
* The default value.
* @name CKEDITOR.dialog.definition.textInput.prototype.default
* @type String
* @field
* @example
*/
/**
* (Optional) The maximum length.
* @name CKEDITOR.dialog.definition.textInput.prototype.maxLength
* @type Number
* @field
* @example
*/
/**
* (Optional) The size of the input field.
* @name CKEDITOR.dialog.definition.textInput.prototype.size
* @type Number
* @field
* @example
*/
/**
* (Optional) The validation function.
* @name CKEDITOR.dialog.definition.textInput.prototype.validate
* @field
* @type Function
* @example
*/
// ----- textarea ------
/**
* The definition of a text field (multiple lines).
* <div class="notapi">
* This class is not really part of the API. It just illustrates the properties
* that developers can use to define and create textarea.
* <br /><br />Once the dialog is opened, the created element becomes a {@link CKEDITOR.ui.dialog.textarea} object and can be accessed with {@link CKEDITOR.dialog#getContentElement}.
* </div>
* For a complete example of dialog definition, please check {@link CKEDITOR.dialog.add}.
* @name CKEDITOR.dialog.definition.textarea
* @extends CKEDITOR.dialog.definition.labeledElement
* @constructor
* @example
* // There is no constructor for this class, the user just has to define an
* // object with the appropriate properties.
*
* // Example:
* {
* <b>type : 'textarea',</b>
* id : 'message',
* label : 'Your comment',
* 'default' : '',
* validate : function() {
* if ( this.getValue().length < 5 )
* {
* api.openMsgDialog( 'The comment is too short.' );
* return false;
* }
* }
* }
*/
/**
* The number of rows.
* @name CKEDITOR.dialog.definition.textarea.prototype.rows
* @type Number
* @field
* @example
*/
/**
* The number of columns.
* @name CKEDITOR.dialog.definition.textarea.prototype.cols
* @type Number
* @field
* @example
*/
/**
* (Optional) The validation function.
* @name CKEDITOR.dialog.definition.textarea.prototype.validate
* @field
* @type Function
* @example
*/
/**
* The default value.
* @name CKEDITOR.dialog.definition.textarea.prototype.default
* @type String
* @field
* @example
*/
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/dialog/dialogDefinition.js | JavaScript | asf20 | 31,825 |
/*
Copyright (c) 2003-2012, 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', '' );
}
}
}
}
// Handle dialog element validation state UI changes.
function handleFieldValidated( isValid, msg )
{
var input = this.getInputElement();
if ( input )
{
isValid ? input.removeAttribute( 'aria-invalid' )
: input.setAttribute( 'aria-invalid', true );
}
if ( !isValid )
{
if ( this.select )
this.select();
else
this.focus();
}
msg && alert( msg );
this.fire( 'validated', { valid : isValid, msg : msg } );
}
function resetField()
{
var input = this.getInputElement();
input && input.removeAttribute( 'aria-invalid' );
}
/**
* 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,
tabsToRemove = {},
i,
processed, stopPropagation;
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.
var startStyles = {
position : CKEDITOR.env.ie6Compat ? 'absolute' : 'fixed',
top : 0,
visibility : 'hidden'
};
startStyles[ dir == 'rtl' ? 'right' : 'left' ] = 0;
this.parts.dialog.setStyles( startStyles );
// 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;
// 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 retval = item.validate( this ),
invalid = typeof ( retval ) == 'string' || retval === false;
if ( invalid )
{
evt.data.hide = false;
evt.stop();
}
handleFieldValidated.call( item, !invalid, typeof retval == 'string' ? retval : undefined );
return invalid;
}
});
}, 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( offset )
{
var focusList = me._.focusList;
offset = offset || 0;
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 ( offset && !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;
function keydownHandler( 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',
button;
processed = stopPropagation = 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 ? -1 : 1 );
}
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( 1 );
processed = 1;
}
// If user presses enter key in a text box, it implies clicking OK for the dialog.
else if ( keystroke == 13 /*ENTER*/ )
{
// Don't do that for a target that handles ENTER.
var target = evt.data.getTarget();
if ( !target.is( 'a', 'button', 'select' ) && ( !target.is( 'input' ) || target.$.type != 'button' ) )
{
button = this.getButton( 'ok' );
button && CKEDITOR.tools.setTimeout( button.click, 0, button );
processed = 1;
}
stopPropagation = 1; // Always block the propagation (#4269)
}
else if ( keystroke == 27 /*ESC*/ )
{
button = this.getButton( 'cancel' );
// If there's a Cancel button, click it, else just fire the cancel event and hide the dialog.
if ( button )
CKEDITOR.tools.setTimeout( button.click, 0, button );
else
{
if ( this.fire( 'cancel', { hide : true } ).hide !== false )
this.hide();
}
stopPropagation = 1; // Always block the propagation (#4269)
}
else
return;
keypressHandler( evt );
}
function keypressHandler( evt )
{
if ( processed )
evt.data.preventDefault(1);
else if ( stopPropagation )
evt.data.stopPropagation();
}
var dialogElement = this._.element;
// Add the dialog keyboard handlers.
this.on( 'show', function()
{
dialogElement.on( 'keydown', keydownHandler, 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. (#4531,#8985)
if ( CKEDITOR.env.opera || CKEDITOR.env.gecko )
dialogElement.on( 'keypress', keypressHandler, this );
} );
this.on( 'hide', function()
{
dialogElement.removeListener( 'keydown', keydownHandler );
if ( CKEDITOR.env.opera || CKEDITOR.env.gecko )
dialogElement.removeListener( 'keypress', keypressHandler );
// Reset fields state when closing dialog.
iterContents( function( item ) { resetField.apply( item ); } );
} );
this.on( 'iframeAdded', function( evt )
{
var doc = new CKEDITOR.dom.document( evt.data.iframe.$.contentWindow.document );
doc.on( 'keydown', keydownHandler, 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( 1 );
/*
* 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 ( 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( 1 );
}
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.fire( 'resize',
{
skin : this._.editor.skinName,
width : width,
height : height
}, this._.editor );
// Update dialog position when dimension get changed in RTL.
if ( this._.editor.lang.dir == 'rtl' && this._.position )
this._.position.x = CKEDITOR.document.getWindow().getViewPaneSize().width -
this._.contentSize.width - parseInt( this._.element.getFirst().getStyle( 'right' ), 10 );
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(),
rtl = this._.editor.lang.dir == 'rtl';
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;
}
// Translate coordinate for RTL.
if ( rtl )
{
var dialogSize = this.getSize(),
viewPaneSize = CKEDITOR.document.getWindow().getViewPaneSize();
x = viewPaneSize.width - dialogSize.width - x;
}
var styles = { 'top' : ( y > 0 ? y : 0 ) + 'px' };
styles[ rtl ? 'right' : 'left' ] = ( x > 0 ? x : 0 ) + 'px';
element.setStyles( styles );
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()
{
// 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.width || definition.minWidth,
this._.contentSize && this._.contentSize.height || definition.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.
if ( CKEDITOR.dialog._.currentTop === null )
{
CKEDITOR.dialog._.currentTop = this;
this._.parentDialog = null;
showCover( this._.editor );
}
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;
}
element.on( 'keydown', accessKeyDownHandler );
element.on( CKEDITOR.env.opera ? 'keypress' : 'keyup', accessKeyUpHandler );
// 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.call( this, 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; };
})(),
/**
* Calls the {@link CKEDITOR.dialog.definition.uiElement#setup} method of each of the UI elements, with the arguments passed through it.
* It is usually being called when the dialog is opened, to put the initial value inside the field.
* @example
* dialogObj.setupContent();
* @example
* var timestamp = ( new Date() ).valueOf();
* dialogObj.setupContent( timestamp );
*/
setupContent : function()
{
var args = arguments;
this.foreach( function( widget )
{
if ( widget.setup )
widget.setup.apply( widget, args );
});
},
/**
* Calls the {@link CKEDITOR.dialog.definition.uiElement#commit} method of each of the UI elements, with the arguments passed through it.
* It is usually being called when the user confirms the dialog, to process the values.
* @example
* dialogObj.commitContent();
* @example
* var timestamp = ( new Date() ).valueOf();
* dialogObj.commitContent( timestamp );
*/
commitContent : function()
{
var args = arguments;
this.foreach( function( widget )
{
// Make sure IE triggers "change" event on last focused input before closing the dialog. (#7915)
if ( CKEDITOR.env.ie && this._.currentFocusIndex == widget.focusIndex )
widget.getInputElement().$.blur();
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 );
// Reset the tab page.
this.selectPage( this._.tabIdList[ 0 ] );
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 );
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%;height: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
* dialogObj.getContentElement( 'tabId', 'elementId' ).setValue( '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
* alert( dialogObj.getValueOf( 'tabId', 'elementId' ) );
* @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
* dialogObj.setValueOf( 'tabId', 'elementId', '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.definition}.
* @see CKEDITOR.dialog.definition
* @example
* // Full sample plugin, which does not only register a dialog window but also adds an item to the context menu.
* // To open the dialog window, choose "Open dialog" in the context menu.
* CKEDITOR.plugins.add( 'myplugin',
* {
* init: function( editor )
* {
* editor.addCommand( 'mydialog',new CKEDITOR.dialogCommand( 'mydialog' ) );
*
* if ( editor.contextMenu )
* {
* editor.addMenuGroup( 'mygroup', 10 );
* editor.addMenuItem( 'My Dialog',
* {
* label : 'Open dialog',
* command : 'mydialog',
* group : 'mygroup'
* });
* editor.contextMenu.addListener( function( element )
* {
* return { 'My Dialog' : CKEDITOR.TRISTATE_OFF };
* });
* }
*
* <strong>CKEDITOR.dialog.add</strong>( 'mydialog', function( api )
* {
* // CKEDITOR.dialog.definition
* var <strong>dialogDefinition</strong> =
* {
* title : 'Sample dialog',
* minWidth : 390,
* minHeight : 130,
* contents : [
* {
* id : 'tab1',
* label : 'Label',
* title : 'Title',
* expand : true,
* padding : 0,
* elements :
* [
* {
* type : 'html',
* html : '<p>This is some sample HTML content.</p>'
* },
* {
* type : 'textarea',
* id : 'textareaId',
* rows : 4,
* cols : 40
* }
* ]
* }
* ],
* buttons : [ CKEDITOR.dialog.okButton, CKEDITOR.dialog.cancelButton ],
* onOk : function() {
* // "this" is now a CKEDITOR.dialog object.
* // Accessing dialog elements:
* var textareaObj = this.<strong>getContentElement</strong>( 'tab1', 'textareaId' );
* alert( "You have entered: " + textareaObj.getValue() );
* }
* };
*
* return dialogDefinition;
* } );
* }
* } );
*
* CKEDITOR.replace( 'editor1', { extraPlugins : 'myplugin' } );
*/
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.definitionObject
* @extends CKEDITOR.dialog.definition
* @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.definitionObject.prototype */
{
/**
* Gets a content definition.
* @param {String} id The id of the content definition.
* @returns {CKEDITOR.dialog.definition.content} 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.definition.button} 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.definition.content} 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.definition.content} 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.definition.button} 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.definition.button} 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.definition.content} 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.definition.button} 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.definitionObject.
* @constructor
* @name CKEDITOR.dialog.definition.contentObject
* @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.definition.contentObject.prototype */
{
/**
* Gets a UI element definition under the content definition.
* @param {String} id The id of the UI element definition.
* @returns {CKEDITOR.dialog.definition.uiElement}
*/
get : function( id )
{
return getById( this.elements, id, 'children' );
},
/**
* Adds a UI element definition to the content definition.
* @param {CKEDITOR.dialog.definition.uiElement} 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.definition.uiElement} 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.definition.uiElement} 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,
dialogCover;
var mouseDownFn = CKEDITOR.tools.addFunction( function( $event )
{
startSize = dialog.getSize();
var content = dialog.parts.contents,
iframeDialog = content.$.getElementsByTagName( 'iframe' ).length;
// Shim to help capturing "mousemove" over iframe.
if ( iframeDialog )
{
dialogCover = CKEDITOR.dom.element.createFromHtml( '<div class="cke_dialog_resize_cover" style="height: 100%; position: absolute; width: 100%;"></div>' );
content.append( dialogCover );
}
// 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 + ' cke_resizer_' + editor.lang.dir + '"' +
' 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();
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 ) )
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 );
if ( !dialog._.moved )
dialog.layout();
evt.data.preventDefault();
}
function mouseUpHandler()
{
CKEDITOR.document.removeListener( 'mouseup', mouseUpHandler );
CKEDITOR.document.removeListener( 'mousemove', mouseMoveHandler );
if ( dialogCover )
{
dialogCover.remove();
dialogCover = null;
}
if ( CKEDITOR.env.ie6Compat )
{
var coverDoc = currentCover.getChild( 0 ).getFrameDocument();
coverDoc.removeListener( 'mouseup', mouseUpHandler );
coverDoc.removeListener( 'mousemove', mouseMoveHandler );
}
}
}
var resizeCover;
// Caching resuable covers and allowing only one cover
// on screen.
var covers = {},
currentCover;
function cancelEvent( ev )
{
ev.data.preventDefault(1);
}
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 tabIndex="-1" 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.on( 'keydown', cancelEvent );
coverElement.on( 'keypress', cancelEvent );
coverElement.on( 'keyup', cancelEvent );
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'
});
if ( cursor )
{
do
{
var dialogPos = cursor.getPosition();
cursor.move( dialogPos.x, dialogPos.y );
} while ( ( cursor = cursor._.parentDialog ) );
}
};
resizeCover = resizeFunc;
win.on( 'resize', resizeFunc );
resizeFunc();
// Using Safari/Mac, focus must be kept where it is (#7027)
if ( !( CKEDITOR.env.mac && CKEDITOR.env.webkit ) )
coverElement.focus();
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 )
{
};
(function()
{
CKEDITOR.ui.dialog =
{
/**
* The base class of all dialog UI elements.
* @constructor
* @param {CKEDITOR.dialog} dialog Parent dialog object.
* @param {CKEDITOR.dialog.definition.uiElement} 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;
if ( elementDefinition.disabled )
classes[ 'cke_disabled' ] = 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( ';' );
// Element alignment support.
if ( elementDefinition.align )
{
var align = elementDefinition.align;
styles[ 'margin-left' ] = align == 'left' ? 0 : 'auto';
styles[ 'margin-right' ] = align == 'right' ? 0 : 'auto';
}
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;
// Overload 'get(set)Value' on definition.
if ( typeof( elementDefinition.setValue ) == 'function' )
{
this.setValue = CKEDITOR.tools.override( this.setValue, function( org )
{
return function( val ){ org.call( this, elementDefinition.setValue.call( this, val ) ); };
} );
}
if ( typeof( elementDefinition.getValue ) == 'function' )
{
this.getValue = CKEDITOR.tools.override( this.getValue, function( org )
{
return function(){ return elementDefinition.getValue.call( this, org.call( this ) ); };
} );
}
// 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()
{
var input = me.getInputElement();
if ( input )
{
var focusClass = me.type in { 'checkbox' : 1, 'ratio' : 1 } && CKEDITOR.env.ie && CKEDITOR.env.version < 8 ? 'cke_dialog_ui_focused' : '';
input.on( 'focus', function()
{
dialog._.tabBarMode = false;
dialog._.hasFocus = true;
me.fire( 'focus' );
focusClass && this.addClass( focusClass );
});
input.on( 'blur', function()
{
me.fire( 'blur' );
focusClass && this.removeClass( focusClass );
});
}
} );
// 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.definition.uiElement} 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 ) );
// In IE Quirks alignment has to be done on table cells. (#7324)
if ( CKEDITOR.env.ie && CKEDITOR.env.quirks && children[ i ].align )
styles.push( 'text-align:' + children[ i ].align );
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.definition.uiElement} 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 ) );
// In IE Quirks alignment has to be done on table cells. (#7324)
if ( CKEDITOR.env.ie && CKEDITOR.env.quirks && children[ i ].align )
styles.push( 'text-align:' + children[ i ].align );
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.definition.uiElement} 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.getElement(),
input = this.getInputElement();
input.setAttribute( 'disabled', 'true' );
element.addClass( 'cke_disabled' );
},
/**
* Enables a UI element.
* @example
*/
enable : function()
{
var element = this.getElement(),
input = this.getInputElement();
input.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.getElement().hasClass( 'cke_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 )
{
// Special treatment for Opera. (#8031)
CKEDITOR.env.opera ?
CKEDITOR.tools.setTimeout( function() { editor.openDialog( this.dialogName ); }, 0, this )
: 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+)?$/,
htmlLengthRegex = /^(((\d*(\.\d+))|(\d*))(px|\%)?)?$/,
cssLengthRegex = /^(((\d*(\.\d+))|(\d*))(px|em|ex|in|cm|mm|pt|pc|\%)?)?$/i,
inlineStyleRegex = /^(\s*[\w-]+\s*:\s*[^:;]+(?:;|$))*$/;
CKEDITOR.VALIDATE_OR = 1;
CKEDITOR.VALIDATE_AND = 2;
CKEDITOR.dialog.validate =
{
functions : function()
{
var args = arguments;
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() : args[ 0 ];
var msg = undefined,
relation = CKEDITOR.VALIDATE_AND,
functions = [], i;
for ( i = 0 ; i < args.length ; i++ )
{
if ( typeof( args[i] ) == 'function' )
functions.push( args[i] );
else
break;
}
if ( i < args.length && typeof( args[i] ) == 'string' )
{
msg = args[i];
i++;
}
if ( i < args.length && typeof( args[i]) == 'number' )
relation = args[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 );
}
return !passed ? msg : 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];
return !regex.test( value ) ? msg : 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 );
},
'cssLength' : function( msg )
{
return this.functions( function( val ){ return cssLengthRegex.test( CKEDITOR.tools.trim( val ) ); }, msg );
},
'htmlLength' : function( msg )
{
return this.functions( function( val ){ return htmlLengthRegex.test( CKEDITOR.tools.trim( val ) ); }, msg );
},
'inlineStyle' : function( msg )
{
return this.functions( function( val ){ return inlineStyleRegex.test( CKEDITOR.tools.trim( val ) ); }, 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 )
{
if ( this.mode == 'wysiwyg' && CKEDITOR.env.ie )
{
var selection = this.getSelection();
selection && selection.lock();
}
var dialogDefinitions = CKEDITOR.dialog._.dialogDefinitions[ dialogName ],
dialogSkin = this.skin.dialog;
if ( CKEDITOR.dialog._.currentTop === null )
showCover( this );
// 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' )
{
hideCover();
throw new Error( '[CKEDITOR.dialog.openDialog] Dialog "' + dialogName + '" failed when loading definition.' );
}
var me = this;
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 );
}
if ( typeof dialogDefinitions == 'string' )
{
var loadDefinition = 1;
CKEDITOR.scriptLoader.load( CKEDITOR.getUrl( dialogDefinitions ), onDialogFileLoaded, null, 0, 1 );
}
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 guideline 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.definition} 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 CKEDITOR.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.
*/
/**
* Fired when the user tries to dismiss a dialog
* @name CKEDITOR.dialog#cancel
* @event
* @param {Boolean} hide Whether the event should proceed or not.
*/
/**
* Fired when the user tries to confirm a dialog
* @name CKEDITOR.dialog#ok
* @event
* @param {Boolean} hide Whether the event should proceed or not.
*/
/**
* Fired when a dialog is shown
* @name CKEDITOR.dialog#show
* @event
*/
/**
* Fired when a dialog is shown
* @name CKEDITOR.editor#dialogShow
* @event
*/
/**
* Fired when a dialog is hidden
* @name CKEDITOR.dialog#hide
* @event
*/
/**
* Fired when a dialog is hidden
* @name CKEDITOR.editor#dialogHide
* @event
*/
/**
* Fired when a dialog is being resized. The event is fired on
* both the 'CKEDITOR.dialog' object and the dialog instance
* since 3.5.3, previously it's available only in the global object.
* @name CKEDITOR.dialog#resize
* @since 3.5
* @event
* @param {CKEDITOR.dialog} dialog The dialog being resized (if
* it's fired on the dialog itself, this parameter isn't sent).
* @param {String} skin The skin name.
* @param {Number} width The new width.
* @param {Number} height The new height.
*/
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/dialog/plugin.js | JavaScript | asf20 | 101,447 |
/*
Copyright (c) 2003-2012, 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 =
{
readOnly : 1,
preserveState : true,
editorFocus : false,
exec : function ( editor )
{
this.toggleState();
this.refresh( editor );
},
refresh : function( editor )
{
if ( editor.document )
{
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;
*/
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/showblocks/plugin.js | JavaScript | asf20 | 3,212 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @stylesheetParser plugin.
*/
(function()
{
// We want to extract only the elements with classes defined in the stylesheets:
function parseClasses( aRules, skipSelectors, validSelectors )
{
// aRules are just the different rules in the style sheets
// We want to merge them and them split them by commas, so we end up with only
// the selectors
var s = aRules.join(' ');
// Remove selectors splitting the elements, leave only the class selector (.)
s = s.replace( /(,|>|\+|~)/g, ' ' );
// Remove attribute selectors: table[border="0"]
s = s.replace( /\[[^\]]*/g, '' );
// Remove Ids: div#main
s = s.replace( /#[^\s]*/g, '' );
// Remove pseudo-selectors and pseudo-elements: :hover :nth-child(2n+1) ::before
s = s.replace( /\:{1,2}[^\s]*/g, '' );
s = s.replace( /\s+/g, ' ' );
var aSelectors = s.split( ' ' ),
aClasses = [];
for ( var i = 0; i < aSelectors.length ; i++ )
{
var selector = aSelectors[ i ];
if ( validSelectors.test( selector ) && !skipSelectors.test( selector ) )
{
// If we still don't know about this one, add it
if ( CKEDITOR.tools.indexOf( aClasses, selector ) == -1 )
aClasses.push( selector );
}
}
return aClasses;
}
function LoadStylesCSS( theDoc, skipSelectors, validSelectors )
{
var styles = [],
// It will hold all the rules of the applied stylesheets (except those internal to CKEditor)
aRules = [],
i;
for ( i = 0; i < theDoc.styleSheets.length; i++ )
{
var sheet = theDoc.styleSheets[ i ],
node = sheet.ownerNode || sheet.owningElement;
// Skip the internal stylesheets
if ( node.getAttribute( 'data-cke-temp' ) )
continue;
// Exclude stylesheets injected by extensions
if ( sheet.href && sheet.href.substr(0, 9) == 'chrome://' )
continue;
var sheetRules = sheet.cssRules || sheet.rules;
for ( var j = 0; j < sheetRules.length; j++ )
aRules.push( sheetRules[ j ].selectorText );
}
var aClasses = parseClasses( aRules, skipSelectors, validSelectors );
// Add each style to our "Styles" collection.
for ( i = 0; i < aClasses.length; i++ )
{
var oElement = aClasses[ i ].split( '.' ),
element = oElement[ 0 ].toLowerCase(),
sClassName = oElement[ 1 ];
styles.push( {
name : element + '.' + sClassName,
element : element,
attributes : {'class' : sClassName}
});
}
return styles;
}
// Register a plugin named "stylesheetparser".
CKEDITOR.plugins.add( 'stylesheetparser',
{
requires: [ 'styles' ],
onLoad : function()
{
var obj = CKEDITOR.editor.prototype;
obj.getStylesSet = CKEDITOR.tools.override( obj.getStylesSet, function( org )
{
return function( callback )
{
var self = this;
org.call( this, function( definitions )
{
// Rules that must be skipped
var skipSelectors = self.config.stylesheetParser_skipSelectors || ( /(^body\.|^\.)/i ),
// Rules that are valid
validSelectors = self.config.stylesheetParser_validSelectors || ( /\w+\.\w+/ );
callback( ( self._.stylesDefinitions = definitions.concat( LoadStylesCSS( self.document.$, skipSelectors, validSelectors ) ) ) );
});
};
});
}
});
})();
/**
* A regular expression that defines whether a CSS rule will be
* skipped by the Stylesheet Parser plugin. A CSS rule matching
* the regular expression will be ignored and will not be available
* in the Styles drop-down list.
* @name CKEDITOR.config.stylesheetParser_skipSelectors
* @type RegExp
* @default /(^body\.|^\.)/i
* @since 3.6
* @see CKEDITOR.config.stylesheetParser_validSelectors
* @example
* // Ignore rules for body and caption elements, classes starting with "high", and any class defined for no specific element.
* config.stylesheetParser_skipSelectors = /(^body\.|^caption\.|\.high|^\.)/i;
*/
/**
* A regular expression that defines which CSS rules will be used
* by the Stylesheet Parser plugin. A CSS rule matching the regular
* expression will be available in the Styles drop-down list.
* @name CKEDITOR.config.stylesheetParser_validSelectors
* @type RegExp
* @default /\w+\.\w+/
* @since 3.6
* @see CKEDITOR.config.stylesheetParser_skipSelectors
* @example
* // Only add rules for p and span elements.
* config.stylesheetParser_validSelectors = /\^(p|span)\.\w+/;
*/
| 10npsite | trunk/guanli/system/ckeditor/_source/plugins/stylesheetparser/plugin.js | JavaScript | asf20 | 4,621 |