htmldataprocessor.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /**
  2. * @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. 'use strict';
  6. import BasicHtmlWriter from './basichtmlwriter.js';
  7. /**
  8. * HtmlDataProcessor class.
  9. * This data processor implementation uses HTML as input/output data.
  10. *
  11. * @memberOf core.dataProcessor
  12. * @implements core.dataProcessor.DataProcessor
  13. */
  14. export default class HtmlDataProcessor {
  15. /**
  16. * Creates a new instance of the HtmlDataProcessor class.
  17. */
  18. constructor() {
  19. /**
  20. * DOMParser instance used to parse HTML string to HTMLDocument.
  21. *
  22. * @private
  23. * @member {DOMParser} core.dataProcessor.HtmlDataProcessor#_domParser
  24. */
  25. this._domParser = new DOMParser();
  26. /**
  27. * BasicHtmlWriter instance used to convert DOM elements to HTML string.
  28. *
  29. * @private
  30. * @member {core.dataProcessor.BasicHtmlWriter} core.dataProcessor.HtmlDataProcessor#_htmlWriter
  31. */
  32. this._htmlWriter = new BasicHtmlWriter();
  33. }
  34. /**
  35. * Converts provided document fragment to data format - in this case HTML string.
  36. *
  37. * @param {DocumentFragment} fragment
  38. * @returns {String}
  39. */
  40. toData( fragment ) {
  41. return this._htmlWriter.getHtml( fragment );
  42. }
  43. /**
  44. * Converts HTML String to its DOM representation. Returns DocumentFragment, containing nodes parsed from
  45. * provided data.
  46. *
  47. * @param {String} data
  48. * @returns {DocumentFragment}
  49. */
  50. toDom( data ) {
  51. const document = this._domParser.parseFromString( data, 'text/html' );
  52. const fragment = document.createDocumentFragment();
  53. const nodes = document.body.childNodes;
  54. while ( nodes.length > 0 ) {
  55. fragment.appendChild( nodes[ 0 ] );
  56. }
  57. return fragment;
  58. }
  59. }