perf(planner): tabs that open ready instead of building in front of the user

Two seconds after a trip opens, the code of every tab panel loads in the background, and the packing list's bags with it, which are kept per trip so Lists opens with its bag sidebar in place. The plan and tour planner maps stay mounted (hidden) once opened, so switching between them no longer starts a map again and flickers. Not on a narrow screen, where the plan tab portals its own controls over the page.
This commit is contained in:
Maurice
2026-11-29 10:04:15 +01:00
parent 64697fdb7f
commit 467287f138
6 changed files with 94 additions and 10 deletions
@@ -13,6 +13,20 @@ interface Toaster {
error: (message: string) => void;
}
/**
* The last bags read per trip in this tab. A list opened again, or opened after
* the trip read them ahead (warmPackingBags), starts with them instead of
* drawing the list first and the bag sidebar a moment later; the read that
* follows only refreshes them.
*/
const keptBags = new Map<number, { bags: PackingBag[]; unassigned: number | null }>();
/** Reads a trip's bags ahead, while it sits open, for the list to start with. */
export async function warmPackingBags(tripId: number): Promise<void> {
const r = await packingApi.listBags(tripId);
keptBags.set(tripId, { bags: r.bags || [], unassigned: r.unassigned_weight_grams ?? null });
}
/**
* The trip's bags behind both packing lists: the bags with their server-summed
* weights, kept fresh by the room's totals ping, and the bag writes. The desktop
@@ -29,9 +43,16 @@ export function usePackingBags({
t: Translate;
toast: Toaster;
}) {
const [bags, setBags] = useState<PackingBag[]>([]);
const [bags, setBags] = useState<PackingBag[]>(() => keptBags.get(tripId)?.bags ?? []);
/** Server-summed weight of everything in no bag (#2191); null until the first load. */
const [unassignedWeightGrams, setUnassignedWeightGrams] = useState<number | null>(null);
const [unassignedWeightGrams, setUnassignedWeightGrams] = useState<number | null>(
() => keptBags.get(tripId)?.unassigned ?? null
);
// What the list shows now is what it starts with next time.
useEffect(() => {
keptBags.set(tripId, { bags, unassigned: unassignedWeightGrams });
}, [tripId, bags, unassignedWeightGrams]);
const reloadBags = useCallback(async () => {
if (!bagTrackingEnabled) return;
+8 -5
View File
@@ -73,7 +73,7 @@ function TripPlannerPageDesktop(): React.ReactElement | null {
dawarichEnabled, dawarichTrailShown, toggleDawarichTrail, dawarichTrail, dawarichHiddenDates,
followTrack, roadtripViaCounts,
allowedFileTypes, tripMembers, setTripMembers, refreshMembers, loadAccommodations,
TRANSPORT_TYPES, TRIP_TABS, activeTab, setActiveTab, handleTabChange,
TRANSPORT_TYPES, TRIP_TABS, activeTab, setActiveTab, handleTabChange, keptMapTabs,
leftWidth, rightWidth,
leftHidden, rightHidden, toggleLeft, toggleRight,
startResizeLeft, startResizeRight, nudgeLeft, nudgeRight, resizing, resizeMin, resizeMaxLeft, resizeMaxRight,
@@ -259,8 +259,11 @@ function TripPlannerPageDesktop(): React.ReactElement | null {
plugins with a tab here, floating bottom overlay for the rest. */}
<TripWarningsBanner tripId={tripId} onOpenPluginTab={(pid) => handleTabChange(`plugin:${pid}`)} />
{activeTab === 'plan' && (
<div style={{ position: 'absolute', inset: 0 }}>
{/* Plan and the tour planner each keep their map once opened, hidden while
another tab shows, so switching back does not start a map again. Not on
a narrow screen, where the plan tab puts its own controls over the page. */}
{(activeTab === 'plan' || (keptMapTabs.has('plan') && !isMobile)) && (
<div style={{ position: 'absolute', inset: 0, visibility: activeTab === 'plan' ? undefined : 'hidden' }}>
<PlanMapStage
tripId={tripId} trip={trip} can={can} days={days} places={places} reservations={reservations} isMobile={isMobile}
selectedDayId={selectedDayId} selectedPlaceId={selectedPlaceId} selectedPlace={selectedPlace} showDayDetail={showDayDetail} handleSelectDay={handleSelectDay}
@@ -617,8 +620,8 @@ function TripPlannerPageDesktop(): React.ReactElement | null {
</div>
)}
{activeTab === 'tour-planner' && enabledAddons.tours && !isMobile && (
<TourGpxDropZone gpxImport={tourGpxImport} canEdit={canPlaceEdit} className="absolute inset-0">
{(activeTab === 'tour-planner' || keptMapTabs.has('tour-planner')) && enabledAddons.tours && !isMobile && (
<TourGpxDropZone gpxImport={tourGpxImport} canEdit={canPlaceEdit} className={activeTab === 'tour-planner' ? 'absolute inset-0' : 'invisible absolute inset-0'}>
<TourPlannerMapStage
tripId={tripId} mapTileUrl={mapTileUrl} leftHidden={leftHidden} rightHidden={rightHidden} t={t}
tourPlanner={tourPlanner} tourMap={tourMap} locationSearch={locationSearch} canPlaceEdit={canPlaceEdit}
+3 -2
View File
@@ -20,8 +20,9 @@ export function LazyPanel({ id, children, overlay }: Readonly<{ id: string; chil
place to hold. Drawn in the page flow, that skeleton was a pale block flashing
under the planner the first time each dialog was ever opened, and never again
once the chunk was cached. Nothing is the right placeholder for something that
is about to cover the screen anyway. */}
<Suspense fallback={overlay ? null : <div className="h-full w-full min-h-[180px] rounded-xl bg-surface-secondary animate-pulse" />}>
is about to cover the screen anyway. Opening the trip holds the previous
page while this skeleton is up (data-route-fallback, utils/viewTransition.ts). */}
<Suspense fallback={overlay ? null : <div data-route-fallback="" className="h-full w-full min-h-[180px] rounded-xl bg-surface-secondary animate-pulse" />}>
{children}
</Suspense>
</ErrorBoundary>
@@ -0,0 +1,16 @@
import { describe, expect, it, vi } from 'vitest';
import { TAB_PANEL_LOADS } from './tabPanelPreload';
vi.mock('../../components/Planner/ReservationsPanel', () => ({ default: 'reservations' }));
vi.mock('../../components/Packing/PackingListPanel', () => ({ default: 'packing' }));
vi.mock('../../components/Todo/TodoListPanel', () => ({ default: 'todo' }));
vi.mock('../../components/Files/FileManager', () => ({ default: 'files' }));
vi.mock('../../components/Budget/CostsPanel', () => ({ default: 'costs' }));
vi.mock('../../components/Collab/CollabPanel', () => ({ default: 'collab' }));
describe('tabPanelPreload', () => {
it('FE-PAGE-PLANNER-PRELOAD-001: loads the module of every tab panel', async () => {
const loaded = (await Promise.all(TAB_PANEL_LOADS.map((load) => load()))) as Array<{ default: string }>;
expect(loaded.map((m) => m.default)).toEqual(['reservations', 'packing', 'todo', 'files', 'costs', 'collab']);
});
});
@@ -0,0 +1,14 @@
/**
* The tabs' panels, loaded ahead once a trip is up and quiet, so the first
* switch to a tab finds its code already here instead of drawing a skeleton and
* building the panel in front of the user. The same modules plannerLazy.ts
* loads on demand; asking twice for a module costs nothing.
*/
export const TAB_PANEL_LOADS: ReadonlyArray<() => Promise<unknown>> = [
() => import('../../components/Planner/ReservationsPanel'),
() => import('../../components/Packing/PackingListPanel'),
() => import('../../components/Todo/TodoListPanel'),
() => import('../../components/Files/FileManager'),
() => import('../../components/Budget/CostsPanel'),
() => import('../../components/Collab/CollabPanel'),
];
+30 -1
View File
@@ -15,6 +15,7 @@ import { TRANSPORT_TYPES } from '../../utils/dayMerge'
import { offlineDb } from '../../db/offlineDb'
import { isEffectivelyOffline } from '../../sync/networkMode'
import { useAuthStore } from '../../store/authStore'
import { useAddonStore } from '../../store/addonStore'
import { useResizablePanels } from '../../hooks/useResizablePanels'
import { useTripWebSocket } from '../../hooks/useTripWebSocket'
import { useRouteCalculation } from '../../hooks/useRouteCalculation'
@@ -38,6 +39,8 @@ import { isDeepLinkableTripTab, TRIP_TAB_LABEL_KEYS } from '../../constants/trip
import { isRoutableReservation } from '../../utils/reservationRoutes'
import { showReservationOnMap } from '../../components/Planner/bookings/showOnMap'
import { useTripStays } from '../../components/Planner/useTripStays'
import { TAB_PANEL_LOADS } from './tabPanelPreload'
import { warmPackingBags } from '../../components/Packing/usePackingBags'
import {
parseStoredConnections, resolveEffectiveConnections, resolveVisibleConnectionIds,
toggleConnectionId, toggleAllConnections as flipAllConnectionsMode,
@@ -87,6 +90,13 @@ async function fetchRoster(tripId: number): Promise<TripMember[] | null> {
}
}
/** Tabs whose map is kept alive behind the others once it has been opened. */
const MAP_TABS_KEPT = new Set(['plan', 'tour-planner'])
/** How long an opened trip sits before the other tabs' code loads behind it. */
const TAB_PANELS_AHEAD_AFTER_MS = 2000
function loadedOnOpenInstead(): void {}
/**
* Trip planner page logic, the big one. Owns the trip store wiring, addon
* gating, accommodations/members loading, the tab + resizable-panel + selection
@@ -270,12 +280,31 @@ export function useTripPlanner() {
}
}, [activeTab, enabledAddons, addonsLoaded, tripPluginIds, pluginsLoaded, isMobile, largeTouch, journal.settled, journal.openJournalId])
const bagTracking = useAddonStore(s => s.bagTracking)
// The other tabs' code loads while the trip sits open; a load that fails here
// is no error, the tab loads it again when it is opened.
useEffect(() => {
const timer = window.setTimeout(() => {
for (const load of TAB_PANEL_LOADS) load().catch(loadedOnOpenInstead)
// The packing list's bag sidebar too, so Lists opens with it in place.
if (bagTracking && Number.isFinite(tripId) && !isEffectivelyOffline()) warmPackingBags(tripId).catch(loadedOnOpenInstead)
}, TAB_PANELS_AHEAD_AFTER_MS)
return () => window.clearTimeout(timer)
}, [tripId, bagTracking])
// The map tabs opened so far: their maps stay mounted (hidden) once started,
// so going back to one shows it as it was instead of loading it again.
const [keptMapTabs, setKeptMapTabs] = useState<ReadonlySet<string>>(
() => new Set(MAP_TABS_KEPT.has(activeTab) ? [activeTab] : [])
)
const handleTabChange = (rawTabId: string): void => {
// A core tab a plugin replaced is gone from the bar, but a programmatic jump
// (e.g. onNavigateToFiles) could still target it and render a dead panel with
// no active pill — fall back to the plan view like the invalid-tab guard does.
const tabId = replacedTabs.has(rawTabId) ? 'plan' : rawTabId
setActiveTab(tabId)
if (MAP_TABS_KEPT.has(tabId)) setKeptMapTabs(prev => (prev.has(tabId) ? prev : new Set(prev).add(tabId)))
sessionStorage.setItem(`trip-tab-${tripId}`, tabId)
if (tabId === 'finanzplan') tripActions.loadBudgetItems?.(tripId)
if (tabId === 'dateien' && (!files || files.length === 0)) tripActions.loadFiles?.(tripId)
@@ -754,7 +783,7 @@ export function useTripPlanner() {
dawarichTrailShown, toggleDawarichTrail, dawarichTrail, dawarichHiddenDates, dawarichEnabled: !!enabledAddons.dawarich,
followTrack, roadtripViaCounts,
allowedFileTypes, tripMembers, setTripMembers, refreshMembers, loadAccommodations,
TRANSPORT_TYPES, TRIP_TABS, activeTab, setActiveTab, handleTabChange, tabLink,
TRANSPORT_TYPES, TRIP_TABS, activeTab, setActiveTab, handleTabChange, keptMapTabs, tabLink,
leftWidth, rightWidth, viewportWidth, leftCollapsed, rightCollapsed, setLeftCollapsed, setRightCollapsed,
leftHidden, rightHidden, toggleLeft, toggleRight, narrowPanels,
startResizeLeft, startResizeRight, nudgeLeft, nudgeRight, resizing, resizeMin, resizeMaxLeft, resizeMaxRight,