• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Copyright (C) 2024 The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//      http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15export interface Rect {
16  readonly left: number;
17  readonly top: number;
18  readonly right: number;
19  readonly bottom: number;
20}
21
22export interface Size {
23  readonly width: number;
24  readonly height: number;
25}
26
27export interface Vector {
28  readonly x: number;
29  readonly y: number;
30}
31
32export function intersectRects(a: Rect, b: Rect): Rect {
33  return {
34    top: Math.max(a.top, b.top),
35    left: Math.max(a.left, b.left),
36    bottom: Math.min(a.bottom, b.bottom),
37    right: Math.min(a.right, b.right),
38  };
39}
40
41export function expandRect(r: Rect, amount: number): Rect {
42  return {
43    top: r.top - amount,
44    left: r.left - amount,
45    bottom: r.bottom + amount,
46    right: r.right + amount,
47  };
48}
49
50export function rebaseRect(r: Rect, x: number, y: number): Rect {
51  return {
52    left: r.left - x,
53    right: r.right - x,
54    top: r.top - y,
55    bottom: r.bottom - y,
56  };
57}
58
59export function rectSize(r: Rect): Size {
60  return {
61    width: r.right - r.left,
62    height: r.bottom - r.top,
63  };
64}
65
66/**
67 * Return true if rect a contains rect b.
68 *
69 * @param a A rect.
70 * @param b Another rect.
71 * @returns True if rect a contains rect b, false otherwise.
72 */
73export function containsRect(a: Rect, b: Rect): boolean {
74  return !(
75    b.top < a.top ||
76    b.bottom > a.bottom ||
77    b.left < a.left ||
78    b.right > a.right
79  );
80}
81
82export function translateRect(a: Rect, b: Vector): Rect {
83  return {
84    top: a.top + b.y,
85    left: a.left + b.x,
86    bottom: a.bottom + b.y,
87    right: a.right + b.x,
88  };
89}
90