我正在设计一个类似 google-doc 的协作工具,其中最新的 React + Slate 作为前端,Flask 在后端。我在 React 中使用 socket-io,在 Python 中使用 flask_socketio 来发出和监听来自其他合作者的内容。反应应用程序代码:
const RichTextExample = props => {
const [value, setValue] = useState(props.currentEditor);
const editor = useMemo(() => withHistory(withReact(createEditor())), []);
const id = useRef(`${Date.now()}`);
const remote = useRef(false);
const socketchange = useRef(false);
useEffect(() => {
socket.on("new-remote-operations", ({ editorId, ops, doc_id }) => {
if (id.current !== editorId && doc_id === props.document.doc_id) {
remote.current = true;
JSON.parse(ops).forEach(op => {
console.log("LISTEN: applying op", op);
editor.apply(op);
});
remote.current = false;
console.log('value is ', value);
socketchange.current = true; //variable to track socket changes in editor via operations
}
});}, [])
return(
<Slate
editor={editor}
value={value}
onChange={value => {
setValue(value);
const ops = editor.operations
.filter(o => {
if (o) {
return o.type !== "set_selection" && o.type !== "set_value";
}
return false;
});
if (ops.length && !remote.current && !socketchange.current) {
console.log("EMIT: Editor operations are ", ops);
socket.emit("new-operations", {
editorId: id.current,
ops: JSON.stringify(ops),
doc_id: props.document.doc_id
});
}
socketchange.current = false;
}}
>
套接字的 Python 代码很简单:
app = Flask(__name__)
db_name = 'userdoc.db'
app.config['SECRET_KEY'] = 'secret-key'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///'+db_name
socketio = SocketIO(app, cors_allowed_origins="*")
@socketio.on('new-operations', namespace='/')
def operations(data):
print('operations listened...1/2/3..')
emit('new-remote-operations', data, broadcast=True, include_self=False)
问题:
当 split_node 作为 socket.on() 中的一种操作类型传递时,editor.apply(op) 不会按预期应用它。请帮助我。