们看一下CKEditor4的编辑器内容的设置和获取过程,也就是setData和getData过程。
我们在调用editor.setData的时候,调用的就是core/editor.js里面的setData方法。
// src/core/editor.js
setData: function( data, options, internal ) {
var fireSnapshot = true,
// Backward compatibility.
callback = options,
eventData;
if ( options && typeof options == 'object' ) {
internal = options.internal;
callback = options.callback;
fireSnapshot = !options.noSnapshot;
}
if ( !internal && fireSnapshot )
this.fire( 'saveSnapshot' );
if ( callback || !internal ) {
this.once( 'dataReady', function( evt ) {
if ( !internal && fireSnapshot )
this.fire( 'saveSnapshot' );
if ( callback )
callback.call( evt.editor );
} );
}
// Fire "setData" so data manipulation may happen.
eventData = { dataValue: data };
!internal && this.fire( 'setData', eventData );
this._.data = eventData.dataValue;
!internal && this.fire( 'afterSetData', eventData );
},
我们可以看到里面的set过程实际是分三步
saveSnapshot主要是方便撤销操作的
// src/plugins/undo.plugin.js
// Save snapshots before doing custom changes.
editor.on( 'saveSnapshot', function( evt ) {
undoManager.save( evt.data && evt.data.contentOnly );
} );
我们接着看setData事件的处理
src/core/section.js
editor.on( 'setData', function() {
// Invalidate locked selection when unloading DOM.
// (https://dev.ckeditor.com/ticket/9521, https://dev.ckeditor.com/ticket/5217#comment:32 and https://dev.ckeditor.com/ticket/11500#comment:11)
editor.unlockSelection();
// Webkit's selection will mess up after the data loading.
if ( CKEDITOR.env.webkit )
clearSelection();
} );
我们可以看到,它做的工作主要是解锁选区,看来实际做工作的还不是setData啊,它算是一个setData的准备工作可能更合适些。
// src/core/editable.js
this.attachListener( editor, 'afterSetData', function() {
this.setData( editor.getData( 1 ) );
}, this );
没错,这里又有个一个setData和getData。。。原来他们才是真正的setData和getData啊。
// src/core/editable.js
/**
* @see CKEDITOR.editor#setData
*/
setData: function( data, isSnapshot ) {
if ( !isSnapshot )
data = this.editor.dataProcessor.toHtml( data );
this.setHtml( data );
this.fixInitialSelection();
// Editable is ready after first setData.
if ( this.status == 'unloaded' )
this.status = 'ready';
this.editor.fire( 'dataReady' );
},
/**
* @see CKEDITOR.editor#getData
*/
getData: function( isSnapshot ) {
var data = this.getHtml();
if ( !isSnapshot )
data = this.editor.dataProcessor.toDataFormat( data );
return data;
},
setHtml和getHtml本质就是原生node的innerHTML,所以setData和getData的过程其实就是 this.editor.dataProcessor.toHtml和this.editor.dataProcessor.toDataFormat的过程,这个两个方法哪来的?它们都源自dataProcessor,它是在编辑器初始化的时候赋值的。
// src/core/editor.js
// Various other core components that read editor configuration.
function initComponents( editor ) {
// Documented in dataprocessor.js.
editor.dataProcessor = new CKEDITOR.htmlDataProcessor( editor );
// Set activeFilter directly to avoid firing event.
editor.filter = editor.activeFilter = new CKEDITOR.filter( editor );
loadSkin( editor );
}
dataProcessor的两个具体方法如下
// src/core/dataProcessor.js
toHtml: function( data, options, fixForBody, dontFilter ) {
var editor = this.editor,
context, filter, enterMode, protectedWhitespaces;
// Typeof null == 'object', so check truthiness of options too.
if ( options && typeof options == 'object' ) {
context = options.context;
fixForBody = options.fixForBody;
dontFilter = options.dontFilter;
filter = options.filter;
enterMode = options.enterMode;
protectedWhitespaces = options.protectedWhitespaces;
}
// Backward compatibility. Since CKEDITOR 4.3.0 every option was a separate argument.
else {
context = options;
}
// Fall back to the editable as context if not specified.
if ( !context && context !== null )
context = editor.editable().getName();
return editor.fire( 'toHtml', {
dataValue: data,
context: context,
fixForBody: fixForBody,
dontFilter: dontFilter,
filter: filter || editor.filter,
enterMode: enterMode || editor.enterMode,
protectedWhitespaces: protectedWhitespaces
} ).dataValue;
},
toDataFormat: function( html, options ) {
var context, filter, enterMode;
// Do not shorten this to `options && options.xxx`, because
// falsy `options` will be passed instead of undefined.
if ( options ) {
context = options.context;
filter = options.filter;
enterMode = options.enterMode;
}
// Fall back to the editable as context if not specified.
if ( !context && context !== null )
context = this.editor.editable().getName();
return this.editor.fire( 'toDataFormat', {
dataValue: html,
filter: filter || this.editor.filter,
context: context,
enterMode: enterMode || this.editor.enterMode
} ).dataValue;
},
这两个方法的具体实现被化成对两个(toHtml和toDataFormat)事件的处理逻辑了。
这两个事件有哪些回调呢,先看toHtml。
// src/core/dataProcessor.js
editor.on( 'toHtml', function( evt ) {
var evtData = evt.data,
data = evtData.dataValue,
fixBodyTag;
// Before we start protecting markup, make sure there are no externally injected
// protection keywords.
data = removeReservedKeywords( data );
// The source data is already HTML, but we need to clean
// it up and apply the filter.
data = protectSource( data, editor );
// Protect content of textareas. (https://dev.ckeditor.com/ticket/9995)
// Do this before protecting attributes to avoid breaking:
// <textarea><img src="..." /></textarea>
data = protectElements( data, protectTextareaRegex );
// 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. (https://dev.ckeditor.com/ticket/3710)
data = protectElements( data, protectElementsRegex );
// Certain elements has problem to go through DOM operation, protect
// them by prefixing 'cke' namespace. (https://dev.ckeditor.com/ticket/3591)
data = protectElementsNames( data );
// All none-IE browsers ignore self-closed custom elements,
// protecting them into open-close. (https://dev.ckeditor.com/ticket/3591)
data = protectSelfClosingElements( data );
// Compensate one leading line break after <pre> open as browsers
// eat it up. (https://dev.ckeditor.com/ticket/5789)
data = protectPreFormatted( data );
// There are attributes which may execute JavaScript code inside fixBin.
// Encode them greedily. They will be unprotected right after getting HTML from fixBin. (https://dev.ckeditor.com/ticket/10)
data = protectInsecureAttributes( data );
var fixBin = evtData.context || editor.editable().getName(),
isPre;
// Old IEs loose formats when load html into <pre>.
if ( CKEDITOR.env.ie && CKEDITOR.env.version < 9 && fixBin == 'pre' ) {
fixBin = 'div';
data = '<pre>' + data + '</pre>';
isPre = 1;
}
// Call the browser to help us fixing a possibly invalid HTML
// structure.
var el = editor.document.createElement( fixBin );
// Add fake character to workaround IE comments bug. (https://dev.ckeditor.com/ticket/3801)
el.setHtml( 'a' + data );
data = el.getHtml().substr( 1 );
// Restore shortly protected attribute names.
data = data.replace( new RegExp( 'data-cke-' + CKEDITOR.rnd + '-', 'ig' ), '' );
isPre && ( data = data.replace( /^<pre>|<\/pre>$/gi, '' ) );
// 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 );
if ( evtData.fixForBody === false ) {
fixBodyTag = false;
} else {
fixBodyTag = getFixBodyTag( evtData.enterMode, editor.config.autoParagraph );
}
// Now use our parser to make further fixes to the structure, as
// well as apply the filter.
data = CKEDITOR.htmlParser.fragment.fromHtml( data, evtData.context, fixBodyTag );
// The empty root element needs to be fixed by adding 'p' or 'div' into it.
// This avoids the need to create that element on the first focus (https://dev.ckeditor.com/ticket/12630).
if ( fixBodyTag ) {
fixEmptyRoot( data, fixBodyTag );
}
evtData.dataValue = data;
}, null, null, 5 );
// Filter incoming "data".
// Add element filter before htmlDataProcessor.dataFilter when purifying input data to correct html.
editor.on( 'toHtml', function( evt ) {
if ( evt.data.filter.applyTo( evt.data.dataValue, true, evt.data.dontFilter, evt.data.enterMode ) )
editor.fire( 'dataFiltered' );
}, null, null, 6 );
editor.on( 'toHtml', function( evt ) {
evt.data.dataValue.filterChildren( that.dataFilter, true );
}, null, null, 10 );
editor.on( 'toHtml', function( evt ) {
var evtData = evt.data,
data = evtData.dataValue,
writer = new CKEDITOR.htmlParser.basicWriter();
data.writeChildrenHtml( writer );
data = writer.getHtml( true );
// Protect the real comments again.
evtData.dataValue = protectRealComments( data );
}, null, null, 15 );
我们可以看到这些回调里面最多的几个单词就是protect和filter,它们主要也是做这些工作。
再看看toDataFormat的回调
// src/core/dataProcessor.js
editor.on( 'toDataFormat', function( evt ) {
var data = evt.data.dataValue;
// https://dev.ckeditor.com/ticket/10854 - we need to strip leading blockless <br> which FF adds
// automatically when editable contains only non-editable content.
// We do that for every browser (so it's a constant behavior) and
// not in BR mode, in which chance of valid leading blockless <br> is higher.
if ( evt.data.enterMode != CKEDITOR.ENTER_BR )
data = data.replace( /^<br *\/?>/i, '' );
evt.data.dataValue = CKEDITOR.htmlParser.fragment.fromHtml(
data, evt.data.context, getFixBodyTag( evt.data.enterMode, editor.config.autoParagraph ) );
}, null, null, 5 );
editor.on( 'toDataFormat', function( evt ) {
evt.data.dataValue.filterChildren( that.htmlFilter, true );
}, null, null, 10 );
// Transform outcoming "data".
// Add element filter after htmlDataProcessor.htmlFilter when preparing output data HTML.
editor.on( 'toDataFormat', function( evt ) {
evt.data.filter.applyTo( evt.data.dataValue, false, true );
}, null, null, 11 );
editor.on( 'toDataFormat', function( evt ) {
var data = evt.data.dataValue,
writer = that.writer;
writer.reset();
data.writeChildrenHtml( writer );
data = writer.getHtml( true );
// Restore those non-HTML protected source. (https://dev.ckeditor.com/ticket/4475,https://dev.ckeditor.com/ticket/4880)
data = unprotectRealComments( data );
data = unprotectSource( data, editor );
evt.data.dataValue = data;
}, null, null, 15 );
编辑器内容的设置和获取表面上是简单只是调用一个方法就完成了,但是其实内部的流程还是很长的,大致分为:
击右上方,关注开源中国OSC头条号,获取最新技术资讯
CKEditor 5 v11.2.0 发布了,CKEditor 是一个网页在线文字编辑器,特点是高性能与可扩展。
此版本带来了期待已久的 Office 粘贴支持,例如可以直接复制 Microsoft Word 的文档,还集成了 CKFinder 文件上传器,此外,完善了图像上传文档,改进了移动设备上的 UI,并引入了许多其它功能和改进。
复制 Word 文档
此新功能允许粘贴 Microsoft Word 中的内容并保留原始结构和格式,包括基本文本样式、标题级别、链接、列表、表格和图像等。
集成 CKFinder
CKFinder 是一个文件管理器和上传器,它是 CKEditor 4 的一个关键特性,现在已经集成到了此版本的 CKEditor 5 中。集成之后允许将图像以及文件链接插入到编辑内容中。
其它变更
插件开发者需要关注一下,Position、Range 和 Writer 引擎类 API 已经发生变化。在此版本中,对 @ckeditor/ckeditor5-engine 软件包中的公共 API 进行了一些重大更改,view 和 model 中不再开放 Position 和 Range 类的各种方法,例如Position#createAt()、Position#createFromParentAndOffset()、Range#createIn() 和Range#createCollapsedAt()。它们已被相应的方法替换,例如 createPositionAt( parent, offset )、createRangeIn() 和createRange( position )。
比如之前的写法:
import Position from '@ckeditor/ckeditor5-engine/src/model/position'; import Range from '@ckeditor/ckeditor5-engine/src/model/range'; // ... editor.model.change( writer => { const imageElement = writer.createElement( 'image', { src: 'https://example.com/image.jpg' } ); // Insert the image at the current selection location. editor.model.insertContent( imageElement, editor.model.document.selection ); const paragraph = writer.createElement( 'paragraph' ); const insertPosition = Position.createAfter( imageElement ); writer.insert( paragraph, insertPosition ); // Set the selection in the <paragraph>. writer.setSelection( Range.createIn( paragraph ) ); } );
现在这样写:
// Imports from `@ckeditor/ckeditor5-engine` are no longer needed. // ... editor.model.change( writer => { const imageElement = writer.createElement( 'image', { src: 'https://example.com/image.jpg' } ); editor.model.insertContent( imageElement ); const paragraph = writer.createElement( 'paragraph' ); // Writer#createPositionAfter() instead of Position#createAfter(). const insertPosition = writer.createPositionAfter( imageElement ); writer.insert( paragraph, insertPosition ); // Writer#createRangeIn() instead of Range#createIn(). writer.setSelection( writer.createRangeIn( paragraph ) ); } );
移动设备上更好的 UI
改进的 UI 带有下拉面板定位,可确保下拉内容始终对用户可见。还使一些 UI 元素根据环境响应,例如,链接和图像文本替代小气球图标现在适应屏幕的大小,使触摸按钮更容易。
其它更新内容,点击下方“了解更多”,查看发布公告。
↓↓↓
KEditor 5 v23.1.0 稳定版已发布,主要更新内容包括:支持在编辑器嵌入原生 HTML 代码并进行渲染、改进 reconversion API 以及支持将表格内容粘贴到另一个表格。
嵌入 Raw HTML
此功能支持在编辑器中嵌入任意 HTML 代码片段,因此用户可以嵌入其他 CKEditor 5 功能不支持的 HTML 代码,并绕过编辑器的过滤机制。
因此该功能具有一定的风险,因为错误的配置可能会导致安全问题。在启用 HTML 嵌入内容预览功能前,请始终使用 sanitizer ,并使用 CSP 额外保护网站。
详细用法查看使用文档。
将表格内容粘贴到另一个表格
支持多种情况:
其他改进和 bugfix
*请认真填写需求信息,我们会在24小时内与您取得联系。