cell_data_operation.rs 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. use crate::services::field::*;
  2. use flowy_error::{ErrorCode, FlowyError, FlowyResult};
  3. use flowy_grid_data_model::entities::{CellMeta, FieldMeta, FieldType};
  4. use serde::{Deserialize, Serialize};
  5. use std::fmt::Formatter;
  6. use std::str::FromStr;
  7. pub trait CellDataOperation<D, CO: ToString> {
  8. fn decode_cell_data<T>(
  9. &self,
  10. encoded_data: T,
  11. decoded_field_type: &FieldType,
  12. field_meta: &FieldMeta,
  13. ) -> FlowyResult<DecodedCellData>
  14. where
  15. T: Into<D>;
  16. //
  17. fn apply_changeset<C: Into<CellContentChangeset>>(
  18. &self,
  19. changeset: C,
  20. cell_meta: Option<CellMeta>,
  21. ) -> FlowyResult<CO>;
  22. }
  23. #[derive(Debug)]
  24. pub struct CellContentChangeset(pub String);
  25. impl std::fmt::Display for CellContentChangeset {
  26. fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
  27. write!(f, "{}", &self.0)
  28. }
  29. }
  30. impl<T: AsRef<str>> std::convert::From<T> for CellContentChangeset {
  31. fn from(s: T) -> Self {
  32. let s = s.as_ref().to_owned();
  33. CellContentChangeset(s)
  34. }
  35. }
  36. impl std::ops::Deref for CellContentChangeset {
  37. type Target = str;
  38. fn deref(&self) -> &Self::Target {
  39. &self.0
  40. }
  41. }
  42. #[derive(Debug, Serialize, Deserialize)]
  43. pub struct TypeOptionCellData {
  44. pub data: String,
  45. pub field_type: FieldType,
  46. }
  47. impl TypeOptionCellData {
  48. pub fn split(self) -> (String, FieldType) {
  49. (self.data, self.field_type)
  50. }
  51. }
  52. impl std::str::FromStr for TypeOptionCellData {
  53. type Err = FlowyError;
  54. fn from_str(s: &str) -> Result<Self, Self::Err> {
  55. let type_option_cell_data: TypeOptionCellData = serde_json::from_str(s)?;
  56. Ok(type_option_cell_data)
  57. }
  58. }
  59. impl std::convert::TryInto<TypeOptionCellData> for String {
  60. type Error = FlowyError;
  61. fn try_into(self) -> Result<TypeOptionCellData, Self::Error> {
  62. TypeOptionCellData::from_str(&self)
  63. }
  64. }
  65. impl TypeOptionCellData {
  66. pub fn new<T: ToString>(data: T, field_type: FieldType) -> Self {
  67. TypeOptionCellData {
  68. data: data.to_string(),
  69. field_type,
  70. }
  71. }
  72. pub fn json(&self) -> String {
  73. serde_json::to_string(self).unwrap_or_else(|_| "".to_owned())
  74. }
  75. pub fn is_number(&self) -> bool {
  76. self.field_type == FieldType::Number
  77. }
  78. pub fn is_text(&self) -> bool {
  79. self.field_type == FieldType::RichText
  80. }
  81. pub fn is_checkbox(&self) -> bool {
  82. self.field_type == FieldType::Checkbox
  83. }
  84. pub fn is_date(&self) -> bool {
  85. self.field_type == FieldType::DateTime
  86. }
  87. pub fn is_single_select(&self) -> bool {
  88. self.field_type == FieldType::SingleSelect
  89. }
  90. pub fn is_multi_select(&self) -> bool {
  91. self.field_type == FieldType::MultiSelect
  92. }
  93. pub fn is_select_option(&self) -> bool {
  94. self.field_type == FieldType::MultiSelect || self.field_type == FieldType::SingleSelect
  95. }
  96. }
  97. /// The changeset will be deserialized into specific data base on the FieldType.
  98. /// For example, it's String on FieldType::RichText, and SelectOptionChangeset on FieldType::SingleSelect
  99. pub fn apply_cell_data_changeset<T: Into<CellContentChangeset>>(
  100. changeset: T,
  101. cell_meta: Option<CellMeta>,
  102. field_meta: &FieldMeta,
  103. ) -> Result<String, FlowyError> {
  104. let s = match field_meta.field_type {
  105. FieldType::RichText => RichTextTypeOption::from(field_meta).apply_changeset(changeset, cell_meta),
  106. FieldType::Number => NumberTypeOption::from(field_meta).apply_changeset(changeset, cell_meta),
  107. FieldType::DateTime => DateTypeOption::from(field_meta)
  108. .apply_changeset(changeset, cell_meta)
  109. .map(|data| data.to_string()),
  110. FieldType::SingleSelect => SingleSelectTypeOption::from(field_meta).apply_changeset(changeset, cell_meta),
  111. FieldType::MultiSelect => MultiSelectTypeOption::from(field_meta).apply_changeset(changeset, cell_meta),
  112. FieldType::Checkbox => CheckboxTypeOption::from(field_meta).apply_changeset(changeset, cell_meta),
  113. }?;
  114. Ok(TypeOptionCellData::new(s, field_meta.field_type.clone()).json())
  115. }
  116. pub fn decode_cell_data_from_type_option_cell_data<T: TryInto<TypeOptionCellData>>(
  117. data: T,
  118. field_meta: &FieldMeta,
  119. field_type: &FieldType,
  120. ) -> DecodedCellData {
  121. if let Ok(type_option_cell_data) = data.try_into() {
  122. let (encoded_data, s_field_type) = type_option_cell_data.split();
  123. decode_cell_data(encoded_data, &s_field_type, field_type, field_meta).unwrap_or_default()
  124. } else {
  125. DecodedCellData::default()
  126. }
  127. }
  128. pub fn decode_cell_data<T: Into<String>>(
  129. encoded_data: T,
  130. s_field_type: &FieldType,
  131. t_field_type: &FieldType,
  132. field_meta: &FieldMeta,
  133. ) -> FlowyResult<DecodedCellData> {
  134. let encoded_data = encoded_data.into();
  135. let get_cell_data = || {
  136. let data = match t_field_type {
  137. FieldType::RichText => field_meta
  138. .get_type_option_entry::<RichTextTypeOption>(t_field_type)?
  139. .decode_cell_data(encoded_data, s_field_type, field_meta),
  140. FieldType::Number => field_meta
  141. .get_type_option_entry::<NumberTypeOption>(t_field_type)?
  142. .decode_cell_data(encoded_data, s_field_type, field_meta),
  143. FieldType::DateTime => field_meta
  144. .get_type_option_entry::<DateTypeOption>(t_field_type)?
  145. .decode_cell_data(encoded_data, s_field_type, field_meta),
  146. FieldType::SingleSelect => field_meta
  147. .get_type_option_entry::<SingleSelectTypeOption>(t_field_type)?
  148. .decode_cell_data(encoded_data, s_field_type, field_meta),
  149. FieldType::MultiSelect => field_meta
  150. .get_type_option_entry::<MultiSelectTypeOption>(t_field_type)?
  151. .decode_cell_data(encoded_data, s_field_type, field_meta),
  152. FieldType::Checkbox => field_meta
  153. .get_type_option_entry::<CheckboxTypeOption>(t_field_type)?
  154. .decode_cell_data(encoded_data, s_field_type, field_meta),
  155. };
  156. Some(data)
  157. };
  158. match get_cell_data() {
  159. Some(Ok(data)) => {
  160. tracing::Span::current().record(
  161. "content",
  162. &format!("{:?}: {}", field_meta.field_type, data.content).as_str(),
  163. );
  164. Ok(data)
  165. }
  166. Some(Err(err)) => {
  167. tracing::error!("{:?}", err);
  168. Ok(DecodedCellData::default())
  169. }
  170. None => Ok(DecodedCellData::default()),
  171. }
  172. }
  173. pub(crate) struct EncodedCellData<T>(pub Option<T>);
  174. impl<T> EncodedCellData<T> {
  175. pub fn try_into_inner(self) -> FlowyResult<T> {
  176. match self.0 {
  177. None => Err(ErrorCode::InvalidData.into()),
  178. Some(data) => Ok(data),
  179. }
  180. }
  181. }
  182. impl<T> std::convert::From<String> for EncodedCellData<T>
  183. where
  184. T: FromStr<Err = FlowyError>,
  185. {
  186. fn from(s: String) -> Self {
  187. match T::from_str(&s) {
  188. Ok(inner) => EncodedCellData(Some(inner)),
  189. Err(e) => {
  190. tracing::error!("Deserialize Cell Data failed: {}", e);
  191. EncodedCellData(None)
  192. }
  193. }
  194. }
  195. }
  196. #[derive(Default)]
  197. pub struct DecodedCellData {
  198. raw: String,
  199. pub content: String,
  200. }
  201. impl DecodedCellData {
  202. pub fn from_content(content: String) -> Self {
  203. Self {
  204. raw: content.clone(),
  205. content,
  206. }
  207. }
  208. pub fn new(raw: String, content: String) -> Self {
  209. Self { raw, content }
  210. }
  211. pub fn split(self) -> (String, String) {
  212. (self.raw, self.content)
  213. }
  214. }