修复编辑器插件缺少问题

This commit is contained in:
2019-03-06 01:03:19 +08:00
parent 03fbfc3688
commit a8eca37bba
9 changed files with 2931 additions and 0 deletions
@@ -0,0 +1,187 @@
/* global ActiveXObject */
/**
* @license Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
/**
* @fileOverview Defines the {@link CKEDITOR.ajax} object, which stores Ajax methods for
* data loading.
*/
( function() {
CKEDITOR.plugins.add( 'ajax', {
requires: 'xml'
} );
/**
* Ajax methods for data loading.
*
* @class
* @singleton
*/
CKEDITOR.ajax = ( function() {
function createXMLHttpRequest() {
// 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;
}
function checkStatus( 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 ) );
}
function getResponseText( xhr ) {
if ( checkStatus( xhr ) )
return xhr.responseText;
return null;
}
function getResponseXml( xhr ) {
if ( checkStatus( xhr ) ) {
var xml = xhr.responseXML;
return new CKEDITOR.xml( xml && xml.firstChild ? xml : xhr.responseText );
}
return null;
}
function load( 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.
xhr.onreadystatechange = function() {
if ( xhr.readyState == 4 ) {
callback( getResponseFn( xhr ) );
xhr = null;
}
};
}
xhr.send( null );
return async ? '' : getResponseFn( xhr );
}
function post( url, data, contentType, callback, getResponseFn ) {
var xhr = createXMLHttpRequest();
if ( !xhr )
return null;
xhr.open( 'POST', url, true );
xhr.onreadystatechange = function() {
if ( xhr.readyState == 4 ) {
if ( callback ) {
callback( getResponseFn( xhr ) );
}
xhr = null;
}
};
xhr.setRequestHeader( 'Content-type', contentType || 'application/x-www-form-urlencoded; charset=UTF-8' );
xhr.send( data );
}
return {
/**
* Loads data from a URL as plain text.
*
* // Load data synchronously.
* var data = CKEDITOR.ajax.load( 'somedata.txt' );
* alert( data );
*
* // Load data asynchronously.
* var data = CKEDITOR.ajax.load( 'somedata.txt', function( data ) {
* alert( data );
* } );
*
* @param {String} url The URL from which the data is loaded.
* @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`.
*/
load: function( url, callback ) {
return load( url, callback, getResponseText );
},
/**
* Creates an asynchronous POST `XMLHttpRequest` of the given `url`, `data` and optional `contentType`.
* Once the request is done, regardless if it is successful or not, the `callback` is called
* with `XMLHttpRequest#responseText` or `null` as an argument.
*
* CKEDITOR.ajax.post( 'url/post.php', 'foo=bar', null, function( data ) {
* console.log( data );
* } );
*
* CKEDITOR.ajax.post( 'url/post.php', JSON.stringify( { foo: 'bar' } ), 'application/json', function( data ) {
* console.log( data );
* } );
*
* @since 4.4
* @param {String} url The URL of the request.
* @param {String/Object/Array} data Data passed to `XMLHttpRequest#send`.
* @param {String} [contentType='application/x-www-form-urlencoded; charset=UTF-8'] The value of the `Content-type` header.
* @param {Function} [callback] A callback executed asynchronously with `XMLHttpRequest#responseText` or `null` as an argument,
* depending on the `status` of the request.
*/
post: function( url, data, contentType, callback ) {
return post( url, data, contentType, callback, getResponseText );
},
/**
* Loads data from a URL as XML.
*
* // Load XML synchronously.
* var xml = CKEDITOR.ajax.loadXml( 'somedata.xml' );
* alert( xml.getInnerXml( '//' ) );
*
* // Load XML asynchronously.
* var data = CKEDITOR.ajax.loadXml( 'somedata.xml', function( xml ) {
* alert( xml.getInnerXml( '//' ) );
* } );
*
* @param {String} url The URL from which the data is loaded.
* @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 storing the loaded data. For asynchronous requests, an
* empty string. For invalid requests, `null`.
*/
loadXml: function( url, callback ) {
return load( url, callback, getResponseXml );
}
};
} )();
} )();
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,162 @@
<!DOCTYPE html>
<!--
Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
-->
<html>
<head>
<meta charset="utf-8">
<title>Autocomplete Custom View &mdash; CKEditor Sample</title>
<script src="../../../ckeditor.js"></script>
<script src="utils.js"></script>
<link rel="stylesheet" href="../../../samples/css/samples.css">
<link href="../skins/moono/autocomplete.css" rel="stylesheet">
</head>
<body>
<style>
.adjoined-bottom:before {
height: 270px;
}
</style>
<nav class="navigation-a">
<div class="grid-container">
<ul class="navigation-a-left grid-width-70">
<li><a href="https://ckeditor.com">Project Homepage</a></li>
<li><a href="https://github.com/ckeditor/ckeditor-dev/issues">I found a bug</a></li>
<li><a href="https://github.com/ckeditor/ckeditor-dev" class="icon-pos-right icon-navigation-a-github">Fork CKEditor on GitHub</a></li>
</ul>
<ul class="navigation-a-right grid-width-30">
<li><a href="https://ckeditor.com/blog/">CKEditor Blog</a></li>
</ul>
</div>
</nav>
<header class="header-a">
<div class="grid-container">
<h1 class="header-a-logo grid-width-30">
<img src="../../../samples/img/logo.svg" onerror="this.src='../../../samples/img/logo.png'; this.onerror=null;" alt="CKEditor Sample">
</h1>
</div>
</header>
<main>
<div class="adjoined-top">
<div class="grid-container">
<div class="content grid-width-100">
<h1>Autocomplete Custom View Demo</h1>
<p>This sample shows the progress of work on Autocomplete with custom View. Type &#8220; @ &#8221; (at least 2 characters) to start autocompletion.</p>
</div>
</div>
</div>
<div class="adjoined-bottom">
<div class="grid-container">
<div class="grid-width-100">
<div id="editor">
<h1>Apollo 11</h1>
<figure class="image easyimage">
<img alt="Saturn V carrying Apollo 11" src="../../../samples/img/logo.png">
</figure>
<p><strong>Apollo 11</strong> was the spaceflight that landed the first humans, Americans <a href="http://en.wikipedia.org/wiki/Neil_Armstrong">Neil Armstrong</a> and <a href="http://en.wikipedia.org/wiki/Buzz_Aldrin">Buzz Aldrin</a>, on the Moon on July 20, 1969, at 20:18 UTC. Armstrong became the first to step onto the lunar surface 6 hours later on July 21 at 02:56 UTC.</p>
<figure class="easyimage easyimage-side">
<img alt="Saturn V carrying Apollo 11" src="../../image2/samples/assets/image1.jpg">
<figcaption>Saturn V carrying Apollo 11</figcaption>
</figure>
<p>Armstrong spent about <s>three and a half</s> two and a half hours outside the spacecraft, Aldrin slightly less; and together they collected 47.5 pounds (21.5&nbsp;kg) of lunar material for return to Earth. A third member of the mission, <a href="http://en.wikipedia.org/wiki/Michael_Collins_(astronaut)">Michael Collins</a>, piloted the <a href="http://en.wikipedia.org/wiki/Apollo_Command/Service_Module">command</a> spacecraft alone in lunar orbit until Armstrong and Aldrin returned to it for the trip back to Earth.</p>
</div>
</div>
</div>
</div>
</main>
<footer class="footer-a grid-container">
<div class="grid-container">
<p class="grid-width-100">
CKEditor &ndash; The text editor for the Internet &ndash; <a class="samples" href="https://ckeditor.com/">https://ckeditor.com</a>
</p>
<p class="grid-width-100" id="copy">
Copyright &copy; 2003-2019, <a class="samples" href="https://cksource.com/">CKSource</a> &ndash; Frederico Knabben. All rights reserved.
</p>
</div>
</footer>
<script>
'use strict';
( function() {
// For simplicity we define the plugin in the sample, but normally
// it would be extracted to a separate file.
CKEDITOR.plugins.add( 'customautocomplete', {
requires: 'autocomplete',
onLoad: function() {
var View = CKEDITOR.plugins.autocomplete.view,
Autocomplete = CKEDITOR.plugins.autocomplete;
function CustomView( editor ) {
// Call the parent class constructor.
View.call( this, editor );
}
// Inherit the view methods.
CustomView.prototype = CKEDITOR.tools.prototypedCopy( View.prototype );
// Change the positioning of the panel, so it is stretched
// to 100% of the editor container width and is positioned
// according to the editor container.
CustomView.prototype.updatePosition = function( range ) {
var caretRect = this.getViewPosition( range ),
container = this.editor.container;
this.setPosition( {
// Position the panel according to the editor container.
left: container.$.offsetLeft,
top: caretRect.top,
bottom: caretRect.bottom
} );
// Stretch the panel to 100% of the editor container width.
this.element.setStyle( 'width', container.getSize( 'width' ) + 'px' );
};
function CustomAutocomplete( editor, textTestCallback, dataCallback ) {
// Call the parent class constructor.
Autocomplete.call( this, editor, textTestCallback, dataCallback );
}
// Inherit the autocomplete methods.
CustomAutocomplete.prototype = CKEDITOR.tools.prototypedCopy( Autocomplete.prototype );
CustomAutocomplete.prototype.getView = function() {
return new CustomView( this.editor );
}
// Expose the custom autocomplete so it can be used later.
CKEDITOR.plugins.customAutocomplete = CustomAutocomplete;
}
} );
var editor = CKEDITOR.replace( 'editor', {
height: 600,
extraPlugins: 'customautocomplete,autocomplete,textmatch,easyimage,sourcearea,toolbar,undo,wysiwygarea,basicstyles',
toolbar: [
{ name: 'document', items: [ 'Source', 'Undo', 'Redo' ] },
{ name: 'basicstyles', items: [ 'Bold', 'Italic', 'Strike' ] },
]
} );
editor.on( 'instanceReady', function() {
var prefix = '@',
minChars = 2,
requireSpaceAfter = true,
data = autocompleteUtils.generateData( CKEDITOR.dom.element.prototype, prefix );
// Use the custom autocomplete class.
new CKEDITOR.plugins.customAutocomplete(
editor,
autocompleteUtils.getTextTestCallback( prefix, minChars, requireSpaceAfter ),
autocompleteUtils.getAsyncDataCallback( data )
);
} );
} )();
</script>
</body>
</html>
@@ -0,0 +1,172 @@
<!DOCTYPE html>
<!--
Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
-->
<html>
<head>
<meta charset="utf-8">
<title>Autocomplete Smileys &mdash; CKEditor Sample</title>
<script src="../../../ckeditor.js"></script>
<script src="utils.js"></script>
<link rel="stylesheet" href="../../../samples/css/samples.css">
<link href="../skins/moono/autocomplete.css" rel="stylesheet">
</head>
<body>
<style>
.adjoined-bottom:before {
height: 270px;
}
.cke_autocomplete_icon
{
vertical-align: middle;
}
</style>
<nav class="navigation-a">
<div class="grid-container">
<ul class="navigation-a-left grid-width-70">
<li><a href="https://ckeditor.com">Project Homepage</a></li>
<li><a href="https://github.com/ckeditor/ckeditor-dev/issues">I found a bug</a></li>
<li><a href="https://github.com/ckeditor/ckeditor-dev" class="icon-pos-right icon-navigation-a-github">Fork CKEditor on GitHub</a></li>
</ul>
<ul class="navigation-a-right grid-width-30">
<li><a href="https://ckeditor.com/blog/">CKEditor Blog</a></li>
</ul>
</div>
</nav>
<header class="header-a">
<div class="grid-container">
<h1 class="header-a-logo grid-width-30">
<img src="../../../samples/img/logo.svg" onerror="this.src='../../../samples/img/logo.png'; this.onerror=null;" alt="CKEditor Sample">
</h1>
</div>
</header>
<main>
<div class="adjoined-top">
<div class="grid-container">
<div class="content grid-width-100">
<h1>Autocomplete Smileys Demo</h1>
<p>This sample shows the progress of work on Autocomplete with Smileys integration. Type &#8220; : &#8221; to start smileys autocompletion.</p>
</div>
</div>
</div>
<div class="adjoined-bottom">
<div class="grid-container">
<div class="grid-width-100">
<div id="editor">
<h1>Apollo 11</h1>
<figure class="image easyimage">
<img alt="Saturn V carrying Apollo 11" src="../../../samples/img/logo.png">
</figure>
<p><strong>Apollo 11</strong> was the spaceflight that landed the first humans, Americans <a href="http://en.wikipedia.org/wiki/Neil_Armstrong">Neil Armstrong</a> and <a href="http://en.wikipedia.org/wiki/Buzz_Aldrin">Buzz Aldrin</a>, on the Moon on July 20, 1969, at 20:18 UTC. Armstrong became the first to step onto the lunar surface 6 hours later on July 21 at 02:56 UTC.</p>
<figure class="easyimage easyimage-side">
<img alt="Saturn V carrying Apollo 11" src="../../image2/samples/assets/image1.jpg">
<figcaption>Saturn V carrying Apollo 11</figcaption>
</figure>
<p>Armstrong spent about <s>three and a half</s> two and a half hours outside the spacecraft, Aldrin slightly less; and together they collected 47.5 pounds (21.5&nbsp;kg) of lunar material for return to Earth. A third member of the mission, <a href="http://en.wikipedia.org/wiki/Michael_Collins_(astronaut)">Michael Collins</a>, piloted the <a href="http://en.wikipedia.org/wiki/Apollo_Command/Service_Module">command</a> spacecraft alone in lunar orbit until Armstrong and Aldrin returned to it for the trip back to Earth.</p>
</div>
</div>
</div>
</div>
</main>
<footer class="footer-a grid-container">
<div class="grid-container">
<p class="grid-width-100">
CKEditor &ndash; The text editor for the Internet &ndash; <a class="samples" href="https://ckeditor.com/">https://ckeditor.com</a>
</p>
<p class="grid-width-100" id="copy">
Copyright &copy; 2003-2019, <a class="samples" href="https://cksource.com/">CKSource</a> &ndash; Frederico Knabben. All rights reserved.
</p>
</div>
</footer>
<script>
'use strict';
( function() {
// For simplicity we define the plugin in the sample, but normally
// it would be extracted to a separate file.
CKEDITOR.plugins.add( 'smileyautocomplete', {
requires: 'autocomplete,textmatch,smiley',
onLoad: function() {
var that = this,
View = CKEDITOR.plugins.autocomplete.view,
Autocomplete = CKEDITOR.plugins.autocomplete;
function SmileyView( editor ) {
// Call the parent class constructor.
View.call( this, editor );
this.itemTemplate = new CKEDITOR.template(
'<li data-id="{id}"><img src="{src}" alt="{id}" class="cke_autocomplete_icon"> {name}</li>'
);
}
// Inherit the view methods.
SmileyView.prototype = CKEDITOR.tools.prototypedCopy( View.prototype );
function SmileyAutocomplete( editor ) {
var data = that.getData( editor );
// Call the parent class constructor.
Autocomplete.call(
this, editor,
autocompleteUtils.getTextTestCallback( ':', 0, false ),
autocompleteUtils.getSyncDataCallback( data )
);
}
// Inherit the autocomplete methods.
SmileyAutocomplete.prototype = CKEDITOR.tools.prototypedCopy( Autocomplete.prototype );
SmileyAutocomplete.prototype.getHtmlToInsert = function( item ) {
return '<img src=' + item.src + ' alt="' + item.id + '" />';
};
SmileyAutocomplete.prototype.getView = function() {
return new SmileyView( this.editor );
}
// Expose the smiley autocomplete so it can be used later.
CKEDITOR.plugins.smileyAutocomplete = SmileyAutocomplete;
},
getData: function( editor ) {
var descriptions = editor.config.smiley_descriptions,
images = editor.config.smiley_images,
path = editor.config.smiley_path,
data = [];
for ( var i = 0; i < descriptions.length; ++i ) {
data.push( {
id: descriptions[ i ],
name: ':' + descriptions[ i ],
src: CKEDITOR.tools.htmlEncode( path + images[ i ] )
} );
}
return data;
}
} );
var editor = CKEDITOR.replace( 'editor', {
height: 600,
extraPlugins: 'smileyautocomplete,autocomplete,textmatch,easyimage,sourcearea,toolbar,undo,wysiwygarea,basicstyles',
toolbar: [
{ name: 'document', items: [ 'Source', 'Undo', 'Redo' ] },
{ name: 'basicstyles', items: [ 'Bold', 'Italic', 'Strike' ] },
]
} );
editor.on( 'instanceReady', function() {
// Use the smiley autocomplete class.
new CKEDITOR.plugins.smileyAutocomplete( editor );
} );
} )();
</script>
</body>
</html>
@@ -0,0 +1,97 @@
/**
* @license Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
/* exported autocompleteUtils */
'use strict';
var autocompleteUtils = {
generateData: function( object, prefix ) {
return Object.keys( object ).sort().map( function( prop, index ) {
return {
id: index,
name: prefix + prop
};
} );
},
getAsyncDataCallback: function( data ) {
return function( query, range, callback ) {
setTimeout( function() {
callback(
data.filter( function( item ) {
return item.name.indexOf( query ) === 0;
} )
);
}, Math.random() * 500 );
};
},
getSyncDataCallback: function( data ) {
return function( query, range, callback ) {
callback(
data.filter( function( item ) {
return item.name.indexOf( query ) === 0;
} )
);
};
},
getTextTestCallback: function( prefix, minChars, requireSpaceAfter ) {
var matchPattern = createPattern();
return function( range ) {
if ( !range.collapsed ) {
return null;
}
return CKEDITOR.plugins.textMatch.match( range, matchCallback );
};
function matchCallback( text, offset ) {
var left = text.slice( 0, offset ),
right = text.slice( offset ),
match = left.match( matchPattern );
if ( !match ) {
return null;
}
if ( requireSpaceAfter ) {
// Require space (or end of text) after the caret.
if ( right && !right.match( /^\s/ ) ) {
return null;
}
}
return { start: match.index, end: offset };
}
function createPattern() {
var pattern = prefix + '\\w';
if ( minChars ) {
pattern += '{' + minChars + ',}';
} else {
pattern += '*';
}
pattern += '$';
return new RegExp( pattern );
}
}
};
@@ -0,0 +1,38 @@
/*
Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
.cke_autocomplete_panel
{
position: absolute;
display: none;
box-sizing: border-box;
width: 200px;
max-height: 300px;
overflow: auto;
padding: 0;
margin: 0;
list-style: none;
background: #FFF;
border: 1px solid #b6b6b6;
border-bottom-color: #999;
border-radius: 3px;
font: 12px Arial, Helvetica, Tahoma, Verdana, Sans-Serif;
}
.cke_autocomplete_opened
{
display: block;
}
.cke_autocomplete_panel > li
{
padding: 5px;
}
.cke_autocomplete_panel > li:hover
{
cursor: pointer;
}
.cke_autocomplete_selected, .cke_autocomplete_panel > li:hover
{
background-color: #EFF0EF;
}
@@ -0,0 +1,331 @@
/**
* @license Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
'use strict';
( function() {
CKEDITOR.plugins.add( 'textmatch', {} );
/**
* A global namespace for methods exposed by the [Text Match](https://ckeditor.com/cke4/addon/textmatch) plugin.
*
* The most important function is {@link #match} which performs a text
* search in the DOM.
*
* @singleton
* @class
* @since 4.10.0
*/
CKEDITOR.plugins.textMatch = {};
/**
* Allows to search in the DOM for matching text using a callback which operates on strings instead of text nodes.
* Returns {@link CKEDITOR.dom.range} and the matching text.
*
* ```javascript
* var range = editor.getSelection().getRanges()[ 0 ];
*
* CKEDITOR.plugins.textMatch.match( range, function( text, offset ) {
* // Let's assume that text is 'Special thanks to #jo.' and offset is 21.
* // The offset "21" means that the caret is between '#jo' and '.'.
*
* // Get the text before the caret.
* var left = text.slice( 0, offset ),
* // Will look for a literal '#' character and at least two word characters.
* match = left.match( /#\w{2,}$/ );
*
* if ( !match ) {
* return null;
* }
*
* // The matching fragment is the '#jo', which can
* // be identified by the following offsets: { start: 18, end: 21 }.
* return { start: match.index, end: offset };
* } );
* ```
*
* @member CKEDITOR.plugins.textMatch
* @param {CKEDITOR.dom.range} range A collapsed range &mdash; the position from which the scanning starts.
* Usually the caret position.
* @param {Function} testCallback A callback executed to check if the text matches.
* @param {String} testCallback.text The full text to check.
* @param {Number} testCallback.rangeOffset An offset of the `range` in the `text` to be checked.
* @param {Object} [testCallback.return] The position of the matching fragment (`null` if nothing matches).
* @param {Number} testCallback.return.start The offset of the start of the matching fragment.
* @param {Number} testCallback.return.end The offset of the end of the matching fragment.
*
* @returns {Object/null} An object with information about the matching text or `null`.
* @returns {String} return.text The matching text.
* The text does not reflect the range offsets. The range could contain additional,
* browser-related characters like {@link CKEDITOR.dom.selection#FILLING_CHAR_SEQUENCE}.
* @returns {CKEDITOR.dom.range} return.range A range in the DOM for the text that matches.
*/
CKEDITOR.plugins.textMatch.match = function( range, callback ) {
var textAndOffset = CKEDITOR.plugins.textMatch.getTextAndOffset( range ),
fillingCharSequence = CKEDITOR.dom.selection.FILLING_CHAR_SEQUENCE,
fillingSequenceOffset = 0;
if ( !textAndOffset ) {
return;
}
// Remove filling char sequence for clean query (#2038).
if ( textAndOffset.text.indexOf( fillingCharSequence ) == 0 ) {
fillingSequenceOffset = fillingCharSequence.length;
textAndOffset.text = textAndOffset.text.replace( fillingCharSequence, '' );
textAndOffset.offset -= fillingSequenceOffset;
}
var result = callback( textAndOffset.text, textAndOffset.offset );
if ( !result ) {
return null;
}
return {
range: CKEDITOR.plugins.textMatch.getRangeInText( range, result.start, result.end + fillingSequenceOffset ),
text: textAndOffset.text.slice( result.start, result.end )
};
};
/**
* Returns a text (as a string) in which the DOM range is located (the function scans for adjacent text nodes)
* and the offset of the caret in that text.
*
* ## Examples
*
* * `{}` is the range position in the text node (it means that the text node is **not** split at that position).
* * `[]` is the range position in the element (it means that the text node is split at that position).
* * `.` is a separator for text nodes (it means that the text node is split at that position).
*
* Examples:
*
* ```
* Input: <p>he[]llo</p>
* Result: { text: 'hello', offset: 2 }
*
* Input: <p>he.llo{}</p>
* Result: { text: 'hello', offset: 5 }
*
* Input: <p>{}he.ll<i>o</i></p>
* Result: { text: 'hell', offset: 0 }
*
* Input: <p>he{}<i>ll</i>o</p>
* Result: { text: 'he', offset: 2 }
*
* Input: <p>he<i>ll</i>o.m{}y.friend</p>
* Result: { text: 'omyfriend', offset: 2 }
* ```
*
* @member CKEDITOR.plugins.textMatch
* @param {CKEDITOR.dom.range} range
* @returns {Object/null}
* @returns {String} return.text The text in which the DOM range is located.
* @returns {Number} return.offset An offset of the caret.
*/
CKEDITOR.plugins.textMatch.getTextAndOffset = function( range ) {
if ( !range.collapsed ) {
return null;
}
var text = '', offset = 0,
textNodes = CKEDITOR.plugins.textMatch.getAdjacentTextNodes( range ),
nodeReached = false,
elementIndex,
startContainerIsText = ( range.startContainer.type != CKEDITOR.NODE_ELEMENT );
if ( startContainerIsText ) {
// Determining element index in textNodes array.
elementIndex = indexOf( textNodes, function( current ) {
return range.startContainer.equals( current );
} );
} else {
// Based on range startOffset decreased by first text node index.
elementIndex = range.startOffset - ( textNodes[ 0 ] ? textNodes[ 0 ].getIndex() : 0 );
}
var max = textNodes.length;
for ( var i = 0; i < max; i += 1 ) {
var currentNode = textNodes[ i ];
text += currentNode.getText();
// We want to increase text offset only when startContainer is not reached.
if ( !nodeReached ) {
if ( startContainerIsText ) {
if ( i == elementIndex ) {
nodeReached = true;
offset += range.startOffset;
} else {
offset += currentNode.getText().length;
}
} else {
if ( i == elementIndex ) {
nodeReached = true;
}
// In below example there are three text nodes in p element and four possible offsets ( 0, 1, 2, 3 )
// We are going to increase offset while iteration:
// index 0 ==> 0
// index 1 ==> 3
// index 2 ==> 3 + 3
// index 3 ==> 3 + 3 + 2
// <p> foo bar ba </p>
// 0^^^1^^^2^^3
if ( i > 0 ) {
offset += textNodes[ i - 1 ].getText().length;
}
// If element index at last element we also want to increase offset.
if ( max == elementIndex && i + 1 == max ) {
offset += currentNode.getText().length;
}
}
}
}
return {
text: text,
offset: offset
};
};
/**
* Transforms the `start` and `end` offsets in the text generated by the {@link #getTextAndOffset}
* method into a DOM range.
*
* ## Examples
*
* * `{}` is the range position in the text node (it means that the text node is **not** split at that position).
* * `.` is a separator for text nodes (it means that the text node is split at that position).
*
* Examples:
*
* ```
* Input: <p>f{}oo.bar</p>, 0, 3
* Result: <p>{foo}.bar</p>
*
* Input: <p>f{}oo.bar</p>, 1, 5
* Result: <p>f{oo.ba}r</p>
* ```
*
* @member CKEDITOR.plugins.textMatch
* @param {CKEDITOR.dom.range} range
* @param {Number} start A start offset.
* @param {Number} end An end offset.
* @returns {CKEDITOR.dom.range} Transformed range.
*/
CKEDITOR.plugins.textMatch.getRangeInText = function( range, start, end ) {
var resultRange = new CKEDITOR.dom.range( range.root ),
elements = CKEDITOR.plugins.textMatch.getAdjacentTextNodes( range ),
startData = findElementAtOffset( elements, start ),
endData = findElementAtOffset( elements, end );
resultRange.setStart( startData.element, startData.offset );
resultRange.setEnd( endData.element, endData.offset );
return resultRange;
};
/**
* Creates a collection of adjacent text nodes which are between DOM elements, starting from the given range.
* This function works only for collapsed ranges.
*
* ## Examples
*
* * `{}` is the range position in the text node (it means that the text node is **not** split at that position).
* * `.` is a separator for text nodes (it means that the text node is split at that position).
*
* Examples:
*
* ```
* Input: <p>he.llo{}</p>
* Result: [ 'he', 'llo' ]
*
* Input: <p>{}he.ll<i>o</i></p>
* Result: [ 'he', 'll' ]
*
* Input: <p>he{}<i>ll</i>o.</p>
* Result: [ 'he' ]
*
* Input: <p>he<i>ll</i>{}o.my.friend</p>
* Result: [ 'o', 'my', 'friend' ]
* ```
*
* @member CKEDITOR.plugins.textMatch
* @param {CKEDITOR.dom.range} range
* @return {CKEDITOR.dom.text[]} An array of text nodes.
*/
CKEDITOR.plugins.textMatch.getAdjacentTextNodes = function( range ) {
if ( !range.collapsed ) {
throw new Error( 'Range must be collapsed.' ); // %REMOVE_LINE%
// Reachable in prod mode.
return []; // jshint ignore:line
}
var collection = [],
siblings,
elementIndex,
node, i;
if ( range.startContainer.type != CKEDITOR.NODE_ELEMENT ) {
siblings = range.startContainer.getParent().getChildren();
elementIndex = range.startContainer.getIndex();
} else {
siblings = range.startContainer.getChildren();
elementIndex = range.startOffset;
}
i = elementIndex;
while ( node = siblings.getItem( --i ) ) {
if ( node.type == CKEDITOR.NODE_TEXT ) {
collection.unshift( node );
} else {
break;
}
}
i = elementIndex;
while ( node = siblings.getItem( i++ ) ) {
if ( node.type == CKEDITOR.NODE_TEXT ) {
collection.push( node );
} else {
break;
}
}
return collection;
};
function findElementAtOffset( elements, offset ) {
var max = elements.length,
currentOffset = 0;
for ( var i = 0; i < max; i += 1 ) {
var current = elements[ i ];
if ( offset >= currentOffset && currentOffset + current.getText().length >= offset ) {
return {
element: current,
offset: offset - currentOffset
};
}
currentOffset += current.getText().length;
}
return null;
}
function indexOf( arr, checker ) {
for ( var i = 0; i < arr.length; i++ ) {
if ( checker( arr[ i ] ) ) {
return i;
}
}
return -1;
}
} )();
@@ -0,0 +1,295 @@
/**
* @license Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
'use strict';
( function() {
CKEDITOR.plugins.add( 'textwatcher', {} );
/**
* API exposed by the [Text Watcher](https://ckeditor.com/cke4/addon/textwatcher) plugin.
*
* Class implementing the text watcher &mdash; a base for features like
* autocomplete. It fires the {@link #matched} and {@link #unmatched} events
* based on changes in the text and the position of the caret in the editor.
*
* To check whether the text matches some criteria, the text watcher uses
* a callback function which should return the matching text and a {@link CKEDITOR.dom.range}
* for that text.
*
* Since the text watcher works on the DOM where searching for text
* is pretty complicated, it is usually recommended to use the {@link CKEDITOR.plugins.textMatch#match}
* function.
*
* Example:
*
* ```javascript
* function textTestCallback( range ) {
* // You do not want to autocomplete a non-empty selection.
* if ( !range.collapsed ) {
* return null;
* }
*
* // Use the text match plugin which does the tricky job of doing
* // a text search in the DOM. The matchCallback function should return
* // a matching fragment of the text.
* return CKEDITOR.plugins.textMatch.match( range, matchCallback );
* }
*
* function matchCallback( text, offset ) {
* // Get the text before the caret.
* var left = text.slice( 0, offset ),
* // Will look for an '@' character followed by word characters.
* match = left.match( /@\w*$/ );
*
* if ( !match ) {
* return null;
* }
* return { start: match.index, end: offset };
* }
*
* // Initialize the text watcher.
* var textWatcher = new CKEDITOR.plugins.textWatcher( editor, textTestCallback );
* // Start listening.
* textWatcher.attach();
*
* // Handle text matching.
* textWatcher.on( 'matched', function( evt ) {
* autocomplete.setQuery( evt.data.text );
* } );
* ```
*
* @class CKEDITOR.plugins.textWatcher
* @since 4.10.0
* @mixins CKEDITOR.event
* @constructor Creates the text watcher instance.
* @param {CKEDITOR.editor} editor The editor instance to watch in.
* @param {Function} callback Callback executed when the text watcher
* thinks that something might have changed.
* @param {Number} [throttle=0] Throttle interval, see {@link #throttle}.
* @param {CKEDITOR.dom.range} callback.range The range representing the caret position.
* @param {Object} [callback.return=null] Matching text data (`null` if nothing matches).
* @param {String} callback.return.text The matching text.
* @param {CKEDITOR.dom.range} callback.return.range A range in the DOM for the text that matches.
*/
function TextWatcher( editor, callback, throttle ) {
/**
* The editor instance which the text watcher watches.
*
* @readonly
* @property {CKEDITOR.editor}
*/
this.editor = editor;
/**
* The last matched text.
*
* @readonly
* @property {String}
*/
this.lastMatched = null;
/**
* Whether the next check should be ignored. See the {@link #consumeNext} method.
*
* @readonly
*/
this.ignoreNext = false;
/**
* The callback passed to the {@link CKEDITOR.plugins.textWatcher} constructor.
*
* @readonly
* @property {Function}
*/
this.callback = callback;
/**
* Keys that should be ignored by the {@link #check} method.
*
* @readonly
* @property {Number[]}
*/
this.ignoredKeys = [
16, // Shift
17, // Ctrl
18, // Alt
91, // Cmd
35, // End
36, // Home
37, // Left
38, // Up
39, // Right
40, // Down
33, // PageUp
34 // PageUp
];
/**
* Listeners registered by this text watcher.
*
* @private
*/
this._listeners = [];
/**
* Indicates throttle threshold mitigating text checks.
*
* Higher levels of the throttle threshold will create a delay for text watcher checks
* but also improve its performance.
*
* See the {@link CKEDITOR.tools#throttle throttle} feature for more information.
*
* @readonly
* @property {Number} [throttle=0]
*/
this.throttle = throttle || 0;
/**
* The {@link CKEDITOR.tools#throttle throttle buffer} used to mitigate text checks.
*
* @private
*/
this._buffer = CKEDITOR.tools.throttle( this.throttle, testTextMatch, this );
/**
* Event fired when the text is no longer matching.
*
* @event matched
* @param {Object} data The value returned by the {@link #callback}.
* @param {String} data.text
* @param {CKEDITOR.dom.range} data.range
*/
/**
* Event fired when the text stops matching.
*
* @event unmatched
*/
function testTextMatch( selectionRange ) {
var matched = this.callback( selectionRange );
if ( matched ) {
if ( matched.text == this.lastMatched ) {
return;
}
this.lastMatched = matched.text;
this.fire( 'matched', matched );
} else if ( this.lastMatched ) {
this.unmatch();
}
}
}
TextWatcher.prototype = {
/**
* Attaches the text watcher to the {@link #editor}.
*
* @chainable
*/
attach: function() {
var editor = this.editor;
this._listeners.push( editor.on( 'contentDom', onContentDom, this ) );
this._listeners.push( editor.on( 'blur', unmatch, this ) );
this._listeners.push( editor.on( 'beforeModeUnload', unmatch, this ) );
this._listeners.push( editor.on( 'setData', unmatch, this ) );
this._listeners.push( editor.on( 'afterCommandExec', unmatch, this ) );
// Attach if editor is already initialized.
if ( editor.editable() ) {
onContentDom.call( this );
}
return this;
function onContentDom() {
var editable = editor.editable();
this._listeners.push( editable.attachListener( editable, 'keyup', check, this ) );
}
// CKEditor's event system has a limitation that one function (in this case this.check)
// cannot be used as listener for the same event more than once. Hence, wrapper function.
function check( evt ) {
this.check( evt );
}
function unmatch() {
this.unmatch();
}
},
/**
* Triggers a text check. Fires the {@link #matched} and {@link #unmatched} events.
* The {@link #matched} event will not be fired twice in a row for the same text
* unless the text watcher is {@link #unmatch reset}.
*
* @param {CKEDITOR.dom.event/CKEDITOR.eventInfo} [evt]
*/
check: function( evt ) {
if ( this.ignoreNext ) {
this.ignoreNext = false;
return;
}
// Ignore control keys, so they don't trigger the check.
if ( evt && evt.name == 'keyup' && ( CKEDITOR.tools.array.indexOf( this.ignoredKeys, evt.data.getKey() ) != -1 ) ) {
return;
}
var sel = this.editor.getSelection();
if ( !sel ) {
return;
}
var selectionRange = sel.getRanges()[ 0 ];
if ( !selectionRange ) {
return;
}
this._buffer.input( selectionRange );
},
/**
* Ignores the next {@link #check}.
*
* @chainable
*/
consumeNext: function() {
this.ignoreNext = true;
return this;
},
/**
* Resets the state and fires the {@link #unmatched} event.
*
* @chainable
*/
unmatch: function() {
this.lastMatched = null;
this.fire( 'unmatched' );
return this;
},
/**
* Destroys the text watcher instance. The DOM event listeners will be cleaned up.
*/
destroy: function() {
CKEDITOR.tools.array.forEach( this._listeners, function( obj ) {
obj.removeListener();
} );
this._listeners = [];
}
};
CKEDITOR.event.implementOn( TextWatcher.prototype );
CKEDITOR.plugins.textWatcher = TextWatcher;
} )();
@@ -0,0 +1,167 @@
/**
* @license Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
/**
* @fileOverview Defines the {@link CKEDITOR.xml} class, which represents a
* loaded XML document.
*/
( function() {
/* global ActiveXObject */
CKEDITOR.plugins.add( 'xml', {} );
/**
* Represents a loaded XML document.
*
* var xml = new CKEDITOR.xml( '<books><book title="My Book" /></books>' );
*
* @class
* @constructor Creates xml class instance.
* @param {Object/String} xmlObjectOrData A native XML (DOM document) object or
* a string containing the XML definition to be loaded.
*/
CKEDITOR.xml = function( xmlObjectOrData ) {
var baseXml = null;
if ( typeof xmlObjectOrData == 'object' )
baseXml = xmlObjectOrData;
else {
var data = ( xmlObjectOrData || '' ).replace( /&nbsp;/g, '\xA0' );
// Check ActiveXObject before DOMParser, because IE10+ support both, but
// there's no XPath support in DOMParser instance.
// Also, the only check for ActiveXObject which still works in IE11+ is with `in` operator.
if ( 'ActiveXObject' in window ) {
try {
baseXml = new ActiveXObject( 'MSXML2.DOMDocument' );
} catch ( e ) {
try {
baseXml = new ActiveXObject( 'Microsoft.XmlDom' );
} catch ( err ) {}
}
if ( baseXml ) {
baseXml.async = false;
baseXml.resolveExternals = false;
baseXml.validateOnParse = false;
baseXml.loadXML( data );
}
}
else if ( window.DOMParser ) {
baseXml = ( new DOMParser() ).parseFromString( data, 'text/xml' );
}
}
/**
* The native XML (DOM document) used by the class instance.
*
* @property {Object}
*/
this.baseXml = baseXml;
};
CKEDITOR.xml.prototype = {
/**
* Get a single node from the XML document, based on a XPath query.
*
* // 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 );
*
* @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.
*/
selectSingleNode: function( xpath, contextNode ) {
var baseXml = this.baseXml;
if ( contextNode || ( contextNode = baseXml ) ) {
if ( 'selectSingleNode' in contextNode ) // IEs
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.
*
* // Create the XML instance.
* var xml = new CKEDITOR.xml( '<list><item id="test1" /><item id="test2" /></list>' );
* // Get all <item> nodes.
* var itemNodes = xml.selectNodes( 'list/item' );
* // Alert "item" twice, one for each <item>.
* for ( var i = 0; i < itemNodes.length; i++ )
* alert( itemNodes[i].nodeName );
*
* @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 {Array} An array containing all matched nodes. The array will
* be empty if the query has no results.
*/
selectNodes: function( xpath, contextNode ) {
var baseXml = this.baseXml,
nodes = [];
if ( contextNode || ( contextNode = baseXml ) ) {
if ( 'selectNodes' in contextNode ) // IEs
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.
*
* // 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' ) );
*
* @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.
*/
getInnerXml: function( xpath, contextNode ) {
var node = this.selectSingleNode( xpath, contextNode ),
xml = [];
if ( node ) {
node = node.firstChild;
while ( node ) {
if ( node.xml ) // IEs
xml.push( node.xml );
else if ( window.XMLSerializer ) // Others
xml.push( ( new XMLSerializer() ).serializeToString( node ) );
node = node.nextSibling;
}
}
return xml.length ? xml.join( '' ) : null;
}
};
} )();