attributes.rs 11 KB

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