inlineautoformatediting.js 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. /**
  2. * @license Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
  4. */
  5. /**
  6. * @module autoformat/inlineautoformatediting
  7. */
  8. import getText from '@ckeditor/ckeditor5-typing/src/utils/gettext';
  9. /**
  10. * The inline autoformatting engine. It allows to format various inline patterns. For example,
  11. * it can be configured to make "foo" bold when typed `**foo**` (the `**` markers will be removed).
  12. *
  13. * The autoformatting operation is integrated with the undo manager,
  14. * so the autoformatting step can be undone if the user's intention was not to format the text.
  15. *
  16. * See the constructors documentation to learn how to create custom inline autoformatters. You can also use
  17. * the {@link module:autoformat/autoformat~Autoformat} feature which enables a set of default autoformatters
  18. * (lists, headings, bold and italic).
  19. */
  20. export default class InlineAutoformatEditing {
  21. /**
  22. * Enables autoformatting mechanism for a given {@link module:core/editor/editor~Editor}.
  23. *
  24. * It formats the matched text by applying the given model attribute or by running the provided formatting callback.
  25. * On every change applied to the model the autoformatting engine checks the text on the left of the selection
  26. * and executes the provided action if the text matches given criteria (regular expression or callback).
  27. *
  28. * @param {module:core/editor/editor~Editor} editor The editor instance.
  29. * @param {Function|RegExp} testRegexpOrCallback The regular expression or callback to execute on text.
  30. * Provided regular expression *must* have three capture groups. The first and the third capture group
  31. * should match opening and closing delimiters. The second capture group should match the text to format.
  32. *
  33. * // Matches the `**bold text**` pattern.
  34. * // There are three capturing groups:
  35. * // - The first to match the starting `**` delimiter.
  36. * // - The second to match the text to format.
  37. * // - The third to match the ending `**` delimiter.
  38. * new InlineAutoformatEditing( editor, /(\*\*)([^\*]+?)(\*\*)$/g, 'bold' );
  39. *
  40. * When a function is provided instead of the regular expression, it will be executed with the text to match as a parameter.
  41. * The function should return proper "ranges" to delete and format.
  42. *
  43. * {
  44. * remove: [
  45. * [ 0, 1 ], // Remove the first letter from the given text.
  46. * [ 5, 6 ] // Remove the 6th letter from the given text.
  47. * ],
  48. * format: [
  49. * [ 1, 5 ] // Format all letters from 2nd to 5th.
  50. * ]
  51. * }
  52. *
  53. * @param {Function|String} attributeOrCallback The name of attribute to apply on matching text or a callback for manual
  54. * formatting. If callback is passed it should return `false` if changes should not be applied (e.g. if a command is disabled).
  55. *
  56. * // Use attribute name:
  57. * new InlineAutoformatEditing( editor, /(\*\*)([^\*]+?)(\*\*)$/g, 'bold' );
  58. *
  59. * // Use formatting callback:
  60. * new InlineAutoformatEditing( editor, /(\*\*)([^\*]+?)(\*\*)$/g, ( writer, rangesToFormat ) => {
  61. * const command = editor.commands.get( 'bold' );
  62. *
  63. * if ( !command.isEnabled ) {
  64. * return false;
  65. * }
  66. *
  67. * const validRanges = editor.model.schema.getValidRanges( rangesToFormat, 'bold' );
  68. *
  69. * for ( let range of validRanges ) {
  70. * writer.setAttribute( 'bold', true, range );
  71. * }
  72. * } );
  73. */
  74. constructor( editor, testRegexpOrCallback, attributeOrCallback ) {
  75. let regExp;
  76. let attributeKey;
  77. let testCallback;
  78. let formatCallback;
  79. if ( testRegexpOrCallback instanceof RegExp ) {
  80. regExp = testRegexpOrCallback;
  81. } else {
  82. testCallback = testRegexpOrCallback;
  83. }
  84. if ( typeof attributeOrCallback == 'string' ) {
  85. attributeKey = attributeOrCallback;
  86. } else {
  87. formatCallback = attributeOrCallback;
  88. }
  89. // A test callback run on changed text.
  90. testCallback = testCallback || ( text => {
  91. let result;
  92. const remove = [];
  93. const format = [];
  94. while ( ( result = regExp.exec( text ) ) !== null ) {
  95. // There should be full match and 3 capture groups.
  96. if ( result && result.length < 4 ) {
  97. break;
  98. }
  99. let {
  100. index,
  101. '1': leftDel,
  102. '2': content,
  103. '3': rightDel
  104. } = result;
  105. // Real matched string - there might be some non-capturing groups so we need to recalculate starting index.
  106. const found = leftDel + content + rightDel;
  107. index += result[ 0 ].length - found.length;
  108. // Start and End offsets of delimiters to remove.
  109. const delStart = [
  110. index,
  111. index + leftDel.length
  112. ];
  113. const delEnd = [
  114. index + leftDel.length + content.length,
  115. index + leftDel.length + content.length + rightDel.length
  116. ];
  117. remove.push( delStart );
  118. remove.push( delEnd );
  119. format.push( [ index + leftDel.length, index + leftDel.length + content.length ] );
  120. }
  121. return {
  122. remove,
  123. format
  124. };
  125. } );
  126. // A format callback run on matched text.
  127. formatCallback = formatCallback || ( ( writer, rangesToFormat ) => {
  128. const validRanges = editor.model.schema.getValidRanges( rangesToFormat, attributeKey );
  129. for ( const range of validRanges ) {
  130. writer.setAttribute( attributeKey, true, range );
  131. }
  132. // After applying attribute to the text, remove given attribute from the selection.
  133. // This way user is able to type a text without attribute used by auto formatter.
  134. writer.removeSelectionAttribute( attributeKey );
  135. } );
  136. editor.model.document.on( 'change', ( evt, batch ) => {
  137. if ( batch.type == 'transparent' ) {
  138. return;
  139. }
  140. const selection = editor.model.document.selection;
  141. // Do nothing if selection is not collapsed.
  142. if ( !selection.isCollapsed ) {
  143. return;
  144. }
  145. const changes = Array.from( editor.model.document.differ.getChanges() );
  146. const entry = changes[ 0 ];
  147. // Typing is represented by only a single change.
  148. if ( changes.length != 1 || entry.type !== 'insert' || entry.name != '$text' || entry.length != 1 ) {
  149. return;
  150. }
  151. const model = editor.model;
  152. const focus = selection.focus;
  153. const block = focus.parent;
  154. const { text, range } = getText( model.createRange( model.createPositionAt( block, 0 ), focus ), model );
  155. const testOutput = testCallback( text );
  156. const rangesToFormat = testOutputToRanges( range.start, testOutput.format, editor.model );
  157. const rangesToRemove = testOutputToRanges( range.start, testOutput.remove, editor.model );
  158. if ( !( rangesToFormat.length && rangesToRemove.length ) ) {
  159. return;
  160. }
  161. // Use enqueueChange to create new batch to separate typing batch from the auto-format changes.
  162. editor.model.enqueueChange( writer => {
  163. // Apply format.
  164. const hasChanged = formatCallback( writer, rangesToFormat );
  165. // Strict check on `false` to have backward compatibility (when callbacks were returning `undefined`).
  166. if ( hasChanged === false ) {
  167. return;
  168. }
  169. // Remove delimiters - use reversed order to not mix the offsets while removing.
  170. for ( const range of rangesToRemove.reverse() ) {
  171. writer.remove( range );
  172. }
  173. } );
  174. } );
  175. }
  176. }
  177. // Converts output of the test function provided to the InlineAutoformatEditing and converts it to the model ranges
  178. // inside provided block.
  179. //
  180. // @private
  181. // @param {module:engine/model/position~Position} start
  182. // @param {Array.<Array>} arrays
  183. // @param {module:engine/model/model~Model} model
  184. function testOutputToRanges( start, arrays, model ) {
  185. return arrays
  186. .filter( array => ( array[ 0 ] !== undefined && array[ 1 ] !== undefined ) )
  187. .map( array => {
  188. return model.createRange( start.getShiftedBy( array[ 0 ] ), start.getShiftedBy( array[ 1 ] ) );
  189. } );
  190. }