mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-29 16:10:07 +00:00
fix(ci): green the dev gates after the native and popup rounds
- RTL: the measured pills and centred controls use logical forms or a marked line - i18n: the two native widget numbers are positions, not counts (NOT_PLURAL) - Types: styleOverride on the lazy GL map, the location and shared-file payloads, the capabilities fallback, the transport sheet's stay metadata - ESLint: latest-value refs move to layout effects, usePresence keeps the last open state in state, the booking import opens clean with a shared document kept in the list (the reset effect used to clear it again) - Layers: the phone import sheet lives under mobile/ and reads through tripRepo; the offline host check moves to utils/tileUrl - Sizes: plugin layer geometry, hardNavigate and the exit animations get modules of their own - Tests follow the status radios, the stay chip overview, the dock + button for the first list and the field token; store registry lists the new stores
This commit is contained in:
@@ -2,7 +2,8 @@ import { act, fireEvent, render, screen } from '@testing-library/react';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { tickHaptic } from '../../native/haptics';
|
||||
import type { Day } from '../../types';
|
||||
import MDayPager, { pagesFor } from './MDayPager';
|
||||
import MDayPager from './MDayPager';
|
||||
import { pagesFor } from './dayPagerPages';
|
||||
|
||||
vi.mock('../../native/haptics', () => ({ tickHaptic: vi.fn() }));
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';
|
||||
import { tickHaptic } from '../../native/haptics';
|
||||
import type { Day } from '../../types';
|
||||
import { pagesFor, type PagerItem } from './dayPagerPages';
|
||||
|
||||
/**
|
||||
* Pages through the trip's days the way a native pager does: the previous,
|
||||
@@ -28,7 +28,6 @@ const SETTLE_MS = 90;
|
||||
const REST_PX = 2;
|
||||
|
||||
/** Anything with an id pages: trip days, a leave year's months, the plan's years. */
|
||||
export type PagerItem = Pick<Day, 'id'>;
|
||||
|
||||
export interface MDayPagerProps {
|
||||
days: PagerItem[];
|
||||
@@ -55,33 +54,6 @@ export interface MDayPagerProps {
|
||||
onPreview?: (dayId: number | null) => void;
|
||||
}
|
||||
|
||||
interface Page {
|
||||
key: string;
|
||||
dayId: number | null;
|
||||
active: boolean;
|
||||
}
|
||||
|
||||
/** The window of pages around the selection. A selection that points at no
|
||||
* day (the whole-trip view, or a day deleted remotely) still gets its page,
|
||||
* with the first day next to it as a way back. */
|
||||
export function pagesFor(days: PagerItem[], selectedDayId: number | null): Page[] {
|
||||
const i = days.findIndex((d) => d.id === selectedDayId);
|
||||
if (i < 0) {
|
||||
const first = days[0];
|
||||
return [
|
||||
{ key: 'none', dayId: selectedDayId, active: true },
|
||||
...(first ? [{ key: `d${first.id}`, dayId: first.id, active: false }] : []),
|
||||
];
|
||||
}
|
||||
const pages: Page[] = [];
|
||||
const prev = days[i - 1];
|
||||
const next = days[i + 1];
|
||||
if (prev) pages.push({ key: `d${prev.id}`, dayId: prev.id, active: false });
|
||||
pages.push({ key: `d${days[i].id}`, dayId: days[i].id, active: true });
|
||||
if (next) pages.push({ key: `d${next.id}`, dayId: next.id, active: false });
|
||||
return pages;
|
||||
}
|
||||
|
||||
export default function MDayPager({
|
||||
days,
|
||||
selectedDayId,
|
||||
@@ -99,7 +71,9 @@ export default function MDayPager({
|
||||
|
||||
// The handlers below are attached once, so they read the props through here.
|
||||
const latest = useRef({ days, onSelectDay, describeDay, selectedDayId, onPreview });
|
||||
latest.current = { days, onSelectDay, describeDay, selectedDayId, onPreview };
|
||||
useLayoutEffect(() => {
|
||||
latest.current = { days, onSelectDay, describeDay, selectedDayId, onPreview };
|
||||
});
|
||||
/** The day a landed swipe asked for, until the selection catches up. Stops a
|
||||
* late scroll event from selecting it twice. */
|
||||
const requested = useRef<number | null>(null);
|
||||
|
||||
@@ -28,7 +28,7 @@ export default function MSegmented<T extends string = string>({
|
||||
className = '',
|
||||
}: MSegmentedProps<T>) {
|
||||
const trackRef = useRef<HTMLDivElement>(null)
|
||||
const pill = useActivePill(trackRef, '[data-active="true"]', [value, options.length])
|
||||
const pill = useActivePill(trackRef, '[data-active="true"]', `${String(value)}:${options.length}`)
|
||||
|
||||
return (
|
||||
<div
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { act, fireEvent, render, screen } from '../../../tests/helpers/render';
|
||||
import { useSharedImportStore } from '../../native/sharedFiles';
|
||||
import { tripRepo } from '../../repo/tripRepo';
|
||||
import NativeImportSheet from './NativeImportSheet';
|
||||
|
||||
const navigate = vi.hoisted(() => vi.fn());
|
||||
vi.mock('react-router', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('react-router')>()),
|
||||
useNavigate: () => navigate,
|
||||
}));
|
||||
|
||||
beforeEach(() => {
|
||||
// A second spyOn returns the first spy with its calls; start every test clean.
|
||||
vi.restoreAllMocks();
|
||||
navigate.mockReset();
|
||||
useSharedImportStore.setState({ file: null, tripId: null });
|
||||
vi.spyOn(tripRepo, 'list').mockResolvedValue({
|
||||
trips: [
|
||||
{ id: 1, title: 'Past trip', start_date: '2020-01-01', end_date: '2020-01-05' },
|
||||
{ id: 2, title: 'Japan', start_date: '2099-03-01', end_date: '2099-03-10' },
|
||||
],
|
||||
archivedTrips: [],
|
||||
} as unknown as Awaited<ReturnType<typeof tripRepo.list>>);
|
||||
});
|
||||
|
||||
describe('NativeImportSheet', () => {
|
||||
it('asks which trip a shared document goes to, upcoming trips first, and opens it there', async () => {
|
||||
render(<NativeImportSheet />);
|
||||
act(() => useSharedImportStore.getState().setFile(new File(['x'], 'booking.pdf', { type: 'application/pdf' })));
|
||||
|
||||
const rows = await screen.findAllByRole('button', { name: /Japan|Past trip/ });
|
||||
expect(rows.map((r) => r.textContent)).toEqual(['Japan', 'Past trip']);
|
||||
expect(screen.getByText('booking.pdf')).toBeInTheDocument();
|
||||
|
||||
fireEvent.click(rows[0]);
|
||||
expect(useSharedImportStore.getState().tripId).toBe(2);
|
||||
expect(navigate).toHaveBeenCalledWith('/trips/2');
|
||||
});
|
||||
|
||||
it('stays closed with nothing shared', () => {
|
||||
render(<NativeImportSheet />);
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
|
||||
expect(tripRepo.list).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,89 @@
|
||||
/**
|
||||
* NativeImportSheet: a booking document was shared to TREK (native/sharedFiles.ts),
|
||||
* so this asks which trip it belongs to and opens that trip's booking import with
|
||||
* the file already chosen. Trips still ahead come first, the ones that ended after.
|
||||
*/
|
||||
import { ChevronRight, FileText } from 'lucide-react';
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { useNavigate } from 'react-router';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { useSharedImportStore } from '../../native/sharedFiles';
|
||||
import { tripRepo } from '../../repo/tripRepo';
|
||||
import { TileHeader } from '../screens/trip/sheets/MTripSheetUi';
|
||||
import MSheet from './MSheet';
|
||||
|
||||
interface TripRow {
|
||||
id: number;
|
||||
title: string;
|
||||
start_date?: string | null;
|
||||
end_date?: string | null;
|
||||
}
|
||||
|
||||
export default function NativeImportSheet(): React.ReactElement | null {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const file = useSharedImportStore((s) => s.file);
|
||||
const tripId = useSharedImportStore((s) => s.tripId);
|
||||
const chooseTrip = useSharedImportStore((s) => s.chooseTrip);
|
||||
const setFile = useSharedImportStore((s) => s.setFile);
|
||||
const [trips, setTrips] = useState<TripRow[]>([]);
|
||||
|
||||
const open = !!file && tripId == null;
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
tripRepo.list().then(
|
||||
(data: { trips?: TripRow[] }) => {
|
||||
const today = new Date().toISOString().slice(0, 10);
|
||||
const list = [...(data.trips ?? [])];
|
||||
const ahead = (trip: TripRow) => (trip.end_date ?? '9999') >= today;
|
||||
list.sort(
|
||||
(a, b) => Number(ahead(b)) - Number(ahead(a)) || (a.start_date ?? '').localeCompare(b.start_date ?? '')
|
||||
);
|
||||
setTrips(list);
|
||||
},
|
||||
() => setTrips([])
|
||||
);
|
||||
}, [open]);
|
||||
|
||||
const pick = (id: number) => {
|
||||
chooseTrip(id);
|
||||
void navigate(`/trips/${id}`);
|
||||
};
|
||||
|
||||
return (
|
||||
<MSheet open={open} onClose={() => setFile(null)} variant="bottom" ariaLabel={t('native.share.title')}>
|
||||
<div className="px-[18px] pb-4 pt-4">
|
||||
<div className="mb-3">
|
||||
<TileHeader
|
||||
icon={<FileText size={19} strokeWidth={1.8} />}
|
||||
title={t('native.share.title')}
|
||||
sub={file?.name}
|
||||
onClose={() => setFile(null)}
|
||||
closeLabel={t('common.close')}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex max-h-[50vh] flex-col gap-2 overflow-y-auto">
|
||||
{trips.map((trip) => (
|
||||
<button
|
||||
key={trip.id}
|
||||
type="button"
|
||||
onClick={() => pick(trip.id)}
|
||||
className="flex items-center gap-3 rounded-[16px] border border-[color:var(--m-gbr)] bg-[color:var(--m-glass)] px-4 py-3 text-start transition-transform active:scale-[.98]"
|
||||
>
|
||||
<span className="min-w-0 flex-1 truncate text-[length:calc(14px*var(--fs-scale-body,1))] font-bold text-m-ink">
|
||||
{trip.title}
|
||||
</span>
|
||||
<ChevronRight size={16} className="flex-none text-m-faint" aria-hidden="true" />
|
||||
</button>
|
||||
))}
|
||||
{trips.length === 0 && (
|
||||
<p className="px-1 text-[length:calc(12px*var(--fs-scale-body,1))] text-m-muted">
|
||||
{t('native.share.noTrips')}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</MSheet>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import type { Day } from '../../types';
|
||||
|
||||
/** A day as the pager needs it: only its id, so the plan and Vacay can both page. */
|
||||
export type PagerItem = Pick<Day, 'id'>;
|
||||
|
||||
interface Page {
|
||||
key: string;
|
||||
dayId: number | null;
|
||||
active: boolean;
|
||||
}
|
||||
|
||||
/** The window of pages around the selection. A selection that points at no
|
||||
* day (the whole-trip view, or a day deleted remotely) still gets its page,
|
||||
* with the first day next to it as a way back. */
|
||||
export function pagesFor(days: PagerItem[], selectedDayId: number | null): Page[] {
|
||||
const i = days.findIndex((d) => d.id === selectedDayId);
|
||||
if (i < 0) {
|
||||
const first = days[0];
|
||||
return [
|
||||
{ key: 'none', dayId: selectedDayId, active: true },
|
||||
...(first ? [{ key: `d${first.id}`, dayId: first.id, active: false }] : []),
|
||||
];
|
||||
}
|
||||
const pages: Page[] = [];
|
||||
const prev = days[i - 1];
|
||||
const next = days[i + 1];
|
||||
if (prev) pages.push({ key: `d${prev.id}`, dayId: prev.id, active: false });
|
||||
pages.push({ key: `d${days[i].id}`, dayId: days[i].id, active: true });
|
||||
if (next) pages.push({ key: `d${next.id}`, dayId: next.id, active: false });
|
||||
return pages;
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { CSSProperties, DependencyList, RefObject } from 'react';
|
||||
import type { CSSProperties, RefObject } from 'react';
|
||||
import { useLayoutEffect, useState } from 'react';
|
||||
|
||||
/**
|
||||
@@ -17,15 +17,18 @@ export function useActivePill(
|
||||
/** The track, as a ref or as the element itself (a callback-ref'd rail). */
|
||||
trackRef: RefObject<HTMLElement | null> | HTMLElement | null,
|
||||
selector: string,
|
||||
deps: DependencyList,
|
||||
/** What moves the active item, as one value: a change re-measures the pill. */
|
||||
key: string | number,
|
||||
/** Follow the item across rows too (a grid of chips): the pill then also takes
|
||||
* the item's top and height, and the caller leaves top/bottom unset. */
|
||||
rows = false
|
||||
): CSSProperties | null {
|
||||
const [box, setBox] = useState<{ left: number; top: number; width: number; height: number; animate: boolean } | null>(null);
|
||||
const [box, setBox] = useState<{ x: number; y: number; width: number; height: number; animate: boolean } | null>(
|
||||
null
|
||||
);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const track = trackRef && 'current' in trackRef ? trackRef.current : trackRef;
|
||||
const track = trackRef instanceof HTMLElement ? trackRef : (trackRef?.current ?? null);
|
||||
if (!track) return;
|
||||
const measure = () => {
|
||||
const active = track.querySelector<HTMLElement>(selector);
|
||||
@@ -34,8 +37,8 @@ export function useActivePill(
|
||||
return;
|
||||
}
|
||||
setBox((prev) => ({
|
||||
left: active.offsetLeft,
|
||||
top: active.offsetTop,
|
||||
x: active.offsetLeft,
|
||||
y: active.offsetTop,
|
||||
width: active.offsetWidth,
|
||||
height: active.offsetHeight,
|
||||
animate: prev !== null,
|
||||
@@ -46,14 +49,12 @@ export function useActivePill(
|
||||
const observer = new ResizeObserver(measure);
|
||||
observer.observe(track);
|
||||
return () => observer.disconnect();
|
||||
// The caller names what moves the active item; the ref and selector are stable.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, deps);
|
||||
}, [trackRef, selector, key]);
|
||||
|
||||
if (!box) return null;
|
||||
const transition = box.animate ? 'transform 320ms var(--ease-drawer), width 320ms var(--ease-drawer)' : 'none';
|
||||
if (rows) {
|
||||
return { top: 0, width: box.width, height: box.height, transform: `translate(${box.left}px, ${box.top}px)`, transition };
|
||||
return { top: 0, width: box.width, height: box.height, transform: `translate(${box.x}px, ${box.y}px)`, transition };
|
||||
}
|
||||
return { width: box.width, transform: `translateX(${box.left}px)`, transition };
|
||||
return { width: box.width, transform: `translateX(${box.x}px)`, transition };
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { PointerEvent as ReactPointerEvent, RefObject } from 'react';
|
||||
import { useCallback, useEffect, useRef } from 'react';
|
||||
import type { MutableRefObject, PointerEvent as ReactPointerEvent, RefObject } from 'react';
|
||||
import { useCallback, useEffect, useLayoutEffect, useRef } from 'react';
|
||||
|
||||
/**
|
||||
* Drag-to-dismiss for the docked bottom sheet, the way a native sheet takes it.
|
||||
@@ -32,7 +32,7 @@ const SAMPLE_MS = 80;
|
||||
/** Upward pull: a fraction of the travel, capped, as a stretch rather than a move. */
|
||||
const STRETCH = 0.2;
|
||||
const STRETCH_MAX = 20;
|
||||
export const SPRING_BACK = 'transform 280ms var(--ease-drawer)';
|
||||
const SPRING_BACK = 'transform 280ms var(--ease-drawer)';
|
||||
|
||||
/** Controls that own a downward finger themselves. */
|
||||
const OWNS_GESTURE =
|
||||
@@ -77,7 +77,9 @@ export function useSheetDrag({ enabled, panelRef, onDismiss }: SheetDragOptions)
|
||||
const drag = useRef<Drag | null>(null);
|
||||
const frame = useRef(0);
|
||||
const latest = useRef(onDismiss);
|
||||
latest.current = onDismiss;
|
||||
useLayoutEffect(() => {
|
||||
latest.current = onDismiss;
|
||||
});
|
||||
|
||||
const write = useCallback(
|
||||
(y: number, transition: string) => {
|
||||
@@ -163,111 +165,7 @@ export function useSheetDrag({ enabled, panelRef, onDismiss }: SheetDragOptions)
|
||||
useEffect(() => {
|
||||
const panel = panelRef.current;
|
||||
if (!enabled || !panel) return;
|
||||
/** Set by a claimed drag: the click the browser sends after it is not a tap. */
|
||||
let swallowClick = false;
|
||||
|
||||
const begin = (x: number, y: number, t: number, target: EventTarget | null): boolean => {
|
||||
const el = target as Element | null;
|
||||
if (el?.closest?.('[data-sheet-grab]') || el?.closest?.(OWNS_GESTURE)) return false;
|
||||
swallowClick = false;
|
||||
drag.current = { y0: y, x0: x, samples: [{ y, t }], claimed: false, scroller: nearestScroller(target, panel) };
|
||||
return true;
|
||||
};
|
||||
/** False once the gesture is not ours, so the caller lets it go. */
|
||||
const advance = (x: number, y: number, t: number): boolean => {
|
||||
const d = drag.current;
|
||||
if (!d) return false;
|
||||
if (!d.claimed) {
|
||||
const dy = y - d.y0;
|
||||
const dx = x - d.x0;
|
||||
if (Math.abs(dy) <= CLASSIFY_PX && Math.abs(dx) <= CLASSIFY_PX) return true;
|
||||
const atTop = !d.scroller || d.scroller.scrollTop <= 0;
|
||||
if (!(dy > 0 && Math.abs(dy) > Math.abs(dx) * AXIS_BIAS && atTop)) {
|
||||
drag.current = null;
|
||||
return false;
|
||||
}
|
||||
d.claimed = true;
|
||||
// Measured from here, so the sheet does not jump by the classify slop.
|
||||
d.y0 = y;
|
||||
d.samples = [{ y, t }];
|
||||
}
|
||||
sample(d, y, t);
|
||||
follow(y - d.y0);
|
||||
return true;
|
||||
};
|
||||
const finish = (y: number | undefined) => {
|
||||
const d = drag.current;
|
||||
drag.current = null;
|
||||
if (!d?.claimed) return;
|
||||
swallowClick = true;
|
||||
const last = d.samples[d.samples.length - 1];
|
||||
release(d, y ?? last.y);
|
||||
};
|
||||
|
||||
const onTouchStart = (e: TouchEvent) => {
|
||||
if (e.touches.length !== 1) {
|
||||
drag.current = null;
|
||||
return;
|
||||
}
|
||||
const t = e.touches[0];
|
||||
begin(t.clientX, t.clientY, e.timeStamp, e.target);
|
||||
};
|
||||
const onTouchMove = (e: TouchEvent) => {
|
||||
if (!drag.current || e.touches.length !== 1) return;
|
||||
const t = e.touches[0];
|
||||
if (advance(t.clientX, t.clientY, e.timeStamp) && drag.current?.claimed && e.cancelable) e.preventDefault();
|
||||
};
|
||||
const onTouchEnd = (e: TouchEvent) => finish(e.changedTouches[0]?.clientY);
|
||||
|
||||
// Touch has its own path above: a touch pointer is cancelled the moment the
|
||||
// browser starts scrolling, so only mouse and pen come through here.
|
||||
const onPointerDown = (e: PointerEvent) => {
|
||||
if (e.pointerType === 'touch' || e.button !== 0) return;
|
||||
if (!begin(e.clientX, e.clientY, e.timeStamp, e.target)) return;
|
||||
window.addEventListener('pointermove', onPointerMove);
|
||||
window.addEventListener('pointerup', onPointerUp);
|
||||
window.addEventListener('pointercancel', onPointerUp);
|
||||
};
|
||||
const onPointerMove = (e: PointerEvent) => {
|
||||
if (!advance(e.clientX, e.clientY, e.timeStamp)) {
|
||||
stopPointer();
|
||||
return;
|
||||
}
|
||||
// No text selection while the sheet is being pulled.
|
||||
if (drag.current?.claimed) e.preventDefault();
|
||||
};
|
||||
const onPointerUp = (e: PointerEvent) => {
|
||||
stopPointer();
|
||||
finish(e.type === 'pointercancel' ? undefined : e.clientY);
|
||||
};
|
||||
const stopPointer = () => {
|
||||
window.removeEventListener('pointermove', onPointerMove);
|
||||
window.removeEventListener('pointerup', onPointerUp);
|
||||
window.removeEventListener('pointercancel', onPointerUp);
|
||||
};
|
||||
const onClickCapture = (e: MouseEvent) => {
|
||||
if (!swallowClick) return;
|
||||
swallowClick = false;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
};
|
||||
|
||||
panel.addEventListener('touchstart', onTouchStart, { passive: true });
|
||||
panel.addEventListener('touchmove', onTouchMove, { passive: false });
|
||||
panel.addEventListener('touchend', onTouchEnd, { passive: true });
|
||||
panel.addEventListener('touchcancel', onTouchEnd, { passive: true });
|
||||
panel.addEventListener('pointerdown', onPointerDown);
|
||||
panel.addEventListener('click', onClickCapture, true);
|
||||
return () => {
|
||||
cancelAnimationFrame(frame.current);
|
||||
stopPointer();
|
||||
panel.removeEventListener('touchstart', onTouchStart);
|
||||
panel.removeEventListener('touchmove', onTouchMove);
|
||||
panel.removeEventListener('touchend', onTouchEnd);
|
||||
panel.removeEventListener('touchcancel', onTouchEnd);
|
||||
panel.removeEventListener('pointerdown', onPointerDown);
|
||||
panel.removeEventListener('click', onClickCapture, true);
|
||||
};
|
||||
return attachContentDrag(panel, drag, frame, follow, release);
|
||||
}, [enabled, panelRef, follow, release]);
|
||||
|
||||
return {
|
||||
@@ -280,3 +178,121 @@ export function useSheetDrag({ enabled, panelRef, onDismiss }: SheetDragOptions)
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The content's half of the drag: a finger (touch events) or a mouse or pen
|
||||
* (pointer events), claimed on the first move or let go. Returns the detach.
|
||||
*/
|
||||
function attachContentDrag(
|
||||
panel: HTMLElement,
|
||||
drag: MutableRefObject<Drag | null>,
|
||||
frame: MutableRefObject<number>,
|
||||
follow: (dy: number) => void,
|
||||
release: (d: Drag, lastY: number) => void
|
||||
): () => void {
|
||||
/** Set by a claimed drag: the click the browser sends after it is not a tap. */
|
||||
let swallowClick = false;
|
||||
|
||||
const begin = (x: number, y: number, t: number, target: EventTarget | null): boolean => {
|
||||
const el = target as Element | null;
|
||||
if (el?.closest?.('[data-sheet-grab]') || el?.closest?.(OWNS_GESTURE)) return false;
|
||||
swallowClick = false;
|
||||
drag.current = { y0: y, x0: x, samples: [{ y, t }], claimed: false, scroller: nearestScroller(target, panel) };
|
||||
return true;
|
||||
};
|
||||
/** False once the gesture is not ours, so the caller lets it go. */
|
||||
const advance = (x: number, y: number, t: number): boolean => {
|
||||
const d = drag.current;
|
||||
if (!d) return false;
|
||||
if (!d.claimed) {
|
||||
const dy = y - d.y0;
|
||||
const dx = x - d.x0;
|
||||
if (Math.abs(dy) <= CLASSIFY_PX && Math.abs(dx) <= CLASSIFY_PX) return true;
|
||||
const atTop = !d.scroller || d.scroller.scrollTop <= 0;
|
||||
if (!(dy > 0 && Math.abs(dy) > Math.abs(dx) * AXIS_BIAS && atTop)) {
|
||||
drag.current = null;
|
||||
return false;
|
||||
}
|
||||
d.claimed = true;
|
||||
// Measured from here, so the sheet does not jump by the classify slop.
|
||||
d.y0 = y;
|
||||
d.samples = [{ y, t }];
|
||||
}
|
||||
sample(d, y, t);
|
||||
follow(y - d.y0);
|
||||
return true;
|
||||
};
|
||||
const finish = (y: number | undefined) => {
|
||||
const d = drag.current;
|
||||
drag.current = null;
|
||||
if (!d?.claimed) return;
|
||||
swallowClick = true;
|
||||
const last = d.samples[d.samples.length - 1];
|
||||
release(d, y ?? last.y);
|
||||
};
|
||||
|
||||
const onTouchStart = (e: TouchEvent) => {
|
||||
if (e.touches.length !== 1) {
|
||||
drag.current = null;
|
||||
return;
|
||||
}
|
||||
const t = e.touches[0];
|
||||
begin(t.clientX, t.clientY, e.timeStamp, e.target);
|
||||
};
|
||||
const onTouchMove = (e: TouchEvent) => {
|
||||
if (!drag.current || e.touches.length !== 1) return;
|
||||
const t = e.touches[0];
|
||||
if (advance(t.clientX, t.clientY, e.timeStamp) && drag.current?.claimed && e.cancelable) e.preventDefault();
|
||||
};
|
||||
const onTouchEnd = (e: TouchEvent) => finish(e.changedTouches[0]?.clientY);
|
||||
|
||||
// Touch has its own path above: a touch pointer is cancelled the moment the
|
||||
// browser starts scrolling, so only mouse and pen come through here.
|
||||
const onPointerDown = (e: PointerEvent) => {
|
||||
if (e.pointerType === 'touch' || e.button !== 0) return;
|
||||
if (!begin(e.clientX, e.clientY, e.timeStamp, e.target)) return;
|
||||
window.addEventListener('pointermove', onPointerMove);
|
||||
window.addEventListener('pointerup', onPointerUp);
|
||||
window.addEventListener('pointercancel', onPointerUp);
|
||||
};
|
||||
const onPointerMove = (e: PointerEvent) => {
|
||||
if (!advance(e.clientX, e.clientY, e.timeStamp)) {
|
||||
stopPointer();
|
||||
return;
|
||||
}
|
||||
// No text selection while the sheet is being pulled.
|
||||
if (drag.current?.claimed) e.preventDefault();
|
||||
};
|
||||
const onPointerUp = (e: PointerEvent) => {
|
||||
stopPointer();
|
||||
finish(e.type === 'pointercancel' ? undefined : e.clientY);
|
||||
};
|
||||
const stopPointer = () => {
|
||||
window.removeEventListener('pointermove', onPointerMove);
|
||||
window.removeEventListener('pointerup', onPointerUp);
|
||||
window.removeEventListener('pointercancel', onPointerUp);
|
||||
};
|
||||
const onClickCapture = (e: MouseEvent) => {
|
||||
if (!swallowClick) return;
|
||||
swallowClick = false;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
};
|
||||
|
||||
panel.addEventListener('touchstart', onTouchStart, { passive: true });
|
||||
panel.addEventListener('touchmove', onTouchMove, { passive: false });
|
||||
panel.addEventListener('touchend', onTouchEnd, { passive: true });
|
||||
panel.addEventListener('touchcancel', onTouchEnd, { passive: true });
|
||||
panel.addEventListener('pointerdown', onPointerDown);
|
||||
panel.addEventListener('click', onClickCapture, true);
|
||||
return () => {
|
||||
cancelAnimationFrame(frame.current);
|
||||
stopPointer();
|
||||
panel.removeEventListener('touchstart', onTouchStart);
|
||||
panel.removeEventListener('touchmove', onTouchMove);
|
||||
panel.removeEventListener('touchend', onTouchEnd);
|
||||
panel.removeEventListener('touchcancel', onTouchEnd);
|
||||
panel.removeEventListener('pointerdown', onPointerDown);
|
||||
panel.removeEventListener('click', onClickCapture, true);
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user