mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-02 09:22:15 +00:00
feat(native): swipe rows, long-press menus, placeholders while loading, fading pictures, iOS bounce and app icon quick actions
Packing items, tasks and expenses swipe sideways to their actions, as in Mail or Reminders: done or open one way, delete and edit the other, the first one run by a full swipe. They are second ways to what each row already offers; an expense still asks before it goes. A long press on a trip card lifts it and opens its menu with the card's own actions. Plain confirmations in MConfirmSheet now also ask through the system where the app can. Lists, the atlas and a journey show grey placeholders in their shape while loading instead of a spinner in an empty screen (MSkeleton); buttons keep theirs. A picture still loading fades in once it is there; one from the cache shows at once. In the iOS app the page bounces at its ends again, except on screens with pull-to-refresh, whose pull it would race; Android keeps its stretch off. On iOS a long press on the app icon offers "New trip" and the trip coming up by its name, set by the UI in its language (TrekShell.setQuickActions, feature quickActions), and a tap opens it, also from a cold start. The app's own CSS moves out of index.css into native/nativeApp.css, which had outgrown its size budget.
This commit is contained in:
@@ -0,0 +1,26 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { fireEvent, render, screen } from '../../../tests/helpers/render';
|
||||
import MContextMenu from './MContextMenu';
|
||||
|
||||
describe('MContextMenu', () => {
|
||||
it('FE-MOB-CTXMENU-001: names what it is about, lists the actions, and closes before running one', () => {
|
||||
const onClose = vi.fn();
|
||||
const onDelete = vi.fn(() => expect(onClose).toHaveBeenCalled());
|
||||
render(
|
||||
<MContextMenu
|
||||
open
|
||||
title="Lisbon"
|
||||
onClose={onClose}
|
||||
actions={[
|
||||
{ key: 'edit', label: 'Edit', icon: <span />, onClick: vi.fn() },
|
||||
{ key: 'delete', label: 'Delete', icon: <span />, onClick: onDelete },
|
||||
]}
|
||||
/>
|
||||
);
|
||||
expect(screen.getByText('Lisbon')).toBeTruthy();
|
||||
const del = screen.getByText('Delete').closest('button') as HTMLElement;
|
||||
expect(del.className).toContain('--m-st-danger');
|
||||
fireEvent.click(del);
|
||||
expect(onDelete).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,53 @@
|
||||
import type { ReactElement } from 'react';
|
||||
import MSheet from './MSheet';
|
||||
|
||||
/**
|
||||
* The menu a long press on a card opens (useLongPress): what it is about on
|
||||
* top, then its actions, the destructive one in red. The same actions the
|
||||
* card's own buttons offer, so this is a second way, never the only one.
|
||||
*/
|
||||
|
||||
export interface ContextAction {
|
||||
key: string;
|
||||
label: string;
|
||||
icon: ReactElement;
|
||||
onClick: () => void;
|
||||
}
|
||||
|
||||
interface MContextMenuProps {
|
||||
open: boolean;
|
||||
title: string;
|
||||
actions: ContextAction[];
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export default function MContextMenu({ open, title, actions, onClose }: MContextMenuProps) {
|
||||
return (
|
||||
<MSheet open={open} onClose={onClose} variant="bottom" wideWidth="compact" ariaLabel={title}>
|
||||
<div className="min-h-0 overflow-y-auto overscroll-contain p-[10px]">
|
||||
<div dir="auto" className="truncate px-[10px] pb-2 pt-1 text-caption font-semibold text-m-muted">
|
||||
{title}
|
||||
</div>
|
||||
{actions.map((action) => {
|
||||
const danger = action.key === 'delete';
|
||||
return (
|
||||
<button
|
||||
key={action.key}
|
||||
type="button"
|
||||
onClick={() => {
|
||||
onClose();
|
||||
action.onClick();
|
||||
}}
|
||||
className={`flex w-full items-center gap-[11px] rounded-xl px-[10px] py-[11px] text-start text-[0.84375rem] font-semibold active:bg-[color:var(--m-ic)] ${
|
||||
danger ? 'text-[color:var(--m-st-danger)]' : 'text-m-ink'
|
||||
}`}
|
||||
>
|
||||
<span className={`flex flex-none ${danger ? '' : 'text-m-muted'}`}>{action.icon}</span>
|
||||
<span className="min-w-0 flex-1 truncate">{action.label}</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</MSheet>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { render, screen } from '../../../tests/helpers/render';
|
||||
import MSkeleton from './MSkeleton';
|
||||
|
||||
describe('MSkeleton', () => {
|
||||
it('FE-MOB-SKELETON-001: is announced once as loading, its shapes hidden from a screen reader', () => {
|
||||
render(<MSkeleton variant="rows" count={3} />);
|
||||
const status = screen.getByRole('status');
|
||||
expect(status.getAttribute('aria-label')).toBeTruthy();
|
||||
const shapes = status.firstElementChild as HTMLElement;
|
||||
expect(shapes.getAttribute('aria-hidden')).toBe('true');
|
||||
expect(shapes.children).toHaveLength(3);
|
||||
});
|
||||
|
||||
it('FE-MOB-SKELETON-002: rows inside a card drop their own frame', () => {
|
||||
render(<MSkeleton variant="rows" count={2} framed={false} />);
|
||||
const first = screen.getByRole('status').firstElementChild?.firstElementChild as HTMLElement;
|
||||
expect(first.className).not.toContain('rounded-[14px]');
|
||||
expect(first.className).toContain('border-b');
|
||||
});
|
||||
|
||||
it('FE-MOB-SKELETON-003: does not pulse with reduced motion', () => {
|
||||
render(<MSkeleton variant="cards" count={1} />);
|
||||
expect(screen.getByRole('status').className).toContain('motion-reduce:animate-none');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,83 @@
|
||||
import { useTranslation } from '../../i18n';
|
||||
|
||||
/**
|
||||
* Grey stand-ins in the shape of what is loading, where a native app shows the
|
||||
* list before its content rather than a spinner in an empty screen: rows for a
|
||||
* list, cards for a feed, a cover and lines for a detail page, a plain surface
|
||||
* for a map. They pulse softly, and not at all with reduced motion. Announced
|
||||
* once as "Loading" for a screen reader; the shapes themselves are hidden from it.
|
||||
*/
|
||||
|
||||
export type MSkeletonVariant = 'rows' | 'cards' | 'detail' | 'map';
|
||||
|
||||
interface MSkeletonProps {
|
||||
variant: MSkeletonVariant;
|
||||
/** How many rows or cards (rows, cards). */
|
||||
count?: number;
|
||||
/** Rows as cards of their own (default), or as lines inside a card that already frames them. */
|
||||
framed?: boolean;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
const BLOCK = 'bg-[color:var(--m-ic)]';
|
||||
// Lines of different lengths read as text; equal ones read as a table.
|
||||
const WIDTHS = ['w-2/3', 'w-1/2', 'w-3/4', 'w-3/5'];
|
||||
|
||||
function Row({ i, framed }: { i: number; framed: boolean }) {
|
||||
const frame = framed
|
||||
? 'mb-2 rounded-[14px] border border-[color:var(--m-rowbr)] px-3 py-[10px]'
|
||||
: 'border-b border-[color:var(--m-rowbr)] py-3 last:border-b-0';
|
||||
return (
|
||||
<div className={`flex items-center gap-[11px] ${frame}`}>
|
||||
<span className={`h-9 w-9 flex-none rounded-[10px] ${BLOCK}`} />
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className={`block h-3 rounded-full ${BLOCK} ${WIDTHS[i % WIDTHS.length]}`} />
|
||||
<span className={`mt-2 block h-2.5 w-1/3 rounded-full ${BLOCK}`} />
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Card({ i }: { i: number }) {
|
||||
return (
|
||||
<div className="mb-3">
|
||||
<div className={`h-[180px] w-full rounded-[22px] ${BLOCK}`} />
|
||||
<span className={`mt-3 block h-3.5 rounded-full ${BLOCK} ${WIDTHS[i % WIDTHS.length]}`} />
|
||||
<span className={`mt-2 block h-2.5 w-1/3 rounded-full ${BLOCK}`} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Detail() {
|
||||
return (
|
||||
<div>
|
||||
<div className={`h-[300px] w-full ${BLOCK}`} />
|
||||
<div className="px-4 pt-5">
|
||||
<span className={`block h-5 w-2/3 rounded-full ${BLOCK}`} />
|
||||
<span className={`mt-3 block h-3 w-1/3 rounded-full ${BLOCK}`} />
|
||||
{WIDTHS.map((w) => (
|
||||
<span key={w} className={`mt-4 block h-3 rounded-full ${BLOCK} ${w}`} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function MSkeleton({ variant, count = 4, framed = true, className = '' }: MSkeletonProps) {
|
||||
const { t } = useTranslation();
|
||||
const items = Array.from({ length: count }, (_, i) => i);
|
||||
return (
|
||||
<div
|
||||
role="status"
|
||||
aria-label={t('common.loading')}
|
||||
className={`animate-pulse motion-reduce:animate-none ${className}`}
|
||||
>
|
||||
<div aria-hidden="true" className={variant === 'map' ? 'h-full' : undefined}>
|
||||
{variant === 'rows' && items.map((i) => <Row key={i} i={i} framed={framed} />)}
|
||||
{variant === 'cards' && items.map((i) => <Card key={i} i={i} />)}
|
||||
{variant === 'detail' && <Detail />}
|
||||
{variant === 'map' && <div className={`h-full w-full ${BLOCK}`} />}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
import { Check, Trash2 } from 'lucide-react';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { act, fireEvent, render, screen } from '../../../tests/helpers/render';
|
||||
import MSwipeRow from './MSwipeRow';
|
||||
|
||||
vi.mock('../../native/haptics', () => ({ tickHaptic: vi.fn() }));
|
||||
|
||||
/** jsdom has no Touch to build a TouchEvent from: an Event with the touches set on it, as MEdgeBack's test does. */
|
||||
function touch(el: Element, type: 'touchstart' | 'touchmove' | 'touchend', x = 0, y = 100) {
|
||||
const e = new Event(type, { bubbles: true, cancelable: true });
|
||||
Object.defineProperty(e, 'touches', { value: type === 'touchend' ? [] : [{ clientX: x, clientY: y }] });
|
||||
act(() => {
|
||||
el.dispatchEvent(e);
|
||||
});
|
||||
}
|
||||
|
||||
function setup() {
|
||||
const onDelete = vi.fn();
|
||||
const onDone = vi.fn();
|
||||
const onRowClick = vi.fn();
|
||||
render(
|
||||
<MSwipeRow
|
||||
leading={{ label: 'Done', icon: Check, tone: 'accent', onAction: onDone }}
|
||||
trailing={[{ label: 'Delete', icon: Trash2, tone: 'danger', onAction: onDelete }]}
|
||||
>
|
||||
<button type="button" onClick={onRowClick}>
|
||||
Sunscreen
|
||||
</button>
|
||||
</MSwipeRow>
|
||||
);
|
||||
const row = screen.getByText('Sunscreen').closest('div')?.parentElement as HTMLElement;
|
||||
return { row, onDelete, onDone, onRowClick };
|
||||
}
|
||||
|
||||
describe('MSwipeRow', () => {
|
||||
it('FE-MOB-SWIPE-001: shows no action buttons until the row is swiped', () => {
|
||||
setup();
|
||||
expect(screen.queryByText('Delete')).toBeNull();
|
||||
expect(screen.queryByText('Done')).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-MOB-SWIPE-002: a swipe towards the start opens the trailing action, a tap on it runs it', () => {
|
||||
const { row, onDelete } = setup();
|
||||
touch(row, 'touchstart', 200);
|
||||
touch(row, 'touchmove', 160);
|
||||
touch(row, 'touchmove', 120);
|
||||
touch(row, 'touchend');
|
||||
fireEvent.click(screen.getByText('Delete'));
|
||||
expect(onDelete).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('FE-MOB-SWIPE-003: a mostly vertical drag is a scroll and opens nothing', () => {
|
||||
const { row } = setup();
|
||||
touch(row, 'touchstart', 200, 100);
|
||||
touch(row, 'touchmove', 190, 160);
|
||||
touch(row, 'touchend');
|
||||
expect(screen.queryByText('Delete')).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-MOB-SWIPE-004: a tap on an open row closes it instead of opening the row', () => {
|
||||
const { row, onRowClick } = setup();
|
||||
touch(row, 'touchstart', 200);
|
||||
touch(row, 'touchmove', 160);
|
||||
touch(row, 'touchmove', 120);
|
||||
touch(row, 'touchend');
|
||||
fireEvent.click(screen.getByText('Sunscreen'));
|
||||
expect(onRowClick).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-MOB-SWIPE-005: a swipe that starts at the screen edge is left to the back gesture', () => {
|
||||
const { row } = setup();
|
||||
touch(row, 'touchstart', 10);
|
||||
touch(row, 'touchmove', 120);
|
||||
touch(row, 'touchend');
|
||||
expect(screen.queryByText('Done')).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-MOB-SWIPE-006: swiped through past most of the row, the first action runs at once', () => {
|
||||
const { row, onDelete } = setup();
|
||||
row.getBoundingClientRect = () => ({
|
||||
width: 360,
|
||||
height: 48,
|
||||
top: 0,
|
||||
left: 0,
|
||||
right: 360,
|
||||
bottom: 48,
|
||||
x: 0,
|
||||
y: 0,
|
||||
toJSON: () => ({}),
|
||||
});
|
||||
touch(row, 'touchstart', 330);
|
||||
touch(row, 'touchmove', 300);
|
||||
touch(row, 'touchmove', 60);
|
||||
touch(row, 'touchend');
|
||||
expect(onDelete).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,226 @@
|
||||
import type { LucideIcon } from 'lucide-react';
|
||||
import { type ReactNode, useEffect, useRef, useState } from 'react';
|
||||
import { tickHaptic } from '../../native/haptics';
|
||||
|
||||
/**
|
||||
* A list row that swipes sideways to show its actions, as in Mail or Reminders.
|
||||
*
|
||||
* Swiped towards the start it shows the trailing actions (delete, in red), the
|
||||
* other way the leading one (pack, done). Let go past half of them and the row
|
||||
* stays open on its buttons; swipe through to the far end and the first action
|
||||
* runs straight away, with a tick when the finger crosses that point. A tap
|
||||
* anywhere closes an open row, and opening one closes the one open before.
|
||||
*
|
||||
* The gesture claims only a clearly sideways drag, so the list still scrolls,
|
||||
* and none that starts at the screen's left edge, which goes back (MEdgeBack).
|
||||
* Every action here is a second way to something the row already offers, so
|
||||
* nothing is lost to a screen reader or a mouse: the buttons are hidden from
|
||||
* both until the row is open.
|
||||
*/
|
||||
|
||||
export interface SwipeAction {
|
||||
label: string;
|
||||
icon: LucideIcon;
|
||||
tone: 'danger' | 'accent' | 'neutral';
|
||||
onAction: () => void;
|
||||
}
|
||||
|
||||
interface MSwipeRowProps {
|
||||
/** Shown by a swipe towards the end of the line (to the right in LTR). */
|
||||
leading?: SwipeAction;
|
||||
/** Shown by a swipe towards the start; the first one is what a full swipe runs. */
|
||||
trailing?: SwipeAction[];
|
||||
disabled?: boolean;
|
||||
className?: string;
|
||||
/** The row's own background: it covers the buttons until the row moves, so it must match what is around it. */
|
||||
surface?: string;
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
const BUTTON_W = 76;
|
||||
const EDGE_PX = 24;
|
||||
const CLAIM_PX = 10;
|
||||
const AXIS_BIAS = 1.5;
|
||||
/** Past this share of the row's width a release runs the first action. */
|
||||
const FULL_SHARE = 0.62;
|
||||
|
||||
const TONE: Record<SwipeAction['tone'], string> = {
|
||||
danger: 'bg-danger text-white', // theme-lint-disable: white on the danger fill, as the delete buttons draw it
|
||||
accent: 'bg-m-act text-m-actfg',
|
||||
neutral: 'bg-[color:var(--m-faint)] text-white', // theme-lint-disable: white on the neutral action fill
|
||||
};
|
||||
|
||||
// The row open now, so opening another closes it.
|
||||
let closeOpenRow: (() => void) | null = null;
|
||||
|
||||
export default function MSwipeRow({
|
||||
leading,
|
||||
trailing = [],
|
||||
disabled = false,
|
||||
className = '',
|
||||
surface = 'bg-[color:var(--m-card)]',
|
||||
children,
|
||||
}: MSwipeRowProps) {
|
||||
const rowRef = useRef<HTMLDivElement>(null);
|
||||
const contentRef = useRef<HTMLDivElement>(null);
|
||||
const [open, setOpen] = useState<'leading' | 'trailing' | null>(null);
|
||||
// Which side shows while the finger moves, so the right buttons sit under the row.
|
||||
const [side, setSide] = useState<'leading' | 'trailing' | null>(null);
|
||||
const latest = useRef({ leading, trailing });
|
||||
useEffect(() => {
|
||||
latest.current = { leading, trailing };
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
const row = rowRef.current;
|
||||
const content = contentRef.current;
|
||||
if (!row || !content || disabled) return;
|
||||
const rtl = () => getComputedStyle(row).direction === 'rtl';
|
||||
let start: { x: number; y: number } | null = null;
|
||||
let claimed = false;
|
||||
let base = 0;
|
||||
let offset = 0;
|
||||
let beyond = false;
|
||||
|
||||
const place = (x: number, animate: boolean) => {
|
||||
offset = x;
|
||||
content.style.transition = animate ? 'transform 0.28s cubic-bezier(0.32, 0.72, 0, 1)' : 'none';
|
||||
content.style.transform = x ? `translateX(${x}px)` : '';
|
||||
};
|
||||
const width = () => row.getBoundingClientRect().width;
|
||||
// Positive offset reveals the leading side in LTR; RTL mirrors it.
|
||||
const leadSign = () => (rtl() ? -1 : 1);
|
||||
const openWidth = (which: 'leading' | 'trailing') =>
|
||||
which === 'leading' ? (latest.current.leading ? BUTTON_W : 0) : latest.current.trailing.length * BUTTON_W;
|
||||
|
||||
const close = () => {
|
||||
place(0, true);
|
||||
setOpen(null);
|
||||
setSide(null);
|
||||
if (closeOpenRow === close) closeOpenRow = null;
|
||||
};
|
||||
|
||||
const onStart = (e: TouchEvent) => {
|
||||
claimed = false;
|
||||
start = null;
|
||||
if (e.touches.length !== 1) return;
|
||||
const t = e.touches[0];
|
||||
if (t.clientX < EDGE_PX) return;
|
||||
start = { x: t.clientX, y: t.clientY };
|
||||
base = offset;
|
||||
beyond = false;
|
||||
};
|
||||
|
||||
const onMove = (e: TouchEvent) => {
|
||||
if (!start) return;
|
||||
const t = e.touches[0];
|
||||
const dx = t.clientX - start.x;
|
||||
const dy = t.clientY - start.y;
|
||||
if (!claimed) {
|
||||
if (Math.abs(dx) < CLAIM_PX && Math.abs(dy) < CLAIM_PX) return;
|
||||
if (Math.abs(dx) < Math.abs(dy) * AXIS_BIAS) {
|
||||
start = null;
|
||||
return;
|
||||
}
|
||||
claimed = true;
|
||||
if (closeOpenRow && closeOpenRow !== close) closeOpenRow();
|
||||
}
|
||||
if (e.cancelable) e.preventDefault();
|
||||
let x = base + dx;
|
||||
const which = x * leadSign() > 0 ? 'leading' : 'trailing';
|
||||
const room = openWidth(which);
|
||||
if (!room) x = x / 4;
|
||||
setSide((s) => (s === which ? s : which));
|
||||
// Unmeasured (width 0) means no full swipe: a row never runs an action by accident.
|
||||
const w = width();
|
||||
const crossed = w > 0 && room > 0 && Math.abs(x) > w * FULL_SHARE;
|
||||
if (crossed !== beyond) {
|
||||
beyond = crossed;
|
||||
if (crossed) tickHaptic();
|
||||
}
|
||||
place(x, false);
|
||||
};
|
||||
|
||||
const onEnd = () => {
|
||||
if (!start || !claimed) {
|
||||
start = null;
|
||||
return;
|
||||
}
|
||||
start = null;
|
||||
claimed = false;
|
||||
const which = offset * leadSign() > 0 ? 'leading' : 'trailing';
|
||||
const room = openWidth(which);
|
||||
const action = which === 'leading' ? latest.current.leading : latest.current.trailing[0];
|
||||
if (beyond && action) {
|
||||
close();
|
||||
action.onAction();
|
||||
return;
|
||||
}
|
||||
if (room && Math.abs(offset) > room / 2) {
|
||||
place(room * (which === 'leading' ? leadSign() : -leadSign()), true);
|
||||
setOpen(which);
|
||||
closeOpenRow = close;
|
||||
} else {
|
||||
close();
|
||||
}
|
||||
};
|
||||
|
||||
// A tap on an open row closes it instead of opening what is under the finger.
|
||||
const onClickCapture = (e: MouseEvent) => {
|
||||
if (offset === 0) return;
|
||||
if (e.target instanceof Element && e.target.closest('[data-swipe-action]')) return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
close();
|
||||
};
|
||||
|
||||
row.addEventListener('touchstart', onStart, { passive: true });
|
||||
row.addEventListener('touchmove', onMove, { passive: false });
|
||||
row.addEventListener('touchend', onEnd, { passive: true });
|
||||
row.addEventListener('touchcancel', onEnd, { passive: true });
|
||||
row.addEventListener('click', onClickCapture, true);
|
||||
return () => {
|
||||
row.removeEventListener('touchstart', onStart);
|
||||
row.removeEventListener('touchmove', onMove);
|
||||
row.removeEventListener('touchend', onEnd);
|
||||
row.removeEventListener('touchcancel', onEnd);
|
||||
row.removeEventListener('click', onClickCapture, true);
|
||||
if (closeOpenRow === close) closeOpenRow = null;
|
||||
};
|
||||
}, [disabled]);
|
||||
|
||||
const run = (action: SwipeAction) => {
|
||||
closeOpenRow?.();
|
||||
action.onAction();
|
||||
};
|
||||
const shown = open ?? side;
|
||||
const button = (action: SwipeAction) => (
|
||||
<button
|
||||
key={action.label}
|
||||
type="button"
|
||||
data-swipe-action=""
|
||||
tabIndex={open ? 0 : -1}
|
||||
onClick={() => run(action)}
|
||||
className={`flex h-full w-[76px] flex-none flex-col items-center justify-center gap-1 text-[0.6875rem] font-semibold ${TONE[action.tone]}`}
|
||||
>
|
||||
<action.icon size={18} strokeWidth={2.2} aria-hidden="true" />
|
||||
{action.label}
|
||||
</button>
|
||||
);
|
||||
|
||||
return (
|
||||
<div ref={rowRef} className={`relative overflow-hidden ${className}`}>
|
||||
{shown && (
|
||||
<div
|
||||
aria-hidden={!open}
|
||||
className={`absolute inset-0 flex ${shown === 'leading' ? 'justify-start' : 'justify-end'}`}
|
||||
>
|
||||
{shown === 'leading' ? leading && button(leading) : trailing.map(button)}
|
||||
</div>
|
||||
)}
|
||||
<div ref={contentRef} className={`relative ${surface}`}>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { act, fireEvent, render, screen } from '../../../tests/helpers/render';
|
||||
import { pressHaptic } from '../../native/haptics';
|
||||
import { useLongPress } from './useLongPress';
|
||||
|
||||
vi.mock('../../native/haptics', () => ({ pressHaptic: vi.fn() }));
|
||||
|
||||
function Card({ onLongPress, onClick }: { onLongPress: () => void; onClick: () => void }) {
|
||||
const press = useLongPress(onLongPress);
|
||||
return (
|
||||
<div {...press} role="button" tabIndex={0} onClick={onClick}>
|
||||
Lisbon
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
beforeEach(() => vi.useFakeTimers());
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
/** jsdom has no Touch to build a TouchEvent from: an Event with the touches set on it, as MEdgeBack's test does. */
|
||||
function touch(el: Element, type: 'touchstart' | 'touchmove' | 'touchend', x = 50, y = 50) {
|
||||
const e = new Event(type, { bubbles: true, cancelable: true });
|
||||
Object.defineProperty(e, 'touches', { value: type === 'touchend' ? [] : [{ clientX: x, clientY: y }] });
|
||||
act(() => {
|
||||
el.dispatchEvent(e);
|
||||
});
|
||||
}
|
||||
|
||||
function setup() {
|
||||
const onLongPress = vi.fn();
|
||||
const onClick = vi.fn();
|
||||
render(<Card onLongPress={onLongPress} onClick={onClick} />);
|
||||
return { card: screen.getByRole('button'), onLongPress, onClick };
|
||||
}
|
||||
|
||||
describe('useLongPress', () => {
|
||||
it('FE-MOB-LONGPRESS-001: a held finger lifts the card, bumps and opens the menu, and the tap that ends it opens nothing', () => {
|
||||
const { card, onLongPress, onClick } = setup();
|
||||
touch(card, 'touchstart');
|
||||
act(() => vi.advanceTimersByTime(200));
|
||||
expect(card.hasAttribute('data-pressing')).toBe(true);
|
||||
act(() => vi.advanceTimersByTime(300));
|
||||
expect(onLongPress).toHaveBeenCalledOnce();
|
||||
expect(pressHaptic).toHaveBeenCalled();
|
||||
expect(card.hasAttribute('data-pressing')).toBe(false);
|
||||
touch(card, 'touchend');
|
||||
fireEvent.click(card);
|
||||
expect(onClick).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-MOB-LONGPRESS-002: a finger that moves is scrolling and cancels it', () => {
|
||||
const { card, onLongPress } = setup();
|
||||
touch(card, 'touchstart');
|
||||
touch(card, 'touchmove', 50, 80);
|
||||
act(() => vi.advanceTimersByTime(600));
|
||||
expect(onLongPress).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-MOB-LONGPRESS-003: a short tap is a tap', () => {
|
||||
const { card, onLongPress, onClick } = setup();
|
||||
touch(card, 'touchstart');
|
||||
act(() => vi.advanceTimersByTime(100));
|
||||
touch(card, 'touchend');
|
||||
fireEvent.click(card);
|
||||
expect(onLongPress).not.toHaveBeenCalled();
|
||||
expect(onClick).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("FE-MOB-LONGPRESS-004: Android's contextmenu counts as the long press", () => {
|
||||
const { card, onLongPress } = setup();
|
||||
fireEvent.contextMenu(card);
|
||||
expect(onLongPress).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,84 @@
|
||||
import { type MouseEvent, type TouchEvent, useEffect, useRef } from 'react';
|
||||
import { pressHaptic } from '../../native/haptics';
|
||||
|
||||
/**
|
||||
* A long press on a card, as the phone knows it: hold still for a moment and
|
||||
* the card lifts, the phone bumps, and `onLongPress` opens its menu. A finger
|
||||
* that moves is scrolling and cancels it; the tap that ends a long press opens
|
||||
* nothing else. Android also reports the press as a contextmenu event, which
|
||||
* counts as the same press.
|
||||
*
|
||||
* Spread the returned props on the card. For the first moments it presses like
|
||||
* any tap; once the hold is clearly a hold the card gets data-pressing and lifts
|
||||
* (index.css), and the press dimming lets go of it.
|
||||
*/
|
||||
|
||||
const LIFT_MS = 180;
|
||||
const HOLD_MS = 450;
|
||||
const SLOP_PX = 8;
|
||||
|
||||
export function useLongPress(onLongPress: (() => void) | undefined) {
|
||||
const timer = useRef<number | null>(null);
|
||||
const lift = useRef<number | null>(null);
|
||||
const start = useRef<{ x: number; y: number } | null>(null);
|
||||
// The click that ends a long press, swallowed.
|
||||
const fired = useRef(false);
|
||||
const target = useRef<HTMLElement | null>(null);
|
||||
const handler = useRef(onLongPress);
|
||||
useEffect(() => {
|
||||
handler.current = onLongPress;
|
||||
});
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (timer.current) window.clearTimeout(timer.current);
|
||||
if (lift.current) window.clearTimeout(lift.current);
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
const settle = () => {
|
||||
if (timer.current) window.clearTimeout(timer.current);
|
||||
if (lift.current) window.clearTimeout(lift.current);
|
||||
timer.current = null;
|
||||
lift.current = null;
|
||||
start.current = null;
|
||||
target.current?.removeAttribute('data-pressing');
|
||||
};
|
||||
const fire = () => {
|
||||
settle();
|
||||
fired.current = true;
|
||||
pressHaptic();
|
||||
handler.current?.();
|
||||
};
|
||||
|
||||
if (!onLongPress) return {};
|
||||
return {
|
||||
'data-long-press': '',
|
||||
onTouchStart: (e: TouchEvent<HTMLElement>) => {
|
||||
fired.current = false;
|
||||
if (e.touches.length !== 1) return;
|
||||
start.current = { x: e.touches[0].clientX, y: e.touches[0].clientY };
|
||||
const card = e.currentTarget;
|
||||
target.current = card;
|
||||
lift.current = window.setTimeout(() => card.setAttribute('data-pressing', ''), LIFT_MS);
|
||||
timer.current = window.setTimeout(fire, HOLD_MS);
|
||||
},
|
||||
onTouchMove: (e: TouchEvent<HTMLElement>) => {
|
||||
if (!start.current) return;
|
||||
const t = e.touches[0];
|
||||
if (Math.abs(t.clientX - start.current.x) > SLOP_PX || Math.abs(t.clientY - start.current.y) > SLOP_PX) settle();
|
||||
},
|
||||
onTouchEnd: settle,
|
||||
onTouchCancel: settle,
|
||||
onContextMenu: (e: MouseEvent<HTMLElement>) => {
|
||||
e.preventDefault();
|
||||
if (!fired.current) fire();
|
||||
},
|
||||
onClickCapture: (e: MouseEvent<HTMLElement>) => {
|
||||
if (!fired.current) return;
|
||||
fired.current = false;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
},
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user