first commit

This commit is contained in:
Raven Scott 2024-11-26 03:12:55 -05:00
commit e1bc040673
5 changed files with 443 additions and 0 deletions

2
.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
node_modules
package-lock.json

228
app.js Normal file
View File

@ -0,0 +1,228 @@
import Hyperswarm from 'hyperswarm';
import b4a from 'b4a';
import { Terminal } from 'xterm';
import { FitAddon } from 'xterm-addon-fit';
const swarm = new Hyperswarm();
const connections = {};
let activePeer = null;
let terminalSessions = {}; // Track terminal states per container
let xterm = null; // The current terminal instance
let fitAddon = null; // FitAddon instance
// DOM Elements
const terminalModal = document.getElementById('terminal-modal');
const terminalTitle = document.getElementById('terminal-title');
const terminalContainer = document.getElementById('terminal-container');
const tray = document.getElementById('tray');
const containerList = document.getElementById('container-list');
// Initialize the app
console.log('[INFO] Client app initialized');
// Add a new connection
document.getElementById('add-connection-form').addEventListener('submit', (e) => {
e.preventDefault();
const topicHex = document.getElementById('new-connection-topic').value;
const topic = b4a.from(topicHex, 'hex');
const topicId = topicHex.substring(0, 12);
console.log(`[INFO] Adding connection with topic: ${topicHex}`);
const connectionItem = document.createElement('li');
connectionItem.className = 'list-group-item d-flex align-items-center';
connectionItem.dataset.topicId = topicId;
connectionItem.innerHTML = `
<span class="connection-status status-disconnected"></span>${topicId}
`;
connectionItem.addEventListener('click', () => window.switchConnection(topicId));
document.getElementById('connection-list').appendChild(connectionItem);
connections[topicId] = { topic, peer: null };
swarm.join(topic, { client: true, server: false });
swarm.on('connection', (peer) => {
console.log(`[INFO] Connected to peer for topic: ${topicHex}`);
connections[topicId].peer = peer;
updateConnectionStatus(topicId, true);
peer.on('data', (data) => {
try {
const response = JSON.parse(data.toString());
console.log(`[DEBUG] Received data from server: ${JSON.stringify(response)}`);
if (response.type === 'containers') {
renderContainers(response.data);
} else if (response.type === 'terminalOutput') {
appendTerminalOutput(response.data, response.containerId);
}
} catch (err) {
console.error(`[ERROR] Failed to parse data from server: ${err.message}`);
}
});
peer.on('close', () => {
console.log(`[INFO] Disconnected from peer for topic: ${topicHex}`);
updateConnectionStatus(topicId, false);
});
});
});
// Collapse/Expand Sidebar
document.getElementById('collapse-sidebar-btn').addEventListener('click', () => {
const sidebar = document.getElementById('sidebar');
sidebar.classList.toggle('collapsed');
const btn = document.getElementById('collapse-sidebar-btn');
btn.textContent = sidebar.classList.contains('collapsed') ? '>' : '<';
});
// Update connection status
function updateConnectionStatus(topicId, isConnected) {
const connectionItem = document.querySelector(`[data-topic-id="${topicId}"] .connection-status`);
connectionItem.className = `connection-status ${isConnected ? 'status-connected' : 'status-disconnected'}`;
}
// Switch between connections
function switchConnection(topicId) {
activePeer = connections[topicId].peer;
const connectionTitle = document.getElementById('connection-title');
if (!connectionTitle) {
console.error('[ERROR] Connection title element is missing.');
return;
}
connectionTitle.textContent = `Connection: ${topicId}`;
document.getElementById('dashboard').classList.remove('hidden');
if (activePeer) {
console.log('[INFO] Sending "listContainers" command');
window.sendCommand('listContainers');
} else {
console.error('[ERROR] No active peer to send command.');
}
}
// Attach switchConnection to the global window object
window.switchConnection = switchConnection;
// Send a command to the active peer
function sendCommand(command, args = {}) {
if (activePeer) {
const message = JSON.stringify({ command, args });
console.log(`[DEBUG] Sending command to server: ${message}`);
activePeer.write(message);
} else {
console.error('[ERROR] No active peer to send command.');
}
}
// Attach sendCommand to the global window object
window.sendCommand = sendCommand;
// Render the container list
function renderContainers(containers) {
console.log(`[INFO] Rendering ${containers.length} containers`);
containerList.innerHTML = '';
containers.forEach((container) => {
const name = container.Names[0].replace(/^\//, ''); // Remove leading slash from container names
const row = document.createElement('tr');
row.innerHTML = `
<td>${name}</td>
<td>${container.State}</td>
<td>
<button class="btn btn-success btn-sm" onclick="window.sendCommand('startContainer', { id: '${container.Id}' })">Start</button>
<button class="btn btn-warning btn-sm" onclick="window.sendCommand('stopContainer', { id: '${container.Id}' })">Stop</button>
<button class="btn btn-danger btn-sm" onclick="window.sendCommand('removeContainer', { id: '${container.Id}' })">Remove</button>
<button class="btn btn-info btn-sm" onclick="window.startTerminal('${container.Id}')">Terminal</button>
</td>
`;
containerList.appendChild(row);
});
}
// Initialize Xterm.js terminal
function initializeTerminal() {
if (xterm) {
xterm.dispose(); // Dispose existing terminal instance
}
xterm = new Terminal({ cursorBlink: true, theme: { background: '#000000', foreground: '#ffffff' } });
fitAddon = new FitAddon(); // Create a new FitAddon instance
xterm.loadAddon(fitAddon);
xterm.open(terminalContainer);
setTimeout(() => fitAddon.fit(), 10); // Ensure terminal fits properly after rendering
xterm.write('\x1b[1;32mWelcome to the Docker Terminal\x1b[0m\r\n');
// Adjust terminal size dynamically when the window is resized
window.addEventListener('resize', () => {
fitAddon.fit();
});
}
// Start terminal session
function startTerminal(containerId) {
if (!activePeer) {
console.error('[ERROR] No active peer for terminal.');
return;
}
if (!terminalSessions[containerId]) {
terminalSessions[containerId] = { output: '' }; // Initialize terminal state
}
const session = terminalSessions[containerId];
initializeTerminal();
xterm.write(session.output);
terminalModal.style.display = 'flex';
terminalTitle.textContent = `Container Terminal: ${containerId}`;
console.log(`[INFO] Starting terminal for container: ${containerId}`);
activePeer.write(JSON.stringify({ command: 'startTerminal', args: { containerId } }));
xterm.onData((data) => {
console.log(`[DEBUG] Sending terminal input: ${data}`);
activePeer.write(JSON.stringify({ type: 'terminalInput', data }));
});
document.getElementById('minimize-terminal-btn').onclick = () => {
terminalModal.style.display = 'none';
addToTray(containerId); // Minimize to tray
};
}
// Attach startTerminal to the global window object
window.startTerminal = startTerminal;
// Append terminal output
function appendTerminalOutput(data, containerId) {
if (!terminalSessions[containerId]) {
console.error(`[ERROR] No terminal session found for container: ${containerId}`);
return;
}
console.log(`[DEBUG] Appending terminal output: ${data}`);
const session = terminalSessions[containerId];
session.output += data;
if (terminalTitle.textContent.includes(containerId)) {
xterm.write(data);
}
}
// Add terminal to tray
function addToTray(containerId) {
let trayItem = document.querySelector(`.tray-item[data-id="${containerId}"]`);
if (!trayItem) {
trayItem = document.createElement('div');
trayItem.className = 'tray-item';
trayItem.dataset.id = containerId;
trayItem.textContent = `Terminal: ${containerId}`;
trayItem.onclick = () => {
terminalModal.style.display = 'flex';
xterm.write(terminalSessions[containerId].output);
setTimeout(() => fitAddon.fit(), 10); // Ensure proper resize
};
tray.appendChild(trayItem);
}
}

176
index.html Normal file
View File

@ -0,0 +1,176 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/xterm/css/xterm.css">
<title>Docker P2P Manager</title>
<style>
body {
margin: 0;
display: flex;
height: 100vh;
background-color: #1a1a1a;
color: white;
overflow: hidden;
}
#titlebar {
-webkit-app-region: drag;
height: 30px;
width: 100%;
position: fixed;
top: 0;
background-color: #2c2c2c;
z-index: 1000;
}
pear-ctrl[data-platform="darwin"] {
float: left;
margin-top: 5px;
margin-left: 10px;
}
#sidebar {
position: fixed;
top: 30px;
left: 0;
background-color: #2c2c2c;
height: calc(100vh - 30px);
width: 250px;
overflow-y: auto;
transition: width 0.3s ease-in-out;
}
#sidebar.collapsed {
width: 50px;
}
#sidebar.collapsed .content {
display: none;
}
#collapse-sidebar-btn {
position: absolute;
top: 10px;
right: 10px;
background-color: #444;
border: none;
color: white;
width: 30px;
height: 30px;
border-radius: 50%;
font-size: 16px;
line-height: 30px;
text-align: center;
cursor: pointer;
}
#content {
margin-left: 250px;
flex: 1;
padding: 30px;
overflow-y: auto;
transition: margin-left 0.3s ease-in-out;
}
#sidebar.collapsed ~ #content {
margin-left: 50px;
}
.connection-status {
border-radius: 50%;
width: 10px;
height: 10px;
display: inline-block;
margin-right: 8px;
}
.status-connected {
background-color: green;
}
.status-disconnected {
background-color: red;
}
#terminal-modal {
position: fixed;
bottom: 0;
left: 0;
width: 100%;
max-height: 400px;
height: 300px;
background-color: #1a1a1a;
border-top: 2px solid #444;
display: none;
flex-direction: column;
z-index: 1000;
}
#terminal-modal .header {
background-color: #444;
padding: 10px;
display: flex;
justify-content: space-between;
align-items: center;
}
#terminal-container {
flex: 1;
overflow: hidden; /* Ensure no scrollbars appear */
background-color: black;
color: white;
}
#tray {
position: fixed;
bottom: 0;
left: 0;
width: 100%;
background-color: #444;
padding: 5px 10px;
display: flex;
gap: 10px;
overflow-x: auto;
white-space: nowrap;
z-index: 999;
}
#tray .tray-item {
background-color: #555;
color: white;
padding: 5px 10px;
border-radius: 5px;
cursor: pointer;
}
</style>
</head>
<body>
<div id="titlebar">
<pear-ctrl></pear-ctrl>
</div>
<div id="sidebar">
<button id="collapse-sidebar-btn">&lt;</button>
<div class="content">
<h4 class="text-center mt-3">Connections</h4>
<ul id="connection-list" class="list-group mb-3"></ul>
<form id="add-connection-form" class="px-3">
<input type="text" id="new-connection-topic" class="form-control mb-2" placeholder="Enter server topic" required>
<button type="submit" class="btn btn-primary w-100">Add Connection</button>
</form>
</div>
</div>
<div id="content">
<h1 id="connection-title">Select a Connection</h1>
<div id="dashboard" class="hidden">
<h2>Containers</h2>
<table class="table table-dark table-striped">
<thead>
<tr>
<th>Name</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
<tbody id="container-list"></tbody>
</table>
</div>
</div>
<div id="terminal-modal">
<div class="header">
<span id="terminal-title"></span>
<button id="minimize-terminal-btn" class="btn btn-sm btn-secondary">Minimize</button>
</div>
<div id="terminal-container"></div>
</div>
<div id="tray"></div>
<script src="https://cdn.jsdelivr.net/npm/xterm/lib/xterm.js"></script>
<script type="module" src="app.js"></script>
</body>
</html>

36
package.json Normal file
View File

@ -0,0 +1,36 @@
{
"name": "peartainer",
"main": "index.html",
"pear": {
"name": "peartainer",
"type": "desktop",
"gui": {
"backgroundColor": "#1F2430",
"height": "540",
"width": "720"
},
"links": [
"http://127.0.0.1",
"http://localhost",
"https://ka-f.fontawesome.com",
"https://cdn.jsdelivr.net",
"https://cdnjs.cloudflare.com",
"ws://localhost:8080"
]
},
"type": "module",
"license": "Apache-2.0",
"scripts": {
"dev": "pear run -d .",
"test": "brittle test/*.test.js"
},
"devDependencies": {
"brittle": "^3.0.0",
"pear-interface": "^1.0.0"
},
"dependencies": {
"hyperswarm": "^4.8.4",
"xterm": "^5.3.0",
"xterm-addon-fit": "^0.8.0"
}
}

1
test/index.test.js Normal file
View File

@ -0,0 +1 @@
import test from 'brittle' // https://github.com/holepunchto/brittle