summaryrefslogtreecommitdiffstats
path: root/static/app.js
blob: 3fdd32e39b37c9e3557ac6a9962f967bfb05e401 (plain) (blame)
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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
/* jshint esversion: 2024, module: true */

import { ApiClient } from "./api-client.js";
import { ConfigManager } from "./config-manager.js";
import { EditorMode, ValidationState } from "./enums.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 {
	#elements;
	#state;
	#themeManager;
	#structuredEditor;

	/**
	 * @param {Object} elements - DOM elements
	 */
	constructor(elements) {
		this.#elements = elements;
		this.#state = {
			currentInterface: null,
			interfaces: [],
			editorMode: EditorMode.RAW,
			currentConfigFile: null,
		};

		// Initialize modules
		this.#themeManager = new ThemeManager(elements);
		this.#structuredEditor = null;

		// Create editor mode toggle UI
		this.#createEditorModeToggle();
	}

	/**
	 * Initialize the application
	 * @method init
	 */
	init() {
		this.#themeManager.init();
		this.#setupEventListeners();
		this.#loadStatus();
		this.#initializeStructuredEditor();
	}

	/**
	 * Create editor mode toggle UI
	 * @private
	 */
	#createEditorModeToggle() {
		const editorToggleHTML = `
            <div class="editor-mode-toggle" style="margin-bottom: var(--spacing-l);">
                <button class="button small ${this.#state.editorMode === EditorMode.RAW ? "active" : ""}"
                        data-mode="raw" id="rawEditorBtn">
                    📝 Raw Editor
                </button>
                <button class="button small ${this.#state.editorMode === 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
	 * @private
	 */
	#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
	 * @private
	 */
	#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.#handleRefreshConfigs(),
		);
		this.#elements.buttons.saveConfig?.addEventListener("click", () =>
			this.#handleSaveConfig(),
		);
		this.#elements.buttons.validateConfig?.addEventListener("click", () =>
			this.#handleValidateConfig(),
		);
		this.#elements.inputs.configSelect?.addEventListener("change", () =>
			this.#handleConfigFileChange(),
		);

		// Editor mode toggle
		this.#elements.editorButtons?.raw?.addEventListener("click", () =>
			this.#setEditorMode(EditorMode.RAW),
		);
		this.#elements.editorButtons?.structured?.addEventListener("click", () =>
			this.#setEditorMode(EditorMode.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,
		});
	}

	/**
	 * Handle touch events for better mobile support
	 * @private
	 * @param {TouchEvent} event
	 */
	#handleTouchStart = (event) => {
		// Add visual feedback for touch
		if (
			event.target.classList.contains("button") ||
			event.target.classList.contains("nav-button")
		) {
			event.target.style.opacity = "0.7";
			setTimeout(() => {
				event.target.style.opacity = "";
			}, 150);
		}
	};

	/**
	 * Handle refresh configuration files
	 * @private
	 */
	async #handleRefreshConfigs() {
		try {
			const files = await ConfigManager.refreshConfigs();
			this.#updateConfigSelect(files);

			if (files.length > 0) {
				this.#state.currentConfigFile = files[0];
				await this.#handleConfigFileChange();
			} else {
				this.#elements.inputs.cfgEditor.value = "";
				this.#state.currentConfigFile = null;
			}
		} catch (error) {
			alert(error.message);
		}
	}

	/**
	 * Update configuration select element
	 * @private
	 * @param {Array} files - File names
	 */
	#updateConfigSelect(files) {
		this.#elements.inputs.configSelect.innerHTML = "";
		files.forEach((file) => {
			const option = new Option(file, file);
			this.#elements.inputs.configSelect.add(option);
		});
	}

	/**
	 * Handle configuration file change
	 * @private
	 */
	async #handleConfigFileChange() {
		const name = this.#elements.inputs.configSelect.value;
		if (!name) return;

		this.#state.currentConfigFile = name;

		if (this.#state.editorMode === EditorMode.RAW) {
			await this.#loadConfigForRawEditor();
		} else {
			await this.#loadConfigForStructuredEditor();
		}
	}

	/**
	 * Load config for raw editor
	 * @private
	 */
	async #loadConfigForRawEditor() {
		try {
			const content = await ConfigManager.loadConfig(
				this.#state.currentConfigFile,
			);
			this.#elements.inputs.cfgEditor.value = content;
			this.#clearValidationResult();
		} catch (error) {
			alert(error.message);
		}
	}

	/**
	 * Load config for structured editor
	 * @private
	 */
	async #loadConfigForStructuredEditor() {
		if (!this.#structuredEditor) {
			console.error("Structured editor not initialized");
			return;
		}

		try {
			const content = await ConfigManager.loadConfig(
				this.#state.currentConfigFile,
			);

			// Parse configuration and get schema
			const { NetworkConfiguration } = await import("./systemd-network.js");
			const config = NetworkConfiguration.fromSystemdConfiguration(content);
			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}`);
		}
	}

	/**
	 * Handle add section from structured editor
	 * @private
	 * @param {Object} detail - Event detail
	 */
	#handleAddSection(detail) {
		console.log("Add section:", detail);
		// TODO: Implement section addition logic
	}

	/**
	 * Handle remove section from structured editor
	 * @private
	 * @param {Object} detail - Event detail
	 */
	#handleRemoveSection(detail) {
		console.log("Remove section:", detail);
		// TODO: Implement section removal logic
	}

	/**
	 * Handle validate configuration
	 * @private
	 */
	async #handleValidateConfig() {
		const name = this.#state.currentConfigFile;
		if (!name) {
			alert("Please select a configuration file first.");
			return;
		}

		let content;
		if (this.#state.editorMode === EditorMode.RAW) {
			content = this.#elements.inputs.cfgEditor.value;
		} else if (this.#structuredEditor) {
			content = this.#structuredEditor.getConfigurationText();
		} else {
			alert("Structured editor not available");
			return;
		}

		this.#setValidationResult(ValidationState.PENDING);

		try {
			const result = await ConfigManager.validateConfig(name, content);

			if (result.ok) {
				this.#setValidationResult(ValidationState.SUCCESS);
			} else {
				this.#setValidationResult(ValidationState.ERROR, result.output);
			}
		} catch (error) {
			this.#setValidationResult(ValidationState.ERROR, error.message);
		}
	}

	/**
	 * Set validation result
	 * @private
	 * @param {Symbol} state - Validation state
	 * @param {string} [message] - Additional message
	 */
	#setValidationResult(state, message = "") {
		this.#elements.outputs.validateResult.textContent =
			ConfigManager.getValidationMessage(state, message);
		this.#elements.outputs.validateResult.className =
			ConfigManager.getValidationClass(state);
	}

	/**
	 * Clear validation result
	 * @private
	 */
	#clearValidationResult() {
		this.#elements.outputs.validateResult.textContent = "";
		this.#elements.outputs.validateResult.className = "";
	}

	/**
	 * Set editor mode (raw or structured)
	 * @private
	 * @param {Symbol} 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 === EditorMode.RAW,
			);
			this.#elements.editorButtons.structured.classList.toggle(
				"active",
				mode === EditorMode.STRUCTURED,
			);
		}

		if (
			this.#elements.editorContainers?.raw &&
			this.#elements.editorContainers?.structured
		) {
			this.#elements.editorContainers.raw.style.display =
				mode === EditorMode.RAW ? "block" : "none";
			this.#elements.editorContainers.structured.style.display =
				mode === EditorMode.STRUCTURED ? "block" : "none";
		}

		// If switching to structured mode and we have a config file loaded, load it
		if (
			mode === EditorMode.STRUCTURED &&
			this.#state.currentConfigFile &&
			this.#structuredEditor
		) {
			this.#loadConfigForStructuredEditor();
		}
	}

	/**
	 * Handle save configuration based on current editor mode
	 * @private
	 */
	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 === 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 ConfigManager.saveConfig(name, content, restart);
			alert(`Saved: ${result.status ?? "ok"}`);

			// Refresh the config in structured editor if needed
			if (
				this.#state.editorMode === EditorMode.STRUCTURED &&
				this.#structuredEditor
			) {
				await this.#loadConfigForStructuredEditor();
			}
		} catch (error) {
			alert(`Save failed: ${error.message}`);
		}
	}

	/**
	 * Load and display network status
	 * @private
	 */
	async #loadStatus() {
		try {
			const data = await ApiClient.getNetworkStatus();
			this.#state.interfaces = data.Interfaces ?? [];

			// Render interface tabs
			const tabsHTML = InterfaceRenderer.renderInterfaceTabs(
				this.#state.interfaces,
				this.#state.currentInterface,
			);
			this.#elements.outputs.ifaceTabs.innerHTML = tabsHTML;

			// Show first interface by default
			if (this.#state.interfaces.length > 0 && !this.#state.currentInterface) {
				this.#showInterfaceDetails(this.#state.interfaces[0]);
			}

			// Add event listeners to tabs
			this.#elements.outputs.ifaceTabs
				.querySelectorAll(".interface-tab")
				.forEach((tab) => {
					tab.addEventListener("click", (event) => {
						const ifaceName = event.currentTarget.dataset.interface;
						const iface = this.#state.interfaces.find(
							(i) => i.Name === ifaceName,
						);
						if (iface) {
							this.#showInterfaceDetails(iface);
						}
					});
				});
		} catch (error) {
			this.#elements.outputs.ifaceDetails.innerHTML = `<div class="error-message">Error loading status: ${error.message}</div>`;
		}
	}

	/**
	 * Show interface details
	 * @private
	 * @param {Object} iface - Interface object
	 */
	#showInterfaceDetails(iface) {
		this.#state.currentInterface = iface;

		// Update active tab
		this.#elements.outputs.ifaceTabs
			.querySelectorAll(".interface-tab")
			.forEach((tab) => {
				tab.classList.toggle("active", tab.dataset.interface === iface.Name);
			});

		const detailsHTML = InterfaceRenderer.showInterfaceDetails(iface);
		this.#elements.outputs.ifaceDetails.innerHTML = detailsHTML;
	}

	/**
	 * Load system logs
	 * @private
	 */
	async #loadLogs() {
		try {
			const text = await ApiClient.getSystemLogs();
			this.#elements.outputs.logsArea.textContent = text;
		} catch (error) {
			this.#elements.outputs.logsArea.textContent = `Error: ${error.message}`;
		}
	}

	/**
	 * Restart networkd service
	 * @private
	 */
	async #restartNetworkd() {
		if (!confirm("Restart systemd-networkd? Active connections may be reset."))
			return;

		try {
			const result = await ApiClient.restartNetworkd();
			this.#elements.outputs.cmdResult.textContent = `Success: ${JSON.stringify(result)}`;
		} catch (error) {
			this.#elements.outputs.cmdResult.textContent = `Error: ${error.message}`;
		}
	}

	/**
	 * Reboot the device
	 * @private
	 */
	async #rebootDevice() {
		if (!confirm("Reboot device now?")) return;

		try {
			const result = await ApiClient.rebootDevice();
			this.#elements.outputs.cmdResult.textContent = `Success: ${JSON.stringify(result)}`;
		} catch (error) {
			this.#elements.outputs.cmdResult.textContent = `Error: ${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.#handleRefreshConfigs(),
			logs: () => this.#loadLogs(),
		};

		panelActions[panel]?.();
	}

	/**
	 * Get current application state (for debugging)
	 * @method getState
	 * @returns {Object} Application state
	 */
	getState() {
		return { ...this.#state };
	}

	/**
	 * Get theme manager instance
	 * @method getThemeManager
	 * @returns {ThemeManager} Theme manager instance
	 */
	getThemeManager() {
		return this.#themeManager;
	}
}

// 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 };