This repository has been archived by the owner on Sep 27, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 24
/
base.rs
290 lines (249 loc) · 9.28 KB
/
base.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
// Copyright 2022 The Matrix.org Foundation C.I.C.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::action_state::ActionState;
use crate::composer_model::menu_state::MenuStateComputeType;
use crate::composer_state::ComposerState;
use crate::dom::parser::markdown::markdown_html_parser::MarkdownHTMLParser;
use crate::dom::parser::parse;
use crate::dom::to_plain_text::ToPlainText;
use crate::dom::{Dom, DomCreationError, UnicodeString};
use crate::link_action::LinkActionUpdate;
use crate::{
ComposerAction, ComposerUpdate, DomHandle, Location, ToHtml, ToMarkdown,
ToTree,
};
use std::collections::HashMap;
#[derive(Clone, Default)]
pub struct ComposerModel<S>
where
S: UnicodeString,
{
/// The current state of the model
pub state: ComposerState<S>,
/// Old states that may be restored by calling undo()
pub(crate) previous_states: Vec<ComposerState<S>>,
/// States after the current one that may be restored by calling redo()
pub(crate) next_states: Vec<ComposerState<S>>,
/// The states of the buttons for each action e.g. bold, undo
pub(crate) action_states: HashMap<ComposerAction, ActionState>,
}
impl<S> ComposerModel<S>
where
S: UnicodeString,
{
pub fn new() -> Self {
let mut instance = Self {
state: ComposerState::default(),
previous_states: Vec::new(),
next_states: Vec::new(),
action_states: HashMap::new(), // TODO: Calculate state based on ComposerState
};
instance.compute_menu_state(MenuStateComputeType::AlwaysUpdate);
instance
}
pub fn from_state(state: ComposerState<S>) -> Self {
Self {
state,
previous_states: Vec::new(),
next_states: Vec::new(),
action_states: HashMap::new(), // TODO: Calculate state based on ComposerState
}
}
/// Create a UTF-16 model from an HTML string, or panic if HTML parsing
/// fails.
pub fn from_html(
html: &str,
start_codeunit: usize,
end_codeunit: usize,
) -> Self {
let mut model = Self {
state: ComposerState {
dom: parse(html).expect("HTML parsing failed"),
start: Location::from(start_codeunit),
end: Location::from(end_codeunit),
toggled_format_types: Vec::new(),
},
previous_states: Vec::new(),
next_states: Vec::new(),
action_states: HashMap::new(), // TODO: Calculate state based on ComposerState
};
model.compute_menu_state(MenuStateComputeType::AlwaysUpdate);
Self::post_process_dom(&mut model.state.dom);
model
}
/// Replace the entire content of the model with given HTML string.
/// This will remove all previous and next states, effectively disabling
/// undo and redo until further updates.
pub fn set_content_from_html(
&mut self,
html: &S,
) -> Result<ComposerUpdate<S>, DomCreationError> {
let dom = parse(&html.to_string())
.map_err(DomCreationError::HtmlParseError)?;
self.state.dom = dom;
self.previous_states.clear();
self.next_states.clear();
Self::post_process_dom(&mut self.state.dom);
self.state.start = Location::from(self.state.dom.text_len());
self.state.end = self.state.start;
Ok(self.create_update_replace_all_with_menu_state())
}
fn post_process_dom(dom: &mut Dom<S>) {
dom.wrap_inline_nodes_into_paragraphs_if_needed(&DomHandle::root());
dom.explicitly_assert_invariants();
}
pub fn set_content_from_markdown(
&mut self,
markdown: &S,
) -> Result<ComposerUpdate<S>, DomCreationError> {
let html = MarkdownHTMLParser::to_html(markdown)
.map_err(DomCreationError::MarkdownParseError)?;
self.set_content_from_html(&html)
}
pub fn action_states(&self) -> &HashMap<ComposerAction, ActionState> {
&self.action_states
}
#[cfg(test)]
pub(crate) fn action_is_enabled(&self, action: ComposerAction) -> bool {
self.action_states.get(&action) == Some(&ActionState::Enabled)
}
pub(crate) fn action_is_reversed(&self, action: ComposerAction) -> bool {
self.action_states.get(&action) == Some(&ActionState::Reversed)
}
#[cfg(test)]
pub(crate) fn action_is_disabled(&self, action: ComposerAction) -> bool {
self.action_states.get(&action) == Some(&ActionState::Disabled)
}
pub(crate) fn create_update_update_selection(
&mut self,
) -> ComposerUpdate<S> {
#[cfg(any(test, feature = "assert-invariants"))]
self.state.dom.assert_transaction_not_in_progress();
let menu_state =
self.compute_menu_state(MenuStateComputeType::KeepIfUnchanged);
ComposerUpdate::update_selection(
self.state.start,
self.state.end,
menu_state,
self.compute_menu_action(),
LinkActionUpdate::Update(self.get_link_action()),
)
}
pub(crate) fn create_update_replace_all(&mut self) -> ComposerUpdate<S> {
#[cfg(any(test, feature = "assert-invariants"))]
self.state.dom.assert_transaction_not_in_progress();
ComposerUpdate::replace_all(
self.state.dom.to_html(),
self.state.start,
self.state.end,
self.compute_menu_state(MenuStateComputeType::KeepIfUnchanged),
self.compute_menu_action(),
LinkActionUpdate::Update(self.get_link_action()),
)
}
pub(crate) fn create_update_replace_all_with_menu_state(
&mut self,
) -> ComposerUpdate<S> {
#[cfg(any(test, feature = "assert-invariants"))]
self.state.dom.assert_transaction_not_in_progress();
ComposerUpdate::replace_all(
self.state.dom.to_html(),
self.state.start,
self.state.end,
self.compute_menu_state(MenuStateComputeType::AlwaysUpdate),
self.compute_menu_action(),
LinkActionUpdate::Update(self.get_link_action()),
)
}
pub fn get_selection(&self) -> (Location, Location) {
(self.state.start, self.state.end)
}
pub fn get_content_as_html(&self) -> S {
self.state.dom.to_html()
}
pub fn get_content_as_message_html(&self) -> S {
self.state.dom.to_message_html()
}
pub fn get_content_as_markdown(&self) -> S {
self.state.dom.to_markdown().unwrap()
}
pub fn get_content_as_message_markdown(&self) -> S {
self.state.dom.to_message_markdown().unwrap()
}
pub fn get_content_as_plain_text(&self) -> S {
self.state.dom.to_plain_text()
}
pub fn get_current_state(&self) -> &ComposerState<S> {
&self.state
}
pub fn to_tree(&self) -> S {
self.state.dom.to_tree()
}
pub fn clear(&mut self) -> ComposerUpdate<S> {
self.set_content_from_html(&"".into())
.expect("empty content")
}
}
#[cfg(test)]
mod test {
use widestring::Utf16String;
use crate::tests::testutils_composer_model::{cm, tx};
use crate::tests::testutils_conversion::utf16;
use super::*;
// Most tests for ComposerModel are inside the tests/ modules
#[test]
fn completely_replacing_html_works() {
let mut model = cm("{hello}| world");
model
.set_content_from_html(&Utf16String::from_str("foo <b>bar</b>"))
.unwrap();
assert_eq!(model.state.dom.to_string(), "foo <b>bar</b>")
}
#[test]
fn action_states_are_reported() {
let mut model = ComposerModel::new();
model.replace_text(Utf16String::from("a"));
model.select(Location::from(0), Location::from(1));
model.bold();
assert!(model.action_is_reversed(ComposerAction::Bold));
assert!(model.action_is_enabled(ComposerAction::StrikeThrough));
assert!(model.action_is_disabled(ComposerAction::Redo));
}
#[test]
fn set_content_from_html_with_complex_html_has_proper_selection() {
let mut model = cm("|");
let result = model.set_content_from_html(&utf16(
"<blockquote>\
<p>Some</p>\
<p>multi-line</p>\
<p>quote</p>\
</blockquote>\
<p> </p>\
<p>Some text</p>\
<pre><code>A\n\tcode\nblock</code></pre>\
<p>Some <code>inline</code> code</p>",
));
assert!(result.is_ok());
assert_eq!(
tx(&model),
"<blockquote>\
<p>Some</p><p>multi-line</p><p>quote</p>\
</blockquote>\
<p> </p>\
<p>Some text</p>\
<pre><code>A\n\tcode\nblock</code></pre>\
<p>Some <code>inline</code> code|</p>"
);
}
}