text_operation.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682
  1. /**
  2. * The text operation from OT.js with some minor cosmetic changes.
  3. *
  4. * Specifically, this is based on
  5. * https://github.com/Operational-Transformation/ot.js/
  6. * blob/298825f58fb51fefb352e7df5ddbc668f4d5646f/lib/text-operation.js
  7. * from 18 Mar 2013.
  8. */
  9. 'use strict'
  10. const containsNonBmpChars = require('../util').containsNonBmpChars
  11. const OError = require('@overleaf/o-error')
  12. /**
  13. * Create an empty text operation.
  14. *
  15. * @class
  16. */
  17. function TextOperation() {
  18. // When an operation is applied to an input string, you can think of this as
  19. // if an imaginary cursor runs over the entire string and skips over some
  20. // parts, removes some parts and inserts characters at some positions. These
  21. // actions (skip/remove/insert) are stored as an array in the "ops" property.
  22. this.ops = []
  23. // An operation's baseLength is the length of every string the operation
  24. // can be applied to.
  25. this.baseLength = 0
  26. // The targetLength is the length of every string that results from applying
  27. // the operation on a valid input string.
  28. this.targetLength = 0
  29. }
  30. /**
  31. * Length of the longest file that we'll attempt to edit, in characters.
  32. *
  33. * @type {number}
  34. */
  35. TextOperation.MAX_STRING_LENGTH = 2 * Math.pow(1024, 2)
  36. TextOperation.prototype.equals = function (other) {
  37. if (this.baseLength !== other.baseLength) {
  38. return false
  39. }
  40. if (this.targetLength !== other.targetLength) {
  41. return false
  42. }
  43. if (this.ops.length !== other.ops.length) {
  44. return false
  45. }
  46. for (let i = 0; i < this.ops.length; i++) {
  47. if (this.ops[i] !== other.ops[i]) {
  48. return false
  49. }
  50. }
  51. return true
  52. }
  53. class UnprocessableError extends OError {}
  54. TextOperation.UnprocessableError = UnprocessableError
  55. class ApplyError extends UnprocessableError {
  56. constructor(message, operation, operand) {
  57. super(message, { operation, operand })
  58. this.operation = operation
  59. this.operand = operand
  60. }
  61. }
  62. TextOperation.ApplyError = ApplyError
  63. class InvalidInsertionError extends UnprocessableError {
  64. constructor(str, operation) {
  65. super('inserted text contains non BMP characters', { str, operation })
  66. this.str = str
  67. this.operation = operation
  68. }
  69. }
  70. TextOperation.InvalidInsertionError = InvalidInsertionError
  71. class TooLongError extends UnprocessableError {
  72. constructor(operation, resultLength) {
  73. super(`resulting string would be too long: ${resultLength}`, {
  74. operation,
  75. resultLength,
  76. })
  77. this.operation = operation
  78. this.resultLength = resultLength
  79. }
  80. }
  81. TextOperation.TooLongError = TooLongError
  82. // Operation are essentially lists of ops. There are three types of ops:
  83. //
  84. // * Retain ops: Advance the cursor position by a given number of characters.
  85. // Represented by positive ints.
  86. // * Insert ops: Insert a given string at the current cursor position.
  87. // Represented by strings.
  88. // * Remove ops: Remove the next n characters. Represented by negative ints.
  89. const isRetain = (TextOperation.isRetain = function (op) {
  90. return typeof op === 'number' && op > 0
  91. })
  92. const isInsert = (TextOperation.isInsert = function (op) {
  93. return typeof op === 'string'
  94. })
  95. const isRemove = (TextOperation.isRemove = function (op) {
  96. return typeof op === 'number' && op < 0
  97. })
  98. // After an operation is constructed, the user of the library can specify the
  99. // actions of an operation (skip/insert/remove) with these three builder
  100. // methods. They all return the operation for convenient chaining.
  101. // Skip over a given number of characters.
  102. TextOperation.prototype.retain = function (n) {
  103. if (typeof n !== 'number') {
  104. throw new Error('retain expects an integer')
  105. }
  106. if (n === 0) {
  107. return this
  108. }
  109. this.baseLength += n
  110. this.targetLength += n
  111. if (isRetain(this.ops[this.ops.length - 1])) {
  112. // The last op is a retain op => we can merge them into one op.
  113. this.ops[this.ops.length - 1] += n
  114. } else {
  115. // Create a new op.
  116. this.ops.push(n)
  117. }
  118. return this
  119. }
  120. // Insert a string at the current position.
  121. TextOperation.prototype.insert = function (str) {
  122. if (typeof str !== 'string') {
  123. throw new Error('insert expects a string')
  124. }
  125. if (containsNonBmpChars(str)) {
  126. throw new TextOperation.InvalidInsertionError(str)
  127. }
  128. if (str === '') {
  129. return this
  130. }
  131. this.targetLength += str.length
  132. const ops = this.ops
  133. if (isInsert(ops[ops.length - 1])) {
  134. // Merge insert op.
  135. ops[ops.length - 1] += str
  136. } else if (isRemove(ops[ops.length - 1])) {
  137. // It doesn't matter when an operation is applied whether the operation
  138. // is remove(3), insert("something") or insert("something"), remove(3).
  139. // Here we enforce that in this case, the insert op always comes first.
  140. // This makes all operations that have the same effect when applied to
  141. // a document of the right length equal in respect to the `equals` method.
  142. if (isInsert(ops[ops.length - 2])) {
  143. ops[ops.length - 2] += str
  144. } else {
  145. ops[ops.length] = ops[ops.length - 1]
  146. ops[ops.length - 2] = str
  147. }
  148. } else {
  149. ops.push(str)
  150. }
  151. return this
  152. }
  153. // Remove a string at the current position.
  154. TextOperation.prototype.remove = function (n) {
  155. if (typeof n === 'string') {
  156. n = n.length
  157. }
  158. if (typeof n !== 'number') {
  159. throw new Error('remove expects an integer or a string')
  160. }
  161. if (n === 0) {
  162. return this
  163. }
  164. if (n > 0) {
  165. n = -n
  166. }
  167. this.baseLength -= n
  168. if (isRemove(this.ops[this.ops.length - 1])) {
  169. this.ops[this.ops.length - 1] += n
  170. } else {
  171. this.ops.push(n)
  172. }
  173. return this
  174. }
  175. // Tests whether this operation has no effect.
  176. TextOperation.prototype.isNoop = function () {
  177. return (
  178. this.ops.length === 0 || (this.ops.length === 1 && isRetain(this.ops[0]))
  179. )
  180. }
  181. // Pretty printing.
  182. TextOperation.prototype.toString = function () {
  183. return this.ops
  184. .map(op => {
  185. if (isRetain(op)) {
  186. return 'retain ' + op
  187. } else if (isInsert(op)) {
  188. return "insert '" + op + "'"
  189. } else {
  190. return 'remove ' + -op
  191. }
  192. })
  193. .join(', ')
  194. }
  195. // Converts operation into a JSON value.
  196. TextOperation.prototype.toJSON = function () {
  197. return this.ops
  198. }
  199. // Converts a plain JS object into an operation and validates it.
  200. TextOperation.fromJSON = function (ops) {
  201. const o = new TextOperation()
  202. for (let i = 0, l = ops.length; i < l; i++) {
  203. const op = ops[i]
  204. if (isRetain(op)) {
  205. o.retain(op)
  206. } else if (isInsert(op)) {
  207. o.insert(op)
  208. } else if (isRemove(op)) {
  209. o.remove(op)
  210. } else {
  211. throw new Error(
  212. 'unknown operation: ' +
  213. JSON.stringify(op) +
  214. ' in ' +
  215. JSON.stringify(ops)
  216. )
  217. }
  218. }
  219. return o
  220. }
  221. // Apply an operation to a string, returning a new string. Throws an error if
  222. // there's a mismatch between the input string and the operation.
  223. TextOperation.prototype.apply = function (str) {
  224. const operation = this
  225. if (containsNonBmpChars(str)) {
  226. throw new TextOperation.ApplyError(
  227. 'The string contains non BMP characters.',
  228. operation,
  229. str
  230. )
  231. }
  232. if (str.length !== operation.baseLength) {
  233. throw new TextOperation.ApplyError(
  234. "The operation's base length must be equal to the string's length.",
  235. operation,
  236. str
  237. )
  238. }
  239. // Build up the result string directly by concatenation (which is actually
  240. // faster than joining arrays because it is optimised in v8).
  241. let result = ''
  242. let strIndex = 0
  243. const ops = this.ops
  244. for (let i = 0, l = ops.length; i < l; i++) {
  245. const op = ops[i]
  246. if (isRetain(op)) {
  247. if (strIndex + op > str.length) {
  248. throw new TextOperation.ApplyError(
  249. "Operation can't retain more chars than are left in the string.",
  250. operation,
  251. str
  252. )
  253. }
  254. // Copy skipped part of the old string.
  255. result += str.slice(strIndex, strIndex + op)
  256. strIndex += op
  257. } else if (isInsert(op)) {
  258. if (containsNonBmpChars(op)) {
  259. throw new TextOperation.InvalidInsertionError(str, operation)
  260. }
  261. // Insert string.
  262. result += op
  263. } else {
  264. // remove op
  265. strIndex -= op
  266. }
  267. }
  268. if (strIndex !== str.length) {
  269. throw new TextOperation.ApplyError(
  270. "The operation didn't operate on the whole string.",
  271. operation,
  272. str
  273. )
  274. }
  275. if (result.length > TextOperation.MAX_STRING_LENGTH) {
  276. throw new TextOperation.TooLongError(operation, result.length)
  277. }
  278. return result
  279. }
  280. /**
  281. * Determine the effect of this operation on the length of the text.
  282. *
  283. * NB: This is an Overleaf addition to the original TextOperation.
  284. *
  285. * @param {number} length of the original string; non-negative
  286. * @return {number} length of the new string; non-negative
  287. */
  288. TextOperation.prototype.applyToLength = function (length) {
  289. const operation = this
  290. if (length !== operation.baseLength) {
  291. throw new TextOperation.ApplyError(
  292. "The operation's base length must be equal to the string's length.",
  293. operation,
  294. length
  295. )
  296. }
  297. let newLength = 0
  298. let strIndex = 0
  299. const ops = this.ops
  300. for (let i = 0, l = ops.length; i < l; i++) {
  301. const op = ops[i]
  302. if (isRetain(op)) {
  303. if (strIndex + op > length) {
  304. throw new TextOperation.ApplyError(
  305. "Operation can't retain more chars than are left in the string.",
  306. operation,
  307. length
  308. )
  309. }
  310. // Copy skipped part of the old string.
  311. newLength += op
  312. strIndex += op
  313. } else if (isInsert(op)) {
  314. // Insert string.
  315. newLength += op.length
  316. } else {
  317. // remove op
  318. strIndex -= op
  319. }
  320. }
  321. if (strIndex !== length) {
  322. throw new TextOperation.ApplyError(
  323. "The operation didn't operate on the whole string.",
  324. operation,
  325. length
  326. )
  327. }
  328. if (newLength > TextOperation.MAX_STRING_LENGTH) {
  329. throw new TextOperation.TooLongError(operation, newLength)
  330. }
  331. return newLength
  332. }
  333. // Computes the inverse of an operation. The inverse of an operation is the
  334. // operation that reverts the effects of the operation, e.g. when you have an
  335. // operation 'insert("hello "); skip(6);' then the inverse is 'remove("hello ");
  336. // skip(6);'. The inverse should be used for implementing undo.
  337. TextOperation.prototype.invert = function (str) {
  338. let strIndex = 0
  339. const inverse = new TextOperation()
  340. const ops = this.ops
  341. for (let i = 0, l = ops.length; i < l; i++) {
  342. const op = ops[i]
  343. if (isRetain(op)) {
  344. inverse.retain(op)
  345. strIndex += op
  346. } else if (isInsert(op)) {
  347. inverse.remove(op.length)
  348. } else {
  349. // remove op
  350. inverse.insert(str.slice(strIndex, strIndex - op))
  351. strIndex -= op
  352. }
  353. }
  354. return inverse
  355. }
  356. // When you use ctrl-z to undo your latest changes, you expect the program not
  357. // to undo every single keystroke but to undo your last sentence you wrote at
  358. // a stretch or the deletion you did by holding the backspace key down. This
  359. // This can be implemented by composing operations on the undo stack. This
  360. // method can help decide whether two operations should be composed. It
  361. // returns true if the operations are consecutive insert operations or both
  362. // operations delete text at the same position. You may want to include other
  363. // factors like the time since the last change in your decision.
  364. TextOperation.prototype.canBeComposedWithForUndo = function (other) {
  365. if (this.isNoop() || other.isNoop()) {
  366. return true
  367. }
  368. const startA = getStartIndex(this)
  369. const startB = getStartIndex(other)
  370. const simpleA = getSimpleOp(this)
  371. const simpleB = getSimpleOp(other)
  372. if (!simpleA || !simpleB) {
  373. return false
  374. }
  375. if (isInsert(simpleA) && isInsert(simpleB)) {
  376. return startA + simpleA.length === startB
  377. }
  378. if (isRemove(simpleA) && isRemove(simpleB)) {
  379. // there are two possibilities to delete: with backspace and with the
  380. // delete key.
  381. return startB - simpleB === startA || startA === startB
  382. }
  383. return false
  384. }
  385. /**
  386. * @inheritdoc
  387. */
  388. TextOperation.prototype.canBeComposedWith = function (other) {
  389. return this.targetLength === other.baseLength
  390. }
  391. // Compose merges two consecutive operations into one operation, that
  392. // preserves the changes of both. Or, in other words, for each input string S
  393. // and a pair of consecutive operations A and B,
  394. // apply(apply(S, A), B) = apply(S, compose(A, B)) must hold.
  395. TextOperation.prototype.compose = function (operation2) {
  396. const operation1 = this
  397. if (operation1.targetLength !== operation2.baseLength) {
  398. throw new Error(
  399. 'The base length of the second operation has to be the ' +
  400. 'target length of the first operation'
  401. )
  402. }
  403. const operation = new TextOperation() // the combined operation
  404. const ops1 = operation1.ops
  405. const ops2 = operation2.ops // for fast access
  406. let i1 = 0
  407. let i2 = 0 // current index into ops1 respectively ops2
  408. let op1 = ops1[i1++]
  409. let op2 = ops2[i2++] // current ops
  410. for (;;) {
  411. // Dispatch on the type of op1 and op2
  412. if (typeof op1 === 'undefined' && typeof op2 === 'undefined') {
  413. // end condition: both ops1 and ops2 have been processed
  414. break
  415. }
  416. if (isRemove(op1)) {
  417. operation.remove(op1)
  418. op1 = ops1[i1++]
  419. continue
  420. }
  421. if (isInsert(op2)) {
  422. operation.insert(op2)
  423. op2 = ops2[i2++]
  424. continue
  425. }
  426. if (typeof op1 === 'undefined') {
  427. throw new Error(
  428. 'Cannot compose operations: first operation is too short.'
  429. )
  430. }
  431. if (typeof op2 === 'undefined') {
  432. throw new Error('Cannot compose operations: first operation is too long.')
  433. }
  434. if (isRetain(op1) && isRetain(op2)) {
  435. if (op1 > op2) {
  436. operation.retain(op2)
  437. op1 = op1 - op2
  438. op2 = ops2[i2++]
  439. } else if (op1 === op2) {
  440. operation.retain(op1)
  441. op1 = ops1[i1++]
  442. op2 = ops2[i2++]
  443. } else {
  444. operation.retain(op1)
  445. op2 = op2 - op1
  446. op1 = ops1[i1++]
  447. }
  448. } else if (isInsert(op1) && isRemove(op2)) {
  449. if (op1.length > -op2) {
  450. op1 = op1.slice(-op2)
  451. op2 = ops2[i2++]
  452. } else if (op1.length === -op2) {
  453. op1 = ops1[i1++]
  454. op2 = ops2[i2++]
  455. } else {
  456. op2 = op2 + op1.length
  457. op1 = ops1[i1++]
  458. }
  459. } else if (isInsert(op1) && isRetain(op2)) {
  460. if (op1.length > op2) {
  461. operation.insert(op1.slice(0, op2))
  462. op1 = op1.slice(op2)
  463. op2 = ops2[i2++]
  464. } else if (op1.length === op2) {
  465. operation.insert(op1)
  466. op1 = ops1[i1++]
  467. op2 = ops2[i2++]
  468. } else {
  469. operation.insert(op1)
  470. op2 = op2 - op1.length
  471. op1 = ops1[i1++]
  472. }
  473. } else if (isRetain(op1) && isRemove(op2)) {
  474. if (op1 > -op2) {
  475. operation.remove(op2)
  476. op1 = op1 + op2
  477. op2 = ops2[i2++]
  478. } else if (op1 === -op2) {
  479. operation.remove(op2)
  480. op1 = ops1[i1++]
  481. op2 = ops2[i2++]
  482. } else {
  483. operation.remove(op1)
  484. op2 = op2 + op1
  485. op1 = ops1[i1++]
  486. }
  487. } else {
  488. throw new Error(
  489. "This shouldn't happen: op1: " +
  490. JSON.stringify(op1) +
  491. ', op2: ' +
  492. JSON.stringify(op2)
  493. )
  494. }
  495. }
  496. return operation
  497. }
  498. function getSimpleOp(operation, fn) {
  499. const ops = operation.ops
  500. switch (ops.length) {
  501. case 1:
  502. return ops[0]
  503. case 2:
  504. return isRetain(ops[0]) ? ops[1] : isRetain(ops[1]) ? ops[0] : null
  505. case 3:
  506. if (isRetain(ops[0]) && isRetain(ops[2])) {
  507. return ops[1]
  508. }
  509. }
  510. return null
  511. }
  512. function getStartIndex(operation) {
  513. if (isRetain(operation.ops[0])) {
  514. return operation.ops[0]
  515. }
  516. return 0
  517. }
  518. // Transform takes two operations A and B that happened concurrently and
  519. // produces two operations A' and B' (in an array) such that
  520. // `apply(apply(S, A), B') = apply(apply(S, B), A')`. This function is the
  521. // heart of OT.
  522. TextOperation.transform = function (operation1, operation2) {
  523. if (operation1.baseLength !== operation2.baseLength) {
  524. throw new Error('Both operations have to have the same base length')
  525. }
  526. const operation1prime = new TextOperation()
  527. const operation2prime = new TextOperation()
  528. const ops1 = operation1.ops
  529. const ops2 = operation2.ops
  530. let i1 = 0
  531. let i2 = 0
  532. let op1 = ops1[i1++]
  533. let op2 = ops2[i2++]
  534. for (;;) {
  535. // At every iteration of the loop, the imaginary cursor that both
  536. // operation1 and operation2 have that operates on the input string must
  537. // have the same position in the input string.
  538. if (typeof op1 === 'undefined' && typeof op2 === 'undefined') {
  539. // end condition: both ops1 and ops2 have been processed
  540. break
  541. }
  542. // next two cases: one or both ops are insert ops
  543. // => insert the string in the corresponding prime operation, skip it in
  544. // the other one. If both op1 and op2 are insert ops, prefer op1.
  545. if (isInsert(op1)) {
  546. operation1prime.insert(op1)
  547. operation2prime.retain(op1.length)
  548. op1 = ops1[i1++]
  549. continue
  550. }
  551. if (isInsert(op2)) {
  552. operation1prime.retain(op2.length)
  553. operation2prime.insert(op2)
  554. op2 = ops2[i2++]
  555. continue
  556. }
  557. if (typeof op1 === 'undefined') {
  558. throw new Error(
  559. 'Cannot compose operations: first operation is too short.'
  560. )
  561. }
  562. if (typeof op2 === 'undefined') {
  563. throw new Error('Cannot compose operations: first operation is too long.')
  564. }
  565. let minl
  566. if (isRetain(op1) && isRetain(op2)) {
  567. // Simple case: retain/retain
  568. if (op1 > op2) {
  569. minl = op2
  570. op1 = op1 - op2
  571. op2 = ops2[i2++]
  572. } else if (op1 === op2) {
  573. minl = op2
  574. op1 = ops1[i1++]
  575. op2 = ops2[i2++]
  576. } else {
  577. minl = op1
  578. op2 = op2 - op1
  579. op1 = ops1[i1++]
  580. }
  581. operation1prime.retain(minl)
  582. operation2prime.retain(minl)
  583. } else if (isRemove(op1) && isRemove(op2)) {
  584. // Both operations remove the same string at the same position. We don't
  585. // need to produce any operations, we just skip over the remove ops and
  586. // handle the case that one operation removes more than the other.
  587. if (-op1 > -op2) {
  588. op1 = op1 - op2
  589. op2 = ops2[i2++]
  590. } else if (op1 === op2) {
  591. op1 = ops1[i1++]
  592. op2 = ops2[i2++]
  593. } else {
  594. op2 = op2 - op1
  595. op1 = ops1[i1++]
  596. }
  597. // next two cases: remove/retain and retain/remove
  598. } else if (isRemove(op1) && isRetain(op2)) {
  599. if (-op1 > op2) {
  600. minl = op2
  601. op1 = op1 + op2
  602. op2 = ops2[i2++]
  603. } else if (-op1 === op2) {
  604. minl = op2
  605. op1 = ops1[i1++]
  606. op2 = ops2[i2++]
  607. } else {
  608. minl = -op1
  609. op2 = op2 + op1
  610. op1 = ops1[i1++]
  611. }
  612. operation1prime.remove(minl)
  613. } else if (isRetain(op1) && isRemove(op2)) {
  614. if (op1 > -op2) {
  615. minl = -op2
  616. op1 = op1 + op2
  617. op2 = ops2[i2++]
  618. } else if (op1 === -op2) {
  619. minl = op1
  620. op1 = ops1[i1++]
  621. op2 = ops2[i2++]
  622. } else {
  623. minl = op1
  624. op2 = op2 + op1
  625. op1 = ops1[i1++]
  626. }
  627. operation2prime.remove(minl)
  628. } else {
  629. throw new Error("The two operations aren't compatible")
  630. }
  631. }
  632. return [operation1prime, operation2prime]
  633. }
  634. module.exports = TextOperation