Files
bworld/client/gui/widgets.ts
T

443 lines
14 KiB
TypeScript

// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
import { point_inside_rec } from "@/common/utils.ts";
import { InputManager, type KeyCode } from "@/client/input_manager.ts";
import { draw_rect, draw_rect_stroke, draw_text, measure_text } from "@/client/renderer/mod.ts";
import { draw_gui_sprite } from "./gui_sprites.ts";
import { platform } from "@/client/platform.ts";
export const TEXT_SCALE = 2;
// how tall the font is at scale 1
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;
// catppuccin mocha's pink, like the gui sprites' highlights
const SELECTION_COLOR: [number, number, number, number] = [0.96, 0.76, 0.91, 0.45];
// 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();
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();
}
const copy = InputManager.is_shortcut_pressed("c");
const cut = InputManager.is_shortcut_pressed("x");
if ((copy || cut) && this.anchor !== this.caret) {
platform.write_clipboard(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
platform.read_clipboard().then((text) => this.insert(text), () => {});
}
for (const char of InputManager.get_typed_characters()) {
this.insert(char);
}
if (this.#fires("Backspace", now)) {
this.delete_to(word ? this.word_start(this.caret) : this.caret - 1);
}
if (this.#fires("Delete", now)) {
this.delete_to(word ? this.word_end(this.caret) : 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.move_caret(0, shift);
}
if (InputManager.is_key_pressed("End")) {
this.move_caret(this.value.length, shift);
}
}
// 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;
}
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
caret_x(x: number, scale = TEXT_SCALE) {
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;
}
}
// a clickable button, like minecraft's Button
export class Button {
x = 0;
y = 0;
width: number;
height: number;
label: string;
on_press: () => void;
active = true;
#hovered = false;
constructor(label: string, width: number, height: number, on_press: () => void) {
this.label = label;
this.width = width;
this.height = height;
this.on_press = on_press;
}
// returns whether it was pressed
handle_input(): boolean {
const mouse = InputManager.get_mouse_position();
this.#hovered = this.active && point_inside_rec(mouse.x, mouse.y, this.x, this.y, this.width, this.height);
if (this.#hovered && InputManager.is_mouse_pressed(0)) {
InputManager.consume_mouse(0);
this.on_press();
return true;
}
return false;
}
render() {
const sprite = !this.active ? "button_disabled" : this.#hovered ? "button_highlighted" : "button";
draw_gui_sprite(sprite, this.x, this.y, this.width, this.height);
const text_width = measure_text(this.label, TEXT_SCALE);
draw_text(
this.label,
this.x + (this.width - text_width) / 2,
this.y + (this.height - TEXT_HEIGHT * TEXT_SCALE) / 2,
TEXT_SCALE,
this.active ? [1, 1, 1, 1] : [0.7, 0.7, 0.7, 1],
);
}
}
// a one line text field, like minecraft's EditBox. clicking it gives it the keyboard
export class EditBox {
x = 0;
y = 0;
width: number;
height: number;
input: TextInput;
focused = false;
// shown greyed out while it's empty
hint: string;
active = true;
constructor(width: number, height: number, input: TextInput, hint = "") {
this.width = width;
this.height = height;
this.input = input;
this.hint = hint;
}
get value() {
return this.input.value;
}
// returns whether it was clicked, so the screen can move focus to it. the click also moves the caret there
handle_input(): boolean {
const clicked = this.active && this.input.handle_mouse(this, this.#text_x);
if (clicked) {
InputManager.consume_mouse(0);
}
if (this.focused && this.active) {
this.input.handle_keys();
}
return clicked;
}
render() {
const sprite = this.focused ? "text_field_highlighted" : "text_field";
draw_gui_sprite(sprite, this.x, this.y, this.width, this.height);
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 {
draw_text(this.value, text_x, text_y, TEXT_SCALE, this.active ? [1, 1, 1, 1] : [0.7, 0.7, 0.7, 1]);
}
if (this.focused && this.active && TextInput.caret_visible()) {
draw_rect(this.input.caret_x(text_x), text_y, 2, TEXT_HEIGHT * TEXT_SCALE);
}
}
get #text_x() {
return this.x + 10;
}
}
export const LIST_ROW_HEIGHT = 40;
const CHECK_SIZE = 20;
// rows of text that scroll with the mouse wheel, like minecraft's selection lists. a row can have a box ticked or not
// in front, for lists of things to turn on and off
export class ListBox {
x = 0;
y = 0;
width: number;
height: number;
rows: { text: string; checked?: boolean }[] = [];
selected = -1;
// clicking a row, double is whether it was the second click of a double click
on_click: (row: number, double: boolean) => void;
#scroll = 0;
#hovered = -1;
#last_click = { row: -1, time: -Infinity };
constructor(width: number, height: number, on_click: (row: number, double: boolean) => void) {
this.width = width;
this.height = height;
this.on_click = on_click;
}
get #visible() {
return Math.max(1, Math.floor(this.height / LIST_ROW_HEIGHT));
}
handle_input() {
const mouse = InputManager.get_mouse_position();
const inside = point_inside_rec(mouse.x, mouse.y, this.x, this.y, this.width, this.height);
const max_scroll = Math.max(0, this.rows.length - this.#visible);
if (inside) this.#scroll += Math.sign(InputManager.get_wheel_delta());
this.#scroll = Math.max(0, Math.min(max_scroll, this.#scroll));
const row = this.#scroll + Math.floor((mouse.y - this.y) / LIST_ROW_HEIGHT);
this.#hovered = inside && row < this.rows.length ? row : -1;
if (this.#hovered >= 0 && InputManager.is_mouse_pressed(0)) {
InputManager.consume_mouse(0);
const now = performance.now();
const double = this.#last_click.row === row && now - this.#last_click.time < DOUBLE_CLICK_MS;
this.#last_click = double ? { row: -1, time: -Infinity } : { row, time: now };
this.on_click(row, double);
}
}
render() {
draw_rect(this.x, this.y, this.width, this.height, [0, 0, 0, 0.5]);
const shown = this.rows.slice(this.#scroll, this.#scroll + this.#visible);
for (const [i, row] of shown.entries()) {
const index = this.#scroll + i;
const y = this.y + i * LIST_ROW_HEIGHT;
if (index === this.selected) {
draw_rect(this.x, y, this.width, LIST_ROW_HEIGHT, SELECTION_COLOR);
} else if (index === this.#hovered) {
draw_rect(this.x, y, this.width, LIST_ROW_HEIGHT, [1, 1, 1, 0.1]);
}
let text_x = this.x + 12;
if (row.checked !== undefined) {
const box_y = y + (LIST_ROW_HEIGHT - CHECK_SIZE) / 2;
draw_rect_stroke(text_x, box_y, CHECK_SIZE, CHECK_SIZE, [1, 1, 1, 1], 2);
if (row.checked) draw_rect(text_x + 5, box_y + 5, CHECK_SIZE - 10, CHECK_SIZE - 10);
text_x += CHECK_SIZE + 12;
}
draw_text(row.text, text_x, y + (LIST_ROW_HEIGHT - TEXT_HEIGHT * TEXT_SCALE) / 2, TEXT_SCALE);
}
// how far down it's scrolled, when it doesn't all fit
if (this.rows.length > this.#visible) {
const bar = this.height * this.#visible / this.rows.length;
const bar_y = this.y + (this.height - bar) * this.#scroll / (this.rows.length - this.#visible);
draw_rect(this.x + this.width - 6, bar_y, 6, bar, [1, 1, 1, 0.5]);
}
}
}
// text split into lines no wider than width pixels at TEXT_SCALE, at spaces and at its own line breaks
export function wrap_text(text: string, width: number): string[] {
const lines: string[] = [];
for (const line of text.split("\n")) {
let current = "";
for (const word of line.split(" ")) {
const next = current ? `${current} ${word}` : word;
if (current && measure_text(next, TEXT_SCALE) > width) {
lines.push(current);
current = word;
} else {
current = next;
}
}
lines.push(current);
}
return lines;
}