344 lines
16 KiB
JavaScript
344 lines
16 KiB
JavaScript
// Font zoom per panel: Ctrl + mouse wheel (a touchpad pinch reaches the page as Ctrl + wheel too), Ctrl+= / Ctrl+- / Ctrl+0 with the
|
|
// focus in the panel. Only over a marked panel (`data-zoom="<id>"`) is the page's own zoom stopped.
|
|
// - 'px' panels (the code editor, the Terminal): a font size, 1 px steps, 8..40 px; the panel applies it (Monaco / xterm option).
|
|
// - 'pct' panels (Claude, Debug, Run, Git, Search...): a scale of the whole panel (CSS `zoom` on its content), 5 % steps, 50..300 %.
|
|
// - 'ui' (the id `ui`): Ctrl + Shift + wheel anywhere scales the WHOLE IDE, 10 % steps, 50..250 %: the desktop WebView's own zoom
|
|
// (`zoom.native`, the command window.zoom: the page's coordinates stay right, Monaco's clicks too); in a browser, or with an older
|
|
// runtime library, CSS `zoom` on <html> (standard CSS zoom there keeps them right too).
|
|
// A wheel turn is added up (a notch = 1 step, a touchpad's many small deltas make 1 step each ~60 px) and the panel is redrawn at most
|
|
// once per frame: Monaco / xterm / a big panel are not re-laid out for every wheel event.
|
|
// The value is remembered per panel in prefs (`zoom:<id>`) and by the window layout record (layout.js, `zoom` map).
|
|
// The pure part (clamp / step / format / clean) has no DOM: ide/ui/js/zoom.test.mjs.
|
|
|
|
export const KINDS = {
|
|
px: { min: 8, max: 40, step: 1, unit: 'px' },
|
|
pct: { min: 50, max: 300, step: 5, unit: '%' },
|
|
ui: { min: 50, max: 250, step: 10, unit: '%' },
|
|
};
|
|
|
|
/** The wheel distance (CSS px) that makes one step; a mouse notch (100 px in Chrome / WebKit, 3 lines elsewhere) is at least one. */
|
|
export const WHEEL_STEP = 60;
|
|
|
|
/** A value brought into the allowed range (a number or null when it is not one). */
|
|
export function clamp(value, kind) {
|
|
const k = KINDS[kind];
|
|
if (!k || typeof value !== 'number' || !Number.isFinite(value)) return null;
|
|
return Math.round(Math.min(k.max, Math.max(k.min, value)) * 100) / 100;
|
|
}
|
|
|
|
/** The next value: dir > 0 bigger, < 0 smaller. A pct value lands on the 5 % grid, a px value moves by 1 (13.5 -> 14.5). */
|
|
export function stepValue(value, dir, kind) {
|
|
const k = KINDS[kind];
|
|
const base = clamp(value, kind) ?? k.min;
|
|
const next = base + (dir > 0 ? k.step : -k.step);
|
|
return clamp(kind === 'px' ? next : Math.round(next / k.step) * k.step, kind);
|
|
}
|
|
|
|
/** '14 px' / '120 %' */
|
|
export function format(value, kind) {
|
|
const n = Math.round(value * 10) / 10;
|
|
return `${n} ${KINDS[kind].unit}`;
|
|
}
|
|
|
|
/** A zoom map read from storage: {id: number} with every value in range (anything else dropped). `kinds` = {id: 'px'|'pct'}; unknown ids kept as pct. */
|
|
export function cleanMap(raw, kinds = {}) {
|
|
const out = {};
|
|
if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return out;
|
|
for (const [id, v] of Object.entries(raw).slice(0, 60)) {
|
|
const c = clamp(v, kinds[id] || 'pct');
|
|
if (c !== null && /^[\w.-]{1,64}$/.test(id)) out[id] = c;
|
|
}
|
|
return out;
|
|
}
|
|
|
|
/** The wheel distance in CSS px, up = positive (Shift turns the wheel into deltaX in most browsers: that one is read too). */
|
|
export function wheelDelta(e) {
|
|
const d = e.deltaY || (e.shiftKey ? e.deltaX : 0) || 0;
|
|
const unit = e.deltaMode === 1 ? 33 : e.deltaMode === 2 ? 400 : 1;
|
|
return d ? -d * unit : 0;
|
|
}
|
|
|
|
/** What the wheel does: ctrl + wheel up (deltaY < 0) = +1. */
|
|
export const wheelDir = (e) => Math.sign(wheelDelta(e));
|
|
|
|
/**
|
|
* The wheel turned into steps. A mouse notch (a big delta, >= 50 px) is one step; a touchpad's / pinch's small deltas are added up,
|
|
* one step each WHEEL_STEP px, the first event of a turn (or one going the other way) stepping at once so a small move is never lost.
|
|
* Returns the steps of this event (-3..3).
|
|
*/
|
|
export function wheelSteps(acc, delta, now) {
|
|
if (!delta) return 0;
|
|
const turn = now - acc.at > 250 || Math.sign(delta) !== Math.sign(acc.sum || delta);
|
|
acc.at = now;
|
|
if (Math.abs(delta) >= 50) { acc.sum = 0; acc.fresh = false; return Math.sign(delta) * Math.min(3, Math.max(1, Math.round(Math.abs(delta) / 100))); }
|
|
if (turn) { acc.sum = 0; acc.fresh = true; }
|
|
acc.sum += delta;
|
|
let n = Math.trunc(acc.sum / WHEEL_STEP);
|
|
if (!n && acc.fresh) n = Math.sign(delta);
|
|
if (n) { acc.sum = acc.fresh && Math.abs(acc.sum) < WHEEL_STEP ? 0 : acc.sum - n * WHEEL_STEP; acc.fresh = false; }
|
|
return Math.max(-3, Math.min(3, n));
|
|
}
|
|
|
|
class Zoom {
|
|
constructor() {
|
|
this.panels = new Map(); // id -> {kind, def(), apply(value, containers), label}
|
|
this.store = null; // prefs-like {get, set}
|
|
this.t = (s) => s;
|
|
this.badge = null;
|
|
this.badgeTimer = 0;
|
|
this.last = 'editor'; // the panel used last (for the commands without a focus)
|
|
this.installed = false;
|
|
this.listeners = new Set();
|
|
this.values = new Map(); // id -> value (null = default): what get() reads, ahead of the store
|
|
this.dirty = new Set(); // ids to apply at the next frame
|
|
this.unsaved = new Map(); // id -> value, written to the store (and told to the listeners) a moment after the wheel stops
|
|
this.frame = 0;
|
|
this.saveTimer = 0;
|
|
this.acc = { sum: 0, at: 0, fresh: true, id: null };
|
|
this.native = null; // (scale) => Promise: the WebView's own zoom (app.js wires it on the desktop); null / rejected = CSS zoom
|
|
this.uiMode = 'css'; // how the IDE zoom is applied now: 'native' | 'css'
|
|
this.define('ui', { kind: 'ui', label: 'IDE', def: () => 100, apply: (v) => this.applyUi(v) });
|
|
}
|
|
|
|
/** Wires the page's prefs and t(); starts listening (once). */
|
|
use(store, t) {
|
|
this.store = store;
|
|
if (t) this.t = t;
|
|
if (typeof document !== 'undefined' && !this.installed) { this.installed = true; this.install(); }
|
|
}
|
|
|
|
/** A panel that can be zoomed. `def` = its value with no zoom, `apply(value)` puts it on screen (default for pct: CSS zoom on the content). */
|
|
define(id, { kind = 'pct', def = null, apply = null, label = id } = {}) {
|
|
const panel = { kind, label, def: def || (() => (kind === 'px' ? 13 : 100)), apply: apply || ((v) => this.applyCss(id, v)) };
|
|
this.panels.set(id, panel);
|
|
return panel;
|
|
}
|
|
|
|
/** The IDE zoom: the WebView's own when there is one, else CSS zoom on <html>; then the window's size changed for everyone. */
|
|
applyUi(value) {
|
|
if (typeof document === 'undefined') return;
|
|
const css = (v) => {
|
|
document.documentElement.style.zoom = v === 100 ? '' : String(v / 100);
|
|
dispatchEvent(new Event('resize'));
|
|
};
|
|
if (!this.native) { this.uiMode = 'css'; css(value); return; }
|
|
const seq = (this.uiSeq = (this.uiSeq || 0) + 1);
|
|
Promise.resolve().then(() => this.native(value / 100)).then(() => {
|
|
if (seq !== this.uiSeq) return;
|
|
this.uiMode = 'native';
|
|
if (document.documentElement.style.zoom) css(100);
|
|
}, (e) => {
|
|
console.warn('zoom: no native zoom, CSS zoom instead', e?.message || e);
|
|
this.native = null;
|
|
if (seq === this.uiSeq) { this.uiMode = 'css'; css(this.get('ui')); }
|
|
});
|
|
}
|
|
|
|
/** The desktop's WebView zoom (a function (scale) => Promise); the current IDE zoom is put through it at once. */
|
|
useNative(fn) {
|
|
this.native = fn;
|
|
if (!this.isDefault('ui')) this.applyNow('ui');
|
|
}
|
|
|
|
kindOf(id) { return this.panels.get(id)?.kind || 'pct'; }
|
|
kinds() { return Object.fromEntries([...this.panels].map(([id, p]) => [id, p.kind])); }
|
|
|
|
/** The value now (pref, else the panel's default). */
|
|
get(id) {
|
|
const p = this.panels.get(id);
|
|
const raw = this.values.has(id) ? this.values.get(id) : (this.store ? this.store.get('zoom:' + id, null) : null);
|
|
return clamp(raw, p?.kind || 'pct') ?? (p ? p.def() : 100);
|
|
}
|
|
|
|
isDefault(id) { return (this.values.has(id) ? this.values.get(id) : this.store?.get('zoom:' + id, null)) == null; }
|
|
|
|
/**
|
|
* Sets (and applies, remembers) a value; `null` = back to the default. `live` (the wheel, the keys): drawn at the next frame and
|
|
* saved a moment later, so a fast wheel costs one layout per frame; otherwise applied and saved now.
|
|
*/
|
|
set(id, value, { show = false, quiet = false, live = false } = {}) {
|
|
const p = this.panels.get(id);
|
|
if (!p) return null;
|
|
const v = value === null ? null : clamp(value, p.kind);
|
|
if (value !== null && v === null) return null;
|
|
const now = v ?? p.def();
|
|
if (show) this.show(id, now);
|
|
if (now === this.get(id) && (v === null) === this.isDefault(id)) return now;
|
|
this.values.set(id, v);
|
|
if (live && typeof requestAnimationFrame === 'function') {
|
|
this.dirty.add(id);
|
|
// the next frame, or 50 ms when the WebView gives no frames (hidden, busy): never later
|
|
if (!this.frame) this.frame = [requestAnimationFrame(() => this.flushFrame()), setTimeout(() => this.flushFrame(), 50)];
|
|
this.unsaved.set(id, quiet);
|
|
clearTimeout(this.saveTimer);
|
|
this.saveTimer = setTimeout(() => this.flushSave(), 400);
|
|
} else {
|
|
this.dirty.delete(id);
|
|
this.unsaved.delete(id);
|
|
this.applyNow(id);
|
|
this.store?.set('zoom:' + id, v);
|
|
if (!quiet) for (const fn of this.listeners) fn(id, v);
|
|
}
|
|
return now;
|
|
}
|
|
|
|
/** Draws the panels changed since the last frame. */
|
|
flushFrame() {
|
|
if (this.frame) { if (typeof cancelAnimationFrame === 'function') cancelAnimationFrame(this.frame[0]); clearTimeout(this.frame[1]); }
|
|
this.frame = 0;
|
|
const ids = [...this.dirty];
|
|
this.dirty.clear();
|
|
for (const id of ids) this.applyNow(id);
|
|
}
|
|
|
|
/** Writes the values changed by the wheel / keys (prefs, then the listeners: the layout record). */
|
|
flushSave() {
|
|
clearTimeout(this.saveTimer);
|
|
const items = [...this.unsaved];
|
|
this.unsaved.clear();
|
|
for (const [id, quiet] of items) {
|
|
const v = this.values.get(id) ?? null;
|
|
this.store?.set('zoom:' + id, v);
|
|
if (!quiet) for (const fn of this.listeners) fn(id, v);
|
|
}
|
|
}
|
|
|
|
/** Re-applies the value of a panel (after its content was built / rebuilt) keeping the scroll places of its lists. */
|
|
applyNow(id) {
|
|
const p = this.panels.get(id);
|
|
if (!p) return;
|
|
if (id === 'ui') { try { p.apply(this.get(id), []); } catch (e) { console.warn('zoom', id, e); } return; }
|
|
const containers = typeof document === 'undefined' ? [] : [...document.querySelectorAll(`[data-zoom="${id}"]`)];
|
|
const keep = p.kind === 'pct' ? containers.flatMap((c) => keepScroll(c)) : [];
|
|
try { p.apply(this.get(id), containers); } catch (e) { console.warn('zoom', id, e); }
|
|
for (const fn of keep) fn();
|
|
}
|
|
|
|
/** The pct default apply: CSS zoom on the content of each marked container (a scale of 1 = nothing). */
|
|
applyCss(id, value) {
|
|
for (const c of document.querySelectorAll(`[data-zoom="${id}"]`)) {
|
|
const content = c.firstElementChild;
|
|
if (content) content.style.zoom = value === 100 ? '' : String(value / 100);
|
|
}
|
|
}
|
|
|
|
step(id, dir, opts = {}) {
|
|
const p = this.panels.get(id);
|
|
if (!p) return null;
|
|
let v = this.get(id);
|
|
for (let i = 0; i < Math.abs(dir); i++) v = stepValue(v, Math.sign(dir), p.kind);
|
|
return this.set(id, v, { show: true, ...opts });
|
|
}
|
|
|
|
reset(id) { return this.set(id, null, { show: true }); }
|
|
|
|
resetAll() {
|
|
this.flushSave();
|
|
for (const id of this.panels.keys()) if (!this.isDefault(id)) this.set(id, null, { quiet: true });
|
|
for (const fn of this.listeners) fn(null, null);
|
|
this.show(this.last, this.get(this.last));
|
|
}
|
|
|
|
/** The non-default values, for the layout record (the IDE zoom is not in it: it is the same for every project). */
|
|
snapshot() {
|
|
const out = {};
|
|
for (const id of this.panels.keys()) if (id !== 'ui' && !this.isDefault(id)) out[id] = this.get(id);
|
|
return out;
|
|
}
|
|
|
|
/** Puts back the values of a layout record (only the ids it holds; an id not in it is left alone). */
|
|
restore(map) {
|
|
for (const [id, v] of Object.entries(cleanMap(map, this.kinds()))) if (id !== 'ui' && this.panels.has(id)) this.set(id, v, { quiet: true });
|
|
}
|
|
|
|
/** The panel under an element (its closest `data-zoom`). */
|
|
idOf(node) {
|
|
if (node && node.nodeType === 3) node = node.parentElement;
|
|
const c = node?.closest?.('[data-zoom]');
|
|
const id = c?.dataset.zoom;
|
|
return id && this.panels.has(id) ? id : null;
|
|
}
|
|
|
|
/** The panel of the focus, else of the last pointer / wheel use, else the editor. */
|
|
focusedId() {
|
|
return this.idOf(document.activeElement) || (this.panels.has(this.last) ? this.last : null) || 'editor';
|
|
}
|
|
|
|
onChange(fn) { this.listeners.add(fn); return () => this.listeners.delete(fn); }
|
|
|
|
install() {
|
|
// Ctrl + wheel over a panel: its font; Ctrl + Shift + wheel anywhere: the whole IDE. The page's own zoom is stopped there only.
|
|
document.addEventListener('wheel', (e) => {
|
|
if (!e.ctrlKey || e.altKey) return;
|
|
const id = e.shiftKey ? 'ui' : this.idOf(e.target);
|
|
if (!id) return;
|
|
e.preventDefault();
|
|
e.stopImmediatePropagation();
|
|
if (id !== 'ui') this.last = id;
|
|
this.badgeAt = [e.clientX, e.clientY];
|
|
if (this.acc.id !== id) { this.acc = { sum: 0, at: 0, fresh: true, id }; }
|
|
const n = wheelSteps(this.acc, wheelDelta(e), performance.now());
|
|
if (n) this.step(id, n, { live: true }); else this.show(id, this.get(id));
|
|
}, { capture: true, passive: false });
|
|
document.addEventListener('pointerdown', (e) => { const id = this.idOf(e.target); if (id) this.last = id; }, true);
|
|
// Ctrl+= / Ctrl+- / Ctrl+0 with the focus in a panel (Shift is how = makes +)
|
|
document.addEventListener('keydown', (e) => {
|
|
if (!(e.ctrlKey || e.metaKey) || e.altKey) return;
|
|
const id = this.idOf(e.target);
|
|
if (!id) return;
|
|
const k = e.key;
|
|
const dir = k === '=' || k === '+' ? 1 : k === '-' || k === '_' ? -1 : 0;
|
|
if (!dir && k !== '0') return;
|
|
e.preventDefault();
|
|
e.stopImmediatePropagation();
|
|
this.last = id;
|
|
this.badgeAt = null;
|
|
if (dir) this.step(id, dir, { live: true }); else this.reset(id);
|
|
}, true);
|
|
addEventListener('pagehide', () => this.flushSave());
|
|
addEventListener('beforeunload', () => this.flushSave());
|
|
}
|
|
|
|
/** The small badge near the pointer ('14 px' / '120 %') for a second; a double click on it resets that panel. */
|
|
show(id, value) {
|
|
if (typeof document === 'undefined') return;
|
|
const p = this.panels.get(id);
|
|
if (!p) return;
|
|
if (!this.badge) {
|
|
this.badge = document.createElement('div');
|
|
this.badge.className = 'zoom-badge';
|
|
this.badge.addEventListener('dblclick', () => { if (this.badge.dataset.id) this.reset(this.badge.dataset.id); });
|
|
document.body.append(this.badge);
|
|
}
|
|
const b = this.badge;
|
|
b.dataset.id = id;
|
|
b.textContent = (id === 'ui' ? 'IDE ' : '') + format(value, p.kind);
|
|
b.title = this.t('Double-click to reset');
|
|
// the badge lives under <html>, which the IDE zoom scales: pointer pixels are divided by it
|
|
const s = parseFloat(document.documentElement.style.zoom) || 1;
|
|
const [x, y] = this.badgeAt || [innerWidth / 2, innerHeight / 2];
|
|
b.style.left = Math.max(4, Math.min(innerWidth - 120, x + 12)) / s + 'px';
|
|
b.style.top = Math.max(4, Math.min(innerHeight - 40, y + 12)) / s + 'px';
|
|
b.classList.add('on');
|
|
clearTimeout(this.badgeTimer);
|
|
this.badgeTimer = setTimeout(() => b.classList.remove('on'), 1200);
|
|
}
|
|
}
|
|
|
|
/** Remembers the scroll place of the lists in a container (by ratio, or at the end when they were at the end): call the returned functions after a change. */
|
|
function keepScroll(container) {
|
|
const out = [];
|
|
const nodes = [container, ...container.querySelectorAll('.claude-log, .console, .game-log, .claude-livelog')];
|
|
for (const n of nodes) {
|
|
if (!n.clientHeight || n.scrollHeight <= n.clientHeight) continue;
|
|
const atEnd = n.scrollHeight - n.scrollTop - n.clientHeight < 80;
|
|
const ratio = n.scrollTop / n.scrollHeight;
|
|
out.push(() => {
|
|
n.scrollTop = atEnd ? n.scrollHeight : Math.round(ratio * n.scrollHeight);
|
|
requestAnimationFrame(() => { if (atEnd) n.scrollTop = n.scrollHeight; });
|
|
});
|
|
}
|
|
return out;
|
|
}
|
|
|
|
export const zoom = new Zoom();
|