text-composable.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. /* eslint-disable
  2. no-cond-assign,
  3. no-return-assign,
  4. no-undef,
  5. no-unused-vars,
  6. */
  7. // TODO: This file was created by bulk-decaffeinate.
  8. // Fix any style issues and re-enable lint.
  9. /*
  10. * decaffeinate suggestions:
  11. * DS101: Remove unnecessary use of Array.from
  12. * DS102: Remove unnecessary code created because of implicit returns
  13. * DS205: Consider reworking code to avoid use of IIFEs
  14. * DS207: Consider shorter variations of null checks
  15. * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  16. */
  17. // An alternate composable implementation for text. This is much closer
  18. // to the implementation used by google wave.
  19. //
  20. // Ops are lists of components which iterate over the whole document.
  21. // Components are either:
  22. // A number N: Skip N characters in the original document
  23. // {i:'str'}: Insert 'str' at the current position in the document
  24. // {d:'str'}: Delete 'str', which appears at the current position in the document
  25. //
  26. // Eg: [3, {i:'hi'}, 5, {d:'internet'}]
  27. //
  28. // Snapshots are strings.
  29. let makeAppend
  30. const p = function () {} // require('util').debug
  31. const i = function () {} // require('util').inspect
  32. const exports = typeof WEB !== 'undefined' && WEB !== null ? {} : module.exports
  33. exports.name = 'text-composable'
  34. exports.create = () => ''
  35. // -------- Utility methods
  36. const checkOp = function (op) {
  37. if (!Array.isArray(op)) {
  38. throw new Error('Op must be an array of components')
  39. }
  40. let last = null
  41. return (() => {
  42. const result = []
  43. for (const c of Array.from(op)) {
  44. if (typeof c === 'object') {
  45. if (
  46. (c.i == null || !(c.i.length > 0)) &&
  47. (c.d == null || !(c.d.length > 0))
  48. ) {
  49. throw new Error(`Invalid op component: ${i(c)}`)
  50. }
  51. } else {
  52. if (typeof c !== 'number') {
  53. throw new Error('Op components must be objects or numbers')
  54. }
  55. if (!(c > 0)) {
  56. throw new Error('Skip components must be a positive number')
  57. }
  58. if (typeof last === 'number') {
  59. throw new Error('Adjacent skip components should be added')
  60. }
  61. }
  62. result.push((last = c))
  63. }
  64. return result
  65. })()
  66. }
  67. // Makes a function for appending components to a given op.
  68. // Exported for the randomOpGenerator.
  69. exports._makeAppend = makeAppend = op =>
  70. function (component) {
  71. if (component === 0 || component.i === '' || component.d === '') {
  72. } else if (op.length === 0) {
  73. return op.push(component)
  74. } else if (
  75. typeof component === 'number' &&
  76. typeof op[op.length - 1] === 'number'
  77. ) {
  78. return (op[op.length - 1] += component)
  79. } else if (component.i != null && op[op.length - 1].i != null) {
  80. return (op[op.length - 1].i += component.i)
  81. } else if (component.d != null && op[op.length - 1].d != null) {
  82. return (op[op.length - 1].d += component.d)
  83. } else {
  84. return op.push(component)
  85. }
  86. }
  87. // checkOp op
  88. // Makes 2 functions for taking components from the start of an op, and for peeking
  89. // at the next op that could be taken.
  90. const makeTake = function (op) {
  91. // The index of the next component to take
  92. let idx = 0
  93. // The offset into the component
  94. let offset = 0
  95. // Take up to length n from the front of op. If n is null, take the next
  96. // op component. If indivisableField == 'd', delete components won't be separated.
  97. // If indivisableField == 'i', insert components won't be separated.
  98. const take = function (n, indivisableField) {
  99. let c
  100. if (idx === op.length) {
  101. return null
  102. }
  103. // assert.notStrictEqual op.length, i, 'The op is too short to traverse the document'
  104. if (typeof op[idx] === 'number') {
  105. if (n == null || op[idx] - offset <= n) {
  106. c = op[idx] - offset
  107. ++idx
  108. offset = 0
  109. return c
  110. } else {
  111. offset += n
  112. return n
  113. }
  114. } else {
  115. // Take from the string
  116. const field = op[idx].i ? 'i' : 'd'
  117. c = {}
  118. if (
  119. n == null ||
  120. op[idx][field].length - offset <= n ||
  121. field === indivisableField
  122. ) {
  123. c[field] = op[idx][field].slice(offset)
  124. ++idx
  125. offset = 0
  126. } else {
  127. c[field] = op[idx][field].slice(offset, offset + n)
  128. offset += n
  129. }
  130. return c
  131. }
  132. }
  133. const peekType = () => op[idx]
  134. return [take, peekType]
  135. }
  136. // Find and return the length of an op component
  137. const componentLength = function (component) {
  138. if (typeof component === 'number') {
  139. return component
  140. } else if (component.i != null) {
  141. return component.i.length
  142. } else {
  143. return component.d.length
  144. }
  145. }
  146. // Normalize an op, removing all empty skips and empty inserts / deletes. Concatenate
  147. // adjacent inserts and deletes.
  148. exports.normalize = function (op) {
  149. const newOp = []
  150. const append = makeAppend(newOp)
  151. for (const component of Array.from(op)) {
  152. append(component)
  153. }
  154. return newOp
  155. }
  156. // Apply the op to the string. Returns the new string.
  157. exports.apply = function (str, op) {
  158. p(`Applying ${i(op)} to '${str}'`)
  159. if (typeof str !== 'string') {
  160. throw new Error('Snapshot should be a string')
  161. }
  162. checkOp(op)
  163. const pos = 0
  164. const newDoc = []
  165. for (const component of Array.from(op)) {
  166. if (typeof component === 'number') {
  167. if (component > str.length) {
  168. throw new Error('The op is too long for this document')
  169. }
  170. newDoc.push(str.slice(0, component))
  171. str = str.slice(component)
  172. } else if (component.i != null) {
  173. newDoc.push(component.i)
  174. } else {
  175. if (component.d !== str.slice(0, component.d.length)) {
  176. throw new Error(
  177. `The deleted text '${
  178. component.d
  179. }' doesn't match the next characters in the document '${str.slice(
  180. 0,
  181. component.d.length
  182. )}'`
  183. )
  184. }
  185. str = str.slice(component.d.length)
  186. }
  187. }
  188. if (str !== '') {
  189. throw new Error("The applied op doesn't traverse the entire document")
  190. }
  191. return newDoc.join('')
  192. }
  193. // transform op1 by op2. Return transformed version of op1.
  194. // op1 and op2 are unchanged by transform.
  195. exports.transform = function (op, otherOp, side) {
  196. let component
  197. if (side !== 'left' && side !== 'right') {
  198. throw new Error(`side (${side} must be 'left' or 'right'`)
  199. }
  200. checkOp(op)
  201. checkOp(otherOp)
  202. const newOp = []
  203. const append = makeAppend(newOp)
  204. const [take, peek] = Array.from(makeTake(op))
  205. for (component of Array.from(otherOp)) {
  206. var chunk, length
  207. if (typeof component === 'number') {
  208. // Skip
  209. length = component
  210. while (length > 0) {
  211. chunk = take(length, 'i')
  212. if (chunk === null) {
  213. throw new Error(
  214. 'The op traverses more elements than the document has'
  215. )
  216. }
  217. append(chunk)
  218. if (typeof chunk !== 'object' || chunk.i == null) {
  219. length -= componentLength(chunk)
  220. }
  221. }
  222. } else if (component.i != null) {
  223. // Insert
  224. if (side === 'left') {
  225. // The left insert should go first.
  226. const o = peek()
  227. if (o != null ? o.i : undefined) {
  228. append(take())
  229. }
  230. }
  231. // Otherwise, skip the inserted text.
  232. append(component.i.length)
  233. } else {
  234. // Delete.
  235. // assert.ok component.d
  236. ;({ length } = component.d)
  237. while (length > 0) {
  238. chunk = take(length, 'i')
  239. if (chunk === null) {
  240. throw new Error(
  241. 'The op traverses more elements than the document has'
  242. )
  243. }
  244. if (typeof chunk === 'number') {
  245. length -= chunk
  246. } else if (chunk.i != null) {
  247. append(chunk)
  248. } else {
  249. // assert.ok chunk.d
  250. // The delete is unnecessary now.
  251. length -= chunk.d.length
  252. }
  253. }
  254. }
  255. }
  256. // Append extras from op1
  257. while ((component = take())) {
  258. if ((component != null ? component.i : undefined) == null) {
  259. throw new Error(`Remaining fragments in the op: ${i(component)}`)
  260. }
  261. append(component)
  262. }
  263. return newOp
  264. }
  265. // Compose 2 ops into 1 op.
  266. exports.compose = function (op1, op2) {
  267. let component
  268. p(`COMPOSE ${i(op1)} + ${i(op2)}`)
  269. checkOp(op1)
  270. checkOp(op2)
  271. const result = []
  272. const append = makeAppend(result)
  273. const [take, _] = Array.from(makeTake(op1))
  274. for (component of Array.from(op2)) {
  275. var chunk, length
  276. if (typeof component === 'number') {
  277. // Skip
  278. length = component
  279. while (length > 0) {
  280. chunk = take(length, 'd')
  281. if (chunk === null) {
  282. throw new Error(
  283. 'The op traverses more elements than the document has'
  284. )
  285. }
  286. append(chunk)
  287. if (typeof chunk !== 'object' || chunk.d == null) {
  288. length -= componentLength(chunk)
  289. }
  290. }
  291. } else if (component.i != null) {
  292. // Insert
  293. append({ i: component.i })
  294. } else {
  295. // Delete
  296. let offset = 0
  297. while (offset < component.d.length) {
  298. chunk = take(component.d.length - offset, 'd')
  299. if (chunk === null) {
  300. throw new Error(
  301. 'The op traverses more elements than the document has'
  302. )
  303. }
  304. // If its delete, append it. If its skip, drop it and decrease length. If its insert, check the strings match, drop it and decrease length.
  305. if (typeof chunk === 'number') {
  306. append({ d: component.d.slice(offset, offset + chunk) })
  307. offset += chunk
  308. } else if (chunk.i != null) {
  309. if (component.d.slice(offset, offset + chunk.i.length) !== chunk.i) {
  310. throw new Error("The deleted text doesn't match the inserted text")
  311. }
  312. offset += chunk.i.length
  313. // The ops cancel each other out.
  314. } else {
  315. // Delete
  316. append(chunk)
  317. }
  318. }
  319. }
  320. }
  321. // Append extras from op1
  322. while ((component = take())) {
  323. if ((component != null ? component.d : undefined) == null) {
  324. throw new Error(`Trailing stuff in op1 ${i(component)}`)
  325. }
  326. append(component)
  327. }
  328. return result
  329. }
  330. const invertComponent = function (c) {
  331. if (typeof c === 'number') {
  332. return c
  333. } else if (c.i != null) {
  334. return { d: c.i }
  335. } else {
  336. return { i: c.d }
  337. }
  338. }
  339. // Invert an op
  340. exports.invert = function (op) {
  341. const result = []
  342. const append = makeAppend(result)
  343. for (const component of Array.from(op)) {
  344. append(invertComponent(component))
  345. }
  346. return result
  347. }
  348. if (typeof window !== 'undefined' && window !== null) {
  349. if (!window.ot) {
  350. window.ot = {}
  351. }
  352. if (!window.ot.types) {
  353. window.ot.types = {}
  354. }
  355. window.ot.types.text = exports
  356. }