pastefromoffice.js 2.2 KB

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