gfmdataprocessor.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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 marked from './lib/marked/marked';
  9. import toMarkdown from './lib/to-markdown/to-markdown';
  10. import HtmlDataProcessor from '@ckeditor/ckeditor5-engine/src/dataprocessor/htmldataprocessor';
  11. import GFMRenderer from './lib/marked/renderer';
  12. import converters from './lib/to-markdown/converters';
  13. /**
  14. * This data processor implementation uses GitHub Flavored Markdown as input/output data.
  15. *
  16. * See the {@glink features/markdown Markdown output} guide to learn more on how to enable it.
  17. *
  18. * @implements module:engine/dataprocessor/dataprocessor~DataProcessor
  19. */
  20. export default class GFMDataProcessor {
  21. /**
  22. * Creates a new instance of the Markdown data processor class.
  23. *
  24. * @param {module:engine/view/document~Document} document
  25. */
  26. constructor( document ) {
  27. /**
  28. * HTML data processor used to process HTML produced by the Markdown-to-HTML converter and the other way.
  29. *
  30. * @private
  31. * @member {module:engine/dataprocessor/htmldataprocessor~HtmlDataProcessor}
  32. */
  33. this._htmlDP = new HtmlDataProcessor( document );
  34. }
  35. /**
  36. * Converts the provided Markdown string to view tree.
  37. *
  38. * @param {String} data A Markdown string.
  39. * @returns {module:engine/view/documentfragment~DocumentFragment} The converted view element.
  40. */
  41. toView( data ) {
  42. const html = marked.parse( data, {
  43. gfm: true,
  44. breaks: true,
  45. tables: true,
  46. xhtml: true,
  47. renderer: new GFMRenderer()
  48. } );
  49. return this._htmlDP.toView( html );
  50. }
  51. /**
  52. * Converts the provided {@link module:engine/view/documentfragment~DocumentFragment} to data format — in this
  53. * case to a Markdown string.
  54. *
  55. * @param {module:engine/view/documentfragment~DocumentFragment} viewFragment
  56. * @returns {String} Markdown string.
  57. */
  58. toData( viewFragment ) {
  59. const html = this._htmlDP.toData( viewFragment );
  60. return toMarkdown( html, { gfm: true, converters } );
  61. }
  62. }