xonecas.io
70160
Ce

cel-tui / files

cel-tui / packages / core / src / hit-test.ts

6.8 KB
1import type { ContainerProps } from "@cel-tui/types";
2import type { LayoutNode, Rect } from "./layout.js";
3import { clampScrollOffset } from "./scroll.js";
4
5/**
6 * Test if a point is inside a rect.
7 */
8function pointInRect(x: number, y: number, rect: Rect): boolean {
9  return (
10    x >= rect.x &&
11    x < rect.x + rect.width &&
12    y >= rect.y &&
13    y < rect.y + rect.height
14  );
15}
16
17function requiredAt<T>(
18  items: readonly T[],
19  index: number,
20  description: string,
21): T {
22  const item = items[index];
23  if (item === undefined) {
24    throw new Error(`Missing ${description} at index ${index}`);
25  }
26  return item;
27}
28
29/**
30 * Callback to resolve the current scroll offset for a scrollable container.
31 * Used to adjust hit coordinates when testing children of scrolled containers.
32 */
33type ScrollOffsetResolver = (ln: LayoutNode) => number;
34
35/** Default resolver: reads scrollOffset from props, defaults to 0. */
36function defaultScrollResolver(ln: LayoutNode): number {
37  return getProps(ln)?.scrollOffset ?? 0;
38}
39
40/**
41 * Find the path from root to the deepest node at `(x, y)`.
42 *
43 * Returns an array of {@link LayoutNode}s from root (index 0) to the
44 * deepest hit node (last index). Returns empty array if the point is
45 * outside the root.
46 *
47 * For scrollable containers, child coordinates are adjusted by the
48 * scroll offset so clicks target the visually correct child.
49 *
50 * @param root - Root of the layout tree.
51 * @param x - Column position.
52 * @param y - Row position.
53 * @param getScrollOffset - Optional resolver for scroll offsets.
54 * @returns Path from root to deepest node at the position.
55 */
56export function hitTest(
57  root: LayoutNode,
58  x: number,
59  y: number,
60  getScrollOffset?: ScrollOffsetResolver,
61): LayoutNode[] {
62  const resolver = getScrollOffset ?? defaultScrollResolver;
63  if (!pointInRect(x, y, root.rect)) return [];
64
65  const path: LayoutNode[] = [root];
66
67  // Track accumulated scroll adjustments as we descend.
68  // When a scrollable container is encountered, subsequent child rect
69  // checks use coordinates shifted by the scroll offset.
70  let adjustX = 0;
71  let adjustY = 0;
72  let current = root;
73  let found = true;
74
75  while (found) {
76    found = false;
77
78    // Check if current node is scrollable — if so, adjust coordinates
79    const props = getProps(current);
80    if (props?.overflow === "scroll" || current.node.type === "textinput") {
81      const offset = clampScrollOffset(current, resolver(current));
82      if (offset !== 0) {
83        const isVertical =
84          current.node.type === "vstack" || current.node.type === "textinput";
85        if (isVertical) {
86          adjustY += offset;
87        } else {
88          adjustX += offset;
89        }
90      }
91    }
92
93    // Test children with scroll-adjusted coordinates
94    const testX = x + adjustX;
95    const testY = y + adjustY;
96    for (let i = current.children.length - 1; i >= 0; i--) {
97      const child = requiredAt(current.children, i, "layout child");
98      if (pointInRect(testX, testY, child.rect)) {
99        path.push(child);
100        current = child;
101        found = true;
102        break;
103      }
104    }
105  }
106
107  return path;
108}
109
110// --- Handler lookups ---
111
112function getProps(ln: LayoutNode): ContainerProps | null {
113  const node = ln.node;
114  if (node.type === "text") return null;
115  return node.props;
116}
117
118/**
119 * Find the nearest ancestor with an `onClick` handler (innermost wins).
120 * Walks the path from deepest to root.
121 *
122 * @param path - Hit test path (root to deepest).
123 * @returns The handler and its layout node, or null.
124 */
125export function findClickHandler(
126  path: LayoutNode[],
127): { layoutNode: LayoutNode; handler: () => void } | null {
128  for (let i = path.length - 1; i >= 0; i--) {
129    const layoutNode = requiredAt(path, i, "hit path node");
130    const props = getProps(layoutNode);
131    if (props?.onClick) {
132      return { layoutNode, handler: props.onClick };
133    }
134  }
135  return null;
136}
137
138/**
139 * Collect scrollable ancestors in bubbling order (innermost first).
140 * Matches containers with `overflow: "scroll"` or TextInput nodes.
141 *
142 * @param path - Hit test path (root to deepest).
143 * @returns Scrollable layout nodes ordered deepest to root.
144 */
145export function collectScrollTargets(path: LayoutNode[]): LayoutNode[] {
146  const targets: LayoutNode[] = [];
147  for (let i = path.length - 1; i >= 0; i--) {
148    const layoutNode = requiredAt(path, i, "hit path node");
149    const node = layoutNode.node;
150    if (node.type === "textinput") {
151      targets.push(layoutNode);
152      continue;
153    }
154    const props = getProps(layoutNode);
155    if (props?.overflow === "scroll") targets.push(layoutNode);
156  }
157  return targets;
158}
159
160/**
161 * Find the nearest scrollable ancestor.
162 *
163 * For full scroll dispatch, prefer {@link collectScrollTargets} so container
164 * handlers can propagate by returning `false`. TextInput consumes directly.
165 *
166 * @param path - Hit test path (root to deepest).
167 * @returns The innermost scrollable layout node, or null.
168 */
169export function findScrollTarget(path: LayoutNode[]): LayoutNode | null {
170  return collectScrollTargets(path)[0] ?? null;
171}
172
173/**
174 * Collect all `onKeyPress` handlers along a path, ordered innermost-first
175 * (deepest to root) for bubbling dispatch.
176 *
177 * @param path - Path from root to current node.
178 * @returns Array of handlers ordered from deepest to root.
179 */
180export function collectKeyPressHandlers(path: LayoutNode[]): {
181  layoutNode: LayoutNode;
182  handler: NonNullable<ContainerProps["onKeyPress"]>;
183}[] {
184  const handlers: {
185    layoutNode: LayoutNode;
186    handler: NonNullable<ContainerProps["onKeyPress"]>;
187  }[] = [];
188  for (let i = path.length - 1; i >= 0; i--) {
189    const layoutNode = requiredAt(path, i, "hit path node");
190    const props = getProps(layoutNode);
191    if (props?.onKeyPress) {
192      handlers.push({ layoutNode, handler: props.onKeyPress });
193    }
194  }
195  return handlers;
196}
197
198/**
199 * Collect all focusable nodes in document order (depth-first traversal).
200 *
201 * A node is focusable if:
202 * - It's a TextInput whose `focusable` prop is not `false`, OR
203 * - It's a container with `onClick` and `focusable` is not `false`, OR
204 * - It's a container with explicit `focusable: true`
205 *
206 * @param root - Root of the layout tree.
207 * @returns Focusable nodes in document order.
208 */
209export function collectFocusable(root: LayoutNode): LayoutNode[] {
210  const result: LayoutNode[] = [];
211  collectFocusableRecursive(root, result);
212  return result;
213}
214
215function collectFocusableRecursive(ln: LayoutNode, result: LayoutNode[]): void {
216  const node = ln.node;
217
218  if (node.type === "textinput" && node.props.focusable !== false) {
219    result.push(ln);
220  } else if (node.type === "vstack" || node.type === "hstack") {
221    const isFocusable =
222      node.props.focusable === true ||
223      (node.props.onClick != null && node.props.focusable !== false);
224    if (isFocusable) {
225      result.push(ln);
226    }
227  }
228
229  for (const child of ln.children) {
230    collectFocusableRecursive(child, result);
231  }
232}