chahuadev
Update README
857cdcf
/**
* CHAHUADEV FRAMEWORK - ระบบจัดการปลั๊กอินอัจฉริยะ
* =========================================================
*
* ภาพรวมระบบ:
* - ระบบจัดการปลั๊กอิน HTML, Node.js, Python, Java
* - ตัวอย่างการใช้งาง และการ build แบบอัตโนมัติ
* - การตรวจสอบ Error และ Debug แบบขั้นสูง
* - UI ที่ทันสมัยและใช้งานง่าย
*
* การเชื่อมโยง API หลัก:
* - window.electronAPI (preload.js) -> Main Process (main.js)
* - validation_gateway.js -> Security & Command Validation
*
* ฟังก์ชันหลัก:
* 1. addTerminalLine() -> แสดงข้อความใน Log Viewer
* 2. scanAndRenderPlugins() -> สแกนและแสดงปลั๊กอิน
* 3. Build Functions -> การ Build และ Deploy ปลั๊กอิน
* 4. Animation & Effects -> เอฟเฟกต์ UI ต่างๆ
* 5. Plugin Management -> จัดการปลั๊กอินและโปรเจกต์
*/
// --- เพิ่มส่วนนี้เข้าไป ---
// รายการคำสั่งของระบบที่อนุญาตให้รันได้ (ปลอดภัยและมีประโยชน์)
const safeExternalCommands = new Set([
'ping', // สำหรับทดสอบการเชื่อมต่อเครือข่าย
'tracert', // สำหรับติดตามเส้นทางเครือข่าย
'ipconfig', // (สำหรับ Windows) สำหรับดูข้อมูล IP Address
'ifconfig', // (สำหรับ Mac/Linux) สำหรับดูข้อมูล IP Address
'getmac', // สำหรับดู MAC Address ของเครื่อง
'node', // อนุญาตให้รัน node เช่น node -v
'npm' // อนุญาตให้รัน npm เช่น npm -v
]);
// --- จบส่วนที่เพิ่ม ---
const logViewer = document.getElementById('log-viewer');
const pluginContainer = document.getElementById('plugin-container');
// --- CORE FUNCTIONS ---
// [เวอร์ชันใหม่] ฟังก์ชันสำหรับเขียน Log ที่เข้ากับ debugger.html
/**
* ฟังก์ชันแสดงข้อความใน Log Viewer หลัก
*
* @function addTerminalLine
* @description แสดงข้อความใน Log Viewer พร้อม timestamp และสีที่เหมาะสม
* @param {string} text - ข้อความที่ต้องการแสดง
* @param {string} [type='info'] - ประเภทของข้อความ (info, success, error, warning, command)
*
* @example
* addTerminalLine('ระบบเริ่มทำงานแล้ว', 'success');
* addTerminalLine('เกิดข้อผิดพลาด', 'error');
*
* @dependencies
* - logViewer (DOM element) -> #log-viewer
*
* @calledBy
* - scanAndRenderPlugins() -> แสดงผลการสแกนปลั๊กอิน
* - runGeneratorAndRefresh() -> แสดงผลการ build
* - openDebugWindow() -> แสดงสถานะการเปิด debug
* - DOMContentLoaded event -> แสดงข้อความเริ่มต้น
*
* @sideEffects
* - เพิ่ม DOM element ใหม่ใน #log-viewer
* - เลื่อน scroll ไปบรรทัดล่าสุดอัตโนมัติ
*/
const addTerminalLine = (text, type = 'info') => {
if (!logViewer) return;
const timestamp = new Date();
const time = timestamp.toLocaleTimeString('th-TH', { hour12: false });
// สร้าง Element ใหม่สำหรับแต่ละบรรทัด Log
const logLine = document.createElement('span');
logLine.className = `log-line log-${type}`;
// สร้างข้อความ Log พร้อม timestamp
logLine.textContent = `[${time}] ${text}\n`;
// เพิ่มบรรทัดใหม่ลงใน Log Viewer
logViewer.appendChild(logLine);
// เลื่อนหน้าจอไปที่บรรทัดล่าสุดเสมอ
logViewer.scrollTop = logViewer.scrollHeight;
};
// เพิ่มฟังก์ชันนี้สำหรับปุ่ม "เปิดหน้าต่าง Debug"
/**
* ฟังก์ชันเปิดหน้าต่าง Debug Window
*
* @function openDebugWindow
* @async
* @description เปิดหน้าต่างใหม่สำหรับ Debug และตรวจสอบ Error
*
* @returns {Promise<void>}
*
* @dependencies
* - window.electronAPI.openDebugWindow() -> API จาก preload.js
*
* @calledBy
* - onclick ของปุ่ม Debug ใน HTML
* - คีย์ลัด Ctrl+D (Developer mode เท่านั้น)
*
* @calls
* - addTerminalLine() -> แสดงสถานะการเปิด debug
*
* @throws {Error} เมื่อไม่สามารถเปิดหน้าต่าง debug ได้
*/
async function openDebugWindow() {
addTerminalLine(' กำลังเปิดหน้าต่าง Debug...', 'command');
try {
// เรียก API ที่เราจะสร้างในขั้นตอนต่อไป
await window.electronAPI.openDebugWindow();
addTerminalLine(' เปิดหน้าต่าง Debug สำเร็จ', 'success');
} catch (error) {
addTerminalLine(` ไม่สามารถเปิดหน้าต่าง Debug ได้: ${error.message}`, 'error');
}
}
// Keyboard support (Escape key + Resize)
document.addEventListener('keydown', (event) => {
if (event.key === 'Escape') {
// Stop resize if active
if (window.resizeController && window.resizeController.isResizing) {
window.resizeController.stopResize();
}
}
});
/**
* ฟังก์ชันคัดลอก Machine ID
*
* @function copyMachineID
* @async
* @param {string} machineID - รหัสเครื่อง
* @description คัดลอก Machine ID ไปยัง Clipboard
*
* @returns {Promise<void>}
*
* @dependencies
* - navigator.clipboard API -> Clipboard access
*
* @calledBy
* - UI elements -> ปุ่ม copy machine ID
*
* @calls addTerminalLine() -> แสดงผลการคัดลอก
*
* @sideEffects
* - คัดลอกข้อมูลไป clipboard
* - แสดงข้อความยืนยัน
*/
async function copyMachineID(machineID) {
try {
await navigator.clipboard.writeText(machineID);
addTerminalLine(` คัดลอกรหัสเครื่องแล้ว: ${machineID}`, 'success');
} catch (error) {
addTerminalLine(` ไม่สามารถคัดลอกได้: ${error.message}`, 'error');
}
}
/**
* ฟังก์ชันสแกนและแสดงรายการปลั๊กอิน
*
* @function scanAndRenderPlugins
* @async
* @description สแกนหาปลั๊กอินในระบบและแสดงผลใน UI
*
* @returns {Promise<void>}
*
* @dependencies
* - window.electronAPI.executeCommand() -> API จาก preload.js
* - pluginContainer (DOM) -> #plugin-container
*
* @calledBy
* - DOMContentLoaded event -> โหลดเริ่มต้น
* - runGeneratorAndRefresh() -> หลังจาก build เสร็จ
* - ปุ่ม Refresh ต่างๆ
*
* @calls
* - addTerminalLine() -> แสดงสถานะการสแกน
* - createPluginButtons() -> สร้างปุ่มสำหรับแต่ละปลั๊กอิน
*
* @throws {Error} เมื่อไม่สามารถสแกนปลั๊กอินได้
*
* @sideEffects
* - เปลี่ยน innerHTML ของ #plugin-container
* - แสดงข้อความใน Log Viewer
*/
async function scanAndRenderPlugins() {
addTerminalLine(' กำลังสแกนปลั๊กอิน...', 'command');
// แสดง loading animation
showLoadingAnimation(pluginContainer, 'กำลังสแกนปลั๊กอิน');
// เรียกใช้ API ที่ถูกต้องและมีอยู่จริงใน main.js
// preload.js ได้เตรียม window.electronAPI.plugins.getAll() ไว้ให้แล้ว
const result = await window.electronAPI.plugins.getAll();
console.log('--- Data from Main Process (get-available-plugins) ---', result);
if (result.success && result.plugins) {
pluginContainer.innerHTML = '<div class="plugin-grid"></div>';
const grid = pluginContainer.querySelector('.plugin-grid');
const plugins = result.plugins;
if (plugins.length === 0) {
grid.innerHTML = `<div class="loading">ไม่พบปลั๊กอินหรือโปรเจกต์ที่ทำงานได้</div>`;
addTerminalLine(' ไม่พบโปรเจกต์ที่สามารถสร้างปุ่มการทำงานได้', 'info');
} else {
// เพิ่ม plugins ทีละตัวพร้อม animation delay
plugins.forEach((pluginData, index) => {
setTimeout(() => {
const card = document.createElement('div');
card.className = 'plugin-card';
card.style.animationDelay = `${index * 0.1}s`;
card.innerHTML = `
${pluginData.previewImage ? `<img src="${pluginData.previewImage}" class="plugin-preview-image" alt="Preview for ${pluginData.name}">` : ''}
<h3>${getIconForType(pluginData)} ${pluginData.name}</h3>
<p>${pluginData.description || `ประเภท: ${pluginData.type}`}</p>
${pluginData.debugInfo ? `
<div class="debug-info">
<div class="debug-stats">
<span class="stat-files"> ${pluginData.debugInfo.totalFiles || 0} files</span>
<span class="stat-issues ${pluginData.debugInfo.errors > 0 ? 'has-errors' : ''}">
${pluginData.debugInfo.errors || 0} errors, ${pluginData.debugInfo.warnings || 0} warnings
</span>
</div>
</div>
` : ''}
<div class="plugin-buttons">
${createPluginButtons(pluginData)}
</div>
`;
grid.appendChild(card);
}, index * 100);
});
// แสดงผลลัพธ์หลังจาก animations เสร็จ
setTimeout(() => {
addTerminalLine(` สแกนเสร็จสิ้น พบ ${plugins.length} โปรเจกต์ที่พร้อมใช้งาน`, 'success');
showNotification(` พบ ${plugins.length} ปลั๊กอินที่พร้อมใช้งาน!`, 'success');
}, (plugins.length * 100) + 200);
}
} else {
pluginContainer.innerHTML = `<div class="loading">เกิดข้อผิดพลาดในการโหลดปลั๊กอิน</div>`;
addTerminalLine(` ข้อผิดพลาดในการสแกนปลั๊กอิน: ${result.error || 'ไม่ได้รับข้อมูลจาก Main Process'}`, 'error');
showNotification(' เกิดข้อผิดพลาดในการสแกนปลั๊กอิน', 'error');
}
}
// Enhanced Plugin Scan with Debug Info
/**
* ฟังก์ชันสแกนปลั๊กอินพร้อมข้อมูล Debug
*
* @function scanAndRenderPluginsWithDebug
* @async
* @description สแกนปลั๊กอินและแสดงข้อมูล Debug เพิ่มเติม
*
* @returns {Promise<void>}
*
* @dependencies
* - window.electronAPI.executeCommand() -> API การสแกนแบบ Debug
*
* @calledBy
* - Developer mode functions
* - Debug buttons
*
* @calls
* - addTerminalLine() -> แสดงข้อมูล Debug
* - createPluginButtons() -> สร้าง UI ปลั๊กอิน
*
* @sideEffects
* - แสดงข้อมูล Debug ใน Log Viewer
* - อัพเดต Plugin Container
*/
async function scanAndRenderPluginsWithDebug() {
addTerminalLine(' กำลังสแกนปลั๊กอินพร้อมข้อมูล Debug...', 'command');
// แสดง loading animation
showLoadingAnimation(pluginContainer, 'กำลังวิเคราะห์ปลั๊กอิน');
try {
// ใช้ IPC handler ที่เราสร้างใหม่ - แก้ไขใช้ API ที่ถูกต้อง
const result = await window.electronAPI.projectInspector.scanWithDebug();
console.log('--- Enhanced Scan Result ---', result);
if (result.success && result.plugins) {
pluginContainer.innerHTML = '<div class="plugin-grid"></div>';
const grid = pluginContainer.querySelector('.plugin-grid');
const plugins = result.plugins;
if (plugins.length === 0) {
grid.innerHTML = `<div class="loading">ไม่พบปลั๊กอินหรือโปรเจกต์ที่ทำงานได้</div>`;
addTerminalLine(' ไม่พบโปรเจกต์ที่สามารถสร้างปุ่มการทำงานได้', 'info');
} else {
let totalErrors = 0;
let totalWarnings = 0;
// เพิ่ม plugins ทีละตัวพร้อม animation delay
plugins.forEach((pluginData, index) => {
setTimeout(() => {
const card = document.createElement('div');
card.className = 'plugin-card';
card.style.animationDelay = `${index * 0.1}s`;
card.innerHTML = `
${pluginData.previewImage ? `<img src="${pluginData.previewImage}" class="plugin-preview-image" alt="Preview for ${pluginData.name}">` : ''}
<h3>${getIconForType(pluginData)} ${pluginData.name}</h3>
<p>${pluginData.description || `ประเภท: ${pluginData.type}`}</p>
${pluginData.debugInfo ? `
<div class="debug-info">
<div class="debug-stats">
<span class="stat-files"> ${pluginData.debugInfo.totalFiles || 0} files</span>
<span class="stat-issues ${pluginData.debugInfo.errors > 0 ? 'has-errors' : ''}">
${pluginData.debugInfo.errors || 0} errors, ${pluginData.debugInfo.warnings || 0} warnings
</span>
</div>
</div>
` : ''}
<div class="plugin-buttons">
${createPluginButtons(pluginData)}
</div>
`;
grid.appendChild(card);
// รวมสถิติ
if (pluginData.debugInfo) {
totalErrors += pluginData.debugInfo.errors || 0;
totalWarnings += pluginData.debugInfo.warnings || 0;
}
}, index * 100);
});
// แสดงผลลัพธ์หลังจาก animations เสร็จ
setTimeout(() => {
addTerminalLine(` Enhanced scan เสร็จสิ้น: ${plugins.length} projects`, 'success');
addTerminalLine(` พบปัญหา: ${totalErrors} errors, ${totalWarnings} warnings`,
totalErrors > 0 ? 'error' : 'info');
showNotification(` สแกน ${plugins.length} ปลั๊กอิน พร้อมข้อมูล Debug!`, 'success');
}, (plugins.length * 100) + 200);
}
} else {
pluginContainer.innerHTML = `<div class="loading">เกิดข้อผิดพลาดในการสแกน Debug</div>`;
addTerminalLine(` ข้อผิดพลาดในการสแกน Debug: ${result.error || 'ไม่ได้รับข้อมูลจาก Main Process'}`, 'error');
showNotification(' เกิดข้อผิดพลาดในการสแกน Debug', 'error');
}
} catch (error) {
console.error('Enhanced scan error:', error);
pluginContainer.innerHTML = `<div class="loading">เกิดข้อผิดพลาดในการสแกน Debug</div>`;
addTerminalLine(` Enhanced scan failed: ${error.message}`, 'error');
showNotification(' เกิดข้อผิดพลาดในการสแกน Debug', 'error');
}
}
// ฟังก์ชันใหม่สำหรับรัน Generator และ Refresh
/**
* ฟังก์ชันรัน Generator และ Refresh ปลั๊กอิน
*
* @function runGeneratorAndRefresh
* @async
* @description รัน Plugin Generator เพื่อสร้างไฟล์ manifest และ refresh รายการปลั๊กอิน
*
* @returns {Promise<void>}
*
* @dependencies
* - window.electronAPI.executeCommand() -> API รัน generator
*
* @calledBy
* - ปุ่ม "สแกน & สร้าง" ใน UI
* - คีย์ลัด Ctrl+R (Developer mode)
*
* @calls
* - addTerminalLine() -> แสดงสถานะการทำงาน
* - scanAndRenderPlugins() -> อัพเดตรายการปลั๊กอิน
*
* @throws {Error} เมื่อ Generator ทำงานไม่สำเร็จ
*
* @sideEffects
* - สร้างไฟล์ manifest.json สำหรับปลั๊กอิน
* - อัพเดต UI รายการปลั๊กอิน
* - แสดงข้อความสถานะใน Log
*/
async function runGeneratorAndRefresh() {
addTerminalLine(' กำลังสั่งให้ระบบสแกนหาปลั๊กอินใหม่และสร้าง Manifest...', 'command');
// แสดง loading ใน plugin container
showLoadingAnimation(pluginContainer, 'กำลังสร้าง Manifest');
try {
const result = await window.electronAPI.runManifestGenerator();
if (result.success) {
addTerminalLine(' สร้าง Manifest สำเร็จ! กำลังโหลดรายการปลั๊กอินใหม่...', 'success');
showNotification(' สร้าง Manifest สำเร็จ!', 'success');
// โหลดรายการปลั๊กอินใหม่หลังจากสร้างเสร็จ
setTimeout(async () => {
await scanAndRenderPlugins();
}, 500);
} else {
addTerminalLine(` เกิดข้อผิดพลาดในการสร้าง Manifest: ${result.error}`, 'error');
showNotification(' เกิดข้อผิดพลาดในการสร้าง Manifest', 'error');
pluginContainer.innerHTML = `<div class="loading">เกิดข้อผิดพลาดในการสร้าง Manifest</div>`;
}
} catch (error) {
addTerminalLine(` ข้อผิดพลาด IPC ร้ายแรง: ${error.message}`, 'error');
showNotification(' ข้อผิดพลาด IPC ร้ายแรง', 'error');
pluginContainer.innerHTML = `<div class="loading">เกิดข้อผิดพลาดร้ายแรง</div>`;
}
}
// ฟังก์ชันสำหรับรัน Manifest Generator เท่านั้น
/**
* ฟังก์ชันสร้างเฉพาะไฟล์ Manifest
*
* @function runGenerateManifestOnly
* @async
* @description รัน Generator เพื่อสร้างเฉพาะไฟล์ manifest.json
*
* @returns {Promise<void>}
*
* @dependencies
* - window.electronAPI.executeCommand() -> API รัน manifest generator
*
* @calledBy
* - ปุ่ม "สร้าง Manifest" ใน UI
*
* @calls addTerminalLine() -> แสดงสถานะ
*
* @sideEffects
* - สร้างไฟล์ manifest.json
* - แสดงข้อความใน Log
*/
async function runGenerateManifestOnly() {
addTerminalLine(' กำลังรันตัวสร้าง Manifest Files...', 'command');
try {
const result = await window.electronAPI.runManifestGenerator();
if (result.success) {
addTerminalLine(' สร้าง Manifest Files สำเร็จ!', 'success');
addTerminalLine(` ผลลัพธ์:`, 'info');
addTerminalLine(result.output, 'stdout');
} else {
addTerminalLine(` เกิดข้อผิดพลาดในการสร้าง Manifest: ${result.error}`, 'error');
}
} catch (error) {
addTerminalLine(` ข้อผิดพลาด IPC ร้ายแรง: ${error.message}`, 'error');
}
}
// ฟังก์ชันเปิดโฟลเดอร์ปลั๊กอิน (NEW)
/**
* ฟังก์ชันเปิดโฟลเดอร์ Plugins
*
* @function openPluginsFolder
* @async
* @description เปิด File Explorer ไปยังโฟลเดอร์ plugins
*
* @returns {Promise<void>}
*
* @dependencies
* - window.electronAPI.executeCommand() -> API เปิดโฟลเดอร์
*
* @calledBy ปุ่ม "เปิดโฟลเดอร์" ใน UI
* @calls addTerminalLine() -> แสดงสถานะ
*
* @sideEffects
* - เปิด File Explorer/Finder
* - แสดงข้อความใน Log
*/
async function openPluginsFolder() {
addTerminalLine(' กำลังเปิดโฟลเดอร์ปลั๊กอิน...', 'command');
try {
const result = await window.electronAPI.openPluginsFolder();
if (result.success) {
addTerminalLine(' เปิดโฟลเดอร์ปลั๊กอินใน File Explorer แล้ว', 'success');
addTerminalLine(` ตำแหน่ง: ${result.path}`, 'info');
addTerminalLine(' คุณสามารถวางไฟล์ปลั๊กอินของคุณในโฟลเดอร์นี้แล้วกดปุ่ม " สแกนหาปลั๊กอินใหม่"', 'info');
showNotification(' เปิดโฟลเดอร์ปลั๊กอินแล้ว!', 'success');
} else {
addTerminalLine(` ไม่สามารถเปิดโฟลเดอร์ปลั๊กอินได้: ${result.error}`, 'error');
showNotification(' ไม่สามารถเปิดโฟลเดอร์ปลั๊กอินได้', 'error');
}
} catch (error) {
addTerminalLine(` ข้อผิดพลาด IPC: ${error.message}`, 'error');
showNotification(' ข้อผิดพลาด IPC', 'error');
}
}
// ฟังก์ชัน Build App (MSI/EXE) - NEW
/**
* ฟังก์ชันเริ่มกระบวนการ Build
*
* @function startBuildProcess
* @async
* @description เริ่มกระบวนการ build ปลั๊กอินพร้อม UI animation
*
* @returns {Promise<void>}
*
* @dependencies
* - window.electronAPI.executeCommand() -> API build process
*
* @calledBy
* - ปุ่ม Build ของแต่ละปลั๊กอิน
* - createPluginButtons() -> สร้างปุ่ม build
*
* @calls
* - addTerminalLine() -> แสดงสถานะ build
* - onBuildComplete() -> เมื่อ build เสร็จสิ้น
*
* @sideEffects
* - แสดง build animation
* - สร้างไฟล์ output
* - อัพเดต UI
*/
async function startBuildProcess() {
addTerminalLine(' กำลังเริ่มต้นกระบวนการ Build แอปพลิเคชัน...', 'command');
addTerminalLine(' คำสั่ง: npx electron-builder --win --x64', 'command');
addTerminalLine(' กรุณารอสักครู่ กระบวนการนี้อาจใช้เวลาหลายนาที...', 'info');
addTerminalLine(' การ Build จะสร้างไฟล์ MSI และ EXE สำหรับติดตั้งบน Windows', 'info');
// แสดงการแจ้งเตือนและอนิเมชั่น
showNotification(' เริ่มต้น Build Process...', 'info');
// แสดง loading animation แบบพิเศษสำหรับ build process
const buildStatusDiv = document.createElement('div');
buildStatusDiv.id = 'build-status';
buildStatusDiv.style.cssText = `
background: linear-gradient(135deg, #fd7e14, #e76500);
color: white;
padding: 15px;
margin: 10px 0;
border-radius: 8px;
border-left: 4px solid #fff;
animation: pulse 2s infinite;
`;
buildStatusDiv.innerHTML = `
<div style="display: flex; align-items: center; justify-content: center;">
<div style="
width: 20px;
height: 20px;
border: 3px solid rgba(255,255,255,0.3);
border-top: 3px solid white;
border-radius: 50%;
animation: spin 1s linear infinite;
margin-right: 10px;
"></div>
<span> กำลัง Build แอปพลิเคชัน...</span>
</div>
`;
// เพิ่ม build status
const licenseStatus = document.getElementById('license-status');
licenseStatus.parentNode.insertBefore(buildStatusDiv, licenseStatus.nextSibling);
try {
const result = await window.electronAPI.startBuild();
if (!result.success) {
addTerminalLine(` ไม่สามารถเริ่ม Build ได้: ${result.error}`, 'error');
showNotification(' ไม่สามารถเริ่ม Build ได้', 'error');
// ลบ build status
buildStatusDiv.remove();
} else {
addTerminalLine(' เริ่มกระบวนการ Build สำเร็จ!', 'success');
// เปลี่ยน build status เป็น running
buildStatusDiv.innerHTML = `
<div style="display: flex; align-items: center; justify-content: center;">
<div style="
width: 20px;
height: 20px;
border: 3px solid rgba(255,255,255,0.3);
border-top: 3px solid white;
border-radius: 50%;
animation: spin 1s linear infinite;
margin-right: 10px;
"></div>
<span> กำลังดำเนินการ Build... (ตรวจสอบ Log ด้านล่าง)</span>
</div>
`;
}
} catch (error) {
addTerminalLine(` เกิดข้อผิดพลาดร้ายแรง: ${error.message}`, 'error');
showNotification(' เกิดข้อผิดพลาดร้ายแรง', 'error');
// ลบ build status
buildStatusDiv.remove();
}
}
// ฟังก์ชันจัดการเมื่อ Build เสร็จสิ้น
/**
* ฟังก์ชันที่ทำงานเมื่อ Build เสร็จสิ้น
*
* @function onBuildComplete
* @param {boolean} success - สถานะความสำเร็จของการ build
* @description จัดการ UI และแสดงผลหลังจาก build เสร็จสิ้น
*
* @calledBy startBuildProcess() -> หลังจาก build เสร็จ
* @calls addTerminalLine() -> แสดงผลลัพธ์
*
* @sideEffects
* - ลบ build animation
* - แสดงข้อความผลลัพธ์
* - อัพเดต UI elements
*/
function onBuildComplete(success) {
const buildStatusDiv = document.getElementById('build-status');
if (buildStatusDiv) {
if (success) {
buildStatusDiv.style.background = 'linear-gradient(135deg, #28a745, #1e7e34)';
buildStatusDiv.innerHTML = `
<div style="display: flex; align-items: center; justify-content: center;">
<span style="font-size: 1.2em; margin-right: 10px;"></span>
<span> Build เสร็จสมบูรณ์! ตรวจสอบไฟล์ในโฟลเดอร์ dist/</span>
</div>
`;
showNotification(' Build สำเร็จ! ไฟล์ MSI/EXE พร้อมใช้งาน', 'success');
} else {
buildStatusDiv.style.background = 'linear-gradient(135deg, #dc3545, #c82333)';
buildStatusDiv.innerHTML = `
<div style="display: flex; align-items: center; justify-content: center;">
<span style="font-size: 1.2em; margin-right: 10px;"></span>
<span> Build ล้มเหลว! ตรวจสอบ Log เพื่อดูรายละเอียด</span>
</div>
`;
showNotification(' Build ล้มเหลว!', 'error');
}
// ลบ build status หลังจาก 10 วินาที
setTimeout(() => {
buildStatusDiv.remove();
}, 10000);
}
}
// ฟังก์ชัน createPluginButtons เวอร์ชันใหม่ที่ง่ายกว่าเดิม
/**
* ฟังก์ชันสร้างปุ่มสำหรับปลั๊กอิน
*
* @function createPluginButtons
* @param {Object} pluginData - ข้อมูลปลั๊กอิน
* @param {string} pluginData.name - ชื่อปลั๊กอิน
* @param {string} pluginData.type - ประเภทปลั๊กอิน (html, node, python, java)
* @param {string} pluginData.path - path ของปลั๊กอิน
* @param {Object} pluginData.manifest - ข้อมูล manifest
*
* @description สร้าง HTML buttons สำหรับจัดการปลั๊กอินแต่ละตัว
*
* @returns {string} HTML string ของปุ่มทั้งหมด
*
* @dependencies
* - startBuildProcess() -> สำหรับปุ่ม Build
* - window.electronAPI -> APIs ต่างๆ
*
* @calledBy
* - scanAndRenderPlugins() -> สร้างปุ่มสำหรับปลั๊กอินแต่ละตัว
* - scanAndRenderPluginsWithDebug() -> ใน debug mode
*
* @sideEffects
* - สร้าง HTML elements ใหม่
* - เชื่อมโยง onclick events
*/
function createPluginButtons(pluginData) {
let buttonsHTML = '';
if (pluginData.buttons && pluginData.buttons.length > 0) {
pluginData.buttons.forEach(buttonInfo => {
// ไม่ต้องเปลี่ยน command เพราะเราแก้ไข button-generator.js แล้ว
buttonsHTML += `
<button
onclick="runPluginAction('${pluginData.name}', '${buttonInfo.command}', '${pluginData.path.replace(/\\/g, '\\\\')}')"
title="${buttonInfo.tooltip || buttonInfo.name}"
>
${buttonInfo.icon || ''} ${buttonInfo.name}
</button>
`;
});
}
buttonsHTML += `<button onclick="runPluginAction('${pluginData.name}', 'info', '${pluginData.path.replace(/\\/g, '\\\\')}')" title="แสดงข้อมูล">ℹ ข้อมูล</button>`;
return buttonsHTML || '<span>ไม่มีคำสั่งที่ใช้ได้</span>';
}
// อัปเดตฟังก์ชัน getIconForType เล็กน้อย
function getIconForType(pluginData) {
// ใช้ icon จาก manifest เป็นหลัก ถ้าไม่มีก็ใช้แบบเดิม
if (pluginData.icon) {
return pluginData.icon;
}
// Fallback icons ตาม type
const icons = {
'node': '',
'python': '',
'java': '',
'api': '',
'html': '',
'project': '',
'batch_project': '',
'executable_project': '',
'electron_app': '',
'utility_tool': '',
'chahuadev_studio': '',
'html_plugin': '',
'javascript_plugin': ''
};
return icons[pluginData.type] || '';
}
// --- EVENT HANDLERS ---
// ฟังก์ชันสำหรับรันคำสั่งปลั๊กอิน - ส่ง action ไปให้ validation_gateway.js
/**
* ฟังก์ชันรันคำสั่งเฉพาะของปลั๊กอิน
*
* @function runPluginAction
* @async
* @param {string} pluginName - ชื่อปลั๊กอิน
* @param {string} action - คำสั่งที่ต้องการรัน (run, build, test, install)
* @param {string} projectPath - path ของโปรเจกต์ปลั๊กอิน
* @description รันคำสั่งเฉพาะสำหรับปลั๊กอินแต่ละประเภท
*
* @returns {Promise<void>}
*
* @dependencies
* - window.electronAPI.executePluginCommand() -> API รันคำสั่งปลั๊กอิน
*
* @calledBy
* - createPluginButtons() -> ปุ่มต่างๆ ของปลั๊กอิน
* - onclick events ในปุ่ม Run, Build, Test
*
* @calls addTerminalLine() -> แสดงผลการทำงาน
*
* @throws {Error} เมื่อรันคำสั่งไม่สำเร็จ
*
* @sideEffects
* - รันคำสั่งใน plugin directory
* - แสดงผลใน Log Viewer
*/
async function runPluginAction(pluginName, action, projectPath) {
addTerminalLine(` กำลังรัน Action: "${action}" บนปลั๊กอิน "${pluginName}"...`, 'command');
try {
// เรียกใช้ Gateway โดยตรงผ่านสะพานใหม่ที่เราสร้าง
const result = await window.electronAPI.processCommand({
action: action, // ส่ง action name ที่ถูกต้องไปให้ validation_gateway.js
pluginName: pluginName,
projectPath: projectPath
});
if (result.success) {
addTerminalLine(` Action สำเร็จ!`, 'success');
const output = result.data?.output || result.data?.message || result.message;
if (output) {
addTerminalLine(output, 'stdout');
}
} else {
addTerminalLine(` Action ล้มเหลว: ${result.error}`, 'error');
}
} catch (err) {
addTerminalLine(` ข้อผิดพลาดร้ายแรง (IPC): ${err.message}`, 'error');
}
}
// ทำให้ onclick เรียกใช้ได้
window.runPluginAction = runPluginAction;
// ฟังก์ชันใหม่สำหรับรันคำสั่งภายนอกผ่าน Main Process
/**
* ฟังก์ชันรันคำสั่งภายนอก (External Commands)
*
* @function runExternalCommand
* @async
* @param {string} command - คำสั่งที่ต้องการรัน
* @description รันคำสั่งภายนอกผ่าน Terminal API พร้อมการตรวจสอบความปลอดภัย
*
* @returns {Promise<Object>} ผลลัพธ์การรันคำสั่ง
*
* @dependencies
* - window.electronAPI.terminal.executeCommand() -> Terminal API
* - safeExternalCommands Set -> รายการคำสั่งที่ปลอดภัย
*
* @calledBy
* - Plugin action buttons
* - Developer tools
*
* @calls addTerminalLine() -> แสดงผลการทำงาน
*
* @security
* - ตรวจสอบคำสั่งที่อนุญาต (whitelist)
* - ป้องกันการรัน malicious commands
*
* @throws {Error} เมื่อคำสั่งไม่ปลอดภัยหรือรันไม่สำเร็จ
*/
async function runExternalCommand(command) {
try {
// เรียกใช้ API ที่เราสร้างไว้ใน preload.js
// main.js จะรับคำสั่งนี้ไปรันใน shell ของเครื่อง
const result = await window.electronAPI.executeQuickCommand(command);
if (result.success) {
// ถ้าสำเร็จ ให้นำผลลัพธ์ (output) มาแสดง
addTerminalLine(result.data.output, 'stdout');
} else {
// ถ้าล้มเหลว ให้แสดงข้อผิดพลาด
addTerminalLine(result.error, 'error');
}
} catch (err) {
// กรณีที่การเชื่อมต่อกับ Main Process มีปัญหา
addTerminalLine(` IPC Error: ${err.message}`, 'error');
}
}
// ฟังก์ชันใหม่สำหรับรันคำสั่งผ่าน ValidationGateway
/**
* ฟังก์ชันรันคำสั่งผ่าน Gateway System
*
* @function runGatewayCommand
* @async
* @param {string} action - คำสั่งที่ต้องการรัน
* @param {string} [loadingMessage='กำลังดำเนินการ...'] - ข้อความแสดงขณะรัน
* @description รันคำสั่งผ่าน validation_gateway.js เพื่อความปลอดภัย
*
* @returns {Promise<Object>} ผลลัพธ์จาก gateway
*
* @dependencies
* - window.electronAPI.processCommand() -> Gateway API
* - validation_gateway.js -> ระบบตรวจสอบคำสั่ง
*
* @calledBy
* - checkLicenseCommand() -> ตรวจสอบ license
* - Plugin management functions
*
* @calls addTerminalLine() -> แสดงสถานะการทำงาน
*
* @security
* - ผ่าน validation_gateway.js
* - ตรวจสอบสิทธิ์การเข้าถึง
*
* @sideEffects
* - แสดงข้อความ loading
* - รันคำสั่งใน system
*/
async function runGatewayCommand(action, loadingMessage = 'กำลังดำเนินการ...') {
try {
addTerminalLine(loadingMessage, 'command');
const result = await window.electronAPI.processCommand({
action: action,
projectPath: process.cwd ? process.cwd() : '.'
});
if (result.success) {
addTerminalLine(' คำสั่งสำเร็จ!', 'success');
if (result.data && result.data.output) {
addTerminalLine(result.data.output, 'stdout');
} else if (result.data && result.data.message) {
addTerminalLine(result.data.message, 'info');
}
} else {
addTerminalLine(` คำสั่งล้มเหลว: ${result.error}`, 'error');
}
} catch (error) {
addTerminalLine(` ข้อผิดพลาด: ${error.message}`, 'error');
}
}
// ลบฟังก์ชันการรันคำสั่ง เพราะเปลี่ยนเป็น log viewer แล้ว
// ฟังก์ชันเอฟเฟกต์พิเศษและอนิเมชั่น
/**
* ฟังก์ชันเพิ่มเอฟเฟกต์ความสำเร็จให้ Element
*
* @function addSuccessEffect
* @param {HTMLElement} element - Element ที่ต้องการเพิ่มเอฟเฟกต์
* @description เพิ่ม CSS animation class สำหรับแสดงเอฟเฟกต์ความสำเร็จ
*
* @dependencies
* - CSS class 'success-animation' -> ต้องมี keyframe animation ใน CSS
*
* @calledBy
* - UI success callbacks -> เมื่อการดำเนินการสำเร็จ
* - Plugin action completions -> หลังจากปลั๊กอินทำงานสำเร็จ
*
* @sideEffects
* - เพิ่ม/ลบ CSS class จาก element
* - แสดง animation เป็นเวลา 600ms
*
* @example
* const button = document.getElementById('my-button');
* addSuccessEffect(button); // แสดงเอฟเฟกต์ความสำเร็จ 600ms
*/
function addSuccessEffect(element) {
element.classList.add('success-animation');
setTimeout(() => {
element.classList.remove('success-animation');
}, 600);
}
/**
* ฟังก์ชันเพิ่มเอฟเฟกต์ Ripple เมื่อคลิก
*
* @function addClickEffect
* @param {Event} event - Mouse click event object
* @description สร้างเอฟเฟกต์ ripple animation เมื่อคลิกปุ่ม
*
* @dependencies
* - CSS keyframe 'ripple' -> สร้างอัตโนมัติถ้าไม่มี
* - DOM manipulation -> สร้าง span element สำหรับ ripple
*
* @calledBy
* - initializeButtonEffects() -> document click listener
* - Button click events -> ทุกปุ่มในแอป
*
* @calls
* - createElement() -> สร้าง ripple element
* - getBoundingClientRect() -> คำนวณตำแหน่ง
*
* @sideEffects
* - เพิ่ม CSS style ใน document head (ครั้งแรกเท่านั้น)
* - สร้างและลบ DOM elements ชั่วคราว
* - เปลี่ยน style ของปุ่มเป็น relative position
*
* @example
* // จะถูกเรียกอัตโนมัติเมื่อคลิกปุ่มใดๆ
* button.addEventListener('click', addClickEffect);
*/
function addClickEffect(event) {
const button = event.target;
// สร้าง ripple effect
const ripple = document.createElement('span');
const rect = button.getBoundingClientRect();
const size = Math.max(rect.width, rect.height);
const x = event.clientX - rect.left - size / 2;
const y = event.clientY - rect.top - size / 2;
ripple.style.cssText = `
position: absolute;
width: ${size}px;
height: ${size}px;
left: ${x}px;
top: ${y}px;
background: rgba(255, 255, 255, 0.6);
border-radius: 50%;
transform: scale(0);
animation: ripple 0.6s linear;
pointer-events: none;
`;
// เพิ่ม keyframe สำหรับ ripple animation
if (!document.querySelector('#ripple-style')) {
const style = document.createElement('style');
style.id = 'ripple-style';
style.textContent = `
@keyframes ripple {
to {
transform: scale(4);
opacity: 0;
}
}
`;
document.head.appendChild(style);
}
button.style.position = 'relative';
button.style.overflow = 'hidden';
button.appendChild(ripple);
setTimeout(() => {
ripple.remove();
}, 600);
}
/**
* ฟังก์ชันเพิ่มเอฟเฟกต์การพิมพ์ทีละตัวอักษร
*
* @function addTypingEffect
* @param {HTMLElement} element - Element ที่จะแสดงข้อความ
* @param {string} text - ข้อความที่ต้องการแสดงแบบพิมพ์
* @param {number} [speed=50] - ความเร็วในการพิมพ์ (milliseconds ต่อตัวอักษร)
* @description สร้างเอฟเฟกต์การพิมพ์ข้อความทีละตัวอักษรแบบ typewriter
*
* @dependencies
* - CSS class 'typing-effect' -> สำหรับ styling ขณะพิมพ์
*
* @calledBy
* - Welcome messages -> ข้อความต้อนรับ
* - Status updates -> อัพเดตสถานะที่สำคัญ
*
* @calls
* - setTimeout() -> ควบคุมความเร็วการพิมพ์
* - charAt() -> ดึงตัวอักษรทีละตัว
*
* @sideEffects
* - เปลี่ยน textContent ของ element
* - เพิ่ม/ลบ CSS class 'typing-effect'
* - ใช้ recursive setTimeout
*
* @example
* const messageEl = document.getElementById('message');
* addTypingEffect(messageEl, 'สวัสดี!', 100); // พิมพ์ช้าๆ
*/
function addTypingEffect(element, text, speed = 50) {
element.textContent = '';
element.classList.add('typing-effect');
let i = 0;
const typeWriter = () => {
if (i < text.length) {
element.textContent += text.charAt(i);
i++;
setTimeout(typeWriter, speed);
} else {
element.classList.remove('typing-effect');
}
};
typeWriter();
}
// เพิ่ม event listener สำหรับปุ่มทั้งหมด
/**
* ฟังก์ชันเริ่มต้นระบบเอฟเฟกต์ปุ่ม
*
* @function initializeButtonEffects
* @description ตั้งค่า global event listener สำหรับเอฟเฟกต์ปุ่มทั้งหมด
*
* @dependencies
* - addClickEffect() -> เอฟเฟกต์ ripple
*
* @calledBy
* - DOMContentLoaded event -> เริ่มต้นระบบ
*
* @calls
* - addEventListener() -> ตั้งค่า global click listener
* - addClickEffect() -> เมื่อคลิกปุ่ม
*
* @sideEffects
* - เพิ่ม global click event listener
* - ทุกปุ่มจะมีเอฟเฟกต์ ripple อัตโนมัติ
*
* @example
* // เรียกครั้งเดียวตอน init
* initializeButtonEffects();
*/
function initializeButtonEffects() {
document.addEventListener('click', (event) => {
if (event.target.tagName === 'BUTTON') {
addClickEffect(event);
}
});
}
// ฟังก์ชันสำหรับเพิ่มอนิเมชั่นแบบ Stagger (เรียงลำดับ)
/**
* ฟังก์ชันเพิ่มอนิเมชั่นแบบ Stagger สำหรับ Plugin Cards
*
* @function animatePluginCards
* @description เพิ่มอนิเมชั่น fadeIn ให้ plugin cards โดยมีช่วงเวลาต่างกัน
*
* @dependencies
* - CSS class 'fadeIn' -> ต้องมี keyframe animation ใน CSS
* - DOM selector '.plugin-card' -> plugin card elements
*
* @calledBy
* - scanAndRenderPlugins() -> หลังจากแสดงปลั๊กอินเสร็จ
* - createPluginButtons() -> เมื่อสร้าง plugin UI
*
* @calls
* - querySelectorAll() -> หา plugin cards ทั้งหมด
* - forEach() -> วนลูปเพิ่ม animation
*
* @sideEffects
* - เปลี่ยน animationDelay ของแต่ละ card
* - เพิ่ม CSS class 'fadeIn'
*
* @algorithm
* 1. หา plugin cards ทั้งหมด
* 2. เพิ่ม delay แต่ละ card (index * 0.1s)
* 3. เพิ่ม fadeIn class สำหรับ animation
*/
function animatePluginCards() {
const cards = document.querySelectorAll('.plugin-card');
cards.forEach((card, index) => {
card.style.animationDelay = `${index * 0.1}s`;
card.classList.add('fadeIn');
});
}
// ฟังก์ชันสำหรับ Loading Animation - with safety check
/**
* ฟังก์ชันแสดง Loading Animation
*
* @function showLoadingAnimation
* @param {HTMLElement} element - Element ที่จะแสดง loading animation
* @param {string} [text='กำลังโหลด'] - ข้อความที่แสดงใต้ spinner
* @description แสดง loading spinner พร้อมข้อความในใน element ที่กำหนด
*
* @dependencies
* - CSS keyframe 'spin' -> สร้างอัตโนมัติถ้าไม่มี
*
* @calledBy
* - scanAndRenderPlugins() -> ขณะสแกนปลั๊กอิน
* - runGeneratorAndRefresh() -> ขณะสร้าง manifest
* - Plugin loading operations -> การโหลดปลั๊กอิน
*
* @calls
* - console.warn() -> เตือนเมื่อ element เป็น null
* - createElement() -> สร้าง style element สำหรับ keyframe
*
* @sideEffects
* - เปลี่ยน innerHTML ของ element
* - เพิ่ม CSS keyframe 'spin' ใน document head
*
* @safety
* - ตรวจสอบ element null/undefined ก่อนใช้งาน
* - ป้องกัน error จาก null reference
*
* @example
* showLoadingAnimation(pluginContainer, 'กำลังสแกนปลั๊กอิน');
*/
function showLoadingAnimation(element, text = 'กำลังโหลด') {
// Add safety check to prevent null element error
if (!element) {
console.warn(' showLoadingAnimation: Element is null or undefined');
return;
}
element.innerHTML = `
<div class="loading-container" style="text-align: center; padding: 20px;">
<div class="loading-spinner" style="
width: 40px;
height: 40px;
border: 4px solid #e9ecef;
border-top: 4px solid #667eea;
border-radius: 50%;
animation: spin 1s linear infinite;
margin: 0 auto 10px;
"></div>
<div class="loading-text">${text}</div>
</div>
`;
// เพิ่ม keyframe สำหรับ spinner
if (!document.querySelector('#spinner-style')) {
const style = document.createElement('style');
style.id = 'spinner-style';
style.textContent = `
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
`;
document.head.appendChild(style);
}
}
// ฟังก์ชันทดแทนเพื่อป้องกันข้อผิดพลาด - ไม่แสดง notification
/**
* ฟังก์ชันแสดง Notification (ปิดใช้งาน)
*
* @function showNotification
* @param {string} message - ข้อความที่ต้องการแสดง
* @param {string} [type='info'] - ประเภทของ notification (info, success, error, warning)
* @description ฟังก์ชันทดแทนสำหรับระบบ notification (ปิดใช้งานเพื่อไม่รบกวนระบบ)
*
* @deprecated ปิดใช้งานเพื่อไม่ให้บังระบบการทำงานหลัก
*
* @calledBy
* - สถานที่ที่เคยใช้ notification system
* - ฟังก์ชันต่างๆ ที่ต้องการแจ้งเตือน
*
* @calls console.log() -> แสดงข้อความใน console แทน
*
* @sideEffects
* - ไม่มี UI notification
* - แสดงเฉพาะใน console log
*
* @note
* - หากต้องการเปิดใช้งานอีกครั้ง ให้ uncomment โค้ดการแสดง notification
* - ออกแบบเพื่อป้องกัน error จากการเรียกฟังก์ชันที่ไม่มี
*/
function showNotification(message, type = 'info') {
// ปิดการใช้งาน notification เพื่อไม่ให้บังระบบการทำงาน
// หากต้องการเปิดใช้งานอีกครั้ง ให้ uncomment บรรทัดด้านบน
console.log(` [Notification Disabled] ${message} (${type})`);
}
// --- INITIALIZATION ---
// =============================================================
// PRODUCTION SECURITY SYSTEM (Same as debugger.html)
// =============================================================
// Development Mode Detection
/**
* ฟังก์ชันตรวจสอบโหมด Development
*
* @function isDevMode
* @returns {boolean} true ถ้าอยู่ในโหมด development, false ถ้าเป็น production
* @description ตรวจสอบจากหลายแหล่งว่าแอปกำลังทำงานในโหมด development หรือไม่
*
* @dependencies
* - URLSearchParams -> ตรวจสอบ ?dev=true
* - localStorage -> ตรวจสอบ 'chahua_dev_mode'
* - window.location -> ตรวจสอบ hostname
*
* @calledBy
* - initProductionSecurity() -> เช็คโหมดก่อนปิด security
* - DOMContentLoaded event -> ตั้งค่าเริ่มต้น
* - devLog(), devError(), devWarn() -> ควบคุมการแสดง log
*
* @algorithm
* 1. เช็ค URL parameter ?dev=true
* 2. เช็ค localStorage chahua_dev_mode = 'true'
* 3. เช็ค hostname เป็น localhost/127.0.0.1
* 4. return true ถ้าเงื่อนไขใดเงื่อนไขหนึ่งเป็น true
*
* @security
* - ป้องกันการเปิด dev mode ใน production โดยไม่ตั้งใจ
* - ใช้หลายเงื่อนไขเพื่อความแม่นยำ
*/
function isDevMode() {
// Check multiple indicators for dev mode
const urlParams = new URLSearchParams(window.location.search);
const devParam = urlParams.get('dev') === 'true';
const devStorage = localStorage.getItem('chahua_dev_mode') === 'true';
const isLocalhost = window.location.hostname === 'localhost' ||
window.location.hostname === '127.0.0.1' ||
window.location.hostname === '';
return devParam || devStorage || isLocalhost;
}
// Production Security Implementation
/**
* ฟังก์ชันเริ่มต้นระบบรักษาความปลอดภัยแบบ Production
*
* @function initProductionSecurity
* @returns {boolean} true ถ้าเป็น dev mode, false ถ้าเป็น production mode
* @description เริ่มต้นระบบรักษาความปลอดภัยเมื่อไม่ใช่ development mode
*
* @dependencies
* - isDevMode() -> ตรวจสอบโหมดการทำงาน
* - showDeveloperToolsWarning() -> แสดงคำเตือนเมื่อเปิด dev tools
*
* @calledBy
* - DOMContentLoaded event -> เริ่มต้นระบบความปลอดภัย
*
* @calls
* - isDevMode() -> ตรวจสอบโหมด
* - addEventListener() -> บล็อค shortcuts และ context menu
* - setInterval() -> ตรวจสอบ developer tools
*
* @sideEffects
* - ปิด console methods ใน production mode
* - บล็อค keyboard shortcuts (F12, Ctrl+Shift+I, etc.)
* - ปิด right-click context menu
* - ปิดการเลือกข้อความและ drag
* - ตรวจสอบ developer tools แบบ real-time
*
* @security Features:
* 1. Console Methods Disabling -> ป้องกันการ debug ใน console
* 2. Keyboard Shortcuts Blocking -> บล็อค F12, Ctrl+Shift+I/J/C, Ctrl+U/S
* 3. Context Menu Disabling -> ปิด right-click menu
* 4. Text Selection Blocking -> ป้องกันการคัดลอกโค้ด
* 5. Developer Tools Detection -> เตือนเมื่อเปิด dev tools
*
* @example
* // เรียกตอน app initialization
* const isDev = initProductionSecurity();
*/
function initProductionSecurity() {
const isDev = isDevMode();
console.log(' Security Mode:', isDev ? 'DEVELOPMENT' : 'PRODUCTION');
if (!isDev) {
// 1. Disable Console Methods
const consoleMethods = ['log', 'debug', 'info', 'warn', 'error', 'assert', 'dir', 'dirxml',
'group', 'groupEnd', 'time', 'timeEnd', 'count', 'trace', 'profile', 'profileEnd'];
consoleMethods.forEach(method => {
console[method] = function() {
// Silent in production
};
});
// 2. Block Developer Shortcuts
document.addEventListener('keydown', function(e) {
// Block F12
if (e.key === 'F12') {
e.preventDefault();
e.stopPropagation();
return false;
}
// Block Ctrl+Shift+I (Developer Tools)
if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key === 'I') {
e.preventDefault();
e.stopPropagation();
return false;
}
// Block Ctrl+Shift+J (Console)
if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key === 'J') {
e.preventDefault();
e.stopPropagation();
return false;
}
// Block Ctrl+Shift+C (Element Inspector)
if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key === 'C') {
e.preventDefault();
e.stopPropagation();
return false;
}
// Block Ctrl+U (View Source)
if ((e.ctrlKey || e.metaKey) && e.key === 'u') {
e.preventDefault();
e.stopPropagation();
return false;
}
// Block Ctrl+S (Save)
if ((e.ctrlKey || e.metaKey) && e.key === 's') {
e.preventDefault();
e.stopPropagation();
return false;
}
}, true);
// 3. Disable Right-Click Context Menu
document.addEventListener('contextmenu', function(e) {
e.preventDefault();
e.stopPropagation();
return false;
}, true);
// 4. Disable Text Selection and Drag
document.addEventListener('selectstart', function(e) {
e.preventDefault();
return false;
}, true);
document.addEventListener('dragstart', function(e) {
e.preventDefault();
return false;
}, true);
// 5. Developer Tools Detection
let devtools = {
open: false,
orientation: null
};
const threshold = 160;
setInterval(() => {
if (window.outerHeight - window.innerHeight > threshold ||
window.outerWidth - window.innerWidth > threshold) {
if (!devtools.open) {
devtools.open = true;
showDeveloperToolsWarning();
}
} else {
devtools.open = false;
hideDeveloperToolsWarning();
}
}, 500);
// Additional detection methods
let startTime = new Date();
debugger;
let endTime = new Date();
if (endTime - startTime > 100) {
showDeveloperToolsWarning();
}
}
return isDev;
}
// Developer Tools Warning System
/**
* ฟังก์ชันแสดงคำเตือนเมื่อเปิด Developer Tools
*
* @function showDeveloperToolsWarning
* @description แสดง overlay เตือนผู้ใช้เมื่อตรวจพบการเปิด Developer Tools ใน Production Mode
*
* @dependencies
* - DOM manipulation -> สร้าง warning overlay
*
* @calledBy
* - initProductionSecurity() -> เมื่อตรวจพบ dev tools
* - Developer tools detection algorithms
*
* @calls
* - getElementById() -> ตรวจสอบว่าแสดงอยู่แล้วหรือไม่
* - createElement() -> สร้าง warning element
*
* @sideEffects
* - สร้าง fullscreen overlay
* - บล็อค interaction กับแอป
* - แสดงข้อความเตือนความปลอดภัย
*
* @security
* - ป้องกันการใช้ dev tools ใน production
* - แจ้งให้ผู้ใช้ปิด dev tools
* - แนะนำ ?dev=true สำหรับนักพัฒนา
*
* @ui Components:
* - Full-screen red overlay
* - Warning icon และข้อความ
* - คำแนะนำสำหรับนักพัฒนา
* - Backdrop blur effect
*/
function showDeveloperToolsWarning() {
if (document.getElementById('dev-tools-warning')) return;
const warningOverlay = document.createElement('div');
warningOverlay.id = 'dev-tools-warning';
warningOverlay.style.cssText = `
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(220, 53, 69, 0.95);
color: white;
z-index: 999999;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
font-family: 'Segoe UI', sans-serif;
font-size: 24px;
text-align: center;
backdrop-filter: blur(10px);
`;
warningOverlay.innerHTML = `
<div style="max-width: 600px; padding: 40px; background: rgba(0,0,0,0.8); border-radius: 20px; border: 3px solid #dc3545;">
<h1 style="color: #ff6b6b; margin-bottom: 20px; font-size: 2.5em;"> การเข้าถึงถูกปฏิเสธ</h1>
<p style="font-size: 1.2em; margin-bottom: 20px; line-height: 1.6;">
ระบบตรวจพบการเปิด Developer Tools<br/>
แอปพลิเคชันนี้ได้รับการป้องกันเพื่อความปลอดภัย
</p>
<div style="background: rgba(255,255,255,0.1); padding: 20px; border-radius: 10px; margin: 20px 0;">
<p style="font-size: 1em; margin: 0;">
Production Mode Active<br/>
Security Features Enabled<br/>
For End Users Only
</p>
</div>
<p style="font-size: 0.9em; color: #ffcccb;">
กรุณาปิด Developer Tools เพื่อใช้งานต่อ<br/>
หากคุณเป็นนักพัฒนา ให้เพิ่ม ?dev=true ใน URL
</p>
</div>
`;
document.body.appendChild(warningOverlay);
}
/**
* ฟังก์ชันซ่อนคำเตือน Developer Tools
*
* @function hideDeveloperToolsWarning
* @description ลบ warning overlay เมื่อผู้ใช้ปิด Developer Tools
*
* @calledBy
* - initProductionSecurity() -> เมื่อ dev tools ถูกปิด
* - Developer tools detection -> เมื่อไม่พบ dev tools
*
* @calls
* - getElementById() -> หา warning element
* - remove() -> ลบ element
*
* @sideEffects
* - ลบ warning overlay
* - ปล่อยให้ผู้ใช้ใช้งานแอปได้ต่อ
*
* @safety
* - ตรวจสอบว่า element มีอยู่ก่อนลบ
* - ป้องกัน error จาก null reference
*/
function hideDeveloperToolsWarning() {
const warning = document.getElementById('dev-tools-warning');
if (warning) {
warning.remove();
}
}
// Enhanced Console Logging (Only in Dev Mode)
/**
* ฟังก์ชัน Console Log สำหรับ Developer Mode เท่านั้น
*
* @function devLog
* @param {...any} args - arguments ที่จะส่งไป console.log
* @description แสดง console.log เฉพาะใน development mode
*
* @dependencies
* - isDevMode() -> ตรวจสอบโหมดก่อนแสดง log
*
* @calledBy
* - ทุกที่ที่ต้องการ debug log แต่ไม่ต้องการแสดงใน production
*
* @calls
* - isDevMode() -> เช็คโหมด
* - console.log() -> แสดงข้อความ (dev mode เท่านั้น)
*
* @sideEffects
* - แสดงข้อความใน browser console (dev mode เท่านั้น)
*
* @security
* - ไม่แสดงข้อมูล sensitive ใน production
*
* @example
* devLog('Debug information:', data); // แสดงเฉพาะใน dev mode
*/
function devLog(...args) {
if (isDevMode()) {
console.log(...args);
}
}
/**
* ฟังก์ชัน Console Error สำหรับ Developer Mode เท่านั้น
*
* @function devError
* @param {...any} args - arguments ที่จะส่งไป console.error
* @description แสดง console.error เฉพาะใน development mode
*
* @dependencies
* - isDevMode() -> ตรวจสอบโหมดก่อนแสดง error
*
* @calledBy
* - Error handling ในโหมดพัฒนา
* - Debug error messages
*
* @calls
* - isDevMode() -> เช็คโหมด
* - console.error() -> แสดงข้อผิดพลาด (dev mode เท่านั้น)
*
* @sideEffects
* - แสดงข้อผิดพลาดใน browser console (dev mode เท่านั้น)
*
* @security
* - ไม่เปิดเผยข้อมูล error ใน production
*
* @example
* devError('API Error:', error.message); // แสดงเฉพาะใน dev mode
*/
function devError(...args) {
if (isDevMode()) {
console.error(...args);
}
}
/**
* ฟังก์ชัน Console Warning สำหรับ Developer Mode เท่านั้น
*
* @function devWarn
* @param {...any} args - arguments ที่จะส่งไป console.warn
* @description แสดง console.warn เฉพาะใน development mode
*
* @dependencies
* - isDevMode() -> ตรวจสอบโหมดก่อนแสดง warning
*
* @calledBy
* - Warning messages ในโหมดพัฒนา
* - Deprecation warnings
*
* @calls
* - isDevMode() -> เช็คโหมด
* - console.warn() -> แสดงคำเตือน (dev mode เท่านั้น)
*
* @sideEffects
* - แสดงคำเตือนใน browser console (dev mode เท่านั้น)
*
* @security
* - ไม่เปิดเผยข้อมูล warning ใน production
*
* @example
* devWarn('Deprecated function used:', functionName); // แสดงเฉพาะใน dev mode
*/
function devWarn(...args) {
if (isDevMode()) {
console.warn(...args);
}
}
// =============================================================
// END SECURITY SYSTEM
// =============================================================
document.addEventListener('DOMContentLoaded', async () => {
// Initialize Security System First
const isDev = initProductionSecurity();
// ประกาศตัวแปร isDev ใน scope ที่เข้าถึงได้
window.isDev = isDev;
addTerminalLine('กำลังเริ่มต้นระบบ...', 'info');
if (isDev) {
addTerminalLine(' Developer Mode: Security features disabled for development', 'warning');
document.body.classList.add('dev-mode');
} else {
addTerminalLine(' Production Mode: Security features active', 'success');
document.body.classList.remove('dev-mode');
}
if (window.electronAPI) {
addTerminalLine('สคริปต์โหลดเสร็จสิ้น เชื่อมต่อกับระบบหลักแล้ว', 'success');
// ตรวจสอบโหมดการทำงาน (นักพัฒนา vs ลูกค้า)
try {
const runMode = await window.electronAPI.getRunMode();
if (runMode.isDevMode) {
console.log('ทำงานในโหมดนักพัฒนา - แสดงฟีเจอร์สำหรับนักพัฒนา');
addTerminalLine('โหมดนักพัฒนา: เปิดใช้งานฟีเจอร์สำหรับนักพัฒนา', 'success');
window.isDev = true; // ตั้งค่า isDev เป็น true
document.body.classList.add('dev-mode');
showNotification('โหมดนักพัฒนา: เครื่องมือพิเศษพร้อมใช้งาน', 'info');
} else {
console.log('ทำงานในโหมดลูกค้า - ซ่อนฟีเจอร์สำหรับนักพัฒนา');
addTerminalLine('โหมดลูกค้า: เฉพาะฟีเจอร์สำหรับผู้ใช้ทั่วไป', 'info');
document.body.classList.remove('dev-mode');
showNotification('เวอร์ชันลูกค้า - พร้อมใช้งาน!', 'success');
}
} catch (error) {
console.error('ไม่สามารถตรวจสอบโหมดการทำงานได้:', error);
addTerminalLine('ไม่สามารถตรวจสอบโหมดการทำงาน - ใช้โหมดปกติ', 'warning');
// Default: ถ้าเช็คไม่ได้ให้ใช้โหมดลูกค้า (ปลอดภัยกว่า)
document.body.classList.remove('dev-mode');
}
// เริ่มต้น effects
initializeButtonEffects();
// ลบ command input event listeners เพราะเปลี่ยนเป็น log viewer แล้ว
// เพิ่มข้อความต้อนรับใน Log Viewer
addTerminalLine('===== Chahua Plugin Management System =====', 'success');
addTerminalLine('ระบบจัดการปลั๊กอิน - โหมด Log Viewer', 'info');
addTerminalLine('ข้อความจากระบบและปุ่มต่างๆ จะแสดงที่นี่', 'info');
addTerminalLine('', 'info');
setTimeout(() => {
scanAndRenderPlugins();
}, 1000);
// เพิ่ม: เฝ้าฟัง Log จากกระบวนการ Build แบบ Real-time
window.electronAPI.onBuildLog((log) => {
// ตรวจสอบว่าเป็น Error Log หรือไม่
if (log.includes('[ERROR]')) {
addTerminalLine(log.replace('[ERROR] ', ''), 'error');
} else if (log.includes('') || log.includes('')) {
addTerminalLine(log, 'success');
// เรียกฟังก์ชันเมื่อ Build สำเร็จ
if (log.includes('Build เสร็จสมบูรณ์')) {
onBuildComplete(true);
}
} else if (log.includes('') || log.includes('')) {
addTerminalLine(log, 'error');
// เรียกฟังก์ชันเมื่อ Build ล้มเหลว
if (log.includes('Build ล้มเหลว')) {
onBuildComplete(false);
}
} else {
// Log ปกติ
addTerminalLine(log, 'stdout');
}
});
// เพิ่ม: เฝ้าฟัง Enhanced Scan Complete จาก Menu
if (window.electronAPI && window.electronAPI.onEnhancedScanComplete) {
window.electronAPI.onEnhancedScanComplete((result) => {
console.log(' Enhanced scan complete from menu:', result);
if (result.success) {
addTerminalLine(' Enhanced scan completed via keyboard shortcut', 'success');
// อัปเดตการแสดงผลปลั๊กอิน
scanAndRenderPluginsWithDebug();
} else {
addTerminalLine(` Enhanced scan failed: ${result.error}`, 'error');
}
});
}
// แสดง welcome notification
setTimeout(() => {
showNotification('ยินดีต้อนรับสู่ระบบจัดการปลั๊กอิน Chahuadev!', 'success');
}, 2000);
// Initialize license dropdown
initializeLicenseDropdown();
// Initialize resize panel system
window.resizeController = new ResizePanelController();
// Parameterized Diagnostics System
initParameterizedDiagnostics();
// System Check Button Event Listener
const systemCheckBtn = document.getElementById('runSystemCheckBtn');
if (systemCheckBtn) {
systemCheckBtn.addEventListener('click', async () => {
const scope = document.getElementById('diagnosticScope').value;
const selectedPlugins = scope === 'specific' ? getSelectedPlugins() : [];
addTerminalLine(` กำลังเริ่มการวินิจฉัย (${getDiagnosticScopeText(scope)})...`, 'info');
try {
const result = await window.electronAPI.runParameterizedSystemCheck({
scope: scope,
plugins: selectedPlugins
});
if (result.success) {
addTerminalLine(' การวินิจฉัยเสร็จสิ้น', 'success');
if (result.message) {
addTerminalLine(result.message, 'info');
}
if (result.fixed) {
addTerminalLine(' ระบบได้รับการซ่อมแซมเรียบร้อยแล้ว', 'success');
}
if (result.recommendations && result.recommendations.length > 0) {
addTerminalLine(` คำแนะนำ: ${result.recommendations.join(', ')}`, 'info');
}
} else {
addTerminalLine(` การวินิจฉัยล้มเหลว: ${result.error}`, 'error');
}
} catch (error) {
addTerminalLine(` ไม่สามารถเริ่มการวินิจฉัยได้: ${error.message}`, 'error');
}
});
}
} else {
addTerminalLine('ข้อผิดพลาดร้ายแรง: ไม่พบสคริปต์โหลด (electronAPI)!', 'error');
}
});
// Parameterized Diagnostics Functions
/**
* ฟังก์ชันเริ่มต้นระบบ Parameterized Diagnostics
*
* @function initParameterizedDiagnostics
* @description ตั้งค่า event listeners สำหรับระบบวินิจฉัยแบบกำหนดพารามิเตอร์ได้
*
* @dependencies
* - DOM elements: diagnosticScope, specificPluginSelector
*
* @calledBy
* - DOMContentLoaded event -> เริ่มต้นระบบ
*
* @calls
* - addEventListener() -> ตั้งค่า scope change listener
* - loadAvailablePlugins() -> โหลดปลั๊กอินเมื่อเลือก specific
* - updateDiagnosticButtonText() -> อัพเดตข้อความปุ่ม
*
* @sideEffects
* - เพิ่ม event listeners
* - ควบคุมการแสดง/ซ่อน plugin selector
* - อัพเดต UI text ตาม scope ที่เลือก
*
* @features
* - Scope Selection (all/project-only/specific)
* - Dynamic Plugin List Loading
* - Button Text Updates
*/
function initParameterizedDiagnostics() {
const diagnosticScope = document.getElementById('diagnosticScope');
const specificPluginSelector = document.getElementById('specificPluginSelector');
if (diagnosticScope) {
diagnosticScope.addEventListener('change', function() {
if (this.value === 'specific') {
specificPluginSelector.style.display = 'block';
loadAvailablePlugins();
} else {
specificPluginSelector.style.display = 'none';
}
// อัปเดตข้อความปุ่ม
updateDiagnosticButtonText(this.value);
});
}
}
/**
* ฟังก์ชันโหลดปลั๊กอินที่มีให้ใช้งาน
*
* @function loadAvailablePlugins
* @async
* @description โหลดรายการปลั๊กอินจาก Marketplace/Store
*
* @returns {Promise<void>}
*
* @dependencies
* - window.electronAPI -> APIs สำหรับ marketplace
*
* @calledBy
* - Store/Marketplace view switching
* - Refresh marketplace button
*
* @calls addTerminalLine() -> แสดงสถานะการโหลด
*
* @sideEffects
* - อัพเดต Marketplace UI
* - โหลดข้อมูลจาก remote server
*/
async function loadAvailablePlugins() {
const pluginList = document.getElementById('pluginList');
if (!pluginList) return;
try {
// ดึงรายชื่อปลั๊กอินที่ตรวจพบ
const result = await window.electronAPI.getAvailablePlugins();
if (result.success) {
pluginList.innerHTML = '';
result.plugins.forEach(plugin => {
const option = document.createElement('option');
option.value = plugin.path;
option.textContent = `${plugin.name} (${plugin.type})`;
pluginList.appendChild(option);
});
if (result.plugins.length === 0) {
const option = document.createElement('option');
option.textContent = 'ไม่พบปลั๊กอิน';
option.disabled = true;
pluginList.appendChild(option);
}
} else {
pluginList.innerHTML = '<option disabled>ไม่สามารถโหลดรายชื่อปลั๊กอินได้</option>';
}
} catch (error) {
console.error('Error loading plugins:', error);
pluginList.innerHTML = '<option disabled>เกิดข้อผิดพลาดในการโหลด</option>';
}
}
/**
* ฟังก์ชันดึงปลั๊กอินที่ถูกเลือก
*
* @function getSelectedPlugins
* @returns {string[]} array ของ plugin paths ที่ถูกเลือก
* @description ดึงปลั๊กอินที่ผู้ใช้เลือกจาก multi-select dropdown
*
* @dependencies
* - DOM element 'pluginList' -> dropdown element
*
* @calledBy
* - Diagnostic system -> เมื่อต้องการรายการปลั๊กอินที่เลือก
* - System check functions -> สำหรับ specific scope
*
* @returns
* - empty array ถ้าไม่มี element หรือไม่มีการเลือก
* - array of plugin paths ที่ถูกเลือก
*
* @example
* const selectedPlugins = getSelectedPlugins();
* // ['path/to/plugin1', 'path/to/plugin2']
*/
function getSelectedPlugins() {
const pluginList = document.getElementById('pluginList');
if (!pluginList) return [];
const selected = [];
for (let option of pluginList.selectedOptions) {
selected.push(option.value);
}
return selected;
}
/**
* ฟังก์ชันแปลง Diagnostic Scope เป็นข้อความไทย
*
* @function getDiagnosticScopeText
* @param {string} scope - diagnostic scope ('all', 'plugins', 'core', 'dependencies', 'specific')
* @returns {string} ข้อความภาษาไทยสำหรับ scope ที่กำหนด
* @description แปลง scope code เป็นข้อความแสดงผลภาษาไทย
*
* @calledBy
* - updateDiagnosticButtonText() -> อัพเดตข้อความปุ่ม
* - Diagnostic UI functions -> แสดงข้อความใน log
*
* @example
* getDiagnosticScopeText('all'); // 'ทั้งระบบ'
* getDiagnosticScopeText('plugins'); // 'ปลั๊กอินทั้งหมด'
*/
function getDiagnosticScopeText(scope) {
const scopeTexts = {
'all': 'ทั้งระบบ',
'plugins': 'ปลั๊กอินทั้งหมด',
'core': 'ระบบหลัก',
'dependencies': 'Dependencies',
'specific': 'ปลั๊กอินที่เลือก'
};
return scopeTexts[scope] || 'ไม่ระบุ';
}
/**
* ฟังก์ชันอัพเดตข้อความปุ่ม Diagnostic ตาม Scope
*
* @function updateDiagnosticButtonText
* @param {string} scope - diagnostic scope ที่เลือก
* @description อัพเดตข้อความของปุ่ม "เริ่มการวินิจฉัย" ให้ตรงกับ scope ที่เลือก
*
* @dependencies
* - DOM element 'runSystemCheckBtn' -> ปุ่มเริ่มการวินิจฉัย
*
* @calledBy
* - initParameterizedDiagnostics() -> เมื่อเปลี่ยน scope
* - Diagnostic scope change event -> อัตโนมัติ
*
* @sideEffects
* - เปลี่ยน innerHTML ของปุ่ม
* - เพิ่มไอคอน Font Awesome
*
* @example
* updateDiagnosticButtonText('all'); // " วินิจฉัยทั้งระบบ"
* updateDiagnosticButtonText('specific'); // " วินิจฉัยปลั๊กอินที่เลือก"
*/
function updateDiagnosticButtonText(scope) {
const button = document.getElementById('runSystemCheckBtn');
if (!button) return;
const icon = '<i class="fas fa-shield-alt"></i>';
const texts = {
'all': `${icon} วินิจฉัยทั้งระบบ`,
'plugins': `${icon} วินิจฉัยปลั๊กอิน`,
'core': `${icon} วินิจฉัยระบบหลัก`,
'dependencies': `${icon} วินิจฉัย Dependencies`,
'specific': `${icon} วินิจฉัยปลั๊กอินที่เลือก`
};
button.innerHTML = texts[scope] || `${icon} เริ่มการวินิจฉัย`;
}
// Resize Panel System
/**
* คลาสควบคุมระบบ Resize Panel
*
* @class ResizePanelController
* @description จัดการการ resize panel ระหว่าง terminal section และ sidebar
*
* @property {boolean} isResizing - สถานะว่ากำลัง resize อยู่หรือไม่
* @property {number} startX - ตำแหน่ง X เริ่มต้นของการ resize
* @property {number} startWidth - ความกว้างเริ่มต้นของ panel
* @property {HTMLElement} sidebar - element ของ sidebar
* @property {HTMLElement} container - element ของ container หลัก
* @property {HTMLElement} resizeHandle - element ของ resize handle
*
* @dependencies
* - DOM elements: .terminal-section, .container, #resizeHandle
* - Mouse/Touch events
* - CSS styles สำหรับ resizing
*
* @methods
* - init() -> เริ่มต้นระบบ
* - initializeResizePanel() -> ตั้งค่า event listeners
* - startResize() -> เริ่มการ resize
* - handleResize() -> จัดการขณะ resize
* - stopResize() -> หยุดการ resize
* - emergencyCleanup() -> ทำความสะอาดฉุกเฉิน
*
* @features
* - Mouse drag resize
* - Keyboard shortcuts (Escape to stop)
* - Emergency cleanup
* - Responsive design support
*
* @example
* const resizeController = new ResizePanelController();
* // จะเริ่มทำงานอัตโนมัติผ่าน constructor
*/
class ResizePanelController {
constructor() {
this.isResizing = false;
this.startX = 0;
this.startWidth = 0;
this.sidebar = null;
this.container = null;
this.resizeHandle = null;
this.init();
}
init() {
this.terminalSection = document.querySelector('.terminal-section');
this.container = document.querySelector('.container');
this.resizeHandle = document.getElementById('resizeHandle');
if (!this.terminalSection || !this.container || !this.resizeHandle) {
console.error(' Resize elements not found');
return;
}
this.initializeResizePanel();
console.log(' Resize panel system initialized');
}
initializeResizePanel() {
// ทำการ bind ฟังก์ชันเก็บไว้ในตัวแปร
this.boundHandleResize = this.handleResize.bind(this);
this.boundStopResize = this.stopResize.bind(this);
// เพิ่ม emergency cleanup function
this.emergencyCleanup = () => {
console.log(" Emergency cleanup triggered!");
this.stopResize();
};
// เพิ่ม bound function สำหรับ keydown event
this.boundKeydownHandler = (event) => {
if (event.key === 'Escape') {
console.log(" Escape key pressed, stopping resize");
this.emergencyCleanup();
}
};
// เมื่อกดเมาส์ลงบนตัวลาก
this.resizeHandle.addEventListener('mousedown', (e) => {
// ป้องกันการทำงานเริ่มต้นของ browser
e.preventDefault();
e.stopPropagation();
console.log(" Mouse down on resize handle");
// เพิ่ม event listener ที่ document เพื่อให้ลากได้ทั่วจอ
document.addEventListener('mousemove', this.boundHandleResize);
document.addEventListener('mouseup', this.boundStopResize);
// เพิ่ม emergency cleanup listeners
document.addEventListener('mouseleave', this.emergencyCleanup);
window.addEventListener('blur', this.emergencyCleanup);
document.addEventListener('keydown', this.boundKeydownHandler);
// --- เริ่มกระบวนการ Resize ---
this.isResizing = true;
this.startX = e.clientX;
// อ่านค่าความกว้างเริ่มต้นจาก element โดยตรง
this.startWidth = this.terminalSection.offsetWidth;
// เพิ่มคลาสเพื่อแสดงผลและปิด pointer-events
this.container.classList.add('resizing');
this.resizeHandle.classList.add('resizing');
// เพิ่ม timeout fallback - หากไม่มีการปล่อยเมาส์ภายใน 10 วินาที
this.resizeTimeout = setTimeout(() => {
console.log(" Resize timeout - forcing cleanup");
this.emergencyCleanup();
}, 10000);
});
}
startResize(e) {
e.preventDefault();
e.stopPropagation();
console.log(' Starting resize');
// Add global event listeners
document.addEventListener('mousemove', this.boundHandleResize);
document.addEventListener('mouseup', this.boundStopResize);
document.addEventListener('mouseleave', this.boundEmergencyCleanup);
window.addEventListener('blur', this.boundEmergencyCleanup);
// Set initial values
this.isResizing = true;
this.startX = e.clientX;
this.startWidth = this.sidebar.offsetWidth;
// Add visual feedback
this.container.classList.add('resizing');
this.resizeHandle.classList.add('resizing');
// Safety timeout
this.resizeTimeout = setTimeout(() => {
console.log(' Resize timeout - forcing cleanup');
this.emergencyCleanup();
}, 10000);
}
handleResize(e) {
// ถ้าไม่ได้อยู่ในโหมด resizing ก็ไม่ต้องทำอะไร
if (!this.isResizing) return;
e.preventDefault();
// คำนวณความกว้างใหม่
const newWidth = this.startWidth + (e.clientX - this.startX);
// กำหนดขอบเขตความกว้าง
const minWidth = 400;
const maxWidth = this.container.offsetWidth * 0.75;
// ปรับความกว้างของ terminalSection โดยไม่ให้เกินขอบเขต
if (newWidth >= minWidth && newWidth <= maxWidth) {
this.terminalSection.style.width = newWidth + 'px';
}
}
stopResize() {
console.log(" stopResize() called, current isResizing:", this.isResizing);
// --- การันตีว่าส่วนนี้จะทำงานเสมอ ไม่ว่าจะเกิดอะไรขึ้น ---
try {
// ถ้าไม่ได้อยู่ในโหมด resizing แต่ยังมีคลาส resizing ติดอยู่ ให้ลบออก
if (!this.isResizing && this.container.classList.contains('resizing')) {
console.log(" Found orphaned resizing class, cleaning up...");
}
// แสดง notification เมื่อ resize สำเร็จ
if (this.isResizing && window.showNotification) {
const currentWidth = this.terminalSection.offsetWidth;
window.showNotification(` ปรับขนาด Terminal เป็น ${currentWidth}px`, 'success');
}
} catch (error) {
console.error("เกิดข้อผิดพลาดระหว่าง resize:", error);
} finally {
// --- การันตีว่าส่วนนี้จะทำงานเสมอ ไม่ว่าจะเกิด Error หรือไม่ ---
console.log(" Finally block: Cleaning up resize state...");
this.isResizing = false;
// นำคลาสที่บล็อกการทำงานออก (บังคับลบ)
this.container.classList.remove('resizing');
this.resizeHandle.classList.remove('resizing');
// ลบ event listener ที่ไม่ต้องการแล้วออกจาก document (บังคับลบ)
document.removeEventListener('mousemove', this.boundHandleResize);
document.removeEventListener('mouseup', this.boundStopResize);
// ลบ emergency cleanup listeners
document.removeEventListener('mouseleave', this.emergencyCleanup);
window.removeEventListener('blur', this.emergencyCleanup);
document.removeEventListener('keydown', this.boundKeydownHandler);
// Clear timeout
if (this.resizeTimeout) {
clearTimeout(this.resizeTimeout);
this.resizeTimeout = null;
}
console.log(" Resizing stopped and ALL listeners cleaned up.");
}
}
}
// Initialize resize controller
window.resizeController = null;
// License Dropdown Functions
function initializeLicenseDropdown() {
const licenseDropdown = document.getElementById('licenseDropdown');
const checkLicenseBtn = document.getElementById('checkLicenseBtn');
const licenseModalOverlay = document.getElementById('licenseModalOverlay');
const licenseModalCloseBtn = document.getElementById('licenseModalCloseBtn');
if (licenseDropdown) {
const toggleBtn = licenseDropdown.querySelector('.dropdown-toggle');
const menu = licenseDropdown.querySelector('.dropdown-menu');
toggleBtn.addEventListener('click', (event) => {
event.stopPropagation();
menu.classList.toggle('show');
});
checkLicenseBtn.addEventListener('click', (event) => {
event.preventDefault();
checkMyLicense();
menu.classList.remove('show');
});
// Close dropdown when clicking outside
window.addEventListener('click', (event) => {
if (licenseDropdown && !licenseDropdown.contains(event.target)) {
menu.classList.remove('show');
}
});
}
// License Modal Event Listeners
if (licenseModalOverlay) {
const closeModal = () => licenseModalOverlay.classList.remove('show');
licenseModalCloseBtn.addEventListener('click', closeModal);
licenseModalOverlay.addEventListener('click', (event) => {
if (event.target === licenseModalOverlay) {
closeModal();
}
});
}
console.log(' License dropdown initialized');
}
// Theme Dropdown Functions
function initializeThemeDropdown() {
const themeDropdown = document.getElementById('themeDropdown');
if (themeDropdown) {
const toggleBtn = themeDropdown.querySelector('.dropdown-toggle');
const menu = themeDropdown.querySelector('.dropdown-menu');
toggleBtn.addEventListener('click', (event) => {
event.stopPropagation();
menu.classList.toggle('show');
});
// Close dropdown when clicking outside
window.addEventListener('click', (event) => {
if (themeDropdown && !themeDropdown.contains(event.target)) {
menu.classList.remove('show');
}
});
// Close dropdown when theme is selected
const themeItems = menu.querySelectorAll('.dropdown-item');
themeItems.forEach(item => {
item.addEventListener('click', () => {
menu.classList.remove('show');
});
});
}
console.log(' Theme dropdown initialized');
}
// ===== ENHANCED LICENSE POPUP FUNCTIONS (จาก Chahua License Framework) =====
// แสดงป๊อปอัพไลเซนส์ขั้นสูง
/**
* ฟังก์ชันแสดง License Popup (จะถูก DEPRECATED)
*
* @function showLicensePopup
* @async
* @param {string} title - หัวข้อ popup
* @param {string} message - ข้อความใน popup
* @param {string} [type='info'] - ประเภทของ popup (info, warning, error)
* @description แสดง License Popup แบบ Modal
* @deprecated ฟังก์ชันนี้จะไม่ถูกใช้งานแล้ว
*
* @returns {Promise<void>}
*
* @calledBy License functions ต่างๆ
*/
async function showLicensePopup(title, message, type = 'info') {
try {
if (window.electronAPI && window.electronAPI.showLicensePopup) {
const result = await window.electronAPI.showLicensePopup(title, message, type);
console.log(' License popup result:', result);
return result;
} else {
// Fallback to alert
alert(`${title}\n\n${message}`);
return { success: true, method: 'fallback' };
}
} catch (error) {
console.error(' Error showing license popup:', error);
alert(`Error: ${title}\n\n${message}`);
return { success: false, error: error.message };
}
}
// แสดงสถานะไลเซนส์แบบป๊อปอัพใหม่
async function showLicenseStatusPopup() {
try {
const status = await window.electronAPI.getLicenseStatus();
if (status && status.success) {
const data = status.data;
const message = `ประเภทไลเซนส์: ${data.type || 'ไม่ระบุ'}\n` +
`สถานะ: ${data.message || 'ใช้งานได้'}\n` +
`วันที่สร้าง: ${data.generatedAt ? new Date(data.generatedAt).toLocaleString('th-TH') : 'ไม่ระบุ'}\n` +
`เวลาคงเหลือ: ${data.daysRemaining > 365 ? 'ไม่จำกัด' : data.daysRemaining + ' วัน'}\n` +
`รหัส License: ${data.licenseId || 'AUTO-GENERATED'}`;
await showLicensePopup(' ข้อมูลสถานะไลเซนส์', message, 'info');
addTerminalLine(` License Status: ${data.type} (${data.status})`, 'success');
} else {
await showLicensePopup(' ข้อผิดพลาดไลเซนส์', status.error || 'ไม่สามารถตรวจสอบสถานะไลเซนส์ได้', 'error');
addTerminalLine(` License Error: ${status.error || 'ไม่พบ License'}`, 'error');
}
} catch (error) {
await showLicensePopup(' ข้อผิดพลาดระบบ', `เกิดข้อผิดพลาดในการตรวจสอบไลเซนส์:\n${error.message}`, 'error');
addTerminalLine(` ข้อผิดพลาดในการตรวจสอบ License: ${error.message}`, 'error');
}
}
// แสดงช่วยเหลือการ Activate License
async function showLicenseActivationHelp() {
const helpMessage = ` วิธีการ Activate License:\n\n` +
`1. ติดต่อ: chahuadev@gmail.com\n` +
`2. เยี่ยมชม: www.chahuadev.com\n` +
`3. แฟนเพจ: Chahua Development Thailand\n\n` +
` สำหรับการสนับสนุนและขอไลเซนส์`;
await showLicensePopup(' ช่วยเหลือการ Activate License', helpMessage, 'info');
}
// ทดสอบป๊อปอัพแต่ละประเภท
async function testLicensePopups() {
console.log(' เริ่มทดสอบระบบป๊อปอัพ License...');
addTerminalLine(' เริ่มทดสอบระบบป๊อปอัพ License...', 'info');
await showLicensePopup(' ทดสอบ Info', 'นี่คือป๊อปอัพแสดงข้อมูลทั่วไป\nระบบทำงานปกติ', 'info');
setTimeout(async () => {
await showLicensePopup(' ทดสอบ Success', 'นี่คือป๊อปอัพแสดงความสำเร็จ\nการทำงานสำเร็จลุล่วง', 'success');
}, 1500);
setTimeout(async () => {
await showLicensePopup(' ทดสอบ Warning', 'นี่คือป๊อปอัพแสดงคำเตือน\nกรุณาตรวจสอบระบบ', 'warning');
}, 3000);
setTimeout(async () => {
await showLicensePopup(' ทดสอบ Error', 'นี่คือป๊อปอัพแสดงข้อผิดพลาด\nระบบพบปัญหาบางอย่าง', 'error');
addTerminalLine(' ทดสอบระบบป๊อปอัพเสร็จสิ้น', 'success');
}, 4500);
}
// แสดงข้อมูลเวอร์ชันของระบบ License Framework
async function showLicenseSystemInfo() {
const systemInfo = ` Chahua License Framework v3.0\n\n` +
` Integration: Chahuadev Framework\n` +
` Security: Validation Gateway\n` +
` Protection: Hardware Fingerprint Binding\n` +
` Performance: Zero External Dependencies\n` +
` Architecture: Electron + Node.js\n\n` +
` Chahua Development Thailand\n` +
` CEO: Saharath C.\n` +
` Website: www.chahuadev.com\n` +
` Email: chahuadev@gmail.com`;
await showLicensePopup(' ข้อมูลระบบ License Framework', systemInfo, 'info');
}
// เมนูสำหรับผู้พัฒนา (Developer Menu)
function showDeveloperLicenseMenu() {
const choice = prompt(` Developer License Tools:\n\n` +
`1. ทดสอบป๊อปอัพทุกประเภท\n` +
`2. แสดงข้อมูลระบบ License\n` +
`3. ตรวจสอบสถานะ License (Popup)\n` +
`4. แสดงช่วยเหลือ Activation\n\n` +
`เลือกหมายเลข (1-4):`);
switch(choice) {
case '1':
testLicensePopups();
break;
case '2':
showLicenseSystemInfo();
break;
case '3':
showLicenseStatusPopup();
break;
case '4':
showLicenseActivationHelp();
break;
default:
if (choice !== null) {
alert(' กรุณาเลือกหมายเลข 1-4');
}
}
}
// License Checking Function (อัปเกรดให้ใช้ป๊อปอัพแทน Modal)
async function checkMyLicense() {
// ใช้ระบบป๊อปอัพใหม่แทน modal เดิม
await showLicenseStatusPopup();
}
// --- View Switcher Logic ---
document.addEventListener('DOMContentLoaded', () => {
const logPanel = document.getElementById('log-viewer');
const marketplacePanel = document.getElementById('marketplace-webview');
// URL ของร้านค้าบนเว็บไซต์ของคุณ
const marketplaceUrl = 'https://chahuadev.com'; // <-- แก้ไขเป็น URL ของคุณ
let isMarketplaceLoaded = false;
function switchView(viewToShow) {
// ซ่อน Panel ทั้งหมดและเอา active class ออกจากปุ่ม
document.querySelectorAll('.view-panel').forEach(p => p.classList.remove('active'));
document.querySelectorAll('.view-btn').forEach(b => b.classList.remove('active'));
// แสดง Panel และปุ่มที่เลือก
if (viewToShow === 'log') {
if (logPanel) logPanel.classList.add('active');
} else if (viewToShow === 'marketplace') {
if (marketplacePanel) marketplacePanel.classList.add('active');
// โหลด URL ของร้านค้าแค่ครั้งแรกที่กด
if (!isMarketplaceLoaded && marketplacePanel) {
addTerminalLine(`กำลังเชื่อมต่อกับร้านค้าที่ ${marketplaceUrl}...`, 'command');
marketplacePanel.src = marketplaceUrl;
isMarketplaceLoaded = true;
marketplacePanel.addEventListener('did-finish-load', () => {
addTerminalLine(' เชื่อมต่อร้านค้าสำเร็จ!', 'success');
});
marketplacePanel.addEventListener('did-fail-load', (error) => {
addTerminalLine(` ไม่สามารถเชื่อมต่อร้านค้าได้: ${error.errorDescription}`, 'error');
});
}
}
}
// เพิ่ม switchView ให้เป็น global function เพื่อให้ Top Nav ใช้ได้
window.switchView = switchView;
});
// ทำความสะอาด Event Listeners เมื่อปิดหน้าต่าง
window.addEventListener('beforeunload', () => {
if (window.electronAPI && window.electronAPI.removeBuildLogListeners) {
window.electronAPI.removeBuildLogListeners();
}
});