From d822267bd39b314750d007398d2f808f06e5e25c Mon Sep 17 00:00:00 2001 From: Paula Date: Sun, 27 Sep 2026 12:54:10 -0300 Subject: [PATCH] Improve chat input --- MODS.md | 3 +- client/gui/gui_chat.ts | 5 +- client/gui/mod_graphics.ts | 6 + client/gui/widgets.ts | 224 ++++++++++++++++++++++++++++++++----- client/input_manager.ts | 21 +++- tests/text_input_test.ts | 62 ++++++++++ 6 files changed, 288 insertions(+), 33 deletions(-) create mode 100644 tests/text_input_test.ts diff --git a/MODS.md b/MODS.md index 291def3..908938f 100644 --- a/MODS.md +++ b/MODS.md @@ -934,7 +934,8 @@ ctx.ui.add_inventory_overlay({ Overlays get the mouse before the slots. A click they use (`g.button`, or `g.consume_click()`) doesn't reach the slots, and `g.block_mouse(x, y, w, h)` keeps the slots from taking the mouse under something drawn over them. While a -`g.text_input` has the keyboard, keybinds like the inventory key don't fire. An overlay that throws is removed, with the +`g.text_input` has the keyboard, keybinds like the inventory key don't fire. Text inputs edit like chat does: selecting +with shift or the mouse, ctrl+a, and copy, cut and paste. An overlay that throws is removed, with the error in the console. Client scripts are for presentation. They can't change the world or inventories; they ask the server over a diff --git a/client/gui/gui_chat.ts b/client/gui/gui_chat.ts index c7ae1f6..25128b5 100644 --- a/client/gui/gui_chat.ts +++ b/client/gui/gui_chat.ts @@ -45,6 +45,7 @@ export class GuiChat extends GuiScreen { this.client.chat.render(true, y - 8); draw_rect(0, y, canvas.width, canvas.height, [0, 0, 0, 0.4]); + this.input.draw_selection(0, y + 4, INPUT_HEIGHT - 4, SCALE); draw_text(this.input.value, 0, y, SCALE, [1, 1, 1]); draw_rect(this.input.caret_x(0, SCALE), y + 4, 1, INPUT_HEIGHT - 4); @@ -53,6 +54,8 @@ export class GuiChat extends GuiScreen { override on_tick(_delta: number): void { this.#handle_suggestion_keys(); + const y = canvas.height - INPUT_HEIGHT; + this.input.handle_mouse({ x: 0, y, width: canvas.width, height: INPUT_HEIGHT }, 0, SCALE); this.input.handle_keys(); this.#ask_for_suggestions(); if (InputManager.is_key_pressed("Enter")) { @@ -112,7 +115,7 @@ export class GuiChat extends GuiScreen { const caret = this.input.caret; const start = Math.min(this.suggestions_start, caret); this.input.value = (value.slice(0, start) + suggestion.text + value.slice(caret)).slice(0, MAX_CHAT_LENGTH); - this.input.caret = Math.min(start + suggestion.text.length, this.input.value.length); + this.input.move_caret(start + suggestion.text.length); // the list stays for tabbing through, it's asked for again once they type this.#asked = this.input.value.slice(0, this.input.caret); } diff --git a/client/gui/mod_graphics.ts b/client/gui/mod_graphics.ts index c1719b5..0b090fa 100644 --- a/client/gui/mod_graphics.ts +++ b/client/gui/mod_graphics.ts @@ -147,6 +147,9 @@ export class ModGraphics implements Graphics { this.#inputs.set(id, input); } const hovered = point_inside_rec(this.mouse.x, this.mouse.y, x, y, w, INPUT_HEIGHT); + if (this.#focused === id || (hovered && this.mouse.pressed)) { + input.handle_mouse({ x, y, width: w, height: INPUT_HEIGHT }, x + 6); + } if (this.mouse.pressed) { if (hovered) { this.#focused = id; @@ -167,6 +170,9 @@ export class ModGraphics implements Graphics { draw_rect(x, y, w, INPUT_HEIGHT, focused ? WHITE : GREY); draw_rect(x + 2, y + 2, w - 4, INPUT_HEIGHT - 4, [0, 0, 0, 1]); this.clip(x + 2, y + 2, w - 4, INPUT_HEIGHT - 4, () => { + if (focused) { + input.draw_selection(x + 6, y + 6, INPUT_HEIGHT - 12); + } draw_text(input.value, x + 6, y + 4, TEXT_SCALE, WHITE); if (focused && TextInput.caret_visible()) { draw_rect(input.caret_x(x + 6), y + 6, 2, INPUT_HEIGHT - 12, WHITE); diff --git a/client/gui/widgets.ts b/client/gui/widgets.ts index 1c6defd..6a9b615 100644 --- a/client/gui/widgets.ts +++ b/client/gui/widgets.ts @@ -1,6 +1,6 @@ import { point_inside_rec } from "$/common/utils.ts"; import { AssetManager } from "$/client/assets.ts"; -import { InputManager } from "$/client/input_manager.ts"; +import { InputManager, type KeyCode } from "$/client/input_manager.ts"; import { draw_nine_slice } from "$/client/rendering/render_utils.ts"; import { draw_rect, draw_text, measure_text, Texture } from "$/client/renderer/mod.ts"; @@ -11,63 +11,197 @@ export const TEXT_HEIGHT = 11; const REPEAT_DELAY_MS = 400; const REPEAT_RATE_MS = 40; const CARET_BLINK_MS = 500; +const DOUBLE_CLICK_MS = 400; +const SELECTION_COLOR: [number, number, number, number] = [0.25, 0.45, 1, 0.6]; -// editing a line of text with the keyboard: typing, backspace (held repeats), delete, arrows, home and end +// editing a line of text, like minecraft's EditBox without the drawing. typing, backspace and delete, arrows, home +// and end. shift with those selects, ctrl (alt on macs) moves and deletes whole words, ctrl+a selects everything, and +// ctrl+c, x and v copy, cut and paste. see handle_mouse for clicking and dragging export class TextInput { value: string; caret: number; + // the other end of the selection, the same as caret when nothing is selected + anchor: number; max_length: number; // which typed characters are kept allowed: (char: string) => boolean; + #repeat_key: KeyCode | undefined; #repeat_timer = 0; + #dragging = false; + #last_click = -Infinity; constructor(value = "", max_length = 256, allowed: (char: string) => boolean = () => true) { this.value = value; this.caret = value.length; + this.anchor = this.caret; this.max_length = max_length; this.allowed = allowed; } + // start and end, in order + selection(): [number, number] { + const anchor = Math.min(this.anchor, this.value.length); + return [Math.min(anchor, this.caret), Math.max(anchor, this.caret)]; + } + + selected_text() { + const [start, end] = this.selection(); + return this.value.slice(start, end); + } + + // replaces the selection with as much of the text as fits. line breaks and tabs become spaces and characters that + // aren't allowed are left out. nothing changes when none of it can go in + insert(text: string) { + const [start, end] = this.selection(); + const room = this.max_length - (this.value.length - (end - start)); + let kept = ""; + for (const char of text.replace(/\r\n|[\r\n\t]/g, " ")) { + if (char < " " || !this.allowed(char)) { + continue; + } + if (kept.length + char.length > room) { + break; + } + kept += char; + } + if (kept === "") { + return; + } + this.value = this.value.slice(0, start) + kept + this.value.slice(end); + this.move_caret(start + kept.length); + } + + // moves the caret. extending keeps the selection's other end where it is + move_caret(to: number, extend = false) { + this.caret = Math.max(0, Math.min(this.value.length, to)); + if (!extend) { + this.anchor = this.caret; + } + } + + select_all() { + this.anchor = 0; + this.caret = this.value.length; + } + + // the selection, or else from the caret to `to` + delete_to(to: number) { + const [start, end] = this.anchor !== this.caret + ? this.selection() + : [Math.min(this.caret, to), Math.max(this.caret, to)]; + this.value = this.value.slice(0, start) + this.value.slice(end); + this.move_caret(start); + } + + // where ctrl+left goes from i: back over spaces, then to the start of the word + word_start(i: number) { + while (i > 0 && this.value[i - 1] === " ") i--; + while (i > 0 && this.value[i - 1] !== " ") i--; + return i; + } + + // where ctrl+right goes from i: past the rest of the word, then its spaces + word_end(i: number) { + while (i < this.value.length && this.value[i] !== " ") i++; + while (i < this.value.length && this.value[i] === " ") i++; + return i; + } + // call once per frame while it has the keyboard handle_keys() { const now = performance.now(); - let backspace = false; - if (InputManager.is_key_pressed("Backspace")) { - this.#repeat_timer = now; - backspace = true; - } else if (InputManager.is_key_down("Backspace") && now - this.#repeat_timer > REPEAT_DELAY_MS) { - this.#repeat_timer = now - (REPEAT_DELAY_MS - REPEAT_RATE_MS); - backspace = true; + const shift = InputManager.is_key_down("ShiftLeft") || InputManager.is_key_down("ShiftRight"); + const word = InputManager.is_key_down("ControlLeft") || InputManager.is_key_down("ControlRight") || + InputManager.is_key_down("AltLeft") || InputManager.is_key_down("AltRight"); + + if (InputManager.is_shortcut_pressed("a")) { + this.select_all(); } - if (backspace && this.caret > 0) { - this.value = this.value.slice(0, this.caret - 1) + this.value.slice(this.caret); - this.caret -= 1; + const copy = InputManager.is_shortcut_pressed("c"); + const cut = InputManager.is_shortcut_pressed("x"); + if ((copy || cut) && this.anchor !== this.caret) { + navigator.clipboard?.writeText(this.selected_text()).catch(() => {}); + if (cut) { + this.delete_to(this.caret); + } + } + if (InputManager.is_shortcut_pressed("v")) { + // the browser may ask first, it's put in once it answers + navigator.clipboard?.readText().then((text) => this.insert(text), () => {}); + } + for (const char of InputManager.get_typed_characters()) { + this.insert(char); } - if (InputManager.is_key_pressed("Delete")) { - this.value = this.value.slice(0, this.caret) + this.value.slice(this.caret + 1); + if (this.#fires("Backspace", now)) { + this.delete_to(word ? this.word_start(this.caret) : this.caret - 1); } - if (InputManager.is_key_pressed("ArrowLeft")) { - this.caret = Math.max(0, this.caret - 1); + if (this.#fires("Delete", now)) { + this.delete_to(word ? this.word_end(this.caret) : this.caret + 1); } - if (InputManager.is_key_pressed("ArrowRight")) { - this.caret = Math.min(this.value.length, this.caret + 1); + const [start, end] = this.selection(); + if (this.#fires("ArrowLeft", now)) { + // without shift, a selection collapses to its start + const from = !shift && start !== end ? start + 1 : this.caret; + this.move_caret(word ? this.word_start(this.caret) : from - 1, shift); + } + if (this.#fires("ArrowRight", now)) { + const from = !shift && start !== end ? end - 1 : this.caret; + this.move_caret(word ? this.word_end(this.caret) : from + 1, shift); } if (InputManager.is_key_pressed("Home")) { - this.caret = 0; + this.move_caret(0, shift); } if (InputManager.is_key_pressed("End")) { - this.caret = this.value.length; + this.move_caret(this.value.length, shift); } + } - for (const char of InputManager.get_typed_characters()) { - if (this.value.length >= this.max_length || !this.allowed(char)) { - continue; + // click to move the caret, drag or shift+click to select, double click for a word. clicks count inside the box, + // the text is drawn from text_x. returns whether it was clicked + handle_mouse(box: { x: number; y: number; width: number; height: number }, text_x: number, scale = TEXT_SCALE) { + const mouse = InputManager.get_mouse_position(); + if ( + InputManager.is_mouse_pressed(0) && + point_inside_rec(mouse.x, mouse.y, box.x, box.y, box.width, box.height) + ) { + const index = this.index_at(mouse.x - text_x, scale); + const now = performance.now(); + if (now - this.#last_click < DOUBLE_CLICK_MS) { + let start = index; + while (start > 0 && this.value[start - 1] !== " ") start--; + this.anchor = start; + this.caret = this.word_end(index); + this.#dragging = false; + this.#last_click = -Infinity; + } else { + const shift = InputManager.is_key_down("ShiftLeft") || InputManager.is_key_down("ShiftRight"); + this.move_caret(index, shift); + this.#dragging = true; + this.#last_click = now; } - this.value = this.value.slice(0, this.caret) + char + this.value.slice(this.caret); - this.caret += 1; + return true; } + if (!InputManager.is_mouse_down(0)) { + this.#dragging = false; + } else if (this.#dragging) { + this.move_caret(this.index_at(mouse.x - text_x, scale), true); + } + return false; + } + + // the gap between characters nearest to x pixels from the start of the text + index_at(x: number, scale = TEXT_SCALE) { + let previous = 0; + for (let i = 1; i <= this.value.length; i++) { + const width = measure_text(this.value.slice(0, i), scale); + if (width >= x) { + return x - previous < width - x ? i - 1 : i; + } + previous = width; + } + return this.value.length; } // where the caret goes when the text starts at x @@ -75,6 +209,31 @@ export class TextInput { return x + measure_text(this.value.slice(0, this.caret), scale); } + // behind the selected text, when the text starts at x + draw_selection(x: number, y: number, height: number, scale = TEXT_SCALE) { + const [start, end] = this.selection(); + if (start === end) { + return; + } + const x0 = x + measure_text(this.value.slice(0, start), scale); + const x1 = x + measure_text(this.value.slice(0, end), scale); + draw_rect(x0, y, x1 - x0, height, SELECTION_COLOR); + } + + // pressed this frame, or held long enough to repeat like the os does + #fires(key: KeyCode, now: number) { + if (InputManager.is_key_pressed(key)) { + this.#repeat_key = key; + this.#repeat_timer = now; + return true; + } + if (this.#repeat_key === key && InputManager.is_key_down(key) && now - this.#repeat_timer > REPEAT_DELAY_MS) { + this.#repeat_timer = now - (REPEAT_DELAY_MS - REPEAT_RATE_MS); + return true; + } + return false; + } + static caret_visible() { return Math.floor(performance.now() / CARET_BLINK_MS) % 2 === 0; } @@ -150,11 +309,9 @@ export class EditBox { return this.input.value; } - // returns whether it was clicked, so the screen can move focus to it + // returns whether it was clicked, so the screen can move focus to it. the click also moves the caret there handle_input(): boolean { - const mouse = InputManager.get_mouse_position(); - const clicked = this.active && InputManager.is_mouse_pressed(0) && - point_inside_rec(mouse.x, mouse.y, this.x, this.y, this.width, this.height); + const clicked = this.active && this.input.handle_mouse(this, this.#text_x); if (clicked) { InputManager.consume_mouse(0); } @@ -168,8 +325,11 @@ export class EditBox { const ui = AssetManager.instance.get("bworld:ui"); draw_nine_slice(ui, this.focused ? 320 : 304, 0, 16, 16, 4, 4, 4, 4, this.x, this.y, this.width, this.height); - const text_x = this.x + 10; + const text_x = this.#text_x; const text_y = this.y + (this.height - TEXT_HEIGHT * TEXT_SCALE) / 2; + if (this.focused && this.active) { + this.input.draw_selection(text_x, text_y, TEXT_HEIGHT * TEXT_SCALE); + } if (this.value === "" && !this.focused) { draw_text(this.hint, text_x, text_y, TEXT_SCALE, [0.6, 0.6, 0.6, 1]); } else { @@ -179,4 +339,8 @@ export class EditBox { draw_rect(this.input.caret_x(text_x), text_y, 2, TEXT_HEIGHT * TEXT_SCALE); } } + + get #text_x() { + return this.x + 10; + } } diff --git a/client/input_manager.ts b/client/input_manager.ts index 3050409..e7e141e 100644 --- a/client/input_manager.ts +++ b/client/input_manager.ts @@ -53,6 +53,8 @@ export type KeyCode = | "ShiftRight" | "ControlLeft" | "ControlRight" + | "MetaLeft" + | "MetaRight" | "AltLeft" | "AltRight" | "Home" @@ -92,6 +94,8 @@ export class InputManager { // in the order they were typed. a list, since the same letter can be typed twice in one frame static typed_characters: string[] = []; + // letters pressed with ctrl (cmd on macs) held, like "a" for select all + static shortcuts: string[] = []; static pointer_lock_flag = false; static mouse_grab_timer = 0; @@ -110,7 +114,11 @@ export class InputManager { } this.keys_down.add(e.code); if (e.key.length === 1) { - this.typed_characters.push(e.key); + if (this.#is_shortcut(e)) { + this.shortcuts.push(e.key.toLowerCase()); + } else { + this.typed_characters.push(e.key); + } } }); @@ -222,6 +230,16 @@ export class InputManager { this.mouse_buttons_consumed.add(button); } + // ctrl (cmd on macs) held for a shortcut. altgr types characters like @ and comes as ctrl+alt on windows, so it + // isn't one. getModifierState("AltGraph") isn't used, some linux layouts report it along with plain ctrl + static #is_shortcut(e: KeyboardEvent) { + return e.metaKey || (e.ctrlKey && !e.altKey); + } + + static is_shortcut_pressed(letter: string): boolean { + return this.shortcuts.includes(letter); + } + static get_typed_characters(): string[] { const chars = this.typed_characters; this.typed_characters = []; @@ -237,6 +255,7 @@ export class InputManager { this.mouse_delta_y = 0; this.wheel_delta = 0; this.typed_characters = []; + this.shortcuts = []; this.mouse_buttons_consumed.clear(); } diff --git a/tests/text_input_test.ts b/tests/text_input_test.ts new file mode 100644 index 0000000..6cd8f85 --- /dev/null +++ b/tests/text_input_test.ts @@ -0,0 +1,62 @@ +import { assertEquals } from "@std/assert"; +import { TextInput } from "$/client/gui/widgets.ts"; + +// the text with the selection in [brackets], or a | at the caret when nothing is selected +function show(input: TextInput) { + const [start, end] = input.selection(); + if (start === end) { + return input.value.slice(0, start) + "|" + input.value.slice(start); + } + return input.value.slice(0, start) + "[" + input.value.slice(start, end) + "]" + input.value.slice(end); +} + +Deno.test("typing and pasting replace the selection", () => { + const input = new TextInput("hello world"); + input.move_caret(6); + input.move_caret(11, true); + assertEquals(show(input), "hello [world]"); + assertEquals(input.selected_text(), "world"); + + input.insert("there"); + assertEquals(show(input), "hello there|"); + + input.select_all(); + assertEquals(show(input), "[hello there]"); + input.insert("two\r\nlines\tand a tab"); + assertEquals(show(input), "two lines and a tab|"); +}); + +Deno.test("pasting keeps what fits and what's allowed", () => { + const input = new TextInput("ab", 5, (char) => /[a-z]/.test(char)); + input.insert("c-d-e-f"); + assertEquals(show(input), "abcde|"); + + // nothing fits, so the selection isn't deleted either + input.move_caret(0, true); + input.insert("123"); + assertEquals(show(input), "[abcde]"); +}); + +Deno.test("deleting takes the selection, or back to where it's asked", () => { + const input = new TextInput("say hello there"); + input.move_caret(4); + input.move_caret(10, true); + input.delete_to(input.caret - 1); + assertEquals(show(input), "say |there"); + + input.move_caret(input.value.length); + input.delete_to(input.word_start(input.caret)); + assertEquals(show(input), "say |"); + input.delete_to(input.caret - 1); + assertEquals(show(input), "say|"); +}); + +Deno.test("word jumps skip spaces and stop at the next word", () => { + const input = new TextInput("/give bworld:carrot 5"); + assertEquals(input.word_start(22), 21); + assertEquals(input.word_start(21), 7); + assertEquals(input.word_start(7), 0); + assertEquals(input.word_end(0), 7); + assertEquals(input.word_end(7), 21); + assertEquals(input.word_end(21), 22); +});