--- a/vite.config.ts +++ b/vite.config.ts @@ -1,6 +1,5 @@ import { defineConfig } from "vite"; import react from "@vitejs/plugin-react"; -import { VitePWA } from "vite-plugin-pwa"; const buildMonth = new Date().toLocaleString("en-US", { month: "long", @@ -10,23 +9,36 @@ // https://vite.dev/config/ export default defineConfig({ base: "", + build: { + rollupOptions: { + external: ["nethack-wasm-loader"], + output: { + chunkFileNames: "assets/chunk-[name]-[hash].js", + paths: { "nethack-wasm-loader": "./wasm-loader.js" }, + manualChunks(id) { + if (id.includes("/node_modules/react-dom/")) return "react-dom"; + if (id.endsWith("/build/nethack.js")) return "emscripten"; + }, + }, + }, + }, define: { __BUILD_MONTH__: JSON.stringify(buildMonth), }, plugins: [ + { + name: "nethack-wasm-from-parts", + enforce: "pre", + transform(code, id) { + if (id.endsWith("/build/nethack.js")) { + return code.replace('new URL("nethack.wasm",import.meta.url).href', '"nethack.wasm"'); + } + }, + }, react({ babel: { // plugins: ["./tools/babel-plugin-auto-observe.js"], }, }), - VitePWA({ - registerType: "autoUpdate", - workbox: { - globPatterns: [ - "**/*.{js,css,html,webp,wasm,woff,woff2}", - ], - maximumFileSizeToCacheInBytes: 10 * 1024 * 1024, - }, - }), ], }); --- a/index.html +++ b/index.html @@ -1,25 +1,15 @@ - - - - - - - - - - NethackJS + + + + Play NetHack + -
+

Loading NetHack…

+ --- a/lib/wasmBindings.ts +++ b/lib/wasmBindings.ts @@ -3,6 +3,7 @@ // @ts-expect-error: build/nethack.js is emscripten-generated and untyped import createModuleRaw from "../build/nethack.js"; +import { loadWasmBinary } from "nethack-wasm-loader"; type NethackCallback = (name: string, ...args: unknown[]) => Promise; type NethackModule = Partial & { @@ -56,6 +57,7 @@ ).catch(() => {}); }; + Module.wasmBinary = await loadWasmBinary(); const M = await createModule(Module); window.getValue = M.getValue; --- a/src/main.tsx +++ b/src/main.tsx @@ -1,9 +1,19 @@ import { StrictMode } from "react"; import { createRoot } from "react-dom/client"; import { App } from "./App.tsx"; +import { loadWasmBinary } from "nethack-wasm-loader"; -createRoot(document.getElementById("root")!).render( - - - , -); +const root = document.getElementById("root")!; + +loadWasmBinary().then(() => { + createRoot(root).render( + + + , + ); +}).catch((error) => { + const message = document.createElement("p"); + message.setAttribute("role", "alert"); + message.textContent = error instanceof Error ? error.message : "Could not load NetHack. Reload the page to try again."; + root.replaceChildren(message); +}); --- /dev/null +++ b/src/wasm-loader.d.ts @@ -0,0 +1,3 @@ +declare module "nethack-wasm-loader" { + export function loadWasmBinary(): Promise; +} --- a/lib/nethackInterface.ts +++ b/lib/nethackInterface.ts @@ -689,12 +689,9 @@ const parseExtcmdlist = (extcmdlist: number) => { const extCmdList: ExtCmd[] = []; - for (let i = 0; i < 100; i++) { + // The NetHack command table ends with an entry whose name is null. + for (let name = readString(extcmdlist + 4); name; name = readString(extcmdlist + 4)) { const key = String.fromCharCode(getValue(extcmdlist, "i8")); - const name = readString(extcmdlist + 4); - if (!name) { - break; - } const description = readString(extcmdlist + 8) || "unknown description"; const flagsI = getValue(extcmdlist + 16, "i32"); const flags = { @@ -712,32 +709,22 @@ return extCmdList.filter((extCmd) => extCmd.name.startsWith(prefix)); }; -export const getUniqueExtCmdAutocomplete = (prefix: string) => { - const extcmdlist = nethackGlobal.pointers.extcmdlist; - const extCmdList = parseExtcmdlist(extcmdlist); - const cmds = extCmdList.filter( - (extCmd) => extCmd.name.startsWith(prefix) && extCmd.flags.autocomplete, +const matchExtCmd = (commands: ExtCmd[], prefix: string) => { + const exact = commands.find((command) => command.name === prefix); + if (exact) return exact; + const matches = commands.filter( + (command) => command.name.startsWith(prefix) && command.flags.autocomplete, ); - if (cmds.length == 1) { - return cmds[0]; - } + return matches.length === 1 ? matches[0] : null; +}; - const cmds2 = extCmdList.filter((extCmd) => extCmd.name == prefix); - if (cmds2.length == 1) { - return cmds2[0]; - } +export const getUniqueExtCmdAutocomplete = (prefix: string) => + matchExtCmd(parseExtcmdlist(nethackGlobal.pointers.extcmdlist), prefix); - return null; -}; - export const getExtCmdIndex = (extcmd: string) => { - const command = getUniqueExtCmdAutocomplete(extcmd.toLowerCase()); - if (!command) { - return -1; - } - return parseExtcmdlist(nethackGlobal.pointers.extcmdlist).findIndex( - (extCmd) => extCmd.name === command.name, - ); + const commands = parseExtcmdlist(nethackGlobal.pointers.extcmdlist); + const command = matchExtCmd(commands, extcmd.toLowerCase()); + return command ? commands.indexOf(command) : -1; }; /** @@ -892,9 +879,6 @@ } runNethackWasm(async (name: string, ...args: unknown[]) => { - if (typeof getValue !== "undefined") { - parseExtcmdlist(nethackGlobal.pointers.extcmdlist); - } const newName = name .slice(5) // remove "shim_" .split("_") // convert to camelCase --- a/src/App.css +++ b/src/App.css @@ -1,966 +1,212 @@ -:root { - --fg: #d0cfcc; - color: var(--fg); - font-family: "DejaVu Mono"; - --padding: 7px; - --cell-size: 40px; - --dir-size: 200px; - --main-gap: 8px; - user-select: none; - overflow: hidden; - overscroll-behavior: none; - background: #333; - touch-action: none; -} - -@media (max-width: 430px) { - :root { - --cell-size: 36px; - --dir-size: 180px; - --main-gap: 6px; - } -} - -* { +.nethack-terminal { + --fg: #f3ebdc; + --bg: #181613; + --border: #665743; + --padding: 0.6rem; box-sizing: border-box; -} - -body { - margin: 0; - height: 100dvh; + container-type: inline-size; display: grid; - place-items: center; -} - -#root { - width: 100%; - /* height: 100%; */ - display: grid; - justify-items: center; - -webkit-tap-highlight-color: transparent; -} - -#footer { - text-align: center; - a { - color: cyan; - } -} - -#root > main { - --bg: #300a24; - outline: 1px solid grey; - background-color: var(--bg); - display: grid; - grid: auto minmax(0, min-content) auto auto auto / 1fr; - place-items: center; + grid-template-rows: auto minmax(0, 1fr) auto; + grid-template-columns: minmax(0, 1fr); + gap: 3px; align-content: start; - height: 100dvh; - width: min(100vw, calc(80ch + 4 * var(--padding))); - padding: var(--padding); - padding-top: max(var(--padding), env(safe-area-inset-top)); - padding-bottom: max(var(--padding), env(safe-area-inset-bottom)); - padding-left: max(var(--padding), env(safe-area-inset-left)); - padding-right: max(var(--padding), env(safe-area-inset-right)); + width: 100%; + min-width: 0; + height: clamp(22rem, 58svh, 35rem); + padding: 0.5rem; position: relative; + background: var(--bg); + color: var(--fg); + font: clamp(0.78rem, 2.9vw, 0.95rem)/1.35 "DejaVu Mono", ui-monospace, monospace; white-space-collapse: preserve; - justify-items: stretch; } -/** Scrollbars */ - -::-webkit-scrollbar { - width: calc(var(--padding) - 0.5px); +.nethack-terminal :where(*) { + box-sizing: border-box; } -::-webkit-scrollbar-track { - background: #222; +.nethack-terminal:focus-visible { + outline: 2px solid #e9a34b; + outline-offset: -2px; } -::-webkit-scrollbar-thumb { - background: #555; +.nethack-terminal :where(.message, .map-container, .status) { + min-width: 0; + border: 1px solid var(--border); } -@media (hover: hover) { - ::-webkit-scrollbar-thumb:hover { - background: #888; - } -} - -/** Copyright message */ - -.copyright { - position: absolute; - left: 0; - bottom: 0; - padding: calc(2 * var(--padding)); - white-space: normal; - - .line { - padding-top: 2px; - padding-bottom: 2px; - padding-right: var(--padding); - padding-left: calc(2ch + var(--padding)); - &:first-child { - padding-left: 0; - } - } -} - -/** Message window */ - -.message { - height: 3.6lh; - border: 0.5px solid grey; +.nethack-terminal .message { + height: 4.5lh; padding: var(--padding); overflow: auto; display: flex; - flex-direction: column-reverse; /* Auto scroll to the bottom */ - gap: 5px; - box-sizing: content-box; + flex-direction: column-reverse; + gap: 0.2rem; + grid-column: 1; + grid-row: 1; + overflow-wrap: anywhere; +} - .line, - .oldline { - font-size: 0.99em; - } - - .oldline { - --fg: #555; - } +.nethack-terminal .message .oldline { + --fg: #a49887; } -/** Map window */ - -.map-container { +.nethack-terminal .map-container { grid-column: 1; grid-row: 2; display: grid; - place-items: center; + place-content: center; + place-content: safe center; overflow: auto; - height: 100%; - padding: var(--padding); - border: 0.5px solid grey; - touch-action: pinch-zoom; position: relative; - - & * { - scroll-margin: 50px; - } - - &::-webkit-scrollbar { - width: 0px; - height: 0px; - } } -.map { - overflow: auto; - --height: 2ch; - +.nethack-terminal .map { display: grid; - grid: repeat(24, var(--height)) / repeat(80, 1ch); + grid: repeat(24, 1.45em) / repeat(80, 1ch); + font-size: clamp(9px, 2cqi, 1em); + line-height: 1.45; width: 80ch; - height: 48ch; +} - margin: -1px; +.nethack-terminal .map .cell { + white-space: pre; +} - &.displayed { - outline: var(--padding) solid grey; - } +.nethack-terminal .copyright { + position: absolute; + inset: auto 0 0; + padding: var(--padding); + white-space: normal; + background: var(--bg); } -.cell { - &.clickable { - cursor: pointer; - } - - @media (hover: hover) { - &.clickable:hover { - --bg: #444455; - background-color: var(--bg); - } - } - - &.clickable:active { - --bg: #444455; - background-color: var(--bg); - } +.nethack-terminal .copyright .line + .line { + margin-top: 0.15rem; } -/** Temporary windows */ - -.temporary-windows { - position: fixed; - top: 0; - left: 0; - z-index: 10; - width: 100vw; - height: 100dvh; +.nethack-terminal .temporary-windows { + position: absolute; + inset: 0; + z-index: 2; display: grid; - grid: auto / auto; place-items: center; + padding: var(--padding); pointer-events: none; - padding: calc(2 * var(--padding)); - - &.backdrop { - pointer-events: auto; - backdrop-filter: blur(0.7px); - height: 100%; - } } -.text { - padding: var(--padding); - border: 0.5px solid grey; +.nethack-terminal .temporary-windows > * { + grid-area: 1 / 1; max-width: 100%; max-height: 100%; - z-index: 10; + padding: var(--padding); + border: 1px solid var(--border); overflow: auto; - background-color: #300a24f0; - white-space: pre; - - .line { - padding-top: 2px; - padding-bottom: 2px; - } + background: var(--bg); + pointer-events: auto; } -/** Prompts */ - -.prompt { - align-self: start; - justify-self: stretch; - padding: var(--padding); - border: 0.5px solid grey; - grid-column: 1; - grid-row: 2; - display: grid; - align-items: start; - grid: auto / auto; - top: -2px; - z-index: 1; - - * { - grid-row: 1; - grid-column: 1; - } - - .autocomplete { - color: #616161; - z-index: 1; - } - .line { - z-index: 2; - } - - input { - background-color: transparent; - width: auto; - color: inherit; - border: none; - outline: none; - font: inherit; - padding: 0; - z-index: 1; - } +.nethack-terminal :where(.menu, .text) .line { + min-height: 1lh; + white-space: pre-wrap; } -/** Menus */ - -.menu { - padding: var(--padding); - border: 0.5px solid grey; - z-index: 10; - - margin: calc(2 * var(--padding)); - max-width: 100%; - max-height: 100%; - overflow: auto; - --bg: #300a24e0; - background-color: var(--bg); - - .line { - padding-top: 2px; - padding-bottom: 2px; - } -} - -.blocking { - border-color: #7474ff; - --bg: #1e0c33e0; - background-color: var(--bg); -} - -.selected { - --bg: #444455; +.nethack-terminal .window-hint { + position: sticky; + bottom: calc(-1 * var(--padding)); + margin-top: 0.55rem; + padding: 0.45rem 0 0.25rem; + border-top: 1px solid var(--border); background: var(--bg); + color: #e9a34b; + font-size: 0.85em; } -.menu_entry { - cursor: pointer; - background-color: var(--bg); - padding-left: 4ch; +.nethack-terminal .menu_entry { + padding-inline-start: 4ch; text-indent: -4ch; - - @media (hover: hover) { - &:hover { - --bg: #444455; - } - } - - &:active { - --bg: #666; - } } -kbd { - background-color: var(--bg); - cursor: pointer; - font: inherit; - - @media (hover: hover) { - &:hover { - --bg: #444455; - } - } - - &:active { - --bg: #666; - } +.nethack-terminal .selected { + --bg: #594022; + background: var(--bg); } -/** Status window */ - -.status { - display: flex; - flex-wrap: wrap; - column-gap: 1ch; - row-gap: 3px; - border: 0.5px solid grey; - padding: var(--padding); - min-height: 3lh; - - &.compact { - column-gap: 1ch; - row-gap: 1px; - padding: 2px var(--padding); - min-height: 0; - - & > span, & > b { - white-space: nowrap; - } - } +.nethack-terminal .blocking { + --bg: #272016; + border-color: #8b673e; + background: var(--bg); } -/** Mobile inputs */ - -.main-inputs { - display: flex; - flex-direction: row; - align-items: center; - justify-content: space-around; - padding: var(--padding) 0; - gap: var(--main-gap); - - .mod-column { - display: flex; - flex-direction: column; - gap: calc(var(--cell-size) / 3); - } - - .mod-button { - min-width: var(--cell-size); - width: var(--cell-size); - height: var(--cell-size); - padding: 0; - border: 1px solid #ee7474; - border-radius: 5px; - background-color: #431e0c; - display: grid; - place-items: center; - cursor: pointer; - user-select: none; - font-size: 1.2em; - touch-action: manipulation; - - &.armed { - background-color: #622; - border-color: #ffaaaa; - } - - &.locked { - background-color: #833; - border-color: #ffdddd; - box-shadow: inset 0 0 0 1px #ffdddd; - } - - &.kbd-button.active { - background-color: #622; - border-color: #ffaaaa; - } - } - - .shortcut-inputs { - display: grid; - grid: repeat(4, var(--cell-size)) / repeat(3, var(--cell-size)); - gap: calc(var(--cell-size) / 3); - } - - .direction_input { - --border-color: #74ff74; - --inactive-bg-color: #020; - --active-bg-color: #252; - position: relative; - width: var(--dir-size); - height: var(--dir-size); - display: grid; - place-items: center; - - .label { - z-index: 2; - position: absolute; - font-size: calc(var(--dir-size) * 0.075); - white-space: nowrap; - pointer-events: none; - transform: rotate(var(--angle)) - translate(0, calc(var(--dir-size) * -0.325)) - rotate(calc(360deg - var(--angle))); - } - - .center { - position: absolute; - display: grid; - place-items: center; - width: calc(var(--dir-size) * 0.3); - height: calc(var(--dir-size) * 0.3); - border-radius: 100%; - background: #1e0c33; - cursor: pointer; - font-size: calc(var(--dir-size) * 0.075); - - @media (hover: hover) { - &:hover { - background: #225; - } - } - - &:active { - background: #225; - } - } - - .corner { - --offset: -0.5px; - --size: calc(var(--dir-size) * 0.525); - position: absolute; - width: calc(var(--size) - var(--offset)); - height: calc(var(--size) - var(--offset)); - --border-color: #7474ff; - --inactive-bg-color: #1e0c33; - --active-bg-color: #225; - border: 1px solid var(--border-color); - background-color: var(--inactive-bg-color); - display: grid; - border-radius: 10px; - flex-shrink: 0; - cursor: pointer; - padding: calc(var(--dir-size) * 0.075); - font-size: calc(var(--dir-size) * 0.075); - box-sizing: border-box; - - @media (hover: hover) { - &:hover { - background-color: var(--active-bg-color); - } - } - - &:active { - background-color: var(--active-bg-color); - } - - &.top { - top: 0; - align-items: start; - border-bottom-width: 0; - border-bottom-left-radius: 0; - border-bottom-right-radius: 0; - } - - &.bottom { - bottom: 0; - align-items: end; - border-top-width: 0; - border-top-left-radius: 0; - border-top-right-radius: 0; - } - - &.left { - left: 0; - justify-items: start; - border-right-width: 0; - border-top-right-radius: 0; - border-bottom-right-radius: 0; - } - - &.right { - right: 0; - justify-items: end; - border-left-width: 0; - border-top-left-radius: 0; - border-bottom-left-radius: 0; - } - } - - svg { - --border-color: #74ff74; - --inactive-bg-color: #020; - --active-bg-color: #252; - fill: var(--inactive-bg-color); - stroke: var(--border-color); - stroke-width: 1px; - pointer-events: none; - z-index: 1; - - path { - pointer-events: auto; - - @media (hover: hover) { - &:hover { - fill: var(--active-bg-color); - cursor: pointer; - } - } - - &:active { - fill: var(--active-bg-color); - cursor: pointer; - } - } - } - } -} - -.simple_inputs { - overflow-x: scroll; - width: 100%; - display: flex; - flex-direction: row; - gap: 1ch; +.nethack-terminal .prompt { + align-self: start; + grid-column: 1; + grid-row: 2; + z-index: 1; padding: var(--padding); - padding-top: 10px; - padding-bottom: 0; - - & > .simple_input { - width: auto; - padding: 0 8px; - } - - &::-webkit-scrollbar { - width: 0px; - height: 0px; - } - - &.fade-left.fade-right { - mask-image: linear-gradient(to right, transparent, black 20px, black calc(100% - 20px), transparent); - -webkit-mask-image: linear-gradient(to right, transparent, black 20px, black calc(100% - 20px), transparent); - } - - &.fade-left:not(.fade-right) { - mask-image: linear-gradient(to right, transparent, black 20px); - -webkit-mask-image: linear-gradient(to right, transparent, black 20px); - } - - &.fade-right:not(.fade-left) { - mask-image: linear-gradient(to left, transparent, black 20px); - -webkit-mask-image: linear-gradient(to left, transparent, black 20px); - } + border: 1px solid #8b673e; + overflow-wrap: anywhere; } -.simple_input { - min-width: var(--cell-size); - width: var(--cell-size); - height: var(--cell-size); - --border-color: #7474ff; - --inactive-bg-color: #1e0c33; - --active-bg-color: #225; - border: 1px solid var(--border-color); - background-color: var(--inactive-bg-color); - display: grid; - place-items: center; - border-radius: 5px; - flex-shrink: 0; - cursor: pointer; - - @media (hover: hover) { - &:hover { - background-color: var(--active-bg-color); - } - } - - &:active { - background-color: var(--active-bg-color); - } - - &.numlock { - font-size: 0.8em; - } - - &.toggle, - &.numlock { - --border-color: #ee7474; - --inactive-bg-color: #431e0c; - --active-bg-color: #622; - - &.active { - --inactive-bg-color: #833; - --active-bg-color: #a55; - } - } +.nethack-terminal .prompt .autocomplete { + color: #c3ac86; } -.kbd-bar { - position: fixed; - left: 0; - right: 0; - top: var(--bar-top, 200px); - z-index: 12; - display: flex; - align-items: center; - gap: 10px; - padding: 6px 10px; - background-color: #1e0c33; - border-top: 1px solid #7474ff; - box-shadow: 0 -4px 12px rgba(0, 0, 0, 0.5); - - .mod-button { - flex-shrink: 0; - min-width: var(--cell-size); - width: var(--cell-size); - height: var(--cell-size); - padding: 0; - border: 1px solid #7474ff; - border-radius: 5px; - background-color: #140628; - display: grid; - place-items: center; - cursor: pointer; - user-select: none; - font-size: 1em; - touch-action: manipulation; - - &:not(.kbd-dismiss) { - border-color: #ee7474; - background-color: #2a0e08; - } - - &.armed { - background-color: #622; - border-color: #ffaaaa; - } - - &.locked { - background-color: #833; - border-color: #ffdddd; - box-shadow: inset 0 0 0 1px #ffdddd; - } - } - - .kbd-bar-field { - flex: 1; - min-width: 0; - display: flex; - align-items: center; - gap: 4px; - padding: 4px 8px; - border: 1px solid #7474ff; - border-radius: 5px; - background-color: #140628; - } - - .kbd-bar-prefix { - color: #aaaaff; - font-weight: bold; - flex-shrink: 0; - } - - .kbd-bar-input { - flex: 1; - min-width: 0; - background: transparent; - color: inherit; - border: none; - outline: none; - font: inherit; - padding: 0; - } -} - -/** Settings */ - -.play-again-button { - position: fixed; - top: 50%; - left: 50%; - transform: translate(-50%, -50%); - z-index: 11; - padding: 12px 32px; - font: inherit; - font-size: 1.25em; - background-color: #225; +.nethack-terminal .prompt .extcmd { + width: min(24ch, 100%); color: inherit; - border: 1px solid #7474ff; - border-radius: 5px; - cursor: pointer; - box-shadow: 0 4px 16px rgba(0, 0, 0, 0.5); - - @media (hover: hover) { - &:hover { - background-color: #336; - } - } -} - -.gear-button, -.info-button { - position: fixed; - top: max(var(--padding), env(safe-area-inset-top)); - z-index: 11; - width: 32px; - height: 32px; - background-color: #2228; - color: var(--fg); - border: 0.5px solid grey; - border-radius: 4px; - font-family: inherit; - font-size: 18px; - line-height: 1; - cursor: pointer; - user-select: none; - - &:hover { - background-color: #333a; - } -} - -.gear-button { - right: max(var(--padding), env(safe-area-inset-right)); -} - -.info-button { - right: calc(max(var(--padding), env(safe-area-inset-right)) + 40px); -} - -.modal-backdrop { - position: fixed; - top: 0; - left: 0; - z-index: 20; - width: 100vw; - height: 100dvh; - background-color: #0008; - backdrop-filter: blur(0.7px); - display: grid; - place-items: center; - padding: var(--padding); -} - -.modal { - background-color: #300a24f0; - border: 0.5px solid grey; - max-width: 100%; - max-height: 100%; - width: min(560px, 100%); - display: flex; - flex-direction: column; - overflow: hidden; -} - -.modal-header { - display: flex; - justify-content: space-between; - align-items: center; - padding: calc(var(--padding) / 2) var(--padding); - border-bottom: 0.5px solid grey; - - h2 { - margin: 0; - font-size: 1em; - font-weight: normal; - } -} - -.modal-close { + border: 0; + border-bottom: 1px solid currentColor; background: transparent; - color: var(--fg); - border: none; - font-family: inherit; - font-size: 1.4em; - line-height: 1; - cursor: pointer; - padding: 0 6px; -} - -.modal-body { - padding: var(--padding); - overflow: auto; -} - -.settings-row { - margin-bottom: var(--padding); - padding-bottom: var(--padding); - border-bottom: 0.5px solid #555; - - &:last-child { - border-bottom: none; - } - - input[type="text"] { - width: 100%; - background-color: transparent; - color: inherit; - border: 0.5px solid grey; - font: inherit; - padding: 4px 6px; - } - - button { - background-color: #2228; - color: var(--fg); - border: 0.5px solid grey; - font-family: inherit; - padding: 4px 10px; - cursor: pointer; - - &:hover { - background-color: #333a; - } - } -} - -.settings-label { - display: block; - margin-bottom: 4px; -} - -.settings-note { - font-size: 0.85em; - color: #999; - margin-top: 4px; -} - -.settings-radio { - margin-right: var(--padding); -} - -.settings-grid-slots { - display: grid; - grid-template-columns: repeat(3, 42px); - gap: 4px; -} - -.settings-grid-slot { - width: 42px; - height: 36px; - box-sizing: border-box; - background-color: #1e0c33; - color: var(--fg); - border: 1px solid #7474ff; - border-radius: 4px; font: inherit; - font-size: 0.85em; - cursor: pointer; - overflow: hidden; - padding: 0; - appearance: none; - -webkit-appearance: none; - text-align: center; - text-align-last: center; - line-height: 34px; - - &:active { - background-color: #225; - } } -.settings-toolbar-grid { - display: grid; - grid-template-columns: repeat(auto-fill, minmax(160px, 1fr)); - gap: 4px; +.nethack-terminal .prompt .extcmd:focus-visible { + outline: 1px solid #e9a34b; + outline-offset: 1px; } -.settings-scroll-active { - display: flex; - flex-direction: column; - gap: 2px; - margin: 4px 0; -} - -.settings-scroll-row { - display: grid; - grid-template-columns: auto auto auto 1fr; - gap: 4px; - align-items: center; -} - -.settings-scroll-row button { - width: 28px; - height: 28px; +.nethack-terminal kbd { padding: 0; + background: transparent; + color: inherit; font: inherit; - cursor: pointer; } -.settings-scroll-row button:disabled { - opacity: 0.3; - cursor: default; +.nethack-terminal kbd.def { + color: #e9a34b; + text-decoration: underline; } -.settings-scroll-available { +.nethack-terminal .status { + grid-column: 1; + grid-row: 3; display: flex; flex-wrap: wrap; - gap: 4px; - margin-top: 4px; + gap: 2px 1ch; + align-content: start; + padding: var(--padding); + min-height: 3lh; } -.settings-scroll-available button { - font: inherit; - cursor: pointer; - padding: 2px 8px; +.nethack-terminal .status.compact { + min-height: 0; } -.settings-custom-list { - display: flex; - flex-direction: column; - gap: 4px; +.nethack-terminal .status > * { + white-space: nowrap; } -.settings-custom-row { - display: grid; - grid-template-columns: 1fr 1fr auto; - gap: 4px; - align-items: center; -} - -.settings-custom-row input { +.nethack-terminal .play-again-button { + position: absolute; + inset: 50% auto auto 50%; + transform: translate(-50%, -50%); + z-index: 3; + padding: 0.75rem 1rem; + border: 1px solid #e9a34b; + border-radius: 0.3rem; + background: #272016; + color: #f3ebdc; font: inherit; - background-color: transparent; - color: inherit; - border: 0.5px solid grey; - padding: 2px 4px; + cursor: pointer; } - -.settings-custom-header { - font-size: 0.85em; - opacity: 0.7; -} - -.settings-rc-textarea { - width: 100%; - min-height: 300px; - background-color: transparent; - color: inherit; - border: 0.5px solid grey; - font: inherit; - padding: 4px 6px; - resize: vertical; -} --- a/src/App.tsx +++ b/src/App.tsx @@ -1,254 +1,131 @@ -import { useCallback, useEffect, useRef, useState } from "react"; +import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react"; import "@fontsource/dejavu-mono"; import "./App.css"; -import { OnInputContext, useNethack, useOnInput } from "./useNethack"; -import { ESC, type NetHack, type NHWindow } from "./nethack"; +import { OnInputContext, useNethack } from "./useNethack"; +import { type NetHack, type NHWindow } from "./nethack"; import { MessageWindow } from "./MessageWindow"; import { Prompt } from "./Prompt"; import { MapWindow } from "./MapWindow"; import { MenuWindow } from "./MenuWindow"; import { TextWindow } from "./TextWindow"; import { StatusWindow } from "./StatusWindow"; -import { MobileInputs } from "./MobileInput"; import { CopyrightWindow } from "./CopyrightWindow"; -import { SettingsDialog } from "./SettingsDialog"; -import { Modal } from "./Modal"; -import { Footer } from "./Footer"; -import { loadSettings, saveSettings, Settings } from "./settings"; +import { loadSettings } from "./settings"; const Window = ({ window_ }: { window_: NHWindow }) => { - if (!window_.displayed) { - return null; - } - switch (window_.type) { - case "NHW_MENU": - return ; - case "NHW_TEXT": - return ; - default: - console.error("Unknown window type:", window_.type); - } + if (window_.type === "NHW_MENU") return ; + if (window_.type === "NHW_TEXT") return ; + return null; }; const TemporaryWindows = ({ state }: { state: NetHack }) => { - const onInput = useOnInput(); - const hasTemporaryWindow = - // state.isLoading || - Object.values(state.windows).some( - (window_) => - window_.id !== state.messageWindow?.id && - window_.id !== state.mapWindow?.id && - window_.displayed, - ); - useEffect(() => { - if (hasTemporaryWindow) { - history.pushState(null, ""); - const callback = () => { - onInput(ESC); - }; - window.addEventListener("popstate", callback); - return () => { - window.removeEventListener("popstate", callback); - }; - } - }, [hasTemporaryWindow, onInput]); + const windows = Object.values(state.windows).filter( + (window_) => window_.displayed && (window_.type === "NHW_MENU" || window_.type === "NHW_TEXT"), + ); + if (!windows.length) return null; return ( -
onInput(ESC)} - > - {Object.entries(state.windows).map(([windowId, window_]) => - ( - window_.id === state.messageWindow?.id || - window_.id === state.mapWindow?.id - ) ? - null - : , - )} +
+ {windows.map((window_) => )}
); }; export const App = () => { - const sentEofRef = useRef(false); - useEffect(() => { - history.pushState(null, ""); - const callback = (e: BeforeUnloadEvent) => { - if (sentEofRef.current) return; - e.preventDefault(); - }; - window.addEventListener("beforeunload", callback); - return () => { - window.removeEventListener("beforeunload", callback); - }; - }, []); - const [state, onInput, restartNethack] = useNethack(); - // In-place restart: drop the old wasm + NetHack instance, boot a fresh - // one. Used by both Play again (game-end) and the save-on-hide auto-resume - // path. The save (if any) is already persisted to IDBFS by the prior run's - // exitNhwindows shim, so the new wasm's preRun syncfs picks it up. + const [settings] = useState(loadSettings); + const sentEof = useRef(false); + const terminal = useRef(null); + const textPrompt = state.prompt?.type === "getlin" || state.prompt?.type === "extcmd"; + const playing = Boolean(state.mapWindow?.displayed && !state.gameEnded); + const focusTerminal = () => terminal.current?.focus({ preventScroll: true }); + + useLayoutEffect(() => { + if (document.activeElement === document.body) { + terminal.current?.focus({ preventScroll: true }); + } + }, [textPrompt]); + const restart = useCallback(() => { - sentEofRef.current = false; + sentEof.current = false; restartNethack(); + terminal.current?.focus({ preventScroll: true }); }, [restartNethack]); - const [isNumLock, setIsNumLock] = useState(false); - const [showSettings, setShowSettings] = useState(false); - const [showInfo, setShowInfo] = useState(false); - const [keyboardOpen, setKeyboardOpen] = useState(false); useEffect(() => { - const root = document.documentElement; - if (!keyboardOpen) { - root.style.removeProperty("--bar-top"); - return; - } - const vv = window.visualViewport; - const barEl = () => - document.querySelector(".kbd-bar"); - const update = () => { - if (!vv) return; - const barHeight = barEl()?.offsetHeight ?? 60; - const top = vv.offsetTop + vv.height - barHeight; - root.style.setProperty("--bar-top", `${top}px`); + if (!playing) return; + const beforeUnload = (event: BeforeUnloadEvent) => { + if (!sentEof.current) event.preventDefault(); }; - vv?.addEventListener("resize", update); - vv?.addEventListener("scroll", update); - return () => { - vv?.removeEventListener("resize", update); - vv?.removeEventListener("scroll", update); - root.style.removeProperty("--bar-top"); - }; - }, [keyboardOpen]); + window.addEventListener("beforeunload", beforeUnload); + return () => window.removeEventListener("beforeunload", beforeUnload); + }, [playing]); - const [settings, setSettings] = useState(loadSettings); - const updateSettings = (patch: Partial) => { - setSettings((prev) => { - const next = { ...prev, ...patch }; - saveSettings(next); - return next; - }); - }; - // Save-on-hide simulates a SIGHUP without exporting any new C symbol. - // The chain: visibilitychange hidden -> onInput({eof:true}) sets a sticky - // flag in NetHack -> nh_poskey/nhgetch wrappers return -1 to wasm -> - // readchar_core hits EOF and calls hangup(0) -> SAFERHANGUP defers, but - // the moveloop's done_hup check at allmain.c:182 calls end_of_input the - // next iteration, which runs dosave0 and exit_nhwindows. Our exit_nhwindows - // shim awaits FS.syncfs to persist /save/ to IDBFS, then sets - // savedAndExited so the second effect can reload once the user returns. + // Honor the upstream preference for visitors who enabled saving on tab hide. useEffect(() => { - const triggerSave = () => { - if (settings.saveOnHide && !sentEofRef.current) { - sentEofRef.current = true; - onInput({ eof: true }); - } + if (!settings.saveOnHide || !playing) return; + const save = () => { + if (sentEof.current) return; + sentEof.current = true; + onInput({ eof: true }); }; const onVisibilityChange = () => { - if (document.visibilityState === "hidden") { - triggerSave(); - } + if (document.visibilityState === "hidden") save(); }; - // pagehide is more reliable than visibilitychange when iOS suspends - // an installed PWA directly rather than backgrounding Safari. - const onPageHide = () => triggerSave(); document.addEventListener("visibilitychange", onVisibilityChange); - window.addEventListener("pagehide", onPageHide); + window.addEventListener("pagehide", save); return () => { document.removeEventListener("visibilitychange", onVisibilityChange); - window.removeEventListener("pagehide", onPageHide); + window.removeEventListener("pagehide", save); }; - }, [settings.saveOnHide, onInput]); + }, [settings.saveOnHide, playing, onInput]); - // Wait for the save to actually persist before restarting; restarting - // straight from visibilitychange races the in-flight IDBFS write. useEffect(() => { - if (!sentEofRef.current || !state.savedAndExited) return; + if (!sentEof.current || !state.savedAndExited) return; if (document.visibilityState === "visible") { restart(); return; } - const handler = () => { - if (document.visibilityState === "visible") { - restart(); - } + const resume = () => { + if (document.visibilityState === "visible") restart(); }; - document.addEventListener("visibilitychange", handler); - return () => document.removeEventListener("visibilitychange", handler); + document.addEventListener("visibilitychange", resume); + return () => document.removeEventListener("visibilitychange", resume); }, [state.savedAndExited, restart]); + return ( -
+
{ + if (event.target === event.currentTarget) { + event.currentTarget.querySelector("input")?.focus({ preventScroll: true }); + } + }} + onClick={(event) => { + if (event.target instanceof Element && !event.target.closest("input, button")) { + focusTerminal(); + } + }} + > -
- +
+ {!state.mapWindow?.displayed && }
{state.prompt && } - {!keyboardOpen && ( - - )} - - {!keyboardOpen && ( - <> - - - - )} - {showInfo && ( - setShowInfo(false)}> -
- - )} + {state.gameEnded && ( - + )} - {showSettings && ( - setShowSettings(false)} - /> - )} -
+
); }; --- a/src/MapWindow.tsx +++ b/src/MapWindow.tsx @@ -3,7 +3,6 @@ import { Text } from "./Common"; import { Attr, iflags } from "../lib/nethackInterface"; import { memo, useLayoutEffect, useRef } from "react"; -import { useOnInput } from "./useNethack"; const GlyphC = memo( ({ @@ -12,28 +11,29 @@ glyph, isCursor, isCliparound, - isNumLock, }: { x: number; y: number; glyph: Glyph; isCursor: boolean; isCliparound: boolean; - isNumLock: boolean; }) => { const ref = useRef(null); useLayoutEffect(() => { if (!ref.current || !isCliparound) { return; } - ref.current.scrollIntoView({ + const map = ref.current.closest(".map-container"); + if (!map) return; + const viewport = map.getBoundingClientRect(); + const glyph = ref.current.getBoundingClientRect(); + map.scrollBy({ + left: glyph.left + glyph.width / 2 - viewport.left - viewport.width / 2, + top: glyph.top + glyph.height / 2 - viewport.top - viewport.height / 2, behavior: "instant", - block: "center", - inline: "center", }); }, [x, y, isCliparound]); - const onInput = useOnInput(); const attrs: Attr[] = []; if (isCursor) { attrs.push("ATR_BLINK"); @@ -60,12 +60,9 @@ } return ( { - onInput({ x, y, mod: isNumLock ? 2 : 1 }); - }} ref_={ref} > {decodeCP437(glyph.glyphinfo.ttychar)} @@ -81,13 +78,11 @@ row, cursorX, cliparoundX, - isNumLock, }: { y: number; row: Glyph[]; cursorX: number | null; cliparoundX: number | null; - isNumLock: boolean; }) => { return row.map((glyph, x) => ( )); }, @@ -105,13 +99,11 @@ export const MapWindow = ({ window_, - isNumLock, }: { window_?: NHMapWindow; - isNumLock: boolean; }) => { return ( -
+
{window_?.map.map((row, y) => ( ))}
--- a/src/MenuWindow.tsx +++ b/src/MenuWindow.tsx @@ -1,7 +1,6 @@ import { Text } from "./Common"; import { NHMenuEntry, NHMenuWindow } from "./nethack"; import { TextWindow } from "./TextWindow"; -import { useOnInput } from "./useNethack"; const selectedSeparator = (count: number) => { if (count == 0) { @@ -14,7 +13,6 @@ }; const MenuEntry = ({ menuEntry }: { menuEntry: NHMenuEntry }) => { - const onInput = useOnInput(); const accelerator = menuEntry.accelerator || menuEntry.customAccelerator; return (
onInput(accelerator) : undefined} > {accelerator && ( <> @@ -39,23 +36,25 @@ }; export const MenuWindow = ({ window_ }: { window_: NHMenuWindow }) => { - const onInput = useOnInput(); if (window_.text.length > 0) { return ; } if (!window_.prompt && !window_.menuEntries.length) { return null; } + const mode = window_.selectionMode; + const informational = !mode || mode === "PICK_NONE"; return ( -
+
{window_.prompt &&
{window_.prompt}
} {window_.prompt &&
} {window_.menuEntries.map((menuEntry, i) => ( ))} -
-
onInput(" ")}> - Ok +
+ {informational ? "Press Space to continue." : + mode === "PICK_ONE" ? "Press a listed key to choose, or Esc to cancel." : + "Use the listed keys, then press Enter, or Esc to cancel."}
); --- a/src/MessageWindow.tsx +++ b/src/MessageWindow.tsx @@ -3,7 +3,7 @@ export const MessageWindow = ({ window_ }: { window_?: NHMessageWindow }) => { return ( -
+
{window_?.blocking && (
--More-- --- a/src/Prompt.tsx +++ b/src/Prompt.tsx @@ -1,124 +1,51 @@ import { getUniqueExtCmdAutocomplete } from "../lib/nethackInterface"; -import { - ESC, - ExtCmdPrompt as ExtCmdPromptType, - GetlinPrompt as GetlinPromptType, - Prompt as PromptType, - YNPrompt, -} from "./nethack"; +import { ESC, type Prompt as PromptType, type YNPrompt } from "./nethack"; import { useOnInput } from "./useNethack"; -const Kbd = ({ - children, - className, -}: { - children: string; - className?: string; -}) => { - const onInput = useOnInput(); - return ( - onInput(children)}> - {children} - - ); -}; - -const YNQuestion = ({ question, choices, def }: YNPrompt) => { - return ( -
-
- {question} - {choices && ( - <> - {" ["} - {choices.split("").map((c, i) => ( - - {c == "\x1b" ? "ESC" : c} - - ))} - {"]"} - - )} -
-
- ); -}; - -const ExtCmdPrompt = ({ cmd }: ExtCmdPromptType) => { - const autocomplete = getUniqueExtCmdAutocomplete(cmd.toLowerCase()); - const onInput = useOnInput(); - const resetPrompt = () => { - onInput(ESC); - }; - return ( -
- {autocomplete && ( -
- #{autocomplete.name} ({autocomplete.description}) -
+const YNQuestion = ({ question, choices, def }: YNPrompt) => ( +
+
+ {question} + {choices && ( + <> + {" ["} + {choices.split("").map((char, index) => ( + + {char === ESC ? "Esc" : char} + + ))} + {"]"} + )} -
- {"#"} - { - onInput(e.target.value); - }} - onKeyDown={(e) => { - e.stopPropagation(); - if (e.key == "Enter") { - onInput({ submit: true }); - } else if (e.key == "Escape") { - resetPrompt(); - } - }} - /> -
- ); -}; +
+); -const GetlinPrompt = ({ prompt, answer }: GetlinPromptType) => { +const PromptInput = ({ label, value }: { label: string; value: string }) => { const onInput = useOnInput(); - const resetPrompt = () => { - onInput(ESC); - }; return ( -
-
- {prompt + " "} - { - onInput(e.target.value); - }} - onKeyDown={(e) => { - e.stopPropagation(); - if (e.key == "Enter") { - onInput({ submit: true }); - } else if (e.key == "Escape") { - resetPrompt(); - } - }} - /> -
-
+ onInput(event.target.value)} + onKeyDown={(event) => { + if (event.nativeEvent.isComposing) return; + if (event.key === "Enter") { + event.preventDefault(); + onInput({ submit: true }); + } else if (event.key === "Escape") { + event.preventDefault(); + onInput(ESC); + } + }} + /> ); }; @@ -126,9 +53,27 @@ switch (prompt.type) { case "yn": return ; - case "extcmd": - return ; + case "extcmd": { + const command = prompt.cmd.toLowerCase(); + const autocomplete = getUniqueExtCmdAutocomplete(command); + return ( +
+ {autocomplete && ( +
+ #{autocomplete.name} ({autocomplete.description}) +
+ )} +
#
+
+ ); + } case "getlin": - return ; + return ( +
+
+ {prompt.prompt}{" "} +
+
+ ); } }; --- a/src/TextWindow.tsx +++ b/src/TextWindow.tsx @@ -1,25 +1,25 @@ import { Text } from "./Common"; import { NHMenuWindow, NHTextWindow } from "./nethack"; -import { useOnInput } from "./useNethack"; export const TextWindow = ({ window_, }: { window_: NHTextWindow | NHMenuWindow; }) => { - const onInput = useOnInput(); + const informational = !("selectionMode" in window_) || + window_.selectionMode === null || window_.selectionMode === "PICK_NONE"; return (
{ - onInput(" "); - }} + tabIndex={-1} + data-window-kind={informational ? "information" : "selection"} > {window_.text.map(({ str, attr }, i) => (
{str}
))} + {informational &&
Press Space to continue.
}
); }; --- a/src/nethack.ts +++ b/src/nethack.ts @@ -34,6 +34,38 @@ const ENTER = "\n"; const BACKSPACE = "\x08"; +const movementKeys = new Map([ + ["ArrowLeft", "h"], ["ArrowDown", "j"], ["ArrowUp", "k"], ["ArrowRight", "l"], + ["Numpad1", "b"], ["Numpad2", "j"], ["Numpad3", "n"], ["Numpad4", "h"], + ["Numpad5", "."], ["Numpad6", "l"], ["Numpad7", "y"], ["Numpad8", "k"], ["Numpad9", "u"], +]); + +function terminalKey(event: KeyboardEvent, direction: boolean) { + const { key, code, ctrlKey, altKey, metaKey, shiftKey } = event; + const altGraph = event.getModifierState("AltGraph"); + if (event.defaultPrevented || event.isComposing || metaKey) return; + if (key === "Escape") return ESC; + if (key === "Enter") return ENTER; + if (key === "Backspace") return BACKSPACE; + if (direction && !ctrlKey && !altKey) { + const movement = movementKeys.get(code) ?? movementKeys.get(key); + if (movement) return shiftKey ? movement.toUpperCase() : movement; + } + if (ctrlKey && !altGraph) { + if (key.toLowerCase() === "c" && window.getSelection()?.isCollapsed === false) return; + const ascii = key.length === 1 ? key.toUpperCase().charCodeAt(0) : 0; + if (ascii >= 64 && ascii <= 95) return String.fromCharCode(ascii - 64); + return; + } + if (altKey && !altGraph) { + const character = /^[ -~]$/.test(key) ? key : + /^Key[A-Z]$/.test(code) ? (shiftKey ? code[3] : code[3].toLowerCase()) : ""; + if (character) return String.fromCharCode(character.charCodeAt(0) + 128); + return; + } + if (/^[ -~]$/.test(key)) return key; +} + export class NHMenuWindow { constructor(public id: number) {} type = "NHW_MENU" as const; @@ -42,10 +74,12 @@ text: { str: string; attr: Attr }[] = []; menuEntries: NHMenuEntry[] = []; prompt = ""; + selectionMode: How | null = null; customAcceleratorIndex = 0; customAccelerators = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; startMenu() { this.menuEntries = []; + this.selectionMode = null; this.customAcceleratorIndex = 0; } endMenu(prompt: string) { @@ -104,7 +138,7 @@ } case "PICK_ONE": { const { char, count } = await this.getCharWithCount(getChar); - if (char == ESC || char == " ") { + if (char === ESC || char === " " || char === ENTER) { this.displayed = false; return []; } @@ -122,7 +156,11 @@ while (!exited) { const { char, count } = await this.getCharWithCount(getChar); - if (char == ESC || char == " ") { + if (char === ESC) { + this.displayed = false; + return []; + } + if (char === " " || char === ENTER) { exited = true; } else if (char == ",") { for (const entry of this.menuEntries) { @@ -374,7 +412,6 @@ export class NetHack implements NetHackInterface { start(playerName: string) { startNethack(this, { - LOG_PROCESSED_CALLS: true, commandLineArguments: ["-u", playerName], }); } @@ -443,38 +480,33 @@ resolve_(input); this.resolveInput = () => {}; }; - const callback = (e: KeyboardEvent) => { - const resolve = (input: Input) => { - e.preventDefault(); - window.removeEventListener("keydown", callback); - this.waitingForInput = false; - resolve_(input); - this.resolveInput = () => {}; - }; - if (e.key.length == 1) { - if (e.ctrlKey) { - resolve( - String.fromCharCode( - e.key.toUpperCase().charCodeAt(0) - - "A".charCodeAt(0) + - 1, - ), - ); - } else if (e.altKey) { - resolve(String.fromCharCode(e.key.charCodeAt(0) + 128)); - } else { - resolve(e.key); + const callback = (event: KeyboardEvent) => { + const target = event.target; + if (!(target instanceof Element) || target.closest("a, button, input, select, textarea, [contenteditable]")) return; + const terminal = target.closest("#nethack-terminal"); + if (!terminal) return; + const prompt = this.prompt; + if (prompt?.type === "getlin" || prompt?.type === "extcmd") return; + const direction = prompt?.type === "poskey" || + (prompt?.type === "yn" && !prompt.choices && /\bdirection\b/i.test(prompt.question)); + if (!direction && !event.defaultPrevented && !event.isComposing && + !event.metaKey && !event.altKey && !event.ctrlKey) { + const down = event.key === "ArrowDown" || event.key === "PageDown"; + const up = event.key === "ArrowUp" || event.key === "PageUp"; + if (down || up) { + const window = [...terminal.querySelectorAll(".temporary-windows > *")].at(-1); + if (window) { + event.preventDefault(); + const distance = event.key.startsWith("Page") ? window.clientHeight : 40; + window.scrollBy(0, down ? distance : -distance); + return; + } } } - if (e.key == "Escape") { - resolve(ESC); - } - if (e.key == "Enter") { - resolve(ENTER); - } - if (e.key == "Backspace") { - resolve(BACKSPACE); - } + const key = terminalKey(event, direction); + if (key === undefined) return; + event.preventDefault(); + this.resolveInput(key); }; window.addEventListener("keydown", callback); }); @@ -709,6 +741,7 @@ async selectMenu(windowId: number, how: How) { const win = this.windows[windowId] as NHMenuWindow; win.displayed = true; + win.selectionMode = how; return await win.selectMenu(how, this.getChar.bind(this)); } async messageMenu() { --- a/src/settings.ts +++ b/src/settings.ts @@ -36,7 +36,7 @@ playerName: "Adventurer", nethackrc: nethackrcContents, compactStatus: window.matchMedia("(max-width: 600px)").matches, - saveOnHide: true, + saveOnHide: false, gridButtons: [ "look", "cast", "fire", "run", "drop-type", "inven",