60 lines
2.8 KiB
JavaScript
60 lines
2.8 KiB
JavaScript
// The live reload of a served web site, in the status bar: "Live: 2" = 2 browser tabs follow the saves (CSS injected, anything
|
|
// else reloaded). A click: open the site in the browser (the live-reload address, not the raw PHP port), turn it off / on.
|
|
// The IDE's PHP side (ide/src/Web/LiveReload.php) tells the reload container each saved file and answers `web.live`.
|
|
import { backend } from './backend.js';
|
|
import { t, el, icon, menu, notify } from './ui.js';
|
|
|
|
/** The status bar's words for what `web.live` answered: {text, title, state: 'off' | 'down' | 'idle' | 'on'} */
|
|
export function liveSummary(s) {
|
|
if (!s || !s.enabled) return { text: t('Live: off'), title: t('Live reload: off'), state: 'off' };
|
|
if (!s.running) return { text: t('Live: {n}', { n: '-' }), title: t('Live reload: the site is not running'), state: 'down' };
|
|
if (s.clients <= 0) return { text: t('Live: {n}', { n: 0 }), title: t('Live reload: no browser tab connected'), state: 'idle' };
|
|
const title = s.clients === 1 ? t('Live reload: 1 browser tab connected') : t('Live reload: {n} browser tabs connected', { n: s.clients });
|
|
return { text: t('Live: {n}', { n: s.clients }), title, state: 'on' };
|
|
}
|
|
|
|
export class LiveReload {
|
|
constructor(app) {
|
|
this.app = app;
|
|
this.status = null;
|
|
this.node = el('span.sb-item.clickable', { id: 'sbLive', onclick: (e) => this.popup(e.currentTarget) }, icon('globe'), el('span'));
|
|
document.getElementById('sbBranch')?.before(this.node);
|
|
this.refresh();
|
|
setInterval(() => { if (document.visibilityState === 'visible') this.refresh(); }, 4000);
|
|
}
|
|
|
|
async refresh() {
|
|
try { this.status = await backend.invoke('web.live', {}); } catch (e) { this.status = null; }
|
|
this.render();
|
|
}
|
|
|
|
render() {
|
|
const s = liveSummary(this.status);
|
|
this.node.lastChild.textContent = s.text;
|
|
this.node.title = s.title;
|
|
this.node.dataset.state = s.state;
|
|
this.node.style.opacity = s.state === 'off' || s.state === 'down' ? '0.6' : '1';
|
|
}
|
|
|
|
open() {
|
|
const url = this.status?.url;
|
|
if (url) this.app.openUrl(url);
|
|
}
|
|
|
|
popup(node) {
|
|
const r = node.getBoundingClientRect();
|
|
const s = this.status || {};
|
|
menu([
|
|
{ head: liveSummary(s).title },
|
|
{ label: t('Open the site in the browser'), icon: 'globe', action: () => this.open(), disabled: !s.url },
|
|
'-',
|
|
{ label: s.enabled ? t('Turn live reload off') : t('Turn live reload on'), action: () => this.toggle(!s.enabled) },
|
|
], { x: Math.max(8, r.right - 260), y: Math.max(8, r.top - 120) });
|
|
}
|
|
|
|
async toggle(enabled) {
|
|
try { this.status = await backend.invoke('web.live.set', { enabled }); } catch (e) { notify(String(e.message || e), 'error'); return; }
|
|
this.render();
|
|
notify(t('Live reload changed: restart the site (Serve the site) to apply it.'), 'info', { title: t('Live reload') });
|
|
}
|
|
}
|