cell_data_operation.rs 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. use crate::entities::FieldType;
  2. use crate::services::field::*;
  3. use bytes::Bytes;
  4. use flowy_error::{internal_error, ErrorCode, FlowyError, FlowyResult};
  5. use flowy_grid_data_model::revision::{CellRevision, FieldRevision, FieldTypeRevision};
  6. use serde::{Deserialize, Serialize};
  7. use std::fmt::Formatter;
  8. use std::str::FromStr;
  9. pub trait CellFilterOperation<T> {
  10. fn apply_filter(&self, any_cell_data: AnyCellData, filter: &T) -> FlowyResult<bool>;
  11. }
  12. pub trait CellDataOperation<D> {
  13. fn decode_cell_data<T>(
  14. &self,
  15. cell_data: T,
  16. decoded_field_type: &FieldType,
  17. field_rev: &FieldRevision,
  18. ) -> FlowyResult<DecodedCellData>
  19. where
  20. T: Into<D>;
  21. fn apply_changeset<C: Into<CellContentChangeset>>(
  22. &self,
  23. changeset: C,
  24. cell_rev: Option<CellRevision>,
  25. ) -> FlowyResult<String>;
  26. }
  27. #[derive(Debug)]
  28. pub struct CellContentChangeset(pub String);
  29. impl std::fmt::Display for CellContentChangeset {
  30. fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
  31. write!(f, "{}", &self.0)
  32. }
  33. }
  34. impl<T: AsRef<str>> std::convert::From<T> for CellContentChangeset {
  35. fn from(s: T) -> Self {
  36. let s = s.as_ref().to_owned();
  37. CellContentChangeset(s)
  38. }
  39. }
  40. impl std::ops::Deref for CellContentChangeset {
  41. type Target = str;
  42. fn deref(&self) -> &Self::Target {
  43. &self.0
  44. }
  45. }
  46. #[derive(Debug, Serialize, Deserialize)]
  47. pub struct AnyCellData {
  48. pub cell_data: String,
  49. pub field_type: FieldType,
  50. }
  51. impl std::str::FromStr for AnyCellData {
  52. type Err = FlowyError;
  53. fn from_str(s: &str) -> Result<Self, Self::Err> {
  54. let type_option_cell_data: AnyCellData = serde_json::from_str(s)?;
  55. Ok(type_option_cell_data)
  56. }
  57. }
  58. impl std::convert::TryInto<AnyCellData> for String {
  59. type Error = FlowyError;
  60. fn try_into(self) -> Result<AnyCellData, Self::Error> {
  61. AnyCellData::from_str(&self)
  62. }
  63. }
  64. impl std::convert::TryFrom<&CellRevision> for AnyCellData {
  65. type Error = FlowyError;
  66. fn try_from(value: &CellRevision) -> Result<Self, Self::Error> {
  67. Self::from_str(&value.data)
  68. }
  69. }
  70. impl std::convert::TryFrom<&Option<CellRevision>> for AnyCellData {
  71. type Error = FlowyError;
  72. fn try_from(value: &Option<CellRevision>) -> Result<Self, Self::Error> {
  73. match value {
  74. None => Err(FlowyError::invalid_data().context("Expected CellRevision, but receive None")),
  75. Some(cell_rev) => AnyCellData::try_from(cell_rev),
  76. }
  77. }
  78. }
  79. impl std::convert::TryFrom<Option<CellRevision>> for AnyCellData {
  80. type Error = FlowyError;
  81. fn try_from(value: Option<CellRevision>) -> Result<Self, Self::Error> {
  82. Self::try_from(&value)
  83. }
  84. }
  85. impl AnyCellData {
  86. pub fn new(content: String, field_type: FieldType) -> Self {
  87. AnyCellData {
  88. cell_data: content,
  89. field_type,
  90. }
  91. }
  92. pub fn json(&self) -> String {
  93. serde_json::to_string(self).unwrap_or_else(|_| "".to_owned())
  94. }
  95. pub fn is_number(&self) -> bool {
  96. self.field_type == FieldType::Number
  97. }
  98. pub fn is_text(&self) -> bool {
  99. self.field_type == FieldType::RichText
  100. }
  101. pub fn is_checkbox(&self) -> bool {
  102. self.field_type == FieldType::Checkbox
  103. }
  104. pub fn is_date(&self) -> bool {
  105. self.field_type == FieldType::DateTime
  106. }
  107. pub fn is_single_select(&self) -> bool {
  108. self.field_type == FieldType::SingleSelect
  109. }
  110. pub fn is_multi_select(&self) -> bool {
  111. self.field_type == FieldType::MultiSelect
  112. }
  113. pub fn is_url(&self) -> bool {
  114. self.field_type == FieldType::URL
  115. }
  116. pub fn is_select_option(&self) -> bool {
  117. self.field_type == FieldType::MultiSelect || self.field_type == FieldType::SingleSelect
  118. }
  119. }
  120. /// The changeset will be deserialized into specific data base on the FieldType.
  121. /// For example, it's String on FieldType::RichText, and SelectOptionChangeset on FieldType::SingleSelect
  122. pub fn apply_cell_data_changeset<C: Into<CellContentChangeset>, T: AsRef<FieldRevision>>(
  123. changeset: C,
  124. cell_rev: Option<CellRevision>,
  125. field_rev: T,
  126. ) -> Result<String, FlowyError> {
  127. let field_rev = field_rev.as_ref();
  128. let field_type = field_rev.field_type_rev.into();
  129. let s = match field_type {
  130. FieldType::RichText => RichTextTypeOption::from(field_rev).apply_changeset(changeset, cell_rev),
  131. FieldType::Number => NumberTypeOption::from(field_rev).apply_changeset(changeset, cell_rev),
  132. FieldType::DateTime => DateTypeOption::from(field_rev).apply_changeset(changeset, cell_rev),
  133. FieldType::SingleSelect => SingleSelectTypeOption::from(field_rev).apply_changeset(changeset, cell_rev),
  134. FieldType::MultiSelect => MultiSelectTypeOption::from(field_rev).apply_changeset(changeset, cell_rev),
  135. FieldType::Checkbox => CheckboxTypeOption::from(field_rev).apply_changeset(changeset, cell_rev),
  136. FieldType::URL => URLTypeOption::from(field_rev).apply_changeset(changeset, cell_rev),
  137. }?;
  138. Ok(AnyCellData::new(s, field_type).json())
  139. }
  140. pub fn decode_any_cell_data<T: TryInto<AnyCellData>>(data: T, field_rev: &FieldRevision) -> DecodedCellData {
  141. if let Ok(any_cell_data) = data.try_into() {
  142. let AnyCellData { cell_data, field_type } = any_cell_data;
  143. let to_field_type = field_rev.field_type_rev.into();
  144. match try_decode_cell_data(cell_data, field_rev, &field_type, &to_field_type) {
  145. Ok(cell_data) => cell_data,
  146. Err(e) => {
  147. tracing::error!("Decode cell data failed, {:?}", e);
  148. DecodedCellData::default()
  149. }
  150. }
  151. } else {
  152. tracing::error!("Decode type option data failed");
  153. DecodedCellData::default()
  154. }
  155. }
  156. pub fn try_decode_cell_data(
  157. cell_data: String,
  158. field_rev: &FieldRevision,
  159. s_field_type: &FieldType,
  160. t_field_type: &FieldType,
  161. ) -> FlowyResult<DecodedCellData> {
  162. let get_cell_data = || {
  163. let field_type: FieldTypeRevision = t_field_type.into();
  164. let data = match t_field_type {
  165. FieldType::RichText => field_rev
  166. .get_type_option_entry::<RichTextTypeOption>(field_type)?
  167. .decode_cell_data(cell_data, s_field_type, field_rev),
  168. FieldType::Number => field_rev
  169. .get_type_option_entry::<NumberTypeOption>(field_type)?
  170. .decode_cell_data(cell_data, s_field_type, field_rev),
  171. FieldType::DateTime => field_rev
  172. .get_type_option_entry::<DateTypeOption>(field_type)?
  173. .decode_cell_data(cell_data, s_field_type, field_rev),
  174. FieldType::SingleSelect => field_rev
  175. .get_type_option_entry::<SingleSelectTypeOption>(field_type)?
  176. .decode_cell_data(cell_data, s_field_type, field_rev),
  177. FieldType::MultiSelect => field_rev
  178. .get_type_option_entry::<MultiSelectTypeOption>(field_type)?
  179. .decode_cell_data(cell_data, s_field_type, field_rev),
  180. FieldType::Checkbox => field_rev
  181. .get_type_option_entry::<CheckboxTypeOption>(field_type)?
  182. .decode_cell_data(cell_data, s_field_type, field_rev),
  183. FieldType::URL => field_rev
  184. .get_type_option_entry::<URLTypeOption>(field_type)?
  185. .decode_cell_data(cell_data, s_field_type, field_rev),
  186. };
  187. Some(data)
  188. };
  189. match get_cell_data() {
  190. Some(Ok(data)) => Ok(data),
  191. Some(Err(err)) => {
  192. tracing::error!("{:?}", err);
  193. Ok(DecodedCellData::default())
  194. }
  195. None => Ok(DecodedCellData::default()),
  196. }
  197. }
  198. pub(crate) struct EncodedCellData<T>(pub Option<T>);
  199. impl<T> EncodedCellData<T> {
  200. pub fn try_into_inner(self) -> FlowyResult<T> {
  201. match self.0 {
  202. None => Err(ErrorCode::InvalidData.into()),
  203. Some(data) => Ok(data),
  204. }
  205. }
  206. }
  207. impl<T> std::convert::From<String> for EncodedCellData<T>
  208. where
  209. T: FromStr<Err = FlowyError>,
  210. {
  211. fn from(s: String) -> Self {
  212. match T::from_str(&s) {
  213. Ok(inner) => EncodedCellData(Some(inner)),
  214. Err(e) => {
  215. tracing::error!("Deserialize Cell Data failed: {}", e);
  216. EncodedCellData(None)
  217. }
  218. }
  219. }
  220. }
  221. /// The data is encoded by protobuf or utf8. You should choose the corresponding decode struct to parse it.
  222. ///
  223. /// For example:
  224. ///
  225. /// * Use DateCellData to parse the data when the FieldType is Date.
  226. /// * Use URLCellData to parse the data when the FieldType is URL.
  227. /// * Use String to parse the data when the FieldType is RichText, Number, or Checkbox.
  228. /// * Check out the implementation of CellDataOperation trait for more information.
  229. #[derive(Default)]
  230. pub struct DecodedCellData {
  231. pub data: Vec<u8>,
  232. }
  233. impl DecodedCellData {
  234. pub fn new<T: AsRef<[u8]>>(data: T) -> Self {
  235. Self {
  236. data: data.as_ref().to_vec(),
  237. }
  238. }
  239. pub fn try_from_bytes<T: TryInto<Bytes>>(bytes: T) -> FlowyResult<Self>
  240. where
  241. <T as TryInto<Bytes>>::Error: std::fmt::Debug,
  242. {
  243. let bytes = bytes.try_into().map_err(internal_error)?;
  244. Ok(Self { data: bytes.to_vec() })
  245. }
  246. pub fn parse<'a, T: TryFrom<&'a [u8]>>(&'a self) -> FlowyResult<T>
  247. where
  248. <T as TryFrom<&'a [u8]>>::Error: std::fmt::Debug,
  249. {
  250. T::try_from(self.data.as_ref()).map_err(internal_error)
  251. }
  252. }
  253. impl ToString for DecodedCellData {
  254. fn to_string(&self) -> String {
  255. match String::from_utf8(self.data.clone()) {
  256. Ok(s) => s,
  257. Err(e) => {
  258. tracing::error!("DecodedCellData to string failed: {:?}", e);
  259. "".to_string()
  260. }
  261. }
  262. }
  263. }