264 lines
8.9 KiB
Rust
Raw Normal View History

2022-04-14 21:57:00 +08:00
use crate::web_socket::EditorCommandSender;
2021-12-20 15:37:37 +08:00
use crate::{
2022-01-04 15:05:52 +08:00
errors::FlowyError,
2022-02-26 11:03:42 +08:00
queue::{EditBlockQueue, EditorCommand},
2022-03-10 17:14:10 +08:00
TextBlockUser,
2021-11-19 12:18:46 +08:00
};
2021-12-20 15:37:37 +08:00
use bytes::Bytes;
2022-03-19 16:52:28 +08:00
use flowy_error::{internal_error, FlowyResult};
2022-04-14 21:57:00 +08:00
use flowy_revision::{RevisionCloudService, RevisionManager, RevisionObjectBuilder, RevisionWebSocket};
2022-03-19 16:52:28 +08:00
use flowy_sync::entities::ws_data::ServerRevisionWSData;
use flowy_sync::{
2022-07-19 11:31:04 +08:00
entities::{revision::Revision, text_block::DocumentPB},
2022-01-14 15:23:21 +08:00
errors::CollaborateResult,
util::make_delta_from_revisions,
};
2021-12-07 19:59:08 +08:00
use lib_ot::{
2022-01-14 15:23:21 +08:00
core::{Interval, Operation},
2021-12-07 19:59:08 +08:00
rich_text::{RichTextAttribute, RichTextDelta},
};
2022-02-25 22:27:44 +08:00
use lib_ws::WSConnectState;
2021-12-20 15:37:37 +08:00
use std::sync::Arc;
2022-01-12 12:40:41 +08:00
use tokio::sync::{mpsc, oneshot};
2021-12-18 00:23:26 +08:00
2022-05-26 17:28:44 +08:00
pub struct TextBlockEditor {
2021-12-16 22:24:05 +08:00
pub doc_id: String,
2022-01-09 15:13:45 +08:00
#[allow(dead_code)]
2022-01-14 15:23:21 +08:00
rev_manager: Arc<RevisionManager>,
2022-04-14 21:57:00 +08:00
#[cfg(feature = "sync")]
2022-04-17 20:50:16 +08:00
ws_manager: Arc<flowy_revision::RevisionWebSocketManager>,
2022-01-12 12:40:41 +08:00
edit_cmd_tx: EditorCommandSender,
}
2022-05-26 17:28:44 +08:00
impl TextBlockEditor {
2022-04-17 20:50:16 +08:00
#[allow(unused_variables)]
pub(crate) async fn new(
doc_id: &str,
2022-03-10 17:14:10 +08:00
user: Arc<dyn TextBlockUser>,
2022-01-14 15:23:21 +08:00
mut rev_manager: RevisionManager,
2022-04-17 20:50:16 +08:00
rev_web_socket: Arc<dyn RevisionWebSocket>,
2022-02-18 23:04:55 +08:00
cloud_service: Arc<dyn RevisionCloudService>,
2021-12-14 18:04:51 +08:00
) -> FlowyResult<Arc<Self>> {
2022-03-12 21:06:15 +08:00
let document_info = rev_manager.load::<TextBlockInfoBuilder>(Some(cloud_service)).await?;
2022-01-14 15:23:21 +08:00
let delta = document_info.delta()?;
2022-01-05 23:15:55 +08:00
let rev_manager = Arc::new(rev_manager);
let doc_id = doc_id.to_string();
2022-04-17 20:50:16 +08:00
let user_id = user.user_id()?;
2021-12-20 15:37:37 +08:00
2022-01-12 12:40:41 +08:00
let edit_cmd_tx = spawn_edit_queue(user, rev_manager.clone(), delta);
2022-04-14 21:57:00 +08:00
#[cfg(feature = "sync")]
2022-04-17 20:50:16 +08:00
let ws_manager = crate::web_socket::make_block_ws_manager(
2021-12-25 21:44:45 +08:00
doc_id.clone(),
user_id.clone(),
2022-01-12 12:40:41 +08:00
edit_cmd_tx.clone(),
2021-12-25 21:44:45 +08:00
rev_manager.clone(),
2022-02-18 23:04:55 +08:00
rev_web_socket,
2021-12-25 21:44:45 +08:00
)
.await;
2021-12-16 21:31:36 +08:00
let editor = Arc::new(Self {
doc_id,
rev_manager,
2022-04-14 21:57:00 +08:00
#[cfg(feature = "sync")]
2021-12-25 21:44:45 +08:00
ws_manager,
2022-01-12 12:40:41 +08:00
edit_cmd_tx,
2021-12-08 21:51:06 +08:00
});
2021-12-16 21:31:36 +08:00
Ok(editor)
}
2021-12-14 18:04:51 +08:00
pub async fn insert<T: ToString>(&self, index: usize, data: T) -> Result<(), FlowyError> {
2022-01-05 23:15:55 +08:00
let (ret, rx) = oneshot::channel::<CollaborateResult<()>>();
2021-12-18 18:35:45 +08:00
let msg = EditorCommand::Insert {
index,
data: data.to_string(),
ret,
};
2022-01-12 12:40:41 +08:00
let _ = self.edit_cmd_tx.send(msg).await;
2022-01-05 23:15:55 +08:00
let _ = rx.await.map_err(internal_error)??;
2021-11-12 21:44:26 +08:00
Ok(())
}
2021-12-14 18:04:51 +08:00
pub async fn delete(&self, interval: Interval) -> Result<(), FlowyError> {
2022-01-05 23:15:55 +08:00
let (ret, rx) = oneshot::channel::<CollaborateResult<()>>();
2021-12-18 18:35:45 +08:00
let msg = EditorCommand::Delete { interval, ret };
2022-01-12 12:40:41 +08:00
let _ = self.edit_cmd_tx.send(msg).await;
2022-01-05 23:15:55 +08:00
let _ = rx.await.map_err(internal_error)??;
Ok(())
}
2021-12-14 18:04:51 +08:00
pub async fn format(&self, interval: Interval, attribute: RichTextAttribute) -> Result<(), FlowyError> {
2022-01-05 23:15:55 +08:00
let (ret, rx) = oneshot::channel::<CollaborateResult<()>>();
2021-12-18 18:35:45 +08:00
let msg = EditorCommand::Format {
interval,
attribute,
ret,
};
2022-01-12 12:40:41 +08:00
let _ = self.edit_cmd_tx.send(msg).await;
2022-01-05 23:15:55 +08:00
let _ = rx.await.map_err(internal_error)??;
Ok(())
}
2021-12-14 18:04:51 +08:00
pub async fn replace<T: ToString>(&self, interval: Interval, data: T) -> Result<(), FlowyError> {
2022-01-05 23:15:55 +08:00
let (ret, rx) = oneshot::channel::<CollaborateResult<()>>();
2021-12-18 18:35:45 +08:00
let msg = EditorCommand::Replace {
interval,
data: data.to_string(),
ret,
};
2022-01-12 12:40:41 +08:00
let _ = self.edit_cmd_tx.send(msg).await;
2022-01-05 23:15:55 +08:00
let _ = rx.await.map_err(internal_error)??;
Ok(())
}
pub async fn can_undo(&self) -> bool {
let (ret, rx) = oneshot::channel::<bool>();
2021-12-18 18:35:45 +08:00
let msg = EditorCommand::CanUndo { ret };
2022-01-12 12:40:41 +08:00
let _ = self.edit_cmd_tx.send(msg).await;
rx.await.unwrap_or(false)
}
pub async fn can_redo(&self) -> bool {
let (ret, rx) = oneshot::channel::<bool>();
2021-12-18 18:35:45 +08:00
let msg = EditorCommand::CanRedo { ret };
2022-01-12 12:40:41 +08:00
let _ = self.edit_cmd_tx.send(msg).await;
rx.await.unwrap_or(false)
}
2022-01-05 23:15:55 +08:00
pub async fn undo(&self) -> Result<(), FlowyError> {
let (ret, rx) = oneshot::channel();
2021-12-18 18:35:45 +08:00
let msg = EditorCommand::Undo { ret };
2022-01-12 12:40:41 +08:00
let _ = self.edit_cmd_tx.send(msg).await;
2022-01-05 23:15:55 +08:00
let _ = rx.await.map_err(internal_error)??;
Ok(())
}
2022-01-05 23:15:55 +08:00
pub async fn redo(&self) -> Result<(), FlowyError> {
let (ret, rx) = oneshot::channel();
2021-12-18 18:35:45 +08:00
let msg = EditorCommand::Redo { ret };
2022-01-12 12:40:41 +08:00
let _ = self.edit_cmd_tx.send(msg).await;
2022-01-05 23:15:55 +08:00
let _ = rx.await.map_err(internal_error)??;
Ok(())
}
2022-03-05 22:30:42 +08:00
pub async fn delta_str(&self) -> FlowyResult<String> {
2021-12-31 10:32:25 +08:00
let (ret, rx) = oneshot::channel::<CollaborateResult<String>>();
2022-03-05 22:30:42 +08:00
let msg = EditorCommand::ReadDeltaStr { ret };
2022-01-12 12:40:41 +08:00
let _ = self.edit_cmd_tx.send(msg).await;
2021-12-31 10:32:25 +08:00
let json = rx.await.map_err(internal_error)??;
Ok(json)
}
2022-01-23 22:33:47 +08:00
#[tracing::instrument(level = "trace", skip(self, data), err)]
2021-12-31 10:32:25 +08:00
pub(crate) async fn compose_local_delta(&self, data: Bytes) -> Result<(), FlowyError> {
2021-12-07 10:39:01 +08:00
let delta = RichTextDelta::from_bytes(&data)?;
2022-01-05 23:15:55 +08:00
let (ret, rx) = oneshot::channel::<CollaborateResult<()>>();
let msg = EditorCommand::ComposeLocalDelta {
2021-10-06 23:21:57 +08:00
delta: delta.clone(),
ret,
};
2022-01-12 12:40:41 +08:00
let _ = self.edit_cmd_tx.send(msg).await;
2022-01-05 23:15:55 +08:00
let _ = rx.await.map_err(internal_error)??;
2021-11-12 21:44:26 +08:00
Ok(())
}
2022-04-14 21:57:00 +08:00
#[cfg(feature = "sync")]
2022-01-24 17:35:58 +08:00
pub fn stop(&self) {
self.ws_manager.stop();
}
2021-12-09 11:00:05 +08:00
2022-04-14 21:57:00 +08:00
#[cfg(not(feature = "sync"))]
pub fn stop(&self) {}
#[cfg(feature = "sync")]
2022-02-25 22:27:44 +08:00
pub(crate) async fn receive_ws_data(&self, data: ServerRevisionWSData) -> Result<(), FlowyError> {
self.ws_manager.receive_ws_data(data).await
}
2022-04-14 21:57:00 +08:00
#[cfg(not(feature = "sync"))]
pub(crate) async fn receive_ws_data(&self, _data: ServerRevisionWSData) -> Result<(), FlowyError> {
Ok(())
}
2022-02-25 22:27:44 +08:00
2022-04-14 21:57:00 +08:00
#[cfg(feature = "sync")]
2022-02-25 22:27:44 +08:00
pub(crate) fn receive_ws_state(&self, state: &WSConnectState) {
self.ws_manager.connect_state_changed(state.clone());
2022-01-24 17:35:58 +08:00
}
2022-04-14 21:57:00 +08:00
#[cfg(not(feature = "sync"))]
pub(crate) fn receive_ws_state(&self, _state: &WSConnectState) {}
2021-12-16 21:31:36 +08:00
}
2022-05-26 17:28:44 +08:00
impl std::ops::Drop for TextBlockEditor {
2022-01-24 17:35:58 +08:00
fn drop(&mut self) {
2022-02-26 11:03:42 +08:00
tracing::trace!("{} ClientBlockEditor was dropped", self.doc_id)
2022-01-24 17:35:58 +08:00
}
2022-01-12 17:08:50 +08:00
}
2022-01-12 12:40:41 +08:00
// The edit queue will exit after the EditorCommandSender was dropped.
2022-01-05 23:15:55 +08:00
fn spawn_edit_queue(
2022-03-10 17:14:10 +08:00
user: Arc<dyn TextBlockUser>,
2022-01-14 15:23:21 +08:00
rev_manager: Arc<RevisionManager>,
2022-01-05 23:15:55 +08:00
delta: RichTextDelta,
2022-01-12 12:40:41 +08:00
) -> EditorCommandSender {
let (sender, receiver) = mpsc::channel(1000);
2022-02-26 11:03:42 +08:00
let edit_queue = EditBlockQueue::new(user, rev_manager, delta, receiver);
2022-06-29 13:44:15 +08:00
// We can use tokio::task::spawn_local here by using tokio::spawn_blocking.
// https://github.com/tokio-rs/tokio/issues/2095
// tokio::task::spawn_blocking(move || {
// let rt = tokio::runtime::Handle::current();
// rt.block_on(async {
// let local = tokio::task::LocalSet::new();
// local.run_until(edit_queue.run()).await;
// });
// });
2022-02-26 11:03:42 +08:00
tokio::spawn(edit_queue.run());
2021-12-16 21:31:36 +08:00
sender
}
2021-12-09 11:00:05 +08:00
#[cfg(feature = "flowy_unit_test")]
2022-05-26 17:28:44 +08:00
impl TextBlockEditor {
2022-03-12 21:06:15 +08:00
pub async fn text_block_delta(&self) -> FlowyResult<RichTextDelta> {
let (ret, rx) = oneshot::channel::<CollaborateResult<RichTextDelta>>();
2022-03-12 21:06:15 +08:00
let msg = EditorCommand::ReadDelta { ret };
2022-01-12 12:40:41 +08:00
let _ = self.edit_cmd_tx.send(msg).await;
2021-12-09 11:00:05 +08:00
let delta = rx.await.map_err(internal_error)??;
Ok(delta)
}
2022-01-24 17:35:58 +08:00
pub fn rev_manager(&self) -> Arc<RevisionManager> {
self.rev_manager.clone()
}
2022-01-14 15:23:21 +08:00
}
2022-03-12 09:30:13 +08:00
struct TextBlockInfoBuilder();
impl RevisionObjectBuilder for TextBlockInfoBuilder {
2022-07-19 11:31:04 +08:00
type Output = DocumentPB;
2022-01-14 15:23:21 +08:00
2022-02-19 11:34:31 +08:00
fn build_object(object_id: &str, revisions: Vec<Revision>) -> FlowyResult<Self::Output> {
2022-01-14 15:23:21 +08:00
let (base_rev_id, rev_id) = revisions.last().unwrap().pair_rev_id();
let mut delta = make_delta_from_revisions(revisions)?;
correct_delta(&mut delta);
2022-07-19 11:31:04 +08:00
Result::<DocumentPB, FlowyError>::Ok(DocumentPB {
2022-03-02 21:12:21 +08:00
block_id: object_id.to_owned(),
2022-08-02 09:11:04 +08:00
text: delta.json_str(),
2022-01-14 15:23:21 +08:00
rev_id,
base_rev_id,
})
}
}
// quill-editor requires the delta should end with '\n' and only contains the
// insert operation. The function, correct_delta maybe be removed in the future.
fn correct_delta(delta: &mut RichTextDelta) {
if let Some(op) = delta.ops.last() {
let op_data = op.get_data();
if !op_data.ends_with('\n') {
tracing::warn!("The document must end with newline. Correcting it by inserting newline op");
delta.ops.push(Operation::Insert("\n".into()));
}
}
if let Some(op) = delta.ops.iter().find(|op| !op.is_insert()) {
tracing::warn!("The document can only contains insert operations, but found {:?}", op);
delta.ops.retain(|op| op.is_insert());
}
2021-12-09 11:00:05 +08:00
}