| 46 | export const ChatCommandPrefix = /^[::]/; |
| 47 | |
| 48 | export function useChatCommand(commands: ChatCommands = {}) { |
| 49 | function extract(userInput: string) { |
| 50 | const match = userInput.match(ChatCommandPrefix); |
| 51 | if (match) { |
| 52 | return userInput.slice(1) as keyof ChatCommands; |
| 53 | } |
| 54 | return userInput as keyof ChatCommands; |
| 55 | } |
| 56 | |
| 57 | function search(userInput: string) { |
| 58 | const input = extract(userInput); |
| 59 | const desc = Locale.Chat.Commands; |
| 60 | return Object.keys(commands) |
| 61 | .filter((c) => c.startsWith(input)) |
| 62 | .map((c) => ({ |
| 63 | title: desc[c as keyof ChatCommands], |
| 64 | content: ":" + c, |
| 65 | })); |
| 66 | } |
| 67 | |
| 68 | function match(userInput: string) { |
| 69 | const command = extract(userInput); |
| 70 | const matched = typeof commands[command] === "function"; |
| 71 | |
| 72 | return { |
| 73 | matched, |
| 74 | invoke: () => matched && commands[command]!(userInput), |
| 75 | }; |
| 76 | } |
| 77 | |
| 78 | return { match, search }; |
| 79 | } |