-
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathCommandsProvider.tsx
More file actions
82 lines (70 loc) · 2.69 KB
/
Copy pathCommandsProvider.tsx
File metadata and controls
82 lines (70 loc) · 2.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import React from 'react';
import { createContext, useCallback, useContext, useEffect, useState } from 'react';
import { I18nRegistry, CommandList } from '../interfaces';
import logToConsole from '../helpers/logger';
import getTerminalCommandRegistry from '../registry/TerminalCommandRegistry';
interface CommandsContextProps {
children: React.ReactElement;
i18nRegistry: I18nRegistry;
}
interface CommandsContextValues {
commands: CommandList;
invokeCommand: (endPoint: string, param: string[]) => AsyncGenerator<string | JSX.Element, null, void>;
translate: (
id: string,
fallback?: string,
params?: Record<string, unknown> | string[],
packageKey?: string,
sourceName?: string
) => string;
}
export const CommandsContext = createContext({} as CommandsContextValues);
export const useCommands = (): CommandsContextValues => useContext(CommandsContext);
export const CommandsProvider = ({ children, i18nRegistry }: CommandsContextProps) => {
const [commands, setCommands] = useState<CommandList>({});
useEffect(() => {
getTerminalCommandRegistry().getCommands().then(setCommands);
}, []);
const translate = useCallback(
(
id: string,
fallback = '',
params: Record<string, unknown> | string[] = [],
packageKey = 'Shel.Neos.Terminal',
sourceName = 'Main'
): string => {
return i18nRegistry.translate(id, fallback, params, packageKey, sourceName);
},
[]
);
const invokeCommand = useCallback(
async function* (commandName: string, args: string[]): AsyncGenerator<string | JSX.Element, null, void> {
const command = commands[commandName];
if (!command)
throw Error(
translate('command.doesNotExist', `The command {commandName} does not exist!`, { commandName })
);
for await (const { success, view, message, options } of getTerminalCommandRegistry().invokeCommand(
commandName,
args.join(' ')
)) {
logToConsole(
success ? 'log' : 'error',
translate('command.output', `"{commandName} {argument}":`, {
commandName,
argument: args.join(' '),
}),
message,
view,
options
);
yield view;
}
return;
},
[commands]
);
return (
<CommandsContext.Provider value={{ invokeCommand, commands, translate }}>{children}</CommandsContext.Provider>
);
};