rob-revisited/ide/ui/js/hover-model.js

46 lines
2.1 KiB
JavaScript

// The data side of the hover card's life (no DOM: tested by hover-model.test.mjs): when it may close, which side of the text it sits on.
// It closes only on Escape / a click outside (the caller) or when the pointer has been away from it for LEAVE ms with nothing pending.
export const LEAVE = 350; // ms away from the card before it closes (more than 300)
/** The "may it close now" rules: hovered, a request pending (an expansion being read), a field being typed in: it stays. */
export class LeaveGuard {
constructor(onClose, { delay = LEAVE, set = (f, ms) => setTimeout(f, ms), clear = (i) => clearTimeout(i) } = {}) {
Object.assign(this, { onClose, delay, set, clear });
this.timer = null;
this.hovered = false;
this.pending = 0;
this.deferred = false; // the pointer left while a read was pending: judged again when it ends
this.typing = () => false;
}
enter() { this.hovered = true; this.cancel(); }
leave() { this.hovered = false; this.soon(); }
cancel() { this.clear(this.timer); this.timer = null; }
/** A read started (+1) / ended (-1): the card stays while one is pending, and the pointer leaving is judged again at its end. */
busy(delta) {
this.pending = Math.max(0, this.pending + delta);
if (this.pending === 0 && this.deferred && !this.hovered && this.timer === null) this.soon();
}
soon() {
this.cancel();
this.timer = this.set(() => {
this.timer = null;
if (this.pending > 0) { this.deferred = true; return; }
this.deferred = false;
if (this.hovered || this.typing()) return;
this.onClose();
}, this.delay);
}
}
/** An editor scroll closes the card only when the text really moved (Monaco also reports layout changes). */
export const scrollMoved = (e) => !!(e && (e.scrollTopChanged || e.scrollLeftChanged));
/** The side of the text: chosen when the card opens (the larger room, or below when it fits) and kept: a card that flips while it grows moves from under the pointer. */
export function pickSide(kept, need, below, above) {
if (kept) return kept;
return need <= below || below >= above ? 'below' : 'above';
}