|
|
@@ -0,0 +1,906 @@
|
|
|
+'use strict';
|
|
|
+
|
|
|
+/**
|
|
|
+ * Projects / resources / MCP views.
|
|
|
+ *
|
|
|
+ * The flashing view lives in app.js. This file only uses the shared
|
|
|
+ * window.api bridge and never assumes a browser (WKWebView) has Node access.
|
|
|
+ */
|
|
|
+(() => {
|
|
|
+ const api = window.api;
|
|
|
+ if (!api) {
|
|
|
+ console.error('window.api 不存在,项目管理/资源下载不可用');
|
|
|
+ return;
|
|
|
+ }
|
|
|
+
|
|
|
+ const $ = (selector) => document.querySelector(selector);
|
|
|
+ const $$ = (selector) => Array.from(document.querySelectorAll(selector));
|
|
|
+
|
|
|
+ const state = {
|
|
|
+ current: 'flash',
|
|
|
+ paths: null,
|
|
|
+ projects: [],
|
|
|
+ activeProject: null,
|
|
|
+ projectInfo: null,
|
|
|
+ activeFile: null,
|
|
|
+ resources: { categories: [], activeCategory: null, detail: null, output: '', busy: false },
|
|
|
+ mcp: null,
|
|
|
+ };
|
|
|
+
|
|
|
+ function toast(message, kind = '') {
|
|
|
+ const el = $('#toast');
|
|
|
+ if (!el) return;
|
|
|
+ el.textContent = message;
|
|
|
+ el.className = `toast ${kind}`.trim();
|
|
|
+ clearTimeout(toast._timer);
|
|
|
+ toast._timer = setTimeout(() => el.classList.add('hidden'), 3200);
|
|
|
+ }
|
|
|
+
|
|
|
+ function escapeHtml(value) {
|
|
|
+ return String(value)
|
|
|
+ .replaceAll('&', '&')
|
|
|
+ .replaceAll('<', '<')
|
|
|
+ .replaceAll('>', '>')
|
|
|
+ .replaceAll('"', '"');
|
|
|
+ }
|
|
|
+
|
|
|
+ function formatSize(bytes) {
|
|
|
+ const value = Number(bytes) || 0;
|
|
|
+ const units = ['B', 'KB', 'MB', 'GB'];
|
|
|
+ let index = 0;
|
|
|
+ let size = value;
|
|
|
+ while (size >= 1024 && index < units.length - 1) {
|
|
|
+ size /= 1024;
|
|
|
+ index += 1;
|
|
|
+ }
|
|
|
+ return `${size.toFixed(index === 0 ? 0 : 1)} ${units[index]}`;
|
|
|
+ }
|
|
|
+
|
|
|
+ function baseName(filePath) {
|
|
|
+ return String(filePath).split(/[\\/]/).pop() || filePath;
|
|
|
+ }
|
|
|
+
|
|
|
+ function isAbsolutePath(value) {
|
|
|
+ return /^[\\/]/.test(value) || /^[A-Za-z]:[\\/]/.test(value);
|
|
|
+ }
|
|
|
+
|
|
|
+ function joinPath(root, relative) {
|
|
|
+ if (!relative) return root;
|
|
|
+ if (isAbsolutePath(relative)) return relative;
|
|
|
+ return `${root.replace(/[\\/]+$/, '')}/${relative}`;
|
|
|
+ }
|
|
|
+
|
|
|
+ function relativeToProject(filePath) {
|
|
|
+ if (!state.activeProject) return filePath;
|
|
|
+ const root = state.activeProject.replace(/[\\/]+$/, '');
|
|
|
+ if (filePath.startsWith(`${root}/`) || filePath.startsWith(`${root}\\`)) {
|
|
|
+ return filePath.slice(root.length + 1).replaceAll('\\', '/');
|
|
|
+ }
|
|
|
+ return filePath;
|
|
|
+ }
|
|
|
+
|
|
|
+ async function ensurePaths() {
|
|
|
+ if (state.paths) return state.paths;
|
|
|
+ const result = await api.appPaths();
|
|
|
+ if (!result?.ok) throw new Error(result?.error || '无法读取应用目录');
|
|
|
+ state.paths = result;
|
|
|
+ return result;
|
|
|
+ }
|
|
|
+
|
|
|
+ /* ── Navigation ─────────────────────────────────────────────── */
|
|
|
+
|
|
|
+ const VIEWS = ['flash', 'projects', 'resources', 'mcp'];
|
|
|
+
|
|
|
+ function showView(name) {
|
|
|
+ if (!VIEWS.includes(name)) return;
|
|
|
+ state.current = name;
|
|
|
+ $$('#tabs .tab').forEach((tab) => {
|
|
|
+ tab.classList.toggle('active', tab.dataset.view === name);
|
|
|
+ });
|
|
|
+ for (const view of VIEWS) {
|
|
|
+ const el = $(`#view-${view}`);
|
|
|
+ if (!el) continue;
|
|
|
+ el.classList.toggle('active', view === name);
|
|
|
+ el.classList.toggle('hidden', view !== name);
|
|
|
+ }
|
|
|
+ const flashTop = $('#btn-flash-top');
|
|
|
+ if (flashTop) flashTop.style.display = name === 'flash' ? '' : 'none';
|
|
|
+
|
|
|
+ if (name === 'projects') loadProjects().catch((error) => toast(error.message, 'err'));
|
|
|
+ if (name === 'resources') loadResources().catch((error) => toast(error.message, 'err'));
|
|
|
+ if (name === 'mcp') loadMcp().catch((error) => toast(error.message, 'err'));
|
|
|
+ }
|
|
|
+
|
|
|
+ /* ── Projects ───────────────────────────────────────────────── */
|
|
|
+
|
|
|
+ function projectLog(text, level = 'info') {
|
|
|
+ const log = $('#project-log');
|
|
|
+ if (!log) return;
|
|
|
+ const line = document.createElement('span');
|
|
|
+ line.className = 'line';
|
|
|
+ const time = document.createElement('span');
|
|
|
+ time.className = 't';
|
|
|
+ time.textContent = new Date().toTimeString().slice(0, 8);
|
|
|
+ const body = document.createElement('span');
|
|
|
+ body.className = level;
|
|
|
+ body.textContent = text;
|
|
|
+ line.append(time, body);
|
|
|
+ log.appendChild(line);
|
|
|
+ log.scrollTop = log.scrollHeight;
|
|
|
+ }
|
|
|
+
|
|
|
+ function projectClearLog() {
|
|
|
+ const log = $('#project-log');
|
|
|
+ if (log) log.textContent = '';
|
|
|
+ }
|
|
|
+
|
|
|
+ function renderProjects() {
|
|
|
+ const list = $('#project-list');
|
|
|
+ if (!list) return;
|
|
|
+ const filter = ($('#project-filter')?.value || '').trim().toLowerCase();
|
|
|
+ const projects = state.projects.filter((project) =>
|
|
|
+ !filter || project.name.toLowerCase().includes(filter) || project.path.toLowerCase().includes(filter),
|
|
|
+ );
|
|
|
+
|
|
|
+ list.textContent = '';
|
|
|
+ if (!projects.length) {
|
|
|
+ const empty = document.createElement('div');
|
|
|
+ empty.className = 'empty';
|
|
|
+ empty.style.minHeight = '120px';
|
|
|
+ empty.textContent = state.projects.length ? '没有匹配的项目' : '还没有项目';
|
|
|
+ list.appendChild(empty);
|
|
|
+ } else {
|
|
|
+ for (const project of projects) {
|
|
|
+ const button = document.createElement('button');
|
|
|
+ button.type = 'button';
|
|
|
+ button.className = `project-item${project.path === state.activeProject ? ' active' : ''}`;
|
|
|
+ const name = document.createElement('strong');
|
|
|
+ name.textContent = project.name;
|
|
|
+ const path = document.createElement('span');
|
|
|
+ path.textContent = project.path;
|
|
|
+ button.append(name, path);
|
|
|
+ button.addEventListener('click', () => {
|
|
|
+ openProject(project.path).catch((error) => toast(error.message, 'err'));
|
|
|
+ });
|
|
|
+ list.appendChild(button);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ $('#project-count').textContent = `${state.projects.length} 个`;
|
|
|
+ }
|
|
|
+
|
|
|
+ async function loadProjects() {
|
|
|
+ const paths = await ensurePaths();
|
|
|
+ const result = await api.scanProjects(paths.projects);
|
|
|
+ if (!result?.ok) throw new Error(result?.error || '扫描项目失败');
|
|
|
+ state.projects = result.projects || [];
|
|
|
+ renderProjects();
|
|
|
+ if (!state.activeProject && state.projects.length) {
|
|
|
+ await openProject(state.projects[0].path);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ async function openProject(projectPath) {
|
|
|
+ const result = await api.runCliJson(['project', 'info', '--dir', projectPath]);
|
|
|
+ if (!result?.ok) throw new Error(result?.error || '读取项目失败');
|
|
|
+ const project = result.data;
|
|
|
+ state.activeProject = projectPath;
|
|
|
+ state.projectInfo = project;
|
|
|
+ state.activeFile = null;
|
|
|
+
|
|
|
+ $('#project-empty').classList.add('hidden');
|
|
|
+ $('#project-content').classList.remove('hidden');
|
|
|
+ $('#project-name').textContent = project.project?.name || baseName(projectPath);
|
|
|
+ $('#project-meta').textContent = `${project.project?.chip || 'unknown'} · ${project.project?.version || ''} · ${projectPath}`;
|
|
|
+ $('#project-editor').value = '';
|
|
|
+
|
|
|
+ renderProjectInfo(project);
|
|
|
+ renderProjects();
|
|
|
+ updateProjectLibState().catch(() => {});
|
|
|
+ projectClearLog();
|
|
|
+ projectLog(`打开项目:${projectPath}`, 'ok');
|
|
|
+
|
|
|
+ const files = await loadProjectFiles(projectPath);
|
|
|
+ const main = files.find((file) => !file.isDir && file.name.toLowerCase() === 'main.lua');
|
|
|
+ if (main) {
|
|
|
+ await openProjectFile(main.path);
|
|
|
+ } else {
|
|
|
+ $('#project-editor-title').textContent = 'main.lua';
|
|
|
+ $('#project-editor').value = '-- 这个项目里没有找到 main.lua\n';
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ function renderProjectInfo(project) {
|
|
|
+ const info = $('#project-info');
|
|
|
+ if (!info) return;
|
|
|
+ info.textContent = '';
|
|
|
+ const rows = [
|
|
|
+ ['芯片', project.project?.chip],
|
|
|
+ ['版本', project.project?.version],
|
|
|
+ ['脚本目录', (project.build?.script_dirs || []).join(', ') || '—'],
|
|
|
+ ['脚本文件', (project.build?.script_files || []).join(', ') || '—'],
|
|
|
+ ['输出目录', project.build?.output_dir || 'build/'],
|
|
|
+ ['使用 luac', project.build?.use_luac ? '是' : '否'],
|
|
|
+ ['SOC 固件', project.flash?.soc_file || '未设置'],
|
|
|
+ ['串口', project.flash?.port || '未设置'],
|
|
|
+ ];
|
|
|
+ for (const [label, value] of rows) {
|
|
|
+ const dt = document.createElement('dt');
|
|
|
+ dt.textContent = label;
|
|
|
+ const dd = document.createElement('dd');
|
|
|
+ dd.textContent = value || '—';
|
|
|
+ info.append(dt, dd);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ async function loadProjectFiles(projectPath) {
|
|
|
+ const result = await api.listFiles(projectPath);
|
|
|
+ if (!result?.ok) throw new Error(result?.error || '读取项目文件失败');
|
|
|
+ const files = (result.files || []).filter(
|
|
|
+ (file) =>
|
|
|
+ !file.path.startsWith('.git/') &&
|
|
|
+ !file.path.startsWith('node_modules/') &&
|
|
|
+ !file.path.startsWith('resource/') &&
|
|
|
+ !file.path.startsWith('build/'),
|
|
|
+ );
|
|
|
+ const container = $('#project-files');
|
|
|
+ container.textContent = '';
|
|
|
+ for (const file of files) {
|
|
|
+ if (file.isDir) continue;
|
|
|
+ const row = document.createElement('div');
|
|
|
+ row.className = 'file-row';
|
|
|
+ row.dataset.path = file.path;
|
|
|
+ const icon = document.createElement('span');
|
|
|
+ icon.textContent = file.name.endsWith('.lua') ? '◈' : '•';
|
|
|
+ const name = document.createElement('span');
|
|
|
+ name.textContent = file.path;
|
|
|
+ const size = document.createElement('span');
|
|
|
+ size.className = 'size';
|
|
|
+ size.textContent = formatSize(file.size);
|
|
|
+ row.append(icon, name, size);
|
|
|
+ if (file.name.endsWith('.lua') || file.name.endsWith('.luac') || file.name.endsWith('.txt')) {
|
|
|
+ row.addEventListener('click', () => {
|
|
|
+ openProjectFile(file.path).catch((error) => toast(error.message, 'err'));
|
|
|
+ });
|
|
|
+ }
|
|
|
+ container.appendChild(row);
|
|
|
+ }
|
|
|
+ if (!container.children.length) {
|
|
|
+ const empty = document.createElement('div');
|
|
|
+ empty.className = 'muted';
|
|
|
+ empty.textContent = '没有脚本文件';
|
|
|
+ container.appendChild(empty);
|
|
|
+ }
|
|
|
+ return files;
|
|
|
+ }
|
|
|
+
|
|
|
+ async function openProjectFile(relativePath) {
|
|
|
+ if (!state.activeProject) return;
|
|
|
+ const fullPath = joinPath(state.activeProject, relativePath);
|
|
|
+ const result = await api.readTextFile(fullPath);
|
|
|
+ if (!result?.ok) throw new Error(result?.error || '读取文件失败');
|
|
|
+ state.activeFile = fullPath;
|
|
|
+ $('#project-editor').value = result.content || '';
|
|
|
+ $('#project-editor-title').textContent = relativePath;
|
|
|
+ $$('#project-files .file-row').forEach((row) => {
|
|
|
+ row.classList.toggle('active', row.dataset.path === relativePath);
|
|
|
+ });
|
|
|
+ }
|
|
|
+
|
|
|
+ async function saveProjectFile() {
|
|
|
+ if (!state.activeFile) {
|
|
|
+ toast('没有打开文件', 'err');
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ const result = await api.writeTextFile(state.activeFile, $('#project-editor').value);
|
|
|
+ if (result?.ok) {
|
|
|
+ toast('已保存', 'ok');
|
|
|
+ projectLog(`保存:${state.activeFile}`, 'ok');
|
|
|
+ } else {
|
|
|
+ toast(result?.error || '保存失败', 'err');
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ function parseConfigList(value) {
|
|
|
+ return String(value || '')
|
|
|
+ .split(',')
|
|
|
+ .map((item) => item.trim())
|
|
|
+ .filter(Boolean);
|
|
|
+ }
|
|
|
+
|
|
|
+ async function updateProjectConfig(key, value) {
|
|
|
+ if (!state.activeProject) return;
|
|
|
+ const result = await api.runCliJson([
|
|
|
+ 'project',
|
|
|
+ 'config',
|
|
|
+ '--dir',
|
|
|
+ state.activeProject,
|
|
|
+ key,
|
|
|
+ value,
|
|
|
+ ]);
|
|
|
+ if (!result?.ok) throw new Error(result?.error || '修改项目配置失败');
|
|
|
+ await openProject(state.activeProject);
|
|
|
+ }
|
|
|
+
|
|
|
+ async function addProjectDir() {
|
|
|
+ const selected = await api.openFolderDialog();
|
|
|
+ if (!selected) return;
|
|
|
+ const current = state.projectInfo?.build?.script_dirs || [];
|
|
|
+ const relative = relativeToProject(selected);
|
|
|
+ if (current.includes(relative)) {
|
|
|
+ toast('该目录已在项目中', 'warn');
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ await updateProjectConfig('build.script_dirs', [...current, relative].join(','));
|
|
|
+ toast('已添加脚本目录', 'ok');
|
|
|
+ }
|
|
|
+
|
|
|
+ async function addProjectFile() {
|
|
|
+ const selected = await api.openFileDialog(['lua', 'luac', 'txt']);
|
|
|
+ if (!selected) return;
|
|
|
+ const current = state.projectInfo?.build?.script_files || [];
|
|
|
+ const relative = relativeToProject(selected);
|
|
|
+ if (current.includes(relative)) {
|
|
|
+ toast('该文件已在项目中', 'warn');
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ await updateProjectConfig('build.script_files', [...current, relative].join(','));
|
|
|
+ toast('已添加脚本文件', 'ok');
|
|
|
+ }
|
|
|
+
|
|
|
+ function showProjectModal() {
|
|
|
+ $('#project-modal-error').textContent = '';
|
|
|
+ $('#project-name-input').value = '';
|
|
|
+ $('#project-modal').classList.remove('hidden');
|
|
|
+ setTimeout(() => $('#project-name-input').focus(), 30);
|
|
|
+ }
|
|
|
+
|
|
|
+ async function createProject() {
|
|
|
+ const name = $('#project-name-input').value.trim();
|
|
|
+ const chip = $('#project-chip').value;
|
|
|
+ if (!name) {
|
|
|
+ $('#project-modal-error').textContent = '请输入项目名称';
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ if (!/^[A-Za-z0-9_.-]+$/.test(name)) {
|
|
|
+ $('#project-modal-error').textContent = '项目名只能包含字母、数字、下划线、点和短横线';
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ const paths = await ensurePaths();
|
|
|
+ const dir = `${paths.projects}/${name}`;
|
|
|
+ const button = $('#btn-project-create');
|
|
|
+ button.disabled = true;
|
|
|
+ try {
|
|
|
+ const result = await api.runCliJson(['project', 'new', name, '--chip', chip, '--dir', dir]);
|
|
|
+ if (!result?.ok) throw new Error(result?.error || '创建项目失败');
|
|
|
+ $('#project-modal').classList.add('hidden');
|
|
|
+ await loadProjects();
|
|
|
+ await openProject(dir);
|
|
|
+ toast(`项目已创建:${name}`, 'ok');
|
|
|
+ } catch (error) {
|
|
|
+ $('#project-modal-error').textContent = error.message || String(error);
|
|
|
+ } finally {
|
|
|
+ button.disabled = false;
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ async function importProject() {
|
|
|
+ const file = await api.openFileDialog(['ini', 'luatos']);
|
|
|
+ if (!file) return;
|
|
|
+ const paths = await ensurePaths();
|
|
|
+ const directoryName = baseName(file).replace(/\.(ini|luatos)$/i, '');
|
|
|
+ const dir = `${paths.projects}/${directoryName}`;
|
|
|
+ const result = await api.runCliJson(['project', 'import', file, '--dir', dir]);
|
|
|
+ if (!result?.ok) {
|
|
|
+ toast(result?.error || '导入失败', 'err');
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ await loadProjects();
|
|
|
+ await openProject(dir);
|
|
|
+ toast('项目已导入', 'ok');
|
|
|
+ }
|
|
|
+
|
|
|
+ async function deleteActiveProject() {
|
|
|
+ if (!state.activeProject) return;
|
|
|
+ const name = state.projectInfo?.project?.name || baseName(state.activeProject);
|
|
|
+ if (!window.confirm(`确定删除项目“${name}”?此操作会删除整个项目目录,不可撤销。`)) return;
|
|
|
+ const result = await api.deleteProject(state.activeProject);
|
|
|
+ if (!result?.ok) {
|
|
|
+ toast(result?.error || '删除失败', 'err');
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ state.activeProject = null;
|
|
|
+ state.projectInfo = null;
|
|
|
+ state.activeFile = null;
|
|
|
+ $('#project-content').classList.add('hidden');
|
|
|
+ $('#project-empty').classList.remove('hidden');
|
|
|
+ await loadProjects();
|
|
|
+ toast('项目已删除', 'ok');
|
|
|
+ }
|
|
|
+
|
|
|
+ async function analyzeProject() {
|
|
|
+ if (!state.activeProject) return;
|
|
|
+ projectClearLog();
|
|
|
+ projectLog('开始分析项目…', 'cmd');
|
|
|
+ const result = await api.runCliJson(['project', 'analyze', '--dir', state.activeProject]);
|
|
|
+ if (!result?.ok) {
|
|
|
+ projectLog(result?.error || '分析失败', 'err');
|
|
|
+ toast('分析失败', 'err');
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ projectLog(JSON.stringify(result.data, null, 2), 'info');
|
|
|
+ toast('分析完成', 'ok');
|
|
|
+ }
|
|
|
+
|
|
|
+ async function prepareProjectLibraries() {
|
|
|
+ if (!state.activeProject) return;
|
|
|
+ const output = joinPath(state.activeProject, 'resource');
|
|
|
+ projectLog('下载 public/soc_script 到项目 resource/ …', 'cmd');
|
|
|
+ const button = $('#btn-project-libs');
|
|
|
+ button.disabled = true;
|
|
|
+ try {
|
|
|
+ const result = await api.startCliStream('project', [
|
|
|
+ 'resource',
|
|
|
+ 'download',
|
|
|
+ 'public',
|
|
|
+ 'soc_script',
|
|
|
+ '--output',
|
|
|
+ output,
|
|
|
+ ]);
|
|
|
+ if (result?.ok) {
|
|
|
+ toast('扩展库已下载', 'ok');
|
|
|
+ projectLog('扩展库已就绪,可以点击“构建”', 'ok');
|
|
|
+ await updateProjectLibState();
|
|
|
+ } else {
|
|
|
+ toast(result?.error || '扩展库下载失败', 'err');
|
|
|
+ }
|
|
|
+ } finally {
|
|
|
+ button.disabled = false;
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ async function updateProjectLibState() {
|
|
|
+ if (!state.activeProject) return;
|
|
|
+ const button = $('#btn-project-libs');
|
|
|
+ const exists = await api.pathExists(joinPath(state.activeProject, 'resource/public/soc_script'));
|
|
|
+ if (button) {
|
|
|
+ button.textContent = exists?.exists ? '扩展库已就绪' : '准备扩展库';
|
|
|
+ button.classList.toggle('secondary', Boolean(exists?.exists));
|
|
|
+ button.classList.toggle('ghost', !exists?.exists);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ async function buildProject() {
|
|
|
+ if (!state.activeProject) return;
|
|
|
+ projectClearLog();
|
|
|
+ projectLog('开始构建…', 'cmd');
|
|
|
+ const button = $('#btn-project-build');
|
|
|
+ button.disabled = true;
|
|
|
+ try {
|
|
|
+ const result = await api.startCliStream('project', ['project', 'build', '--dir', state.activeProject]);
|
|
|
+ if (result?.ok) {
|
|
|
+ toast('构建完成', 'ok');
|
|
|
+ } else {
|
|
|
+ toast(result?.error || '构建失败', 'err');
|
|
|
+ }
|
|
|
+ } catch (error) {
|
|
|
+ projectLog(error.message || String(error), 'err');
|
|
|
+ toast('构建失败', 'err');
|
|
|
+ } finally {
|
|
|
+ button.disabled = false;
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ async function exportProject() {
|
|
|
+ if (!state.activeProject) return;
|
|
|
+ const name = state.projectInfo?.project?.name || 'project';
|
|
|
+ const output = await api.saveFileDialog(`${name}.luatos`, ['luatos']);
|
|
|
+ if (!output) return;
|
|
|
+ const result = await api.runCliJson(['project', 'export', '--dir', state.activeProject, '-o', output]);
|
|
|
+ if (result?.ok) {
|
|
|
+ toast(`已导出:${output}`, 'ok');
|
|
|
+ } else {
|
|
|
+ toast(result?.error || '导出失败', 'err');
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ async function setProjectSoc() {
|
|
|
+ if (!state.activeProject) return;
|
|
|
+ const selected = await api.openFileDialog(['soc']);
|
|
|
+ if (!selected) return;
|
|
|
+ await updateProjectConfig('flash.soc_file', selected);
|
|
|
+ toast('已设置项目固件', 'ok');
|
|
|
+ }
|
|
|
+
|
|
|
+ async function projectToFlash() {
|
|
|
+ if (!state.projectInfo) return;
|
|
|
+ const soc = state.projectInfo.flash?.soc_file;
|
|
|
+ if (!soc) {
|
|
|
+ toast('项目还没有设置 SOC 固件,请在项目配置里设置 flash.soc_file', 'err');
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ const socPath = joinPath(state.activeProject, soc);
|
|
|
+ const scriptRelative = state.projectInfo.build?.script_dirs?.[0] || 'lua/';
|
|
|
+ const scriptDir = joinPath(state.activeProject, scriptRelative);
|
|
|
+ await window.__luatos.loadSoc(socPath);
|
|
|
+ window.__luatos.state.scriptDir = scriptDir;
|
|
|
+ const input = $('#script-dir');
|
|
|
+ if (input) input.value = scriptDir;
|
|
|
+ window.__luatos.updateFlashButton();
|
|
|
+ showView('flash');
|
|
|
+ toast('已带入项目固件和脚本目录', 'ok');
|
|
|
+ }
|
|
|
+
|
|
|
+ function bindProjectEvents() {
|
|
|
+ $('#btn-project-new').addEventListener('click', showProjectModal);
|
|
|
+ $('#btn-project-cancel').addEventListener('click', () => $('#project-modal').classList.add('hidden'));
|
|
|
+ $('#btn-project-create').addEventListener('click', () => {
|
|
|
+ createProject().catch((error) => {
|
|
|
+ $('#project-modal-error').textContent = error.message || String(error);
|
|
|
+ });
|
|
|
+ });
|
|
|
+ $('#btn-project-import').addEventListener('click', () => importProject().catch((error) => toast(error.message, 'err')));
|
|
|
+ $('#btn-project-root').addEventListener('click', async () => {
|
|
|
+ const paths = await ensurePaths();
|
|
|
+ await api.revealPath(paths.projects);
|
|
|
+ });
|
|
|
+ $('#project-filter').addEventListener('input', renderProjects);
|
|
|
+ $('#btn-project-save').addEventListener('click', () => saveProjectFile().catch((error) => toast(error.message, 'err')));
|
|
|
+ $('#btn-project-add-dir').addEventListener('click', () => addProjectDir().catch((error) => toast(error.message, 'err')));
|
|
|
+ $('#btn-project-add-file').addEventListener('click', () => addProjectFile().catch((error) => toast(error.message, 'err')));
|
|
|
+ $('#btn-project-build').addEventListener('click', () => buildProject().catch((error) => toast(error.message, 'err')));
|
|
|
+ $('#btn-project-libs').addEventListener('click', () => prepareProjectLibraries().catch((error) => toast(error.message, 'err')));
|
|
|
+ $('#btn-project-analyze').addEventListener('click', () => analyzeProject().catch((error) => toast(error.message, 'err')));
|
|
|
+ $('#btn-project-soc').addEventListener('click', () => setProjectSoc().catch((error) => toast(error.message, 'err')));
|
|
|
+ $('#btn-project-flash').addEventListener('click', () => projectToFlash().catch((error) => toast(error.message, 'err')));
|
|
|
+ $('#btn-project-reveal').addEventListener('click', () => {
|
|
|
+ if (state.activeProject) api.revealPath(state.activeProject);
|
|
|
+ });
|
|
|
+ $('#btn-project-delete').addEventListener('click', () => deleteActiveProject().catch((error) => toast(error.message, 'err')));
|
|
|
+ $('#btn-project-export').addEventListener('click', () => exportProject().catch((error) => toast(error.message, 'err')));
|
|
|
+
|
|
|
+ api.onCliEvent('project', (event) => {
|
|
|
+ if (!event || typeof event !== 'object') return;
|
|
|
+ if (event.type === 'progress') {
|
|
|
+ const message = event.message || event.stage || '';
|
|
|
+ if (message) projectLog(message, event.error ? 'err' : 'info');
|
|
|
+ } else if (event.type === 'resource_download') {
|
|
|
+ if (event.event === 'start_file') {
|
|
|
+ projectLog(`[${Number(event.index || 0) + 1}/${event.total || 1}] 下载 ${event.filename}(${formatSize(event.size)})`, 'cmd');
|
|
|
+ } else if (event.event === 'verified') {
|
|
|
+ projectLog(`SHA256 校验通过:${event.filename}`, 'ok');
|
|
|
+ } else if (event.event === 'extracted') {
|
|
|
+ projectLog(`已解压:${event.filename} → ${event.dest_dir}`, 'ok');
|
|
|
+ } else if (event.event === 'file_failed' || event.event === 'hash_mismatch') {
|
|
|
+ projectLog(`下载失败:${event.filename}`, 'err');
|
|
|
+ }
|
|
|
+ } else if (event.type === 'message') {
|
|
|
+ projectLog(event.message || '', event.level === 'error' ? 'err' : event.level === 'warn' ? 'warn' : 'info');
|
|
|
+ } else if (event.type === 'error') {
|
|
|
+ projectLog(event.message || '构建错误', 'err');
|
|
|
+ } else if (event.type === 'result') {
|
|
|
+ projectLog(event.status === 'ok' ? '构建成功' : `构建返回:${event.status}`, event.status === 'ok' ? 'ok' : 'err');
|
|
|
+ }
|
|
|
+ });
|
|
|
+ api.onCliLine('project', ({ line, source }) => {
|
|
|
+ if (line) projectLog(line, source === 'stderr' ? 'muted' : 'info');
|
|
|
+ });
|
|
|
+ api.onCliExit('project', ({ code, signal, error }) => {
|
|
|
+ if (error) projectLog(error, 'err');
|
|
|
+ else projectLog(`构建结束(code=${code}${signal ? `, signal=${signal}` : ''})`, code === 0 ? 'ok' : 'err');
|
|
|
+ });
|
|
|
+ }
|
|
|
+
|
|
|
+ /* ── Resources ──────────────────────────────────────────────── */
|
|
|
+
|
|
|
+ function resLog(text, level = 'info') {
|
|
|
+ const log = $('#res-log');
|
|
|
+ if (!log) return;
|
|
|
+ const line = document.createElement('span');
|
|
|
+ line.className = 'line';
|
|
|
+ const time = document.createElement('span');
|
|
|
+ time.className = 't';
|
|
|
+ time.textContent = new Date().toTimeString().slice(0, 8);
|
|
|
+ const body = document.createElement('span');
|
|
|
+ body.className = level;
|
|
|
+ body.textContent = text;
|
|
|
+ line.append(time, body);
|
|
|
+ log.appendChild(line);
|
|
|
+ log.scrollTop = log.scrollHeight;
|
|
|
+ }
|
|
|
+
|
|
|
+ function resClearLog() {
|
|
|
+ const log = $('#res-log');
|
|
|
+ if (log) log.textContent = '';
|
|
|
+ }
|
|
|
+
|
|
|
+ function setResProgress(percent, stage, message) {
|
|
|
+ const value = Math.max(0, Math.min(100, Number(percent) || 0));
|
|
|
+ $('#res-bar-fill').style.width = `${value}%`;
|
|
|
+ $('#res-percent').textContent = `${Math.round(value)}%`;
|
|
|
+ if (stage) $('#res-stage').textContent = stage;
|
|
|
+ if (message) resLog(message, 'info');
|
|
|
+ }
|
|
|
+
|
|
|
+ function renderResourceCategories() {
|
|
|
+ const container = $('#res-categories');
|
|
|
+ container.textContent = '';
|
|
|
+ $('#res-category-count').textContent = `${state.resources.categories.length} 类`;
|
|
|
+ for (const category of state.resources.categories) {
|
|
|
+ const button = document.createElement('button');
|
|
|
+ button.type = 'button';
|
|
|
+ button.className = `resource-category${category.name === state.resources.activeCategory ? ' active' : ''}`;
|
|
|
+ const name = document.createElement('strong');
|
|
|
+ name.textContent = category.name;
|
|
|
+ const desc = document.createElement('span');
|
|
|
+ desc.textContent = category.desc || '';
|
|
|
+ button.append(name, desc);
|
|
|
+ button.addEventListener('click', () => {
|
|
|
+ openResourceCategory(category.name).catch((error) => toast(error.message, 'err'));
|
|
|
+ });
|
|
|
+ container.appendChild(button);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ async function loadResources() {
|
|
|
+ const paths = await ensurePaths();
|
|
|
+ state.resources.output = paths.resources;
|
|
|
+ $('#res-output-path').textContent = paths.resources;
|
|
|
+ const result = await api.runCliJson(['resource', 'list']);
|
|
|
+ if (!result?.ok) throw new Error(result?.error || '读取资源清单失败');
|
|
|
+ state.resources.categories = Array.isArray(result.data) ? result.data : [];
|
|
|
+ renderResourceCategories();
|
|
|
+ if (state.resources.activeCategory) {
|
|
|
+ await openResourceCategory(state.resources.activeCategory);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ function renderResourceDetail(detail) {
|
|
|
+ const container = $('#res-detail');
|
|
|
+ container.textContent = '';
|
|
|
+ if (!detail?.childrens?.length) {
|
|
|
+ const empty = document.createElement('div');
|
|
|
+ empty.className = 'empty';
|
|
|
+ empty.textContent = '这个分类没有可下载内容';
|
|
|
+ container.appendChild(empty);
|
|
|
+ return;
|
|
|
+ }
|
|
|
+
|
|
|
+ for (const child of detail.childrens) {
|
|
|
+ const card = document.createElement('section');
|
|
|
+ card.className = 'resource-child';
|
|
|
+ const head = document.createElement('div');
|
|
|
+ head.className = 'resource-child-head';
|
|
|
+ const titleBox = document.createElement('div');
|
|
|
+ const title = document.createElement('h3');
|
|
|
+ title.textContent = child.name;
|
|
|
+ const desc = document.createElement('p');
|
|
|
+ desc.textContent = child.desc || '';
|
|
|
+ titleBox.append(title, desc);
|
|
|
+ const latest = document.createElement('button');
|
|
|
+ latest.type = 'button';
|
|
|
+ latest.className = 'primary small';
|
|
|
+ latest.textContent = '下载最新';
|
|
|
+ latest.addEventListener('click', () => {
|
|
|
+ downloadResource(detail.name, child.name, null, child.name).catch((error) => toast(error.message, 'err'));
|
|
|
+ });
|
|
|
+ head.append(titleBox, latest);
|
|
|
+ card.appendChild(head);
|
|
|
+
|
|
|
+ const versions = document.createElement('div');
|
|
|
+ versions.className = 'resource-versions';
|
|
|
+ for (const version of child.versions || []) {
|
|
|
+ const versionBox = document.createElement('div');
|
|
|
+ versionBox.className = 'resource-version';
|
|
|
+ const versionHead = document.createElement('div');
|
|
|
+ versionHead.className = 'resource-version-head';
|
|
|
+ const versionTitle = document.createElement('span');
|
|
|
+ versionTitle.textContent = version.name;
|
|
|
+ const download = document.createElement('button');
|
|
|
+ download.type = 'button';
|
|
|
+ download.className = 'secondary small';
|
|
|
+ download.textContent = '下载此版本';
|
|
|
+ download.addEventListener('click', () => {
|
|
|
+ downloadResource(detail.name, child.name, version.name, `${child.name} ${version.name}`).catch((error) =>
|
|
|
+ toast(error.message, 'err'),
|
|
|
+ );
|
|
|
+ });
|
|
|
+ versionHead.append(versionTitle, download);
|
|
|
+
|
|
|
+ const files = document.createElement('div');
|
|
|
+ files.className = 'resource-files';
|
|
|
+ for (const file of version.files || []) {
|
|
|
+ const row = document.createElement('div');
|
|
|
+ row.className = 'resource-file';
|
|
|
+ const name = document.createElement('span');
|
|
|
+ name.textContent = file.filename;
|
|
|
+ const size = document.createElement('span');
|
|
|
+ size.textContent = formatSize(file.size);
|
|
|
+ row.append(name, size);
|
|
|
+ files.appendChild(row);
|
|
|
+ }
|
|
|
+
|
|
|
+ versionBox.append(versionHead, files);
|
|
|
+ versions.appendChild(versionBox);
|
|
|
+ }
|
|
|
+ card.appendChild(versions);
|
|
|
+ container.appendChild(card);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ async function openResourceCategory(name) {
|
|
|
+ state.resources.activeCategory = name;
|
|
|
+ renderResourceCategories();
|
|
|
+ const result = await api.runCliJson(['resource', 'list', name]);
|
|
|
+ if (!result?.ok) throw new Error(result?.error || '读取分类失败');
|
|
|
+ const detail = result.data;
|
|
|
+ state.resources.detail = detail;
|
|
|
+ $('#res-title').textContent = `${detail.name || name} · ${detail.desc || ''}`;
|
|
|
+ renderResourceDetail(detail);
|
|
|
+ }
|
|
|
+
|
|
|
+ async function downloadResource(category, sub, item, label) {
|
|
|
+ if (state.resources.busy) {
|
|
|
+ toast('已有下载任务正在运行', 'warn');
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ const output = state.resources.output;
|
|
|
+ state.resources.busy = true;
|
|
|
+ resClearLog();
|
|
|
+ setResProgress(0, `准备下载 ${label}`, `目标目录:${output}`);
|
|
|
+ try {
|
|
|
+ const args = ['resource', 'download', category, sub];
|
|
|
+ if (item) args.push(item);
|
|
|
+ args.push('--output', output);
|
|
|
+ const result = await api.startCliStream('resource', args);
|
|
|
+ if (result?.ok) {
|
|
|
+ toast('资源下载完成', 'ok');
|
|
|
+ } else {
|
|
|
+ toast(result?.error || '资源下载失败', 'err');
|
|
|
+ }
|
|
|
+ } finally {
|
|
|
+ state.resources.busy = false;
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ function bindResourceEvents() {
|
|
|
+ $('#btn-res-refresh').addEventListener('click', () => loadResources().catch((error) => toast(error.message, 'err')));
|
|
|
+ $('#btn-res-choose').addEventListener('click', async () => {
|
|
|
+ const selected = await api.openFolderDialog();
|
|
|
+ if (selected) {
|
|
|
+ state.resources.output = selected;
|
|
|
+ $('#res-output-path').textContent = selected;
|
|
|
+ toast('下载目录已更新', 'ok');
|
|
|
+ }
|
|
|
+ });
|
|
|
+ $('#btn-res-output').addEventListener('click', async () => {
|
|
|
+ const paths = await ensurePaths();
|
|
|
+ await api.revealPath(state.resources.output || paths.resources);
|
|
|
+ });
|
|
|
+
|
|
|
+ api.onCliEvent('resource', (event) => {
|
|
|
+ if (!event || typeof event !== 'object') return;
|
|
|
+ if (event.type === 'resource_download') {
|
|
|
+ if (event.event === 'start_file') {
|
|
|
+ const index = Number(event.index || 0) + 1;
|
|
|
+ const total = Number(event.total || 1);
|
|
|
+ state.resources.currentSize = Number(event.size || 0);
|
|
|
+ setResProgress(0, `[${index}/${total}] ${event.filename}`, `开始下载 ${event.filename}(${formatSize(event.size)})`);
|
|
|
+ } else if (event.event === 'progress') {
|
|
|
+ const total = state.resources.currentSize || 1;
|
|
|
+ setResProgress((Number(event.downloaded || 0) / total) * 100, '', '');
|
|
|
+ } else if (event.event === 'verified') {
|
|
|
+ setResProgress(100, '', `SHA256 校验通过:${event.filename}`);
|
|
|
+ } else if (event.event === 'extracted') {
|
|
|
+ resLog(`已解压:${event.filename} → ${event.dest_dir}`, 'ok');
|
|
|
+ } else if (event.event === 'file_failed') {
|
|
|
+ resLog(`下载失败:${event.filename}`, 'err');
|
|
|
+ } else if (event.event === 'hash_mismatch') {
|
|
|
+ resLog(`SHA256 不匹配:${event.filename}`, 'err');
|
|
|
+ } else if (event.event === 'mirror_failed') {
|
|
|
+ resLog(`镜像失败:${event.mirror_url}(${event.filename})`, 'warn');
|
|
|
+ }
|
|
|
+ } else if (event.type === 'message') {
|
|
|
+ resLog(event.message || '', event.level === 'error' ? 'err' : event.level === 'warn' ? 'warn' : 'info');
|
|
|
+ } else if (event.type === 'error') {
|
|
|
+ resLog(event.message || '下载错误', 'err');
|
|
|
+ } else if (event.type === 'result') {
|
|
|
+ resLog(`下载结束:${event.status}`, event.status === 'ok' ? 'ok' : 'warn');
|
|
|
+ }
|
|
|
+ });
|
|
|
+ api.onCliLine('resource', ({ line, source }) => {
|
|
|
+ if (line) resLog(line, source === 'stderr' ? 'muted' : 'info');
|
|
|
+ });
|
|
|
+ api.onCliExit('resource', ({ code, signal, error }) => {
|
|
|
+ if (error) resLog(error, 'err');
|
|
|
+ else resLog(`下载进程结束(code=${code}${signal ? `, signal=${signal}` : ''})`, code === 0 ? 'ok' : 'err');
|
|
|
+ });
|
|
|
+ }
|
|
|
+
|
|
|
+ /* ── MCP ────────────────────────────────────────────────────── */
|
|
|
+
|
|
|
+ const MCP_TOOL_NAMES = [
|
|
|
+ 'serial_list',
|
|
|
+ 'guide_models',
|
|
|
+ 'firmware_info',
|
|
|
+ 'flash_firmware',
|
|
|
+ 'resource_list',
|
|
|
+ 'resource_download',
|
|
|
+ 'project_list',
|
|
|
+ 'project_create',
|
|
|
+ 'project_import',
|
|
|
+ 'project_info',
|
|
|
+ 'project_config',
|
|
|
+ 'project_analyze',
|
|
|
+ 'project_prepare',
|
|
|
+ 'project_build',
|
|
|
+ 'project_export',
|
|
|
+ 'project_deps',
|
|
|
+ 'app_paths',
|
|
|
+ ];
|
|
|
+
|
|
|
+ async function loadMcp() {
|
|
|
+ const result = await api.mcpInfo();
|
|
|
+ state.mcp = result;
|
|
|
+ const config = $('#mcp-config');
|
|
|
+ const status = $('#mcp-status');
|
|
|
+ const tools = $('#mcp-tools');
|
|
|
+
|
|
|
+ tools.textContent = '';
|
|
|
+ for (const name of MCP_TOOL_NAMES) {
|
|
|
+ const chip = document.createElement('span');
|
|
|
+ chip.className = 'mcp-tool';
|
|
|
+ chip.textContent = name;
|
|
|
+ tools.appendChild(chip);
|
|
|
+ }
|
|
|
+
|
|
|
+ if (!result?.ok) {
|
|
|
+ status.textContent = '未找到 MCP 脚本';
|
|
|
+ config.textContent = '请确认 App 包内的 Resources/mcp/luatos-mcp.mjs 存在,或重新构建。';
|
|
|
+ $('#mcp-script').textContent = result?.script || '—';
|
|
|
+ $('#mcp-cli').textContent = result?.cli || '—';
|
|
|
+ return;
|
|
|
+ }
|
|
|
+
|
|
|
+ status.textContent = result.node ? `Node ${result.node}` : '未检测到 node';
|
|
|
+ config.textContent = JSON.stringify(result.config, null, 2);
|
|
|
+ $('#mcp-script').textContent = result.script || '—';
|
|
|
+ $('#mcp-cli').textContent = result.cli || '—';
|
|
|
+ }
|
|
|
+
|
|
|
+ async function copyMcpConfig() {
|
|
|
+ const text = $('#mcp-config').textContent;
|
|
|
+ if (!text) return;
|
|
|
+ try {
|
|
|
+ await navigator.clipboard.writeText(text);
|
|
|
+ toast('MCP 配置已复制', 'ok');
|
|
|
+ } catch {
|
|
|
+ const area = document.createElement('textarea');
|
|
|
+ area.value = text;
|
|
|
+ document.body.appendChild(area);
|
|
|
+ area.select();
|
|
|
+ document.execCommand('copy');
|
|
|
+ area.remove();
|
|
|
+ toast('MCP 配置已复制', 'ok');
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ /* ── Init ───────────────────────────────────────────────────── */
|
|
|
+
|
|
|
+ function init() {
|
|
|
+ $$('#tabs .tab').forEach((tab) => {
|
|
|
+ tab.addEventListener('click', () => showView(tab.dataset.view));
|
|
|
+ });
|
|
|
+ bindProjectEvents();
|
|
|
+ bindResourceEvents();
|
|
|
+ $('#btn-mcp-copy').addEventListener('click', () => copyMcpConfig().catch((error) => toast(error.message, 'err')));
|
|
|
+ $('#btn-mcp-refresh').addEventListener('click', () => loadMcp().catch((error) => toast(error.message, 'err')));
|
|
|
+
|
|
|
+ document.addEventListener('keydown', (event) => {
|
|
|
+ if (event.key === 'Escape') {
|
|
|
+ $('#project-modal')?.classList.add('hidden');
|
|
|
+ }
|
|
|
+ });
|
|
|
+ }
|
|
|
+
|
|
|
+ init();
|
|
|
+})();
|