Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 86x 26x 5x 1x 2x 8x 1x 10x 1x 10x 1x 1x 1x 48x 13x 1x 3x 12x 14x 1x 10x 1x 6x 4x 42x 21x 8x 21x 8x 12x 12x 4x 6x 1x 2x 8x 4x 12x 12x 4x 2x 12x 6x 6x 6x 24x 1x 12x 1x 1x 1x 91x 83x 1x 1x 6x 2x 10x 10x 10x 10x 10x 33x 33x 33x 33x 15x 33x 33x 33x 14x 2x 27x 34x 23x 27x 1x 1x 26x 24x 16x 16x 16x 34x 34x | import "./touch-keyboard.css";
import { navbarHeightOf } from "./floating-panel.js";
import { toast } from "./toast.js";
const StorageKey = "touchKeyboardOpen";
const LayerStorageKey = "touchKeyboardLayer";
const PresetStorageKey = "touchPadPreset";
const NarrowScreenQuery = "(max-width: 700px)";
const TouchQuery = "(pointer: coarse)";
const AnyTouchQuery = "(any-pointer: coarse)";
const PhoneShortSidePx = 500;
const LandscapePhoneQuery = `(orientation: landscape) and (max-height: ${PhoneShortSidePx}px)`;
// In the machine's own time, which falls behind the wall clock when the page is busy. The OS scans the keyboard every
// 10 ms and misses a press shorter than two scans, and reads SHIFT and CTRL some 20 ms after BREAK comes up.
const MinHoldMs = 40;
const BreakGraceMs = 100;
const BreakModifiers = new Set(["SHIFT", "CTRL"]);
// A touch in the gap between keys goes to the nearest key if it is within this many CSS pixels of one.
const GapReachPx = 8;
const VibrateMs = 8;
const BreakKey = "BREAK";
// The narrowest margin the pad takes beside the picture: room for its d-pad and a row of four keys.
const PadSidePx = 156;
const OpenClass = "touch-keyboard-open";
const NavbarHiddenClass = "touch-keyboard-navbar-hidden";
const BesidePictureClass = "touch-keyboard-beside-picture";
const LandscapeClass = "landscape";
const OnPadClass = "on-pad";
const HeldClass = "held";
const ShiftedClass = "shifted";
// Safari has no vibrate, which eslint-plugin-compat objects to; the optional call is the guard.
// eslint-disable-next-line compat/compat
const buzz = () => navigator.vibrate?.(VibrateMs);
/**
* A key on the glass. `key` names a position in the model's key table, or BREAK; `sub` is the shifted legend the
* keycap prints above; `digit` follows the legend, small and on its baseline; `w` is the columns the key spans (flex
* weight outside the grid) and `rows` the rows.
*/
const k = (label, key, ...extra) => Object.assign({ label, key, w: 1 }, ...extra);
const letters = (row) => [...row].map((c) => k(c, c));
const gap = (w) => ({ w });
const small = { cls: "small" };
const BottomRow = (layerLabel, layer) => [
k(layerLabel, null, { w: 1.6, cls: "layer", layer }),
k("ESC", "ESCAPE", { w: 1.2 }, small),
k("CTRL", "CTRL", { w: 1.2 }, small),
k("SPACE", "SPACE", { w: 3.6 }),
...[
["←", "LEFT"],
["↓", "DOWN"],
["↑", "UP"],
["→", "RIGHT"],
].map(([label, key]) => k(label, key, { w: 0.9, cls: "cursor" })),
];
export const FunctionRow = [
...[0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map((n) => k("f", `F${n}`, { cls: "fkey", digit: `${n}` })),
gap(0.5),
k("BREAK", BreakKey, { w: 1.6 }, small),
];
/**
* Every row but the last goes in a 12-column grid; the last is the bottom row, the same on every layer, in flex
* weights.
*/
export const Layers = {
main: [
[
...[..."1234567890"].map((digit, i) => k(digit, `K${digit}`, { sub: "!\"#$%&'()"[i] })),
k("-", "MINUS", { sub: "=" }),
k("^", "HAT_TILDE", { sub: "~" }),
],
[...letters("QWERTYUIOP"), k("@", "AT"), k("RETURN", "RETURN", { rows: 2, cls: "small vertical" })],
[...letters("ASDFGHJKL"), k(";", "SEMICOLON_PLUS", { sub: "+" }), k(":", "COLON_STAR", { sub: "*" })],
[
k("SHIFT", "SHIFT", { cls: "tiny" }),
...letters("ZXCVBNM"),
k(",", "COMMA", { sub: "<" }),
k(".", "PERIOD", { sub: ">" }),
k("/", "SLASH", { sub: "?" }),
k("DEL", "DELETE", { cls: "tiny" }),
],
BottomRow("more", "more"),
],
more: [
[k("pad", null, { w: 2, cls: "layer", layer: "pad" }), gap(9), k("\\", "PIPE_BACKSLASH", { sub: "|" })],
[
k("TAB", "TAB", { w: 2 }, small),
gap(7),
k("[", "LEFT_SQUARE_BRACKET", { sub: "{" }),
k("]", "RIGHT_SQUARE_BRACKET", { sub: "}" }),
k("_", "UNDERSCORE_POUND", { sub: "£" }),
],
[k("CAPS", "CAPSLOCK", { w: 2 }, small), gap(8), k("RETURN", "RETURN", { w: 2 }, small)],
[
k("SH LK", "SHIFTLOCK", { w: 2 }, small),
k("SHIFT", "SHIFT", { w: 2 }, small),
gap(4),
k("DEL", "DELETE", { w: 2 }, small),
k("COPY", "COPY", { w: 2, cls: "small cursor" }),
],
BottomRow("ABC", "main"),
],
};
const DpadRoles = ["left", "right", "up", "down"];
const DpadArrows = { left: "←", right: "→", up: "↑", down: "↓" };
const MaxKeysPerLine = 5;
const action = (key, label, role) => ({ key, label, role });
const group = (name, shape, side, use, actions) => ({ name, shape, side, use, actions });
const move = (keys, labels) =>
group(
"move",
"dpad",
"left",
"core",
DpadRoles.map((role, i) => action(keys[i], labels[i], role)),
);
const legends = (keys) => keys.map((key) => action(key, null, null));
/** ESC, Y and N and the digits, for the prompts between goes; a preset keeps them unless it has a better use for the room. */
export const PromptGroups = [
group("answers", "row", "left", "often", legends(["ESCAPE", "Y", "N"])),
group("digits", "row", "right", "often", legends([..."1234567890"].map((digit) => `K${digit}`))),
];
/**
* Game pad layouts, as data in the shape per-game controls will take. A preset is a list of groups, each with a shape,
* the thumb it is for, whether it is in use all the time (core) or often, and actions that name the BBC key pressed,
* what it does in the game (null where the key's own legend says it) and its role in the group. The shapes:
* - `dpad`: the four directions by role, left, right, up and down;
* - `buttons`: the big buttons, by role `fire` and `second`;
* - `column`: keys one above another in order, as a rocker such as aim up, centre and down reads;
* - `row`: keys side by side in order, in even lines when there are many.
*/
export const PadPresets = {
classic: {
title: "classic",
groups: [
move(["Z", "X", "COLON_STAR", "SLASH"], [null, null, null, null]),
group("buttons", "buttons", "right", "core", [
action("RETURN", null, "fire"),
action("SPACE", null, "second"),
]),
...PromptGroups,
],
},
// Kieran's keys for the Bitshifters ports: 1942, Paradroid, Stryker's Run Redux.
zxmkl: {
title: "ZXMKL",
groups: [
move(["Z", "X", "K", "M"], [null, null, null, null]),
group("buttons", "buttons", "right", "core", [
action("L", "fire", "fire"),
action("SPACE", "action", "second"),
]),
...PromptGroups,
group("enter", "row", "right", "often", legends(["RETURN"])),
],
},
// Superior's Exile (1988), by how often each is used; the keys are from the action table in Level 7's disassembly.
exile: {
title: "Exile",
groups: [
move(["Q", "W", "P", "L"], [null, null, "jet / jump", null]),
group("body", "row", "left", "often", [
action("AT", "boost", "booster"),
action("S", "store", "store"),
action("G", "get", "retrieve"),
action("TAB", "turn", "turn"),
action("CTRL", "lie", "lie-down"),
]),
group(
"weapons",
"row",
"right",
"often",
["jet", "pistol", "icer", "blast", "plasma", "suit"].map((label, n) => action(`F${n}`, label, label)),
),
group("fire", "buttons", "right", "core", [action("SPACE", "fire", "fire")]),
group("aim", "column", "right", "core", [
action("O", "aim ▲", "up"),
action("I", "aim ●", "centre"),
action("K", "aim ▼", "down"),
]),
group("hand", "row", "right", "core", [
action("COMMA", "pick up", "pick-up"),
action("M", "drop", "drop"),
action("PERIOD", "throw", "throw"),
]),
],
},
};
/**
* Where each side's groups go, top to bottom: its often groups as rows, its core d-pad or big buttons with its core
* columns beside them, then its core rows.
*/
export function placeGroups(groups) {
const side = (name) => {
const mine = groups.filter((each) => each.side === name);
const core = mine.filter((each) => each.use === "core");
return {
often: mine.filter((each) => each.use === "often"),
thumb: core.find((each) => each.shape === "dpad" || each.shape === "buttons") ?? null,
columns: core.filter((each) => each.shape === "column"),
rows: core.filter((each) => each.shape === "row"),
};
};
return { left: side("left"), right: side("right") };
}
/** How many keys a row of `count` puts on each line, so that its lines come out even. */
export const keysPerLine = (count) => Math.ceil(count / Math.ceil(count / MaxKeysPerLine));
/** The `GP.` URL parameter whose key each role of the d-pad and big buttons takes, so one remap moves a gamepad and the pad. */
const GamepadControlByRole = { left: "LEFT", right: "RIGHT", up: "UP", down: "DOWN", fire: "FIRE", second: "START" };
/** `preset` with the keys the URL gave a gamepad's directions, FIRE and START in place of its own. */
export function followingGamepad(preset, remapped) {
const follow = (each) => {
if (each.shape !== "dpad" && each.shape !== "buttons") return each;
const actions = each.actions.map((one) => {
const key = remapped[GamepadControlByRole[one.role]];
return key ? { ...one, key } : one;
});
return { ...each, actions };
};
return { ...preset, groups: preset.groups.map(follow) };
}
/**
* The keys a d-pad presses for a touch at `x`, `y`: its outer thirds are the directions, so a corner presses two.
* A touch past its edge counts as on the edge, so a thumb that slides off keeps its direction.
*/
export function dpadKeysAt(box, x, y, keyFor) {
const third = (from, size, at) => Math.min(2, Math.max(0, Math.floor(((at - from) / size) * 3)));
const column = third(box.left, box.width, x);
const row = third(box.top, box.height, y);
const roles = [column === 0 && "left", column === 2 && "right", row === 0 && "up", row === 2 && "down"];
return roles.filter((role) => role).map((role) => keyFor[role]);
}
/** The Model B's lights, along the bottom left of its keyboard. */
const Leds = [
["cassette motor", (processor) => processor.tapeInterface.motorOn],
["caps lock", (processor) => processor.sysvia.capsLockLight],
["shift lock", (processor) => processor.sysvia.shiftLockLight],
];
const FunctionRowKeys = new Set(FunctionRow.map((def) => def.key));
const LayerNames = [...Object.keys(Layers), "pad"];
const UprightHint = "Turn the phone upright to type.";
/** What each key's cap says, by the key it presses, for the pad's buttons to say the same. */
const LegendOf = new Map(
[FunctionRow, ...Object.values(Layers).flat()]
.flat()
.filter((def) => def.key)
.map(({ key, label, sub, digit, cls }) => [key, { label, sub, digit, cls }]),
);
const padKey = (key, meaning, cls) => {
const legend = LegendOf.get(key) ?? { label: key };
return k(legend.label, key, legend, { meaning, cls: `${legend.cls ?? ""} ${cls}` });
};
/** How the keyboard starts, "open" or "closed", or null where it is not offered. */
export const touchKeyboardStart = (forced, matches) => {
if (forced || matches(TouchQuery) || matches(NarrowScreenQuery)) return "open";
return matches(AnyTouchQuery) ? "closed" : null;
};
/**
* The keys held on the glass and when the machine is told they are up, in the machine's milliseconds. `send(key,
* down)` presses a key in the matrix, or holds the machine in reset for BREAK.
*/
export class KeyPresses {
constructor(send) {
this.send = send;
/** @type {Map<number, Map<string, number>>} by pointer, the keys it holds and when each went down */
this.held = new Map();
/** @type {Map<string, number>} keys lifted from the glass and not yet sent up, by when they went down */
this.releasing = new Map();
this.resetting = false;
this.breakUpAt = -Infinity;
}
/** Makes `keys` all that a pointer holds, pressing the new ones; true if any was. */
hold(pointerId, keys, now) {
const before = this.held.get(pointerId) ?? new Map();
const after = new Map(keys.map((key) => [key, before.get(key) ?? now]));
for (const [key, pressedAt] of before) if (!after.has(key)) this.releasing.set(key, pressedAt);
if (after.size) this.held.set(pointerId, after);
else this.held.delete(pointerId);
const pressed = keys.filter((key) => !before.has(key));
for (const key of pressed) this.sendKey(key, true);
return pressed.length > 0;
}
release(pointerId) {
this.hold(pointerId, [], null);
}
releaseAll() {
for (const pointerId of [...this.held.keys()]) this.release(pointerId);
}
isHeld(key) {
return [...this.held.values()].some((keys) => keys.has(key));
}
/** SHIFT and CTRL stay down until BREAK has been up a while, so SHIFT+BREAK boots whichever thumb lifts first. */
sendDueReleases(now) {
const isWithin = (since, ms) => now >= since && now - since < ms;
for (const [key, pressedAt] of this.releasing) {
if (this.isHeld(key)) {
this.releasing.delete(key);
continue;
}
if (isWithin(pressedAt, MinHoldMs)) continue;
if (BreakModifiers.has(key) && (this.resetting || isWithin(this.breakUpAt, BreakGraceMs))) continue;
this.releasing.delete(key);
this.sendKey(key, false);
if (key === BreakKey) this.breakUpAt = now;
}
}
sendKey(key, down) {
if (key === BreakKey) this.resetting = down;
this.send(key, down);
}
}
/**
* An on-screen BBC keyboard, and a game pad that a landscape phone shows in the margins beside the picture. Keys go to
* the machine's matrix by position through the same input as the physical keyboard, so held keys and chords work with
* as many fingers as the screen reports.
*/
export class TouchKeyboard {
constructor({ processor, model, keyboard, layout, loop, forced, openMedia, onAnyKeyDown, gamepadRemaps }) {
const start = touchKeyboardStart(forced, (query) => window.matchMedia(query).matches);
if (!start) return;
this.processor = processor;
this.model = model;
this.layout = layout;
this.loop = loop;
this.onAnyKeyDown = onAnyKeyDown;
this.presses = new KeyPresses((key, down) => {
const { input } = keyboard;
if (key === BreakKey) input.setReset(down);
else input.keyRaw(model.keys[key], down);
});
this.presets = { ...PadPresets, classic: followingGamepad(PadPresets.classic, gamepadRemaps) };
const storedPreset = window.localStorage[PresetStorageKey];
this.presetName = Object.hasOwn(PadPresets, storedPreset) ? storedPreset : "classic";
const storedLayer = window.localStorage[LayerStorageKey];
this.portraitLayer = LayerNames.includes(storedLayer) ? storedLayer : "main";
/** @type {Set<number>} pointers that went down on the d-pad, whose keys follow them as they slide */
this.dpadPointers = new Set();
this.navbarWanted = false;
this.root = this.build(openMedia);
this.toggle = this.buildToggle();
document.body.append(this.root, this.toggle);
window.addEventListener("pointermove", (evt) => this.slide(evt));
window.addEventListener("pointerup", (evt) => this.release(evt));
window.addEventListener("pointercancel", (evt) => this.release(evt));
window.addEventListener("blur", () => this.releaseAll());
loop.addEventListener("tick", () => {
this.presses.sendDueReleases(this.machineMs());
this.syncLeds();
});
this.landscapePhone = window.matchMedia(LandscapePhoneQuery);
this.landscapePhone.addEventListener("change", () => {
this.releaseAll();
this.navbarWanted = false;
this.show();
});
new ResizeObserver(() => this.show()).observe(this.root);
const stored = window.localStorage[StorageKey];
this.open = stored ? stored === "true" : start === "open";
this.show();
}
build(openMedia) {
const root = document.createElement("div");
root.id = "touch-keyboard";
const bar = document.createElement("div");
bar.className = "tk-bar";
this.presetButton = this.buildButton("", "tk-preset", () => this.nextPreset());
bar.append(
this.buildButton("☰ menu", "tk-menu", () => this.toggleNavbar()),
this.buildButton("media", "tk-media", openMedia),
this.presetButton,
this.buildButton("⌄ hide", "tk-hide", () => this.setOpen(false)),
);
root.append(bar, this.buildRow(FunctionRow));
this.layers = Object.entries(Layers).map(([name, rows]) => {
const layer = document.createElement("div");
layer.className = "tk-layer";
layer.dataset.name = name;
const grid = document.createElement("div");
grid.className = "tk-grid";
for (const def of rows.slice(0, -1).flat()) grid.append(this.buildKey(def, true));
layer.append(grid, this.buildRow(rows.at(-1)));
return layer;
});
this.padLayer = document.createElement("div");
this.padLayer.className = "tk-layer tk-pad";
this.padLayer.dataset.name = "pad";
this.layers.push(this.padLayer);
this.buildPad();
root.append(...this.layers, this.buildLeds());
root.addEventListener("pointerdown", (evt) => this.press(evt));
for (const type of ["contextmenu", "selectstart", "mousedown"]) {
root.addEventListener(type, (evt) => evt.preventDefault());
}
// iOS ignores a cancelled pointerdown and runs its long-press text selection on the page around the keys.
root.addEventListener(
"touchstart",
(evt) => {
if (!evt.target.closest("button")) evt.preventDefault();
},
{ passive: false },
);
return root;
}
/** The chosen preset's groups, placed by `placeGroups` on the side of the thumb each is for. */
buildPad() {
const { title, groups } = this.presets[this.presetName];
this.presetButton.textContent = `⇄ ${title}`;
const div = (className, ...children) => {
const el = document.createElement("div");
el.className = className;
el.append(...children);
return el;
};
const keyOf = (one, cls) => this.buildKey(padKey(one.key, one.label, cls), false);
const onFunctionRow = (one) => (FunctionRowKeys.has(one.key) ? "on-function-row" : "");
const row = (keys, visibleCount, cls) => {
const el = div(`tk-pad-group tk-pad-row ${cls}`, ...keys);
el.style.setProperty("--per-line", String(keysPerLine(visibleCount)));
return el;
};
const oftenRow = ({ actions }, extra) =>
row(
[...actions.map((one) => keyOf(one, onFunctionRow(one))), ...extra],
actions.length + (extra.length ? 1 : 0),
actions.every((one) => onFunctionRow(one)) ? "on-function-row" : "",
);
// One of the two shows, by orientation.
const layerKeys = [
this.buildKey(k("ABC", null, { cls: "layer portrait", layer: "main" }), false),
this.buildKey(k("⌨", null, { cls: "layer landscape", hint: UprightHint }), false),
];
this.dpad = null;
this.dpadKeys = {};
const thumb = (control) => {
if (control.shape === "buttons") {
const onlyFire = control.actions.every((one) => one.role !== "second");
return div(
`tk-pad-fire${onlyFire ? " only-fire" : ""}`,
...control.actions.map((one) => keyOf(one, one.role)),
);
}
this.dpadKeys = Object.fromEntries(control.actions.map((one) => [one.role, one.key]));
this.dpad = div(
"tk-dpad",
...control.actions.map((one) =>
this.buildKey({ ...padKey(one.key, one.label, one.role), arrow: DpadArrows[one.role] }, false),
),
div("tk-dpad-hub"),
);
return div("tk-dpad-room", this.dpad);
};
const side = (name, { often, thumb: control, columns, rows }) => {
const oftenRows = often.map((each, i) => oftenRow(each, name === "left" && i === 0 ? layerKeys : []));
if (name === "left" && !often.length) oftenRows.push(row(layerKeys, 1, ""));
return div(
`tk-pad-side ${name}`,
...oftenRows,
div(
"tk-pad-core",
thumb(control),
...columns.map(({ actions }) =>
div("tk-pad-group tk-pad-column", ...actions.map((one) => keyOf(one, ""))),
),
),
...rows.map(({ actions }) =>
row(
actions.map((one) => keyOf(one, "")),
actions.length,
"",
),
),
);
};
const sides = placeGroups(groups);
this.padLayer.replaceChildren(side("left", sides.left), side("right", sides.right));
}
nextPreset() {
const names = Object.keys(this.presets);
this.presetName = names[(names.indexOf(this.presetName) + 1) % names.length];
window.localStorage[PresetStorageKey] = this.presetName;
this.releaseAll();
this.buildPad();
}
toggleNavbar() {
this.navbarWanted = !this.navbarWanted;
this.show();
}
buildButton(text, className, onClick) {
const button = document.createElement("button");
button.type = "button";
button.tabIndex = -1;
button.className = className;
button.textContent = text;
button.addEventListener("click", onClick);
return button;
}
buildLeds() {
const leds = document.createElement("div");
leds.className = "tk-leds";
this.leds = Leds.map(([label, lit]) => {
const light = document.createElement("span");
light.textContent = label;
const led = document.createElement("i");
light.append(led);
leds.append(light);
return { led, lit };
});
const hint = document.createElement("span");
hint.className = "tk-rotate-hint";
hint.textContent = "rotate for gamepad";
hint.hidden =
!window.matchMedia(TouchQuery).matches || Math.min(screen.width, screen.height) > PhoneShortSidePx;
leds.append(hint);
return leds;
}
syncLeds() {
if (this.root.hidden) return;
for (const { led, lit } of this.leds) led.classList.toggle("on", !!lit(this.processor));
}
buildRow(row) {
const rowEl = document.createElement("div");
rowEl.className = "tk-row";
for (const def of row) rowEl.append(this.buildKey(def, false));
return rowEl;
}
buildKey(def, inGrid) {
const el = document.createElement("div");
if (inGrid) {
el.style.gridColumn = `span ${def.w}`;
if (def.rows) el.style.gridRow = `span ${def.rows}`;
} else {
el.style.flexGrow = def.w;
}
if (!def.label) return el;
el.className = `tk-key ${def.cls ?? ""}`;
const span = (className, text) => {
const child = document.createElement("span");
child.className = className;
child.textContent = text;
return child;
};
if (def.arrow) el.append(span("tk-arrow", def.arrow));
if (def.sub) el.append(span("tk-shifted", def.sub));
const label = span("", def.label);
if (def.digit) label.append(span("tk-digit", def.digit));
el.append(label);
if (def.meaning) {
el.classList.add("meaning");
el.append(span("tk-meaning", def.meaning));
}
el.def = def;
return el;
}
buildToggle() {
const toggle = this.buildButton("⌨", "", () => this.setOpen(true));
toggle.id = "touch-keyboard-toggle";
toggle.title = "Show the on-screen keyboard";
toggle.setAttribute("aria-label", toggle.title);
return toggle;
}
setOpen(open) {
this.open = open;
window.localStorage[StorageKey] = String(open);
this.show();
}
/** Upright, the keys go below the picture; a landscape phone has room only beside it, and there shows the pad. */
show() {
const landscape = this.landscapePhone.matches;
const layer = landscape ? "pad" : this.portraitLayer;
this.root.hidden = !this.open;
this.toggle.hidden = this.open;
this.root.classList.toggle(LandscapeClass, landscape);
this.root.classList.toggle(OnPadClass, layer === "pad");
for (const el of this.layers) el.hidden = el.dataset.name !== layer;
document.body.classList.toggle(OpenClass, this.open);
document.body.classList.toggle(BesidePictureClass, this.open && landscape);
document.body.classList.toggle(NavbarHiddenClass, this.open && landscape && !this.navbarWanted);
if (!this.open) {
this.releaseAll();
this.layout.reserveForTouchKeyboard(null);
return;
}
this.layout.reserveForTouchKeyboard(
landscape ? { below: 0, beside: PadSidePx } : { below: this.root.offsetHeight, beside: 0 },
);
const side = (window.innerWidth - this.layout.cubMonitor.offsetWidth) / 2;
this.root.style.setProperty("--tk-side", `${side}px`);
this.root.style.setProperty("--tk-top", `${navbarHeightOf(document.getElementById("header-bar"))}px`);
}
chooseLayer(name) {
this.releaseAll();
this.portraitLayer = name;
window.localStorage[LayerStorageKey] = name;
this.show();
}
press(evt) {
if (evt.target.closest("button")) return;
if (this.presses.held.has(evt.pointerId) || this.dpadPointers.has(evt.pointerId)) return;
if (evt.target.closest(".tk-dpad")) {
evt.preventDefault();
if (!this.loop.running) return;
this.dpadPointers.add(evt.pointerId);
this.slide(evt);
return;
}
const el = evt.target.closest(".tk-key") ?? this.nearestKey(evt.clientX, evt.clientY);
if (!el) return;
evt.preventDefault();
const { def } = el;
if (def.layer) this.chooseLayer(def.layer);
else if (def.hint) toast(def.hint);
else if (this.loop.running) this.presses.hold(evt.pointerId, [def.key], this.machineMs());
else return;
buzz();
this.onAnyKeyDown();
this.showHeld();
}
/** A thumb on the d-pad presses what is under it now, so it can roll from one direction through a diagonal. */
slide(evt) {
if (!this.dpadPointers.has(evt.pointerId)) return;
const keys = dpadKeysAt(this.dpad.getBoundingClientRect(), evt.clientX, evt.clientY, this.dpadKeys);
const holding = this.presses.held.get(evt.pointerId) ?? new Map();
if (keys.length === holding.size && keys.every((key) => holding.has(key))) return;
if (this.presses.hold(evt.pointerId, keys, this.machineMs())) {
buzz();
this.onAnyKeyDown();
}
this.showHeld();
}
/** A touch's pointerdown does not count as a user gesture for starting audio, but its pointerup does. */
release(evt) {
this.dpadPointers.delete(evt.pointerId);
if (!this.presses.held.has(evt.pointerId)) return;
this.onAnyKeyDown();
this.presses.release(evt.pointerId);
this.showHeld();
}
/** The key whose face is closest to a touch that landed in a gap, so the gaps are part of the keys. */
nearestKey(x, y) {
let nearest = null;
let nearestDistance = GapReachPx;
for (const el of this.root.querySelectorAll(".tk-key")) {
const box = el.getBoundingClientRect();
if (box.width === 0) continue;
const distance = Math.hypot(
Math.max(box.left - x, 0, x - box.right),
Math.max(box.top - y, 0, y - box.bottom),
);
if (distance < nearestDistance) {
nearest = el;
nearestDistance = distance;
}
}
return nearest;
}
releaseAll() {
this.dpadPointers.clear();
this.presses.releaseAll();
this.showHeld();
}
/** Lights every key held, and the shifted legends while SHIFT is. */
showHeld() {
for (const el of this.root.querySelectorAll(".tk-key")) {
el.classList.toggle(HeldClass, this.presses.isHeld(el.def.key));
}
this.root.classList.toggle(ShiftedClass, this.presses.isHeld("SHIFT"));
}
machineMs() {
const { processor } = this;
return (processor.cycleSeconds + processor.currentCycles / this.model.cyclesPerSecond) * 1000;
}
}
|