Sure! Below is a complete implementation of a CMD-like interface using HTML, CSS, and JavaScript. The interface is dark-themed and supports the echo, sum, and generate commands as specified.
Features Implemented:
-
Dark-Themed Interface: Styled to resemble a classic command-line interface with a dark background and light text.
-
Command Support:
echo <message>: Prints back the provided message.
sum <math expression>: Safely evaluates mathematical expressions without using eval, preventing the execution of arbitrary JavaScript code.
generate <alphabetic|alphanumeric|digits> <length> <options>: Generates a string based on the specified type and length. It can include additional options like --includeuppercase for the alphabetic type.
-
Command Parsing: The input is parsed to identify commands and their arguments.
-
User Experience: Commands are entered in an input field, and outputs are displayed above it.
Complete Code:
1. HTML (index.html)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CMD-like Interface</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id="terminal">
<div id="output"></div>
<div id="input-line">
<span class="prompt">C:\></span>
<input type="text" id="command-input" autofocus autocomplete="off">
</div>
</div>
<script src="script.js"></script>
</body>
</html>
2. CSS (styles.css)
body {
margin: 0;
padding: 0;
background-color: #1e1e1e;
color: #ffffff;
font-family: Consolas, monospace;
font-size: 16px;
}
#terminal {
display: flex;
flex-direction: column;
height: 100vh;
padding: 10px;
box-sizing: border-box;
}
#output {
flex: 1;
overflow-y: auto;
white-space: pre-wrap;
}
#input-line {
display: flex;
}
.prompt {
margin-right: 5px;
color: #00ff00;
}
#command-input {
background: none;
border: none;
outline: none;
color: #ffffff;
flex: 1;
font-family: inherit;
font-size: inherit;
}
3. JavaScript (script.js)
document.addEventListener('DOMContentLoaded', () => {
const input = document.getElementById('command-input');
const output = document.getElementById('output');
input.addEventListener('keydown', function(event) {
if (event.key === 'Enter') {
const command = input.value.trim();
if (command !== '') {
appendOutput(`C:\\> ${command}`);
handleCommand(command);
input.value = '';
}
}
});
function appendOutput(text) {
const line = document.createElement('div');
line.textContent = text;
output.appendChild(line);
output.scrollTop = output.scrollHeight;
}
function handleCommand(command) {
const args = parseArgs(command);
const primaryCommand = args.shift().toLowerCase();
switch(primaryCommand) {
case 'echo':
handleEcho(args);
break;
case 'sum':
handleSum(args);
break;
case 'generate':
handleGenerate(args);
break;
default:
appendOutput(`'${primaryCommand}' is not recognized as an internal or external command.`);
break;
}
}
function parseArgs(command) {
// Simple parser that handles quoted strings
const regex = /"([^"]+)"|'([^']+)'|(\S+)/g;
const args = [];
let match;
while ((match = regex.exec(command)) !== null) {
args.push(match[1] || match[2] || match[3]);
}
// Remove the command itself
args.shift();
return args;
}
function handleEcho(args) {
const message = args.join(' ');
appendOutput(message);
}
function handleSum(args) {
if (args.length === 0) {
appendOutput('Usage: sum <math expression>');
return;
}
const expression = args.join(' ');
try {
const result = evaluateMathExpression(expression);
appendOutput(result.toString());
} catch (e) {
appendOutput('Error: Invalid mathematical expression.');
}
}
// Safe math expression evaluator
function evaluateMathExpression(expr) {
// Tokenize the input
const tokens = expr.match(/(\d+\.?\d*)|[\+\-\*\/\^\(\)]/g);
if (!tokens) throw new Error('Invalid expression');
// Convert to Reverse Polish Notation using Shunting Yard algorithm
const outputQueue = [];
const operatorStack = [];
const operators = {
'+': { precedence: 2, associativity: 'Left' },
'-': { precedence: 2, associativity: 'Left' },
'*': { precedence: 3, associativity: 'Left' },
'/': { precedence: 3, associativity: 'Left' },
'^': { precedence: 4, associativity: 'Right' }
};
tokens.forEach(token => {
if (parseFloat(token)) {
outputQueue.push(token);
} else if (token in operators) {
const o1 = token;
let o2 = operatorStack[operatorStack.length - 1];
while (o2 in operators && (
(operators[o1].associativity === 'Left' && operators[o1].precedence <= operators[o2].precedence) ||
(operators[o1].associativity === 'Right' && operators[o1].precedence < operators[o2].precedence)
)) {
outputQueue.push(operatorStack.pop());
o2 = operatorStack[operatorStack.length - 1];
}
operatorStack.push(o1);
} else if (token === '(') {
operatorStack.push(token);
} else if (token === ')') {
while (operatorStack.length && operatorStack[operatorStack.length - 1] !== '(') {
outputQueue.push(operatorStack.pop());
}
operatorStack.pop(); // Remove '('
}
});
while (operatorStack.length) {
outputQueue.push(operatorStack.pop());
}
// Evaluate RPN
const stack = [];
outputQueue.forEach(token => {
if (parseFloat(token)) {
stack.push(parseFloat(token));
} else {
const b = stack.pop();
const a = stack.pop();
switch(token) {
case '+': stack.push(a + b); break;
case '-': stack.push(a - b); break;
case '*': stack.push(a * b); break;
case '/': stack.push(a / b); break;
case '^': stack.push(Math.pow(a, b)); break;
}
}
});
if (stack.length !== 1) throw new Error('Invalid expression');
return stack[0];
}
function handleGenerate(args) {
if (args.length < 2) {
appendOutput('Usage: generate <alphabetic|alphanumeric|digits> <length> [options]');
return;
}
const type = args[0].toLowerCase();
const length = parseInt(args[1], 10);
if (isNaN(length) || length <= 0) {
appendOutput('Error: Length must be a positive integer.');
return;
}
const options = args.slice(2);
let includeUppercase = false;
options.forEach(option => {
if (option === '--includeuppercase') {
includeUppercase = true;
}
// Add more options here if needed
});
let charset = '';
switch(type) {
case 'alphabetic':
charset = 'abcdefghijklmnopqrstuvwxyz';
if (includeUppercase) {
charset += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
}
break;
case 'alphanumeric':
charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
break;
case 'digits':
charset = '0123456789';
break;
default:
appendOutput(`Error: Unknown type '${type}'. Use alphabetic, alphanumeric, or digits.`);
return;
}
if (charset.length === 0) {
appendOutput('Error: Character set is empty.');
return;
}
const generated = generateRandomString(charset, length);
appendOutput(generated);
}
function generateRandomString(charset, length) {
let result = '';
const crypto = window.crypto || window.msCrypto;
const randomValues = new Uint32Array(length);
crypto.getRandomValues(randomValues);
for (let i = 0; i < length; i++) {
result += charset[randomValues[i] % charset.length];
}
return result;
}
});
How It Works:
-
HTML Structure:
- The terminal consists of two main parts:
#output: Displays the command outputs.
#input-line: Contains the prompt (C:\>) and an input field for the user to type commands.
-
Styling with CSS:
- A dark background (
#1e1e1e) with light-colored text (#ffffff).
- The prompt is colored green (
#00ff00) to resemble traditional command prompts.
- The layout is flexible to occupy the full viewport height, with the output area scrollable.
-
JavaScript Functionality:
- Event Listener: Captures the
Enter key press to process commands.
- Command Parsing:
- Splits the input into command and arguments, respecting quoted strings.
- Command Handling:
- Echo: Concatenates and displays the provided message.
- Sum:
- Uses a safe math expression evaluator that parses the expression, converts it to Reverse Polish Notation (RPN) using the Shunting Yard algorithm, and then evaluates it.
- This approach avoids using
eval and mitigates security risks.
- Generate:
- Supports
alphabetic, alphanumeric, and digits types.
- Can include options like
--includeuppercase for the alphabetic type.
- Utilizes
crypto.getRandomValues for secure random generation.
- Output Display: Each command and its output are appended to the
#output div, emulating a real terminal experience.
Usage Examples:
-
Echo Command:
C:\> echo Hello, World!
Hello, World!
-
Sum Command:
C:\> sum 6 * 9 + 6 + 9
69
-
Generate Command:
C:\> generate alphabetic 12 --includeuppercase
aBcdEfGhIjKl
How to Run:
-
Create Files:
- Create three files in the same directory:
index.html, styles.css, and script.js.
- Copy the respective code snippets into these files.
-
Open in Browser:
- Open
index.html in your web browser.
- You should see a dark terminal interface where you can type and execute the supported commands.
-
Interact:
- Click on the input field or press
Ctrl+L (if implemented) to focus, type your command, and press Enter to execute.
Notes:
- The math evaluator supports basic arithmetic operations and respects operator precedence.
- The
generate command uses the browser's cryptographic functions to ensure randomness.
- Additional commands and features can be added by extending the
handleCommand function and implementing corresponding handlers.
Feel free to customize and extend this interface to suit your needs!