first commit

This commit is contained in:
2026-06-24 09:48:54 +02:00
commit 41e62ddcad
33739 changed files with 4266226 additions and 0 deletions
+2
View File
@@ -0,0 +1,2 @@
/.coverage
/node_modules
+8
View File
@@ -0,0 +1,8 @@
language: node_js
node_js: '0.10'
before_install:
- npm install -g grunt-cli
script:
- grunt coverage
after_success:
- grunt coverage:report
+64
View File
@@ -0,0 +1,64 @@
var fs = require('fs');
module.exports = function (grunt) {
// Define to control testing order
var tests = [
'test/is.js',
'test/attributes.js',
'test/op.js',
'test/delta/builder.js',
'test/delta/helpers.js',
'test/delta/compose.js',
'test/delta/transform.js',
'test/delta/transform-position.js',
'test/delta/diff.js'
];
grunt.registerTask('coverage', function () {
grunt.util.spawn({
cmd: './node_modules/.bin/istanbul',
args: ['cover', './node_modules/.bin/_mocha'].concat(tests).concat(['--dir', '.coverage']),
opts: { stdio: 'inherit' }
}, this.async());
});
grunt.registerTask('coverage:fuzzer', function () {
grunt.util.spawn({
cmd: './node_modules/.bin/istanbul',
args: ['cover', './node_modules/.bin/_mocha', 'test/fuzzer.js', '--dir', '.coverage'],
opts: { stdio: 'inherit' }
}, this.async());
});
grunt.registerTask('coverage:report', function () {
var file = fs.createReadStream('.coverage/lcov.info');
var child = grunt.util.spawn({
cmd: './node_modules/coveralls/bin/coveralls.js',
}, this.async());
file.pipe(child.stdin);
});
grunt.registerTask('test', function () {
grunt.util.spawn({
cmd: './node_modules/.bin/mocha',
args: tests.concat(['test/fuzzer.js']),
opts: { stdio: 'inherit' }
}, this.async());
});
grunt.registerTask('test:unit', function () {
grunt.util.spawn({
cmd: './node_modules/.bin/mocha',
args: tests,
opts: { stdio: 'inherit' }
}, this.async());
});
grunt.registerTask('test:fuzzer', function () {
grunt.util.spawn({
cmd: './node_modules/.bin/mocha',
args: ['test/fuzzer.js'],
opts: { stdio: 'inherit' }
}, this.async());
});
};
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2014 Jason Chen
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
+398
View File
@@ -0,0 +1,398 @@
# Rich Text [![Build Status](https://travis-ci.org/ottypes/rich-text.svg?branch=master)](http://travis-ci.org/ottypes/rich-text) [![Coverage Status](https://img.shields.io/coveralls/ottypes/rich-text.svg)](https://coveralls.io/r/ottypes/rich-text)
A format for representing rich text documents and changes. It aimes to be intuitive and human readable with the ability to express any change necessary to deal with rich text. A document can also be expressed with this format--as the change from an empty document.
## Quick Example
```js
var delta = new Delta([
{ insert: 'Gandalf', attributes: { bold: true } },
{ insert: ' the ' },
{ insert: 'Grey', attributes: { color: '#ccc' } }
]);
// Keep the first 12 characters, delete the next 4, and insert a white 'White'
var death = new Delta().retain(12)
.delete(4)
.insert('White', { color: '#fff' });
// this produces:
// {
// ops: [
// { retain: 12 },
// { delete: '4 ' },
// { insert: 'White', attributes: { color: '#fff' } }
// ]
// }
delta.compose(death);
// delta is now:
// {
// ops: [
// { insert: 'Gandalf ', attributes: { bold: true } },
// { insert: 'the ' },
// { insert: 'White', attributes: { color: '#fff' } }
// ]
// }
```
This format is suitable for [Operational Transform](https://en.wikipedia.org/wiki/Operational_transformation) and defines several functions to support this use case.
## Contents
#### [Operations](#operations-1)
- [insert](#insert-operation)
- [delete](#delete-operation)
- [retain](#retain-operation)
#### [Deltas](#deltas-1)
- [`constructor`](#constructor)
- [`insert`](#insert)
- [`delete`](#delete)
- [`retain`](#retain)
- [`length`](#length)
- [`slice`](#slice)
- [`compose`](#compose)
- [`transform`](#transform)
#### [Documents](#documents-1)
- [`diff`](#diff)
## Operations
Operations describe a singular change to a document. They can be an [`insert`](#insert-operation), [`delete`](#delete-operation) or [`retain`](#retain-operation). Note operations do not take an index. They always describe the change at the current index. Use retains to "keep" or "skip" certain parts of the document.
### Insert Operation
Insert operations have an `insert` key defined. A String value represents inserting text. A Number value represents inserting an embed, with the value corresponding to an embed type (such as an image or video).
Here we will use 1 to represent images and 2 to represent videos, but your application can choose whatever mapping is convenient.
In both cases of text and embeds, an optional `attributes` key can be defined with an Object to describe additonal formatting information. Formats can be changed by the [retain](#retain) operation.
```js
// Insert a bolded "Text"
{ insert: "Text", attributes: { bold: true } }
// Insert a link
{ insert: "Google", attributes: { href: 'https://www.google.com' } }
// Insert an image
{
insert: 1,
attributes: {
alt: "Lab Octocat",
src: 'https://octodex.github.com/images/labtocat.png'
}
}
// Insert a video
{
insert: 2,
attributes: {
src: "https://www.youtube.com/watch?v=dMH0bHeiRNg",
width: 420,
height: 315
}
}
```
### Delete Operation
Delete operations have a Number `delete` key defined representing the number of characters to delete. All embeds have a length of 1.
```js
// Delete the next 10 characters
{ delete: 10 }
```
### Retain Operation
Retain operations have a Number `retain` key defined representing the number of characters to keep (other libraries might use the name keep or skip). An optional `attributes` key can be defined with an Object to describe formatting changes to the character range. A value of null in the `attributes` Object represents removal of that key.
*Note: It is not necessary to retain the last characters of a document as this is implied.*
```js
// Keep the next 5 characters
{ retain: 5 }
// Keep and bold the next 5 characters
{ retain: 5, attributes: { bold: true } }
// Keep and unbold the next 5 characters
// More specifically, remove the bold key in the attributes Object
// in the next 5 characters
{ retain: 5, attributes: { bold: null } }
```
## Deltas
A Delta is made up of an array of operations. Unless otherwise specified all methods are self modifying and return `this` for chainability.
All methods also maintain the property that Deltas are represented in the most compact form. For example two consecutive insert operations of plain text will be merged into one.
---
### constructor
Creates a new Delta object.
#### Methods
- `new Delta()`
- `new Delta(ops)`
- `new Delta(delta)`
#### Parameters
- `ops` - Array of operations
- `delta` - Object with an `ops` key set to an array of operations
*Note: No validity/sanity check is performed when constructed with ops or delta. The new delta's internal ops array will also be assigned to ops or delta.ops without deep copying.*
#### Example
```js
var delta = new Delta([
{ insert: 'Hello World' },
{ insert: '!', attributes: { bold: true }}
]);
var packet = JSON.stringify(delta);
var other = new Delta(JSON.parse(packet));
var chained = new Delta().insert('Hello World').insert('!', { bold: true });
```
---
### insert()
Appends an insert operation.
#### Methods
- `insert(text, attributes)`
- `insert(embed, attributes)`
#### Parameters
- `text` - String representing text to insert
- `embed` - Number representing embed type to insert
- `attributes` - Optional attributes to apply
#### Example
```js
delta.insert('Text', { bold: true, color: '#ccc' });
delta.insert(1, { src: 'https://octodex.github.com/images/labtocat.png' });
```
---
### delete()
Appends a delete operation.
#### Methods
- `delete(length)`
#### Parameters
- `length` - Number of characters to delete
#### Example
```js
delta.delete(5);
```
---
### retain()
Appends a retain operation.
#### Methods
- `retain(length, attributes)`
#### Parameters
- `length` - Number of characters to retain
- `attributes` - Optional attributes to apply
#### Example
```js
delta.retain(4).retain(5, { color: '#0c6' });
```
---
### length()
Returns length of Delta.
#### Methods
- `length()`
#### Example
```js
new Delta().insert('Hello').length(); // Returns 5
new Delta().insert('A').retain(2).delete(1) // Returns 4
```
---
### slice()
Returns copy of delta with subset of operations.
#### Methods
- `slice()`
- `slice(start)`
- `slice(start, end)`
#### Parameters
- `start` - Start index of subset, defaults to 0
- `end` - End index of subset, defaults to rest of operations
#### Example
```js
var delta = new Delta().insert('Hello', { bold: true }).insert(' World');
// {
// ops: [
// { insert: 'Hello', attributes: { bold: true } },
// { insert: ' World' }
// ]
// }
var copy = delta.slice();
// { ops: [{ insert: 'World' }] }
var world = delta.slice(6);
// { ops: [{ insert: ' ' }] }
var space = delta.slice(5, 6);
```
---
### compose()
Compose with another Delta, i.e. merge the operations of another Delta. This method is self modifying.
#### Methods
- `compose(other)`
#### Parameters
- `other` - Delta to compose
#### Example
```js
var a = new Delta().insert('abc');
var b = new Delta().retain(1).delete(1);
a.compose(b); // a == new Delta().insert('ac');
```
### transform()
Transform given Delta against own operations.
#### Methods
- `transform(other, priority)`
- `transform(index)` - Alias for [`transformPosition`](#tranformposition)
#### Parameters
- `other` - Delta to transform
- `priority` - Boolean used to break ties
#### Returns
- `Delta` - transformed Delta
#### Example
```js
var a = new Delta().insert('a');
var b = new Delta().insert('b');
b = a.transform(b, true); // new Delta().retain(1).insert('b');
```
---
### transformPosition()
Transform an index against the delta. Useful for representing cursor/selection positions.
#### Methods
- `transformPosition(index)`
#### Parameters
- `index` - index to transform
#### Returns
- `Number` - transformed index
#### Example
```js
var index = 12;
var transformedIndex = delta.transformPosition(index);
```
## Documents
A Delta with only insert operations can be used to represent a rich text document. This can be thought of as a Delta applied to an empty document.
---
### diff()
Calculates the difference between two documents expressed as a Delta.
#### Methods
- `diff(other)`
#### Parameters
- `other` - Document Delta to diff against
#### Returns
- `Delta` - difference between the two documents
#### Example
```js
var a = new Delta().insert('Hello');
var b = new Delta().insert('Hello!');
var diff = a.diff(b); // { ops: [{ retain: 5 }, { insert: '!' }] }
```
+1
View File
@@ -0,0 +1 @@
module.exports = require('./lib/type');
+243
View File
@@ -0,0 +1,243 @@
var diff = require('fast-diff');
var is = require('./is');
var op = require('./op');
var NULL_CHARACTER = String.fromCharCode(0); // Placeholder char for embed in diff()
var Delta = function (ops) {
// Assume we are given a well formed ops
if (is.array(ops)) {
this.ops = ops;
} else if (is.object(ops) && is.array(ops.ops)) {
this.ops = ops.ops;
} else {
this.ops = [];
}
};
Delta.prototype.insert = function (text, attributes) {
var newOp = {};
if (is.string(text)) {
if (text.length === 0) return this;
newOp.insert = text;
} else if (is.number(text)) {
newOp.insert = text;
}
if (is.object(attributes) && Object.keys(attributes).length > 0) newOp.attributes = attributes;
return this.push(newOp);
};
Delta.prototype['delete'] = function (length) {
if (length <= 0) return this;
return this.push({ 'delete': length });
};
Delta.prototype.retain = function (length, attributes) {
if (length <= 0) return this;
var newOp = { retain: length };
if (is.object(attributes) && Object.keys(attributes).length > 0) newOp.attributes = attributes;
return this.push(newOp);
};
Delta.prototype.push = function (newOp) {
var index = this.ops.length;
var lastOp = this.ops[index - 1];
newOp = op.clone(newOp);
if (is.object(lastOp)) {
if (is.number(newOp['delete']) && is.number(lastOp['delete'])) {
this.ops[index - 1] = { 'delete': lastOp['delete'] + newOp['delete'] };
return this;
}
// Since it does not matter if we insert before or after deleting at the same index,
// always prefer to insert first
if (is.number(lastOp['delete']) && (is.string(newOp.insert) || is.number(newOp.insert))) {
index -= 1;
lastOp = this.ops[index - 1];
if (!is.object(lastOp)) {
this.ops.unshift(newOp);
return this;
}
}
if (is.equal(newOp.attributes, lastOp.attributes)) {
if (is.string(newOp.insert) && is.string(lastOp.insert)) {
this.ops[index - 1] = { insert: lastOp.insert + newOp.insert };
if (is.object(newOp.attributes)) this.ops[index - 1].attributes = newOp.attributes
return this;
} else if (is.number(newOp.retain) && is.number(lastOp.retain)) {
this.ops[index - 1] = { retain: lastOp.retain + newOp.retain };
if (is.object(newOp.attributes)) this.ops[index - 1].attributes = newOp.attributes
return this;
}
}
}
this.ops.splice(index, 0, newOp);
return this;
};
Delta.prototype.chop = function () {
var lastOp = this.ops[this.ops.length - 1];
if (lastOp && lastOp.retain && !lastOp.attributes) {
this.ops.pop();
}
return this;
};
Delta.prototype.length = function () {
return this.ops.reduce(function (length, elem) {
return length + op.length(elem);
}, 0);
};
Delta.prototype.slice = function (start, end) {
start = start || 0;
if (!is.number(end)) end = Infinity;
var delta = new Delta();
var iter = op.iterator(this.ops);
var index = 0;
while (index < end && iter.hasNext()) {
var nextOp;
if (index < start) {
nextOp = iter.next(start - index);
} else {
nextOp = iter.next(end - index);
delta.push(nextOp);
}
index += op.length(nextOp);
}
return delta;
};
Delta.prototype.compose = function (other) {
var thisIter = op.iterator(this.ops);
var otherIter = op.iterator(other.ops);
this.ops = [];
while (thisIter.hasNext() || otherIter.hasNext()) {
if (otherIter.peekType() === 'insert') {
this.push(otherIter.next());
} else if (thisIter.peekType() === 'delete') {
this.push(thisIter.next());
} else {
var length = Math.min(thisIter.peekLength(), otherIter.peekLength());
var thisOp = thisIter.next(length);
var otherOp = otherIter.next(length);
if (is.number(otherOp.retain)) {
var newOp = {};
if (is.number(thisOp.retain)) {
newOp.retain = length;
} else {
newOp.insert = thisOp.insert;
}
// Preserve null when composing with a retain, otherwise remove it for inserts
var attributes = op.attributes.compose(thisOp.attributes, otherOp.attributes, is.number(thisOp.retain));
if (attributes) newOp.attributes = attributes;
this.push(newOp);
// Other op should be delete, we could be an insert or retain
// Insert + delete cancels out
} else if (is.number(otherOp['delete']) && is.number(thisOp.retain)) {
this.push(otherOp);
}
}
}
return this.chop();
};
Delta.prototype.diff = function (other) {
var strings = [this.ops, other.ops].map(function (ops) {
return ops.map(function (op) {
if (is.string(op.insert)) return op.insert;
if (is.number(op.insert)) return NULL_CHARACTER;
var prep = ops === other.ops ? 'on' : 'with';
throw new Error('diff() called ' + prep + ' non-document');
}).join('');
});
var diffResult = diff(strings[0], strings[1]);
var thisIter = op.iterator(this.ops);
var otherIter = op.iterator(other.ops);
var delta = new Delta();
diffResult.forEach(function (component) {
var length = component[1].length;
while (length > 0) {
var opLength = 0;
switch (component[0]) {
case diff.INSERT:
opLength = Math.min(otherIter.peekLength(), length);
delta.push(otherIter.next(opLength));
break;
case diff.DELETE:
opLength = Math.min(length, thisIter.peekLength());
thisIter.next(opLength);
delta['delete'](opLength);
break;
case diff.EQUAL:
opLength = Math.min(thisIter.peekLength(), otherIter.peekLength(), length);
var thisOp = thisIter.next(opLength);
var otherOp = otherIter.next(opLength);
if (thisOp.insert === otherOp.insert) {
delta.retain(opLength, op.attributes.diff(thisOp.attributes, otherOp.attributes));
} else {
delta.push(otherOp)['delete'](opLength);
}
break;
}
length -= opLength;
}
});
return delta.chop();
};
Delta.prototype.transform = function (other, priority) {
priority = !!priority;
if (is.number(other)) {
return this.transformPosition(other, priority);
}
var thisIter = op.iterator(this.ops);
var otherIter = op.iterator(other.ops);
var delta = new Delta();
while (thisIter.hasNext() || otherIter.hasNext()) {
if (thisIter.peekType() === 'insert' && (priority || otherIter.peekType() !== 'insert')) {
delta.retain(op.length(thisIter.next()));
} else if (otherIter.peekType() === 'insert') {
delta.push(otherIter.next());
} else {
var length = Math.min(thisIter.peekLength(), otherIter.peekLength());
var thisOp = thisIter.next(length);
var otherOp = otherIter.next(length);
if (thisOp['delete']) {
// Our delete either makes their delete redundant or removes their retain
continue;
} else if (otherOp['delete']) {
delta.push(otherOp);
} else {
// We retain either their retain or insert
delta.retain(length, op.attributes.transform(thisOp.attributes, otherOp.attributes, priority));
}
}
}
return delta.chop();
};
Delta.prototype.transformPosition = function (index, priority) {
priority = !!priority;
var thisIter = op.iterator(this.ops);
var offset = 0;
while (thisIter.hasNext() && offset <= index) {
var length = thisIter.peekLength();
var nextType = thisIter.peekType();
thisIter.next();
if (nextType === 'delete') {
index -= Math.min(length, index - offset);
continue;
} else if (nextType === 'insert' && (offset < index || !priority)) {
index += length;
}
offset += length;
}
return index;
};
module.exports = Delta;
+34
View File
@@ -0,0 +1,34 @@
module.exports = {
equal: function (a, b) {
if (a === b) return true;
if (a == null && b == null) return true;
if (a == null || b == null) return false;
if (Object.keys(a).length != Object.keys(b).length) return false;
for(var key in a) {
// Only compare one level deep
if (a[key] !== b[key]) return false;
}
return true;
},
array: function (value) {
return Array.isArray(value);
},
number: function (value) {
if (typeof value === 'number') return true;
if (typeof value === 'object' && Object.prototype.toString.call(value) === '[object Number]') return true;
return false;
},
object: function (value) {
if (!value) return false;
return (typeof value === 'function' || typeof value === 'object');
},
string: function (value) {
if (typeof value === 'string') return true;
if (typeof value === 'object' && Object.prototype.toString.call(value) === '[object String]') return true;
return false;
}
};
+144
View File
@@ -0,0 +1,144 @@
var is = require('./is');
var lib = {
attributes: {
clone: function (attributes, keepNull) {
if (!is.object(attributes)) return {};
return Object.keys(attributes).reduce(function (memo, key) {
if (attributes[key] !== undefined && (attributes[key] !== null || keepNull)) {
memo[key] = attributes[key];
}
return memo;
}, {});
},
compose: function (a, b, keepNull) {
if (!is.object(a)) a = {};
if (!is.object(b)) b = {};
var attributes = this.clone(b, keepNull);
for (var key in a) {
if (a[key] !== undefined && b[key] === undefined) {
attributes[key] = a[key];
}
}
return Object.keys(attributes).length > 0 ? attributes : undefined;
},
diff: function(a, b) {
if (!is.object(a)) a = {};
if (!is.object(b)) b = {};
var attributes = Object.keys(a).concat(Object.keys(b)).reduce(function (attributes, key) {
if (a[key] !== b[key]) {
attributes[key] = b[key] === undefined ? null : b[key];
}
return attributes;
}, {});
return Object.keys(attributes).length > 0 ? attributes : undefined;
},
transform: function (a, b, priority) {
if (!is.object(a)) return b;
if (!is.object(b)) return undefined;
if (!priority) return b; // b simply overwrites us without priority
var attributes = Object.keys(b).reduce(function (attributes, key) {
if (a[key] === undefined) attributes[key] = b[key]; // null is a valid value
return attributes;
}, {});
return Object.keys(attributes).length > 0 ? attributes : undefined;
}
},
clone: function (op) {
var newOp = this.attributes.clone(op);
if (is.object(newOp.attributes)) {
newOp.attributes = this.attributes.clone(newOp.attributes, true);
}
return newOp;
},
iterator: function (ops) {
return new Iterator(ops);
},
length: function (op) {
if (is.number(op['delete'])) {
return op['delete'];
} else if (is.number(op.retain)) {
return op.retain;
} else {
return is.string(op.insert) ? op.insert.length : 1;
}
}
};
function Iterator(ops) {
this.ops = ops;
this.index = 0;
this.offset = 0;
};
Iterator.prototype.hasNext = function () {
return this.peekLength() < Infinity;
};
Iterator.prototype.next = function (length) {
if (!length) length = Infinity;
var nextOp = this.ops[this.index];
if (nextOp) {
var offset = this.offset;
var opLength = lib.length(nextOp)
if (length >= opLength - offset) {
length = opLength - offset;
this.index += 1;
this.offset = 0;
} else {
this.offset += length;
}
if (is.number(nextOp['delete'])) {
return { 'delete': length };
} else {
var retOp = {};
if (nextOp.attributes) {
retOp.attributes = nextOp.attributes;
}
if (is.number(nextOp.retain)) {
retOp.retain = length;
} else if (is.string(nextOp.insert)) {
retOp.insert = nextOp.insert.substr(offset, length);
} else {
// offset should === 0, length should === 1
retOp.insert = nextOp.insert;
}
return retOp;
}
} else {
return { retain: Infinity };
}
};
Iterator.prototype.peekLength = function () {
if (this.ops[this.index]) {
// Should never return 0 if our index is being managed correctly
return lib.length(this.ops[this.index]) - this.offset;
} else {
return Infinity;
}
};
Iterator.prototype.peekType = function () {
if (this.ops[this.index]) {
if (is.number(this.ops[this.index]['delete'])) {
return 'delete';
} else if (is.number(this.ops[this.index].retain)) {
return 'retain';
} else {
return 'insert';
}
}
return 'retain';
};
module.exports = lib;
+38
View File
@@ -0,0 +1,38 @@
var Delta = require('./delta');
var pkg = require('../package.json');
module.exports = {
Delta: Delta,
name: 'rich-text',
uri: 'http://sharejs.org/types/rich-text/v1',
create: function (initial) {
return new Delta(initial);
},
apply: function (snapshot, delta) {
snapshot = new Delta(snapshot);
delta = new Delta(delta);
return snapshot.compose(delta);
},
compose: function (delta1, delta2) {
delta1 = new Delta(delta1);
delta2 = new Delta(delta2);
return delta1.compose(delta2);
},
diff: function (delta1, delta2) {
delta1 = new Delta(delta1);
delta2 = new Delta(delta2);
return delta1.diff(delta2);
},
transform: function (delta1, delta2, side) {
delta1 = new Delta(delta1);
delta2 = new Delta(delta2);
// Fuzzer specs is in opposite order of delta interface
return delta2.transform(delta1, side === 'left');
}
};
+40
View File
@@ -0,0 +1,40 @@
{
"name": "rich-text",
"version": "1.0.3",
"description": "Format for representing rich text documents and changes.",
"author": "Jason Chen <jhchen7@gmail.com>",
"homepage": "https://github.com/ottypes/rich-text",
"main": "index.js",
"dependencies": {
"fast-diff": "~1.0.0"
},
"devDependencies": {
"chai": "~1.9.1",
"coveralls": "~2.11.1",
"grunt": "~0.4.5",
"istanbul": "~0.3.0",
"lodash": "~2.4.1",
"mocha": "~1.21.4",
"ot-fuzzer": "~1.0.0"
},
"engines": {
"node": ">=0.10"
},
"license": "MIT",
"scripts": {
"test": "grunt test"
},
"repository": {
"type": "git",
"url": "https://github.com/ottypes/rich-text"
},
"bugs": {
"url": "https://github.com/ottypes/rich-text/issues"
},
"keywords": [
"rich text",
"ot",
"operational transform",
"delta"
]
}
+139
View File
@@ -0,0 +1,139 @@
var op = require('../lib/op');
var expect = require('chai').expect;
describe('attributes', function () {
describe('clone()', function () {
var attributes = {
bold: true,
color: 'red',
italic: null
};
it('undefined', function () {
expect(op.attributes.clone(undefined)).to.deep.equal({});
});
it('keep null', function () {
var clone = op.attributes.clone(attributes, true);
expect(clone === attributes).to.equal(false);
expect(clone).to.deep.equal(attributes);
});
it('dont keep null', function () {
var clone = op.attributes.clone(attributes, false);
expect(clone === attributes).to.equal(false);
expect(clone).to.deep.equal({
bold: true,
color: 'red'
});
});
});
describe('compose()', function () {
var attributes = { bold: true, color: 'red' };
it('left is undefined', function () {
expect(op.attributes.compose(undefined, attributes)).to.deep.equal(attributes);
});
it('right is undefined', function () {
expect(op.attributes.compose(attributes, undefined)).to.deep.equal(attributes);
});
it('both are undefined', function () {
expect(op.attributes.compose(undefined, undefined)).to.equal(undefined);
});
it('missing', function () {
expect(op.attributes.compose(attributes, { italic: true })).to.deep.equal({
bold: true,
italic: true,
color: 'red'
});
});
it('overwrite', function () {
expect(op.attributes.compose(attributes, { bold: false, color: 'blue' })).to.deep.equal({
bold: false,
color: 'blue'
});
});
it('remove', function () {
expect(op.attributes.compose(attributes, { bold: null })).to.deep.equal({
color: 'red'
});
});
it('remove to none', function () {
expect(op.attributes.compose(attributes, { bold: null, color: null })).to.equal(undefined);
});
it('remove missing', function () {
expect(op.attributes.compose(attributes, { italic: null })).to.deep.equal(attributes);
});
});
describe('diff()', function () {
var format = { bold: true, color: 'red' };
it('left is undefined', function () {
expect(op.attributes.diff(undefined, format)).to.deep.equal(format);
});
it('right is undefined', function () {
var expected = { bold: null, color: null };
expect(op.attributes.diff(format, undefined)).to.deep.equal(expected);
});
it('same format', function () {
expect(op.attributes.diff(format, format)).to.equal(undefined);
});
it('add format', function () {
var added = { bold: true, italic: true, color: 'red' };
var expected = { italic: true };
expect(op.attributes.diff(format, added)).to.deep.equal(expected);
});
it('remove format', function () {
var removed = { bold: true };
var expected = { color: null };
expect(op.attributes.diff(format, removed)).to.deep.equal(expected);
});
it('overwrite format', function () {
var overwritten = { bold: true, color: 'blue' };
var expected = { color: 'blue' };
expect(op.attributes.diff(format, overwritten)).to.deep.equal(expected);
});
});
describe('transform()', function () {
var left = { bold: true, color: 'red', font: null };
var right = { color: 'blue', font: 'serif', italic: true };
it('left is undefined', function () {
expect(op.attributes.transform(undefined, left, false)).to.deep.equal(left);
});
it('right is undefined', function () {
expect(op.attributes.transform(left, undefined, false)).to.equal(undefined);
});
it('both are undefined', function () {
expect(op.attributes.transform(undefined, undefined, false)).to.equal(undefined);
});
it('with priority', function () {
expect(op.attributes.transform(left, right, true)).to.deep.equal({
italic: true
});
});
it('without priority', function () {
expect(op.attributes.transform(left, right, false)).to.deep.equal(right);
});
});
});
+187
View File
@@ -0,0 +1,187 @@
var Delta = require('../../lib/delta');
var expect = require('chai').expect;
describe('constructor', function () {
var ops = [
{ insert: 'abc' },
{ retain: 1, attributes: { color: 'red' } },
{ delete: 4 },
{ insert: 'def', attributes: { bold: true } },
{ retain: 6 }
];
it('empty', function () {
var delta = new Delta();
expect(delta).to.exist;
expect(delta.ops).to.exist;
expect(delta.ops.length).to.equal(0);
});
it('empty ops', function () {
var delta = new Delta().insert('').delete(0).retain(0);
expect(delta).to.exist;
expect(delta.ops).to.exist;
expect(delta.ops.length).to.equal(0);
});
it('array of ops', function () {
var delta = new Delta(ops);
expect(delta.ops).to.deep.equal(ops);
});
it('delta in object form', function () {
var delta = new Delta({ ops: ops });
expect(delta.ops).to.deep.equal(ops);
});
it('delta', function () {
var original = new Delta(ops);
var delta = new Delta(original);
expect(delta.ops).to.deep.equal(original.ops);
expect(delta.ops).to.deep.equal(ops);
});
});
describe('insert()', function () {
it('insert(text)', function () {
var delta = new Delta().insert('test');
expect(delta.ops.length).to.equal(1);
expect(delta.ops[0]).to.deep.equal({ insert: 'test' });
});
it('insert(embed)', function () {
var delta = new Delta().insert(1);
expect(delta.ops.length).to.equal(1);
expect(delta.ops[0]).to.deep.equal({ insert: 1 });
});
it('insert(embed, attributes)', function () {
var obj = { url: 'http://quilljs.com', alt: 'Quill' };
var delta = new Delta().insert(1, obj);
expect(delta.ops.length).to.equal(1);
expect(delta.ops[0]).to.deep.equal({ insert: 1, attributes: obj });
});
it('insert(text, attributes)', function () {
var delta = new Delta().insert('test', { bold: true });
expect(delta.ops.length).to.equal(1);
expect(delta.ops[0]).to.deep.equal({ insert: 'test', attributes: { bold: true } });
});
it('insert(text) after delete', function () {
var delta = new Delta().delete(1).insert('a');
var expected = new Delta().insert('a').delete(1);
expect(delta).to.deep.equal(expected);
});
it('insert(text) after delete with merge', function () {
var delta = new Delta().insert('a').delete(1).insert('b');
var expected = new Delta().insert('ab').delete(1);
expect(delta).to.deep.equal(expected);
});
it('insert(text) after delete no merge', function () {
var delta = new Delta().insert(1).delete(1).insert('a');
var expected = new Delta().insert(1).insert('a').delete(1);
expect(delta).to.deep.equal(expected);
});
it('insert(text, {})', function () {
var delta = new Delta().insert('a', {});
var expected = new Delta().insert('a');
expect(delta).to.deep.equal(expected);
});
});
describe('delete()', function () {
it('delete(0)', function () {
var delta = new Delta().delete(0);
expect(delta.ops.length).to.equal(0);
});
it('delete(positive)', function () {
var delta = new Delta().delete(1);
expect(delta.ops.length).to.equal(1);
expect(delta.ops[0]).to.deep.equal({ delete: 1 });
});
});
describe('retain()', function () {
it('retain(0)', function () {
var delta = new Delta().retain(0);
expect(delta.ops.length).to.equal(0);
});
it('retain(length)', function () {
var delta = new Delta().retain(2);
expect(delta.ops.length).to.equal(1);
expect(delta.ops[0]).to.deep.equal({ retain: 2 });
});
it('retain(length, attributes)', function () {
var delta = new Delta().retain(1, { bold: true });
expect(delta.ops.length).to.equal(1);
expect(delta.ops[0]).to.deep.equal({ retain: 1, attributes: { bold: true } });
});
it('retain(length, {})', function () {
var delta = new Delta().retain(2, {}).delete(1); // Delete prevents chop
var expected = new Delta().retain(2).delete(1);
expect(delta).to.deep.equal(expected);
});
});
describe('push()', function () {
it('push(op) into empty', function () {
var delta = new Delta();
delta.push({ insert: 'test' });
expect(delta.ops.length).to.equal(1);
});
it('push(op) consecutive delete', function () {
var delta = new Delta().delete(2);
delta.push({ delete: 3 });
expect(delta.ops.length).to.equal(1);
expect(delta.ops[0]).to.deep.equal({ delete: 5 });
});
it('push(op) consecutive text', function () {
var delta = new Delta().insert('a');
delta.push({ insert: 'b' });
expect(delta.ops.length).to.equal(1);
expect(delta.ops[0]).to.deep.equal({ insert: 'ab' });
});
it('push(op) consecutive texts with matching attributes', function () {
var delta = new Delta().insert('a', { bold: true });
delta.push({ insert: 'b', attributes: { bold: true } });
expect(delta.ops.length).to.equal(1);
expect(delta.ops[0]).to.deep.equal({ insert: 'ab', attributes: { bold: true } });
});
it('push(op) consecutive retains with matching attributes', function () {
var delta = new Delta().retain(1, { bold: true });
delta.push({ retain: 3, attributes: { bold : true } });
expect(delta.ops.length).to.equal(1);
expect(delta.ops[0]).to.deep.equal({ retain: 4, attributes: { bold: true } });
});
it('push(op) consecutive texts with mismatched attributes', function () {
var delta = new Delta().insert('a', { bold: true });
delta.push({ insert: 'b' });
expect(delta.ops.length).to.equal(2);
});
it('push(op) consecutive retains with mismatched attributes', function () {
var delta = new Delta().retain(1, { bold: true });
delta.push({ retain: 3 });
expect(delta.ops.length).to.equal(2);
});
it('push(op) consecutive embeds with matching attributes', function () {
var delta = new Delta().insert({ url: 'http://quilljs.com' });
delta.push({ attributes: { url: 'http://quilljs.com' } });
expect(delta.ops.length).to.equal(2);
});
});
+127
View File
@@ -0,0 +1,127 @@
var Delta = require('../../lib/delta');
var expect = require('chai').expect;
describe('compose()', function () {
it('insert + insert', function () {
var a = new Delta().insert('A');
var b = new Delta().insert('B');
var expected = new Delta().insert('B').insert('A');
expect(a.compose(b)).to.deep.equal(expected);
});
it('insert + retain', function () {
var a = new Delta().insert('A');
var b = new Delta().retain(1, { bold: true, color: 'red', font: null });
var expected = new Delta().insert('A', { bold: true, color: 'red' });
expect(a.compose(b)).to.deep.equal(expected);
});
it('insert + delete', function () {
var a = new Delta().insert('A');
var b = new Delta().delete(1);
var expected = new Delta();
expect(a.compose(b)).to.deep.equal(expected);
});
it('delete + insert', function () {
var a = new Delta().delete(1);
var b = new Delta().insert('B');
var expected = new Delta().insert('B').delete(1);
expect(a.compose(b)).to.deep.equal(expected);
});
it('delete + retain', function () {
var a = new Delta().delete(1);
var b = new Delta().retain(1, { bold: true, color: 'red' });
var expected = new Delta().delete(1).retain(1, { bold: true, color: 'red' });
expect(a.compose(b)).to.deep.equal(expected);
});
it('delete + delete', function () {
var a = new Delta().delete(1);
var b = new Delta().delete(1);
var expected = new Delta().delete(2);
expect(a.compose(b)).to.deep.equal(expected);
});
it('retain + insert', function () {
var a = new Delta().retain(1, { color: 'blue' });
var b = new Delta().insert('B');
var expected = new Delta().insert('B').retain(1, { color: 'blue' });
expect(a.compose(b)).to.deep.equal(expected);
});
it('retain + retain', function () {
var a = new Delta().retain(1, { color: 'blue' });
var b = new Delta().retain(1, { bold: true, color: 'red', font: null });
var expected = new Delta().retain(1, { bold: true, color: 'red', font: null });
expect(a.compose(b)).to.deep.equal(expected);
});
it('retain + delete', function () {
var a = new Delta().retain(1, { color: 'blue' });
var b = new Delta().delete(1);
var expected = new Delta().delete(1);
expect(a.compose(b)).to.deep.equal(expected);
});
it('insert in middle of text', function () {
var a = new Delta().insert('Hello');
var b = new Delta().retain(3).insert('X');
var expected = new Delta().insert('HelXlo');
expect(a.compose(b)).to.deep.equal(expected);
});
it('insert and delete ordering', function () {
var a = new Delta().insert('Hello');
var b = new Delta().insert('Hello');
var insertFirst = new Delta().retain(3).insert('X').delete(1);
var deleteFirst = new Delta().retain(3).delete(1).insert('X');
var expected = new Delta().insert('HelXo');
expect(a.compose(insertFirst)).to.deep.equal(expected);
expect(b.compose(deleteFirst)).to.deep.equal(expected);
});
it('insert embed', function () {
var a = new Delta().insert(1, { src: 'http://quilljs.com/image.png' });
var b = new Delta().retain(1, { alt: 'logo' });
var expected = new Delta().insert(1, { src: 'http://quilljs.com/image.png', alt: 'logo' });
expect(a.compose(b)).to.deep.equal(expected);
});
it('delete entire text', function () {
var a = new Delta().retain(4).insert('Hello');
var b = new Delta().delete(9);
var expected = new Delta().delete(4);
expect(a.compose(b)).to.deep.equal(expected);
});
it('retain more than length of text', function () {
var a = new Delta().insert('Hello');
var b = new Delta().retain(10);
var expected = new Delta().insert('Hello');
expect(a.compose(b)).to.deep.equal(expected);
});
it('retain empty embed', function () {
var a = new Delta().insert(1);
var b = new Delta().retain(1);
var expected = new Delta().insert(1);
expect(a.compose(b)).to.deep.equal(expected);
});
it('remove all attributes', function () {
var a = new Delta().insert('A', { bold: true });
var b = new Delta().retain(1, { bold: null });
var expected = new Delta().insert('A');
expect(a.compose(b)).to.deep.equal(expected);
});
it('remove all embed attributes', function () {
var a = new Delta().insert(2, { bold: true });
var b = new Delta().retain(1, { bold: null });
var expected = new Delta().insert(2);
expect(a.compose(b)).to.deep.equal(expected);
});
});
+72
View File
@@ -0,0 +1,72 @@
var Delta = require('../../lib/delta');
var expect = require('chai').expect;
describe('diff()', function () {
it('insert', function () {
var a = new Delta().insert('A');
var b = new Delta().insert('AB');
var expected = new Delta().retain(1).insert('B');
expect(a.diff(b)).to.deep.equal(expected);
});
it('delete', function () {
var a = new Delta().insert('AB');
var b = new Delta().insert('A');
var expected = new Delta().retain(1).delete(1);
expect(a.diff(b)).to.deep.equal(expected);
});
it('retain', function () {
var a = new Delta().insert('A');
var b = new Delta().insert('A');
var expected = new Delta();
expect(a.diff(b)).to.deep.equal(expected);
});
it('format', function () {
var a = new Delta().insert('A');
var b = new Delta().insert('A', { bold: true });
var expected = new Delta().retain(1, { bold: true });
expect(a.diff(b)).to.deep.equal(expected);
});
it('embed match', function () {
var a = new Delta().insert(1);
var b = new Delta().insert(1);
var expected = new Delta();
expect(a.diff(b)).to.deep.equal(expected);
});
it('embed false positive', function () {
var a = new Delta().insert(1);
var b = new Delta().insert(String.fromCharCode(0)); // Placeholder char for embed in diff()
var expected = new Delta().insert(String.fromCharCode(0)).delete(1);
expect(a.diff(b)).to.deep.equal(expected);
});
it('error on non-documents', function () {
var a = new Delta().insert('A');
var b = new Delta().retain(1).insert('B');
expect(function () {
a.diff(b);
}).to.throw(Error);
expect(function () {
b.diff(a);
}).to.throw(Error);
});
it('inconvenient indexes', function () {
var a = new Delta().insert('12', { bold: true }).insert('34', { italic: true });
var b = new Delta().insert('123', { color: 'red' });
var expected = new Delta().retain(2, { bold: null, color: 'red' }).retain(1, { italic: null, color: 'red' }).delete(1);
expect(a.diff(b)).to.deep.equal(expected);
});
it('combination', function () {
var a = new Delta().insert('Bad', { color: 'red' }).insert('cat', { color: 'blue' });
var b = new Delta().insert('Good', { bold: true }).insert('dog', { italic: true });
var expected = new Delta().insert('Good', { bold: true }).delete(2).retain(1, { italic: true, color: null }).delete(3).insert('og', { italic: true });
expect(a.diff(b)).to.deep.equal(expected);
});
});
+81
View File
@@ -0,0 +1,81 @@
var Delta = require('../../lib/delta');
var expect = require('chai').expect;
describe('helpers', function () {
describe('chop()', function () {
it('retain', function () {
var delta = new Delta().insert('Test').retain(4);
var expected = new Delta().insert('Test');
expect(delta.chop()).to.deep.equal(expected);
});
it('insert', function () {
var delta = new Delta().insert('Test');
var expected = new Delta().insert('Test');
expect(delta.chop()).to.deep.equal(expected);
});
it('formatted retain', function () {
var delta = new Delta().insert('Test').retain(4, { bold: true });
var expected = new Delta().insert('Test').retain(4, { bold: true });
expect(delta.chop()).to.deep.equal(expected);
})
});
describe('length()', function () {
it('document', function () {
var delta = new Delta().insert('AB', { bold: true }).insert(1);
expect(delta.length()).to.equal(3);
});
it('mixed', function () {
var delta = new Delta().insert('AB', { bold: true }).insert(1).retain(2, { bold: null }).delete(1);
expect(delta.length()).to.equal(6);
});
});
describe('slice()', function () {
it('start', function () {
var slice = new Delta().retain(2).insert('A').slice(2);
var expected = new Delta().insert('A');
expect(slice).to.deep.equal(expected);
});
it('start and end chop', function () {
var slice = new Delta().insert('0123456789').slice(2, 7);
var expected = new Delta().insert('23456');
expect(slice).to.deep.equal(expected);
});
it('start and end multiple chop', function () {
var slice = new Delta().insert('0123', { bold: true }).insert('4567').slice(3, 5);
var expected = new Delta().insert('3', { bold: true }).insert('4');
expect(slice).to.deep.equal(expected);
});
it('start and end', function () {
var slice = new Delta().retain(2).insert('A', { bold: true }).insert('B').slice(2, 3);
var expected = new Delta().insert('A', { bold: true });
expect(slice).to.deep.equal(expected);
});
it('no params', function () {
var delta = new Delta().retain(2).insert('A', { bold: true }).insert('B');
var slice = delta.slice();
expect(slice).to.deep.equal(delta);
});
it('split ops', function () {
var slice = new Delta().insert('AB', { bold: true }).insert('C').slice(1, 2);
var expected = new Delta().insert('B', { bold: true });
expect(slice).to.deep.equal(expected);
});
it('split ops multiple times', function () {
var slice = new Delta().insert('ABC', { bold: true }).insert('D').slice(1, 2);
var expected = new Delta().insert('B', { bold: true });
expect(slice).to.deep.equal(expected);
});
});
});
+51
View File
@@ -0,0 +1,51 @@
var Delta = require('../../lib/delta');
var expect = require('chai').expect;
describe('transformPosition()', function () {
it('insert before position', function () {
var delta = new Delta().insert('A');
expect(delta.transform(2)).to.equal(3);
});
it('insert after position', function () {
var delta = new Delta().retain(2).insert('A');
expect(delta.transform(1)).to.equal(1);
});
it('insert at position', function () {
var delta = new Delta().retain(2).insert('A');
expect(delta.transform(2, true)).to.equal(2);
expect(delta.transform(2, false)).to.equal(3);
});
it('delete before position', function () {
var delta = new Delta().delete(2);
expect(delta.transform(4)).to.equal(2);
});
it('delete after position', function () {
var delta = new Delta().retain(4).delete(2);
expect(delta.transform(2)).to.equal(2);
});
it('delete across position', function () {
var delta = new Delta().retain(1).delete(4);
expect(delta.transform(2)).to.equal(1);
});
it('insert and delete before position', function () {
var delta = new Delta().retain(2).insert('A').delete(2);
expect(delta.transform(4)).to.equal(3);
});
it('insert before and delete across position', function () {
var delta = new Delta().retain(2).insert('A').delete(4);
expect(delta.transform(4)).to.equal(3);
});
it('delete before and delete across position', function () {
var delta = new Delta().delete(1).retain(1).delete(4);
expect(delta.transform(4)).to.equal(1);
});
});
+131
View File
@@ -0,0 +1,131 @@
var Delta = require('../../lib/delta');
var expect = require('chai').expect;
describe('transform()', function () {
it('insert + insert', function () {
var a1 = new Delta().insert('A');
var b1 = new Delta().insert('B');
var a2 = new Delta(a1);
var b2 = new Delta(b1);
var expected1 = new Delta().retain(1).insert('B');
var expected2 = new Delta().insert('B');
expect(a1.transform(b1, true)).to.deep.equal(expected1);
expect(a2.transform(b2, false)).to.deep.equal(expected2);
});
it('insert + retain', function () {
var a = new Delta().insert('A');
var b = new Delta().retain(1, { bold: true, color: 'red' });
var expected = new Delta().retain(1).retain(1, { bold: true, color: 'red' });
expect(a.transform(b, true)).to.deep.equal(expected);
});
it('insert + delete', function () {
var a = new Delta().insert('A');
var b = new Delta().delete(1);
var expected = new Delta().retain(1).delete(1);
expect(a.transform(b, true)).to.deep.equal(expected);
});
it('delete + insert', function () {
var a = new Delta().delete(1);
var b = new Delta().insert('B');
var expected = new Delta().insert('B');
expect(a.transform(b, true)).to.deep.equal(expected);
});
it('delete + retain', function () {
var a = new Delta().delete(1);
var b = new Delta().retain(1, { bold: true, color: 'red' });
var expected = new Delta();
expect(a.transform(b, true)).to.deep.equal(expected);
});
it('delete + delete', function () {
var a = new Delta().delete(1);
var b = new Delta().delete(1);
var expected = new Delta();
expect(a.transform(b, true)).to.deep.equal(expected);
});
it('retain + insert', function () {
var a = new Delta().retain(1, { color: 'blue' });
var b = new Delta().insert('B');
var expected = new Delta().insert('B');
expect(a.transform(b, true)).to.deep.equal(expected);
});
it('retain + retain', function () {
var a1 = new Delta().retain(1, { color: 'blue' });
var b1 = new Delta().retain(1, { bold: true, color: 'red' });
var a2 = new Delta().retain(1, { color: 'blue' });
var b2 = new Delta().retain(1, { bold: true, color: 'red' });
var expected1 = new Delta().retain(1, { bold: true });
var expected2 = new Delta();
expect(a1.transform(b1, true)).to.deep.equal(expected1);
expect(b2.transform(a2, true)).to.deep.equal(expected2);
});
it('retain + retain without priority', function () {
var a1 = new Delta().retain(1, { color: 'blue' });
var b1 = new Delta().retain(1, { bold: true, color: 'red' });
var a2 = new Delta().retain(1, { color: 'blue' });
var b2 = new Delta().retain(1, { bold: true, color: 'red' });
var expected1 = new Delta().retain(1, { bold: true, color: 'red' });
var expected2 = new Delta().retain(1, { color: 'blue' });
expect(a1.transform(b1, false)).to.deep.equal(expected1);
expect(b2.transform(a2, false)).to.deep.equal(expected2);
});
it('retain + delete', function () {
var a = new Delta().retain(1, { color: 'blue' });
var b = new Delta().delete(1);
var expected = new Delta().delete(1);
expect(a.transform(b, true)).to.deep.equal(expected);
});
it('alternating edits', function () {
var a1 = new Delta().retain(2).insert('si').delete(5);
var b1 = new Delta().retain(1).insert('e').delete(5).retain(1).insert('ow');
var a2 = new Delta(a1);
var b2 = new Delta(b1);
var expected1 = new Delta().retain(1).insert('e').delete(1).retain(2).insert('ow');
var expected2 = new Delta().retain(2).insert('si').delete(1);
expect(a1.transform(b1, false)).to.deep.equal(expected1);
expect(b2.transform(a2, false)).to.deep.equal(expected2);
});
it('conflicting appends', function () {
var a1 = new Delta().retain(3).insert('aa');
var b1 = new Delta().retain(3).insert('bb');
var a2 = new Delta(a1);
var b2 = new Delta(b1);
var expected1 = new Delta().retain(5).insert('bb');
var expected2 = new Delta().retain(3).insert('aa');
expect(a1.transform(b1, true)).to.deep.equal(expected1);
expect(b2.transform(a2, false)).to.deep.equal(expected2);
});
it('prepend + append', function () {
var a1 = new Delta().insert('aa');
var b1 = new Delta().retain(3).insert('bb');
var expected1 = new Delta().retain(5).insert('bb');
var a2 = new Delta(a1);
var b2 = new Delta(b1);
var expected2 = new Delta().insert('aa');
expect(a1.transform(b1, false)).to.deep.equal(expected1);
expect(b2.transform(a2, false)).to.deep.equal(expected2);
});
it('trailing deletes with differing lengths', function () {
var a1 = new Delta().retain(2).delete(1);
var b1 = new Delta().delete(3);
var expected1 = new Delta().delete(2);
var a2 = new Delta(a1);
var b2 = new Delta(b1);
var expected2 = new Delta();
expect(a1.transform(b1, false)).to.deep.equal(expected1);
expect(b2.transform(a2, false)).to.deep.equal(expected2);
});
});
+139
View File
@@ -0,0 +1,139 @@
var _ = require('lodash');
var fuzzer = require('ot-fuzzer');
var richType = require('../lib/type');
var Delta = richType.Delta;
var FORMATS = {
color: ['red', 'orange', 'yellow', 'green', 'blue', 'purple', null],
font: ['serif', 'sans-serif', 'monospace', null],
bold: [true, null],
italic: [true, null]
};
function generateRandomFormat (includeNull) {
var format = {};
for (var key in FORMATS) {
if (fuzzer.randomReal() < 0.5) {
var value = FORMATS[key][fuzzer.randomInt(FORMATS[key].length)];
if (value || includeNull) {
format[key] = value;
}
}
}
return Object.keys(format).length > 0 ? format : undefined;
};
function generateRandomOp (snapshot) {
snapshot = _.cloneDeep(snapshot);
var length = snapshot.ops.reduce(function(length, op) {
if (!op.insert) {
console.error(snapshot);
throw new Error('Snapshot should only have inserts');
}
// Snapshot should only have inserts
return length + (_.isString(op.insert) ? op.insert.length : 1);
}, 0);
var base = length > 100 ? 10 : 7; // Favor deleting on long documents
var delta = new Delta();
var result = new Delta();
do {
// Allows insert/delete to occur at the end (deletes will be noop)
var modIndex = fuzzer.randomInt(Math.min(length, 5) + 1);
length -= modIndex;
var modLength = Math.min(length, fuzzer.randomInt(4) + 1);
delta.retain(modIndex);
var ops = next(snapshot, modIndex);
for (var i in ops) {
result.push(ops[i]);
}
switch (fuzzer.randomInt(base)) {
case 0:
// Insert plain text
var word = fuzzer.randomWord();
delta.insert(word);
result.insert(word);
break;
case 1:
// Insert formatted text
var word = fuzzer.randomWord();
var formats = generateRandomFormat(false);
delta.insert(word, formats);
result.insert(word, formats);
break;
case 2:
// Insert embed
var type = fuzzer.randomInt(2) + 1;
var formats = generateRandomFormat(false);
delta.insert(type, formats);
result.insert(type, formats);
break;
case 3: case 4:
var attributes = generateRandomFormat(true);
delta.retain(modLength, attributes);
ops = next(snapshot, modLength);
for (var i in ops) {
ops[i].attributes = ops[i].attributes || {};
for (var key in attributes) {
ops[i].attributes[key] = (attributes[key] === null) ? undefined : attributes[key];
}
ops[i].attributes = _.reduce(ops[i].attributes, function (memo, value, key) {
if (value !== null && value !== undefined) {
memo[key] = value;
}
return memo;
}, {});
var newOp = { insert: ops[i].insert };
if (_.keys(ops[i].attributes).length > 0) newOp.attributes = ops[i].attributes;
result.push(newOp);
}
length -= modLength;
break;
default:
next(snapshot, modLength);
delta.delete(modLength);
length -= modLength;
break;
}
} while (length > 0 && fuzzer.randomInt(2) > 0);
for (var i in snapshot.ops) {
result.push(snapshot.ops[i]);
}
return [delta, result];
};
function next (snapshot, length) {
var ops = [];
while (length > 0) {
var opLength;
if (_.isString(snapshot.ops[0].insert)) {
if (length >= snapshot.ops[0].insert.length) {
opLength = snapshot.ops[0].insert.length;
ops.push(snapshot.ops.shift());
} else {
var insert = snapshot.ops[0].insert.substr(0, length);
snapshot.ops[0].insert = snapshot.ops[0].insert.substr(insert.length);
opLength = insert.length;
var op = { insert: insert };
if (snapshot.ops[0].attributes) {
op.attributes = _.clone(snapshot.ops[0].attributes);
}
ops.push(op);
}
} else {
ops.push(snapshot.ops.shift());
opLength = 1;
}
length -= opLength;
}
return ops;
};
fuzzer(richType, generateRandomOp, 100);
+132
View File
@@ -0,0 +1,132 @@
var is = require('../lib/is');
var expect = require('chai').expect;
describe('is', function () {
describe('equal()', function () {
it('exact objects', function () {
var obj = { a: 1, b: true, c: 'test' };
expect(is.equal(obj, obj)).to.equal(true);
});
it('deep equal objects', function () {
var obj1 = { a: 1, b: true, c: 'test' };
var obj2 = { a: 1, c: 'test', b: true };
expect(is.equal(obj1, obj2)).to.equal(true);
});
it('different keys', function () {
var obj1 = { a: 1, b: true, c: 'test' };
var obj2 = { a: 1, c: 'test', b: false };
expect(is.equal(obj1, obj2)).to.equal(false);
});
it('missing keys', function () {
var obj1 = { a: 1, b: true, c: 'test' };
var obj2 = { a: 1, c: 'test'};
expect(is.equal(obj1, obj2)).to.equal(false);
});
it('null and undefined', function () {
expect(is.equal(null, undefined)).to.equal(true);
});
it('existing with nonexisting', function () {
expect(is.equal({}, null)).to.equal(false);
});
});
describe('array()', function () {
it('literal', function () {
expect(is.array([])).to.equal(true);
});
it('instance', function () {
expect(is.array(new Array())).to.equal(true);
});
it('null', function () {
expect(is.array(null)).to.equal(false);
});
});
describe('number()', function () {
it('literal', function () {
expect(is.number(11)).to.equal(true);
});
it('object', function () {
expect(is.number(new Number(0))).to.equal(true);
});
it('NaN', function () {
expect(is.number(NaN)).to.equal(true);
});
it('Infinity', function () {
expect(is.number(Infinity)).to.equal(true);
});
it('null', function () {
expect(is.number(null)).to.equal(false);
});
it('wrong type', function () {
expect(is.number({})).to.equal(false);
});
});
describe('object()', function () {
it('literal', function () {
expect(is.object({})).to.equal(true);
});
it('instance', function () {
function obj() {};
expect(is.object(new obj)).to.equal(true);
});
it('string literal', function () {
expect(is.object('test')).to.equal(false);
});
it('string instance', function () {
expect(is.object(new String('test'))).to.equal(true);
});
it('number literal', function () {
expect(is.object(1)).to.equal(false);
});
it('number instance', function () {
expect(is.object(new Number(1))).to.equal(true);
});
it('null', function () {
expect(is.object(null)).to.equal(false);
});
it('function', function () {
expect(is.object(function () {})).to.equal(true);
});
});
describe('string()', function () {
it('literal', function () {
expect(is.string('test')).to.equal(true);
});
it('object', function () {
expect(is.string(new String('test'))).to.equal(true);
});
it('null', function () {
expect(is.string(null)).to.equal(false);
});
it('wrong type', function () {
expect(is.string({})).to.equal(false);
});
});
});
+93
View File
@@ -0,0 +1,93 @@
var Delta = require('../lib/delta');
var op = require('../lib/op');
var expect = require('chai').expect;
describe('op', function () {
describe('length()', function () {
it('delete', function () {
expect(op.length({ delete: 5 })).to.equal(5);
});
it('retain', function () {
expect(op.length({ retain: 2 })).to.equal(2);
});
it('insert text', function () {
expect(op.length({ insert: 'text' })).to.equal(4);
});
it('insert embed', function () {
expect(op.length({ insert: 2 })).to.equal(1);
});
});
describe('iterator()', function () {
beforeEach(function () {
this.delta = new Delta().insert('Hello', { bold: true }).retain(3).insert(2, { src: 'http://quilljs.com/' }).delete(4);
});
it('hasNext() true', function () {
var iter = op.iterator(this.delta.ops);
expect(iter.hasNext()).to.equal(true);
});
it('hasNext() false', function () {
var iter = op.iterator([]);
expect(iter.hasNext()).to.equal(false);
});
it('peekLength() offset === 0', function () {
var iter = op.iterator(this.delta.ops);
expect(iter.peekLength()).to.equal(5);
iter.next();
expect(iter.peekLength()).to.equal(3);
iter.next();
expect(iter.peekLength()).to.equal(1);
iter.next();
expect(iter.peekLength()).to.equal(4);
});
it('peekLength() offset > 0', function () {
var iter = op.iterator(this.delta.ops);
iter.next(2);
expect(iter.peekLength()).to.equal(5 - 2);
});
it('peekLength() no ops left', function () {
var iter = op.iterator([]);
expect(iter.peekLength()).to.equal(Infinity);
});
it('peekType()', function () {
var iter = op.iterator(this.delta.ops);
expect(iter.peekType()).to.equal('insert');
iter.next();
expect(iter.peekType()).to.equal('retain');
iter.next();
expect(iter.peekType()).to.equal('insert');
iter.next();
expect(iter.peekType()).to.equal('delete');
iter.next();
expect(iter.peekType()).to.equal('retain');
});
it('next()', function () {
var iter = op.iterator(this.delta.ops);
for (var i = 0; i < this.delta.ops.length; i += 1) {
expect(iter.next()).to.deep.equal(this.delta.ops[i]);
}
expect(iter.next()).to.deep.equal({ retain: Infinity });
expect(iter.next(4)).to.deep.equal({ retain: Infinity });
expect(iter.next()).to.deep.equal({ retain: Infinity });
});
it('next(length)', function () {
var iter = op.iterator(this.delta.ops);
expect(iter.next(2)).to.deep.equal({ insert: 'He', attributes: { bold: true }});
expect(iter.next(10)).to.deep.equal({ insert: 'llo', attributes: { bold: true }});
expect(iter.next(1)).to.deep.equal({ retain: 1 });
expect(iter.next(2)).to.deep.equal({ retain: 2 });
});
});
});