restrictededitingexceptioncommand.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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 restricted-editing/restrictededitingexceptioncommand
  7. */
  8. import Command from '@ckeditor/ckeditor5-core/src/command';
  9. /**
  10. * @extends module:core/command~Command
  11. */
  12. export default class RestrictedEditingExceptionCommand extends Command {
  13. /**
  14. * @inheritDoc
  15. */
  16. refresh() {
  17. const model = this.editor.model;
  18. const doc = model.document;
  19. this.value = !!doc.selection.getAttribute( 'restrictedEditingException' );
  20. this.isEnabled = model.schema.checkAttributeInSelection( doc.selection, 'restrictedEditingException' );
  21. }
  22. /**
  23. * @inheritDoc
  24. */
  25. execute( options = {} ) {
  26. const model = this.editor.model;
  27. const document = model.document;
  28. const selection = document.selection;
  29. const valueToSet = ( options.forceValue === undefined ) ? !this.value : options.forceValue;
  30. model.change( writer => {
  31. const ranges = model.schema.getValidRanges( selection.getRanges(), 'restrictedEditingException' );
  32. if ( selection.isCollapsed ) {
  33. if ( valueToSet ) {
  34. writer.setSelectionAttribute( 'restrictedEditingException', valueToSet );
  35. } else {
  36. const isSameException = value => value.item.getAttribute( 'restrictedEditingException' ) === this.value;
  37. const exceptionStart = selection.focus.getLastMatchingPosition( isSameException, { direction: 'backward' } );
  38. const exceptionEnd = selection.focus.getLastMatchingPosition( isSameException );
  39. const focus = selection.focus;
  40. writer.removeSelectionAttribute( 'restrictedEditingException' );
  41. if ( !( focus.isEqual( exceptionStart ) || focus.isEqual( exceptionEnd ) ) ) {
  42. writer.removeAttribute( 'restrictedEditingException', writer.createRange( exceptionStart, exceptionEnd ) );
  43. }
  44. }
  45. } else {
  46. for ( const range of ranges ) {
  47. if ( valueToSet ) {
  48. writer.setAttribute( 'restrictedEditingException', valueToSet, range );
  49. } else {
  50. writer.removeAttribute( 'restrictedEditingException', range );
  51. }
  52. }
  53. }
  54. } );
  55. }
  56. }