]> git.proxmox.com Git - mirror_xterm.js.git/blame - src/utils/CharMeasure.ts
Merge pull request #556 from Tyriar/555_fix_mouse_coords
[mirror_xterm.js.git] / src / utils / CharMeasure.ts
CommitLineData
4f18d842
DI
1/**
2 * @module xterm/utils/CharMeasure
3 * @license MIT
4 */
5
6import { EventEmitter } from '../EventEmitter.js';
7
8/**
9 * Utility class that measures the size of a character.
10 */
11export class CharMeasure extends EventEmitter {
12 private _parentElement: HTMLElement;
13 private _measureElement: HTMLElement;
14 private _width: number;
15 private _height: number;
16
17 constructor(parentElement: HTMLElement) {
18 super();
19 this._parentElement = parentElement;
20 }
21
22 public get width(): number {
23 return this._width;
24 }
25
26 public get height(): number {
27 return this._height;
28 }
29
30 public measure(): void {
4f18d842
DI
31 if (!this._measureElement) {
32 this._measureElement = document.createElement('span');
33 this._measureElement.style.position = 'absolute';
34 this._measureElement.style.top = '0';
35 this._measureElement.style.left = '-9999em';
36 this._measureElement.textContent = 'W';
d06c920a 37 this._measureElement.setAttribute('aria-hidden', 'true');
d9682bd6
DI
38 this._parentElement.appendChild(this._measureElement);
39 // Perform _doMeasure async if the element was just attached as sometimes
40 // getBoundingClientRect does not return accurate values without this.
41 setTimeout(() => this._doMeasure(), 0);
42 } else {
43 this._doMeasure();
4f18d842 44 }
d9682bd6 45 }
4f18d842 46
d9682bd6 47 private _doMeasure(): void {
4f18d842 48 const geometry = this._measureElement.getBoundingClientRect();
9626b1e3
DI
49 // The element is likely currently display:none, we should retain the
50 // previous value.
51 if (geometry.width === 0 || geometry.height === 0) {
52 return;
53 }
d9682bd6
DI
54 if (this._width !== geometry.width || this._height !== geometry.height) {
55 this._width = geometry.width;
56 this._height = geometry.height;
4f18d842
DI
57 this.emit('charsizechanged');
58 }
59 }
60}