text.js 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. /* eslint-disable
  2. no-return-assign,
  3. no-undef,
  4. */
  5. // TODO: This file was created by bulk-decaffeinate.
  6. // Fix any style issues and re-enable lint.
  7. /*
  8. * decaffeinate suggestions:
  9. * DS101: Remove unnecessary use of Array.from
  10. * DS102: Remove unnecessary code created because of implicit returns
  11. * DS207: Consider shorter variations of null checks
  12. * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  13. */
  14. // A simple text implementation
  15. //
  16. // Operations are lists of components.
  17. // Each component either inserts or deletes at a specified position in the document.
  18. //
  19. // Components are either:
  20. // {i:'str', p:100}: Insert 'str' at position 100 in the document
  21. // {d:'str', p:100}: Delete 'str' at position 100 in the document
  22. //
  23. // Components in an operation are executed sequentially, so the position of components
  24. // assumes previous components have already executed.
  25. //
  26. // Eg: This op:
  27. // [{i:'abc', p:0}]
  28. // is equivalent to this op:
  29. // [{i:'a', p:0}, {i:'b', p:1}, {i:'c', p:2}]
  30. // NOTE: The global scope here is shared with other sharejs files when built with closure.
  31. // Be careful what ends up in your namespace.
  32. let append, transformComponent
  33. const text = {}
  34. text.name = 'text'
  35. text.create = () => ''
  36. const strInject = (s1, pos, s2) => s1.slice(0, pos) + s2 + s1.slice(pos)
  37. const checkValidComponent = function (c) {
  38. if (typeof c.p !== 'number') {
  39. throw new Error('component missing position field')
  40. }
  41. const iType = typeof c.i
  42. const dType = typeof c.d
  43. if (!((iType === 'string') ^ (dType === 'string'))) {
  44. throw new Error('component needs an i or d field')
  45. }
  46. if (!(c.p >= 0)) {
  47. throw new Error('position cannot be negative')
  48. }
  49. }
  50. const checkValidOp = function (op) {
  51. for (const c of Array.from(op)) {
  52. checkValidComponent(c)
  53. }
  54. return true
  55. }
  56. text.apply = function (snapshot, op) {
  57. checkValidOp(op)
  58. for (const component of Array.from(op)) {
  59. if (component.i != null) {
  60. snapshot = strInject(snapshot, component.p, component.i)
  61. } else {
  62. const deleted = snapshot.slice(
  63. component.p,
  64. component.p + component.d.length
  65. )
  66. if (component.d !== deleted) {
  67. throw new Error(
  68. `Delete component '${component.d}' does not match deleted text '${deleted}'`
  69. )
  70. }
  71. snapshot =
  72. snapshot.slice(0, component.p) +
  73. snapshot.slice(component.p + component.d.length)
  74. }
  75. }
  76. return snapshot
  77. }
  78. // Exported for use by the random op generator.
  79. //
  80. // For simplicity, this version of append does not compress adjacent inserts and deletes of
  81. // the same text. It would be nice to change that at some stage.
  82. text._append = append = function (newOp, c) {
  83. if (c.i === '' || c.d === '') {
  84. return
  85. }
  86. if (newOp.length === 0) {
  87. return newOp.push(c)
  88. } else {
  89. const last = newOp[newOp.length - 1]
  90. // Compose the insert into the previous insert if possible
  91. if (
  92. last.i != null &&
  93. c.i != null &&
  94. last.p <= c.p &&
  95. c.p <= last.p + last.i.length
  96. ) {
  97. return (newOp[newOp.length - 1] = {
  98. i: strInject(last.i, c.p - last.p, c.i),
  99. p: last.p,
  100. })
  101. } else if (
  102. last.d != null &&
  103. c.d != null &&
  104. c.p <= last.p &&
  105. last.p <= c.p + c.d.length
  106. ) {
  107. return (newOp[newOp.length - 1] = {
  108. d: strInject(c.d, last.p - c.p, last.d),
  109. p: c.p,
  110. })
  111. } else {
  112. return newOp.push(c)
  113. }
  114. }
  115. }
  116. text.compose = function (op1, op2) {
  117. checkValidOp(op1)
  118. checkValidOp(op2)
  119. const newOp = op1.slice()
  120. for (const c of Array.from(op2)) {
  121. append(newOp, c)
  122. }
  123. return newOp
  124. }
  125. // Attempt to compress the op components together 'as much as possible'.
  126. // This implementation preserves order and preserves create/delete pairs.
  127. text.compress = op => text.compose([], op)
  128. text.normalize = function (op) {
  129. const newOp = []
  130. // Normalize should allow ops which are a single (unwrapped) component:
  131. // {i:'asdf', p:23}.
  132. // There's no good way to test if something is an array:
  133. // http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/
  134. // so this is probably the least bad solution.
  135. if (op.i != null || op.p != null) {
  136. op = [op]
  137. }
  138. for (const c of Array.from(op)) {
  139. if (c.p == null) {
  140. c.p = 0
  141. }
  142. append(newOp, c)
  143. }
  144. return newOp
  145. }
  146. // This helper method transforms a position by an op component.
  147. //
  148. // If c is an insert, insertAfter specifies whether the transform
  149. // is pushed after the insert (true) or before it (false).
  150. //
  151. // insertAfter is optional for deletes.
  152. const transformPosition = function (pos, c, insertAfter) {
  153. if (c.i != null) {
  154. if (c.p < pos || (c.p === pos && insertAfter)) {
  155. return pos + c.i.length
  156. } else {
  157. return pos
  158. }
  159. } else {
  160. // I think this could also be written as: Math.min(c.p, Math.min(c.p - otherC.p, otherC.d.length))
  161. // but I think its harder to read that way, and it compiles using ternary operators anyway
  162. // so its no slower written like this.
  163. if (pos <= c.p) {
  164. return pos
  165. } else if (pos <= c.p + c.d.length) {
  166. return c.p
  167. } else {
  168. return pos - c.d.length
  169. }
  170. }
  171. }
  172. // Helper method to transform a cursor position as a result of an op.
  173. //
  174. // Like transformPosition above, if c is an insert, insertAfter specifies whether the cursor position
  175. // is pushed after an insert (true) or before it (false).
  176. text.transformCursor = function (position, op, side) {
  177. const insertAfter = side === 'right'
  178. for (const c of Array.from(op)) {
  179. position = transformPosition(position, c, insertAfter)
  180. }
  181. return position
  182. }
  183. // Transform an op component by another op component. Asymmetric.
  184. // The result will be appended to destination.
  185. //
  186. // exported for use in JSON type
  187. text._tc = transformComponent = function (dest, c, otherC, side) {
  188. checkValidOp([c])
  189. checkValidOp([otherC])
  190. if (c.i != null) {
  191. append(dest, {
  192. i: c.i,
  193. p: transformPosition(c.p, otherC, side === 'right'),
  194. })
  195. } else {
  196. // Delete
  197. if (otherC.i != null) {
  198. // delete vs insert
  199. let s = c.d
  200. if (c.p < otherC.p) {
  201. append(dest, { d: s.slice(0, otherC.p - c.p), p: c.p })
  202. s = s.slice(otherC.p - c.p)
  203. }
  204. if (s !== '') {
  205. append(dest, { d: s, p: c.p + otherC.i.length })
  206. }
  207. } else {
  208. // Delete vs delete
  209. if (c.p >= otherC.p + otherC.d.length) {
  210. append(dest, { d: c.d, p: c.p - otherC.d.length })
  211. } else if (c.p + c.d.length <= otherC.p) {
  212. append(dest, c)
  213. } else {
  214. // They overlap somewhere.
  215. const newC = { d: '', p: c.p }
  216. if (c.p < otherC.p) {
  217. newC.d = c.d.slice(0, otherC.p - c.p)
  218. }
  219. if (c.p + c.d.length > otherC.p + otherC.d.length) {
  220. newC.d += c.d.slice(otherC.p + otherC.d.length - c.p)
  221. }
  222. // This is entirely optional - just for a check that the deleted
  223. // text in the two ops matches
  224. const intersectStart = Math.max(c.p, otherC.p)
  225. const intersectEnd = Math.min(
  226. c.p + c.d.length,
  227. otherC.p + otherC.d.length
  228. )
  229. const cIntersect = c.d.slice(intersectStart - c.p, intersectEnd - c.p)
  230. const otherIntersect = otherC.d.slice(
  231. intersectStart - otherC.p,
  232. intersectEnd - otherC.p
  233. )
  234. if (cIntersect !== otherIntersect) {
  235. throw new Error(
  236. 'Delete ops delete different text in the same region of the document'
  237. )
  238. }
  239. if (newC.d !== '') {
  240. // This could be rewritten similarly to insert v delete, above.
  241. newC.p = transformPosition(newC.p, otherC)
  242. append(dest, newC)
  243. }
  244. }
  245. }
  246. }
  247. return dest
  248. }
  249. const invertComponent = function (c) {
  250. if (c.i != null) {
  251. return { d: c.i, p: c.p }
  252. } else {
  253. return { i: c.d, p: c.p }
  254. }
  255. }
  256. // No need to use append for invert, because the components won't be able to
  257. // cancel with one another.
  258. text.invert = op =>
  259. Array.from(op.slice().reverse()).map(c => invertComponent(c))
  260. if (typeof WEB !== 'undefined' && WEB !== null) {
  261. if (!exports.types) {
  262. exports.types = {}
  263. }
  264. // This is kind of awful - come up with a better way to hook this helper code up.
  265. bootstrapTransform(text, transformComponent, checkValidOp, append)
  266. // [] is used to prevent closure from renaming types.text
  267. exports.types.text = text
  268. } else {
  269. module.exports = text
  270. // The text type really shouldn't need this - it should be possible to define
  271. // an efficient transform function by making a sort of transform map and passing each
  272. // op component through it.
  273. require('./helpers').bootstrapTransform(
  274. text,
  275. transformComponent,
  276. checkValidOp,
  277. append
  278. )
  279. }