211 lines
11 KiB
JavaScript
211 lines
11 KiB
JavaScript
// Paths in the editor (the pure part: path-links.js; the backend: JumPHP\Ide\Links):
|
||
// - completion of a path being typed (import './|', src="img/|", url(|), {% extends '|' %}, asset('|'), a Markdown link...): the
|
||
// folders then the files next to the file (or in templates/, assets/, public/), and for a bare `import '|'` the packages of
|
||
// importmap.php and node_modules (path.complete);
|
||
// - the WHOLE path as one link (underlined on Ctrl+hover, Ctrl+click opens it; path.resolve tells which ones exist);
|
||
// - an image's preview on a long hover (a thumbnail, its size in pixels and bytes; an http(s) image is fetched by the backend:
|
||
// image.fetch, public addresses only) and Ctrl+click opens it in the image tab;
|
||
// - JavaScript / TypeScript: Monaco's worker only sees the open file; the project's modules it imports and the packages' files
|
||
// (AssetMapper's assets/vendor/, node_modules' types) are given to it as extra libraries (js.libraries), so
|
||
// `import { Controller } from '@hotwired/stimulus'` then `this.` completes.
|
||
import { backend } from './backend.js';
|
||
import { PATH_LANGUAGES, IMAGE, refsInLine, refAt, pathTypedAt, rankEntries, formatSize, fitIn, importsOf } from './path-links.js';
|
||
|
||
const OPEN = 'jumphp-open';
|
||
const THUMB = 240;
|
||
|
||
/** A link's target as a Monaco URI (the link opener below opens it in the IDE). */
|
||
const openUri = (monaco, target) => monaco.Uri.from({ scheme: OPEN, path: '/', query: target });
|
||
|
||
export function registerPathFeatures(monaco, { pathOf, open }) {
|
||
const K = monaco.languages.CompletionItemKind;
|
||
for (const language of PATH_LANGUAGES) {
|
||
monaco.languages.registerCompletionItemProvider(language, {
|
||
triggerCharacters: ['/', "'", '"', '@', '.', '('],
|
||
provideCompletionItems: async (model, position) => {
|
||
const before = model.getLineContent(position.lineNumber).slice(0, position.column - 1);
|
||
const at = pathTypedAt(model.getLanguageId(), before);
|
||
if (!at) return { suggestions: [] };
|
||
const result = await backend.invoke('path.complete', { path: pathOf(model.uri), typed: at.typed, kind: at.kind }).catch(() => null);
|
||
if (!result?.items?.length) return { suggestions: [] };
|
||
const typed = result.typed ?? '';
|
||
const range = new monaco.Range(position.lineNumber, position.column - typed.length, position.lineNumber, position.column);
|
||
const ranked = rankEntries(result.items, at.kind === 'module' && !/^[./]/.test(at.typed) ? '' : typed);
|
||
return {
|
||
suggestions: ranked.map((item, i) => ({
|
||
label: { label: item.label, description: item.detail || undefined },
|
||
kind: item.kind === 'folder' ? K.Folder : item.kind === 'package' ? K.Module : K.File,
|
||
insertText: item.insertText, filterText: item.label, sortText: String(i).padStart(4, '0'), range,
|
||
// a folder: its entries at once
|
||
command: item.kind === 'folder' ? { id: 'editor.action.triggerSuggest', title: '' } : undefined,
|
||
})),
|
||
};
|
||
},
|
||
});
|
||
|
||
monaco.languages.registerLinkProvider(language, {
|
||
provideLinks: async (model) => {
|
||
const count = model.getLineCount();
|
||
if (count > 5000) return { links: [] };
|
||
const found = [];
|
||
for (let line = 1; line <= count; line++) {
|
||
for (const r of refsInLine(model.getLanguageId(), model.getLineContent(line))) found.push({ line, ...r });
|
||
if (found.length > 1000) break;
|
||
}
|
||
if (!found.length) return { links: [] };
|
||
const local = found.filter((r) => r.kind !== 'url');
|
||
const targets = local.length ? await backend.invoke('path.resolve', { path: pathOf(model.uri), refs: local.map((r) => ({ ref: r.ref, kind: r.kind })) }).catch(() => []) : [];
|
||
const range = (r) => new monaco.Range(r.line, r.start + 1, r.line, r.end + 1);
|
||
const links = [];
|
||
local.forEach((r, i) => { if (targets[i]) links.push({ range: range(r), url: openUri(monaco, targets[i]), tooltip: targets[i] }); });
|
||
for (const r of found) if (r.kind === 'url') links.push({ range: range(r), url: openUri(monaco, r.ref), tooltip: r.ref });
|
||
return { links };
|
||
},
|
||
});
|
||
|
||
monaco.languages.registerHoverProvider(language, {
|
||
provideHover: async (model, position) => {
|
||
const r = refAt(model.getLanguageId(), model.getLineContent(position.lineNumber), position.column - 1);
|
||
if (!r || !IMAGE.test(r.ref.replace(/[?#].*$/, ''))) return null;
|
||
const preview = await imagePreview(pathOf(model.uri), r).catch(() => null);
|
||
if (!preview) return null;
|
||
return {
|
||
range: new monaco.Range(position.lineNumber, r.start + 1, position.lineNumber, r.end + 1),
|
||
contents: [{ value: `![${preview.name.replace(/[[\]]/g, '')}](${preview.thumb})` },
|
||
{ value: `**${preview.name}** · ${preview.width} × ${preview.height} px · ${formatSize(preview.size)}` }],
|
||
};
|
||
},
|
||
});
|
||
}
|
||
|
||
// a link of ours: the file (or the web image) in a tab of the IDE
|
||
monaco.editor.registerLinkOpener({
|
||
open(resource) {
|
||
const uri = typeof resource === 'string' ? monaco.Uri.parse(resource) : resource;
|
||
if (uri.scheme !== OPEN || !uri.query) return false;
|
||
open(uri.query);
|
||
return true;
|
||
},
|
||
});
|
||
}
|
||
|
||
const previews = new Map(); // key -> {at, preview}
|
||
|
||
/** A thumbnail of the image a reference names: {name, thumb (data URL), width, height, size}. */
|
||
async function imagePreview(from, ref) {
|
||
let target = ref.ref;
|
||
if (ref.kind !== 'url') {
|
||
[target] = await backend.invoke('path.resolve', { path: from, refs: [{ ref: ref.ref, kind: ref.kind }] });
|
||
if (!target) return null;
|
||
}
|
||
const cached = previews.get(target);
|
||
if (cached && performance.now() - cached.at < 30000) return cached.preview;
|
||
let dataUrl;
|
||
let size;
|
||
if (ref.kind === 'url') {
|
||
const data = await backend.invoke('image.fetch', { url: target });
|
||
[dataUrl, size] = [data.image, data.size];
|
||
} else if (/\.svg$/i.test(target)) {
|
||
const data = await backend.invoke('file.bytes', { path: target, offset: 0, length: 1048576 });
|
||
[dataUrl, size] = ['data:image/svg+xml;base64,' + data.base64, data.size];
|
||
} else {
|
||
const data = await backend.invoke('file.read', { path: target });
|
||
if (!data.image) return null;
|
||
[dataUrl, size] = [data.image, data.size];
|
||
}
|
||
const img = await new Promise((resolve, reject) => { const i = new Image(); i.onload = () => resolve(i); i.onerror = reject; i.src = dataUrl; });
|
||
const width = img.naturalWidth;
|
||
const height = img.naturalHeight;
|
||
const fit = fitIn(width, height, THUMB);
|
||
const canvas = document.createElement('canvas');
|
||
canvas.width = fit.width;
|
||
canvas.height = fit.height;
|
||
const g = canvas.getContext('2d');
|
||
// pixel art stays sharp when it is made bigger
|
||
g.imageSmoothingEnabled = fit.width < width;
|
||
g.drawImage(img, 0, 0, fit.width, fit.height);
|
||
let thumb = canvas.toDataURL('image/png');
|
||
if (thumb.length > 90000) thumb = canvas.toDataURL('image/jpeg', 0.85); // Monaco's markdown cuts at 100 000 characters
|
||
const preview = { name: target.split(/[\\/]/).pop().replace(/[?#].*$/, '') || target, thumb, width, height, size };
|
||
previews.set(target, { at: performance.now(), preview });
|
||
if (previews.size > 60) previews.delete(previews.keys().next().value);
|
||
return preview;
|
||
}
|
||
|
||
/**
|
||
* The project's JavaScript for Monaco's TypeScript worker: when a JS / TS file is shown or its imports change, the files it imports
|
||
* (and theirs) become extra libraries at their own file:/// URI, and importmap.php's specifiers map to their assets/vendor/ files.
|
||
* `editors` = the Editors (its 'active' and 'saved' events, files map); uriOf = the editor's path -> URI.
|
||
*/
|
||
export function attachJsProject(monaco, editors, uriOf) {
|
||
const ts = monaco.languages.typescript;
|
||
if (!ts) return;
|
||
const options = {
|
||
target: ts.ScriptTarget.ESNext, module: ts.ModuleKind.ESNext, moduleResolution: ts.ModuleResolutionKind.NodeJs,
|
||
allowJs: true, checkJs: false, allowNonTsExtensions: true, esModuleInterop: true, allowSyntheticDefaultImports: true,
|
||
experimentalDecorators: true, jsx: ts.JsxEmit.Preserve, baseUrl: 'file:///',
|
||
};
|
||
const paths = {};
|
||
const libs = new Map(); // path -> {content, js: disposable, ts: disposable}
|
||
const asked = new Map(); // path -> imports signature last asked for
|
||
let warmed = false;
|
||
// only when they change: new options restart the worker (a request in flight is cancelled)
|
||
const apply = () => {
|
||
for (const defaults of [ts.javascriptDefaults, ts.typescriptDefaults]) {
|
||
const next = { ...defaults.getCompilerOptions(), ...options, paths };
|
||
if (JSON.stringify(next) !== JSON.stringify(defaults.getCompilerOptions())) defaults.setCompilerOptions(next);
|
||
}
|
||
};
|
||
apply();
|
||
// a library that becomes an open file: the model wins (the same file twice would declare everything twice)
|
||
monaco.editor.onDidCreateModel((model) => {
|
||
for (const [path, lib] of libs) if (uriOf(path).toString() === model.uri.toString()) { lib.js.dispose(); lib.ts.dispose(); libs.delete(path); }
|
||
});
|
||
const refresh = async (path, force = false) => {
|
||
const file = editors.files.get(path);
|
||
const model = file?.model;
|
||
if (!model || !['javascript', 'typescript'].includes(model.getLanguageId())) return;
|
||
// the worker starts (and reads its 5 MB) now, not at the first completion
|
||
if (!warmed) { warmed = true; (model.getLanguageId() === 'typescript' ? ts.getTypeScriptWorker() : ts.getJavaScriptWorker()).then((get) => get(model.uri)).catch(() => {}); }
|
||
const text = model.getValue();
|
||
const signature = importsOf(text).join('\n');
|
||
if (!force && asked.get(path) === signature) return;
|
||
asked.set(path, signature);
|
||
if (!signature) return;
|
||
const result = await backend.invoke('js.libraries', { path, text }).catch(() => null);
|
||
if (!result) return;
|
||
if (libs.size > 600) { for (const lib of libs.values()) { lib.js.dispose(); lib.ts.dispose(); } libs.clear(); }
|
||
for (const { path: lib, content } of result.libs) {
|
||
// the raw path (not uri.toString(), which writes @ as %40): what the worker's module resolution and `paths` look for
|
||
const uri = 'file:///' + lib;
|
||
if (monaco.editor.getModel(uriOf(lib))) continue;
|
||
const old = libs.get(lib);
|
||
if (old?.content === content) continue;
|
||
if (old) { old.js.dispose(); old.ts.dispose(); }
|
||
libs.set(lib, { content, js: ts.javascriptDefaults.addExtraLib(content, uri), ts: ts.typescriptDefaults.addExtraLib(content, uri) });
|
||
}
|
||
let changed = false;
|
||
for (const [spec, files] of Object.entries(result.paths || {})) {
|
||
if (JSON.stringify(paths[spec]) !== JSON.stringify(files)) { paths[spec] = files; changed = true; }
|
||
}
|
||
if (changed) apply();
|
||
};
|
||
let timer = null;
|
||
const watched = new WeakSet();
|
||
editors.on('active', (tab) => {
|
||
if (!tab?.path) return;
|
||
refresh(tab.path);
|
||
const model = editors.files.get(tab.path)?.model;
|
||
if (model && !watched.has(model)) {
|
||
watched.add(model);
|
||
model.onDidChangeContent(() => { clearTimeout(timer); timer = setTimeout(() => refresh(tab.path), 1200); });
|
||
}
|
||
});
|
||
// a module saved: what imports it reads it again
|
||
editors.on('saved', (path) => {
|
||
if (!/\.(m?js|ts|jsx|tsx)$/.test(path)) return;
|
||
asked.clear();
|
||
const active = editors.focused?.tabs?.find((t) => t.id === editors.focused.active);
|
||
if (active?.path && active.path !== path) refresh(active.path, true);
|
||
});
|
||
}
|