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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
|
/* jshint esversion: 2024, module: true */
import { ApiClient } from './api-client.js';
import { ConfigManager } from './config-manager.js';
import { InterfaceRenderer } from './interface-renderer.js';
import { StructuredEditor } from './structured-editor.js';
import { ThemeManager } from './theme-manager.js';
/**
* Main Application Class
* @class Application
*/
class Application {
/**
* @param {Object} elements - DOM elements
*/
constructor(elements) {
this.elements = elements;
this.state = {
currentInterface: null,
interfaces: [],
editorMode: 'raw', // 'raw' or 'structured'
currentConfigFile: null
};
// Initialize modules
this.themeManager = new ThemeManager(elements);
this.apiClient = new ApiClient();
this.interfaceRenderer = new InterfaceRenderer(elements, this.state);
this.configManager = new ConfigManager(elements, this.apiClient, this.state);
// Structured editor will be initialized after DOM is ready
this.structuredEditor = null;
// Create editor mode toggle UI
this.createEditorModeToggle();
}
/**
* Initialize the application
* @method init
*/
init() {
this.themeManager.init();
this.setupEventListeners();
this.loadStatus();
// Initialize structured editor now that DOM is ready
this.initializeStructuredEditor();
}
/**
* Create editor mode toggle UI
* @method createEditorModeToggle
*/
createEditorModeToggle() {
const editorToggleHTML = `
<div class="editor-mode-toggle" style="margin-bottom: var(--spacing-l);">
<button class="button small ${this.state.editorMode === 'raw' ? 'active' : ''}"
data-mode="raw" id="rawEditorBtn">
📝 Raw Editor
</button>
<button class="button small ${this.state.editorMode === 'structured' ? 'active' : ''}"
data-mode="structured" id="structuredEditorBtn">
🏗️ Structured Editor
</button>
</div>
<div id="rawEditorContainer">
<!-- Existing raw editor will go here -->
</div>
<div id="structuredEditorContainer" style="display: none;">
<!-- Structured editor will be rendered here -->
</div>
`;
// Insert the toggle and containers into the configs panel
const configCard = this.elements.panels.configs.querySelector('.card:last-child');
configCard.insertAdjacentHTML('afterbegin', editorToggleHTML);
// Move existing form elements to raw editor container
const rawEditorContainer = document.getElementById('rawEditorContainer');
const formGroups = Array.from(configCard.querySelectorAll('.form-group, .checkbox-group'));
const configActions = configCard.querySelector('.config-actions') ||
configCard.querySelector('div:has(> #validateConfig)');
formGroups.forEach(group => {
if (!group.closest('.editor-mode-toggle')) {
rawEditorContainer.appendChild(group);
}
});
// Move config actions if they exist
if (configActions) {
rawEditorContainer.appendChild(configActions);
}
// Update elements reference
this.elements.editorContainers = {
raw: document.getElementById('rawEditorContainer'),
structured: document.getElementById('structuredEditorContainer')
};
this.elements.editorButtons = {
raw: document.getElementById('rawEditorBtn'),
structured: document.getElementById('structuredEditorBtn')
};
}
/**
* Initialize structured editor
* @method initializeStructuredEditor
*/
initializeStructuredEditor() {
if (this.elements.editorContainers.structured) {
this.structuredEditor = new StructuredEditor(this.elements.editorContainers.structured);
} else {
console.error('Structured editor container not found');
}
}
/**
* Set up all event listeners
* @method setupEventListeners
*/
setupEventListeners() {
// Navigation
this.elements.buttons.nav.forEach(button => {
button.addEventListener('click', (event) => {
this.show(event.currentTarget.dataset.panel);
});
});
// Status panel
this.elements.buttons.refreshStatus?.addEventListener('click', () => this.loadStatus());
// Configs panel - raw editor
this.elements.buttons.refreshConfigs?.addEventListener('click',
() => this.configManager.refreshConfigs());
this.elements.buttons.saveConfig?.addEventListener('click',
() => this.handleSaveConfig());
this.elements.buttons.validateConfig?.addEventListener('click',
() => this.configManager.validateConfig());
this.elements.inputs.configSelect?.addEventListener('change',
() => this.handleConfigFileChange());
// Editor mode toggle
this.elements.editorButtons?.raw?.addEventListener('click',
() => this.setEditorMode('raw'));
this.elements.editorButtons?.structured?.addEventListener('click',
() => this.setEditorMode('structured'));
// Logs panel
this.elements.buttons.refreshLogs?.addEventListener('click', () => this.loadLogs());
// Commands panel
this.elements.buttons.restartNetworkd?.addEventListener('click', () => this.restartNetworkd());
this.elements.buttons.rebootDevice?.addEventListener('click', () => this.rebootDevice());
// Touch support
document.addEventListener('touchstart', this.handleTouchStart, { passive: true });
}
// Add event handlers for structured editor
handleAddSection(detail) {
console.log('Add section:', detail);
// Implement section addition logic
}
handleRemoveSection(detail) {
console.log('Remove section:', detail);
// Implement section removal logic
}
/**
* Handle configuration file change
* @method handleConfigFileChange
*/
async handleConfigFileChange() {
const name = this.elements.inputs.configSelect.value;
if (!name) return;
this.state.currentConfigFile = name;
if (this.state.editorMode === 'raw') {
await this.configManager.loadConfig();
} else {
await this.loadConfigForStructuredEditor();
}
}
/**
* Load config for structured editor
* @method loadConfigForStructuredEditor
*/
async loadConfigForStructuredEditor() {
if (!this.structuredEditor) {
console.error('Structured editor not initialized');
return;
}
try {
const text = await this.apiClient.getText(`/api/config/${encodeURIComponent(this.state.currentConfigFile)}`);
// Parse configuration and get schema
const { NetworkConfiguration } = await import('./systemd-network.js');
const config = NetworkConfiguration.fromSystemdConfiguration(text);
const schema = config.getSchema();
// Load schema into structured editor
this.structuredEditor.loadSchema(schema, this.state.currentConfigFile);
// Set up event listeners for structured editor
this.structuredEditor.on('addSection', (event) => this.handleAddSection(event.detail));
this.structuredEditor.on('removeSection', (event) => this.handleRemoveSection(event.detail));
} catch (error) {
alert(`Failed to load config for structured editor: ${error.message}`);
}
}
/**
* Set editor mode (raw or structured)
* @method setEditorMode
* @param {string} mode - Editor mode
*/
setEditorMode(mode) {
this.state.editorMode = mode;
// Update UI
if (this.elements.editorButtons?.raw && this.elements.editorButtons?.structured) {
this.elements.editorButtons.raw.classList.toggle('active', mode === 'raw');
this.elements.editorButtons.structured.classList.toggle('active', mode === 'structured');
}
if (this.elements.editorContainers?.raw && this.elements.editorContainers?.structured) {
this.elements.editorContainers.raw.style.display = mode === 'raw' ? 'block' : 'none';
this.elements.editorContainers.structured.style.display = mode === 'structured' ? 'block' : 'none';
}
// If switching to structured mode and we have a config file loaded, load it
if (mode === 'structured' && this.state.currentConfigFile && this.structuredEditor) {
this.loadConfigForStructuredEditor();
}
}
/**
* Handle save configuration based on current editor mode
* @method handleSaveConfig
*/
async handleSaveConfig() {
const name = this.state.currentConfigFile;
if (!name) {
alert('Please select a configuration file first.');
return;
}
const restart = this.elements.inputs.restartAfterSave.checked;
if (!confirm(`Save file ${name}? This will create a backup and ${restart ? 'restart' : 'not restart'} networkd.`)) {
return;
}
try {
let content;
if (this.state.editorMode === 'raw') {
content = this.elements.inputs.cfgEditor.value;
} else if (this.structuredEditor) {
content = this.structuredEditor.getConfigurationText();
} else {
throw new Error('Structured editor not available');
}
const result = await this.apiClient.post('/api/save', { name, content, restart });
alert(`Saved: ${result.status ?? 'ok'}`);
// Refresh the config in structured editor if needed
if (this.state.editorMode === 'structured' && this.structuredEditor) {
await this.structuredEditor.loadConfiguration(content, name);
}
} catch (error) {
alert(`Save failed: ${error.message}`);
}
}
/**
* Show specified panel and hide others
* @method show
* @param {string} panel - Panel to show
*/
show(panel) {
// Hide all panels and remove active class from buttons
Object.values(this.elements.panels).forEach(p => {
if (p) p.classList.remove('active');
});
this.elements.buttons.nav.forEach(btn => {
if (btn) btn.classList.remove('active');
});
// Show selected panel and activate button
const targetPanel = this.elements.panels[panel];
const targetButton = document.querySelector(`[data-panel="${panel}"]`);
if (targetPanel) targetPanel.classList.add('active');
if (targetButton) targetButton.classList.add('active');
// Load panel-specific data
const panelActions = {
status: () => this.loadStatus(),
configs: () => this.configManager.refreshConfigs(),
logs: () => this.loadLogs(),
};
panelActions[panel]?.();
}
/**
* Load and display network status
* @method loadStatus
*/
async loadStatus() {
try {
const data = await this.apiClient.get('/api/status');
this.state.interfaces = data.Interfaces ?? [];
this.interfaceRenderer.renderInterfaceTabs(this.state.interfaces);
// Show first interface by default
if (this.state.interfaces.length > 0 && !this.state.currentInterface) {
this.interfaceRenderer.showInterfaceDetails(this.state.interfaces[0]);
}
} catch (error) {
this.elements.outputs.ifaceDetails.innerHTML =
`<div class="error-message">Error loading status: ${error.message}</div>`;
}
}
/**
* Load system logs
* @method loadLogs
*/
async loadLogs() {
try {
const text = await this.apiClient.getText('/api/logs');
this.elements.outputs.logsArea.textContent = text;
} catch (error) {
this.elements.outputs.logsArea.textContent = `Error: ${error.message}`;
}
}
/**
* Restart networkd service
* @method restartNetworkd
*/
async restartNetworkd() {
if (!confirm('Restart systemd-networkd? Active connections may be reset.')) return;
try {
const result = await this.apiClient.post('/api/reload');
this.elements.outputs.cmdResult.textContent = `Success: ${JSON.stringify(result)}`;
} catch (error) {
this.elements.outputs.cmdResult.textContent = `Error: ${error.message}`;
}
}
/**
* Reboot the device
* @method rebootDevice
*/
async rebootDevice() {
if (!confirm('Reboot device now?')) return;
try {
const result = await this.apiClient.post('/api/reboot');
this.elements.outputs.cmdResult.textContent = `Success: ${JSON.stringify(result)}`;
} catch (error) {
this.elements.outputs.cmdResult.textContent = `Error: ${error.message}`;
}
}
}
// Initialize application when DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
const elements = {
themeToggle: document.getElementById('themeToggle'),
themeIcon: document.getElementById('themeIcon'),
panels: {
status: document.getElementById('panelStatus'),
configs: document.getElementById('panelConfigs'),
logs: document.getElementById('panelLogs'),
commands: document.getElementById('panelCommands'),
},
buttons: {
nav: document.querySelectorAll('.nav-button'),
refreshStatus: document.getElementById('refreshStatus'),
refreshConfigs: document.getElementById('refreshConfigs'),
saveConfig: document.getElementById('saveConfig'),
validateConfig: document.getElementById('validateConfig'),
refreshLogs: document.getElementById('refreshLogs'),
restartNetworkd: document.getElementById('restartNetworkd'),
rebootDevice: document.getElementById('rebootDevice'),
},
inputs: {
configSelect: document.getElementById('configSelect'),
cfgEditor: document.getElementById('cfgEditor'),
restartAfterSave: document.getElementById('restartAfterSave'),
},
outputs: {
ifaceTabs: document.getElementById('interfaceTabs'),
ifaceDetails: document.getElementById('interfaceDetails'),
validateResult: document.getElementById('validateResult'),
logsArea: document.getElementById('logsArea'),
cmdResult: document.getElementById('cmdResult'),
},
};
const app = new Application(elements);
app.init();
// Make app globally available for debugging
window.app = app;
});
export { Application };
|