attributes.rs 10 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<TextAttributes>;
  13. impl RichTextOperation {
  14. pub fn contain_attribute(&self, attribute: &TextAttribute) -> bool {
  15. self.get_attributes().contains_key(&attribute.key)
  16. }
  17. }
  18. #[derive(Debug, Clone, Eq, PartialEq)]
  19. pub struct TextAttributes {
  20. pub(crate) inner: HashMap<TextAttributeKey, TextAttributeValue>,
  21. }
  22. impl std::default::Default for TextAttributes {
  23. fn default() -> Self {
  24. Self {
  25. inner: HashMap::with_capacity(0),
  26. }
  27. }
  28. }
  29. impl fmt::Display for TextAttributes {
  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() -> TextAttributes {
  36. TextAttributes::default()
  37. }
  38. impl TextAttributes {
  39. pub fn new() -> Self {
  40. TextAttributes { inner: HashMap::new() }
  41. }
  42. pub fn is_empty(&self) -> bool {
  43. self.inner.is_empty()
  44. }
  45. pub fn add(&mut self, attribute: TextAttribute) {
  46. let TextAttribute { key, value, scope: _ } = attribute;
  47. self.inner.insert(key, value);
  48. }
  49. pub fn insert(&mut self, key: TextAttributeKey, value: TextAttributeValue) {
  50. self.inner.insert(key, value);
  51. }
  52. pub fn delete(&mut self, key: &TextAttributeKey) {
  53. self.inner.insert(key.clone(), TextAttributeValue(None));
  54. }
  55. pub fn mark_all_as_removed_except(&mut self, attribute: Option<TextAttributeKey>) {
  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: TextAttributeKey) {
  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<TextAttributes>) {
  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 TextAttributes {
  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 TextAttributes {
  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.iter().fold(TextAttributes::new(), |mut new_attributes, (k, v)| {
  120. if !other.contains_key(k) {
  121. new_attributes.insert(k.clone(), v.clone());
  122. }
  123. new_attributes
  124. });
  125. let b = other.iter().fold(TextAttributes::new(), |mut new_attributes, (k, v)| {
  126. if !self.contains_key(k) {
  127. new_attributes.insert(k.clone(), v.clone());
  128. }
  129. new_attributes
  130. });
  131. Ok((a, b))
  132. }
  133. fn invert(&self, other: &Self) -> Self {
  134. let base_inverted = other.iter().fold(TextAttributes::new(), |mut attributes, (k, v)| {
  135. if other.get(k) != self.get(k) && self.contains_key(k) {
  136. attributes.insert(k.clone(), v.clone());
  137. }
  138. attributes
  139. });
  140. let inverted = self.iter().fold(base_inverted, |mut attributes, (k, _)| {
  141. if other.get(k) != self.get(k) && !other.contains_key(k) {
  142. attributes.delete(k);
  143. }
  144. attributes
  145. });
  146. inverted
  147. }
  148. }
  149. impl std::ops::Deref for TextAttributes {
  150. type Target = HashMap<TextAttributeKey, TextAttributeValue>;
  151. fn deref(&self) -> &Self::Target {
  152. &self.inner
  153. }
  154. }
  155. impl std::ops::DerefMut for TextAttributes {
  156. fn deref_mut(&mut self) -> &mut Self::Target {
  157. &mut self.inner
  158. }
  159. }
  160. pub fn attributes_except_header(op: &RichTextOperation) -> TextAttributes {
  161. let mut attributes = op.get_attributes();
  162. attributes.remove(TextAttributeKey::Header);
  163. attributes
  164. }
  165. #[derive(Debug, Clone)]
  166. pub struct TextAttribute {
  167. pub key: TextAttributeKey,
  168. pub value: TextAttributeValue,
  169. pub scope: AttributeScope,
  170. }
  171. impl TextAttribute {
  172. // inline
  173. inline_attribute!(Bold, bool);
  174. inline_attribute!(Italic, bool);
  175. inline_attribute!(Underline, bool);
  176. inline_attribute!(StrikeThrough, bool);
  177. inline_attribute!(Link, &str);
  178. inline_attribute!(Color, String);
  179. inline_attribute!(Font, usize);
  180. inline_attribute!(Size, usize);
  181. inline_attribute!(Background, String);
  182. inline_attribute!(InlineCode, bool);
  183. // block
  184. block_attribute!(Header, usize);
  185. block_attribute!(Indent, usize);
  186. block_attribute!(Align, String);
  187. block_attribute!(List, &str);
  188. block_attribute!(CodeBlock, bool);
  189. block_attribute!(BlockQuote, bool);
  190. // ignore
  191. ignore_attribute!(Width, usize);
  192. ignore_attribute!(Height, usize);
  193. // List extension
  194. list_attribute!(Bullet, "bullet");
  195. list_attribute!(Ordered, "ordered");
  196. list_attribute!(Checked, "checked");
  197. list_attribute!(UnChecked, "unchecked");
  198. pub fn to_json(&self) -> String {
  199. match serde_json::to_string(self) {
  200. Ok(json) => json,
  201. Err(e) => {
  202. log::error!("Attribute serialize to str failed: {}", e);
  203. "".to_owned()
  204. }
  205. }
  206. }
  207. }
  208. impl fmt::Display for TextAttribute {
  209. fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
  210. let s = format!("{:?}:{:?} {:?}", self.key, self.value.0, self.scope);
  211. f.write_str(&s)
  212. }
  213. }
  214. impl std::convert::From<TextAttribute> for TextAttributes {
  215. fn from(attr: TextAttribute) -> Self {
  216. let mut attributes = TextAttributes::new();
  217. attributes.add(attr);
  218. attributes
  219. }
  220. }
  221. #[derive(Clone, Debug, Display, Hash, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
  222. // serde.rs/variant-attrs.html
  223. // #[serde(rename_all = "snake_case")]
  224. pub enum TextAttributeKey {
  225. #[serde(rename = "bold")]
  226. Bold,
  227. #[serde(rename = "italic")]
  228. Italic,
  229. #[serde(rename = "underline")]
  230. Underline,
  231. #[serde(rename = "strike")]
  232. StrikeThrough,
  233. #[serde(rename = "font")]
  234. Font,
  235. #[serde(rename = "size")]
  236. Size,
  237. #[serde(rename = "link")]
  238. Link,
  239. #[serde(rename = "color")]
  240. Color,
  241. #[serde(rename = "background")]
  242. Background,
  243. #[serde(rename = "indent")]
  244. Indent,
  245. #[serde(rename = "align")]
  246. Align,
  247. #[serde(rename = "code_block")]
  248. CodeBlock,
  249. #[serde(rename = "code")]
  250. InlineCode,
  251. #[serde(rename = "list")]
  252. List,
  253. #[serde(rename = "blockquote")]
  254. BlockQuote,
  255. #[serde(rename = "width")]
  256. Width,
  257. #[serde(rename = "height")]
  258. Height,
  259. #[serde(rename = "header")]
  260. Header,
  261. }
  262. // pub trait AttributeValueData<'a>: Serialize + Deserialize<'a> {}
  263. #[derive(Debug, Clone, PartialEq, Eq, Hash)]
  264. pub struct TextAttributeValue(pub Option<String>);
  265. impl std::convert::From<&usize> for TextAttributeValue {
  266. fn from(val: &usize) -> Self {
  267. TextAttributeValue::from(*val)
  268. }
  269. }
  270. impl std::convert::From<usize> for TextAttributeValue {
  271. fn from(val: usize) -> Self {
  272. if val > 0_usize {
  273. TextAttributeValue(Some(format!("{}", val)))
  274. } else {
  275. TextAttributeValue(None)
  276. }
  277. }
  278. }
  279. impl std::convert::From<&str> for TextAttributeValue {
  280. fn from(val: &str) -> Self {
  281. val.to_owned().into()
  282. }
  283. }
  284. impl std::convert::From<String> for TextAttributeValue {
  285. fn from(val: String) -> Self {
  286. if val.is_empty() {
  287. TextAttributeValue(None)
  288. } else {
  289. TextAttributeValue(Some(val))
  290. }
  291. }
  292. }
  293. impl std::convert::From<&bool> for TextAttributeValue {
  294. fn from(val: &bool) -> Self {
  295. TextAttributeValue::from(*val)
  296. }
  297. }
  298. impl std::convert::From<bool> for TextAttributeValue {
  299. fn from(val: bool) -> Self {
  300. let val = match val {
  301. true => Some("true".to_owned()),
  302. false => None,
  303. };
  304. TextAttributeValue(val)
  305. }
  306. }
  307. pub fn is_block_except_header(k: &TextAttributeKey) -> bool {
  308. if k == &TextAttributeKey::Header {
  309. return false;
  310. }
  311. BLOCK_KEYS.contains(k)
  312. }
  313. pub fn is_block(k: &TextAttributeKey) -> bool {
  314. BLOCK_KEYS.contains(k)
  315. }
  316. lazy_static! {
  317. static ref BLOCK_KEYS: HashSet<TextAttributeKey> = HashSet::from_iter(vec![
  318. TextAttributeKey::Header,
  319. TextAttributeKey::Indent,
  320. TextAttributeKey::Align,
  321. TextAttributeKey::CodeBlock,
  322. TextAttributeKey::List,
  323. TextAttributeKey::BlockQuote,
  324. ]);
  325. static ref INLINE_KEYS: HashSet<TextAttributeKey> = HashSet::from_iter(vec![
  326. TextAttributeKey::Bold,
  327. TextAttributeKey::Italic,
  328. TextAttributeKey::Underline,
  329. TextAttributeKey::StrikeThrough,
  330. TextAttributeKey::Link,
  331. TextAttributeKey::Color,
  332. TextAttributeKey::Font,
  333. TextAttributeKey::Size,
  334. TextAttributeKey::Background,
  335. TextAttributeKey::InlineCode,
  336. ]);
  337. static ref INGORE_KEYS: HashSet<TextAttributeKey> =
  338. HashSet::from_iter(vec![TextAttributeKey::Width, TextAttributeKey::Height,]);
  339. }
  340. #[derive(Debug, PartialEq, Eq, Clone)]
  341. pub enum AttributeScope {
  342. Inline,
  343. Block,
  344. Embeds,
  345. Ignore,
  346. }