본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

useTerminal

원문 보기 위키 갱신

터미널 스타일 인터페이스를 위해 명령 실행, 입력 상태, 명령 히스토리를 관리하는 훅이에요.

출처: 문서

본문

사용법 (Usage)

import { useTerminal, TerminalResponse } from '@primereact/headless/terminal';
const { rootProps, promptValueProps, commandResponseProps, state } = useTerminal({
    prompt: '$',
    onCommand: commandHandler
});

<div {...rootProps}>
    {state.commands.map((cmd, index) => (
        <div key={index}>
            <span>{cmd.text}</span>
            {cmd.response && <div {...commandResponseProps}>{cmd.response}</div>}
        </div>
    ))}
    <input {...promptValueProps} />
</div>;

useTerminal은 명령 입력, 실행, 히스토리 탐색을 관리해요. 컴포넌트 기반 API가 필요하다면 Primitive 문서를 참고하세요.

기능 (Features)

  • 명령 실행, onCommand는 입력된 텍스트를 받고 ReactNode, 명확한 신호(null), 또는 promise를 반환해요
  • 명령 히스토리, state.commands는 렌더링된 응답과 함께 입력된 모든 명령을 기록해요
  • 히스토리 불러오기, Arrow Up으로 이전에 입력했던 명령을 거슬러 탐색해요
  • 비동기 지원, onCommand는 네트워크 기반 명령을 위해 Promise<TerminalResponse>를 반환할 수 있어요
  • 라이브 리전 출력, commandResponseProps에는 aria-live가 포함되어 있어 보조 기술에 응답이 전달돼요

콜백 다루기 (Working with callbacks)

명령 처리 (Handling commands)

ReactNode를 반환하면 응답을 렌더링하고, null을 반환하면 히스토리를 지우며, undefined를 반환하면 렌더링을 건너뜁니다.

const handler = (text: string): TerminalResponse => {
    if (text === 'clear') return null;
    if (text === 'help')
        return (
            <ul>
                <li>clear</li>
                <li>help</li>
            </ul>
        );
    return `Unknown command: ${text}`;
};

const terminal = useTerminal({ onCommand: handler });

비동기 명령 실행 (Async command execution)

네트워크 호출을 처리하려면 onCommand에서 promise를 반환하세요. promise가 resolve되면 응답이 렌더링돼요.

const handler = async (text: string): Promise<TerminalResponse> => {
    const result = await fetch(`/api/cmd?q=${encodeURIComponent(text)}`);
    return result.text();
};

명령 히스토리 읽기 (Reading command history)

state.commands는 { text, response? } 항목의 배열이에요. 그대로 렌더링해서 실행 로그를 보여줄 수 있어요.

const { state } = useTerminal({ onCommand: handler });

state.commands.map((cmd) => cmd.text);

명령으로 지우기 (Clearing via command)

onCommand에서 null을 반환하면 터미널을 비워요. 사용자에게 관례적인 clear 명령을 제공하는 셈이죠.

const handler = (text: string): TerminalResponse => {
    if (text === 'clear') return null;
    return `echo: ${text}`;
};

data 속성으로 스타일링 (Styling with data attributes)

prop 객체에는 data-scope="terminal"과 data-part 속성이 포함돼요.

Scope (Scope) Part (Part)
terminal root
terminal promptvalue
terminal commandresponse
[data-scope='terminal'][data-part='root'] {
    background-color: #1e1e1e;
    color: #fff;
    font-family: monospace;
}

[data-scope='terminal'][data-part='promptvalue'] {
    background: transparent;
    border: none;
    outline: none;
}

[data-scope='terminal'][data-part='commandresponse'] {
    padding-left: 1rem;
}

API

useTerminal

접근성 (Accessibility)

Enter는 현재 명령을 제출하고, Up/Down 화살표는 명령 히스토리를 탐색하며, 포커스는 입력에 유지돼요. 전체 WAI-ARIA 준수 세부 사항은 Primitive 문서를 참고하세요.

더 알아보기 (Learn more)