1// Text fields: a caret moving by graphemes, lines and the ends of lines2// with the arrows, Home and End, Left and Right as the text is shown3// where its direction changes, and by words (UAX #29) with Ctrl, Option4// on macOS; a selection by Shift or the pointer, a double click taking a5// word; typing, Enter, Backspace and Delete (by the text's order, a word6// with Ctrl or Option); Ctrl+C,7// Ctrl+X and Ctrl+V through the clipboard; an input method's8// compositions shown underlined at the caret. One line scrolls to keep9// the caret in view, on the right when it reads right to left; several10// wrap, each paragraph on its own side. A secret field shows a dot for11// each grapheme, its caret and selection moving among the dots, the12// offsets in the text taken to and from theirs (`shown_at`, `text_at`).1314import std::string;15import std::vector;16import std::option;17import std::math;18import std::process;19import pkg::alloy::window;20import pkg::alloy::gpu;21import pkg::alloy::draw;22import pkg::alloy::text as text;2324import ui;25import tree;26import widgets;27import extensions;2829pub fn layout(self f: &var TextField, arrange: &var Arrange, limits: Limits) -> Extent {30 const inner = limits.inside(&f.padding);31 const width = if (inner.max_width < UNBOUNDED) inner.max_width else max(inner.min_width, 200.0);32 const size = arrange.theme().text_size;33 // nothing typed, or no letter, reads as the field does, as an input34 // with dir=auto35 const plain = arrange.text_style(size);36 const fonts = &var arrange.fonts();37 const e = &var f.editing;38 e.caret = min(e.caret, f.text.length());39 e.anchor = min(e.anchor, f.text.length());40 // the text, the composition in it at the caret, underlined; a secret41 // field's dots, which nothing composes in42 const composing = e.preedit.text.length();43 var shown = if (f.secret) f.dots() else String::from(&f.text.view()[..e.caret]);44 if (!f.secret) {45 shown.append(&e.preedit.text.view());46 shown.append(&f.text.view()[e.caret..]);47 }48 const hint_style = copy plain;49 var underlined = copy plain;50 underlined.underline = true;51 // one span while nothing is composed, so the caret neither splits the52 // shaping nor makes moving it a new layout53 var spans = Vector<text::Span>::empty();54 if (composing == 0) {55 spans.push(text::Span { .start = 0, .end = shown.length(), .style = copy plain });56 } else {57 spans.push(text::Span { .start = 0, .end = e.caret, .style = copy plain });58 spans.push(text::Span {59 .start = e.caret,60 .end = e.caret + composing,61 .style = move underlined62 });63 spans.push(text::Span {64 .start = e.caret + composing,65 .end = shown.length(),66 .style = copy plain67 });68 }69 var laid = text::Layout::spans(70 &fonts,71 &shown.view(),72 &spans.view(),73 if (f.multiline) width else 0.0,74 text::Align::Start75 );76 const line = if (laid.lines.try_get(0) is ::Some |&first|) first.height else size * 1.25;77 // the placeholder at the field's start, the typed text on its own side78 const rtl = arrange.direction() is ::RightToLeft;79 e.inset = if (rtl) f.padding.end else f.padding.start;80 e.hint = ::None;81 e.hint_at = 0.0;82 if (f.text.length() == 0 && composing == 0 && f.placeholder.length() > 0) {83 const hint_spans: [text::Span : 1] = [text::Span {84 .start = 0,85 .end = f.placeholder.length(),86 .style = copy hint_style87 }];88 var hint = text::Layout::spans(89 &fonts,90 &f.placeholder.view(),91 &hint_spans,92 if (f.multiline) width else 0.0,93 if (rtl) text::Align::Right else text::Align::Left94 );95 if (rtl && !f.multiline) {96 e.hint_at = max(width - hint.width, 0.0);97 }98 e.hint = ::Some(move hint);99 }100 const height = if (f.multiline) max(laid.height, line) else line;101 e.line = line;102 e.width = width;103 e.laid = ::Some(move laid);104 const caret = f.shown_at(e.caret) + e.preedit.cursor;105 e.follow_caret(f.multiline, caret);106 f.remap(&var arrange.ui);107 return Extent {108 .width = width + f.padding.start + f.padding.end,109 .height = height + f.padding.top + f.padding.bottom110 };111}112113exp fn paint(self f: &TextField, look: &Look, paint: &var Paint) {114 const theme = &look.theme;115 const e = &f.editing;116 const area = Rect::sized(look.size.width, look.size.height);117 var surface = theme.surface;118 if (!f.enabled) {119 surface.a = 0.5;120 }121 paint.rounded_rect(area, Radii::all(theme.radius), Fill::Color(surface));122 if (f.error.length() > 0) {123 paint.border(area, Radii::all(theme.radius), if (look.focused) 2.0 else 1.5, theme.danger);124 } else if (look.focused) {125 paint.border(area, Radii::all(theme.radius), 2.0, theme.focus);126 } else {127 paint.border(128 area,129 Radii::all(theme.radius),130 1.0,131 if (look.hovered && f.enabled) theme.muted else theme.border132 );133 }134 const origin = Point { .x = e.inset + e.shift - e.scroll, .y = f.padding.top };135 const laid = if (e.laid is ::Some |&l|) &l else {136 return;137 };138 const composing = e.preedit.text.length();139 if (e.caret != e.anchor && look.focused) {140 const start = min(e.caret, e.anchor);141 const end = max(e.caret, e.anchor);142 const from = f.shown_at(if (start < e.caret) start else start + composing);143 const to_end = f.shown_at(if (end <= e.caret) end else end + composing);144 var mark = theme.primary;145 mark.a = 0.25;146 for (laid.selection(from, to_end).view()) |&b| {147 paint.rect(148 Rect::at(origin.x + b.x, origin.y + b.y, b.width, b.height),149 Fill::Color(mark)150 );151 }152 }153 if (e.hint is ::Some |&hint|) {154 paint.text(&hint, Point { .x = e.inset + e.hint_at, .y = origin.y }, theme.muted);155 } else {156 var ink = theme.text;157 if (!f.enabled) {158 ink.a = 0.5;159 }160 paint.text(&laid, origin, ink);161 }162 if (look.focused) {163 const box = laid.caret(f.shown_at(e.caret) + e.preedit.cursor);164 paint.rect(165 Rect::at(origin.x + floor(box.x), origin.y + box.y, 1.5, box.height),166 Fill::Color(theme.text)167 );168 }169}170171pub fn event(self f: &var TextField, ui: &var Ui, input: &Input) -> bool {172 if (!f.enabled) {173 return claims(&input);174 }175 match (input) {176 ::Press |p| {177 f.place(p, !ui.modifiers().shift);178 // a second press soon after the first, and near it, takes a word179 const now = ui.now();180 var again = false;181 if (182 f.editing.pressed is ::Some |last|183 && now.nanoseconds - last.nanoseconds < DOUBLE_CLICK184 && absolute(p.x - f.editing.pressed_at.x) < 4.0185 && absolute(p.y - f.editing.pressed_at.y) < 4.0186 ) {187 again = true;188 }189 f.editing.pressed = if (again) ::None else ::Some(now);190 f.editing.pressed_at = p;191 f.editing.dragging = !again;192 if (again) {193 f.select_word();194 }195 f.caret_moved(&var ui);196 }197 ::Moved |p| {198 if (f.editing.dragging) {199 f.place(p, false);200 f.caret_moved(&var ui);201 }202 }203 ::Release {204 f.editing.dragging = false;205 }206 ::Click {}207 ::Focus |gained| {208 if (!gained) {209 f.editing.dragging = false;210 f.editing.anchor = f.editing.caret;211 }212 ui.refresh(Change::Paint);213 return false;214 }215 ::Key |&k| {216 if (!k.pressed) {217 return false;218 }219 return f.key(&var ui, &k);220 }221 ::Text |&t| {222 // control characters come as keys223 if (t.length() > 0 && t.get(0) >= 0x20 && t.get(0) != 0x7F) {224 f.insert(&var ui, &t.view());225 }226 }227 ::Preedit |&p| {228 // a secret field's text comes typed, never composed229 if (!f.secret) {230 f.editing.preedit = copy p;231 ui.refresh(Change::Layout);232 }233 }234 ::Paste |&t| {235 f.insert(&var ui, &t.view());236 }237 ::Scroll {238 return false;239 }240 ::Action |&a| {241 match (a) {242 ::SetValue |&t| {243 f.editing.anchor = 0;244 f.editing.caret = f.text.length();245 f.insert(&var ui, &t.view());246 }247 ::SetSelection |range| {248 f.editing.anchor = min(f.text_at(range[0]), f.text.length());249 f.editing.caret = min(f.text_at(range[1]), f.text.length());250 f.caret_moved(&var ui);251 }252 else {}253 }254 }255 else {}256 }257 return true;258}259260pub fn semantics(self f: &TextField) -> Semantics => Semantics {261 .role = Role::TextInput,262 .label = said(&f.accessible, &f.placeholder),263 .value = if (f.secret) f.dots() else copy f.text,264 .multiline = f.multiline,265 .selection = ::Some([f.shown_at(f.editing.anchor), f.shown_at(f.editing.caret)]),266 .secret = f.secret,267 .disabled = !f.enabled,268 .focusable = f.enabled,269 .invalid = f.error.length() > 0,270 .required = f.required,271 .description = described(&f.error, &f.description)272};273274// What a secret field shows for each grapheme.275const DOT: &[u8] = &"•";276277// A secret field's dots, one a grapheme of its text.278fn dots(self f: &TextField) -> String {279 var out = String::empty();280 for ([..text::grapheme_count(&f.text.view())]) {281 out.append(&DOT);282 }283 return move out;284}285286// Where an offset in the text (on a grapheme's boundary) is in what the287// field shows: the same, but among a secret field's dots.288fn shown_at(self f: &TextField, at: u64) -> u64 {289 if (!f.secret) {290 return at;291 }292 return DOT.length() * text::grapheme_count(&f.text.view()[..min(at, f.text.length())]);293}294295// The offset in the text of one in what the field shows, the296// composition's aside (`from_shown`).297fn text_at(self f: &TextField, shown: u64) -> u64 {298 if (!f.secret) {299 return shown;300 }301 const k = shown / DOT.length();302 if (k == 0) {303 return 0;304 }305 const ends = text::grapheme_ends(&f.text.view());306 return if (k <= ends.length()) ends.get(k - 1) else f.text.length();307}308309// How soon a second press makes a double click, in nanoseconds.310const DOUBLE_CLICK: u64 = 500000000;311312fn absolute(x: f32) -> f32 => if (x < 0.0) -x else x;313314// Selects the word holding the caret: from its start to the next word's,315// the spaces after it included.316fn select_word(self f: &var TextField) {317 const e = &var f.editing;318 const laid = if (e.laid is ::Some |&l|) &l else {319 return;320 };321 const at = f.shown_at(e.caret);322 var start: u64 = 0;323 var end = laid.text.length();324 for (text::word_starts(&laid.text.view()).view()) |word| {325 const w = word to u64;326 if (w <= at) {327 start = w;328 } else {329 end = w;330 break;331 }332 }333 e.anchor = f.text_at(start);334 e.caret = f.text_at(end);335}336337// The word start before the offset in what is shown, or its start; or338// the one after it, or its end.339fn word_before(laid: &text::Layout, at: u64) -> u64 {340 var found: u64 = 0;341 for (text::word_starts(&laid.text.view()).view()) |word| {342 if (word to u64 >= at) {343 break;344 }345 found = word to u64;346 }347 return found;348}349350fn word_after(laid: &text::Layout, at: u64) -> u64 {351 for (text::word_starts(&laid.text.view()).view()) |word| {352 if (word to u64 > at) {353 return word to u64;354 }355 }356 return laid.text.length();357}358359// The word start Ctrl+Right (or Left) goes to: the next in the text on a360// line reading left to right, the one before on a line reading right to361// left.362fn word_toward(laid: &text::Layout, at: u64, right: bool) -> u64 {363 var rtl = false;364 if (laid.lines.length() > 0) {365 rtl = laid.lines.get(laid.line_of(at)).direction is ::RightToLeft;366 }367 return if (right != rtl) word_after(&laid, at) else word_before(&laid, at);368}369370// Where the selection starts and ends in the text.371type Selection = struct {372 start: u64,373 end: u64,374};375376fn selection(self f: &TextField) -> Selection {377 const e = &f.editing;378 return Selection {379 .start = min(min(e.caret, e.anchor), f.text.length()),380 .end = min(max(e.caret, e.anchor), f.text.length())381 };382}383384// The selected text.385fn selected(self f: &TextField) -> &[u8] {386 const s = f.selection();387 return &f.text.view()[s.start..s.end];388}389390// Scrolls one line so the caret, at `caret` in what is shown, shows; one391// shorter than the field and right to left moves to its right edge.392fn follow_caret(self e: &var Editing, multiline: bool, caret: u64) {393 e.shift = 0.0;394 if (multiline) {395 e.scroll = 0.0;396 return;397 }398 var x: f32 = 0.0;399 var end: f32 = 0.0;400 if (e.laid is ::Some |&laid|) {401 x = laid.caret(caret).x;402 end = laid.width;403 if (404 laid.lines.try_get(0) is ::Some |&first|405 && first.direction is ::RightToLeft406 && laid.width < e.width - 1.0407 ) {408 e.shift = e.width - 1.0 - laid.width;409 }410 }411 if (x - e.scroll > e.width - 1.0) {412 e.scroll = x - e.width + 1.0;413 }414 if (x < e.scroll) {415 e.scroll = x;416 }417 e.scroll = clamp(e.scroll, 0.0, max(end - e.width + 1.0, 0.0));418}419420// The caret or the selection moved: repainted, the text laid out again421// only while a composition, which sits at the caret, shows.422fn caret_moved(self f: &var TextField, ui: &var Ui) {423 if (f.editing.preedit.text.length() == 0) {424 const caret = f.shown_at(f.editing.caret);425 const was = [f.editing.scroll, f.editing.shift];426 f.editing.follow_caret(f.multiline, caret);427 if (was != [f.editing.scroll, f.editing.shift]) {428 f.remap(&var ui);429 }430 ui.refresh(Change::Paint);431 } else {432 ui.refresh(Change::Layout);433 }434}435436// The map a text field or a text of several lines keeps while a screen437// reader reads.438exp fn text_map_of(widget: &Widget) -> Option<TextMap> {439 if (widget is Text |&t| && t.map is ::Some |&m|) {440 return ::Some(copy m);441 }442 if (widget is TextField |&f| && f.editing.map is ::Some |&m|) {443 return ::Some(copy m);444 }445 return ::None;446}447448// Makes the map a screen reader reads the field by, where its text is449// drawn now, while one reads (not on the web, whose browser reads the450// field itself); a composition keeps the last, as the value leaves it451// out.452fn remap(self f: &var TextField, ui: &var Ui) {453 if (target() == "web-wasm32") {454 return;455 }456 const e = &var f.editing;457 if (!ui.access_on) {458 e.map = ::None;459 return;460 }461 if (e.preedit.text.length() > 0) {462 return;463 }464 const laid = if (e.laid is ::Some |&l|) &l else {465 return;466 };467 const look = TextLook {468 .size = ui.theme.text_size,469 .weight = REGULAR,470 .color = ui.theme.text,471 .read_only = !f.enabled472 };473 const origin = Point { .x = e.inset + e.shift - e.scroll, .y = f.padding.top };474 if (ui.extensions_text_map(&laid, origin, look) is ::Some |move map|) {475 e.map = ::Some(new move map);476 }477}478479// Moves the caret to the point, in the field's coordinates; the480// selection's other end stays unless `place`.481fn place(self f: &var TextField, at: Point, place: bool) {482 const e = &var f.editing;483 if (e.laid is ::Some |&laid|) {484 const shown = laid.hit(at.x - e.inset - e.shift + e.scroll, at.y - f.padding.top);485 e.caret = if (f.secret) f.text_at(shown) else from_shown(&e, shown);486 if (place) {487 e.anchor = e.caret;488 }489 }490}491492// An offset in the text shown, the composition in it, as one in the493// text.494fn from_shown(e: &Editing, at: u64) -> u64 {495 const length = e.preedit.text.length();496 if (at <= e.caret) {497 return at;498 }499 return if (at < e.caret + length) e.caret else at - length;500}501502// What a key does; whether the field took it. The caret moves among503// what is shown, from `at`, to `target`.504fn key(self f: &var TextField, ui: &var Ui, k: &KeyEvent) -> bool {505 const e = &var f.editing;506 if (e.preedit.text.length() != 0) {507 return true; // the input method's508 }509 const extend = k.modifiers.shift;510 const laid = if (e.laid is ::Some |&l|) &l else {511 return false;512 };513 const at = f.shown_at(e.caret);514 const anchor = f.shown_at(e.anchor);515 const last = f.shown_at(f.text.length());516 const words = by_words(&k.modifiers);517 var target = at;518 match (k.key) {519 ::Left {520 if (words) {521 target = word_toward(&laid, at, false);522 } else {523 target = if (524 at != anchor525 && !extend526 ) collapsed(&laid, at, anchor, false) else laid.previous_position(at);527 }528 }529 ::Right {530 if (words) {531 target = word_toward(&laid, at, true);532 } else {533 target = if (534 at != anchor535 && !extend536 ) collapsed(&laid, at, anchor, true) else laid.next_position(at);537 }538 }539 ::Home {540 target = if (shortcut(&k.modifiers)) 0 else laid.line_start(at);541 }542 ::End {543 target = if (shortcut(&k.modifiers)) last else laid.line_end(at);544 }545 ::Up, ::Down {546 if (!f.multiline) {547 return false;548 }549 const box = laid.caret(at);550 const y = if (k.key is ::Up) box.y - 1.0 else box.y + box.height + 1.0;551 if (y < 0.0) {552 target = 0;553 } else if (y >= laid.height) {554 target = last;555 } else {556 target = laid.hit(box.x, y);557 }558 }559 ::Backspace {560 if (e.caret == e.anchor) {561 e.anchor = f.text_at(562 if (words) word_before(&laid, at) else laid.previous_logical(at)563 );564 }565 f.insert(&var ui, &"");566 return true;567 }568 ::Delete {569 if (e.caret == e.anchor) {570 e.anchor = f.text_at(if (words) word_after(&laid, at) else laid.next_logical(at));571 }572 f.insert(&var ui, &"");573 return true;574 }575 ::Enter {576 if (f.multiline) {577 f.insert(&var ui, &"\n");578 } else {579 f.on_submit(&var ui);580 }581 return true;582 }583 ::Character |c| {584 if (shortcut(&k.modifiers)) {585 match (c) {586 'a' {587 e.anchor = 0;588 e.caret = f.text.length();589 ui.refresh(Change::Paint);590 return true;591 }592 'c', 'x' {593 // a password stays in the field594 if (f.secret) {595 return true;596 }597 if (e.caret != e.anchor) {598 ui.set_clipboard(String::from(&f.selected()));599 if (c == 'x') {600 f.insert(&var ui, &"");601 }602 return true;603 }604 }605 'v' {606 ui.request_paste();607 return true;608 }609 }610 }611 // typing comes as Text612 return !shortcut(&k.modifiers) && !k.modifiers.alt;613 }614 else {615 return false;616 }617 }618 e.caret = f.text_at(target);619 if (!extend) {620 e.anchor = e.caret;621 }622 f.caret_moved(&var ui);623 return true;624}625626// Where Left (or Right) leaves a selection between `a` and `b`: at its627// end shown further left (or right) on one line, otherwise at the end628// before (or after) in the text's order, the other way right to left.629fn collapsed(laid: &text::Layout, a: u64, b: u64, right: bool) -> u64 {630 const start = min(a, b);631 const end = max(a, b);632 const first = laid.caret(start);633 const last = laid.caret(end);634 if (first.y == last.y) {635 return if ((first.x < last.x) == right) end else start;636 }637 const rtl = laid.lines.get(laid.line_of(a)).direction is ::RightToLeft;638 return if (right != rtl) end else start;639}640641// Replaces the selection with the text, the caret after it, and tells642// the program.643fn insert(self f: &var TextField, ui: &var Ui, text: &[u8]) {644 const s = f.selection();645 var edited = String::from(&f.text.view()[..s.start]);646 edited.append(&text);647 edited.append(&f.text.view()[s.end..]);648 f.text = move edited;649 const e = &var f.editing;650 e.caret = s.start + text.length();651 e.anchor = e.caret;652 ui.refresh(Change::Layout);653 f.on_change(&var ui, copy f.text);654}655656exp fn renew(self f: &var TextField, next: TextField) -> Change {657 var change = Change::Paint;658 if (f.text != next.text) {659 f.text = move next.text;660 f.editing.caret = min(f.editing.caret, f.text.length());661 f.editing.anchor = min(f.editing.anchor, f.text.length());662 change = Change::Layout;663 }664 if (f.secret != next.secret) {665 f.editing.preedit = Preedit { .text = String::empty(), .cursor = 0 };666 }667 if (668 f.placeholder != next.placeholder669 || f.multiline != next.multiline670 || f.secret != next.secret671 || f.padding != next.padding672 || f.sizing != next.sizing673 ) {674 change = Change::Layout;675 }676 f.on_change = move next.on_change;677 f.on_submit = move next.on_submit;678 f.placeholder = move next.placeholder;679 f.accessible = move next.accessible;680 f.error = move next.error;681 f.description = move next.description;682 f.required = next.required;683 f.multiline = next.multiline;684 f.secret = next.secret;685 f.enabled = next.enabled;686 f.padding = next.padding;687 f.sizing = next.sizing;688 return change;689}690691pub fn caret(self f: &TextField) -> Option<Rect> {692 const e = &f.editing;693 if (e.laid is ::Some |&laid|) {694 const box = laid.caret(f.shown_at(e.caret) + e.preedit.cursor);695 return ::Some(Rect::at(696 e.inset + e.shift - e.scroll + box.x,697 f.padding.top + box.y,698 1.0,699 box.height700 ));701 }702 return ::None;703}704705pub fn sizing(self f: &TextField) -> Sizing => f.sizing;706pub fn interactive(self f: &TextField) -> bool => true;707pub fn focusable(self f: &TextField) -> bool => f.enabled;708pub fn cursor(self f: &TextField) -> Cursor => if (f.enabled) Cursor::Text else Cursor::Arrow;709pub fn clips(self f: &TextField) -> bool => true;710711// Whether the modifiers make an arrow, Backspace or Delete go by words:712// Option on macOS, Control elsewhere.713fn by_words(m: &Modifiers) -> bool {714 if (target() == "macos-arm64" || target() == "macos-x86_64") {715 return m.alt;716 }717 return m.control;718}719720// Whether the modifiers make a key a shortcut: Command on macOS, Control721// elsewhere.722fn shortcut(m: &Modifiers) -> bool {723 if (target() == "macos-arm64" || target() == "macos-x86_64") {724 return m.super;725 }726 return m.control;727}