upcast-selection-converters.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /**
  2. * @license Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * Contains {@link module:engine/view/selection~Selection view selection}
  7. * to {@link module:engine/model/selection~Selection model selection} conversion helpers.
  8. *
  9. * @module engine/conversion/upcast-selection-converters
  10. */
  11. import ModelSelection from '../model/selection';
  12. /**
  13. * Function factory, creates a callback function which converts a {@link module:engine/view/selection~Selection view selection} taken
  14. * from the {@link module:engine/view/document~Document#event:selectionChange} event
  15. * and sets in on the {@link module:engine/model/document~Document#selection model}.
  16. *
  17. * **Note**: because there is no view selection change dispatcher nor any other advanced view selection to model
  18. * conversion mechanism, the callback should be set directly on view document.
  19. *
  20. * view.document.on( 'selectionChange', convertSelectionChange( modelDocument, mapper ) );
  21. *
  22. * @param {module:engine/model/model~Model} model Data model.
  23. * @param {module:engine/conversion/mapper~Mapper} mapper Conversion mapper.
  24. * @returns {Function} {@link module:engine/view/document~Document#event:selectionChange} callback function.
  25. */
  26. export function convertSelectionChange( model, mapper ) {
  27. return ( evt, data ) => {
  28. const viewSelection = data.newSelection;
  29. const modelSelection = new ModelSelection();
  30. const ranges = [];
  31. for ( const viewRange of viewSelection.getRanges() ) {
  32. ranges.push( mapper.toModelRange( viewRange ) );
  33. }
  34. modelSelection.setTo( ranges, viewSelection.isBackward );
  35. if ( !modelSelection.isEqual( model.document.selection ) ) {
  36. model.change( writer => {
  37. writer.setSelection( modelSelection );
  38. } );
  39. }
  40. };
  41. }