This repository has been archived by the owner on Jun 26, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathpastefromoffice.js
77 lines (66 loc) · 2.42 KB
/
pastefromoffice.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/**
* @license Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md.
*/
/**
* @module paste-from-office/pastefromoffice
*/
import Plugin from '@ckeditor/ckeditor5-core/src/plugin';
import Clipboard from '@ckeditor/ckeditor5-clipboard/src/clipboard';
import { parseHtml } from './filters/parse';
import { transformListItemLikeElementsIntoLists } from './filters/list';
import { replaceImagesSourceWithBase64 } from './filters/image';
/**
* The Paste from Office plugin.
*
* This plugin handles content pasted from Office apps (for now only Word) and transforms it (if necessary)
* to a valid structure which can then be understood by the editor features.
*
* For more information about this feature check the {@glink api/paste-from-office package page}.
*
* @extends module:core/plugin~Plugin
*/
export default class PasteFromOffice extends Plugin {
/**
* @inheritDoc
*/
static get pluginName() {
return 'PasteFromOffice';
}
/**
* @inheritDoc
*/
init() {
const editor = this.editor;
this.listenTo( editor.plugins.get( Clipboard ), 'inputTransformation', ( evt, data ) => {
const html = data.dataTransfer.getData( 'text/html' );
if ( isWordInput( html ) ) {
data.content = this._normalizeWordInput( html, data.dataTransfer );
}
}, { priority: 'high' } );
}
/**
* Normalizes input pasted from Word to format suitable for editor {@link module:engine/model/model~Model}.
*
* **Note**: this function was exposed mainly for testing purposes and should not be called directly.
*
* @protected
* @param {String} input Word input.
* @param {module:clipboard/datatransfer~DataTransfer} dataTransfer Data transfer instance.
* @returns {module:engine/view/documentfragment~DocumentFragment} Normalized input.
*/
_normalizeWordInput( input, dataTransfer ) {
const { body, stylesString } = parseHtml( input );
transformListItemLikeElementsIntoLists( body, stylesString );
replaceImagesSourceWithBase64( body, dataTransfer.getData( 'text/rtf' ) );
return body;
}
}
// Checks if given HTML string is a result of pasting content from Word.
//
// @param {String} html HTML string to test.
// @returns {Boolean} True if given HTML string is a Word HTML.
function isWordInput( html ) {
return !!( html && ( html.match( /<meta\s*name="?generator"?\s*content="?microsoft\s*word\s*\d+"?\/?>/gi ) ||
html.match( /xmlns:o="urn:schemas-microsoft-com/gi ) ) );
}