1use std::rc::Rc;
4
5use cosmic_text::Cursor;
6use crabshell_reactive::Signal;
7
8use crate::cx::Cx;
9use crate::edit::{Edit, grapheme_start, graphemes_before};
10use crate::geometry::{Point, Rect};
11use crate::input::Handler;
12use crate::prop::{IntoProp, Prop};
13use crate::style::Style;
14use crate::text::TextNode;
15use crate::tree::{NodeKind, borrow};
16use crate::widgets::{Common, Element, ElementKind, Widget, visibility_methods};
17use crate::window::Window;
18
19const DOT: char = '•';
21
22pub(crate) const DEFAULT_WIDTH: f32 = 200.0;
24
25pub(crate) type AcceptHandler = Rc<Handler<dyn Fn(&Cx, &str)>>;
26
27pub(crate) struct InputProps {
28 pub(crate) text: Signal<String>,
29 pub(crate) placeholder: Option<Prop<String>>,
30 pub(crate) password: Option<Prop<bool>>,
31 pub(crate) focus: Option<Prop<bool>>,
32 pub(crate) on_accept: Option<AcceptHandler>,
33}
34
35pub struct TextInput {
54 input: InputProps,
55 common: Common,
56}
57
58impl TextInput {
59 pub fn new(text: Signal<String>) -> TextInput {
61 TextInput {
62 input: InputProps {
63 text,
64 placeholder: None,
65 password: None,
66 focus: None,
67 on_accept: None,
68 },
69 common: Common::default(),
70 }
71 }
72
73 pub fn placeholder(mut self, text: impl IntoProp<String>) -> TextInput {
75 self.input.placeholder = Some(text.into_prop());
76 self
77 }
78
79 pub fn password(mut self, password: impl IntoProp<bool>) -> TextInput {
82 self.input.password = Some(password.into_prop());
83 self
84 }
85
86 pub fn focus(mut self, focus: impl IntoProp<bool>) -> TextInput {
89 self.input.focus = Some(focus.into_prop());
90 self
91 }
92
93 pub fn on_accept(mut self, handler: impl Fn(&Cx, &str) + 'static) -> TextInput {
95 self.input.on_accept = Some(Rc::new(Handler::new(handler)));
96 self
97 }
98
99 pub fn style(mut self, style: impl IntoProp<Style>) -> TextInput {
101 self.common.style = Some(style.into_prop());
102 self
103 }
104
105 visibility_methods!();
106}
107
108impl Widget for TextInput {
109 fn into_element(self: Box<Self>) -> Element {
110 Element {
111 name: "TextInput",
112 common: self.common,
113 kind: ElementKind::Input(Box::new(self.input)),
114 children: Vec::new(),
115 }
116 }
117}
118
119#[derive(Clone, Debug, PartialEq, Eq)]
122pub struct Preedit {
123 pub text: String,
125 pub cursor: Option<(usize, usize)>,
127}
128
129#[derive(Clone, Debug, PartialEq)]
131pub struct FieldState {
132 pub field: u64,
134 pub text: String,
136 pub cursor: usize,
138 pub anchor: usize,
140 pub caret: Rect,
142}
143
144impl Window {
145 pub fn field(&self) -> Option<FieldState> {
148 let tree = self.tree.borrow();
149 if !tree.keyboard.entered {
150 return None;
151 }
152 let id = tree.keyboard.focused?;
153 let NodeKind::Input(input) = &tree.node(id)?.kind else {
154 return None;
155 };
156 (!input.password).then(|| FieldState {
157 field: u64::from(id),
158 text: input.edit.text.clone(),
159 cursor: input.edit.cursor,
160 anchor: input.edit.anchor.unwrap_or(input.edit.cursor),
161 caret: tree.window_rect(id, input.caret),
162 })
163 }
164
165 pub fn commit_text(&self, text: &str) {
168 let text = text.replace(['\n', '\r'], " ");
169 self.edit_field(|edit| edit.insert(&text));
170 }
171
172 pub fn paste(&self, text: &str) {
176 if text.is_empty() {
178 return;
179 }
180 let text = text.replace(['\n', '\r'], " ");
181 self.change_field(true, |edit| edit.insert(&text));
182 }
183
184 pub fn delete_around(&self, before: usize, after: usize) {
189 self.edit_field(|edit| {
190 let selected = edit.selection().unwrap_or(edit.cursor..edit.cursor);
191 let start = selected.start.saturating_sub(before);
192 let end = selected.end.saturating_add(after).min(edit.text.len());
193 if !(edit.text.is_char_boundary(start) && edit.text.is_char_boundary(end)) {
194 return;
195 }
196 edit.text.replace_range(selected.end..end, "");
197 edit.text.replace_range(start..selected.start, "");
198 let removed = selected.start - start;
199 edit.cursor -= removed;
200 edit.anchor = edit.anchor.map(|anchor| anchor - removed);
201 });
202 }
203
204 pub fn set_preedit(&self, preedit: Option<Preedit>) {
207 let preedit = preedit.filter(|preedit| !preedit.text.is_empty());
208 if preedit.is_some() {
209 self.edit_field(|edit| {
210 if edit.selection().is_some() {
211 edit.insert("");
212 }
213 });
214 }
215 let mut tree = borrow(&self.tree);
216 let Some(id) = tree.keyboard.focused else {
217 return;
218 };
219 if matches!(tree.node(id).map(|node| &node.kind), Some(NodeKind::Input(input)) if input.password)
220 {
221 return;
222 }
223 tree.update_input(id, |input| {
224 input.preedit = preedit;
225 input.refresh();
226 });
227 }
228
229 fn edit_field(&self, change: impl FnOnce(&mut Edit)) {
233 self.change_field(false, change);
234 }
235
236 fn change_field(&self, passwords: bool, change: impl FnOnce(&mut Edit)) {
239 let write = {
240 let mut tree = borrow(&self.tree);
241 let Some(id) = tree.keyboard.focused else {
242 return;
243 };
244 let before = match tree.node(id).map(|node| &node.kind) {
245 Some(NodeKind::Input(input)) if passwords || !input.password => input.edit.text.clone(),
246 _ => return,
247 };
248 let mut write = None;
249 tree.update_input(id, |input| {
250 change(&mut input.edit);
251 input.refresh();
252 if input.edit.text != before {
253 write = Some((input.signal, input.edit.text.clone()));
254 }
255 });
256 write
257 };
258 if let Some((signal, text)) = write {
259 signal.try_set(text);
261 }
262 }
263}
264
265pub(crate) struct InputNode {
267 pub(crate) text: TextNode,
269 pub(crate) edit: Edit,
270 pub(crate) signal: Signal<String>,
272 pub(crate) placeholder: String,
273 pub(crate) password: bool,
274 pub(crate) focused: bool,
276 pub(crate) wants_focus: bool,
279 pub(crate) scroll: f32,
281 pub(crate) caret: Rect,
284 pub(crate) selection: Vec<Rect>,
286 pub(crate) area: Rect,
288 pub(crate) preedit: Option<Preedit>,
290 pub(crate) underline: Vec<Rect>,
292 pub(crate) on_accept: Signal<Option<AcceptHandler>>,
295}
296
297impl InputNode {
298 pub(crate) fn new(signal: Signal<String>, on_accept: Signal<Option<AcceptHandler>>) -> InputNode {
299 InputNode {
300 text: TextNode::new(),
301 edit: Edit::default(),
302 signal,
303 placeholder: String::new(),
304 password: false,
305 focused: false,
306 wants_focus: false,
307 scroll: 0.0,
308 caret: Rect::default(),
309 selection: Vec::new(),
310 area: Rect::default(),
311 preedit: None,
312 underline: Vec::new(),
313 on_accept,
314 }
315 }
316
317 pub(crate) fn showing_placeholder(&self) -> bool {
319 self.edit.text.is_empty() && self.preedit.is_none()
320 }
321
322 fn preedit_len(&self) -> usize {
324 self
325 .preedit
326 .as_ref()
327 .map_or(0, |preedit| preedit.text.len())
328 }
329
330 pub(crate) fn refresh(&mut self) -> bool {
333 let shown = if self.showing_placeholder() {
334 self.placeholder.clone()
335 } else if self.password {
336 DOT
337 .to_string()
338 .repeat(graphemes_before(&self.edit.text, self.edit.text.len()))
339 } else if let Some(preedit) = &self.preedit {
340 let (before, after) = self.edit.text.split_at(self.edit.cursor);
341 format!("{before}{}{after}", preedit.text)
342 } else {
343 self.edit.text.clone()
344 };
345 self.text.set_content(shown)
346 }
347
348 fn shown_index(&self, at: usize) -> usize {
350 if self.showing_placeholder() {
351 0
352 } else if self.password {
353 graphemes_before(&self.edit.text, at) * DOT.len_utf8()
354 } else if at > self.edit.cursor {
355 at + self.preedit_len()
356 } else {
357 at
358 }
359 }
360
361 fn text_index(&self, at: usize) -> usize {
363 if self.showing_placeholder() {
364 0
365 } else if self.password {
366 grapheme_start(&self.edit.text, at / DOT.len_utf8())
367 } else if at <= self.edit.cursor {
368 at
369 } else {
370 let after = at.saturating_sub(self.preedit_len()).max(self.edit.cursor);
372 after.min(self.edit.text.len())
373 }
374 }
375
376 fn x_at(&self, at: usize) -> f32 {
379 self
380 .text
381 .runs()
382 .next()
383 .and_then(|run| run.cursor_position(&Cursor::new(0, at)))
384 .unwrap_or(0.0)
385 }
386
387 pub(crate) fn place(&mut self, content: Rect) {
390 let at = self.shown_index(self.edit.cursor);
391 let caret = match &self.preedit {
392 Some(preedit) => {
393 at + preedit
394 .cursor
395 .map_or(preedit.text.len(), |(start, _)| start)
396 }
397 None => at,
398 };
399 let caret = self.x_at(caret);
400 let width = self.text.runs().next().map_or(0.0, |run| run.line_w);
401 let room = (content.width - 1.0).max(0.0);
403 let mut scroll = self.scroll.min((width - room).max(0.0));
404 if caret - scroll > room {
405 scroll = caret - room;
406 }
407 if caret < scroll {
408 scroll = caret;
409 }
410 self.scroll = scroll.max(0.0);
411 self.text.origin.x = content.x - self.scroll;
412 let origin = self.text.origin;
413 let height = self
414 .text
415 .runs()
416 .next()
417 .map_or(content.height, |run| run.line_height);
418 self.caret = Rect::new(origin.x + caret, origin.y, 1.0, height);
419 self.area = content;
420 self.selection = match (self.edit.selection(), self.text.runs().next()) {
421 (Some(range), Some(run)) => {
422 let start = Cursor::new(0, self.shown_index(range.start));
423 let end = Cursor::new(0, self.shown_index(range.end));
424 run
425 .highlight(start, end)
426 .map(|(x, width)| Rect::new(origin.x + x, origin.y, width, height))
427 .collect()
428 }
429 _ => Vec::new(),
430 };
431 self.underline = match (&self.preedit, self.text.runs().next()) {
432 (Some(preedit), Some(run)) => run
433 .highlight(Cursor::new(0, at), Cursor::new(0, at + preedit.text.len()))
434 .map(|(x, width)| Rect::new(origin.x + x, origin.y + height - 1.0, width, 1.0))
435 .collect(),
436 _ => Vec::new(),
437 };
438 }
439
440 pub(crate) fn hit(&self, point: Point) -> usize {
442 let origin = self.text.origin;
443 let at = self
444 .text
445 .buffer
446 .hit(point.x - origin.x, point.y - origin.y)
447 .map_or(0, |cursor| cursor.index);
448 self.text_index(at)
449 }
450}