gfmdataprocessor.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /**
  2. * @license Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
  4. */
  5. /**
  6. * @module markdown-gfm/gfmdataprocessor
  7. */
  8. import HtmlDataProcessor from '@ckeditor/ckeditor5-engine/src/dataprocessor/htmldataprocessor';
  9. import markdown2html from './markdown2html/markdown2html';
  10. import html2markdown, { turndownService } from './html2markdown/html2markdown';
  11. /**
  12. * This data processor implementation uses GitHub Flavored Markdown as input/output data.
  13. *
  14. * See the {@glink features/markdown Markdown output} guide to learn more on how to enable it.
  15. *
  16. * @implements module:engine/dataprocessor/dataprocessor~DataProcessor
  17. */
  18. export default class GFMDataProcessor {
  19. /**
  20. * Creates a new instance of the Markdown data processor class.
  21. *
  22. * @param {module:engine/view/document~Document} document
  23. */
  24. constructor( document ) {
  25. /**
  26. * HTML data processor used to process HTML produced by the Markdown-to-HTML converter and the other way.
  27. *
  28. * @private
  29. * @member {module:engine/dataprocessor/htmldataprocessor~HtmlDataProcessor}
  30. */
  31. this._htmlDP = new HtmlDataProcessor( document );
  32. }
  33. /**
  34. * Keeps the specified element in the output as HTML. This is useful if the editor contains
  35. * features that produce HTML that are not part of the markdon standards.
  36. *
  37. * By default, all HTML tags are removed.
  38. *
  39. * @param element {String} The element name to be kept.
  40. */
  41. keepHtml( element ) {
  42. turndownService.keep( [ element ] );
  43. }
  44. /**
  45. * Converts the provided Markdown string to view tree.
  46. *
  47. * @param {String} data A Markdown string.
  48. * @returns {module:engine/view/documentfragment~DocumentFragment} The converted view element.
  49. */
  50. toView( data ) {
  51. const html = markdown2html( data );
  52. return this._htmlDP.toView( html );
  53. }
  54. /**
  55. * Converts the provided {@link module:engine/view/documentfragment~DocumentFragment} to data format — in this
  56. * case to a Markdown string.
  57. *
  58. * @param {module:engine/view/documentfragment~DocumentFragment} viewFragment
  59. * @returns {String} Markdown string.
  60. */
  61. toData( viewFragment ) {
  62. const html = this._htmlDP.toData( viewFragment );
  63. return html2markdown( html );
  64. }
  65. }