text_operation.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916
  1. // @ts-check
  2. /**
  3. * The text operation from OT.js with some minor cosmetic changes.
  4. *
  5. * Specifically, this is based on
  6. * https://github.com/Operational-Transformation/ot.js/
  7. * blob/298825f58fb51fefb352e7df5ddbc668f4d5646f/lib/text-operation.js
  8. * from 18 Mar 2013.
  9. */
  10. 'use strict'
  11. const containsNonBmpChars = require('../util').containsNonBmpChars
  12. const EditOperation = require('./edit_operation')
  13. const {
  14. RetainOp,
  15. InsertOp,
  16. RemoveOp,
  17. isRetain,
  18. isInsert,
  19. isRemove,
  20. } = require('./scan_op')
  21. const {
  22. UnprocessableError,
  23. ApplyError,
  24. InvalidInsertionError,
  25. TooLongError,
  26. } = require('../errors')
  27. const Range = require('../range')
  28. const ClearTrackingProps = require('../file_data/clear_tracking_props')
  29. const TrackingProps = require('../file_data/tracking_props')
  30. /**
  31. * @import StringFileData from '../file_data/string_file_data'
  32. * @import { RawTextOperation, TrackingDirective } from '../types'
  33. * @import { ScanOp } from '../operation/scan_op'
  34. * @import TrackedChangeList from '../file_data/tracked_change_list'
  35. *
  36. * @typedef {{tracking?: TrackingProps, commentIds?: string[]}} InsertOptions
  37. */
  38. /**
  39. * Create an empty text operation.
  40. * @extends EditOperation
  41. */
  42. class TextOperation extends EditOperation {
  43. /**
  44. * Length of the longest file that we'll attempt to edit, in characters.
  45. *
  46. * @type {number}
  47. */
  48. static MAX_STRING_LENGTH = 2 * Math.pow(1024, 2)
  49. static UnprocessableError = UnprocessableError
  50. static ApplyError = ApplyError
  51. static InvalidInsertionError = InvalidInsertionError
  52. static TooLongError = TooLongError
  53. constructor() {
  54. super()
  55. /**
  56. * When an operation is applied to an input string, you can think of this as
  57. * if an imaginary cursor runs over the entire string and skips over some
  58. * parts, removes some parts and inserts characters at some positions. These
  59. * actions (skip/remove/insert) are stored as an array in the "ops" property.
  60. * @type {ScanOp[]}
  61. */
  62. this.ops = []
  63. /**
  64. * An operation's baseLength is the length of every string the operation
  65. * can be applied to.
  66. */
  67. this.baseLength = 0
  68. /**
  69. * The targetLength is the length of every string that results from applying
  70. * the operation on a valid input string.
  71. */
  72. this.targetLength = 0
  73. /**
  74. * The expected content hash after this operation is applied
  75. *
  76. * @type {string | null}
  77. */
  78. this.contentHash = null
  79. }
  80. /**
  81. * @param {TextOperation} other
  82. * @return {boolean}
  83. */
  84. equals(other) {
  85. if (this.baseLength !== other.baseLength) {
  86. return false
  87. }
  88. if (this.targetLength !== other.targetLength) {
  89. return false
  90. }
  91. if (this.ops.length !== other.ops.length) {
  92. return false
  93. }
  94. for (let i = 0; i < this.ops.length; i++) {
  95. if (!this.ops[i].equals(other.ops[i])) {
  96. return false
  97. }
  98. }
  99. return true
  100. }
  101. // After an operation is constructed, the user of the library can specify the
  102. // actions of an operation (skip/insert/remove) with these three builder
  103. // methods. They all return the operation for convenient chaining.
  104. /**
  105. * Skip over a given number of characters.
  106. * @param {number | {r: number}} n
  107. * @param {{tracking?: TrackingDirective}} opts
  108. * @returns {TextOperation}
  109. */
  110. retain(n, opts = {}) {
  111. if (n === 0) {
  112. return this
  113. }
  114. if (!isRetain(n)) {
  115. throw new Error('retain expects an integer or a retain object')
  116. }
  117. const newOp = RetainOp.fromJSON(n)
  118. newOp.tracking = opts.tracking
  119. if (newOp.length === 0) {
  120. return this
  121. }
  122. this.baseLength += newOp.length
  123. this.targetLength += newOp.length
  124. const lastOperation = this.ops[this.ops.length - 1]
  125. if (lastOperation?.canMergeWith(newOp)) {
  126. // The last op is a retain op => we can merge them into one op.
  127. lastOperation.mergeWith(newOp)
  128. } else {
  129. // Create a new op.
  130. this.ops.push(newOp)
  131. }
  132. return this
  133. }
  134. /**
  135. * Insert a string at the current position.
  136. * @param {string | {i: string}} insertValue
  137. * @param {InsertOptions} opts
  138. * @returns {TextOperation}
  139. */
  140. insert(insertValue, opts = {}) {
  141. if (!isInsert(insertValue)) {
  142. throw new Error('insert expects a string or an insert object')
  143. }
  144. const newOp = InsertOp.fromJSON(insertValue)
  145. newOp.tracking = opts.tracking
  146. newOp.commentIds = opts.commentIds
  147. if (newOp.insertion === '') {
  148. return this
  149. }
  150. this.targetLength += newOp.insertion.length
  151. const ops = this.ops
  152. const lastOp = this.ops[this.ops.length - 1]
  153. if (lastOp?.canMergeWith(newOp)) {
  154. // Merge insert op.
  155. lastOp.mergeWith(newOp)
  156. } else if (lastOp instanceof RemoveOp) {
  157. // It doesn't matter when an operation is applied whether the operation
  158. // is remove(3), insert("something") or insert("something"), remove(3).
  159. // Here we enforce that in this case, the insert op always comes first.
  160. // This makes all operations that have the same effect when applied to
  161. // a document of the right length equal in respect to the `equals` method.
  162. const secondToLastOp = ops[ops.length - 2]
  163. if (secondToLastOp?.canMergeWith(newOp)) {
  164. secondToLastOp.mergeWith(newOp)
  165. } else {
  166. ops[ops.length] = ops[ops.length - 1]
  167. ops[ops.length - 2] = newOp
  168. }
  169. } else {
  170. ops.push(newOp)
  171. }
  172. return this
  173. }
  174. /**
  175. * Remove a string at the current position.
  176. * @param {number | string} n
  177. * @returns {TextOperation}
  178. */
  179. remove(n) {
  180. if (typeof n === 'string') {
  181. n = n.length
  182. }
  183. if (typeof n !== 'number') {
  184. throw new Error('remove expects an integer or a string')
  185. }
  186. if (n === 0) {
  187. return this
  188. }
  189. if (n > 0) {
  190. n = -n
  191. }
  192. const newOp = RemoveOp.fromJSON(n)
  193. this.baseLength -= n
  194. const lastOp = this.ops[this.ops.length - 1]
  195. if (lastOp?.canMergeWith(newOp)) {
  196. lastOp.mergeWith(newOp)
  197. } else {
  198. this.ops.push(newOp)
  199. }
  200. return this
  201. }
  202. /**
  203. * Tests whether this operation has no effect.
  204. */
  205. isNoop() {
  206. return (
  207. this.ops.length === 0 ||
  208. (this.ops.length === 1 && this.ops[0] instanceof RetainOp)
  209. )
  210. }
  211. /**
  212. * Pretty printing.
  213. */
  214. toString() {
  215. return this.ops.map(op => op.toString()).join(', ')
  216. }
  217. /**
  218. * @inheritdoc
  219. * @returns {RawTextOperation}
  220. */
  221. toJSON() {
  222. /** @type {RawTextOperation} */
  223. const json = { textOperation: this.ops.map(op => op.toJSON()) }
  224. if (this.contentHash != null) {
  225. json.contentHash = this.contentHash
  226. }
  227. return json
  228. }
  229. /**
  230. * Converts a plain JS object into an operation and validates it.
  231. * @param {RawTextOperation} obj
  232. * @returns {TextOperation}
  233. */
  234. static fromJSON = function ({ textOperation: ops, contentHash }) {
  235. const o = new TextOperation()
  236. for (const op of ops) {
  237. if (isRetain(op)) {
  238. const retain = RetainOp.fromJSON(op)
  239. o.retain(retain.length, { tracking: retain.tracking })
  240. } else if (isInsert(op)) {
  241. const insert = InsertOp.fromJSON(op)
  242. o.insert(insert.insertion, {
  243. commentIds: insert.commentIds,
  244. tracking: insert.tracking,
  245. })
  246. } else if (isRemove(op)) {
  247. const remove = RemoveOp.fromJSON(op)
  248. o.remove(-remove.length)
  249. } else {
  250. throw new UnprocessableError('unknown operation: ' + JSON.stringify(op))
  251. }
  252. }
  253. if (contentHash != null) {
  254. o.contentHash = contentHash
  255. }
  256. return o
  257. }
  258. /**
  259. * Apply an operation to a string, returning a new string. Throws an error if
  260. * there's a mismatch between the input string and the operation.
  261. * @override
  262. * @inheritdoc
  263. * @param {StringFileData} file
  264. */
  265. apply(file) {
  266. const str = file.getContent()
  267. const operation = this
  268. if (containsNonBmpChars(str)) {
  269. throw new TextOperation.ApplyError(
  270. 'The string contains non BMP characters.',
  271. operation,
  272. str
  273. )
  274. }
  275. if (str.length !== operation.baseLength) {
  276. throw new TextOperation.ApplyError(
  277. "The operation's base length must be equal to the string's length.",
  278. operation,
  279. str
  280. )
  281. }
  282. const ops = this.ops
  283. let inputCursor = 0
  284. let result = ''
  285. for (const op of ops) {
  286. if (op instanceof RetainOp) {
  287. if (inputCursor + op.length > str.length) {
  288. throw new ApplyError(
  289. "Operation can't retain more chars than are left in the string.",
  290. op.toJSON(),
  291. str
  292. )
  293. }
  294. result += str.slice(inputCursor, inputCursor + op.length)
  295. inputCursor += op.length
  296. } else if (op instanceof InsertOp) {
  297. if (containsNonBmpChars(op.insertion)) {
  298. throw new InvalidInsertionError(str, op.toJSON())
  299. }
  300. file.comments.applyInsert(
  301. new Range(result.length, op.insertion.length),
  302. { commentIds: op.commentIds }
  303. )
  304. result += op.insertion
  305. } else if (op instanceof RemoveOp) {
  306. file.comments.applyDelete(new Range(result.length, op.length))
  307. inputCursor += op.length
  308. } else {
  309. throw new UnprocessableError('Unknown ScanOp type during apply')
  310. }
  311. }
  312. if (inputCursor !== str.length) {
  313. throw new TextOperation.ApplyError(
  314. "The operation didn't operate on the whole string.",
  315. operation,
  316. str
  317. )
  318. }
  319. if (result.length > TextOperation.MAX_STRING_LENGTH) {
  320. throw new TextOperation.TooLongError(operation, result.length)
  321. }
  322. file.trackedChanges.applyTextOperation(this)
  323. file.content = result
  324. }
  325. /**
  326. * @inheritdoc
  327. * @param {number} length of the original string; non-negative
  328. * @return {number} length of the new string; non-negative
  329. */
  330. applyToLength(length) {
  331. const operation = this
  332. if (length !== operation.baseLength) {
  333. throw new TextOperation.ApplyError(
  334. "The operation's base length must be equal to the string's length.",
  335. operation,
  336. length
  337. )
  338. }
  339. const { length: newLength, inputCursor } = this.ops.reduce(
  340. (intermediate, op) => op.applyToLength(intermediate),
  341. { length: 0, inputCursor: 0, inputLength: length }
  342. )
  343. if (inputCursor !== length) {
  344. throw new TextOperation.ApplyError(
  345. "The operation didn't operate on the whole string.",
  346. operation,
  347. length
  348. )
  349. }
  350. if (newLength > TextOperation.MAX_STRING_LENGTH) {
  351. throw new TextOperation.TooLongError(operation, newLength)
  352. }
  353. return newLength
  354. }
  355. /**
  356. * @inheritdoc
  357. * @param {StringFileData} previousState
  358. */
  359. invert(previousState) {
  360. const str = previousState.getContent()
  361. let strIndex = 0
  362. const inverse = new TextOperation()
  363. const ops = this.ops
  364. for (let i = 0, l = ops.length; i < l; i++) {
  365. const op = ops[i]
  366. if (op instanceof RetainOp) {
  367. if (op.tracking) {
  368. // Where we need to end up after the retains
  369. const target = strIndex + op.length
  370. // A previous retain could have overriden some tracking info. Now we
  371. // need to restore it.
  372. const previousChanges = previousState.trackedChanges.intersectRange(
  373. new Range(strIndex, op.length)
  374. )
  375. for (const change of previousChanges) {
  376. if (strIndex < change.range.start) {
  377. inverse.retain(change.range.start - strIndex, {
  378. tracking: new ClearTrackingProps(),
  379. })
  380. strIndex = change.range.start
  381. }
  382. inverse.retain(change.range.length, {
  383. tracking: change.tracking,
  384. })
  385. strIndex += change.range.length
  386. }
  387. if (strIndex < target) {
  388. inverse.retain(target - strIndex, {
  389. tracking: new ClearTrackingProps(),
  390. })
  391. strIndex = target
  392. }
  393. } else {
  394. inverse.retain(op.length)
  395. strIndex += op.length
  396. }
  397. } else if (op instanceof InsertOp) {
  398. inverse.remove(op.insertion.length)
  399. } else if (op instanceof RemoveOp) {
  400. const segments = calculateTrackingCommentSegments(
  401. strIndex,
  402. op.length,
  403. previousState.comments,
  404. previousState.trackedChanges
  405. )
  406. for (const segment of segments) {
  407. inverse.insert(str.slice(strIndex, strIndex + segment.length), {
  408. tracking: segment.tracking,
  409. commentIds: segment.commentIds,
  410. })
  411. strIndex += segment.length
  412. }
  413. } else {
  414. throw new UnprocessableError('unknown scanop during inversion')
  415. }
  416. }
  417. return inverse
  418. }
  419. /**
  420. * @inheritdoc
  421. * @param {EditOperation} other
  422. */
  423. canBeComposedWithForUndo(other) {
  424. if (!(other instanceof TextOperation)) {
  425. return false
  426. }
  427. if (this.isNoop() || other.isNoop()) {
  428. return true
  429. }
  430. const startA = getStartIndex(this)
  431. const startB = getStartIndex(other)
  432. const simpleA = getSimpleOp(this)
  433. const simpleB = getSimpleOp(other)
  434. if (!simpleA || !simpleB) {
  435. return false
  436. }
  437. if (simpleA instanceof InsertOp && simpleB instanceof InsertOp) {
  438. return startA + simpleA.insertion.length === startB
  439. }
  440. if (simpleA instanceof RemoveOp && simpleB instanceof RemoveOp) {
  441. // there are two possibilities to delete: with backspace and with the
  442. // delete key.
  443. return startB + simpleB.length === startA || startA === startB
  444. }
  445. return false
  446. }
  447. /**
  448. * @inheritdoc
  449. * @param {EditOperation} other
  450. */
  451. canBeComposedWith(other) {
  452. if (!(other instanceof TextOperation)) {
  453. return false
  454. }
  455. return this.targetLength === other.baseLength
  456. }
  457. /**
  458. * @inheritdoc
  459. * @param {EditOperation} operation2
  460. */
  461. compose(operation2) {
  462. if (!(operation2 instanceof TextOperation)) {
  463. throw new Error(
  464. `Trying to compose TextOperation with ${operation2?.constructor?.name}.`
  465. )
  466. }
  467. const operation1 = this
  468. if (operation1.targetLength !== operation2.baseLength) {
  469. throw new Error(
  470. 'The base length of the second operation has to be the ' +
  471. 'target length of the first operation'
  472. )
  473. }
  474. const operation = new TextOperation() // the combined operation
  475. const ops1 = operation1.ops
  476. const ops2 = operation2.ops // for fast access
  477. let i1 = 0
  478. let i2 = 0 // current index into ops1 respectively ops2
  479. let op1 = ops1[i1++]
  480. let op2 = ops2[i2++] // current ops
  481. for (;;) {
  482. // Dispatch on the type of op1 and op2
  483. if (typeof op1 === 'undefined' && typeof op2 === 'undefined') {
  484. // end condition: both ops1 and ops2 have been processed
  485. break
  486. }
  487. if (op1 instanceof RemoveOp) {
  488. operation.remove(-op1.length)
  489. op1 = ops1[i1++]
  490. continue
  491. }
  492. if (op2 instanceof InsertOp) {
  493. operation.insert(op2.insertion, {
  494. tracking: op2.tracking,
  495. commentIds: op2.commentIds,
  496. })
  497. op2 = ops2[i2++]
  498. continue
  499. }
  500. if (typeof op1 === 'undefined') {
  501. throw new Error(
  502. 'Cannot compose operations: first operation is too short.'
  503. )
  504. }
  505. if (typeof op2 === 'undefined') {
  506. throw new Error(
  507. 'Cannot compose operations: first operation is too long.'
  508. )
  509. }
  510. if (op1 instanceof RetainOp && op2 instanceof RetainOp) {
  511. // If both have tracking info, use the latter one. Otherwise use the
  512. // tracking info from the former.
  513. const tracking = op2.tracking ?? op1.tracking
  514. if (op1.length > op2.length) {
  515. operation.retain(op2.length, {
  516. tracking,
  517. })
  518. op1 = new RetainOp(op1.length - op2.length, op1.tracking)
  519. op2 = ops2[i2++]
  520. } else if (op1.length === op2.length) {
  521. operation.retain(op1.length, {
  522. tracking,
  523. })
  524. op1 = ops1[i1++]
  525. op2 = ops2[i2++]
  526. } else {
  527. operation.retain(op1.length, {
  528. tracking,
  529. })
  530. op2 = new RetainOp(op2.length - op1.length, op2.tracking)
  531. op1 = ops1[i1++]
  532. }
  533. } else if (op1 instanceof InsertOp && op2 instanceof RemoveOp) {
  534. if (op1.insertion.length > op2.length) {
  535. op1 = new InsertOp(
  536. op1.insertion.slice(op2.length),
  537. op1.tracking,
  538. op1.commentIds
  539. )
  540. op2 = ops2[i2++]
  541. } else if (op1.insertion.length === op2.length) {
  542. op1 = ops1[i1++]
  543. op2 = ops2[i2++]
  544. } else {
  545. op2 = RemoveOp.fromJSON(op1.insertion.length - op2.length)
  546. op1 = ops1[i1++]
  547. }
  548. } else if (op1 instanceof InsertOp && op2 instanceof RetainOp) {
  549. /** @type InsertOptions */
  550. const opts = {
  551. commentIds: op1.commentIds,
  552. }
  553. if (op2.tracking instanceof TrackingProps) {
  554. // Prefer the tracking info on the second operation
  555. opts.tracking = op2.tracking
  556. } else if (!(op2.tracking instanceof ClearTrackingProps)) {
  557. // The second operation does not cancel the first operation's tracking
  558. opts.tracking = op1.tracking
  559. }
  560. if (op1.insertion.length > op2.length) {
  561. operation.insert(op1.insertion.slice(0, op2.length), opts)
  562. op1 = new InsertOp(
  563. op1.insertion.slice(op2.length),
  564. op1.tracking,
  565. op1.commentIds
  566. )
  567. op2 = ops2[i2++]
  568. } else if (op1.insertion.length === op2.length) {
  569. operation.insert(op1.insertion, opts)
  570. op1 = ops1[i1++]
  571. op2 = ops2[i2++]
  572. } else {
  573. operation.insert(op1.insertion, opts)
  574. op2 = new RetainOp(op2.length - op1.insertion.length, op2.tracking)
  575. op1 = ops1[i1++]
  576. }
  577. } else if (op1 instanceof RetainOp && op2 instanceof RemoveOp) {
  578. if (op1.length > op2.length) {
  579. operation.remove(-op2.length)
  580. op1 = new RetainOp(op1.length - op2.length, op1.tracking)
  581. op2 = ops2[i2++]
  582. } else if (op1.length === op2.length) {
  583. operation.remove(-op2.length)
  584. op1 = ops1[i1++]
  585. op2 = ops2[i2++]
  586. } else {
  587. operation.remove(op1.length)
  588. op2 = RemoveOp.fromJSON(op1.length - op2.length)
  589. op1 = ops1[i1++]
  590. }
  591. } else {
  592. throw new Error(
  593. "This shouldn't happen: op1: " +
  594. JSON.stringify(op1) +
  595. ', op2: ' +
  596. JSON.stringify(op2)
  597. )
  598. }
  599. }
  600. return operation
  601. }
  602. /**
  603. * Transform takes two operations A and B that happened concurrently and
  604. * produces two operations A' and B' (in an array) such that
  605. * `apply(apply(S, A), B') = apply(apply(S, B), A')`. This function is the
  606. * heart of OT.
  607. * @param {TextOperation} operation1
  608. * @param {TextOperation} operation2
  609. * @returns {[TextOperation, TextOperation]}
  610. */
  611. static transform(operation1, operation2) {
  612. if (operation1.baseLength !== operation2.baseLength) {
  613. throw new Error('Both operations have to have the same base length')
  614. }
  615. const operation1prime = new TextOperation()
  616. const operation2prime = new TextOperation()
  617. const ops1 = operation1.ops
  618. const ops2 = operation2.ops
  619. let i1 = 0
  620. let i2 = 0
  621. let op1 = ops1[i1++]
  622. let op2 = ops2[i2++]
  623. for (;;) {
  624. // At every iteration of the loop, the imaginary cursor that both
  625. // operation1 and operation2 have that operates on the input string must
  626. // have the same position in the input string.
  627. if (typeof op1 === 'undefined' && typeof op2 === 'undefined') {
  628. // end condition: both ops1 and ops2 have been processed
  629. break
  630. }
  631. // next two cases: one or both ops are insert ops
  632. // => insert the string in the corresponding prime operation, skip it in
  633. // the other one. If both op1 and op2 are insert ops, prefer op1.
  634. if (op1 instanceof InsertOp) {
  635. operation1prime.insert(op1.insertion, {
  636. tracking: op1.tracking,
  637. commentIds: op1.commentIds,
  638. })
  639. operation2prime.retain(op1.insertion.length)
  640. op1 = ops1[i1++]
  641. continue
  642. }
  643. if (op2 instanceof InsertOp) {
  644. operation1prime.retain(op2.insertion.length)
  645. operation2prime.insert(op2.insertion, {
  646. tracking: op2.tracking,
  647. commentIds: op2.commentIds,
  648. })
  649. op2 = ops2[i2++]
  650. continue
  651. }
  652. if (typeof op1 === 'undefined') {
  653. throw new Error(
  654. 'Cannot compose operations: first operation is too short.'
  655. )
  656. }
  657. if (typeof op2 === 'undefined') {
  658. throw new Error(
  659. 'Cannot compose operations: first operation is too long.'
  660. )
  661. }
  662. let minl
  663. if (op1 instanceof RetainOp && op2 instanceof RetainOp) {
  664. // Simple case: retain/retain
  665. // If both have tracking info, we use the one from op1
  666. /** @type {TrackingProps | ClearTrackingProps | undefined} */
  667. let operation1primeTracking
  668. /** @type {TrackingProps | ClearTrackingProps | undefined} */
  669. let operation2primeTracking
  670. if (op1.tracking) {
  671. operation1primeTracking = op1.tracking
  672. } else {
  673. operation2primeTracking = op2.tracking
  674. }
  675. if (op1.length > op2.length) {
  676. minl = op2.length
  677. op1 = new RetainOp(op1.length - op2.length, op1.tracking)
  678. op2 = ops2[i2++]
  679. } else if (op1.length === op2.length) {
  680. minl = op2.length
  681. op1 = ops1[i1++]
  682. op2 = ops2[i2++]
  683. } else {
  684. minl = op1.length
  685. op2 = new RetainOp(op2.length - op1.length, op2.tracking)
  686. op1 = ops1[i1++]
  687. }
  688. operation1prime.retain(minl, { tracking: operation1primeTracking })
  689. operation2prime.retain(minl, { tracking: operation2primeTracking })
  690. } else if (op1 instanceof RemoveOp && op2 instanceof RemoveOp) {
  691. // Both operations remove the same string at the same position. We don't
  692. // need to produce any operations, we just skip over the remove ops and
  693. // handle the case that one operation removes more than the other.
  694. if (op1.length > op2.length) {
  695. op1 = RemoveOp.fromJSON(op2.length - op1.length)
  696. op2 = ops2[i2++]
  697. } else if (op1.length === op2.length) {
  698. op1 = ops1[i1++]
  699. op2 = ops2[i2++]
  700. } else {
  701. op2 = RemoveOp.fromJSON(op1.length - op2.length)
  702. op1 = ops1[i1++]
  703. }
  704. // next two cases: remove/retain and retain/remove
  705. } else if (op1 instanceof RemoveOp && op2 instanceof RetainOp) {
  706. if (op1.length > op2.length) {
  707. minl = op2.length
  708. op1 = RemoveOp.fromJSON(op2.length - op1.length)
  709. op2 = ops2[i2++]
  710. } else if (op1.length === op2.length) {
  711. minl = op2.length
  712. op1 = ops1[i1++]
  713. op2 = ops2[i2++]
  714. } else {
  715. minl = op1.length
  716. op2 = new RetainOp(op2.length - op1.length, op2.tracking)
  717. op1 = ops1[i1++]
  718. }
  719. operation1prime.remove(minl)
  720. } else if (op1 instanceof RetainOp && op2 instanceof RemoveOp) {
  721. if (op1.length > op2.length) {
  722. minl = op2.length
  723. op1 = new RetainOp(op1.length - op2.length, op1.tracking)
  724. op2 = ops2[i2++]
  725. } else if (op1.length === op2.length) {
  726. minl = op1.length
  727. op1 = ops1[i1++]
  728. op2 = ops2[i2++]
  729. } else {
  730. minl = op1.length
  731. op2 = RemoveOp.fromJSON(op1.length - op2.length)
  732. op1 = ops1[i1++]
  733. }
  734. operation2prime.remove(minl)
  735. } else {
  736. throw new Error("The two operations aren't compatible")
  737. }
  738. }
  739. return [operation1prime, operation2prime]
  740. }
  741. }
  742. // Operation are essentially lists of ops. There are three types of ops:
  743. //
  744. // * Retain ops: Advance the cursor position by a given number of characters.
  745. // Represented by positive ints.
  746. // * Insert ops: Insert a given string at the current cursor position.
  747. // Represented by strings.
  748. // * Remove ops: Remove the next n characters. Represented by negative ints.
  749. /**
  750. *
  751. * @param {TextOperation} operation
  752. * @returns {ScanOp | null}
  753. */
  754. function getSimpleOp(operation) {
  755. const ops = operation.ops
  756. switch (ops.length) {
  757. case 1:
  758. return ops[0]
  759. case 2:
  760. return ops[0] instanceof RetainOp
  761. ? ops[1]
  762. : ops[1] instanceof RetainOp
  763. ? ops[0]
  764. : null
  765. case 3:
  766. if (ops[0] instanceof RetainOp && ops[2] instanceof RetainOp) {
  767. return ops[1]
  768. }
  769. }
  770. return null
  771. }
  772. /**
  773. * @param {TextOperation} operation
  774. * @return {number}
  775. */
  776. function getStartIndex(operation) {
  777. if (operation.ops[0] instanceof RetainOp) {
  778. return operation.ops[0].length
  779. }
  780. return 0
  781. }
  782. /**
  783. * Constructs the segments defined as each overlapping range of tracked
  784. * changes and comments. Each segment can have it's own tracking props and
  785. * attached comment ids.
  786. *
  787. * The quick brown fox jumps over the lazy dog
  788. * Tracked inserts ---------- -----
  789. * Tracked deletes ------
  790. * Comment 1 -------
  791. * Comment 2 ----
  792. * Comment 3 -----------------
  793. *
  794. * Approx. boundaries: | | | || | | | |
  795. *
  796. * @param {number} cursor
  797. * @param {number} length
  798. * @param {import('../file_data/comment_list')} commentsList
  799. * @param {TrackedChangeList} trackedChangeList
  800. * @returns {{length: number, commentIds?: string[], tracking?: TrackingProps}[]}
  801. */
  802. function calculateTrackingCommentSegments(
  803. cursor,
  804. length,
  805. commentsList,
  806. trackedChangeList
  807. ) {
  808. const breaks = new Set()
  809. const opStart = cursor
  810. const opEnd = cursor + length
  811. /**
  812. * Utility function to limit breaks to the boundary set by the operation range
  813. * @param {number} rangeBoundary
  814. */
  815. function addBreak(rangeBoundary) {
  816. if (rangeBoundary < opStart || rangeBoundary > opEnd) {
  817. return
  818. }
  819. breaks.add(rangeBoundary)
  820. }
  821. // Add comment boundaries
  822. for (const comment of commentsList.comments.values()) {
  823. for (const range of comment.ranges) {
  824. addBreak(range.end)
  825. addBreak(range.start)
  826. }
  827. }
  828. // Add tracked change boundaries
  829. for (const trackedChange of trackedChangeList.asSorted()) {
  830. addBreak(trackedChange.range.start)
  831. addBreak(trackedChange.range.end)
  832. }
  833. // Add operation boundaries
  834. addBreak(opStart)
  835. addBreak(opEnd)
  836. // Sort the boundaries so that we can construct ranges between them
  837. const sortedBreaks = Array.from(breaks).sort((a, b) => a - b)
  838. const separateRanges = []
  839. for (let i = 1; i < sortedBreaks.length; i++) {
  840. const start = sortedBreaks[i - 1]
  841. const end = sortedBreaks[i]
  842. const currentRange = new Range(start, end - start)
  843. // The comment ids that cover the current range is part of this sub-range
  844. const commentIds = commentsList.idsCoveringRange(currentRange)
  845. // The tracking info that covers the current range is part of this sub-range
  846. const tracking = trackedChangeList.propsAtRange(currentRange)
  847. separateRanges.push({
  848. length: currentRange.length,
  849. commentIds: commentIds.length > 0 ? commentIds : undefined,
  850. tracking,
  851. })
  852. }
  853. return separateRanges
  854. }
  855. module.exports = TextOperation