cursor.ts 1.2 KB

123456789101112131415161718192021222324252627282930313233343536
  1. import { Command } from '@codemirror/view'
  2. import { EditorSelection } from '@codemirror/state'
  3. import { emitShortcutEvent } from '@/features/source-editor/extensions/toolbar/utils/analytics'
  4. export const cloneSelectionVertically =
  5. (forward: boolean, cumulative: boolean, modifier: string): Command =>
  6. view => {
  7. const { main, ranges, mainIndex } = view.state.selection
  8. const { anchor, head, goalColumn } = main
  9. const start = EditorSelection.range(anchor, head, goalColumn)
  10. const nextRange = view.moveVertically(start, forward)
  11. let filteredRanges = [...ranges]
  12. if (!cumulative && filteredRanges.length > 1) {
  13. // remove the current main range
  14. filteredRanges.splice(mainIndex, 1)
  15. }
  16. // prevent duplication when going in the opposite direction
  17. filteredRanges = filteredRanges.filter(
  18. item => item.from !== nextRange.from && item.to !== nextRange.to
  19. )
  20. const selection = EditorSelection.create(
  21. filteredRanges.concat(nextRange),
  22. filteredRanges.length
  23. )
  24. view.dispatch({ selection })
  25. emitShortcutEvent(view, 'clone-selection-vertically', {
  26. forward,
  27. cumulative,
  28. modifier,
  29. })
  30. return true
  31. }