rob-revisited/ide/ui/js/quick.js

344 lines
18 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// The quick editor (quick.html): `jumphp-ide <file>` or "Open with JumPHP" in the system's file manager. One file of the disk,
// edited at once: Monaco and nothing else (no project, no index, no Git, no assistant). PHP: games/ide/src/QuickEditor.php
// (quick.state, quick.save, quick.pick), quick.project opens the whole IDE on the file's folder.
import { backend } from './backend.js';
import { registerTwig, availableLanguage } from './twig-lang.js';
import { registerYaml } from './yaml-lang.js';
import { loadLanguage, t, notify, prefs, debounce } from './ui.js';
import { HexView, bytesReader } from './hexview.js';
import { HtmlPreview, dataUrlOf, textOfBase64 } from './html-preview.js';
import { renderMarkdown } from './markdown.js';
import { LANGUAGE_CHOICES, VIEW_CHOICES, mediaElement, readAll } from './filetype.js';
const LANGUAGES = { php: 'php', phtml: 'php', inc: 'php', module: 'php', js: 'javascript', mjs: 'javascript', cjs: 'javascript', ts: 'typescript', jsx: 'javascript',
tsx: 'typescript', json: 'json', lock: 'json', webmanifest: 'json', map: 'json', jsonc: 'json', html: 'html', htm: 'html', xhtml: 'html', twig: 'twig', tpl: 'html', css: 'css', scss: 'scss',
sass: 'scss', hbs: 'handlebars', handlebars: 'handlebars', mustache: 'handlebars', kt: 'kotlin', kts: 'kotlin', swift: 'swift', dart: 'dart', r: 'r', pl: 'perl', pm: 'perl',
graphql: 'graphql', gql: 'graphql', proto: 'proto', sol: 'sol', scala: 'scala', ex: 'elixir', exs: 'elixir', clj: 'clojure', fs: 'fsharp', vb: 'vb', pas: 'pascal',
m: 'objective-c', coffee: 'coffee', pug: 'pug', jade: 'pug', tcl: 'tcl', hcl: 'hcl', tf: 'hcl', bicep: 'bicep', csv: 'plaintext', log: 'plaintext', diff: 'plaintext', patch: 'plaintext',
glsl: 'cpp', vert: 'cpp', frag: 'cpp', mk: 'shell', zsh: 'shell', fish: 'shell', cfg: 'ini', properties: 'ini', gitignore: 'ini', editorconfig: 'ini',
tmj: 'json', tsj: 'json', tmx: 'xml', plist: 'xml', csproj: 'xml', xaml: 'xml', rss: 'xml', atom: 'xml',
less: 'less', yaml: 'yaml', yml: 'yaml', neon: 'yaml', md: 'markdown', markdown: 'markdown', xml: 'xml', svg: 'xml', xlf: 'xml', sh: 'shell',
bash: 'shell', ini: 'ini', env: 'ini', conf: 'ini', toml: 'ini', sql: 'sql', py: 'python', rs: 'rust', go: 'go', java: 'java', c: 'c', h: 'c',
cpp: 'cpp', hpp: 'cpp', cs: 'csharp', rb: 'ruby', lua: 'lua', bat: 'bat', ps1: 'powershell', dockerfile: 'dockerfile', vue: 'html', txt: 'plaintext' };
const $ = (id) => document.getElementById(id);
const languageOf = (name, text = '') => {
if (/^dockerfile/i.test(name) || /\.dockerfile$/i.test(name)) return 'dockerfile';
if (/^makefile$/i.test(name)) return 'shell';
if (/^\.(env|htaccess|gitignore|gitattributes|editorconfig)/.test(name)) return 'ini';
const found = name.includes('.') ? LANGUAGES[(name.split('.').pop() || '').toLowerCase()] : null;
if (found) return found;
// no extension (a script): its first line says it
const first = text.slice(0, 200).split('\n')[0];
if (/^<\?php/.test(first) || /^#!.*\bphp\b/.test(first)) return 'php';
if (/^#!.*\b(ba|z|da|k)?sh\b/.test(first)) return 'shell';
if (/^#!.*\bpython/.test(first)) return 'python';
if (/^#!.*\bnode\b/.test(first)) return 'javascript';
if (/^#!.*\bruby\b/.test(first)) return 'ruby';
if (/^#!.*\bperl\b/.test(first)) return 'perl';
if (/^\s*<!doctype html|^\s*<html/i.test(first)) return 'html';
if (/^\s*<\?xml/.test(first)) return 'xml';
if (/^\s*[{[]/.test(first) && /[}\]]\s*$/.test(text.trim())) return 'json';
return 'plaintext';
};
const kb = (n) => (n >= 1048576 ? (n / 1048576).toFixed(1) + ' MB' : n >= 1024 ? (n / 1024).toFixed(1) + ' KB' : n + ' B');
let file = null; // what quick.state answered
let editor = null;
let savedVersion = 0;
let hexMode = false; // the file's bytes in hexadecimal instead of its text / picture
let hexView = null;
let preview = null; // the live preview of an HTML / CSS file, beside the code
// the files a page uses, read from the disk (paths with '/': the preview's own; 'C:/...' on Windows)
const diskPath = (p) => (/^[A-Za-z]:/.test(p) ? p : '/' + p);
const readRange = (p, length = 1024 * 1024) => backend.invoke('quick.bytes', { path: diskPath(p), offset: 0, length });
const canPreview = (f) => !!f && !f.binary && /\.(html?|css|twig|md|markdown)$/i.test(f.name);
const isMarkdown = (f) => /\.(md|markdown)$/i.test(f?.name || '');
/** Twig in the preview: its tags taken out ({{ x }} shown as x, {% %} and {# #} dropped): the page's look, not its data */
const untwig = (text) => text.replace(/\{#[\s\S]*?#\}/g, '').replace(/\{%[\s\S]*?%\}/g, '').replace(/\{\{-?\s*([\s\S]*?)\s*-?\}\}/g, (m, e) => e.replace(/\|.*$/, ''));
/** code | both | preview, kept for HTML / CSS / Twig / Markdown files (the bottom switch, and the top button) */
const previewMode = () => prefs.get('quickMode', prefs.get('quickPreview', false) ? 'split' : 'code');
function dirty() { return !!editor && editor.getModel().getAlternativeVersionId() !== savedVersion; }
function showDirty() {
$('dirty').classList.toggle('on', dirty());
$('save').disabled = !file || file.readOnly || !dirty();
document.title = (dirty() ? '● ' : '') + (file ? file.name : 'JumPHP') + ' – JumPHP';
}
function show(f) {
file = f;
$('name').textContent = f.name;
$('path').textContent = f.dir;
$('path').title = f.path;
const ro = $('ro');
ro.hidden = !f.readOnly;
ro.textContent = f.binary ? t('read only') : f.size > 20 * 1024 * 1024 ? t('big file: read only') : t('read only');
$('size').textContent = f.exists ? kb(f.size) : t('new file');
$('eol').textContent = f.eol === '\r\n' ? 'CRLF' : 'LF';
const chosen = prefs.get('quickLang', {})[f.path];
const language = f.binary ? (f.media ? f.media.mime : 'binary') : availableLanguage(window.monaco, chosen || languageOf(f.name, f.text));
$('lang').textContent = language;
hexMode = false;
showViewer(f);
const model = window.monaco.editor.createModel(f.text, f.binary ? 'plaintext' : language);
model.setEOL(f.eol === '\r\n' ? 1 : 0);
const old = editor.getModel();
editor.setModel(model);
old?.dispose();
editor.updateOptions({ readOnly: f.readOnly });
savedVersion = model.getAlternativeVersionId();
model.onDidChangeContent(showDirty);
model.onDidChangeContent(debounce(() => preview?.update(), 400));
showDirty();
showPreview();
editor.focus();
}
/** Preview (an HTML / CSS file): the page beside the code, drawn again a moment after each change */
function showPreview() {
const mode = canPreview(file) && !hexMode ? previewMode() : 'code';
const on = mode !== 'code';
const btn = $('preview-btn');
btn.hidden = !canPreview(file);
btn.classList.toggle('on', on);
renderModeSwitch(mode);
preview?.destroy();
preview = null;
$('preview').hidden = !on;
// the preview alone: the code is hidden (still there: back with Code or Both)
$('editor').classList.toggle('hidden', mode === 'preview' || !$('viewer').hidden);
$('preview').style.borderLeft = mode === 'preview' ? '0' : '';
if (!on) return;
if (isMarkdown(file)) {
// Markdown: drawn as a document, again a moment after each change
const box = document.createElement('div');
box.className = 'md-preview';
const draw = () => { box.replaceChildren(...[].concat(renderMarkdown(editor.getValue(), (href) => backend.invoke('native.openUrl', { url: href }).catch(() => null), null) || [])); };
draw();
$('preview').replaceChildren(box);
preview = { update: draw, destroy: () => box.remove() };
return;
}
const twig = /\.twig$/i.test(file.name);
preview = new HtmlPreview($('preview'), {
path: file.path.replace(/\\/g, '/').replace(/^\//, ''),
kind: /\.css$/i.test(file.name) ? 'css' : 'html',
prefix: 'quickPreview',
text: () => (twig ? untwig(editor.getValue()) : editor.getValue()),
readText: async (p) => { const r = await readRange(p).catch(() => null); return r && r.length >= r.size ? textOfBase64(r.base64) : null; },
readDataUrl: async (p) => { const r = await readRange(p, 16 * 1024 * 1024); return r.length >= r.size ? dataUrlOf(p, r.base64) : null; },
});
}
/** The status bar's type (click): read the file as another language, or show it in hexadecimal / as a picture, PDF, film, sound */
function chooseType() {
document.getElementById('type-menu')?.remove();
if (!file) return;
const menu = document.createElement('div');
menu.id = 'type-menu';
const add = (label, action, on = false) => {
const b = document.createElement('button');
b.textContent = (on ? '✓ ' : '') + label;
b.onclick = () => { menu.remove(); action(); };
menu.append(b);
};
const current = editor.getModel()?.getLanguageId();
if (!file.binary) {
for (const [id, label] of LANGUAGE_CHOICES) {
add(label, () => {
window.monaco.editor.setModelLanguage(editor.getModel(), availableLanguage(window.monaco, id));
prefs.set('quickLang', { ...prefs.get('quickLang', {}), [file.path]: id });
if (hexMode) toggleHex();
$('lang').textContent = id;
}, id === current);
}
menu.append(document.createElement('hr'));
}
for (const [kind, label] of VIEW_CHOICES) {
add(label, async () => {
if (kind === 'hex') { if (!hexMode) toggleHex(); return; }
try {
const bytes = await readAll((offset, length) => backend.invoke('quick.bytes', { path: file.path, offset, length }));
const viewer = $('viewer');
viewer.replaceChildren(mediaElement(kind, bytes));
viewer.hidden = false;
$('editor').classList.add('hidden');
$('lang').textContent = kind;
} catch (e) { notify(String(e.message || e), 'error'); }
});
}
document.body.append(menu);
const close = (e) => { if (!menu.contains(e.target)) { menu.remove(); document.removeEventListener('mousedown', close); } };
setTimeout(() => document.addEventListener('mousedown', close));
}
/** the switch at the bottom right: Code | Both | Preview (HTML, CSS, Twig, Markdown) */
function renderModeSwitch(mode) {
let sw = $('mode-switch');
if (!sw) {
sw = document.createElement('div');
sw.id = 'mode-switch';
document.body.append(sw);
}
sw.hidden = !canPreview(file) || hexMode;
sw.replaceChildren(...[['code', t('Code')], ['split', t('Both')], ['preview', t('Preview')]].map(([m, label]) => {
const b = document.createElement('button');
b.textContent = label;
b.className = m === mode ? 'on' : '';
b.onclick = () => { prefs.set('quickMode', m); showPreview(); if (m !== 'preview') editor.focus(); };
return b;
}));
}
/** a picture, a film, a sound, a PDF, a font: shown; another binary file: its first bytes in hexadecimal; an SVG: its picture or its code (the button) */
function showViewer(f) {
const viewer = $('viewer');
const toggle = $('toggle');
viewer.replaceChildren();
hexView?.destroy();
hexView = null;
viewer.classList.remove('hexmode');
$('hex').classList.toggle('on', hexMode);
const media = f.media;
const text = !f.binary && !(media && media.kind !== 'image');
const asPicture = media && (!text || prefs.get('quickSvgView', 'picture') === 'picture');
toggle.hidden = !(media && text); // an SVG: picture or code
toggle.textContent = asPicture ? t('Code') : t('Picture');
toggle.onclick = () => { prefs.set('quickSvgView', asPicture ? 'code' : 'picture'); showViewer(file); };
const meta = (...parts) => Object.assign(document.createElement('div'), { className: 'meta', textContent: parts.filter(Boolean).join(' · ') });
const make = (tag, props) => Object.assign(document.createElement(tag), props);
let shown = false;
if (hexMode || (f.binary && !media)) {
// any file in hexadecimal (a binary file without a viewer: always), read a range at a time: a big file stays fast
viewer.hidden = false;
viewer.classList.add('hexmode');
$('editor').classList.add('hidden');
$('hex').classList.toggle('on', true);
hexView = new HexView(viewer, { read: bytesReader(backend, 'quick.bytes', f.path), note: hexMode && dirty() ? t('Unsaved changes are not shown: this is the file on the disk') : '' });
return;
}
if (media && asPicture) {
shown = true;
if (!media.data) viewer.append(meta(t('Too big to be shown here'), kb(f.size)));
else if (media.kind === 'image') {
const img = make('img', { src: media.data, alt: f.name, title: t('Click: actual size / fit') });
img.onclick = () => img.classList.toggle('zoomed');
img.onload = () => viewer.append(meta(`${img.naturalWidth} × ${img.naturalHeight}`, media.mime, kb(f.size)));
viewer.append(img);
} else if (media.kind === 'video') {
const v = make('video', { src: media.data, controls: true });
v.onloadedmetadata = () => viewer.append(meta(`${v.videoWidth} × ${v.videoHeight}`, `${v.duration.toFixed(1)} s`, media.mime, kb(f.size)));
viewer.append(v);
} else if (media.kind === 'audio') {
const a = make('audio', { src: media.data, controls: true });
a.onloadedmetadata = () => viewer.append(meta(`${a.duration.toFixed(1)} s`, media.mime, kb(f.size)));
viewer.append(a);
} else if (media.kind === 'pdf') {
viewer.append(make('iframe', { src: media.data, title: f.name }));
} else if (media.kind === 'font') {
const family = 'quick-font-' + Date.now();
new FontFace(family, `url(${media.data})`).load().then((face) => {
document.fonts.add(face);
const sample = make('div', { className: 'font-sample' });
sample.style.fontFamily = family;
for (const size of [14, 20, 32, 48]) {
sample.append(make('div', { textContent: 'The quick brown fox jumps over the lazy dog 0123456789 ÀÉÎÕÜ àéîõü @#&!?', style: `font-size:${size}px` }));
}
viewer.append(sample, meta(f.name, media.mime, kb(f.size)));
}).catch((e) => viewer.append(meta(t('This font can not be read'), String(e.message || e))));
}
}
viewer.hidden = !shown;
viewer.classList.toggle('top', !!f.binary && !media);
$('editor').classList.toggle('hidden', shown);
}
/** Hexadecimal: the file's bytes, or its normal view again (a binary file without a viewer stays in hexadecimal) */
function toggleHex() {
if (!file?.exists) return;
if (file.binary && !file.media) return;
hexMode = !hexMode;
showViewer(file);
showPreview();
if (!hexMode && !$('editor').classList.contains('hidden')) editor.focus();
}
async function save(force = false) {
if (!file || file.readOnly || (!dirty() && !force)) return;
const version = editor.getModel().getAlternativeVersionId();
const r = await backend.invoke('quick.save', { path: file.path, text: editor.getValue(), mtime: force ? null : file.mtime, force });
if (r.conflict) {
if (confirm(t('{name} was changed by another program since it was opened. Overwrite it with yours?', { name: file.name }))) return save(true);
return;
}
file.mtime = r.mtime;
file.exists = true;
savedVersion = version;
showDirty();
}
async function openOther() {
if (dirty() && !confirm(t('Your changes to {name} are not saved. Open another file anyway?', { name: file.name }))) return;
const f = await backend.invoke('quick.pick').catch((e) => { notify(e.message, 'error'); return null; });
if (f) show(f);
}
async function asProject() {
if (dirty() && !confirm(t('Your changes to {name} are not saved. Open the folder anyway?', { name: file.name }))) return;
await backend.invoke('quick.project', { dir: file.dir }).catch((e) => notify(e.message, 'error'));
}
async function main() {
await loadLanguage();
const light = prefs.get('theme', 'dark') === 'light';
document.documentElement.dataset.theme = light ? 'light' : 'dark';
$('loading').textContent = t('Opening…');
$('open').textContent = t('Open…');
$('save').textContent = t('Save');
$('project').textContent = t('Open the folder as a project');
$('project').title = t('The whole IDE on this file\'s folder');
$('dirty').title = t('Not saved');
$('open').onclick = openOther;
$('save').onclick = () => save().catch((e) => notify(e.message, 'error'));
$('project').onclick = asProject;
$('hex').textContent = t('Hexadecimal');
$('hex').title = t('The file\'s bytes in hexadecimal') + ' (Ctrl+Shift+H)';
$('hex').onclick = toggleHex;
$('lang').title = t('Read this file as another type (language, hexadecimal, picture, PDF…)');
$('lang').style.cursor = 'pointer';
$('lang').onclick = chooseType;
$('preview-btn').textContent = t('Preview');
$('preview-btn').title = t('The page beside its code, drawn again as you type');
$('preview-btn').onclick = () => { prefs.set('quickMode', previewMode() === 'code' ? 'split' : 'code'); showPreview(); };
// the file and Monaco at the same time: both are ready about together
const [f] = await Promise.all([
// a window opened by the IDE already running (another jumphp-ide <file>) says its file in its address
backend.invoke('quick.state', new URLSearchParams(location.search).get('path') ? { path: new URLSearchParams(location.search).get('path') } : {}).catch((e) => ({ error: e.message })),
new Promise((resolve, reject) => {
window.require.config({ paths: { vs: new URL('vendor/monaco/vs', document.baseURI).href } });
window.require(['vs/editor/editor.main'], () => { registerYaml(window.monaco); registerTwig(window.monaco).then(resolve, resolve); }, reject);
}),
]);
$('editor').replaceChildren();
editor = window.monaco.editor.create($('editor'), {
theme: light ? 'vs' : 'vs-dark', automaticLayout: true, fontSize: prefs.get('fontSize', 13.5), minimap: { enabled: true },
scrollBeyondLastLine: false, renderWhitespace: 'selection', wordWrap: 'off', bracketPairColorization: { enabled: true },
});
editor.onDidChangeCursorPosition((e) => { $('pos').textContent = `${e.position.lineNumber}:${e.position.column}`; });
editor.addCommand(window.monaco.KeyMod.CtrlCmd | window.monaco.KeyCode.KeyS, () => save().catch((e) => notify(e.message, 'error')));
editor.addCommand(window.monaco.KeyMod.CtrlCmd | window.monaco.KeyCode.KeyO, openOther);
editor.addCommand(window.monaco.KeyMod.CtrlCmd | window.monaco.KeyMod.Shift | window.monaco.KeyCode.KeyH, toggleHex);
editor.addAction({ id: 'quick.hex', label: t('View as Hexadecimal'), run: toggleHex });
editor.addAction({ id: 'quick.preview', label: t('Preview HTML'), run: () => { if (canPreview(file)) $('preview-btn').click(); } });
if (f.error) {
$('name').textContent = t('No file');
notify(f.error, 'error');
return;
}
show(f);
}
window.addEventListener('beforeunload', (e) => { if (dirty()) { e.preventDefault(); e.returnValue = ''; } });
main().catch((e) => { const p = $('loading'); if (p) p.textContent = String(e.message || e); });