simple.coffee 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. # This is a really simple OT type. Its not compiled with the web client, but it could be.
  2. #
  3. # Its mostly included for demonstration purposes and its used in a lot of unit tests.
  4. #
  5. # This defines a really simple text OT type which only allows inserts. (No deletes).
  6. #
  7. # Ops look like:
  8. # {position:#, text:"asdf"}
  9. #
  10. # Document snapshots look like:
  11. # {str:string}
  12. module.exports =
  13. # The name of the OT type. The type is stored in types[type.name]. The name can be
  14. # used in place of the actual type in all the API methods.
  15. name: 'simple'
  16. # Create a new document snapshot
  17. create: -> {str:""}
  18. # Apply the given op to the document snapshot. Returns the new snapshot.
  19. #
  20. # The original snapshot should not be modified.
  21. apply: (snapshot, op) ->
  22. throw new Error 'Invalid position' unless 0 <= op.position <= snapshot.str.length
  23. str = snapshot.str
  24. str = str.slice(0, op.position) + op.text + str.slice(op.position)
  25. {str}
  26. # transform op1 by op2. Return transformed version of op1.
  27. # sym describes the symmetry of the op. Its 'left' or 'right' depending on whether the
  28. # op being transformed comes from the client or the server.
  29. transform: (op1, op2, sym) ->
  30. pos = op1.position
  31. pos += op2.text.length if op2.position < pos or (op2.position == pos and sym is 'left')
  32. return {position:pos, text:op1.text}