selectallcommand.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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 select-all/selectallcommand
  7. */
  8. import Command from '@ckeditor/ckeditor5-core/src/command';
  9. /**
  10. * The select all command.
  11. *
  12. * It is used by the {@link module:select-all/selectallediting~SelectAllEditing select all editing feature} to handle
  13. * the <kbd>Ctrl/⌘</kbd>+<kbd>A</kbd> keystroke.
  14. *
  15. * Executing this command changes the {@glink framework/guides/architecture/editing-engine#model model}
  16. * selection so it contains the entire content of the editable root of the editor the selection is
  17. * {@link module:engine/model/selection~Selection#anchor anchored} in.
  18. *
  19. * If the selection was anchored in a {@glink framework/guides/tutorials/implementing-a-block-widget nested editable}
  20. * (e.g. a caption of an image), the new selection will contain its entire content. Successive executions of this command
  21. * will expand the selection to encompass more and more content up to the entire editable root of the editor.
  22. *
  23. * @extends module:core/command~Command
  24. */
  25. export default class SelectAllCommand extends Command {
  26. /**
  27. * @inheritDoc
  28. */
  29. execute() {
  30. const model = this.editor.model;
  31. const selection = model.document.selection;
  32. let scopeElement = model.schema.getLimitElement( selection );
  33. // If an entire scope is selected, or the selection's ancestor is not a scope yet,
  34. // browse through ancestors to find the enclosing parent scope.
  35. if ( selection.containsEntireContent( scopeElement ) || !isSelectAllScope( model.schema, scopeElement ) ) {
  36. do {
  37. scopeElement = scopeElement.parent;
  38. // Do nothing, if the entire `root` is already selected.
  39. if ( !scopeElement ) {
  40. return;
  41. }
  42. } while ( !isSelectAllScope( model.schema, scopeElement ) );
  43. }
  44. model.change( writer => {
  45. writer.setSelection( scopeElement, 'in' );
  46. } );
  47. }
  48. }
  49. // Checks whether the element is a valid select-all scope.
  50. // Returns true, if the element is a {@link module:engine/model/schema~Schema#isLimit limit},
  51. // and can contain any text or paragraph.
  52. //
  53. // @param {module:engine/model/schema~Schema} schema The schema to check against.
  54. // @param {module:engine/model/element~Element} element
  55. // @return {Boolean}
  56. function isSelectAllScope( schema, element ) {
  57. return schema.isLimit( element ) && ( schema.checkChild( element, '$text' ) || schema.checkChild( element, 'paragraph' ) );
  58. }