blockautoformatediting.js 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  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. import LiveRange from '@ckeditor/ckeditor5-engine/src/model/liverange';
  6. /**
  7. * The block autoformatting engine. It allows to format various block patterns. For example,
  8. * it can be configured to turn a paragraph starting with `*` and followed by a space into a list item.
  9. *
  10. * The autoformatting operation is integrated with the undo manager,
  11. * so the autoformatting step can be undone if the user's intention was not to format the text.
  12. *
  13. * See the {@link module:autoformat/blockautoformatediting~blockAutoformatEditing `blockAutoformatEditing`} documentation
  14. * to learn how to create custom block autoformatters. You can also use
  15. * the {@link module:autoformat/autoformat~Autoformat} feature which enables a set of default autoformatters
  16. * (lists, headings, bold and italic).
  17. *
  18. * @module autoformat/blockautoformatediting
  19. */
  20. /**
  21. * Creates a listener triggered on {@link module:engine/model/document~Document#event:change:data `change:data`} event in the document.
  22. * Calls the callback when inserted text matches the regular expression or the command name
  23. * if provided instead of the callback.
  24. *
  25. * Examples of usage:
  26. *
  27. * To convert a paragraph to heading 1 when `- ` is typed, using just the command name:
  28. *
  29. * blockAutoformatEditing( editor, plugin, /^\- $/, 'heading1' );
  30. *
  31. * To convert a paragraph to heading 1 when `- ` is typed, using just the callback:
  32. *
  33. * blockAutoformatEditing( editor, plugin, /^\- $/, ( context ) => {
  34. * const { match } = context;
  35. * const headingLevel = match[ 1 ].length;
  36. *
  37. * editor.execute( 'heading', {
  38. * formatId: `heading${ headingLevel }`
  39. * } );
  40. * } );
  41. *
  42. * @param {module:core/editor/editor~Editor} editor The editor instance.
  43. * @param {module:autoformat/autoformat~Autoformat} plugin The autoformat plugin instance.
  44. * @param {RegExp} pattern The regular expression to execute on just inserted text.
  45. * @param {Function|String} callbackOrCommand The callback to execute or the command to run when the text is matched.
  46. * In case of providing the callback, it receives the following parameter:
  47. * * {Object} match RegExp.exec() result of matching the pattern to inserted text.
  48. */
  49. export default function blockAutoformatEditing( editor, plugin, pattern, callbackOrCommand ) {
  50. let callback;
  51. let command = null;
  52. if ( typeof callbackOrCommand == 'function' ) {
  53. callback = callbackOrCommand;
  54. } else {
  55. // We assume that the actual command name was provided.
  56. command = editor.commands.get( callbackOrCommand );
  57. callback = () => {
  58. editor.execute( callbackOrCommand );
  59. };
  60. }
  61. editor.model.document.on( 'change:data', ( evt, batch ) => {
  62. if ( command && !command.isEnabled || !plugin.isEnabled ) {
  63. return;
  64. }
  65. if ( batch.type == 'transparent' ) {
  66. return;
  67. }
  68. const changes = Array.from( editor.model.document.differ.getChanges() );
  69. const entry = changes[ 0 ];
  70. // Typing is represented by only a single change.
  71. if ( changes.length != 1 || entry.type !== 'insert' || entry.name != '$text' || entry.length != 1 ) {
  72. return;
  73. }
  74. const blockToFormat = entry.position.parent;
  75. // Block formatting should be disabled in codeBlocks, and in non-empty blocks (ckeditor5#5671).
  76. if ( blockToFormat.is( 'codeBlock' ) || blockToFormat.childCount !== 1 ) {
  77. return;
  78. }
  79. // In case a command is bound, do not re-execute it over an existing block style which would result with a style removal.
  80. // Instead just drop processing so that autoformatting trigger text is not lost. E.g. writing "# " in a level 1 heading.
  81. if ( command && command.value === true ) {
  82. return;
  83. }
  84. const match = pattern.exec( blockToFormat.getChild( 0 ).data );
  85. // ...and this text node's data match the pattern.
  86. if ( !match ) {
  87. return;
  88. }
  89. // Use enqueueChange to create new batch to separate typing batch from the auto-format changes.
  90. editor.model.enqueueChange( writer => {
  91. // Matched range.
  92. const start = writer.createPositionAt( blockToFormat, 0 );
  93. const end = writer.createPositionAt( blockToFormat, match[ 0 ].length );
  94. const range = new LiveRange( start, end );
  95. const wasChanged = callback( { match } );
  96. // Remove matched text.
  97. if ( wasChanged !== false ) {
  98. writer.remove( range );
  99. }
  100. range.detach();
  101. } );
  102. } );
  103. }