first commit

This commit is contained in:
Beyhan Oğur
2026-04-26 21:33:39 +03:00
commit 4362c3b83f
1991 changed files with 285411 additions and 0 deletions

View File

@@ -0,0 +1,14 @@
BSD 3-Clause License
Copyright (c) 2022, Slab, Inc.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View File

@@ -0,0 +1,672 @@
# Delta [![Build Status](https://github.com/quilljs/delta/actions/workflows/main.yml/badge.svg?branch=master)](https://github.com/quilljs/delta/actions?query=branch%3Amaster) [![Coverage Status](https://img.shields.io/coveralls/quilljs/delta.svg)](https://coveralls.io/r/quilljs/delta)
Deltas are a simple, yet expressive format that can be used to describe contents and changes. The format is JSON based, and is human readable, yet easily parsible by machines. Deltas can describe any rich text document, includes all text and formatting information, without the ambiguity and complexity of HTML.
A Delta is made up of an [Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) of Operations, which describe changes 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.
Dont be confused by its name Delta—Deltas represents both documents and changes to documents. If you think of Deltas as the instructions from going from one document to another, the way Deltas represent a document is by expressing the instructions starting from an empty document.
## Quick Example
```js
// Document with text "Gandalf the Grey"
// with "Gandalf" bolded, and "Grey" in grey
const delta = new Delta([
{ insert: 'Gandalf', attributes: { bold: true } },
{ insert: ' the ' },
{ insert: 'Grey', attributes: { color: '#ccc' } }
]);
// Change intended to be applied to above:
// Keep the first 12 characters, insert a white 'White'
// and delete the next four characters ('Grey')
const death = new Delta().retain(12)
.insert('White', { color: '#fff' })
.delete(4);
// {
// ops: [
// { retain: 12 },
// { insert: 'White', attributes: { color: '#fff' } },
// { delete: 4 }
// ]
// }
// Applying the above:
const restored = delta.compose(death);
// {
// ops: [
// { insert: 'Gandalf', attributes: { bold: true } },
// { insert: ' the ' },
// { insert: 'White', attributes: { color: '#fff' } }
// ]
// }
```
This README describes Deltas in its general form and API functionality. Additional information on the way Quill specifically uses Deltas can be found on its own [Delta docs](http://quilljs.com/docs/delta/). A walkthough of the motivation and design thinking behind Deltas are on [Designing the Delta Format](http://quilljs.com/guides/designing-the-delta-format/).
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
- [`insert`](#insert-operation)
- [`delete`](#delete-operation)
- [`retain`](#retain-operation)
#### Construction
- [`constructor`](#constructor)
- [`insert`](#insert)
- [`delete`](#delete)
- [`retain`](#retain)
#### Documents
These methods called on or with non-document Deltas will result in undefined behavior.
- [`concat`](#concat)
- [`diff`](#diff)
- [`eachLine`](#eachline)
- [`invert`](#invert)
#### Utility
- [`filter`](#filter)
- [`forEach`](#foreach)
- [`length`](#length)
- [`map`](#map)
- [`partition`](#partition)
- [`reduce`](#reduce)
- [`slice`](#slice)
#### Operational Transform
- [`compose`](#compose)
- [`transform`](#transform)
- [`transformPosition`](#transformposition)
## Operations
### Insert Operation
Insert operations have an `insert` key defined. A String value represents inserting text. Any other type represents inserting an embed (however only one level of object comparison will be performed for equality).
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: { link: 'https://www.google.com' } }
// Insert an embed
{
insert: { image: 'https://octodex.github.com/images/labtocat.png' },
attributes: { alt: "Lab Octocat" }
}
// Insert another embed
{
insert: { video: 'https://www.youtube.com/watch?v=dMH0bHeiRNg' },
attributes: {
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 } }
```
## Construction
### 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 from ops or delta.ops without deep copying.*
#### Example
```js
const delta = new Delta([
{ insert: 'Hello World' },
{ insert: '!', attributes: { bold: true }}
]);
const packet = JSON.stringify(delta);
const other = new Delta(JSON.parse(packet));
const chained = new Delta().insert('Hello World').insert('!', { bold: true });
```
---
### insert()
Appends an insert operation. Returns `this` for chainability.
#### Methods
- `insert(text, attributes)`
- `insert(embed, attributes)`
#### Parameters
- `text` - String representing text to insert
- `embed` - Object representing embed type to insert
- `attributes` - Optional attributes to apply
#### Example
```js
delta.insert('Text', { bold: true, color: '#ccc' });
delta.insert({ image: 'https://octodex.github.com/images/labtocat.png' });
```
---
### delete()
Appends a delete operation. Returns `this` for chainability.
#### Methods
- `delete(length)`
#### Parameters
- `length` - Number of characters to delete
#### Example
```js
delta.delete(5);
```
---
### retain()
Appends a retain operation. Returns `this` for chainability.
#### 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' });
```
## Documents
### concat()
Returns a new Delta representing the concatenation of this and another document Delta's operations.
#### Methods
- `concat(other)`
#### Parameters
- `other` - Document Delta to concatenate
#### Returns
- `Delta` - Concatenated document Delta
#### Example
```js
const a = new Delta().insert('Hello');
const b = new Delta().insert('!', { bold: true });
// {
// ops: [
// { insert: 'Hello' },
// { insert: '!', attributes: { bold: true } }
// ]
// }
const concat = a.concat(b);
```
---
### diff()
Returns a Delta representing the difference between two documents. Optionally, accepts a suggested index where change took place, often representing a cursor position *before* change.
#### Methods
- `diff(other)`
- `diff(other, index)`
#### Parameters
- `other` - Document Delta to diff against
- `index` - Suggested index where change took place
#### Returns
- `Delta` - difference between the two documents
#### Example
```js
const a = new Delta().insert('Hello');
const b = new Delta().insert('Hello!');
const diff = a.diff(b); // { ops: [{ retain: 5 }, { insert: '!' }] }
// a.compose(diff) == b
```
---
### eachLine()
Iterates through document Delta, calling a given function with a Delta and attributes object, representing the line segment.
#### Methods
- `eachLine(predicate, newline)`
#### Parameters
- `predicate` - function to call on each line group
- `newline` - newline character, defaults to `\n`
#### Example
```js
const delta = new Delta().insert('Hello\n\n')
.insert('World')
.insert({ image: 'octocat.png' })
.insert('\n', { align: 'right' })
.insert('!');
delta.eachLine((line, attributes, i) => {
console.log(line, attributes, i);
// Can return false to exit loop early
});
// Should log:
// { ops: [{ insert: 'Hello' }] }, {}, 0
// { ops: [] }, {}, 1
// { ops: [{ insert: 'World' }, { insert: { image: 'octocat.png' } }] }, { align: 'right' }, 2
// { ops: [{ insert: '!' }] }, {}, 3
```
---
### invert()
Returned an inverted delta that has the opposite effect of against a base document delta. That is `base.compose(delta).compose(inverted) === base`.
#### Methods
- `invert(base)`
#### Parameters
- `base` - Document delta to invert against
#### Returns
- `Delta` - inverted delta against the base delta
#### Example
```js
const base = new Delta().insert('Hello\n')
.insert('World');
const delta = new Delta().retain(6, { bold: true }).insert('!').delete(5);
const inverted = delta.invert(base); // { ops: [
// { retain: 6, attributes: { bold: null } },
// { insert: 'World' },
// { delete: 1 }
// ]}
// base.compose(delta).compose(inverted) === base
```
## Utility
### filter()
Returns an array of operations that passes a given function.
#### Methods
- `filter(predicate)`
#### Parameters
- `predicate` - Function to test each operation against. Return `true` to keep the operation, `false` otherwise.
#### Returns
- `Array` - Filtered resulting array
#### Example
```js
const delta = new Delta().insert('Hello', { bold: true })
.insert({ image: 'https://octodex.github.com/images/labtocat.png' })
.insert('World!');
const text = delta
.filter((op) => typeof op.insert === 'string')
.map((op) => op.insert)
.join('');
```
---
### forEach()
Iterates through operations, calling the provided function for each operation.
#### Methods
- `forEach(predicate)`
#### Parameters
- `predicate` - Function to call during iteration, passing in the current operation.
#### Example
```js
delta.forEach((op) => {
console.log(op);
});
```
---
### length()
Returns length of a Delta, which is the sum of the lengths of its operations.
#### Methods
- `length()`
#### Example
```js
new Delta().insert('Hello').length(); // Returns 5
new Delta().insert('A').retain(2).delete(1).length(); // Returns 4
```
---
### map()
Returns a new array with the results of calling provided function on each operation.
#### Methods
- `map(predicate)`
#### Parameters
- `predicate` - Function to call, passing in the current operation, returning an element of the new array to be returned
#### Returns
- `Array` - A new array with each element being the result of the given function.
#### Example
```js
const delta = new Delta().insert('Hello', { bold: true })
.insert({ image: 'https://octodex.github.com/images/labtocat.png' })
.insert('World!');
const text = delta
.map((op) => {
if (typeof op.insert === 'string') {
return op.insert;
} else {
return '';
}
})
.join('');
```
---
### partition()
Create an array of two arrays, the first with operations that pass the given function, the other that failed.
#### Methods
- `partition(predicate)`
#### Parameters
- `predicate` - Function to call, passing in the current operation, returning whether that operation passed
#### Returns
- `Array` - A new array of two Arrays, the first with passed operations, the other with failed operations
#### Example
```js
const delta = new Delta().insert('Hello', { bold: true })
.insert({ image: 'https://octodex.github.com/images/labtocat.png' })
.insert('World!');
const results = delta.partition((op) => typeof op.insert === 'string');
const passed = results[0]; // [{ insert: 'Hello', attributes: { bold: true }},
// { insert: 'World'}]
const failed = results[1]; // [{ insert: { image: 'https://octodex.github.com/images/labtocat.png' }}]
```
---
### reduce()
Applies given function against an accumulator and each operation to reduce to a single value.
#### Methods
- `reduce(predicate, initialValue)`
#### Parameters
- `predicate` - Function to call per iteration, returning an accumulated value
- `initialValue` - Initial value to pass to first call to predicate
#### Returns
- `any` - the accumulated value
#### Example
```js
const delta = new Delta().insert('Hello', { bold: true })
.insert({ image: 'https://octodex.github.com/images/labtocat.png' })
.insert('World!');
const length = delta.reduce((length, op) => (
length + (op.insert.length || 1);
), 0);
```
---
### 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
const delta = new Delta().insert('Hello', { bold: true }).insert(' World');
// {
// ops: [
// { insert: 'Hello', attributes: { bold: true } },
// { insert: ' World' }
// ]
// }
const copy = delta.slice();
// { ops: [{ insert: 'World' }] }
const world = delta.slice(6);
// { ops: [{ insert: ' ' }] }
const space = delta.slice(5, 6);
```
## Operational Transform
### compose()
Returns a Delta that is equivalent to applying the operations of own Delta, followed by another Delta.
#### Methods
- `compose(other)`
#### Parameters
- `other` - Delta to compose
#### Example
```js
const a = new Delta().insert('abc');
const b = new Delta().retain(1).delete(1);
const composed = a.compose(b); // composed == new Delta().insert('ac');
```
---
### transform()
Transform given Delta against own operations.
#### Methods
- `transform(other, priority = false)`
- `transform(index, priority = false)` - Alias for [`transformPosition`](#tranformposition)
#### Parameters
- `other` - Delta to transform
- `priority` - Boolean used to break ties. If `true`, then `this` takes priority
over `other`, that is, its actions are considered to happen "first."
#### Returns
- `Delta` - transformed Delta
#### Example
```js
const a = new Delta().insert('a');
const b = new Delta().insert('b').retain(5).insert('c');
a.transform(b, true); // new Delta().retain(1).insert('b').retain(5).insert('c');
a.transform(b, false); // new Delta().insert('b').retain(6).insert('c');
```
---
### transformPosition()
Transform an index against the delta. Useful for representing cursor/selection positions.
#### Methods
- `transformPosition(index, priority = false)`
#### Parameters
- `index` - index to transform
#### Returns
- `Number` - transformed index
#### Example
```js
const delta = new Delta().retain(5).insert('a');
delta.transformPosition(4); // 4
delta.transformPosition(5); // 6
```

View File

@@ -0,0 +1,10 @@
interface AttributeMap {
[key: string]: unknown;
}
declare namespace AttributeMap {
function compose(a?: AttributeMap, b?: AttributeMap, keepNull?: boolean): AttributeMap | undefined;
function diff(a?: AttributeMap, b?: AttributeMap): AttributeMap | undefined;
function invert(attr?: AttributeMap, base?: AttributeMap): AttributeMap;
function transform(a: AttributeMap | undefined, b: AttributeMap | undefined, priority?: boolean): AttributeMap | undefined;
}
export default AttributeMap;

View File

@@ -0,0 +1,86 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const cloneDeep = require("lodash.clonedeep");
const isEqual = require("lodash.isequal");
var AttributeMap;
(function (AttributeMap) {
function compose(a = {}, b = {}, keepNull = false) {
if (typeof a !== 'object') {
a = {};
}
if (typeof b !== 'object') {
b = {};
}
let attributes = cloneDeep(b);
if (!keepNull) {
attributes = Object.keys(attributes).reduce((copy, key) => {
if (attributes[key] != null) {
copy[key] = attributes[key];
}
return copy;
}, {});
}
for (const key in a) {
if (a[key] !== undefined && b[key] === undefined) {
attributes[key] = a[key];
}
}
return Object.keys(attributes).length > 0 ? attributes : undefined;
}
AttributeMap.compose = compose;
function diff(a = {}, b = {}) {
if (typeof a !== 'object') {
a = {};
}
if (typeof b !== 'object') {
b = {};
}
const attributes = Object.keys(a)
.concat(Object.keys(b))
.reduce((attrs, key) => {
if (!isEqual(a[key], b[key])) {
attrs[key] = b[key] === undefined ? null : b[key];
}
return attrs;
}, {});
return Object.keys(attributes).length > 0 ? attributes : undefined;
}
AttributeMap.diff = diff;
function invert(attr = {}, base = {}) {
attr = attr || {};
const baseInverted = Object.keys(base).reduce((memo, key) => {
if (base[key] !== attr[key] && attr[key] !== undefined) {
memo[key] = base[key];
}
return memo;
}, {});
return Object.keys(attr).reduce((memo, key) => {
if (attr[key] !== base[key] && base[key] === undefined) {
memo[key] = null;
}
return memo;
}, baseInverted);
}
AttributeMap.invert = invert;
function transform(a, b, priority = false) {
if (typeof a !== 'object') {
return b;
}
if (typeof b !== 'object') {
return undefined;
}
if (!priority) {
return b; // b simply overwrites us without priority
}
const attributes = Object.keys(b).reduce((attrs, key) => {
if (a[key] === undefined) {
attrs[key] = b[key]; // null is a valid value
}
return attrs;
}, {});
return Object.keys(attributes).length > 0 ? attributes : undefined;
}
AttributeMap.transform = transform;
})(AttributeMap || (AttributeMap = {}));
exports.default = AttributeMap;
//# sourceMappingURL=AttributeMap.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"AttributeMap.js","sourceRoot":"","sources":["../src/AttributeMap.ts"],"names":[],"mappings":"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"}

View File

@@ -0,0 +1,45 @@
import * as diff from 'fast-diff';
import AttributeMap from './AttributeMap';
import Op from './Op';
import OpIterator from './OpIterator';
interface EmbedHandler<T> {
compose(a: T, b: T, keepNull: boolean): T;
invert(a: T, b: T): T;
transform(a: T, b: T, priority: boolean): T;
}
declare class Delta {
static Op: typeof Op;
static OpIterator: typeof OpIterator;
static AttributeMap: typeof AttributeMap;
private static handlers;
static registerEmbed<T>(embedType: string, handler: EmbedHandler<T>): void;
static unregisterEmbed(embedType: string): void;
private static getHandler;
ops: Op[];
constructor(ops?: Op[] | {
ops: Op[];
});
insert(arg: string | Record<string, unknown>, attributes?: AttributeMap | null): this;
delete(length: number): this;
retain(length: number | Record<string, unknown>, attributes?: AttributeMap | null): this;
push(newOp: Op): this;
chop(): this;
filter(predicate: (op: Op, index: number) => boolean): Op[];
forEach(predicate: (op: Op, index: number) => void): void;
map<T>(predicate: (op: Op, index: number) => T): T[];
partition(predicate: (op: Op) => boolean): [Op[], Op[]];
reduce<T>(predicate: (accum: T, curr: Op, index: number) => T, initialValue: T): T;
changeLength(): number;
length(): number;
slice(start?: number, end?: number): Delta;
compose(other: Delta): Delta;
concat(other: Delta): Delta;
diff(other: Delta, cursor?: number | diff.CursorInfo): Delta;
eachLine(predicate: (line: Delta, attributes: AttributeMap, index: number) => boolean | void, newline?: string): void;
invert(base: Delta): Delta;
transform(index: number, priority?: boolean): number;
transform(other: Delta, priority?: boolean): Delta;
transformPosition(index: number, priority?: boolean): number;
}
export default Delta;
export { Op, OpIterator, AttributeMap };

478
public/assets/quill-delta/dist/Delta.js vendored Normal file
View File

@@ -0,0 +1,478 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AttributeMap = exports.OpIterator = exports.Op = void 0;
const diff = require("fast-diff");
const cloneDeep = require("lodash.clonedeep");
const isEqual = require("lodash.isequal");
const AttributeMap_1 = require("./AttributeMap");
exports.AttributeMap = AttributeMap_1.default;
const Op_1 = require("./Op");
exports.Op = Op_1.default;
const OpIterator_1 = require("./OpIterator");
exports.OpIterator = OpIterator_1.default;
const NULL_CHARACTER = String.fromCharCode(0); // Placeholder char for embed in diff()
const getEmbedTypeAndData = (a, b) => {
if (typeof a !== 'object' || a === null) {
throw new Error(`cannot retain a ${typeof a}`);
}
if (typeof b !== 'object' || b === null) {
throw new Error(`cannot retain a ${typeof b}`);
}
const embedType = Object.keys(a)[0];
if (!embedType || embedType !== Object.keys(b)[0]) {
throw new Error(`embed types not matched: ${embedType} != ${Object.keys(b)[0]}`);
}
return [embedType, a[embedType], b[embedType]];
};
class Delta {
constructor(ops) {
// Assume we are given a well formed ops
if (Array.isArray(ops)) {
this.ops = ops;
}
else if (ops != null && Array.isArray(ops.ops)) {
this.ops = ops.ops;
}
else {
this.ops = [];
}
}
static registerEmbed(embedType, handler) {
this.handlers[embedType] = handler;
}
static unregisterEmbed(embedType) {
delete this.handlers[embedType];
}
static getHandler(embedType) {
const handler = this.handlers[embedType];
if (!handler) {
throw new Error(`no handlers for embed type "${embedType}"`);
}
return handler;
}
insert(arg, attributes) {
const newOp = {};
if (typeof arg === 'string' && arg.length === 0) {
return this;
}
newOp.insert = arg;
if (attributes != null &&
typeof attributes === 'object' &&
Object.keys(attributes).length > 0) {
newOp.attributes = attributes;
}
return this.push(newOp);
}
delete(length) {
if (length <= 0) {
return this;
}
return this.push({ delete: length });
}
retain(length, attributes) {
if (typeof length === 'number' && length <= 0) {
return this;
}
const newOp = { retain: length };
if (attributes != null &&
typeof attributes === 'object' &&
Object.keys(attributes).length > 0) {
newOp.attributes = attributes;
}
return this.push(newOp);
}
push(newOp) {
let index = this.ops.length;
let lastOp = this.ops[index - 1];
newOp = cloneDeep(newOp);
if (typeof lastOp === 'object') {
if (typeof newOp.delete === 'number' &&
typeof lastOp.delete === 'number') {
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 (typeof lastOp.delete === 'number' && newOp.insert != null) {
index -= 1;
lastOp = this.ops[index - 1];
if (typeof lastOp !== 'object') {
this.ops.unshift(newOp);
return this;
}
}
if (isEqual(newOp.attributes, lastOp.attributes)) {
if (typeof newOp.insert === 'string' &&
typeof lastOp.insert === 'string') {
this.ops[index - 1] = { insert: lastOp.insert + newOp.insert };
if (typeof newOp.attributes === 'object') {
this.ops[index - 1].attributes = newOp.attributes;
}
return this;
}
else if (typeof newOp.retain === 'number' &&
typeof lastOp.retain === 'number') {
this.ops[index - 1] = { retain: lastOp.retain + newOp.retain };
if (typeof newOp.attributes === 'object') {
this.ops[index - 1].attributes = newOp.attributes;
}
return this;
}
}
}
if (index === this.ops.length) {
this.ops.push(newOp);
}
else {
this.ops.splice(index, 0, newOp);
}
return this;
}
chop() {
const lastOp = this.ops[this.ops.length - 1];
if (lastOp && typeof lastOp.retain === 'number' && !lastOp.attributes) {
this.ops.pop();
}
return this;
}
filter(predicate) {
return this.ops.filter(predicate);
}
forEach(predicate) {
this.ops.forEach(predicate);
}
map(predicate) {
return this.ops.map(predicate);
}
partition(predicate) {
const passed = [];
const failed = [];
this.forEach((op) => {
const target = predicate(op) ? passed : failed;
target.push(op);
});
return [passed, failed];
}
reduce(predicate, initialValue) {
return this.ops.reduce(predicate, initialValue);
}
changeLength() {
return this.reduce((length, elem) => {
if (elem.insert) {
return length + Op_1.default.length(elem);
}
else if (elem.delete) {
return length - elem.delete;
}
return length;
}, 0);
}
length() {
return this.reduce((length, elem) => {
return length + Op_1.default.length(elem);
}, 0);
}
slice(start = 0, end = Infinity) {
const ops = [];
const iter = new OpIterator_1.default(this.ops);
let index = 0;
while (index < end && iter.hasNext()) {
let nextOp;
if (index < start) {
nextOp = iter.next(start - index);
}
else {
nextOp = iter.next(end - index);
ops.push(nextOp);
}
index += Op_1.default.length(nextOp);
}
return new Delta(ops);
}
compose(other) {
const thisIter = new OpIterator_1.default(this.ops);
const otherIter = new OpIterator_1.default(other.ops);
const ops = [];
const firstOther = otherIter.peek();
if (firstOther != null &&
typeof firstOther.retain === 'number' &&
firstOther.attributes == null) {
let firstLeft = firstOther.retain;
while (thisIter.peekType() === 'insert' &&
thisIter.peekLength() <= firstLeft) {
firstLeft -= thisIter.peekLength();
ops.push(thisIter.next());
}
if (firstOther.retain - firstLeft > 0) {
otherIter.next(firstOther.retain - firstLeft);
}
}
const delta = new Delta(ops);
while (thisIter.hasNext() || otherIter.hasNext()) {
if (otherIter.peekType() === 'insert') {
delta.push(otherIter.next());
}
else if (thisIter.peekType() === 'delete') {
delta.push(thisIter.next());
}
else {
const length = Math.min(thisIter.peekLength(), otherIter.peekLength());
const thisOp = thisIter.next(length);
const otherOp = otherIter.next(length);
if (otherOp.retain) {
const newOp = {};
if (typeof thisOp.retain === 'number') {
newOp.retain =
typeof otherOp.retain === 'number' ? length : otherOp.retain;
}
else {
if (typeof otherOp.retain === 'number') {
if (thisOp.retain == null) {
newOp.insert = thisOp.insert;
}
else {
newOp.retain = thisOp.retain;
}
}
else {
const action = thisOp.retain == null ? 'insert' : 'retain';
const [embedType, thisData, otherData] = getEmbedTypeAndData(thisOp[action], otherOp.retain);
const handler = Delta.getHandler(embedType);
newOp[action] = {
[embedType]: handler.compose(thisData, otherData, action === 'retain'),
};
}
}
// Preserve null when composing with a retain, otherwise remove it for inserts
const attributes = AttributeMap_1.default.compose(thisOp.attributes, otherOp.attributes, typeof thisOp.retain === 'number');
if (attributes) {
newOp.attributes = attributes;
}
delta.push(newOp);
// Optimization if rest of other is just retain
if (!otherIter.hasNext() &&
isEqual(delta.ops[delta.ops.length - 1], newOp)) {
const rest = new Delta(thisIter.rest());
return delta.concat(rest).chop();
}
// Other op should be delete, we could be an insert or retain
// Insert + delete cancels out
}
else if (typeof otherOp.delete === 'number' &&
(typeof thisOp.retain === 'number' ||
(typeof thisOp.retain === 'object' && thisOp.retain !== null))) {
delta.push(otherOp);
}
}
}
return delta.chop();
}
concat(other) {
const delta = new Delta(this.ops.slice());
if (other.ops.length > 0) {
delta.push(other.ops[0]);
delta.ops = delta.ops.concat(other.ops.slice(1));
}
return delta;
}
diff(other, cursor) {
if (this.ops === other.ops) {
return new Delta();
}
const strings = [this, other].map((delta) => {
return delta
.map((op) => {
if (op.insert != null) {
return typeof op.insert === 'string' ? op.insert : NULL_CHARACTER;
}
const prep = delta === other ? 'on' : 'with';
throw new Error('diff() called ' + prep + ' non-document');
})
.join('');
});
const retDelta = new Delta();
const diffResult = diff(strings[0], strings[1], cursor, true);
const thisIter = new OpIterator_1.default(this.ops);
const otherIter = new OpIterator_1.default(other.ops);
diffResult.forEach((component) => {
let length = component[1].length;
while (length > 0) {
let opLength = 0;
switch (component[0]) {
case diff.INSERT:
opLength = Math.min(otherIter.peekLength(), length);
retDelta.push(otherIter.next(opLength));
break;
case diff.DELETE:
opLength = Math.min(length, thisIter.peekLength());
thisIter.next(opLength);
retDelta.delete(opLength);
break;
case diff.EQUAL:
opLength = Math.min(thisIter.peekLength(), otherIter.peekLength(), length);
const thisOp = thisIter.next(opLength);
const otherOp = otherIter.next(opLength);
if (isEqual(thisOp.insert, otherOp.insert)) {
retDelta.retain(opLength, AttributeMap_1.default.diff(thisOp.attributes, otherOp.attributes));
}
else {
retDelta.push(otherOp).delete(opLength);
}
break;
}
length -= opLength;
}
});
return retDelta.chop();
}
eachLine(predicate, newline = '\n') {
const iter = new OpIterator_1.default(this.ops);
let line = new Delta();
let i = 0;
while (iter.hasNext()) {
if (iter.peekType() !== 'insert') {
return;
}
const thisOp = iter.peek();
const start = Op_1.default.length(thisOp) - iter.peekLength();
const index = typeof thisOp.insert === 'string'
? thisOp.insert.indexOf(newline, start) - start
: -1;
if (index < 0) {
line.push(iter.next());
}
else if (index > 0) {
line.push(iter.next(index));
}
else {
if (predicate(line, iter.next(1).attributes || {}, i) === false) {
return;
}
i += 1;
line = new Delta();
}
}
if (line.length() > 0) {
predicate(line, {}, i);
}
}
invert(base) {
const inverted = new Delta();
this.reduce((baseIndex, op) => {
if (op.insert) {
inverted.delete(Op_1.default.length(op));
}
else if (typeof op.retain === 'number' && op.attributes == null) {
inverted.retain(op.retain);
return baseIndex + op.retain;
}
else if (op.delete || typeof op.retain === 'number') {
const length = (op.delete || op.retain);
const slice = base.slice(baseIndex, baseIndex + length);
slice.forEach((baseOp) => {
if (op.delete) {
inverted.push(baseOp);
}
else if (op.retain && op.attributes) {
inverted.retain(Op_1.default.length(baseOp), AttributeMap_1.default.invert(op.attributes, baseOp.attributes));
}
});
return baseIndex + length;
}
else if (typeof op.retain === 'object' && op.retain !== null) {
const slice = base.slice(baseIndex, baseIndex + 1);
const baseOp = new OpIterator_1.default(slice.ops).next();
const [embedType, opData, baseOpData] = getEmbedTypeAndData(op.retain, baseOp.insert);
const handler = Delta.getHandler(embedType);
inverted.retain({ [embedType]: handler.invert(opData, baseOpData) }, AttributeMap_1.default.invert(op.attributes, baseOp.attributes));
return baseIndex + 1;
}
return baseIndex;
}, 0);
return inverted.chop();
}
transform(arg, priority = false) {
priority = !!priority;
if (typeof arg === 'number') {
return this.transformPosition(arg, priority);
}
const other = arg;
const thisIter = new OpIterator_1.default(this.ops);
const otherIter = new OpIterator_1.default(other.ops);
const delta = new Delta();
while (thisIter.hasNext() || otherIter.hasNext()) {
if (thisIter.peekType() === 'insert' &&
(priority || otherIter.peekType() !== 'insert')) {
delta.retain(Op_1.default.length(thisIter.next()));
}
else if (otherIter.peekType() === 'insert') {
delta.push(otherIter.next());
}
else {
const length = Math.min(thisIter.peekLength(), otherIter.peekLength());
const thisOp = thisIter.next(length);
const 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 {
const thisData = thisOp.retain;
const otherData = otherOp.retain;
let transformedData = typeof otherData === 'object' && otherData !== null
? otherData
: length;
if (typeof thisData === 'object' &&
thisData !== null &&
typeof otherData === 'object' &&
otherData !== null) {
const embedType = Object.keys(thisData)[0];
if (embedType === Object.keys(otherData)[0]) {
const handler = Delta.getHandler(embedType);
if (handler) {
transformedData = {
[embedType]: handler.transform(thisData[embedType], otherData[embedType], priority),
};
}
}
}
// We retain either their retain or insert
delta.retain(transformedData, AttributeMap_1.default.transform(thisOp.attributes, otherOp.attributes, priority));
}
}
}
return delta.chop();
}
transformPosition(index, priority = false) {
priority = !!priority;
const thisIter = new OpIterator_1.default(this.ops);
let offset = 0;
while (thisIter.hasNext() && offset <= index) {
const length = thisIter.peekLength();
const 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;
}
}
Delta.Op = Op_1.default;
Delta.OpIterator = OpIterator_1.default;
Delta.AttributeMap = AttributeMap_1.default;
Delta.handlers = {};
exports.default = Delta;
if (typeof module === 'object') {
module.exports = Delta;
module.exports.default = Delta;
}
//# sourceMappingURL=Delta.js.map

File diff suppressed because one or more lines are too long

11
public/assets/quill-delta/dist/Op.d.ts vendored Normal file
View File

@@ -0,0 +1,11 @@
import AttributeMap from './AttributeMap';
interface Op {
insert?: string | Record<string, unknown>;
delete?: number;
retain?: number | Record<string, unknown>;
attributes?: AttributeMap;
}
declare namespace Op {
function length(op: Op): number;
}
export default Op;

22
public/assets/quill-delta/dist/Op.js vendored Normal file
View File

@@ -0,0 +1,22 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var Op;
(function (Op) {
function length(op) {
if (typeof op.delete === 'number') {
return op.delete;
}
else if (typeof op.retain === 'number') {
return op.retain;
}
else if (typeof op.retain === 'object' && op.retain !== null) {
return 1;
}
else {
return typeof op.insert === 'string' ? op.insert.length : 1;
}
}
Op.length = length;
})(Op || (Op = {}));
exports.default = Op;
//# sourceMappingURL=Op.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"Op.js","sourceRoot":"","sources":["../src/Op.ts"],"names":[],"mappings":";;AAWA,IAAU,EAAE,CAYX;AAZD,WAAU,EAAE;IACV,SAAgB,MAAM,CAAC,EAAM;QAC3B,IAAI,OAAO,EAAE,CAAC,MAAM,KAAK,QAAQ,EAAE;YACjC,OAAO,EAAE,CAAC,MAAM,CAAC;SAClB;aAAM,IAAI,OAAO,EAAE,CAAC,MAAM,KAAK,QAAQ,EAAE;YACxC,OAAO,EAAE,CAAC,MAAM,CAAC;SAClB;aAAM,IAAI,OAAO,EAAE,CAAC,MAAM,KAAK,QAAQ,IAAI,EAAE,CAAC,MAAM,KAAK,IAAI,EAAE;YAC9D,OAAO,CAAC,CAAC;SACV;aAAM;YACL,OAAO,OAAO,EAAE,CAAC,MAAM,KAAK,QAAQ,CAAC,CAAC,CAAC,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;SAC7D;IACH,CAAC;IAVe,SAAM,SAUrB,CAAA;AACH,CAAC,EAZS,EAAE,KAAF,EAAE,QAYX;AAED,kBAAe,EAAE,CAAC"}

View File

@@ -0,0 +1,13 @@
import Op from './Op';
export default class Iterator {
ops: Op[];
index: number;
offset: number;
constructor(ops: Op[]);
hasNext(): boolean;
next(length?: number): Op;
peek(): Op;
peekLength(): number;
peekType(): string;
rest(): Op[];
}

View File

@@ -0,0 +1,106 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const Op_1 = require("./Op");
class Iterator {
constructor(ops) {
this.ops = ops;
this.index = 0;
this.offset = 0;
}
hasNext() {
return this.peekLength() < Infinity;
}
next(length) {
if (!length) {
length = Infinity;
}
const nextOp = this.ops[this.index];
if (nextOp) {
const offset = this.offset;
const opLength = Op_1.default.length(nextOp);
if (length >= opLength - offset) {
length = opLength - offset;
this.index += 1;
this.offset = 0;
}
else {
this.offset += length;
}
if (typeof nextOp.delete === 'number') {
return { delete: length };
}
else {
const retOp = {};
if (nextOp.attributes) {
retOp.attributes = nextOp.attributes;
}
if (typeof nextOp.retain === 'number') {
retOp.retain = length;
}
else if (typeof nextOp.retain === 'object' &&
nextOp.retain !== null) {
// offset should === 0, length should === 1
retOp.retain = nextOp.retain;
}
else if (typeof nextOp.insert === 'string') {
retOp.insert = nextOp.insert.substr(offset, length);
}
else {
// offset should === 0, length should === 1
retOp.insert = nextOp.insert;
}
return retOp;
}
}
else {
return { retain: Infinity };
}
}
peek() {
return this.ops[this.index];
}
peekLength() {
if (this.ops[this.index]) {
// Should never return 0 if our index is being managed correctly
return Op_1.default.length(this.ops[this.index]) - this.offset;
}
else {
return Infinity;
}
}
peekType() {
const op = this.ops[this.index];
if (op) {
if (typeof op.delete === 'number') {
return 'delete';
}
else if (typeof op.retain === 'number' ||
(typeof op.retain === 'object' && op.retain !== null)) {
return 'retain';
}
else {
return 'insert';
}
}
return 'retain';
}
rest() {
if (!this.hasNext()) {
return [];
}
else if (this.offset === 0) {
return this.ops.slice(this.index);
}
else {
const offset = this.offset;
const index = this.index;
const next = this.next();
const rest = this.ops.slice(this.index);
this.offset = offset;
this.index = index;
return [next].concat(rest);
}
}
}
exports.default = Iterator;
//# sourceMappingURL=OpIterator.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"OpIterator.js","sourceRoot":"","sources":["../src/OpIterator.ts"],"names":[],"mappings":";;AAAA,6BAAsB;AAEtB,MAAqB,QAAQ;IAK3B,YAAY,GAAS;QACnB,IAAI,CAAC,GAAG,GAAG,GAAG,CAAC;QACf,IAAI,CAAC,KAAK,GAAG,CAAC,CAAC;QACf,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC;IAClB,CAAC;IAED,OAAO;QACL,OAAO,IAAI,CAAC,UAAU,EAAE,GAAG,QAAQ,CAAC;IACtC,CAAC;IAED,IAAI,CAAC,MAAe;QAClB,IAAI,CAAC,MAAM,EAAE;YACX,MAAM,GAAG,QAAQ,CAAC;SACnB;QACD,MAAM,MAAM,GAAG,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACpC,IAAI,MAAM,EAAE;YACV,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC;YAC3B,MAAM,QAAQ,GAAG,YAAE,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;YACnC,IAAI,MAAM,IAAI,QAAQ,GAAG,MAAM,EAAE;gBAC/B,MAAM,GAAG,QAAQ,GAAG,MAAM,CAAC;gBAC3B,IAAI,CAAC,KAAK,IAAI,CAAC,CAAC;gBAChB,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC;aACjB;iBAAM;gBACL,IAAI,CAAC,MAAM,IAAI,MAAM,CAAC;aACvB;YACD,IAAI,OAAO,MAAM,CAAC,MAAM,KAAK,QAAQ,EAAE;gBACrC,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC;aAC3B;iBAAM;gBACL,MAAM,KAAK,GAAO,EAAE,CAAC;gBACrB,IAAI,MAAM,CAAC,UAAU,EAAE;oBACrB,KAAK,CAAC,UAAU,GAAG,MAAM,CAAC,UAAU,CAAC;iBACtC;gBACD,IAAI,OAAO,MAAM,CAAC,MAAM,KAAK,QAAQ,EAAE;oBACrC,KAAK,CAAC,MAAM,GAAG,MAAM,CAAC;iBACvB;qBAAM,IACL,OAAO,MAAM,CAAC,MAAM,KAAK,QAAQ;oBACjC,MAAM,CAAC,MAAM,KAAK,IAAI,EACtB;oBACA,2CAA2C;oBAC3C,KAAK,CAAC,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC;iBAC9B;qBAAM,IAAI,OAAO,MAAM,CAAC,MAAM,KAAK,QAAQ,EAAE;oBAC5C,KAAK,CAAC,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;iBACrD;qBAAM;oBACL,2CAA2C;oBAC3C,KAAK,CAAC,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC;iBAC9B;gBACD,OAAO,KAAK,CAAC;aACd;SACF;aAAM;YACL,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC;SAC7B;IACH,CAAC;IAED,IAAI;QACF,OAAO,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAC9B,CAAC;IAED,UAAU;QACR,IAAI,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE;YACxB,gEAAgE;YAChE,OAAO,YAAE,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,GAAG,IAAI,CAAC,MAAM,CAAC;SACtD;aAAM;YACL,OAAO,QAAQ,CAAC;SACjB;IACH,CAAC;IAED,QAAQ;QACN,MAAM,EAAE,GAAG,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QAChC,IAAI,EAAE,EAAE;YACN,IAAI,OAAO,EAAE,CAAC,MAAM,KAAK,QAAQ,EAAE;gBACjC,OAAO,QAAQ,CAAC;aACjB;iBAAM,IACL,OAAO,EAAE,CAAC,MAAM,KAAK,QAAQ;gBAC7B,CAAC,OAAO,EAAE,CAAC,MAAM,KAAK,QAAQ,IAAI,EAAE,CAAC,MAAM,KAAK,IAAI,CAAC,EACrD;gBACA,OAAO,QAAQ,CAAC;aACjB;iBAAM;gBACL,OAAO,QAAQ,CAAC;aACjB;SACF;QACD,OAAO,QAAQ,CAAC;IAClB,CAAC;IAED,IAAI;QACF,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,EAAE;YACnB,OAAO,EAAE,CAAC;SACX;aAAM,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,EAAE;YAC5B,OAAO,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;SACnC;aAAM;YACL,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC;YAC3B,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC;YACzB,MAAM,IAAI,GAAG,IAAI,CAAC,IAAI,EAAE,CAAC;YACzB,MAAM,IAAI,GAAG,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;YACxC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;YACrB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;YACnB,OAAO,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;SAC5B;IACH,CAAC;CACF;AAvGD,2BAuGC"}

View File

@@ -0,0 +1,77 @@
{
"name": "quill-delta",
"version": "5.1.0",
"description": "Format for representing rich text documents and changes.",
"author": "Jason Chen <jhchen7@gmail.com>",
"homepage": "https://github.com/quilljs/delta",
"main": "dist/Delta.js",
"dependencies": {
"fast-diff": "^1.3.0",
"lodash.clonedeep": "^4.5.0",
"lodash.isequal": "^4.5.0"
},
"devDependencies": {
"@types/jasmine": "^3.10.3",
"@types/lodash.clonedeep": "^4.5.6",
"@types/lodash.isequal": "^4.5.5",
"@types/node": "^17.0.21",
"@typescript-eslint/eslint-plugin": "^5.14.0",
"@typescript-eslint/parser": "^5.14.0",
"eslint": "^8.10.0",
"eslint-config-prettier": "^8.5.0",
"eslint-plugin-prettier": "^4.0.0",
"jasmine": "^4.0.2",
"nyc": "^15.1.0",
"prettier": "^2.5.1",
"ts-node": "^10.7.0",
"typescript": "^4.6.2"
},
"engines": {
"node": ">= 12.0.0"
},
"files": [
"tsconfig.json",
"dist",
"src"
],
"license": "MIT",
"scripts": {
"build": "tsc",
"prepare": "npm run build",
"lint": "eslint 'src/**/*.ts'",
"test": "jasmine --config=jasmine.json",
"test:coverage": "nyc npm run test",
"test:coverage:report": "nyc report --reporter=lcov"
},
"eslintConfig": {
"parser": "@typescript-eslint/parser",
"extends": [
"plugin:@typescript-eslint/recommended",
"plugin:prettier/recommended"
],
"parserOptions": {
"ecmaVersion": 6,
"sourceType": "module"
},
"rules": {
"@typescript-eslint/no-namespace": "off"
}
},
"prettier": {
"singleQuote": true,
"trailingComma": "all"
},
"repository": {
"type": "git",
"url": "https://github.com/quilljs/delta"
},
"bugs": {
"url": "https://github.com/quilljs/delta/issues"
},
"keywords": [
"rich text",
"ot",
"operational transform",
"delta"
]
}

View File

@@ -0,0 +1,101 @@
import cloneDeep = require('lodash.clonedeep');
import isEqual = require('lodash.isequal');
interface AttributeMap {
[key: string]: unknown;
}
namespace AttributeMap {
export function compose(
a: AttributeMap = {},
b: AttributeMap = {},
keepNull = false,
): AttributeMap | undefined {
if (typeof a !== 'object') {
a = {};
}
if (typeof b !== 'object') {
b = {};
}
let attributes = cloneDeep(b);
if (!keepNull) {
attributes = Object.keys(attributes).reduce<AttributeMap>((copy, key) => {
if (attributes[key] != null) {
copy[key] = attributes[key];
}
return copy;
}, {});
}
for (const key in a) {
if (a[key] !== undefined && b[key] === undefined) {
attributes[key] = a[key];
}
}
return Object.keys(attributes).length > 0 ? attributes : undefined;
}
export function diff(
a: AttributeMap = {},
b: AttributeMap = {},
): AttributeMap | undefined {
if (typeof a !== 'object') {
a = {};
}
if (typeof b !== 'object') {
b = {};
}
const attributes = Object.keys(a)
.concat(Object.keys(b))
.reduce<AttributeMap>((attrs, key) => {
if (!isEqual(a[key], b[key])) {
attrs[key] = b[key] === undefined ? null : b[key];
}
return attrs;
}, {});
return Object.keys(attributes).length > 0 ? attributes : undefined;
}
export function invert(
attr: AttributeMap = {},
base: AttributeMap = {},
): AttributeMap {
attr = attr || {};
const baseInverted = Object.keys(base).reduce<AttributeMap>((memo, key) => {
if (base[key] !== attr[key] && attr[key] !== undefined) {
memo[key] = base[key];
}
return memo;
}, {});
return Object.keys(attr).reduce<AttributeMap>((memo, key) => {
if (attr[key] !== base[key] && base[key] === undefined) {
memo[key] = null;
}
return memo;
}, baseInverted);
}
export function transform(
a: AttributeMap | undefined,
b: AttributeMap | undefined,
priority = false,
): AttributeMap | undefined {
if (typeof a !== 'object') {
return b;
}
if (typeof b !== 'object') {
return undefined;
}
if (!priority) {
return b; // b simply overwrites us without priority
}
const attributes = Object.keys(b).reduce<AttributeMap>((attrs, key) => {
if (a[key] === undefined) {
attrs[key] = b[key]; // null is a valid value
}
return attrs;
}, {});
return Object.keys(attributes).length > 0 ? attributes : undefined;
}
}
export default AttributeMap;

View File

@@ -0,0 +1,573 @@
import * as diff from 'fast-diff';
import cloneDeep = require('lodash.clonedeep');
import isEqual = require('lodash.isequal');
import AttributeMap from './AttributeMap';
import Op from './Op';
import OpIterator from './OpIterator';
const NULL_CHARACTER = String.fromCharCode(0); // Placeholder char for embed in diff()
interface EmbedHandler<T> {
compose(a: T, b: T, keepNull: boolean): T;
invert(a: T, b: T): T;
transform(a: T, b: T, priority: boolean): T;
}
const getEmbedTypeAndData = (
a: Op['insert'] | Op['retain'],
b: Op['insert'],
): [string, unknown, unknown] => {
if (typeof a !== 'object' || a === null) {
throw new Error(`cannot retain a ${typeof a}`);
}
if (typeof b !== 'object' || b === null) {
throw new Error(`cannot retain a ${typeof b}`);
}
const embedType = Object.keys(a)[0];
if (!embedType || embedType !== Object.keys(b)[0]) {
throw new Error(
`embed types not matched: ${embedType} != ${Object.keys(b)[0]}`,
);
}
return [embedType, a[embedType], b[embedType]];
};
class Delta {
static Op = Op;
static OpIterator = OpIterator;
static AttributeMap = AttributeMap;
private static handlers: { [embedType: string]: EmbedHandler<unknown> } = {};
static registerEmbed<T>(embedType: string, handler: EmbedHandler<T>): void {
this.handlers[embedType] = handler;
}
static unregisterEmbed(embedType: string): void {
delete this.handlers[embedType];
}
private static getHandler(embedType: string): EmbedHandler<unknown> {
const handler = this.handlers[embedType];
if (!handler) {
throw new Error(`no handlers for embed type "${embedType}"`);
}
return handler;
}
ops: Op[];
constructor(ops?: Op[] | { ops: Op[] }) {
// Assume we are given a well formed ops
if (Array.isArray(ops)) {
this.ops = ops;
} else if (ops != null && Array.isArray(ops.ops)) {
this.ops = ops.ops;
} else {
this.ops = [];
}
}
insert(
arg: string | Record<string, unknown>,
attributes?: AttributeMap | null,
): this {
const newOp: Op = {};
if (typeof arg === 'string' && arg.length === 0) {
return this;
}
newOp.insert = arg;
if (
attributes != null &&
typeof attributes === 'object' &&
Object.keys(attributes).length > 0
) {
newOp.attributes = attributes;
}
return this.push(newOp);
}
delete(length: number): this {
if (length <= 0) {
return this;
}
return this.push({ delete: length });
}
retain(
length: number | Record<string, unknown>,
attributes?: AttributeMap | null,
): this {
if (typeof length === 'number' && length <= 0) {
return this;
}
const newOp: Op = { retain: length };
if (
attributes != null &&
typeof attributes === 'object' &&
Object.keys(attributes).length > 0
) {
newOp.attributes = attributes;
}
return this.push(newOp);
}
push(newOp: Op): this {
let index = this.ops.length;
let lastOp = this.ops[index - 1];
newOp = cloneDeep(newOp);
if (typeof lastOp === 'object') {
if (
typeof newOp.delete === 'number' &&
typeof lastOp.delete === 'number'
) {
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 (typeof lastOp.delete === 'number' && newOp.insert != null) {
index -= 1;
lastOp = this.ops[index - 1];
if (typeof lastOp !== 'object') {
this.ops.unshift(newOp);
return this;
}
}
if (isEqual(newOp.attributes, lastOp.attributes)) {
if (
typeof newOp.insert === 'string' &&
typeof lastOp.insert === 'string'
) {
this.ops[index - 1] = { insert: lastOp.insert + newOp.insert };
if (typeof newOp.attributes === 'object') {
this.ops[index - 1].attributes = newOp.attributes;
}
return this;
} else if (
typeof newOp.retain === 'number' &&
typeof lastOp.retain === 'number'
) {
this.ops[index - 1] = { retain: lastOp.retain + newOp.retain };
if (typeof newOp.attributes === 'object') {
this.ops[index - 1].attributes = newOp.attributes;
}
return this;
}
}
}
if (index === this.ops.length) {
this.ops.push(newOp);
} else {
this.ops.splice(index, 0, newOp);
}
return this;
}
chop(): this {
const lastOp = this.ops[this.ops.length - 1];
if (lastOp && typeof lastOp.retain === 'number' && !lastOp.attributes) {
this.ops.pop();
}
return this;
}
filter(predicate: (op: Op, index: number) => boolean): Op[] {
return this.ops.filter(predicate);
}
forEach(predicate: (op: Op, index: number) => void): void {
this.ops.forEach(predicate);
}
map<T>(predicate: (op: Op, index: number) => T): T[] {
return this.ops.map(predicate);
}
partition(predicate: (op: Op) => boolean): [Op[], Op[]] {
const passed: Op[] = [];
const failed: Op[] = [];
this.forEach((op) => {
const target = predicate(op) ? passed : failed;
target.push(op);
});
return [passed, failed];
}
reduce<T>(
predicate: (accum: T, curr: Op, index: number) => T,
initialValue: T,
): T {
return this.ops.reduce(predicate, initialValue);
}
changeLength(): number {
return this.reduce((length, elem) => {
if (elem.insert) {
return length + Op.length(elem);
} else if (elem.delete) {
return length - elem.delete;
}
return length;
}, 0);
}
length(): number {
return this.reduce((length, elem) => {
return length + Op.length(elem);
}, 0);
}
slice(start = 0, end = Infinity): Delta {
const ops = [];
const iter = new OpIterator(this.ops);
let index = 0;
while (index < end && iter.hasNext()) {
let nextOp;
if (index < start) {
nextOp = iter.next(start - index);
} else {
nextOp = iter.next(end - index);
ops.push(nextOp);
}
index += Op.length(nextOp);
}
return new Delta(ops);
}
compose(other: Delta): Delta {
const thisIter = new OpIterator(this.ops);
const otherIter = new OpIterator(other.ops);
const ops = [];
const firstOther = otherIter.peek();
if (
firstOther != null &&
typeof firstOther.retain === 'number' &&
firstOther.attributes == null
) {
let firstLeft = firstOther.retain;
while (
thisIter.peekType() === 'insert' &&
thisIter.peekLength() <= firstLeft
) {
firstLeft -= thisIter.peekLength();
ops.push(thisIter.next());
}
if (firstOther.retain - firstLeft > 0) {
otherIter.next(firstOther.retain - firstLeft);
}
}
const delta = new Delta(ops);
while (thisIter.hasNext() || otherIter.hasNext()) {
if (otherIter.peekType() === 'insert') {
delta.push(otherIter.next());
} else if (thisIter.peekType() === 'delete') {
delta.push(thisIter.next());
} else {
const length = Math.min(thisIter.peekLength(), otherIter.peekLength());
const thisOp = thisIter.next(length);
const otherOp = otherIter.next(length);
if (otherOp.retain) {
const newOp: Op = {};
if (typeof thisOp.retain === 'number') {
newOp.retain =
typeof otherOp.retain === 'number' ? length : otherOp.retain;
} else {
if (typeof otherOp.retain === 'number') {
if (thisOp.retain == null) {
newOp.insert = thisOp.insert;
} else {
newOp.retain = thisOp.retain;
}
} else {
const action = thisOp.retain == null ? 'insert' : 'retain';
const [embedType, thisData, otherData] = getEmbedTypeAndData(
thisOp[action],
otherOp.retain,
);
const handler = Delta.getHandler(embedType);
newOp[action] = {
[embedType]: handler.compose(
thisData,
otherData,
action === 'retain',
),
};
}
}
// Preserve null when composing with a retain, otherwise remove it for inserts
const attributes = AttributeMap.compose(
thisOp.attributes,
otherOp.attributes,
typeof thisOp.retain === 'number',
);
if (attributes) {
newOp.attributes = attributes;
}
delta.push(newOp);
// Optimization if rest of other is just retain
if (
!otherIter.hasNext() &&
isEqual(delta.ops[delta.ops.length - 1], newOp)
) {
const rest = new Delta(thisIter.rest());
return delta.concat(rest).chop();
}
// Other op should be delete, we could be an insert or retain
// Insert + delete cancels out
} else if (
typeof otherOp.delete === 'number' &&
(typeof thisOp.retain === 'number' ||
(typeof thisOp.retain === 'object' && thisOp.retain !== null))
) {
delta.push(otherOp);
}
}
}
return delta.chop();
}
concat(other: Delta): Delta {
const delta = new Delta(this.ops.slice());
if (other.ops.length > 0) {
delta.push(other.ops[0]);
delta.ops = delta.ops.concat(other.ops.slice(1));
}
return delta;
}
diff(other: Delta, cursor?: number | diff.CursorInfo): Delta {
if (this.ops === other.ops) {
return new Delta();
}
const strings = [this, other].map((delta) => {
return delta
.map((op) => {
if (op.insert != null) {
return typeof op.insert === 'string' ? op.insert : NULL_CHARACTER;
}
const prep = delta === other ? 'on' : 'with';
throw new Error('diff() called ' + prep + ' non-document');
})
.join('');
});
const retDelta = new Delta();
const diffResult = diff(strings[0], strings[1], cursor, true);
const thisIter = new OpIterator(this.ops);
const otherIter = new OpIterator(other.ops);
diffResult.forEach((component: diff.Diff) => {
let length = component[1].length;
while (length > 0) {
let opLength = 0;
switch (component[0]) {
case diff.INSERT:
opLength = Math.min(otherIter.peekLength(), length);
retDelta.push(otherIter.next(opLength));
break;
case diff.DELETE:
opLength = Math.min(length, thisIter.peekLength());
thisIter.next(opLength);
retDelta.delete(opLength);
break;
case diff.EQUAL:
opLength = Math.min(
thisIter.peekLength(),
otherIter.peekLength(),
length,
);
const thisOp = thisIter.next(opLength);
const otherOp = otherIter.next(opLength);
if (isEqual(thisOp.insert, otherOp.insert)) {
retDelta.retain(
opLength,
AttributeMap.diff(thisOp.attributes, otherOp.attributes),
);
} else {
retDelta.push(otherOp).delete(opLength);
}
break;
}
length -= opLength;
}
});
return retDelta.chop();
}
eachLine(
predicate: (
line: Delta,
attributes: AttributeMap,
index: number,
) => boolean | void,
newline = '\n',
): void {
const iter = new OpIterator(this.ops);
let line = new Delta();
let i = 0;
while (iter.hasNext()) {
if (iter.peekType() !== 'insert') {
return;
}
const thisOp = iter.peek();
const start = Op.length(thisOp) - iter.peekLength();
const index =
typeof thisOp.insert === 'string'
? thisOp.insert.indexOf(newline, start) - start
: -1;
if (index < 0) {
line.push(iter.next());
} else if (index > 0) {
line.push(iter.next(index));
} else {
if (predicate(line, iter.next(1).attributes || {}, i) === false) {
return;
}
i += 1;
line = new Delta();
}
}
if (line.length() > 0) {
predicate(line, {}, i);
}
}
invert(base: Delta): Delta {
const inverted = new Delta();
this.reduce((baseIndex, op) => {
if (op.insert) {
inverted.delete(Op.length(op));
} else if (typeof op.retain === 'number' && op.attributes == null) {
inverted.retain(op.retain);
return baseIndex + op.retain;
} else if (op.delete || typeof op.retain === 'number') {
const length = (op.delete || op.retain) as number;
const slice = base.slice(baseIndex, baseIndex + length);
slice.forEach((baseOp) => {
if (op.delete) {
inverted.push(baseOp);
} else if (op.retain && op.attributes) {
inverted.retain(
Op.length(baseOp),
AttributeMap.invert(op.attributes, baseOp.attributes),
);
}
});
return baseIndex + length;
} else if (typeof op.retain === 'object' && op.retain !== null) {
const slice = base.slice(baseIndex, baseIndex + 1);
const baseOp = new OpIterator(slice.ops).next();
const [embedType, opData, baseOpData] = getEmbedTypeAndData(
op.retain,
baseOp.insert,
);
const handler = Delta.getHandler(embedType);
inverted.retain(
{ [embedType]: handler.invert(opData, baseOpData) },
AttributeMap.invert(op.attributes, baseOp.attributes),
);
return baseIndex + 1;
}
return baseIndex;
}, 0);
return inverted.chop();
}
transform(index: number, priority?: boolean): number;
transform(other: Delta, priority?: boolean): Delta;
transform(arg: number | Delta, priority = false): typeof arg {
priority = !!priority;
if (typeof arg === 'number') {
return this.transformPosition(arg, priority);
}
const other: Delta = arg;
const thisIter = new OpIterator(this.ops);
const otherIter = new OpIterator(other.ops);
const 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 {
const length = Math.min(thisIter.peekLength(), otherIter.peekLength());
const thisOp = thisIter.next(length);
const 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 {
const thisData = thisOp.retain;
const otherData = otherOp.retain;
let transformedData: Op['retain'] =
typeof otherData === 'object' && otherData !== null
? otherData
: length;
if (
typeof thisData === 'object' &&
thisData !== null &&
typeof otherData === 'object' &&
otherData !== null
) {
const embedType = Object.keys(thisData)[0];
if (embedType === Object.keys(otherData)[0]) {
const handler = Delta.getHandler(embedType);
if (handler) {
transformedData = {
[embedType]: handler.transform(
thisData[embedType],
otherData[embedType],
priority,
),
};
}
}
}
// We retain either their retain or insert
delta.retain(
transformedData,
AttributeMap.transform(
thisOp.attributes,
otherOp.attributes,
priority,
),
);
}
}
}
return delta.chop();
}
transformPosition(index: number, priority = false): number {
priority = !!priority;
const thisIter = new OpIterator(this.ops);
let offset = 0;
while (thisIter.hasNext() && offset <= index) {
const length = thisIter.peekLength();
const 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;
}
}
export default Delta;
export { Op, OpIterator, AttributeMap };
if (typeof module === 'object') {
module.exports = Delta;
module.exports.default = Delta;
}

View File

@@ -0,0 +1,26 @@
import AttributeMap from './AttributeMap';
interface Op {
// only one property out of {insert, delete, retain} will be present
insert?: string | Record<string, unknown>;
delete?: number;
retain?: number | Record<string, unknown>;
attributes?: AttributeMap;
}
namespace Op {
export function length(op: Op): number {
if (typeof op.delete === 'number') {
return op.delete;
} else if (typeof op.retain === 'number') {
return op.retain;
} else if (typeof op.retain === 'object' && op.retain !== null) {
return 1;
} else {
return typeof op.insert === 'string' ? op.insert.length : 1;
}
}
}
export default Op;

View File

@@ -0,0 +1,106 @@
import Op from './Op';
export default class Iterator {
ops: Op[];
index: number;
offset: number;
constructor(ops: Op[]) {
this.ops = ops;
this.index = 0;
this.offset = 0;
}
hasNext(): boolean {
return this.peekLength() < Infinity;
}
next(length?: number): Op {
if (!length) {
length = Infinity;
}
const nextOp = this.ops[this.index];
if (nextOp) {
const offset = this.offset;
const opLength = Op.length(nextOp);
if (length >= opLength - offset) {
length = opLength - offset;
this.index += 1;
this.offset = 0;
} else {
this.offset += length;
}
if (typeof nextOp.delete === 'number') {
return { delete: length };
} else {
const retOp: Op = {};
if (nextOp.attributes) {
retOp.attributes = nextOp.attributes;
}
if (typeof nextOp.retain === 'number') {
retOp.retain = length;
} else if (
typeof nextOp.retain === 'object' &&
nextOp.retain !== null
) {
// offset should === 0, length should === 1
retOp.retain = nextOp.retain;
} else if (typeof nextOp.insert === 'string') {
retOp.insert = nextOp.insert.substr(offset, length);
} else {
// offset should === 0, length should === 1
retOp.insert = nextOp.insert;
}
return retOp;
}
} else {
return { retain: Infinity };
}
}
peek(): Op {
return this.ops[this.index];
}
peekLength(): number {
if (this.ops[this.index]) {
// Should never return 0 if our index is being managed correctly
return Op.length(this.ops[this.index]) - this.offset;
} else {
return Infinity;
}
}
peekType(): string {
const op = this.ops[this.index];
if (op) {
if (typeof op.delete === 'number') {
return 'delete';
} else if (
typeof op.retain === 'number' ||
(typeof op.retain === 'object' && op.retain !== null)
) {
return 'retain';
} else {
return 'insert';
}
}
return 'retain';
}
rest(): Op[] {
if (!this.hasNext()) {
return [];
} else if (this.offset === 0) {
return this.ops.slice(this.index);
} else {
const offset = this.offset;
const index = this.index;
const next = this.next();
const rest = this.ops.slice(this.index);
this.offset = offset;
this.index = index;
return [next].concat(rest);
}
}
}

View File

@@ -0,0 +1,15 @@
{
"compilerOptions": {
"declaration": true,
"outDir": "dist/",
"sourceMap": true,
"strict": true,
"target": "ES2015",
"module": "commonjs",
"strictNullChecks": true,
"noErrorTruncation": true,
"noUnusedLocals": true,
"noUnusedParameters": true
},
"include": ["src/**/*.ts"]
}