]> git.proxmox.com Git - mirror_xterm.js.git/blob - src/utils/Mouse.ts
79c5d5c1160735a0f47ce37f161e3a787840b467
[mirror_xterm.js.git] / src / utils / Mouse.ts
1 /**
2 * @license MIT
3 */
4
5 import { CharMeasure } from './CharMeasure';
6
7 export function getCoordsRelativeToElement(event: MouseEvent, element: HTMLElement): [number, number] {
8 // Ignore browsers that don't support MouseEvent.pageX
9 if (event.pageX == null) {
10 return null;
11 }
12
13 let x = event.pageX;
14 let y = event.pageY;
15
16 // Converts the coordinates from being relative to the document to being
17 // relative to the terminal.
18 while (element && element !== self.document.documentElement) {
19 x -= element.offsetLeft;
20 y -= element.offsetTop;
21 element = 'offsetParent' in element ? <HTMLElement>element.offsetParent : <HTMLElement>element.parentElement;
22 }
23 return [x, y];
24 }
25
26 /**
27 * Gets coordinates within the terminal for a particular mouse event. The result
28 * is returned as an array in the form [x, y] instead of an object as it's a
29 * little faster and this function is used in some low level code.
30 * @param event The mouse event.
31 * @param rowContainer The terminal's row container.
32 * @param charMeasure The char measure object used to determine character sizes.
33 */
34 export function getCoords(event: MouseEvent, rowContainer: HTMLElement, charMeasure: CharMeasure, colCount: number, rowCount: number): [number, number] {
35 const coords = getCoordsRelativeToElement(event, rowContainer);
36
37 // Convert to cols/rows
38 coords[0] = Math.ceil(coords[0] / charMeasure.width);
39 coords[1] = Math.ceil(coords[1] / charMeasure.height);
40
41 // Ensure coordinates are within the terminal viewport.
42 coords[0] = Math.min(Math.max(coords[0], 1), colCount + 1);
43 coords[1] = Math.min(Math.max(coords[1], 1), rowCount + 1);
44
45 return coords;
46 }
47
48 /**
49 * Gets coordinates within the terminal for a particular mouse event, wrapping
50 * them to the bounds of the terminal and adding 32 to both the x and y values
51 * as expected by xterm.
52 * @param event The mouse event.
53 * @param rowContainer The terminal's row container.
54 * @param charMeasure The char measure object used to determine character sizes.
55 * @param colCount The number of columns in the terminal.
56 * @param rowCount The number of rows in the terminal.
57 */
58 export function getRawByteCoords(event: MouseEvent, rowContainer: HTMLElement, charMeasure: CharMeasure, colCount: number, rowCount: number): { x: number, y: number } {
59 const coords = getCoords(event, rowContainer, charMeasure, colCount, rowCount);
60 let x = coords[0];
61 let y = coords[1];
62
63 // xterm sends raw bytes and starts at 32 (SP) for each.
64 x += 32;
65 y += 32;
66
67 return { x, y };
68 }