Electron_generator/main.js

141 lines
4.9 KiB
JavaScript

// main.js - DEFINITIVE VERSION - Dynamic Line-by-Line Generation
const { app, BrowserWindow, ipcMain, dialog } = require('electron');
const path = require('path');
const fs = require('fs');
const createWindow = () => {
const win = new BrowserWindow({
width: 900,
height: 750,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
contextIsolation: true,
nodeIntegration: false
}
});
win.loadFile('index.html');
win.webContents.openDevTools();
};
app.whenReady().then(() => {
ipcMain.handle('form:submit', (event, data) => {
console.log('--- Data received in main.js ---', data);
// --- YAML Generation by Building an Array of Lines ---
// Define spacing constants for indentation
const sp2 = ' ';
const sp4 = ' ';
const sp6 = ' ';
// Create an array to hold each line of the YAML file
const yamlLines = [];
// 1. Build the 'machine' section line by line
yamlLines.push('machine:');
yamlLines.push(`${sp2}profile: ${data.machineType || 'Unspecified'}`);
yamlLines.push(`${sp2}identification:`);
// Build the 'identification' sub-section, using the [VendorName] placeholder literally
const machineType = data.machineType || 'Unspecified';
const machineModel = data.model || '';
const serialNo = data.serialNo || '';
const VendorName = data.vendor || '';
yamlLines.push(`${sp4}namespace: http://${VendorName}/${machineType}/${machineModel}/${serialNo}`);
yamlLines.push(`${sp4}browseName: ${data.browseName || ''}`);
yamlLines.push(`${sp4}manufacturer: "[${VendorName}]"`);
// Append the user-provided vendor as a comment, if it exists
if (data.vendor) {
yamlLines.push(`${sp4}# User-provided Vendor: ${data.vendor}`);
}
yamlLines.push(`${sp4}model: "${machineModel}"`);
yamlLines.push(`${sp4}serialNumber: "${serialNo}"`);
yamlLines.push(`${sp4}yearofconstruction: "${data.buildYear || ''}"`);
// Add the final line for the 'machine' section
yamlLines.push(`${sp2}version: "${data.version || 'Unset'}"`);
// 2. Build and Append the 'optionals' section if needed
if (data.stopReason === 'Yes') {
yamlLines.push(''); // Add a blank line for spacing
yamlLines.push(`${sp2}optionals:`);
yamlLines.push(`${sp4}- StopReason`);
}
// 3. Build and Append the 'addins' section if needed
const selectedAddins = data.addins || []; // Default to an empty array
if (selectedAddins.length > 0) {
yamlLines.push('');
yamlLines.push(`${sp2}addins:`);
if (selectedAddins.includes('AcPower')) {
yamlLines.push(`${sp4}- name: AcPower`);
}
if (selectedAddins.includes('Utilities')) {
yamlLines.push(`${sp4}- name: EnergyUtilitiesAddin`);
yamlLines.push(`${sp6}# Requires data from a future 'Utilities ADDIN' UI.`);
}
if (selectedAddins.includes('TrackAdvance')) {
yamlLines.push(`${sp4}- name: TrackAdvance`);
yamlLines.push(`${sp6}# Requires data from a future 'TrackAdvance ADDIN' UI.`);
}
if (selectedAddins.includes('AGV')) {
yamlLines.push(`${sp4}- name: AGV`);
yamlLines.push(`${sp6}# Requires data from a future 'AGV ADDIN' UI.`);
}
}
// 4. Join all the generated lines into a single string
const generatedContent = yamlLines.join('\n');
// --- End of YAML Generation Logic ---
console.log('--- Generated YAML Content ---\n', generatedContent);
// File saving logic
const nameParts = [
data.machineType,
data.vendor,
data.model,
data.serialNo,
data.browseName
];
// Filter out any empty or null values
const nonEmptyParts = nameParts.filter(Boolean);
// Join the parts with an underscore
const baseName = nonEmptyParts.join('_');
// Sanitize the final string to remove characters invalid for filenames, but keep underscores and hyphens.
const safeBaseName = baseName.replace(/[/\\?%*:|"<>]/g, '-');
const yamlFileName = `${safeBaseName}.yml`;
const documentsPath = app.getPath('documents');
const yamlFilePath = path.join(documentsPath, yamlFileName);
try {
fs.writeFileSync(yamlFilePath, generatedContent, 'utf8');
dialog.showMessageBox({
type: 'info',
title: 'Success',
message: 'YAML File Generated Successfully!',
detail: `The file was saved to:\n${yamlFilePath}`
});
return { success: true, filePath: yamlFilePath };
} catch (error) {
console.error("Failed to write YAML file:", error);
dialog.showErrorBox('File Save Error', `Failed to save the YAML file.\nError: ${error.message}`);
return { success: false, error: error.message };
}
});
createWindow();
app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) createWindow(); });
});
app.on('window-all-closed', () => { if (process.platform !== 'darwin') app.quit(); });