projection.test.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import { expect } from 'chai'
  2. import { EditorState } from '@codemirror/state'
  3. import {
  4. ProjectionItem,
  5. updatePosition,
  6. } from '../../../../../frontend/js/features/source-editor/utils/tree-operations/projection'
  7. class TestItem extends ProjectionItem {}
  8. const itemAt = (
  9. from: number,
  10. to: number,
  11. line: number,
  12. toLine: number
  13. ): TestItem => Object.assign(new TestItem(), { from, to, line, toLine })
  14. describe('updatePosition', function () {
  15. it('returns the same instance when positions and lines are unchanged', function () {
  16. const state = EditorState.create({ doc: 'first line\nsecond line' })
  17. const tr = state.update({ changes: { from: 0, to: 0, insert: '' } })
  18. const item = itemAt(11, 22, 2, 2)
  19. expect(updatePosition(item, tr)).to.equal(item)
  20. })
  21. it('refreshes both line and toLine after an upstream insert adds lines', function () {
  22. const state = EditorState.create({ doc: 'first line\nsecond line' })
  23. const tr = state.update({
  24. changes: { from: 0, to: 0, insert: 'top\nmiddle\n' },
  25. })
  26. // Item originally covered "second line" (lines 2..2) at offsets 11..22.
  27. const item = itemAt(11, 22, 2, 2)
  28. const updated = updatePosition(item, tr)
  29. expect(updated).to.not.equal(item)
  30. expect(updated.from).to.equal(22)
  31. expect(updated.to).to.equal(33)
  32. expect(updated.line).to.equal(4)
  33. expect(updated.toLine).to.equal(4)
  34. })
  35. it('refreshes line and toLine independently for multi-line items', function () {
  36. const state = EditorState.create({
  37. doc: 'a\nbb\nccc\ndddd\neeeee',
  38. })
  39. // Item covers "bb\nccc" at offsets 2..8, on lines 2..3.
  40. const item = itemAt(2, 8, 2, 3)
  41. const tr = state.update({
  42. changes: { from: 0, to: 0, insert: 'X\n' },
  43. })
  44. const updated = updatePosition(item, tr)
  45. expect(updated.from).to.equal(4)
  46. expect(updated.to).to.equal(10)
  47. expect(updated.line).to.equal(3)
  48. expect(updated.toLine).to.equal(4)
  49. })
  50. })