share/ottypes — pull request #9 by devongovett (2014-02-23 00:21:57+00:00)
Title: JSON Subtypes

Adds a `registerSubtype` method to the JSON type that takes an object with a number of functions needed to convert ops to and from the subtype's ops, and apply/transform them etc.

The string support was already kind of a subtype, it was just hard coded, so I abstracted it so that other types could be registered in the same way. For example, I have a richtext type, and I need to embed it inside a JSON document, so I need the JSON type to delegate the richtext ops to my richtext type. This enables that in a generic way rather than maintaining a fork of ottypes etc.

These are the methods required by all subtypes:

* `supportsOp(op)` - returns whether an operation/component is supported by the subtype.
* `convertTo(op)` - converts a JSON op to a format understood by the subtype. Could only be changing the path value (to the last element of the path) or could involve changing names of properties as in the string type.
* `convertFrom(op)` - converts a subtype op back to a JSON op.
* `invert(op)` - inverts a subtype op. The op is NOT preconverted to a subtype op in this case, for performance, since inverting is often quite simple and doesn't touch the path.
* `apply(snapshot, op)` - applies an already converted subtype op to the snapshot. The snapshot passed is the object at `path[path.length - 2]`, assuming `path[path.length - 1]` is the position given in the converted op for the subtype. The result replaces the existing snapshot embedded in the JSON document.
* `append(dest, op)` - appends a subtype op to a list of ops.
* `transform(op1, op2, type)` - transforms two subtype ops.

You can see an example of this in the text subtype at the end of json0.js, which I've extracted from the previous code. I have a richtext type that is using this as well, and I imagine it could be used for other types if people have them.

All of the tests still pass. Let me know what you think!