text-tp2.coffee 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. # A TP2 implementation of text, following this spec:
  2. # http://code.google.com/p/lightwave/source/browse/trunk/experimental/ot/README
  3. #
  4. # A document is made up of a string and a set of tombstones inserted throughout
  5. # the string. For example, 'some ', (2 tombstones), 'string'.
  6. #
  7. # This is encoded in a document as: {s:'some string', t:[5, -2, 6]}
  8. #
  9. # Ops are lists of components which iterate over the whole document.
  10. # Components are either:
  11. # N: Skip N characters in the original document
  12. # {i:'str'}: Insert 'str' at the current position in the document
  13. # {i:N}: Insert N tombstones at the current position in the document
  14. # {d:N}: Delete (tombstone) N characters at the current position in the document
  15. #
  16. # Eg: [3, {i:'hi'}, 5, {d:8}]
  17. #
  18. # Snapshots are lists with characters and tombstones. Characters are stored in strings
  19. # and adjacent tombstones are flattened into numbers.
  20. #
  21. # Eg, the document: 'Hello .....world' ('.' denotes tombstoned (deleted) characters)
  22. # would be represented by a document snapshot of ['Hello ', 5, 'world']
  23. type =
  24. name: 'text-tp2'
  25. tp2: true
  26. create: -> {charLength:0, totalLength:0, positionCache:[], data:[]}
  27. serialize: (doc) ->
  28. throw new Error 'invalid doc snapshot' unless doc.data
  29. doc.data
  30. deserialize: (data) ->
  31. doc = type.create()
  32. doc.data = data
  33. for component in data
  34. if typeof component is 'string'
  35. doc.charLength += component.length
  36. doc.totalLength += component.length
  37. else
  38. doc.totalLength += component
  39. doc
  40. checkOp = (op) ->
  41. throw new Error('Op must be an array of components') unless Array.isArray(op)
  42. last = null
  43. for c in op
  44. if typeof(c) == 'object'
  45. if c.i != undefined
  46. throw new Error('Inserts must insert a string or a +ive number') unless (typeof(c.i) == 'string' and c.i.length > 0) or (typeof(c.i) == 'number' and c.i > 0)
  47. else if c.d != undefined
  48. throw new Error('Deletes must be a +ive number') unless typeof(c.d) == 'number' and c.d > 0
  49. else
  50. throw new Error('Operation component must define .i or .d')
  51. else
  52. throw new Error('Op components must be objects or numbers') unless typeof(c) == 'number'
  53. throw new Error('Skip components must be a positive number') unless c > 0
  54. throw new Error('Adjacent skip components should be combined') if typeof(last) == 'number'
  55. last = c
  56. # Take the next part from the specified position in a document snapshot.
  57. # position = {index, offset}. It will be updated.
  58. type._takeDoc = takeDoc = (doc, position, maxlength, tombsIndivisible) ->
  59. throw new Error 'Operation goes past the end of the document' if position.index >= doc.data.length
  60. part = doc.data[position.index]
  61. # peel off data[0]
  62. result = if typeof(part) == 'string'
  63. if maxlength != undefined
  64. part[position.offset...(position.offset + maxlength)]
  65. else
  66. part[position.offset...]
  67. else
  68. if maxlength == undefined or tombsIndivisible
  69. part - position.offset
  70. else
  71. Math.min(maxlength, part - position.offset)
  72. resultLen = result.length || result
  73. if (part.length || part) - position.offset > resultLen
  74. position.offset += resultLen
  75. else
  76. position.index++
  77. position.offset = 0
  78. result
  79. # Append a part to the end of a document
  80. type._appendDoc = appendDoc = (doc, p) ->
  81. return if p == 0 or p == ''
  82. if typeof p is 'string'
  83. doc.charLength += p.length
  84. doc.totalLength += p.length
  85. else
  86. doc.totalLength += p
  87. data = doc.data
  88. if data.length == 0
  89. data.push p
  90. else if typeof(data[data.length - 1]) == typeof(p)
  91. data[data.length - 1] += p
  92. else
  93. data.push p
  94. return
  95. # Apply the op to the document. The document is not modified in the process.
  96. type.apply = (doc, op) ->
  97. unless doc.totalLength != undefined and doc.charLength != undefined and doc.data.length != undefined
  98. throw new Error('Snapshot is invalid')
  99. checkOp op
  100. newDoc = type.create()
  101. position = {index:0, offset:0}
  102. for component in op
  103. if typeof(component) is 'number'
  104. remainder = component
  105. while remainder > 0
  106. part = takeDoc doc, position, remainder
  107. appendDoc newDoc, part
  108. remainder -= part.length || part
  109. else if component.i != undefined
  110. appendDoc newDoc, component.i
  111. else if component.d != undefined
  112. remainder = component.d
  113. while remainder > 0
  114. part = takeDoc doc, position, remainder
  115. remainder -= part.length || part
  116. appendDoc newDoc, component.d
  117. newDoc
  118. # Append an op component to the end of the specified op.
  119. # Exported for the randomOpGenerator.
  120. type._append = append = (op, component) ->
  121. if component == 0 || component.i == '' || component.i == 0 || component.d == 0
  122. return
  123. else if op.length == 0
  124. op.push component
  125. else
  126. last = op[op.length - 1]
  127. if typeof(component) == 'number' && typeof(last) == 'number'
  128. op[op.length - 1] += component
  129. else if component.i != undefined && last.i? && typeof(last.i) == typeof(component.i)
  130. last.i += component.i
  131. else if component.d != undefined && last.d?
  132. last.d += component.d
  133. else
  134. op.push component
  135. # Makes 2 functions for taking components from the start of an op, and for peeking
  136. # at the next op that could be taken.
  137. makeTake = (op) ->
  138. # The index of the next component to take
  139. index = 0
  140. # The offset into the component
  141. offset = 0
  142. # Take up to length maxlength from the op. If maxlength is not defined, there is no max.
  143. # If insertsIndivisible is true, inserts (& insert tombstones) won't be separated.
  144. #
  145. # Returns null when op is fully consumed.
  146. take = (maxlength, insertsIndivisible) ->
  147. return null if index == op.length
  148. e = op[index]
  149. if typeof((current = e)) == 'number' or typeof((current = e.i)) == 'number' or (current = e.d) != undefined
  150. if !maxlength? or current - offset <= maxlength or (insertsIndivisible and e.i != undefined)
  151. # Return the rest of the current element.
  152. c = current - offset
  153. ++index; offset = 0
  154. else
  155. offset += maxlength
  156. c = maxlength
  157. if e.i != undefined then {i:c} else if e.d != undefined then {d:c} else c
  158. else
  159. # Take from the inserted string
  160. if !maxlength? or e.i.length - offset <= maxlength or insertsIndivisible
  161. result = {i:e.i[offset..]}
  162. ++index; offset = 0
  163. else
  164. result = {i:e.i[offset...offset + maxlength]}
  165. offset += maxlength
  166. result
  167. peekType = -> op[index]
  168. [take, peekType]
  169. # Find and return the length of an op component
  170. componentLength = (component) ->
  171. if typeof(component) == 'number'
  172. component
  173. else if typeof(component.i) == 'string'
  174. component.i.length
  175. else
  176. # This should work because c.d and c.i must be +ive.
  177. component.d or component.i
  178. # Normalize an op, removing all empty skips and empty inserts / deletes. Concatenate
  179. # adjacent inserts and deletes.
  180. type.normalize = (op) ->
  181. newOp = []
  182. append newOp, component for component in op
  183. newOp
  184. # This is a helper method to transform and prune. goForwards is true for transform, false for prune.
  185. transformer = (op, otherOp, goForwards, side) ->
  186. checkOp op
  187. checkOp otherOp
  188. newOp = []
  189. [take, peek] = makeTake op
  190. for component in otherOp
  191. length = componentLength component
  192. if component.i != undefined # Insert text or tombs
  193. if goForwards # transform - insert skips over inserted parts
  194. if side == 'left'
  195. # The left insert should go first.
  196. append newOp, take() while peek()?.i != undefined
  197. # In any case, skip the inserted text.
  198. append newOp, length
  199. else # Prune. Remove skips for inserts.
  200. while length > 0
  201. chunk = take length, true
  202. throw new Error 'The transformed op is invalid' unless chunk != null
  203. throw new Error 'The transformed op deletes locally inserted characters - it cannot be purged of the insert.' if chunk.d != undefined
  204. if typeof chunk is 'number'
  205. length -= chunk
  206. else
  207. append newOp, chunk
  208. else # Skip or delete
  209. while length > 0
  210. chunk = take length, true
  211. throw new Error('The op traverses more elements than the document has') unless chunk != null
  212. append newOp, chunk
  213. length -= componentLength chunk unless chunk.i
  214. # Append extras from op1
  215. while (component = take())
  216. throw new Error "Remaining fragments in the op: #{component}" unless component.i != undefined
  217. append newOp, component
  218. newOp
  219. # transform op1 by op2. Return transformed version of op1.
  220. # op1 and op2 are unchanged by transform.
  221. # side should be 'left' or 'right', depending on if op1.id <> op2.id. 'left' == client op.
  222. type.transform = (op, otherOp, side) ->
  223. throw new Error "side (#{side}) should be 'left' or 'right'" unless side == 'left' or side == 'right'
  224. transformer op, otherOp, true, side
  225. # Prune is the inverse of transform.
  226. type.prune = (op, otherOp) -> transformer op, otherOp, false
  227. # Compose 2 ops into 1 op.
  228. type.compose = (op1, op2) ->
  229. return op2 if op1 == null or op1 == undefined
  230. checkOp op1
  231. checkOp op2
  232. result = []
  233. [take, _] = makeTake op1
  234. for component in op2
  235. if typeof(component) == 'number' # Skip
  236. # Just copy from op1.
  237. length = component
  238. while length > 0
  239. chunk = take length
  240. throw new Error('The op traverses more elements than the document has') unless chunk != null
  241. append result, chunk
  242. length -= componentLength chunk
  243. else if component.i != undefined # Insert
  244. append result, {i:component.i}
  245. else # Delete
  246. length = component.d
  247. while length > 0
  248. chunk = take length
  249. throw new Error('The op traverses more elements than the document has') unless chunk != null
  250. chunkLength = componentLength chunk
  251. if chunk.i != undefined
  252. append result, {i:chunkLength}
  253. else
  254. append result, {d:chunkLength}
  255. length -= chunkLength
  256. # Append extras from op1
  257. while (component = take())
  258. throw new Error "Remaining fragments in op1: #{component}" unless component.i != undefined
  259. append result, component
  260. result
  261. if WEB?
  262. exports.types['text-tp2'] = type
  263. else
  264. module.exports = type