8
0

blockautoformatediting.js 4.9 KB

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