mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-30 08:30:05 +00:00
feat(tours): fold the rail cards, remembered across reloads; trip totals as badges
The planner's cards fold to their head: waypoints, the paddle time estimate, the wind and the checklist on the left, the open tour's summary on the right. The title or the chevron folds a card, and the choice is kept in this browser, so a reload finds the rails as they were left. A folded card still says what matters in its head: the checklist what is open, the wind its day, and the time estimate now its total as a badge, in the warning tone while parts of it are unknown. The "planning values" badge and info dot of the estimate go; what the starting values are is said once under its figures. The obstacle entry dialog sits outside the checklist's body, so an obstacle picked on the map still opens with the card folded. The trip totals start folded to their counts and show each type's sums as the row's white badges, each named in its tooltip, an incomplete one marked as at least that much with how many tours it is known for. The info text is shorter. The Tours locale contract counts the 574 general keys the planned cards brought in.
This commit is contained in:
@@ -1,12 +1,27 @@
|
||||
import type { TourListItem, TourTypeKey } from '@trek/shared';
|
||||
import { ChartColumnBig, ChevronDown, Mountain, Route, Waves } from 'lucide-react';
|
||||
import { useMemo, useState, type ComponentType } from 'react';
|
||||
import {
|
||||
ArrowDown,
|
||||
ArrowUp,
|
||||
CalendarClock,
|
||||
ChartColumnBig,
|
||||
ChevronDown,
|
||||
Clock,
|
||||
FileDown,
|
||||
Mountain,
|
||||
Route,
|
||||
Ruler,
|
||||
Waves,
|
||||
type LucideIcon,
|
||||
} from 'lucide-react';
|
||||
import { useMemo, type ComponentType } from 'react';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { useSettingsStore } from '../../store/settingsStore';
|
||||
import { useTripStore } from '../../store/tripStore';
|
||||
import { formatDistance, formatElevation } from '../../utils/units';
|
||||
import { fs } from '../shared/DialogShell';
|
||||
import { InfoDot, RailCard, RailFacts, type TourMetricField } from './tourParts';
|
||||
import { useRailFold } from './railFold';
|
||||
import { TourDayRowPill } from './TourDayRowFacts';
|
||||
import { InfoDot, RailCard } from './tourParts';
|
||||
import { formatPlannedTourDuration } from './tourPresentation';
|
||||
import { tourScopeSummary, type ScopeSum, type TourTypeScope } from './tourScope';
|
||||
|
||||
@@ -17,23 +32,6 @@ const TYPE_ICON: Partial<Record<TourTypeKey, ComponentType<{ size?: number; stro
|
||||
kayak: Waves,
|
||||
};
|
||||
|
||||
/** Whether the card is folded, kept per browser like other view conveniences; a blocked storage keeps it open. */
|
||||
const FOLDED_KEY = 'trek.tours.scopeSummary.folded';
|
||||
function readFolded(): boolean {
|
||||
try {
|
||||
return localStorage.getItem(FOLDED_KEY) === '1';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
function storeFolded(folded: boolean): void {
|
||||
try {
|
||||
localStorage.setItem(FOLDED_KEY, folded ? '1' : '0');
|
||||
} catch {
|
||||
// Private mode or blocked storage: the card simply opens again next time.
|
||||
}
|
||||
}
|
||||
|
||||
/** A count as a white badge of the card: the number, then what it counts. */
|
||||
function CountBadge({ value, label, tone = 'neutral' }: { value: number; label: string; tone?: 'neutral' | 'faint' }) {
|
||||
return (
|
||||
@@ -47,53 +45,71 @@ function CountBadge({ value, label, tone = 'neutral' }: { value: number; label:
|
||||
);
|
||||
}
|
||||
|
||||
/** One measure of a type as a badge: its icon and sum, its name (and how complete it is) in the tooltip. */
|
||||
interface ScopeBadge {
|
||||
key: string;
|
||||
icon: LucideIcon;
|
||||
value: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* A sum as a fact: nothing when no tour has the value, else the sum, marked as
|
||||
* at least that much with the reason in its info dot when some tours lack it.
|
||||
* A sum as a badge: nothing when no tour has the value, else the sum, marked
|
||||
* as at least that much when some tours lack it, the tooltip saying for how many.
|
||||
*/
|
||||
function sumFact(
|
||||
label: string,
|
||||
function sumBadge(
|
||||
{ key, icon, name }: Pick<ScopeBadge, 'key' | 'icon'> & { name: string },
|
||||
sum: ScopeSum,
|
||||
format: (value: number) => string,
|
||||
t: Translate
|
||||
): TourMetricField | null {
|
||||
): ScopeBadge | null {
|
||||
if (sum.value === null) return null;
|
||||
const partial = sum.known < sum.of;
|
||||
return {
|
||||
label,
|
||||
value: partial ? `≥ ${format(sum.value)}` : format(sum.value),
|
||||
info: partial
|
||||
? {
|
||||
label: t('tours.scope.partial'),
|
||||
description: t('tours.scope.partialBody', { known: sum.known, of: sum.of }),
|
||||
}
|
||||
: undefined,
|
||||
};
|
||||
const value = partial ? `≥ ${format(sum.value)}` : format(sum.value);
|
||||
const label = partial
|
||||
? `${name}: ${value} (${t('tours.scope.partialBody', { known: sum.known, of: sum.of })})`
|
||||
: `${name}: ${value}`;
|
||||
return { key, icon, value, label };
|
||||
}
|
||||
|
||||
function typeFacts(scope: TourTypeScope, unit: Parameters<typeof formatDistance>[1], t: Translate): TourMetricField[] {
|
||||
function typeBadges(scope: TourTypeScope, unit: Parameters<typeof formatDistance>[1], t: Translate): ScopeBadge[] {
|
||||
const distance = (km: number) => formatDistance(km, unit);
|
||||
const height = (m: number) => formatElevation(m, unit);
|
||||
return [
|
||||
sumFact(t('tours.detail.distance'), scope.distanceKm, distance, t),
|
||||
sumFact(t('tours.detail.ascent'), scope.ascentM, height, t),
|
||||
sumFact(t('tours.detail.descent'), scope.descentM, height, t),
|
||||
sumFact(t('tours.scope.routed'), scope.routedMinutes, formatPlannedTourDuration, t),
|
||||
sumFact(t('tours.scope.imported'), scope.importedMinutes, formatPlannedTourDuration, t),
|
||||
sumFact(t('tours.scope.planned'), scope.plannedMinutes, formatPlannedTourDuration, t),
|
||||
].filter((fact): fact is TourMetricField => fact !== null);
|
||||
sumBadge({ key: 'distance', icon: Ruler, name: t('tours.detail.distance') }, scope.distanceKm, distance, t),
|
||||
sumBadge({ key: 'ascent', icon: ArrowUp, name: t('tours.detail.ascent') }, scope.ascentM, height, t),
|
||||
sumBadge({ key: 'descent', icon: ArrowDown, name: t('tours.detail.descent') }, scope.descentM, height, t),
|
||||
sumBadge(
|
||||
{ key: 'routed', icon: Clock, name: t('tours.scope.routed') },
|
||||
scope.routedMinutes,
|
||||
formatPlannedTourDuration,
|
||||
t
|
||||
),
|
||||
sumBadge(
|
||||
{ key: 'imported', icon: FileDown, name: t('tours.scope.imported') },
|
||||
scope.importedMinutes,
|
||||
formatPlannedTourDuration,
|
||||
t
|
||||
),
|
||||
sumBadge(
|
||||
{ key: 'planned', icon: CalendarClock, name: t('tours.scope.planned') },
|
||||
scope.plannedMinutes,
|
||||
formatPlannedTourDuration,
|
||||
t
|
||||
),
|
||||
].filter((badge): badge is ScopeBadge => badge !== null);
|
||||
}
|
||||
|
||||
/** One tour type: its name with how many tours and how many are on a day, then its sums. */
|
||||
/** One tour type: its name and how many tours, then its sums as a line of badges. */
|
||||
function TypeScope({ scope }: { scope: TourTypeScope }) {
|
||||
const { t } = useTranslation();
|
||||
const unit = useSettingsStore((state) => state.settings.distance_unit) ?? 'metric';
|
||||
const Icon = TYPE_ICON[scope.type] ?? Route;
|
||||
const facts = typeFacts(scope, unit, t);
|
||||
const badges = typeBadges(scope, unit, t);
|
||||
return (
|
||||
<section
|
||||
aria-label={t(`tourTypes.${scope.type}`)}
|
||||
className="flex flex-col gap-2.5"
|
||||
className="flex flex-col gap-1.5"
|
||||
data-testid={`tour-scope-${scope.type}`}
|
||||
>
|
||||
<div className="flex min-w-0 items-center gap-1.5">
|
||||
@@ -107,10 +123,20 @@ function TypeScope({ scope }: { scope: TourTypeScope }) {
|
||||
{scope.count}
|
||||
</span>
|
||||
</div>
|
||||
{facts.length > 0 ? (
|
||||
<RailFacts facts={facts} />
|
||||
{badges.length > 0 ? (
|
||||
<div className="flex flex-wrap gap-1.5 ps-[22px]">
|
||||
{badges.map((badge) => (
|
||||
<TourDayRowPill
|
||||
key={badge.key}
|
||||
icon={badge.icon}
|
||||
value={badge.value}
|
||||
label={badge.label}
|
||||
testId={`tour-scope-${scope.type}-${badge.key}`}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<p className="m-0 text-content-faint" style={fs(11.5, 'body')}>
|
||||
<p className="m-0 ps-[22px] text-content-faint" style={fs(11.5, 'body')}>
|
||||
{t('tours.scope.noMeasures')}
|
||||
</p>
|
||||
)}
|
||||
@@ -124,12 +150,13 @@ function TypeScope({ scope }: { scope: TourTypeScope }) {
|
||||
* time apart (the router's, an import's, the planned one with breaks), never
|
||||
* added up across types. It reads the list as filtered, so a type chosen in the
|
||||
* filter narrows both. A value no tour has is left out rather than shown as
|
||||
* zero; a sum some tours lack is marked as at least that much. Folding it is
|
||||
* remembered in this browser.
|
||||
* zero; a sum some tours lack is marked as at least that much. It starts folded
|
||||
* to its counts, and opening it is remembered in this browser.
|
||||
*/
|
||||
export function TourScopeSummary({ tours }: { tours: readonly TourListItem[] }) {
|
||||
const { t } = useTranslation();
|
||||
const [folded, setFolded] = useState(readFolded);
|
||||
// Folded until opened: the list is what the rail is for, the totals a look on demand.
|
||||
const { folded, toggle } = useRailFold('trip-totals', true);
|
||||
// On a day as the day lists say, not the list's flag, so a tour put on a day counts at once (as its row's badge does).
|
||||
const assignments = useTripStore((state) => state.assignments);
|
||||
const scope = useMemo(() => {
|
||||
@@ -137,12 +164,6 @@ export function TourScopeSummary({ tours }: { tours: readonly TourListItem[] })
|
||||
return tourScopeSummary(tours, (tour) => onDays.has(tour.place_id));
|
||||
}, [assignments, tours]);
|
||||
if (scope.count === 0) return null;
|
||||
const toggle = () => {
|
||||
setFolded((value) => {
|
||||
storeFolded(!value);
|
||||
return !value;
|
||||
});
|
||||
};
|
||||
const toggleLabel = folded ? t('common.expand') : t('common.collapse');
|
||||
return (
|
||||
<RailCard
|
||||
@@ -170,7 +191,7 @@ export function TourScopeSummary({ tours }: { tours: readonly TourListItem[] })
|
||||
<CountBadge value={scope.count - scope.onDays} label={t('places.unplanned')} tone="faint" />
|
||||
</div>
|
||||
{!folded && (
|
||||
<div className="mt-3.5 flex flex-col gap-4 border-t border-edge-faint pt-3.5">
|
||||
<div className="mt-3 flex flex-col gap-3 border-t border-edge-faint pt-3">
|
||||
{scope.types.map((typeScope) => (
|
||||
<TypeScope key={typeScope.type} scope={typeScope} />
|
||||
))}
|
||||
|
||||
@@ -367,21 +367,25 @@ export function PaddleCheckCard({ checklist }: { checklist: PaddleChecklist }) {
|
||||
const notice = noticeOf(checklist);
|
||||
const { summary, check } = checklist;
|
||||
return (
|
||||
<RailCard
|
||||
icon={<ListChecks size={14} strokeWidth={2} />}
|
||||
title={t('tours.paddle.check.title')}
|
||||
aside={summary ? <PaddleCheckPill check={summary} /> : null}
|
||||
>
|
||||
<div data-testid="paddle-check-card" className="flex flex-col gap-2.5">
|
||||
{notice && <CheckNoticeLine notice={notice} evaluatedAt={check?.evaluated_at ?? null} />}
|
||||
{notice === 'new' && <PaddleObstacleNotice />}
|
||||
{summary && <PaddleCheckDataLine check={summary} />}
|
||||
{check && <CheckList checklist={checklist} check={check} />}
|
||||
<p className="m-0 text-content-faint" style={fs(10.5, 'body')}>
|
||||
{t('tours.paddle.check.notClearance')}
|
||||
</p>
|
||||
</div>
|
||||
<>
|
||||
<RailCard
|
||||
icon={<ListChecks size={14} strokeWidth={2} />}
|
||||
title={t('tours.paddle.check.title')}
|
||||
foldId="paddle-check"
|
||||
aside={summary ? <PaddleCheckPill check={summary} /> : null}
|
||||
>
|
||||
<div data-testid="paddle-check-card" className="flex flex-col gap-2.5">
|
||||
{notice && <CheckNoticeLine notice={notice} evaluatedAt={check?.evaluated_at ?? null} />}
|
||||
{notice === 'new' && <PaddleObstacleNotice />}
|
||||
{summary && <PaddleCheckDataLine check={summary} />}
|
||||
{check && <CheckList checklist={checklist} check={check} />}
|
||||
<p className="m-0 text-content-faint" style={fs(10.5, 'body')}>
|
||||
{t('tours.paddle.check.notClearance')}
|
||||
</p>
|
||||
</div>
|
||||
</RailCard>
|
||||
{/* Outside the card's body: an obstacle picked on the map opens its entry with the card folded too. */}
|
||||
{checklist.dialogKey !== null && <ObstacleEntryDialog checklist={checklist} />}
|
||||
</RailCard>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -144,9 +144,9 @@ describe('PaddleTimeCard (PAD-07)', () => {
|
||||
renderCard({ breakMinutes: 30 });
|
||||
|
||||
const region = screen.getByRole('region', { name: 'Time estimate' });
|
||||
expect(within(region).getByText('Planning values')).toBeInTheDocument();
|
||||
const info = within(region).getByRole('button', { name: 'Planning values' });
|
||||
expect(info).toHaveAccessibleDescription(/^TREK starts with 4 km\/h on the water/);
|
||||
expect(within(region).getByText(/^TREK starts with 4 km\/h on the water/)).toBeInTheDocument();
|
||||
// The estimate with its breaks rides in the head, so a folded card still says it.
|
||||
expect(within(region).getByTestId('paddle-time-badge')).toHaveTextContent('3 h 50 min');
|
||||
expect(within(region).getByText('Estimate')).toBeInTheDocument();
|
||||
// 200 minutes of water, carrying, getting out and in and the lock, then 30 minutes of breaks.
|
||||
expect(estimateText()).toBe('3 h 50 min');
|
||||
|
||||
@@ -15,7 +15,7 @@ import { SoftPill } from '../../Planner/planParts';
|
||||
import { fs } from '../../shared/DialogShell';
|
||||
import { paddlePlanPoints } from '../planner/paddlePlanOf';
|
||||
import type { TourPlannerController } from '../planner/useTourPlanner';
|
||||
import { InfoDot, RailCard, TourNotice } from '../tourParts';
|
||||
import { RailCard, TourNotice } from '../tourParts';
|
||||
import { formatPlannedTourDuration } from '../tourPresentation';
|
||||
import { PaddleGlyph } from './PaddleGlyph';
|
||||
import { PORTAGE_CSS_COLOR } from './paddlePaint';
|
||||
@@ -364,7 +364,7 @@ export function PaddleEstimateBody({
|
||||
return (
|
||||
<div data-testid="paddle-time-card" className="flex flex-col gap-3">
|
||||
<EstimateHead
|
||||
total={estimate.estimateMinutes + (breakMinutes ?? 0)}
|
||||
total={paddleTotal(estimate, breakMinutes).minutes}
|
||||
complete={estimate.complete}
|
||||
planned={planned}
|
||||
t={t}
|
||||
@@ -386,25 +386,47 @@ export function PaddleEstimateBody({
|
||||
);
|
||||
}
|
||||
|
||||
/** The card's head: its title, and that its values are planning values to adjust. */
|
||||
export function PaddleTimeCardShell({ children }: { children: ReactNode }) {
|
||||
/**
|
||||
* The card: its title with the estimate as a badge (so a folded card still
|
||||
* says it, in the warning tone while parts are unknown), the figures, and
|
||||
* under them that its values are starting values to adjust.
|
||||
*/
|
||||
export function PaddleTimeCardShell({
|
||||
children,
|
||||
estimate,
|
||||
breakMinutes,
|
||||
}: {
|
||||
children: ReactNode;
|
||||
estimate: PaddleTimeEstimate;
|
||||
breakMinutes: number | null;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const total = paddleTotal(estimate, breakMinutes);
|
||||
return (
|
||||
<RailCard
|
||||
icon={<Timer size={14} strokeWidth={2} />}
|
||||
title={t('tours.paddle.time.title')}
|
||||
foldId="paddle-time"
|
||||
aside={
|
||||
<span className="flex flex-none items-center gap-1">
|
||||
<SoftPill tone="info">{t('tours.paddle.time.assumption')}</SoftPill>
|
||||
<InfoDot label={t('tours.paddle.time.assumption')} description={t('tours.paddle.time.assumptionInfo')} />
|
||||
<span data-testid="paddle-time-badge" className="flex flex-none">
|
||||
<SoftPill tone={total.complete ? 'neutral' : 'warning'}>{formatPlannedTourDuration(total.minutes)}</SoftPill>
|
||||
</span>
|
||||
}
|
||||
>
|
||||
{children}
|
||||
{/* What the starting values are, said once under the figures rather than behind a dot. */}
|
||||
<p className="m-0 mt-3 text-content-faint" style={fs(10.5, 'body')}>
|
||||
{t('tours.paddle.time.assumptionInfo')}
|
||||
</p>
|
||||
</RailCard>
|
||||
);
|
||||
}
|
||||
|
||||
/** The estimate with the breaks added, as the card's head and its body say it. */
|
||||
function paddleTotal(estimate: PaddleTimeEstimate, breakMinutes: number | null) {
|
||||
return { minutes: estimate.estimateMinutes + (breakMinutes ?? 0), complete: estimate.complete };
|
||||
}
|
||||
|
||||
/**
|
||||
* PAD-07: how the time of a paddle tour comes about. Water at the paddling
|
||||
* speed, portages at the carrying speed with their time out and in, locks at
|
||||
@@ -416,7 +438,7 @@ export function PaddleTimeCard({ planner, locked }: { planner: TourPlannerContro
|
||||
const estimate = planner.paddleEstimate;
|
||||
if (!estimate || planner.waypoints.length < 2) return null;
|
||||
return (
|
||||
<PaddleTimeCardShell>
|
||||
<PaddleTimeCardShell estimate={estimate} breakMinutes={planner.breakAdditionalMinutes}>
|
||||
<PaddleEstimateBody
|
||||
estimate={estimate}
|
||||
layout={paddleLayoutOfPoints(paddlePlanPoints(planner.waypoints))}
|
||||
|
||||
@@ -266,6 +266,7 @@ export function PaddleWindCard({ wind, lakes }: { wind: TourWind; lakes?: LakeSt
|
||||
<RailCard
|
||||
icon={<Wind size={14} strokeWidth={2} />}
|
||||
title={t('tours.paddle.wind.title')}
|
||||
foldId="paddle-wind"
|
||||
aside={
|
||||
wind.tourDays.length > 1 ? (
|
||||
<span className="flex flex-none items-center gap-1">
|
||||
|
||||
@@ -159,7 +159,7 @@ export function TrackPaddlePlanCards({ plan, tour }: { plan: TrackPaddlePlan; to
|
||||
const locked = !plan.canEdit || plan.saving;
|
||||
return (
|
||||
<>
|
||||
<PaddleTimeCardShell>
|
||||
<PaddleTimeCardShell estimate={plan.estimate} breakMinutes={tour.break_additional_minutes ?? null}>
|
||||
<PaddleEstimateBody
|
||||
estimate={plan.estimate}
|
||||
layout={plan.layout}
|
||||
|
||||
@@ -705,7 +705,7 @@ export function TourPlannerToursRail({ planner, tours, days, loading, onAssignTo
|
||||
<div className="flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto px-3 py-3.5">
|
||||
{hasRoute && (
|
||||
<div data-testid="tour-planner-overview">
|
||||
<RailCard icon={<Route size={14} strokeWidth={2} />} title={t('tours.planner.inspector.title')}>
|
||||
<RailCard icon={<Route size={14} strokeWidth={2} />} title={t('tours.planner.inspector.title')} foldId="tour-summary">
|
||||
<div className="flex flex-col gap-3">
|
||||
<FerrataCrossingBadges />
|
||||
<RailFacts facts={tourMetricFacts(routeAnalysis, distanceUnit, t, tourTimeFields)} />
|
||||
|
||||
@@ -820,6 +820,7 @@ export default function TourWaypointList({
|
||||
<RailCard
|
||||
icon={<MapPin size={14} strokeWidth={2} />}
|
||||
title={t('tours.planner.waypoints')}
|
||||
foldId="waypoints"
|
||||
aside={
|
||||
planner.waypoints.length > 0 && (
|
||||
<span className="flex flex-none items-center gap-1.5">
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import { act, renderHook } from '@testing-library/react';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { fireEvent, render, screen } from '../../../tests/helpers/render';
|
||||
import { useRailFold } from './railFold';
|
||||
import { RailCard } from './tourParts';
|
||||
|
||||
describe('useRailFold', () => {
|
||||
beforeEach(() => localStorage.clear());
|
||||
|
||||
it('starts at its default, and a choice outlasts a reload', () => {
|
||||
const first = renderHook(() => useRailFold('waypoints'));
|
||||
expect(first.result.current.folded).toBe(false);
|
||||
act(() => first.result.current.toggle());
|
||||
expect(first.result.current.folded).toBe(true);
|
||||
first.unmount();
|
||||
expect(renderHook(() => useRailFold('waypoints')).result.current.folded).toBe(true);
|
||||
// Another card keeps its own state.
|
||||
expect(renderHook(() => useRailFold('paddle-wind')).result.current.folded).toBe(false);
|
||||
});
|
||||
|
||||
it('a card folded by default stays open once opened', () => {
|
||||
const first = renderHook(() => useRailFold('trip-totals', true));
|
||||
expect(first.result.current.folded).toBe(true);
|
||||
act(() => first.result.current.toggle());
|
||||
first.unmount();
|
||||
expect(renderHook(() => useRailFold('trip-totals', true)).result.current.folded).toBe(false);
|
||||
});
|
||||
|
||||
it('falls back to the default where the storage is blocked', () => {
|
||||
const spy = vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => {
|
||||
throw new Error('blocked');
|
||||
});
|
||||
expect(renderHook(() => useRailFold('trip-totals', true)).result.current.folded).toBe(true);
|
||||
spy.mockRestore();
|
||||
});
|
||||
});
|
||||
|
||||
describe('RailCard with a fold', () => {
|
||||
beforeEach(() => localStorage.clear());
|
||||
|
||||
it('folds to its head by the chevron or the title, keeping the head aside', () => {
|
||||
render(
|
||||
<RailCard icon={null} title="Waypoints" foldId="waypoints" aside={<span>5</span>}>
|
||||
<p>rows</p>
|
||||
</RailCard>
|
||||
);
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Collapse: Waypoints' }));
|
||||
expect(screen.queryByText('rows')).toBeNull();
|
||||
expect(screen.getByText('5')).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Waypoints' }));
|
||||
expect(screen.getByText('rows')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('a card without a fold id has no fold', () => {
|
||||
render(
|
||||
<RailCard icon={null} title="Tour summary">
|
||||
<p>facts</p>
|
||||
</RailCard>
|
||||
);
|
||||
expect(screen.queryByRole('button')).toBeNull();
|
||||
expect(screen.getByText('facts')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,38 @@
|
||||
import { useCallback, useState } from 'react';
|
||||
|
||||
/**
|
||||
* Whether a card of the tours rails is folded, kept per browser so a reload
|
||||
* finds the rail as it was left. A view convenience, nothing shared: a blocked
|
||||
* or cleared storage gives every card its default again.
|
||||
*/
|
||||
const keyOf = (id: string) => `trek.tours.fold.${id}`;
|
||||
|
||||
/** The stored choice, else the card's own default. */
|
||||
function readFolded(id: string, byDefault = false): boolean {
|
||||
try {
|
||||
const stored = localStorage.getItem(keyOf(id));
|
||||
return stored === null ? byDefault : stored === '1';
|
||||
} catch {
|
||||
return byDefault;
|
||||
}
|
||||
}
|
||||
|
||||
function storeFolded(id: string, folded: boolean): void {
|
||||
try {
|
||||
localStorage.setItem(keyOf(id), folded ? '1' : '0');
|
||||
} catch {
|
||||
// Private mode or blocked storage: the card takes its default again next time.
|
||||
}
|
||||
}
|
||||
|
||||
/** A card's folded state under `id`, remembered in this browser; `byDefault` until the user chose. */
|
||||
export function useRailFold(id: string, byDefault = false) {
|
||||
const [folded, setFolded] = useState(() => readFolded(id, byDefault));
|
||||
const toggle = useCallback(() => {
|
||||
setFolded((value) => {
|
||||
storeFolded(id, !value);
|
||||
return !value;
|
||||
});
|
||||
}, [id]);
|
||||
return { folded, toggle };
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import { hikeSourceBadgeLabel, tourSource } from './tourPresentation'
|
||||
import { type TourDay, dayMenuLabel } from './tourDays'
|
||||
import { tourMetricFacts } from './tourFacts'
|
||||
import type { TourDayAssignment } from './useTourDayAssignment'
|
||||
import { useRailFold } from './railFold'
|
||||
|
||||
/**
|
||||
* A tour's tile in a list: its T-scale grade in place of the mountain, named in
|
||||
@@ -356,26 +357,46 @@ export function RailCard({
|
||||
aside,
|
||||
children,
|
||||
className = '',
|
||||
foldId,
|
||||
}: {
|
||||
icon: ReactNode
|
||||
title: string
|
||||
aside?: ReactNode
|
||||
children: ReactNode
|
||||
className?: string
|
||||
/** Lets the card fold to its head, remembered in this browser under this id across reloads. */
|
||||
foldId?: string
|
||||
}) {
|
||||
const { t } = useTranslation()
|
||||
const bodyId = useId()
|
||||
const { folded: storedFolded, toggle } = useRailFold(foldId ?? '')
|
||||
const folded = !!foldId && storedFolded
|
||||
return (
|
||||
<section
|
||||
className={`flex-none overflow-hidden rounded-2xl border border-edge-faint bg-surface-card ${className}`}
|
||||
aria-label={title}
|
||||
>
|
||||
<div className="flex items-center gap-2 border-b border-edge-faint bg-surface-secondary px-3 py-2">
|
||||
<div className={`flex items-center gap-2 bg-surface-secondary px-3 py-2 ${folded ? '' : 'border-b border-edge-faint'}`}>
|
||||
<span className="grid h-4 w-4 flex-none place-items-center text-content-muted">{icon}</span>
|
||||
<span className="min-w-0 flex-1 truncate font-semibold text-content" style={fs(12.5, 'body')}>
|
||||
{title}
|
||||
</span>
|
||||
{foldId ? (
|
||||
// The title folds the card too: a wide target, not only the chevron.
|
||||
<button type="button" onClick={toggle} aria-expanded={!folded} aria-controls={bodyId}
|
||||
className="min-w-0 flex-1 truncate text-start font-semibold text-content focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent"
|
||||
style={fs(12.5, 'body')}>
|
||||
{title}
|
||||
</button>
|
||||
) : (
|
||||
<span className="min-w-0 flex-1 truncate font-semibold text-content" style={fs(12.5, 'body')}>
|
||||
{title}
|
||||
</span>
|
||||
)}
|
||||
{aside}
|
||||
{foldId && (
|
||||
<FoldButton expanded={!folded} onToggle={toggle} controls={bodyId}
|
||||
label={`${t(folded ? 'common.expand' : 'common.collapse')}: ${title}`} />
|
||||
)}
|
||||
</div>
|
||||
<div className="px-3 py-3">{children}</div>
|
||||
{!folded && <div id={bodyId} className="px-3 py-3">{children}</div>}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { TourListItem } from '@trek/shared';
|
||||
import { beforeEach, describe, expect, it } from 'vitest';
|
||||
import { fireEvent, render, screen, within } from '../../../tests/helpers/render';
|
||||
import { fireEvent, render, screen } from '../../../tests/helpers/render';
|
||||
import { useTripStore } from '../../store/tripStore';
|
||||
import { TourScopeSummary } from './TourScopeSummary';
|
||||
import { tourScopeSummary } from './tourScope';
|
||||
@@ -116,24 +116,28 @@ describe('TourScopeSummary', () => {
|
||||
expect(counts).toHaveTextContent('3Tours');
|
||||
expect(counts).toHaveTextContent('2Planned');
|
||||
expect(counts).toHaveTextContent('1Unplanned');
|
||||
const hike = screen.getByTestId('tour-scope-hike');
|
||||
expect(within(hike).getByText('15.5 km')).toBeInTheDocument();
|
||||
expect(within(hike).getByText('≥ 600 m')).toBeInTheDocument();
|
||||
expect(within(hike).getByText('Routed time')).toBeInTheDocument();
|
||||
expect(within(hike).queryByText('Time from imports')).toBeNull();
|
||||
// The paddle tour has no heights: no ascent, rather than 0 m.
|
||||
expect(within(screen.getByTestId('tour-scope-kayak')).queryByText('Ascent')).toBeNull();
|
||||
fireEvent.click(screen.getByTestId('tour-scope-toggle'));
|
||||
expect(screen.getByTestId('tour-scope-hike-distance')).toHaveTextContent('15.5 km');
|
||||
const ascent = screen.getByTestId('tour-scope-hike-ascent');
|
||||
expect(ascent).toHaveTextContent('≥ 600 m');
|
||||
expect(ascent).toHaveAccessibleName('Ascent: ≥ 600 m (known for 1 of 2 tours)');
|
||||
expect(screen.getByTestId('tour-scope-hike-routed')).toHaveAccessibleName('Routed time: 5 h');
|
||||
expect(screen.queryByTestId('tour-scope-hike-imported')).toBeNull();
|
||||
// Paddling sums no heights: no ascent badge, rather than 0 m.
|
||||
expect(screen.queryByTestId('tour-scope-kayak-ascent')).toBeNull();
|
||||
expect(screen.getByTestId('tour-scope-kayak-distance')).toHaveTextContent('12 km');
|
||||
});
|
||||
|
||||
it('folds to its counts, and remembers that in this browser', () => {
|
||||
it('starts folded to its counts, and remembers an opening in this browser', () => {
|
||||
const { unmount } = render(<TourScopeSummary tours={[HIKE_A]} />);
|
||||
fireEvent.click(screen.getByTestId('tour-scope-toggle'));
|
||||
expect(screen.queryByTestId('tour-scope-hike')).toBeNull();
|
||||
expect(screen.getByTestId('tour-scope-counts')).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByTestId('tour-scope-toggle'));
|
||||
expect(screen.getByTestId('tour-scope-hike')).toBeInTheDocument();
|
||||
unmount();
|
||||
render(<TourScopeSummary tours={[HIKE_A]} />);
|
||||
expect(screen.queryByTestId('tour-scope-hike')).toBeNull();
|
||||
expect(screen.getByTestId('tour-scope-toggle')).toHaveAttribute('aria-expanded', 'false');
|
||||
expect(screen.getByTestId('tour-scope-hike')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('tour-scope-toggle')).toHaveAttribute('aria-expanded', 'true');
|
||||
});
|
||||
|
||||
it('shows nothing for a trip without tours', () => {
|
||||
|
||||
Reference in New Issue
Block a user