1780 lines
120 KiB
JavaScript
1780 lines
120 KiB
JavaScript
// JumPHP IDE: the workbench. Loads Monaco, opens the project (desktop: the welcome screen first; web: the project of
|
||
// the page), lays out the tool windows (Project, Commit, Structure / Run, Find, Problems, Git), and binds PhpStorm's
|
||
// keyboard shortcuts to the IDE's actions.
|
||
import { backend } from './backend.js';
|
||
import { openShareDialog } from './remote-share.js';
|
||
import { openScreenDialog } from './screen-share.js';
|
||
import { openBugReport } from './bugreport.js';
|
||
import { zoom } from './zoom.js';
|
||
import { layoutKey, serialize, migrate, restore as restoreLayoutRecord, createSaver } from './layout.js';
|
||
import { uiLang, t, el, clear, icon, hydrateIcons, progressBar, menu, chooser, dialog, confirm, copyText, languageSelect, notify, notificationHistory, splitter, prefs, debounce, kbd, basename, timeAgo } from './ui.js';
|
||
import { Editors, loadMonaco, monaco } from './editor.js';
|
||
import { ProjectTree } from './tree.js';
|
||
import { Plugins } from './plugins.js';
|
||
import { Extensions } from './extensions.js';
|
||
import { ExtensionDocs } from './extension-docs.js';
|
||
import { LocalAi } from './local-ai.js';
|
||
import { VideoPreview } from './video-preview.js';
|
||
import { WhatsNew } from './whats-new.js';
|
||
import { LogsPanel } from './logs.js';
|
||
import { searchEverywhere, recentFiles, fileStructure, FindPanel } from './search.js';
|
||
import { CallsPanel } from './calls.js';
|
||
import { LANGUAGE_CHOICES, VIEW_CHOICES, mediaElement, readAll } from './filetype.js';
|
||
import { RecentChangesPanel } from './recent.js';
|
||
import { Git } from './git.js';
|
||
import { svnActions } from './vcs.js';
|
||
import { LiveReload } from './live-reload.js';
|
||
import { Runner, Problems, Structure, Hierarchy } from './run.js';
|
||
import { Welcome } from './welcome.js';
|
||
import { GamePanel } from './game.js';
|
||
import { PublishPanel } from './publish.js';
|
||
import { createInstaller } from './installer.js';
|
||
import { ClaudePanel } from './claude.js';
|
||
import { DebugPanel } from './debug.js';
|
||
import { ProfilerPanel } from './profiler.js';
|
||
import { CryoPanel } from './cryo.js';
|
||
import { ComposerPanel } from './composer.js';
|
||
import { SymfonyConsolePanel } from './symfony-console.js';
|
||
import { SymfonyFormsPanel } from './symfony-forms.js';
|
||
import { ValidationPanel } from './symfony-validation.js';
|
||
import { SecurityPanel } from './symfony-security.js';
|
||
import { EventsPanel } from './symfony-events.js';
|
||
import { MessengerPanel } from './messenger.js';
|
||
import { TranslationsPanel } from './translations.js';
|
||
import { SecurityAuditPanel } from './security-audit.js';
|
||
import { ScriptsPanel } from './scripts.js';
|
||
import { openSymfonyWizard } from './command-wizard.js';
|
||
import { TestsPanel } from './tests.js';
|
||
import { httpTools } from './http-client-boot.js';
|
||
import { DockerPanel } from './docker.js';
|
||
import { SshPanel } from './ssh.js';
|
||
import { Database } from './db.js';
|
||
import { DoctrinePanel } from './doctrine.js';
|
||
import { SchemaCheck } from './schema-check.js';
|
||
import { ApiPlatformPanel } from './api-platform.js';
|
||
import { CpcPanel } from './cpc.js';
|
||
import { CommunityPanel } from './community.js';
|
||
import { BoardPanel } from './board.js';
|
||
import { GutterRun } from './gutter-run.js';
|
||
import { TerminalPanel } from './terminal.js';
|
||
import { showLocalHistory } from './localhistory.js';
|
||
import { DocsBrowser } from './docs-browser.js';
|
||
import { TutorialManager } from './tutorial/tutorial.js';
|
||
import { openNewHub, registerHubActions } from './new-hub.js';
|
||
import { openVcsSetup, openRemotes } from './vcs-setup.js';
|
||
|
||
const $ = (id) => document.getElementById(id);
|
||
|
||
class Actions {
|
||
constructor() { this.items = new Map(); }
|
||
add(id, label, run, { kbd: keys, icon: ico, when } = {}) { this.items.set(id, { id, label, run, kbd: keys, icon: ico, when }); }
|
||
run(id) { const a = this.items.get(id); if (a && (!a.when || a.when())) a.run(); }
|
||
list() { return [...this.items.values()].filter((a) => !a.when || a.when()); }
|
||
}
|
||
|
||
class App {
|
||
constructor() {
|
||
this.actions = new Actions();
|
||
this.outlineCache = new Map();
|
||
this.tools = {};
|
||
this.project = null;
|
||
this.projectKey = '';
|
||
this.tasks = new Set();
|
||
this.tutorial = new TutorialManager(this); // the interactive tutorials (Help > Symfony tutorial, the Welcome screen, Search Everywhere)
|
||
}
|
||
|
||
async start() {
|
||
window.ideBootStarted?.();
|
||
zoom.use(prefs, t); // Ctrl + wheel / Ctrl+= / Ctrl+- / Ctrl+0 over a panel: its font size (zoom.js)
|
||
// Ctrl + Shift + wheel: the whole IDE, the desktop WebView's own zoom (CSS zoom in a browser)
|
||
if (window.jumphp?.native) zoom.useNative((scale) => backend.invoke('window.zoom', { scale })); else zoom.applyNow('ui');
|
||
hydrateIcons();
|
||
// the browser's own context menu never shows over the IDE (the IDE has its menus), but in text fields
|
||
document.addEventListener('contextmenu', (e) => { if (!e.target.closest('input, textarea, .claude-log, .console, .game-log')) e.preventDefault(); });
|
||
// the mouse's back / forward buttons (3 / 4): Navigate > Back / Forward (the last positions, file to file), never
|
||
// the page's own history (the WebView would leave the IDE)
|
||
const side = (e) => e.button === 3 || e.button === 4;
|
||
window.addEventListener('mousedown', (e) => { if (side(e)) e.preventDefault(); }, true);
|
||
window.addEventListener('mouseup', (e) => {
|
||
if (!side(e)) return;
|
||
e.preventDefault();
|
||
e.stopPropagation();
|
||
if (e.button === 3) this.editors?.back(); else this.editors?.forward();
|
||
}, true);
|
||
document.documentElement.dataset.theme = prefs.get('theme', 'dark');
|
||
// a Claude conversation in a window of its own (Open in a Window): that page shows only it
|
||
const claudeWindow = new URLSearchParams(location.search).get('claude');
|
||
if (claudeWindow) { await this.startClaudeWindow(claudeWindow); return; }
|
||
try {
|
||
await loadMonaco();
|
||
} catch (e) {
|
||
document.body.append(el('div.placeholder', {}, 'The editor could not load: ' + e.message));
|
||
return;
|
||
}
|
||
this.bindKeys();
|
||
this.bindHeader();
|
||
backend.on('index.progress', (p) => this.indexProgress(p));
|
||
// vendor/ changed (composer require / remove, outside or from the IDE): re-indexing starts, then the open files are checked again
|
||
backend.on('index.libraries', (p) => notify(t('Libraries changed: re-indexing… ({n} packages)', { n: p.packages ?? 0 }), 'info', { timeout: 4000 }));
|
||
backend.on('index.changed', () => this.diagnoseOpenFiles());
|
||
// the language of the texts the PHP side shows (errors, notices): now, and each time it is chosen again
|
||
this.sendLanguage();
|
||
backend.on('ide.error', (p) => notify(`${p.message} (${p.at})`, 'error', { title: `${p.where}: an error` }));
|
||
backend.on('files.changed', debounce(() => { this.tree?.refresh(); this.git?.refresh(); this.editors?.reloadFromDisk(); }, 300));
|
||
backend.on('project.closed', () => location.reload());
|
||
// a file of this project given by another jumphp-ide <file> ("Open with JumPHP"): opened here
|
||
backend.on('link.open', (p) => this.editors?.open(p.path).catch((e) => notify(String(e.message || e), 'error')));
|
||
// a generated sound or other file the editors want shown (res-ai.js)
|
||
document.addEventListener('jumphp:open-file', (e) => this.editors?.open(e.detail?.path));
|
||
backend.on('bridge.status', (st) => this.bridgeStatus(st));
|
||
if (backend.kind === 'native') backend.invoke('bridge.status').then((st) => this.bridgeStatus(st)).catch(() => null);
|
||
if (backend.kind === 'native') {
|
||
backend.on('update.state', (st) => this.updateState(st));
|
||
backend.invoke('update.state').then((st) => this.updateState(st)).catch(() => null);
|
||
}
|
||
if (backend.kind === 'native') {
|
||
const state = await backend.invoke('session.state');
|
||
this.session = state;
|
||
if (state.project) await this.projectOpened(state.project, false);
|
||
else { this.welcome = new Welcome(this, $('welcome')); await this.welcome.show(); }
|
||
} else {
|
||
await this.projectOpened(await backend.invoke('project.info'), false);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* The page of a window that shows one Claude conversation: its log and its box, nothing else. The files it names open
|
||
* in the main window (ui.broadcast); closing the window brings the conversation back into the Claude window there.
|
||
*/
|
||
async startClaudeWindow(key) {
|
||
const state = await backend.invoke('session.state').catch(() => null);
|
||
if (!state?.project) { document.body.replaceChildren(el('div.placeholder', {}, 'No project is open.')); return; }
|
||
this.project = state.project;
|
||
this.projectKey = state.project.root || state.project.name;
|
||
this.task = undefined; // no status bar here
|
||
this.showTool = () => {};
|
||
const panel = this.claude = new ClaudePanel(this, { detached: key });
|
||
const actions = el('div.tw-actions', {}, ...panel.actions());
|
||
this.refreshToolHeader = () => actions.replaceChildren(...panel.actions());
|
||
document.body.replaceChildren(el('div.claude-window', {},
|
||
el('div.tw-header', {}, panel.headerExtra(), el('span.tw-spacer'), actions),
|
||
el('div.tw-body', { dataset: { zoom: 'claude' } }, panel.node)), el('div', { id: 'overlays' }));
|
||
zoom.define('claude', { kind: 'pct', label: 'Claude' });
|
||
zoom.applyNow('claude');
|
||
hydrateIcons();
|
||
}
|
||
|
||
/**
|
||
* The signed-in user as the computer knows it now. app.session was read once at start: signing out and in on the welcome screen (or in the
|
||
* account menu) left it stale, and the project opened next showed "not signed in".
|
||
*/
|
||
async refreshSession() {
|
||
if (backend.kind !== 'native') return;
|
||
const state = await backend.invoke('session.state').catch(() => null);
|
||
if (state) this.session = { ...(this.session || {}), user: state.user, server: state.server };
|
||
if (this.project) this.updateHeader();
|
||
}
|
||
|
||
/** A project was opened (the welcome screen, or a reload): build the workbench for it. */
|
||
async projectOpened(info, fresh = true) {
|
||
await this.refreshSession();
|
||
if (fresh && this.project) { location.reload(); return; }
|
||
if (this.project && fresh) return;
|
||
this.project = info;
|
||
this.projectKey = info.root || info.name;
|
||
this.welcome?.hide();
|
||
document.title = `${info.name} – JumPHP IDE`;
|
||
$('projectName').textContent = info.name;
|
||
$('projectLetter').textContent = (info.name[0] || 'J').toUpperCase();
|
||
this.editors = new Editors($('editors'), this);
|
||
await this.editors.init();
|
||
this.editors.on('active', (tab) => this.activeChanged(tab));
|
||
this.editors.on('cursor', (pos) => { const s = `${pos.lineNumber}:${pos.column}`; const n = $('sbPosition'); if (n.textContent !== s) n.textContent = s; });
|
||
this.editors.on('dirty', (path) => { if (path.endsWith('.php')) this.diagnose(path); else if (/\.ya?ml$/i.test(path)) this.diagnoseYaml(path, true); });
|
||
this.editors.on('active', (tab) => { if (tab?.kind === 'text' && /\.ya?ml$/i.test(tab.path || '')) this.diagnoseYaml(tab.path); });
|
||
this.editors.on('saved', () => this.git?.refreshSoon());
|
||
this.tree = new ProjectTree(this);
|
||
this.git = new Git(this);
|
||
this.git.refreshSoon = debounce(() => this.git.refresh(), 800);
|
||
this.runner = new Runner(this);
|
||
if (this.project.capabilities?.run && this.project.capabilities?.debug) this.debugger = new DebugPanel(this);
|
||
if (this.project.capabilities?.run && this.project.capabilities?.profile) this.profiler = new ProfilerPanel(this);
|
||
if (this.project.capabilities?.run && this.project.capabilities?.cryo) this.cryo = new CryoPanel(this);
|
||
if (this.project.capabilities?.run && this.project.capabilities?.composer) this.composer = new ComposerPanel(this);
|
||
// bin/console (Symfony) or artisan (Laravel): the Console window (ide/src/Symfony/ConsoleCommands.php)
|
||
if (this.project.capabilities?.run && this.project.capabilities?.console) this.symfonyConsole = new SymfonyConsolePanel(this);
|
||
// Symfony Forms: the FormTypes edited visually, previewed, their controller / template generated (ide/src/Symfony/Form*.php)
|
||
if (this.project.capabilities?.symfonyForms) this.symfonyForms = new SymfonyFormsPanel(this);
|
||
// Symfony validation constraints and security.yaml as forms (ide/src/Symfony/Validation*.php, Security*.php)
|
||
if (this.project.capabilities?.validation) this.validationPanel = new ValidationPanel(this);
|
||
if (this.project.capabilities?.security) this.securityPanel = new SecurityPanel(this);
|
||
// Symfony: the Events window (subscribers, listeners, the project's events) and the Messenger window (workers, queues, transports, messages)
|
||
if (this.project.capabilities?.run && this.project.capabilities?.symfonyEvents) this.symfonyEvents = new EventsPanel(this);
|
||
if (this.project.capabilities?.run && this.project.capabilities?.messenger) this.messenger = new MessengerPanel(this);
|
||
// the Translations window: keys × languages of the catalogues (Symfony, JumPHP lang.yaml, Laravel), AI translations (ide/src/Translations)
|
||
if (this.project.capabilities?.translations) this.translations = new TranslationsPanel(this);
|
||
// the Security Audit window: checks, AI review, patches, exploit proofs against the local site only (ide/src/Audit)
|
||
if (this.project.capabilities?.securityAudit) this.securityAudit = new SecurityAuditPanel(this);
|
||
if (this.project.capabilities?.run && backend.kind === 'native') this.dockerPanel = new DockerPanel(this);
|
||
// the project's own scripts and its Make / Castor / composer / npm tasks (ide/src/Scripts): tool bar pins, shortcuts, events
|
||
if (this.project.capabilities?.run && this.project.capabilities?.scripts) this.scripts = new ScriptsPanel(this);
|
||
// the SSH window (servers, sessions in the terminal, remote files with scp): ide/src/Ssh/SshCommands.php
|
||
if (this.project.capabilities?.ssh) this.sshPanel = new SshPanel(this);
|
||
// the Database window and SQL Results (the project's databases, SQL consoles in the editor): ide/src/Database
|
||
if (this.project.capabilities?.database) this.database = new Database(this);
|
||
// Doctrine ORM: the entities' diagram and editor, DQL, migrations (ide/src/Doctrine)
|
||
if (this.project.capabilities?.doctrine) { this.doctrine = new DoctrinePanel(this); this.schemaCheck = new SchemaCheck(this); }
|
||
// API Platform: #[ApiResource] and its options, groups, filters, State classes, HTTP Client requests (ide/src/ApiPlatform)
|
||
if (this.project.capabilities?.apiplatform) this.apiPlatform = new ApiPlatformPanel(this);
|
||
if (this.project.capabilities?.run && this.project.capabilities?.cryo) this.cpc = new CpcPanel(this); // Amstrad CPC remakes (dsk2jumphp)
|
||
// the Tests window (ide/src/UnitTests): the project's tests as a tree, runs, results, coverage in the gutter
|
||
if (this.project.capabilities?.run && this.project.capabilities?.unitTests) this.tests = new TestsPanel(this);
|
||
// the HTTP Client and the OpenAPI viewer (ide/src/HttpClient), loaded the first time they are shown
|
||
if (this.project.capabilities?.httpClient) ({ client: this.httpClient, openapi: this.openApi } = httpTools(this));
|
||
if (this.project.capabilities?.run) this.gutterRun = new GutterRun(this);
|
||
this.extensionDocs = new ExtensionDocs(this);
|
||
this.docs = new DocsBrowser(this); // the IDE's own documentation (docs/ide/): the Doc button, Help > Documentation, the "?" of tool windows
|
||
if (this.project.capabilities?.run) this.extensions = new Extensions(this);
|
||
this.localAi = new LocalAi(this);
|
||
this.videoPreview = new VideoPreview(this);
|
||
this.whatsNew = new WhatsNew(this);
|
||
// the chat of jumphp.net and its forum (desktop IDE: the IDE's account)
|
||
if (backend.kind === 'native') this.community = new CommunityPanel(this);
|
||
// the Board: Kanban, notes, overview (.jumphp/board.json, or jumphp.net's board of a linked project): board.js
|
||
if (backend.kind === 'native' && this.project.capabilities?.board) this.board = new BoardPanel(this);
|
||
if (this.project.capabilities?.logs && backend.kind === 'native') this.logsPanel = new LogsPanel(this);
|
||
if (this.updates?.current && !this.whatsNewChecked) { this.whatsNewChecked = true; this.whatsNew.check(this.updates.current); }
|
||
this.problems = new Problems(this);
|
||
this.structure = new Structure(this);
|
||
this.hierarchy = new Hierarchy(this);
|
||
this.calls = new CallsPanel(this); // who calls a method (the editor's "↳ calls" lens)
|
||
this.find = new FindPanel(this);
|
||
this.recent = new RecentChangesPanel(this);
|
||
if (this.project.capabilities?.preview) this.game = new GamePanel(this);
|
||
if (this.project.capabilities?.claude) this.claude = new ClaudePanel(this);
|
||
if (this.project.capabilities?.terminal) this.terminal = new TerminalPanel(this);
|
||
if (backend.kind === 'native' && this.project.playground) this.publishPanel = new PublishPanel(this);
|
||
// the web IDE: plugins run in the visitor's browser when jumphp.net serves their PHP core (backend.config.plugins)
|
||
if (this.project.capabilities?.plugins || (backend.kind !== 'native' && backend.config.plugins)) {
|
||
this.plugins = new Plugins(this);
|
||
await this.plugins.load();
|
||
}
|
||
this.console = { append: (source, text) => { if (this.gitConsole) this.gitConsole.textContent += text; } };
|
||
this.registerTools();
|
||
this.registerActions();
|
||
this.layoutTools();
|
||
this.cpc?.check(); // a disc or tools/extract in the project: the Amstrad CPC window joins the stripe
|
||
await this.tree.refresh();
|
||
await this.git.refresh();
|
||
this.updateHeader();
|
||
this.updateRunWidget();
|
||
this.restoreLayout();
|
||
this.docker(); // in the background: Docker Desktop started if needed, before the first run asks for it
|
||
this.updateJumphp(); // the project's JumPHP as new as the IDE (bin/jumphp, engine...; games/ and apps/ never touched)
|
||
// a project made before New Project created repositories: its own GitHub repository, then jumphp.net
|
||
// (a new project is made on this computer only: nothing is online until the user publishes; said once per project)
|
||
if (backend.kind === 'native' && info.needsRepository && !prefs.get('repoHint:' + this.projectKey, false)) {
|
||
prefs.set('repoHint:' + this.projectKey, true);
|
||
notify('This project is on this computer only. Publish (or “Create its Git repository”) puts it on your Git account and on jumphp.net when you want.', 'info',
|
||
{ title: 'Local project', timeout: 0, actions: [{ label: 'Create its Git repository…', action: () => this.createRepository() }, { label: 'Later', action: () => null }] });
|
||
}
|
||
if (backend.kind === 'native' && info.needsPlayground && !prefs.get('playgroundHint:' + this.projectKey, false)) {
|
||
prefs.set('playgroundHint:' + this.projectKey, true);
|
||
notify('This project is on Git but not on jumphp.net: there is nothing to publish from here yet.', 'info',
|
||
{ title: 'jumphp.net', timeout: 0, actions: [{ label: 'Put it on jumphp.net…', action: () => this.putOnPlayground() }, { label: 'Later', action: () => null }] });
|
||
}
|
||
this.tutorial.projectOpened(info); // resumes a tutorial running on this project, or offers the Symfony one after a new Symfony project
|
||
// a served web site: the live reload's state in the status bar (browser tabs connected), open the site, turn it off
|
||
if (this.project.capabilities?.webLive && backend.kind === 'native') this.live = new LiveReload(this);
|
||
setInterval(() => { if (document.visibilityState === 'visible') this.git.refresh(); }, 15000);
|
||
window.addEventListener('focus', () => { this.git.refresh(); this.editors.reloadFromDisk(); this.tree.refresh(); });
|
||
window.addEventListener('beforeunload', () => { this.saveTabs(); this.layoutSaver?.flush(); });
|
||
window.addEventListener('pagehide', () => this.layoutSaver?.flush());
|
||
document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'hidden') this.layoutSaver?.flush(); });
|
||
}
|
||
|
||
// tool windows --------------------------------------------------------------------------------------------
|
||
|
||
registerTools() {
|
||
const caps = this.project.capabilities || {};
|
||
const T = (id, side, label, ico, view, key) => { this.tools[id] = { id, side, label, icon: ico, view, key }; };
|
||
T('project', 'left', 'Project', 'folder', this.tree, 'Alt+1');
|
||
if (caps.git || caps.vcs === 'svn') T('commit', 'left', 'Commit', 'commit', { title: () => 'Commit', node: this.git.commitNode, actions: () => [] }, 'Alt+0');
|
||
T('structure', 'left', 'Structure', 'structure', this.structure, 'Alt+7');
|
||
T('hierarchy', 'left', 'Hierarchy', 'hierarchy', this.hierarchy, 'Ctrl+H');
|
||
T('calls', 'bottom', 'Calls', 'hierarchy', this.calls, null);
|
||
T('recent', 'left', 'Recently Changed', 'history', this.recent, 'Ctrl+Shift+E');
|
||
if (caps.run || caps.tests) T('run', 'bottom', 'Run', 'play', this.runner, 'Alt+4');
|
||
if (this.debugger) T('debug', 'bottom', 'Debug', 'debug', this.debugger, null);
|
||
if (this.profiler) T('profile', 'right', 'Profiler', 'profile', this.profiler, 'Alt+P');
|
||
if (this.cryo) T('cryo', 'right', 'Cryo', 'snowflake', this.cryo, null);
|
||
if (this.composer) T('composer', 'right', 'Composer', 'package', this.composer, null);
|
||
if (this.scripts) T('scripts', 'right', 'Scripts', 'zap', this.scripts, null);
|
||
if (this.tests) T('tests', 'bottom', 'Tests', 'test', this.tests, null);
|
||
if (this.httpClient) T('httpClient', 'bottom', 'HTTP Client', 'globe', this.httpClient, null);
|
||
if (this.openApi) T('openapi', 'right', 'OpenAPI', 'library', this.openApi, null);
|
||
if (this.dockerPanel) T('docker', 'right', 'Docker', 'container', this.dockerPanel, null);
|
||
if (this.sshPanel) T('ssh', 'right', 'SSH', 'server', this.sshPanel, null);
|
||
if (this.database) T('database', 'right', 'Database', 'database', this.database.panel, null);
|
||
if (this.database) T('dbresults', 'bottom', 'SQL Results', 'database', this.database.results, null);
|
||
if (this.doctrine) T('doctrine', 'bottom', 'Doctrine', 'hierarchy', this.doctrine, null);
|
||
if (this.apiPlatform) T('apiplatform', 'bottom', 'API Platform', 'structure', this.apiPlatform, null);
|
||
if (this.cpc && (this.project.modules || []).some((m) => m.kind === 'cpc')) T('cpc', 'right', 'Amstrad CPC', 'disk', this.cpc, null);
|
||
if (this.community) T('community', 'right', 'Community', 'user', this.community, null);
|
||
if (this.board) T('board', 'right', 'Board', 'board', this.board, null);
|
||
T('find', 'bottom', 'Find', 'find', this.find, 'Alt+3');
|
||
T('problems', 'bottom', 'Problems', 'problems', this.problems, 'Alt+6');
|
||
if (this.terminal) T('terminal', 'bottom', 'Terminal', 'terminal', this.terminal, 'Alt+F12');
|
||
// Symfony / Laravel: the console's commands as forms, on the right beside Composer (one click from the tool bar)
|
||
if (this.symfonyConsole) T('console', 'right', this.symfonyConsole.title(), 'console', this.symfonyConsole, 'Alt+S');
|
||
if (this.symfonyForms) T('sfForms', 'right', 'Symfony Forms', 'design', this.symfonyForms, null);
|
||
if (this.validationPanel) T('validation', 'right', 'Validation', 'check', this.validationPanel, null);
|
||
if (this.securityPanel) T('security', 'right', 'Security', 'user', this.securityPanel, null);
|
||
if (this.symfonyEvents) T('sfEvents', 'right', 'Events', 'bell', this.symfonyEvents, null);
|
||
if (this.messenger) T('messenger', 'right', 'Messenger', 'cast', this.messenger, null);
|
||
if (this.translations) T('translations', 'bottom', 'Translations', 'globe', this.translations, null);
|
||
if (this.securityAudit) T('audit', 'bottom', 'Security Audit', 'bug', this.securityAudit, null);
|
||
if (this.logsPanel) T('logs', 'bottom', 'Logs', 'logfile', this.logsPanel, 'Alt+F11');
|
||
if (this.game) T('game', prefs.get('gameSide', 'right'), 'Game', 'game', this.game, 'Alt+5');
|
||
if (this.claude) T('claude', 'right', 'Claude', 'claude', this.claude, 'Alt+8');
|
||
if (this.publishPanel) T('publish', 'right', 'jumphp.net', 'globe', this.publishPanel, 'Alt+J');
|
||
this.plugins?.registerTools(T);
|
||
for (const id of Object.keys(this.tools)) if (!['game', 'terminal', 'commit'].includes(id)) zoom.define(id, { kind: 'pct', label: this.tools[id].label }); // the Terminal defines its own (px)
|
||
if (caps.log) T('git', 'bottom', 'Git', 'log', { title: () => 'Git', node: this.git.logNode, actions: () => [el('button', { title: 'Refresh', onclick: () => this.git.showLog() }, icon('refresh'))] }, 'Alt+9');
|
||
}
|
||
|
||
layoutTools() {
|
||
this.renderStripes();
|
||
const root = document.documentElement;
|
||
for (const v of ['--left-width', '--bottom-height', '--right-width']) { const saved = prefs.get('size' + v); if (saved) root.style.setProperty(v, saved); }
|
||
splitter($('leftSplitter'), '--left-width', { min: 160, max: 700, onEnd: () => prefs.set('size--left-width', getComputedStyle(root).getPropertyValue('--left-width')) });
|
||
splitter($('bottomSplitter'), '--bottom-height', { axis: 'y', invert: true, min: 90, max: innerHeight - 160, onEnd: () => prefs.set('size--bottom-height', getComputedStyle(root).getPropertyValue('--bottom-height')) });
|
||
splitter($('rightSplitter'), '--right-width', { invert: true, min: 240, max: innerWidth - 300, onEnd: () => prefs.set('size--right-width', getComputedStyle(root).getPropertyValue('--right-width')) });
|
||
this.open = { left: null, bottom: null, right: null };
|
||
this.showTool(prefs.get('tool:left', 'project'), true);
|
||
const bottom = prefs.get('tool:bottom', null);
|
||
if (bottom && this.tools[bottom]) this.showTool(bottom, true); else this.closeSide('bottom');
|
||
this.closeSide('right');
|
||
}
|
||
|
||
/** The tool window buttons, on the left (left and bottom tools) and the right stripe. */
|
||
renderStripes() {
|
||
const left = $('leftStripe');
|
||
const right = $('rightStripe');
|
||
clear(left);
|
||
clear(right);
|
||
const button = (tool) => {
|
||
const b = el('button', { title: `${t(tool.label)} (${kbd(tool.key)})`, dataset: { tool: tool.id, tour: 'tool-' + tool.id }, onclick: () => this.toggleTool(tool.id) }, icon(tool.icon));
|
||
tool.button = b;
|
||
b.classList.toggle('on', this.open?.[tool.side] === tool.id);
|
||
return b;
|
||
};
|
||
for (const t of Object.values(this.tools).filter((t) => t.side === 'left')) left.append(button(t));
|
||
left.append(el('div.sep'));
|
||
for (const t of Object.values(this.tools).filter((t) => t.side === 'bottom')) left.append(button(t));
|
||
for (const t of Object.values(this.tools).filter((t) => t.side === 'right')) right.append(button(t));
|
||
right.append(el('button', { title: 'Notifications', onclick: () => this.showNotifications() }, icon('bell')));
|
||
}
|
||
|
||
/** Moves a tool window to another side (the Game window: right or bottom), remembered. */
|
||
moveTool(id, side) {
|
||
const tool = this.tools[id];
|
||
if (!tool || tool.side === side) return;
|
||
if (this.open[tool.side] === id) this.closeSide(tool.side);
|
||
tool.header = null;
|
||
tool.side = side;
|
||
if (id === 'game') prefs.set('gameSide', side);
|
||
this.renderStripes();
|
||
this.showTool(id);
|
||
}
|
||
|
||
toggleTool(id) {
|
||
const tool = this.tools[id];
|
||
if (!tool) return;
|
||
if (this.open[tool.side] === id) this.closeSide(tool.side); else this.showTool(id);
|
||
}
|
||
|
||
showTool(id, quiet = false) {
|
||
const tool = this.tools[id];
|
||
if (!tool) return;
|
||
const panel = $(tool.side + 'Panel');
|
||
this.open[tool.side] = id;
|
||
prefs.set('tool:' + tool.side, id);
|
||
this.layoutSaver?.save();
|
||
panel.classList.remove('closed');
|
||
$(tool.side + 'Splitter').classList.remove('hidden');
|
||
const view = tool.view;
|
||
if (id === 'game' && tool.header && panel.contains(tool.header)) {
|
||
// shown again as it was: moving an iframe in the page would reload the game
|
||
for (const t of Object.values(this.tools)) t.button?.classList.toggle('on', this.open[t.side] === t.id);
|
||
this.editors?.layout();
|
||
return;
|
||
}
|
||
clear(panel);
|
||
const node = typeof view.node === 'function' ? view.node() : view.node;
|
||
if (id === 'commit') {
|
||
panel.append(node);
|
||
} else {
|
||
tool.header = el('div.tw-header', {}, el('span.tw-title', {}, t(typeof view.title === 'function' ? view.title() : tool.label)),
|
||
view.headerExtra ? view.headerExtra() : null, el('span.tw-spacer'), el('div.tw-actions', {}, ...(view.actions ? view.actions() : []),
|
||
this.docs?.helpButton(id), el('button', { title: t('Hide'), onclick: () => this.closeSide(tool.side) }, icon('minus'))));
|
||
panel.append(tool.header, el('div.tw-body', { dataset: id === 'game' ? {} : { zoom: id } }, node));
|
||
zoom.applyNow(id);
|
||
}
|
||
for (const t of Object.values(this.tools)) t.button?.classList.toggle('on', this.open[t.side] === t.id);
|
||
if (id === 'structure') this.structure.update();
|
||
if (id === 'hierarchy') this.hierarchy.update();
|
||
if (id === 'git' && !this.git.logNode.firstChild) this.git.showLog();
|
||
if (id === 'problems') this.problems.render();
|
||
view.shown?.();
|
||
if (!quiet && id === 'project') this.tree.node.focus();
|
||
this.editors?.layout();
|
||
}
|
||
|
||
refreshToolHeader(id) {
|
||
const tool = this.tools[id];
|
||
if (!tool?.header || this.open[tool.side] !== id) return;
|
||
const actions = tool.header.querySelector('.tw-actions');
|
||
clear(actions);
|
||
actions.append(...(tool.view.actions ? tool.view.actions() : []), ...[this.docs?.helpButton(id)].filter(Boolean), el('button', { title: t('Hide'), onclick: () => this.closeSide(tool.side) }, icon('minus')));
|
||
}
|
||
|
||
closeSide(side) {
|
||
this.open[side] = null;
|
||
prefs.set('tool:' + side, null);
|
||
this.layoutSaver?.save();
|
||
const panel = $(side + 'Panel');
|
||
panel.classList.add('closed');
|
||
$(side + 'Splitter').classList.add('hidden');
|
||
for (const t of Object.values(this.tools)) t.button?.classList.toggle('on', this.open[t.side] === t.id);
|
||
this.editors?.layout();
|
||
this.editors?.editor()?.focus();
|
||
}
|
||
|
||
badge(id, kind) {
|
||
const b = this.tools[id]?.button;
|
||
if (!b) return;
|
||
b.querySelector('.badge')?.remove();
|
||
if (kind) b.append(el(`span.badge${kind === 'red' ? '.red' : ''}`));
|
||
}
|
||
|
||
// header, status bar -----------------------------------------------------------------------------------------
|
||
|
||
bindHeader() {
|
||
$('mainMenu').addEventListener('click', (e) => this.mainMenu(e.currentTarget));
|
||
$('updateBtn').addEventListener('click', () => this.updateNow());
|
||
$('shareBtn').addEventListener('click', () => openShareDialog(this));
|
||
$('bugBtn').addEventListener('click', () => openBugReport(this));
|
||
if (backend.kind !== 'native') $('shareBtn').hidden = true; // sharing needs the desktop IDE
|
||
$('screenBtn').addEventListener('click', () => openScreenDialog());
|
||
$('screenBtn').hidden = backend.kind !== 'native'; // "screen on a phone" (WebRTC sidecar): the desktop IDE only
|
||
$('screenBtn').title = t('Screen on a phone: see and drive this computer from a phone (WebRTC)');
|
||
$('updateBtn').title = t('Update the IDE now (downloads the newest version, then restarts)');
|
||
// the other titles of the header and the status bar are English in index.html: translated here, once the language is loaded
|
||
for (const node of document.querySelectorAll('header [title], footer [title], .statusbar [title]')) {
|
||
if (node.id === 'updateBtn' || node.id === 'debugBtn') continue;
|
||
node.dataset.title = node.dataset.title || node.getAttribute('title');
|
||
node.title = t(node.dataset.title);
|
||
}
|
||
if (backend.kind !== 'native') $('updateBtn').hidden = true; // the web IDE updates with the site
|
||
$('sbTask').addEventListener('click', (e) => this.showTasks(e.currentTarget));
|
||
$('projectWidget').addEventListener('click', (e) => this.projectMenu(e.currentTarget));
|
||
$('branchWidget').addEventListener('click', (e) => this.git?.branchPopup(e.currentTarget));
|
||
$('sbBranch').addEventListener('click', (e) => this.git?.branchPopup(e.currentTarget));
|
||
$('runConfig').addEventListener('click', (e) => this.runner?.choose(e.currentTarget));
|
||
$('runBtn').addEventListener('click', () => this.actions.run('run'));
|
||
$('debugBtn').addEventListener('click', (e) => (this.debugger ? this.debugger.debugMenu(e.currentTarget) : this.actions.run('debug')));
|
||
$('debugBtn').addEventListener('contextmenu', (e) => { e.preventDefault(); this.debugger?.debugMenu(e.currentTarget); });
|
||
$('testBtn').addEventListener('click', () => this.actions.run('test'));
|
||
$('stopBtn').addEventListener('click', () => this.runner?.stop());
|
||
$('pullBtn').addEventListener('click', () => this.git?.pull());
|
||
$('commitBtn').addEventListener('click', () => this.showTool('commit'));
|
||
$('pushBtn').addEventListener('click', () => this.git?.push());
|
||
$('commitAllBtn').addEventListener('click', () => this.git?.commitAll());
|
||
$('previewBtn').addEventListener('click', () => (this.game ? this.game.play() : this.runner?.preview()));
|
||
$('publishBtn').addEventListener('click', () => this.publish());
|
||
$('searchBtn').addEventListener('click', () => searchEverywhere(this));
|
||
$('docBtn')?.addEventListener('click', () => this.docs.open());
|
||
$('newBtnLabel').textContent = t('New');
|
||
$('newBtn')?.addEventListener('click', (e) => openNewHub(this, e.currentTarget)); // the hub of every create GUI (new-hub.js)
|
||
$('refreshProjectBtn')?.addEventListener('click', () => this.refreshProject());
|
||
$('refreshProjectBtn')?.setAttribute('title', t('Refresh the project: files, Git, Composer, scripts, the PHP index (Ctrl+Alt+Y)'));
|
||
$('settingsBtn').addEventListener('click', () => this.settings());
|
||
$('userWidget').addEventListener('click', (e) => this.userMenu(e.currentTarget));
|
||
$('sbNotifications').addEventListener('click', () => this.showNotifications());
|
||
$('sbReindex')?.addEventListener('click', () => this.reindex());
|
||
$('sbPosition').addEventListener('click', () => this.editors?.editor()?.trigger('', 'editor.action.gotoLine'));
|
||
}
|
||
|
||
updateHeader() {
|
||
const caps = this.project.capabilities || {};
|
||
const svn = caps.vcs === 'svn' && !caps.git; // a Subversion working copy (vcs.js)
|
||
// with no version control the widget stays (a local project) as the way in: "No version control" opens the Git / Subversion / none choice
|
||
const manage = !!caps.vcsManage && backend.kind === 'native';
|
||
$('branchWidget').hidden = caps.git || svn ? !caps.branches : !manage;
|
||
if (!(caps.git || svn) && manage) { $('branchName').textContent = t('No version control'); $('branchWidget').title = t('Choose Git, Subversion or none for this project'); $('sbBranch').textContent = ''; }
|
||
$('gitButtons').hidden = !(caps.git || svn);
|
||
$('pullBtn').hidden = !caps.branches;
|
||
$('pushBtn').hidden = svn;
|
||
$('runWidget').hidden = !(caps.run && this.project.run?.length) && !caps.tests;
|
||
$('runConfig').hidden = !caps.run;
|
||
$('runBtn').hidden = !caps.run;
|
||
$('debugBtn').hidden = !this.debugger;
|
||
$('stopBtn').hidden = !caps.run;
|
||
$('previewBtn').hidden = !caps.preview;
|
||
$('publishBtn').hidden = !(backend.kind === 'native' && (this.project.playground || this.project.needsPlayground || this.project.needsRepository));
|
||
// a project shared with read rights only (the web IDE): said in the status bar, the files open read-only
|
||
let mark = $('sbReadOnly');
|
||
if (caps.readOnly && !mark) {
|
||
mark = el('span.sb-item.sb-readonly', { id: 'sbReadOnly', title: 'This project is shared with you to read: you can open the files, search and run the tests, not change them' }, icon('eye'), 'Read only');
|
||
$('sbBranch').before(mark);
|
||
}
|
||
if (mark) mark.hidden = !caps.readOnly;
|
||
const user = this.session?.user || backend.config.user;
|
||
const widget = $('userWidget');
|
||
clear(widget);
|
||
if (user?.avatar) widget.style.backgroundImage = `url("${user.avatar}")`;
|
||
else widget.append(icon('user'));
|
||
}
|
||
|
||
onGitStatus(status) {
|
||
$('branchName').textContent = status.branch || 'detached';
|
||
$('sbBranch').textContent = status.vcs === 'svn' ? `SVN r${status.revision ?? '?'}${status.branch ? ' · ' + status.branch : ''}` : this.project.capabilities.gitMode === 'drafts' ? `${status.files.length} draft(s)` : (status.branch ? '⎇ ' + status.branch + (status.merging != null ? ' · merging' : '') + (status.ahead ? ` · ${status.ahead}↑` : '') + (status.behind ? ` · ${status.behind}↓` : '') : '');
|
||
$('sbBranch').title = status.ahead ? `${status.ahead} commit${status.ahead > 1 ? 's' : ''} not pushed yet` : 'Git branch';
|
||
this.badge('commit', status.files.length ? 'on' : null);
|
||
for (const g of this.editors.groups) this.editors.renderTabs(g);
|
||
this.tree.render();
|
||
}
|
||
|
||
updateRunWidget() {
|
||
if (!this.runner) return;
|
||
const config = this.runner.config();
|
||
$('runConfigName').textContent = config ? config.label : t('Run');
|
||
$('stopBtn').disabled = !this.runner.isRunning();
|
||
$('runBtn').classList.toggle('active', this.runner.isRunning());
|
||
}
|
||
|
||
/** The status bar's type: a quick selector to read the file as another language, or show it in hexadecimal / as a picture, PDF, film, sound. */
|
||
chooseFileType(at) {
|
||
const tab = this.editors?.activeTab();
|
||
if (!tab?.path || tab.kind === 'diff') return;
|
||
const path = tab.path;
|
||
const model = this.editors.files.get(path)?.model;
|
||
const overrides = prefs.get('langOverride', {});
|
||
const current = model?.getLanguageId();
|
||
const items = [];
|
||
if (model) {
|
||
for (const [id, label] of LANGUAGE_CHOICES) {
|
||
items.push({ label, hint: id === current ? '✓' : '', action: () => {
|
||
monaco.editor.setModelLanguage(model, id);
|
||
prefs.set('langOverride', { ...prefs.get('langOverride', {}), [path]: id });
|
||
if (tab.hex) this.editors.toggleHex(tab, false);
|
||
this.activeChanged(tab);
|
||
} });
|
||
}
|
||
if (overrides[path]) items.push({ label: t('Detect again (by its extension)'), action: () => { const o = { ...prefs.get('langOverride', {}) }; delete o[path]; prefs.set('langOverride', o); notify(t('Reopen the file to detect it again.'), 'info'); } });
|
||
items.push('-');
|
||
}
|
||
for (const [kind, label] of VIEW_CHOICES) {
|
||
items.push({ label, action: async () => {
|
||
if (kind === 'hex') { this.editors.toggleHex(tab, true); return; }
|
||
try {
|
||
const bytes = await readAll((offset, length) => backend.invoke('file.bytes', { path, offset, length }));
|
||
dialog({ title: `${basename(path)} — ${label}`, body: mediaElement(kind, bytes), wide: true });
|
||
} catch (e) { notify(String(e.message || e), 'error'); }
|
||
} });
|
||
}
|
||
chooser(items, { at, placeholder: 'Read this file as…', width: 320 });
|
||
}
|
||
|
||
chooseEol(path, node) {
|
||
const file = this.editors.files.get(path);
|
||
if (!file?.model) return;
|
||
const r = node.getBoundingClientRect();
|
||
const names = { LF: 'LF — Linux, macOS (\\n)', CRLF: 'CRLF — Windows (\\r\\n)', CR: 'CR — Mac OS 9 (\\r)' };
|
||
chooser(Object.keys(names).map((eol) => ({ label: names[eol], hint: file.eol === eol ? '✓' : '', action: () => {
|
||
if (file.eol === eol) return;
|
||
this.editors.setFormat(path, { eol });
|
||
this.activeChanged(this.editors.activeTab());
|
||
notify(t('{file}: line endings converted to {eol}.', { file: basename(path), eol }), 'info');
|
||
} })), { at: { x: Math.max(8, r.right - 300), y: Math.max(8, r.top - 140) }, placeholder: t('Line endings'), width: 300 });
|
||
}
|
||
|
||
chooseEncoding(path, node) {
|
||
const file = this.editors.files.get(path);
|
||
if (!file?.model) return;
|
||
const r = node.getBoundingClientRect();
|
||
const notes = { 'UTF-8': t('without BOM (recommended)'), 'UTF-8 BOM': t('with a byte order mark (some Windows tools want it)'), 'UTF-16LE': 'BOM', 'UTF-16BE': 'BOM' };
|
||
const items = ['UTF-8', 'UTF-8 BOM', 'UTF-16LE', 'UTF-16BE', 'Windows-1252', 'ISO-8859-1', 'ISO-8859-15'].map((enc) => ({
|
||
label: enc + (notes[enc] ? ' — ' + notes[enc] : ''), hint: file.encoding === enc ? '✓' : '', action: async () => {
|
||
if (file.encoding === enc) return;
|
||
const { lost } = await backend.invoke('text.lost', { content: file.model.getValue(), encoding: enc }).catch(() => ({ lost: 0 }));
|
||
if (lost && !(await confirm(t('Convert the encoding'), t('{n} character(s) of this file cannot be written in {enc}: they will become "?". Convert anyway?', { n: lost, enc })))) return;
|
||
this.editors.setFormat(path, { encoding: enc });
|
||
this.activeChanged(this.editors.activeTab());
|
||
notify(t('{file}: converted to {enc}.', { file: basename(path), enc }), 'info');
|
||
} }));
|
||
chooser(items, { at: { x: Math.max(8, r.right - 380), y: Math.max(8, r.top - 300) }, placeholder: t('Convert to the encoding…'), width: 380 });
|
||
}
|
||
|
||
activeChanged(tab) {
|
||
const path = tab?.path || '';
|
||
const sbLang = $('sbLanguage');
|
||
sbLang.textContent = tab?.kind === 'text' ? (tab.hex ? 'HEX' : (this.editors.files.get(path)?.model.getLanguageId() || '').toUpperCase()) : (tab?.path ? t('View as…') : '');
|
||
sbLang.title = t('Read this file as another type (language, hexadecimal, picture, PDF…)');
|
||
sbLang.style.cursor = 'pointer';
|
||
sbLang.onclick = () => { const r = sbLang.getBoundingClientRect(); this.chooseFileType({ x: Math.max(8, r.right - 320), y: Math.max(8, r.top - 420) }); };
|
||
// the line endings and the encoding of a text file: a click converts it (written at the next save)
|
||
const file = tab?.kind === 'text' ? this.editors.files.get(path) : null;
|
||
const sbEol = $('sbEol');
|
||
const sbEnc = $('sbEncoding');
|
||
sbEol.textContent = file?.model ? (file.eol === 'mixed' ? t('Mixed') : file.eol || 'LF') : '';
|
||
sbEol.title = t('Line endings: click to convert them (LF, CRLF, CR)');
|
||
sbEol.onclick = () => this.chooseEol(path, sbEol);
|
||
sbEnc.textContent = file?.model ? (file.encoding || 'UTF-8') : '';
|
||
sbEnc.title = t('Encoding: click to convert the file (UTF-8, with or without BOM, UTF-16, Windows-1252…)');
|
||
sbEnc.onclick = () => this.chooseEncoding(path, sbEnc);
|
||
$('sbBreadcrumbs').textContent = path;
|
||
if (this.open?.left === 'structure') this.structure.update();
|
||
if (this.open?.left === 'hierarchy') this.hierarchy.update();
|
||
if (tab && prefs.get('autoscroll', false)) this.tree.reveal(path);
|
||
}
|
||
|
||
status(text) {
|
||
const node = $('sbStatus');
|
||
node.textContent = text;
|
||
clearTimeout(this.statusTimer);
|
||
this.statusTimer = setTimeout(() => { node.textContent = ''; }, 4000);
|
||
}
|
||
|
||
/**
|
||
* Docker, made ready in the background when a JumPHP project opens (JumPHP\Ide\Async\Docker: Docker Desktop is
|
||
* started when it is not running): a status bar task meanwhile, nothing waits but the runs that need it.
|
||
* Resolves with its state ({state, message}).
|
||
*/
|
||
docker() {
|
||
if (!this.project?.jumphp || backend.kind !== 'native') return Promise.resolve({ state: 'ready' });
|
||
if (!this.dockerListening) {
|
||
this.dockerListening = true;
|
||
backend.on('docker.state', (s) => this.dockerChanged(s));
|
||
}
|
||
this.dockerWait ??= backend.invoke('docker.ensure').catch((e) => ({ state: 'failed', message: e.message || String(e) }))
|
||
.then((s) => { if (s?.state !== 'ready' && s?.state !== 'wsl') this.dockerWait = null; return s; });
|
||
return this.dockerWait;
|
||
}
|
||
|
||
/**
|
||
* Brings the project's JumPHP files to JumPHP's newest (the IDE's) when it opens: at once when the user did not change
|
||
* them, else asked (the files named). ask: the user asked for it (the debugger needs it): asked even if declined before.
|
||
* Resolves with true when the project is up to date afterwards.
|
||
*/
|
||
async updateJumphp({ ask = false, why = '' } = {}) {
|
||
if (!this.project?.jumphp || backend.kind !== 'native' || !this.actions) return true;
|
||
if (this.jumphpUpdating) return this.jumphpUpdating;
|
||
const run = async () => {
|
||
let plan;
|
||
try { plan = await backend.invoke('jumphp.check'); } catch (e) {
|
||
if (ask) notify(e.message, 'error', { title: 'Cannot get the newest JumPHP' });
|
||
return false;
|
||
}
|
||
if (plan.upToDate) { if (plan.latest && plan.current !== plan.latest) await backend.invoke('jumphp.update').catch(() => null); return true; }
|
||
// "Later" is for a day: an old JumPHP in a project breaks things (extensions, the debugger...), the question comes back
|
||
const declined = prefs.get('jumphpDeclined:' + this.projectKey);
|
||
const [declinedFor, declinedAt] = String(declined || '').split('@');
|
||
if (plan.changed.length && !ask && declinedFor === plan.latest && Date.now() - Number(declinedAt || 0) < 24 * 3600 * 1000) return false;
|
||
const apply = async (force) => {
|
||
const task = this.task('Updating JumPHP in this project…');
|
||
try {
|
||
const r = await backend.invoke('jumphp.update', { force });
|
||
task();
|
||
const n = (r.updated?.length || 0) + (r.removed?.length || 0);
|
||
notify(`${n} file(s) of JumPHP updated in this project (bin/jumphp, the engine, tools…; your games are untouched)` + (r.kept?.length ? `; ${r.kept.length} file(s) you changed were kept` : '') + '.', 'success', { title: 'JumPHP updated' });
|
||
// a project whose games take the engine from Composer: its games' jumphp/engine updated too
|
||
for (const e of r.engine || []) notify(e.ok ? `${e.project}: engine updated (composer update jumphp/engine).` : `${e.project}: the engine was not updated:\n${e.output}`, e.ok ? 'success' : 'error', { title: 'jumphp/engine' });
|
||
this.tree?.refresh();
|
||
this.editors?.reloadFromDisk(); this.git?.refresh();
|
||
return !r.kept?.length;
|
||
} catch (e) {
|
||
task();
|
||
notify(e.message, 'error', { title: 'JumPHP was not updated' });
|
||
return false;
|
||
}
|
||
};
|
||
if (!plan.changed.length) return apply(false);
|
||
const list = plan.changed.slice(0, 12).join('\n') + (plan.changed.length > 12 ? `\n… and ${plan.changed.length - 12} more` : '');
|
||
const text = (why ? why + '\n\n' : '') + (plan.known
|
||
? `A newer JumPHP is out. ${plan.changed.length} of its file(s) were changed in this project: update them too (your version is replaced), or keep them (the others are updated)?`
|
||
: `A newer JumPHP is out. This project does not say which JumPHP it came from: ${plan.changed.length} file(s) of JumPHP differ here (bin/jumphp, the engine…). Update them? Your projects (games/, apps/) are never touched.`);
|
||
return new Promise((resolve) => {
|
||
dialog({ title: 'Update JumPHP in this project', body: el('div', {}, el('p', { style: { whiteSpace: 'pre-wrap' } }, text), el('pre.console', { style: { maxHeight: '180px', overflow: 'auto' } }, list)),
|
||
buttons: [
|
||
{ label: 'Later', action: () => { prefs.set('jumphpDeclined:' + this.projectKey, plan.latest + '@' + Date.now()); resolve(false); } },
|
||
...(plan.known ? [{ label: 'Keep my changes', action: async () => resolve(await apply(false)) }] : []),
|
||
{ label: 'Update', primary: true, action: async () => resolve(await apply(true)) },
|
||
],
|
||
onClose: () => resolve(false) });
|
||
});
|
||
};
|
||
this.jumphpUpdating = run().finally(() => { this.jumphpUpdating = null; });
|
||
return this.jumphpUpdating;
|
||
}
|
||
|
||
/**
|
||
* "Open with JumPHP" (a file: the quick editor) and "Open as a project in JumPHP" (a folder) in the system's file manager:
|
||
* what it is, whether it is there, and the button that adds or removes it (games/ide/src/OsIntegration.php).
|
||
*/
|
||
async osIntegration() {
|
||
let s;
|
||
try { s = await backend.invoke('system.integration'); } catch (e) { notify(e.message, 'error'); return; }
|
||
const run = async (remove) => {
|
||
try {
|
||
await backend.invoke('system.integrate', { remove });
|
||
notify(t(remove ? 'The entries were removed from the system.' : 'Done: right click a file → "Open with JumPHP", a folder → "Open as a project in JumPHP".'), 'success');
|
||
} catch (e) { notify(e.message, 'error', { title: t('Integrate with the System') }); }
|
||
};
|
||
const where = s.system === 'Windows' ? t('Windows Explorer (this user only, no administrator rights).')
|
||
: t('The "Open with" lists, and the context menus of Nautilus (Scripts), Nemo, Caja and Dolphin.');
|
||
dialog({
|
||
title: t('Integrate with the System'),
|
||
body: el('div', {},
|
||
el('p', {}, t('Right click a file: "Open with JumPHP" opens it in the quick editor (one file, fast, no project). Right click a folder (or inside one): "Open as a project in JumPHP".')),
|
||
el('p.pub-faint', {}, where),
|
||
s.supported ? el('p', {}, s.installed ? '✓ ' + t('Installed.') : t('Not installed.')) : el('p.pub-faint', {}, t(s.why || 'Not available on this system yet.')),
|
||
el('p.pub-faint', {}, t('From a terminal too: jumphp-ide <file> (the quick editor), jumphp-ide <folder> (the IDE on that folder).'))),
|
||
buttons: s.supported ? [
|
||
...(s.installed ? [{ label: t('Remove'), action: () => run(true) }] : []),
|
||
{ label: t(s.installed ? 'Install again' : 'Install'), primary: true, action: () => run(false) },
|
||
{ label: t('Close') },
|
||
] : [{ label: t('Close') }],
|
||
});
|
||
}
|
||
|
||
dockerChanged({ state, message }) {
|
||
const busy = state === 'checking' || state === 'starting';
|
||
if (busy) {
|
||
this.dockerTask ??= this.task(message);
|
||
this.dockerTask.update(message, null);
|
||
if (state === 'starting') this.dockerStarted = true;
|
||
return;
|
||
}
|
||
this.dockerTask?.();
|
||
this.dockerTask = null;
|
||
if (state === 'ready' && this.dockerStarted) notify(message, 'success', { title: 'Docker' });
|
||
if (state === 'wsl' && !this.dockerWslSaid) { this.dockerWslSaid = true; notify(message, 'info', { title: 'Docker' }); }
|
||
if (state === 'missing' || state === 'failed') notify(message, 'error', { title: 'Docker', actions: [{ label: 'Retry', action: () => this.docker() }] });
|
||
this.dockerStarted = false;
|
||
}
|
||
|
||
/**
|
||
* A background task in the status bar (spinner, what it does, its progress): every action that runs in the
|
||
* background shows one while it runs. Returns done(); done.update(text, ratio) changes its text and / or progress
|
||
* (ratio 0..1; null: unknown, a moving bar). open: what a click on it in the tasks' list shows.
|
||
*/
|
||
task(text, { ratio = null, open = null } = {}) {
|
||
const entry = { text, ratio, open, started: Date.now() };
|
||
this.tasks.add(entry);
|
||
this.drawTasks();
|
||
const done = () => { if (this.tasks.delete(entry)) this.drawTasks(); };
|
||
done.update = (newText = null, newRatio) => {
|
||
if (newText !== null) entry.text = newText;
|
||
if (newRatio !== undefined) entry.ratio = newRatio;
|
||
if (this.tasks.has(entry)) this.drawTasks();
|
||
};
|
||
return done;
|
||
}
|
||
|
||
drawTasks() {
|
||
const node = clear($('sbTask'));
|
||
const list = [...this.tasks];
|
||
node.classList.toggle('clickable', list.length > 0);
|
||
node.title = list.length ? list.map((t) => t.text).join('\n') + '\n(click: the background tasks)' : '';
|
||
if (!list.length) return;
|
||
const last = list[list.length - 1];
|
||
node.append(el('span.spinner'), el('span.sb-task-text', {}, last.text), progressBar(last.ratio));
|
||
if (list.length > 1) node.append(el('span.sb-more', {}, `+${list.length - 1}`));
|
||
}
|
||
|
||
/** The tasks running in the background, each with its progress (a click on one: where it shows). */
|
||
showTasks(at) {
|
||
const list = [...this.tasks];
|
||
if (!list.length) return;
|
||
const ago = (t) => { const s = Math.round((Date.now() - t.started) / 1000); return s < 60 ? `${s} s` : `${Math.floor(s / 60)} min ${s % 60} s`; };
|
||
menu([{ head: `Background tasks (${list.length})` }, ...list.map((t) => ({
|
||
label: t.text + (t.ratio !== null && t.ratio !== undefined ? ` — ${Math.round(100 * t.ratio)} %` : ''), hint: ago(t),
|
||
action: () => t.open?.(),
|
||
}))], at);
|
||
}
|
||
|
||
indexProgress(p) {
|
||
if (p.libraries) { // the libraries (vendor/...), in the background after the project
|
||
if (p.complete) { this.libraryTask?.(); this.libraryTask = null; return; }
|
||
const text = `Indexing libraries (${p.done}/${p.total} files)…`;
|
||
if (!this.libraryTask) this.libraryTask = this.task(text, { ratio: p.total ? p.done / p.total : null });
|
||
else this.libraryTask.update(text, p.total ? p.done / p.total : null);
|
||
return;
|
||
}
|
||
if (p.complete) { this.indexTask?.(); this.indexTask = null; return; }
|
||
const ratio = p.total ? p.done / p.total : null;
|
||
const text = `Indexing PHP${p.total ? ` (${p.done}/${p.total} files)` : ''}…`;
|
||
if (!this.indexTask) this.indexTask = this.task(text, { ratio });
|
||
else this.indexTask.update(text, ratio);
|
||
}
|
||
|
||
// PHP problems ------------------------------------------------------------------------------------------------
|
||
|
||
/** Code > Rebuild the PHP Index and the status bar's button: the project and its libraries (vendor/) analyzed again, then the problems. */
|
||
/** The top bar's Refresh: everything read from disk again (files changed outside, composer install / require, castor, git). */
|
||
async refreshProject() {
|
||
const done = this.task?.(t('Refreshing the project…'));
|
||
try {
|
||
await this.editors?.saveAll?.(true);
|
||
await Promise.allSettled([this.tree?.refresh?.(), this.git?.refresh?.(), this.editors?.reloadFromDisk?.(),
|
||
this.composer?.load?.(), this.scripts?.load?.(true), this.symfonyConsole?.load?.(true)]);
|
||
} finally { done?.(); }
|
||
await this.reindex();
|
||
this.gutterRun?.rescan?.();
|
||
}
|
||
|
||
async reindex() {
|
||
this.reindexTask?.();
|
||
this.reindexTask = this.task(t('Re-indexing the project and its libraries…'));
|
||
try { await backend.invoke('index.rebuild'); } catch (e) { notify(String(e.message || e), 'error'); }
|
||
this.reindexTask?.();
|
||
this.reindexTask = null;
|
||
}
|
||
|
||
/** API Platform was just installed: its commands and window appear without restarting the IDE. */
|
||
async enableApiPlatform() {
|
||
if (this.apiPlatform) return true;
|
||
const r = await backend.invoke('apiplatform.enable', {});
|
||
if (!r.enabled) return false;
|
||
this.project.capabilities.apiplatform = true;
|
||
this.apiPlatform = new ApiPlatformPanel(this);
|
||
this.registerTools();
|
||
this.renderStripes();
|
||
return true;
|
||
}
|
||
|
||
/** The index learned (or forgot) classes: the PHP files that are open get their problems again, no stale "Undefined class". */
|
||
diagnoseOpenFiles() {
|
||
for (const path of this.editors?.files?.keys?.() ?? []) if (path.endsWith('.php') && !path.includes('vendor/')) this.diagnose(path);
|
||
}
|
||
|
||
diagnose(path) {
|
||
this.diagnoseQueue ??= new Map();
|
||
clearTimeout(this.diagnoseQueue.get(path));
|
||
this.diagnoseQueue.set(path, setTimeout(async () => {
|
||
const model = this.editors.files.get(path)?.model;
|
||
if (!model) return;
|
||
const list = await backend.invoke('php.diagnostics', { path, text: model.getValue() }).catch(() => null);
|
||
if (!list || model.isDisposed()) return;
|
||
monaco.editor.setModelMarkers(model, 'jumphp', list.map((d) => ({
|
||
startLineNumber: d.startLine, startColumn: d.startColumn, endLineNumber: d.endLine, endColumn: Math.max(d.endColumn, d.startColumn + 1),
|
||
message: d.message, severity: d.severity === 'error' ? monaco.MarkerSeverity.Error : monaco.MarkerSeverity.Warning, source: d.source,
|
||
})));
|
||
this.problems.set(path, list);
|
||
}, 700));
|
||
}
|
||
|
||
/** YAML problems as one types: syntax, Compose and Symfony checks (yaml.diagnostics); an edit drops the last docker compose check's. */
|
||
diagnoseYaml(path, edited = false) {
|
||
this.diagnoseQueue ??= new Map();
|
||
clearTimeout(this.diagnoseQueue.get(path));
|
||
if (edited && this.problems.sources?.get(path)?.compose) {
|
||
const model = this.editors.files.get(path)?.model;
|
||
if (model) monaco.editor.setModelMarkers(model, 'compose', []);
|
||
this.problems.set(path, [], 'compose');
|
||
}
|
||
this.diagnoseQueue.set(path, setTimeout(async () => {
|
||
const model = this.editors.files.get(path)?.model;
|
||
if (!model) return;
|
||
const list = await backend.invoke('yaml.diagnostics', { path, text: model.getValue() }).catch(() => null);
|
||
if (!list || model.isDisposed()) return;
|
||
this.setProblems(path, list, 'yaml');
|
||
}, 400));
|
||
}
|
||
|
||
/** Problems of a file from one source: its editor markers (owner = source) and the Problems window. */
|
||
setProblems(path, list, source) {
|
||
const model = this.editors.files.get(path)?.model;
|
||
if (model && !model.isDisposed()) {
|
||
monaco.editor.setModelMarkers(model, source, list.map((d) => ({
|
||
startLineNumber: d.startLine, startColumn: d.startColumn, endLineNumber: d.endLine, endColumn: Math.max(d.endColumn, d.startColumn + 1),
|
||
message: d.message, severity: d.severity === 'error' ? monaco.MarkerSeverity.Error : monaco.MarkerSeverity.Warning, source: d.source,
|
||
})));
|
||
}
|
||
this.problems.set(path, list, source);
|
||
}
|
||
|
||
// actions ----------------------------------------------------------------------------------------------------
|
||
|
||
registerActions() {
|
||
const a = this.actions;
|
||
const ed = () => this.editors.editor();
|
||
const trigger = (id) => () => { const e = ed(); if (e) { e.focus(); e.trigger('action', id, null); } };
|
||
const caps = this.project.capabilities || {};
|
||
a.add('searchEverywhere', 'Search Everywhere', () => searchEverywhere(this), { kbd: 'Double Shift', icon: 'search' });
|
||
a.add('gotoFile', 'Go to File…', () => searchEverywhere(this, 'files'), { kbd: 'Ctrl+Shift+N', icon: 'file' });
|
||
a.add('gotoClass', 'Go to Class…', () => searchEverywhere(this, 'classes'), { kbd: 'Ctrl+N' });
|
||
a.add('gotoSymbol', 'Go to Symbol…', () => searchEverywhere(this, 'symbols'), { kbd: 'Ctrl+Alt+Shift+N' });
|
||
a.add('findAction', 'Find Action…', () => searchEverywhere(this, 'actions'), { kbd: 'Ctrl+Shift+A' });
|
||
a.add('recentFiles', 'Recent Files', () => recentFiles(this), { kbd: 'Ctrl+E', icon: 'history' });
|
||
a.add('recentChanges', 'Recently Changed Files', () => this.toggleTool('recent'), { kbd: 'Ctrl+Shift+E', icon: 'history' });
|
||
a.add('searchText', 'Search Text (indexed)…', () => searchEverywhere(this, 'text'), { icon: 'search' });
|
||
a.add('fileStructure', 'File Structure', () => fileStructure(this), { kbd: 'Ctrl+F12', icon: 'structure' });
|
||
a.add('findInFiles', 'Find in Files…', () => this.findInFiles(), { kbd: 'Ctrl+Shift+F', icon: 'find' });
|
||
if (!caps.readOnly) a.add('replaceInFiles', 'Replace in Files…', () => this.findInFiles({ replace: true }), { kbd: 'Ctrl+Shift+R' });
|
||
a.add('find', 'Find', trigger('actions.find'), { kbd: 'Ctrl+F' });
|
||
a.add('replace', 'Replace', trigger('editor.action.startFindReplaceAction'), { kbd: 'Ctrl+R' });
|
||
a.add('gotoLine', 'Go to Line…', trigger('editor.action.gotoLine'), { kbd: 'Ctrl+G' });
|
||
a.add('declaration', 'Go to Declaration', trigger('editor.action.revealDefinition'), { kbd: 'Ctrl+B' });
|
||
a.add('implementations', 'Go to Implementation(s)', trigger('editor.action.goToImplementation'), { kbd: 'Ctrl+Alt+B' });
|
||
a.add('usages', 'Find Usages', () => this.findUsages(), { kbd: 'Alt+F7', icon: 'find' });
|
||
a.add('callHierarchy', 'Call Hierarchy', () => {
|
||
const ed = this.editors?.focused?.editor; const tab = this.editors?.activeTab();
|
||
if (ed && tab) this.calls.show({ path: tab.path, text: ed.getModel().getValue(), line: ed.getPosition().lineNumber, column: ed.getPosition().column });
|
||
}, { kbd: 'Ctrl+Alt+H', icon: 'hierarchy' });
|
||
a.add('rename', 'Rename…', trigger('editor.action.rename'), { kbd: 'Shift+F6' });
|
||
a.add('reformat', 'Reformat Code', trigger('editor.action.formatDocument'), { kbd: 'Ctrl+Alt+L' });
|
||
a.add('comment', 'Comment Line', trigger('editor.action.commentLine'), { kbd: 'Ctrl+/' });
|
||
a.add('back', 'Back', () => this.editors.back(), { kbd: 'Ctrl+Alt+Left' });
|
||
a.add('forward', 'Forward', () => this.editors.forward(), { kbd: 'Ctrl+Alt+Right' });
|
||
a.add('saveAll', 'Save All', () => this.editors.saveAll(), { kbd: 'Ctrl+S' });
|
||
a.add('closeTab', 'Close Tab', () => { const t = this.editors.activeTab(); if (t) this.editors.closeTab(this.editors.focused, t); }, { kbd: 'Ctrl+F4' });
|
||
a.add('split', 'Split Right', () => this.editors.split(), { icon: 'split' });
|
||
a.add('hexView', 'View as Hexadecimal', () => this.editors.toggleHex(), { when: () => !!this.editors.activeTab() && this.editors.activeTab().kind !== 'diff' });
|
||
a.add('htmlPreview', 'Preview HTML', () => this.editors.togglePreview(), { icon: 'eye', when: () => this.editors.canPreview() });
|
||
if (!caps.readOnly) a.add('newFile', 'New File…', () => this.tree.newFile(this.tree.targetDir()), { kbd: 'Alt+Insert', icon: 'plus' });
|
||
a.add('project', 'Project Tool Window', () => this.toggleTool('project'), { kbd: 'Alt+1', icon: 'folder' });
|
||
a.add('structure', 'Structure Tool Window', () => this.toggleTool('structure'), { kbd: 'Alt+7', icon: 'structure' });
|
||
a.add('problemsTool', 'Problems Tool Window', () => this.toggleTool('problems'), { kbd: 'Alt+6', icon: 'problems' });
|
||
if (this.logsPanel) a.add('logsTool', 'Logs Tool Window', () => this.toggleTool('logs'), { kbd: 'Alt+F11', icon: 'logfile' });
|
||
a.add('findTool', 'Find Tool Window', () => this.toggleTool('find'), { kbd: 'Alt+3' });
|
||
a.add('resetLayout', 'Reset Window Layout', () => this.resetLayout(), { icon: 'refresh' });
|
||
if (this.composer) {
|
||
a.add('composerInstall', 'Composer: Install the Dependencies', () => { this.showTool?.('composer'); this.composer.run({ action: 'install' }).then(() => this.reindex()); }, { icon: 'package' });
|
||
a.add('composerUpdate', 'Composer: Update the Dependencies', () => { this.showTool?.('composer'); this.composer.run({ action: 'update' }).then(() => this.reindex()); }, { icon: 'package' });
|
||
}
|
||
if (this.scripts) a.add('installCastor', 'Install Castor…', () => this.scripts.installCastor(), { icon: 'download' });
|
||
if (this.symfonyConsole && this.project.capabilities?.console === 'bin/console') {
|
||
a.add('symfonyCacheClear', 'Symfony: Clear the Cache', () => { this.showTool('console', true); this.symfonyConsole.runHere({ line: 'cache:clear' }, 'cache:clear'); }, { icon: 'refresh' });
|
||
}
|
||
a.add('refreshProject', 'Refresh the Project', () => this.refreshProject(), { kbd: 'Ctrl+Alt+Y', icon: 'refresh' });
|
||
a.add('zoomIn', 'Increase Font Size', () => zoom.step(zoom.focusedId(), 1), { kbd: 'Ctrl+=' });
|
||
a.add('zoomOut', 'Decrease Font Size', () => zoom.step(zoom.focusedId(), -1), { kbd: 'Ctrl+-' });
|
||
a.add('resetZoom', 'Reset Font Size', () => zoom.reset(zoom.focusedId()), { kbd: 'Ctrl+0' });
|
||
a.add('zoomIdeIn', 'Zoom In the Whole IDE', () => zoom.step('ui', 1), { kbd: 'Ctrl+Shift+Wheel' });
|
||
a.add('zoomIdeOut', 'Zoom Out the Whole IDE', () => zoom.step('ui', -1));
|
||
a.add('resetIdeZoom', 'Reset the Whole IDE Zoom', () => zoom.reset('ui'));
|
||
a.add('resetAllZoom', 'Reset All Zoom', () => zoom.resetAll());
|
||
a.add('hideTools', 'Hide All Tool Windows', () => { this.closeSide('left'); this.closeSide('bottom'); }, { kbd: 'Ctrl+Shift+F12' });
|
||
a.add('selectInProject', 'Select Opened File in Project', () => this.tree.reveal(this.editors.activePath(), true), { kbd: 'Alt+F1' });
|
||
if (caps.vcsManage && backend.kind === 'native') {
|
||
a.add('vcsSetup', 'Version control…', () => openVcsSetup(this), { icon: 'branch' });
|
||
if (caps.git || caps.vcs === 'svn') a.add('vcsRemotes', 'Remotes and hosting…', () => openRemotes(this), { icon: 'globe' });
|
||
}
|
||
if (caps.git) {
|
||
a.add('commit', 'Commit…', () => this.showTool('commit'), { kbd: 'Ctrl+K', icon: 'commit' });
|
||
a.add('commitTool', 'Commit Tool Window', () => this.toggleTool('commit'), { kbd: 'Alt+0', icon: 'commit' });
|
||
a.add('commitAll', 'Commit All and Push…', () => this.git.commitAll(), { kbd: 'Ctrl+Alt+K', icon: 'upload' });
|
||
a.add('gitRemotes', 'Git Remotes…', () => this.git.extra.remotes(), { icon: 'globe' });
|
||
a.add('gitTags', 'Git Tags…', () => this.git.extra.tags(), { icon: 'branch' });
|
||
a.add('gitSubmodules', 'Git Submodules…', () => this.git.extra.submodules(), { icon: 'folder' });
|
||
if (backend.kind === 'native') a.add('sshKeys', 'SSH Keys…', () => this.git.extra.sshKeys(), { icon: 'user' });
|
||
a.add('gitStashes', 'Git Stashes…', () => this.git.extra.stashes(), { icon: 'package' });
|
||
if (backend.kind === 'native') a.add('gitCredentials', 'Git Credentials…', () => this.git.extra.credentials(), { icon: 'user' });
|
||
a.add('push', 'Push…', () => this.git.push(), { kbd: 'Ctrl+Shift+K', icon: 'push' });
|
||
a.add('diff', 'Show Diff with HEAD', () => this.git.diff(this.editors.activePath()), { kbd: 'Ctrl+D', icon: 'diff', when: () => false });
|
||
a.add('rollbackFile', 'Rollback File…', () => { const p = this.editors.activePath(); if (p) this.git.rollback([p]); }, { kbd: 'Ctrl+Alt+Z', icon: 'rollback' });
|
||
} else if (caps.vcs === 'svn') svnActions(this, a);
|
||
if (caps.branches) {
|
||
a.add('update', 'Update Project', () => this.git.pull(), { kbd: 'Ctrl+T', icon: 'pull' });
|
||
a.add('branches', 'Branches…', () => this.git.branchPopup($('branchWidget')), { kbd: 'Ctrl+Shift+`', icon: 'branch' });
|
||
}
|
||
if (caps.log) {
|
||
a.add('gitLog', 'Git Log', () => this.toggleTool('git'), { kbd: 'Alt+9', icon: 'log' });
|
||
a.add('fileHistory', 'Show History of the File', () => this.git.showLog(this.editors.activePath()), { icon: 'history' });
|
||
}
|
||
if (caps.localHistory) a.add('localHistory', 'Show Local History', () => showLocalHistory(this, this.editors.activePath()), { icon: 'history' });
|
||
if (caps.blame) a.add('annotate', 'Annotate with Git Blame', () => this.git.toggleBlame(), { icon: 'history' });
|
||
if (this.httpClient) {
|
||
a.add('httpClientTool', 'HTTP Client', () => this.toggleTool('httpClient'), { icon: 'globe' });
|
||
a.add('openApiTool', 'OpenAPI Viewer', () => this.toggleTool('openapi'), { icon: 'library' });
|
||
}
|
||
if (caps.run) {
|
||
a.add('run', 'Run', () => this.runner.runSelected(), { kbd: 'Shift+F10', icon: 'play' });
|
||
// in a test file: the test at the cursor (the Tests window), else the selected configuration's tests
|
||
a.add('test', 'Run Tests', () => { if (!this.tests?.runAtCursor()) this.runner.runSelected('test'); }, { kbd: 'Ctrl+Shift+F10', icon: 'test' });
|
||
if (this.tests) {
|
||
a.add('testsTool', 'Tests Tool Window', () => this.toggleTool('tests'), { icon: 'test' });
|
||
a.add('runAllTests', 'Run All Tests', () => { this.showTool('tests'); this.tests.runAll(); }, { icon: 'test' });
|
||
a.add('rerunFailedTests', 'Rerun the Failed Tests', () => { this.showTool('tests'); this.tests.runFailed(); }, { icon: 'refresh' });
|
||
a.add('testsCoverage', 'Run All Tests with Coverage', () => { this.showTool('tests'); this.tests.runAll(true); }, { icon: 'check' });
|
||
}
|
||
a.add('shot', 'Take a Screenshot', () => this.runner.runSelected('shot'), { icon: 'camera' });
|
||
a.add('rerun', 'Rerun', () => { const r = this.runner.current(); if (r) this.runner.start(r.config); }, { kbd: 'Ctrl+F5', icon: 'refresh' });
|
||
a.add('stop', 'Stop', () => this.runner.stop(), { kbd: 'Ctrl+F2', icon: 'stop' });
|
||
a.add('runTool', 'Run Tool Window', () => this.toggleTool('run'), { kbd: 'Alt+4', icon: 'play' });
|
||
a.add('runConfigs', 'Run Configurations…', () => this.runner.choose($('runConfig')), { kbd: 'Alt+Shift+F10' });
|
||
a.add('runAnything', 'Run Anything… (bin/jumphp)', () => this.runner.runAnything(), { kbd: 'Ctrl Ctrl', icon: 'terminal' });
|
||
if (this.profiler) {
|
||
a.add('profile', 'Profile…', () => this.profiler.ask(), { kbd: 'Alt+Shift+P', icon: 'profile' });
|
||
a.add('profileTool', 'Profiler Tool Window', () => this.toggleTool('profile'), { kbd: 'Alt+P', icon: 'profile' });
|
||
}
|
||
if (this.debugger) {
|
||
const d = this.debugger;
|
||
const paused = () => !!d.paused;
|
||
a.add('debug', 'Debug', () => d.debug(), { kbd: 'Shift+F9', icon: 'debug' });
|
||
a.add('debugWith', 'Debug with… (Xdebug / PHP Debugger)', () => d.debugWith($('debugBtn')), { icon: 'debug' });
|
||
a.add('debugResume', 'Resume Program', () => d.step('run'), { kbd: 'F9', icon: 'play', when: paused });
|
||
a.add('stepOver', 'Step Over', () => d.step('step_over'), { kbd: 'F8', icon: 'stepOver', when: paused });
|
||
a.add('stepInto', 'Step Into', () => d.step('step_into'), { kbd: 'F7', icon: 'stepInto', when: paused });
|
||
a.add('stepOut', 'Step Out', () => d.step('step_out'), { kbd: 'Shift+F8', icon: 'stepOut', when: paused });
|
||
a.add('runToCursor', 'Run to Cursor', () => {
|
||
const path = this.editors.activePath();
|
||
const line = this.editors.editor()?.getPosition()?.lineNumber;
|
||
if (path && line) d.runTo(path, line);
|
||
}, { kbd: 'Alt+F9', icon: 'play', when: paused });
|
||
a.add('exceptionBreakpoints', 'Stop at Exceptions…', () => d.editExceptions(), { icon: 'warning' });
|
||
a.add('toggleBreakpoint', 'Toggle Line Breakpoint', () => {
|
||
const path = this.editors.activePath();
|
||
const line = this.editors.editor()?.getPosition()?.lineNumber;
|
||
if (path && line && path.endsWith('.php')) d.toggle(path, line);
|
||
}, { kbd: 'Ctrl+F8', icon: 'debug' });
|
||
a.add('debugTool', 'Debug Tool Window', () => this.toggleTool('debug'), { icon: 'debug' });
|
||
}
|
||
if (backend.kind === 'native') a.add('createInstaller', 'Create an Installer…', () => createInstaller(this), { icon: 'package' });
|
||
} else if (caps.tests) {
|
||
a.add('test', 'Run Tests on jumphp.net', () => this.runner.remoteTests(), { kbd: 'Ctrl+Shift+F10', icon: 'test' });
|
||
a.add('runTool', 'Run Tool Window', () => this.toggleTool('run'), { kbd: 'Alt+4', icon: 'play' });
|
||
}
|
||
if (this.claude) a.add('claudeTool', 'Claude', () => this.toggleTool('claude'), { kbd: 'Alt+8', icon: 'claude' });
|
||
if (this.terminal) a.add('terminalTool', 'Terminal', () => this.toggleTool('terminal'), { kbd: 'Alt+F12', icon: 'terminal' });
|
||
if (this.claude && backend.kind === 'native') a.add('claudeMcp', 'Connect Claude to jumphp.net', async () => {
|
||
this.showTool('claude');
|
||
const m = await this.claude.checkMcp();
|
||
if (m?.installed) notify(`Claude Code already has jumphp.net's tools (the "jumphp" MCP server, ${m.scope} scope).`, 'success', { title: 'Claude and jumphp.net' });
|
||
}, { icon: 'globe' });
|
||
if (caps.preview) {
|
||
a.add('preview', 'Play the Game', () => this.game.play(), { kbd: 'Shift+F10', icon: 'play' });
|
||
a.add('gameTool', 'Game', () => this.toggleTool('game'), { kbd: 'Alt+5', icon: 'game' });
|
||
a.add('previewTab', 'Play in a New Tab', () => this.runner.preview(), { icon: 'globe' });
|
||
}
|
||
if (this.board) {
|
||
a.add('boardTool', 'Open the Board', () => this.showTool('board'), { icon: 'board' });
|
||
a.add('boardAddTask', 'Add a Task…', () => this.board.quickAdd(), { icon: 'plus' });
|
||
}
|
||
this.doctrine?.registerActions(a);
|
||
this.schemaCheck?.registerActions(a);
|
||
this.apiPlatform?.registerActions(a);
|
||
this.plugins?.registerActions(a);
|
||
this.extensions?.registerActions(a);
|
||
this.localAi?.registerActions(a);
|
||
this.videoPreview?.registerActions(a);
|
||
a.add('settings', 'Settings…', () => this.settings(), { kbd: 'Ctrl+Alt+S', icon: 'settings' });
|
||
a.add('documentation', 'Documentation', () => this.docs.open(), { icon: 'book' });
|
||
registerHubActions(this, a); // New… (Alt+N) and "New: Controller…" for Search Everywhere
|
||
a.add('symfonyTutorial', 'Symfony tutorial', () => this.tutorial.start('symfony'), { icon: 'star' });
|
||
// the Symfony / Laravel console as forms (its tool window on the right): Tools menu, Search Everywhere, Alt+S
|
||
if (this.symfonyConsole) a.add('symfonyConsole', this.symfonyConsole.title(), () => this.showTool('console', true), { icon: 'console' });
|
||
if (this.symfonyForms) {
|
||
a.add('symfonyForms', 'Symfony Forms', () => this.showTool('sfForms', true), { icon: 'design' });
|
||
a.add('symfonyFormBuilder', 'Open the Form Builder on This File', () => this.symfonyForms.openActive(), { icon: 'design' });
|
||
a.add('symfonyNewFormType', 'New Symfony Form Type…', () => this.symfonyForms.newType(), { icon: 'plus' });
|
||
}
|
||
if (this.validationPanel) a.add('symfonyValidation', 'Validation Constraints', () => this.showTool('validation', true), { icon: 'check' });
|
||
if (this.securityPanel) a.add('symfonySecurity', 'Security (security.yaml)', () => this.showTool('security', true), { icon: 'user' });
|
||
if (this.symfonyEvents) a.add('symfonyEvents', 'Symfony Events', () => this.showTool('sfEvents', true), { icon: 'bell' });
|
||
if (this.messenger) a.add('messengerTool', 'Messenger', () => this.showTool('messenger', true), { icon: 'cast' });
|
||
if (this.translations) a.add('translationsTool', 'Translations', () => this.showTool('translations', true), { icon: 'globe' });
|
||
if (this.securityAudit) a.add('securityAuditTool', 'Security Audit', () => this.showTool('audit', true), { icon: 'bug' });
|
||
// Doctrine fixtures and PHPUnit tests made from forms (ide/ui/js/fixtures.js, test-wizard.js)
|
||
if (this.project.capabilities?.fixtures) {
|
||
a.add('newFixtures', 'New Fixtures…', () => import('./fixtures.js').then((m) => m.openFixtures(this)), { icon: 'plus', kbd: 'Ctrl+Alt+Shift+F' });
|
||
a.add('loadFixtures', 'Load Fixtures…', () => import('./fixtures.js').then((m) => m.openFixtureLoad(this)), { icon: 'play' });
|
||
}
|
||
if (this.project.capabilities?.testWizard) a.add('newTestWizard', 'New Test…', () => import('./test-wizard.js').then((m) => m.openTestWizard(this)), { icon: 'test', kbd: 'Ctrl+Alt+Shift+T' });
|
||
if (this.symfonyConsole && this.project.capabilities?.console === 'bin/console') a.add('newSymfonyCommand', 'New Symfony Command…', () => openSymfonyWizard(this), { icon: 'plus', kbd: 'Ctrl+Alt+Shift+C' });
|
||
if (this.database) {
|
||
a.add('databaseTool', 'Database', () => this.showTool('database'), { icon: 'database' });
|
||
a.add('sqlConsole', 'Open a SQL console', () => this.database.panel.consoleOfSelection(), { icon: 'console' });
|
||
}
|
||
if (this.scripts) {
|
||
a.add('scriptsTool', 'Scripts', () => this.showTool('scripts', true), { icon: 'zap' });
|
||
a.add('newScript', 'New Script…', () => this.scripts.edit(null), { icon: 'plus' });
|
||
a.add('newCastorTask', 'New Castor Task…', () => this.scripts.newCastorTask(), { icon: 'zap' });
|
||
}
|
||
a.add('theme', 'Toggle Light / Dark Theme', () => this.toggleTheme());
|
||
a.add('rebuildIndex', 'Rebuild the PHP Index', () => this.reindex());
|
||
if (backend.kind === 'native') a.add('osIntegration', 'Integrate with the System (Open with JumPHP)…', () => this.osIntegration(), { icon: 'folder' });
|
||
if (backend.kind === 'native') {
|
||
a.add('openProject', 'Open Project…', () => this.switchProject(), { icon: 'folder' });
|
||
a.add('closeProject', 'Close Project', () => backend.invoke('projects.close').then(() => location.reload()));
|
||
}
|
||
// a test-only key in the browser test (headless runs pick files from here)
|
||
window.jumphpIde = this;
|
||
}
|
||
|
||
/** Keys PhpStorm users expect, outside Monaco too. */
|
||
/** Tells the PHP side the language of the interface (its error texts come in it). */
|
||
sendLanguage() { backend.invoke('ide.lang', { lang: uiLang() }).catch(() => null); }
|
||
|
||
bindKeys() {
|
||
const map = this.keyMap = {
|
||
'ctrl+shift+n': 'gotoFile', 'ctrl+n': 'gotoClass', 'ctrl+alt+shift+n': 'gotoSymbol', 'ctrl+shift+a': 'findAction', 'ctrl+e': 'recentFiles', 'ctrl+alt+h': 'callHierarchy', 'ctrl+shift+e': 'recentChanges',
|
||
'ctrl+shift+f': 'findInFiles', 'ctrl+shift+r': 'replaceInFiles', 'ctrl+k': 'commit', 'ctrl+shift+k': 'push', 'ctrl+t': 'update',
|
||
'shift+f10': 'run', 'ctrl+shift+f10': 'test', 'ctrl+f5': 'rerun', 'ctrl+f2': 'stop', 'alt+1': 'project', 'alt+0': 'commitTool',
|
||
'alt+4': 'runTool', 'alt+6': 'problemsTool', 'alt+7': 'structure', 'alt+9': 'gitLog', 'alt+3': 'findTool', 'ctrl+alt+s': 'settings',
|
||
'ctrl+shift+f12': 'hideTools', 'alt+f1': 'selectInProject', 'ctrl+s': 'saveAll', 'alt+shift+f10': 'runConfigs', 'ctrl+alt+z': 'rollbackFile',
|
||
'alt+f12': 'terminalTool', 'alt+insert': 'newFile', 'ctrl+shift+`': 'branches',
|
||
'shift+f9': 'debug', 'f9': 'debugResume', 'f8': 'stepOver', 'f7': 'stepInto', 'shift+f8': 'stepOut', 'alt+f9': 'runToCursor', 'ctrl+f8': 'toggleBreakpoint',
|
||
'alt+p': 'profileTool', 'alt+shift+p': 'profile',
|
||
};
|
||
let lastShift = 0;
|
||
let lastCtrl = 0;
|
||
document.addEventListener('keydown', (e) => {
|
||
if (!this.project) return;
|
||
// in the Terminal the keys are the shell's (Ctrl+E, Ctrl+K, Escape...): only Alt+… reaches the IDE
|
||
if (e.target.closest?.('.terminal-panel') && !(e.altKey && !e.ctrlKey && !e.metaKey)) return;
|
||
// Ctrl twice: Run Anything (bin/jumphp commands)
|
||
if (e.key === 'Control' && !e.repeat && !e.shiftKey && !e.altKey) {
|
||
const now = Date.now();
|
||
if (now - lastCtrl < 350 && this.project.capabilities?.run && !document.querySelector('.overlay')) { lastCtrl = 0; this.runner?.runAnything(); return; }
|
||
lastCtrl = now;
|
||
} else if (e.key !== 'Control') lastCtrl = 0;
|
||
const key = [e.ctrlKey || e.metaKey ? 'ctrl' : '', e.altKey ? 'alt' : '', e.shiftKey ? 'shift' : '', e.key.length === 1 ? e.key.toLowerCase() : e.key.toLowerCase()].filter(Boolean).join('+');
|
||
if (e.key === 'Shift' && !e.repeat) {
|
||
const now = Date.now();
|
||
if (now - lastShift < 350) { lastShift = 0; searchEverywhere(this); return; }
|
||
lastShift = now;
|
||
return;
|
||
}
|
||
if (e.key !== 'Shift') lastShift = 0;
|
||
const id = map[key];
|
||
const item = id && this.actions.items.get(id);
|
||
if (item && (!item.when || item.when())) {
|
||
if (document.querySelector('.overlay') && !['saveAll'].includes(id)) return;
|
||
e.preventDefault();
|
||
e.stopPropagation();
|
||
this.actions.run(id);
|
||
} else if (e.key === 'Escape' && !document.querySelector('.overlay') && this.open?.bottom && !e.target.closest('.monaco-editor')) {
|
||
this.editors.editor()?.focus();
|
||
}
|
||
}, true);
|
||
}
|
||
|
||
mainMenu(at) {
|
||
const item = (id, extra = {}) => {
|
||
const a = this.actions.items.get(id);
|
||
return a ? { label: a.label, kbd: a.kbd ? kbd(a.kbd) : '', icon: a.icon, action: () => this.actions.run(id), ...extra } : null;
|
||
};
|
||
const plugin = (label) => this.plugins?.menuIds(label) || [];
|
||
const section = (label, ids) => ({ label, items: [...ids, ...(plugin(label).length ? ['-', ...plugin(label)] : [])].map((id) => (id === '-' ? '-' : item(id))).filter(Boolean).filter((x, i, all) => x !== '-' || (i > 0 && i < all.length - 1 && all[i - 1] !== '-')) });
|
||
// every tool window of this project (API Platform, Doctrine, Database, Symfony…), grouped by where it opens, with its icon and shortcut
|
||
// Symfony first, all together (its windows + the creators that are not windows: command wizard, new entity…), then the others by side
|
||
const SYMFONY = ['console', 'controllers', 'doctrine', 'apiplatform', 'sfForms', 'validation', 'security', 'sfEvents', 'messenger', 'translations', 'audit'];
|
||
const toolEntry = (tool) => ({ label: t(tool.label), kbd: tool.key ? kbd(tool.key) : '', icon: tool.icon, action: () => this.showTool(tool.id, true) });
|
||
const tools = Object.values(this.tools || {});
|
||
const symfonyTools = SYMFONY.map((id) => tools.find((tool) => tool.id === id)).filter(Boolean);
|
||
const sides = { left: [], bottom: [], right: [] };
|
||
for (const tool of tools) if (!symfonyTools.includes(tool)) (sides[tool.side] || sides.right).push(tool);
|
||
const toolItems = [];
|
||
if (symfonyTools.length) {
|
||
toolItems.push({ label: 'Symfony', items: [
|
||
...symfonyTools.map(toolEntry),
|
||
'-',
|
||
...['newSymfonyCommand', 'newCastorTask', 'doctrineNewEntity', 'newFixtures', 'loadFixtures', 'newTestWizard', 'newHub'].map((id) => item(id)).filter(Boolean),
|
||
] });
|
||
}
|
||
for (const side of ['left', 'bottom', 'right']) {
|
||
const list = sides[side].sort((a, b) => String(t(a.label)).localeCompare(String(t(b.label))));
|
||
if (!list.length) continue;
|
||
if (toolItems.length) toolItems.push('-');
|
||
for (const tool of list) toolItems.push(toolEntry(tool));
|
||
}
|
||
menu([
|
||
section('File', ['newFile', 'openProject', 'saveAll', 'closeTab', 'localHistory', '-', 'settings', 'plugins', 'closeProject']),
|
||
section('Edit', ['find', 'replace', 'findInFiles', 'replaceInFiles', 'comment']),
|
||
{ label: 'Tool Windows', items: toolItems },
|
||
section('View', ['project', 'structure', 'commitTool', 'gameTool', 'claudeTool', 'runTool', 'debugTool', 'findTool', 'problemsTool', 'terminalTool', 'logsTool', 'gitLog', 'hideTools', 'resetLayout', '-', 'zoomIn', 'zoomOut', 'resetZoom', 'zoomIdeIn', 'zoomIdeOut', 'resetIdeZoom', 'resetAllZoom', '-', 'split', 'hexView', 'htmlPreview', 'theme']),
|
||
section('Navigate', ['searchEverywhere', 'searchText', 'gotoClass', 'gotoFile', 'gotoSymbol', 'recentFiles', 'recentChanges', 'gotoLine', '-', 'declaration', 'implementations', 'callHierarchy', 'fileStructure', 'back', 'forward', 'selectInProject']),
|
||
section('Code', ['reformat', 'comment', 'rebuildIndex']),
|
||
section('Refactor', ['rename', 'usages', 'callHierarchy']),
|
||
section('Run', ['run', 'debug', 'test', 'shot', 'rerun', 'stop', 'runConfigs', 'runAnything', '-', 'debugResume', 'stepOver', 'stepInto', 'stepOut', 'runToCursor', 'toggleBreakpoint', 'exceptionBreakpoints', 'debugTool', '-', 'profile', 'profileTool', '-', 'preview', 'previewTab', '-', 'createInstaller']),
|
||
section('Tools', ['scriptsTool', 'newScript', 'newCastorTask', ...(this.scripts?.actionIds || []), '-', 'symfonyConsole', 'symfonyForms', 'symfonyValidation', 'symfonySecurity', 'newSymfonyCommand', 'newFixtures', 'newTestWizard', 'symfonyEvents', 'messengerTool', 'translationsTool', 'securityAuditTool', 'plugins', 'pluginUpdates', 'extensions', 'opencode', 'opencodeAsk', 'videoPreview', '-', 'osIntegration']),
|
||
section('Git', ['vcsSetup', 'vcsRemotes', '-', 'commit', 'commitAll', 'push', 'update', 'branches', 'gitLog', 'fileHistory', 'annotate', 'rollbackFile', 'gitStashes', 'gitTags', 'gitRemotes', 'gitSubmodules', 'gitCredentials', 'sshKeys']),
|
||
{ label: 'Help', items: [
|
||
{ label: 'Documentation', icon: 'book', action: () => this.docs.open() },
|
||
{ label: 'Symfony tutorial', icon: 'star', action: () => this.tutorial.start('symfony') },
|
||
{ label: 'Keyboard Shortcuts', action: () => this.shortcuts() },
|
||
{ label: 'JumPHP Documentation', action: () => this.openUrl('https://jumphp.net/docs') },
|
||
...(this.logsPanel ? [{ label: 'Show Logs', icon: 'logfile', action: () => this.showTool('logs', true) }] : []),
|
||
...(backend.kind === 'native' ? [{ label: 'What\'s New…', icon: 'star', action: () => this.whatsNew.show() }] : []),
|
||
...(backend.kind === 'native' && this.updates && this.updates.state !== 'off' ? ['-',
|
||
{ label: 'Check for Updates…', icon: 'download', action: () => this.checkForUpdates() },
|
||
{ label: 'Update Automatically', checked: !!this.updates.auto, action: () => backend.invoke('update.auto', { on: !this.updates.auto }).then((st) => this.updateState(st)) },
|
||
'-'] : []),
|
||
{ label: 'About JumPHP IDE', action: () => dialog({ title: 'JumPHP IDE', body: el('p', {}, `JumPHP IDE ${this.updates?.current || ''} — an IDE for PHP games and apps, written in PHP (JumPHP) with Monaco, the editor of VS Code.`) }) },
|
||
] },
|
||
].map((s) => (s.items && !s.items.length ? null : s)).filter(Boolean), at);
|
||
}
|
||
|
||
projectMenu(at) {
|
||
const items = [{ head: this.project.name }];
|
||
if (this.project.root) items.push({ label: this.project.root, disabled: true });
|
||
for (const m of this.project.modules || []) items.push({ label: `${m.title} (${m.kindLabel})`, icon: { app: 'app', hybrid: 'hybrid', cpc: 'disk', port: 'fork' }[m.kind] || 'game', action: () => this.tree.reveal(m.dir || '', true) });
|
||
if (backend.kind === 'native') items.push('-', { label: 'Open Another Project…', icon: 'folder', action: () => this.switchProject() }, { label: 'Close Project', icon: 'close', action: () => backend.invoke('projects.close').then(() => location.reload()) });
|
||
else if (backend.config.project?.repoUrl) items.push('-', { label: 'Repository on Git', icon: 'globe', action: () => this.openUrl(backend.config.project.repoUrl) }, { label: 'All my projects', icon: 'folder', action: () => { location.href = '/ide'; } });
|
||
menu(items, at);
|
||
}
|
||
|
||
async switchProject() {
|
||
const state = await backend.invoke('session.state');
|
||
chooser([...(state.recent || []).map((r) => ({ label: r.name, hint: r.path, icon: 'folder', action: () => backend.invoke('projects.open', { path: r.path }).then(() => location.reload()) })),
|
||
'-', { label: 'Welcome screen…', icon: 'star', action: () => backend.invoke('projects.close').then(() => location.reload()) }], { placeholder: 'Open a recent project' });
|
||
}
|
||
|
||
/** The status bar shows when this computer's Claude answers the web IDE. */
|
||
/** The IDE's own updates (games/ide/src/SelfUpdate.php): installed in the background, then one click to restart. */
|
||
updateState(st, force = false) {
|
||
const before = this.updates?.state;
|
||
if (st?.current && this.whatsNew && !this.whatsNewChecked) { this.whatsNewChecked = true; this.whatsNew.check(st.current); }
|
||
this.updates = st;
|
||
if (st?.state === 'installed' && this.restartWhenInstalled) { this.restartWhenInstalled = false; this.restartForUpdate(); return; }
|
||
if (!st || (st.state === before && !force)) return;
|
||
const restart = { label: 'Restart Now', action: () => this.restartForUpdate() };
|
||
if (st.state === 'installed') {
|
||
notify(t('JumPHP IDE {version} is installed: restart to use it (or it starts next time).', { version: st.version }) + (st.notes ? ' ' + st.notes : ''), 'success', { title: t('Update'), actions: [restart, { label: 'Later', action: () => null }], timeout: 0 });
|
||
} else if (st.state === 'available' && (force || !(st.installable && st.auto))) {
|
||
const actions = st.installable ? [{ label: 'Install', action: () => backend.invoke('update.install').then((s) => this.updateState(s)) }] : [];
|
||
notify(t('JumPHP IDE {version} is out (this one: {current}).', { version: st.version, current: st.current }) + (st.installable ? '' : ' ' + t('This IDE runs from its sources: update them with git.')), 'info', { title: t('Update'), actions, timeout: 0 });
|
||
} else if (st.manual && st.state === 'latest') {
|
||
notify(t('JumPHP IDE {current} is the newest version.', { current: st.current }), 'info', { title: t('Update') });
|
||
} else if (st.state === 'error' && (st.manual || /was installed, but/.test(st.error || ''))) {
|
||
notify(st.error || t('Cannot check for updates.'), 'error', { title: t('Update') });
|
||
}
|
||
if (st.state === 'installing' && !this.updateTask) this.updateTask = this.task(t('Downloading JumPHP IDE {version}…', { version: st.version || '' }));
|
||
if (st.state !== 'installing' && this.updateTask) { this.updateTask(); this.updateTask = null; }
|
||
if ((st.manual || force) && st.state === 'installing') {
|
||
notify(t('Downloading JumPHP IDE {version}…', { version: st.version }), 'info', { title: t('Update') });
|
||
}
|
||
}
|
||
|
||
/** The header's update button: check, download and install the newest version, then restart at once. */
|
||
async updateNow() {
|
||
const btn = $('updateBtn');
|
||
btn.disabled = true;
|
||
this.restartWhenInstalled = true;
|
||
try {
|
||
let st = await backend.invoke('update.check');
|
||
if (st.state === 'installed') { this.restartForUpdate(); return; }
|
||
if (st.state === 'available') {
|
||
if (!st.installable) { notify(t('This IDE runs from its sources: update them with git.'), 'info', { title: t('Update') }); this.restartWhenInstalled = false; return; }
|
||
st = await backend.invoke('update.install');
|
||
if (st.state === 'installed') { this.restartForUpdate(); return; }
|
||
}
|
||
if (st.state === 'latest') { notify(t('JumPHP IDE {current} is the newest version.', { current: st.current }), 'info', { title: t('Update') }); this.restartWhenInstalled = false; return; }
|
||
if (st.state === 'error') { notify(st.error || t('Cannot update.'), 'error', { title: t('Update') }); this.restartWhenInstalled = false; return; }
|
||
this.updateState(st, true); // downloading: the 'installed' event restarts it (updateState)
|
||
} catch (e) {
|
||
this.restartWhenInstalled = false;
|
||
notify(e.message, 'error', { title: t('Update') });
|
||
} finally {
|
||
setTimeout(() => { btn.disabled = false; }, 4000);
|
||
}
|
||
}
|
||
|
||
/** Help > Check for Updates: the answer comes as an update.state event (or at once: installing, installed). */
|
||
checkForUpdates() {
|
||
backend.invoke('update.check').then((st) => this.updateState(st, st.state !== 'checking'))
|
||
.catch((e) => notify(e.message, 'error', { title: t('Update') }));
|
||
}
|
||
|
||
async restartForUpdate() {
|
||
try { await this.editors?.saveAll?.(); } catch { /* the files are saved as one types anyway */ }
|
||
backend.invoke('update.restart').catch((e) => notify(e.message, 'error', { title: t('Update') }));
|
||
}
|
||
|
||
bridgeStatus(st) {
|
||
let item = document.getElementById('sbBridge');
|
||
if (!st?.on) { item?.remove(); return; }
|
||
if (!item) {
|
||
item = el('span.sb-item', { id: 'sbBridge', title: 'Claude for jumphp.net: the web IDE uses the Claude of this computer (account menu to turn it off)' });
|
||
$('sbTask').before(item);
|
||
}
|
||
item.textContent = st.state === 'working' ? `✦ Claude for jumphp.net: working on ${st.project}…` : '✦ Claude for jumphp.net';
|
||
}
|
||
|
||
async userMenu(at) {
|
||
const user = this.session?.user || backend.config.user;
|
||
// the desktop: this computer's Claude can answer the web IDE (jumphp.net/ide), ClaudeBridge
|
||
const bridge = backend.kind === 'native' && user ? await backend.invoke('bridge.status').catch(() => null) : null;
|
||
const accounts = backend.kind === 'native' && user ? await backend.invoke('session.accounts').catch(() => null) : null;
|
||
menu(user ? [{ head: user.login }, { label: 'My page on jumphp.net', icon: 'globe', action: () => this.openUrl(user.url || 'https://jumphp.net') },
|
||
{ label: user.forge === 'github' ? 'My GitHub' : 'My Git (git.jumphp.net)', icon: 'branch', action: () => this.openUrl(user.forge === 'github' ? `https://github.com/${user.login}` : `https://git.jumphp.net/${user.login}`) },
|
||
bridge ? { label: 'Claude for jumphp.net (the web IDE uses this computer\'s Claude)', icon: 'claude', checked: bridge.on,
|
||
action: () => backend.invoke('bridge.enable', { on: !bridge.on }).then((s) => notify(s.on ? 'jumphp.net/ide now uses the Claude of this computer, while the JumPHP IDE is open.' : 'Claude for jumphp.net is off.', 'info', { title: 'Claude' })) } : null,
|
||
...(accounts ? [{ head: 'Git accounts' },
|
||
...accounts.accounts.map((a) => ({ label: a.login, icon: 'user', checked: a.login === accounts.active,
|
||
action: () => backend.invoke('session.switch', { login: a.login }).then(() => { notify(`Now using ${a.login}.`, 'success', { title: 'Git' }); this.git?.refresh(); }).catch((e) => notify(e.message, 'error')) })),
|
||
{ label: 'Add another account…', icon: 'plus', action: () => backend.invoke('session.login', { another: true }).then(() => notify('Account added.', 'success', { title: 'Git' })).catch((e) => !/cancel/i.test(e.message) && notify(e.message, 'error')) },
|
||
...(this.project?.root ? [{ label: `Use ${accounts.active} for this project`, checked: accounts.projectAccount === accounts.active,
|
||
action: () => backend.invoke('project.setAccount', { login: accounts.active }).then(() => notify(`This project pushes and publishes as ${accounts.active}.`, 'success', { title: 'Git' })).catch((e) => notify(e.message, 'error')) }] : []), '-'] : []),
|
||
backend.kind === 'native' ? { label: 'Git permissions (create repositories)…', icon: 'branch', action: () => this.openUrl(`https://${this.session?.server || 'jumphp.net'}/compte/git`) } : null,
|
||
backend.kind === 'native' ? { label: 'Sign out', icon: 'logout', action: () => backend.invoke('session.logout').then(() => this.refreshSession()).then(() => notify('Signed out.', 'info', { title: 'jumphp.net' })) } : null].filter(Boolean)
|
||
: [{ label: 'Sign in with jumphp.net', icon: 'user', action: () => backend.invoke('session.login', { another: false }).then(() => this.refreshSession()).then(() => notify('Signed in.', 'success', { title: 'jumphp.net' })).catch((e) => !/cancel/i.test(e.message) && notify(e.message, 'error', { title: 'Sign in' })) }], at);
|
||
}
|
||
|
||
findInFiles(options = {}) {
|
||
const selection = this.editors.editor()?.getModel() && this.editors.editor().getModel().getValueInRange(this.editors.editor().getSelection());
|
||
this.find.show({ query: options.query ?? (selection && !selection.includes('\n') ? selection : ''), replace: !!options.replace, include: options.include });
|
||
}
|
||
|
||
// Play: the game, the scene of a file, the tests of a test file ----------------------------------------------
|
||
|
||
/** The game module a project path belongs to. */
|
||
moduleOf(path) {
|
||
return [...(this.project.modules || [])].sort((a, b) => (b.dir || '').length - (a.dir || '').length)
|
||
.find((m) => !m.dir || path.startsWith(m.dir + '/')) || null;
|
||
}
|
||
|
||
/** What Play does on a file: {kind: 'test'|'scene'|'game', label, module, relative, scene} or null. */
|
||
playTarget(path) {
|
||
if (!path || path.startsWith('/') || !path.endsWith('.php')) return null;
|
||
const caps = this.project.capabilities || {};
|
||
const module = this.moduleOf(path);
|
||
if (!module || !['game', 'hybrid', 'cpc', 'port', 'app'].includes(module.kind)) return null;
|
||
const relative = module.dir ? path.slice(module.dir.length + 1) : path;
|
||
const name = basename(path).replace(/\.php$/, '');
|
||
if (/^tests\/.+Test\.php$/.test(relative)) {
|
||
return caps.run || caps.tests ? { kind: 'test', label: `Run '${name}'`, module, relative } : null;
|
||
}
|
||
if (!caps.run && !caps.preview) return null;
|
||
if (/^src\/Scene\/.+\.php$/.test(relative) && module.kind !== 'app') {
|
||
return { kind: 'scene', label: `Play '${name}'`, module, relative, scene: this.classOf(path) };
|
||
}
|
||
return { kind: 'game', label: `Play '${module.title || module.id}'`, module, relative };
|
||
}
|
||
|
||
/** The class a PHP file declares (namespace + first class), from its open model or its name. */
|
||
classOf(path) {
|
||
const text = this.editors.files.get(path)?.model?.getValue() || '';
|
||
// not open: App\ + its path under src/ (PSR-4, as every JumPHP game)
|
||
if (!text) return 'App\\' + path.replace(/^.*?\bsrc\//, '').replace(/\.php$/, '').split('/').join('\\');
|
||
const ns = text.match(/^\s*namespace\s+([\w\\]+)\s*;/m)?.[1];
|
||
const cls = text.match(/^\s*(?:final\s+|abstract\s+|readonly\s+)*class\s+(\w+)/m)?.[1] || basename(path).replace(/\.php$/, '');
|
||
return ns ? `${ns}\\${cls}` : cls;
|
||
}
|
||
|
||
async playFile(path) {
|
||
const target = this.playTarget(path);
|
||
if (!target) { notify('Nothing to play in ' + basename(path), 'info'); return; }
|
||
const caps = this.project.capabilities || {};
|
||
await this.editors.saveAll(true);
|
||
if (target.kind === 'test') {
|
||
if (caps.run) this.runner.start({ id: 'adhoc', kind: 'test', label: basename(path).replace(/\.php$/, ''), command: ['bin/jumphp', 'test', target.module.id, target.relative] });
|
||
else this.runner.remoteTests(target.relative);
|
||
return;
|
||
}
|
||
if (this.game) { this.game.play({ scene: target.kind === 'scene' ? target.scene : null }); return; }
|
||
// the desktop: the game in its own window, at the scene of the file
|
||
const env = target.kind === 'scene' ? { JUMPHP_SCENE: target.scene } : {};
|
||
this.runner.start({ id: 'adhoc', kind: 'run', label: target.label.replace(/^Play /, ''), command: ['bin/jumphp', 'run', target.module.id] }, env);
|
||
}
|
||
|
||
typeHierarchy() {
|
||
this.showTool('hierarchy');
|
||
this.hierarchy.update(true);
|
||
}
|
||
|
||
async findUsages() {
|
||
const editor = this.editors.editor();
|
||
const model = editor?.getModel();
|
||
if (!model) return;
|
||
const pos = editor.getPosition();
|
||
const path = this.editors.activePath();
|
||
const at = { path, text: model.getValue(), line: pos.lineNumber, column: pos.column };
|
||
// YAML files ask their navigation (yaml-nav.js); in PHP / Twig, a string may be a YAML key (translation, action...)
|
||
let refs = /\.(ya?ml|neon)$/i.test(path) ? [] : await backend.invoke('php.references', at).catch(() => []);
|
||
if (!refs.length && /\.(ya?ml|neon|php|twig)$/i.test(path)) refs = await backend.invoke('yaml.references', at).catch(() => []);
|
||
if (!refs.length) { this.status('No usages found'); return; }
|
||
this.showUsages(refs, model.getWordAtPosition(pos)?.word);
|
||
}
|
||
|
||
showUsages(refs, name) { this.find.usages(refs, name); }
|
||
|
||
fileStructure() { fileStructure(this); }
|
||
|
||
/** The extension's page on jumphp.net: summary, features, screenshots, Documentation, Tutorial; the samples and the example game are listed. */
|
||
async editExtensionPage() {
|
||
let page;
|
||
try { page = await backend.invoke('extension.page.get'); } catch (e) { notify(e.message, 'error', { title: 'Extension page' }); return; }
|
||
const area = (value, rows, ph) => el('textarea.input', { rows, placeholder: ph, style: { width: '100%', fontFamily: 'monospace' } }, value);
|
||
const summary = el('input.input', { value: page.summary, maxlength: 200, placeholder: 'One line: what it brings' });
|
||
const features = area(page.features, 4, 'One feature per line (12 at most)');
|
||
const shots = area(page.screenshots, 2, 'One picture per line (https address, or a path in the package, e.g. doc/shot.png)');
|
||
const doc = area(page.doc, 10, 'Markdown: the Documentation button');
|
||
const tuto = area(page.tutorial, 10, 'Markdown, one "## Step" per action: the Tutorial button (empty = built from the samples)');
|
||
const field = (label, node) => el('label.field', {}, el('span', {}, label), node);
|
||
dialog({
|
||
title: 'Page of ' + (page.name || page.id) + ' on jumphp.net', wide: true,
|
||
body: el('div', {}, field('Summary', summary), field('Features', features), field('Screenshots', shots),
|
||
field('Documentation (doc/index.md)', doc), field('Tutorial, step by step (doc/tutorial.md)', tuto),
|
||
el('p.pub-faint', {}, `Samples (${page.samples.length}): ${page.samples.join(', ') || 'none yet, add doc/samples/*.php (one scene per thing it does)'}. `
|
||
+ (page.demo ? `Example game: games/${page.id}-demo: it opens in the browser on jumphp.net once published as the project ${page.id}-demo.` : 'No example game (games/' + page.id + '-demo).'))),
|
||
buttons: [{ label: 'Cancel' }, { label: 'Save', primary: true, action: async () => {
|
||
try {
|
||
await backend.invoke('extension.page.save', { summary: summary.value, features: features.value, screenshots: shots.value, doc: doc.value, tutorial: tuto.value });
|
||
notify('Saved in the package. Publish extension sends it to jumphp.net.', 'success', { title: 'Extension page' });
|
||
} catch (e) { notify(e.message, 'error', { title: 'Extension page' }); return false; }
|
||
} }],
|
||
});
|
||
}
|
||
|
||
/** Publish extension: the package in its own GitHub repository, tagged; Packagist reads it (submitted once, by hand). */
|
||
publishExtension() {
|
||
const ext = this.project.extension;
|
||
const version = el('input.input', { value: ext.nextVersion });
|
||
const pkUser = el('input.input', { placeholder: 'your Packagist user name', style: { width: '200px' } });
|
||
const pkToken = el('input.input', { type: 'password', placeholder: 'API token (kept: leave empty)', style: { flex: 1 } });
|
||
backend.invoke('packagist.get').then((p) => { pkUser.value = p.username || ''; if (p.saved) pkToken.placeholder = 'API token saved (leave empty to keep it)'; });
|
||
dialog({
|
||
title: 'Publish extension ' + (ext.name || ext.id), wide: true,
|
||
body: el('div', {}, el('label.field', {}, el('span', {}, 'Version (the Git tag v<version>)'), version),
|
||
el('label.field', {}, el('span', {}, 'Packagist (optional): your user name and API token (packagist.org > Profile > Show API token). The IDE then makes or updates the package itself.'),
|
||
el('div', { style: { display: 'flex', gap: '6px' } }, pkUser, pkToken)),
|
||
el('p.pub-faint', {}, `${ext.dir} goes to its own public repository on your Git account (jumphp-${ext.id}, made the first time), under the Composer name <your login>/${ext.id}, tagged. `
|
||
+ 'Then submit it once on packagist.org (the IDE opens the page); jumphp.net lists it in its extensions directory a few hours later.')),
|
||
buttons: [{ label: 'Cancel' }, { label: 'Edit its page…', action: () => { setTimeout(() => this.editExtensionPage(), 0); } }, { label: 'Publish', primary: true, action: async () => {
|
||
const done = this.task('Publishing the extension…');
|
||
try {
|
||
if (pkToken.value.trim()) await backend.invoke('packagist.set', { username: pkUser.value.trim(), token: pkToken.value.trim() });
|
||
const r = await backend.invoke('extension.publish', { version: version.value.trim() });
|
||
const onPackagist = r.packagist === 'created' || r.packagist === 'updated';
|
||
notify(onPackagist ? `${r.package} ${r.tag} is on GitHub and ${r.packagist} on Packagist; jumphp.net lists it shortly.`
|
||
: `${r.package} ${r.tag} is on GitHub. ${r.packagist?.startsWith('error') ? r.packagist + '. ' : ''}Submit ${r.url} on Packagist (once): its page opens.`,
|
||
onPackagist ? 'success' : 'warning', { title: 'Extension', timeout: 0,
|
||
actions: [{ label: 'Open Packagist', action: () => this.openUrl(onPackagist ? 'https://packagist.org/packages/' + r.package : r.submitUrl) }, { label: 'Open the repository', action: () => this.openUrl(r.url) }] });
|
||
if (!onPackagist) { copyText(r.url); this.openUrl(r.submitUrl); }
|
||
} catch (e) { notify(e.message, 'error', { title: 'Publish extension' }); return false; } finally { done(); }
|
||
} }],
|
||
});
|
||
}
|
||
|
||
async publish() {
|
||
if (this.project.extension) { this.publishExtension(); return; }
|
||
if (this.project.needsRepository) { this.createRepository(); return; }
|
||
if (this.project.needsPlayground) { this.putOnPlayground(); return; }
|
||
const done = this.task('Publishing on jumphp.net…');
|
||
try {
|
||
const result = await backend.invoke('playground.publish');
|
||
notify(result.message || 'Published', result.ok === false ? 'error' : 'success', { title: 'jumphp.net', actions: result.url ? [{ label: 'Open its page', action: () => this.openUrl(result.url) }] : [] });
|
||
} catch (e) { this.githubError(e, 'Publish', () => this.publish()); } finally { done(); }
|
||
}
|
||
|
||
/**
|
||
* The project has its own GitHub repository but jumphp.net does not know it: it is imported there (not listed), then Publish works.
|
||
* (The repository made by "Create its GitHub repository" or by hand, without the import, left nothing to publish from the IDE.)
|
||
*/
|
||
/** The import on jumphp.net again, without the confirmation (the user just clicked the button for it). */
|
||
async retryPlayground() {
|
||
const done = this.task('Putting the project on jumphp.net…');
|
||
try {
|
||
const r = await backend.invoke('project.putOnPlayground');
|
||
notify(`On jumphp.net as “${r.playground}”. Publish it now to make it playable.`, 'success', { title: 'jumphp.net', timeout: 0,
|
||
actions: [{ label: 'Reload the project', action: () => location.reload() }] });
|
||
setTimeout(() => location.reload(), 2500);
|
||
} catch (e) { this.githubError(e, 'jumphp.net', () => this.retryPlayground()); } finally { done(); }
|
||
}
|
||
|
||
async putOnPlayground() {
|
||
if (!(await confirm('Put it on jumphp.net?', `This project is on GitHub (${this.project.repository}) but not on jumphp.net yet. jumphp.net takes the repository (not listed in the directory until you say so) and Publish works from then on.`, { ok: 'Put it on jumphp.net' }))) return;
|
||
const done = this.task('Putting the project on jumphp.net…');
|
||
try {
|
||
const r = await backend.invoke('project.putOnPlayground');
|
||
notify(`On jumphp.net as “${r.playground}”. Publish it now to make it playable.`, 'success', { title: 'jumphp.net', timeout: 0,
|
||
actions: [{ label: 'Reload the project', action: () => location.reload() }] });
|
||
setTimeout(() => location.reload(), 2500);
|
||
} catch (e) { this.githubError(e, 'jumphp.net', () => this.putOnPlayground()); } finally { done(); }
|
||
}
|
||
|
||
/**
|
||
* An error of jumphp.net / GitHub as a notification with buttons: the ones the server attached (`e.actions`: login = sign in again then `retry`,
|
||
* retry, open = a url), else "Sign in again" when the message is about a refused token / an ended session.
|
||
*/
|
||
githubError(e, title, retry) {
|
||
let actions = Array.isArray(e.actions) ? e.actions : [];
|
||
if (!actions.length && /bad credentials|refuses the saved token|refused the token saved|refuses the saved token|sign in again|session has ended|token does not have|sign in with jumphp\.net first|reconnect|reconnectez/i.test(e.message)) {
|
||
actions = [{ action: 'login', label: 'Sign in again' }];
|
||
}
|
||
const buttons = actions.map((a) => ({ label: a.label || a.action, action: () => {
|
||
if (a.action === 'login') {
|
||
return backend.invoke('session.login', { another: false })
|
||
.then(() => { notify('Signed in again.', 'success', { title }); retry(); })
|
||
.catch((err) => !/cancel/i.test(err.message) && notify(err.message, 'error', { title: 'Sign in' }));
|
||
}
|
||
if (a.action === 'open' && a.url) return this.openUrl(a.url);
|
||
if (a.action === 'retry') return retry();
|
||
return null;
|
||
} }));
|
||
notify(e.message, 'error', { title, timeout: buttons.length || title !== 'Publish' ? 0 : undefined, actions: buttons });
|
||
}
|
||
|
||
/** Its own public repository on the user's GitHub account, everything committed and pushed, then a jumphp.net project. */
|
||
createRepository() {
|
||
const module = (this.project.modules || [])[0];
|
||
const name = el('input.input', { value: module?.id || this.project.name || '' });
|
||
dialog({
|
||
title: 'Create its Git repository', wide: true,
|
||
body: el('div', {}, el('label.field', {}, el('span', {}, 'Name of the repository (on your Git account, public)'), name),
|
||
el('p.pub-faint', {}, 'The IDE creates the repository, commits every file of the project (but what .gitignore leaves out) and pushes it. '
|
||
+ 'JumPHP stays as the "jumphp" remote, for its updates only. Then the project is put on jumphp.net (not listed): Publish works.')),
|
||
buttons: [{ label: 'Cancel' }, { label: 'Create and push', primary: true, action: async () => {
|
||
const done = this.task('Creating the Git repository…');
|
||
try {
|
||
const r = await backend.invoke('project.createRepository', { name: name.value.trim() });
|
||
if (r.message && !r.playground) {
|
||
// pushed, but jumphp.net did not take the project (token refused, session ended...): the way out is in the buttons
|
||
const again = () => backend.invoke('session.login', { another: false })
|
||
.then(() => { notify('Signed in again.', 'success', { title: 'Git' }); return this.retryPlayground(); })
|
||
.catch((err) => !/cancel/i.test(err.message) && notify(err.message, 'error', { title: 'Sign in' }));
|
||
const extra = (r.actions || []).filter((a) => a.action === 'open' && a.url).map((a) => ({ label: a.label || 'Open', action: () => this.openUrl(a.url) }));
|
||
notify(r.message, 'warning', { title: 'Git', timeout: 0, actions: [
|
||
{ label: 'Sign in again', action: again },
|
||
{ label: 'Put it on jumphp.net', action: () => this.retryPlayground() },
|
||
...extra,
|
||
{ label: 'Open the repository', action: () => this.openUrl(r.url) },
|
||
] });
|
||
} else notify(r.message || `${r.repository}: pushed${r.playground ? ', and on jumphp.net' : ''}.`, r.message ? 'warning' : 'success',
|
||
{ title: 'Git', timeout: 0, actions: [{ label: 'Open the repository', action: () => this.openUrl(r.url) }, { label: 'Reload the project', action: () => location.reload() }] });
|
||
} catch (e) {
|
||
// the IDE's picture of the project was older than its repository (made a moment ago): there is nothing to create, only to put on jumphp.net
|
||
if (/already has its repository/i.test(e.message)) {
|
||
this.project.needsRepository = false;
|
||
const info = await backend.invoke('project.info').catch(() => null);
|
||
if (info) Object.assign(this.project, info);
|
||
if (this.project.playground) { notify('The repository exists and the project is on jumphp.net.', 'success', { title: 'Git', actions: [{ label: 'Reload the project', action: () => location.reload() }] }); return; }
|
||
return this.retryPlayground();
|
||
}
|
||
// GitHub refused the token jumphp.net kept (revoked / expired): sign in again, then the same dialog
|
||
if (/bad credentials|refuses the saved token|refused the token saved|sign in again|session has ended|sign in with jumphp\.net first/i.test(e.message)) {
|
||
notify(e.message, 'error', { title: 'Git', timeout: 0, actions: [{ label: 'Sign in again', action: () => backend.invoke('session.login', { another: false })
|
||
.then(() => { notify('Signed in again.', 'success', { title: 'Git' }); this.createRepository(); })
|
||
.catch((err) => !/cancel/i.test(err.message) && notify(err.message, 'error', { title: 'Sign in' })) }] });
|
||
} else notify(e.message, 'error', { title: 'Git' });
|
||
} finally { done(); }
|
||
} }],
|
||
});
|
||
}
|
||
|
||
afterPush() {
|
||
if (backend.kind === 'native' && this.project.playground) {
|
||
notify('Pushed. jumphp.net publishes the new version in a moment.', 'info', { title: 'jumphp.net', actions: [{ label: 'Check now', action: () => this.publish() }] });
|
||
}
|
||
}
|
||
|
||
afterCommit(result) { if (result.pushed) this.afterPush(); }
|
||
|
||
openUrl(url) {
|
||
if (backend.kind === 'native') backend.invoke('native.openUrl', { url }).catch(() => window.open(url, '_blank'));
|
||
else window.open(url, '_blank', 'noopener');
|
||
}
|
||
|
||
settings() {
|
||
const field = (label, control) => el('label.field', {}, el('span', {}, label), control);
|
||
const theme = el('select.input', {}, el('option', { value: 'dark' }, 'Dark'), el('option', { value: 'light' }, 'Light'));
|
||
theme.value = prefs.get('theme', 'dark');
|
||
const size = el('input.input', { type: 'number', min: 9, max: 28, step: 0.5, value: prefs.get('fontSize', 13.5) });
|
||
const minimap = el('input', { type: 'checkbox', checked: prefs.get('minimap', false) });
|
||
const autosave = el('input', { type: 'checkbox', checked: prefs.get('autosave', true) });
|
||
const previewTabs = el('input', { type: 'checkbox', checked: prefs.get('previewTabs', true) });
|
||
const autoscroll = el('input', { type: 'checkbox', checked: prefs.get('autoscroll', false) });
|
||
const sideBySide = el('input', { type: 'checkbox', checked: prefs.get('diffSideBySide', true) });
|
||
const keepLayout = el('input', { type: 'checkbox', checked: prefs.get('restoreLayout', true) });
|
||
const schemaAuto = el('input', { type: 'checkbox', checked: SchemaCheck.auto() });
|
||
const offerTutorial = el('input', { type: 'checkbox', checked: !TutorialManager.neverOffer() });
|
||
const vcsRow = this.project.capabilities?.vcsManage && backend.kind === 'native'
|
||
? el('div', { style: { margin: '10px 0' } }, el('b', {}, t('Version control')), ' ', el('span.pub-faint', {}, this.project.capabilities.vcs === 'svn' ? 'Subversion' : this.project.capabilities.git ? 'Git' : t('None')), ' ',
|
||
el('button.btn.small', { onclick: () => openVcsSetup(this) }, t('Change…')), ' ', this.project.capabilities.vcs ? el('button.btn.small', { onclick: () => openRemotes(this) }, t('Remotes and hosting…')) : null)
|
||
: null;
|
||
dialog({ title: 'Settings', body: el('div', {}, field('Theme', theme), field('Language (the news; the welcome screen)', languageSelect(() => { this.sendLanguage(); this.welcome?.changeLanguage?.(); })), field('Editor font size', size),
|
||
el('label.checkbox', {}, minimap, 'Show the minimap'), el('br'), el('label.checkbox', {}, autosave, 'Save files automatically'), el('br'),
|
||
el('label.checkbox', {}, previewTabs, 'Open files in a preview tab on single click'), el('br'), el('label.checkbox', {}, autoscroll, 'Always select the opened file in the Project view'), el('br'),
|
||
el('label.checkbox', {}, sideBySide, 'Diffs side by side'), el('br'), el('label.checkbox', {}, keepLayout, 'Restore the windows (tools, tabs, Claude, Terminal) when the IDE reloads'),
|
||
el('br'), el('label.checkbox', {}, offerTutorial, t('Offer the Symfony tutorial after a new Symfony project')),
|
||
this.schemaCheck ? el('div', {}, el('label.checkbox', {}, schemaAuto, t('Check the database schema by itself (when the site starts, when entities or migrations change)'))) : null, vcsRow),
|
||
buttons: [{ label: 'Cancel' }, { label: 'OK', primary: true, action: () => {
|
||
const sizeChanged = +size.value !== prefs.get('fontSize', 13.5);
|
||
prefs.set('fontSize', +size.value); prefs.set('minimap', minimap.checked); prefs.set('autosave', autosave.checked);
|
||
prefs.set('previewTabs', previewTabs.checked); prefs.set('autoscroll', autoscroll.checked); prefs.set('diffSideBySide', sideBySide.checked);
|
||
TutorialManager.setNeverOffer(!offerTutorial.checked);
|
||
this.schemaCheck?.setAuto(schemaAuto.checked);
|
||
prefs.set('restoreLayout', keepLayout.checked); if (!keepLayout.checked) prefs.set(layoutKey(this.projectKey), null);
|
||
if (theme.value !== prefs.get('theme', 'dark')) this.toggleTheme();
|
||
if (sizeChanged) zoom.set('editor', null, { quiet: true }); // the new default replaces the Ctrl + wheel size
|
||
for (const g of this.editors.groups) g.editor.updateOptions({ fontSize: zoom.get('editor'), minimap: { enabled: minimap.checked } });
|
||
} }] });
|
||
}
|
||
|
||
toggleTheme() {
|
||
const next = document.documentElement.dataset.theme === 'light' ? 'dark' : 'light';
|
||
document.documentElement.dataset.theme = next;
|
||
prefs.set('theme', next);
|
||
monaco.editor.setTheme(next === 'light' ? 'jumphp-light' : 'jumphp-dark');
|
||
}
|
||
|
||
shortcuts() {
|
||
const rows = this.actions.list().filter((a) => a.kbd).map((a) => [el('span', {}, t(a.label)), el('kbd', {}, kbd(a.kbd))]).flat();
|
||
dialog({ title: 'Keyboard Shortcuts', wide: true, body: el('div.empty-editor', { style: { height: 'auto' } }, el('div.hints', {}, ...rows)) });
|
||
}
|
||
|
||
showNotifications() {
|
||
const list = notificationHistory();
|
||
dialog({ title: 'Notifications', body: el('div', {}, list.length ? list.map((n) => el('div', { style: { padding: '6px 0', borderBottom: '1px solid var(--border-2)' } },
|
||
el('b', {}, n.title || n.kind), ' ', el('span', { style: { color: 'var(--text-3)', fontSize: '12px' } }, n.time.toLocaleTimeString()), el('div', { style: { color: 'var(--text-2)', whiteSpace: 'pre-wrap' } }, n.text)))
|
||
: el('p', {}, 'No notifications.')) });
|
||
}
|
||
|
||
// open tabs kept between sessions ------------------------------------------------------------------------------
|
||
|
||
saveTabs() {
|
||
if (!this.editors) return;
|
||
prefs.set('tabs:' + this.projectKey, this.editors.groups.map((g) => ({ tabs: g.tabs.filter((t) => t.kind !== 'diff').map((t) => t.path), active: this.editors.activeTab(g)?.path })));
|
||
}
|
||
|
||
// window layout kept between sessions (ide/ui/js/layout.js: one record per project) ---------------------------------
|
||
|
||
/** The layout as it is now (what layout.serialize() cleans and stores). */
|
||
layoutSnapshot() {
|
||
const ed = this.editors;
|
||
const root = document.documentElement;
|
||
const sizes = {};
|
||
for (const v of ['--left-width', '--bottom-height', '--right-width']) { const s = root.style.getPropertyValue(v); if (s) sizes[v] = s.trim(); }
|
||
const view = (g, tab) => {
|
||
if (tab.kind !== 'text') return null;
|
||
const st = g.modelTab === tab && g.editor.getModel() ? g.editor.saveViewState() : tab.viewState;
|
||
const c = st?.cursorState?.[0];
|
||
if (!c) return null;
|
||
const sel = c.selectionStart && c.position && (c.selectionStart.lineNumber !== c.position.lineNumber || c.selectionStart.column !== c.position.column)
|
||
? [c.selectionStart.lineNumber, c.selectionStart.column, c.position.lineNumber, c.position.column] : undefined;
|
||
return { line: c.position?.lineNumber, col: c.position?.column, top: st.viewState?.scrollTop, left: st.viewState?.scrollLeft, sel };
|
||
};
|
||
const rcOf = (tab) => this.claude?.rcOf?.(tab) || null;
|
||
return {
|
||
tools: { open: { ...this.open }, sizes, sides: this.tools.game ? { game: this.tools.game.side } : {} },
|
||
editors: ed ? { activeGroup: Math.max(0, ed.groups.indexOf(ed.focused)),
|
||
groups: ed.groups.map((g) => ({ active: ed.activeTab(g)?.path, tabs: g.tabs.filter((tab) => tab.kind !== 'diff').map((tab) => ({ path: tab.path, view: view(g, tab) })) })) } : { groups: [] },
|
||
tree: { expanded: this.tree ? [...this.tree.open] : [], selected: this.tree?.selected ?? null },
|
||
claude: this.claude?.layoutState?.() || {},
|
||
terminals: this.terminal?.snapshot(rcOf) || {},
|
||
share: { active: !!this.remoteHost?.active },
|
||
zoom: zoom.snapshot(),
|
||
};
|
||
}
|
||
|
||
/** Puts the layout of this project back (after a reload, a restart, a crash). Saving starts only afterwards. */
|
||
async restoreLayout() {
|
||
const key = layoutKey(this.projectKey);
|
||
let rec = null;
|
||
try {
|
||
this.layoutSaver = createSaver(() => (prefs.get('restoreLayout', true) ? serialize(this.layoutSnapshot()) : null), (r) => prefs.set(key, r));
|
||
if (prefs.get('restoreLayout', true)) rec = migrate(prefs.get(key, null));
|
||
if (!rec) { await this.restoreTabs(); return; }
|
||
let list = null;
|
||
if (this.terminal) list = await backend.invoke('terminal.list').catch(() => null);
|
||
let rcTabs = new Map();
|
||
const host = {
|
||
toolIds: () => Object.keys(this.tools),
|
||
files: () => new Set(this.tree.files),
|
||
setSizes: (sizes) => { for (const [v, size] of Object.entries(sizes)) document.documentElement.style.setProperty(v, size); },
|
||
moveTool: (id, side) => this.moveTool(id, side),
|
||
showTool: (id) => this.showTool(id, true),
|
||
closeSide: (side) => this.closeSide(side),
|
||
tree: (r) => {
|
||
this.tree.open = new Set(r.expanded);
|
||
this.tree.selected = r.selected;
|
||
this.tree.save();
|
||
this.tree.render?.();
|
||
},
|
||
zoom: (map) => zoom.restore(map),
|
||
editors: (r) => this.restoreEditors(r),
|
||
terminals: async (r) => { if (this.terminal) rcTabs = await this.terminal.restoreLayout(r, list); host.rcSaved = r.tabs; },
|
||
claude: (r) => this.claude?.restoreLayout?.(r, { restarted: !!list && !!rec.terminals.boot && list.boot !== rec.terminals.boot, rcTabs, rcSaved: host.rcSaved || [] }),
|
||
};
|
||
const done = await restoreLayoutRecord(rec, host);
|
||
if (done.failed.length) console.warn('layout: skipped', done.failed);
|
||
if (rec.share?.active) notify(t('Sharing this IDE was on before the window reloaded. It is not started again by itself: start it from the Share window if you want it.'), 'info', { title: t('Share') });
|
||
} catch (e) {
|
||
console.warn('layout restore failed', e);
|
||
} finally {
|
||
this.layoutSaver.forget();
|
||
this.layoutSaver.flush();
|
||
setInterval(() => this.layoutSaver.flush(), 4000);
|
||
// typing in a box (an unsent message) and scrolling are not events of the app: caught on the way
|
||
document.addEventListener('input', () => this.layoutSaver.save(1000), true);
|
||
document.addEventListener('scroll', () => this.layoutSaver.save(1500), true);
|
||
zoom.onChange(() => this.layoutSaver.save(300));
|
||
this.editors?.on('active', () => this.layoutSaver.save());
|
||
this.editors?.on('cursor', () => this.layoutSaver.save(1500));
|
||
this.layoutReady = true;
|
||
}
|
||
}
|
||
|
||
/** Editor groups with their tabs, then each tab's cursor / selection / scroll (the active tab of a group last). */
|
||
async restoreEditors(r) {
|
||
const ed = this.editors;
|
||
if (!r.groups.length) return;
|
||
for (const [i, g] of r.groups.entries()) {
|
||
const group = i === 0 ? ed.groups[0] : ed.addGroup();
|
||
const apply = (view) => {
|
||
if (!view || !group.editor.getModel()) return;
|
||
const pos = view.line ? { lineNumber: view.line, column: view.col || 1 } : null;
|
||
if (view.sel) group.editor.setSelection({ selectionStartLineNumber: view.sel[0], selectionStartColumn: view.sel[1], positionLineNumber: view.sel[2], positionColumn: view.sel[3] });
|
||
else if (pos) group.editor.setPosition(pos);
|
||
if (view.top !== undefined) group.editor.setScrollTop(view.top);
|
||
if (view.left !== undefined) group.editor.setScrollLeft(view.left);
|
||
};
|
||
const order = [...g.tabs.filter((tab) => tab.path !== g.active), ...g.tabs.filter((tab) => tab.path === g.active)];
|
||
for (const tab of order) {
|
||
await ed.open(tab.path, { group, focus: false });
|
||
apply(tab.view);
|
||
}
|
||
const last = g.tabs.find((tab) => tab.path === g.active);
|
||
if (last) setTimeout(() => apply(last.view), 400); // once the editor has its size
|
||
}
|
||
ed.focus(ed.groups[Math.min(r.activeGroup, ed.groups.length - 1)]);
|
||
}
|
||
|
||
/** View > Reset Window Layout: the default windows again, and the saved layout forgotten. */
|
||
resetLayout() {
|
||
prefs.set(layoutKey(this.projectKey), null);
|
||
const root = document.documentElement;
|
||
for (const v of ['--left-width', '--bottom-height', '--right-width']) { root.style.removeProperty(v); prefs.set('size' + v, null); }
|
||
this.closeSide('bottom');
|
||
this.closeSide('right');
|
||
this.showTool('project', true);
|
||
this.layoutSaver?.forget();
|
||
this.layoutSaver?.flush();
|
||
notify(t('The window layout was reset.'), 'info');
|
||
}
|
||
|
||
async restoreTabs() {
|
||
const saved = prefs.get('tabs:' + this.projectKey, null);
|
||
if (!saved || !saved.length) {
|
||
// a fresh project: its brief or README, like a welcome page
|
||
const first = ['BRIEF.md', ...(this.project.modules || []).map((m) => (m.dir ? m.dir + '/' : '') + 'BRIEF.md'), 'README.md'].find((p) => this.tree.files.includes(p));
|
||
if (first) this.editors.open(first);
|
||
return;
|
||
}
|
||
for (const [i, g] of saved.entries()) {
|
||
const group = i === 0 ? this.editors.groups[0] : this.editors.addGroup();
|
||
for (const path of g.tabs) if (this.tree.files.includes(path)) await this.editors.open(path, { group });
|
||
if (g.active && this.tree.files.includes(g.active)) await this.editors.open(g.active, { group });
|
||
}
|
||
setInterval(() => this.saveTabs(), 10000);
|
||
}
|
||
}
|
||
|
||
const app = new App();
|
||
// the start guard of index.html: the interface is up (or why not)
|
||
app.start().then(() => window.ideBootDone?.(), (e) => window.ideBootFail?.(e));
|