InputContext

InputContext is a lightweight input bus that normalizes RPG Maker MZ inputs and lets components subscribe only when they have focus.

Files

  • menus/src/components/InputContext.tsx

Exports

  • InputContextProvider — place near the root of your UI tree

  • useInputContext() — access the API in child components

  • RPGMakerKeys — enum of logical keys (ok, cancel, up, down, left, right, pageup, pagedown, ...)

API

  • addEventListener(id, type, key, callback)

    • type: 'press' | 'trigger' | 'repeat' | 'direction' | 'direction8'

    • key: one of RPGMakerKeys

    • callback(key, data?) => boolean | Promise<boolean>

      • Return true to consume the input (prevent other listeners in the same frame).

  • removeEventListener(id)

Typical usage pattern

import React, { useEffect, useRef } from 'react';
import { useInputContext, RPGMakerKeys } from '../../components/InputContext';

const PagedList: React.FC<{ hasFocus: boolean }> = ({ hasFocus }) => {
  const input = useInputContext();
  const idRef = useRef(`PagedList_${Math.random().toString(36).slice(2)}`);

  useEffect(() => {
    if (!hasFocus) return; // only active when focused
    const id = idRef.current;
    input.addEventListener(id + '_down', 'trigger', RPGMakerKeys.DOWN, () => {
      // move selection down
      return true; // consume
    });
    input.addEventListener(id + '_up', 'trigger', RPGMakerKeys.UP, () => {
      // move selection up
      return true;
    });
    input.addEventListener(id + '_ok', 'trigger', RPGMakerKeys.OK, () => {
      // confirm selection
      return true;
    });
    return () => {
      input.removeEventListener(id + '_down');
      input.removeEventListener(id + '_up');
      input.removeEventListener(id + '_ok');
    };
  }, [hasFocus]);

  return <div>...</div>;
};

Notes

  • Many stock components (e.g., Chooser, Confirm, Message) already listen to inputs internally; wrap them with a focus flag so they only respond when on top.

  • For analog/directional input, use type: 'direction' (4‑way) or type: 'direction8' (8‑way); the callback receives a numeric direction (2,4,6,8).

See also

Last updated