mirror of
https://github.com/l0ng-ai/openidea.git
synced 2026-11-24 08:03:19 +00:00
fix(ui): scroll text fields while drag-selecting past their edges (#5429)
Drag-selecting in a long Find in Files query (or any text field) and moving the pointer past the field's left or right edge didn't scroll the text, so you couldn't select past what's visible. IntelliJ IDEA does scroll. WebKitGTK extends the selection in this case but never scrolls the field to follow it. Arrow keys do scroll. Now, while a drag that started in the field is past one of its edges, the field moves the selection end and the scroll position itself, faster the further out the pointer is. Once the pointer is back inside, WebKit's own selection takes over again. Both `Input` and `SearchField` get this. Co-authored-by: bertyhell <1710840+bertyhell@users.noreply.github.com>
This commit is contained in:
co-authored by
bertyhell
parent
507258daec
commit
d96060f08b
+18
-2
@@ -5,6 +5,7 @@ import {
|
||||
type InputHTMLAttributes,
|
||||
type FocusEvent,
|
||||
type KeyboardEvent,
|
||||
type MouseEvent,
|
||||
type ReactNode,
|
||||
type Ref,
|
||||
type TextareaHTMLAttributes,
|
||||
@@ -12,6 +13,7 @@ import {
|
||||
import clsx from "clsx";
|
||||
import { Icon, type IconName } from "./icons";
|
||||
import { IconButton } from "./Button";
|
||||
import { startDragAutoscroll } from "./dragAutoscroll";
|
||||
import styles from "./Input.module.css";
|
||||
import { setContext } from "@/platform/context";
|
||||
import { useGivenTx } from "@/platform/i18n";
|
||||
@@ -37,6 +39,7 @@ export const Input = forwardRef<HTMLInputElement, InputProps>(function Input(
|
||||
autoComplete = "off",
|
||||
placeholder,
|
||||
onFocus,
|
||||
onMouseDown,
|
||||
"aria-label": ariaLabel,
|
||||
...rest
|
||||
},
|
||||
@@ -62,6 +65,10 @@ export const Input = forwardRef<HTMLInputElement, InputProps>(function Input(
|
||||
}
|
||||
onFocus?.(e);
|
||||
}}
|
||||
onMouseDown={(e) => {
|
||||
onMouseDown?.(e);
|
||||
startDragAutoscroll(e);
|
||||
}}
|
||||
className={clsx(styles.input, variant === "bare" ? styles.bare : styles.framed, mono && styles.mono, className)}
|
||||
{...rest}
|
||||
/>
|
||||
@@ -163,7 +170,7 @@ export const SearchField = forwardRef<HTMLInputElement, SearchFieldProps>(functi
|
||||
commands.current.newLine = multiline ? insertNewLine : undefined;
|
||||
// oxlint-disable-next-line react/refs
|
||||
commands.current.history = onHistory;
|
||||
const { onKeyDown, onFocus, onBlur, ...fieldProps } = rest;
|
||||
const { onKeyDown, onFocus, onBlur, onMouseDown, ...fieldProps } = rest;
|
||||
const keyDown = (e: KeyboardEvent<HTMLInputElement>) => {
|
||||
if (multiline && isNewLineKey(e)) {
|
||||
e.preventDefault();
|
||||
@@ -186,7 +193,16 @@ export const SearchField = forwardRef<HTMLInputElement, SearchFieldProps>(functi
|
||||
}
|
||||
onBlur?.(e);
|
||||
};
|
||||
const handlers = { onKeyDown: keyDown, onFocus: focus, onBlur: blur };
|
||||
const mouseDown = (e: MouseEvent<HTMLInputElement>) => {
|
||||
onMouseDown?.(e);
|
||||
startDragAutoscroll(e);
|
||||
};
|
||||
const handlers = {
|
||||
onKeyDown: keyDown,
|
||||
onFocus: focus,
|
||||
onBlur: blur,
|
||||
onMouseDown: mouseDown,
|
||||
};
|
||||
// Removing a focused field fires no blur.
|
||||
useEffect(() => {
|
||||
const own = commands.current;
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
import { cleanup, fireEvent, render } from "@testing-library/react";
|
||||
import { afterEach, beforeEach, expect, it, vi } from "vitest";
|
||||
import { Input, SearchField } from "./Input";
|
||||
|
||||
const distancePerCharacter = 20;
|
||||
const fieldWidth = 100;
|
||||
const value = "字".repeat(30);
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
const canvasContext = {
|
||||
measureText: (text: string) => ({ width: text.length * distancePerCharacter }),
|
||||
} as CanvasRenderingContext2D;
|
||||
vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue(canvasContext);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
fireEvent.mouseUp(window);
|
||||
cleanup();
|
||||
vi.useRealTimers();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
function setFieldGeometry(field: HTMLInputElement | HTMLTextAreaElement) {
|
||||
Object.defineProperties(field, {
|
||||
clientWidth: { value: fieldWidth },
|
||||
scrollWidth: { value: value.length * distancePerCharacter },
|
||||
});
|
||||
vi.spyOn(field, "getBoundingClientRect").mockReturnValue(new DOMRect(0, 0, fieldWidth, 20));
|
||||
}
|
||||
|
||||
it.each([
|
||||
{ edge: "left", pointerX: -1, endpoint: "selectionStart" },
|
||||
{ edge: "right", pointerX: fieldWidth + 1, endpoint: "selectionEnd" },
|
||||
] as const)("keeps scrolling past wide characters at the $edge edge", ({ edge, pointerX, endpoint }) => {
|
||||
const view = render(<SearchField value={value} onChange={() => {}} multiline />);
|
||||
const field = view.getByRole("textbox") as HTMLTextAreaElement;
|
||||
setFieldGeometry(field);
|
||||
field.focus();
|
||||
field.scrollLeft = 200;
|
||||
field.setSelectionRange(12, 12);
|
||||
fireEvent.mouseDown(field, { button: 0, clientX: 42, clientY: 10 });
|
||||
fireEvent.mouseMove(window, { buttons: 1, clientX: pointerX, clientY: 10 });
|
||||
for (let i = 0; i < 25; i++) vi.advanceTimersToNextFrame();
|
||||
|
||||
if (edge === "left") {
|
||||
expect(field.scrollLeft).toBeLessThan(200);
|
||||
expect(field[endpoint]).toBeLessThan(10);
|
||||
expect(field.selectionEnd).toBe(12);
|
||||
} else {
|
||||
expect(field.scrollLeft).toBeGreaterThan(200);
|
||||
expect(field[endpoint]).toBeGreaterThan(15);
|
||||
expect(field.selectionStart).toBe(12);
|
||||
}
|
||||
fireEvent.mouseUp(window);
|
||||
const offset = field.scrollLeft;
|
||||
vi.advanceTimersToNextFrame();
|
||||
expect(field.scrollLeft).toBe(offset);
|
||||
});
|
||||
|
||||
it.each(["number", "date", "password"])("leaves selection to the browser for %s inputs", (type) => {
|
||||
const { container } = render(<Input type={type} />);
|
||||
const field = container.querySelector("input")!;
|
||||
setFieldGeometry(field);
|
||||
field.focus();
|
||||
const selection = vi.spyOn(field, "setSelectionRange").mockImplementation(() => {});
|
||||
fireEvent.mouseDown(field, { button: 0, clientX: 42, clientY: 10 });
|
||||
expect(fireEvent.mouseMove(window, { buttons: 1, clientX: 120, clientY: 10 })).toBe(true);
|
||||
expect(selection).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("respects a caller that prevents the start of a drag", () => {
|
||||
const view = render(<Input defaultValue={value} onMouseDown={(e) => e.preventDefault()} />);
|
||||
const field = view.getByRole("textbox") as HTMLInputElement;
|
||||
setFieldGeometry(field);
|
||||
field.focus();
|
||||
fireEvent.mouseDown(field, { button: 0, clientX: 42, clientY: 10 });
|
||||
expect(fireEvent.mouseMove(window, { buttons: 1, clientX: 120, clientY: 10 })).toBe(true);
|
||||
expect(field.scrollLeft).toBe(0);
|
||||
});
|
||||
@@ -0,0 +1,126 @@
|
||||
import type { MouseEvent as ReactMouseEvent } from "react";
|
||||
|
||||
type TextField = HTMLInputElement | HTMLTextAreaElement;
|
||||
|
||||
let canvas: HTMLCanvasElement | null = null;
|
||||
|
||||
function textWidth(field: TextField): ((text: string) => number) | null {
|
||||
canvas ??= document.createElement("canvas");
|
||||
const ctx = canvas.getContext("2d");
|
||||
if (!ctx) return null;
|
||||
const s = getComputedStyle(field);
|
||||
ctx.font = `${s.fontStyle} ${s.fontWeight} ${s.fontSize} ${s.fontFamily}`;
|
||||
return (text) => ctx.measureText(text).width;
|
||||
}
|
||||
|
||||
/** Column of `line` whose left edge is nearest to `x` (px from the line start). */
|
||||
function columnAt(line: string, x: number, width: (text: string) => number): number {
|
||||
let lo = 0;
|
||||
let hi = line.length;
|
||||
while (lo < hi) {
|
||||
const mid = (lo + hi) >> 1;
|
||||
if (width(line.slice(0, mid + 1)) < x) lo = mid + 1;
|
||||
else hi = mid;
|
||||
}
|
||||
if (lo < line.length && width(line.slice(0, lo + 1)) - x < x - width(line.slice(0, lo))) lo++;
|
||||
return lo;
|
||||
}
|
||||
|
||||
/**
|
||||
* WebKitGTK extends a text field's selection while the mouse is dragged past
|
||||
* its left or right edge, but never scrolls the text along. While the pointer
|
||||
* is outside, move the selection focus and the scroll position ourselves, faster
|
||||
* the further out the pointer is, like IDEA's text fields.
|
||||
*/
|
||||
export function startDragAutoscroll(e: ReactMouseEvent<TextField>) {
|
||||
const field = e.currentTarget;
|
||||
if (e.defaultPrevented || e.button !== 0 || e.detail > 1 || field.selectionStart === null) return;
|
||||
// The canvas measures the real value, while the browser draws masking characters.
|
||||
if (field instanceof HTMLInputElement && field.type === "password") return;
|
||||
if (field.scrollWidth <= field.clientWidth || getComputedStyle(field).direction === "rtl") return;
|
||||
const width = textWidth(field);
|
||||
if (!width) return;
|
||||
let pointerX = e.clientX;
|
||||
let pointerY = e.clientY;
|
||||
let frame = 0;
|
||||
let anchor: number | null = null;
|
||||
let focus = 0;
|
||||
|
||||
const edges = () => {
|
||||
const s = getComputedStyle(field);
|
||||
const rect = field.getBoundingClientRect();
|
||||
const left = rect.left + field.clientLeft;
|
||||
const start = left + parseFloat(s.paddingLeft);
|
||||
return {
|
||||
start,
|
||||
end: left + field.clientWidth - parseFloat(s.paddingRight),
|
||||
top: rect.top,
|
||||
bottom: rect.bottom,
|
||||
};
|
||||
};
|
||||
const overshoot = () => {
|
||||
const { start, end, top, bottom } = edges();
|
||||
if (field instanceof HTMLTextAreaElement && (pointerY < top || pointerY > bottom)) return 0;
|
||||
return pointerX < start ? pointerX - start : pointerX > end ? pointerX - end : 0;
|
||||
};
|
||||
|
||||
const tick = () => {
|
||||
frame = 0;
|
||||
if (!field.isConnected || field.selectionStart === null) return stop();
|
||||
const over = overshoot();
|
||||
if (!over) {
|
||||
anchor = null;
|
||||
return;
|
||||
}
|
||||
if (anchor === null) {
|
||||
const backward = field.selectionDirection === "backward";
|
||||
anchor = (backward ? field.selectionEnd : field.selectionStart) ?? 0;
|
||||
focus = (backward ? field.selectionStart : field.selectionEnd) ?? 0;
|
||||
}
|
||||
const value = field.value;
|
||||
const lineStart = focus > 0 ? value.lastIndexOf("\n", focus - 1) + 1 : 0;
|
||||
const newline = value.indexOf("\n", focus);
|
||||
const line = value.slice(lineStart, newline < 0 ? value.length : newline);
|
||||
const { start, end } = edges();
|
||||
const visible = end - start;
|
||||
const step = Math.sign(over) * Math.min(Math.max(Math.abs(over) / 2, 2), 40);
|
||||
// Scroll by pixels even when the next caret position is more than one step away.
|
||||
const previous = field.scrollLeft;
|
||||
field.scrollLeft = previous + step;
|
||||
const scrolled = field.scrollLeft;
|
||||
focus = lineStart + columnAt(line, scrolled + (over < 0 ? 0 : visible), width);
|
||||
field.setSelectionRange(Math.min(anchor, focus), Math.max(anchor, focus), focus < anchor ? "backward" : "forward");
|
||||
field.scrollLeft = scrolled;
|
||||
if (scrolled !== previous) frame = requestAnimationFrame(tick);
|
||||
};
|
||||
|
||||
const move = (ev: MouseEvent) => {
|
||||
if (!(ev.buttons & 1)) return stop();
|
||||
if (!field.isConnected) return stop();
|
||||
pointerX = ev.clientX;
|
||||
pointerY = ev.clientY;
|
||||
if (!overshoot()) {
|
||||
cancelAnimationFrame(frame);
|
||||
frame = 0;
|
||||
anchor = null;
|
||||
return;
|
||||
}
|
||||
// Our focus wins over WebKit's, which jumps to the line's start or end.
|
||||
ev.preventDefault();
|
||||
if (!frame) tick();
|
||||
};
|
||||
const stop = () => {
|
||||
cancelAnimationFrame(frame);
|
||||
frame = 0;
|
||||
window.removeEventListener("mousemove", move, true);
|
||||
window.removeEventListener("mouseup", stop, true);
|
||||
window.removeEventListener("blur", stop);
|
||||
field.removeEventListener("blur", stop);
|
||||
field.removeEventListener("dragstart", stop);
|
||||
};
|
||||
window.addEventListener("mousemove", move, true);
|
||||
window.addEventListener("mouseup", stop, true);
|
||||
window.addEventListener("blur", stop);
|
||||
field.addEventListener("blur", stop);
|
||||
field.addEventListener("dragstart", stop);
|
||||
}
|
||||
Reference in New Issue
Block a user