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:
Maurice
2026-11-06 18:24:25 +01:00
parent f81fe8cb17
commit b7951baf23
75 changed files with 645 additions and 475 deletions
@@ -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() }));
+4 -30
View File
@@ -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);
+1 -1
View File
@@ -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;
}
+12 -11
View File
@@ -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 };
}
+125 -109
View File
@@ -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);
};
}
+4 -2
View File
@@ -1,4 +1,4 @@
import { useEffect, useRef } from 'react';
import { useEffect, useLayoutEffect, useRef } from 'react';
/**
* The overlays open on screen, newest last, so a way back closes the one on
@@ -25,7 +25,9 @@ export function hasOpenOverlay(): boolean {
/** Registers an overlay while `open`, with the way it closes. */
export function useOverlay(open: boolean, close: Close): void {
const closeRef = useRef(close);
closeRef.current = close;
useLayoutEffect(() => {
closeRef.current = close;
});
useEffect(() => {
if (!open) return;
const entry = { id: nextId++, close: () => closeRef.current() };
+11 -11
View File
@@ -1,5 +1,5 @@
import { act, renderHook } from '@testing-library/react';
import type { Location, NavigationType } from 'react-router';
import { NavigationType, type Location } from 'react-router';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { skipNextRouteTransition, transitionKind, useRouteTransition } from './routeTransition';
@@ -7,11 +7,11 @@ const loc = (pathname: string, key = pathname): Location => ({ pathname, key, se
describe('transitionKind', () => {
it('slides deeper pages forward and back, cross-fades between sections', () => {
expect(transitionKind(loc('/dashboard'), loc('/trips/4'), 'PUSH')).toBe('forward');
expect(transitionKind(loc('/trips/4'), loc('/dashboard'), 'POP')).toBe('back');
expect(transitionKind(loc('/trips/4'), loc('/trips/4/files'), 'PUSH')).toBe('forward');
expect(transitionKind(loc('/dashboard'), loc('/atlas'), 'PUSH')).toBe('tab');
expect(transitionKind(loc('/vacay'), loc('/dashboard'), 'POP')).toBe('tab');
expect(transitionKind(loc('/dashboard'), loc('/trips/4'), NavigationType.Push)).toBe('forward');
expect(transitionKind(loc('/trips/4'), loc('/dashboard'), NavigationType.Pop)).toBe('back');
expect(transitionKind(loc('/trips/4'), loc('/trips/4/files'), NavigationType.Push)).toBe('forward');
expect(transitionKind(loc('/dashboard'), loc('/atlas'), NavigationType.Push)).toBe('tab');
expect(transitionKind(loc('/vacay'), loc('/dashboard'), NavigationType.Pop)).toBe('tab');
});
});
@@ -37,14 +37,14 @@ describe('useRouteTransition', () => {
function render(initial: Location, enabled = true) {
return renderHook(
({ location, type }: { location: Location; type: NavigationType }) => useRouteTransition(location, type, enabled),
{ initialProps: { location: initial, type: 'PUSH' as NavigationType } }
{ initialProps: { location: initial, type: NavigationType.Push } }
);
}
it('swaps the page inside a view transition and marks its direction', async () => {
const hook = render(loc('/dashboard'));
await act(async () => {
hook.rerender({ location: loc('/trips/1'), type: 'PUSH' });
hook.rerender({ location: loc('/trips/1'), type: NavigationType.Push });
});
expect(start).toHaveBeenCalledTimes(1);
expect(hook.result.current.pathname).toBe('/trips/1');
@@ -54,16 +54,16 @@ describe('useRouteTransition', () => {
const hook = render(loc('/trips/1'));
skipNextRouteTransition();
await act(async () => {
hook.rerender({ location: loc('/dashboard'), type: 'POP' });
hook.rerender({ location: loc('/dashboard'), type: NavigationType.Pop });
});
await act(async () => {
hook.rerender({ location: { ...loc('/dashboard', 'k2'), search: '?f=1' }, type: 'PUSH' });
hook.rerender({ location: { ...loc('/dashboard', 'k2'), search: '?f=1' }, type: NavigationType.Push });
});
expect(start).not.toHaveBeenCalled();
expect(hook.result.current.key).toBe('k2');
const off = render(loc('/dashboard'), false);
off.rerender({ location: loc('/trips/2'), type: 'PUSH' });
off.rerender({ location: loc('/trips/2'), type: NavigationType.Push });
expect(off.result.current.pathname).toBe('/trips/2');
expect(start).not.toHaveBeenCalled();
});
+9 -8
View File
@@ -22,6 +22,9 @@ const SETTLE_MS = 800;
let skipNext = false;
let current: ViewTransition | null = null;
/** A newer navigation skipped this transition: its promises reject, and that is no error. */
function skippedByNewer(): void {}
/** The edge-swipe back gesture already slid the page away: the next change goes without a transition. */
export function skipNextRouteTransition(): void {
skipNext = true;
@@ -85,14 +88,12 @@ export function useRouteTransition(location: Location, navigationType: Navigatio
});
current = transition;
// A newer navigation skips this one: both promises then reject, which is no error.
transition.ready.catch(() => {});
void transition.finished
.catch(() => {})
.finally(() => {
// Only the newest transition clears the direction, or a skipped one would
// take it away from the one that replaced it.
if (current === transition) delete root.dataset.routeTransition;
});
transition.ready.catch(skippedByNewer);
void transition.finished.catch(skippedByNewer).finally(() => {
// Only the newest transition clears the direction, or a skipped one would
// take it away from the one that replaced it.
if (current === transition) delete root.dataset.routeTransition;
});
}, [location, navigationType, enabled]);
return enabled ? shown : location;
@@ -33,7 +33,7 @@ export default function MAdminResetMfaSheet({ open, onClose, user, onReset, t }:
<MSheet open={open} onClose={onClose} ariaLabel={t('admin.mfa.reset')}>
<MAdminSheetFrame
icon={<ShieldOff size={19} strokeWidth={1.8} />}
title={t('admin.mfa.reset')}
title={t('admin.mfa.reset')}
onClose={onClose}
footer={
<>
@@ -44,7 +44,7 @@ function AddCountrySheet({
<MSheet open={open} onClose={close} variant="card" material="glass" ariaLabel={t('schoolCatalog.addCountry')}>
<MAdminSheetFrame
icon={<GraduationCap size={19} strokeWidth={1.8} />}
title={t('schoolCatalog.addCountry')}
title={t('schoolCatalog.addCountry')}
onClose={close}
footer={
<>
@@ -120,7 +120,7 @@ function RegionSheet({ region, busy, offline, error, onClose, onSave }: EditorPr
>
<MAdminSheetFrame
icon={<GraduationCap size={19} strokeWidth={1.8} />}
title={name.trim() || t('schoolCatalog.region')}
title={name.trim() || t('schoolCatalog.region')}
onClose={() => {
if (!busy) onClose();
}}
@@ -213,7 +213,11 @@ function MCollTourSheet({
return (
<MSheet open={takeOver.open} onClose={takeOver.close} material="glass" ariaLabel={title}>
<SheetHeader
icon={<Route size={19} strokeWidth={1.8} />} title={title} onClose={takeOver.close} closeLabel={t('common.close')} />
icon={<Route size={19} strokeWidth={1.8} />}
title={title}
onClose={takeOver.close}
closeLabel={t('common.close')}
/>
<div className="min-h-0 flex-1 overflow-y-auto px-[18px] pb-[18px] pt-[14px]">
{tour && (
<p className="mb-3 mt-0 font-geist text-m-muted" style={fs(11)}>
@@ -300,13 +300,13 @@ export default function MTripShell({
// The active day's pill glides to the next chip rather than jumping there.
// A booking document shared to TREK, and this trip picked for it: open the import.
const sharedTripId = useSharedImportStore(s => s.tripId)
const { setBookingImportKind, setShowBookingImport } = planner
useEffect(() => {
if (sharedTripId == null || sharedTripId !== Number(tripId)) return
planner.setBookingImportKind('bookings')
planner.setShowBookingImport(true)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [sharedTripId, tripId])
const dayPill = useActivePill(dayRail, '[aria-current="true"]', [railDayId, days, dayRail, language])
setBookingImportKind('bookings')
setShowBookingImport(true)
}, [sharedTripId, tripId, setBookingImportKind, setShowBookingImport])
const dayPill = useActivePill(dayRail, '[aria-current="true"]', `${railDayId}:${days.map(d => d.id).join(',')}:${language}`)
const trTab = planner.activeTab
@@ -516,7 +516,7 @@ export default function MTripShell({
{dayPill && (
<span
aria-hidden="true"
className="pointer-events-none absolute bottom-[3px] left-0 top-[3px] rounded-full bg-m-act shadow-[0_6px_16px_-6px_rgba(0,0,0,.4)]"
className="pointer-events-none absolute bottom-[3px] left-0 top-[3px] rounded-full bg-m-act shadow-[0_6px_16px_-6px_rgba(0,0,0,.4)]" // rtl-lint-disable: moved by the measured offsetLeft (useActivePill)
style={dayPill}
/>
)}
@@ -271,7 +271,9 @@ export default function MMapArea({ planner, shell }: MMapAreaProps) {
* store write and on every sheet it opens, this handler's own included.
*/
const latest = useRef({ planner, shell, stage })
latest.current = { planner, shell, stage }
useLayoutEffect(() => {
latest.current = { planner, shell, stage }
})
const openStagePin = useCallback((placeId?: number) => {
const { planner: now, shell: chrome, stage: card } = latest.current
const stop = placeId == null ? null : firstStopOfPlace(card ? [card] : now.roadtripRoutes.days, placeId)
@@ -24,7 +24,8 @@ import type { RouteSegment } from '../../../../types'
import type { Assignment } from '../../../../types'
import type { ReactNode } from 'react'
import { useSettingsStore } from '../../../../store/settingsStore'
import MRouteAppsSheet, { openRouteTarget } from './MRouteAppsSheet'
import MRouteAppsSheet from './MRouteAppsSheet'
import { openRouteTarget } from './openRouteTarget'
import MDayPager from '../../../components/MDayPager'
import { useDayPreviewStore } from '../../../dayPreviewStore'
@@ -2,13 +2,8 @@ import { ChevronRight, MapPinned } from 'lucide-react';
import type { DayRouteTarget } from '../../../../components/Planner/dayRouteApps';
import type { TranslationFn } from '../../../../types';
import MSheet from '../../../components/MSheet';
import { TileHeader } from '../sheets/MTripSheetUi'
/** Opens a target: a web link in a new tab (the app takes it over), geo: in place. */
export function openRouteTarget(target: DayRouteTarget): void {
if (target.url.startsWith('geo:')) window.location.assign(target.url);
else window.open(target.url, '_blank', 'noopener,noreferrer');
}
import { TileHeader } from '../sheets/MTripSheetUi';
import { openRouteTarget } from './openRouteTarget';
/**
* The plan's one Maps button, asked: which app should get the day. A docked
@@ -0,0 +1,7 @@
import type { DayRouteTarget } from '../../../../components/Planner/dayRouteApps';
/** Opens a target: a web link in a new tab (the app takes it over), geo: in place. */
export function openRouteTarget(target: DayRouteTarget): void {
if (target.url.startsWith('geo:')) window.location.assign(target.url);
else window.open(target.url, '_blank', 'noopener,noreferrer');
}
@@ -126,7 +126,7 @@ export default function MRoadtripTab({ planner, shell }: MTripTabPanelProps) {
* ones either side. Each page reads its own stage, so the one that slides in is
* exactly the one that lands.
*/
function RoadtripStagePage({ planner, shell, dayId: pageDayId, alts, chrome }: MTripTabPanelProps & {
function RoadtripStagePage({ planner, shell, dayId: pageDayId, alts, chrome }: Omit<MTripTabPanelProps, 'tab'> & {
dayId: number | null
alts: ReturnType<typeof useMRtAlternatives>
chrome: RowChrome
@@ -1,14 +1,9 @@
import { X } from 'lucide-react';
import { createContext, useContext } from 'react';
import { useContext } from 'react';
import type { DetailShellProps } from '../../../../components/shared/DetailShell';
import MIconBtn from '../../../components/MIconBtn';
import MSheet from '../../../components/MSheet';
/**
* Whether the tour sheet is open (false while it slides away with the tour it
* showed last) and the tour's name, which names the dialog.
*/
export const TourSheetOpen = createContext<{ open: boolean; label: string }>({ open: true, label: '' });
import { TourSheetOpen } from './tourSheetOpen';
/**
* The phone's frame for the tour detail: the desktop dialog's head, sections
@@ -16,6 +16,7 @@ import { useSearchParams } from 'react-router'
import { isTransportReservationType } from '@trek/shared'
import { useBookingLink } from '../../../../hooks/useBookingLink'
import { bookingFacts, stayStats } from '../../../../components/Planner/bookings/bookingFacts'
import { parseMeta } from '../../../../components/Planner/bookings/bookingsModel'
import { Eyebrow, INNER_CLS, StatBox, TileHeader, displayTime } from './MTripSheetUi'
interface TransportSheetPayload {
@@ -178,7 +179,7 @@ export default function MTransportSheet({ planner, shell }: MTripSheetsProps) {
const hotelStats = res.type === 'hotel'
? stayStats(
bookingFacts(res, { t, locale, timeFormat, days: planner.days, assignmentLookup: {}, hasLinkedCost: false }),
meta,
parseMeta(res),
t,
locale,
)
@@ -32,7 +32,8 @@ import MRtInfoSheet from '../roadtrip/MRtInfoSheet'
import MRtCorridorSheet from '../roadtrip/MRtCorridorSheet'
import MRtDraftSheet from '../roadtrip/MRtDraftSheet'
import type { MTripSheetsProps } from '../MTripShell'
import MTourDetailShell, { TourSheetOpen } from './MTourDetailShell'
import MTourDetailShell from './MTourDetailShell'
import { TourSheetOpen } from './tourSheetOpen'
import { useLastOpen } from '../../../../components/shared/usePresence'
/**
@@ -0,0 +1,7 @@
import { createContext } from 'react';
/**
* Whether the tour sheet is open (false while it slides away with the tour it
* showed last) and the tour's name, which names the dialog.
*/
export const TourSheetOpen = createContext<{ open: boolean; label: string }>({ open: true, label: '' });
+3 -3
View File
@@ -150,7 +150,7 @@ export default function MVacay() {
aria-haspopup="dialog"
className={GLASS_PILL_BUTTON}
>
<span className="flex -space-x-1">
<span className="flex [&>*+*]:-ms-1">
{v.users.slice(0, 4).map(u => (
<span
key={u.id}
@@ -509,11 +509,11 @@ function FuseInfo({ icon: Icon, text }: { icon: LucideIcon; text: string }) {
/** The editor's month picker: the window's twelve months on one glass surface. */
function MonthQuickNav({ names, slot, onPick }: { names: string[]; slot: number; onPick: (slot: number) => void }) {
const trackRef = useRef<HTMLDivElement>(null)
const pill = useActivePill(trackRef, '[data-active="true"]', [slot, names.length], true)
const pill = useActivePill(trackRef, '[data-active="true"]', `${slot}:${names.length}`, true)
return (
<div className="mb-[10px] rounded-[22px] border border-[color:var(--m-gbr)] bg-[color:var(--m-glass)] p-1.5 shadow-[0_8px_24px_-16px_rgba(0,0,0,.3)] backdrop-blur-[24px] backdrop-saturate-[1.7]">
<div ref={trackRef} className="relative grid grid-cols-6 gap-1">
{pill && <span aria-hidden="true" className="pointer-events-none absolute left-0 rounded-full bg-m-act" style={pill} />}
{/* rtl-lint-disable: the pill moves by the measured offsetLeft (useActivePill) */}{pill && <span aria-hidden="true" className="pointer-events-none absolute left-0 rounded-full bg-m-act" style={pill} />}
{names.map((name, i) => (
<button
key={i}
+7 -8
View File
@@ -12,6 +12,11 @@ import {
useDefaultVacayPerson, useVacayCalendarLogic, vacayWindowShape, type VacayMode,
} from '../../../components/Vacay/useVacayCalendarLogic'
/** The full name of a month in the user's language ("März"). */
function longMonthName(locale: string, m: { year: number; month: number }): string {
return new Intl.DateTimeFormat(locale, { month: 'long' }).format(new Date(m.year, m.month, 1))
}
export type MVacayView = 'grid' | 'edit'
export type MVacayMode = VacayMode
export type MVacaySheet = 'invite' | 'settings' | 'share' | 'people' | 'legend' | null
@@ -91,17 +96,11 @@ export function useMVacay() {
return months.map(({ year, month }) => fmt.format(new Date(year, month, 1)))
}, [locale, months])
const monthNameLong = useMemo(
() => new Intl.DateTimeFormat(locale, { month: 'long' }).format(new Date(activeMonth.year, activeMonth.month, 1)),
[locale, activeMonth],
)
const monthNameLong = useMemo(() => longMonthName(locale, activeMonth), [locale, activeMonth])
// The pagers draw the neighbours of the open month and year too: the long name
// of any slot of the window, and the twelve months of any year.
const monthNameLongFor = useCallback((slot: number) => {
const m = months[slot] ?? months[0]
return new Intl.DateTimeFormat(locale, { month: 'long' }).format(new Date(m.year, m.month, 1))
}, [locale, months])
const monthNameLongFor = useCallback((slot: number) => longMonthName(locale, months[slot] ?? months[0]), [locale, months])
const monthsFor = useCallback((year: number) => windowMonths(year, yearSettings), [yearSettings])
const selectedUser = users.find(u => u.id === selectedUserId)
+8 -3
View File
@@ -1,4 +1,4 @@
import { useEffect, useRef, useState, type RefObject } from 'react';
import { useEffect, useLayoutEffect, useRef, useState, type RefObject } from 'react';
import { tickHaptic } from '../native/haptics';
import { hasOpenOverlay } from './overlayStack';
@@ -10,6 +10,9 @@ const MIN_SPIN_MS = 450;
export type PullState = { distance: number; refreshing: boolean; armed: boolean };
/** The screen's own refresh reports its failures (a toast, its error state); the pull only lets go. */
function refreshFailed(): void {}
/**
* Pull-to-refresh on a page whose scroller is the window, as the mobile
* dashboard is. A downward drag that starts at the very top moves `contentRef`
@@ -29,7 +32,9 @@ export function usePullToRefresh(
): PullState {
const [state, setState] = useState<PullState>({ distance: 0, refreshing: false, armed: false });
const refreshRef = useRef(onRefresh);
refreshRef.current = onRefresh;
useLayoutEffect(() => {
refreshRef.current = onRefresh;
});
useEffect(() => {
if (!enabled) return;
@@ -98,7 +103,7 @@ export function usePullToRefresh(
const began = Date.now();
void Promise.resolve()
.then(() => refreshRef.current())
.catch(() => {})
.catch(refreshFailed)
.then(() => new Promise((resolve) => setTimeout(resolve, Math.max(0, MIN_SPIN_MS - (Date.now() - began)))))
.then(() => {
busy = false;