Skip to main content

crabshell_ui/
text_input.rs

1//! [`TextInput`], a one-line text field, and the field node it shares
2//! with [`TextArea`](crate::TextArea).
3
4use std::rc::Rc;
5
6use cosmic_text::{Affinity, FontSystem};
7use crabshell_reactive::Signal;
8
9use crate::cx::Cx;
10use crate::edit::{Edit, Keyed, grapheme_start, graphemes_before};
11use crate::geometry::{Point, Rect};
12use crate::input::Handler;
13use crate::keyboard::{Key, KeyEvent};
14use crate::prop::{IntoProp, Prop};
15use crate::select::{cursor_at, highlights, index_of};
16use crate::style::{Color, Style};
17use crate::text::{TextNode, TextRun};
18use crate::tree::{NodeKind, borrow};
19use crate::widgets::{Common, Element, ElementKind, Widget, visibility_methods};
20use crate::window::Window;
21
22/// What a password shows for each character.
23const DOT: char = '•';
24
25/// The width a field takes when nothing else sets one, in logical pixels.
26pub(crate) const DEFAULT_WIDTH: f32 = 200.0;
27
28pub(crate) type AcceptHandler = Rc<Handler<dyn Fn(&Cx, &str)>>;
29
30pub(crate) struct InputProps {
31  pub(crate) text: Signal<String>,
32  pub(crate) placeholder: Option<Prop<String>>,
33  pub(crate) password: Option<Prop<bool>>,
34  pub(crate) focus: Option<Prop<bool>>,
35  pub(crate) on_accept: Option<AcceptHandler>,
36  /// A text area: many lines.
37  pub(crate) multiline: bool,
38  pub(crate) wrap: Option<Prop<bool>>,
39  pub(crate) max_length: Option<Prop<Option<usize>>>,
40  pub(crate) read_only: Option<Prop<bool>>,
41  pub(crate) selection_color: Option<Prop<Option<Color>>>,
42  pub(crate) selected_text_color: Option<Prop<Option<Color>>>,
43}
44
45/// A one-line text field. It takes the keyboard focus when clicked, when
46/// Tab reaches it, or when [`focus`](Self::focus) says so, and edits the
47/// text in a shared signal: typing writes it, and setting it changes what
48/// the field shows. Arrows, Home and End move the caret, Shift selects,
49/// Ctrl moves and deletes by word, and Ctrl+A selects everything. Keys it
50/// doesn't use, such as Up, Down and Escape, go on to the window's
51/// `on_key`.
52///
53/// ```
54/// use crabshell_ui::{Cx, TextInput};
55///
56/// fn search(cx: &Cx) -> TextInput {
57///     let query = cx.signal(String::new());
58///     TextInput::new(query)
59///         .placeholder("Search")
60///         .on_accept(|_cx, text| println!("run {text}"))
61/// }
62/// ```
63pub struct TextInput {
64  input: InputProps,
65  common: Common,
66}
67
68impl TextInput {
69  /// A field editing `text`.
70  pub fn new(text: Signal<String>) -> TextInput {
71    TextInput {
72      input: InputProps {
73        text,
74        placeholder: None,
75        password: None,
76        focus: None,
77        on_accept: None,
78        multiline: false,
79        wrap: None,
80        max_length: None,
81        read_only: None,
82        selection_color: None,
83        selected_text_color: None,
84      },
85      common: Common::default(),
86    }
87  }
88
89  /// Sets the text shown, dimmed, while the field is empty.
90  pub fn placeholder(mut self, text: impl IntoProp<String>) -> TextInput {
91    self.input.placeholder = Some(text.into_prop());
92    self
93  }
94
95  /// Sets whether the field shows a dot for each character instead of
96  /// the text.
97  pub fn password(mut self, password: impl IntoProp<bool>) -> TextInput {
98    self.input.password = Some(password.into_prop());
99    self
100  }
101
102  /// Lets the field hold at most `max` characters, or any number with
103  /// `None`, the default. Typing, pasting and an input method stop
104  /// there, cutting what they bring between graphemes. Text set from
105  /// outside, or already there when the limit drops, is cut to it, and
106  /// the cut text is written back to the signal.
107  pub fn max_length(mut self, max: impl IntoProp<Option<usize>>) -> TextInput {
108    self.input.max_length = Some(max.into_prop());
109    self
110  }
111
112  /// While on, off by default, the field takes no edits: typing,
113  /// deleting, cutting, pasting and input methods leave it alone, and
114  /// their keys go on to the window's `on_key`. The caret, selection and
115  /// Ctrl+C still work, though a password never copies, Enter still runs
116  /// `on_accept`, and text set from outside still shows.
117  pub fn read_only(mut self, on: impl IntoProp<bool>) -> TextInput {
118    self.input.read_only = Some(on.into_prop());
119    self
120  }
121
122  /// Sets the color the selection is drawn in behind the text. By
123  /// default, or with `None`, it is the text's color at a third of its
124  /// alpha.
125  pub fn selection_color(mut self, color: impl IntoProp<Option<Color>>) -> TextInput {
126    self.input.selection_color = Some(color.into_prop());
127    self
128  }
129
130  /// Sets the color the selected text is drawn in, over any span or
131  /// link color. By default, or with `None`, it keeps its own color.
132  /// Underlines and strikethroughs keep theirs.
133  pub fn selected_text_color(mut self, color: impl IntoProp<Option<Color>>) -> TextInput {
134    self.input.selected_text_color = Some(color.into_prop());
135    self
136  }
137
138  /// Takes the keyboard focus whenever this turns true, as when a
139  /// launcher opens.
140  pub fn focus(mut self, focus: impl IntoProp<bool>) -> TextInput {
141    self.input.focus = Some(focus.into_prop());
142    self
143  }
144
145  /// Runs `handler` with the text when Enter is pressed in the field.
146  pub fn on_accept(mut self, handler: impl Fn(&Cx, &str) + 'static) -> TextInput {
147    self.input.on_accept = Some(Rc::new(Handler::new(handler)));
148    self
149  }
150
151  /// Sets the style. A field cuts its text to the inside of its border.
152  /// Its text takes the font, color, alignment, line height and
153  /// decorations it inherits or sets, as a [`Text`](crate::Text) does.
154  pub fn style(mut self, style: impl IntoProp<Style>) -> TextInput {
155    self.common.style = Some(style.into_prop());
156    self
157  }
158
159  visibility_methods!();
160}
161
162impl Widget for TextInput {
163  fn into_element(self: Box<Self>) -> Element {
164    Element {
165      name: "TextInput",
166      common: self.common,
167      kind: ElementKind::Input(Box::new(self.input)),
168      children: Vec::new(),
169    }
170  }
171}
172
173/// Text an input method is composing, shown at the caret, underlined,
174/// until it commits or drops it.
175#[derive(Clone, Debug, PartialEq, Eq)]
176pub struct Preedit {
177  /// The text.
178  pub text: String,
179  /// Where in `text`, in bytes, its own caret or selection is, if shown.
180  pub cursor: Option<(usize, usize)>,
181}
182
183/// The focused text field, as an input method needs it.
184#[derive(Clone, Debug, PartialEq)]
185pub struct FieldState {
186  /// Which field it is: another number when the focus moves to another.
187  pub field: u64,
188  /// The field's text.
189  pub text: String,
190  /// The caret, in bytes.
191  pub cursor: usize,
192  /// The other end of the selection, or the caret without one.
193  pub anchor: usize,
194  /// Where the caret is drawn, in window coordinates.
195  pub caret: Rect,
196  /// A [`TextArea`](crate::TextArea), whose text has line breaks.
197  pub multiline: bool,
198}
199
200impl Window {
201  /// The focused text field, while the window has the keyboard, for an
202  /// input method. Never a password, as input methods learn what is
203  /// typed, and never a read-only field, which takes no text.
204  pub fn field(&self) -> Option<FieldState> {
205    let tree = self.tree.borrow();
206    if !tree.keyboard.entered {
207      return None;
208    }
209    let id = tree.keyboard.focused?;
210    let NodeKind::Input(input) = &tree.node(id)?.kind else {
211      return None;
212    };
213    (!input.password && !input.edit.read_only).then(|| FieldState {
214      field: u64::from(id),
215      text: input.edit.text.clone(),
216      cursor: input.edit.cursor,
217      anchor: input.edit.anchor.unwrap_or(input.edit.cursor),
218      caret: tree.window_rect(id, input.caret),
219      multiline: input.edit.multiline,
220    })
221  }
222
223  /// Inserts `text` from an input method at the focused field's caret,
224  /// replacing its selection; in a one-line field, line breaks become
225  /// spaces. A password field takes nothing.
226  pub fn commit_text(&self, text: &str) {
227    self.edit_field(|edit| edit.insert(text));
228  }
229
230  /// Pastes `text` from the clipboard into the focused field, replacing
231  /// its selection; in a one-line field, line breaks become spaces.
232  /// Unlike an input method's text, a paste goes into a password field
233  /// too.
234  pub fn paste(&self, text: &str) {
235    // An empty clipboard pastes nothing, not even over the selection.
236    if text.is_empty() {
237      return;
238    }
239    self.change_field(true, |edit| edit.insert(text));
240  }
241
242  /// Deletes `before` bytes before the focused field's selection, or its
243  /// caret, and `after` bytes after it, for an input method; the
244  /// selection itself stays. Lengths that would split a character are
245  /// ignored.
246  pub fn delete_around(&self, before: usize, after: usize) {
247    self.edit_field(|edit| {
248      let selected = edit.selection().unwrap_or(edit.cursor..edit.cursor);
249      let start = selected.start.saturating_sub(before);
250      let end = selected.end.saturating_add(after).min(edit.text.len());
251      if !(edit.text.is_char_boundary(start) && edit.text.is_char_boundary(end)) {
252        return;
253      }
254      edit.text.replace_range(selected.end..end, "");
255      edit.text.replace_range(start..selected.start, "");
256      let removed = selected.start - start;
257      edit.cursor -= removed;
258      edit.anchor = edit.anchor.map(|anchor| anchor - removed);
259    });
260  }
261
262  /// Shows `preedit` at the focused field's caret, replacing its
263  /// selection, or clears it. A password field shows none.
264  pub fn set_preedit(&self, preedit: Option<Preedit>) {
265    let preedit = preedit.filter(|preedit| !preedit.text.is_empty());
266    if preedit.is_some() {
267      self.edit_field(|edit| {
268        if edit.selection().is_some() {
269          edit.insert("");
270        }
271      });
272    }
273    let mut tree = borrow(&self.tree);
274    let Some(id) = tree.keyboard.focused else {
275      return;
276    };
277    if matches!(tree.node(id).map(|node| &node.kind), Some(NodeKind::Input(input)) if input.password || input.edit.read_only)
278    {
279      return;
280    }
281    tree.update_input(id, |input| {
282      input.preedit = preedit;
283      input.refresh();
284    });
285  }
286
287  /// Changes the focused field's text with `change`, then writes it to
288  /// the field's signal once the tree is released. A password field is
289  /// left alone: input methods don't type in one.
290  fn edit_field(&self, change: impl FnOnce(&mut Edit)) {
291    self.change_field(false, change);
292  }
293
294  /// As [`edit_field`](Self::edit_field), into a password field too when
295  /// `passwords`. A read-only field is left alone.
296  fn change_field(&self, passwords: bool, change: impl FnOnce(&mut Edit)) {
297    let write = {
298      let mut tree = borrow(&self.tree);
299      let Some(id) = tree.keyboard.focused else {
300        return;
301      };
302      let before = match tree.node(id).map(|node| &node.kind) {
303        Some(NodeKind::Input(input)) if (passwords || !input.password) && !input.edit.read_only => {
304          input.edit.text.clone()
305        }
306        _ => return,
307      };
308      let mut write = None;
309      tree.update_input(id, |input| {
310        change(&mut input.edit);
311        input.refresh();
312        if input.edit.text != before {
313          write = Some((input.signal, input.edit.text.clone()));
314        }
315      });
316      write
317    };
318    if let Some((signal, text)) = write {
319      // A signal whose owner is gone just isn't written.
320      signal.try_set(text);
321    }
322  }
323}
324
325/// A field in the tree.
326pub(crate) struct InputNode {
327  /// What is shown: the text, its dots, or the placeholder.
328  pub(crate) text: TextNode,
329  pub(crate) edit: Edit,
330  /// Written as the text is edited.
331  pub(crate) signal: Signal<String>,
332  pub(crate) placeholder: String,
333  pub(crate) password: bool,
334  /// The field has the keyboard, so it shows its caret.
335  pub(crate) focused: bool,
336  /// The last value of its `focus` binding, which it takes the focus by
337  /// whenever it is shown.
338  pub(crate) wants_focus: bool,
339  /// How far the text is scrolled left to keep the caret in view.
340  pub(crate) scroll: f32,
341  /// Where the caret and the selection are, from the last layout, in
342  /// window coordinates.
343  pub(crate) caret: Rect,
344  /// More than one span when right-to-left and left-to-right text mix.
345  pub(crate) selection: Vec<Rect>,
346  /// The content box the text is cut to, from the last layout.
347  pub(crate) area: Rect,
348  /// What an input method is composing, shown at the caret.
349  pub(crate) preedit: Option<Preedit>,
350  /// The selection's own color, and the selected text's.
351  pub(crate) selection_color: Option<Color>,
352  pub(crate) selected_text_color: Option<Color>,
353  /// The line under the preedit, from the last layout.
354  pub(crate) underline: Vec<Rect>,
355  /// Where across Up and Down keep the caret, and the caret position it
356  /// led to: a move that lands anywhere else forgets it.
357  pub(crate) goal: Option<(usize, f32)>,
358  /// A caret position shown at the end of a wrapped line rather than at
359  /// the start of the next, where both are the same byte.
360  pub(crate) upstream: Option<usize>,
361  /// Kept in the reactive runtime, which drops the user's closure when the
362  /// field's owner goes.
363  pub(crate) on_accept: Signal<Option<AcceptHandler>>,
364}
365
366impl InputNode {
367  pub(crate) fn new(
368    signal: Signal<String>,
369    on_accept: Signal<Option<AcceptHandler>>,
370    multiline: bool,
371  ) -> InputNode {
372    let mut text = TextNode::new();
373    if multiline {
374      text.set_max_lines(u32::MAX);
375    }
376    InputNode {
377      text,
378      edit: Edit {
379        multiline,
380        ..Edit::default()
381      },
382      signal,
383      placeholder: String::new(),
384      password: false,
385      focused: false,
386      wants_focus: false,
387      scroll: 0.0,
388      caret: Rect::default(),
389      selection: Vec::new(),
390      area: Rect::default(),
391      preedit: None,
392      selection_color: None,
393      selected_text_color: None,
394      underline: Vec::new(),
395      goal: None,
396      upstream: None,
397      on_accept,
398    }
399  }
400
401  /// What a screen reader reads of the field: its text, or a password's
402  /// dots, with the caret and selection in characters of that.
403  pub(crate) fn access_text(&self) -> crate::access::AccessText {
404    let text = &self.edit.text;
405    let at = |byte: usize| match self.password {
406      true => graphemes_before(text, byte),
407      false => text[..byte].chars().count(),
408    };
409    crate::access::AccessText {
410      text: match self.password {
411        true => DOT.to_string().repeat(at(text.len())),
412        false => text.clone(),
413      },
414      caret: at(self.edit.cursor),
415      selection: self
416        .edit
417        .selection()
418        .map(|range| (at(range.start), at(range.end))),
419    }
420  }
421
422  /// Whether the placeholder is what shows.
423  pub(crate) fn showing_placeholder(&self) -> bool {
424    self.edit.text.is_empty() && self.preedit.is_none()
425  }
426
427  /// The preedit's length in bytes, 0 without one.
428  fn preedit_len(&self) -> usize {
429    self
430      .preedit
431      .as_ref()
432      .map_or(0, |preedit| preedit.text.len())
433  }
434
435  /// Puts what should show into the text node. Returns whether that
436  /// changed, which needs a layout.
437  pub(crate) fn refresh(&mut self) -> bool {
438    let shown = if self.showing_placeholder() {
439      self.placeholder.clone()
440    } else if self.password {
441      DOT
442        .to_string()
443        .repeat(graphemes_before(&self.edit.text, self.edit.text.len()))
444    } else if let Some(preedit) = &self.preedit {
445      let (before, after) = self.edit.text.split_at(self.edit.cursor);
446      format!("{before}{}{after}", preedit.text)
447    } else {
448      self.edit.text.clone()
449    };
450    self.text.set_content(shown)
451  }
452
453  /// The selection, in bytes of what is shown.
454  pub(crate) fn shown_selection(&self) -> Option<std::ops::Range<usize>> {
455    let range = self.edit.selection()?;
456    Some(self.shown_index(range.start)..self.shown_index(range.end))
457  }
458
459  /// The byte in what is shown that matches byte `at` of the text.
460  fn shown_index(&self, at: usize) -> usize {
461    if self.showing_placeholder() {
462      0
463    } else if self.password {
464      graphemes_before(&self.edit.text, at) * DOT.len_utf8()
465    } else if at > self.edit.cursor {
466      at + self.preedit_len()
467    } else {
468      at
469    }
470  }
471
472  /// The byte of the text that matches byte `at` of what is shown.
473  fn text_index(&self, at: usize) -> usize {
474    if self.showing_placeholder() {
475      0
476    } else if self.password {
477      grapheme_start(&self.edit.text, at / DOT.len_utf8())
478    } else if at <= self.edit.cursor {
479      at
480    } else {
481      // Inside the preedit is at the caret; past it, shifted back.
482      let after = at.saturating_sub(self.preedit_len()).max(self.edit.cursor);
483      after.min(self.edit.text.len())
484    }
485  }
486
487  /// The line the caret before byte `at` of what is shown is drawn on:
488  /// the first of two that meet there when `upstream`, else the last.
489  fn caret_run(&self, at: usize, upstream: bool) -> Option<TextRun<'_>> {
490    let cursor = cursor_at(&self.text.buffer, at);
491    let mut runs = self.text.runs().filter(|run| {
492      run.line_i == cursor.line
493        && (run.glyphs.is_empty() || {
494          let start = run.glyphs.iter().map(|glyph| glyph.start).min();
495          let end = run.glyphs.iter().map(|glyph| glyph.end).max();
496          start.is_some_and(|start| start <= cursor.index)
497            && end.is_some_and(|end| cursor.index <= end)
498        })
499    });
500    if upstream { runs.next() } else { runs.last() }
501  }
502
503  /// Where the caret before byte `at` of what is shown is, from the
504  /// text's corner: across, the top of its line and the line's height.
505  /// In right-to-left text, the start is on the right. On an empty line,
506  /// or over the placeholder, it is where typed text would start.
507  fn caret_spot(&self, at: usize, upstream: bool) -> Option<(f32, f32, f32)> {
508    let run = self
509      .caret_run(at, upstream)
510      .or_else(|| self.text.runs().next())?;
511    let x = if run.glyphs.is_empty() || self.showing_placeholder() {
512      self.text.empty_line_place(run.rtl) * self.text.layout_width()
513    } else {
514      run
515        .layout()
516        .cursor_position(&cursor_at(&self.text.buffer, at))
517        .unwrap_or(0.0)
518    };
519    Some((x, run.line_top, run.line_height))
520  }
521
522  /// The part of a line `height` tall from `top` that its glyphs fill,
523  /// as top and height: the default line height's, centered as
524  /// cosmic-text centers the glyphs, when the style's is taller.
525  fn glyph_box(&self, top: f32, height: f32) -> (f32, f32) {
526    let natural = (1.2 * self.text.buffer.metrics().font_size).round();
527    let glyphs = natural.min(height);
528    (top + ((height - glyphs) / 2.0).round(), glyphs)
529  }
530
531  /// Lays the text out in the field's `content` box. Aligned text sits
532  /// in the room left of the caret's last pixel; a line too long for it
533  /// starts at the start, as unaligned text does, and scrolls.
534  pub(crate) fn finish(&mut self, content: Rect, fonts: &mut FontSystem) {
535    let room = (content.width - 1.0).max(0.0);
536    let width = match (self.text.aligned(), self.text.wraps()) {
537      (false, wraps) => wraps.then_some(content.width),
538      (true, true) => Some(room),
539      // A long placeholder is cut, but typed text starts where it should.
540      (true, false) if self.showing_placeholder() => Some(room),
541      (true, false) => Some(self.text.width().max(room)),
542    };
543    self.text.finish_at(content, width, fonts);
544  }
545
546  /// Scrolls the text sideways to keep the caret inside `content`, then
547  /// places the caret and the selection. Called after the text node's own
548  /// layout.
549  pub(crate) fn place(&mut self, content: Rect) {
550    let at = self.shown_index(self.edit.cursor);
551    let caret = match &self.preedit {
552      Some(preedit) => {
553        at + preedit
554          .cursor
555          .map_or(preedit.text.len(), |(start, _)| start)
556      }
557      None => at,
558    };
559    let upstream = self.upstream == Some(self.edit.cursor) && self.preedit.is_none();
560    let (x, top, height) = self
561      .caret_spot(caret, upstream)
562      .unwrap_or((0.0, 0.0, content.height));
563    let width = self.text.runs().map(|run| run.line_w).fold(0.0, f32::max);
564    // The caret's own pixel counts as text, so it shows at the end.
565    let room = (content.width - 1.0).max(0.0);
566    let mut scroll = self.scroll.min((width - room).max(0.0));
567    if x - scroll > room {
568      scroll = x - room;
569    }
570    if x < scroll {
571      scroll = x;
572    }
573    self.scroll = scroll.max(0.0);
574    self.text.origin.x = content.x - self.scroll;
575    let origin = self.text.origin;
576    let (top, height) = self.glyph_box(top, height);
577    self.caret = Rect::new(origin.x + x, origin.y + top, 1.0, height);
578    self.area = content;
579    self.selection = match self.shown_selection() {
580      Some(range) => highlights(&self.text, range),
581      None => Vec::new(),
582    };
583    self.underline = match &self.preedit {
584      Some(preedit) => highlights(&self.text, at..at + preedit.text.len())
585        .into_iter()
586        .map(|span| {
587          let (top, height) = self.glyph_box(span.y, span.height);
588          Rect::new(span.x, top + height - 1.0, span.width, 1.0)
589        })
590        .collect(),
591      None => Vec::new(),
592    };
593  }
594
595  /// The text position nearest `point`, in window coordinates, and
596  /// whether it is the end of a wrapped line rather than the start of the
597  /// next.
598  pub(crate) fn hit(&self, point: Point) -> (usize, bool) {
599    let origin = self.text.origin;
600    let Some(cursor) = self.text.buffer.hit(point.x - origin.x, point.y - origin.y) else {
601      return (0, false);
602    };
603    let at = self.text_index(index_of(&self.text.buffer, cursor));
604    (at, cursor.affinity == Affinity::Before)
605  }
606
607  /// What a key that moves by line does in a text area: Up and Down to
608  /// the line above or below, keeping the caret's place across, PageUp
609  /// and PageDown by `page` logical pixels, and Home and End to the ends
610  /// of the line as it is wrapped. Shift extends the selection. `None`
611  /// for any other key.
612  pub(crate) fn line_key(&mut self, event: &KeyEvent, page: f32) -> Option<Keyed> {
613    let ctrl = event.modifiers.ctrl;
614    let lines = match event.key {
615      Key::Up => -1.0,
616      Key::Down => 1.0,
617      Key::PageUp => -page,
618      Key::PageDown => page,
619      Key::Home | Key::End if !ctrl => 0.0,
620      _ => return None,
621    };
622    let at = self.shown_index(self.edit.cursor);
623    let upstream = self.upstream == Some(self.edit.cursor);
624    let (target, upstream, goal) = if lines == 0.0 {
625      let run = self.caret_run(at, upstream)?;
626      let ends = run.glyphs.iter().map(|glyph| (glyph.start, glyph.end));
627      let index = if event.key == Key::Home {
628        ends.map(|(start, _)| start).min()
629      } else {
630        ends.map(|(_, end)| end).max()
631      };
632      let line = cosmic_text::Cursor::new(run.line_i, index.unwrap_or(0));
633      (
634        index_of(&self.text.buffer, line),
635        event.key == Key::End,
636        None,
637      )
638    } else {
639      let (x, top, height) = self.caret_spot(at, upstream)?;
640      let x = self
641        .goal
642        .filter(|&(cursor, _)| cursor == self.edit.cursor)
643        .map_or(x, |(_, x)| x);
644      let step = if matches!(event.key, Key::Up | Key::Down) {
645        lines * height
646      } else {
647        lines
648      };
649      let cursor = self.text.buffer.hit(x, top + height / 2.0 + step)?;
650      (
651        index_of(&self.text.buffer, cursor),
652        cursor.affinity == Affinity::Before,
653        Some(x),
654      )
655    };
656    let target = self.text_index(target);
657    self.edit.move_to(event.modifiers.shift, target);
658    self.upstream = upstream.then_some(target);
659    self.goal = goal.map(|x| (target, x));
660    Some(Keyed::Moved)
661  }
662}