Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

1.6 KB
Raw Blame
import { useEffect, use, useId } from 'react';
import FocusContext from '../components/FocusContext.js';
import useStdin from './use-stdin.js';
/**
A React hook that returns focus state and focus controls for the current component.
A component that uses the `useFocus` hook becomes "focusable" to Ink, so when the user presses <kbd>Tab</kbd>, Ink will switch focus to this component. If there are multiple components that execute the `useFocus` hook, focus will be given to them in registration order. Reordering keyed components does not change their registration order.
*/
const useFocus = ({ isActive = true, autoFocus = false, id: customId, } = {}) => {
    const { isRawModeSupported, setRawMode } = useStdin();
    const { activeId, add, remove, activate, deactivate, focus } = use(FocusContext);
    const generatedId = useId();
    const id = customId ?? generatedId;
    useEffect(() => {
        add(id, { autoFocus });
        return () => {
            remove(id);
        };
    }, [id, autoFocus, add, remove]);
    useEffect(() => {
        // Reapply active state when autoFocus changes and re-registers this component.
        if (isActive) {
            activate(id);
        }
        else {
            deactivate(id);
        }
    }, [isActive, id, autoFocus, activate, deactivate]);
    useEffect(() => {
        if (!isRawModeSupported || !isActive) {
            return;
        }
        setRawMode(true);
        return () => {
            setRawMode(false);
        };
    }, [isActive, isRawModeSupported, setRawMode]);
    return {
        isFocused: activeId === id,
        focus,
    };
};
export default useFocus;