tidy up code

This commit is contained in:
Pavel Murygin 2021-01-16 12:28:01 +03:00
parent f4c79f46ab
commit d3f71f1da2
2 changed files with 134 additions and 133 deletions

View File

@ -1,171 +1,72 @@
import * as Automerge from 'automerge';
import DiffMatchPatch from 'diff-match-patch';
import { useEffect, useRef, useState } from 'react';
import _ from 'lodash';
import { useEffect, useState } from 'react';
import { subscribeToEvent } from '@fluencelabs/fluence';
import { fluentPadServiceId, notifyTextUpdateFnName } from 'src/fluence/constants';
import { useFluenceClient } from './FluenceClientContext';
import { getUpdatedDocFromText, initDoc, SyncClient } from './sync';
import * as calls from 'src/fluence/calls';
import { FluenceClient, subscribeToEvent } from '@fluencelabs/fluence';
import _ from 'lodash';
interface TextDoc {
value: Automerge.Text;
}
const dmp = new DiffMatchPatch();
const getUpdatedDocFromText = (oldDoc: TextDoc | null, newText: string) => {
const prevText = oldDoc ? oldDoc.value.toString() : '';
const diff = dmp.diff_main(prevText, newText);
dmp.diff_cleanupSemantic(diff);
const patches = dmp.patch_make(prevText, diff);
const newDoc = Automerge.change(oldDoc, (doc) => {
patches.forEach((patch) => {
let idx = patch.start1;
patch.diffs.forEach(([operation, changeText]) => {
switch (operation) {
case 1: // Insertion
doc.value.insertAt!(idx, ...changeText.split(''));
break;
case 0: // No Change
idx += changeText.length;
break;
case -1: // Deletion
for (let i = 0; i < changeText.length; i++) {
doc.value.deleteAt!(idx);
}
break;
}
});
});
});
return newDoc;
};
const parseState = (entry: string) => {
try {
return JSON.parse(entry);
} catch (e) {
console.log('couldnt parse state format: ' + entry);
return null;
const broadcastUpdates = _.debounce((text: string, syncClient: SyncClient) => {
let doc = syncClient.getDoc();
if (doc) {
let newDoc = getUpdatedDocFromText(doc, text);
syncClient.syncDoc(newDoc);
}
};
const applyStates = (startingDoc: TextDoc | null, entries: calls.Entry[]) => {
let res = startingDoc;
for (let entry of entries) {
const state = parseState(entry.body) as TextDoc;
if (state) {
if (!res) {
res = state;
} else {
res = Automerge.merge(res, state);
}
}
}
if (res === null) {
res = Automerge.from({
value: new Automerge.Text(),
});
}
return res;
};
const broadcastUpdates = _.debounce(async (client: FluenceClient, doc: TextDoc) => {
const entry = {
fluentPadState: Automerge.save(doc),
};
const entryStr = JSON.stringify(entry);
await calls.addEntry(client, entryStr);
}, 200);
}, 100);
export const CollaborativeEditor = () => {
const client = useFluenceClient()!;
const [text, setText] = useState('');
// const textAreaRef = useRef<HTMLTextAreaElement>(null);
const docSetRef = useRef(new Automerge.DocSet<TextDoc>());
const [amConnection, setAmConnection] = useState<any>();
const [syncClient, setSyncClient] = useState(new SyncClient());
useEffect(() => {
const doc = Automerge.from({ value: new Automerge.Text() });
docSetRef.current.setDoc('doc', doc);
docSetRef.current.registerHandler((id, doc) => {
if (id === 'doc') {
setText(doc.value.toString());
}
});
const connection = new Automerge.Connection(docSetRef.current, (msg) => {
console.log('on update');
calls.addEntry(client, JSON.stringify(msg));
});
connection.open();
setAmConnection(connection);
syncClient.syncDoc(initDoc());
syncClient.handleDocUpdate = (doc) => {
console.log('syncClient.handleDocUpdate');
setText(doc.text.toString());
};
const unsub1 = subscribeToEvent(client, fluentPadServiceId, notifyTextUpdateFnName, (args, tetraplets) => {
const [authorPeerId, stateStr, isAuthorized] = args;
syncClient.handleSendChanges = (changes: string) => {
console.log('syncClient.handleSendChanges');
calls.addEntry(client, changes);
};
const unsub = subscribeToEvent(client, fluentPadServiceId, notifyTextUpdateFnName, (args, tetraplets) => {
const [authorPeerId, changes, isAuthorized] = args;
if (authorPeerId === client.selfPeerId.toB58String()) {
return;
}
const state = parseState(stateStr);
console.log(state);
if (state) {
connection.receiveMsg(state);
if (changes) {
syncClient.receiveChanges(changes);
}
});
syncClient.start();
// don't block
calls.getHistory(client).then((res) => {
for (let e of res) {
try {
const msg = JSON.parse(e.body);
connection.receiveMsg(msg);
} catch (e) {
console.log("history didn't work", e);
}
syncClient.receiveChanges(e.body);
}
// setText(newDoc);
});
return () => {
unsub1();
unsub();
syncClient.stop();
};
}, []);
// const amHistory = text
// ? Automerge.getHistory(text).map((x) => {
// return x.snapshot.value;
// })
// : [];
// const textValue = text ? text.value : '';
const handleTextUpdate = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
setText(e.target.value);
let doc = docSetRef.current.getDoc('doc');
if (doc) {
let res = getUpdatedDocFromText(doc, e.target.value);
console.log(res);
docSetRef.current.setDoc('doc', res!);
}
const newText = e.target.value;
setText(newText);
broadcastUpdates(newText, syncClient);
};
return (
<div>
<textarea value={text} onChange={handleTextUpdate} />
<div>
Automerge changes:
<ul>
{/* {amHistory.map((value, index) => (
<li key={index}>{value}</li>
))} */}
</ul>
</div>
</div>
);
};

100
client/src/app/sync.ts Normal file
View File

@ -0,0 +1,100 @@
import { from, Connection, Doc, DocSet, Text, Message, change } from 'automerge';
import DiffMatchPatch from 'diff-match-patch';
export interface TextDoc {
text: Text;
}
export const initDoc = () => {
return from({
text: new Text(),
});
};
export class SyncClient<T = TextDoc> {
private static globalDocId = 'fluent-pad-doc';
private docSet: DocSet<T>;
private connection: Connection<T>;
constructor() {
this.docSet = new DocSet<T>();
this.connection = new Connection<T>(this.docSet, this.doSendMessage.bind(this));
this.docSet.registerHandler(this.doHandleDocUpdate.bind(this));
}
start() {
this.connection.open();
}
stop() {
this.connection.close();
}
getDoc() {
return this.docSet.getDoc(SyncClient.globalDocId);
}
syncDoc(doc: Doc<T>) {
this.docSet.setDoc(SyncClient.globalDocId, doc);
}
receiveChanges(changes: string) {
try {
const msg = JSON.parse(changes);
this.connection.receiveMsg(msg);
} catch (e) {
console.log('Couldnt receive message', changes);
}
}
handleDocUpdate?: (doc: Doc<T>) => void;
handleSendChanges?: (changes: string) => void;
private doSendMessage(msg: Message) {
if (this.handleSendChanges) {
const body = JSON.stringify(msg);
this.handleSendChanges(body);
}
}
private doHandleDocUpdate(docId: string, doc: Doc<T>) {
if (docId === SyncClient.globalDocId && this.handleDocUpdate) {
console.log(docId, doc);
this.handleDocUpdate(doc);
}
}
}
const dmp = new DiffMatchPatch();
export const getUpdatedDocFromText = (oldDoc: TextDoc, newText: string) => {
const prevText = oldDoc.text.toString();
const diff = dmp.diff_main(prevText, newText);
dmp.diff_cleanupSemantic(diff);
const patches = dmp.patch_make(prevText, diff);
const newDoc = change(oldDoc, (doc) => {
patches.forEach((patch) => {
let idx = patch.start1;
patch.diffs.forEach(([operation, changeText]) => {
switch (operation) {
case 1: // Insertion
doc.text.insertAt!(idx, ...changeText.split(''));
break;
case 0: // No Change
idx += changeText.length;
break;
case -1: // Deletion
for (let i = 0; i < changeText.length; i++) {
doc.text.deleteAt!(idx);
}
break;
}
});
});
});
return newDoc;
};