xterm
[VSoRC/.git] / node_modules / xterm / src / browser / input / Mouse.ts
1 /**
2  * Copyright (c) 2017 The xterm.js authors. All rights reserved.
3  * @license MIT
4  */
5
6 export function getCoordsRelativeToElement(event: {clientX: number, clientY: number}, element: HTMLElement): [number, number] {
7   const rect = element.getBoundingClientRect();
8   return [event.clientX - rect.left, event.clientY - rect.top];
9 }
10
11 /**
12  * Gets coordinates within the terminal for a particular mouse event. The result
13  * is returned as an array in the form [x, y] instead of an object as it's a
14  * little faster and this function is used in some low level code.
15  * @param event The mouse event.
16  * @param element The terminal's container element.
17  * @param colCount The number of columns in the terminal.
18  * @param rowCount The number of rows n the terminal.
19  * @param isSelection Whether the request is for the selection or not. This will
20  * apply an offset to the x value such that the left half of the cell will
21  * select that cell and the right half will select the next cell.
22  */
23 export function getCoords(event: {clientX: number, clientY: number}, element: HTMLElement, colCount: number, rowCount: number, hasValidCharSize: boolean, actualCellWidth: number, actualCellHeight: number, isSelection?: boolean): [number, number] | undefined {
24   // Coordinates cannot be measured if there are no valid
25   if (!hasValidCharSize) {
26     return undefined;
27   }
28
29   const coords = getCoordsRelativeToElement(event, element);
30   if (!coords) {
31     return undefined;
32   }
33
34   coords[0] = Math.ceil((coords[0] + (isSelection ? actualCellWidth / 2 : 0)) / actualCellWidth);
35   coords[1] = Math.ceil(coords[1] / actualCellHeight);
36
37   // Ensure coordinates are within the terminal viewport. Note that selections
38   // need an addition point of precision to cover the end point (as characters
39   // cover half of one char and half of the next).
40   coords[0] = Math.min(Math.max(coords[0], 1), colCount + (isSelection ? 1 : 0));
41   coords[1] = Math.min(Math.max(coords[1], 1), rowCount);
42
43   return coords;
44 }
45
46 /**
47  * Gets coordinates within the terminal for a particular mouse event, wrapping
48  * them to the bounds of the terminal and adding 32 to both the x and y values
49  * as expected by xterm.
50  */
51 export function getRawByteCoords(coords: [number, number] | undefined): { x: number, y: number } | undefined {
52   if (!coords) {
53     return undefined;
54   }
55
56   // xterm sends raw bytes and starts at 32 (SP) for each.
57   return { x: coords[0] + 32, y: coords[1] + 32 };
58 }