mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-29 08:00:06 +00:00
feat(assistant): trip assistant chat with your own AI connection
Adds an in-app assistant that reads and plans the open trip. Users connect their own provider (Sign in with ChatGPT, or an Anthropic, OpenAI, Gemini or OpenRouter key) or use the one the admin set up, including a custom OpenAI-compatible server. It is an addon and only shows while a connection is usable. The chat runs on the existing MCP tools, pinned to the trip. Every change is held as a change card the user applies or discards, and applied changes can be undone. On the desktop it is a floating window that can be moved and resized; on the phone it is fullscreen. Search results show as place cards that can go onto a day, weather lookups as a strip, proposed places as ghost markers on the map with a before/after switch, and an answer can be shared into the trip chat. Booking files can be dropped in and are read into change cards.
This commit is contained in:
@@ -0,0 +1,255 @@
|
||||
// FE-HOOK-DRAG-001 to FE-HOOK-DRAG-019
|
||||
import { act, renderHook } from '@testing-library/react';
|
||||
import type { PointerEvent as ReactPointerEvent } from 'react';
|
||||
|
||||
import {
|
||||
clampRect,
|
||||
cornerRect,
|
||||
expandedRect,
|
||||
keyedRect,
|
||||
resizeRect,
|
||||
snapRect,
|
||||
useDragResize,
|
||||
type WindowRect,
|
||||
type WindowSize,
|
||||
} from './useDragResize';
|
||||
|
||||
const MIN: WindowSize = { width: 340, height: 420 };
|
||||
const bounds = (width = 1280, height = 800, topInset = 0) => ({
|
||||
viewport: { width, height },
|
||||
minSize: MIN,
|
||||
margin: 16,
|
||||
topInset,
|
||||
});
|
||||
const KEY = 'trek.test.window';
|
||||
const OPTIONS = {
|
||||
storageKey: KEY,
|
||||
minSize: MIN,
|
||||
defaultSize: { width: 400, height: 600 },
|
||||
expandedSize: (viewport: WindowSize) => ({ width: 720, height: Math.round(viewport.height * 0.8) }),
|
||||
margin: 16,
|
||||
gap: 24,
|
||||
};
|
||||
|
||||
const press = (key: string, mods: { shiftKey?: boolean; altKey?: boolean } = {}) => ({
|
||||
key,
|
||||
altKey: mods.altKey ?? true,
|
||||
shiftKey: mods.shiftKey ?? false,
|
||||
ctrlKey: false,
|
||||
metaKey: false,
|
||||
});
|
||||
|
||||
function handle(): HTMLElement {
|
||||
const el = document.createElement('div');
|
||||
el.setPointerCapture = vi.fn();
|
||||
return el;
|
||||
}
|
||||
|
||||
function pointerDown(el: HTMLElement, clientX: number, clientY: number) {
|
||||
return {
|
||||
button: 0,
|
||||
pointerId: 1,
|
||||
clientX,
|
||||
clientY,
|
||||
currentTarget: el,
|
||||
preventDefault: vi.fn(),
|
||||
} as unknown as ReactPointerEvent<HTMLElement>;
|
||||
}
|
||||
|
||||
function pointer(el: HTMLElement, type: 'pointermove' | 'pointerup', clientX: number, clientY: number) {
|
||||
act(() => {
|
||||
el.dispatchEvent(new MouseEvent(type, { clientX, clientY }));
|
||||
});
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
vi.stubGlobal('innerWidth', 1280);
|
||||
vi.stubGlobal('innerHeight', 800);
|
||||
document.documentElement.dir = 'ltr';
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
document.documentElement.dir = '';
|
||||
});
|
||||
|
||||
describe('window geometry', () => {
|
||||
it('FE-HOOK-DRAG-001: clampRect keeps the rect inside the viewport, margins included', () => {
|
||||
expect(clampRect({ x: -50, y: 900, width: 400, height: 600 }, bounds())).toEqual({
|
||||
x: 16,
|
||||
y: 184,
|
||||
width: 400,
|
||||
height: 600,
|
||||
});
|
||||
expect(clampRect({ x: 0, y: 0, width: 100, height: 100 }, bounds())).toMatchObject({ width: 340, height: 420 });
|
||||
});
|
||||
|
||||
it('FE-HOOK-DRAG-002: clampRect lets a small viewport win over the minimum size', () => {
|
||||
expect(clampRect({ x: 0, y: 0, width: 400, height: 600 }, bounds(300, 400))).toEqual({
|
||||
x: 16,
|
||||
y: 16,
|
||||
width: 268,
|
||||
height: 368,
|
||||
});
|
||||
});
|
||||
|
||||
it('FE-HOOK-DRAG-003: cornerRect sits in the bottom end corner, gap from both edges', () => {
|
||||
expect(cornerRect({ width: 400, height: 600 }, 24, bounds())).toEqual({ x: 856, y: 176, width: 400, height: 600 });
|
||||
});
|
||||
|
||||
it('FE-HOOK-DRAG-004: snapRect settles a window released near a corner into it', () => {
|
||||
expect(snapRect({ x: 20, y: 10, width: 400, height: 600 }, 24, bounds())).toEqual({
|
||||
x: 24,
|
||||
y: 24,
|
||||
width: 400,
|
||||
height: 600,
|
||||
});
|
||||
expect(snapRect({ x: 870, y: 190, width: 400, height: 600 }, 24, bounds())).toMatchObject({ x: 856, y: 176 });
|
||||
});
|
||||
|
||||
it('FE-HOOK-DRAG-005: snapRect leaves a window near one edge only where it is', () => {
|
||||
const rect = { x: 20, y: 100, width: 400, height: 600 };
|
||||
expect(snapRect(rect, 24, bounds())).toBe(rect);
|
||||
});
|
||||
|
||||
it('FE-HOOK-DRAG-006: resizeRect from the start edge keeps the end edge in place, down to the minimum', () => {
|
||||
const start: WindowRect = { x: 500, y: 100, width: 400, height: 600 };
|
||||
expect(resizeRect(start, 'start', -100, 0, bounds())).toEqual({ x: 400, y: 100, width: 500, height: 600 });
|
||||
expect(resizeRect(start, 'start', 300, 0, bounds())).toEqual({ x: 560, y: 100, width: 340, height: 600 });
|
||||
});
|
||||
|
||||
it('FE-HOOK-DRAG-007: resizeRect from a corner pulls both edges, stopped by the viewport', () => {
|
||||
const start: WindowRect = { x: 500, y: 100, width: 400, height: 600 };
|
||||
expect(resizeRect(start, 's-end', 2000, 2000, bounds())).toEqual({ x: 500, y: 100, width: 764, height: 684 });
|
||||
expect(resizeRect(start, 'n', 0, -500, bounds())).toEqual({ x: 500, y: 16, width: 400, height: 684 });
|
||||
});
|
||||
|
||||
it('FE-HOOK-DRAG-008: expandedRect sits at the inline end, centred from top to bottom', () => {
|
||||
expect(expandedRect({ width: 720, height: 640 }, 24, bounds())).toEqual({ x: 536, y: 80, width: 720, height: 640 });
|
||||
});
|
||||
|
||||
it('FE-HOOK-DRAG-009: keyedRect moves with Alt+arrows, resizes with Alt+Shift+arrows, and reads arrows as seen', () => {
|
||||
const rect: WindowRect = { x: 500, y: 100, width: 400, height: 600 };
|
||||
expect(keyedRect(rect, press('ArrowRight'), false, bounds())).toMatchObject({ x: 516, y: 100 });
|
||||
expect(keyedRect(rect, press('ArrowRight'), true, bounds())).toMatchObject({ x: 484 });
|
||||
expect(keyedRect(rect, press('ArrowDown', { shiftKey: true }), false, bounds())).toMatchObject({ height: 616 });
|
||||
expect(keyedRect(rect, press('ArrowRight', { altKey: false }), false, bounds())).toBeNull();
|
||||
expect(keyedRect(rect, press('Enter'), false, bounds())).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-HOOK-DRAG-018: a top inset keeps the window below the bar there, in every placement', () => {
|
||||
const below = bounds(1280, 800, 64);
|
||||
expect(clampRect({ x: 100, y: 0, width: 400, height: 600 }, below)).toMatchObject({ y: 80 });
|
||||
expect(clampRect({ x: 0, y: 0, width: 400, height: 900 }, below)).toMatchObject({ y: 80, height: 704 });
|
||||
expect(snapRect({ x: 20, y: 80, width: 400, height: 600 }, 24, below)).toMatchObject({ x: 24, y: 88 });
|
||||
const start: WindowRect = { x: 500, y: 100, width: 400, height: 600 };
|
||||
expect(resizeRect(start, 'n', 0, -500, below)).toEqual({ x: 500, y: 80, width: 400, height: 620 });
|
||||
expect(expandedRect({ width: 720, height: 640 }, 24, below)).toMatchObject({ y: 112 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('useDragResize', () => {
|
||||
it('FE-HOOK-DRAG-010: opens in the bottom end corner on a first visit', () => {
|
||||
const { result } = renderHook(() => useDragResize(OPTIONS));
|
||||
expect(result.current.rect).toEqual({ x: 856, y: 176, width: 400, height: 600 });
|
||||
expect(result.current.active).toBe(false);
|
||||
});
|
||||
|
||||
it('FE-HOOK-DRAG-011: comes back where it was left, clamped to the screen it opens on', () => {
|
||||
localStorage.setItem(KEY, JSON.stringify({ x: 2000, y: 50, width: 500, height: 500 }));
|
||||
const { result } = renderHook(() => useDragResize(OPTIONS));
|
||||
expect(result.current.rect).toEqual({ x: 764, y: 50, width: 500, height: 500 });
|
||||
});
|
||||
|
||||
it('FE-HOOK-DRAG-012: ignores a stored value that is not a rect', () => {
|
||||
localStorage.setItem(KEY, '{"x":"left"}');
|
||||
const { result } = renderHook(() => useDragResize(OPTIONS));
|
||||
expect(result.current.rect).toMatchObject({ x: 856, y: 176 });
|
||||
});
|
||||
|
||||
it('FE-HOOK-DRAG-013: drags by the handle, snaps into a corner on release and remembers it', () => {
|
||||
const { result } = renderHook(() => useDragResize(OPTIONS));
|
||||
const el = handle();
|
||||
act(() => result.current.handleProps.onPointerDown(pointerDown(el, 1000, 200)));
|
||||
expect(el.setPointerCapture).toHaveBeenCalledWith(1);
|
||||
expect(result.current.active).toBe(true);
|
||||
|
||||
pointer(el, 'pointermove', 160, 40);
|
||||
expect(result.current.rect).toMatchObject({ x: 16, y: 16 });
|
||||
pointer(el, 'pointerup', 160, 40);
|
||||
|
||||
expect(result.current.active).toBe(false);
|
||||
expect(result.current.rect).toMatchObject({ x: 24, y: 24 });
|
||||
expect(JSON.parse(localStorage.getItem(KEY) ?? 'null')).toEqual({ x: 24, y: 24, width: 400, height: 600 });
|
||||
});
|
||||
|
||||
it('FE-HOOK-DRAG-014: a pointer moving left in a right-to-left page moves the window towards its end', () => {
|
||||
document.documentElement.dir = 'rtl';
|
||||
localStorage.setItem(KEY, JSON.stringify({ x: 400, y: 100, width: 400, height: 600 }));
|
||||
const { result } = renderHook(() => useDragResize(OPTIONS));
|
||||
const el = handle();
|
||||
act(() => result.current.handleProps.onPointerDown(pointerDown(el, 600, 300)));
|
||||
pointer(el, 'pointermove', 500, 300);
|
||||
expect(result.current.rect.x).toBe(500);
|
||||
});
|
||||
|
||||
it('FE-HOOK-DRAG-015: resizes from an edge and switches to the large size and back on a double click', () => {
|
||||
const { result } = renderHook(() => useDragResize(OPTIONS));
|
||||
const el = handle();
|
||||
act(() => result.current.edgeProps('start').onPointerDown(pointerDown(el, 856, 400)));
|
||||
pointer(el, 'pointermove', 756, 400);
|
||||
pointer(el, 'pointerup', 756, 400);
|
||||
expect(result.current.rect).toEqual({ x: 756, y: 176, width: 500, height: 600 });
|
||||
|
||||
act(() => result.current.handleProps.onDoubleClick({} as never));
|
||||
expect(result.current.rect).toEqual({ x: 536, y: 80, width: 720, height: 640 });
|
||||
act(() => result.current.handleProps.onDoubleClick({} as never));
|
||||
expect(result.current.rect).toEqual({ x: 756, y: 176, width: 500, height: 600 });
|
||||
});
|
||||
|
||||
it('FE-HOOK-DRAG-017: the presses of a double click on the handle keep the way back to the compact size', () => {
|
||||
const { result } = renderHook(() => useDragResize(OPTIONS));
|
||||
const el = handle();
|
||||
const doubleClick = () => {
|
||||
act(() => result.current.handleProps.onPointerDown(pointerDown(el, 1000, 200)));
|
||||
pointer(el, 'pointerup', 1000, 200);
|
||||
act(() => result.current.handleProps.onPointerDown(pointerDown(el, 1000, 200)));
|
||||
pointer(el, 'pointerup', 1000, 200);
|
||||
act(() => result.current.handleProps.onDoubleClick({} as never));
|
||||
};
|
||||
|
||||
doubleClick();
|
||||
expect(result.current.rect).toEqual({ x: 536, y: 80, width: 720, height: 640 });
|
||||
doubleClick();
|
||||
expect(result.current.rect).toEqual({ x: 856, y: 176, width: 400, height: 600 });
|
||||
});
|
||||
|
||||
it('FE-HOOK-DRAG-016: Alt+arrows move it and claim the key, a shrinking browser pulls it back in', () => {
|
||||
const { result } = renderHook(() => useDragResize(OPTIONS));
|
||||
const preventDefault = vi.fn();
|
||||
act(() => result.current.onKeyDown({ ...press('ArrowUp'), preventDefault } as never));
|
||||
expect(preventDefault).toHaveBeenCalled();
|
||||
expect(result.current.rect.y).toBe(160);
|
||||
|
||||
act(() => {
|
||||
vi.stubGlobal('innerWidth', 900);
|
||||
window.dispatchEvent(new Event('resize'));
|
||||
});
|
||||
expect(result.current.rect).toMatchObject({ x: 484, width: 400 });
|
||||
});
|
||||
|
||||
it('FE-HOOK-DRAG-019: Alt+arrows typed in a field stay with the field', () => {
|
||||
const { result } = renderHook(() => useDragResize({ ...OPTIONS, topInset: 64 }));
|
||||
const field = document.createElement('textarea');
|
||||
const preventDefault = vi.fn();
|
||||
act(() => result.current.onKeyDown({ ...press('ArrowLeft'), target: field, preventDefault } as never));
|
||||
expect(preventDefault).not.toHaveBeenCalled();
|
||||
expect(result.current.rect).toEqual({ x: 856, y: 176, width: 400, height: 600 });
|
||||
|
||||
const el = handle();
|
||||
act(() => result.current.handleProps.onPointerDown(pointerDown(el, 1000, 200)));
|
||||
pointer(el, 'pointermove', 1000, 0);
|
||||
expect(result.current.rect.y).toBe(80);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,363 @@
|
||||
import {
|
||||
type KeyboardEventHandler,
|
||||
type MouseEventHandler,
|
||||
type PointerEvent,
|
||||
type PointerEventHandler,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useRef,
|
||||
useState,
|
||||
} from 'react';
|
||||
|
||||
export interface WindowSize {
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
/** `x` runs from the viewport's inline-start edge (left, right in Arabic), `y` from the top. */
|
||||
export interface WindowRect {
|
||||
x: number;
|
||||
y: number;
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
export type ResizeEdge = 'n' | 's' | 'start' | 'end' | 'n-start' | 'n-end' | 's-start' | 's-end';
|
||||
|
||||
interface Bounds {
|
||||
viewport: WindowSize;
|
||||
minSize: WindowSize;
|
||||
margin: number;
|
||||
/** What a fixed bar covers at the top (the navbar); the window keeps its margin below it. */
|
||||
topInset: number;
|
||||
}
|
||||
|
||||
interface DragResizeOptions {
|
||||
/** Where the last place and size are kept between visits. */
|
||||
storageKey: string;
|
||||
minSize: WindowSize;
|
||||
/** The size on the first visit, in the bottom inline-end corner. */
|
||||
defaultSize: WindowSize;
|
||||
/** The large size a double click on the handle switches to. */
|
||||
expandedSize: (viewport: WindowSize) => WindowSize;
|
||||
/** The window never comes closer to the viewport's edge than this. */
|
||||
margin: number;
|
||||
/** The distance from the edges a corner keeps, and how near a corner a released window snaps into it. */
|
||||
gap: number;
|
||||
/** Space at the top the window never moves into, so its handle stays above a fixed bar there. */
|
||||
topInset?: number;
|
||||
}
|
||||
|
||||
/** Arrow keys move or resize by this much. */
|
||||
const KEY_STEP = 16;
|
||||
|
||||
const clamp = (value: number, min: number, max: number) => Math.min(Math.max(value, min), Math.max(min, max));
|
||||
|
||||
/** The size that fits: at least the minimum, at most the viewport less its margins, and the viewport wins. */
|
||||
function fitSize(size: WindowSize, { viewport, minSize, margin, topInset }: Bounds): WindowSize {
|
||||
const maxWidth = Math.max(0, viewport.width - 2 * margin);
|
||||
const maxHeight = Math.max(0, viewport.height - topInset - 2 * margin);
|
||||
return {
|
||||
width: Math.min(Math.max(size.width, minSize.width), maxWidth),
|
||||
height: Math.min(Math.max(size.height, minSize.height), maxHeight),
|
||||
};
|
||||
}
|
||||
|
||||
/** The rect moved and shrunk until it lies inside the viewport, its margins kept. */
|
||||
export function clampRect(rect: WindowRect, bounds: Bounds): WindowRect {
|
||||
const { width, height } = fitSize(rect, bounds);
|
||||
const { viewport, margin, topInset } = bounds;
|
||||
return {
|
||||
x: clamp(rect.x, margin, viewport.width - margin - width),
|
||||
y: clamp(rect.y, topInset + margin, viewport.height - margin - height),
|
||||
width,
|
||||
height,
|
||||
};
|
||||
}
|
||||
|
||||
/** A size placed in the bottom inline-end corner, `gap` from both edges. */
|
||||
export function cornerRect(size: WindowSize, gap: number, bounds: Bounds): WindowRect {
|
||||
const fitted = fitSize(size, bounds);
|
||||
return clampRect(
|
||||
{
|
||||
x: bounds.viewport.width - fitted.width - gap,
|
||||
y: bounds.viewport.height - fitted.height - gap,
|
||||
...fitted,
|
||||
},
|
||||
bounds
|
||||
);
|
||||
}
|
||||
|
||||
/** A released window within `gap` of a corner settles into it; anywhere else it stays. */
|
||||
export function snapRect(rect: WindowRect, gap: number, bounds: Bounds): WindowRect {
|
||||
const { width, height } = bounds.viewport;
|
||||
const top = bounds.topInset + gap;
|
||||
const toEnd = width - rect.x - rect.width;
|
||||
const toBottom = height - rect.y - rect.height;
|
||||
const nearX = rect.x <= gap ? 'start' : toEnd <= gap ? 'end' : null;
|
||||
const nearY = rect.y <= top ? 'top' : toBottom <= gap ? 'bottom' : null;
|
||||
if (!nearX || !nearY) return rect;
|
||||
return clampRect(
|
||||
{
|
||||
...rect,
|
||||
x: nearX === 'start' ? gap : width - rect.width - gap,
|
||||
y: nearY === 'top' ? top : height - rect.height - gap,
|
||||
},
|
||||
bounds
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The rect with one edge or corner pulled by (dx, dy), dx along the inline
|
||||
* axis. The opposite edge stays where it was, also when the minimum size or
|
||||
* the viewport stops the pull.
|
||||
*/
|
||||
export function resizeRect(start: WindowRect, edge: ResizeEdge, dx: number, dy: number, bounds: Bounds): WindowRect {
|
||||
const { viewport, minSize, margin, topInset } = bounds;
|
||||
let { x, y, width, height } = start;
|
||||
const right = start.x + start.width;
|
||||
const bottom = start.y + start.height;
|
||||
if (edge.endsWith('end')) width = clamp(start.width + dx, minSize.width, viewport.width - margin - start.x);
|
||||
if (edge.endsWith('start')) {
|
||||
width = clamp(start.width - dx, minSize.width, right - margin);
|
||||
x = right - width;
|
||||
}
|
||||
if (edge.startsWith('s')) height = clamp(start.height + dy, minSize.height, viewport.height - margin - start.y);
|
||||
if (edge.startsWith('n')) {
|
||||
height = clamp(start.height - dy, minSize.height, bottom - topInset - margin);
|
||||
y = bottom - height;
|
||||
}
|
||||
return clampRect({ x, y, width, height }, bounds);
|
||||
}
|
||||
|
||||
/** The large size: at the inline end, `gap` from it, centred from top to bottom below the top inset. */
|
||||
export function expandedRect(size: WindowSize, gap: number, bounds: Bounds): WindowRect {
|
||||
const fitted = fitSize(size, bounds);
|
||||
const { width, height } = bounds.viewport;
|
||||
const y = bounds.topInset + Math.round((height - bounds.topInset - fitted.height) / 2);
|
||||
return clampRect({ x: width - fitted.width - gap, y, ...fitted }, bounds);
|
||||
}
|
||||
|
||||
const ARROWS: Record<string, [number, number]> = {
|
||||
ArrowLeft: [-1, 0],
|
||||
ArrowRight: [1, 0],
|
||||
ArrowUp: [0, -1],
|
||||
ArrowDown: [0, 1],
|
||||
};
|
||||
|
||||
interface ArrowPress {
|
||||
key: string;
|
||||
altKey: boolean;
|
||||
shiftKey: boolean;
|
||||
ctrlKey: boolean;
|
||||
metaKey: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Where Alt+arrow moves the rect and Alt+Shift+arrow resizes it (from its
|
||||
* bottom end corner), the arrows read as they look on screen; null for any
|
||||
* other key.
|
||||
*/
|
||||
export function keyedRect(rect: WindowRect, press: ArrowPress, rtl: boolean, bounds: Bounds): WindowRect | null {
|
||||
const arrow = ARROWS[press.key];
|
||||
if (!arrow || !press.altKey || press.ctrlKey || press.metaKey) return null;
|
||||
const dx = arrow[0] * KEY_STEP * (rtl ? -1 : 1);
|
||||
const dy = arrow[1] * KEY_STEP;
|
||||
if (press.shiftKey) return resizeRect(rect, 's-end', dx, dy, bounds);
|
||||
return clampRect({ ...rect, x: rect.x + dx, y: rect.y + dy }, bounds);
|
||||
}
|
||||
|
||||
function readViewport(): WindowSize {
|
||||
return { width: window.innerWidth, height: window.innerHeight };
|
||||
}
|
||||
|
||||
function isRtl(): boolean {
|
||||
return document.documentElement.dir === 'rtl';
|
||||
}
|
||||
|
||||
/** Typing in a field keeps its own Alt+arrow meaning (word jumps and selection on macOS). */
|
||||
function isEditable(target: EventTarget): boolean {
|
||||
return target instanceof Element && target.closest('input, textarea, select, [contenteditable="true"]') !== null;
|
||||
}
|
||||
|
||||
function readStored(key: string): WindowRect | null {
|
||||
try {
|
||||
const raw = localStorage.getItem(key);
|
||||
const value: unknown = raw ? JSON.parse(raw) : null;
|
||||
if (!value || typeof value !== 'object') return null;
|
||||
const { x, y, width, height } = value as Record<string, unknown>;
|
||||
if (typeof x !== 'number' || typeof y !== 'number' || typeof width !== 'number' || typeof height !== 'number') {
|
||||
return null;
|
||||
}
|
||||
return [x, y, width, height].every(Number.isFinite) ? { x, y, width, height } : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function writeStored(key: string, rect: WindowRect): void {
|
||||
try {
|
||||
localStorage.setItem(key, JSON.stringify(rect));
|
||||
} catch {
|
||||
// A private window or blocked storage: next time the window simply starts in its corner.
|
||||
}
|
||||
}
|
||||
|
||||
/** Reports each position of a captured pointer until it is released; the returned function stops listening. */
|
||||
function followPointer(target: HTMLElement, onMove: (x: number, y: number) => void, onEnd: () => void): () => void {
|
||||
const move = (e: globalThis.PointerEvent) => onMove(e.clientX, e.clientY);
|
||||
const stop = () => {
|
||||
target.removeEventListener('pointermove', move);
|
||||
target.removeEventListener('pointerup', end);
|
||||
target.removeEventListener('pointercancel', end);
|
||||
};
|
||||
const end = () => {
|
||||
stop();
|
||||
onEnd();
|
||||
};
|
||||
target.addEventListener('pointermove', move);
|
||||
target.addEventListener('pointerup', end);
|
||||
target.addEventListener('pointercancel', end);
|
||||
return stop;
|
||||
}
|
||||
|
||||
type Gesture = (dx: number, dy: number, bounds: Bounds) => WindowRect;
|
||||
|
||||
/**
|
||||
* Moves and resizes a floating window with the pointer and the keyboard: the
|
||||
* pointer on the handle drags it, on an edge or corner resizes it; a double
|
||||
* click on the handle switches between its size and a large one; Alt+arrows
|
||||
* move it, Alt+Shift+arrows resize it. It always stays inside the viewport,
|
||||
* also when the browser window shrinks, and it remembers where it was left.
|
||||
*
|
||||
* Logical throughout: `x` runs from the inline start, so in a right-to-left
|
||||
* page a pointer moving left moves the window towards its end.
|
||||
*/
|
||||
export function useDragResize({
|
||||
storageKey,
|
||||
minSize,
|
||||
defaultSize,
|
||||
expandedSize,
|
||||
margin,
|
||||
gap,
|
||||
topInset = 0,
|
||||
}: DragResizeOptions) {
|
||||
const boundsOf = useCallback(
|
||||
(): Bounds => ({ viewport: readViewport(), minSize, margin, topInset }),
|
||||
[minSize, margin, topInset]
|
||||
);
|
||||
const [rect, setRect] = useState<WindowRect>(() => {
|
||||
const stored = readStored(storageKey);
|
||||
return stored ? clampRect(stored, boundsOf()) : cornerRect(defaultSize, gap, boundsOf());
|
||||
});
|
||||
const [active, setActive] = useState(false);
|
||||
/** The rect as last placed, for handlers that run between renders. */
|
||||
const rectRef = useRef(rect);
|
||||
/** The compact rect to go back to while the large size is on. */
|
||||
const restoreRef = useRef<WindowRect | null>(null);
|
||||
/** Stops listening to a pointer still held when the window goes away. */
|
||||
const stopRef = useRef<(() => void) | null>(null);
|
||||
|
||||
const place = useCallback((next: WindowRect) => {
|
||||
rectRef.current = next;
|
||||
setRect(next);
|
||||
}, []);
|
||||
const commit = useCallback(
|
||||
(next: WindowRect) => {
|
||||
place(next);
|
||||
writeStored(storageKey, next);
|
||||
},
|
||||
[place, storageKey]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const onResize = () => place(clampRect(rectRef.current, boundsOf()));
|
||||
window.addEventListener('resize', onResize);
|
||||
return () => window.removeEventListener('resize', onResize);
|
||||
}, [place, boundsOf]);
|
||||
|
||||
useEffect(() => () => stopRef.current?.(), []);
|
||||
|
||||
const startGesture = useCallback(
|
||||
(e: PointerEvent<HTMLElement>, apply: Gesture, settle: (released: WindowRect, bounds: Bounds) => WindowRect) => {
|
||||
if (e.button !== 0) return;
|
||||
e.preventDefault();
|
||||
const origin = { x: e.clientX, y: e.clientY };
|
||||
const flip = isRtl() ? -1 : 1;
|
||||
let latest = rectRef.current;
|
||||
let moved = false;
|
||||
e.currentTarget.setPointerCapture(e.pointerId);
|
||||
setActive(true);
|
||||
stopRef.current = followPointer(
|
||||
e.currentTarget,
|
||||
(x, y) => {
|
||||
// Only a real move or resize ends the large size; the presses of a double click do not.
|
||||
if (!moved) restoreRef.current = null;
|
||||
moved = true;
|
||||
latest = apply((x - origin.x) * flip, y - origin.y, boundsOf());
|
||||
place(latest);
|
||||
},
|
||||
() => {
|
||||
stopRef.current = null;
|
||||
setActive(false);
|
||||
if (moved) commit(settle(latest, boundsOf()));
|
||||
}
|
||||
);
|
||||
},
|
||||
[place, boundsOf, commit]
|
||||
);
|
||||
|
||||
const onHandlePointerDown = useCallback<PointerEventHandler<HTMLElement>>(
|
||||
(e) => {
|
||||
const start = rectRef.current;
|
||||
startGesture(
|
||||
e,
|
||||
(dx, dy, bounds) => clampRect({ ...start, x: start.x + dx, y: start.y + dy }, bounds),
|
||||
(released, bounds) => snapRect(released, gap, bounds)
|
||||
);
|
||||
},
|
||||
[startGesture, gap]
|
||||
);
|
||||
|
||||
const onHandleDoubleClick = useCallback<MouseEventHandler<HTMLElement>>(() => {
|
||||
const bounds = boundsOf();
|
||||
const compact = restoreRef.current;
|
||||
restoreRef.current = compact ? null : rectRef.current;
|
||||
commit(compact ? clampRect(compact, bounds) : expandedRect(expandedSize(bounds.viewport), gap, bounds));
|
||||
}, [boundsOf, commit, expandedSize, gap]);
|
||||
|
||||
const edgeProps = useCallback(
|
||||
(edge: ResizeEdge): { onPointerDown: PointerEventHandler<HTMLElement> } => ({
|
||||
onPointerDown: (e) => {
|
||||
const start = rectRef.current;
|
||||
startGesture(
|
||||
e,
|
||||
(dx, dy, bounds) => resizeRect(start, edge, dx, dy, bounds),
|
||||
(released) => released
|
||||
);
|
||||
},
|
||||
}),
|
||||
[startGesture]
|
||||
);
|
||||
|
||||
const onKeyDown = useCallback<KeyboardEventHandler<HTMLElement>>(
|
||||
(e) => {
|
||||
if (isEditable(e.target)) return;
|
||||
const next = keyedRect(rectRef.current, e, isRtl(), boundsOf());
|
||||
if (!next) return;
|
||||
e.preventDefault();
|
||||
restoreRef.current = null;
|
||||
commit(next);
|
||||
},
|
||||
[boundsOf, commit]
|
||||
);
|
||||
|
||||
return {
|
||||
rect,
|
||||
/** A pointer is moving or resizing the window right now. */
|
||||
active,
|
||||
handleProps: { onPointerDown: onHandlePointerDown, onDoubleClick: onHandleDoubleClick },
|
||||
edgeProps,
|
||||
onKeyDown,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
// FE-HOOK-KBINSET-001 to FE-HOOK-KBINSET-004
|
||||
import { act, renderHook } from '@testing-library/react';
|
||||
|
||||
import { useKeyboardInset } from './useKeyboardInset';
|
||||
|
||||
class FakeVisualViewport extends EventTarget {
|
||||
height = 800;
|
||||
offsetTop = 0;
|
||||
}
|
||||
|
||||
let viewport: FakeVisualViewport;
|
||||
|
||||
beforeEach(() => {
|
||||
viewport = new FakeVisualViewport();
|
||||
vi.stubGlobal('visualViewport', viewport);
|
||||
vi.stubGlobal('innerHeight', 800);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
function keyboard(height: number, offsetTop = 0) {
|
||||
act(() => {
|
||||
viewport.height = 800 - height - offsetTop;
|
||||
viewport.offsetTop = offsetTop;
|
||||
viewport.dispatchEvent(new Event('resize'));
|
||||
});
|
||||
}
|
||||
|
||||
describe('useKeyboardInset', () => {
|
||||
it('FE-HOOK-KBINSET-001: is zero while no keyboard is up', () => {
|
||||
const { result } = renderHook(() => useKeyboardInset());
|
||||
expect(result.current).toBe(0);
|
||||
});
|
||||
|
||||
it('FE-HOOK-KBINSET-002: follows the keyboard as it opens and closes', () => {
|
||||
const { result } = renderHook(() => useKeyboardInset());
|
||||
keyboard(320);
|
||||
expect(result.current).toBe(320);
|
||||
keyboard(0);
|
||||
expect(result.current).toBe(0);
|
||||
});
|
||||
|
||||
it('FE-HOOK-KBINSET-003: leaves out the part the page scrolled the viewport by', () => {
|
||||
const { result } = renderHook(() => useKeyboardInset());
|
||||
act(() => {
|
||||
viewport.height = 480;
|
||||
viewport.offsetTop = 40;
|
||||
viewport.dispatchEvent(new Event('scroll'));
|
||||
});
|
||||
expect(result.current).toBe(280);
|
||||
});
|
||||
|
||||
it('FE-HOOK-KBINSET-004: stays at zero where the browser has no visual viewport', () => {
|
||||
vi.stubGlobal('visualViewport', null);
|
||||
const { result } = renderHook(() => useKeyboardInset());
|
||||
expect(result.current).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
import { useSyncExternalStore } from 'react';
|
||||
|
||||
/** How far the on-screen keyboard reaches into the layout viewport, in px; 0 when none is up. */
|
||||
function readInset(): number {
|
||||
const viewport = window.visualViewport;
|
||||
if (!viewport) return 0;
|
||||
return Math.max(0, Math.round(window.innerHeight - viewport.height - viewport.offsetTop));
|
||||
}
|
||||
|
||||
function subscribe(onChange: () => void): () => void {
|
||||
const viewport = window.visualViewport;
|
||||
if (!viewport) return () => undefined;
|
||||
viewport.addEventListener('resize', onChange);
|
||||
viewport.addEventListener('scroll', onChange);
|
||||
return () => {
|
||||
viewport.removeEventListener('resize', onChange);
|
||||
viewport.removeEventListener('scroll', onChange);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The height the phone's keyboard covers at the bottom of the screen, read
|
||||
* off the visual viewport. A full-screen view pads its bottom by it, so a
|
||||
* composer at the foot stays above the keys instead of under them: iOS
|
||||
* Safari lays the keyboard over the page without resizing it.
|
||||
*/
|
||||
export function useKeyboardInset(): number {
|
||||
return useSyncExternalStore(subscribe, readInset, () => 0);
|
||||
}
|
||||
Reference in New Issue
Block a user