attributes.rs 11 KB

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