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

158 lines
8.1 KiB
JavaScript

// "Report a bug" (the bug button of the header): the person says what happened, may leave a way to answer them, and may attach a
// screenshot of the IDE. It goes to jumphp.net (POST /bug-report), where JumPHP's administrator reads it: with the account when the
// person is signed in (desktop: its token, sent by PHP; web: the session), else anonymous. The desktop IDE adds its version, the
// system and the end of its log (cleaned by PHP: no home folder, no name, no e-mail); never a file of the project.
//
// The screenshot is drawn from the page itself (html2canvas-pro, js/lib/: the same on WebKitGTK, WebView2, WebKit and in a browser):
// the dialog and the overlays are left out, so it shows the IDE as it was. "Retake" hides the dialog and lets the person arrange the
// IDE first (open the panel that shows the problem), then take it.
import { backend } from './backend.js';
import { el, dialog, notify, t, uiLang } from './ui.js';
const MAX_BYTES = 5 * 1024 * 1024;
let library = null;
/** html2canvas, loaded once. Evaluated with its own exports: Monaco's AMD loader owns window.define, the UMD must not register there. */
function html2canvas() {
library ??= fetch(new URL('lib/html2canvas-pro.min.js', import.meta.url)).then((r) => {
if (!r.ok) throw new Error(`HTTP ${r.status}`);
return r.text();
}).then((code) => {
const exports = {};
// eslint-disable-next-line no-new-func
new Function('exports', 'module', 'define', code)(exports, { exports }, undefined);
const fn = exports.html2canvas || exports.default;
if (typeof fn !== 'function') throw new Error('html2canvas did not load');
return fn;
}).catch((e) => { library = null; throw e; });
return library;
}
const skipped = (node) => node.id === 'overlays' || node.classList?.contains('overlay') || node.classList?.contains('bug-shot-bar') || node.id === 'boot-guard';
/** The IDE as a PNG data URL (overlays left out), smaller until it fits the site's 5 MB. */
async function capture() {
const draw = await html2canvas();
const bg = getComputedStyle(document.body).backgroundColor || '#1e1f22';
let scale = Math.min(window.devicePixelRatio || 1, 1.5);
for (let i = 0; i < 4; i++) {
const canvas = await draw(document.body, {
backgroundColor: bg, scale, logging: false, useCORS: true, ignoreElements: skipped,
width: window.innerWidth, height: window.innerHeight, windowWidth: window.innerWidth, windowHeight: window.innerHeight, x: window.scrollX, y: window.scrollY,
});
const url = canvas.toDataURL('image/png');
if ((url.length - 22) * 0.75 <= MAX_BYTES) return url;
scale *= 0.7;
}
throw new Error(t('The screenshot is too big (5 MB at most).'));
}
/** Facts the page knows (the desktop IDE's PHP adds its version, the system and its log). */
function pageMeta(app) {
const kind = app?.project?.modules?.[0]?.kind || (app?.project ? 'game' : '');
return { kind, lang: uiLang(), screen: `${window.innerWidth}x${window.innerHeight}@${window.devicePixelRatio || 1}`, ua: navigator.userAgent };
}
async function send(report) {
if (backend.kind === 'native') return backend.invoke('bugreport.send', report);
const response = await fetch('/bug-report', {
method: 'POST',
credentials: 'same-origin',
headers: { 'Content-Type': 'application/json', Accept: 'application/json', 'X-CSRF-Token': backend.config.csrf || '' },
body: JSON.stringify({
message: report.message, contact: report.contact, screenshot: report.screenshot,
meta: { app: 'ide', source: 'web', ...report.meta, page: location.pathname },
}),
});
let data = null;
try { data = await response.json(); } catch { /* not JSON */ }
if (!response.ok) {
throw new Error(response.status === 429 ? t('Too many reports from this address: try again in an hour.')
: response.status === 413 ? t('The screenshot is too big (5 MB at most).')
: (data && data.error) || `HTTP ${response.status}`);
}
return data;
}
export function openBugReport(app) {
let shot = null; // data URL
let busy = false;
const text = el('textarea.input.bug-text', { rows: 6, placeholder: t('What happened? What did you do just before? What did you expect?') });
const contact = el('input.input', { placeholder: t('E-mail or another way to answer you (optional)'), maxLength: 200, autocomplete: 'off' });
const attach = el('input', { type: 'checkbox', checked: true });
const thumb = el('img.bug-thumb', { alt: t('Screenshot') });
const state = el('span.bug-state');
const retake = el('button.btn', { type: 'button' }, t('Retake'));
const remove = el('button.btn', { type: 'button' }, t('Remove'));
const preview = el('div.bug-preview', {}, thumb, el('div.bug-preview-side', {}, state, retake, remove));
const error = el('div.bug-error');
const refresh = () => {
thumb.hidden = !shot || !attach.checked;
remove.hidden = !shot || !attach.checked;
retake.hidden = !attach.checked || busy;
retake.textContent = shot ? t('Retake') : t('Take the screenshot');
state.textContent = !attach.checked ? t('No screenshot will be sent.') : busy ? t('Taking the screenshot…') : shot ? '' : t('No screenshot yet.');
if (shot) thumb.src = shot;
};
const take = async () => {
busy = true; refresh();
try { shot = await capture(); } catch (e) { shot = null; error.textContent = t('The screenshot could not be taken: {error}', { error: e.message || String(e) }); }
busy = false; refresh();
};
const d = dialog({
title: 'Report a bug',
wide: true,
onClose: () => document.querySelector('.bug-shot-bar')?.remove(),
body: el('div.bug-report', {},
el('p.faint', {}, t('Tell us what went wrong: it goes to the JumPHP team. Your project\'s files are never sent.')),
el('label.bug-label', {}, t('What happened (required)')), text,
el('label.bug-label', {}, t('Contact')), contact,
el('label.bug-check', {}, attach, ' ', t('Attach a screenshot of the IDE')),
preview,
el('p.faint.bug-note', {}, backend.kind === 'native'
? t('Also sent: the IDE\'s version, your system, the project kind and the last 50 lines of the IDE\'s log (without your name, e-mail or home folder).')
: t('Also sent: your browser, the project kind and the page\'s size.')),
error),
buttons: [
{ label: 'Cancel' },
{
label: 'Send', primary: true,
action: async () => {
error.textContent = '';
if (!text.value.trim()) { error.textContent = t('Say what happened.'); text.focus(); return false; }
if (busy) { error.textContent = t('Taking the screenshot…'); return false; }
try {
const result = await send({ message: text.value, contact: contact.value, screenshot: attach.checked ? shot : null, meta: pageMeta(app) });
notify(result && result.account ? t('Bug report sent, thank you. It is linked to your jumphp.net account.') : t('Bug report sent, thank you.'), 'info');
return true;
} catch (e) {
error.textContent = t('The report could not be sent: {error}', { error: e.message || String(e) });
return false;
}
},
},
],
});
// retake: the dialog steps aside, the person arranges the IDE, then takes it (or cancels)
retake.addEventListener('click', () => {
if (busy) return;
const layer = d.box.closest('.overlay') || d.box;
layer.style.visibility = 'hidden';
const back = () => { bar.remove(); layer.style.visibility = ''; };
const bar = el('div.bug-shot-bar', {},
el('span', {}, t('Arrange the IDE to show the problem, then take the screenshot.')),
el('button.btn.primary', { type: 'button', onclick: async () => { bar.remove(); await take(); layer.style.visibility = ''; } }, t('Take the screenshot')),
el('button.btn', { type: 'button', onclick: back }, t('Cancel')));
document.body.append(bar);
});
remove.addEventListener('click', () => { shot = null; attach.checked = false; refresh(); });
attach.addEventListener('change', () => { refresh(); if (attach.checked && !shot && !busy) take(); });
refresh();
take(); // at once: the IDE as it was when the button was pressed (the dialog is left out)
setTimeout(() => text.focus(), 30);
return d;
}