1388 lines
79 KiB
JavaScript
1388 lines
79 KiB
JavaScript
// The editor area: Monaco, editor groups (split) with tabs, text / image / diff / designer views, saving, and the
|
||
// PHP language features answered by the IDE's PHP side (completion, definition, usages, rename, hover...).
|
||
import { backend } from './backend.js';
|
||
import { registerCallLenses } from './calls.js';
|
||
import { registerMissingPackageFix } from './api-install.js';
|
||
import { registerTwig, availableLanguage } from './twig-lang.js';
|
||
import { registerYaml, YAML_DARK, YAML_LIGHT, completesYaml, isComposeFile, imageAt } from './yaml-lang.js';
|
||
import { registerYamlNavigation } from './yaml-nav.js';
|
||
import { showLocalHistory } from './localhistory.js';
|
||
import { renderMarkdown } from './markdown.js';
|
||
import { aiAvailable } from './res-ai.js';
|
||
import { zoom } from './zoom.js';
|
||
import { HexView, bytesReader } from './hexview.js';
|
||
import { HtmlPreview, dataUrlOf } from './html-preview.js';
|
||
import { twigPreviewText } from './twig-preview.js';
|
||
import { registerCssColors, configureCssProject } from './css-colors.js';
|
||
import { registerPathFeatures, attachJsProject } from './path-features.js';
|
||
import { renderDotenv, isDotenvPath, registerDotenv } from './dotenv.js';
|
||
import { el, clear, icon, colorIcon, basename, dirname, extension, fileIcon, notify, debounce, prefs, menu, kbd, copyText, pasteText, t } from './ui.js';
|
||
|
||
export let monaco = null;
|
||
|
||
export function loadMonaco() {
|
||
return new Promise((resolve, reject) => {
|
||
window.require.config({ paths: { vs: new URL('vendor/monaco/vs', document.baseURI).href } });
|
||
window.require(['vs/editor/editor.main'], () => { monaco = window.monaco; registerYaml(monaco); registerCssColors(monaco); registerDotenv(monaco); registerTwig(monaco).then(() => resolve(monaco), () => resolve(monaco)); }, reject);
|
||
});
|
||
}
|
||
|
||
// project path <-> Monaco URI (library files outside the project: absolute paths under /@lib)
|
||
/** A file of an SSH server opened from the SSH window: ssh://<server id>/<absolute remote path> -> {id, path}, else null. */
|
||
export const remoteOf = (path) => { const m = /^ssh:\/\/([0-9a-f]+)(\/.*)$/.exec(path); return m ? { id: m[1], path: m[2] } : null; };
|
||
export const uriOf = (path) => monaco.Uri.from({ scheme: 'file', path: path.startsWith('/') ? '/@lib' + path : '/' + path });
|
||
export const pathOf = (uri) => (uri.path.startsWith('/@lib/') ? uri.path.slice(5) : uri.path.slice(1));
|
||
|
||
const LANGUAGES = { php: 'php', phtml: 'php', js: 'javascript', mjs: 'javascript', ts: 'typescript', json: 'json', tmj: 'json', tsj: 'json',
|
||
webmanifest: 'json', lock: 'json', html: 'html', htm: 'html', twig: 'twig', css: 'css', scss: 'scss', yaml: 'yaml', yml: 'yaml', neon: 'yaml',
|
||
md: 'markdown', xml: 'xml', svg: 'xml', tmx: 'xml', tsx: 'xml', sh: 'shell', ini: 'ini', env: 'ini', sql: 'sql', py: 'python', rs: 'rust',
|
||
c: 'c', h: 'c', glsl: 'cpp', vert: 'cpp', frag: 'cpp', dockerfile: 'dockerfile', toml: 'ini' };
|
||
|
||
/** a file without a known extension read by its first line: "#!/usr/bin/env php" (bin/console, bin/phpunit...) */
|
||
const SHEBANG = [[/\bphp\b/, 'php'], [/\bpython[0-9.]*\b/, 'python'], [/\b(node|deno|bun)\b/, 'javascript'], [/\b(ba|z|da)?sh\b/, 'shell']];
|
||
const sniffed = new Map();
|
||
|
||
export function languageOf(path, content = null) {
|
||
// the type chosen by hand for this file (the status bar's / the tab bar's quick selector), else its extension's
|
||
const chosen = prefs.get('langOverride', {})[path];
|
||
if (chosen) return monaco ? availableLanguage(monaco, chosen) : chosen;
|
||
const base = basename(path);
|
||
if (base === 'Dockerfile') return 'dockerfile';
|
||
if (base === 'jumphp' || base.endsWith('.sh')) return 'shell';
|
||
if (isDotenvPath(base)) return !monaco || monaco.languages.getLanguages().some((l) => l.id === 'dotenv') ? 'dotenv' : 'ini';
|
||
let id = LANGUAGES[extension(path)] || 'plaintext';
|
||
if (id === 'plaintext' && typeof content === 'string') {
|
||
const first = content.slice(0, 200).split('\n')[0];
|
||
const found = first.startsWith('#!') ? SHEBANG.find(([re]) => re.test(first)) : (/^<\?php\b/.test(content) ? [null, 'php'] : null);
|
||
if (found) sniffed.set(path, found[1]); else sniffed.delete(path);
|
||
}
|
||
if (id === 'plaintext' && sniffed.has(path)) id = sniffed.get(path);
|
||
return monaco ? availableLanguage(monaco, id) : id;
|
||
}
|
||
|
||
function defineThemes() {
|
||
monaco.editor.defineTheme('jumphp-dark', {
|
||
base: 'vs-dark', inherit: true,
|
||
rules: [
|
||
{ token: 'keyword', foreground: 'CF8E6D' }, { token: 'keyword.php', foreground: 'CF8E6D' },
|
||
{ token: 'string', foreground: '6AAB73' }, { token: 'string.php', foreground: '6AAB73' },
|
||
{ token: 'number', foreground: '2AACB8' }, { token: 'comment', foreground: '7A7E85', fontStyle: 'italic' },
|
||
{ token: 'variable', foreground: 'C77DBB' }, { token: 'variable.php', foreground: 'C77DBB' },
|
||
{ token: 'type', foreground: 'BCBEC4' }, { token: 'delimiter', foreground: 'BCBEC4' }, { token: 'identifier', foreground: 'BCBEC4' },
|
||
{ token: 'metatag.php', foreground: 'CF8E6D' }, { token: 'tag', foreground: 'D5B778' }, { token: 'attribute.name', foreground: 'BABABA' },
|
||
{ token: 'attribute.value', foreground: '6AAB73' }, { token: 'key', foreground: 'C77DBB' }, { token: 'string.key.json', foreground: 'C77DBB' },
|
||
...YAML_DARK,
|
||
],
|
||
colors: {
|
||
'editor.background': '#1E1F22', 'editor.foreground': '#BCBEC4', 'editorLineNumber.foreground': '#4B5059',
|
||
'editorLineNumber.activeForeground': '#A1A3AB', 'editor.lineHighlightBackground': '#26282E', 'editor.selectionBackground': '#214283',
|
||
'editorCursor.foreground': '#CED0D6', 'editorIndentGuide.background1': '#2B2D30', 'editorIndentGuide.activeBackground1': '#393B40',
|
||
'editorWhitespace.foreground': '#393B40', 'editorGutter.background': '#1E1F22', 'editorWidget.background': '#2B2D30',
|
||
'editorSuggestWidget.background': '#2B2D30', 'editorSuggestWidget.selectedBackground': '#2E436E', 'editorHoverWidget.background': '#2B2D30',
|
||
'editorBracketMatch.background': '#43454A', 'editorBracketMatch.border': '#00000000', 'minimap.background': '#1E1F22',
|
||
'scrollbarSlider.background': '#4E515766', 'diffEditor.insertedTextBackground': '#3D6B4440', 'diffEditor.removedTextBackground': '#7F3B3B40',
|
||
'diffEditor.insertedLineBackground': '#2A3A2C80', 'diffEditor.removedLineBackground': '#3F2A2A80',
|
||
},
|
||
});
|
||
monaco.editor.defineTheme('jumphp-light', { base: 'vs', inherit: true, rules: YAML_LIGHT, colors: { 'editor.background': '#FFFFFF' } });
|
||
}
|
||
|
||
const KIND = () => ({ method: monaco.languages.CompletionItemKind.Method, function: monaco.languages.CompletionItemKind.Function,
|
||
property: monaco.languages.CompletionItemKind.Field, constant: monaco.languages.CompletionItemKind.Constant,
|
||
enumMember: monaco.languages.CompletionItemKind.EnumMember, class: monaco.languages.CompletionItemKind.Class,
|
||
interface: monaco.languages.CompletionItemKind.Interface, trait: monaco.languages.CompletionItemKind.Module,
|
||
enum: monaco.languages.CompletionItemKind.Enum, variable: monaco.languages.CompletionItemKind.Variable,
|
||
keyword: monaco.languages.CompletionItemKind.Keyword, field: monaco.languages.CompletionItemKind.Field, text: monaco.languages.CompletionItemKind.Text,
|
||
value: monaco.languages.CompletionItemKind.Value, snippet: monaco.languages.CompletionItemKind.Snippet, module: monaco.languages.CompletionItemKind.Module });
|
||
|
||
const SYMBOL = () => ({ class: monaco.languages.SymbolKind.Class, interface: monaco.languages.SymbolKind.Interface,
|
||
trait: monaco.languages.SymbolKind.Module, enum: monaco.languages.SymbolKind.Enum, method: monaco.languages.SymbolKind.Method,
|
||
function: monaco.languages.SymbolKind.Function, property: monaco.languages.SymbolKind.Property, constant: monaco.languages.SymbolKind.Constant,
|
||
enumMember: monaco.languages.SymbolKind.EnumMember });
|
||
|
||
const SOUND = /\.(sfx|music)\.json$/;
|
||
const TILED = /\.(tsj|tmj)$/i;
|
||
|
||
export class Editors {
|
||
constructor(root, app) {
|
||
this.root = root;
|
||
this.app = app;
|
||
this.files = new Map(); // path -> {model, saved (version id), readOnly, kind, data}
|
||
this.groups = [];
|
||
this.focused = null;
|
||
this.recent = prefs.get('recent:' + (app.projectKey || ''), []);
|
||
this.navigation = []; // back / forward positions
|
||
this.navIndex = -1;
|
||
this.autosave = debounce(() => this.saveAll(true), 1500);
|
||
// Ctrl + wheel / Ctrl+= / Ctrl+-: ONE font size for every editor of the centre (like VS Code); Settings > Editor font size is its default
|
||
zoom.define('editor', { kind: 'px', label: 'Editor', def: () => prefs.get('fontSize', 13.5), apply: (v) => { for (const g of this.groups) g.editor.updateOptions({ fontSize: v }); } });
|
||
this.listeners = { active: new Set(), dirty: new Set(), saved: new Set(), cursor: new Set() };
|
||
// a sound effect / tune of the resource editors: its WAV (what the game plays) written next to it at each save
|
||
this.listeners.saved.add((path) => { if (SOUND.test(path)) this.writeSoundWav(path); });
|
||
}
|
||
|
||
async writeSoundWav(path) {
|
||
try {
|
||
const { wavOfFile, wavPathOf, base64 } = await import('./res-sound.js');
|
||
const wav = wavPathOf(path);
|
||
await backend.invoke('file.write', { path: wav, base64: base64(await wavOfFile(path, this.files.get(path)?.model?.getValue() ?? '{}')) });
|
||
this.files.delete(wav);
|
||
this.app.tree?.refresh?.();
|
||
} catch (e) {
|
||
notify(e.message, 'error', { title: 'Cannot write the WAV of ' + basename(path) });
|
||
}
|
||
}
|
||
|
||
on(event, fn) { this.listeners[event].add(fn); return () => this.listeners[event].delete(fn); }
|
||
emit(event, ...args) { for (const fn of this.listeners[event]) fn(...args); }
|
||
|
||
async init() {
|
||
defineThemes();
|
||
monaco.editor.setTheme(document.documentElement.dataset.theme === 'light' ? 'jumphp-light' : 'jumphp-dark');
|
||
this.registerPhp();
|
||
this.registerOpener();
|
||
// paths in files: completion, whole-path links (Ctrl+click), image previews; the project's modules for the JavaScript worker
|
||
registerPathFeatures(monaco, { pathOf, open: (path) => this.open(path) });
|
||
attachJsProject(monaco, this, uriOf);
|
||
// YAML: Ctrl+click, usages, hover, links, rename (yaml-nav.js, JumPHP\Ide\Yaml\YamlNavigation)
|
||
registerYamlNavigation(monaco, this, { backend, uriOf, pathOf });
|
||
this.addGroup();
|
||
this.renderEmpty();
|
||
}
|
||
|
||
// groups ---------------------------------------------------------------------------------------------------
|
||
|
||
addGroup() {
|
||
const group = { tabs: [], active: null, node: el('div.group'), tabsNode: el('div.tabs'), host: el('div.editor-host'), crumbs: el('div.breadcrumbs') };
|
||
group.node.append(group.tabsNode, group.host, group.crumbs);
|
||
group.node.dataset.zoom = 'editor';
|
||
group.node.addEventListener('mousedown', () => this.focus(group), true);
|
||
group.editor = monaco.editor.create(el('div.view'), this.editorOptions());
|
||
group.textView = group.editor.getContainerDomNode();
|
||
group.editor.onDidChangeCursorPosition((e) => { if (this.focused === group) this.emit('cursor', e.position, group); this.updateCrumbs(group); });
|
||
group.editor.onDidFocusEditorText(() => this.focus(group));
|
||
this.addEditorActions(group.editor);
|
||
group.editor.onContextMenu((e) => this.editorMenu(group, e));
|
||
this.groups.push(group);
|
||
this.root.append(group.node);
|
||
this.focus(group);
|
||
this.layout();
|
||
return group;
|
||
}
|
||
|
||
editorOptions() {
|
||
return {
|
||
automaticLayout: true, fontFamily: getComputedStyle(document.documentElement).getPropertyValue('--mono'),
|
||
fontSize: zoom.get('editor'), lineHeight: 1.55, minimap: { enabled: prefs.get('minimap', false) }, scrollBeyondLastLine: false,
|
||
renderLineHighlight: 'all', smoothScrolling: true, cursorBlinking: 'smooth', fontLigatures: true, bracketPairColorization: { enabled: true },
|
||
guides: { bracketPairs: false, indentation: true }, stickyScroll: { enabled: true }, tabSize: 4, insertSpaces: true,
|
||
suggest: { showStatusBar: true, preview: true, localityBonus: true }, inlineSuggest: { enabled: true }, quickSuggestions: { other: true, comments: false, strings: false },
|
||
wordBasedSuggestions: 'currentDocument', parameterHints: { enabled: true }, fixedOverflowWidgets: true, mouseWheelZoom: false,
|
||
definitionLinkOpensInPeek: false, gotoLocation: { multiple: 'peek' }, occurrencesHighlight: 'singleFile', renderWhitespace: 'selection',
|
||
folding: true, showFoldingControls: 'mouseover', 'semanticHighlighting.enabled': false, linkedEditing: true, padding: { top: 6 },
|
||
contextmenu: false, // the IDE's own menu (Play, PhpStorm's entries): editorMenu()
|
||
};
|
||
}
|
||
|
||
focus(group) {
|
||
if (this.focused === group) return;
|
||
this.focused = group;
|
||
for (const g of this.groups) g.node.classList.toggle('focused', g === group);
|
||
this.emit('active', this.activeTab());
|
||
}
|
||
|
||
split() {
|
||
if (this.groups.length >= 2) return this.focus(this.groups.find((g) => g !== this.focused));
|
||
const tab = this.activeTab();
|
||
const group = this.addGroup();
|
||
if (tab) this.open(tab.path, { group });
|
||
}
|
||
|
||
closeGroup(group) {
|
||
if (this.groups.length <= 1) return;
|
||
group.editor.dispose();
|
||
group.diff?.dispose();
|
||
group.node.remove();
|
||
this.groups = this.groups.filter((g) => g !== group);
|
||
this.focus(this.groups[0]);
|
||
this.layout();
|
||
}
|
||
|
||
layout() { for (const g of this.groups) g.editor.layout(); }
|
||
|
||
activeTab(group = this.focused) { return group?.tabs.find((t) => t.id === group.active) || null; }
|
||
activePath() { return this.activeTab()?.path || null; }
|
||
editor(group = this.focused) { return group?.editor; }
|
||
|
||
// opening --------------------------------------------------------------------------------------------------
|
||
|
||
/**
|
||
* Opens a file in the focused group (or reveals it). options: {line, col, endLine, endCol, group, preview, kind,
|
||
* focus (false: the keyboard stays where it is, e.g. in the Claude window while Claude opens files)}
|
||
*/
|
||
async open(path, options = {}) {
|
||
const group = options.group || this.focused;
|
||
this.noFocus = options.focus === false;
|
||
this.pushNavigation();
|
||
let tab = group.tabs.find((t) => t.path === path && (t.kind === (options.kind || t.kind)) && t.kind !== 'diff');
|
||
let file;
|
||
if (!tab) {
|
||
try { file = await this.load(path); } catch (e) { notify(e.message, 'error', { title: 'Cannot open ' + basename(path) }); return null; }
|
||
// opened meanwhile (a click then a double click on the file: two open() waited for the same load)
|
||
tab = group.tabs.find((t) => t.path === path && (t.kind === (options.kind || t.kind)) && t.kind !== 'diff');
|
||
if (tab && !options.preview) tab.preview = false;
|
||
}
|
||
if (!tab) {
|
||
tab = { id: 'tab' + Math.random().toString(36).slice(2), path, kind: file.kind, preview: !!options.preview };
|
||
if (file.kind === 'text' && ['html', 'twig'].includes(languageOf(path))) tab.mode = prefs.get('htmlMode', 'code');
|
||
if (file.kind === 'text' && /\.form\.ya?ml$/.test(path)) tab.mode = prefs.get('formMode', 'design');
|
||
if (file.kind === 'text' && ['css', 'scss'].includes(languageOf(path))) tab.mode = prefs.get('cssMode', 'code');
|
||
const replace = options.preview && group.tabs.find((t) => t.preview && !this.isDirty(t.path));
|
||
if (replace) this.closeTab(group, replace, true);
|
||
group.tabs.push(tab);
|
||
} else if (!options.preview) {
|
||
tab.preview = false;
|
||
}
|
||
this.activate(group, tab);
|
||
if (options.line && tab.kind === 'text') this.reveal(group, options);
|
||
this.noFocus = false;
|
||
this.addRecent(path);
|
||
return tab;
|
||
}
|
||
|
||
/** Loads a file once into a model (or what shows it). */
|
||
load(path) {
|
||
if (this.files.has(path)) return Promise.resolve(this.files.get(path));
|
||
// one read for calls made while it is under way (two open() of the same file must not make two tabs, two models)
|
||
this.loading ||= new Map();
|
||
if (!this.loading.has(path)) this.loading.set(path, this.loadNow(path).finally(() => this.loading.delete(path)));
|
||
return this.loading.get(path);
|
||
}
|
||
|
||
async loadNow(path) {
|
||
if (this.files.has(path)) return this.files.get(path);
|
||
// a file of an SSH server (the SSH window: ssh://<server>/<path>): read with ssh, saved back with it
|
||
const remote = remoteOf(path);
|
||
// an image of the web (Ctrl+click on its address): fetched by the backend (public addresses only), shown read only
|
||
const data = remote ? await backend.invoke('ssh.file.read', remote)
|
||
: /^https?:\/\//i.test(path) ? await backend.invoke('image.fetch', { url: path }) : await backend.invoke('file.read', { path });
|
||
let file;
|
||
if (data.text) {
|
||
const model = monaco.editor.getModel(uriOf(path)) || monaco.editor.createModel(data.content, languageOf(path, data.content), uriOf(path));
|
||
if (model.getValue() !== data.content) model.setValue(data.content);
|
||
model.updateOptions({ tabSize: ['yaml', 'json', 'javascript', 'html', 'css'].includes(languageOf(path)) && !/^\t/m.test(data.content) ? detectIndent(data.content) : 4 });
|
||
// its encoding and line endings as read (UTF-8 BOM, UTF-16, Windows-1252...; LF, CRLF, CR): written back the same, or as chosen
|
||
file = { kind: 'text', model, saved: model.getAlternativeVersionId(), readOnly: !!data.readOnly, mtime: data.mtime,
|
||
encoding: data.encoding || 'UTF-8', eol: data.eol || 'LF', formatChanged: false };
|
||
model.onDidChangeContent(() => this.changed(path));
|
||
if (languageOf(path) === 'php' && !remote) this.app.diagnose?.(path);
|
||
// Bootstrap (bootstrap-support.js): the checks as markers in .html / .twig files of a project that uses it
|
||
if (['html', 'twig'].includes(languageOf(path)) && !remote) file.bootstrapReady = this.bootstrapSupport().then((s) => s.attach(path, model)).then((info) => { file.bootstrap = info; return info; }, () => null);
|
||
} else {
|
||
file = { kind: data.image ? 'image' : data.audio ? 'audio' : 'binary', data };
|
||
}
|
||
this.files.set(path, file);
|
||
return file;
|
||
}
|
||
|
||
activate(group, tab) {
|
||
group.active = tab.id;
|
||
this.focus(group);
|
||
this.renderTabs(group);
|
||
this.renderView(group, tab);
|
||
this.emit('active', tab);
|
||
}
|
||
|
||
renderView(group, tab) {
|
||
const host = group.host;
|
||
for (const child of [...host.children]) if (child !== group.textView) child.remove();
|
||
group.textView.style.display = 'none';
|
||
group.designer?.destroy?.();
|
||
group.designer = null;
|
||
group.controllers?.destroy();
|
||
group.controllers = null;
|
||
if (!tab) return this.renderEmpty(group);
|
||
this.updateCrumbs(group);
|
||
const file = this.files.get(tab.path);
|
||
if (tab.kind === 'diff') return this.renderDiff(group, tab);
|
||
if (tab.hex) return this.renderHex(group, tab, file);
|
||
if (tab.kind === 'text') {
|
||
if (!group.textView.parentNode) host.append(group.textView);
|
||
if (/\.(md|markdown)$/i.test(tab.path) && file) return this.renderMarkdownFile(group, tab, file);
|
||
if (['html', 'twig'].includes(languageOf(tab.path)) && file) return this.renderHtml(group, tab, file);
|
||
if (/\.form\.ya?ml$/.test(tab.path) && file) return this.renderHtml(group, tab, file, 'form');
|
||
if ((SOUND.test(tab.path) || TILED.test(tab.path)) && file) return this.renderSound(group, tab, file);
|
||
if (['css', 'scss'].includes(languageOf(tab.path)) && file) return this.renderCss(group, tab, file);
|
||
if (isDotenvPath(tab.path) && file?.model) return renderDotenv(this, group, tab, file);
|
||
group.textView.style.display = '';
|
||
this.showModel(group, tab, file);
|
||
if (file?.model && this.app.project?.capabilities?.controllers && /\.php$/i.test(tab.path) && !file.readOnly) this.mountControllers(group, tab, file);
|
||
return;
|
||
}
|
||
if (tab.kind === 'image') {
|
||
if (/\.png$/i.test(tab.path) && !file.data.remote && !this.app.project?.capabilities?.readOnly) return this.renderImage(group, tab, file);
|
||
host.append(el('div.view.image-view', {}, el('img', { src: file.data.image, alt: tab.path }),
|
||
el('div', {}, `${basename(tab.path)} · ${(file.data.size / 1024).toFixed(1)} KB`)));
|
||
return;
|
||
}
|
||
if (tab.kind === 'audio') {
|
||
host.append(el('div.view.binary-view', {}, icon('play'), el('audio', { src: file.data.audio, controls: true }), basename(tab.path)));
|
||
return;
|
||
}
|
||
if (/\.(cryo|cryf|cryom)$/i.test(tab.path) && this.app.cryo) {
|
||
host.append(el('div.view.binary-view', {}, icon('snowflake'), `${basename(tab.path)} (${file.data.size} bytes)`,
|
||
el('button.btn.primary', { onclick: () => this.app.cryo.openFile(tab.path) }, 'Open in Cryo')));
|
||
return;
|
||
}
|
||
host.append(el('div.view.binary-view', {}, icon('file'), `${basename(tab.path)} is a binary file (${file.data.size} bytes)`,
|
||
el('button.btn.primary', { onclick: () => this.toggleHex(tab, true) }, 'Show in Hexadecimal')));
|
||
}
|
||
|
||
/** The panel of a Symfony controller under its code (controller-panel.js): it shows itself only when the file is one. */
|
||
mountControllers(group, tab, file) {
|
||
import('./controller-panel.js').then(({ ControllerPanel }) => {
|
||
if (group.active !== tab.id || group.controllers) return;
|
||
group.controllers = new ControllerPanel({ app: this.app, editors: this, group, tab, file });
|
||
});
|
||
}
|
||
|
||
/** View as Hexadecimal: any tab (text, picture, sound, binary) <-> its bytes; the file as saved on the disk. */
|
||
toggleHex(tab = this.activeTab(), on = !tab?.hex) {
|
||
if (!tab || tab.kind === 'diff') return;
|
||
const group = this.groups.find((g) => g.tabs.includes(tab)) || this.focused;
|
||
tab.hex = on;
|
||
this.activate(group, tab);
|
||
}
|
||
|
||
renderHex(group, tab) {
|
||
const view = el('div.view');
|
||
group.host.append(view, el('div.mode-switch', {}, el('button', { onclick: () => this.toggleHex(tab, false) }, 'Normal View'), el('button.on', {}, 'Hexadecimal')));
|
||
const note = tab.kind === 'text' && this.isDirty(tab.path) ? 'Unsaved changes are not shown: this is the file on the disk' : '';
|
||
group.designer = new HexView(view, { read: bytesReader(backend, 'file.bytes', tab.path), note });
|
||
this.updateCrumbs(group);
|
||
}
|
||
|
||
/** The Bootstrap helpers of the code editor (checks, completion, hover, quick fixes), made once, when the first page is opened. */
|
||
bootstrapSupport() {
|
||
this.bootstrapPromise ??= import('./bootstrap-support.js').then(({ BootstrapSupport }) => new BootstrapSupport({
|
||
monaco, readText: (p) => this.readProjectText(p), files: () => this.app.tree?.files || [],
|
||
onProblems: (path, list) => this.app.problems?.set(path, list, 'bootstrap'),
|
||
}));
|
||
return this.bootstrapPromise;
|
||
}
|
||
|
||
/** The Bootstrap mode: the code, the page it draws, the components, the utilities of the selected element, the problems, the AI. */
|
||
renderBootstrap(group, tab, file, info) {
|
||
group.textView.style.display = '';
|
||
group.textView.style.right = '58%';
|
||
group.textView.style.width = '42%';
|
||
const view = el('div.view', { style: { left: '42%', borderLeft: '1px solid var(--border-2)' } });
|
||
group.host.append(view);
|
||
this.showModel(group, tab, file);
|
||
const holder = { destroy: () => { holder.editor?.destroy(); group.textView.style.right = ''; group.textView.style.width = ''; } };
|
||
group.designer = holder;
|
||
Promise.all([import('./bootstrap-editor.js'), this.bootstrapSupport()]).then(async ([{ BootstrapEditor }, support]) => {
|
||
if (group.designer !== holder) return;
|
||
holder.editor = new BootstrapEditor(view, {
|
||
model: file.model, monaco, editor: group.editor, path: tab.path, twig: /\.twig$/i.test(tab.path), info, support,
|
||
classes: await support.classes(),
|
||
readText: (p) => this.readProjectText(p), readDataUrl: (p) => this.readDataUrl(p), htmlFiles: () => this.app.tree?.files || [],
|
||
});
|
||
}, (e) => notify(e.message, 'error'));
|
||
}
|
||
|
||
/** The live preview can show this tab: an HTML page or a stylesheet. */
|
||
canPreview(tab = this.activeTab()) {
|
||
return !!tab && tab.kind === 'text' && /\.(html?|css|scss)$/i.test(tab.path);
|
||
}
|
||
|
||
/** Preview HTML: the tab's code beside its live preview, or its code alone again. */
|
||
togglePreview(tab = this.activeTab()) {
|
||
if (!this.canPreview(tab)) return;
|
||
const group = this.groups.find((g) => g.tabs.includes(tab)) || this.focused;
|
||
tab.hex = false;
|
||
tab.mode = tab.mode === 'preview' ? 'code' : 'preview';
|
||
prefs.set(['css', 'scss'].includes(languageOf(tab.path)) ? 'cssMode' : 'htmlMode', tab.mode);
|
||
this.activate(group, tab);
|
||
}
|
||
|
||
/**
|
||
* .css / .scss files: Code, Split (the code beside the visual editor), Design (the visual editor: rules, inspector,
|
||
* preview; css-designer.js) or Preview (the code beside the page it styles).
|
||
*/
|
||
renderCss(group, tab, file) {
|
||
const modes = ['code', 'split', 'design', 'preview'];
|
||
const mode = modes.includes(tab.mode) ? tab.mode : 'code';
|
||
group.host.append(el('div.mode-switch', {}, modes.map((m) => el(`button${m === mode ? '.on' : ''}`, {
|
||
onclick: () => { tab.mode = m; prefs.set('cssMode', m); this.renderView(group, tab); this.renderTabs(group); },
|
||
}, { code: 'Code', split: 'Split', design: 'Design', preview: 'Preview' }[m]))));
|
||
configureCssProject({ files: () => this.app.tree?.files || [], readText: (p) => this.readProjectText(p) });
|
||
group.textView.style.display = '';
|
||
group.textView.style.right = '';
|
||
group.textView.style.width = '';
|
||
if (mode === 'code') return this.showModel(group, tab, file);
|
||
const scss = languageOf(tab.path) === 'scss';
|
||
if (mode === 'preview' && !scss) return this.renderLivePreview(group, tab, file, 'css');
|
||
const view = el('div.view');
|
||
if (mode === 'design') group.textView.style.display = 'none';
|
||
else {
|
||
group.textView.style.right = mode === 'preview' ? '50%' : '58%';
|
||
group.textView.style.width = mode === 'preview' ? '50%' : '42%';
|
||
Object.assign(view.style, { left: mode === 'preview' ? '50%' : '42%', borderLeft: '1px solid var(--border-2)' });
|
||
this.showModel(group, tab, file);
|
||
}
|
||
group.host.append(view);
|
||
const holder = { destroy: () => { holder.designer?.destroy(); group.textView.style.right = ''; group.textView.style.width = ''; } };
|
||
group.designer = holder;
|
||
import('./css-designer.js').then(({ CssDesigner }) => {
|
||
if (group.designer !== holder) return;
|
||
holder.designer = new CssDesigner(view, {
|
||
model: file.model, monaco, path: tab.path, scss, readOnly: file.readOnly,
|
||
layout: mode === 'design' ? 'full' : mode === 'preview' ? 'preview' : 'side',
|
||
editor: mode === 'design' ? null : group.editor,
|
||
readText: (p) => this.readProjectText(p),
|
||
readDataUrl: (p) => this.readDataUrl(p),
|
||
htmlFiles: () => this.app.tree?.files || [],
|
||
compile: scss && !remoteOf(tab.path) ? (text) => backend.invoke('css.sass.compile', { path: tab.path, text }) : null,
|
||
// a problem clicked: the code shows it (Design goes to Split)
|
||
reveal: (offset) => {
|
||
if (tab.mode === 'design') { tab.mode = 'split'; this.renderView(group, tab); }
|
||
const pos = file.model.getPositionAt(offset);
|
||
group.editor.revealPositionInCenter(pos);
|
||
group.editor.setPosition(pos);
|
||
group.editor.focus();
|
||
},
|
||
});
|
||
}, (e) => notify(e.message, 'error'));
|
||
}
|
||
|
||
/** a project file's text: the open model's (unsaved changes included), else the disk's */
|
||
async readProjectText(p) {
|
||
const open = this.files.get(p);
|
||
if (open?.model) return open.model.getValue();
|
||
const f = await backend.invoke('file.read', { path: p }).catch(() => null);
|
||
return f?.text ? f.content : null;
|
||
}
|
||
|
||
/** a project file as a data: URL (pictures, fonts of a preview), null when too big */
|
||
async readDataUrl(p) {
|
||
const f = await backend.invoke('file.read', { path: p });
|
||
if (f.image || f.audio) return f.image || f.audio;
|
||
if (f.text) return 'data:' + (/\.svg$/i.test(p) ? 'image/svg+xml' : 'text/plain') + ';charset=utf-8,' + encodeURIComponent(f.content);
|
||
const r = await backend.invoke('file.bytes', { path: p, offset: 0, length: 1024 * 1024 });
|
||
return r.length < r.size ? null : dataUrlOf(p, r.base64);
|
||
}
|
||
|
||
/** The code on the left, the page on the right, drawn again a moment after each change. */
|
||
renderLivePreview(group, tab, file, kind) {
|
||
group.textView.style.display = '';
|
||
group.textView.style.right = '50%';
|
||
group.textView.style.width = '50%';
|
||
const view = el('div.view', { style: { left: '50%', borderLeft: '1px solid var(--border-2)' } });
|
||
group.host.append(view);
|
||
this.showModel(group, tab, file);
|
||
const readFile = (p) => backend.invoke('file.read', { path: p });
|
||
const readText = async (p) => {
|
||
const open = this.files.get(p);
|
||
if (open?.model) return open.model.getValue();
|
||
const f = await readFile(p).catch(() => null);
|
||
return f?.text ? f.content : null;
|
||
};
|
||
const twig = /\.twig$/i.test(tab.path);
|
||
const preview = new HtmlPreview(view, {
|
||
path: tab.path,
|
||
kind,
|
||
twig,
|
||
// Twig: laid out as Symfony would (extends, includes, the project's CSS: "Layout + CSS"), then its tags taken out
|
||
text: (p) => (twig ? twigPreviewText(tab.path, file.model.getValue(), readText, p?.layout !== false) : file.model.getValue()),
|
||
readText,
|
||
readDataUrl: async (p) => {
|
||
const f = await readFile(p);
|
||
if (f.image || f.audio) return f.image || f.audio;
|
||
if (f.text) return 'data:' + (/\.svg$/i.test(p) ? 'image/svg+xml' : 'text/plain') + ';charset=utf-8,' + encodeURIComponent(f.content);
|
||
const r = await backend.invoke('file.bytes', { path: p, offset: 0, length: 1024 * 1024 });
|
||
return r.length < r.size ? null : dataUrlOf(p, r.base64);
|
||
},
|
||
htmlFiles: () => this.app.tree?.files || [],
|
||
// Twig: the REAL page of a route of the running site (route selector, parameters, session), refreshed when a file is saved
|
||
live: twig && this.app.project?.capabilities?.pagePreview ? {
|
||
routes: () => backend.invoke('preview.routes', { template: tab.path }),
|
||
site: () => backend.invoke('preview.site'),
|
||
fetch: (p) => backend.invoke('preview.fetch', p),
|
||
// the first ids of an entity's table: the Database window's open connection, when there is one
|
||
suggest: async (sql) => {
|
||
const { connections } = await backend.invoke('db.list');
|
||
const c = (connections || []).find((x) => x.open);
|
||
return c ? backend.invoke('db.run', { id: c.id, script: sql, confirmed: false }) : null;
|
||
},
|
||
startSite: () => {
|
||
const config = this.app.runner?.configs.find((c) => c.id === 'web:serve');
|
||
if (config) { this.app.runner.start(config); this.app.showTool?.('run'); } else notify(t('This project has no "Serve the site" run configuration: start its containers yourself.'), 'info');
|
||
},
|
||
} : null,
|
||
});
|
||
const refresh = debounce(() => { if (group.designer === holder) preview.update('saved'); }, 300);
|
||
const holder = { destroy: () => { sub.dispose(); off(); preview.destroy(); group.textView.style.right = ''; group.textView.style.width = ''; } };
|
||
const sub = file.model.onDidChangeContent(debounce(() => { if (group.designer === holder) preview.update('typing'); }, 400));
|
||
const off = this.on('saved', refresh);
|
||
group.designer = holder;
|
||
}
|
||
|
||
showModel(group, tab, file) {
|
||
const editor = group.editor;
|
||
if (editor.getModel() !== file.model) {
|
||
const previous = this.activeTabModelState(group);
|
||
if (previous) previous.tab.viewState = previous.state;
|
||
editor.setModel(file.model);
|
||
if (tab.viewState) editor.restoreViewState(tab.viewState);
|
||
}
|
||
editor.updateOptions({ readOnly: file.readOnly });
|
||
group.modelTab = tab;
|
||
const focus = !this.noFocus;
|
||
requestAnimationFrame(() => { editor.layout(); if (focus) editor.focus(); });
|
||
this.updateCrumbs(group);
|
||
}
|
||
|
||
activeTabModelState(group) {
|
||
return group.modelTab ? { tab: group.modelTab, state: group.editor.saveViewState() } : null;
|
||
}
|
||
|
||
/** A PNG: the picture, or its pixels in the sprite editor (Edit). */
|
||
async renderImage(group, tab, file) {
|
||
const host = group.host;
|
||
const mode = tab.mode || 'view';
|
||
host.append(el('div.mode-switch', {}, ['view', 'edit'].map((m) => el(`button${m === mode ? '.on' : ''}`, {
|
||
onclick: () => { tab.mode = m; this.renderView(group, tab); },
|
||
}, { view: 'View', edit: 'Edit pixels' }[m]))));
|
||
if (mode === 'view') {
|
||
host.append(el('div.view.image-view', {}, el('img', { src: file.data.image, alt: tab.path }),
|
||
el('div', {}, `${basename(tab.path)} · ${(file.data.size / 1024).toFixed(1)} KB`)));
|
||
return;
|
||
}
|
||
const view = el('div.view');
|
||
host.append(view);
|
||
try {
|
||
const { SpriteEditor } = await import('./res-sprite.js');
|
||
group.designer = new SpriteEditor(view, {
|
||
path: tab.path,
|
||
ai: aiAvailable(this.app.project?.capabilities),
|
||
src: file.data.image,
|
||
save: async (png) => {
|
||
await backend.invoke('file.write', { path: tab.path, base64: png });
|
||
file.data = { ...file.data, image: 'data:image/png;base64,' + png, size: Math.floor(png.length * 3 / 4) };
|
||
this.emit('saved', tab.path);
|
||
},
|
||
});
|
||
} catch (e) {
|
||
view.append(el('div.placeholder', {}, 'The sprite editor could not start: ' + e.message));
|
||
}
|
||
}
|
||
|
||
/** *.sfx.json / *.music.json / *.tsj / *.tmj: the resource editors over the JSON (Editor), or the JSON itself (Code). */
|
||
async renderSound(group, tab, file) {
|
||
const host = group.host;
|
||
const mode = tab.mode || 'design';
|
||
host.append(el('div.mode-switch', {}, ['code', 'design'].map((m) => el(`button${m === mode ? '.on' : ''}`, {
|
||
onclick: () => { tab.mode = m; this.renderView(group, tab); },
|
||
}, { code: 'Code', design: 'Editor' }[m]))));
|
||
if (mode === 'code') {
|
||
group.textView.style.display = '';
|
||
this.showModel(group, tab, file);
|
||
return;
|
||
}
|
||
const view = el('div.view');
|
||
host.append(view);
|
||
try {
|
||
const music = /\.music\.json$/.test(tab.path);
|
||
const tiled = TILED.test(tab.path);
|
||
const { SfxEditor } = music || tiled ? {} : await import('./res-sfx.js');
|
||
const { MusicEditor } = music ? await import('./res-music.js') : {};
|
||
const { TilesetEditor, LevelEditor } = tiled ? await import('./res-tiles.js') : {};
|
||
const Editor = tiled ? (/\.tsj$/i.test(tab.path) ? TilesetEditor : LevelEditor) : music ? MusicEditor : SfxEditor;
|
||
let syncing = false;
|
||
const editor = new Editor(view, {
|
||
path: tab.path,
|
||
ai: aiAvailable(this.app.project?.capabilities),
|
||
text: file.model.getValue(),
|
||
files: this.app.tree?.files || [],
|
||
readText: async (p) => this.files.get(p)?.model?.getValue() ?? (await backend.invoke('file.read', { path: p })).content ?? '',
|
||
readImage: async (p) => (await backend.invoke('file.read', { path: p })).image,
|
||
onChange: (text) => {
|
||
if (file.readOnly) return;
|
||
syncing = true;
|
||
file.model.pushEditOperations([], [{ range: file.model.getFullModelRange(), text }], () => null);
|
||
syncing = false;
|
||
},
|
||
});
|
||
group.designer = editor;
|
||
const sub = file.model.onDidChangeContent(debounce(() => { if (!syncing && group.designer === editor) editor.setText(file.model.getValue()); }, 600));
|
||
const destroy = editor.destroy.bind(editor);
|
||
editor.destroy = () => { sub.dispose(); destroy(); };
|
||
requestAnimationFrame(() => editor.node.focus());
|
||
} catch (e) {
|
||
view.append(el('div.placeholder', {}, 'The editor could not start: ' + e.message));
|
||
}
|
||
}
|
||
|
||
/** .md files: read rendered by default (View), the source (Edit), or both side by side (Edit + View). */
|
||
renderMarkdownFile(group, tab, file) {
|
||
const mode = tab.mode || prefs.get('mdMode', 'view');
|
||
const host = group.host;
|
||
host.append(el('div.mode-switch', {}, ['view', 'code', 'split'].map((m) => el(`button${m === mode ? '.on' : ''}`, {
|
||
onclick: () => { tab.mode = m; prefs.set('mdMode', m); this.renderView(group, tab); },
|
||
}, { view: 'View', code: 'Edit', split: 'Edit + View' }[m]))));
|
||
group.textView.style.right = '';
|
||
group.textView.style.width = '';
|
||
if (mode === 'code') {
|
||
group.textView.style.display = '';
|
||
this.showModel(group, tab, file);
|
||
return;
|
||
}
|
||
const view = el('div.view.md-view');
|
||
// pictures of the project only (relative to the .md file): nothing is fetched from the internet by reading a README
|
||
const folder = dirname(tab.path);
|
||
const image = (src, alt) => {
|
||
if (/^[a-z][a-z0-9+.-]*:|^\/\//i.test(src)) return el('span.pub-faint', {}, `[${alt || 'image'}: external pictures are not loaded]`);
|
||
const parts = (src.startsWith('/') ? src.slice(1) : (folder ? folder + '/' : '') + src).split('?')[0].split('/');
|
||
const path = parts.reduce((acc, p) => { if (p === '..') acc.pop(); else if (p !== '.' && p !== '') acc.push(p); return acc; }, []).join('/');
|
||
const img = el('img', { alt: alt || '', style: { maxWidth: '100%' } });
|
||
backend.invoke('file.read', { path }).then((f) => { if (f.image) img.src = f.image; else img.replaceWith(`[${alt || path}]`); }).catch(() => img.replaceWith(`[${alt || path}: not found]`));
|
||
return img;
|
||
};
|
||
const draw = () => {
|
||
const top = view.scrollTop;
|
||
clear(view).append(el('div.md-body', {}, ...renderMarkdown(file.model.getValue(), (url) => this.app.openUrl(url), image)));
|
||
view.scrollTop = top;
|
||
};
|
||
if (mode === 'split') {
|
||
group.textView.style.display = '';
|
||
group.textView.style.right = '50%';
|
||
group.textView.style.width = '50%';
|
||
view.style.left = '50%';
|
||
view.style.borderLeft = '1px solid var(--border-2)';
|
||
this.showModel(group, tab, file);
|
||
}
|
||
host.append(view);
|
||
draw();
|
||
const sub = file.model.onDidChangeContent(debounce(draw, 250));
|
||
group.designer = { destroy: () => { sub.dispose(); group.textView.style.right = ''; group.textView.style.width = ''; } };
|
||
}
|
||
|
||
/** .html files (and forms of graphic apps, *.form.yaml): Code, Design (visual editor) or both side by side. */
|
||
async renderHtml(group, tab, file, kind = 'html') {
|
||
const mode = tab.mode || (kind === 'form' ? 'design' : 'code');
|
||
const host = group.host;
|
||
// a Twig template: its code or its look (the visual designer would rewrite its tags)
|
||
const token = (group.htmlToken = (group.htmlToken || 0) + 1);
|
||
const bootstrap = kind === 'html' ? await file.bootstrapReady?.catch(() => null) : null; // the page / project uses Bootstrap: a mode for it
|
||
if (group.htmlToken !== token) return; // another render started while Bootstrap was being detected
|
||
const modes = kind === 'form' ? ['code', 'split', 'design'] : [...(/\.twig$/i.test(tab.path) ? ['code', 'preview'] : ['code', 'split', 'design', 'preview']), ...(bootstrap?.used ? ['bootstrap'] : [])];
|
||
if (!modes.includes(mode)) { tab.mode = 'code'; return this.renderHtml(group, tab, file, kind); }
|
||
const switcher = el('div.mode-switch', {}, modes.map((m) => el(`button${m === mode ? '.on' : ''}`, {
|
||
...(m === 'preview' ? { 'data-tour': 'editor-preview' } : {}),
|
||
onclick: () => { tab.mode = m; prefs.set(kind === 'form' ? 'formMode' : 'htmlMode', m); this.renderView(group, tab); this.renderTabs(group); },
|
||
}, { code: 'Code', split: 'Split', design: 'Design', preview: 'Preview', bootstrap: 'Bootstrap' }[m])));
|
||
host.append(switcher);
|
||
if (mode === 'bootstrap') return this.renderBootstrap(group, tab, file, bootstrap);
|
||
if (mode === 'preview' && kind === 'html') return this.renderLivePreview(group, tab, file, 'html');
|
||
if (mode === 'code') {
|
||
group.textView.style.display = '';
|
||
group.textView.style.width = '';
|
||
this.showModel(group, tab, file);
|
||
return;
|
||
}
|
||
const designHost = el('div.view');
|
||
if (mode === 'split') {
|
||
group.textView.style.display = '';
|
||
group.textView.style.right = '50%';
|
||
group.textView.style.width = '50%';
|
||
designHost.style.left = '50%';
|
||
designHost.style.borderLeft = '1px solid var(--border-2)';
|
||
this.showModel(group, tab, file);
|
||
}
|
||
host.append(designHost);
|
||
if (kind === 'form') return this.renderFormDesigner(group, tab, file, designHost);
|
||
try {
|
||
const { Designer } = await import('./designer.js');
|
||
let syncing = false;
|
||
const designer = new Designer(designHost, {
|
||
path: tab.path,
|
||
html: file.model.getValue(),
|
||
readFile: (p) => backend.invoke('file.read', { path: p }),
|
||
writeFile: async (p, content) => {
|
||
const open = this.files.get(p);
|
||
if (open?.model) open.model.setValue(content);
|
||
else await backend.invoke('file.write', { path: p, content });
|
||
},
|
||
onChange: (html) => {
|
||
syncing = true;
|
||
file.model.pushEditOperations([], [{ range: file.model.getFullModelRange(), text: html }], () => null);
|
||
syncing = false;
|
||
},
|
||
});
|
||
group.designer = designer;
|
||
const sub = file.model.onDidChangeContent(debounce(() => { if (!syncing && group.designer === designer) designer.setHtml(file.model.getValue()); }, 600));
|
||
const destroy = designer.destroy?.bind(designer);
|
||
designer.destroy = () => { sub.dispose(); destroy && destroy(); group.textView.style.right = ''; group.textView.style.width = ''; };
|
||
} catch (e) {
|
||
designHost.append(el('div.placeholder', {}, 'The visual editor could not start: ' + e.message));
|
||
}
|
||
}
|
||
|
||
/** The visual editor of a form (graphic PHP apps, JumPHP\Gui): the YAML in the model, the code behind in the form's class. */
|
||
async renderFormDesigner(group, tab, file, designHost) {
|
||
try {
|
||
const { FormDesigner } = await import('./form-designer.js');
|
||
let syncing = false;
|
||
const app = tab.path.includes('/forms/') ? tab.path.slice(0, tab.path.indexOf('/forms/')) : '';
|
||
const config = this.app.runner?.config('run:' + app.split('/').pop());
|
||
const run = config ? () => { this.app.runner.start(config); this.app.showTool?.('run'); } : null;
|
||
const designer = new FormDesigner(designHost, {
|
||
path: tab.path,
|
||
text: file.model.getValue(),
|
||
backend,
|
||
run,
|
||
writeFile: async (p, content) => {
|
||
const open = this.files.get(p);
|
||
if (open?.model) { if (open.model.getValue() !== content) open.model.pushEditOperations([], [{ range: open.model.getFullModelRange(), text: content }], () => null); }
|
||
else await backend.invoke('file.write', { path: p, content });
|
||
this.app.tree?.refresh?.();
|
||
},
|
||
openFile: (p, line) => this.open(p, line ? { line, col: 9 } : {}),
|
||
onChange: (text) => {
|
||
syncing = true;
|
||
file.model.pushEditOperations([], [{ range: file.model.getFullModelRange(), text }], () => null);
|
||
syncing = false;
|
||
},
|
||
});
|
||
group.designer = designer;
|
||
const sub = file.model.onDidChangeContent(debounce(() => { if (!syncing && group.designer === designer) designer.setText(file.model.getValue()); }, 600));
|
||
const destroy = designer.destroy.bind(designer);
|
||
designer.destroy = () => { sub.dispose(); destroy(); group.textView.style.right = ''; group.textView.style.width = ''; };
|
||
} catch (e) {
|
||
designHost.append(el('div.placeholder', {}, 'The visual editor could not start: ' + e.message));
|
||
}
|
||
}
|
||
|
||
/** A diff tab: {path, original (text), title, modified?: text (read only, e.g. a past commit)} */
|
||
async openDiff(path, { original, modified = null, title, readOnly = false, left = 'HEAD' } = {}) {
|
||
const group = this.focused;
|
||
const tab = { id: 'diff' + Math.random().toString(36).slice(2), path, kind: 'diff', original, modified, title: title || basename(path) + ' (diff)', readOnly, left };
|
||
if (modified === null) await this.load(path).catch(() => null);
|
||
group.tabs.push(tab);
|
||
this.activate(group, tab);
|
||
}
|
||
|
||
renderDiff(group, tab) {
|
||
const view = el('div.view.with-header');
|
||
const body = el('div.diff-body');
|
||
view.append(el('div.diff-header', {}, icon('diff'), tab.title, el('span', { style: { flex: 1 } }),
|
||
el('span', {}, tab.modified === null ? `${tab.left || 'HEAD'} ↔ your version (editable)` : 'before ↔ after')), body);
|
||
group.host.append(view);
|
||
group.diff?.dispose();
|
||
group.diff = monaco.editor.createDiffEditor(body, { ...this.editorOptions(), renderSideBySide: prefs.get('diffSideBySide', true), originalEditable: false, readOnly: tab.modified !== null, ignoreTrimWhitespace: false });
|
||
const lang = languageOf(tab.path);
|
||
const original = monaco.editor.createModel(tab.original ?? '', lang);
|
||
const modified = tab.modified !== null ? monaco.editor.createModel(tab.modified, lang) : this.files.get(tab.path)?.model || monaco.editor.createModel('', lang);
|
||
group.diff.setModel({ original, modified });
|
||
const dispose = group.diff.dispose.bind(group.diff);
|
||
group.diff.dispose = () => { dispose(); original.dispose(); if (tab.modified !== null) modified.dispose(); };
|
||
}
|
||
|
||
reveal(group, { line, col = 1, endLine, endCol, select = true, focus = !this.noFocus }) {
|
||
const editor = group.editor;
|
||
const range = new monaco.Range(line, col, endLine || line, endCol || col);
|
||
setTimeout(() => {
|
||
if (select) editor.setSelection(range);
|
||
editor.revealRangeInCenterIfOutsideViewport(range, 0);
|
||
if (focus) editor.focus();
|
||
}, 0);
|
||
}
|
||
|
||
renderTabs(group) {
|
||
clear(group.tabsNode);
|
||
for (const tab of group.tabs) {
|
||
const status = this.app.git?.statusOf(tab.path);
|
||
const node = el(`div.tab${tab.id === group.active ? '.on' : ''}${this.isDirty(tab.path) && tab.kind !== 'diff' ? '.dirty' : ''}${tab.preview ? '.preview' : ''}${status ? '.st-' + status : ''}`, {
|
||
title: tab.path,
|
||
onmousedown: (e) => { if (e.button === 1) { e.preventDefault(); this.closeTab(group, tab); } },
|
||
onclick: () => this.activate(group, tab),
|
||
ondblclick: () => { tab.preview = false; this.renderTabs(group); },
|
||
oncontextmenu: (e) => { e.preventDefault(); this.tabMenu(group, tab, e); },
|
||
}, tab.kind === 'diff' ? icon('diff') : fileIcon(tab.path), el('span.name', {}, tab.kind === 'diff' ? tab.title : basename(tab.path)),
|
||
el('button.close', { title: 'Close (Ctrl+F4)', onclick: (e) => { e.stopPropagation(); this.closeTab(group, tab); } }, icon('close')));
|
||
group.tabsNode.append(node);
|
||
if (tab.id === group.active) setTimeout(() => node.scrollIntoView({ block: 'nearest', inline: 'nearest' }), 0);
|
||
}
|
||
const active = this.activeTab(group);
|
||
group.tabsNode.append(el('div.tabs-actions', {},
|
||
this.canPreview(active) ? el(`button.icon-btn${active.mode === 'preview' && !active.hex ? '.on' : ''}`, { 'data-tour': 'editor-preview', title: 'Preview HTML', onclick: () => this.togglePreview(active) }, icon('eye')) : null,
|
||
active?.path && active.kind !== 'diff' ? el('button.icon-btn', { title: t('Read this file as another type (language, hexadecimal, picture, PDF…)'),
|
||
onclick: (e) => { const r = e.currentTarget.getBoundingClientRect(); this.app.chooseFileType({ x: Math.max(8, r.right - 320), y: r.bottom + 4 }); } }, icon('code')) : null,
|
||
el('button.icon-btn', { title: 'Split right', onclick: () => this.split() }, icon('split')),
|
||
this.groups.length > 1 ? el('button.icon-btn', { title: 'Close this group', onclick: () => this.closeGroup(group) }, icon('close')) : null));
|
||
}
|
||
|
||
tabMenu(group, tab, e) {
|
||
menu([
|
||
{ label: 'Close', kbd: kbd('Ctrl+F4'), action: () => this.closeTab(group, tab) },
|
||
{ label: 'Close Other Tabs', action: () => group.tabs.filter((t) => t !== tab).forEach((t) => this.closeTab(group, t)) },
|
||
{ label: 'Close All Tabs', action: () => [...group.tabs].forEach((t) => this.closeTab(group, t)) },
|
||
{ label: 'Close Tabs to the Right', action: () => group.tabs.slice(group.tabs.indexOf(tab) + 1).forEach((t) => this.closeTab(group, t)) },
|
||
'-',
|
||
{ label: 'Split Right', icon: 'split', action: () => { this.activate(group, tab); this.split(); } },
|
||
{ label: 'Select in Project View', action: () => this.app.tree?.reveal(tab.path) },
|
||
{ label: 'Copy Path', action: () => copyText(tab.path) },
|
||
tab.kind === 'text' && this.app.git?.enabled ? { label: 'Show Diff with HEAD', icon: 'diff', action: () => this.app.git.diff(tab.path) } : null,
|
||
tab.kind === 'text' && this.app.project?.capabilities?.localHistory ? { label: 'Show Local History', icon: 'history', action: () => showLocalHistory(this.app, tab.path) } : null,
|
||
tab.kind !== 'diff' ? '-' : null,
|
||
tab.kind !== 'diff' ? { label: 'View as Hexadecimal', checked: !!tab.hex, action: () => this.toggleHex(tab) } : null,
|
||
this.canPreview(tab) ? { label: 'Preview HTML', checked: tab.mode === 'preview' && !tab.hex, action: () => this.togglePreview(tab) } : null,
|
||
].filter(Boolean), { x: e.clientX, y: e.clientY });
|
||
}
|
||
|
||
async closeTab(group, tab, silent = false) {
|
||
if (!silent && tab.kind === 'text' && this.isDirty(tab.path) && !group.tabs.some((t) => t !== tab && t.path === tab.path)) {
|
||
await this.save(tab.path);
|
||
}
|
||
const index = group.tabs.indexOf(tab);
|
||
group.tabs.splice(index, 1);
|
||
if (group.modelTab === tab) group.modelTab = null;
|
||
if (group.active === tab.id) {
|
||
const next = group.tabs[index] || group.tabs[index - 1];
|
||
group.active = next?.id || null;
|
||
if (next) this.activate(group, next); else { this.renderTabs(group); this.renderView(group, null); this.emit('active', null); }
|
||
} else {
|
||
this.renderTabs(group);
|
||
}
|
||
if (tab.kind === 'diff') { group.diff?.dispose(); group.diff = null; }
|
||
if (!this.groups.some((g) => g.tabs.some((t) => t.path === tab.path && t.kind !== 'diff'))) {
|
||
const file = this.files.get(tab.path);
|
||
if (file?.model && !this.isDirty(tab.path)) { file.model.dispose(); this.files.delete(tab.path); }
|
||
else if (file && !file.model) this.files.delete(tab.path);
|
||
}
|
||
if (!group.tabs.length && this.groups.length > 1) this.closeGroup(group);
|
||
}
|
||
|
||
renderEmpty(group = this.focused) {
|
||
if (!group || group.tabs.length) return;
|
||
group.textView.style.display = 'none';
|
||
const hint = (a, b) => [el('span', {}, a), el('kbd', {}, kbd(b))];
|
||
group.host.append(el('div.view.empty-editor', {}, el('div.hints', {},
|
||
...hint('Search Everywhere', 'Double Shift'), ...hint('Go to File', 'Ctrl+Shift+N'), ...hint('Go to Class', 'Ctrl+N'),
|
||
...hint('Recent Files', 'Ctrl+E'), ...hint('Find in Files', 'Ctrl+Shift+F'), ...hint('Commit', 'Ctrl+K'), ...hint('Run', 'Shift+F10'))));
|
||
clear(group.crumbs);
|
||
}
|
||
|
||
updateCrumbs(group) {
|
||
const tab = this.activeTab(group);
|
||
const symbols = tab && this.app.outlineCache?.get(tab.path);
|
||
const pos = group.editor.getPosition();
|
||
const names = [];
|
||
if (symbols && pos) {
|
||
for (const s of symbols) {
|
||
if (pos.lineNumber >= s.line && pos.lineNumber <= (s.endLine || s.line)) {
|
||
names.push(s.name);
|
||
const m = (s.children || []).find((c) => c.kind === 'method' && pos.lineNumber >= c.line && pos.lineNumber <= (c.endLine || c.line));
|
||
if (m) names.push(m.name);
|
||
}
|
||
}
|
||
}
|
||
const key = tab ? tab.path + '|' + names.join('|') : '';
|
||
if (group.crumbKey === key && group.crumbs.firstChild) return;
|
||
group.crumbKey = key;
|
||
clear(group.crumbs);
|
||
if (!tab) return;
|
||
const parts = tab.path.replace(/^\/@lib/, '').split('/');
|
||
parts.forEach((part, i) => {
|
||
if (i) group.crumbs.append(el('span.sep', {}, '›'));
|
||
group.crumbs.append(el('span', { onclick: () => this.app.tree?.reveal(parts.slice(0, i + 1).join('/')) }, part));
|
||
});
|
||
if (symbols && pos) {
|
||
for (const s of symbols) {
|
||
if (pos.lineNumber >= s.line && pos.lineNumber <= (s.endLine || s.line)) {
|
||
group.crumbs.append(el('span.sep', {}, '›'), el('span', { onclick: () => this.reveal(group, { line: s.line, col: s.col }) }, s.name));
|
||
const member = (s.children || []).find((c) => c.kind === 'method' && pos.lineNumber >= c.line && pos.lineNumber <= (c.endLine || c.line));
|
||
if (member) group.crumbs.append(el('span.sep', {}, '›'), el('span', { onclick: () => this.reveal(group, { line: member.line, col: member.col }) }, member.name + '()'));
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
// saving ---------------------------------------------------------------------------------------------------
|
||
|
||
isDirty(path) {
|
||
const file = this.files.get(path);
|
||
return !!file?.model && (file.model.getAlternativeVersionId() !== file.saved || !!file.formatChanged);
|
||
}
|
||
|
||
dirtyPaths() { return [...this.files.keys()].filter((p) => this.isDirty(p)); }
|
||
|
||
changed(path) {
|
||
// the tab bar only changes when the dirty mark flips (not at every key)
|
||
const dirty = this.isDirty(path);
|
||
this.dirtyMark ??= new Map();
|
||
if (this.dirtyMark.get(path) !== dirty) {
|
||
this.dirtyMark.set(path, dirty);
|
||
for (const g of this.groups) if (g.tabs.some((t) => t.path === path)) this.renderTabs(g);
|
||
}
|
||
this.emit('dirty', path);
|
||
if (prefs.get('autosave', true)) this.autosave();
|
||
}
|
||
|
||
async save(path) {
|
||
const file = this.files.get(path);
|
||
if (!file?.model || file.readOnly || !this.isDirty(path)) return;
|
||
const version = file.model.getAlternativeVersionId();
|
||
try {
|
||
const write = { path, content: file.model.getValue(), encoding: file.encoding || 'UTF-8', eol: file.eol === 'mixed' ? 'LF' : (file.eol || 'LF') };
|
||
const remote = remoteOf(path);
|
||
const result = await backend.invoke(remote ? 'ssh.file.write' : 'file.write', remote ? { ...write, ...remote } : write);
|
||
file.saved = version;
|
||
file.formatChanged = false;
|
||
if (file.eol === 'mixed') file.eol = 'LF';
|
||
file.mtime = result?.mtime;
|
||
this.dirtyMark?.set(path, this.isDirty(path));
|
||
for (const g of this.groups) if (g.tabs.some((t) => t.path === path)) this.renderTabs(g);
|
||
this.emit('saved', path);
|
||
} catch (e) {
|
||
notify(e.message, 'error', { title: 'Cannot save ' + basename(path) });
|
||
}
|
||
}
|
||
|
||
/** The status bar's choice: the file written with these line endings / this encoding at the next save (now with autosave). */
|
||
setFormat(path, change) {
|
||
const file = this.files.get(path);
|
||
if (!file?.model || file.readOnly) return;
|
||
Object.assign(file, change, { formatChanged: true });
|
||
this.changed(path);
|
||
}
|
||
|
||
async saveAll(auto = false) {
|
||
for (const path of this.dirtyPaths()) await this.save(path);
|
||
if (!auto) this.app.status?.('All files are saved');
|
||
}
|
||
|
||
/** Reloads files changed on disk (after a git checkout, a pull, a run...) unless edited here. */
|
||
async reloadFromDisk(paths = null) {
|
||
for (const [path, file] of this.files) {
|
||
if (!file.model || (paths && !paths.includes(path)) || this.isDirty(path) || path.startsWith('/') || remoteOf(path)) continue;
|
||
try {
|
||
const version = file.model.getAlternativeVersionId();
|
||
const data = await backend.invoke('file.read', { path });
|
||
// typed while the disk was read: what was typed wins (it is saved next)
|
||
if (this.isDirty(path) || file.model.getAlternativeVersionId() !== version) continue;
|
||
if (data.text && data.content !== file.model.getValue()) {
|
||
file.model.pushEditOperations([], [{ range: file.model.getFullModelRange(), text: data.content }], () => null);
|
||
file.saved = file.model.getAlternativeVersionId();
|
||
}
|
||
} catch {
|
||
// deleted: close its tabs
|
||
for (const g of this.groups) for (const t of g.tabs.filter((t) => t.path === path)) this.closeTab(g, t, true);
|
||
}
|
||
}
|
||
}
|
||
|
||
/** A file was renamed or deleted in the tree: follow it. */
|
||
renamed(from, to) {
|
||
for (const [path, file] of [...this.files]) {
|
||
if (path === from || path.startsWith(from + '/')) {
|
||
const target = to === null ? null : to + path.slice(from.length);
|
||
for (const g of this.groups) {
|
||
for (const t of [...g.tabs].filter((t) => t.path === path)) {
|
||
if (target === null) this.closeTab(g, t, true); else t.path = target;
|
||
}
|
||
}
|
||
if (target !== null && file.model) {
|
||
const model = monaco.editor.createModel(file.model.getValue(), languageOf(target), uriOf(target));
|
||
model.onDidChangeContent(() => this.changed(target));
|
||
file.model.dispose();
|
||
this.files.delete(path);
|
||
this.files.set(target, { ...file, model, saved: model.getAlternativeVersionId() });
|
||
} else this.files.delete(path);
|
||
}
|
||
}
|
||
for (const g of this.groups) { g.modelTab = null; this.renderTabs(g); const tab = this.activeTab(g); if (tab) this.renderView(g, tab); }
|
||
}
|
||
|
||
// navigation -----------------------------------------------------------------------------------------------
|
||
|
||
addRecent(path) {
|
||
this.recent = [path, ...this.recent.filter((p) => p !== path)].slice(0, 50);
|
||
prefs.set('recent:' + (this.app.projectKey || ''), this.recent);
|
||
}
|
||
|
||
pushNavigation() {
|
||
const tab = this.activeTab();
|
||
if (!tab || tab.kind !== 'text') return;
|
||
const pos = this.focused.editor.getPosition();
|
||
const entry = { path: tab.path, line: pos?.lineNumber || 1, col: pos?.column || 1 };
|
||
const last = this.navigation[this.navIndex];
|
||
if (last && last.path === entry.path && Math.abs(last.line - entry.line) < 3) return;
|
||
this.navigation = this.navigation.slice(0, this.navIndex + 1);
|
||
this.navigation.push(entry);
|
||
this.navIndex = this.navigation.length - 1;
|
||
}
|
||
|
||
async back() {
|
||
if (this.navIndex < 0) return;
|
||
const current = this.activeTab();
|
||
if (current && this.navIndex === this.navigation.length - 1) { this.pushNavigation(); this.navIndex--; }
|
||
const entry = this.navigation[this.navIndex];
|
||
if (!entry) return;
|
||
this.navIndex = Math.max(0, this.navIndex - 1);
|
||
await this.openQuiet(entry);
|
||
}
|
||
|
||
async forward() {
|
||
const entry = this.navigation[this.navIndex + 2] || this.navigation[this.navIndex + 1];
|
||
if (!entry) return;
|
||
this.navIndex = this.navigation.indexOf(entry);
|
||
await this.openQuiet(entry);
|
||
}
|
||
|
||
async openQuiet(entry) {
|
||
const group = this.focused;
|
||
let tab = group.tabs.find((t) => t.path === entry.path && t.kind === 'text');
|
||
if (!tab) { await this.load(entry.path); tab = { id: 'tab' + Math.random().toString(36).slice(2), path: entry.path, kind: 'text' }; group.tabs.push(tab); }
|
||
this.activate(group, tab);
|
||
this.reveal(group, entry);
|
||
}
|
||
|
||
// PHP language features ----------------------------------------------------------------------------------
|
||
|
||
registerOpener() {
|
||
monaco.editor.registerEditorOpener({
|
||
openCodeEditor: (source, resource, selection) => {
|
||
const path = pathOf(resource);
|
||
const options = {};
|
||
if (selection) {
|
||
options.line = selection.startLineNumber ?? selection.lineNumber;
|
||
options.col = selection.startColumn ?? selection.column;
|
||
}
|
||
this.open(path, options);
|
||
return true;
|
||
},
|
||
});
|
||
}
|
||
|
||
/** Models for result locations: Monaco's peek view needs them. */
|
||
async ensureModels(paths) {
|
||
for (const path of new Set(paths)) {
|
||
if (!monaco.editor.getModel(uriOf(path))) {
|
||
try {
|
||
const data = await backend.invoke('file.read', { path });
|
||
if (data.text) monaco.editor.createModel(data.content, languageOf(path), uriOf(path));
|
||
} catch { /* gone */ }
|
||
}
|
||
}
|
||
}
|
||
|
||
registerPhp() {
|
||
const args = (model, position) => ({ path: pathOf(model.uri), text: model.getValue(), line: position.lineNumber, column: position.column });
|
||
// "↳ N calls" above each method: a click opens the Calls window (calls.js)
|
||
registerCallLenses(monaco, this.app, pathOf);
|
||
registerMissingPackageFix(monaco, this.app); // quick fix on "Undefined class": install the missing package
|
||
const range = (r) => new monaco.Range(r.startLine, r.startColumn, r.endLine, r.endColumn);
|
||
const location = (l) => ({ uri: uriOf(l.path), range: new monaco.Range(l.line, l.col, l.line, l.col + (l.length || 0)) });
|
||
const kinds = KIND();
|
||
|
||
monaco.languages.registerCompletionItemProvider('php', {
|
||
triggerCharacters: ['>', ':', '$', '\\', "'", '"'],
|
||
provideCompletionItems: async (model, position, context, token) => {
|
||
const line = model.getLineContent(position.lineNumber).slice(0, position.column - 1);
|
||
if (context.triggerCharacter === '>' && !line.endsWith('->')) return { suggestions: [] };
|
||
if ((context.triggerCharacter === "'" || context.triggerCharacter === '"') && !/\(\s*['"]$/.test(line)) return { suggestions: [] };
|
||
if (context.triggerCharacter === ':' && !line.endsWith('::')) return { suggestions: [] };
|
||
// a failed answer (the backend busy indexing, a request dropped) is asked once more before giving up on "Loading…"
|
||
let result = await backend.invoke('php.complete', args(model, position)).catch(() => null);
|
||
if (!result && !token.isCancellationRequested) result = await backend.invoke('php.complete', args(model, position)).catch(() => null);
|
||
if (!result || token.isCancellationRequested) return { suggestions: [] };
|
||
const word = model.getWordUntilPosition(position);
|
||
// a string argument (t('…'), isPressed('…')): what is typed inside the quotes, spaces included
|
||
const from = typeof result.typed === 'string' ? position.column - result.typed.length : word.startColumn;
|
||
const replace = new monaco.Range(position.lineNumber, from, position.lineNumber, position.column);
|
||
return {
|
||
incomplete: result.incomplete,
|
||
suggestions: result.items.map((item) => ({
|
||
label: { label: item.label, detail: item.kind === 'method' || item.kind === 'function' ? item.detail?.replace(/^[^(]*/, '') : undefined, description: item.description || (item.kind !== 'method' ? item.detail : '') },
|
||
kind: kinds[item.kind] ?? monaco.languages.CompletionItemKind.Text,
|
||
insertText: item.insertText,
|
||
insertTextRules: item.snippet ? monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet : undefined,
|
||
filterText: item.filterText, sortText: item.sortText, range: replace,
|
||
documentation: item.documentation ? { value: item.documentation } : undefined,
|
||
detail: item.detail, tags: item.deprecated ? [monaco.languages.CompletionItemTag.Deprecated] : undefined,
|
||
additionalTextEdits: (item.additionalTextEdits || []).map((e) => ({ range: range(e.range), text: e.text })),
|
||
command: item.parameterHints ? { id: 'editor.action.triggerParameterHints', title: '' } : undefined,
|
||
})),
|
||
};
|
||
},
|
||
});
|
||
|
||
// "Undefined class 'Xxx'": the lightbulb / Alt+Enter offers "Import X\Y\Z" for each indexed class of that name (php.importFixes)
|
||
monaco.languages.registerCodeActionProvider('php', {
|
||
provideCodeActions: async (model, selection, context, token) => {
|
||
const markers = context.markers.filter((m) => /^Undefined class\b/.test(m.message || ''));
|
||
if (!markers.length) return { actions: [], dispose() {} };
|
||
const marker = markers[0];
|
||
const fixes = await backend.invoke('php.importFixes', args(model, { lineNumber: marker.startLineNumber, column: marker.startColumn })).catch(() => []);
|
||
if (token.isCancellationRequested) return { actions: [], dispose() {} };
|
||
const actions = (fixes || []).map((fix, i) => ({
|
||
title: t('Import {name}', { name: fix.fqn }), kind: 'quickfix', isPreferred: i === 0, diagnostics: [marker],
|
||
edit: { edits: [{ resource: model.uri, versionId: model.getVersionId(), textEdit: { range: range(fix.edit.range), text: fix.edit.text } }] },
|
||
}));
|
||
return { actions, dispose() {} };
|
||
},
|
||
}, { providedCodeActionKinds: ['quickfix'] });
|
||
|
||
// config/game.yaml, input.yaml, services.yaml, lang.yaml, forms/*.form.yaml, compose files (JumPHP\Ide\Config\ConfigCompletion):
|
||
// keys, values, ready-made services (snippets), image: names and tags from Docker Hub
|
||
monaco.languages.registerCompletionItemProvider('yaml', {
|
||
triggerCharacters: [' ', '[', ',', ':', '/'],
|
||
provideCompletionItems: async (model, position, context) => {
|
||
if (!completesYaml(pathOf(model.uri))) return { suggestions: [] };
|
||
const line = model.getLineContent(position.lineNumber).slice(0, position.column - 1);
|
||
if ((context.triggerCharacter === ':' || context.triggerCharacter === '/') && !/^\s*(?:-\s+)?image\s*:\s*\S/.test(line)) return { suggestions: [] };
|
||
const result = await backend.invoke('config.complete', args(model, position)).catch(() => null);
|
||
if (!result) return { suggestions: [] };
|
||
const typed = typeof result.typed === 'string' ? result.typed : /[\w\\:. -]*$/.exec(line)[0].replace(/^.*[\[,:]\s*|^\s+|^-\s+/, '');
|
||
const replace = new monaco.Range(position.lineNumber, position.column - typed.length, position.lineNumber, position.column);
|
||
return {
|
||
incomplete: !!result.incomplete,
|
||
suggestions: result.items.map((item) => ({
|
||
label: item.label, kind: kinds[item.kind] ?? monaco.languages.CompletionItemKind.Value, insertText: item.insertText,
|
||
insertTextRules: item.snippet ? monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet : undefined,
|
||
detail: item.detail || undefined, documentation: item.documentation ? { value: item.documentation } : undefined,
|
||
sortText: item.sortText, filterText: item.filterText ?? (typed.includes('/') ? item.label : undefined), range: replace,
|
||
})),
|
||
};
|
||
},
|
||
});
|
||
|
||
// a compose file: what Docker Hub says of the image under the mouse (DockerHub keeps its answers a while)
|
||
monaco.languages.registerHoverProvider('yaml', {
|
||
provideHover: async (model, position) => {
|
||
if (!isComposeFile(pathOf(model.uri))) return null;
|
||
const image = imageAt(model.getLineContent(position.lineNumber), position.column);
|
||
if (!image) return null;
|
||
const repo = await backend.invoke('docker.hub.repo', { name: image.name }).catch(() => null);
|
||
if (!repo) return null;
|
||
const n = (x) => (x >= 1e9 ? (x / 1e9).toFixed(1) + 'B' : x >= 1e6 ? (x / 1e6).toFixed(1) + 'M' : x >= 1e3 ? (x / 1e3).toFixed(1) + 'k' : String(x));
|
||
const tag = repo.tags?.find((t) => t.name === image.tag);
|
||
const lines = [`**${repo.name}**${repo.official ? ` · ${t('Official')}` : ''}`, repo.description || '',
|
||
`★ ${n(repo.stars)} · ↓ ${n(repo.pulls)}${repo.updated ? ` · ${t('Updated {date}', { date: new Date(repo.updated).toLocaleDateString() })}` : ''}`,
|
||
tag ? `\`${image.tag}\`: ${(tag.size / 1048576).toFixed(0)} MB${tag.architectures?.length ? ' · ' + tag.architectures.join(', ') : ''}` : '',
|
||
repo.url ? `[${t('Open on Docker Hub')}](${repo.url})` : ''];
|
||
return { range: new monaco.Range(position.lineNumber, image.start, position.lineNumber, image.end), contents: [{ value: lines.filter(Boolean).join('\n\n') }] };
|
||
},
|
||
});
|
||
|
||
// the keys of a YAML file (Ctrl+F12, breadcrumbs, the Structure window): yaml.outline
|
||
monaco.languages.registerDocumentSymbolProvider('yaml', {
|
||
provideDocumentSymbols: async (model) => {
|
||
const outline = await backend.invoke('yaml.outline', { text: model.getValue() }).catch(() => []);
|
||
const K = monaco.languages.SymbolKind;
|
||
const symbol = (s) => ({ name: s.name, detail: s.detail || '', kind: s.kind === 'object' ? K.Module : s.kind === 'item' ? K.EnumMember : K.Property,
|
||
range: new monaco.Range(s.line, 1, s.endLine || s.line, 1), selectionRange: new monaco.Range(s.line, s.col, s.line, s.col + s.name.length), tags: [],
|
||
children: (s.children || []).map(symbol) });
|
||
return outline.map(symbol);
|
||
},
|
||
});
|
||
|
||
monaco.languages.registerDefinitionProvider('php', {
|
||
provideDefinition: async (model, position) => {
|
||
const list = await backend.invoke('php.definition', args(model, position)).catch(() => []);
|
||
await this.ensureModels(list.map((l) => l.path));
|
||
this.pushNavigation();
|
||
if (!list.length) {
|
||
// on a declaration: show its usages (as PhpStorm does)
|
||
const refs = await backend.invoke('php.references', { ...args(model, position), declarations: false }).catch(() => []);
|
||
if (refs.length) this.app.showUsages?.(refs, model.getWordAtPosition(position)?.word);
|
||
return [];
|
||
}
|
||
return list.map((l) => ({ uri: uriOf(l.path), range: new monaco.Range(l.line, l.col, l.line, l.col) }));
|
||
},
|
||
});
|
||
|
||
monaco.languages.registerImplementationProvider('php', {
|
||
provideImplementation: async (model, position) => {
|
||
const list = await backend.invoke('php.implementations', args(model, position)).catch(() => []);
|
||
await this.ensureModels(list.map((l) => l.path));
|
||
return list.map((l) => ({ uri: uriOf(l.path), range: new monaco.Range(l.line, l.col, l.line, l.col) }));
|
||
},
|
||
});
|
||
|
||
monaco.languages.registerReferenceProvider('php', {
|
||
provideReferences: async (model, position, context) => {
|
||
const refs = await backend.invoke('php.references', { ...args(model, position), declarations: context.includeDeclaration }).catch(() => []);
|
||
await this.ensureModels(refs.map((r) => r.path));
|
||
return refs.map(location);
|
||
},
|
||
});
|
||
|
||
monaco.languages.registerDocumentHighlightProvider('php', {
|
||
// the cursor moves at every key: wait until it rests, then this file only (php.highlights; it used to be the symbol, then its
|
||
// references in the whole project: ~150 ms of PHP per move)
|
||
provideDocumentHighlights: async (model, position, token) => {
|
||
await new Promise((resolve) => setTimeout(resolve, 120));
|
||
if (token?.isCancellationRequested || model.isDisposed()) return [];
|
||
const refs = await backend.invoke('php.highlights', args(model, position)).catch(() => []);
|
||
if (token?.isCancellationRequested) return [];
|
||
const path = pathOf(model.uri);
|
||
return refs.filter((r) => r.path === path).map((r) => ({ range: new monaco.Range(r.line, r.col, r.line, r.col + r.length),
|
||
kind: r.declaration ? monaco.languages.DocumentHighlightKind.Write : monaco.languages.DocumentHighlightKind.Read }));
|
||
},
|
||
});
|
||
|
||
monaco.languages.registerRenameProvider('php', {
|
||
resolveRenameLocation: async (model, position) => {
|
||
const symbol = await backend.invoke('php.symbol', args(model, position)).catch(() => null);
|
||
if (!symbol) return { rejectReason: 'This element cannot be renamed.', range: undefined, text: '' };
|
||
const r = range(symbol.range);
|
||
return { range: r, text: model.getValueInRange(r).replace(/^\$/, '') };
|
||
},
|
||
provideRenameEdits: async (model, position, newName) => {
|
||
await this.saveAll(true);
|
||
const result = await backend.invoke('php.rename', { ...args(model, position), newName });
|
||
const edits = [];
|
||
const closed = {};
|
||
for (const [path, list] of Object.entries(result.edits)) {
|
||
const open = monaco.editor.getModel(uriOf(path));
|
||
if (open && this.files.has(path)) {
|
||
for (const e of list) edits.push({ resource: open.uri, versionId: undefined, textEdit: { range: new monaco.Range(e.line, e.col, e.line, e.col + e.length), text: e.text } });
|
||
} else closed[path] = list;
|
||
}
|
||
if (Object.keys(closed).length) await backend.invoke('edits.apply', { edits: closed });
|
||
if (result.renameFile) {
|
||
setTimeout(async () => {
|
||
await this.saveAll(true);
|
||
await backend.invoke('file.rename', { from: result.renameFile.from, to: result.renameFile.to });
|
||
this.renamed(result.renameFile.from, result.renameFile.to);
|
||
this.app.tree?.refresh();
|
||
}, 50);
|
||
}
|
||
if (result.uncertain.length) {
|
||
notify(`${result.uncertain.length} possible use(s) whose type is unknown were left as they are.`, 'info', { title: 'Rename',
|
||
actions: [{ label: 'Show them', action: () => this.app.showUsages?.(result.uncertain, 'not renamed') }] });
|
||
}
|
||
const count = Object.values(result.edits).reduce((n, l) => n + l.length, 0);
|
||
this.app.status?.(`Renamed to ${newName}: ${count} place(s) in ${Object.keys(result.edits).length} file(s)`);
|
||
return { edits };
|
||
},
|
||
});
|
||
|
||
monaco.languages.registerHoverProvider('php', {
|
||
provideHover: async (model, position) => {
|
||
const hover = await backend.invoke('php.hover', args(model, position)).catch(() => null);
|
||
return hover ? { contents: [{ value: hover.contents }], range: range(hover.range) } : null;
|
||
},
|
||
});
|
||
|
||
monaco.languages.registerSignatureHelpProvider('php', {
|
||
signatureHelpTriggerCharacters: ['(', ','],
|
||
signatureHelpRetriggerCharacters: [','],
|
||
provideSignatureHelp: async (model, position) => {
|
||
const help = await backend.invoke('php.signature', args(model, position)).catch(() => null);
|
||
if (!help) return null;
|
||
return { value: { signatures: [{ label: help.label, documentation: help.documentation, parameters: help.params.map((p) => ({ label: p })) }], activeSignature: 0, activeParameter: help.active }, dispose() {} };
|
||
},
|
||
});
|
||
|
||
const symbolKinds = SYMBOL();
|
||
monaco.languages.registerDocumentSymbolProvider('php', {
|
||
provideDocumentSymbols: async (model) => {
|
||
const outline = await backend.invoke('php.outline', { text: model.getValue() }).catch(() => []);
|
||
this.app.outlineCache?.set(pathOf(model.uri), outline);
|
||
const symbol = (s) => {
|
||
const r = new monaco.Range(s.line, 1, s.endLine || s.line, 1);
|
||
return { name: s.name, detail: s.detail || '', kind: symbolKinds[s.kind] ?? monaco.languages.SymbolKind.Variable, range: r,
|
||
selectionRange: new monaco.Range(s.line, s.col, s.line, s.col + s.name.length), tags: [], children: (s.children || []).map(symbol) };
|
||
};
|
||
return outline.map(symbol);
|
||
},
|
||
});
|
||
}
|
||
|
||
/** The editor's context menu: Play (PHP files of a game), then PhpStorm's entries. */
|
||
editorMenu(group, e) {
|
||
e.event?.preventDefault?.();
|
||
e.event?.stopPropagation?.();
|
||
const ed = group.editor;
|
||
const tab = this.activeTab();
|
||
if (!tab || tab.kind !== 'text') return;
|
||
const file = this.files.get(tab.path);
|
||
const position = e.target?.position;
|
||
if (position && !ed.getSelection()?.containsPosition(position)) ed.setPosition(position);
|
||
this.focus(group);
|
||
ed.focus();
|
||
const run = (id) => () => { ed.focus(); ed.trigger('menu', id, null); };
|
||
const php = tab.path.endsWith('.php');
|
||
const writable = !file?.readOnly;
|
||
const play = this.app.playTarget?.(tab.path);
|
||
menu([
|
||
play ? { label: play.label, icon: colorIcon('play', 'green'), kbd: 'Ctrl+Shift+F10', action: () => this.app.playFile(tab.path) } : null,
|
||
play ? '-' : null,
|
||
this.app.claude ? { label: ed.getSelection()?.isEmpty() ? 'Ask Claude about This File' : 'Ask Claude about the Selection', icon: 'claude', action: () => {
|
||
const sel = ed.getSelection();
|
||
this.app.claude.ask(sel && !sel.isEmpty() ? `In ${tab.path} (lines ${sel.startLineNumber}-${sel.endLineNumber}):\n\`\`\`\n${ed.getModel().getValueInRange(sel)}\n\`\`\`\n` : `@${tab.path} `);
|
||
} } : null,
|
||
this.app.claude ? '-' : null,
|
||
php ? { label: 'Go to Declaration', kbd: 'Ctrl+B', action: run('editor.action.revealDefinition') } : null,
|
||
php ? { label: 'Go to Implementation(s)', kbd: 'Ctrl+Alt+B', action: run('editor.action.goToImplementation') } : null,
|
||
php ? { label: 'Find Usages', icon: 'find', kbd: 'Alt+F7', action: () => this.app.findUsages?.() } : null,
|
||
php ? { label: 'Type Hierarchy', icon: 'structure', kbd: 'Ctrl+H', action: () => this.app.typeHierarchy?.() } : null,
|
||
php ? '-' : null,
|
||
php && writable ? { label: 'Rename…', kbd: 'Shift+F6', action: run('editor.action.rename') } : null,
|
||
writable ? { label: 'Reformat Code', kbd: 'Ctrl+Alt+L', action: run('editor.action.formatDocument') } : null,
|
||
writable ? { label: 'Comment with Line Comment', kbd: 'Ctrl+/', action: run('editor.action.commentLine') } : null,
|
||
writable ? '-' : null,
|
||
writable ? { label: 'Cut', kbd: 'Ctrl+X', action: () => { const text = ed.getModel().getValueInRange(ed.getSelection()); copyText(text); ed.executeEdits('cut', [{ range: ed.getSelection(), text: '' }]); } } : null,
|
||
{ label: 'Copy', kbd: 'Ctrl+C', action: () => copyText(ed.getModel().getValueInRange(ed.getSelection())) },
|
||
writable ? { label: 'Paste', kbd: 'Ctrl+V', action: async () => { const text = await pasteText(); if (text != null) { ed.focus(); ed.executeEdits('paste', [{ range: ed.getSelection(), text, forceMoveMarkers: true }]); } } } : null,
|
||
'-',
|
||
this.app.git?.enabled ? { label: 'Git', icon: 'branch', items: [
|
||
{ label: 'Annotate with Git Blame', action: () => this.app.git.toggleBlame() },
|
||
{ label: 'Show Diff with HEAD', icon: 'diff', action: () => this.app.git.diff(tab.path) },
|
||
] } : null,
|
||
{ label: 'Command Palette…', kbd: 'F1', action: run('editor.action.quickCommand') },
|
||
].filter(Boolean), { x: e.event.posx, y: e.event.posy });
|
||
}
|
||
|
||
/** PhpStorm's keys on top of Monaco's. */
|
||
addEditorActions(editor) {
|
||
const K = monaco.KeyMod;
|
||
const C = monaco.KeyCode;
|
||
const run = (id) => () => editor.trigger('keyboard', id, null);
|
||
const add = (id, label, keys, handler, menuGroup) => editor.addAction({ id: 'jph.' + id, label, keybindings: keys, run: handler, contextMenuGroupId: menuGroup });
|
||
add('declaration', 'Go to Declaration', [K.CtrlCmd | C.KeyB], run('editor.action.revealDefinition'), 'navigation');
|
||
add('implementation', 'Go to Implementation(s)', [K.CtrlCmd | K.Alt | C.KeyB], run('editor.action.goToImplementation'), 'navigation');
|
||
add('usages', 'Find Usages', [K.Alt | C.F7], () => this.app.findUsages?.(), 'navigation');
|
||
add('rename', 'Rename…', [K.Shift | C.F6], run('editor.action.rename'), '1_modification');
|
||
add('duplicate', 'Duplicate Line or Selection', [K.CtrlCmd | C.KeyD], run('editor.action.copyLinesDownAction'));
|
||
add('deleteLine', 'Delete Line', [K.CtrlCmd | C.KeyY], run('editor.action.deleteLines'));
|
||
add('expand', 'Extend Selection', [K.CtrlCmd | C.KeyW], run('editor.action.smartSelect.expand'));
|
||
add('shrink', 'Shrink Selection', [K.CtrlCmd | K.Shift | C.KeyW], run('editor.action.smartSelect.shrink'));
|
||
add('moveUp', 'Move Line Up', [K.Alt | K.Shift | C.UpArrow], run('editor.action.moveLinesUpAction'));
|
||
add('moveDown', 'Move Line Down', [K.Alt | K.Shift | C.DownArrow], run('editor.action.moveLinesDownAction'));
|
||
add('format', 'Reformat Code', [K.CtrlCmd | K.Alt | C.KeyL], run('editor.action.formatDocument'));
|
||
add('params', 'Parameter Info', [K.CtrlCmd | C.KeyP], run('editor.action.triggerParameterHints'));
|
||
add('doc', 'Quick Documentation', [K.CtrlCmd | C.KeyQ], run('editor.action.showHover'));
|
||
add('structure', 'File Structure', [K.CtrlCmd | C.F12], () => this.app.fileStructure?.());
|
||
add('comment', 'Comment with Line Comment', [K.CtrlCmd | C.Slash], run('editor.action.commentLine'));
|
||
add('save', 'Save All', [K.CtrlCmd | C.KeyS], () => this.saveAll());
|
||
add('playFile', 'Play', [K.CtrlCmd | K.Shift | C.F10], () => { const p = this.activePath(); if (p) this.app.playFile?.(p); });
|
||
add('hierarchy', 'Type Hierarchy', [K.CtrlCmd | C.KeyH], () => this.app.typeHierarchy?.());
|
||
add('close', 'Close Tab', [K.CtrlCmd | C.F4], () => { const t = this.activeTab(); if (t) this.closeTab(this.focused, t); });
|
||
add('back', 'Back', [K.CtrlCmd | K.Alt | C.LeftArrow], () => this.back());
|
||
add('forward', 'Forward', [K.CtrlCmd | K.Alt | C.RightArrow], () => this.forward());
|
||
add('annotate', 'Annotate with Git Blame', [], () => this.app.git?.toggleBlame(), 'z_git');
|
||
add('diffHead', 'Show Diff with HEAD', [], () => this.app.git?.diff(this.activePath()), 'z_git');
|
||
add('hexView', 'View as Hexadecimal', [], () => this.toggleHex());
|
||
add('htmlPreview', 'Preview HTML', [], () => this.togglePreview());
|
||
}
|
||
}
|
||
|
||
function detectIndent(text) {
|
||
const m = text.match(/^( +)\S/m);
|
||
return m ? Math.min(8, m[1].length) : 4;
|
||
}
|