@mun-ui/ui 0.0.0-stage β†’ 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (158) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +104 -2
  3. package/bin/compile.mjs +38 -0
  4. package/bin/dev-protocol.mjs +94 -0
  5. package/bin/formatter.mjs +109 -0
  6. package/bin/hot-reload.mjs +38 -0
  7. package/bin/mun.mjs +521 -0
  8. package/bin/native.mjs +133 -0
  9. package/bin/pnpm-workspace.mjs +58 -0
  10. package/bin/program-patch.mjs +104 -0
  11. package/bin/project.mjs +322 -0
  12. package/bin/watch.mjs +316 -0
  13. package/bin/workflow.mjs +261 -0
  14. package/dist/astro.d.ts +3 -0
  15. package/dist/astro.d.ts.map +1 -0
  16. package/dist/astro.js +3 -0
  17. package/dist/astro.js.map +1 -0
  18. package/dist/closures.d.ts +2 -0
  19. package/dist/closures.d.ts.map +1 -0
  20. package/dist/closures.js +2 -0
  21. package/dist/closures.js.map +1 -0
  22. package/dist/compiler/index.d.ts +2 -0
  23. package/dist/compiler/index.d.ts.map +1 -0
  24. package/dist/compiler/index.js +2 -0
  25. package/dist/compiler/index.js.map +1 -0
  26. package/dist/core.d.ts +3 -0
  27. package/dist/core.d.ts.map +1 -0
  28. package/dist/core.js +3 -0
  29. package/dist/core.js.map +1 -0
  30. package/dist/experimental.d.ts +2 -0
  31. package/dist/experimental.d.ts.map +1 -0
  32. package/dist/experimental.js +2 -0
  33. package/dist/experimental.js.map +1 -0
  34. package/dist/index.d.ts +3 -0
  35. package/dist/index.d.ts.map +1 -0
  36. package/dist/index.js +3 -0
  37. package/dist/index.js.map +1 -0
  38. package/dist/jsx-dev-runtime.d.ts +2 -0
  39. package/dist/jsx-dev-runtime.d.ts.map +1 -0
  40. package/dist/jsx-dev-runtime.js +2 -0
  41. package/dist/jsx-dev-runtime.js.map +1 -0
  42. package/dist/jsx-runtime.d.ts +2 -0
  43. package/dist/jsx-runtime.d.ts.map +1 -0
  44. package/dist/jsx-runtime.js +2 -0
  45. package/dist/jsx-runtime.js.map +1 -0
  46. package/dist/legacy.d.ts +3 -0
  47. package/dist/legacy.d.ts.map +1 -0
  48. package/dist/legacy.js +3 -0
  49. package/dist/legacy.js.map +1 -0
  50. package/dist/mun.d.ts +5 -0
  51. package/dist/mun.d.ts.map +1 -0
  52. package/dist/mun.js +4 -0
  53. package/dist/mun.js.map +1 -0
  54. package/dist/progressive-blur/index.d.ts +8 -0
  55. package/dist/progressive-blur/index.d.ts.map +1 -0
  56. package/dist/progressive-blur/index.js +8 -0
  57. package/dist/progressive-blur/index.js.map +1 -0
  58. package/dist/progressive-blur/plan.d.ts +3 -0
  59. package/dist/progressive-blur/plan.d.ts.map +1 -0
  60. package/dist/progressive-blur/plan.js +3 -0
  61. package/dist/progressive-blur/plan.js.map +1 -0
  62. package/dist/react-types.d.ts +2 -0
  63. package/dist/react-types.d.ts.map +1 -0
  64. package/dist/react-types.js +2 -0
  65. package/dist/react-types.js.map +1 -0
  66. package/dist/rendering-quality.d.ts +4 -0
  67. package/dist/rendering-quality.d.ts.map +1 -0
  68. package/dist/rendering-quality.js +4 -0
  69. package/dist/rendering-quality.js.map +1 -0
  70. package/dist/state.d.ts +2 -0
  71. package/dist/state.d.ts.map +1 -0
  72. package/dist/state.js +2 -0
  73. package/dist/state.js.map +1 -0
  74. package/dist/types.d.ts +2 -0
  75. package/dist/types.d.ts.map +1 -0
  76. package/dist/types.js +2 -0
  77. package/dist/types.js.map +1 -0
  78. package/dist/vite.d.ts +2 -0
  79. package/dist/vite.d.ts.map +1 -0
  80. package/dist/vite.js +2 -0
  81. package/dist/vite.js.map +1 -0
  82. package/editors/install.mjs +102 -0
  83. package/editors/lsp/mun-lsp.mjs +123 -0
  84. package/editors/lsp/service.mjs +306 -0
  85. package/editors/lsp/source.mjs +58 -0
  86. package/editors/vscode/client.mjs +40 -0
  87. package/editors/vscode/dev-client.mjs +83 -0
  88. package/editors/vscode/discovery.mjs +46 -0
  89. package/editors/vscode/export.mjs +42 -0
  90. package/editors/vscode/extension.cjs +226 -0
  91. package/editors/vscode/language-configuration.json +15 -0
  92. package/editors/vscode/package.json +119 -0
  93. package/editors/vscode/protocol.mjs +29 -0
  94. package/editors/vscode/syntaxes/mun.tmLanguage.json +130 -0
  95. package/native/Cargo.lock +3581 -0
  96. package/native/Cargo.toml +21 -0
  97. package/native/README.md +21 -0
  98. package/native/mun-native/Cargo.toml +23 -0
  99. package/native/mun-native/src/accessibility.rs +738 -0
  100. package/native/mun-native/src/dev.rs +604 -0
  101. package/native/mun-native/src/lib.rs +2676 -0
  102. package/native/mun-native/src/main.rs +204 -0
  103. package/native/mun-native/src/offscreen.rs +393 -0
  104. package/native/mun-native/src/rect.wgsl +63 -0
  105. package/native/mun-native/src/text.rs +310 -0
  106. package/native/mun-native/tests/offscreen_rendering.rs +161 -0
  107. package/native/mun-native/tests/stress.rs +408 -0
  108. package/native/mun-native/tests/window_lifecycle.rs +183 -0
  109. package/native/mun-runtime/Cargo.toml +13 -0
  110. package/native/mun-runtime/src/accessibility.rs +193 -0
  111. package/native/mun-runtime/src/collection.rs +1073 -0
  112. package/native/mun-runtime/src/gesture.rs +1070 -0
  113. package/native/mun-runtime/src/input.rs +325 -0
  114. package/native/mun-runtime/src/ir.rs +782 -0
  115. package/native/mun-runtime/src/kinetics.rs +500 -0
  116. package/native/mun-runtime/src/layout.rs +173 -0
  117. package/native/mun-runtime/src/layout_cache.rs +209 -0
  118. package/native/mun-runtime/src/lib.rs +49 -0
  119. package/native/mun-runtime/src/motion.rs +1162 -0
  120. package/native/mun-runtime/src/retained.rs +574 -0
  121. package/native/mun-runtime/src/runtime.rs +7078 -0
  122. package/native/mun-runtime/src/scene.rs +530 -0
  123. package/native/mun-runtime/src/scroll.rs +521 -0
  124. package/native/mun-runtime/src/scroll_view.rs +220 -0
  125. package/native/mun-runtime/src/text_edit.rs +670 -0
  126. package/native/mun-runtime/src/timeline.rs +1534 -0
  127. package/native/mun-runtime/src/validate.rs +677 -0
  128. package/native/mun-runtime/tests/accessibility_semantics.rs +168 -0
  129. package/native/mun-runtime/tests/compiler_contract.rs +110 -0
  130. package/native/mun-runtime/tests/flexible_frames.rs +47 -0
  131. package/native/mun-runtime/tests/hot_update.rs +367 -0
  132. package/native/mun-runtime/tests/incremental_runtime.rs +323 -0
  133. package/native/mun-runtime/tests/ir_validation.rs +167 -0
  134. package/native/mun-runtime/tests/keyed_collections.rs +251 -0
  135. package/native/mun-runtime/tests/native_controls_style.rs +491 -0
  136. package/native/mun-runtime/tests/native_demo.rs +285 -0
  137. package/native/mun-runtime/tests/native_layout_style.rs +175 -0
  138. package/native/mun-runtime/tests/native_settings_pane.rs +152 -0
  139. package/native/mun-runtime/tests/scroll_view.rs +403 -0
  140. package/native/mun-runtime/tests/text_editing.rs +491 -0
  141. package/package.json +210 -3
  142. package/schemas/README.md +19 -0
  143. package/schemas/semantic-ui-ir-v1.schema.json +1972 -0
  144. package/templates/native/App.mun +15 -0
  145. package/templates/native/gitignore +3 -0
  146. package/templates/native/mun.toml +8 -0
  147. package/templates/project/gitignore +5 -0
  148. package/templates/project/index.html +13 -0
  149. package/templates/project/package.json +21 -0
  150. package/templates/project/src/App.mun +13 -0
  151. package/templates/project/src/index.css +21 -0
  152. package/templates/project/src/main.ts +5 -0
  153. package/templates/project/tsconfig.json +20 -0
  154. package/templates/project/vite.config.ts +6 -0
  155. package/templates/vite/src/App.css +134 -0
  156. package/templates/vite/src/App.tsx +91 -0
  157. package/templates/vite/src/index.css +23 -0
  158. package/templates/vite/vite.config.ts +10 -0
@@ -0,0 +1,670 @@
1
+ //! Platform-neutral single-line editing.
2
+ //!
3
+ //! All public offsets count Unicode scalar values, never UTF-8 bytes or UTF-16
4
+ //! units; platform adapters normalize their offsets before reaching this layer.
5
+ //! Every committed cursor/anchor position additionally lies on an extended
6
+ //! grapheme cluster boundary, so ordinary movement and deletion never split a
7
+ //! combining sequence, decomposed Hangul syllable, emoji modifier/ZWJ sequence
8
+ //! or regional-indicator flag. Word navigation is a separate operation over
9
+ //! Unicode word boundaries and never redefines character movement.
10
+ use unicode_segmentation::UnicodeSegmentation;
11
+
12
+ #[derive(Clone, Debug, PartialEq, Eq)]
13
+ pub struct Composition {
14
+ pub text: String,
15
+ /// Selection inside the preedit, in Unicode scalar offsets.
16
+ pub selection: Option<(usize, usize)>,
17
+ }
18
+
19
+ #[derive(Clone, Debug, PartialEq, Eq)]
20
+ pub enum TextEdit {
21
+ Insert(String),
22
+ /// Previous/next extended grapheme cluster.
23
+ Left {
24
+ select: bool,
25
+ },
26
+ Right {
27
+ select: bool,
28
+ },
29
+ /// Previous word start / next word end (Unicode word boundaries).
30
+ WordLeft {
31
+ select: bool,
32
+ },
33
+ WordRight {
34
+ select: bool,
35
+ },
36
+ Home {
37
+ select: bool,
38
+ },
39
+ End {
40
+ select: bool,
41
+ },
42
+ SelectAll,
43
+ /// Delete the selection, otherwise the previous grapheme cluster.
44
+ Backspace,
45
+ /// Delete the selection, otherwise the next grapheme cluster.
46
+ Delete,
47
+ DeleteWordBackward,
48
+ DeleteWordForward,
49
+ DeleteToStart,
50
+ /// Pointer placement. The offset is snapped to the nearest grapheme boundary;
51
+ /// `select` keeps the anchor (drag or shift-click extension).
52
+ PlaceCursor {
53
+ offset: usize,
54
+ select: bool,
55
+ },
56
+ CompositionStart,
57
+ CompositionUpdate(Composition),
58
+ CompositionCommit(String),
59
+ CompositionCancel,
60
+ /// Restore the state before the last edit group (typing runs coalesce).
61
+ Undo,
62
+ Redo,
63
+ }
64
+
65
+ #[derive(Clone, Debug, Default, PartialEq, Eq)]
66
+ struct Snapshot {
67
+ text: String,
68
+ anchor: usize,
69
+ cursor: usize,
70
+ }
71
+
72
+ /// Which edit group the last recorded undo step belongs to.
73
+ #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
74
+ enum Group {
75
+ #[default]
76
+ None,
77
+ Typing,
78
+ Deleting,
79
+ }
80
+
81
+ const UNDO_LIMIT: usize = 200;
82
+
83
+ /// Scalar offsets of every extended grapheme cluster boundary, including 0 and
84
+ /// the scalar length.
85
+ pub fn grapheme_boundaries(text: &str) -> Vec<usize> {
86
+ let mut boundaries = Vec::with_capacity(text.len() + 1);
87
+ let mut scalar = 0;
88
+ boundaries.push(0);
89
+ for grapheme in text.graphemes(true) {
90
+ scalar += grapheme.chars().count();
91
+ boundaries.push(scalar);
92
+ }
93
+ boundaries
94
+ }
95
+
96
+ /// Scalar ranges of Unicode words (letters/numbers/ideographs; separators excluded).
97
+ pub fn word_ranges(text: &str) -> Vec<std::ops::Range<usize>> {
98
+ let mut output = Vec::new();
99
+ let mut byte_cursor = 0;
100
+ let mut scalar_cursor = 0;
101
+ for (byte, word) in text.unicode_word_indices() {
102
+ scalar_cursor += text[byte_cursor..byte].chars().count();
103
+ let len = word.chars().count();
104
+ output.push(scalar_cursor..scalar_cursor + len);
105
+ scalar_cursor += len;
106
+ byte_cursor = byte + word.len();
107
+ }
108
+ output
109
+ }
110
+
111
+ pub fn scalar_to_byte(text: &str, scalar: usize) -> usize {
112
+ text.char_indices()
113
+ .nth(scalar)
114
+ .map_or(text.len(), |(byte, _)| byte)
115
+ }
116
+
117
+ #[derive(Clone, Debug, Default, PartialEq, Eq)]
118
+ pub struct TextEditor {
119
+ text: String,
120
+ boundaries: Vec<usize>,
121
+ anchor: usize,
122
+ cursor: usize,
123
+ composition: Option<Composition>,
124
+ undo: Vec<Snapshot>,
125
+ redo: Vec<Snapshot>,
126
+ group: Group,
127
+ }
128
+
129
+ impl TextEditor {
130
+ pub fn new(text: String) -> Self {
131
+ let boundaries = grapheme_boundaries(&text);
132
+ let cursor = *boundaries.last().expect("boundary list always contains 0");
133
+ Self {
134
+ text,
135
+ boundaries,
136
+ anchor: cursor,
137
+ cursor,
138
+ composition: None,
139
+ undo: Vec::new(),
140
+ redo: Vec::new(),
141
+ group: Group::None,
142
+ }
143
+ }
144
+ pub fn text(&self) -> &str {
145
+ &self.text
146
+ }
147
+ pub fn cursor(&self) -> usize {
148
+ self.cursor
149
+ }
150
+ pub fn anchor(&self) -> usize {
151
+ self.anchor
152
+ }
153
+ pub fn selection(&self) -> std::ops::Range<usize> {
154
+ self.anchor.min(self.cursor)..self.anchor.max(self.cursor)
155
+ }
156
+ pub fn composition(&self) -> Option<&Composition> {
157
+ self.composition.as_ref()
158
+ }
159
+ pub fn selected_text(&self) -> &str {
160
+ let range = self.selection();
161
+ &self.text[self.byte(range.start)..self.byte(range.end)]
162
+ }
163
+ fn len(&self) -> usize {
164
+ *self
165
+ .boundaries
166
+ .last()
167
+ .expect("boundary list always contains 0")
168
+ }
169
+ /// An external binding change invalidates preedit and collapses selection.
170
+ /// The binding mirrors `presentation_text`; only an external change to it
171
+ /// resets the editor.
172
+ pub fn synchronize(&mut self, text: &str) {
173
+ if self.presentation_text() != text {
174
+ *self = Self::new(text.to_owned());
175
+ }
176
+ }
177
+ pub fn cancel_composition(&mut self) {
178
+ self.composition = None;
179
+ }
180
+ /// Text shown to the user: committed text with the active preedit replacing
181
+ /// the selection. Never written to the binding or accessibility value.
182
+ pub fn presentation_text(&self) -> String {
183
+ let Some(composition) = &self.composition else {
184
+ return self.text.clone();
185
+ };
186
+ let range = self.selection();
187
+ format!(
188
+ "{}{}{}",
189
+ &self.text[..self.byte(range.start)],
190
+ composition.text,
191
+ &self.text[self.byte(range.end)..]
192
+ )
193
+ }
194
+ /// Caret, selection and preedit ranges in presentation-text scalar offsets.
195
+ pub fn presentation_ranges(&self) -> PresentationRanges {
196
+ match &self.composition {
197
+ None => PresentationRanges {
198
+ caret: self.cursor,
199
+ selection: self.selection(),
200
+ preedit: None,
201
+ preedit_selection: None,
202
+ },
203
+ Some(composition) => {
204
+ let start = self.selection().start;
205
+ let len = composition.text.chars().count();
206
+ let (selection_start, selection_end) = composition.selection.unwrap_or((len, len));
207
+ let (a, b) = (
208
+ selection_start.min(selection_end).min(len),
209
+ selection_start.max(selection_end).min(len),
210
+ );
211
+ PresentationRanges {
212
+ caret: start + selection_end.min(len),
213
+ selection: start..start,
214
+ preedit: Some(start..start + len),
215
+ preedit_selection: (a != b).then(|| start + a..start + b),
216
+ }
217
+ }
218
+ }
219
+ }
220
+ fn byte(&self, scalar: usize) -> usize {
221
+ scalar_to_byte(&self.text, scalar)
222
+ }
223
+ fn previous_boundary(&self, offset: usize) -> usize {
224
+ self.boundaries
225
+ .iter()
226
+ .rev()
227
+ .copied()
228
+ .find(|boundary| *boundary < offset)
229
+ .unwrap_or(0)
230
+ }
231
+ fn next_boundary(&self, offset: usize) -> usize {
232
+ self.boundaries
233
+ .iter()
234
+ .copied()
235
+ .find(|boundary| *boundary > offset)
236
+ .unwrap_or(self.len())
237
+ }
238
+ fn nearest_boundary(&self, offset: usize) -> usize {
239
+ let previous = self
240
+ .boundaries
241
+ .iter()
242
+ .rev()
243
+ .copied()
244
+ .find(|boundary| *boundary <= offset)
245
+ .unwrap_or(0);
246
+ let next = self.next_boundary(previous);
247
+ if offset - previous <= next.saturating_sub(offset) {
248
+ previous
249
+ } else {
250
+ next
251
+ }
252
+ }
253
+ fn previous_word_start(&self, offset: usize) -> usize {
254
+ word_ranges(&self.text)
255
+ .into_iter()
256
+ .rev()
257
+ .map(|range| range.start)
258
+ .find(|start| *start < offset)
259
+ .unwrap_or(0)
260
+ }
261
+ fn next_word_end(&self, offset: usize) -> usize {
262
+ word_ranges(&self.text)
263
+ .into_iter()
264
+ .map(|range| range.end)
265
+ .find(|end| *end > offset)
266
+ .unwrap_or(self.len())
267
+ }
268
+ fn replace(&mut self, text: &str) {
269
+ let range = self.selection();
270
+ let start = self.byte(range.start);
271
+ let end = self.byte(range.end);
272
+ self.text.replace_range(start..end, text);
273
+ self.boundaries = grapheme_boundaries(&self.text);
274
+ // Inserted combining marks can merge with the preceding cluster; the end of
275
+ // the inserted text is still a cluster boundary in the new text or snaps to it.
276
+ let cursor = self.text[..start + text.len()].chars().count();
277
+ self.cursor = self.nearest_boundary(cursor);
278
+ self.anchor = self.cursor;
279
+ }
280
+ fn move_to(&mut self, cursor: usize, select: bool) {
281
+ self.cursor = cursor.min(self.len());
282
+ if !select {
283
+ self.anchor = self.cursor;
284
+ }
285
+ }
286
+ fn delete_to(&mut self, target: usize) {
287
+ if self.selection().is_empty() {
288
+ self.anchor = target;
289
+ }
290
+ self.replace("");
291
+ }
292
+ /// Returns whether committed text changed. Preedit never mutates the binding.
293
+ pub fn apply(&mut self, edit: TextEdit) -> bool {
294
+ let before = self.text.clone();
295
+ let snapshot = Snapshot {
296
+ text: before.clone(),
297
+ anchor: self.anchor,
298
+ cursor: self.cursor,
299
+ };
300
+ // Consecutive typing (or deleting) without caret movement is one undo
301
+ // step; a word boundary after typing starts a new one.
302
+ let group = match &edit {
303
+ TextEdit::Insert(text) | TextEdit::CompositionCommit(text) => {
304
+ if text.chars().all(char::is_whitespace) {
305
+ Group::None
306
+ } else {
307
+ Group::Typing
308
+ }
309
+ }
310
+ TextEdit::Backspace | TextEdit::Delete => Group::Deleting,
311
+ _ => Group::None,
312
+ };
313
+ match edit {
314
+ TextEdit::Undo | TextEdit::Redo if self.composition.is_some() => return false,
315
+ TextEdit::Undo => {
316
+ let Some(previous) = self.undo.pop() else {
317
+ return false;
318
+ };
319
+ self.redo.push(snapshot);
320
+ self.restore(previous);
321
+ self.group = Group::None;
322
+ return true;
323
+ }
324
+ TextEdit::Redo => {
325
+ let Some(next) = self.redo.pop() else {
326
+ return false;
327
+ };
328
+ self.undo.push(snapshot);
329
+ self.restore(next);
330
+ self.group = Group::None;
331
+ return true;
332
+ }
333
+ _ => {}
334
+ }
335
+ let composing = self.composition.is_some();
336
+ match edit {
337
+ TextEdit::CompositionStart => {
338
+ self.composition = Some(Composition {
339
+ text: String::new(),
340
+ selection: None,
341
+ })
342
+ }
343
+ TextEdit::CompositionUpdate(mut composition) => {
344
+ let len = composition.text.chars().count();
345
+ composition.selection =
346
+ composition.selection.map(|(a, b)| (a.min(len), b.min(len)));
347
+ self.composition = Some(composition);
348
+ }
349
+ TextEdit::CompositionCancel => self.cancel_composition(),
350
+ TextEdit::CompositionCommit(text) => {
351
+ self.cancel_composition();
352
+ self.replace(&text);
353
+ }
354
+ // A composing IME owns editing keys; the host forwards its eventual
355
+ // commit/cancel rather than letting arrows/backspace corrupt preedit.
356
+ _ if self.composition.is_some() => {}
357
+ TextEdit::Insert(text) => self.replace(&text),
358
+ TextEdit::Left { select } => {
359
+ let cursor = if !select && !self.selection().is_empty() {
360
+ self.selection().start
361
+ } else {
362
+ self.previous_boundary(self.cursor)
363
+ };
364
+ self.move_to(cursor, select);
365
+ }
366
+ TextEdit::Right { select } => {
367
+ let cursor = if !select && !self.selection().is_empty() {
368
+ self.selection().end
369
+ } else {
370
+ self.next_boundary(self.cursor)
371
+ };
372
+ self.move_to(cursor, select);
373
+ }
374
+ TextEdit::WordLeft { select } => {
375
+ let cursor = self.previous_word_start(self.cursor);
376
+ self.move_to(cursor, select);
377
+ }
378
+ TextEdit::WordRight { select } => {
379
+ let cursor = self.next_word_end(self.cursor);
380
+ self.move_to(cursor, select);
381
+ }
382
+ TextEdit::Home { select } => self.move_to(0, select),
383
+ TextEdit::End { select } => self.move_to(self.len(), select),
384
+ TextEdit::SelectAll => {
385
+ self.anchor = 0;
386
+ self.cursor = self.len();
387
+ }
388
+ TextEdit::Backspace => self.delete_to(self.previous_boundary(self.cursor)),
389
+ TextEdit::Delete => self.delete_to(self.next_boundary(self.cursor)),
390
+ TextEdit::DeleteWordBackward => self.delete_to(self.previous_word_start(self.cursor)),
391
+ TextEdit::DeleteWordForward => self.delete_to(self.next_word_end(self.cursor)),
392
+ TextEdit::DeleteToStart => self.delete_to(0),
393
+ TextEdit::PlaceCursor { offset, select } => {
394
+ let cursor = self.nearest_boundary(offset.min(self.len()));
395
+ self.move_to(cursor, select);
396
+ }
397
+ TextEdit::Undo | TextEdit::Redo => unreachable!("handled above"),
398
+ }
399
+ let changed = self.text != before;
400
+ if changed {
401
+ if group == Group::None || group != self.group {
402
+ self.undo.push(snapshot);
403
+ if self.undo.len() > UNDO_LIMIT {
404
+ self.undo.remove(0);
405
+ }
406
+ }
407
+ self.redo.clear();
408
+ self.group = group;
409
+ } else if !composing && !matches!(group, Group::Typing | Group::Deleting) {
410
+ // Caret movement or selection ends the current typing run.
411
+ self.group = Group::None;
412
+ }
413
+ changed
414
+ }
415
+
416
+ fn restore(&mut self, snapshot: Snapshot) {
417
+ self.boundaries = grapheme_boundaries(&snapshot.text);
418
+ self.text = snapshot.text;
419
+ self.anchor = snapshot.anchor.min(self.len());
420
+ self.cursor = snapshot.cursor.min(self.len());
421
+ self.composition = None;
422
+ }
423
+ }
424
+
425
+ /// Presentation-space editing ranges (scalar offsets into `presentation_text`).
426
+ #[derive(Clone, Debug, PartialEq, Eq)]
427
+ pub struct PresentationRanges {
428
+ pub caret: usize,
429
+ pub selection: std::ops::Range<usize>,
430
+ pub preedit: Option<std::ops::Range<usize>>,
431
+ pub preedit_selection: Option<std::ops::Range<usize>>,
432
+ }
433
+
434
+ #[cfg(test)]
435
+ mod tests {
436
+ use super::*;
437
+
438
+ fn edit(text: &str, edits: impl IntoIterator<Item = TextEdit>) -> TextEditor {
439
+ let mut editor = TextEditor::new(text.into());
440
+ for item in edits {
441
+ editor.apply(item);
442
+ }
443
+ editor
444
+ }
445
+
446
+ #[test]
447
+ fn unicode_selection_replacement_and_deletion() {
448
+ let mut editor = TextEditor::new("Aν•œπŸ˜€Z".into());
449
+ editor.apply(TextEdit::Left { select: false });
450
+ editor.apply(TextEdit::Left { select: true });
451
+ assert_eq!(editor.selected_text(), "πŸ˜€");
452
+ editor.apply(TextEdit::Insert("κΈ€".into()));
453
+ assert_eq!(editor.text(), "Aν•œκΈ€Z");
454
+ editor.apply(TextEdit::Backspace);
455
+ editor.apply(TextEdit::Delete);
456
+ assert_eq!(editor.text(), "Aν•œ");
457
+ editor.apply(TextEdit::Home { select: true });
458
+ assert_eq!(editor.selected_text(), "Aν•œ");
459
+ editor.apply(TextEdit::Delete);
460
+ assert_eq!(editor.text(), "");
461
+ }
462
+
463
+ #[test]
464
+ fn extended_grapheme_clusters_are_never_split() {
465
+ // Each case: text, expected cluster count. Left/Right/Backspace/Delete must
466
+ // treat every cluster as one visible character.
467
+ let cases = [
468
+ ("ν•œκ΅­μ–΄", 3), // Hangul syllables
469
+ ("\u{1112}\u{1161}\u{11AB}\u{1100}\u{1173}\u{11AF}", 2), // decomposed Hangul ν•œκΈ€
470
+ ("e\u{301}a\u{308}", 2), // combining accents Γ© Γ€
471
+ ("πŸ˜€πŸŽ‰", 2), // emoji
472
+ ("πŸ‘πŸ½πŸ‘‹πŸΏ", 2), // skin-tone modifiers
473
+ ("πŸ‘©β€πŸ‘©β€πŸ‘§β€πŸ‘¦πŸ§‘β€πŸ’»", 2), // ZWJ sequences
474
+ ("πŸ‡°πŸ‡·πŸ‡―πŸ‡΅", 2), // regional-indicator flags
475
+ ("❀️☺️", 2), // emoji variation selectors
476
+ ("abν•œπŸ˜€\u{1112}\u{1161}e\u{301}", 6), // mixed ASCII/Korean/emoji
477
+ ];
478
+ for (text, clusters) in cases {
479
+ assert_eq!(grapheme_boundaries(text).len() - 1, clusters, "{text:?}");
480
+ let mut editor = TextEditor::new(text.into());
481
+ let mut positions = vec![editor.cursor()];
482
+ for _ in 0..clusters {
483
+ editor.apply(TextEdit::Left { select: false });
484
+ positions.push(editor.cursor());
485
+ }
486
+ assert_eq!(editor.cursor(), 0, "{text:?}");
487
+ positions.reverse();
488
+ assert_eq!(positions, grapheme_boundaries(text), "{text:?}");
489
+ for _ in 0..clusters {
490
+ editor.apply(TextEdit::Right { select: false });
491
+ }
492
+ assert_eq!(editor.cursor(), text.chars().count(), "{text:?}");
493
+
494
+ // Backspace from the end removes exactly one cluster at a time.
495
+ let mut remaining = text.to_owned();
496
+ for step in 0..clusters {
497
+ editor.apply(TextEdit::Backspace);
498
+ let graphemes = remaining.graphemes(true).collect::<Vec<_>>();
499
+ remaining = graphemes[..graphemes.len() - 1].concat();
500
+ assert_eq!(editor.text(), remaining, "{text:?} step {step}");
501
+ }
502
+ // Forward delete from the start likewise.
503
+ let mut editor = TextEditor::new(text.into());
504
+ editor.apply(TextEdit::Home { select: false });
505
+ editor.apply(TextEdit::Delete);
506
+ assert_eq!(
507
+ editor.text(),
508
+ text.graphemes(true).skip(1).collect::<String>(),
509
+ "{text:?}"
510
+ );
511
+ }
512
+ }
513
+
514
+ #[test]
515
+ fn selection_replacement_across_non_ascii_content() {
516
+ let mut editor = edit(
517
+ "abπŸ‘©β€πŸ‘©β€πŸ‘§ν•œ\u{1112}\u{1161}z",
518
+ [
519
+ TextEdit::Home { select: false },
520
+ TextEdit::Right { select: false },
521
+ TextEdit::Right { select: true },
522
+ TextEdit::Right { select: true },
523
+ TextEdit::Right { select: true },
524
+ TextEdit::Right { select: true },
525
+ ],
526
+ );
527
+ assert_eq!(editor.selected_text(), "bπŸ‘©β€πŸ‘©β€πŸ‘§ν•œ\u{1112}\u{1161}");
528
+ editor.apply(TextEdit::Insert("πŸ‡°πŸ‡·".into()));
529
+ assert_eq!(editor.text(), "aπŸ‡°πŸ‡·z");
530
+ assert_eq!(editor.cursor(), 3);
531
+ editor.apply(TextEdit::Left { select: true });
532
+ assert_eq!(editor.selected_text(), "πŸ‡°πŸ‡·");
533
+ }
534
+
535
+ #[test]
536
+ fn pointer_placement_snaps_inside_clusters_to_nearest_boundary() {
537
+ // "e\u{301}" occupies scalars 0..2; "πŸ‘πŸ½" occupies 2..4.
538
+ let mut editor = TextEditor::new("e\u{301}πŸ‘πŸ½x".into());
539
+ editor.apply(TextEdit::PlaceCursor {
540
+ offset: 1,
541
+ select: false,
542
+ });
543
+ assert_eq!(editor.cursor(), 0);
544
+ editor.apply(TextEdit::PlaceCursor {
545
+ offset: 3,
546
+ select: true,
547
+ });
548
+ assert!(editor.cursor() == 2 || editor.cursor() == 4);
549
+ assert_eq!(editor.anchor(), 0);
550
+ editor.apply(TextEdit::PlaceCursor {
551
+ offset: 99,
552
+ select: true,
553
+ });
554
+ assert_eq!(editor.selected_text(), "e\u{301}πŸ‘πŸ½x");
555
+ }
556
+
557
+ #[test]
558
+ fn combining_mark_insertion_keeps_cursor_on_cluster_boundary() {
559
+ let mut editor = TextEditor::new("ab".into());
560
+ editor.apply(TextEdit::Left { select: false });
561
+ editor.apply(TextEdit::Insert("\u{301}".into()));
562
+ assert_eq!(editor.text(), "a\u{301}b");
563
+ assert_eq!(editor.cursor(), 2);
564
+ editor.apply(TextEdit::Backspace);
565
+ assert_eq!(editor.text(), "b");
566
+ }
567
+
568
+ #[test]
569
+ fn word_navigation_is_distinct_from_grapheme_navigation() {
570
+ let mut editor = TextEditor::new("hello 세계 πŸ˜€ wΓΆrld".into());
571
+ editor.apply(TextEdit::WordLeft { select: false });
572
+ assert_eq!(editor.cursor(), 11);
573
+ editor.apply(TextEdit::WordLeft { select: false });
574
+ assert_eq!(editor.cursor(), 6);
575
+ editor.apply(TextEdit::WordRight { select: true });
576
+ assert_eq!(editor.selected_text(), "세계");
577
+ editor.apply(TextEdit::End { select: false });
578
+ editor.apply(TextEdit::DeleteWordBackward);
579
+ assert_eq!(editor.text(), "hello 세계 πŸ˜€ ");
580
+ editor.apply(TextEdit::DeleteToStart);
581
+ assert_eq!(editor.text(), "");
582
+ }
583
+
584
+ #[test]
585
+ fn hangul_preedit_does_not_commit_and_cancel_preserves_selection() {
586
+ let mut editor = TextEditor::new("old".into());
587
+ editor.apply(TextEdit::SelectAll);
588
+ for text in ["γ…Ž", "ν•˜", "ν•œ"] {
589
+ assert!(!editor.apply(TextEdit::CompositionUpdate(Composition {
590
+ text: text.into(),
591
+ selection: Some((1, 1))
592
+ })));
593
+ assert_eq!(editor.text(), "old");
594
+ assert_eq!(editor.presentation_text(), text);
595
+ }
596
+ editor.apply(TextEdit::Backspace);
597
+ assert_eq!(editor.text(), "old");
598
+ editor.apply(TextEdit::CompositionCancel);
599
+ assert_eq!(editor.selected_text(), "old");
600
+ assert!(editor.apply(TextEdit::CompositionCommit("ν•œ".into())));
601
+ assert_eq!(editor.text(), "ν•œ");
602
+ assert_eq!(editor.cursor(), 1);
603
+ }
604
+
605
+ #[test]
606
+ fn presentation_ranges_follow_preedit_and_its_selection() {
607
+ let mut editor = TextEditor::new("ab".into());
608
+ editor.apply(TextEdit::Left { select: false });
609
+ assert_eq!(editor.presentation_ranges().caret, 1);
610
+ editor.apply(TextEdit::CompositionUpdate(Composition {
611
+ text: "にほん".into(),
612
+ selection: Some((0, 2)),
613
+ }));
614
+ let ranges = editor.presentation_ranges();
615
+ assert_eq!(editor.presentation_text(), "aにほんb");
616
+ assert_eq!(ranges.preedit, Some(1..4));
617
+ assert_eq!(ranges.preedit_selection, Some(1..3));
618
+ assert_eq!(ranges.caret, 3);
619
+ assert_eq!(ranges.selection, 1..1);
620
+ }
621
+
622
+ #[test]
623
+ fn japanese_chinese_composition_and_external_change() {
624
+ let mut editor = TextEditor::new("".into());
625
+ for text in ["にほん", "ζ—₯本", "δΈ­ζ–‡"] {
626
+ editor.apply(TextEdit::CompositionUpdate(Composition {
627
+ text: text.into(),
628
+ selection: None,
629
+ }));
630
+ assert_eq!(editor.text(), "");
631
+ }
632
+ editor.synchronize("external");
633
+ assert!(editor.composition().is_none());
634
+ assert_eq!(editor.cursor(), 8);
635
+ }
636
+ }
637
+
638
+ #[cfg(test)]
639
+ mod undo_tests {
640
+ use super::*;
641
+
642
+ #[test]
643
+ fn undo_groups_typing_runs_and_redo_is_cleared_by_new_edits() {
644
+ let mut editor = TextEditor::new(String::new());
645
+ for text in ["ν•œ", "κ΅­", " ", "μ–΄"] {
646
+ editor.apply(TextEdit::CompositionCommit(text.into()));
647
+ }
648
+ editor.apply(TextEdit::Backspace);
649
+ assert_eq!(editor.text(), "ν•œκ΅­ ");
650
+ assert!(editor.apply(TextEdit::Undo));
651
+ assert_eq!(editor.text(), "ν•œκ΅­ μ–΄");
652
+ assert!(editor.apply(TextEdit::Undo));
653
+ assert_eq!(editor.text(), "ν•œκ΅­ ");
654
+ editor.apply(TextEdit::Undo);
655
+ editor.apply(TextEdit::Undo);
656
+ assert_eq!(editor.text(), "");
657
+ assert!(!editor.apply(TextEdit::Undo));
658
+ assert!(editor.apply(TextEdit::Redo));
659
+ assert_eq!(editor.text(), "ν•œκ΅­");
660
+ editor.apply(TextEdit::Insert("!".into()));
661
+ assert!(!editor.apply(TextEdit::Redo), "new edit clears redo");
662
+ // Undo never applies to an uncommitted composition.
663
+ editor.apply(TextEdit::CompositionUpdate(Composition {
664
+ text: "γ„±".into(),
665
+ selection: None,
666
+ }));
667
+ assert!(!editor.apply(TextEdit::Undo));
668
+ assert_eq!(editor.text(), "ν•œκ΅­!");
669
+ }
670
+ }