This commit is contained in:
呈祥
2026-01-06 19:49:07 +08:00
parent 210d948353
commit 68ad8b3726
6 changed files with 233 additions and 571 deletions
+100 -1
View File
@@ -1,7 +1,106 @@
import { useEffect, useLayoutEffect, useRef, useState } from "react";
import "./App.css"; import "./App.css";
import { Client } from "./ot/client";
import { generateOperations } from "./ot/helpers";
import { getDemoServerInstance } from "./ot/server";
function Editor({ name }: { name: string }) {
const clientRef = useRef<Client | null>(null);
const [doc, setDoc] = useState<string>("");
const prevDocRef = useRef<string>("");
const [enableSync, setEnableSync] = useState<boolean>(true);
// 初始化client和文档状态
useLayoutEffect(() => {
if (!clientRef.current) {
clientRef.current = new Client();
clientRef.current.name = name;
const initialDoc = clientRef.current.document || "";
prevDocRef.current = initialDoc;
setDoc(initialDoc);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useEffect(() => {
if (!clientRef.current) return;
// 定期同步client的文档状态到UI
const timer = setInterval(() => {
const currentDoc = clientRef.current!.document || "";
if (currentDoc !== prevDocRef.current) {
setDoc(currentDoc);
prevDocRef.current = currentDoc;
}
}, 100);
return () => clearInterval(timer);
}, []);
const handleChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
if (!clientRef.current) return;
const newValue = e.target.value;
// 使用client当前文档状态作为旧值
const oldValue = clientRef.current.document || "";
if (newValue !== oldValue) {
// 生成操作集合
const operations = generateOperations(oldValue, newValue);
// 按顺序应用操作
operations.forEach((op) => {
clientRef.current!.applyClient(op);
});
}
};
const handleToggleSync = () => {
const newValue = !enableSync;
setEnableSync(newValue);
if (clientRef.current) {
clientRef.current.setEnableSync(newValue);
}
};
return (
<div style={{ border: "1px solid #ccc", padding: 10 }}>
<div
style={{
display: "flex",
justifyContent: "space-between",
alignItems: "center",
marginBottom: 10,
}}
>
<p style={{ margin: 0 }}>Document</p>
<label style={{ display: "flex", alignItems: "center", gap: 8, cursor: "pointer" }}>
<input type="checkbox" checked={enableSync} onChange={handleToggleSync} />
<span></span>
</label>
</div>
<textarea value={doc} onChange={handleChange} rows={5} />
</div>
);
}
function App() { function App() {
return <div>he</div>; const [serverDoc, setServerDoc] = useState<string>("");
useEffect(() => {
const timer = setInterval(() => {
setServerDoc(getDemoServerInstance().document || "");
}, 100);
return () => clearInterval(timer);
}, []);
return (
<div>
<div style={{ border: "1px solid #ccc", padding: 10 }}>
<p>Server Document:</p>
<p>{serverDoc}</p>
</div>
<div style={{ display: "flex", gap: 10, marginTop: 20 }}>
<Editor name="A" />
<Editor name="B" />
</div>
</div>
);
} }
export default App; export default App;
+27 -7
View File
@@ -6,6 +6,7 @@ import { getDemoServerInstance } from "./server";
const server = getDemoServerInstance(); const server = getDemoServerInstance();
export class Client { export class Client {
public name: string = "";
// 当前文档 // 当前文档
public document: string = ""; public document: string = "";
// 当前服务端文档状态 // 当前服务端文档状态
@@ -16,12 +17,15 @@ export class Client {
public outstanding: TextOperation | null = null; public outstanding: TextOperation | null = null;
// 本地缓存的待发送操作队列(包含outstanding // 本地缓存的待发送操作队列(包含outstanding
public buffer: TextOperation[] = []; public buffer: TextOperation[] = [];
// 是否启用同步到服务端
public enableSync: boolean = true;
constructor() { constructor() {
// 模拟连接服务器,获取初始文档状态和修订版本号 // 模拟连接服务器,获取初始文档状态和修订版本号
const { document, revision } = server.connect(this); const { document, revision } = server.connect(this);
this.revision = revision; this.revision = revision;
this.document = document; this.document = document;
this.name = `client-${Math.random().toString(36).substring(2, 15)}`;
} }
// 当用户更改文档时调用此方法 // 当用户更改文档时调用此方法
@@ -33,18 +37,22 @@ export class Client {
// 接收到来自服务器的新操作,可能是另一个客户端的操作,也可能是服务端确认本地操作的响应 // 接收到来自服务器的新操作,可能是另一个客户端的操作,也可能是服务端确认本地操作的响应
applyServer(revision: number, operation: TextOperation): void { applyServer(revision: number, operation: TextOperation): void {
if (revision < 0 || this.revision < revision) { if (revision < 0 || this.revision > revision) {
throw new Error("operation revision not in history"); throw new Error("operation revision not in history");
} }
const isSelfOp = operation.id === this.outstanding?.id;
for (let i = 0; i < this.buffer.length; i++) { for (let i = 0; i < this.buffer.length; i++) {
// TODO: check
// 将buffer中的操作转换为基于服务端文档状态的操作 // 将buffer中的操作转换为基于服务端文档状态的操作
this.buffer[i] = TextOperation.transform(this.buffer[i], this.buffer[i - 1] || operation)[0]; const newOp = TextOperation.transform(this.buffer[i], this.buffer[i - 1] || operation);
newOp.id = this.buffer[i].id;
this.buffer[i] = newOp;
} }
// 本地重新应用buffer中的操作,合并其它客户端的操作到本地 // 本地重新应用buffer中的操作,合并其它客户端的操作到本地
let newDoc = this.syncedDoc; let newDoc = this.syncedDoc;
newDoc = operation.apply(newDoc);
for (let i = 0; i < this.buffer.length; i++) { for (let i = 0; i < this.buffer.length; i++) {
newDoc = this.buffer[i].apply(newDoc); newDoc = this.buffer[i].apply(newDoc);
} }
@@ -55,29 +63,41 @@ export class Client {
this.revision = revision; this.revision = revision;
// 操作来自服务端确认本地操作的响应 // 操作来自服务端确认本地操作的响应
if (operation.id === this.outstanding?.id) { if (isSelfOp) {
this.outstanding = null;
this.serverAck(); this.serverAck();
} }
console.log('mattuy', 'client', this.name, this)
} }
// 服务端已确认收到发送的操作,从buffer中移除该操作,尝试发送下一个 // 服务端已确认收到发送的操作,从buffer中移除该操作,尝试发送下一个
serverAck(): void { serverAck(): void {
this.outstanding = null; this.outstanding = null;
this.buffer.shift();
this.sendOperationIfNeed(); this.sendOperationIfNeed();
} }
// 逐个向服务端发送本地待提交的操作。发送后等待服务端确认,触发serverAck方法后继续发送下一个操作 // 逐个向服务端发送本地待提交的操作。发送后等待服务端确认,触发serverAck方法后继续发送下一个操作
async sendOperationIfNeed() { async sendOperationIfNeed() {
// 如果禁用了同步,则不向服务端发送操作
if (!this.enableSync) {
return;
}
if (this.outstanding || this.buffer.length === 0) { if (this.outstanding || this.buffer.length === 0) {
// 有正在发送的操作,或者没有待提交的操作,no-op // 有正在发送的操作,或者没有待提交的操作,no-op
return; return;
} }
// 向服务端发送本地待提交的操作,这里没有实现操作压缩,我们一个一个发送 // 向服务端发送本地待提交的操作,这里没有实现操作压缩,我们一个一个发送
this.outstanding = this.buffer[0]; this.outstanding = this.buffer.shift()!;
// 模拟向服务端发送操作,实际实现应该通过网络 // 模拟向服务端发送操作,实际实现应该通过网络
server.receiveOperation(this.revision, this.outstanding); server.receiveOperation(this.revision, this.outstanding);
// 应该有超时重发机制,这里没有实现 // 应该有超时重发机制,这里没有实现
} }
// 设置是否启用同步到服务端
setEnableSync(enabled: boolean): void {
this.enableSync = enabled;
// 如果重新启用同步,尝试发送待发送的操作
if (enabled) {
this.sendOperationIfNeed();
}
}
} }
+40
View File
@@ -0,0 +1,40 @@
import { Insert, Delete, SimpleTextOperation } from "./op";
/**
* 根据新旧文档内容生成操作集合
* @param oldDoc 旧文档内容
* @param newDoc 新文档内容
* @returns 操作集合
*/
export function generateOperations(oldDoc: string, newDoc: string): SimpleTextOperation[] {
const operations: SimpleTextOperation[] = [];
// 找到第一个不同的位置
let start = 0;
while (start < oldDoc.length && start < newDoc.length && oldDoc[start] === newDoc[start]) {
start++;
}
// 找到最后一个不同的位置(从末尾开始)
let oldEnd = oldDoc.length;
let newEnd = newDoc.length;
while (oldEnd > start && newEnd > start && oldDoc[oldEnd - 1] === newDoc[newEnd - 1]) {
oldEnd--;
newEnd--;
}
// 计算需要删除的字符数
const deleteCount = oldEnd - start;
if (deleteCount > 0) {
operations.push(new Delete(deleteCount, start));
}
// 计算需要插入的字符串
const insertStr = newDoc.slice(start, newEnd);
if (insertStr.length > 0) {
operations.push(new Insert(insertStr, start));
}
return operations;
}
+55 -47
View File
@@ -1,86 +1,97 @@
// 简单文本操作的实现 // 简单文本操作的实现
import { v4 as uuidv4 } from 'uuid'; import { v4 as uuidv4 } from "uuid";
export abstract class SimpleTextOperation { export abstract class SimpleTextOperation {
id: string = uuidv4(); public id: string = uuidv4();
abstract toString(): string; abstract toString(): string;
abstract equals(other: SimpleTextOperation): boolean; abstract equals(other: SimpleTextOperation): boolean;
abstract apply(doc: string): string; abstract apply(doc: string): string;
static transform(a: SimpleTextOperation, b: SimpleTextOperation): [SimpleTextOperation, SimpleTextOperation] { // 把操作a转换为基于应用操作b后的文档状态的操作,返回操作a'
static transform(a: SimpleTextOperation, b: SimpleTextOperation): SimpleTextOperation {
if (a instanceof Noop || b instanceof Noop) { if (a instanceof Noop || b instanceof Noop) {
return [a, b]; return a;
} }
if (a instanceof Insert && b instanceof Insert) { if (a instanceof Insert && b instanceof Insert) {
if (a.position < b.position || (a.position === b.position && a.str < b.str)) { if (a.position < b.position) {
return [a, new Insert(b.str, b.position + a.str.length)]; // b在a插入的地方之后插入,不转换
return a;
} }
if (a.position > b.position || (a.position === b.position && a.str > b.str)) { // b在a插入的地方之前插入,位置偏移b插入的str长度后插入
return [new Insert(a.str, a.position + b.str.length), b]; return new Insert(a.str, a.position + b.str.length);
}
return [noop, noop];
} }
if (a instanceof Insert && b instanceof Delete) { if (a instanceof Insert && b instanceof Delete) {
if (a.position <= b.position) { if (a.position <= b.position) {
return [a, new Delete(b.count, b.position + a.str.length)]; // b在a插入的地方之后删除,不转换
return a;
} }
if (a.position >= b.position + b.count) { if (a.position >= b.position + b.count) {
return [new Insert(a.str, a.position - b.count), b]; // b在a插入的位置之前删除,并且a插入位置的字符没有被删除
return new Insert(a.str, a.position - b.count);
} }
// 这里,我们必须删除操作 a 插入的字符串。 // b在a插入的位置之前删除,并且a插入位置的字符被删除,在b删除的位置插入a的str
// 这不能保留操作 a 的意图,但这是获得有效转换函数的唯一方法。 return new Insert(a.str, b.position);
return [noop, new Delete(b.count + a.str.length, b.position)];
} }
if (a instanceof Delete && b instanceof Insert) { if (a instanceof Delete && b instanceof Insert) {
if (a.position >= b.position) { if (a.position >= b.position) {
return [new Delete(a.count, a.position + b.str.length), b]; // a在插入位置之后删除,增加删除操作的偏移
return new Delete(a.count, a.position + b.str.length);
} }
if (a.position + a.count <= b.position) { if (a.position + a.count <= b.position) {
return [a, new Insert(b.str, b.position - a.count)]; // a在插入位置之前删除,并且b插入之前的字符没有被删除,不转换
return a;
} }
// 与上面相同的问题。我们必须删除操作 b 中插入的字符串。 // b插入的内容在a删除的范围内,直接把b插入的内容一起删除
return [new Delete(a.count + b.str.length, a.position), noop]; // NOTICE: 这里b插入的内容丢失了,在生产环境应该裂变为前后两个删除操作,这里简化了实现
return new Delete(a.count + b.str.length, a.position);
} }
if (a instanceof Delete && b instanceof Delete) { if (a instanceof Delete && b instanceof Delete) {
// 删除位置相同
if (a.position === b.position) { if (a.position === b.position) {
if (a.count === b.count) { if (a.count <= b.count) {
return [noop, noop]; // b删除得更多,已经把a要删除的删掉了,no-op
} else if (a.count < b.count) { return noop;
return [noop, new Delete(b.count - a.count, b.position)];
} }
return [new Delete(a.count - b.count, a.position), noop]; // b删除得少,a删除得多,删除b没删掉的部分
return new Delete(a.count - b.count, a.position);
} }
if (a.position < b.position) { if (a.position < b.position) {
if (a.position + a.count <= b.position) { if (a.position + a.count <= b.position) {
return [a, new Delete(b.count, b.position - a.count)]; // a在b删除的位置之前删除,并且a删除的结束位置在b删除的开始位置之前,不转换
return a;
} }
if (a.position + a.count >= b.position + b.count) { if (a.position + a.count >= b.position + b.count) {
return [new Delete(a.count - b.count, a.position), noop]; // a删除的范围包含b删除范围,减去b已经删除的长度
return new Delete(a.count - b.count, a.position);
} }
return [ // a删除的范围在b删除的范围之前且有交集,减去交集部分长度
new Delete(b.position - a.position, a.position), // b: *****------****
new Delete(b.position + b.count - (a.position + a.count), a.position) // a: ***----********
]; // a': ***--**********
return new Delete(b.position - a.position, a.position);
} }
if (a.position > b.position) { if (a.position > b.position) {
if (a.position >= b.position + b.count) { if (a.position >= b.position + b.count) {
return [new Delete(a.count, a.position - b.count), b]; // a删除的范围在b之后且没有交集,删除位置减去b删除的长度
return new Delete(a.count, a.position - b.count);
} }
if (a.position + a.count <= b.position + b.count) { if (a.position + a.count <= b.position + b.count) {
return [noop, new Delete(b.count - a.count, b.position)]; // b删除范围包含a删除范围,no-op
return noop;
} }
return [ // a删除的范围在b删除的范围之后且有交集,减去交集部分长度,并把开始位置放到交集结束位置
new Delete(a.position + a.count - (b.position + b.count), b.position), // b: ***----*********
new Delete(a.position - b.position, b.position) // a: *****------*****
]; // a': *******----*****
return new Delete(a.count - b.count, b.position + b.count);
} }
} }
throw new Error('Unsupported operation types for transformation'); throw new Error("Unsupported operation types for transformation");
} }
} }
@@ -96,13 +107,11 @@ export class Insert extends SimpleTextOperation {
} }
toString(): string { toString(): string {
return 'Insert(' + JSON.stringify(this.str) + ', ' + this.position + ')'; return "Insert(" + JSON.stringify(this.str) + ", " + this.position + ")";
} }
equals(other: SimpleTextOperation): boolean { equals(other: SimpleTextOperation): boolean {
return other instanceof Insert && return other instanceof Insert && this.str === other.str && this.position === other.position;
this.str === other.str &&
this.position === other.position;
} }
apply(doc: string): string { apply(doc: string): string {
@@ -122,13 +131,13 @@ export class Delete extends SimpleTextOperation {
} }
toString(): string { toString(): string {
return 'Delete(' + this.count + ', ' + this.position + ')'; return "Delete(" + this.count + ", " + this.position + ")";
} }
equals(other: SimpleTextOperation): boolean { equals(other: SimpleTextOperation): boolean {
return other instanceof Delete && return (
this.count === other.count && other instanceof Delete && this.count === other.count && this.position === other.position
this.position === other.position; );
} }
apply(doc: string): string { apply(doc: string): string {
@@ -139,7 +148,7 @@ export class Delete extends SimpleTextOperation {
// 不执行任何操作的操作。这对于转换两个删除相同字符的结果是必需的 // 不执行任何操作的操作。这对于转换两个删除相同字符的结果是必需的
export class Noop extends SimpleTextOperation { export class Noop extends SimpleTextOperation {
toString(): string { toString(): string {
return 'Noop()'; return "Noop()";
} }
equals(other: SimpleTextOperation): boolean { equals(other: SimpleTextOperation): boolean {
@@ -152,4 +161,3 @@ export class Noop extends SimpleTextOperation {
} }
const noop = new Noop(); const noop = new Noop();
+11 -6
View File
@@ -1,8 +1,8 @@
// 操作转换服务器 // 操作转换服务器
// 接收客户端操作并应用转换 // 接收客户端操作并应用转换
import type { Client } from './client'; import type { Client } from "./client";
import { SimpleTextOperation as TextOperation } from './op'; import { SimpleTextOperation as TextOperation } from "./op";
class Server { class Server {
public document: string; public document: string;
@@ -20,24 +20,29 @@ class Server {
if (revision < 0 || this.operations.length < revision) { if (revision < 0 || this.operations.length < revision) {
throw new Error("operation revision not in history"); throw new Error("operation revision not in history");
} }
console.log("mattuy", "received operation", revision, operation);
// 查找客户端发送操作时不知道的所有操作... // 查找客户端发送操作时不知道的所有操作...
const concurrentOperations = this.operations.slice(revision); const concurrentOperations = this.operations.slice(revision);
// ...并将操作与所有这些操作进行转换... // ...并将操作与所有这些操作进行转换...
const opId = operation.id;
const transform = TextOperation.transform; const transform = TextOperation.transform;
for (let i = 0; i < concurrentOperations.length; i++) { for (let i = 0; i < concurrentOperations.length; i++) {
// op' = transform(op, op1) // op' = transform(op, op1)
// op基于 revision+i 版本的文档操作,op'基于 revision+i+1 版本的文档操作 // op基于 revision+i 版本的文档操作,op'基于 revision+i+1 版本的文档操作
operation = transform(operation, concurrentOperations[i])[0]; operation = transform(operation, concurrentOperations[i]);
} }
operation.id = opId;
// ...并将其应用到文档上 // ...并将其应用到文档上
this.document = operation.apply(this.document); this.document = operation.apply(this.document);
// 将操作存储到历史记录中 // 将操作存储到历史记录中
this.operations.push(operation); this.operations.push(operation);
// 调用者有责任将操作发送给所有连接的客户端并向创建者发送确认 // 将操作发送给所有连接的客户端并向创建者发送确认
return operation; this.clients.forEach((client) => {
client.applyServer(this.operations.length, operation);
});
} }
// 模拟客户端连接 // 模拟客户端连接
@@ -46,7 +51,7 @@ class Server {
return { return {
document: this.document, document: this.document,
revision: this.operations.length, revision: this.operations.length,
} };
} }
} }
-510
View File
@@ -1,510 +0,0 @@
// TextOperation 类型定义
export type Op = number | string; // 正数表示 retain,负数表示 delete,字符串表示 insert
export class TextOperation {
// 操作数组:正数表示 retain,负数表示 delete,字符串表示 insert
public ops: Op[] = [];
// 操作可以应用到的字符串长度
public baseLength: number = 0;
// 应用操作后结果字符串的长度
public targetLength: number = 0;
constructor() {
// 空构造函数,属性已初始化
}
// 判断操作是否相等
equals(other: TextOperation): boolean {
if (this.baseLength !== other.baseLength) return false;
if (this.targetLength !== other.targetLength) return false;
if (this.ops.length !== other.ops.length) return false;
for (let i = 0; i < this.ops.length; i++) {
if (this.ops[i] !== other.ops[i]) return false;
}
return true;
}
// 判断是否为 retain 操作(正数)
static isRetain(op: Op): boolean {
return typeof op === 'number' && op > 0;
}
// 判断是否为 insert 操作(字符串)
static isInsert(op: Op): boolean {
return typeof op === 'string';
}
// 判断是否为 delete 操作(负数)
static isDelete(op: Op): boolean {
return typeof op === 'number' && op < 0;
}
// 跳过指定数量的字符
retain(n: number): this {
if (typeof n !== 'number') {
throw new Error("retain expects an integer");
}
if (n === 0) return this;
this.baseLength += n;
this.targetLength += n;
const lastOp = this.ops[this.ops.length - 1];
if (TextOperation.isRetain(lastOp)) {
// 最后一个操作是 retain,可以合并
this.ops[this.ops.length - 1] = (lastOp as number) + n;
} else {
// 创建新操作
this.ops.push(n);
}
return this;
}
// 在当前位置插入字符串
insert(str: string): this {
if (typeof str !== 'string') {
throw new Error("insert expects a string");
}
if (str === '') return this;
this.targetLength += str.length;
const ops = this.ops;
const lastOp = ops[ops.length - 1];
if (TextOperation.isInsert(lastOp)) {
// 合并 insert 操作
ops[ops.length - 1] = (lastOp as string) + str;
} else if (TextOperation.isDelete(lastOp)) {
// 无论操作是 delete(3), insert("something") 还是 insert("something"), delete(3)
// 应用时效果相同。这里我们强制 insert 操作总是在 delete 之前
// 这使得所有对正确长度文档具有相同效果的操作在 `equals` 方法下相等
const secondLastOp = ops[ops.length - 2];
if (TextOperation.isInsert(secondLastOp)) {
ops[ops.length - 2] = (secondLastOp as string) + str;
} else {
ops[ops.length] = ops[ops.length - 1];
ops[ops.length - 2] = str;
}
} else {
ops.push(str);
}
return this;
}
// 删除当前位置的字符串
delete(n: number | string): this {
if (typeof n === 'string') {
n = n.length;
}
if (typeof n !== 'number') {
throw new Error("delete expects an integer or a string");
}
if (n === 0) return this;
if (n > 0) n = -n;
this.baseLength -= n;
const lastOp = this.ops[this.ops.length - 1];
if (TextOperation.isDelete(lastOp)) {
this.ops[this.ops.length - 1] = (lastOp as number) + n;
} else {
this.ops.push(n);
}
return this;
}
// 测试操作是否无效
isNoop(): boolean {
return this.ops.length === 0 || (this.ops.length === 1 && TextOperation.isRetain(this.ops[0]));
}
// 转换为字符串表示
toString(): string {
return this.ops.map((op) => {
if (TextOperation.isRetain(op)) {
return `retain ${op}`;
} else if (TextOperation.isInsert(op)) {
return `insert '${op}'`;
} else {
return `delete ${-(op as number)}`;
}
}).join(', ');
}
// 转换为 JSON
toJSON(): Op[] {
return this.ops;
}
// 从 JSON 创建操作并验证
static fromJSON(ops: Op[]): TextOperation {
const o = new TextOperation();
for (let i = 0; i < ops.length; i++) {
const op = ops[i];
if (TextOperation.isRetain(op)) {
o.retain(op as number);
} else if (TextOperation.isInsert(op)) {
o.insert(op as string);
} else if (TextOperation.isDelete(op)) {
o.delete(op as number);
} else {
throw new Error(`unknown operation: ${JSON.stringify(op)}`);
}
}
return o;
}
// 将操作应用到字符串,返回新字符串。如果输入字符串和操作不匹配则抛出错误
apply(str: string): string {
if (str.length !== this.baseLength) {
throw new Error("The operation's base length must be equal to the string's length.");
}
const newStr: string[] = [];
let j = 0;
let strIndex = 0;
const ops = this.ops;
for (let i = 0; i < ops.length; i++) {
const op = ops[i];
if (TextOperation.isRetain(op)) {
const retainCount = op as number;
if (strIndex + retainCount > str.length) {
throw new Error("Operation can't retain more characters than are left in the string.");
}
// 复制跳过的旧字符串部分
newStr[j++] = str.slice(strIndex, strIndex + retainCount);
strIndex += retainCount;
} else if (TextOperation.isInsert(op)) {
// 插入字符串
newStr[j++] = op as string;
} else {
// delete 操作
const deleteCount = op as number;
strIndex -= deleteCount;
}
}
if (strIndex !== str.length) {
throw new Error("The operation didn't operate on the whole string.");
}
return newStr.join('');
}
// 计算操作的逆操作。逆操作是撤销操作效果的操作
invert(str: string): TextOperation {
let strIndex = 0;
const inverse = new TextOperation();
const ops = this.ops;
for (let i = 0; i < ops.length; i++) {
const op = ops[i];
if (TextOperation.isRetain(op)) {
const retainCount = op as number;
inverse.retain(retainCount);
strIndex += retainCount;
} else if (TextOperation.isInsert(op)) {
inverse.delete((op as string).length);
} else {
// delete 操作
const deleteCount = op as number;
inverse.insert(str.slice(strIndex, strIndex - deleteCount));
strIndex -= deleteCount;
}
}
return inverse;
}
// 组合两个连续操作为一个操作,保留两者的更改
compose(operation2: TextOperation): TextOperation {
if (this.targetLength !== operation2.baseLength) {
throw new Error("The base length of the second operation has to be the target length of the first operation");
}
const operation = new TextOperation(); // 组合后的操作
const ops1 = this.ops;
const ops2 = operation2.ops; // 快速访问
let i1 = 0;
let i2 = 0; // ops1 和 ops2 的当前索引
let op1: Op | undefined = ops1[i1++];
let op2: Op | undefined = ops2[i2++]; // 当前操作
while (true) {
// 根据 op1 和 op2 的类型进行分发
if (op1 === undefined && op2 === undefined) {
// 结束条件:ops1 和 ops2 都已处理
break;
}
if (op1 !== undefined && TextOperation.isDelete(op1)) {
operation.delete(op1 as number);
op1 = ops1[i1++];
continue;
}
if (op2 !== undefined && TextOperation.isInsert(op2)) {
operation.insert(op2 as string);
op2 = ops2[i2++];
continue;
}
if (op1 === undefined) {
throw new Error("Cannot compose operations: first operation is too short.");
}
if (op2 === undefined) {
throw new Error("Cannot compose operations: first operation is too long.");
}
if (TextOperation.isRetain(op1) && TextOperation.isRetain(op2)) {
const retain1 = op1 as number;
const retain2 = op2 as number;
if (retain1 > retain2) {
operation.retain(retain2);
op1 = retain1 - retain2;
op2 = ops2[i2++];
} else if (retain1 === retain2) {
operation.retain(retain1);
op1 = ops1[i1++];
op2 = ops2[i2++];
} else {
operation.retain(retain1);
op2 = retain2 - retain1;
op1 = ops1[i1++];
}
} else if (TextOperation.isInsert(op1) && TextOperation.isDelete(op2)) {
const insert1 = op1 as string;
const delete2 = op2 as number;
if (insert1.length > -delete2) {
op1 = insert1.slice(-delete2);
op2 = ops2[i2++];
} else if (insert1.length === -delete2) {
op1 = ops1[i1++];
op2 = ops2[i2++];
} else {
op2 = delete2 + insert1.length;
op1 = ops1[i1++];
}
} else if (TextOperation.isInsert(op1) && TextOperation.isRetain(op2)) {
const insert1 = op1 as string;
const retain2 = op2 as number;
if (insert1.length > retain2) {
operation.insert(insert1.slice(0, retain2));
op1 = insert1.slice(retain2);
op2 = ops2[i2++];
} else if (insert1.length === retain2) {
operation.insert(insert1);
op1 = ops1[i1++];
op2 = ops2[i2++];
} else {
operation.insert(insert1);
op2 = retain2 - insert1.length;
op1 = ops1[i1++];
}
} else if (TextOperation.isRetain(op1) && TextOperation.isDelete(op2)) {
const retain1 = op1 as number;
const delete2 = op2 as number;
if (retain1 > -delete2) {
operation.delete(delete2);
op1 = retain1 + delete2;
op2 = ops2[i2++];
} else if (retain1 === -delete2) {
operation.delete(delete2);
op1 = ops1[i1++];
op2 = ops2[i2++];
} else {
operation.delete(retain1);
op2 = delete2 + retain1;
op1 = ops1[i1++];
}
} else {
throw new Error(
`This shouldn't happen: op1: ${JSON.stringify(op1)}, op2: ${JSON.stringify(op2)}`
);
}
}
return operation;
}
// 判断两个操作是否应该组合
shouldBeComposedWith(other: TextOperation): boolean {
if (this.isNoop() || other.isNoop()) return true;
const startA = getStartIndex(this);
const startB = getStartIndex(other);
const simpleA = getSimpleOp(this);
const simpleB = getSimpleOp(other);
if (!simpleA || !simpleB) return false;
if (TextOperation.isInsert(simpleA) && TextOperation.isInsert(simpleB)) {
return startA + (simpleA as string).length === startB;
}
if (TextOperation.isDelete(simpleA) && TextOperation.isDelete(simpleB)) {
// 有两种删除方式:使用退格键和使用删除键
const deleteB = simpleB as number;
return (startB - deleteB === startA) || startA === startB;
}
return false;
}
// 判断两个操作在反转后是否应该组合
shouldBeComposedWithInverted(other: TextOperation): boolean {
if (this.isNoop() || other.isNoop()) return true;
const startA = getStartIndex(this);
const startB = getStartIndex(other);
const simpleA = getSimpleOp(this);
const simpleB = getSimpleOp(other);
if (!simpleA || !simpleB) return false;
if (TextOperation.isInsert(simpleA) && TextOperation.isInsert(simpleB)) {
return startA + (simpleA as string).length === startB || startA === startB;
}
if (TextOperation.isDelete(simpleA) && TextOperation.isDelete(simpleB)) {
const deleteB = simpleB as number;
return startB - deleteB === startA;
}
return false;
}
// 转换两个并发操作,产生两个操作 A' 和 B',使得
// apply(apply(S, A), B') = apply(apply(S, B), A')
static transform(operation1: TextOperation, operation2: TextOperation): [TextOperation, TextOperation] {
if (operation1.baseLength !== operation2.baseLength) {
throw new Error("Both operations have to have the same base length");
}
const operation1prime = new TextOperation();
const operation2prime = new TextOperation();
const ops1 = operation1.ops;
const ops2 = operation2.ops;
let i1 = 0;
let i2 = 0;
let op1: Op | undefined = ops1[i1++];
let op2: Op | undefined = ops2[i2++];
while (true) {
// 在循环的每次迭代中,操作 operation1 和 operation2 的
// 在输入字符串上操作的假想光标必须在输入字符串中具有相同的位置
if (op1 === undefined && op2 === undefined) {
// 结束条件:ops1 和 ops2 都已处理
break;
}
// 接下来两种情况:一个或两个操作都是 insert 操作
// => 在相应的 prime 操作中插入字符串,在另一个中跳过
// 如果 op1 和 op2 都是 insert 操作,优先 op1
if (op1 !== undefined && TextOperation.isInsert(op1)) {
operation1prime.insert(op1 as string);
operation2prime.retain((op1 as string).length);
op1 = ops1[i1++];
continue;
}
if (op2 !== undefined && TextOperation.isInsert(op2)) {
operation1prime.retain((op2 as string).length);
operation2prime.insert(op2 as string);
op2 = ops2[i2++];
continue;
}
if (op1 === undefined) {
throw new Error("Cannot compose operations: first operation is too short.");
}
if (op2 === undefined) {
throw new Error("Cannot compose operations: first operation is too long.");
}
let minl: number;
if (TextOperation.isRetain(op1) && TextOperation.isRetain(op2)) {
// 简单情况:retain/retain
const retain1 = op1 as number;
const retain2 = op2 as number;
if (retain1 > retain2) {
minl = retain2;
op1 = retain1 - retain2;
op2 = ops2[i2++];
} else if (retain1 === retain2) {
minl = retain2;
op1 = ops1[i1++];
op2 = ops2[i2++];
} else {
minl = retain1;
op2 = retain2 - retain1;
op1 = ops1[i1++];
}
operation1prime.retain(minl);
operation2prime.retain(minl);
} else if (TextOperation.isDelete(op1) && TextOperation.isDelete(op2)) {
// 两个操作都在同一位置删除相同的字符串
// 我们不需要产生任何操作,只需跳过 delete 操作并处理一个操作删除比另一个更多的情况
const delete1 = op1 as number;
const delete2 = op2 as number;
if (-delete1 > -delete2) {
op1 = delete1 - delete2;
op2 = ops2[i2++];
} else if (delete1 === delete2) {
op1 = ops1[i1++];
op2 = ops2[i2++];
} else {
op2 = delete2 - delete1;
op1 = ops1[i1++];
}
// 接下来两种情况:delete/retain 和 retain/delete
} else if (TextOperation.isDelete(op1) && TextOperation.isRetain(op2)) {
const delete1 = op1 as number;
const retain2 = op2 as number;
if (-delete1 > retain2) {
minl = retain2;
op1 = delete1 + retain2;
op2 = ops2[i2++];
} else if (-delete1 === retain2) {
minl = retain2;
op1 = ops1[i1++];
op2 = ops2[i2++];
} else {
minl = -delete1;
op2 = retain2 + delete1;
op1 = ops1[i1++];
}
operation1prime.delete(minl);
} else if (TextOperation.isRetain(op1) && TextOperation.isDelete(op2)) {
const retain1 = op1 as number;
const delete2 = op2 as number;
if (retain1 > -delete2) {
minl = -delete2;
op1 = retain1 + delete2;
op2 = ops2[i2++];
} else if (retain1 === -delete2) {
minl = retain1;
op1 = ops1[i1++];
op2 = ops2[i2++];
} else {
minl = retain1;
op2 = delete2 + retain1;
op1 = ops1[i1++];
}
operation2prime.delete(minl);
} else {
throw new Error("The two operations aren't compatible");
}
}
return [operation1prime, operation2prime];
}
}
// 辅助函数:获取简单操作
function getSimpleOp(operation: TextOperation): Op | null {
const ops = operation.ops;
switch (ops.length) {
case 1:
return ops[0];
case 2:
return TextOperation.isRetain(ops[0]) ? ops[1] : (TextOperation.isRetain(ops[1]) ? ops[0] : null);
case 3:
if (TextOperation.isRetain(ops[0]) && TextOperation.isRetain(ops[2])) {
return ops[1];
}
}
return null;
}
// 辅助函数:获取起始索引
function getStartIndex(operation: TextOperation): number {
const firstOp = operation.ops[0];
if (firstOp !== undefined && TextOperation.isRetain(firstOp)) {
return firstOp as number;
}
return 0;
}