All files / js menu.js

85.83% Statements 788/918
78.14% Branches 236/302
84.21% Functions 16/19
85.83% Lines 788/918

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 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 91973x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 474x 474x 474x 474x 474x 474x 474x 474x 474x 474x 474x 474x 474x 474x 474x 474x 474x 474x 474x 474x 474x 474x 474x 73x 73x 73x 73x 73x 73x 427x 427x 427x 427x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 11875x 11875x 8443x 8443x 8443x 11875x 3432x 3432x 11875x 11875x 11875x 11875x 11875x 11875x 11875x 11875x 11875x 11875x 11875x 11875x 11875x 11875x 11875x 73x 73x 73x 73x 73x 73x 73x 73x 73x 1329x 1329x 73x 73x 73x 1493x 1493x 73x 73x 73x 73x 73x 73x 472x 472x 472x 472x 472x 472x 472x 472x 472x 327x 327x 327x 327x 327x 327x 327x 327x 327x 327x 327x 327x 327x 327x 327x 327x 327x 327x 327x 327x 327x 327x 327x 472x 472x 472x 472x 472x 472x 472x 472x 472x 472x 472x 472x 472x 472x 12529x 824x 824x 12529x 12529x 528x 528x 528x 528x 528x 528x 12529x 472x 472x 472x 472x 824x 824x 824x 824x 824x 824x 824x 824x 472x 472x 472x 472x 472x 472x 12529x 12529x 12529x 472x 472x 472x 19x 19x 472x 472x 472x 472x     472x 472x 472x 472x 472x 472x 12x 12x 12x 472x 19x 19x 19x 459x 441x 441x 472x 472x 472x 472x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 472x     472x 472x 472x 472x 472x 472x 472x 472x 472x 472x 472x 472x 472x 472x 472x 472x 472x 472x 472x 472x 3x 472x 12x 469x 457x 457x 457x 457x 457x 457x 472x 472x 472x 472x 472x 472x 472x 472x 594x 594x 594x 594x 575x 594x 594x 594x 338x 8112x 8112x 338x 594x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 249x 249x 249x 249x 256x       256x 594x 594x 594x 594x 594x 17x 17x 594x 594x 594x 594x 594x 594x 594x 594x 594x 594x 594x 472x 472x 472x 472x 472x 472x 472x 472x 472x 472x 77x 77x 472x 472x 472x 4x 472x 354x 354x 354x 472x 472x 472x 472x 472x 472x 472x 472x 472x 472x 472x 472x 472x 813x 813x 337x 337x 809x 476x 476x 813x 813x 813x 813x 11739x 7431x 7431x 7431x 11739x 813x 813x     813x 809x 809x 813x 23x 23x 786x 786x 813x 4x 4x 4x 4x 4x 4x 4x 4x 782x 782x 782x 69x 69x 69x 69x 69x 69x 69x 782x 782x 1x             782x 782x 2x 14x         782x 782x               782x 782x 11x 3x 68x 63x 63x 63x 63x 782x 782x             782x 782x 2x 2x 14x 6x 14x 6x 6x 782x 782x 813x 122x 122x 122x 122x 122x 122x 122x 122x 122x 122x 122x 122x 660x 813x                     660x 813x         660x 813x         660x 813x 1x 1x 1x 659x 813x 2x 2x 2x 657x 813x       657x 813x 11x 11x 11x 646x 813x       646x 813x 2x 2x 2x 644x 644x 806x 356x 2863x 1911x 2863x 2863x 356x 356x 356x 307x 307x 307x 307x 307x 307x 307x 49x 49x 126x 5x     5x 5x 5x 5x 5x 126x 44x   44x 44x 44x 44x 44x 49x 356x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x 356x 288x 288x 288x 288x 3588x 118x 3588x 3588x 288x 782x 3x               3x 3x 3x             3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 285x 285x 285x 813x                                                                                 285x 285x 813x 42x 42x 29x 29x 587x 44x 44x 587x 29x 29x 13x 13x 13x 243x 243x 546x 96x 6x 6x 44x 1x 1x 44x 6x 6x 90x 90x 813x 472x 472x 472x 472x 472x 472x 472x 472x 472x 472x 472x 472x 472x 472x 472x 472x 472x 216x 216x 216x 216x 216x 216x 216x 216x 216x 216x 216x 216x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 214x 204x 204x 472x 256x 256x 256x 472x     472x 472x 472x 472x 472x 472x 472x 73x 73x 73x 73x 73x 73x 412x 412x 412x 412x 412x 412x 412x 412x 412x 412x 412x 412x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 594x 594x 594x 594x 594x 594x 594x 594x 594x 594x 594x 9553x 9553x 9553x 710576x 710576x 9553x 9553x 9553x 9553x 9553x 9553x 9553x 9553x 9553x 9553x 9553x 9553x 9553x 9553x 9553x 9553x 231569x 231569x 231569x 231569x 231569x 231569x 231569x 231569x 231569x 231569x 231569x 9553x 594x 594x 594x 594x 594x 594x 17x 17x 17x 17x 17x 17x 17x 17x 17x 136x 136x 17x 17x 577x 577x 594x 39681x 39681x 577x 577x 577x 577x 577x 577x 577x 577x 594x 4138x 4138x 4138x 4138x 577x 594x 4x 4x 4x 4x 4x 320x 320x 4x 4x 4x 4x 4x 4x 4x 4x 4x         4x 594x 594x 73x 73x 73x 73x 73x                          
// menu.js — TTY menu window system (port of wintty.c menu functions)
//
// Implements the NHW_MENU window type for displaying menus and getting
// user selections. Matches C's tty_add_menu/tty_end_menu/process_menu_window
// rendering: "c - text" format, offx-based corner positioning, ATR_INVERSE
// prompt, and "(end)" morestr.
//
// C refs: wintty.c tty_add_menu(), tty_end_menu(), process_menu_window()
 
import { game } from './gstate.js';
import { isStartupPromptPhase, nhgetch, getlin } from './input.js';
import { enterModal, exitModal } from './modal_guard.js';
import { ATR_INVERSE, ATR_NONE, CLR_GRAY, NO_COLOR } from './terminal.js';
import {
    PICK_NONE, PICK_ONE, PICK_ANY,
    MENU_FIRST_PAGE, MENU_LAST_PAGE, MENU_NEXT_PAGE, MENU_PREVIOUS_PAGE,
    MENU_SELECT_ALL, MENU_UNSELECT_ALL, MENU_INVERT_ALL,
    MENU_SELECT_PAGE, MENU_UNSELECT_PAGE, MENU_INVERT_PAGE,
    MENU_ITEMFLAGS_SKIPINVERT,
} from './const.js';
import { TOPLINE_NEED_MORE } from './const.js';
import { pushRngLogEntry } from './rng.js';
import { bot, docorner, docrt, docrt_cls, erase_menu_or_text, flush_screen, NHW_MENU, NHW_TEXT, render_screen_output_to_display, setBotlx, tty_clear_nhwindow, tty_create_nhwindow, tty_destroy_nhwindow, tty_dismiss_nhwindow, tty_display_nhwindow } from './display.js';
export { NHW_TEXT };
 
const MENU_SEARCH = ':'.charCodeAt(0); // C ref: wintype.h MENU_SEARCH
 
// ── Menu data structures ──
// Mirrors C's tty_menu_item and WinDesc fields for NHW_MENU.
 
/**
 * Create a new menu window.
 * C ref: tty_create_nhwindow(NHW_MENU)
 */
export function create_nhwindow_menu(type = NHW_MENU, existingWinId = null) {
    // C ref: create_nhwindow(NHW_MENU or NHW_TEXT) allocates a game.wins[] slot.
    // For cached pickinv windows we can reactivate an existing slot.
    const winId = (existingWinId != null && existingWinId >= 0 && game.wins[existingWinId])
        ? existingWinId
        : tty_create_nhwindow(type);
    if (game.wins[winId]) game.wins[winId].active = true;
    return {
        winId,           // window ID in game.wins[] array (for tty_dismiss events)
        type,            // NHW_MENU or NHW_TEXT
        items: [],       // tty_menu_item list (in add order, reversed by end_menu)
        pages: [],
        prompt: null,    // set by end_menu
        morestr: null,   // "(end) " or "(X of Y)"
        cols: 0,         // widest item + 2
        rows: 0,         // total items + 1 (for morestr)
        npages: 0,
        maxrow: 0,
        offx: 0,         // horizontal offset on terminal
        offy: 0,
        how: PICK_NONE,
        finalized: false,
    };
}
 
/**
 * Initialize a menu for adding items.
 * C ref: tty_start_menu()
 */
export function start_menu(menu) {
    menu.items = [];
    menu.prompt = null;
    menu.finalized = false;
}
 
/**
 * Add a menu item.
 * C ref: tty_add_menu() — prepends "c - " for selectable items.
 *
 * @param {object} menu - Menu window
 * @param {*} identifier - What to return if selected (null = non-selectable)
 * @param {string} accelerator - Selector letter (0 or '' = auto-assign)
 * @param {number} groupacc - Group accelerator (0 = none)
 * @param {number} attr - Attribute (ATR_INVERSE, ATR_BOLD, etc.)
 * @param {number} color - Color constant
 * @param {string} str - Item text
 * @param {number} itemflags - MENU_ITEMFLAGS_SELECTED etc.
 */
export function add_menu(menu, identifier, accelerator, groupacc, attr, color, str, itemflags = 0) {
    let itemStr;
    if (identifier) {
        // C: Sprintf(buf, "%c - ", ch ? ch : '?');
        const ch = accelerator || '?';
        itemStr = `${ch} - ${str}`;
    } else {
        itemStr = str;
    }
 
    const item = {
        identifier,
        selector: accelerator || 0,
        gselector: groupacc || 0,
        attr: attr || ATR_NONE,
        color: (color != null && color !== NO_COLOR) ? color : NO_COLOR,
        str: itemStr,
        selected: !!(itemflags & 1), // MENU_ITEMFLAGS_SELECTED = 1
        count: -1,
    };
 
    // C: prepend to list (tty_add_menu appends to head)
    menu.items.push(item);
}
 
// add_valid_menu_class canonical in pickup.js (C ref: pickup.c).
// The old TODO stub here had zero importers.
 
/**
 * Add a non-selectable text line to the menu.
 * C ref: add_menu_str() macro → add_menu with null identifier.
 */
export function add_menu_str(menu, str) {
    add_menu(menu, null, 0, 0, ATR_NONE, NO_COLOR, str, 0);
}
 
// C ref: add_menu_heading() — non-selectable heading with heading style.
export function add_menu_heading(menu, str) {
    add_menu(menu, null, 0, 0, ATR_INVERSE, NO_COLOR, str, 0);
}
 
/**
 * Finalize the menu: reverse items, add prompt, calculate layout.
 * C ref: tty_end_menu()
 */
export function end_menu(menu, prompt) {
    // C: Reverse the list so items are in original add order.
    // (In C, items are prepended; we pushed, so they're already in order.
    //  But end_menu then prepends prompt items, which means prompt goes first.)
 
    // C: add empty line + prompt at the beginning
    // tty_end_menu calls tty_add_menu twice (prepending): first empty, then prompt.
    // After prepend, order is: prompt, empty, ...items...
    const promptItems = [];
    if (prompt) {
        // C: tty_menu_promptstyle = { NO_COLOR, ATR_INVERSE } (default)
        // iflags.menu_headings.attr = ATR_INVERSE by default
        promptItems.push({
            identifier: null,
            selector: 0,
            gselector: 0,
            attr: ATR_INVERSE,
            color: NO_COLOR,
            str: prompt,
            selected: false,
            count: -1,
        });
        promptItems.push({
            identifier: null,
            selector: 0,
            gselector: 0,
            attr: ATR_NONE,
            color: NO_COLOR,
            str: '',
            selected: false,
            count: -1,
        });
    }
    menu.items = [...promptItems, ...menu.items];
    menu.prompt = prompt;
 
    const display = game?.nhDisplay || null;
    const displayRows = display?.rows || 24;
    const linesPerPage = Math.min(52, Math.max(1, displayRows - 1));
 
    // C ref: tty_end_menu (wintty.c:2889-2898) — assign selectors.
    // C's tty_add_menu prepends "? - " when identifier is set but selector
    // is 0. tty_end_menu overwrites str[0] (the '?') with the assigned
    // letter. JS's add_menu does the same "? - " prepend, so here we
    // overwrite the first char rather than prepending again.
    let menuCh = 'a';
    for (let i = 0; i < menu.items.length; i++) {
        if ((i % linesPerPage) === 0) {
            menuCh = 'a';
        }
        const item = menu.items[i];
        if (item.identifier && !item.selector) {
            item.selector = menuCh;
            // C: curr->str[0] = curr->selector = menu_ch;
            // Overwrite the '?' placeholder, don't prepend again
            item.str = menuCh + item.str.substring(1);
            menuCh = (menuCh === 'z') ? 'A' : String.fromCharCode(menuCh.charCodeAt(0) + 1);
        }
    }
 
    menu.pages = [];
    menu.npages = Math.ceil(menu.items.length / linesPerPage);
    for (let page = 0; page < menu.npages; page++) {
        const start = page * linesPerPage;
        const end = Math.min(start + linesPerPage, menu.items.length);
        menu.pages.push({
            start,
            end,
            items: menu.items.slice(start, end),
        });
    }
 
    // C ref: wintty.c tty_end_menu/process_text_window:
    // - normal NHW_MENU items reserve one leading and one trailing space (+2)
    // - specific putstr-on-NHW_MENU prompts can use one leading space (+1)
    menu.cols = 0;
    for (const item of menu.items) {
        const len = item.str.length + (menu.putstrLikeWidth ? 1 : 2);
        if (len > menu.cols) menu.cols = len;
    }
 
    menu.morestr = (menu.npages > 1) ? '' : '(end) ';
    if (menu.textLikePrompt) {
        menu.morestr = '--More--';
    }
    const sampleMoreStr = (menu.npages > 1)
        ? `(${menu.npages} of ${menu.npages})`
        : menu.morestr;
    if (sampleMoreStr.length > menu.cols) {
        menu.cols = sampleMoreStr.length;
    }
 
    // C ref: NHW_MENU: maxrow = nitems + 1 (for morestr/end prompt)
    // C ref: NHW_TEXT: maxrow = line count (no +1; process_text_window uses
    //   cw->data directly, with maxrow = total items, not per-page)
    const isTextWindow = !!menu.forceOffx0;
    if (isTextWindow) {
        // C ref: wintty.c:2581-2582 — NHW_TEXT: maxrow tracks total putstr
        // count (not paginated). Text windows use scrollable fullscreen display.
        menu.rows = menu.items.length;
    } else if (menu.textLikePrompt) {
        // C putstr-on-NHW_MENU path (used by disclosure windows) tracks
        // maxrow as text line count and still uses a "--More--" prompt row.
        menu.rows = menu.items.length;
    } else {
        menu.rows = (menu.npages > 1 ? linesPerPage : menu.items.length) + 1;
    }
    menu.maxrow = menu.rows;
 
    menu.finalized = true;
}
 
/**
 * Display the menu and get user selection.
 * C ref: tty_select_menu() → process_menu_window()
 *
 * @param {object} menu - Finalized menu window
 * @param {number} how - PICK_NONE, PICK_ONE, or PICK_ANY
 * @returns {Promise<{count: number, items: Array}>}
 *   count: -1 = ESC, 0 = no selection, >0 = number of selected items
 *   items: [{identifier, count}] for each selected item
 */
export async function select_menu(menu, how) {
    if (!menu.finalized) {
        throw new Error('select_menu: menu not finalized (call end_menu first)');
    }
    menu.how = how;
 
    const display = game?.nhDisplay || null;
    const cols = display?.cols || 80;
    const inventoryDisplayOnly = (menu.displayOnly != null)
        ? !!menu.displayOnly
        : (how === PICK_NONE && !menu.prompt);
    const startupOverlay = isStartupPromptPhase();
    let selectedByLetter = false;
    let currentPage = 0;
    const oldBotDisabled = !!game?.bot_disabled;
    if (game) {
        game.bot_disabled = true;
    }
 
    try {
        // C ref: wintty.c:1906-1917 (H2344_BROKEN path)
        // offx = min(min(82, cols/2), cols - maxcol - 1) for NHW_MENU
        // offx = 0 for NHW_TEXT (text windows use full width)
        if (Number.isInteger(menu.fixedOffx)) {
            menu.offx = menu.fixedOffx;
        } else if (menu.forceOffx0) {
            menu.offx = 0;
        } else {
            menu.offx = Math.min(
                Math.min(82, Math.trunc(cols / 2)),
                cols - menu.cols - 1
            );
            if (menu.offx < 0) menu.offx = 0;
        }
 
        // C ref: wintty.c:1922-1935 (H2344_BROKEN path)
        // Fullscreen if maxrow >= rows OR !menu_overlay
        // NHW_TEXT (forceOffx0) with offx=0: C clears all rows via cl_end
        const fullscreen = menu.forceOffx0
            || menu.maxrow >= (display?.rows || 24);
 
        const renderCurrentPage = async () => {
            const pageItems = menu.pages[currentPage]?.items || menu.items;
            const moreStr = menu.textLikePrompt
                ? '--More--'
                : (menu.npages > 1
                ? `(${currentPage + 1} of ${menu.npages})`
                : menu.morestr);
 
            if (fullscreen) {
                for (let r = 0; r < (display.rows || 24); r++) {
                    display.clearRow(r);
                }
                menu.offx = 0;
            } else {
                // C ref: wintty.c:2088-2090 — non-fullscreen menu clears message.
                // C calls tty_clear_nhwindow(WIN_MESSAGE) to clear the message row
                // and reset toplin. Then the menu overlay is painted on top of
                // the existing map content.
                if (game.level) {
                    await tty_clear_nhwindow('message');
                    // Most overlay menus repaint map+status background.
                    // Some menu-on-menu flows (for example option submenus)
                    // keep the existing screen content instead.
                    if (!menu.skipOverlayBackdropRedraw) {
                        // captureOnly=true avoids emitting ^botlx[docrt_flags].
                        await docrt(false, true);
                        render_screen_output_to_display(display);
                    }
                } else if (display.toplin) {
                    display.toplin = 0;
                    game._pending_message = '';
                }
            }
 
            renderMenuToGrid(menu, display, pageItems, moreStr);
 
            const moreLine = menu.forceOffx0
                ? (menu.forceOffx0PromptAtPageEnd
                    ? pageItems.length
                    : (display.rows || 24) - 1)
                : pageItems.length;
            // C: dmore offset 1 for NHW_TEXT (col 0), 2 for NHW_MENU (col 1)
            // forceOffx0PromptLeadingBlank=true for NHW_MENU fullscreen (death enlightenment)
            const moreOffset = (menu.type === NHW_TEXT) ? 0
                : (menu.forceOffx0PromptLeadingBlank ? 1 : 0);
            const moreCol = menu.forceOffx0
                ? moreOffset + '--More--'.length
                : menu.offx + 1 + moreStr.length;
            if (typeof display.setCursor === 'function') {
                display.setCursor(moreCol, moreLine);
            }
        };
 
        if (display?.grid) {
            const willDisplayMessageFirst = !!(menu.forceOffx0 && menu.preDisplayMessage);
            const willDisplayMenuWindow = !willDisplayMessageFirst
                && !startupOverlay
                && (!inventoryDisplayOnly || fullscreen);
            if (!willDisplayMessageFirst
                && !willDisplayMenuWindow
                && display.toplin === TOPLINE_NEED_MORE) {
                await tty_display_nhwindow('message', true);
            }
            // C-shaped NHW_TEXT open: clear message/topline state without
            // WIN_MENU fullscreen clear pair, then render the text window.
            if (willDisplayMessageFirst) {
                await tty_display_nhwindow('message', false);
            } else if (willDisplayMenuWindow) {
                await tty_display_nhwindow('menu', false,
                    { maxcol: menu.cols, maxrow: menu.maxrow });
            }
            await renderCurrentPage();
            // Set flag so docrt() preserves the grid during nhgetch
            game._menuActive = true;
            game._activeMenu = menu;
        }
 
        enterModal('menu');
        // C ref: process_menu_window count-prefix state
        let counting = false;
        let count = 0;
        let reset_count = false;
        try {
            while (true) {
            // C ref: reset_count logic at top of loop
            if (reset_count) {
                counting = false;
                count = 0;
            } else {
                reset_count = true;
            }
 
            const pageItems = menu.pages[currentPage]?.items || menu.items;
            const selectors = new Set();
            for (const item of pageItems) {
                if (item.identifier && item.selector) {
                    selectors.add(typeof item.selector === 'string'
                        ? item.selector.charCodeAt(0) : item.selector);
                }
            }
 
            if (menu.logSelectionNhgetch) {
                pushRngLogEntry('^toplin[tty_nhgetch]');
            }
            const ch = await nhgetch();
 
            // ESC → cancel
            if (ch === 27) {
                return { count: -1, items: [] };
            }
 
            // C ref: digit handling for count prefix
            if (ch >= 0x30 && ch <= 0x39 && how !== PICK_NONE) {
                const dgt = ch - 0x30;
                count = count * 10 + dgt;
                if (count !== 0) {
                    counting = true;
                    reset_count = false;
                }
                continue;
            }
 
            const skipInvert = (item) => (item.itemflags & MENU_ITEMFLAGS_SKIPINVERT) !== 0;
            const setItemCell = (item) => {
                if (!display?.setCell) return;
                const visibleItems = menu.pages[currentPage]?.items || menu.items;
                const itemIdx = visibleItems.indexOf(item);
                if (itemIdx < 0) return;
                const selCh = item.selected ? (item.count === -1 ? '+' : '#') : '-';
                const textIndent = menu.forceOffx0 ? 0 : 1;
                display.setCell(menu.offx + textIndent + 2, itemIdx, selCh, CLR_GRAY, 0);
            };
            const selectPage = () => {
                if (how !== PICK_ANY) return;
                for (const item of pageItems) {
                    if (!item.identifier || item.selected || skipInvert(item)) continue;
                    item.selected = true;
                    item.count = -1;
                    setItemCell(item);
                }
            };
            const unselectPage = () => {
                for (const item of pageItems) {
                    if (!item.identifier || !item.selected || skipInvert(item)) continue;
                    item.selected = false;
                    item.count = -1;
                    setItemCell(item);
                }
            };
            const invertPage = () => {
                if (how !== PICK_ANY) return;
                for (const item of pageItems) {
                    if (!item.identifier || skipInvert(item)) continue;
                    item.selected = !item.selected;
                    if (!item.selected) item.count = -1;
                    setItemCell(item);
                }
            };
            const selectAll = () => {
                if (how !== PICK_ANY) return;
                for (const item of menu.items) {
                    if (!item.identifier || item.selected || skipInvert(item)) continue;
                    item.selected = true;
                    item.count = -1;
                    setItemCell(item);
                }
            };
            const unselectAll = () => {
                for (const item of menu.items) {
                    if (!item.identifier || !item.selected || skipInvert(item)) continue;
                    item.selected = false;
                    item.count = -1;
                    setItemCell(item);
                }
            };
            const invertAll = () => {
                if (how !== PICK_ANY) return;
                for (const item of menu.items) {
                    if (!item.identifier || skipInvert(item)) continue;
                    item.selected = !item.selected;
                    if (!item.selected) item.count = -1;
                    setItemCell(item);
                }
            };
 
            if ((ch === 32 || ch === MENU_NEXT_PAGE.charCodeAt(0)) && menu.npages > 1 && currentPage !== menu.npages - 1) {
                currentPage++;
                if (display?.grid) {
                    if (fullscreen && !menu.suppressPageBotlx) {
                        // C ref: process_menu_window fullscreen page advance
                        // clears MAP/STATUS and emits two SET_BOTLX marks.
                        setBotlx('tty_clear_nhwindow');
                        setBotlx('tty_clear_nhwindow');
                    }
                    await renderCurrentPage();
                }
                continue;
            }
 
            if (ch === MENU_PREVIOUS_PAGE.charCodeAt(0) && menu.npages > 1 && currentPage !== 0) {
                currentPage--;
                if (display?.grid) {
                    if (fullscreen && !menu.suppressPageBotlx) {
                        setBotlx('tty_clear_nhwindow');
                        setBotlx('tty_clear_nhwindow');
                    }
                    await renderCurrentPage();
                }
                continue;
            }
 
            if (ch === MENU_FIRST_PAGE.charCodeAt(0) && menu.npages > 1 && currentPage !== 0) {
                currentPage = 0;
                if (display?.grid) await renderCurrentPage();
                continue;
            }
 
            if (ch === MENU_LAST_PAGE.charCodeAt(0) && menu.npages > 1 && currentPage !== menu.npages - 1) {
                currentPage = menu.npages - 1;
                if (display?.grid) await renderCurrentPage();
                continue;
            }
 
            if (ch === MENU_SELECT_PAGE.charCodeAt(0)) {
                selectPage();
                continue;
            }
 
            if (ch === MENU_UNSELECT_PAGE.charCodeAt(0)) {
                unselectPage();
                continue;
            }
 
            if (ch === MENU_INVERT_PAGE.charCodeAt(0)) {
                invertPage();
                continue;
            }
 
            if (ch === MENU_SELECT_ALL.charCodeAt(0)) {
                selectAll();
                continue;
            }
 
            if (ch === MENU_UNSELECT_ALL.charCodeAt(0) && how !== PICK_NONE) {
                unselectAll();
                continue;
            }
 
            if (ch === MENU_INVERT_ALL.charCodeAt(0)) {
                invertAll();
                continue;
            }
 
            // Check if it's a selector
            if (selectors.has(ch)) {
                const selected = pageItems.find(item => {
                    if (!item.identifier) return false;
                    const sel = typeof item.selector === 'string'
                        ? item.selector.charCodeAt(0) : item.selector;
                    return sel === ch;
                });
                if (selected) {
                    if (how === PICK_ONE) {
                        // PICK_ONE: return immediately with this item
                        selectedByLetter = true;
                        return {
                            count: 1,
                            items: [{ identifier: selected.identifier, count: counting ? count : -1 }],
                        };
                    }
                    // PICK_ANY: toggle selection with count
                    // C ref: toggle_menu_curr logic
                    if (selected.selected) {
                        if (counting && count > 0) {
                            // Update count on already-selected item
                            selected.count = count;
                        } else {
                            // Deselect
                            selected.selected = false;
                            selected.count = -1;
                        }
                    } else {
                        if (counting && count === 0) {
                            // count prefix of 0 means no-op
                        } else {
                            selected.selected = true;
                            selected.count = counting ? count : -1;
                        }
                    }
                    // C ref: wintty.c:1181 set_item_state — update +/- indicator
                    if (display?.setCell) {
                        const pageItems = menu.pages[currentPage]?.items || menu.items;
                        const itemIdx = pageItems.indexOf(selected);
                        if (itemIdx >= 0) {
                            const selCh = selected.selected ? (selected.count === -1 ? '+' : '#') : '-';
                            const textIndent = menu.forceOffx0 ? 0 : 1;
                            display.setCell(menu.offx + textIndent + 2, itemIdx, selCh, CLR_GRAY, 0);
                        }
                    }
                    continue;
                }
            }
 
            // C ref: process_menu_window group accelerators (gselector).
            // These can select/toggle one or more matching entries.
            const gmatches = menu.items.filter(item => {
                if (!item.identifier || !item.gselector) return false;
                const gsel = typeof item.gselector === 'string'
                    ? item.gselector.charCodeAt(0) : item.gselector;
                return gsel === ch;
            });
            if (gmatches.length > 0) {
                if (how === PICK_ONE) {
                    const chosen = gmatches[0];
                    selectedByLetter = true;
                    return {
                        count: 1,
                        items: [{ identifier: chosen.identifier, count: counting ? count : -1 }],
                    };
                }
                if (how === PICK_ANY) {
                    for (const item of gmatches) {
                        if (item.selected) {
                            if (counting && count > 0) {
                                item.count = count;
                            } else {
                                item.selected = false;
                                item.count = -1;
                            }
                        } else if (!(counting && count === 0)) {
                            item.selected = true;
                            item.count = counting ? count : -1;
                        }
                        if (display?.setCell) {
                            const visibleItems = menu.pages[currentPage]?.items || menu.items;
                            const itemIdx = visibleItems.indexOf(item);
                            if (itemIdx >= 0) {
                                const selCh = item.selected ? (item.count === -1 ? '+' : '#') : '-';
                                const textIndent = menu.forceOffx0 ? 0 : 1;
                                display.setCell(menu.offx + textIndent + 2, itemIdx, selCh, CLR_GRAY, 0);
                            }
                        }
                    }
                    continue;
                }
            }
 
            // C ref: MENU_SEARCH — ':' triggers search-and-select
            // C ref: wintty.c process_menu_window case MENU_SEARCH
            if (ch === MENU_SEARCH && how !== PICK_NONE) {
                // Exit menu modal so getlin can enter its own modal
                exitModal('menu');
                let searchResult;
                try {
                    searchResult = await getlin('Search for:', display, {
                        logHookedLifecycle: true,
                    });
                } finally {
                    enterModal('menu');
                }
                if (searchResult && searchResult !== '\x1b') {
                    const pattern = searchResult.toLowerCase();
                    for (const item of menu.items) {
                        if (item.identifier && item.str &&
                            item.str.toLowerCase().includes(pattern)) {
                            if (how === PICK_ONE) {
                                return {
                                    count: 1,
                                    items: [{ identifier: item.identifier, count: -1 }],
                                };
                            }
                            // PICK_ANY: toggle selection
                            item.selected = !item.selected;
                        }
                    }
                }
                // C ref: process_menu_window keeps menu cursor ownership after
                // getlin returns from MENU_SEARCH. Restore the cursor to the
                // menu "more/end" location before the next key read.
                if (display?.grid && typeof display.setCursor === 'function') {
                    const currentItems = menu.pages[currentPage]?.items || menu.items;
                    const moreStr = menu.npages > 1
                        ? `(${currentPage + 1} of ${menu.npages})`
                        : menu.morestr;
                    const moreLine = currentItems.length;
                    const moreCol = menu.offx + 1 + moreStr.length;
                    display.setCursor(moreCol, moreLine);
                }
                continue;
            }
 
            // NUL, CR, LF → finish
            if (ch === 0 || ch === 13 || ch === 10) {
                // PICK_ANY: collect all selected items
                if (how === PICK_ANY) {
                    const result = [];
                    for (const item of menu.items) {
                        if (item.identifier && item.selected) {
                            result.push({ identifier: item.identifier, count: item.count });
                        }
                    }
                    return { count: result.length, items: result };
                }
                // PICK_ONE/PICK_NONE: no selection
                return { count: 0, items: [] };
            }
 
            // Space on single/last page → finish (same as CR)
            if (ch === 32) {
                if (how === PICK_ANY) {
                    const result = [];
                    for (const item of menu.items) {
                        if (item.identifier && item.selected) {
                            result.push({ identifier: item.identifier, count: item.count });
                        }
                    }
                    return { count: result.length, items: result };
                }
                return { count: 0, items: [] };
            }
            }
        } finally {
            exitModal('menu');
            // C ref: windows.c select_menu() keeps bot_disabled=TRUE during
            // the entire tty_select_menu, INCLUDING the dismiss. C's bot()
            // macro logs >bot/<bot midlog even when disabled, but returns
            // early without clearing disp.botl/botlx. This means flags
            // from docorner's SET_BOTLX persist until after select_menu
            // restores bot_disabled, when moveloop_core's conditional bot
            // can then clear them. Do NOT restore bot_disabled here.
            game._menuActive = false;
            game._activeMenu = null;
            // C ref: tty_select_menu → tty_dismiss_nhwindow → erase_menu_or_text
            // Events must be emitted regardless of display mode (grid or headless).
            tty_dismiss_nhwindow(menu.winId);
            erase_menu_or_text(menu.winId, menu.offx, menu.maxrow || 0);
            if (game.level) {
                if (menu.offx === 0 || fullscreen) {
                    // C ref: erase_menu_or_text offx==0 dispatches to
                    // docrt() + flush_screen(1). C's docrt_flags() calls
                    // cls() first (which produces toplin + botlx events
                    // from tty_clear_nhwindow), then newsym loop, then
                    // SET_BOTLX. JS's docrt_cls() matches this event
                    // sequence: toplin + botlx[cls] + botlx[tty_clear]×3.
                    await docrt_cls();
                    // Repaint map/status into the grid after cls-like clear,
                    // but keep teardown event ownership unchanged.
                    await docrt(false, true);
                    setBotlx('docrt_flags');
                    if (menu.forceOffx0 || menu.flushBotUnsuppressed) {
                        // NHW_TEXT teardown should clear pending bot flags
                        // in this same phase (matching C's single bot call
                        // before reset_cmd_vars for this path).
                        const oldBotSuppressed = !!game?.bot_disabled;
                        if (game) game.bot_disabled = false;
                        try {
                            await flush_screen();
                        } finally {
                            if (game) game.bot_disabled = oldBotSuppressed;
                        }
                    } else {
                        await flush_screen();
                    }
                } else {
                    // C: offx!=0 → docorner (calls bot internally if ymax reaches status)
                    await docorner(menu.offx, (menu.maxrow || 0) + 1);
                }
            } else if (display?.grid) {
                clearMenuFromGrid(menu, display);
            }
        }
    } finally {
        if (game) {
            game.bot_disabled = oldBotDisabled;
        }
    }
}
 
/**
 * Destroy a menu window (cleanup).
 * C ref: tty_destroy_nhwindow()
 */
export function destroy_nhwindow_menu(menu) {
    // C ref: tty_destroy_nhwindow frees the game.wins[] slot.
    // The dismiss (if window is still active) happens in the menu finally block.
    if (menu.winId >= 0) {
        // Don't call tty_destroy_nhwindow here — the dismiss was already
        // handled by the finally block. Just free the slot.
        if (game.wins[menu.winId]) game.wins[menu.winId] = null;
        menu.winId = -1;
    }
    menu.items = [];
    menu.prompt = null;
    menu.finalized = false;
}
 
// ── Internal rendering ──
 
/**
 * Render menu content onto the Terminal grid.
 * C ref: process_menu_window() rendering loop in wintty.c
 *
 * Writes menu items at (offx, row) with space prefix, clearing
 * each row from offx to end of line. Displays morestr on the last row.
 */
function renderMenuToGrid(menu, display) {
    const offx = menu.offx;
    const cols = display.cols || 80;
    const items = arguments[2] || menu.items;
    const moreStr = arguments[3] || menu.morestr;
 
    // C: tty_clear_nhwindow(WIN_MESSAGE) — clear message line before menu
    // (implicit: the menu starts at row 0 which overlaps the message line)
 
    // Render each menu item
    for (let i = 0; i < items.length; i++) {
        const item = items[i];
        // C: cl_end() — clear from offx to end of line
        for (let c = offx; c < cols; c++) {
            display.setCell(c, i, ' ', CLR_GRAY, 0);
        }
 
        // C: putchar(' ') at offx — NHW_MENU adds 1-col indent before items.
        // NHW_TEXT (forceOffx0) doesn't add indent — text starts at offx.
        const textIndent = menu.forceOffx0 ? 0 : 1;
        if (textIndent) display.setCell(offx, i, ' ', CLR_GRAY, 0);
 
        // C: render item text starting at offx + textIndent
        const attr = item.attr || 0;
        const color = (item.color != null && item.color !== NO_COLOR)
            ? item.color : CLR_GRAY;
 
        // Determine where attribute highlighting starts
        // C: attr_n = 0 for non-selectable (whole line), 4 for selectable (after "c - ")
        const attrStart = item.identifier ? 4 : 0;
 
        for (let j = 0; j < item.str.length; j++) {
            const charCol = offx + textIndent + j;
            if (charCol >= cols) break;
            const useAttr = (j >= attrStart) ? attr : 0;
            const useColor = (j >= attrStart) ? color : CLR_GRAY;
            // C ref: wintty.c:1469 — initial page render uses '*' for selected, '#' for counted
            // set_item_state (wintty.c:1181) uses '+' for user-toggled selections
            const ch = (j === 2 && item.identifier && item.selected)
                ? (item.count === -1 ? '*' : '#')
                : item.str[j];
            display.setCell(charCol, i, ch, useColor, useAttr);
        }
    }
 
    // C: Clear extra lines below items, then render morestr
    // C's NHW_TEXT windows show "--More--" at the bottom (line 23 for 24-row)
    // instead of the menu's "(end)" morestr.
    const moreLine = items.length;
    if (menu.forceOffx0) {
        // C ref: dmore (wintty.c:1261) — offset is 1 for NHW_TEXT, 2 for NHW_MENU
        // NHW_TEXT: --More-- at col 0; NHW_MENU fullscreen: --More-- at col 1
        const bottomRow = menu.forceOffx0PromptAtPageEnd
            ? items.length
            : (display?.rows || 24) - 1;
        for (let c = 0; c < cols; c++) display.setCell(c, bottomRow, ' ', CLR_GRAY, 0);
        const moreText = '--More--';
        const moreCol = menu.forceOffx0PromptLeadingBlank ? 1 : 0;
        for (let j = 0; j < moreText.length; j++) {
            display.setCell(moreCol + j, bottomRow, moreText[j], CLR_GRAY, 0);
        }
        return;
    }
 
    // Clear the morestr line
    for (let c = offx; c < cols; c++) {
        display.setCell(c, moreLine, ' ', CLR_GRAY, 0);
    }
 
    // C: dmore() renders "(end) " at curx + 2 offset from window position
    // After last item, cursor is at (offx, moreLine). dmore offsets by 2.
    // tty_curs(BASE_WINDOW, curx + 2, cury) → col = offx + 2 - 1 = offx + 1
    // (tty_curs does --x, then + offx_of_base=0)
    // Actually: ttyDisplay->curx = offx after tty_curs(window, 1, page_lines).
    // dmore: tty_curs(BASE_WINDOW, offx + 2, moreLine) → screen col = offx + 2 - 1 = offx + 1
    const moreCol = offx + 1;
    for (let j = 0; j < moreStr.length; j++) {
        const c = moreCol + j;
        if (c >= cols) break;
        display.setCell(c, moreLine, moreStr[j], CLR_GRAY, 0);
    }
 
    if (menu.statusTitleOnly && Array.isArray(display.grid) && display.grid[22]) {
        // C iactions status-title overlay: show hero name/title only (no stats)
        // on row 22. Row 23 (stats) is cleared.
        const statusRow = display.grid[22];
        let rowText = '';
        for (let i = 0; i < Math.min(statusRow.length, cols); i++) {
            rowText += statusRow[i]?.ch || ' ';
        }
        const statIndex = rowText.indexOf('St:');
        let titleOnly = (statIndex > 0) ? rowText.slice(0, statIndex).trimEnd() : rowText.trimEnd();
        if (titleOnly.length > 22) titleOnly = titleOnly.slice(0, 22);
        if (typeof display.clearRow === 'function') {
            display.clearRow(22);
        }
        if (typeof display.putstr === 'function') {
            display.putstr(0, 22, titleOnly);
        } else {
            for (let i = 0; i < titleOnly.length && i < cols; i++) {
                display.setCell(i, 22, titleOnly[i], CLR_GRAY, 0);
            }
        }
    }
 
}
 
/**
 * Clear menu content from the Terminal grid.
 * C ref: erase_menu_or_text() in wintty.c
 */
function clearMenuFromGrid(menu, display) {
    const offx = menu.offx;
    const cols = display.cols || 80;
    const totalRows = menu.maxrow || (menu.items.length + 1);
    erase_menu_or_text(menu.winId >= 0 ? menu.winId : -1, offx, totalRows);

    for (let i = 0; i < totalRows; i++) {
        for (let c = offx; c < cols; c++) {
            display.setCell(c, i, ' ', CLR_GRAY, 0);
        }
    }
}