/
old
48 lines (40 loc) · 1.12 KB
/
old
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
import { commands } from './commands.js';
let state = {
fs: {},
path: ['root'],
root: '',
commands,
output: [
]
}
const interact = (command) => {
const splitCommand = command.split(' ');
let mainCommand = state.commands[splitCommand[0]];
if (mainCommand === undefined) mainCommand = state.commands.default;
mainCommand.action(state, splitCommand.shift());
return state;
}
const addKeyHandler = (root) => {
root.addEventListener('keydown', e => {
if (e.keyCode === 13) {
e.preventDefault();
interact(getCommand());
}
});
root.addEventListener('click', e => {
getCurrentInput().focus();
})
}
const getCurrentInput = () => {
return state.output[state.output.length - 1].children[1];
}
const getCommand = () => {
return getCurrentInput().innerText;
}
export const createCli = (structure, root) => {
state.fs = typeof structure == 'object' ? structure : state.fs;
if(root instanceof Element) state.root = root;
else throw new Error('No root element provided');
addKeyHandler(root);
return interact;
}