attributes.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. #![allow(non_snake_case)]
  2. use crate::core::{Attributes, Operation, OperationTransform};
  3. use crate::{block_attribute, errors::OTError, ignore_attribute, inline_attribute, list_attribute};
  4. use lazy_static::lazy_static;
  5. use std::{
  6. collections::{HashMap, HashSet},
  7. fmt,
  8. fmt::Formatter,
  9. iter::FromIterator,
  10. };
  11. use strum_macros::Display;
  12. pub type RichTextOperation = Operation<RichTextAttributes>;
  13. impl RichTextOperation {
  14. pub fn contain_attribute(&self, attribute: &RichTextAttribute) -> bool {
  15. self.get_attributes().contains_key(&attribute.key)
  16. }
  17. }
  18. #[derive(Debug, Clone, Eq, PartialEq)]
  19. pub struct RichTextAttributes {
  20. pub(crate) inner: HashMap<RichTextAttributeKey, RichTextAttributeValue>,
  21. }
  22. impl std::default::Default for RichTextAttributes {
  23. fn default() -> Self {
  24. Self {
  25. inner: HashMap::with_capacity(0),
  26. }
  27. }
  28. }
  29. impl fmt::Display for RichTextAttributes {
  30. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  31. f.write_fmt(format_args!("{:?}", self.inner))
  32. }
  33. }
  34. #[inline(always)]
  35. pub fn plain_attributes() -> RichTextAttributes {
  36. RichTextAttributes::default()
  37. }
  38. impl RichTextAttributes {
  39. pub fn new() -> Self {
  40. RichTextAttributes { inner: HashMap::new() }
  41. }
  42. pub fn is_empty(&self) -> bool {
  43. self.inner.is_empty()
  44. }
  45. pub fn add(&mut self, attribute: RichTextAttribute) {
  46. let RichTextAttribute { key, value, scope: _ } = attribute;
  47. self.inner.insert(key, value);
  48. }
  49. pub fn insert(&mut self, key: RichTextAttributeKey, value: RichTextAttributeValue) {
  50. self.inner.insert(key, value);
  51. }
  52. pub fn delete(&mut self, key: &RichTextAttributeKey) {
  53. self.inner.insert(key.clone(), RichTextAttributeValue(None));
  54. }
  55. pub fn mark_all_as_removed_except(&mut self, attribute: Option<RichTextAttributeKey>) {
  56. match attribute {
  57. None => {
  58. self.inner.iter_mut().for_each(|(_k, v)| v.0 = None);
  59. }
  60. Some(attribute) => {
  61. self.inner.iter_mut().for_each(|(k, v)| {
  62. if k != &attribute {
  63. v.0 = None;
  64. }
  65. });
  66. }
  67. }
  68. }
  69. pub fn remove(&mut self, key: RichTextAttributeKey) {
  70. self.inner.retain(|k, _| k != &key);
  71. }
  72. // pub fn block_attributes_except_header(attributes: &Attributes) -> Attributes
  73. // { let mut new_attributes = Attributes::new();
  74. // attributes.iter().for_each(|(k, v)| {
  75. // if k != &AttributeKey::Header {
  76. // new_attributes.insert(k.clone(), v.clone());
  77. // }
  78. // });
  79. //
  80. // new_attributes
  81. // }
  82. // Update inner by constructing new attributes from the other if it's
  83. // not None and replace the key/value with self key/value.
  84. pub fn merge(&mut self, other: Option<RichTextAttributes>) {
  85. if other.is_none() {
  86. return;
  87. }
  88. let mut new_attributes = other.unwrap().inner;
  89. self.inner.iter().for_each(|(k, v)| {
  90. new_attributes.insert(k.clone(), v.clone());
  91. });
  92. self.inner = new_attributes;
  93. }
  94. }
  95. impl Attributes for RichTextAttributes {
  96. fn is_empty(&self) -> bool {
  97. self.inner.is_empty()
  98. }
  99. fn remove_empty(&mut self) {
  100. self.inner.retain(|_, v| v.0.is_some());
  101. }
  102. fn extend_other(&mut self, other: Self) {
  103. self.inner.extend(other.inner);
  104. }
  105. }
  106. impl OperationTransform for RichTextAttributes {
  107. fn compose(&self, other: &Self) -> Result<Self, OTError>
  108. where
  109. Self: Sized,
  110. {
  111. let mut attributes = self.clone();
  112. attributes.extend_other(other.clone());
  113. Ok(attributes)
  114. }
  115. fn transform(&self, other: &Self) -> Result<(Self, Self), OTError>
  116. where
  117. Self: Sized,
  118. {
  119. let a = self
  120. .iter()
  121. .fold(RichTextAttributes::new(), |mut new_attributes, (k, v)| {
  122. if !other.contains_key(k) {
  123. new_attributes.insert(k.clone(), v.clone());
  124. }
  125. new_attributes
  126. });
  127. let b = other
  128. .iter()
  129. .fold(RichTextAttributes::new(), |mut new_attributes, (k, v)| {
  130. if !self.contains_key(k) {
  131. new_attributes.insert(k.clone(), v.clone());
  132. }
  133. new_attributes
  134. });
  135. Ok((a, b))
  136. }
  137. fn invert(&self, other: &Self) -> Self {
  138. let base_inverted = other.iter().fold(RichTextAttributes::new(), |mut attributes, (k, v)| {
  139. if other.get(k) != self.get(k) && self.contains_key(k) {
  140. attributes.insert(k.clone(), v.clone());
  141. }
  142. attributes
  143. });
  144. let inverted = self.iter().fold(base_inverted, |mut attributes, (k, _)| {
  145. if other.get(k) != self.get(k) && !other.contains_key(k) {
  146. attributes.delete(k);
  147. }
  148. attributes
  149. });
  150. inverted
  151. }
  152. }
  153. impl std::ops::Deref for RichTextAttributes {
  154. type Target = HashMap<RichTextAttributeKey, RichTextAttributeValue>;
  155. fn deref(&self) -> &Self::Target {
  156. &self.inner
  157. }
  158. }
  159. impl std::ops::DerefMut for RichTextAttributes {
  160. fn deref_mut(&mut self) -> &mut Self::Target {
  161. &mut self.inner
  162. }
  163. }
  164. pub fn attributes_except_header(op: &RichTextOperation) -> RichTextAttributes {
  165. let mut attributes = op.get_attributes();
  166. attributes.remove(RichTextAttributeKey::Header);
  167. attributes
  168. }
  169. #[derive(Debug, Clone)]
  170. pub struct RichTextAttribute {
  171. pub key: RichTextAttributeKey,
  172. pub value: RichTextAttributeValue,
  173. pub scope: AttributeScope,
  174. }
  175. impl RichTextAttribute {
  176. // inline
  177. inline_attribute!(Bold, bool);
  178. inline_attribute!(Italic, bool);
  179. inline_attribute!(Underline, bool);
  180. inline_attribute!(StrikeThrough, bool);
  181. inline_attribute!(Link, &str);
  182. inline_attribute!(Color, String);
  183. inline_attribute!(Font, usize);
  184. inline_attribute!(Size, usize);
  185. inline_attribute!(Background, String);
  186. inline_attribute!(InlineCode, bool);
  187. // block
  188. block_attribute!(Header, usize);
  189. block_attribute!(Indent, usize);
  190. block_attribute!(Align, String);
  191. block_attribute!(List, &str);
  192. block_attribute!(CodeBlock, bool);
  193. block_attribute!(BlockQuote, bool);
  194. // ignore
  195. ignore_attribute!(Width, usize);
  196. ignore_attribute!(Height, usize);
  197. // List extension
  198. list_attribute!(Bullet, "bullet");
  199. list_attribute!(Ordered, "ordered");
  200. list_attribute!(Checked, "checked");
  201. list_attribute!(UnChecked, "unchecked");
  202. pub fn to_json(&self) -> String {
  203. match serde_json::to_string(self) {
  204. Ok(json) => json,
  205. Err(e) => {
  206. log::error!("Attribute serialize to str failed: {}", e);
  207. "".to_owned()
  208. }
  209. }
  210. }
  211. }
  212. impl fmt::Display for RichTextAttribute {
  213. fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
  214. let s = format!("{:?}:{:?} {:?}", self.key, self.value.0, self.scope);
  215. f.write_str(&s)
  216. }
  217. }
  218. impl std::convert::From<RichTextAttribute> for RichTextAttributes {
  219. fn from(attr: RichTextAttribute) -> Self {
  220. let mut attributes = RichTextAttributes::new();
  221. attributes.add(attr);
  222. attributes
  223. }
  224. }
  225. #[derive(Clone, Debug, Display, Hash, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
  226. // serde.rs/variant-attrs.html
  227. // #[serde(rename_all = "snake_case")]
  228. pub enum RichTextAttributeKey {
  229. #[serde(rename = "bold")]
  230. Bold,
  231. #[serde(rename = "italic")]
  232. Italic,
  233. #[serde(rename = "underline")]
  234. Underline,
  235. #[serde(rename = "strike")]
  236. StrikeThrough,
  237. #[serde(rename = "font")]
  238. Font,
  239. #[serde(rename = "size")]
  240. Size,
  241. #[serde(rename = "link")]
  242. Link,
  243. #[serde(rename = "color")]
  244. Color,
  245. #[serde(rename = "background")]
  246. Background,
  247. #[serde(rename = "indent")]
  248. Indent,
  249. #[serde(rename = "align")]
  250. Align,
  251. #[serde(rename = "code_block")]
  252. CodeBlock,
  253. #[serde(rename = "code")]
  254. InlineCode,
  255. #[serde(rename = "list")]
  256. List,
  257. #[serde(rename = "blockquote")]
  258. BlockQuote,
  259. #[serde(rename = "width")]
  260. Width,
  261. #[serde(rename = "height")]
  262. Height,
  263. #[serde(rename = "header")]
  264. Header,
  265. }
  266. // pub trait AttributeValueData<'a>: Serialize + Deserialize<'a> {}
  267. #[derive(Debug, Clone, PartialEq, Eq, Hash)]
  268. pub struct RichTextAttributeValue(pub Option<String>);
  269. impl std::convert::From<&usize> for RichTextAttributeValue {
  270. fn from(val: &usize) -> Self {
  271. RichTextAttributeValue::from(*val)
  272. }
  273. }
  274. impl std::convert::From<usize> for RichTextAttributeValue {
  275. fn from(val: usize) -> Self {
  276. if val > 0_usize {
  277. RichTextAttributeValue(Some(format!("{}", val)))
  278. } else {
  279. RichTextAttributeValue(None)
  280. }
  281. }
  282. }
  283. impl std::convert::From<&str> for RichTextAttributeValue {
  284. fn from(val: &str) -> Self {
  285. val.to_owned().into()
  286. }
  287. }
  288. impl std::convert::From<String> for RichTextAttributeValue {
  289. fn from(val: String) -> Self {
  290. if val.is_empty() {
  291. RichTextAttributeValue(None)
  292. } else {
  293. RichTextAttributeValue(Some(val))
  294. }
  295. }
  296. }
  297. impl std::convert::From<&bool> for RichTextAttributeValue {
  298. fn from(val: &bool) -> Self {
  299. RichTextAttributeValue::from(*val)
  300. }
  301. }
  302. impl std::convert::From<bool> for RichTextAttributeValue {
  303. fn from(val: bool) -> Self {
  304. let val = match val {
  305. true => Some("true".to_owned()),
  306. false => None,
  307. };
  308. RichTextAttributeValue(val)
  309. }
  310. }
  311. pub fn is_block_except_header(k: &RichTextAttributeKey) -> bool {
  312. if k == &RichTextAttributeKey::Header {
  313. return false;
  314. }
  315. BLOCK_KEYS.contains(k)
  316. }
  317. lazy_static! {
  318. static ref BLOCK_KEYS: HashSet<RichTextAttributeKey> = HashSet::from_iter(vec![
  319. RichTextAttributeKey::Header,
  320. RichTextAttributeKey::Indent,
  321. RichTextAttributeKey::Align,
  322. RichTextAttributeKey::CodeBlock,
  323. RichTextAttributeKey::List,
  324. RichTextAttributeKey::BlockQuote,
  325. ]);
  326. static ref INLINE_KEYS: HashSet<RichTextAttributeKey> = HashSet::from_iter(vec![
  327. RichTextAttributeKey::Bold,
  328. RichTextAttributeKey::Italic,
  329. RichTextAttributeKey::Underline,
  330. RichTextAttributeKey::StrikeThrough,
  331. RichTextAttributeKey::Link,
  332. RichTextAttributeKey::Color,
  333. RichTextAttributeKey::Font,
  334. RichTextAttributeKey::Size,
  335. RichTextAttributeKey::Background,
  336. RichTextAttributeKey::InlineCode,
  337. ]);
  338. static ref INGORE_KEYS: HashSet<RichTextAttributeKey> =
  339. HashSet::from_iter(vec![RichTextAttributeKey::Width, RichTextAttributeKey::Height,]);
  340. }
  341. #[derive(Debug, PartialEq, Eq, Clone)]
  342. pub enum AttributeScope {
  343. Inline,
  344. Block,
  345. Embeds,
  346. Ignore,
  347. }