text-operation

text operation classes for rich text operational transformation

Usage no npm install needed!

<script type="module">
  import textOperation from 'https://cdn.skypack.dev/text-operation';
</script>

README

text-operation Npm version Build Status Coverage Status

Classes for Rich Text Operations using Operational Transformation

Overview

This package is heavily based on firepad's OT operations, which were in turn based on ot.js. Yay OSS!

This package is a conversion of their masterful work into Typescript + ES6, and turned into an easy to use module.

Installation

npm i -S text-operation

Usage

The easiest way to get familiar with the TextOperation class is to check out text-operation.utils.spec.js

The OT operations we allow are retain insert delete. A single TextOperation will contain one or many of these operations, but must traverse exactly entire string for which they will be applied:

import { TextOperation } from 'text-operation';

const testString = 'I am a test string';

const o = new TextOperation();
o.retain(2);
o.delete(2);
o.insert('was');
o.retain(14);
o.insert('!');

// apply operations to a string
console.log(o.apply(testString)); // I was a test string!

// composition example
const o2 = new TextOperation();
o2.retain(2);
o2.delete(3);
o2.insert('still am');
o2.retain(15);
o2.insert('!!');

const composed = o.compose(o2);
console.log(composed);
// TextOperation {
//   ops:
//    [ TextOp { type: 'retain', chars: 2, text: null, attributes: {} },
//      TextOp { type: 'insert', chars: null, text: 'still am', attributes: {} },
//      TextOp { type: 'delete', chars: 2, text: null, attributes: null },
//      TextOp { type: 'retain', chars: 14, text: null, attributes: {} },
//      TextOp { type: 'insert', chars: null, text: '!!!!', attributes: {} } ],
//   baseLength: 18,
//   targetLength: 28 }

console.log(composed.apply(testString)); // I still am a test string!!!

// transformation example
const simpleString = 'abcdef';

const op1 = new TextOperation();
const op2 = new TextOperation();

op1.retain(6).insert('ghijk');
op2.retain(3).delete(3);
const transformed = op1.transform(op2);
console.log(transformed[0].toJSON(), transformed[1].toJSON()); // [ 3, 'ghijk' ] [ 3, -3, 5 ]

console.log(transformed[1].apply(op1.apply(simpleString))); // abcghijk

Contributing

This project welcomes code contributions, bug reports and feature requests. Please see the guidelines in CONTRIBUTING.md if you are interested in contributing.