File size: 2,117 Bytes
f716e02
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
const output = document.getElementById('output');
const input = document.getElementById('command-input');

let commandHistory = [];
let historyIndex = -1;

input.addEventListener('keydown', async (event) => {
    if (event.key === 'Enter') {
        event.preventDefault();
        const command = input.value.trim();
        if (command) {
            commandHistory.push(command);
            historyIndex = commandHistory.length;
            await executeCommand(command);
        }
        input.value = '';
    } else if (event.key === 'ArrowUp') {
        event.preventDefault();
        if (historyIndex > 0) {
            historyIndex--;
            input.value = commandHistory[historyIndex];
        }
    } else if (event.key === 'ArrowDown') {
        event.preventDefault();
        if (historyIndex < commandHistory.length - 1) {
            historyIndex++;
            input.value = commandHistory[historyIndex];
        } else {
            historyIndex = commandHistory.length;
            input.value = '';
        }
    }
});

async function executeCommand(command) {
    output.innerHTML += `$ ${command}\n`;

    try {
        const response = await fetch('http://localhost:5000/execute', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ command }),
        });

        const data = await response.json();

        if (response.ok) {
            output.innerHTML += data.output;
            if (data.error) {
                output.innerHTML += `Error: ${data.error}\n`;
            }
        } else {
            output.innerHTML += `Error: ${data.error}\n`;
        }
    } catch (error) {
        output.innerHTML += `Error: ${error.message}\n`;
    }

    output.scrollTop = output.scrollHeight;
}

// Focus on input when clicking anywhere in the terminal
document.getElementById('terminal').addEventListener('click', () => {
    input.focus();
});

// Initial welcome message
output.innerHTML = "Welcome to the Linux Practice Tool!\nType 'help' for a list of available commands.\n\n";