From a9ca4ab885b288ced94bd94ddb81b08350e0083e Mon Sep 17 00:00:00 2001 From: Yipeng Liu Date: Tue, 23 May 2023 18:38:38 +0800 Subject: [PATCH] Enhance tab completion. --- src/components/input.tsx | 2 +- src/utils/tabCompletion.ts | 15 ++++++++++++--- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/src/components/input.tsx b/src/components/input.tsx index bf9de68..a9647e6 100644 --- a/src/components/input.tsx +++ b/src/components/input.tsx @@ -34,7 +34,7 @@ export const Input = ({ if (event.key === 'Tab') { event.preventDefault(); - handleTabCompletion(command, setCommand); + handleTabCompletion(command, setHistory, setCommand); } if (event.key === 'Enter' || event.code === '13') { diff --git a/src/utils/tabCompletion.ts b/src/utils/tabCompletion.ts index be3035e..747f294 100644 --- a/src/utils/tabCompletion.ts +++ b/src/utils/tabCompletion.ts @@ -2,13 +2,22 @@ import * as bin from './bin'; export const handleTabCompletion = ( command: string, + setHistory: (value: string) => void, setCommand: React.Dispatch>, ) => { - const commands = Object.keys(bin).filter((entry) => + const commands = ['clear', ...Object.keys(bin)].filter((entry) => entry.startsWith(command), ); - if (commands.length === 1) { - setCommand(commands[0]); + if (commands.length >= 1) { + const prefix = commands.reduce((prev, curr) => { + let i = 0; + while (i < prev.length && i < curr.length && prev[i] === curr[i]) + ++i; + return prev.slice(0, i); + }, commands[0]); + setCommand(prefix); + if (commands.length > 1) + setHistory(commands.join(' ')); } };