chahuadev-framework-en / modules /button-generator.js
chahuadev
Update README
857cdcf
/**
* Button Generator - Smart Button Creation System
* Chahua Development Thailand
* CEO: Saharath C.
*
* Purpose: สร้างปุ่มแบบอัจฉริยะตามการทำงานของโปรเจค
*/
const fs = require('fs');
const path = require('path');
class ButtonGenerator {
constructor(language = 'en') {
this.buttonRegistry = new Map();
this.language = language; // ภาษาปัจจุบัน: 'en' หรือ 'th'
this.templateLibrary = this.initializeTemplateLibrary();
this.actionHandlers = new Map();
this.translations = this.initializeTranslations();
console.log(` Button Generator initialized (Language: ${language})`);
}
// ระบบแปลหลายภาษา
initializeTranslations() {
return {
'en': {
// Node.js
'npm-install': 'Install',
'npm-start': 'Start',
'npm-test': 'Test',
'npm-build': 'Build',
'npm-lint': 'Lint',
'npm-dev': 'Dev',
'npm-serve': 'Serve',
// Python
'pip-install': 'Install',
'python-run': 'Run Main',
'python-test': 'Test',
'python-format': 'Format',
// Executable
'launch-exe': 'Launch App',
'run-as-admin': 'Run as Admin',
// Batch
'run-batch': 'Run Script',
'edit-batch': 'Edit Script',
// Utility
'open-terminal': 'Terminal',
'file-explorer': 'Open Folder',
'refresh': 'Refresh',
'settings': 'Settings',
// Web
'npm-watch': 'Watch',
'deploy': 'Deploy',
// Categories
'Node.js Basic': 'Node.js Basic',
'Node.js Advanced': 'Node.js Advanced',
'Python Basic': 'Python Basic',
'Python Advanced': 'Python Advanced',
'Application': 'Application',
'Batch Scripts': 'Batch Scripts',
'Utility': 'Utility',
'Web Development': 'Web Development'
},
'th': {
// Node.js
'npm-install': 'ติดตั้ง',
'npm-start': 'เริ่มต้น',
'npm-test': 'ทดสอบ',
'npm-build': 'สร้าง',
'npm-lint': 'ตรวจสอบ',
'npm-dev': 'พัฒนา',
'npm-serve': 'เรียกใช้',
// Python
'pip-install': 'ติดตั้ง',
'python-run': 'รันหลัก',
'python-test': 'ทดสอบ',
'python-format': 'จัดรูป',
// Executable
'launch-exe': 'เปิดแอป',
'run-as-admin': 'รันเป็นผู้ดูแลระบบ',
// Batch
'run-batch': 'รันสคริปต์',
'edit-batch': 'แก้ไขสคริปต์',
// Utility
'open-terminal': 'เทอร์มินัล',
'file-explorer': 'เปิดโฟลเดอร์',
'refresh': 'รีเฟรช',
'settings': 'ตั้งค่า',
// Web
'npm-watch': 'เฝ้าดู',
'deploy': 'ปรับใช้',
// Categories
'Node.js Basic': 'Node.js พื้นฐาน',
'Node.js Advanced': 'Node.js ขั้นสูง',
'Python Basic': 'Python พื้นฐาน',
'Python Advanced': 'Python ขั้นสูง',
'Application': 'แอปพลิเคชัน',
'Batch Scripts': 'สคริปต์ Batch',
'Utility': 'เครื่องมือ',
'Web Development': 'พัฒนา Web'
}
};
}
// ฟังก์ชันแปลข้อความ
translate(key) {
const trans = this.translations[this.language] || this.translations['en'];
return trans[key] || key;
}
// ตั้งภาษา
setLanguage(language) {
if (this.translations[language]) {
this.language = language;
console.log(` Button language changed to: ${language}`);
} else {
console.warn(` Unsupported language: ${language}, using English`);
this.language = 'en';
}
}
// ไลบรารีเทมเพลตปุ่มสำหรับโปรเจคต่างๆ
initializeTemplateLibrary() {
return {
// Node.js Project Templates
'node-basic': {
category: 'Node.js Basic',
buttons: [
{ id: 'npm-install', nameKey: 'npm-install', command: 'npm-install', icon: '' },
{ id: 'npm-start', nameKey: 'npm-start', command: 'npm-start', icon: '' }
]
},
'node-advanced': {
category: 'Node.js Advanced',
buttons: [
{ id: 'npm-test', nameKey: 'npm-test', command: 'npm-test', icon: '' },
{ id: 'npm-build', nameKey: 'npm-build', command: 'npm-build', icon: '' },
{ id: 'npm-lint', nameKey: 'npm-lint', command: 'npm-lint', icon: '' }
]
},
// Python Project Templates
'python-basic': {
category: 'Python Basic',
buttons: [
{ id: 'pip-install', nameKey: 'pip-install', command: 'pip-install', icon: '' },
{ id: 'python-run', nameKey: 'python-run', command: 'python-run', icon: '' }
]
},
// เพิ่ม Template ใหม่สำหรับ EXE
'executable-runner': {
category: 'Application',
buttons: [
{ id: 'launch-exe', nameKey: 'launch-exe', command: 'launch-exe', icon: '' },
{ id: 'run-as-admin', nameKey: 'run-as-admin', command: 'run-as-admin', icon: '' }
]
},
// เพิ่ม Template ใหม่สำหรับ BAT
'batch-runner': {
category: 'Batch Scripts',
buttons: [
{ id: 'run-batch', nameKey: 'run-batch', command: 'run-batch', icon: '' },
{ id: 'edit-batch', nameKey: 'edit-batch', command: 'edit-batch', icon: '' }
]
},
// Utility Templates (ปุ่มพื้นฐาน)
'utility': {
category: 'Utility',
buttons: [
{ id: 'open-terminal', nameKey: 'open-terminal', command: 'open_terminal', icon: '' },
{ id: 'file-explorer', nameKey: 'file-explorer', command: 'open_explorer', icon: '' }
]
}
};
}
// สร้างปุ่มตามข้อมูลโปรเจค
generateProjectButtons(projectInfo, features) {
const { name, type, path: projectPath, previewImage } = projectInfo; // เพิ่ม previewImage
let buttons = [];
console.log(` Generating buttons for project: ${name} (Type: ${type})`);
// เพิ่ม fallback สำหรับ unknown type
let projectType = type;
if (projectType === 'unknown') {
projectType = 'executable_project'; // fallback เป็น executable_project
console.log(` -> [Fallback] Using executable_project type instead of unknown`);
projectInfo.type = projectType; // อัปเดต type ใน object
}
// --- อัปเกรดตรรกะการตัดสินใจเป็นแบบ 3 ทาง ---
if (features.hasBatchRunner) {
// 1. ทางพิเศษสำหรับ .bat
console.log(` -> Using Batch Runner strategy`);
const batchTemplate = this.templateLibrary['batch-runner'];
if (batchTemplate) {
const batchButtons = this.customizeButtons(batchTemplate.buttons, projectInfo, features);
buttons.push(...this.customizeBatchButtons(batchButtons, projectInfo));
}
} else if (projectType === 'executable_project') {
// 2. ทางพิเศษสำหรับ .exe
console.log(` -> Using Executable Runner strategy`);
const exeTemplate = this.templateLibrary['executable-runner'];
if (exeTemplate) {
const exeButtons = this.customizeButtons(exeTemplate.buttons, projectInfo, features);
buttons.push(...this.customizeExecutableButtons(exeButtons, projectInfo));
}
} else {
// 3. ทางปกติสำหรับ npm และอื่นๆ
console.log(` -> Using standard template strategy`);
const templates = this.selectTemplates(projectType, features);
for (const template of templates) {
const templateButtons = this.templateLibrary[template];
if (templateButtons) {
buttons.push(...this.customizeButtons(templateButtons.buttons, projectInfo, features));
}
}
}
// --- จบส่วนตรรกะ ---
// เพิ่มปุ่มพิเศษตามฟีเจอร์ (เฉพาะโปรเจคธรรมดา)
if (!features.hasBatchRunner && projectType !== 'executable_project') {
buttons.push(...this.generateConditionalButtons(features, projectInfo));
}
// เพิ่มปุ่มยูทิลิตี้พื้นฐาน
buttons.push(...this.generateUtilityButtons(projectInfo));
// เพิ่มข้อมูลภาพตัวอย่างในปุ่มทุกปุ่ม
buttons = buttons.map(button => ({
...button,
previewImage: previewImage, // เพิ่มภาพตัวอย่าง
projectPreview: previewImage // เก็บ reference เพิ่มเติม
}));
// ลงทะเบียนปุ่ม
this.buttonRegistry.set(name, {
projectInfo,
buttons,
previewImage, // เก็บ previewImage ใน registry
generated: new Date().toISOString()
});
console.log(` Generated ${buttons.length} buttons for ${name} with preview: ${previewImage || 'none'}`);
return buttons;
}
// เลือกเทมเพลตตามประเภทและฟีเจอร์
selectTemplates(projectType, features) {
const templates = [];
switch (projectType) {
case 'node':
templates.push('node-basic');
if (features.hasLinter || features.hasTests || features.hasTypeScript) {
templates.push('node-advanced');
}
break;
case 'python':
templates.push('python-basic');
if (features.hasFlask || features.hasDjango || features.hasJupyter) {
templates.push('python-web');
}
break;
case 'html':
templates.push('web-basic');
break;
case 'studio':
templates.push('studio');
break;
// เพิ่มการรองรับ executable และ batch projects
case 'executable_project':
templates.push('executable-runner');
break;
case 'batch_project':
templates.push('batch-runner');
break;
default:
templates.push('utility');
break;
}
return templates;
}
// ปรับแต่งปุ่มตามโปรเจค
customizeButtons(templateButtons, projectInfo, features) {
return templateButtons.map(btn => ({
...btn,
name: this.translate(btn.nameKey), // แปลชื่อปุ่ม
projectName: projectInfo.name,
projectPath: projectInfo.path,
projectType: projectInfo.type,
enabled: this.checkButtonCompatibility(btn, features),
tooltip: `${this.translate(btn.nameKey)} for ${projectInfo.name}`,
lastUsed: null
}));
}
// สร้างปุ่มแบบมีเงื่อนไข
generateConditionalButtons(features, projectInfo) {
const conditionalButtons = [];
// Electron specific buttons - ลบปุ่ม Dev ออก
// if (features.hasElectron) {
// conditionalButtons.push({
// id: 'electron-dev',
// name: 'Electron Dev',
// command: 'electron-dev',
// icon: '',
// color: '#9F7AEA',
// category: 'electron',
// projectName: projectInfo.name,
// projectPath: projectInfo.path,
// enabled: true
// });
// }
// TypeScript specific buttons
if (features.hasTypeScript) {
conditionalButtons.push({
id: 'tsc-check',
nameKey: 'npm-build', // ใช้ key ที่เป็น static
name: this.translate(features.hasTypeScript ? 'npm-build' : 'npm-lint'),
// FIX: เปลี่ยน command จาก 'npx tsc --noEmit' เป็น 'tsc-check'
command: 'tsc-check',
icon: '',
color: '#3182CE',
category: 'typescript',
projectName: projectInfo.name,
projectPath: projectInfo.path,
enabled: true
});
}
return conditionalButtons;
}
// สร้างปุ่มยูทิลิตี้
generateUtilityButtons(projectInfo) {
const utilityTemplate = this.templateLibrary['utility'];
return this.customizeButtons(utilityTemplate.buttons, projectInfo, {});
}
// ตรวจสอบความเข้ากันได้ของปุ่ม
checkButtonCompatibility(button, features) {
// ตรวจสอบเงื่อนไขเฉพาะ
if (button.requires) {
return button.requires.every(req => features[req]);
}
// ปุ่มพื้นฐานใช้ได้เสมอ
return true;
}
// ปรับแต่งปุ่มสำหรับ Batch Scripts (เวอร์ชันแก้ไข)
customizeBatchButtons(batchButtons, projectInfo) {
const fs = require('fs');
const path = require('path');
const { path: projectPath, name } = projectInfo;
const customizedButtons = [];
try {
const files = fs.readdirSync(projectPath);
const batchFiles = files.filter(file =>
file.endsWith('.bat') || file.endsWith('.cmd')
);
console.log(` -> Found ${batchFiles.length} batch files: ${batchFiles.join(', ')}`);
// ถ้าไม่เจอไฟล์ batch เลย ก็ไม่ต้องสร้างปุ่ม
if (batchFiles.length === 0) return [];
// ใช้ไฟล์ .bat แรกที่เจอ หรือหาตัวที่ชื่อตรงกับโฟลเดอร์
const targetBatch = batchFiles.find(file =>
file.toLowerCase().includes(name.toLowerCase())
) || batchFiles[0];
for (const button of batchButtons) {
const customButton = { ...button };
// **จุดแก้ไข:** ให้ command เป็น action name ไม่ใช่ชื่อไฟล์
if (button.id === 'run-batch') {
customButton.command = 'run-batch'; // <--- แก้ไขตรงนี้
customButton.name = `Run ${path.parse(targetBatch).name}`;
customButton.tooltip = `Execute ${targetBatch}`;
} else if (button.id === 'edit-batch') {
customButton.command = 'edit-batch'; // <--- แก้ไขตรงนี้
customButton.name = `Edit ${path.parse(targetBatch).name}`;
customButton.tooltip = `Edit ${targetBatch} in Notepad`;
}
if (customButton.command) {
customizedButtons.push(customButton);
}
}
console.log(` -> Customized ${customizedButtons.length} batch buttons`);
return customizedButtons;
} catch (error) {
console.log(` -> Error customizing batch buttons: ${error.message}`);
return [];
}
}
// ปรับแต่งปุ่มสำหรับ Executable Files (เวอร์ชันแก้ไข)
customizeExecutableButtons(exeButtons, projectInfo) {
const fs = require('fs');
const path = require('path');
const { path: projectPath, name } = projectInfo;
const customizedButtons = [];
try {
const files = fs.readdirSync(projectPath);
const exeFiles = files.filter(file => file.endsWith('.exe'));
console.log(` -> Found ${exeFiles.length} executable files: ${exeFiles.join(', ')}`);
// ถ้าไม่เจอไฟล์ .exe เลย ก็ไม่ต้องสร้างปุ่ม
if (exeFiles.length === 0) return [];
// ใช้ไฟล์ .exe แรกที่เจอ หรือหาตัวที่ชื่อตรงกับโฟลเดอร์
const targetExe = exeFiles.find(file =>
file.toLowerCase().includes(name.toLowerCase())
) || exeFiles[0];
for (const button of exeButtons) {
const customButton = { ...button };
// **จุดแก้ไข:** ให้ command เป็น action name ที่ Gateway รู้จัก
if (button.id === 'launch-exe') {
customButton.command = 'launch-exe'; // <--- แก้ไขตรงนี้
customButton.name = `Launch ${path.parse(targetExe).name}`;
customButton.tooltip = `Execute ${targetExe}`;
} else if (button.id === 'run-as-admin') {
customButton.command = 'run-as-admin'; // <--- แก้ไขตรงนี้
customButton.name = `Admin ${path.parse(targetExe).name}`;
customButton.tooltip = `Run ${targetExe} as Administrator`;
}
if (customButton.command) {
customizedButtons.push(customButton);
}
}
console.log(` -> Customized ${customizedButtons.length} executable buttons`);
return customizedButtons;
} catch (error) {
console.log(` -> Error customizing executable buttons: ${error.message}`);
return [];
}
}
// สร้าง HTML สำหรับปุ่ม
generateButtonHTML(button) {
const hotkey = button.hotkey ? `title="${button.tooltip || button.name} (${button.hotkey})"` : `title="${button.tooltip || button.name}"`;
// เพิ่ม preview image ถ้ามี
const previewImageHTML = button.previewImage ?
`<div class="button-preview" style="background-image: url('${button.previewImage}'); background-size: cover; background-position: center; width: 40px; height: 30px; border-radius: 4px; margin-right: 8px;"></div>` : '';
return `
<button
class="project-button"
data-button-id="${button.id}"
data-project="${button.projectName}"
data-command="${button.command}"
style="background-color: ${button.color || '#718096'}; margin: 4px; padding: 8px 12px; border: none; border-radius: 6px; color: white; cursor: pointer; font-size: 14px; display: inline-flex; align-items: center; gap: 6px;"
${hotkey}
${!button.enabled ? 'disabled' : ''}
>
${previewImageHTML}
<span>${button.icon || ''}</span>
<span>${button.name}</span>
</button>
`;
}
// สร้างภาพตัวอย่างแบบ SVG สำหรับปุ่ม
generateButtonPreviewSVG(projectType, projectName) {
const previewConfigs = {
'executable_project': {
color: '#4A5568',
icon: '',
label: 'EXE'
},
'batch_project': {
color: '#38A169',
icon: '',
label: 'BAT'
},
'node': {
color: '#68D391',
icon: '',
label: 'NODE'
},
'python': {
color: '#4FD1C7',
icon: '',
label: 'PY'
},
'html': {
color: '#90CDF4',
icon: '',
label: 'WEB'
},
'default': {
color: '#718096',
icon: '',
label: 'PLUGIN'
}
};
const config = previewConfigs[projectType] || previewConfigs['default'];
const svgContent = `
<svg width="100" height="80" xmlns="http://www.w3.org/2000/svg">
<rect width="100" height="80" fill="${config.color}" rx="4"/>
<text x="50" y="35" font-family="Arial" font-size="20" fill="white" text-anchor="middle">${config.icon}</text>
<text x="50" y="55" font-family="Arial" font-size="10" fill="#E2E8F0" text-anchor="middle">${config.label}</text>
<text x="50" y="70" font-family="Arial" font-size="8" fill="#CBD5E0" text-anchor="middle">${projectName.substring(0, 12)}</text>
</svg>
`;
return `data:image/svg+xml;base64,${Buffer.from(svgContent).toString('base64')}`;
}
// สร้างภาพตัวอย่างสำหรับปุ่มเก่าที่ยังไม่มี
generateMissingPreviews() {
const updated = [];
for (const [projectName, projectData] of this.buttonRegistry.entries()) {
if (!projectData.previewImage) {
const { projectInfo } = projectData;
const previewImage = this.generateButtonPreviewSVG(projectInfo.type, projectInfo.name);
// อัปเดตข้อมูลใน registry
projectData.previewImage = previewImage;
projectData.projectInfo.previewImage = previewImage;
// อัปเดตปุ่มทั้งหมด
projectData.buttons = projectData.buttons.map(button => ({
...button,
previewImage: previewImage,
projectPreview: previewImage
}));
updated.push(projectName);
console.log(` Generated missing preview for: ${projectName}`);
}
}
if (updated.length > 0) {
console.log(` Updated ${updated.length} projects with missing previews`);
}
return updated;
}
// สร้าง HTML การ์ดโปรเจคแบบเต็ม (รวมภาพตัวอย่าง)
generateProjectCardHTML(projectData) {
const { projectInfo, buttons, previewImage } = projectData;
const cardPreviewImage = previewImage || this.generateButtonPreviewSVG(projectInfo.type, projectInfo.name);
const buttonsHTML = buttons.map(button => this.generateButtonHTML(button)).join('');
return `
<div class="project-card" data-project="${projectInfo.name}">
<div class="project-header">
<div class="project-preview">
<img src="${cardPreviewImage}" alt="Preview for ${projectInfo.name}" class="preview-image">
</div>
<div class="project-info">
<h3 class="project-title">${projectInfo.name}</h3>
<p class="project-type">${projectInfo.type}</p>
<p class="project-path">${projectInfo.path}</p>
</div>
</div>
<div class="project-buttons">
${buttonsHTML}
</div>
</div>
`;
}
// ดึงข้อมูลปุ่มทั้งหมด
getAllButtons() {
return Array.from(this.buttonRegistry.values());
}
// ดึงปุ่มสำหรับโปรเจคเฉพาะ
getProjectButtons(projectName) {
const projectData = this.buttonRegistry.get(projectName);
return projectData ? projectData.buttons : [];
}
// รีเซ็ตระบบปุ่ม
reset() {
this.buttonRegistry.clear();
console.log(' Button registry reset');
}
}
module.exports = ButtonGenerator;