mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-22 03:50:30 +00:00
Compare commits
31 Commits
v5.1.4-tf.1
..
dev
| Author | SHA1 | Date | |
|---|---|---|---|
| 49b9ffc77d | |||
| 7006891ce0 | |||
| 4d01439c75 | |||
| adb6a2c80d | |||
| 1824cc77ec | |||
| 9e2805fc89 | |||
| 77380ea5cf | |||
| 9956c58dd5 | |||
| 3f38621024 | |||
| 2f7b8357ce | |||
| 6861687b1f | |||
| 8fc9fe7945 | |||
| f668eee227 | |||
| 711015d5fd | |||
| 6ebd5cf0c7 | |||
| 8ab7547edf | |||
| f599892a4b | |||
| 1436cec35c | |||
| fe90502955 | |||
| 0431741ad7 | |||
| fa99940945 | |||
| 09316025c3 | |||
| 100313cfa9 | |||
| 411ec4af59 | |||
| ec7f5e0585 | |||
| 8e38749bc3 | |||
| 2c17edd74c | |||
| c5e2afc21b | |||
| 502e6916d9 | |||
| 61674cf918 | |||
| ac01925be7 |
+4
-4
@@ -94,8 +94,8 @@ RUN echo 'deb [signed-by=/etc/apt/keyrings/pgdg.asc] http://apt.postgresql.org/p
|
||||
rm -rf /var/lib/apt/lists/* /usr/local/lib/node_modules/npm /usr/local/bin/npm /usr/local/bin/npx && \
|
||||
chown -R node:node /app
|
||||
|
||||
# gosu rebuilt with a current Go toolchain (stage 0) — the entrypoint script uses
|
||||
# it to drop to node.
|
||||
# gosu rebuilt with a current Go toolchain (stage 0). The entrypoint drops to node
|
||||
# with setpriv since #3135; gosu stays in the image for anyone who calls it by hand.
|
||||
COPY --from=gosu-build /out/gosu /usr/local/bin/gosu
|
||||
|
||||
ENV XDG_CACHE_HOME=/tmp/kf6-cache
|
||||
@@ -173,8 +173,8 @@ HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \
|
||||
# carrying quotes does not survive that round-trip (the container then dies with
|
||||
# a shell syntax error before Node starts). A CMD of one bare token does.
|
||||
COPY server/scripts/entrypoint.sh /usr/local/bin/trek-entrypoint
|
||||
# Root-owned on purpose — this is what calls gosu, so it runs before the drop to
|
||||
# node. chmod is explicit because a checkout on Windows carries no exec bit.
|
||||
# Root-owned on purpose: it runs as root and drops to node itself, with setpriv.
|
||||
# chmod is explicit because a checkout on Windows carries no exec bit.
|
||||
RUN chmod 0755 /usr/local/bin/trek-entrypoint
|
||||
|
||||
ENTRYPOINT ["dumb-init", "--"]
|
||||
|
||||
@@ -512,8 +512,8 @@ struct StopList: View {
|
||||
ForEach(Array(window.enumerated()), id: \.offset) { offset, stop in
|
||||
let past = (stop.minutes ?? Int.max) < nowMinutes
|
||||
let isNext = !past && (offset == 0 || (window[offset - 1].minutes ?? Int.max) < nowMinutes)
|
||||
if isNext && offset > 0, let nowLabel { nowLine(nowLabel) }
|
||||
row(stop, past: past, isNext: isNext, last: offset == window.count - 1)
|
||||
if isNext && offset > 0, let nowLabel { nowLine(nowLabel, in: window) }
|
||||
row(stop, in: window, past: past, isNext: isNext, last: offset == window.count - 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -528,13 +528,33 @@ struct StopList: View {
|
||||
|
||||
private var ink: Color { onPhoto ? .white : Trek.ink(scheme) }
|
||||
|
||||
private func row(_ stop: WidgetSnapshot.Stop, past: Bool, isNext: Bool, last: Bool) -> some View {
|
||||
/// The time column, as wide as the longest time in the window (and the now
|
||||
/// marker's label): every row lays all of them over each other, hidden, so
|
||||
/// "5:45 AM" fits as well as "09:30" and the dots still stand in one line.
|
||||
private func timeColumn<Label: View>(_ window: [WidgetSnapshot.Stop], @ViewBuilder label: () -> Label) -> some View {
|
||||
ZStack(alignment: .leading) {
|
||||
ForEach(Array(window.enumerated()), id: \.offset) { _, stop in
|
||||
Text(stop.time ?? "–").font(Trek.number(11.5, .heavy)).hidden()
|
||||
}
|
||||
if let nowLabel { nowText(nowLabel).hidden() }
|
||||
label()
|
||||
}
|
||||
.lineLimit(1)
|
||||
.fixedSize(horizontal: true, vertical: false)
|
||||
.frame(minWidth: 38, alignment: .leading)
|
||||
}
|
||||
|
||||
private func nowText(_ label: String) -> some View {
|
||||
Text(label.uppercased()).font(.system(size: 8.5, weight: .heavy)).tracking(0.5).foregroundStyle(Trek.danger)
|
||||
}
|
||||
|
||||
private func row(_ stop: WidgetSnapshot.Stop, in window: [WidgetSnapshot.Stop], past: Bool, isNext: Bool, last: Bool) -> some View {
|
||||
let color = Color(css: stop.color) ?? (onPhoto ? .white : Trek.info)
|
||||
return HStack(alignment: .top, spacing: 8) {
|
||||
Text(stop.time ?? "–")
|
||||
.font(Trek.number(11.5, isNext ? .heavy : .semibold))
|
||||
.frame(width: 38, alignment: .leading)
|
||||
.padding(.top, 1)
|
||||
timeColumn(window) {
|
||||
Text(stop.time ?? "–").font(Trek.number(11.5, isNext ? .heavy : .semibold))
|
||||
}
|
||||
.padding(.top, 1)
|
||||
VStack(spacing: 0) {
|
||||
ZStack {
|
||||
Circle().fill(color).frame(width: isNext ? 11 : 8, height: isNext ? 11 : 8)
|
||||
@@ -562,10 +582,9 @@ struct StopList: View {
|
||||
.frame(height: 24, alignment: .top)
|
||||
}
|
||||
|
||||
private func nowLine(_ label: String) -> some View {
|
||||
private func nowLine(_ label: String, in window: [WidgetSnapshot.Stop]) -> some View {
|
||||
HStack(spacing: 5) {
|
||||
Text(label.uppercased()).font(.system(size: 8.5, weight: .heavy)).tracking(0.5).foregroundStyle(Trek.danger)
|
||||
.frame(width: 38, alignment: .leading)
|
||||
timeColumn(window) { nowText(label) }
|
||||
Circle().fill(Trek.danger).frame(width: 5, height: 5).frame(width: 15)
|
||||
Rectangle().fill(Trek.danger).frame(height: 1.2)
|
||||
}
|
||||
|
||||
@@ -5,14 +5,14 @@
|
||||
"no-console": 88,
|
||||
"complexity": 217,
|
||||
"@typescript-eslint/no-explicit-any": 143,
|
||||
"trek/no-swallowed-catch": 127,
|
||||
"trek/no-swallowed-catch": 126,
|
||||
"max-params": 31,
|
||||
"trek/store-without-selector": 66,
|
||||
"react-hooks/refs": 534,
|
||||
"react-hooks/set-state-in-effect": 189,
|
||||
"@typescript-eslint/no-floating-promises": 162,
|
||||
"react-hooks/exhaustive-deps": 113,
|
||||
"@typescript-eslint/no-unused-vars": 121,
|
||||
"@typescript-eslint/no-unused-vars": 120,
|
||||
"react-hooks/immutability": 28,
|
||||
"max-lines-per-function": 127,
|
||||
"react-hooks/static-components": 50,
|
||||
|
||||
@@ -190,7 +190,7 @@
|
||||
{
|
||||
"feature": "Booking mail import: admin card",
|
||||
"hooks": ["src/components/Admin/mailIngest/useMailIngestAdmin.ts", "src/components/Admin/mailIngest/mailIngestAdminModel.ts"],
|
||||
"desktop": ["src/components/Admin/mailIngest/MailIngestAdminCard.tsx"],
|
||||
"desktop": ["src/components/Admin/mailIngest/MailIngestAddonTile.tsx"],
|
||||
"mobile": ["src/mobile/screens/admin/MMailIngestAdminCard.tsx"]
|
||||
},
|
||||
{
|
||||
@@ -1113,8 +1113,8 @@
|
||||
"mobile": ["src/mobile/screens/admin/MAdminSchoolHolidayCatalog.tsx"]
|
||||
},
|
||||
{
|
||||
"feature": "Trip settings: members, guests, public and invite link",
|
||||
"hooks": ["src/components/Trips/useTripShare.ts"],
|
||||
"feature": "Trip settings: members, guests, public and invite link, the trip's own addons",
|
||||
"hooks": ["src/components/Trips/useTripShare.ts", "src/components/Trips/useTripAddonRows.ts"],
|
||||
"desktop": ["src/components/Trips/TripShareDialog.tsx"],
|
||||
"mobile": ["src/mobile/screens/trip/sheets/MTripSettingsSheet.tsx"]
|
||||
}
|
||||
|
||||
@@ -1542,7 +1542,6 @@
|
||||
"src/pages/journeyDetail/useJourneyDetail.ts",
|
||||
"src/pages/journeyDetail/useProviderPhotoAdds.test.tsx",
|
||||
"src/pages/journeyDetail/useProviderPhotoAdds.ts",
|
||||
"src/pages/journeyPublic/journeyPublicModel.ts",
|
||||
"src/pages/journeyPublic/useJourneyPublic.ts",
|
||||
"src/pages/journeyStudio/useJourneyStudio.test.tsx",
|
||||
"src/pages/journeyStudio/useJourneyStudio.ts",
|
||||
|
||||
@@ -22,6 +22,6 @@
|
||||
"src/pages/TripPlannerPage.tsx": 1128,
|
||||
"src/pages/atlas/useAtlas.ts": 1207,
|
||||
"src/pages/tripPlanner/useTripPlanner.roadtrip.test.tsx": 3518,
|
||||
"src/pages/tripPlanner/useTripPlanner.test.tsx": 3269,
|
||||
"src/pages/tripPlanner/useTripPlanner.test.tsx": 3267,
|
||||
"src/styles/studio.css": 1918
|
||||
}
|
||||
|
||||
@@ -113,7 +113,6 @@
|
||||
"src/pages/AtlasPage.tsx": 6,
|
||||
"src/pages/FilesPage.tsx": 1,
|
||||
"src/pages/JourneyDetailPage.tsx": 1,
|
||||
"src/pages/JourneyPublicPage.test.tsx": 1,
|
||||
"src/pages/LoginPage.tsx": 1,
|
||||
"src/pages/VacayPage.tsx": 1,
|
||||
"src/pages/admin/useAdmin.ts": 4,
|
||||
@@ -130,7 +129,7 @@
|
||||
"src/pages/tripPlanner/usePlaceEdits.ts": 2,
|
||||
"src/pages/tripPlanner/usePlaceFormOpeners.test.ts": 2,
|
||||
"src/pages/tripPlanner/usePlaceFormOpeners.ts": 1,
|
||||
"src/pages/tripPlanner/useTripPlanner.ts": 2,
|
||||
"src/pages/tripPlanner/useTripPlanner.ts": 1,
|
||||
"src/repo/tripRepo.ts": 2,
|
||||
"src/store/slices/budgetSlice.test.ts": 1,
|
||||
"src/utils/formatters.test.ts": 1,
|
||||
|
||||
@@ -146,7 +146,7 @@
|
||||
"mobile/components/MToastHost.tsx": 2,
|
||||
"mobile/components/MUserPickerList.tsx": 1,
|
||||
"mobile/screens/admin/MAdmin.tsx": 8,
|
||||
"mobile/screens/admin/MAdminAddonManager.tsx": 4,
|
||||
"mobile/screens/admin/MAdminAddonManager.tsx": 3,
|
||||
"mobile/screens/admin/MAdminAuditLogPanel.tsx": 15,
|
||||
"mobile/screens/admin/MAdminBackupPanel.tsx": 7,
|
||||
"mobile/screens/admin/MAdminCategoryManager.tsx": 8,
|
||||
|
||||
@@ -30,6 +30,7 @@ import { takeResumeRoute, useRememberRoute } from './utils/resumeRoute'
|
||||
import { usePermissionsStore, PermissionLevel } from './store/permissionsStore'
|
||||
import { useInAppNotificationListener } from './hooks/useInAppNotificationListener.ts'
|
||||
import { useRoadtripPreferencesSync } from './hooks/useRoadtripPreferencesSync'
|
||||
import { useTripAddonsSync } from './hooks/useTripAddonsSync'
|
||||
import { registerSyncTriggers, unregisterSyncTriggers } from './sync/syncTriggers'
|
||||
import OfflineBanner from './components/Layout/OfflineBanner'
|
||||
import NewVersionNotice from './components/Layout/NewVersionNotice'
|
||||
@@ -379,6 +380,7 @@ export default function App() {
|
||||
|
||||
useInAppNotificationListener()
|
||||
useRoadtripPreferencesSync()
|
||||
useTripAddonsSync()
|
||||
|
||||
useEffect(() => {
|
||||
if (isAuthenticated) {
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
import type { TripAddonsResponse, TripAddonUpdateRequest } from '@trek/shared';
|
||||
import apiClient from './client';
|
||||
|
||||
/** The trip addons of one trip, each on or off for it: every member reads them, only the owner switches one. */
|
||||
export const tripAddonsApi = {
|
||||
list: (tripId: number): Promise<TripAddonsResponse> => apiClient.get(`/trips/${tripId}/addons`).then((r) => r.data),
|
||||
/** `enabled: null` drops the trip's own choice, so the instance setting applies again. */
|
||||
update: (tripId: number, addonId: string, body: TripAddonUpdateRequest): Promise<TripAddonsResponse> =>
|
||||
apiClient.put(`/trips/${tripId}/addons/${encodeURIComponent(addonId)}`, body).then((r) => r.data),
|
||||
};
|
||||
@@ -46,6 +46,10 @@ export const HANDLED_OUTSIDE_TRIP_STORE = [
|
||||
'roadtripVia:changed',
|
||||
'roadtripTrack:changed',
|
||||
'roadtripPreferences:changed',
|
||||
// Per-trip addons: store/tripAddonsStore (watchTripAddons, mounted by App through
|
||||
// hooks/useTripAddonsSync) puts the trip's list into the store and the device's copy, so the
|
||||
// tabs and panels a trip switched off disappear for every member at once.
|
||||
'tripAddons:changed',
|
||||
// components/Roadtrip/useDayBoundaries reloads the shared boundaries.
|
||||
'roadtripBoundary:changed',
|
||||
// In-app notifications: hooks/useInAppNotificationListener, which also keeps
|
||||
|
||||
@@ -7,6 +7,7 @@ import { useAuthStore } from '../../store/authStore';
|
||||
import { useSettingsStore } from '../../store/settingsStore';
|
||||
import { useAddonStore } from '../../store/addonStore';
|
||||
import { ToastContainer } from '../shared/Toast';
|
||||
import { mailIngestRepo } from '../../repo/mailIngestRepo';
|
||||
import AddonManager from './AddonManager';
|
||||
|
||||
function buildAddon(overrides = {}) {
|
||||
@@ -691,4 +692,40 @@ describe('AddonManager', () => {
|
||||
expect(roadtrip.querySelector('svg.lucide-car-front')).toBeInTheDocument();
|
||||
expect(tours.querySelector('svg.lucide-puzzle')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-ADDON-045: live flight status is a row of the trip card, switched there and locked by the environment', async () => {
|
||||
server.use(addonsRoute([buildAddon({ id: 'packing', name: 'Lists', icon: 'ListChecks', type: 'trip', enabled: true })]));
|
||||
const onToggle = vi.fn();
|
||||
const { unmount } = render(<AddonManager flightLive={{ on: false, locked: false, managed: false, onToggle }} />);
|
||||
const trip = (await screen.findByRole('heading', { name: 'Trip' })).closest('section') as HTMLElement;
|
||||
await userEvent.click(within(trip).getByRole('button', { name: 'Follow booked flights live' }));
|
||||
expect(onToggle).toHaveBeenCalledTimes(1);
|
||||
// The count stays the addons': the flight row is an instance option beside them.
|
||||
expect(within(trip).getByText('1/1')).toBeInTheDocument();
|
||||
unmount();
|
||||
|
||||
render(<AddonManager flightLive={{ on: true, locked: true, managed: false, onToggle }} />);
|
||||
expect(await screen.findByRole('button', { name: 'Follow booked flights live' })).toBeDisabled();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-ADDON-046: the booking mail import is a row of the integration card whose setup opens in a dialog', async () => {
|
||||
server.use(addonsRoute([buildAddon({ id: 'mcp', name: 'MCP', icon: 'Terminal', type: 'integration', enabled: false })]));
|
||||
vi.spyOn(mailIngestRepo, 'adminSettings').mockResolvedValue({ mail_ingest_enabled: 'true' });
|
||||
vi.spyOn(mailIngestRepo, 'adminStatus').mockRejectedValue(new Error('no status'));
|
||||
render(<AddonManager mailImport />);
|
||||
const integration = (await screen.findByRole('heading', { name: 'Integration' })).closest('section') as HTMLElement;
|
||||
expect(within(integration).getByText('Booking mail import')).toBeInTheDocument();
|
||||
await userEvent.click(await within(integration).findByRole('button', { name: 'Set up mail import' }));
|
||||
const dialog = await screen.findByRole('dialog');
|
||||
expect(within(dialog).getByText('How mail arrives')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-ADDON-047: without the mail option the integration card has no mail row and nothing is loaded', async () => {
|
||||
server.use(addonsRoute([buildAddon({ id: 'mcp', name: 'MCP', icon: 'Terminal', type: 'integration', enabled: false })]));
|
||||
const load = vi.spyOn(mailIngestRepo, 'adminSettings');
|
||||
render(<AddonManager />);
|
||||
await screen.findByRole('heading', { name: 'Integration' });
|
||||
expect(screen.queryByText('Booking mail import')).not.toBeInTheDocument();
|
||||
expect(load).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { ComponentType, ReactNode } from 'react'
|
||||
import type { ComponentType } from 'react'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { Puzzle, ListChecks, Wallet, FileText, CalendarDays, Globe, Briefcase, Image, Terminal, Link2, Compass, BookOpen, Sparkles, Luggage, Plane, Bookmark, Users, Loader2, Mountain, CarFront } from 'lucide-react'
|
||||
import { Puzzle, ListChecks, Wallet, FileText, CalendarDays, Globe, Briefcase, Image, Terminal, Link2, Compass, BookOpen, Sparkles, Luggage, Plane, Bookmark, Users, Loader2, Mountain, CarFront, Radar } from 'lucide-react'
|
||||
import EmptyState from '../shared/EmptyState'
|
||||
import DawarichIcon from '../shared/DawarichIcon'
|
||||
import AirTrailIcon from '../shared/AirTrailIcon'
|
||||
@@ -12,6 +12,9 @@ import { SettingsCard, SettingsColumns, StatusPill } from '../Settings/settingsK
|
||||
import { type Addon, type CollabFeatures, COLLAB_SUB_FEATURES, getAddonLabel } from './addons/addonModel'
|
||||
import { useAddonManager } from './addons/useAddonManager'
|
||||
import AiAddonTile from './addons/AiAddonTile'
|
||||
import MailIngestAddonTile from './mailIngest/MailIngestAddonTile'
|
||||
import PaddleRegionsPanel from './paddle/PaddleRegionsPanel'
|
||||
import ToggleSwitch from '../Settings/ToggleSwitch'
|
||||
import { ImmichIcon, SynologyIcon } from './addons/PhotoProviderIcons'
|
||||
import WandererMark from '../Tours/wanderer/WandererMark'
|
||||
|
||||
@@ -65,13 +68,24 @@ const TYPE_META: Record<string, { icon: ComponentType<{ size?: number }>; labelK
|
||||
integration: { icon: Link2, labelKey: 'admin.addons.type.integration', hintKey: 'admin.addons.integrationHint' },
|
||||
}
|
||||
|
||||
export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking, collabFeatures, onToggleCollabFeature, aside }: {
|
||||
/** The live flight status switch, an instance setting that sits with the trip addons. */
|
||||
export interface FlightLiveOption {
|
||||
on: boolean
|
||||
/** The server environment (FLIGHT_LIVE_ENABLED) holds it; the switch shows the state and says why. */
|
||||
locked: boolean
|
||||
managed: boolean
|
||||
onToggle: () => void
|
||||
}
|
||||
|
||||
export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking, collabFeatures, onToggleCollabFeature, flightLive, mailImport = false }: {
|
||||
bagTrackingEnabled?: boolean
|
||||
onToggleBagTracking?: () => void
|
||||
collabFeatures?: CollabFeatures
|
||||
onToggleCollabFeature?: (key: string) => void
|
||||
/** Cards that set up what the integrations reach (flight status, booking mails), under them in the right column. */
|
||||
aside?: ReactNode
|
||||
/** Live flight status, a row of the trip card: it follows the trips' booked flights. */
|
||||
flightLive?: FlightLiveOption
|
||||
/** Booking mail import, a row of the integration card with its setup dialog; off on a managed install. */
|
||||
mailImport?: boolean
|
||||
}) {
|
||||
const { t } = useTranslation()
|
||||
const {
|
||||
@@ -181,6 +195,8 @@ export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking,
|
||||
onToggle={() => void toggle()}
|
||||
/>
|
||||
)),
|
||||
// The paddle water data the tour planner reads, set up in a dialog of its own.
|
||||
<PaddleRegionsPanel key="paddle-regions" />,
|
||||
]
|
||||
}
|
||||
return null
|
||||
@@ -202,6 +218,9 @@ export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking,
|
||||
)
|
||||
}
|
||||
|
||||
/** Whether a card holds rows beside its own addons: the AI tile, an instance option. */
|
||||
const extraRows = (key: string) =>
|
||||
(key === 'trip' && !!flightLive) || (key === 'integration' && (aiAddons.length > 0 || mailImport))
|
||||
/* A card per type, the way every other admin tab sets its cards: Trip in the
|
||||
left column, Global and Integration in the right one, each card with the
|
||||
dialogs' head band carrying the type, its count and what it means. */
|
||||
@@ -209,14 +228,14 @@ export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking,
|
||||
{ key: 'trip', addons: tripAddons },
|
||||
{ key: 'global', addons: globalAddons },
|
||||
{ key: 'integration', addons: integrationAddons },
|
||||
].filter(g => g.addons.length > 0 || (g.key === 'integration' && aiAddons.length > 0))
|
||||
].filter(g => g.addons.length > 0 || extraRows(g.key))
|
||||
|
||||
const card = (g: (typeof groups)[number]) => {
|
||||
const meta = TYPE_META[g.key]
|
||||
const all = g.key === 'integration' ? [...aiAddons, ...g.addons] : g.addons
|
||||
const visible = g.addons
|
||||
const ai = g.key === 'integration' && aiAddons.length > 0
|
||||
if (!visible.length && !ai) return null
|
||||
if (!visible.length && !ai && !extraRows(g.key)) return null
|
||||
const on = all.filter(a => a.enabled).length
|
||||
return (
|
||||
<SettingsCard
|
||||
@@ -235,6 +254,10 @@ export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking,
|
||||
{/* The AI addons share a connection and a settings dialog, so they head the card as one tile. */}
|
||||
{ai && <AiAddonTile addons={aiAddons} onToggle={handleToggle} />}
|
||||
{visible.map(tile)}
|
||||
{/* Not addons but instance options of the same kind, as rows of the same card;
|
||||
the count above stays the addons'. */}
|
||||
{g.key === 'trip' && flightLive && <FlightLiveTile option={flightLive} />}
|
||||
{g.key === 'integration' && mailImport && <MailIngestAddonTile />}
|
||||
</div>
|
||||
</SettingsCard>
|
||||
)
|
||||
@@ -251,5 +274,21 @@ export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking,
|
||||
)
|
||||
}
|
||||
|
||||
return <SettingsColumns start={cards.start} end={<>{cards.end}{aside}</>} />
|
||||
return <SettingsColumns start={cards.start} end={cards.end} />
|
||||
}
|
||||
|
||||
/** Live flight status as a trip row: on, it follows every booked flight on its day. */
|
||||
function FlightLiveTile({ option }: { option: FlightLiveOption }) {
|
||||
const { t } = useTranslation()
|
||||
const name = t('flightLive.adminTitle')
|
||||
const hint = option.managed ? t('flightLive.adminHintManaged') : t('flightLive.adminHint')
|
||||
return (
|
||||
<AddonTile
|
||||
icon={<Radar size={18} />}
|
||||
name={name}
|
||||
description={option.locked ? `${hint} ${t('flightLive.envLocked')}` : hint}
|
||||
enabled={option.on}
|
||||
trailing={<ToggleSwitch on={option.on} label={t('flightLive.adminToggle')} disabled={option.locked} onToggle={option.onToggle} />}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
import React, { useId, type ReactNode } from 'react';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import {
|
||||
DialogButton,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogShell,
|
||||
DialogTile,
|
||||
FooterSpacer,
|
||||
NEUTRAL_TINT,
|
||||
} from '../shared/DialogShell';
|
||||
|
||||
/**
|
||||
* The dialog an addon's setup row opens: the icon tile, the addon it belongs
|
||||
* to above the title, what it sets up below, and one Close, since everything
|
||||
* inside saves on its own (booking mails, paddle water data).
|
||||
*/
|
||||
export default function AddonSetupDialog({
|
||||
icon,
|
||||
eyebrow,
|
||||
title,
|
||||
sub,
|
||||
onClose,
|
||||
blocked = false,
|
||||
children,
|
||||
}: {
|
||||
icon: ReactNode;
|
||||
eyebrow: string;
|
||||
title: string;
|
||||
sub: string;
|
||||
onClose: () => void;
|
||||
/** A confirmation stacked on top holds the dialog while it is open. */
|
||||
blocked?: boolean;
|
||||
children: ReactNode;
|
||||
}): React.ReactElement {
|
||||
const { t } = useTranslation();
|
||||
const labelId = useId();
|
||||
return (
|
||||
<DialogShell
|
||||
onClose={onClose}
|
||||
labelledBy={labelId}
|
||||
width="detail"
|
||||
blocked={blocked}
|
||||
header={
|
||||
<DialogHeader
|
||||
tile={<DialogTile>{icon}</DialogTile>}
|
||||
tint={NEUTRAL_TINT}
|
||||
labelId={labelId}
|
||||
eyebrow={eyebrow}
|
||||
title={title}
|
||||
sub={sub}
|
||||
subWraps
|
||||
onClose={onClose}
|
||||
/>
|
||||
}
|
||||
footer={
|
||||
<DialogFooter>
|
||||
<FooterSpacer />
|
||||
<DialogButton variant="primary" onClick={onClose}>
|
||||
{t('common.close')}
|
||||
</DialogButton>
|
||||
</DialogFooter>
|
||||
}
|
||||
>
|
||||
{children}
|
||||
</DialogShell>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { ChevronRight, Settings2 } from 'lucide-react';
|
||||
import React, { type ReactNode } from 'react';
|
||||
import { fs } from '../shared/DialogShell';
|
||||
|
||||
/**
|
||||
* The last row of an addon's shelf that opens its settings dialog: a gear, what
|
||||
* the dialog sets up, and a chevron. It keeps a card of addons as short as its
|
||||
* switches and puts the long forms behind one tap (AI, booking mails, paddle
|
||||
* water data). A badge says what waits inside, such as requests to look at.
|
||||
*/
|
||||
export default function AddonSetupRow({
|
||||
label,
|
||||
onOpen,
|
||||
badge,
|
||||
}: {
|
||||
label: string;
|
||||
onOpen: () => void;
|
||||
badge?: ReactNode;
|
||||
}): React.ReactElement {
|
||||
return (
|
||||
<li>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onOpen}
|
||||
className="flex min-h-[44px] w-full items-center gap-2.5 border-0 bg-transparent py-1.5 pe-4 ps-[60px] text-start transition-colors hover:bg-surface-hover focus-visible:bg-surface-hover focus-visible:outline-none"
|
||||
>
|
||||
<span className="grid h-6 w-6 flex-none place-items-center text-content-muted">
|
||||
<Settings2 size={14} />
|
||||
</span>
|
||||
<span className="min-w-0 flex-1 truncate font-medium text-content" style={fs(12.5, 'body')}>
|
||||
{label}
|
||||
</span>
|
||||
{badge}
|
||||
<ChevronRight size={15} strokeWidth={2.2} className="flex-none text-content-faint rtl:rotate-180" />
|
||||
</button>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
import { ChevronRight, Settings2, Sparkles } from 'lucide-react';
|
||||
import { Sparkles } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import { useTranslation } from '../../../i18n';
|
||||
import { StatusPill } from '../../Settings/settingsKit';
|
||||
import { fs } from '../../shared/DialogShell';
|
||||
import AddonSetupRow from '../AddonSetupRow';
|
||||
import AddonSubRow from '../AddonSubRow';
|
||||
import AddonTile from '../AddonTile';
|
||||
import { type Addon, getAddonLabel } from './addonModel';
|
||||
@@ -54,23 +55,7 @@ export default function AiAddonTile({
|
||||
/>
|
||||
);
|
||||
})}
|
||||
{tile.canSetUp && (
|
||||
<li>
|
||||
<button
|
||||
type="button"
|
||||
onClick={tile.openDialog}
|
||||
className="flex min-h-[44px] w-full items-center gap-2.5 border-0 bg-transparent py-1.5 pe-4 ps-[60px] text-start transition-colors hover:bg-surface-hover focus-visible:bg-surface-hover focus-visible:outline-none"
|
||||
>
|
||||
<span className="grid h-6 w-6 flex-none place-items-center text-content-muted">
|
||||
<Settings2 size={14} />
|
||||
</span>
|
||||
<span className="min-w-0 flex-1 truncate font-medium text-content" style={fs(12.5, 'body')}>
|
||||
{t('admin.addons.ai.setup')}
|
||||
</span>
|
||||
<ChevronRight size={15} strokeWidth={2.2} className="flex-none text-content-faint rtl:rotate-180" />
|
||||
</button>
|
||||
</li>
|
||||
)}
|
||||
{tile.canSetUp && <AddonSetupRow label={t('admin.addons.ai.setup')} onOpen={tile.openDialog} />}
|
||||
</AddonTile>
|
||||
{tile.dialogOpen && <AiSettingsDialog addons={addons} onClose={tile.closeDialog} />}
|
||||
</>
|
||||
|
||||
+42
-33
@@ -1,22 +1,17 @@
|
||||
import { AlertTriangle, CheckCircle, Copy, Loader2, Mail, PlugZap, Save, XCircle } from 'lucide-react';
|
||||
import type { ReactNode } from 'react';
|
||||
import { useState, type ReactNode } from 'react';
|
||||
import { useTranslation } from '../../../i18n';
|
||||
import type { TranslationFn } from '../../../types';
|
||||
import { copyText } from '../../../utils/clipboard';
|
||||
import { relativeTime } from '../../../utils/relativeTime';
|
||||
import {
|
||||
HintMark,
|
||||
SETTINGS_BUTTON,
|
||||
SETTINGS_BUTTON_PRIMARY,
|
||||
SettingRow,
|
||||
SettingRows,
|
||||
SettingsCard,
|
||||
StatusPill,
|
||||
} from '../../Settings/settingsKit';
|
||||
import { HintMark, SETTINGS_BUTTON, SETTINGS_BUTTON_PRIMARY, StatusPill } from '../../Settings/settingsKit';
|
||||
import ToggleSwitch from '../../Settings/ToggleSwitch';
|
||||
import CustomSelect from '../../shared/CustomSelect';
|
||||
import { EditorField, GRID_2, INPUT, READONLY_BOX } from '../../shared/dialogParts';
|
||||
import { useToast } from '../../shared/Toast';
|
||||
import AddonSetupDialog from '../AddonSetupDialog';
|
||||
import AddonSetupRow from '../AddonSetupRow';
|
||||
import AddonTile from '../AddonTile';
|
||||
import {
|
||||
TRANSPORTS,
|
||||
problemText,
|
||||
@@ -306,32 +301,46 @@ function Setup({ admin, form, t, locale }: { admin: MailIngestAdmin; form: MailA
|
||||
}
|
||||
|
||||
/**
|
||||
* The booking mail import in the admin settings of a self-hosted install: the
|
||||
* instance switch, how mail arrives (IMAP or a signed webhook), the forwarding
|
||||
* address template, the AI allowance per person and day, a connection test and
|
||||
* the status in counts. Not shown on a managed install, where the operator
|
||||
* runs the TREK Cloud relay.
|
||||
* The booking mail import as a row of the integration card: its switch, and
|
||||
* while it is on one row to the dialog that sets it up (how mail arrives, the
|
||||
* forwarding address template, the AI allowance per person and day, a
|
||||
* connection test and the status in counts). Not shown on a managed install,
|
||||
* where the operator runs the TREK Cloud relay.
|
||||
*/
|
||||
export default function MailIngestAdminCard() {
|
||||
export default function MailIngestAddonTile() {
|
||||
const { t, locale } = useTranslation();
|
||||
const admin = useMailIngestAdmin(true);
|
||||
const [open, setOpen] = useState(false);
|
||||
const name = t('mailAdmin.title');
|
||||
return (
|
||||
<SettingsCard icon={Mail} title={t('mailAdmin.title')} hint={t('mailAdmin.hint')}>
|
||||
<SettingRows>
|
||||
<SettingRow
|
||||
label={t('mailAdmin.enabled')}
|
||||
hint={t('mailAdmin.enabledHint')}
|
||||
control={
|
||||
<ToggleSwitch
|
||||
on={admin.enabled}
|
||||
label={t('mailAdmin.enabled')}
|
||||
disabled={!admin.loaded}
|
||||
onToggle={() => admin.toggle(!admin.enabled)}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</SettingRows>
|
||||
{admin.enabled && admin.form && <Setup admin={admin} form={admin.form} t={t} locale={locale} />}
|
||||
</SettingsCard>
|
||||
<>
|
||||
<AddonTile
|
||||
icon={<Mail size={15} />}
|
||||
name={name}
|
||||
description={`${t('mailAdmin.hint')} ${t('mailAdmin.enabledHint')}`}
|
||||
enabled={admin.enabled}
|
||||
trailing={
|
||||
<ToggleSwitch
|
||||
on={admin.enabled}
|
||||
label={t('mailAdmin.enabled')}
|
||||
disabled={!admin.loaded}
|
||||
onToggle={() => admin.toggle(!admin.enabled)}
|
||||
/>
|
||||
}
|
||||
>
|
||||
{admin.enabled && admin.form && <AddonSetupRow label={t('mailAdmin.setup')} onOpen={() => setOpen(true)} />}
|
||||
</AddonTile>
|
||||
{open && admin.enabled && admin.form && (
|
||||
<AddonSetupDialog
|
||||
icon={<Mail size={20} strokeWidth={2} />}
|
||||
eyebrow={name}
|
||||
title={t('mailAdmin.setup')}
|
||||
sub={t('mailAdmin.hint')}
|
||||
onClose={() => setOpen(false)}
|
||||
>
|
||||
<Setup admin={admin} form={admin.form} t={t} locale={locale} />
|
||||
</AddonSetupDialog>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -78,17 +78,22 @@ function adminState(overrides: Partial<Admin> = {}, search: Partial<Admin['searc
|
||||
};
|
||||
}
|
||||
|
||||
function show(overrides: Partial<Admin> = {}, search: Partial<Admin['search']> = {}) {
|
||||
/** The panel as the Tours shelf shows it: a setup row, opened into its dialog unless asked not to. */
|
||||
function show(overrides: Partial<Admin> = {}, search: Partial<Admin['search']> = {}, { open = true } = {}) {
|
||||
const state = adminState(overrides, search);
|
||||
hook.usePaddleRegionsAdmin.mockReturnValue(state);
|
||||
return { state, ...render(<PaddleRegionsPanel />) };
|
||||
const view = render(
|
||||
<ul>
|
||||
<PaddleRegionsPanel />
|
||||
</ul>
|
||||
);
|
||||
if (open && state.toursOn) fireEvent.click(setupRow());
|
||||
return { state, ...view };
|
||||
}
|
||||
|
||||
/** The card's title row, where the number of regions sits beside the title. */
|
||||
function titleRow(): HTMLElement {
|
||||
const row = screen.getByRole('heading', { name: 'Paddle water data' }).parentElement;
|
||||
if (!row) throw new Error('no title row');
|
||||
return row;
|
||||
/** The shelf row that opens the dialog, where the count of requests or regions sits beside the title. */
|
||||
function setupRow(): HTMLElement {
|
||||
return screen.getAllByRole('button', { name: /^Paddle water data/ })[0];
|
||||
}
|
||||
|
||||
function rowOf(name: string): HTMLElement {
|
||||
@@ -100,7 +105,7 @@ function rowOf(name: string): HTMLElement {
|
||||
describe('PaddleRegionsPanel', () => {
|
||||
it('FE-ADMIN-PADDLEREG-001: renders nothing while the Tours addon is off', () => {
|
||||
const { container } = show({ toursOn: false, regions: [READY] });
|
||||
expect(container).toBeEmptyDOMElement();
|
||||
expect(container.querySelector('ul')).toBeEmptyDOMElement();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-PADDLEREG-002: shows the card with its hint, the attribution and the empty state', () => {
|
||||
@@ -110,7 +115,7 @@ describe('PaddleRegionsPanel', () => {
|
||||
expect(screen.getByText(EMPTY)).toBeInTheDocument();
|
||||
expect(screen.getByText(ATTRIBUTION)).toBeInTheDocument();
|
||||
// No count beside the title while there is no region.
|
||||
expect(titleRow()).toHaveTextContent(/^Paddle water data$/);
|
||||
expect(setupRow()).toHaveTextContent(/^Paddle water data$/);
|
||||
const search = screen.getByRole('searchbox', { name: 'Add a region' });
|
||||
expect(search).toBeEnabled();
|
||||
expect(search).toHaveAttribute('placeholder', 'Search Geofabrik, for example Oberpfalz');
|
||||
@@ -277,12 +282,31 @@ describe('PaddleRegionsPanel', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('FE-ADMIN-PADDLEREG-019: the title carries the number of regions', () => {
|
||||
it('FE-ADMIN-PADDLEREG-019: the setup row carries the open requests, else the number of regions', () => {
|
||||
show({ regions: [READY, WAITING, FAILED_FIRST] });
|
||||
expect(within(titleRow()).getByText('3')).toBeInTheDocument();
|
||||
expect(within(setupRow()).getByText('3')).toBeInTheDocument();
|
||||
expect(screen.getAllByTestId('paddle-region-row')).toHaveLength(3);
|
||||
});
|
||||
|
||||
it('FE-ADMIN-PADDLEREG-019b: an open request outranks the region count, a declined one does not count', () => {
|
||||
const base = { bytes: 1, requested_by: 'elmo', requested_at: '2026-10-18T09:00:00Z' };
|
||||
show(
|
||||
{
|
||||
regions: [READY, WAITING],
|
||||
requests: [
|
||||
{ ...base, id: 'norway', name: 'Norway', reason: 'too_large', declined: true },
|
||||
{ ...base, id: 'saale', name: 'Saale', reason: 'limit', declined: false },
|
||||
],
|
||||
},
|
||||
{},
|
||||
{ open: false }
|
||||
);
|
||||
expect(within(setupRow()).getByText('1')).toBeInTheDocument();
|
||||
expect(within(setupRow()).queryByText('2')).toBeNull();
|
||||
// Closed until the row is opened.
|
||||
expect(screen.queryByRole('dialog')).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-PADDLEREG-020: removing asks first, naming the region, and confirming hands it to the hook', () => {
|
||||
const { state } = show({ regions: [READY], removing: READY });
|
||||
const message = 'Oberpfalz and its obstacle data are removed. Paddle tours there then show no data.';
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { PaddleRegion, PaddleRegionCatalogEntry } from '@trek/shared';
|
||||
import { Check, ChevronRight, Loader2, Plus, RefreshCw, Search, Trash2, Waves, WifiOff } from 'lucide-react';
|
||||
import { useId } from 'react';
|
||||
import { useId, useState } from 'react';
|
||||
import { useDateFormat } from '../../../hooks/useDateFormat';
|
||||
import { useTranslation } from '../../../i18n';
|
||||
import { formatDisplayDate } from '../../../utils/dateFormat';
|
||||
@@ -8,7 +8,6 @@ import {
|
||||
SettingRows,
|
||||
SETTINGS_BUTTON,
|
||||
SETTINGS_ICON_BUTTON,
|
||||
SettingsCard,
|
||||
SettingsHint,
|
||||
StatusPill,
|
||||
} from '../../Settings/settingsKit';
|
||||
@@ -17,6 +16,8 @@ import { EditorField, INPUT } from '../../shared/dialogParts';
|
||||
import { fs } from '../../shared/DialogShell';
|
||||
import ErrorBoundary from '../../shared/ErrorBoundary';
|
||||
import { Tooltip } from '../../shared/Tooltip';
|
||||
import AddonSetupDialog from '../AddonSetupDialog';
|
||||
import AddonSetupRow from '../AddonSetupRow';
|
||||
import { AutoLoadSettings, AutoOriginPill, RequestList } from './PaddleAutoLoadParts';
|
||||
import { progressPercent, regionStatusTone } from './paddleRegionsModel';
|
||||
import { usePaddleRegionsAdmin } from './usePaddleRegionsAdmin';
|
||||
@@ -27,8 +28,10 @@ type Admin = ReturnType<typeof usePaddleRegionsAdmin>;
|
||||
* PAD-05A in the admin area: the regions TREK reads paddle obstacles for,
|
||||
* picked from Geofabrik's list, and (PAD-11C) how TREK loads the region of a
|
||||
* place a paddler plans in by itself, with the regions that wait for an admin.
|
||||
* The desktop admin shows this card under the addons while the Tours addon
|
||||
* is on; the phone has MAdminPaddleRegionsPanel on the same hook.
|
||||
* The desktop admin shows it as a row of the Tours addon that opens it as a
|
||||
* dialog while the addon is on; the row counts what waits for the admin (the
|
||||
* requests) or else the regions. The phone has MAdminPaddleRegionsPanel on
|
||||
* the same hook.
|
||||
*/
|
||||
export default function PaddleRegionsPanel() {
|
||||
return (
|
||||
@@ -41,14 +44,42 @@ export default function PaddleRegionsPanel() {
|
||||
function Panel() {
|
||||
const { t } = useTranslation();
|
||||
const admin = usePaddleRegionsAdmin();
|
||||
const [open, setOpen] = useState(false);
|
||||
if (!admin.toursOn) return null;
|
||||
const title = t('admin.paddleRegions.title');
|
||||
// A declined request no longer waits for anyone; only the open ones ask for a look.
|
||||
const waiting = admin.requests.filter((r) => !r.declined).length;
|
||||
const badge =
|
||||
waiting > 0 ? (
|
||||
<StatusPill tone="warning">{waiting}</StatusPill>
|
||||
) : admin.regions.length > 0 ? (
|
||||
<StatusPill>{admin.regions.length}</StatusPill>
|
||||
) : undefined;
|
||||
const close = () => setOpen(false);
|
||||
return (
|
||||
<SettingsCard
|
||||
icon={Waves}
|
||||
title={t('admin.paddleRegions.title')}
|
||||
hint={t('admin.paddleRegions.hint')}
|
||||
badge={admin.regions.length > 0 ? <StatusPill>{admin.regions.length}</StatusPill> : undefined}
|
||||
>
|
||||
<>
|
||||
<AddonSetupRow label={title} onOpen={() => setOpen(true)} badge={badge} />
|
||||
{open && (
|
||||
<AddonSetupDialog
|
||||
icon={<Waves size={20} strokeWidth={2} />}
|
||||
eyebrow={t('admin.addons.catalog.tours.name')}
|
||||
title={title}
|
||||
sub={t('admin.paddleRegions.hint')}
|
||||
onClose={close}
|
||||
blocked={admin.removing !== null}
|
||||
>
|
||||
<PanelBody admin={admin} />
|
||||
</AddonSetupDialog>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** What the dialog holds: the state of the list, the settings, the requests, the search and the regions. */
|
||||
function PanelBody({ admin }: { admin: Admin }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
{admin.offline && (
|
||||
<p
|
||||
role="status"
|
||||
@@ -86,7 +117,7 @@ function Panel() {
|
||||
message={t('admin.paddleRegions.removeMessage', { name: admin.removing?.name ?? '' })}
|
||||
confirmLabel={t('common.remove')}
|
||||
/>
|
||||
</SettingsCard>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -47,7 +47,6 @@ function look(over: Partial<JourneyEntryLook> = {}): JourneyEntryLook {
|
||||
photoId: 7,
|
||||
video: false,
|
||||
photoCount: 1,
|
||||
visibility: 'private',
|
||||
draft: false,
|
||||
fromTripPlace: false,
|
||||
dayIndex: 0,
|
||||
@@ -86,13 +85,15 @@ afterEach(() => {
|
||||
|
||||
describe('the journal entries card', () => {
|
||||
it('FE-AI-JOURNEY-001: one entry reads as a row with its photo, facts, marks and text under the journal', () => {
|
||||
const { container } = block([card([look({ visibility: 'public', draft: true, photoCount: 4, video: true })])]);
|
||||
// A card stored while entries carried a visibility: it reads, and says nothing of it.
|
||||
const stored = { ...look({ draft: true, photoCount: 4, video: true }), visibility: 'public' };
|
||||
const { container } = block([card([stored])]);
|
||||
expect(screen.getByRole('region', { name: 'Journal entries' })).toBeInTheDocument();
|
||||
expect(screen.getByText('Sunset at the Spree')).toBeInTheDocument();
|
||||
expect(screen.getByText('14:30')).toBeInTheDocument();
|
||||
expect(screen.getByText('Berlin')).toBeInTheDocument();
|
||||
expect(screen.getByText('The light over the river was unreal.')).toBeInTheDocument();
|
||||
expect(screen.getByText('Public')).toBeInTheDocument();
|
||||
expect(screen.queryByText('Public')).toBeNull();
|
||||
expect(screen.getByText('Draft')).toBeInTheDocument();
|
||||
expect(screen.getByText('4 photos')).toBeInTheDocument();
|
||||
expect(screen.getByText('Opens with a video')).toBeInTheDocument();
|
||||
@@ -225,13 +226,12 @@ describe('a change row of a journal entry', () => {
|
||||
}
|
||||
|
||||
it('FE-AI-JOURNEY-008: a waiting delete shows the photo, the text and that it goes back to a suggestion; a receipt opens it', () => {
|
||||
const entry = look({ fromTripPlace: true, visibility: 'shared' });
|
||||
const entry = look({ fromTripPlace: true });
|
||||
const held = card([entry], { change: 'willDelete', tripJournal: true });
|
||||
const onOpen = vi.fn();
|
||||
const first = inView(<AssistantChangeCard items={[item('pending', held)]} />, { onOpen });
|
||||
expect(screen.getByText('Delete the journal entry')).toBeInTheDocument();
|
||||
expect(screen.getByText('The light over the river was unreal.')).toBeInTheDocument();
|
||||
expect(screen.getByText('Shared')).toBeInTheDocument();
|
||||
expect(screen.getByText('Goes back to a suggestion')).toBeInTheDocument();
|
||||
expect(screen.getByText('Tue, Oct 21')).toBeInTheDocument();
|
||||
expect(screen.getByText('Museum Island')).toBeInTheDocument();
|
||||
@@ -255,7 +255,6 @@ describe('a change row of a journal entry', () => {
|
||||
{ op: 'change', labelKey: 'name', before: 'Sunset', after: 'Sunset at the Spree' },
|
||||
{ op: 'change', labelKey: 'time', before: '14:30', after: '' },
|
||||
{ op: 'change', labelKey: 'text', before: 'Old story', after: 'New story' },
|
||||
{ op: 'change', labelKey: 'field', field: 'visibility', before: 'private', after: 'public' },
|
||||
{ op: 'change', labelKey: 'field', field: 'mood', before: 'good', after: '' },
|
||||
{ op: 'change', labelKey: 'field', field: 'weather', before: 'sunny', after: 'Drizzle' },
|
||||
{ op: 'change', labelKey: 'field', field: 'is_draft', before: '✓', after: '✗' },
|
||||
@@ -267,8 +266,6 @@ describe('a change row of a journal entry', () => {
|
||||
expect(screen.getByText('14:30')).toHaveClass('line-through');
|
||||
expect(screen.getByText('Old story')).toHaveClass('line-through');
|
||||
expect(screen.getByText('New story')).toBeInTheDocument();
|
||||
expect(screen.getByText('Private')).toHaveClass('line-through');
|
||||
expect(screen.getByText('Public')).toBeInTheDocument();
|
||||
expect(screen.getByText('Good')).toHaveClass('line-through');
|
||||
expect(screen.getByText('Sunny')).toHaveClass('line-through');
|
||||
expect(screen.getByText('Drizzle')).toBeInTheDocument();
|
||||
|
||||
@@ -28,7 +28,6 @@ const ENTRY: JourneyEntryLook = {
|
||||
photoId: null,
|
||||
video: false,
|
||||
photoCount: 0,
|
||||
visibility: 'private',
|
||||
draft: false,
|
||||
fromTripPlace: false,
|
||||
dayIndex: null,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { JourneyEntryLook } from '@trek/shared';
|
||||
import { CalendarDays, Globe, Images, MapPin, Play, Tag, ThumbsDown, ThumbsUp, Users } from 'lucide-react';
|
||||
import { CalendarDays, Images, MapPin, Play, Tag, ThumbsDown, ThumbsUp } from 'lucide-react';
|
||||
|
||||
import { useTranslation } from '../../../../i18n';
|
||||
import { cardDateLabel, cardPlace } from '../../../Journey/journeyCard';
|
||||
@@ -12,8 +12,8 @@ import { moodOf, weatherOf } from './journeyTones';
|
||||
/**
|
||||
* The pieces a journal entry is drawn from in the chat, the same in an
|
||||
* answer, a change row and a receipt: its photo, the facts of when and where
|
||||
* as the planner's badges, the marks of how it reads (shared, draft, mood,
|
||||
* weather, more photos) and the start of its text. Every fact wraps, none is
|
||||
* as the planner's badges, the marks of how it reads (draft, mood, weather,
|
||||
* more photos) and the start of its text. Every fact wraps, none is
|
||||
* cut.
|
||||
*/
|
||||
|
||||
@@ -63,19 +63,6 @@ export function EntryWhen({ look }: { look: JourneyEntryLook }) {
|
||||
);
|
||||
}
|
||||
|
||||
/** Shared or public; nothing for a private entry. */
|
||||
function VisibilityMark({ visibility }: { visibility: JourneyEntryLook['visibility'] }) {
|
||||
const { t } = useTranslation();
|
||||
if (visibility === 'private') return null;
|
||||
const shared = visibility === 'shared';
|
||||
const Icon = shared ? Users : Globe;
|
||||
return (
|
||||
<SoftPill tone="info" icon={<Icon size={10} strokeWidth={2.2} aria-hidden="true" />}>
|
||||
{shared ? t('journey.visibility.shared') : t('journey.visibility.public')}
|
||||
</SoftPill>
|
||||
);
|
||||
}
|
||||
|
||||
/** A mood the journal knows, in its own colour; nothing for any other. */
|
||||
function MoodMark({ id }: { id: string | null }) {
|
||||
const { t } = useTranslation();
|
||||
@@ -129,17 +116,16 @@ function ListMarks({ look }: { look: JourneyEntryLook }) {
|
||||
);
|
||||
}
|
||||
|
||||
/** How the entry reads: shared or public, a draft, its mood and weather, its photos past the first, its tags and verdict. */
|
||||
/** How the entry reads: a draft, its mood and weather, its photos past the first, its tags and verdict. */
|
||||
export function EntryMarks({ look }: { look: JourneyEntryLook }) {
|
||||
const { t } = useTranslation();
|
||||
const mood = moodOf(look.mood) !== null;
|
||||
const lists = (look.tags?.length ?? 0) > 0 || !!look.verdict;
|
||||
if (look.visibility === 'private' && !look.draft && !mood && !look.weather && look.photoCount < 2 && !lists) {
|
||||
if (!look.draft && !mood && !look.weather && look.photoCount < 2 && !lists) {
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
<CardFacts>
|
||||
<VisibilityMark visibility={look.visibility} />
|
||||
{look.draft && <SoftPill tone="warning">{t('journey.entry.draft')}</SoftPill>}
|
||||
<MoodMark id={look.mood} />
|
||||
<WeatherMark weather={look.weather} />
|
||||
|
||||
@@ -31,7 +31,6 @@ function look(over: Partial<JourneyEntryLook> = {}): JourneyEntryLook {
|
||||
photoId: null,
|
||||
video: false,
|
||||
photoCount: 0,
|
||||
visibility: 'private',
|
||||
draft: false,
|
||||
fromTripPlace: false,
|
||||
dayIndex: null,
|
||||
@@ -97,12 +96,13 @@ describe('journeyCardModel', () => {
|
||||
});
|
||||
|
||||
it('FE-AI-JOURNEY-MODEL-009: the states an update sets are named by field, flags by on and off', () => {
|
||||
expect(stateOf('visibility', 'public')?.labelKey).toBe('journey.visibility.public');
|
||||
// The stored visibility keeps nothing off the share link, so it has no name to show.
|
||||
expect(stateOf('visibility', 'private')).toBeNull();
|
||||
expect(stateOf('type', 'skeleton')?.labelKey).toBe('journey.entry.suggestion');
|
||||
expect(stateOf('mood', 'good')?.labelKey).toBe('journey.mood.good');
|
||||
expect(stateOf('weather', 'cold')?.labelKey).toBe('journey.weather.cold');
|
||||
expect(stateOf('weather', 'Drizzle')).toBeNull();
|
||||
expect(stateOf('visibility', 'toString')).toBeNull();
|
||||
expect(stateOf('type', 'toString')).toBeNull();
|
||||
expect(stateOf(undefined, 'public')).toBeNull();
|
||||
expect(flagOf('is_draft', '✓')?.labelKey).toBe('journey.entry.draft');
|
||||
expect(flagOf('is_draft', '✗')?.labelKey).toBe('assistant.card.journey.notDraft');
|
||||
|
||||
@@ -7,8 +7,6 @@ import {
|
||||
Eye,
|
||||
EyeOff,
|
||||
Frown,
|
||||
Globe,
|
||||
Lock,
|
||||
type LucideIcon,
|
||||
MapPinCheck,
|
||||
Meh,
|
||||
@@ -19,14 +17,13 @@ import {
|
||||
Snowflake,
|
||||
Sparkles,
|
||||
Sun,
|
||||
Users,
|
||||
} from 'lucide-react';
|
||||
|
||||
/**
|
||||
* How the states of a journal entry read in the chat, the way the journal
|
||||
* draws them: its moods with the glyphs of its tiles, its weathers, and the
|
||||
* words for what an update sets beyond the text (who sees the entry, its
|
||||
* kind, a draft, the route, a waved-away suggestion).
|
||||
* words for what an update sets beyond the text (its kind, a draft, the
|
||||
* route, a waved-away suggestion).
|
||||
*/
|
||||
|
||||
/** How a state is drawn: its glyph and the key of its name. */
|
||||
@@ -57,12 +54,6 @@ const WEATHERS: Readonly<Record<string, EntryTone>> = {
|
||||
cold: { Icon: Snowflake, labelKey: 'journey.weather.cold' },
|
||||
};
|
||||
|
||||
const VISIBILITIES: Readonly<Record<string, EntryTone>> = {
|
||||
private: { Icon: Lock, labelKey: 'journey.visibility.private' },
|
||||
shared: { Icon: Users, labelKey: 'journey.visibility.shared' },
|
||||
public: { Icon: Globe, labelKey: 'journey.visibility.public' },
|
||||
};
|
||||
|
||||
const TYPES: Readonly<Record<string, EntryTone>> = {
|
||||
entry: { Icon: BookOpenText, labelKey: 'assistant.card.journey.typeEntry' },
|
||||
checkin: { Icon: MapPinCheck, labelKey: 'assistant.card.journey.typeCheckin' },
|
||||
@@ -119,7 +110,6 @@ export function flagOf(field: string | undefined, value: string): EntryTone | nu
|
||||
export function stateOf(field: string | undefined, value: string | null): EntryTone | null {
|
||||
if (field === 'mood') return moodOf(value);
|
||||
if (field === 'weather') return weatherOf(value);
|
||||
if (field === 'visibility') return own(VISIBILITIES, value);
|
||||
if (field === 'type') return own(TYPES, value);
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import { OnlineOnlyError } from '../../repo/onlineOnly';
|
||||
import { useAddonStore } from '../../store/addonStore';
|
||||
import { chatOf, useAssistantStore } from '../../store/assistantStore';
|
||||
import { useCanDo } from '../../store/permissionsStore';
|
||||
import { useTripAddonEnabled } from '../../store/tripAddonsStore';
|
||||
import { useTripStore } from '../../store/tripStore';
|
||||
import { useToast } from '../shared/Toast';
|
||||
import { chatTextOf } from './assistantShare';
|
||||
@@ -35,7 +36,10 @@ export function useAssistantShare(tripId: number, message: AssistantMessage, wri
|
||||
const { offline } = useNetworkMode();
|
||||
const can = useCanDo();
|
||||
const trip = useTripStore((s) => (s.trip?.id === tripId ? s.trip : null));
|
||||
const chatOn = useAddonStore((s) => s.collabChat && s.addons.some((a) => a.id === 'collab' && a.enabled));
|
||||
// The chat is an instance-wide part of Collab, which this trip may have on or off.
|
||||
const chatFeatureOn = useAddonStore((s) => s.collabChat);
|
||||
const collabOn = useTripAddonEnabled(tripId, 'collab');
|
||||
const chatOn = chatFeatureOn && collabOn;
|
||||
const threadId = useAssistantStore((s) => chatOf(s, tripId).threadId);
|
||||
const [previewing, setPreviewing] = useState(false);
|
||||
const [includeChanges, setIncludeChanges] = useState(true);
|
||||
|
||||
@@ -34,6 +34,7 @@ vi.mock('../../native/widgets', async (importOriginal) => {
|
||||
};
|
||||
});
|
||||
|
||||
import { collabSummary, packingDetail } from '../../native/widgetOnline';
|
||||
import NativeWidgetsSync from './NativeWidgetsSync';
|
||||
|
||||
const trip = {
|
||||
@@ -69,6 +70,8 @@ describe('NativeWidgetsSync', () => {
|
||||
vi.useRealTimers();
|
||||
await offlineDb.trips.clear();
|
||||
await offlineDb.days.clear();
|
||||
await offlineDb.todoItems.clear();
|
||||
await offlineDb.tripAddons.clear();
|
||||
});
|
||||
|
||||
it('FE-NATIVE-WSYNC-001: writes today and every day ahead, so the widgets turn the day without the app', async () => {
|
||||
@@ -84,4 +87,29 @@ describe('NativeWidgetsSync', () => {
|
||||
['2026-11-08', 'Market'],
|
||||
]);
|
||||
});
|
||||
|
||||
it('FE-NATIVE-WSYNC-002: a trip with Lists and Collab switched off shows neither its todos nor its chat', async () => {
|
||||
await offlineDb.todoItems.put({ id: 70, trip_id: 7, name: 'Book ferry', checked: 0 } as never);
|
||||
const off = (id: string) => ({ id, name: id, icon: null, enabled: false, instanceEnabled: true, overridden: true });
|
||||
await offlineDb.tripAddons.put({ tripId: 7, addons: [off('packing'), off('collab')] });
|
||||
vi.mocked(packingDetail).mockClear();
|
||||
vi.mocked(collabSummary).mockClear();
|
||||
|
||||
render(<NativeWidgetsSync />);
|
||||
await waitFor(() => expect(published.calls.length).toBeGreaterThan(0));
|
||||
const snapshot = published.calls[0][0] as { todos?: unknown; collab?: unknown };
|
||||
expect(snapshot.todos).toBeUndefined();
|
||||
expect(snapshot.collab).toBeUndefined();
|
||||
expect(vi.mocked(packingDetail)).not.toHaveBeenCalled();
|
||||
expect(vi.mocked(collabSummary)).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-NATIVE-WSYNC-003: a trip the device never read the addons of shows its todos, as before', async () => {
|
||||
await offlineDb.todoItems.put({ id: 71, trip_id: 7, name: 'Book ferry', checked: 0 } as never);
|
||||
|
||||
render(<NativeWidgetsSync />);
|
||||
await waitFor(() => expect(published.calls.length).toBeGreaterThan(0));
|
||||
const snapshot = published.calls[0][0] as { todos?: { items?: unknown[] } };
|
||||
expect(snapshot.todos).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -32,12 +32,15 @@ import {
|
||||
type TripWidgetSnapshot,
|
||||
type WidgetLabels,
|
||||
} from '../../native/widgets';
|
||||
import { cachedTripAddons } from '../../repo/tripAddonsRepo';
|
||||
import { instanceAddonOn, useAddonStore } from '../../store/addonStore';
|
||||
import { useAuthStore } from '../../store/authStore';
|
||||
import { useFlightLiveStore } from '../../store/flightLiveStore';
|
||||
import { useSettingsStore } from '../../store/settingsStore';
|
||||
import { useTripStore } from '../../store/tripStore';
|
||||
import type { Day, Place, Reservation, TranslationFn, Trip } from '../../types';
|
||||
import { formatTime } from '../../utils/formatters';
|
||||
import { tripAddonEnabled } from '../../utils/tripAddons';
|
||||
import { localDateStr } from '../../vacay/monthGrid';
|
||||
|
||||
const REFRESH_MS = 15 * 60 * 1000;
|
||||
@@ -120,15 +123,31 @@ async function flightOf(trip: Trip, reservations: Reservation[], path: string, c
|
||||
return widgetFlight(legs, Date.now(), path, { locale: context.language, timeFormat: context.timeFormat });
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the trip has Lists and Collab on, from the list the device kept for it
|
||||
* (the sync reads it with the trip). A trip it never read follows the instance,
|
||||
* and while that is not known either the widgets show both, as they always did.
|
||||
*/
|
||||
async function tripSections(tripId: number): Promise<{ lists: boolean; collab: boolean }> {
|
||||
const own = await cachedTripAddons(tripId);
|
||||
const instance = useAddonStore.getState();
|
||||
const on = (id: string) => tripAddonEnabled(own, id, instanceAddonOn(instance, id, true));
|
||||
return { lists: on('packing'), collab: on('collab') };
|
||||
}
|
||||
|
||||
async function tripExtras(trip: Trip, days: Day[], context: SyncContext) {
|
||||
const { today, language, unit, time } = context;
|
||||
const [places, reservations, todos, packing, memberRows] = await Promise.all([
|
||||
const [places, reservations, todoRows, packingRows, memberRows, sections] = await Promise.all([
|
||||
offlineDb.places.where('trip_id').equals(trip.id).toArray(),
|
||||
offlineDb.reservations.where('trip_id').equals(trip.id).toArray(),
|
||||
offlineDb.todoItems.where('trip_id').equals(trip.id).toArray(),
|
||||
offlineDb.packingItems.where('trip_id').equals(trip.id).toArray(),
|
||||
offlineDb.tripMembers.where('tripId').equals(trip.id).toArray(),
|
||||
tripSections(trip.id),
|
||||
]);
|
||||
// A trip with Lists off shows no todos or packing, on the widgets and the watch alike.
|
||||
const todos = sections.lists ? todoRows : [];
|
||||
const packing = sections.lists ? packingRows : [];
|
||||
const members = memberRows.length;
|
||||
const names = [trip.owner_username, ...memberRows.map((m) => m.username)].filter((n): n is string => !!n);
|
||||
const path = `/trips/${trip.id}`;
|
||||
@@ -144,13 +163,15 @@ async function tripExtras(trip: Trip, days: Day[], context: SyncContext) {
|
||||
const [weather, cover, bags, collab, flight] = await Promise.all([
|
||||
spot && inRange ? widgetWeather(spot, { date: weatherDate, lang: language, unit, place }) : Promise.resolve(null),
|
||||
widgetCover(trip.cover_image),
|
||||
packingDetail(trip.id, packing),
|
||||
collabSummary(
|
||||
trip.id,
|
||||
`/trips/${trip.id}?tab=collab`,
|
||||
[...new Set(names)],
|
||||
useAuthStore.getState().user?.id ?? null
|
||||
),
|
||||
sections.lists ? packingDetail(trip.id, packing) : Promise.resolve(null),
|
||||
sections.collab
|
||||
? collabSummary(
|
||||
trip.id,
|
||||
`/trips/${trip.id}?tab=collab`,
|
||||
[...new Set(names)],
|
||||
useAuthStore.getState().user?.id ?? null
|
||||
)
|
||||
: Promise.resolve(null),
|
||||
flightOf(trip, reservations, path, context),
|
||||
]);
|
||||
const packed = packingSummary(packing, `/trips/${trip.id}?tab=listen`);
|
||||
@@ -166,7 +187,7 @@ async function tripExtras(trip: Trip, days: Day[], context: SyncContext) {
|
||||
memberCount: members > 0 ? members + 1 : 0,
|
||||
weather,
|
||||
bookings: bookingsAhead(reservations, { dayDates, today, tripPath: path, formatTime: time }),
|
||||
todos: todosSummary(todos, `${path}?tab=listen`),
|
||||
todos: sections.lists ? todosSummary(todos, `${path}?tab=listen`) : undefined,
|
||||
packing: packed && bags ? { ...packed, ...bags } : packed,
|
||||
collab,
|
||||
flight,
|
||||
|
||||
@@ -5,7 +5,7 @@ import {
|
||||
type TripRouteAnswers, type TripRouteSummary,
|
||||
} from './tripRouteGeometry'
|
||||
import { useSettingsStore } from '../../store/settingsStore'
|
||||
import { useAddonStore } from '../../store/addonStore'
|
||||
import { useTripAddonEnabled } from '../../store/tripAddonsStore'
|
||||
import type { RoadtripVia } from '@trek/shared'
|
||||
import type { Accommodation, AssignmentsMap, Day, Place, Reservation } from '../../types'
|
||||
import type { TourStageStops } from './dayTourProjection'
|
||||
@@ -51,7 +51,7 @@ export function useTripRouteOverview(
|
||||
tourStageStops?: TourStageStops,
|
||||
): TripRouteOverview {
|
||||
const optimizeFromAccommodation = useSettingsStore(s => s.settings.optimize_from_accommodation)
|
||||
const toursEnabled = useAddonStore(s => s.isEnabled('tours'))
|
||||
const toursEnabled = useTripAddonEnabled(tripId, 'tours')
|
||||
// Leg text is formatted at compute time, so a km↔mi switch has to re-run (#1300).
|
||||
const distanceUnit = useSettingsStore(s => s.settings.distance_unit)
|
||||
const [result, setResult] = useState<TripRouteOverview>(EMPTY)
|
||||
|
||||
@@ -259,6 +259,25 @@ describe('downloadTripPDF', () => {
|
||||
expect(iframe!.srcdoc).toContain('Air Italia · AI123 · CDG → FCO')
|
||||
})
|
||||
|
||||
it('FE-COMP-TRIPPDF-013s: a flight prints its seat, a direct one and each leg of one with a stop alike', async () => {
|
||||
const direct = { ...transportReservation, metadata: JSON.stringify({ airline: 'Air Italia', flight_number: 'AI123', seat: '31A', departure_airport: 'CDG', arrival_airport: 'FCO' }) }
|
||||
const stopover = {
|
||||
...multiLegFlight,
|
||||
metadata: JSON.stringify({
|
||||
legs: [
|
||||
{ from: 'FRA', to: 'BER', airline: 'Lufthansa', flight_number: 'LH1' },
|
||||
{ from: 'BER', to: 'HND', airline: 'Lufthansa', flight_number: 'LH2', seat: '14C' },
|
||||
],
|
||||
departure_airport: 'FRA', arrival_airport: 'HND', airline: 'Lufthansa', flight_number: 'LH1',
|
||||
}),
|
||||
}
|
||||
await downloadTripPDF({ ...richArgs, reservations: [direct, stopover] })
|
||||
const html = getIframe()?.srcdoc ?? ''
|
||||
expect(html).toContain('Air Italia · AI123 · reservations.meta.seat 31A · CDG → FCO')
|
||||
expect(html).toContain('Lufthansa · LH2 · reservations.meta.seat 14C · BER → HND')
|
||||
expect(html).not.toContain('LH1 · reservations.meta.seat')
|
||||
})
|
||||
|
||||
it('FE-COMP-TRIPPDF-013f: the stop a booked night wrote is not listed, so a morning flight prints before the hotel (#2434)', async () => {
|
||||
// The desktop toolbar hands the export the store's assignments, hidden stop and
|
||||
// all, and that stop heads its check-in day. The day plan hides it and shows the
|
||||
|
||||
@@ -14,7 +14,7 @@ import { renderIconMarkup } from '../../utils/iconMarkup'
|
||||
import { formatMoney, formatMoneySum, formatClockTime, splitReservationDateTime, type MoneyEntry } from '../../utils/formatters'
|
||||
import { useSettingsStore } from '../../store/settingsStore'
|
||||
import { useTripStore } from '../../store/tripStore'
|
||||
import { useAddonStore } from '../../store/addonStore'
|
||||
import { tripAddonEnabledNow } from '../../store/tripAddonsStore'
|
||||
import { projectDayItinerary } from '../Map/dayTourProjection'
|
||||
import { planCosts } from '../Planner/planCosts'
|
||||
import { routeDistanceLabel } from '../Map/tripRouteLabels'
|
||||
@@ -180,8 +180,10 @@ interface downloadTripPDFProps {
|
||||
showServiceStops?: boolean
|
||||
/** The trip's expenses, which the cost figures add up with Costs on (#2551). Read from the trip store when left out. */
|
||||
budgetItems?: BudgetItem[]
|
||||
/** Whether the Costs addon is on. Read from the addon store when left out. */
|
||||
/** Whether the Costs addon is on for this trip. Read from the trip's addons when left out. */
|
||||
costsEnabled?: boolean
|
||||
/** Whether the Tours addon is on for this trip. Read from the trip's addons when left out. */
|
||||
toursEnabled?: boolean
|
||||
/** Prints only this member's plan (#2168): the stops and bookings that name them, and the ones that name nobody. */
|
||||
onlyUserId?: number
|
||||
/** The planner's road trip vias and tour stages, and the routing progress and stop (#2876). */
|
||||
@@ -192,7 +194,7 @@ interface downloadTripPDFProps {
|
||||
|
||||
// `assignments` is normalised here once, to the plan's own list; every read below
|
||||
// (and fetchPlacePhotos) relies on it being an object.
|
||||
export async function downloadTripPDF({ trip, days, places, assignments: allStored = {}, categories, dayNotes, reservations: allReservations = [], t: _t, locale: _locale, timeFormat: _timeFormat, distanceUnit: _distanceUnit, showServiceStops = true, budgetItems, costsEnabled, onlyUserId, route, signal }: downloadTripPDFProps) {
|
||||
export async function downloadTripPDF({ trip, days, places, assignments: allStored = {}, categories, dayNotes, reservations: allReservations = [], t: _t, locale: _locale, timeFormat: _timeFormat, distanceUnit: _distanceUnit, showServiceStops = true, budgetItems, costsEnabled, toursEnabled: toursOn, onlyUserId, route, signal }: downloadTripPDFProps) {
|
||||
const { assignments: stored, reservations } = onlyUserId != null
|
||||
? onlyMyPlan(allStored, allReservations, onlyUserId)
|
||||
: { assignments: allStored, reservations: allReservations }
|
||||
@@ -226,7 +228,7 @@ export async function downloadTripPDF({ trip, days, places, assignments: allStor
|
||||
|
||||
const unit: DistanceUnit = (_distanceUnit || useSettingsStore.getState().settings.distance_unit) === 'imperial'
|
||||
? 'imperial' : 'metric'
|
||||
const toursEnabled = useAddonStore.getState().isEnabled('tours')
|
||||
const toursEnabled = toursOn ?? tripAddonEnabledNow(trip.id, 'tours')
|
||||
const hasInvalidTour = toursEnabled && Object.values(assignments).some(list =>
|
||||
projectDayItinerary(list || [], true, places).some(item => item.kind === 'tour' && !item.valid))
|
||||
const { route: tripRoute, mapSvg: tripMapSvg } = await drawTripRoute({
|
||||
@@ -289,7 +291,7 @@ export async function downloadTripPDF({ trip, days, places, assignments: allStor
|
||||
// The same figures the plan shows (#2551): the expenses with Costs on, each once,
|
||||
// else each planned place's own price once. An expense linked to a place finds its
|
||||
// day through every stop, the booked night's included.
|
||||
const withCosts = costsEnabled ?? useAddonStore.getState().isEnabled('budget')
|
||||
const withCosts = costsEnabled ?? tripAddonEnabledNow(trip.id, 'budget')
|
||||
const costs = planCosts({
|
||||
days: sorted,
|
||||
assignments: withCosts ? stored : assignments,
|
||||
@@ -415,7 +417,7 @@ export async function downloadTripPDF({ trip, days, places, assignments: allStor
|
||||
// flat metadata pair for legacy single-leg flights without endpoints.
|
||||
const stops = (r.endpoints || []).slice().sort((a, b) => (a.sequence ?? 0) - (b.sequence ?? 0)).map(e => e.code || e.name)
|
||||
const route = stops.length >= 2 ? stops.join(' → ') : (meta.departure_airport && meta.arrival_airport ? `${meta.departure_airport} → ${meta.arrival_airport}` : '')
|
||||
subtitle = [meta.airline, meta.flight_number, route].filter(Boolean).join(' · ')
|
||||
subtitle = [meta.airline, meta.flight_number, meta.seat ? `${tr('reservations.meta.seat')} ${meta.seat}` : '', route].filter(Boolean).join(' · ')
|
||||
}
|
||||
}
|
||||
else if (r.type === 'train') {
|
||||
|
||||
@@ -33,6 +33,7 @@ import { useTripStore } from '../../store/tripStore'
|
||||
import { useCanDo } from '../../store/permissionsStore'
|
||||
import { useSettingsStore } from '../../store/settingsStore'
|
||||
import { useAddonStore } from '../../store/addonStore'
|
||||
import { useTripAddonEnabled } from '../../store/tripAddonsStore'
|
||||
import { openSaveToCollection } from '../Collections/saveTarget'
|
||||
import { computeMultiDayMove as computeMultiDayMoveIn, getDayOrder as getDayOrderIn, type SpanPhase } from './DayPlanSidebar.multiDayMove'
|
||||
import { useTranslation } from '../../i18n'
|
||||
@@ -41,7 +42,6 @@ import { Tooltip } from '../shared/Tooltip'
|
||||
import { NEUTRAL_TINT, fs } from '../shared/DialogShell'
|
||||
import { BarButton, MoreButton, SoftPill, TimePill, tintOf } from './planParts'
|
||||
import './dayPlanRows.css'
|
||||
|
||||
import { TypeTile } from './bookings/bookingParts'
|
||||
import { typeInfo } from './bookings/bookingsModel'
|
||||
import { transportSubtitle } from './transportDetailModel'
|
||||
@@ -218,7 +218,7 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {
|
||||
const toast = useToast()
|
||||
const { t, locale } = useTranslation()
|
||||
const mirrorServiceStops = useRoadtripSettings(s => s.roadtrip_service_stops_in_days !== false)
|
||||
const toursEnabled = useAddonStore(s => s.isEnabled('tours'))
|
||||
const toursEnabled = useTripAddonEnabled(tripId, 'tours')
|
||||
const tripActions = useRef(useTripStore.getState()).current
|
||||
|
||||
const { noteUi, setNoteUi, noteInputRef, dayNotes, openAddNote: _openAddNote, openEditNote: _openEditNote, cancelNote, saveNote, deleteNote: _deleteNote, moveNote: _moveNote } = useDayNotes(tripId)
|
||||
@@ -1098,7 +1098,7 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {
|
||||
|
||||
// Total Cost reads the expenses in Costs when it is on (#2551).
|
||||
const budgetItems = useTripStore(s => s.budgetItems)
|
||||
const costsEnabled = useAddonStore(s => s.isEnabled('budget'))
|
||||
const costsEnabled = useTripAddonEnabled(tripId, 'budget')
|
||||
const totalCostLabel = useMemo(() => {
|
||||
return formatMoneySum(planCosts({ days, assignments, reservations, budgetItems, costsEnabled, tripCurrency: currency, displayCurrency: costBase }).total, costBase, locale, fxRates)
|
||||
}, [days, assignments, reservations, budgetItems, costsEnabled, currency, costBase, locale, fxRates])
|
||||
@@ -1276,7 +1276,7 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
|
||||
const optimizeFromAccommodation = useSettingsStore(s => s.settings.optimize_from_accommodation)
|
||||
const dateFirst = useSettingsStore(s => s.settings.day_date_first === true)
|
||||
const collectionsEnabled = useAddonStore(s => s.isEnabled('collections'))
|
||||
const toursEnabled = useAddonStore(s => s.isEnabled('tours'))
|
||||
const toursEnabled = useTripAddonEnabled(tripId, 'tours')
|
||||
// Plugin time contributions in the day plan (dayScheduleProvider hook).
|
||||
const daySchedule = usePluginDaySchedule(tripId)
|
||||
// Per-day colours from the dayTintProvider hook — e.g. which leg of the trip a
|
||||
|
||||
@@ -8,7 +8,7 @@ import { BlurredCode } from '../shared/BookingCode'
|
||||
import { DialogButton, DialogFooter, DialogSection, DialogShell, FooterSpacer, PILL } from '../shared/DialogShell'
|
||||
import { useTripStore } from '../../store/tripStore'
|
||||
import { formatTime, splitReservationDateTime } from '../../utils/formatters'
|
||||
import { parseReservationMetadata } from '../../utils/flightLegs'
|
||||
import { parseReservationMetadata, seatCells } from '../../utils/flightLegs'
|
||||
import { BookingDialogHeader } from './bookings/BookingDialogShell'
|
||||
import { BOX, Eyebrow, Field, fs, toneColor, toneOf } from './bookings/bookingParts'
|
||||
import { filesFor } from '../../utils/reservationFiles'
|
||||
@@ -175,11 +175,13 @@ function detailCells(res: Reservation, meta: Record<string, unknown>, t: Transla
|
||||
add(t('reservations.meta.flightNumber'), meta.flight_number)
|
||||
add(t('reservations.meta.from'), meta.departure_airport)
|
||||
add(t('reservations.meta.to'), meta.arrival_airport)
|
||||
add(t('reservations.meta.seat'), meta.seat)
|
||||
} else if (res.type === 'train') {
|
||||
add(t('reservations.meta.trainNumber'), meta.train_number)
|
||||
add(t('reservations.meta.platform'), meta.platform)
|
||||
add(t('reservations.meta.seat'), meta.seat)
|
||||
}
|
||||
// Each leg's seat under its route on a booking with a stop, not just the first leg's.
|
||||
if (res.type === 'flight' || res.type === 'train') {
|
||||
for (const c of seatCells(res, t('reservations.meta.seat'))) add(c.label, c.value)
|
||||
}
|
||||
add(t('reservations.confirmationCode'), res.confirmation_number, true)
|
||||
// A stopover booking can carry its own reference per segment (#1943); the
|
||||
|
||||
@@ -2,6 +2,7 @@ import { useState, useEffect, useRef, useMemo, useCallback, useId, type ReactNod
|
||||
import type { PlaceClientOrigin, RoadtripStopType, TourListItem } from '@trek/shared'
|
||||
import { useAuthStore } from '../../store/authStore'
|
||||
import { useAddonStore } from '../../store/addonStore'
|
||||
import { useTripAddonEnabled } from '../../store/tripAddonsStore'
|
||||
import { useCanDo } from '../../store/permissionsStore'
|
||||
import { useTripStore } from '../../store/tripStore'
|
||||
import { useSettingsStore } from '../../store/settingsStore'
|
||||
@@ -120,7 +121,7 @@ function usePlaceFormModal(props: PlaceFormModalProps) {
|
||||
const tripObj = useTripStore((s) => s.trip)
|
||||
const canUploadFiles = can('file_upload', tripObj)
|
||||
const collectionsEnabled = useAddonStore((s) => s.isEnabled('collections'))
|
||||
const isBudgetEnabled = useAddonStore((s) => s.isEnabled('budget'))
|
||||
const isBudgetEnabled = useTripAddonEnabled(tripId, 'budget')
|
||||
const deleteBudgetItem = useTripStore((s) => s.deleteBudgetItem)
|
||||
const {
|
||||
form, setForm, autoFilledRef, pendingFiles, addFilesFromInput, removeFile, handlePaste, isSaving, setIsSaving,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useEffect, useRef, useMemo, useId } from 'react'
|
||||
import { useParams } from 'react-router'
|
||||
import { useTripStore } from '../../store/tripStore'
|
||||
import { useAddonStore } from '../../store/addonStore'
|
||||
import { useTripAddonEnabled } from '../../store/tripAddonsStore'
|
||||
import CustomSelect from '../shared/CustomSelect'
|
||||
import { BookingCodeInput } from '../shared/BookingCode'
|
||||
import { buildAssignmentOptions } from './assignmentOptions'
|
||||
@@ -71,7 +71,7 @@ export function ReservationModal({ isOpen, onClose, onSave, reservation, days, p
|
||||
const fileInputRef = useRef(null)
|
||||
const titleId = useId()
|
||||
|
||||
const isBudgetEnabled = useAddonStore(s => s.isEnabled('budget'))
|
||||
const isBudgetEnabled = useTripAddonEnabled(Number(tripId), 'budget')
|
||||
const deleteBudgetItem = useTripStore(s => s.deleteBudgetItem)
|
||||
// Set right before submit when the user clicked create/edit expense.
|
||||
const expense = useBookingExpenseIntent(() => handleSubmit(), {
|
||||
|
||||
@@ -12,7 +12,7 @@ import { toLocationPicks } from './locationPicks'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { useToast } from '../shared/Toast'
|
||||
import { useTripStore } from '../../store/tripStore'
|
||||
import { useAddonStore } from '../../store/addonStore'
|
||||
import { useTripAddonEnabled } from '../../store/tripAddonsStore'
|
||||
import type { Day, Place, Accommodation, Reservation, TripFile, AssignmentsMap } from '../../types'
|
||||
import { BookingNotesFilesCosts } from './BookingNotesFilesCosts'
|
||||
import { TravelerPicker } from './TravelerPicker'
|
||||
@@ -83,10 +83,10 @@ export function TransportModal({ isOpen, onClose, onSave, reservation, days, sel
|
||||
const toast = useToast()
|
||||
// The trip's places, offered by every location field of the manual tab (#2468).
|
||||
const locationPicks = useMemo(() => toLocationPicks(places), [places])
|
||||
const isBudgetEnabled = useAddonStore(s => s.isEnabled('budget'))
|
||||
const budgetItems = useTripStore(s => s.budgetItems)
|
||||
const deleteBudgetItem = useTripStore(s => s.deleteBudgetItem)
|
||||
const { id: tripId } = useParams<{ id: string }>()
|
||||
const isBudgetEnabled = useTripAddonEnabled(Number(tripId), 'budget')
|
||||
// Set right before submitting when the user clicked "create/edit expense", so
|
||||
// the post-save handler knows to open the Costs editor for the saved booking.
|
||||
const expense = useBookingExpenseIntent(() => handleSubmit(), {
|
||||
|
||||
@@ -118,6 +118,19 @@ describe('BookingDetailDialog', () => {
|
||||
expect(screen.getByText('#SEG2')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKDETAIL-015: a flight with a stop shows the seat booked on its second leg, once, under that leg', () => {
|
||||
const r = buildReservation({
|
||||
title: 'MXP to JFK', type: 'flight',
|
||||
metadata: JSON.stringify({ class: 'Economy', legs: [{ from: 'MXP', to: 'IST' }, { from: 'IST', to: 'JFK', seat: '14C' }] }),
|
||||
});
|
||||
renderDetail(r);
|
||||
const dialog = screen.getByRole('dialog', { name: 'MXP to JFK' });
|
||||
expect(within(dialog).getByText('14C')).toBeInTheDocument();
|
||||
expect(within(dialog).getByText('Seat IST → JFK')).toBeInTheDocument();
|
||||
// The tile stands for it; the field grid does not repeat it.
|
||||
expect(within(dialog).queryByText('14C, Economy')).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKDETAIL-006: place, accommodation, linked stop, link, travelers and notes', () => {
|
||||
const place = buildPlace({ name: 'Kinkaku-ji', place_time: '10:00' });
|
||||
const a = buildAssignment({ id: 4401, day_id: 1302, place });
|
||||
|
||||
@@ -27,7 +27,7 @@ import { BookingDialogHeader, StatusPill, TypePill } from './BookingDialogShell'
|
||||
import { DeleteButton, DialogButton, DialogFooter, DialogSection as Section, DialogShell, FooterSpacer, PILL } from '../../shared/DialogShell'
|
||||
import FlightLiveCard from '../flightLive/FlightLiveCard'
|
||||
import { useFlightLiveCardLegs } from '../flightLive/useFlightLiveCard'
|
||||
import { getFlightLegs } from '../../../utils/flightLegs'
|
||||
import { bookingSeats, getFlightLegs, seatLabel } from '../../../utils/flightLegs'
|
||||
|
||||
export interface BookingDetailDialogProps {
|
||||
r: Reservation
|
||||
@@ -84,6 +84,7 @@ export default function BookingDetailDialog(p: BookingDetailDialogProps) {
|
||||
const subParts = [meta.airline, meta.flight_number, meta.train_number, facts.endpoints.length >= 2 ? facts.endpoints.map(e => e.code || e.name).join(' → ') : null].filter(Boolean)
|
||||
const sub = subParts.length ? subParts.join(' ') : null
|
||||
|
||||
const seats = bookingSeats(r)
|
||||
const stats: { value: string; label: string }[] = []
|
||||
if (facts.isHotel) {
|
||||
stats.push(...stayStats(facts, meta, t, locale))
|
||||
@@ -100,7 +101,8 @@ export default function BookingDetailDialog(p: BookingDetailDialogProps) {
|
||||
// Under a minute of walking is not worth a tile.
|
||||
if (transit && transit.walk > 59) stats.push({ value: t('transit.min', { count: Math.round(transit.walk / 60) }), label: t('transit.walkLabel') })
|
||||
if (meta.platform) stats.push({ value: meta.platform, label: t('reservations.meta.platform') })
|
||||
if (meta.seat) stats.push({ value: meta.seat, label: t('reservations.meta.seat') })
|
||||
// Each leg's seat under its route on a booking with a stop, not just the first leg's.
|
||||
for (const s of seats) stats.push({ value: s.seat, label: seatLabel(t('reservations.meta.seat'), s.route) })
|
||||
}
|
||||
// Cells already shown as a stat stay out of the field grid below.
|
||||
const shownAsStat = new Set([t('reservations.meta.platform'), t('reservations.meta.seat'), t('reservations.meta.checkIn'), t('reservations.meta.checkOut')])
|
||||
|
||||
@@ -4,6 +4,7 @@ import type { Reservation } from '../../../types'
|
||||
import { useTranslation } from '../../../i18n'
|
||||
import { BlurredCode } from '../../shared/BookingCode'
|
||||
import { formatMoney } from '../../../utils/formatters'
|
||||
import { bookingSeats } from '../../../utils/flightLegs'
|
||||
import { TransitLegChips } from '../transitDisplay'
|
||||
import { displayTitle, parseMeta, type BookingGroup, type CostTotal } from './bookingsModel'
|
||||
import type { BookingFacts } from './bookingFacts'
|
||||
@@ -82,7 +83,7 @@ function Row({ r, p, facts, files, costs, t, locale }: {
|
||||
const sub = facts.endpoints.length >= 2
|
||||
? facts.endpoints.map(e => e.code || e.name).join(' → ')
|
||||
: facts.accommodation || facts.place || ''
|
||||
const extras: string[] = [meta.airline && meta.flight_number ? `${meta.airline} ${meta.flight_number}` : meta.flight_number || meta.airline, meta.train_number, meta.seat, meta.platform].filter(Boolean)
|
||||
const extras: string[] = [meta.airline && meta.flight_number ? `${meta.airline} ${meta.flight_number}` : meta.flight_number || meta.airline, meta.train_number, ...bookingSeats(r).map(s => s.seat), meta.platform].filter(Boolean)
|
||||
|
||||
return (
|
||||
<div
|
||||
|
||||
@@ -231,3 +231,14 @@ describe('bookingFacts: codes, links and places', () => {
|
||||
expect(bookingFacts(buildReservation({ url: 'javascript:alert(1)' }), ctx()).url?.href).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('bookingFacts: seats of a flight with a stop', () => {
|
||||
it('FE-PLANNER-BKFACTS-025: the Seat cell holds the seat booked only on the second leg', () => {
|
||||
const r = buildReservation({
|
||||
type: 'flight',
|
||||
metadata: JSON.stringify({ class: 'Economy', legs: [{ from: 'MXP', to: 'IST' }, { from: 'IST', to: 'JFK', seat: '14C' }] }),
|
||||
});
|
||||
const facts = bookingFacts(r, ctx());
|
||||
expect(cell(facts, 'reservations.meta.seat')).toBe('14C, Economy');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { Day, Reservation, ReservationEndpoint } from '../../../types'
|
||||
import { formatPriceText, formatTime, splitReservationDateTime } from '../../../utils/formatters'
|
||||
import { getFlightLegs, getTrainLegs, usesStationRoute } from '../../../utils/flightLegs'
|
||||
import { getFlightLegs, getTrainLegs, seatCells, usesStationRoute } from '../../../utils/flightLegs'
|
||||
import { safeExternalHref } from '../../../utils/safeUrl'
|
||||
import { bookingDates, daySpan, hotelStayTimes, parseMeta, type AssignmentLookupEntry } from './bookingsModel'
|
||||
|
||||
@@ -102,7 +102,8 @@ export function bookingFacts(r: Reservation, c: FactsContext): BookingFacts {
|
||||
if (!hasEndpoints && meta.arrival_airport) cells.push({ label: t('reservations.meta.to'), value: meta.arrival_airport })
|
||||
if (meta.train_number) cells.push({ label: t('reservations.meta.trainNumber'), value: meta.train_number })
|
||||
if (meta.platform) cells.push({ label: t('reservations.meta.platform'), value: meta.platform })
|
||||
if (meta.seat) cells.push({ label: t('reservations.meta.seat'), value: meta.class ? `${meta.seat}, ${meta.class}` : meta.seat })
|
||||
// One seat per leg on a booking with a stop, each under its route; otherwise the booking's own.
|
||||
cells.push(...seatCells(r, t('reservations.meta.seat'), meta.class ? `, ${meta.class}` : ''))
|
||||
if (!c.hasLinkedCost && meta.price != null && meta.price !== '') {
|
||||
cells.push({ label: t('reservations.price'), value: formatPriceText(meta.price, meta.priceCurrency, c.tripCurrency, locale) })
|
||||
}
|
||||
|
||||
@@ -54,6 +54,14 @@ describe('TransitLegs', () => {
|
||||
expect(screen.getByText('BVG')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKTRANSIT-009: stop names and a walk target wrap instead of being cut off (#3139)', () => {
|
||||
render(<TransitLegs legs={[ride, walk]} compact />);
|
||||
for (const text of ['Alexanderplatz', 'Eberswalder Str.', 'Walk to Mauerpark']) {
|
||||
expect(screen.getByText(text)).not.toHaveClass('truncate');
|
||||
expect(screen.getByText(text)).toHaveClass('break-words');
|
||||
}
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKTRANSIT-006: a walk reads as one and leaves out the ride facts', () => {
|
||||
render(<TransitLegs legs={[walk]} compact />);
|
||||
expect(screen.getByText('Walk to Mauerpark')).toBeInTheDocument();
|
||||
|
||||
@@ -48,9 +48,11 @@ export function TransitLegs({ legs, compact = false }: { legs: TransitLegDisplay
|
||||
}}>{leg.line || leg.mode}</span>
|
||||
)}
|
||||
<div className={`flex min-w-0 flex-1 flex-col ${compact ? 'gap-1' : 'gap-1.5'}`}>
|
||||
<div className="flex min-w-0 items-center gap-1 font-medium text-content" style={fs(compact ? 12 : 13, 'body')}>
|
||||
{walk ? <span className="truncate text-content-muted">{t('transit.walkTo', { name: leg.to?.name || '' })}</span> : (
|
||||
<><span className="truncate">{leg.from?.name}</span><ArrowRight size={compact ? 11 : 12} strokeWidth={2} className="flex-none text-content-faint" /><span className="truncate">{leg.to?.name}</span></>
|
||||
{/* Detail views show a stop name whole: the names wrap and the
|
||||
arrow moves to the next line with them when it has to (#3139). */}
|
||||
<div className="flex min-w-0 flex-wrap items-center gap-1 font-medium text-content" style={fs(compact ? 12 : 13, 'body')}>
|
||||
{walk ? <span className="min-w-0 break-words text-content-muted [overflow-wrap:anywhere]">{t('transit.walkTo', { name: leg.to?.name || '' })}</span> : (
|
||||
<><span dir="auto" className="min-w-0 break-words [overflow-wrap:anywhere]">{leg.from?.name}</span><ArrowRight size={compact ? 11 : 12} strokeWidth={2} className="flex-none text-content-faint" /><span dir="auto" className="min-w-0 break-words [overflow-wrap:anywhere]">{leg.to?.name}</span></>
|
||||
)}
|
||||
</div>
|
||||
<TransitMetaBadges size={compact ? 'sm' : 'md'} items={[
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
// FE-PLANNER-TRANSITDISPLAY-001 to FE-PLANNER-TRANSITDISPLAY-003
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { render, screen } from '../../../tests/helpers/render';
|
||||
import type { TransitLegDisplay } from './transitDisplay';
|
||||
import { TransitItineraryInline, TransitWalkDivider } from './transitDisplay';
|
||||
|
||||
const t = (key: string, params?: Record<string, string | number>) =>
|
||||
params ? `${key}:${Object.values(params).join(',')}` : key;
|
||||
|
||||
const ride: TransitLegDisplay = {
|
||||
mode: 'RAIL',
|
||||
line: 'XC',
|
||||
duration: 1260,
|
||||
from: { name: 'Basingstoke', time: '12:48' },
|
||||
to: { name: 'Reading', time: '13:09' },
|
||||
};
|
||||
const walk: TransitLegDisplay = { mode: 'WALK', duration: 240, to: { name: 'Reading station, Station Approach' } };
|
||||
|
||||
/** Whether a rendered element clips its text to one line. */
|
||||
function clipsToOneLine(el: HTMLElement): boolean {
|
||||
return el.style.whiteSpace === 'nowrap' || el.style.textOverflow === 'ellipsis';
|
||||
}
|
||||
|
||||
describe('TransitItineraryInline (#3139)', () => {
|
||||
it('FE-PLANNER-TRANSITDISPLAY-001: a ride shows both stop names in full', () => {
|
||||
render(<TransitItineraryInline legs={[ride]} t={t} />);
|
||||
for (const name of ['Basingstoke', 'Reading']) {
|
||||
const el = screen.getByText(name);
|
||||
expect(clipsToOneLine(el)).toBe(false);
|
||||
expect(el.style.overflowWrap).toBe('anywhere');
|
||||
}
|
||||
});
|
||||
|
||||
it('FE-PLANNER-TRANSITDISPLAY-002: a ride shows its arrival time under its departure', () => {
|
||||
render(<TransitItineraryInline legs={[ride, { ...ride, to: { name: 'Oxford' } }]} t={t} />);
|
||||
expect(screen.getByText('13:09')).toBeInTheDocument();
|
||||
expect(screen.getAllByText('12:48')).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('TransitWalkDivider (#3139)', () => {
|
||||
it('FE-PLANNER-TRANSITDISPLAY-003: the walk target wraps instead of being cut off', () => {
|
||||
render(<TransitWalkDivider leg={walk} t={t} size="sm" />);
|
||||
const text = screen.getByText(/transit\.walkTo:Reading station, Station Approach/);
|
||||
expect(clipsToOneLine(text)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -41,14 +41,14 @@ export function TransitWalkDivider({ leg, t, size = 'md' }: {
|
||||
background: `linear-gradient(to ${dir}, var(--text-faint), transparent)`,
|
||||
opacity: 0.55,
|
||||
})
|
||||
// On phones the minutes lead so a long stop name only ever clips the name.
|
||||
// On phones the minutes lead, so they stay on the first line when a long stop name wraps.
|
||||
const text = isMobile
|
||||
? `${mins ? `${t('transit.min', { count: mins })} · ` : ''}${t('transit.walkTo', { name: leg.to?.name || '' })}`
|
||||
: `${t('transit.walkTo', { name: leg.to?.name || '' })}${mins ? ` · ${t('transit.min', { count: mins })}` : ''}`
|
||||
return (
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: size === 'sm' ? '1px 0' : '2px 0' }}>
|
||||
<span style={rule('left')} />
|
||||
<span className="text-content-faint" style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: size === 'sm' ? 'calc(10px * var(--fs-scale-caption, 1))' : 'calc(11.5px * var(--fs-scale-caption, 1))', fontWeight: 500, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', maxWidth: isMobile ? '85%' : '75%' }}>
|
||||
<span className="text-content-faint" style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: size === 'sm' ? 'calc(10px * var(--fs-scale-caption, 1))' : 'calc(11.5px * var(--fs-scale-caption, 1))', fontWeight: 500, textAlign: 'center', overflowWrap: 'anywhere', maxWidth: isMobile ? '85%' : '75%' }}>
|
||||
<Footprints size={size === 'sm' ? 11 : 12} style={{ flexShrink: 0 }} />
|
||||
{text}
|
||||
</span>
|
||||
@@ -72,8 +72,10 @@ export function TransitItineraryInline({ legs, t }: {
|
||||
const mins = leg.duration ? Math.round(leg.duration / 60) : null
|
||||
return (
|
||||
<div key={i} style={{ display: 'flex', alignItems: 'flex-start', gap: 7 }}>
|
||||
<span className="text-content-muted" style={{ width: 34, flexShrink: 0, textAlign: 'end', fontSize: 'calc(10px * var(--fs-scale-caption, 1))', fontWeight: 600, paddingTop: 1 }}>
|
||||
{leg.from?.time || ''}
|
||||
{/* Departure beside the stops, arrival under it (#3139). */}
|
||||
<span className="text-content-muted" style={{ width: 34, flexShrink: 0, alignSelf: 'stretch', display: 'flex', flexDirection: 'column', justifyContent: 'space-between', textAlign: 'end', fontSize: 'calc(10px * var(--fs-scale-caption, 1))', fontWeight: 600, paddingTop: 1 }}>
|
||||
<span>{leg.from?.time || ''}</span>
|
||||
{leg.to?.time && <span className="text-content-faint">{leg.to.time}</span>}
|
||||
</span>
|
||||
<span style={{
|
||||
display: 'inline-flex', alignItems: 'center', borderRadius: 4, padding: '0 5px',
|
||||
@@ -84,10 +86,11 @@ export function TransitItineraryInline({ legs, t }: {
|
||||
{leg.line || leg.mode}
|
||||
</span>
|
||||
<div style={{ flex: 1, minWidth: 0 }}>
|
||||
<div className="text-content" style={{ fontSize: 'calc(11px * var(--fs-scale-caption, 1))', fontWeight: 500, display: 'flex', alignItems: 'center', gap: 4, minWidth: 0 }}>
|
||||
<span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{leg.from?.name}</span>
|
||||
{/* The folded-out itinerary is where a journey is read in full: stop names wrap (#3139). */}
|
||||
<div className="text-content" style={{ fontSize: 'calc(11px * var(--fs-scale-caption, 1))', fontWeight: 500, display: 'flex', flexWrap: 'wrap', alignItems: 'center', columnGap: 4, minWidth: 0 }}>
|
||||
<span dir="auto" style={{ minWidth: 0, overflowWrap: 'anywhere' }}>{leg.from?.name}</span>
|
||||
<MoveRight size={10} className="text-content-faint" style={{ flexShrink: 0 }} />
|
||||
<span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{leg.to?.name}</span>
|
||||
<span dir="auto" style={{ minWidth: 0, overflowWrap: 'anywhere' }}>{leg.to?.name}</span>
|
||||
</div>
|
||||
<div className="text-content-faint" style={{ fontSize: 'calc(9.5px * var(--fs-scale-caption, 1))', marginTop: 1 }}>
|
||||
{[
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
// FE-PLANNER-TRIPEXPORT-001 to -014: the trip exports behind the desktop export
|
||||
// FE-PLANNER-TRIPEXPORT-001 to -015: the trip exports behind the desktop export
|
||||
// dialog and the phone's export sheet.
|
||||
import { act, renderHook } from '@testing-library/react';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi, type MockInstance } from 'vitest';
|
||||
|
||||
import { buildAssignment, buildReservation, buildTrip, buildUser } from '../../../tests/helpers/factories';
|
||||
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
|
||||
import { resetAllStores, seedInstanceAddons, seedStore } from '../../../tests/helpers/store';
|
||||
import { useAuthStore } from '../../store/authStore';
|
||||
import { useTripAddonsStore } from '../../store/tripAddonsStore';
|
||||
import type { DayNote } from '../../types';
|
||||
import { downloadTripPDF } from '../PDF/TripPDF';
|
||||
import { flatDayNotes, saveBlob, useTripExport, type TripExportOptions } from './useTripExport';
|
||||
@@ -133,6 +134,17 @@ describe('useTripExport', () => {
|
||||
expect(vi.mocked(downloadTripPDF).mock.calls[1][0]).toMatchObject({ onlyUserId: 9 });
|
||||
});
|
||||
|
||||
it('FE-PLANNER-TRIPEXPORT-015: the PDF prints costs and tours as the trip has them, not the instance', async () => {
|
||||
seedInstanceAddons(['budget']);
|
||||
useTripAddonsStore.getState().publish(3, [
|
||||
{ id: 'budget', name: 'Costs', icon: null, enabled: false, instanceEnabled: true, overridden: true },
|
||||
{ id: 'tours', name: 'Tours', icon: null, enabled: true, instanceEnabled: false, overridden: true },
|
||||
]);
|
||||
const { result } = renderHook(() => useTripExport(options()));
|
||||
await act(() => result.current.exportPdf());
|
||||
expect(vi.mocked(downloadTripPDF).mock.calls[0][0]).toMatchObject({ costsEnabled: false, toursEnabled: true });
|
||||
});
|
||||
|
||||
it('FE-PLANNER-TRIPEXPORT-005: the phone stays open after the PDF and prints nothing without a trip', async () => {
|
||||
const opts = options(PHONE);
|
||||
const { result } = renderHook(() => useTripExport(opts));
|
||||
|
||||
@@ -3,6 +3,7 @@ import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { useRoadtripSettings } from '../../hooks/useRoadtripSettings';
|
||||
import { useAuthStore } from '../../store/authStore';
|
||||
import { useSettingsStore } from '../../store/settingsStore';
|
||||
import { useTripAddonEnabled } from '../../store/tripAddonsStore';
|
||||
import type { AssignmentsMap, Category, Day, DayNote, Place, Reservation, Trip } from '../../types';
|
||||
import { importChunk } from '../../utils/chunkReload';
|
||||
import type { ViasByDay } from '../../utils/dayRouteVias';
|
||||
@@ -144,6 +145,9 @@ export function useTripExport({
|
||||
// them, so it needs the same switch the plan reads.
|
||||
const showServiceStops = useRoadtripSettings((s) => s.roadtrip_service_stops_in_days !== false, tripId);
|
||||
const myId = useAuthStore((s) => s.user?.id);
|
||||
// The sections the trip has on, as the plan shows them: costs in the figures, tours on the route.
|
||||
const costsEnabled = useTripAddonEnabled(tripId, 'budget');
|
||||
const toursEnabled = useTripAddonEnabled(tripId, 'tours');
|
||||
const offerMine = myId != null && hasPersonalPlan(data.assignments, data.reservations);
|
||||
const fileBase = data.trip?.title || 'trip';
|
||||
|
||||
@@ -185,6 +189,8 @@ export function useTripExport({
|
||||
timeFormat,
|
||||
distanceUnit,
|
||||
showServiceStops,
|
||||
costsEnabled,
|
||||
toursEnabled,
|
||||
onlyUserId: mine ? myId : undefined,
|
||||
route: { viasByDay: data.viasByDay, tourStageStops: data.tourStageStops, ...routing },
|
||||
signal: givenUp,
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { dayColor } from './dayColors'
|
||||
import { stageMapData, stagePlaceIds, stagePoints } from './stageMap'
|
||||
import { stageConnectionIds, stageMapData, stagePlaceIds, stagePoints } from './stageMap'
|
||||
import type { AccessSpur, RoadtripDay, RoadtripRoutes, RoadtripStop } from '@trek/shared/roadtrip'
|
||||
|
||||
// FE-RTSTAGE-001 to FE-RTSTAGE-021
|
||||
// FE-RTSTAGE-001 to FE-RTSTAGE-023
|
||||
|
||||
function stop(name: string, over: Partial<RoadtripStop> = {}): RoadtripStop {
|
||||
return {
|
||||
@@ -268,3 +268,23 @@ describe('a stage that starts or ends at a booked night', () => {
|
||||
expect(data.accessLines).toEqual([walk])
|
||||
})
|
||||
})
|
||||
|
||||
describe('stageConnectionIds', () => {
|
||||
const flight = (reservationId: number, role: 'arrival' | 'departure') =>
|
||||
stop('Airport', { carrier: { reservationId, type: 'flight', role, title: 'Flight', code: null, at: null } })
|
||||
|
||||
it("FE-RTSTAGE-022: a stage draws its own rides, not the drive's ride home from a later day", () => {
|
||||
// The flight in (31) seams this stage; the flight home (32) belongs to a stage days later
|
||||
// and is not on this one at all.
|
||||
const stage = day([flight(31, 'arrival'), stop('Ubud')])
|
||||
expect(stageConnectionIds(stage, [], () => true)).toEqual([31])
|
||||
})
|
||||
|
||||
it('FE-RTSTAGE-023: of the bookings switched on by hand only those running on the stage day stay', () => {
|
||||
const stage = day([stop('Ubud')])
|
||||
const onThisDay = new Set([40])
|
||||
expect(stageConnectionIds(stage, [40, 41], id => onThisDay.has(id))).toEqual([40])
|
||||
// A ride that seams the stage stays even when it was booked on another day.
|
||||
expect(stageConnectionIds(day([flight(31, 'arrival')]), [31], () => false)).toEqual([31])
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { dayColor } from './dayColors'
|
||||
import { carrierReservationIds } from '@trek/shared/roadtrip'
|
||||
import type { AccessSpur, RoadtripDay, RoadtripRoutes } from '@trek/shared/roadtrip'
|
||||
|
||||
/**
|
||||
@@ -88,6 +89,20 @@ export function stagePlaceIds(stage: RoadtripDay): Set<number> {
|
||||
return new Set(stage.stops.filter(s => !s.automaticNight).map(s => s.placeId))
|
||||
}
|
||||
|
||||
/**
|
||||
* The bookings the map draws as arcs on ONE stage: the rides that seam this stage's
|
||||
* drive, whatever day they were booked on, and of the ones switched on by hand only
|
||||
* those that run on the stage's day. Taking the rides of the whole drive put a flight
|
||||
* home across every stage before it, as if it were part of that day.
|
||||
*/
|
||||
export function stageConnectionIds(
|
||||
stage: RoadtripDay,
|
||||
switchedOn: readonly number[],
|
||||
runsOnStageDay: (reservationId: number) => boolean,
|
||||
): number[] {
|
||||
return [...new Set([...switchedOn.filter(runsOnStageDay), ...carrierReservationIds([stage])])]
|
||||
}
|
||||
|
||||
/** The stage's stops as coordinates, for the fit. */
|
||||
export function stagePoints(stage: RoadtripDay): [number, number][] {
|
||||
return stage.stops
|
||||
|
||||
@@ -447,7 +447,28 @@ describe('CollectionToursSection', () => {
|
||||
expect(await screen.findByTestId('kept-tour-preview')).toBeInTheDocument();
|
||||
unmount();
|
||||
useAddonStore.setState({ addons: [{ id: 'collections', enabled: true }] as never });
|
||||
const off = { response: { status: 404, data: { error: 'Tours addon is not enabled' } } };
|
||||
list.mockRejectedValue(off);
|
||||
render(<CollectionToursSection collectionId={3} canRemove />);
|
||||
await waitFor(() => expect(list).toHaveBeenLastCalledWith(3));
|
||||
expect(screen.queryByTestId('collection-tours')).toBeNull();
|
||||
expect(screen.queryByText('The tours of this list could not be loaded.')).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-COLLECTION-TOURS-021: with Tours off for the instance, the tours show once the server hands them over', async () => {
|
||||
useAddonStore.setState({ addons: [{ id: 'collections', enabled: true }] as never });
|
||||
// A trip of the user switched Tours on for itself, so the server answers.
|
||||
vi.spyOn(collectionToursRepo, 'list').mockResolvedValue({ tours: [kept()] });
|
||||
render(<CollectionToursSection collectionId={3} canRemove />);
|
||||
expect(await screen.findByTestId('kept-tour-4')).toHaveTextContent('Ridge');
|
||||
});
|
||||
|
||||
it('FE-COLLECTION-TOURS-022: with Tours off for the instance, a failed read shows nothing, as it always did', async () => {
|
||||
useAddonStore.setState({ addons: [{ id: 'collections', enabled: true }] as never });
|
||||
const list = vi.spyOn(collectionToursRepo, 'list').mockRejectedValue(new Error('500'));
|
||||
render(<CollectionToursSection collectionId={3} canRemove />);
|
||||
await waitFor(() => expect(list).toHaveBeenCalled());
|
||||
expect(screen.queryByText('The tours of this list could not be loaded.')).toBeNull();
|
||||
expect(screen.queryByTestId('collection-tours')).toBeNull();
|
||||
});
|
||||
|
||||
|
||||
@@ -13,23 +13,26 @@ import { useToast } from '../../shared/Toast';
|
||||
/**
|
||||
* LIB-03: the tours a collection keeps, for the collection's page. Read when
|
||||
* the collection opens and kept current while its members keep or remove one;
|
||||
* nothing at all while the Tours addon is off. Removing asks first and says
|
||||
* nothing at all while the Tours addon is off. Tours counts as on while the
|
||||
* instance has it on or any of the user's trips switched it on for itself;
|
||||
* only the server knows the second, so with the instance off the tours are
|
||||
* read all the same and its refusal hides them. Removing asks first and says
|
||||
* how it went.
|
||||
*/
|
||||
export function useCollectionTours(collectionId: number) {
|
||||
const { t } = useTranslation();
|
||||
const toast = useToast();
|
||||
const enabled = useAddonStore((state) => state.isEnabled('tours'));
|
||||
const instanceOn = useAddonStore((state) => state.isEnabled('tours'));
|
||||
const { tours, status, shownFor } = useCollectionTourStore(
|
||||
useShallow((state) => ({ tours: state.tours, status: state.status, shownFor: state.collectionId }))
|
||||
);
|
||||
const [removing, setRemoving] = useState<CollectionTourItem | null>(null);
|
||||
|
||||
// Read again when the instance switch flips, since the answer may change with it.
|
||||
useEffect(() => {
|
||||
if (!enabled) return undefined;
|
||||
void useCollectionTourStore.getState().load(collectionId);
|
||||
return watchCollectionTours();
|
||||
}, [collectionId, enabled]);
|
||||
}, [collectionId, instanceOn]);
|
||||
|
||||
const confirmRemove = async () => {
|
||||
const tour = removing;
|
||||
@@ -44,6 +47,9 @@ export function useCollectionTours(collectionId: number) {
|
||||
};
|
||||
|
||||
const current = shownFor === collectionId;
|
||||
// With the instance on nothing changes; with it off only tours the server handed over show,
|
||||
// so an install without a trip of its own choice shows nothing, as it always did.
|
||||
const enabled = instanceOn ? !(current && status === 'off') : current && status === 'ready';
|
||||
return {
|
||||
enabled,
|
||||
tours: enabled && current ? tours : [],
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { translateApiError, useTranslation } from '../../../i18n';
|
||||
import { tourPackingLinkRepo } from '../../../repo/tourPackingLinkRepo';
|
||||
import { useAddonStore } from '../../../store/addonStore';
|
||||
import { useTripAddonEnabled } from '../../../store/tripAddonsStore';
|
||||
import { useTripStore } from '../../../store/tripStore';
|
||||
import type { PackingItem } from '../../../types';
|
||||
import { packingCategoryOrder, packingViewItems } from '../../Packing/packingListModel';
|
||||
@@ -42,7 +42,7 @@ interface TourPackingCategory extends PackingCategoryChoice {
|
||||
export function useTourPackingLink({ tripId, tour }: { tripId: number; tour: TourListItem }) {
|
||||
const { t } = useTranslation();
|
||||
const toast = useToast();
|
||||
const packingEnabled = useAddonStore((state) => state.isEnabled('packing'));
|
||||
const packingEnabled = useTripAddonEnabled(tripId, 'packing');
|
||||
const items = useTripStore((state) => state.packingItems);
|
||||
const placeId = tour.place_id;
|
||||
const key = `${tripId}:${placeId}`;
|
||||
|
||||
@@ -23,7 +23,7 @@ const state = vi.hoisted(() => ({
|
||||
}))
|
||||
|
||||
vi.mock('../../store/tripStore', () => ({ useTripStore: (selector: (store: unknown) => unknown) => selector({ trip: state.trip, loadTrip: state.loadTrip, refreshPlaces: state.refreshPlaces, places: [], packingItems: state.packingItems }) }))
|
||||
vi.mock('../../store/authStore', () => ({ useAuthStore: (selector: (store: unknown) => unknown) => selector({ user: state.user }) }))
|
||||
vi.mock('../../store/authStore', () => ({ useAuthStore: Object.assign((selector: (store: unknown) => unknown) => selector({ user: state.user }), { getState: () => ({ user: state.user }) }) }))
|
||||
vi.mock('../../store/settingsStore', () => ({ useSettingsStore: (selector: (store: unknown) => unknown) => selector({ settings: { distance_unit: 'metric' } }) }))
|
||||
vi.mock('../Map/MapViewAuto', () => ({ MapViewAuto: () => null }))
|
||||
vi.mock('../../repo/tourRepo', () => ({ tourRepo: { importGpx: state.importGpx, previewGpx: state.previewGpx, create: state.create, update: state.update, detail: state.detail } }))
|
||||
|
||||
@@ -7,7 +7,7 @@ import { server } from '../../../tests/helpers/msw/server';
|
||||
import { useAuthStore } from '../../store/authStore';
|
||||
import { useTripStore } from '../../store/tripStore';
|
||||
import { usePermissionsStore } from '../../store/permissionsStore';
|
||||
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
|
||||
import { resetAllStores, seedInstanceAddons, seedStore } from '../../../tests/helpers/store';
|
||||
import { buildUser, buildTrip } from '../../../tests/helpers/factories';
|
||||
import TripMembersModal from './TripMembersModal';
|
||||
|
||||
@@ -101,6 +101,8 @@ beforeEach(() => {
|
||||
);
|
||||
seedStore(useAuthStore, { user: ownerUser, isAuthenticated: true });
|
||||
seedStore(useTripStore, { trip: buildTrip({ id: 1, title: 'Test Trip' }) });
|
||||
// The instance has the three addons a link section belongs to; the trip names none of its own.
|
||||
seedInstanceAddons(['packing', 'budget', 'collab']);
|
||||
addToast = vi.fn<AddToast>(() => 0);
|
||||
window.__addToast = addToast;
|
||||
});
|
||||
@@ -1131,4 +1133,34 @@ describe('TripMembersModal', () => {
|
||||
expect(await screen.findByText('owner')).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: 'Edit Trip' })).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-COMP-MEMBERS-064: the owner switches the trip addons in an area of their own', async () => {
|
||||
const user = userEvent.setup();
|
||||
const bodies: unknown[] = [];
|
||||
const list = [
|
||||
{ id: 'budget', name: 'Budget', icon: 'Wallet', enabled: false, instanceEnabled: true, overridden: true },
|
||||
];
|
||||
server.use(
|
||||
http.get('/api/trips/1/addons', () => HttpResponse.json({ tripId: 1, addons: list })),
|
||||
http.put('/api/trips/1/addons/:addonId', async ({ request }) => {
|
||||
bodies.push(await request.json());
|
||||
return HttpResponse.json({ tripId: 1, addons: list });
|
||||
}),
|
||||
);
|
||||
render(<TripMembersModal {...defaultProps} />);
|
||||
|
||||
const nav = await screen.findByRole('navigation', { name: 'Trip settings' });
|
||||
await user.click(await within(nav).findByRole('button', { name: 'Addons' }));
|
||||
expect(await screen.findByText('This trip only')).toBeInTheDocument();
|
||||
await user.click(screen.getByRole('button', { name: 'Costs' }));
|
||||
await waitFor(() => expect(bodies).toEqual([{ enabled: null }]));
|
||||
});
|
||||
|
||||
it('FE-COMP-MEMBERS-065: a member who is not the owner gets no Addons area', async () => {
|
||||
seedStore(useAuthStore, { user: memberUser, isAuthenticated: true });
|
||||
render(<TripMembersModal {...defaultProps} />);
|
||||
|
||||
expect(await screen.findByText('owner')).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: 'Addons' })).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { useId, useState, type ComponentProps, type ReactNode } from 'react'
|
||||
import { Check, Copy, Crown, Link2, LogOut, Pencil, Plus, Settings, Trash2, UserMinus, UserPlus, UserRound, Users } from 'lucide-react'
|
||||
import { Check, Copy, Crown, Link2, LogOut, Pencil, Plus, Puzzle, Settings, Trash2, UserMinus, UserPlus, UserRound, Users } from 'lucide-react'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import CustomSelect from '../shared/CustomSelect'
|
||||
import ConfirmDialog from '../shared/ConfirmDialog'
|
||||
import ToggleSwitch from '../Settings/ToggleSwitch'
|
||||
import { Tooltip } from '../shared/Tooltip'
|
||||
import { DialogButton, DialogHeader, DialogSection, DialogShell, DialogTile, NEUTRAL_TINT, PILL, fs } from '../shared/DialogShell'
|
||||
import { AddRowButton, CardHead, INPUT, LABEL, PANEL } from '../shared/dialogParts'
|
||||
@@ -12,7 +13,8 @@ import TripFormModal from './TripFormModal'
|
||||
import { TripJournalLinkSection } from './TripJournalLinkSection'
|
||||
import { TripMemberAvatar } from './TripMemberAvatar'
|
||||
import { useTripJournalSectionVisible } from './useTripJournalLink'
|
||||
import { SHARE_OPTIONS, SHARE_SECTIONS, useShareLink, useTripInviteLink, useTripMembers, type TripMembersState } from './useTripShare'
|
||||
import { useTripAddonRows } from './useTripAddonRows'
|
||||
import { SHARE_OPTIONS, useShareLink, useTripInviteLink, useTripMembers, type TripMembersState } from './useTripShare'
|
||||
|
||||
interface TripShareDialogProps {
|
||||
isOpen: boolean
|
||||
@@ -57,19 +59,21 @@ const NAV_ENTRY_OFF = 'text-content-muted hover:bg-surface-hover hover:text-cont
|
||||
|
||||
/**
|
||||
* The trip's Settings on the desktop: who is on the trip, its guests, the two
|
||||
* links that let others in, and the journal the trip shows.
|
||||
* links that let others in, the journal the trip shows, and for the owner
|
||||
* which addons the trip uses.
|
||||
*/
|
||||
export default function TripShareDialog(props: TripShareDialogProps) {
|
||||
return props.isOpen ? <OpenDialog {...props} /> : null
|
||||
}
|
||||
|
||||
type Area = 'people' | 'sharing' | 'journal' | 'trip'
|
||||
type Area = 'people' | 'sharing' | 'journal' | 'addons' | 'trip'
|
||||
|
||||
/** The areas of the dialog, each with its icon, its name and the line under the name. */
|
||||
const AREAS: { id: Area; icon: (on: boolean) => ReactNode; labelKey: string; hintKey: string }[] = [
|
||||
{ id: 'people', icon: () => <Users size={16} strokeWidth={2} />, labelKey: 'trip.settings.people', hintKey: 'trip.settings.peopleHint' },
|
||||
{ id: 'sharing', icon: () => <Link2 size={16} strokeWidth={2} />, labelKey: 'trip.settings.sharing', hintKey: 'trip.settings.sharingHint' },
|
||||
{ id: 'journal', icon: () => <LinkedJournalIcon size={16} />, labelKey: 'trip.journal.title', hintKey: 'trip.journal.hint' },
|
||||
{ id: 'addons', icon: () => <Puzzle size={16} strokeWidth={2} />, labelKey: 'trip.settings.addons', hintKey: 'trip.settings.addonsHint' },
|
||||
{ id: 'trip', icon: () => <Pencil size={16} strokeWidth={2} />, labelKey: 'dashboard.editTrip', hintKey: 'trip.settings.editTripHint' },
|
||||
]
|
||||
|
||||
@@ -81,7 +85,7 @@ function OpenDialog({ onClose, tripId, tripTitle, onMembersChanged, editTrip }:
|
||||
const [area, setArea] = useState<Area>('people')
|
||||
const [tripReviewing, setTripReviewing] = useState(false)
|
||||
const journalSection = useTripJournalSectionVisible(tripId)
|
||||
const shows: Record<Area, boolean> = { people: true, sharing: m.canManageShare, journal: journalSection, trip: !!editTrip }
|
||||
const shows: Record<Area, boolean> = { people: true, sharing: m.canManageShare, journal: journalSection, addons: m.isCurrentOwner, trip: !!editTrip }
|
||||
const areas = AREAS.filter(a => shows[a.id])
|
||||
const current = areas.find(a => a.id === area) ?? areas[0]
|
||||
const panelOf = (id: Area) => areas.find(a => a.id === id)
|
||||
@@ -132,6 +136,11 @@ function OpenDialog({ onClose, tripId, tripTitle, onMembersChanged, editTrip }:
|
||||
<TripJournalLinkSection tripId={tripId} framed={false} />
|
||||
</AreaPanel>
|
||||
)}
|
||||
{m.isCurrentOwner && (
|
||||
<AreaPanel area={panelOf('addons')} shown={current.id === 'addons'} titled>
|
||||
<TripAddonsList tripId={tripId} />
|
||||
</AreaPanel>
|
||||
)}
|
||||
{editTrip && (
|
||||
<AreaPanel area={panelOf('trip')} shown={current.id === 'trip'} titled>
|
||||
<TripFormModal embedded isOpen onClose={onClose} onReviewChange={setTripReviewing} {...editTrip} />
|
||||
@@ -418,6 +427,32 @@ function PermChip({ on, disabled, label, hint, onToggle }: { on: boolean; disabl
|
||||
return hint ? <Tooltip label={hint}>{chip}</Tooltip> : chip
|
||||
}
|
||||
|
||||
/** The trip addons, each with its switch; a badge marks the ones the owner set apart from the instance. */
|
||||
function TripAddonsList({ tripId }: { tripId: number }) {
|
||||
const { t } = useTranslation()
|
||||
const { rows, loading } = useTripAddonRows(tripId)
|
||||
if (loading) return <div className="h-[120px] animate-pulse rounded-[14px] bg-surface-secondary" />
|
||||
return (
|
||||
<div className={ROWS}>
|
||||
{rows.map(row => (
|
||||
<div key={row.id} className={ROW}>
|
||||
<span className={`flex h-8 w-8 flex-none items-center justify-center rounded-[10px] bg-surface-tertiary ${row.enabled ? 'text-content' : 'text-content-faint'}`}>
|
||||
<row.Icon size={16} strokeWidth={2} />
|
||||
</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<span className="truncate font-semibold text-content" style={fs(13.5, 'body')}>{row.name}</span>
|
||||
{row.ownChoice && <span className={`${BADGE} bg-surface-tertiary text-content-muted`} style={fs(10.5, 'caption')}>{t('trip.addons.thisTripOnly')}</span>}
|
||||
</div>
|
||||
{row.description && <p className="m-0 truncate text-content-muted" style={fs(12, 'caption')}>{row.description}</p>}
|
||||
</div>
|
||||
<ToggleSwitch on={row.enabled} onToggle={row.toggle} label={row.name} disabled={row.busy} />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** The read-only public link, and which parts of the trip it shows. */
|
||||
function PublicLink({ tripId }: { tripId: number }) {
|
||||
const { t } = useTranslation()
|
||||
@@ -429,7 +464,7 @@ function PublicLink({ tripId }: { tripId: number }) {
|
||||
<div>
|
||||
<span className={LABEL}>{t('share.options')}</span>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{SHARE_SECTIONS.map(opt => (
|
||||
{link.sections.map(opt => (
|
||||
<PermChip key={opt.key} on={link.perms[opt.key]} disabled={opt.always} label={t(opt.label)}
|
||||
onToggle={() => void link.setPerm(opt.key, !link.perms[opt.key])} />
|
||||
))}
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
// FE-TRIPADDONROWS-001 to FE-TRIPADDONROWS-003: the rows of the trip settings' Addons area,
|
||||
// shared by the desktop dialog and the phone sheet.
|
||||
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||
import type { TripAddon } from '@trek/shared';
|
||||
import 'fake-indexeddb/auto';
|
||||
import { CarFront, ListChecks, Puzzle } from 'lucide-react';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import type { ReactNode } from 'react';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { buildUser } from '../../../tests/helpers/factories';
|
||||
import { server } from '../../../tests/helpers/msw/server';
|
||||
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
|
||||
import { clearAll } from '../../db/offlineDb';
|
||||
import { TranslationProvider } from '../../i18n/TranslationContext';
|
||||
import { useAuthStore } from '../../store/authStore';
|
||||
import { useTripAddonRows } from './useTripAddonRows';
|
||||
|
||||
const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn(), warning: vi.fn(), info: vi.fn() }));
|
||||
vi.mock('../shared/Toast', () => ({ useToast: () => toast }));
|
||||
|
||||
const LIST: TripAddon[] = [
|
||||
{ id: 'packing', name: 'Packing', icon: 'ListChecks', enabled: true, instanceEnabled: true, overridden: false },
|
||||
{ id: 'roadtrip', name: 'Road trip', icon: 'Route', enabled: false, instanceEnabled: true, overridden: true },
|
||||
{ id: 'someplugin', name: 'Some plugin', icon: 'Unknown', enabled: true, instanceEnabled: false, overridden: true },
|
||||
];
|
||||
|
||||
function wrapper({ children }: { children: ReactNode }) {
|
||||
return <TranslationProvider>{children}</TranslationProvider>;
|
||||
}
|
||||
|
||||
let bodies: unknown[] = [];
|
||||
|
||||
beforeEach(async () => {
|
||||
await clearAll();
|
||||
resetAllStores();
|
||||
bodies = [];
|
||||
seedStore(useAuthStore, { user: buildUser({ id: 1 }), isAuthenticated: true });
|
||||
server.use(
|
||||
http.get('/api/trips/4/addons', () => HttpResponse.json({ tripId: 4, addons: LIST })),
|
||||
http.put('/api/trips/4/addons/:addonId', async ({ request }) => {
|
||||
bodies.push(await request.json());
|
||||
return HttpResponse.json({ tripId: 4, addons: LIST });
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
describe('useTripAddonRows', () => {
|
||||
it('FE-TRIPADDONROWS-001: names each addon from the catalog, with its icon and whether the trip chose it', async () => {
|
||||
const { result } = renderHook(() => useTripAddonRows(4), { wrapper });
|
||||
expect(result.current.loading).toBe(true);
|
||||
await waitFor(() => expect(result.current.rows).toHaveLength(3));
|
||||
|
||||
const [packing, roadtrip, plugin] = result.current.rows;
|
||||
expect(packing).toMatchObject({ name: 'Lists', Icon: ListChecks, enabled: true, ownChoice: false });
|
||||
expect(packing.description).not.toBe('');
|
||||
expect(roadtrip).toMatchObject({ Icon: CarFront, enabled: false, ownChoice: true });
|
||||
// An addon the catalog does not know keeps the server's name, no description and the fallback icon.
|
||||
expect(plugin).toMatchObject({ name: 'Some plugin', description: '', Icon: Puzzle });
|
||||
expect(result.current.loading).toBe(false);
|
||||
});
|
||||
|
||||
it('FE-TRIPADDONROWS-002: a switch away from the instance stores the choice, back to it drops the choice', async () => {
|
||||
const { result } = renderHook(() => useTripAddonRows(4), { wrapper });
|
||||
await waitFor(() => expect(result.current.rows).toHaveLength(3));
|
||||
|
||||
act(() => result.current.rows[0].toggle());
|
||||
await waitFor(() => expect(bodies).toEqual([{ enabled: false }]));
|
||||
await waitFor(() => expect(result.current.rows[0].busy).toBe(false));
|
||||
|
||||
act(() => result.current.rows[1].toggle());
|
||||
await waitFor(() => expect(bodies).toEqual([{ enabled: false }, { enabled: null }]));
|
||||
});
|
||||
|
||||
it('FE-TRIPADDONROWS-003: a second switch while one is saving is ignored', async () => {
|
||||
const { result } = renderHook(() => useTripAddonRows(4), { wrapper });
|
||||
await waitFor(() => expect(result.current.rows).toHaveLength(3));
|
||||
|
||||
act(() => result.current.rows[0].toggle());
|
||||
expect(result.current.rows[0].busy).toBe(true);
|
||||
act(() => result.current.rows[2].toggle());
|
||||
await waitFor(() => expect(result.current.rows[0].busy).toBe(false));
|
||||
expect(bodies).toEqual([{ enabled: false }]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
import {
|
||||
CarFront,
|
||||
Compass,
|
||||
FileText,
|
||||
ListChecks,
|
||||
Mountain,
|
||||
Puzzle,
|
||||
Users,
|
||||
Wallet,
|
||||
type LucideIcon,
|
||||
} from 'lucide-react';
|
||||
import { useState } from 'react';
|
||||
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { useTripAddons } from './useTripAddons';
|
||||
|
||||
/** The addons table's `icon` names of the trip addons; road trip was seeded as `Route`, the car says it better. */
|
||||
const ICONS: Readonly<Record<string, LucideIcon>> = {
|
||||
ListChecks,
|
||||
Wallet,
|
||||
FileText,
|
||||
Users,
|
||||
Route: CarFront,
|
||||
Mountain,
|
||||
Compass,
|
||||
};
|
||||
|
||||
/** One trip addon as the trip settings list it. */
|
||||
interface TripAddonRow {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
Icon: LucideIcon;
|
||||
enabled: boolean;
|
||||
/** The owner chose this for the trip, so it differs from the instance. */
|
||||
ownChoice: boolean;
|
||||
busy: boolean;
|
||||
toggle: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* The rows of the trip settings' Addons area, the same on the desktop dialog and
|
||||
* the phone sheet. Flipping a switch back to what the instance says drops the
|
||||
* trip's own choice instead of storing a copy of it, so a later change by the
|
||||
* admin reaches the trip again and no reset button is needed.
|
||||
*/
|
||||
export function useTripAddonRows(tripId: number) {
|
||||
const { t } = useTranslation();
|
||||
const trip = useTripAddons(tripId);
|
||||
const [busy, setBusy] = useState<string | null>(null);
|
||||
|
||||
const rows: TripAddonRow[] = trip.addons.map((addon) => {
|
||||
// Spelled out inside t() so the key check sees which catalog keys this reaches.
|
||||
const name = t(`admin.addons.catalog.${addon.id}.name`);
|
||||
const description = t(`admin.addons.catalog.${addon.id}.description`);
|
||||
return {
|
||||
id: addon.id,
|
||||
name: name === `admin.addons.catalog.${addon.id}.name` ? addon.name : name,
|
||||
description: description === `admin.addons.catalog.${addon.id}.description` ? '' : description,
|
||||
Icon: (addon.icon && ICONS[addon.icon]) || Puzzle,
|
||||
enabled: addon.enabled,
|
||||
ownChoice: addon.overridden,
|
||||
busy: busy === addon.id,
|
||||
toggle: () => {
|
||||
if (busy) return;
|
||||
const next = !addon.enabled;
|
||||
setBusy(addon.id);
|
||||
void trip.setOverride(addon.id, next === addon.instanceEnabled ? null : next).finally(() => setBusy(null));
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
return { rows, loading: trip.loading && rows.length === 0 };
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
// FE-TRIPADDONS-HOOK-001 to FE-TRIPADDONS-HOOK-006: the trip addons of one trip for the
|
||||
// planner and the trip settings: read, refreshed when the connection returns, switched
|
||||
// by the owner online only.
|
||||
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||
import type { TripAddon } from '@trek/shared';
|
||||
import 'fake-indexeddb/auto';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import type { ReactNode } from 'react';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { buildUser } from '../../../tests/helpers/factories';
|
||||
import { server } from '../../../tests/helpers/msw/server';
|
||||
import { resetAllStores, seedInstanceAddons, seedStore } from '../../../tests/helpers/store';
|
||||
import { clearAll } from '../../db/offlineDb';
|
||||
import { TranslationProvider } from '../../i18n/TranslationContext';
|
||||
import { useAuthStore } from '../../store/authStore';
|
||||
import { useTripAddons } from './useTripAddons';
|
||||
|
||||
const env = vi.hoisted(() => ({
|
||||
offline: false,
|
||||
modeListeners: [] as Array<() => void>,
|
||||
toast: { success: vi.fn(), error: vi.fn(), warning: vi.fn(), info: vi.fn() },
|
||||
}));
|
||||
|
||||
vi.mock('../../sync/networkMode', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../../sync/networkMode')>();
|
||||
return {
|
||||
...actual,
|
||||
isEffectivelyOffline: () => env.offline,
|
||||
onNetworkModeChange: (fn: () => void) => {
|
||||
env.modeListeners.push(fn);
|
||||
return () => {
|
||||
env.modeListeners = env.modeListeners.filter((l) => l !== fn);
|
||||
};
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock('../shared/Toast', () => ({ useToast: () => env.toast }));
|
||||
|
||||
const addon = (id: string, enabled: boolean, instanceEnabled: boolean): TripAddon => ({
|
||||
id,
|
||||
name: id,
|
||||
icon: null,
|
||||
enabled,
|
||||
instanceEnabled,
|
||||
overridden: enabled !== instanceEnabled,
|
||||
});
|
||||
|
||||
function wrapper({ children }: { children: ReactNode }) {
|
||||
return <TranslationProvider>{children}</TranslationProvider>;
|
||||
}
|
||||
|
||||
function tripHas(addons: TripAddon[]) {
|
||||
server.use(http.get('/api/trips/4/addons', () => HttpResponse.json({ tripId: 4, addons })));
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
await clearAll();
|
||||
resetAllStores();
|
||||
vi.clearAllMocks();
|
||||
env.offline = false;
|
||||
env.modeListeners = [];
|
||||
seedStore(useAuthStore, { user: buildUser({ id: 1 }), isAuthenticated: true });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe('useTripAddons', () => {
|
||||
it('FE-TRIPADDONS-HOOK-001: reads the trip’s list, and until then answers with the instance switches', async () => {
|
||||
seedInstanceAddons(['budget']);
|
||||
tripHas([addon('budget', false, true), addon('tours', true, false)]);
|
||||
|
||||
const { result } = renderHook(() => useTripAddons(4), { wrapper });
|
||||
|
||||
expect(result.current.loading).toBe(true);
|
||||
expect(result.current.loaded).toBe(false);
|
||||
expect(result.current.isEnabled('budget')).toBe(true);
|
||||
|
||||
await waitFor(() => expect(result.current.loaded).toBe(true));
|
||||
expect(result.current.loading).toBe(false);
|
||||
expect(result.current.addons.map((a) => a.id)).toEqual(['budget', 'tours']);
|
||||
expect(result.current.isEnabled('budget')).toBe(false);
|
||||
expect(result.current.isEnabled('tours')).toBe(true);
|
||||
// Not a trip addon: the instance decides.
|
||||
expect(result.current.isEnabled('dawarich')).toBe(false);
|
||||
});
|
||||
|
||||
it('FE-TRIPADDONS-HOOK-002: reads again when the connection comes back, and no trip reads nothing', async () => {
|
||||
let asked = 0;
|
||||
server.use(
|
||||
http.get('/api/trips/4/addons', () => {
|
||||
asked++;
|
||||
return HttpResponse.json({ tripId: 4, addons: [addon('budget', asked > 1, true)] });
|
||||
})
|
||||
);
|
||||
const { result } = renderHook(() => useTripAddons(4), { wrapper });
|
||||
await waitFor(() => expect(result.current.loading).toBe(false));
|
||||
expect(result.current.isEnabled('budget')).toBe(false);
|
||||
|
||||
expect(env.modeListeners).toHaveLength(1);
|
||||
act(() => env.modeListeners.forEach((listener) => listener()));
|
||||
|
||||
await waitFor(() => expect(result.current.isEnabled('budget')).toBe(true));
|
||||
expect(asked).toBe(2);
|
||||
|
||||
const none = renderHook(() => useTripAddons(null), { wrapper });
|
||||
expect(none.result.current).toMatchObject({ addons: [], loading: false, loaded: false });
|
||||
});
|
||||
|
||||
it('FE-TRIPADDONS-HOOK-003: the owner switches an addon, and the trip follows the answer', async () => {
|
||||
let sent: unknown = null;
|
||||
server.use(
|
||||
http.put('/api/trips/4/addons/budget', async ({ request }) => {
|
||||
sent = await request.json();
|
||||
return HttpResponse.json({ tripId: 4, addons: [addon('budget', true, false)] });
|
||||
})
|
||||
);
|
||||
const { result } = renderHook(() => useTripAddons(4), { wrapper });
|
||||
await waitFor(() => expect(result.current.loaded).toBe(true));
|
||||
|
||||
let ok = false;
|
||||
await act(async () => {
|
||||
ok = await result.current.setOverride('budget', true);
|
||||
});
|
||||
|
||||
expect(ok).toBe(true);
|
||||
expect(sent).toEqual({ enabled: true });
|
||||
expect(result.current.isEnabled('budget')).toBe(true);
|
||||
expect(env.toast.error).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-TRIPADDONS-HOOK-004: offline the switch is refused with a word why, and nothing is sent', async () => {
|
||||
let sent = false;
|
||||
server.use(
|
||||
http.put('/api/trips/4/addons/:addonId', () => {
|
||||
sent = true;
|
||||
return HttpResponse.json({ tripId: 4, addons: [] });
|
||||
})
|
||||
);
|
||||
const { result } = renderHook(() => useTripAddons(4), { wrapper });
|
||||
env.offline = true;
|
||||
|
||||
let ok = true;
|
||||
await act(async () => {
|
||||
ok = await result.current.setOverride('budget', false);
|
||||
});
|
||||
|
||||
expect(ok).toBe(false);
|
||||
expect(sent).toBe(false);
|
||||
expect(env.toast.error).toHaveBeenCalledWith(expect.stringMatching(/connection/i));
|
||||
});
|
||||
|
||||
it('FE-TRIPADDONS-HOOK-005: a refusal from the server is said in its own words', async () => {
|
||||
server.use(
|
||||
http.put('/api/trips/4/addons/budget', () =>
|
||||
HttpResponse.json({ error: 'Only the owner can change the addons of this trip' }, { status: 403 })
|
||||
)
|
||||
);
|
||||
const { result } = renderHook(() => useTripAddons(4), { wrapper });
|
||||
|
||||
let ok = true;
|
||||
await act(async () => {
|
||||
ok = await result.current.setOverride('budget', null);
|
||||
});
|
||||
|
||||
expect(ok).toBe(false);
|
||||
expect(env.toast.error).toHaveBeenCalledWith('Only the owner can change the addons of this trip');
|
||||
});
|
||||
|
||||
it('FE-TRIPADDONS-HOOK-006: a failure without the server’s words falls back to the localized one', async () => {
|
||||
server.use(http.put('/api/trips/4/addons/budget', () => HttpResponse.json({}, { status: 500 })));
|
||||
const { result } = renderHook(() => useTripAddons(4), { wrapper });
|
||||
|
||||
await act(async () => {
|
||||
await result.current.setOverride('budget', true);
|
||||
});
|
||||
|
||||
expect(env.toast.error).toHaveBeenCalledWith('The addons of this trip could not be changed.');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,79 @@
|
||||
import type { TripAddon } from '@trek/shared';
|
||||
import { useCallback, useEffect, useMemo } from 'react';
|
||||
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { useAddonStore } from '../../store/addonStore';
|
||||
import { tripAddonsEntry, useTripAddonsStore } from '../../store/tripAddonsStore';
|
||||
import { onNetworkModeChange } from '../../sync/networkMode';
|
||||
import { getApiErrorMessage } from '../../types';
|
||||
import { refusedOffline } from '../../utils/needsConnection';
|
||||
import { tripAddonEnabled } from '../../utils/tripAddons';
|
||||
import { useToast } from '../shared/Toast';
|
||||
|
||||
const NONE: TripAddon[] = [];
|
||||
|
||||
/**
|
||||
* The trip addons of one trip, each on or off for it, for the trip planner and
|
||||
* the trip's settings. Reads the trip's list when the trip changes and again
|
||||
* when the connection comes back; a change another member's owner made arrives
|
||||
* live through useTripAddonsSync.
|
||||
*
|
||||
* - `addons`: every trip addon as the trip sees it, in the admin's order; empty
|
||||
* until the first read answered (or offline with nothing kept).
|
||||
* - `isEnabled(id)`: whether an addon applies here; before the list is known,
|
||||
* and for an addon it does not name, the instance switch.
|
||||
* - `setOverride(id, enabled)`: the owner switches one addon for the trip,
|
||||
* `null` going back to the instance setting. Online only: offline it says so
|
||||
* and answers false. Answers whether the server took the change.
|
||||
*/
|
||||
export function useTripAddons(tripId: number | null | undefined) {
|
||||
const toast = useToast();
|
||||
const { t } = useTranslation();
|
||||
const validId = tripId != null && Number.isSafeInteger(tripId) && tripId > 0 ? tripId : null;
|
||||
const entry = useTripAddonsStore((state) => tripAddonsEntry(state, validId));
|
||||
// The instance list, so isEnabled answers anew once it is read.
|
||||
const instanceAddons = useAddonStore((state) => state.addons);
|
||||
|
||||
useEffect(() => {
|
||||
if (validId == null) return;
|
||||
const load = () => void useTripAddonsStore.getState().load(validId);
|
||||
load();
|
||||
return onNetworkModeChange(load);
|
||||
}, [validId]);
|
||||
|
||||
const isEnabled = useCallback(
|
||||
(addonId: string) =>
|
||||
tripAddonEnabled(
|
||||
entry?.addons,
|
||||
addonId,
|
||||
instanceAddons.some((addon) => addon.id === addonId && addon.enabled)
|
||||
),
|
||||
[entry?.addons, instanceAddons]
|
||||
);
|
||||
|
||||
const setOverride = useCallback(
|
||||
async (addonId: string, enabled: boolean | null): Promise<boolean> => {
|
||||
if (validId == null || refusedOffline(toast, t)) return false;
|
||||
try {
|
||||
await useTripAddonsStore.getState().setOverride(validId, addonId, enabled);
|
||||
return true;
|
||||
} catch (err) {
|
||||
toast.error(getApiErrorMessage(err, t('trip.addons.saveFailed')));
|
||||
return false;
|
||||
}
|
||||
},
|
||||
[validId, toast, t]
|
||||
);
|
||||
|
||||
return useMemo(
|
||||
() => ({
|
||||
addons: entry?.addons ?? NONE,
|
||||
loading: validId != null && (!entry || entry.status === 'loading'),
|
||||
/** A list is held, or the first read failed; until then isEnabled is the instance switch. */
|
||||
loaded: !!entry && (entry.addons != null || entry.status !== 'loading'),
|
||||
isEnabled,
|
||||
setOverride,
|
||||
}),
|
||||
[entry, validId, isEnabled, setOverride]
|
||||
);
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import { useTranslation } from '../../i18n'
|
||||
import { getApiErrorMessage } from '../../types'
|
||||
import { useCopied } from '../../hooks/useCopied'
|
||||
import { refusedOffline } from '../../utils/needsConnection'
|
||||
import { useTripAddons } from './useTripAddons'
|
||||
|
||||
// The state behind the share dialog, shared by the desktop dialog and the one the
|
||||
// phone opens from its More sheet. The questions ("Remove this member?") are the
|
||||
@@ -22,13 +23,13 @@ const DEFAULT_PERMS: SharePerms = {
|
||||
share_travel_only: false, share_hide_images: false,
|
||||
}
|
||||
|
||||
/** What the link shows, one tab each. */
|
||||
export const SHARE_SECTIONS: { key: SharePerm; label: string; always?: boolean }[] = [
|
||||
/** What the link shows, one tab each; a tab of an addon only while the trip has that addon on. */
|
||||
const SHARE_SECTIONS: { key: SharePerm; label: string; always?: boolean; addon?: string }[] = [
|
||||
{ key: 'share_map', label: 'share.permMap', always: true },
|
||||
{ key: 'share_bookings', label: 'share.permBookings' },
|
||||
{ key: 'share_packing', label: 'share.permPacking' },
|
||||
{ key: 'share_budget', label: 'share.permBudget' },
|
||||
{ key: 'share_collab', label: 'share.permCollab' },
|
||||
{ key: 'share_packing', label: 'share.permPacking', addon: 'packing' },
|
||||
{ key: 'share_budget', label: 'share.permBudget', addon: 'budget' },
|
||||
{ key: 'share_collab', label: 'share.permCollab', addon: 'collab' },
|
||||
]
|
||||
|
||||
/** How the plan it shows is narrowed (#1712). */
|
||||
@@ -45,6 +46,10 @@ export function useShareLink(tripId: number) {
|
||||
const { copied, copy } = useCopied()
|
||||
const toast = useToast()
|
||||
const { t } = useTranslation()
|
||||
// A section of an addon the trip has off is not offered: the link would not show it
|
||||
// anyway. Its stored choice stays and counts again once the addon is back on.
|
||||
const tripAddons = useTripAddons(tripId)
|
||||
const sections = SHARE_SECTIONS.filter(section => !section.addon || tripAddons.isEnabled(section.addon))
|
||||
|
||||
useEffect(() => {
|
||||
shareApi.getLink(tripId).then(d => {
|
||||
@@ -85,7 +90,7 @@ export function useShareLink(tripId: number) {
|
||||
} catch { toast.error(t('common.error')) }
|
||||
}
|
||||
|
||||
return { loading, url, perms, copied, create, setPerm, remove, copy: () => copy(url) }
|
||||
return { loading, url, perms, sections, copied, create, setPerm, remove, copy: () => copy(url) }
|
||||
}
|
||||
|
||||
/** The rotating link an existing user opens to join the trip (#1143). */
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { Ferrata, RoadtripPreferences, TourActivity, TourDraft, TourListItem, TourObstacleCheck, TourPackingLink, TourProvenance, TourVisit, TourWaypoint } from '@trek/shared';
|
||||
import type { Ferrata, RoadtripPreferences, TripAddon, TourActivity, TourDraft, TourListItem, TourObstacleCheck, TourPackingLink, TourProvenance, TourVisit, TourWaypoint } from '@trek/shared';
|
||||
import Dexie, { type Table } from 'dexie';
|
||||
import type { Trip, Day, Place, PackingItem, TodoItem, BudgetItem, Reservation, TripFile, Accommodation, TripMember, Tag, Category } from '../types';
|
||||
|
||||
@@ -80,6 +80,15 @@ interface CachedTripTags {
|
||||
tags: Tag[];
|
||||
}
|
||||
|
||||
/**
|
||||
* The trip addons of one trip as the server last listed them, each on or off for
|
||||
* that trip: one row per trip, so a trip opened offline shows the tabs it had.
|
||||
*/
|
||||
interface CachedTripAddons {
|
||||
tripId: number;
|
||||
addons: TripAddon[];
|
||||
}
|
||||
|
||||
/**
|
||||
* A road route as the router answered it, kept on the device so a trip opens
|
||||
* with its roads drawn instead of asking the router for every leg again (#2794).
|
||||
@@ -304,6 +313,7 @@ export class TrekOfflineDb extends Dexie {
|
||||
tourDrafts!: Table<CachedTourDraft, number>;
|
||||
routeCache!: Table<CachedRoute, string>;
|
||||
tripTags!: Table<CachedTripTags, number>;
|
||||
tripAddons!: Table<CachedTripAddons, number>;
|
||||
|
||||
constructor(name: string = ANON_DB_NAME) {
|
||||
super(name);
|
||||
@@ -400,6 +410,10 @@ export class TrekOfflineDb extends Dexie {
|
||||
// v15: the tags a trip owns, one list per trip, so they are offered offline
|
||||
// and go with the trip.
|
||||
this.version(15).stores({ tripTags: 'tripId' });
|
||||
|
||||
// v16: the trip addons of each trip, on or off for that trip, one list per
|
||||
// trip, so the tabs a trip switched off stay hidden offline too.
|
||||
this.version(16).stores({ tripAddons: 'tripId' });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -702,11 +716,13 @@ export async function clearTripData(tripId: number): Promise<void> {
|
||||
offlineDb.tourStationVisits,
|
||||
offlineDb.tourDrafts,
|
||||
offlineDb.tripTags,
|
||||
offlineDb.tripAddons,
|
||||
],
|
||||
async () => {
|
||||
await offlineDb.roadtripPreferences.delete(tripId);
|
||||
await offlineDb.tourDrafts.delete(tripId);
|
||||
await offlineDb.tripTags.delete(tripId);
|
||||
await offlineDb.tripAddons.delete(tripId);
|
||||
await offlineDb.budgetSettlements.delete(tripId);
|
||||
await offlineDb.days.where('trip_id').equals(tripId).delete();
|
||||
await offlineDb.places.where('trip_id').equals(tripId).delete();
|
||||
|
||||
@@ -3,7 +3,7 @@ import { isServiceStopType } from '../components/Roadtrip/roadtripModel'
|
||||
import { useState, useCallback, useRef, useEffect, useMemo } from 'react'
|
||||
import { useTripStore } from '../store/tripStore'
|
||||
import { useSettingsStore } from '../store/settingsStore'
|
||||
import { useAddonStore } from '../store/addonStore'
|
||||
import { useTripAddonEnabled } from '../store/tripAddonsStore'
|
||||
import { calculateRouteWithRetries, type RouteProfileKey } from '../components/Map/routeRetry'
|
||||
import { buildDayRouteRuns, hotelBookendOf, TRANSPORT_TYPES, type DayRouteInputs } from '../components/Map/dayRoutePlan'
|
||||
import { dayViaLookup, foldViaLegs, threadVias, viaKeyOf, viasOnDayLeg } from '../utils/dayRouteVias'
|
||||
@@ -36,7 +36,8 @@ export function useRouteCalculation(tripStore: Pick<TripStoreState, 'assignments
|
||||
// Charging stops / rest areas a plugin route places on the drawn line.
|
||||
const [routeVias, setRouteVias] = useState<RouteVia[]>([])
|
||||
const mirrorServiceStops = useRoadtripSettings(s => s.roadtrip_service_stops_in_days !== false)
|
||||
const toursEnabled = useAddonStore(s => s.isEnabled('tours'))
|
||||
const activeTripId = useTripStore(s => s.trip?.id)
|
||||
const toursEnabled = useTripAddonEnabled(activeTripId, 'tours')
|
||||
const places = useTripStore(s => s.places)
|
||||
const routeAbortRef = useRef<AbortController | null>(null)
|
||||
const reservationsForSignature = useTripStore((s) => s.reservations)
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import { useEffect } from 'react';
|
||||
|
||||
import { useAuthStore } from '../store/authStore';
|
||||
import { watchTripAddons } from '../store/tripAddonsStore';
|
||||
|
||||
/**
|
||||
* Keeps the trip addons of every trip the app looks at live while someone is
|
||||
* signed in: the trip owner switching an addon reaches every member at once.
|
||||
* Mounted once, by App.
|
||||
*/
|
||||
export function useTripAddonsSync(): void {
|
||||
const userId = useAuthStore((s) => s.user?.id);
|
||||
useEffect(() => (userId ? watchTripAddons() : undefined), [userId]);
|
||||
}
|
||||
@@ -1,8 +1,11 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { act, fireEvent, render, screen, waitFor } from '../../../tests/helpers/render';
|
||||
import { ToastContainer } from '../../components/shared/Toast';
|
||||
import { saveSharedLink, useSharedImportStore } from '../../native/sharedFiles';
|
||||
import { tripAddonsRepo } from '../../repo/tripAddonsRepo';
|
||||
import { tripRepo } from '../../repo/tripRepo';
|
||||
import { useAddonStore } from '../../store/addonStore';
|
||||
import { useTripAddonsStore } from '../../store/tripAddonsStore';
|
||||
import NativeImportSheet from './NativeImportSheet';
|
||||
|
||||
const navigate = vi.hoisted(() => vi.fn());
|
||||
@@ -21,6 +24,9 @@ beforeEach(() => {
|
||||
navigate.mockReset();
|
||||
useSharedImportStore.setState({ file: null, tripId: null, link: null });
|
||||
useAddonStore.setState({ addons: [{ id: 'collab', enabled: true }] as never, loaded: true });
|
||||
useTripAddonsStore.setState({ trips: {} });
|
||||
// Every trip follows the instance switch unless a test says otherwise; answered at once, so no read outlives its test.
|
||||
vi.spyOn(tripAddonsRepo, 'list').mockResolvedValue([]);
|
||||
vi.mocked(saveSharedLink).mockReset().mockResolvedValue();
|
||||
vi.spyOn(tripRepo, 'list').mockResolvedValue({
|
||||
trips: [
|
||||
@@ -33,6 +39,15 @@ beforeEach(() => {
|
||||
|
||||
const page = () => new File(['<html></html>'], 'hotel.html', { type: 'text/html' });
|
||||
const bareLink = () => new File(['https://hotel.example/stay'], 'link.url', { type: 'text/uri-list' });
|
||||
/** Trip 2's own Collab choice; trip 1 follows the instance. */
|
||||
const collabOnlyFor2 = (enabled: boolean) =>
|
||||
vi
|
||||
.spyOn(tripAddonsRepo, 'list')
|
||||
.mockImplementation(async (tripId: number) =>
|
||||
tripId === 2
|
||||
? [{ id: 'collab', name: 'Collab', icon: null, enabled, instanceEnabled: !enabled, overridden: true }]
|
||||
: []
|
||||
);
|
||||
const link = (presetTripId: number | null = null) => ({
|
||||
url: 'https://hotel.example/stay',
|
||||
title: 'Hotel Kanra',
|
||||
@@ -116,6 +131,33 @@ describe('NativeImportSheet', () => {
|
||||
expect(useSharedImportStore.getState().file).not.toBeNull();
|
||||
});
|
||||
|
||||
it('keeps a link in a trip that switched Collab on while the instance has it off, offering only that trip', async () => {
|
||||
useAddonStore.setState({ addons: [], loaded: true });
|
||||
collabOnlyFor2(true);
|
||||
render(<NativeImportSheet />);
|
||||
act(() => useSharedImportStore.getState().setFile(page(), link()));
|
||||
|
||||
fireEvent.click(await screen.findByRole('button', { name: /Save to the trip's links/ }));
|
||||
expect(await screen.findByRole('button', { name: /Japan/ })).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: /Past trip/ })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('leaves out a trip that switched Collab off, and shows why when the server refuses the link', async () => {
|
||||
collabOnlyFor2(false);
|
||||
vi.mocked(saveSharedLink).mockRejectedValue({ response: { data: { error: 'Collab addon is not enabled' } } });
|
||||
render(
|
||||
<>
|
||||
<ToastContainer />
|
||||
<NativeImportSheet />
|
||||
</>
|
||||
);
|
||||
act(() => useSharedImportStore.getState().setFile(bareLink(), link(2)));
|
||||
|
||||
expect(await screen.findByText('Collab addon is not enabled')).toBeInTheDocument();
|
||||
expect(await screen.findByRole('button', { name: /Past trip/ })).toBeInTheDocument();
|
||||
await waitFor(() => expect(screen.queryByRole('button', { name: /Japan/ })).not.toBeInTheDocument());
|
||||
});
|
||||
|
||||
it('stays closed with nothing shared', () => {
|
||||
render(<NativeImportSheet />);
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
|
||||
|
||||
@@ -6,16 +6,21 @@
|
||||
* A web page or a link is asked about first: kept among the trip's links
|
||||
* (Collaboration, Links), or read as a booking. A bare link, whose page the phone
|
||||
* could not read, can only be kept; with Collaboration off, a page can only be read.
|
||||
* Collaboration counts per trip: a link goes only to a trip that has it on.
|
||||
*/
|
||||
import { ChevronRight, FileText, Link2, ScanText } from 'lucide-react';
|
||||
import React, { useEffect, useEffectEvent, useRef, useState } from 'react';
|
||||
import { useLocation, useNavigate } from 'react-router';
|
||||
import { useShallow } from 'zustand/react/shallow';
|
||||
import { useToast } from '../../components/shared/Toast';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { saveSharedLink, useSharedImportStore, type SharedLink } from '../../native/sharedFiles';
|
||||
import { tripRepo } from '../../repo/tripRepo';
|
||||
import { useAddonStore } from '../../store/addonStore';
|
||||
import { tripAddonsEntry, useTripAddonsStore } from '../../store/tripAddonsStore';
|
||||
import { getApiErrorMessage } from '../../utils/apiError';
|
||||
import { offlineOr } from '../../utils/needsConnection';
|
||||
import { tripAddonEnabled } from '../../utils/tripAddons';
|
||||
import { TileHeader } from '../screens/trip/sheets/MTripSheetUi';
|
||||
import MSheet from './MSheet';
|
||||
|
||||
@@ -83,6 +88,27 @@ function useTripRows(open: boolean): TripRow[] {
|
||||
return trips;
|
||||
}
|
||||
|
||||
/**
|
||||
* The trips a shared link may go to: those with Collaboration on, each by its
|
||||
* own list (the owner's choice, else the instance switch). The lists are read
|
||||
* once the sheet opens for a link, so a trip that switched Collaboration on is
|
||||
* offered while the instance has it off, and one that switched it off is not.
|
||||
*/
|
||||
function useCollabTrips(trips: TripRow[], active: boolean): TripRow[] {
|
||||
const instanceOn = useAddonStore((s) => s.isEnabled('collab'));
|
||||
const load = useTripAddonsStore((s) => s.load);
|
||||
useEffect(() => {
|
||||
if (!active) return;
|
||||
trips.forEach((trip) => void load(trip.id));
|
||||
}, [active, trips, load]);
|
||||
const on = useTripAddonsStore(
|
||||
useShallow((state) =>
|
||||
trips.map((trip) => tripAddonEnabled(tripAddonsEntry(state, trip.id)?.addons, 'collab', instanceOn))
|
||||
)
|
||||
);
|
||||
return trips.filter((_trip, i) => on[i]);
|
||||
}
|
||||
|
||||
export default function NativeImportSheet(): React.ReactElement | null {
|
||||
const { t } = useTranslation();
|
||||
const toast = useToast();
|
||||
@@ -93,7 +119,12 @@ export default function NativeImportSheet(): React.ReactElement | null {
|
||||
const link = useSharedImportStore((s) => s.link);
|
||||
const chooseTrip = useSharedImportStore((s) => s.chooseTrip);
|
||||
const setFile = useSharedImportStore((s) => s.setFile);
|
||||
const collabOn = useAddonStore((s) => s.isEnabled('collab'));
|
||||
const instanceCollab = useAddonStore((s) => s.isEnabled('collab'));
|
||||
const open = !!file && tripId == null;
|
||||
const trips = useTripRows(open);
|
||||
const collabTrips = useCollabTrips(trips, open && !!link);
|
||||
// Before the trips are known the instance switch decides, as it always did.
|
||||
const collabOn = trips.length === 0 ? instanceCollab : collabTrips.length > 0;
|
||||
// Both belong to the item they were made for, so a newly shared one starts afresh.
|
||||
const [pick, setPick] = useState<{ file: File; choice: LinkChoice } | null>(null);
|
||||
const [failedFile, setFailedFile] = useState<File | null>(null);
|
||||
@@ -107,8 +138,6 @@ export default function NativeImportSheet(): React.ReactElement | null {
|
||||
picked,
|
||||
presetFailed: failedFile != null && failedFile === file,
|
||||
});
|
||||
const open = !!file && tripId == null;
|
||||
const trips = useTripRows(open);
|
||||
|
||||
// Once a trip is picked (here, or in the share sheet before the app opened), go to
|
||||
// it; its planner opens the booking import with the file (MTripShell).
|
||||
@@ -126,8 +155,9 @@ export default function NativeImportSheet(): React.ReactElement | null {
|
||||
setFile(null);
|
||||
void navigate(`/trips/${id}?tab=collab`);
|
||||
},
|
||||
() => {
|
||||
toast.error(offlineOr(t, t('common.error')));
|
||||
(err: unknown) => {
|
||||
// The server says why, such as a trip that has Collaboration off.
|
||||
toast.error(offlineOr(t, getApiErrorMessage(err, t('common.error'))));
|
||||
savingRef.current = null;
|
||||
setFailedFile(file);
|
||||
}
|
||||
@@ -164,7 +194,7 @@ export default function NativeImportSheet(): React.ReactElement | null {
|
||||
{t('native.share.linkUnsupported')}
|
||||
</p>
|
||||
)}
|
||||
{showTrips && <TripPicker trips={trips} onPick={pickTrip} />}
|
||||
{showTrips && <TripPicker trips={choice === 'link' ? collabTrips : trips} onPick={pickTrip} />}
|
||||
</div>
|
||||
</MSheet>
|
||||
);
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import MAdminSchoolHolidayCatalog from './MAdminSchoolHolidayCatalog'
|
||||
import MAdminPaddleRegionsPanel from './MAdminPaddleRegionsPanel'
|
||||
import { useState } from 'react'
|
||||
import {
|
||||
ArrowUp,
|
||||
@@ -246,10 +245,17 @@ export default function MAdmin() {
|
||||
onToggleBagTracking={toggleBagTracking}
|
||||
collabFeatures={collabFeatures}
|
||||
onToggleCollabFeature={toggleCollabFeature}
|
||||
// Live flight status and the booking mail import are rows of the addon groups,
|
||||
// and the paddle water data a row under Tours (desktop parity).
|
||||
flightLive={{
|
||||
on: admin.flightLive,
|
||||
locked: admin.flightLiveLocked,
|
||||
managed: !!managed,
|
||||
onToggle: () =>
|
||||
void admin.handleToggleAuthSetting('flight_live_enabled', !admin.flightLive, admin.setFlightLive),
|
||||
}}
|
||||
mailImport={!managed}
|
||||
/>
|
||||
{/* How the integrations reach the world (live flights, booking mails), beside the addons they serve. */}
|
||||
<MAdminSettingsSection admin={admin} t={t} part="features" />
|
||||
<MAdminPaddleRegionsPanel />
|
||||
</div>
|
||||
)}
|
||||
{activeTab === 'plugins' && <MAdminPluginsPanel />}
|
||||
|
||||
@@ -3,7 +3,7 @@ import { useTranslation } from '../../../i18n'
|
||||
import { useIsDark } from '../../../hooks/useIsDark'
|
||||
import {
|
||||
Puzzle, ListChecks, Wallet, FileText, CalendarDays, Globe, Briefcase, Image, Terminal, Link2, Compass, BookOpen,
|
||||
Sparkles, Luggage, Plane, Bookmark, Users, Mountain, CarFront, Settings2, ChevronRight,
|
||||
Sparkles, Luggage, Plane, Bookmark, Users, Mountain, CarFront, Radar,
|
||||
} from 'lucide-react'
|
||||
import DawarichIcon from '../../../components/shared/DawarichIcon'
|
||||
import AirTrailIcon from '../../../components/shared/AirTrailIcon'
|
||||
@@ -21,7 +21,10 @@ import AiSettingsDialog from '../../../components/Admin/addons/AiAdminConfig'
|
||||
import { AI_ADDON_ICONS, type AiAddonId } from '../../../components/Admin/addons/aiAddons'
|
||||
import { useAiAddonTile } from '../../../components/Admin/addons/useAiAddonTile'
|
||||
import { ImmichIcon, SynologyIcon } from '../../../components/Admin/addons/PhotoProviderIcons'
|
||||
import { MAdminCard } from './MAdminUi'
|
||||
import { MAdminCard, MAdminOptionRow, MAdminSetupRow } from './MAdminUi'
|
||||
import MAdminPaddleRegionsPanel from './MAdminPaddleRegionsPanel'
|
||||
import MMailIngestAdminCard from './MMailIngestAdminCard'
|
||||
import type { FlightLiveOption } from '../../../components/Admin/AddonManager'
|
||||
import MHintLabel from '../../components/MHintLabel'
|
||||
import WandererMark from '../../../components/Tours/wanderer/WandererMark'
|
||||
import MSkeleton from '../../components/MSkeleton'
|
||||
@@ -59,7 +62,16 @@ function AddonIcon({ name, size = 18, enabled = true }: AddonIconProps) {
|
||||
return <Icon size={size} />
|
||||
}
|
||||
|
||||
export default function MAdminAddonManager({ bagTrackingEnabled, onToggleBagTracking, collabFeatures, onToggleCollabFeature }: { bagTrackingEnabled?: boolean; onToggleBagTracking?: () => void; collabFeatures?: CollabFeatures; onToggleCollabFeature?: (key: string) => void }) {
|
||||
export default function MAdminAddonManager({ bagTrackingEnabled, onToggleBagTracking, collabFeatures, onToggleCollabFeature, flightLive, mailImport = false }: {
|
||||
bagTrackingEnabled?: boolean
|
||||
onToggleBagTracking?: () => void
|
||||
collabFeatures?: CollabFeatures
|
||||
onToggleCollabFeature?: (key: string) => void
|
||||
/** Live flight status, a row of the trip group (desktop parity). */
|
||||
flightLive?: FlightLiveOption
|
||||
/** Booking mail import, a row of the integration group with its setup sheet; off on a managed install. */
|
||||
mailImport?: boolean
|
||||
}) {
|
||||
const { t } = useTranslation()
|
||||
const dark = useIsDark()
|
||||
const {
|
||||
@@ -98,7 +110,7 @@ export default function MAdminAddonManager({ bagTrackingEnabled, onToggleBagTrac
|
||||
) : (
|
||||
<>
|
||||
{/* Trip Addons */}
|
||||
{tripAddons.length > 0 && (
|
||||
{(tripAddons.length > 0 || flightLive) && (
|
||||
<MAdminCard>
|
||||
<MGroupHead icon={Briefcase} label={t('admin.addons.type.trip')} hint={t('admin.addons.tripHint')} />
|
||||
{tripAddons.map((addon, i) => (
|
||||
@@ -135,6 +147,7 @@ export default function MAdminAddonManager({ bagTrackingEnabled, onToggleBagTrac
|
||||
onToggle={() => void toggle()}
|
||||
/>
|
||||
))}
|
||||
<MAdminPaddleRegionsPanel />
|
||||
</>
|
||||
)}
|
||||
{addon.id === 'collab' && addon.enabled && collabFeatures && onToggleCollabFeature && (
|
||||
@@ -153,6 +166,7 @@ export default function MAdminAddonManager({ bagTrackingEnabled, onToggleBagTrac
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
{flightLive && <MFlightLiveRow option={flightLive} first={tripAddons.length === 0} />}
|
||||
</MAdminCard>
|
||||
)}
|
||||
|
||||
@@ -171,13 +185,14 @@ export default function MAdminAddonManager({ bagTrackingEnabled, onToggleBagTrac
|
||||
)}
|
||||
|
||||
{/* Integration Addons, headed by the AI ones as one group, as on the desktop */}
|
||||
{(integrationAddons.length > 0 || aiAddons.length > 0) && (
|
||||
{(integrationAddons.length > 0 || aiAddons.length > 0 || mailImport) && (
|
||||
<MAdminCard>
|
||||
<MGroupHead icon={Link2} label={t('admin.addons.type.integration')} hint={t('admin.addons.integrationHint')} />
|
||||
{aiAddons.length > 0 && <MAiAddons addons={aiAddons} onToggle={handleToggle} />}
|
||||
{integrationAddons.map((addon, i) => (
|
||||
<MAddonRow key={addon.id} addon={addon} onToggle={handleToggle} t={t} first={i === 0 && aiAddons.length === 0} />
|
||||
))}
|
||||
{mailImport && <MMailIngestAdminCard first={integrationAddons.length === 0 && aiAddons.length === 0} />}
|
||||
</MAdminCard>
|
||||
)}
|
||||
</>
|
||||
@@ -216,16 +231,28 @@ interface MAddonRowProps {
|
||||
function MAddonRow({ addon, onToggle, t, first }: MAddonRowProps) {
|
||||
const label = getAddonLabel(t, addon)
|
||||
return (
|
||||
<div className={`flex items-center gap-3 py-[11px] ${first ? '' : 'border-t border-[color:var(--m-rowbr)]'}`}>
|
||||
{/* overflow-hidden so a brand mark that fills the slot keeps its rounded corners. */}
|
||||
<span className="flex h-[38px] w-[38px] flex-none items-center justify-center overflow-hidden rounded-[11px] bg-[color:var(--m-ic)] text-m-ink">
|
||||
<AddonIcon name={addon.icon} size={18} enabled={addon.enabled} />
|
||||
</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<MHintLabel label={label.name} hint={label.description} />
|
||||
</div>
|
||||
<MToggle checked={addon.enabled} ariaLabel={label.name} onChange={() => onToggle(addon)} />
|
||||
</div>
|
||||
<MAdminOptionRow
|
||||
icon={<AddonIcon name={addon.icon} size={18} enabled={addon.enabled} />}
|
||||
title={label.name}
|
||||
hint={label.description}
|
||||
first={first}
|
||||
trailing={<MToggle checked={addon.enabled} ariaLabel={label.name} onChange={() => onToggle(addon)} />}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
/** Live flight status as a trip row, locked with a word when the server environment holds it. */
|
||||
function MFlightLiveRow({ option, first }: { option: FlightLiveOption; first: boolean }) {
|
||||
const { t } = useTranslation()
|
||||
const hint = option.managed ? t('flightLive.adminHintManaged') : t('flightLive.adminHint')
|
||||
return (
|
||||
<MAdminOptionRow
|
||||
icon={<Radar size={18} />}
|
||||
title={t('flightLive.adminTitle')}
|
||||
hint={option.locked ? `${hint} ${t('flightLive.envLocked')}` : hint}
|
||||
first={first}
|
||||
trailing={<MToggle checked={option.on} ariaLabel={t('flightLive.adminToggle')} disabled={option.locked} onChange={option.onToggle} />}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -301,17 +328,7 @@ function MAiAddons({ addons, onToggle }: { addons: Addon[]; onToggle: (addon: Ad
|
||||
/>
|
||||
)
|
||||
})}
|
||||
{tile.canSetUp && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={tile.openDialog}
|
||||
className="flex w-full items-center gap-3 border-t border-[color:var(--m-rowbr)] py-[11px] ps-[50px] text-start"
|
||||
>
|
||||
<Settings2 size={14} className="flex-none text-m-faint" />
|
||||
<span className="min-w-0 flex-1 truncate text-[0.75rem] font-bold text-m-ink">{t('admin.addons.ai.setup')}</span>
|
||||
<ChevronRight size={15} className="flex-none text-m-faint rtl:rotate-180" />
|
||||
</button>
|
||||
)}
|
||||
{tile.canSetUp && <MAdminSetupRow label={t('admin.addons.ai.setup')} onOpen={tile.openDialog} />}
|
||||
{tile.dialogOpen && <AiSettingsDialog addons={addons} onClose={tile.closeDialog} />}
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
Waves,
|
||||
WifiOff,
|
||||
} from 'lucide-react';
|
||||
import { useState } from 'react';
|
||||
import {
|
||||
AUTO_LOAD_MODES,
|
||||
autoLoadSizes,
|
||||
@@ -28,8 +29,9 @@ import { useTranslation } from '../../../i18n';
|
||||
import { formatDisplayDate } from '../../../utils/dateFormat';
|
||||
import MBadge from '../../components/MBadge';
|
||||
import MChip from '../../components/MChip';
|
||||
import MSheet from '../../components/MSheet';
|
||||
import MConfirmSheet from '../settings/MConfirmSheet';
|
||||
import { MAdminButton, MAdminCard, MAdminClampedText } from './MAdminUi';
|
||||
import { MAdminButton, MAdminClampedText, MAdminSetupRow, MAdminSheetFrame } from './MAdminUi';
|
||||
|
||||
type Admin = ReturnType<typeof usePaddleRegionsAdmin>;
|
||||
|
||||
@@ -393,32 +395,49 @@ function Regions({ admin }: { admin: Admin }) {
|
||||
|
||||
/**
|
||||
* PAD-05A/PAD-11C on the phone: the regions TREK reads paddle data for, how it
|
||||
* loads a paddler's region by itself and the regions that wait for an admin.
|
||||
* usePaddleRegionsAdmin is the desktop card's state; this is only the markup.
|
||||
* loads a paddler's region by itself and the regions that wait for an admin, as
|
||||
* a row under the Tours addon that opens them in a sheet. The row counts the
|
||||
* open requests, else the regions. usePaddleRegionsAdmin is the desktop
|
||||
* dialog's state; this is only the markup.
|
||||
*/
|
||||
export default function MAdminPaddleRegionsPanel() {
|
||||
const { t } = useTranslation();
|
||||
const admin = usePaddleRegionsAdmin();
|
||||
const [open, setOpen] = useState(false);
|
||||
if (!admin.toursOn) return null;
|
||||
const title = t('admin.paddleRegions.title');
|
||||
// A declined request no longer waits for anyone; only the open ones ask for a look.
|
||||
const waiting = admin.requests.filter((r) => !r.declined).length;
|
||||
const badge =
|
||||
waiting > 0 ? (
|
||||
<MBadge caps={false} tone="strong">
|
||||
{waiting}
|
||||
</MBadge>
|
||||
) : admin.regions.length > 0 ? (
|
||||
<MBadge caps={false}>{admin.regions.length}</MBadge>
|
||||
) : undefined;
|
||||
return (
|
||||
<MAdminCard>
|
||||
<div className="flex items-start gap-3">
|
||||
<span className="flex h-[38px] w-[38px] flex-none items-center justify-center rounded-[11px] bg-[color:var(--m-ic)] text-m-ink">
|
||||
<Waves size={18} />
|
||||
</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="min-w-0 truncate text-[length:calc(14px*var(--fs-scale-body,1))] font-extrabold text-m-ink">
|
||||
{t('admin.paddleRegions.title')}
|
||||
</span>
|
||||
{admin.regions.length > 0 && <MBadge caps={false}>{admin.regions.length}</MBadge>}
|
||||
</div>
|
||||
<MAdminClampedText className="mt-[2px] text-[length:calc(10px*var(--fs-scale-caption,1))]">
|
||||
{t('admin.paddleRegions.hint')}
|
||||
</MAdminClampedText>
|
||||
</div>
|
||||
</div>
|
||||
<>
|
||||
<MAdminSetupRow label={title} onOpen={() => setOpen(true)} badge={badge} />
|
||||
{open && (
|
||||
<MSheet open onClose={() => setOpen(false)} variant="bottom" material="glass" ariaLabel={title}>
|
||||
<MAdminSheetFrame icon={<Waves size={19} strokeWidth={1.8} />} title={title} onClose={() => setOpen(false)}>
|
||||
<p className="m-0 font-geist text-[length:calc(10px*var(--fs-scale-caption,1))] leading-relaxed text-m-muted">
|
||||
{t('admin.paddleRegions.hint')}
|
||||
</p>
|
||||
<PanelBody admin={admin} />
|
||||
</MAdminSheetFrame>
|
||||
</MSheet>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** What the sheet holds: the state of the list, the settings, the requests, the search and the regions. */
|
||||
function PanelBody({ admin }: { admin: Admin }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<>
|
||||
{admin.offline && (
|
||||
<p
|
||||
role="status"
|
||||
@@ -462,6 +481,6 @@ export default function MAdminPaddleRegionsPanel() {
|
||||
danger
|
||||
onConfirm={admin.confirmRemove}
|
||||
/>
|
||||
</MAdminCard>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -6,7 +6,6 @@ import type { useAdmin } from '../../../pages/admin/useAdmin'
|
||||
import MToggle from '../../components/MToggle'
|
||||
import { MBlockDisclosure, MProviderBlock, MTrekApiBlock } from './MApiProviderBlocks'
|
||||
import MAdminOidcCard from './MAdminOidcCard'
|
||||
import MMailIngestAdminCard from './MMailIngestAdminCard'
|
||||
import MAdminGoogleDailyLimit from './MAdminGoogleDailyLimit'
|
||||
import MAdminPlaceContrib from './MAdminPlaceContrib'
|
||||
import MAdminServiceQuota from './MAdminServiceQuota'
|
||||
@@ -27,41 +26,22 @@ interface MAdminSettingsSectionProps {
|
||||
t: TranslationFn
|
||||
/**
|
||||
* Which section this renders, cut the way the desktop tabs are: who may sign
|
||||
* in and what it takes (security), what the install talks to outside
|
||||
* (services), and the setup of the features the addons switch on (features).
|
||||
* in and what it takes (security) or what the install talks to outside
|
||||
* (services). Live flight status and the booking mail import are rows of the
|
||||
* addon groups (MAdminAddonManager).
|
||||
*/
|
||||
part: 'security' | 'services' | 'features'
|
||||
part: 'security' | 'services'
|
||||
}
|
||||
|
||||
type PartProps = Omit<MAdminSettingsSectionProps, 'part'>
|
||||
|
||||
// The admin's security, services and feature setup sections as phone cards,
|
||||
// The admin's security and services sections as phone cards,
|
||||
// one function each. All state and mutations come from useAdmin.
|
||||
export default function MAdminSettingsSection({ admin, t, part }: MAdminSettingsSectionProps) {
|
||||
if (part === 'features') return <FeaturesPart admin={admin} t={t} />
|
||||
if (part === 'security') return <SecurityPart admin={admin} t={t} />
|
||||
return <ServicesPart admin={admin} t={t} />
|
||||
}
|
||||
|
||||
/** Live flights and booking mails: how the integrations of the addons tab reach the world. */
|
||||
function FeaturesPart({ admin, t }: PartProps) {
|
||||
const { managed, flightLive, setFlightLive, flightLiveLocked, handleToggleAuthSetting } = admin
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{/* Live flight status: open ADS-B data, no key, on by default (desktop parity). */}
|
||||
<FlightLiveCard
|
||||
t={t}
|
||||
managed={!!managed}
|
||||
on={flightLive}
|
||||
locked={flightLiveLocked}
|
||||
onChange={(v) => void handleToggleAuthSetting('flight_live_enabled', v, setFlightLive)}
|
||||
/>
|
||||
{/* Booking mail import: self-hosted only, the operator runs the TREK Cloud relay (desktop parity). */}
|
||||
{!managed && <MMailIngestAdminCard />}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** Who may sign in and what it takes, with the one destructive action last. */
|
||||
function SecurityPart({ admin, t }: PartProps) {
|
||||
const {
|
||||
@@ -482,23 +462,3 @@ function ServicesPart({ admin, t }: PartProps) {
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** The live flight status switch, locked with a word when the server environment holds it. */
|
||||
function FlightLiveCard({ t, managed, on, locked, onChange }: {
|
||||
t: TranslationFn
|
||||
managed: boolean
|
||||
on: boolean
|
||||
locked: boolean
|
||||
onChange: (on: boolean) => void
|
||||
}) {
|
||||
return (
|
||||
<MAdminCard>
|
||||
<MAdminCardHead title={t('flightLive.adminTitle')} hint={managed ? t('flightLive.adminHintManaged') : t('flightLive.adminHint')} />
|
||||
<MAdminRow
|
||||
title={t('flightLive.adminToggle')}
|
||||
hint={locked ? t('flightLive.envLocked') : undefined}
|
||||
trailing={<MToggle checked={on} ariaLabel={t('flightLive.adminToggle')} disabled={locked} onChange={onChange} />}
|
||||
/>
|
||||
</MAdminCard>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { InputHTMLAttributes, ReactNode, useState } from 'react'
|
||||
import { ChevronDown, Eye, EyeOff, Loader2, X } from 'lucide-react'
|
||||
import { ChevronDown, ChevronRight, Eye, EyeOff, Loader2, Settings2, X } from 'lucide-react'
|
||||
import { useTranslation } from '../../../i18n'
|
||||
import MIconBtn from '../../components/MIconBtn'
|
||||
import MHintLabel from '../../components/MHintLabel'
|
||||
@@ -61,6 +61,58 @@ export function MAdminRow({
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* A row of the addons screen: the icon tile, the name with its description
|
||||
* behind the info mark, and the switch. Addons and the instance options that
|
||||
* sit with them (live flight status, booking mails) share it.
|
||||
*/
|
||||
export function MAdminOptionRow({
|
||||
icon,
|
||||
title,
|
||||
hint,
|
||||
trailing,
|
||||
first = false,
|
||||
}: {
|
||||
icon: ReactNode
|
||||
title: string
|
||||
hint?: string
|
||||
trailing: ReactNode
|
||||
first?: boolean
|
||||
}) {
|
||||
return (
|
||||
<div className={`flex items-center gap-3 py-[11px] ${first ? '' : 'border-t border-[color:var(--m-rowbr)]'}`}>
|
||||
{/* overflow-hidden so a brand mark that fills the slot keeps its rounded corners. */}
|
||||
<span className="flex h-[38px] w-[38px] flex-none items-center justify-center overflow-hidden rounded-[11px] bg-[color:var(--m-ic)] text-m-ink">
|
||||
{icon}
|
||||
</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<MHintLabel label={title} hint={hint} />
|
||||
</div>
|
||||
{trailing}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The last row under an addon that opens its settings: a gear, what it sets up,
|
||||
* an optional badge for what waits inside, and a chevron (AI, booking mails,
|
||||
* paddle water data).
|
||||
*/
|
||||
export function MAdminSetupRow({ label, onOpen, badge }: { label: string; onOpen: () => void; badge?: ReactNode }) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onOpen}
|
||||
className="flex w-full items-center gap-3 border-t border-[color:var(--m-rowbr)] py-[11px] ps-[50px] text-start"
|
||||
>
|
||||
<Settings2 size={14} className="flex-none text-m-faint" />
|
||||
<span className="min-w-0 flex-1 truncate text-[length:calc(12px*var(--fs-scale-body,1))] font-bold text-m-ink">{label}</span>
|
||||
{badge}
|
||||
<ChevronRight size={15} className="flex-none text-m-faint rtl:rotate-180" />
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* A description that keeps to two lines until it is tapped. On a phone the long
|
||||
* ones (a map provider's terms, how a loader decides) pushed every control off
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Inbox, Upload, Webhook, type LucideIcon } from 'lucide-react';
|
||||
import { Inbox, Mail, Upload, Webhook, type LucideIcon } from 'lucide-react';
|
||||
import { useState } from 'react';
|
||||
import {
|
||||
TRANSPORTS,
|
||||
problemText,
|
||||
@@ -15,15 +16,16 @@ import { useTranslation } from '../../../i18n';
|
||||
import type { TranslationFn } from '../../../types';
|
||||
import { relativeTime } from '../../../utils/relativeTime';
|
||||
import MSegmented from '../../components/MSegmented';
|
||||
import MSheet from '../../components/MSheet';
|
||||
import MToggle from '../../components/MToggle';
|
||||
import {
|
||||
MAdminButton,
|
||||
MAdminCard,
|
||||
MAdminCardHead,
|
||||
MAdminField,
|
||||
MAdminInput,
|
||||
MAdminRow,
|
||||
MAdminOptionRow,
|
||||
MAdminSecretInput,
|
||||
MAdminSetupRow,
|
||||
MAdminSheetFrame,
|
||||
} from './MAdminUi';
|
||||
|
||||
interface PartProps {
|
||||
@@ -250,19 +252,23 @@ function Setup({ admin, form, t, locale }: PartProps & { locale: string }) {
|
||||
}
|
||||
|
||||
/**
|
||||
* The booking mail import in the phone's admin settings, the same card as on
|
||||
* the desktop (useMailIngestAdmin): the switch, how mail arrives, the address
|
||||
* template, the AI allowance, the test and the status. Self-hosted only.
|
||||
* The booking mail import as a row of the phone's integration group, the same
|
||||
* as on the desktop (useMailIngestAdmin): the switch, and while it is on a row
|
||||
* to the sheet that sets it up (how mail arrives, the address template, the AI
|
||||
* allowance, the test and the status). Self-hosted only.
|
||||
*/
|
||||
export default function MMailIngestAdminCard() {
|
||||
export default function MMailIngestAdminCard({ first = false }: { first?: boolean }) {
|
||||
const { t, locale } = useTranslation();
|
||||
const admin = useMailIngestAdmin(true);
|
||||
const [open, setOpen] = useState(false);
|
||||
const setupLabel = t('mailAdmin.setup');
|
||||
return (
|
||||
<MAdminCard>
|
||||
<MAdminCardHead title={t('mailAdmin.title')} hint={t('mailAdmin.hint')} />
|
||||
<MAdminRow
|
||||
title={t('mailAdmin.enabled')}
|
||||
hint={t('mailAdmin.enabledHint')}
|
||||
<>
|
||||
<MAdminOptionRow
|
||||
icon={<Mail size={18} />}
|
||||
title={t('mailAdmin.title')}
|
||||
hint={`${t('mailAdmin.hint')} ${t('mailAdmin.enabledHint')}`}
|
||||
first={first}
|
||||
trailing={
|
||||
<MToggle
|
||||
checked={admin.enabled}
|
||||
@@ -272,7 +278,18 @@ export default function MMailIngestAdminCard() {
|
||||
/>
|
||||
}
|
||||
/>
|
||||
{admin.enabled && admin.form && <Setup admin={admin} form={admin.form} t={t} locale={locale} />}
|
||||
</MAdminCard>
|
||||
{admin.enabled && admin.form && <MAdminSetupRow label={setupLabel} onOpen={() => setOpen(true)} />}
|
||||
{open && admin.enabled && admin.form && (
|
||||
<MSheet open onClose={() => setOpen(false)} variant="bottom" material="glass" ariaLabel={setupLabel}>
|
||||
<MAdminSheetFrame
|
||||
icon={<Mail size={19} strokeWidth={1.8} />}
|
||||
title={setupLabel}
|
||||
onClose={() => setOpen(false)}
|
||||
>
|
||||
<Setup admin={admin} form={admin.form} t={t} locale={locale} />
|
||||
</MAdminSheetFrame>
|
||||
</MSheet>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ import PoiCategoryPill from '../../../../components/Map/PoiCategoryPill'
|
||||
import { usePoiExplore } from '../../../../components/Map/usePoiExplore'
|
||||
import { useMergedMapPois } from '../../../../components/Map/useMergedMapPois'
|
||||
import { firstStopOfPlace, stageOf } from '../../../../components/Roadtrip/roadtripRowModel'
|
||||
import { stageMapData } from '../../../../components/Roadtrip/stageMap'
|
||||
import { stageConnectionIds, stageMapData } from '../../../../components/Roadtrip/stageMap'
|
||||
import { usePlanMapViewport } from '../../../../hooks/usePlanMapViewport'
|
||||
import { useIsDark } from '../../../../hooks/useIsDark'
|
||||
import { useTileUrl } from '../../../../hooks/useTileUrl'
|
||||
@@ -21,6 +21,7 @@ import { RT_ALT_BAR_LIFT } from '../roadtrip/useMRtAlternatives'
|
||||
import type { MMapAreaProps } from '../MTripShell'
|
||||
import type { Poi } from '../../../../components/Map/poiCategories'
|
||||
import type { ViewportPadding } from '../../../../utils/mapViewport'
|
||||
import { runsOnDay } from '../../../../utils/reservationRoutes'
|
||||
|
||||
/** One array, so an explore set switched off does not move every pin on the stage. */
|
||||
const NO_POIS: Poi[] = []
|
||||
@@ -215,6 +216,20 @@ export default function MMapArea({ planner, shell }: MMapAreaProps) {
|
||||
() => onStage ? stageMapData(planner.roadtripRoutes, stage, !!dayColorsOn) : null,
|
||||
[onStage, planner.roadtripRoutes, stage, dayColorsOn],
|
||||
)
|
||||
// The arcs the stage draws: its own rides and what was switched on for its day. The
|
||||
// all-days view keeps every ride of the drive.
|
||||
const stageConnections = useMemo(() => {
|
||||
if (!onStage) return null
|
||||
if (!stage) return planner.roadtripConnections
|
||||
const byId = new Map(planner.reservations.map(r => [r.id, r]))
|
||||
return stageConnectionIds(stage, planner.visibleConnections, id => {
|
||||
const r = byId.get(id)
|
||||
return !r || runsOnDay(r, planner.selectedDayId, planner.days)
|
||||
})
|
||||
}, [
|
||||
onStage, stage, planner.roadtripConnections, planner.reservations,
|
||||
planner.visibleConnections, planner.selectedDayId, planner.days,
|
||||
])
|
||||
|
||||
// Only what the stage carries, so a trip's other 200 pins stay off a screen that
|
||||
// is answering one question. Without a stage (the all-days view) every place a stored
|
||||
@@ -412,10 +427,11 @@ export default function MMapArea({ planner, shell }: MMapAreaProps) {
|
||||
// toggled on or not, the way the desktop map does it in road trip mode. The
|
||||
// ride's leg carries no geometry, so without this the road ended at the
|
||||
// departure terminal and picked up again at the arrival with nothing between.
|
||||
visibleConnectionIds={onStage ? planner.roadtripConnections : planner.visibleConnections}
|
||||
visibleConnectionIds={stageConnections ?? planner.visibleConnections}
|
||||
// The plan map shows one day, so a booking switched on for another day stays off
|
||||
// it until that day is picked, or the whole trip is. The switch itself is still
|
||||
// trip-wide. The stage keeps its seamed rides whatever day they were booked on.
|
||||
// trip-wide. The stage scopes its own set above, since its seamed rides stay on
|
||||
// it whatever day they were booked on.
|
||||
scopeConnectionsToDay={!onStage}
|
||||
// Transport overlay tap → the mobile transport detail sheet (desktop
|
||||
// routes this through mapTransportDetail into the day sidebar instead).
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
import MDancingTrek from '../../../components/MDancingTrek'
|
||||
import MChipStrip from '../../../components/MChipStrip'
|
||||
import { useAddonStore } from '../../../../store/addonStore'
|
||||
import { useTripAddonEnabled } from '../../../../store/tripAddonsStore'
|
||||
import PlaceAvatar from '../../../../components/shared/PlaceAvatar'
|
||||
import MarkdownText from '../../../../components/shared/MarkdownText'
|
||||
import { getCategoryIcon } from '../../../../components/shared/categoryIcons'
|
||||
@@ -45,7 +46,7 @@ export default function MPlacesBrowser({ planner, shell }: MPlacesBrowserProps)
|
||||
const { locale } = useTranslation()
|
||||
const canEditPlaces = planner.can('place_edit', trip)
|
||||
const collectionsEnabled = useAddonStore(s => s.isEnabled('collections'))
|
||||
const toursEnabled = useAddonStore(s => s.isEnabled('tours'))
|
||||
const toursEnabled = useTripAddonEnabled(tripId, 'tours')
|
||||
// Top level of the places browser, mirroring the desktop right add-panel's
|
||||
// Places <-> Tours switch placement.
|
||||
const [toursMode, setToursMode] = useState(false)
|
||||
|
||||
@@ -508,12 +508,15 @@ function TimelineHeader({ tl, dayLabel, openLabel, weatherLabel, onOpenDay, onOp
|
||||
stayLabel: (chip: HotelChip) => string
|
||||
}) {
|
||||
const WeatherIcon = weatherIconFor(tl.weather?.main)
|
||||
const [strip, setStrip] = useState<HTMLSpanElement | null>(null)
|
||||
const stripFade = useEdgeFade(strip)
|
||||
return (
|
||||
<div className="flex items-center gap-1.5 border-b border-[color:var(--m-rowbr)] px-0.5 py-[9px]">
|
||||
{/* The one horizontal scroller inside the day pager. Nested scrolling is
|
||||
the browser's: while the chips overflow they pan first, and the pager
|
||||
takes over at their end or when they fit. */}
|
||||
<span className="flex min-w-0 items-center gap-1.5 overflow-x-auto">
|
||||
takes over at their end or when they fit. The ends fade while more
|
||||
waits behind them. */}
|
||||
<span ref={setStrip} className={`flex min-w-0 items-center gap-1.5 overflow-x-auto ${edgeFadeClass(stripFade)}`}>
|
||||
{/* The same glass controls as the edit header's: a round one when the day
|
||||
is already named above it, a pill with the day's name otherwise. */}
|
||||
<button
|
||||
@@ -532,20 +535,20 @@ function TimelineHeader({ tl, dayLabel, openLabel, weatherLabel, onOpenDay, onOp
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
{/* A stay gives way before anything else in the header does: its name ends
|
||||
in an ellipsis rather than under the edge or the weather (the chip's
|
||||
label says it whole), and the time after it stays. */}
|
||||
{/* A stay's name stands whole: two stays and the weather rarely fit a
|
||||
phone, and a name cut to a letter or two said nothing, so the strip
|
||||
scrolls instead of squeezing the chips. */}
|
||||
{tl.hotelChips.map(chip => (
|
||||
<button
|
||||
key={chip.key}
|
||||
type="button"
|
||||
onClick={() => onOpenStay(chip)}
|
||||
aria-label={stayLabel(chip)}
|
||||
className={`${GLASS_CHIP} min-w-[4.5rem] shrink gap-[5px] px-2.5`}
|
||||
className={`${GLASS_CHIP} gap-[5px] px-2.5`}
|
||||
>
|
||||
<HotelChipIcon variant={chip.variant} />
|
||||
{/* Its own direction, so a Latin name in an Arabic header is cut at its end, not its start. */}
|
||||
<span dir="auto" className="min-w-0 truncate">{chip.name}</span>
|
||||
{/* Its own direction, so a Latin name reads the right way in an Arabic header. */}
|
||||
<span dir="auto">{chip.name}</span>
|
||||
{chip.time && <span className="flex-none tabular-nums text-m-muted">{chip.time.slice(0, 5)}</span>}
|
||||
</button>
|
||||
))}
|
||||
|
||||
@@ -350,8 +350,11 @@ function TransitLegRows({ legs, t }: { legs: TransitLegDisplay[]; t: Translation
|
||||
const hasSeg = i < legs.length - 1
|
||||
return (
|
||||
<div key={i} className="flex gap-[9px]">
|
||||
<span className="w-9 flex-none pt-[9px] text-end font-geist text-[0.65625rem] font-semibold tabular-nums text-m-muted">
|
||||
{isWalk ? '' : leg.from?.time?.slice(0, 5) || ''}
|
||||
{/* A ride's departure stands beside its stops, its arrival at the
|
||||
bottom of its row, so the open card holds the whole journey (#3139). */}
|
||||
<span className="flex w-9 flex-none flex-col justify-between py-[9px] text-end font-geist text-[0.65625rem] font-semibold tabular-nums text-m-muted">
|
||||
<span>{isWalk ? '' : leg.from?.time?.slice(0, 5) || ''}</span>
|
||||
{!isWalk && leg.to?.time && <span className="text-m-faint">{leg.to.time.slice(0, 5)}</span>}
|
||||
</span>
|
||||
<div className="flex w-3 flex-none flex-col items-center">
|
||||
{isWalk ? (
|
||||
@@ -371,16 +374,16 @@ function TransitLegRows({ legs, t }: { legs: TransitLegDisplay[]; t: Translation
|
||||
</div>
|
||||
<div className="min-w-0 flex-1 py-[7px]">
|
||||
{isWalk ? (
|
||||
<div className="truncate font-geist text-[0.6875rem] font-semibold text-m-muted">
|
||||
<div className="break-words font-geist text-[0.6875rem] font-semibold text-m-muted [overflow-wrap:anywhere]">
|
||||
<Footprints size={10} strokeWidth={2.2} className="me-1 inline-block align-[-1px]" />
|
||||
{[mins ? t('transit.min', { count: mins }) : '', t('transit.walkTo', { name: leg.to?.name || '' })]
|
||||
.filter(Boolean).join(' · ')}
|
||||
</div>
|
||||
) : (
|
||||
<div>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<LineBadge leg={leg} className="flex-none" />
|
||||
<span className="truncate text-[0.78125rem] font-bold">
|
||||
<div className="flex items-start gap-1.5">
|
||||
<LineBadge leg={leg} className="mt-px flex-none" />
|
||||
<span dir="auto" className="min-w-0 break-words text-[0.78125rem] font-bold [overflow-wrap:anywhere]">
|
||||
{flowText([leg.from?.name, leg.to?.name].filter((n): n is string => !!n))}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
@@ -6,9 +6,9 @@ import MIconBtn from '../../../components/MIconBtn'
|
||||
import { FormSheetHeader } from './PlSheetChrome'
|
||||
import ImpFileStep from './ImpFileStep'
|
||||
import ImpListStep from './ImpListStep'
|
||||
import { useAddonStore } from '../../../../store/addonStore'
|
||||
import { usePlacesColumnFileImport } from '../../../../components/Planner/usePlacesColumnFileImport'
|
||||
import TourGpxPreviewDialog from '../../../../components/Tours/TourGpxPreviewDialog'
|
||||
import { useTripAddonEnabled } from '../../../../store/tripAddonsStore'
|
||||
import type { TripPlanner } from '../MTripShell'
|
||||
|
||||
export interface MImportSheetProps {
|
||||
@@ -32,7 +32,7 @@ type ImportStep = 'menu' | 'file' | 'list'
|
||||
export default function MImportSheet({ planner, open, onClose }: MImportSheetProps) {
|
||||
const { t, tripId, trip, can } = planner
|
||||
const [step, setStep] = useState<ImportStep>('menu')
|
||||
const toursEnabled = useAddonStore(s => s.isEnabled('tours'))
|
||||
const toursEnabled = useTripAddonEnabled(tripId, 'tours')
|
||||
const fileImport = usePlacesColumnFileImport({
|
||||
tripId,
|
||||
toursEnabled,
|
||||
|
||||
@@ -16,7 +16,7 @@ import { usePlaceForm } from '../../../../components/Planner/usePlaceForm'
|
||||
import { usePlaceTags } from '../../../../components/Planner/usePlaceTags'
|
||||
import { addressWithoutCoordinates } from '../../../../components/Planner/placeCoordinates'
|
||||
import { AMOUNT_FIELD_CLS, Eyebrow, FIELD_CLS, FormSheetBody, FormSheetFooter, FormSheetHeader } from './PlSheetChrome'
|
||||
import { useAddonStore } from '../../../../store/addonStore'
|
||||
import { useTripAddonEnabled } from '../../../../store/tripAddonsStore'
|
||||
import type { BookingExpenseRequest } from '../../../../components/Planner/BookingCostsSection.types'
|
||||
import PlPlaceSearch, { type PlSearchPick } from './PlPlaceSearch'
|
||||
import PlCategoryPicker from './PlCategoryPicker'
|
||||
@@ -90,7 +90,7 @@ export default function MPlaceEditSheet({ planner, onOpenExpense }: MPlaceEditSh
|
||||
const [resolvingPick, setResolvingPick] = useState(false)
|
||||
// The hours the details looked up, offered to the hours editor as on the desktop.
|
||||
const [detailsHours, setDetailsHours] = useState<PlaceOpeningHours | null>(null)
|
||||
const isBudgetEnabled = useAddonStore(s => s.isEnabled('budget'))
|
||||
const isBudgetEnabled = useTripAddonEnabled(planner.tripId, 'budget')
|
||||
// Set right before submit: the place has to exist before an expense can point
|
||||
// at it, exactly like MReservationSheet does it.
|
||||
const expenseIntentRef = useRef(false)
|
||||
|
||||
@@ -122,3 +122,15 @@ describe('MPlaceSheet ask the assistant', () => {
|
||||
expect(chatOf(useAssistantStore.getState(), 5).focus).toEqual({ placeIds: [42] })
|
||||
})
|
||||
})
|
||||
|
||||
describe('MPlaceSheet header (#3140)', () => {
|
||||
it('lets a long place name wrap instead of cutting it to one line', () => {
|
||||
const longName = 'Broad Street Christmas Lights & Market'
|
||||
render(<MPlaceSheet planner={planner({ selectedPlace: buildPlace({ id: 7, name: longName, address: 'Broad Street, RG1 2AF, Reading' }) })} shell={shell} />)
|
||||
|
||||
const title = screen.getByText(longName)
|
||||
expect(title).not.toHaveClass('truncate')
|
||||
expect(title).toHaveClass('break-words')
|
||||
expect(screen.getByText('Broad Street, RG1 2AF, Reading').closest('div')).not.toHaveClass('truncate')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -208,12 +208,14 @@ export default function MPlaceSheet({ planner, shell }: MTripSheetsProps) {
|
||||
</PlacePhotoGallery>
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<span dir="auto" className="min-w-0 truncate text-[1rem] font-bold leading-snug">{place.name}</span>
|
||||
<div className="flex items-start gap-1.5">
|
||||
{/* The sheet is where a place is read in full, so its name wraps
|
||||
onto as many lines as it needs, as on the desktop (#3140). */}
|
||||
<span dir="auto" className="min-w-0 break-words text-[1rem] font-bold leading-snug [overflow-wrap:anywhere]">{place.name}</span>
|
||||
{/* Accepted out of the traveller's own recordings — the same
|
||||
mark the desktop inspector carries. */}
|
||||
{place.source === 'dawarich' && (
|
||||
<span className="flex-none overflow-hidden rounded-[5px]">
|
||||
<span className="mt-[3px] flex-none overflow-hidden rounded-[5px]">
|
||||
<DawarichIcon size={15} />
|
||||
</span>
|
||||
)}
|
||||
|
||||
@@ -3,7 +3,7 @@ import { Link2, Ticket } from 'lucide-react'
|
||||
import MSheet from '../../../components/MSheet'
|
||||
import MWalletButton from '../../../components/MWalletButton'
|
||||
import { MBookingCodeStatus, MBookingNotes, MBookingTravelers } from './MBookingFields'
|
||||
import { useAddonStore } from '../../../../store/addonStore'
|
||||
import { useTripAddonEnabled } from '../../../../store/tripAddonsStore'
|
||||
import { useTranslation } from '../../../../i18n'
|
||||
import CustomSelect from '../../../../components/shared/CustomSelect'
|
||||
import CustomTimePicker from '../../../../components/shared/CustomTimePicker'
|
||||
@@ -59,7 +59,7 @@ export default function MReservationSheet({ planner, onOpenExpense }: MReservati
|
||||
} = planner
|
||||
const { locale } = useTranslation()
|
||||
|
||||
const isBudgetEnabled = useAddonStore(s => s.isEnabled('budget'))
|
||||
const isBudgetEnabled = useTripAddonEnabled(tripId, 'budget')
|
||||
|
||||
const {
|
||||
form, setForm, set, isSaving, setIsSaving, pendingFiles, setPendingFiles, travelerIds, setTravelerIds, toggleTraveler,
|
||||
|
||||
@@ -2,7 +2,7 @@ import { useEffect, useMemo, useState } from 'react'
|
||||
import { ChevronDown, ChevronUp, Plus, TrainFront, TramFront, X } from 'lucide-react'
|
||||
import MSheet from '../../../components/MSheet'
|
||||
import { MBookingCodeStatus, MBookingNotes, MBookingTravelers, MRouteStopCard } from './MBookingFields'
|
||||
import { useAddonStore } from '../../../../store/addonStore'
|
||||
import { useTripAddonEnabled } from '../../../../store/tripAddonsStore'
|
||||
import { useTranslation } from '../../../../i18n'
|
||||
import CustomSelect from '../../../../components/shared/CustomSelect'
|
||||
import CustomTimePicker from '../../../../components/shared/CustomTimePicker'
|
||||
@@ -56,7 +56,7 @@ export default function MTransportFormSheet({ planner, onOpenExpense }: MTranspo
|
||||
} = planner
|
||||
const { locale } = useTranslation()
|
||||
|
||||
const isBudgetEnabled = useAddonStore(s => s.isEnabled('budget'))
|
||||
const isBudgetEnabled = useTripAddonEnabled(tripId, 'budget')
|
||||
const tripHasDates = Boolean(trip?.start_date && trip?.end_date)
|
||||
// The trip's places, offered by every location field of the manual tab (#2468).
|
||||
const locationPicks = useMemo(() => toLocationPicks(places), [places])
|
||||
|
||||
@@ -7,7 +7,7 @@ import { useTranslation } from '../../../../i18n'
|
||||
import { useSettingsStore } from '../../../../store/settingsStore'
|
||||
import { RES_ICONS } from '../../../../components/Planner/DayPlanSidebar.constants'
|
||||
import { splitReservationDateTime } from '../../../../utils/formatters'
|
||||
import { getFlightLegs, getTrainLegs, usesStationRoute, type FlightLeg, type TrainLeg } from '../../../../utils/flightLegs'
|
||||
import { getFlightLegs, getTrainLegs, seatLabel, seatsOfLegs, usesStationRoute, type FlightLeg, type TrainLeg } from '../../../../utils/flightLegs'
|
||||
import { runsOnDay } from '../../../../utils/reservationRoutes'
|
||||
import { filesFor } from '../../../../utils/reservationFiles'
|
||||
import { bookingDayLabel, segmentCodeLabel } from '../../../../components/Planner/transportDetailModel'
|
||||
@@ -169,8 +169,12 @@ export default function MTransportSheet({ planner, shell }: MTripSheetsProps) {
|
||||
if (leg && (leg.from || leg.to)) subParts.push(flowText([leg.from, leg.to].filter((n): n is string => !!n)))
|
||||
else if (from?.name && to?.name) subParts.push(flowText([from.name, to.name]))
|
||||
|
||||
// A flight's legs carry no seat or platform of their own, so those stay the booking's.
|
||||
const seat = leg && !isFlight ? legDetail.seat : meta.seat
|
||||
// Opened from a leg, that leg's own seat; the whole booking lists the seat of
|
||||
// every leg that has one, each under its route, rather than only the first's.
|
||||
const seats: { route: string | null; seat: string }[] = leg ? (legDetail.seat ? [{ route: null, seat: legDetail.seat }] : []) : seatsOfLegs(routeLegs, meta.seat)
|
||||
const ownSeat = seats.find(s => s.route == null)?.seat
|
||||
const legSeats = seats.filter(s => s.route != null)
|
||||
// A flight's legs carry no platform of their own, so that stays the booking's.
|
||||
const platform = leg && !isFlight ? legDetail.platform : meta.platform
|
||||
const transitLegs: TransitLeg[] = Array.isArray(meta.transit?.legs) ? meta.transit.legs : []
|
||||
|
||||
@@ -212,6 +216,9 @@ export default function MTransportSheet({ planner, shell }: MTripSheetsProps) {
|
||||
)
|
||||
: []
|
||||
|
||||
// The times, platform and booking seat; each leg's seat gets a row of its own below it.
|
||||
const statRow = hotelStats.length === 0 && ((showTimes && (depTime || arrTime)) || !!ownSeat || !!platform)
|
||||
|
||||
// The editor that fits the booking: transports have their own, everything
|
||||
// else (a stay, a table, a ticket) the booking editor, as in the Bookings tab.
|
||||
const editTransport = () => {
|
||||
@@ -236,8 +243,9 @@ export default function MTransportSheet({ planner, shell }: MTripSheetsProps) {
|
||||
<div className="flex-none px-[18px] pt-4">
|
||||
<TileHeader
|
||||
icon={<ResIcon size={19} strokeWidth={1.8} />}
|
||||
title={<span dir="auto" className="truncate text-[1rem]">{res.title}</span>}
|
||||
title={<span dir="auto" className="min-w-0 break-words text-[1rem] [overflow-wrap:anywhere]">{res.title}</span>}
|
||||
sub={subParts.length > 0 ? subParts.join(' · ') : undefined}
|
||||
subWrap
|
||||
onClose={shell.closeSheet}
|
||||
closeLabel={t('common.close')}
|
||||
/>
|
||||
@@ -274,7 +282,7 @@ export default function MTransportSheet({ planner, shell }: MTripSheetsProps) {
|
||||
))}
|
||||
|
||||
{/* ── Times / seat stats (the live card already shows the times) ── */}
|
||||
{hotelStats.length === 0 && ((showTimes && (depTime || arrTime)) || seat || platform) && (
|
||||
{statRow && (
|
||||
<div className="mt-[14px] flex gap-[6px]">
|
||||
{showTimes && depTime && (
|
||||
<StatBox caption={depDate} value={displayTime(depTime, locale, timeFormat)} label={depLabel} />
|
||||
@@ -283,7 +291,12 @@ export default function MTransportSheet({ planner, shell }: MTripSheetsProps) {
|
||||
<StatBox caption={arrDate} value={displayTime(arrTime, locale, timeFormat)} label={arrLabel} />
|
||||
)}
|
||||
{platform && <StatBox value={platform} label={t('reservations.meta.platform')} />}
|
||||
{seat && <StatBox value={seat} label={t('reservations.meta.seat')} />}
|
||||
{ownSeat && <StatBox value={ownSeat} label={t('reservations.meta.seat')} />}
|
||||
</div>
|
||||
)}
|
||||
{hotelStats.length === 0 && legSeats.length > 0 && (
|
||||
<div className={`${statRow ? 'mt-[6px]' : 'mt-[14px]'} flex gap-[6px]`}>
|
||||
{legSeats.map((s, i) => <StatBox key={i} value={s.seat} label={seatLabel(t('reservations.meta.seat'), s.route)} />)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -314,9 +327,9 @@ export default function MTransportSheet({ planner, shell }: MTripSheetsProps) {
|
||||
<span className="text-m-muted">{t('transit.walkTo', { name: leg.to?.name || '' })}</span>
|
||||
) : (
|
||||
<>
|
||||
<span dir="auto" className="truncate">{leg.from?.name}</span>
|
||||
<span dir="auto" className="min-w-0 break-words [overflow-wrap:anywhere]">{leg.from?.name}</span>
|
||||
<ArrowRight size={10} strokeWidth={2} className="flex-none text-m-faint" />
|
||||
<span dir="auto" className="truncate">{leg.to?.name}</span>
|
||||
<span dir="auto" className="min-w-0 break-words [overflow-wrap:anywhere]">{leg.to?.name}</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
LogOut,
|
||||
Pencil,
|
||||
Plus,
|
||||
Puzzle,
|
||||
RefreshCw,
|
||||
Settings2,
|
||||
Trash2,
|
||||
@@ -20,10 +21,10 @@ import CustomSelect from '../../../../components/shared/CustomSelect';
|
||||
import { LinkedJournalIcon } from '../../../../components/Trips/LinkedJournalIcon';
|
||||
import { TripJournalLinkSection } from '../../../../components/Trips/TripJournalLinkSection';
|
||||
import { TripMemberAvatar } from '../../../../components/Trips/TripMemberAvatar';
|
||||
import { useTripAddonRows } from '../../../../components/Trips/useTripAddonRows';
|
||||
import { useTripJournalSectionVisible } from '../../../../components/Trips/useTripJournalLink';
|
||||
import {
|
||||
SHARE_OPTIONS,
|
||||
SHARE_SECTIONS,
|
||||
useShareLink,
|
||||
useTripInviteLink,
|
||||
useTripMembers,
|
||||
@@ -33,6 +34,7 @@ import { useTranslation } from '../../../../i18n';
|
||||
import MChip from '../../../components/MChip';
|
||||
import MLinkField from '../../../components/MLinkField';
|
||||
import MSheet from '../../../components/MSheet';
|
||||
import MToggle from '../../../components/MToggle';
|
||||
import MConfirmSheet from '../../settings/MConfirmSheet';
|
||||
import {
|
||||
SHEET_FIELD as FIELD,
|
||||
@@ -91,7 +93,7 @@ function ShareLinkSection({ tripId }: { tripId: number }) {
|
||||
return (
|
||||
<Section title={t('share.linkTitle')} hint={t('share.linkHint')}>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{[...SHARE_SECTIONS, ...SHARE_OPTIONS].map((option) => {
|
||||
{[...link.sections, ...SHARE_OPTIONS].map((option) => {
|
||||
const always = 'always' in option && !!option.always;
|
||||
const on = !!link.perms[option.key];
|
||||
return (
|
||||
@@ -396,8 +398,40 @@ function GuestsSection({ m, ask }: { m: Members; ask: Ask }) {
|
||||
);
|
||||
}
|
||||
|
||||
/** The trip addons with their switches, for the owner; a pill marks the ones set apart from the instance. */
|
||||
function AddonsSection({ tripId }: { tripId: number }) {
|
||||
const { t } = useTranslation();
|
||||
const { rows, loading } = useTripAddonRows(tripId);
|
||||
return (
|
||||
<Section hint={t('trip.settings.addonsHint')}>
|
||||
{loading ? (
|
||||
<div className="h-[44px] animate-pulse rounded-full bg-[color:var(--m-ic)]" />
|
||||
) : (
|
||||
rows.map((row) => (
|
||||
<div key={row.id} className="flex min-h-[44px] items-center gap-[10px]">
|
||||
<span
|
||||
className={`flex h-8 w-8 flex-none items-center justify-center rounded-[10px] bg-[color:var(--m-ic)] ${row.enabled ? 'text-m-ink' : 'text-m-faint'}`}
|
||||
>
|
||||
<row.Icon size={16} strokeWidth={2} />
|
||||
</span>
|
||||
<div className="flex min-w-0 flex-1 flex-wrap items-center gap-1.5">
|
||||
<span className="min-w-0 truncate text-[length:calc(13.5px*var(--fs-scale-body,1))] font-semibold text-m-ink">
|
||||
{row.name}
|
||||
</span>
|
||||
{row.ownChoice && (
|
||||
<span className={`${PILL} bg-[color:var(--m-ic)] text-m-muted`}>{t('trip.addons.thisTripOnly')}</span>
|
||||
)}
|
||||
</div>
|
||||
<MToggle checked={row.enabled} onChange={row.toggle} ariaLabel={row.name} disabled={row.busy} />
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</Section>
|
||||
);
|
||||
}
|
||||
|
||||
/** The areas the sheet opens into, each a page of its own. */
|
||||
type Page = 'people' | 'sharing' | 'journal';
|
||||
type Page = 'people' | 'sharing' | 'journal' | 'addons';
|
||||
|
||||
/** One row of the sheet's first page: an icon tile, the area's name, what it holds, a chevron. */
|
||||
function AreaRow({
|
||||
@@ -427,9 +461,10 @@ function AreaRow({
|
||||
* The trip's settings on the phone (the Mehr sheet's "Trip settings"). The
|
||||
* first page lists the areas, like the phone's own settings, and each opens as
|
||||
* a page of its own with a way back: who is on the trip and its guests, the two
|
||||
* links, and the linked journal. One list rather than every card at once, so
|
||||
* the sheet stays calm as areas are added. The state is useTripShare's, the same
|
||||
* the desktop dialog runs on; only the markup and the questions are the phone's.
|
||||
* links, the linked journal, and for the owner the trip's own addons. One list
|
||||
* rather than every card at once, so the sheet stays calm as areas are added.
|
||||
* The state is useTripShare's and useTripAddonRows', the same the desktop
|
||||
* dialog runs on; only the markup and the questions are the phone's.
|
||||
*/
|
||||
export default function MTripSettingsSheet({
|
||||
open,
|
||||
@@ -463,6 +498,7 @@ export default function MTripSettingsSheet({
|
||||
people: t('trip.settings.people'),
|
||||
sharing: t('trip.settings.sharing'),
|
||||
journal: t('trip.journal.title'),
|
||||
addons: t('trip.settings.addons'),
|
||||
};
|
||||
const people = m.realMembers.length + m.guests.length;
|
||||
|
||||
@@ -518,6 +554,13 @@ export default function MTripSettingsSheet({
|
||||
onOpen={() => setPage('journal')}
|
||||
/>
|
||||
)}
|
||||
{m.isCurrentOwner && (
|
||||
<AreaRow
|
||||
icon={<Puzzle size={16} strokeWidth={2} />}
|
||||
label={pageTitle.addons}
|
||||
onOpen={() => setPage('addons')}
|
||||
/>
|
||||
)}
|
||||
</nav>
|
||||
)}
|
||||
{page === 'people' && (
|
||||
@@ -533,6 +576,7 @@ export default function MTripSettingsSheet({
|
||||
</>
|
||||
)}
|
||||
{page === 'journal' && <TripJournalLinkSection tripId={tripId} />}
|
||||
{page === 'addons' && m.isCurrentOwner && <AddonsSection tripId={tripId} />}
|
||||
</div>
|
||||
</MSheet>
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ import { cardWhen, parseTransportMeta, timeRange } from './transportsModel'
|
||||
import { BOOKING_TYPE_COLOR, hotelStayTimes } from '../../../../components/Planner/bookings/bookingsModel'
|
||||
import { useReservationListFilter } from '../../../../components/Planner/bookings/useReservationListFilter'
|
||||
import { useReservationCard } from '../../../../components/Planner/bookings/useReservationCard'
|
||||
import { orderedEndpoints } from '../../../../utils/flightLegs'
|
||||
import { orderedEndpoints, seatCells } from '../../../../utils/flightLegs'
|
||||
import { filesFor } from '../../../../utils/reservationFiles'
|
||||
|
||||
/**
|
||||
@@ -115,7 +115,7 @@ function BookingCard({ res, planner, canEdit, compact, onView }: {
|
||||
if (!hasEndpoints && meta.departure_airport) metaCells.push({ label: t('reservations.meta.from'), value: meta.departure_airport })
|
||||
if (!hasEndpoints && meta.arrival_airport) metaCells.push({ label: t('reservations.meta.to'), value: meta.arrival_airport })
|
||||
if (meta.platform) metaCells.push({ label: t('reservations.meta.platform'), value: meta.platform })
|
||||
if (meta.seat) metaCells.push({ label: t('reservations.meta.seat'), value: meta.seat + (meta.class ? ` · ${meta.class}` : '') })
|
||||
metaCells.push(...seatCells(res, t('reservations.meta.seat'), meta.class ? ` · ${meta.class}` : ''))
|
||||
if (meta.price != null && meta.price !== '') {
|
||||
metaCells.push({ label: t('reservations.price'), value: formatPriceText(meta.price, meta.priceCurrency, planner.trip?.currency, locale) })
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ import { cardWhen, parseTransportMeta } from './transportsModel'
|
||||
import { TRANSPORT_TYPE_COLOR } from '../../../../components/Planner/bookings/bookingsModel'
|
||||
import { useReservationListFilter } from '../../../../components/Planner/bookings/useReservationListFilter'
|
||||
import { useReservationCard } from '../../../../components/Planner/bookings/useReservationCard'
|
||||
import { orderedEndpoints } from '../../../../utils/flightLegs'
|
||||
import { orderedEndpoints, seatCells } from '../../../../utils/flightLegs'
|
||||
import { filesFor } from '../../../../utils/reservationFiles'
|
||||
import MFlightLiveStrip from '../MFlightLiveStrip'
|
||||
|
||||
@@ -113,7 +113,7 @@ function TransportCard({ res, planner, shell, canEdit, compact }: {
|
||||
if (!hasEndpoints && meta.arrival_airport) metaCells.push({ label: t('reservations.meta.to'), value: meta.arrival_airport })
|
||||
if (meta.train_number) metaCells.push({ label: t('reservations.meta.trainNumber'), value: meta.train_number })
|
||||
if (meta.platform) metaCells.push({ label: t('reservations.meta.platform'), value: meta.platform })
|
||||
if (meta.seat) metaCells.push({ label: t('reservations.meta.seat'), value: meta.seat + (meta.class ? ` · ${meta.class}` : '') })
|
||||
metaCells.push(...seatCells(res, t('reservations.meta.seat'), meta.class ? ` · ${meta.class}` : ''))
|
||||
if (meta.price != null && meta.price !== '') {
|
||||
metaCells.push({ label: t('reservations.price'), value: formatPriceText(meta.price, meta.priceCurrency, planner.trip?.currency, locale) })
|
||||
}
|
||||
|
||||
@@ -168,6 +168,20 @@ describe('watchBooking', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('carries the seat of every leg of a flight with a stop, also one booked only on the second', () => {
|
||||
const stopover = reservation({
|
||||
...flight,
|
||||
metadata: JSON.stringify({
|
||||
legs: [
|
||||
{ from: 'MXP', to: 'IST' },
|
||||
{ from: 'IST', to: 'JFK', seat: '14C' },
|
||||
],
|
||||
}),
|
||||
});
|
||||
const b = watchBooking(stopover, { day: '2026-11-17', time: '13:05' }, { dayDates: new Map(), places: new Map() });
|
||||
expect(b.seat).toBe('14C');
|
||||
});
|
||||
|
||||
it('gives a stay its check-in, check-out, dates from its days and the hotel as the place to go', () => {
|
||||
const dayDates = new Map([
|
||||
[2, '2026-11-18'],
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { Day, PackingItem, Place, Reservation, TodoItem, Trip } from '../types';
|
||||
import { parseReservationMetadata } from '../utils/flightLegs';
|
||||
import { bookingSeats, parseReservationMetadata } from '../utils/flightLegs';
|
||||
import { splitReservationDateTime } from '../utils/formatters';
|
||||
import { hasNativeFeature } from './capabilities';
|
||||
import { isNativeIos } from './platform';
|
||||
@@ -274,7 +274,13 @@ export function watchBooking(
|
||||
to: point(to),
|
||||
code: text(r.confirmation_number, 40),
|
||||
carrier: carrierOf(meta),
|
||||
seat: metaText(meta, 'seat'),
|
||||
// A flight or train with a stop: the seat of every leg, not only the first leg's.
|
||||
seat: text(
|
||||
bookingSeats(r)
|
||||
.map((s) => s.seat)
|
||||
.join(', '),
|
||||
20
|
||||
),
|
||||
platform: metaText(meta, 'platform'),
|
||||
...whereOf(r, places),
|
||||
checkIn: metaText(meta, 'check_in_time'),
|
||||
|
||||
@@ -20,9 +20,6 @@ vi.mock('../components/Admin/BackupPanel', () => ({
|
||||
vi.mock('../components/Admin/GitHubPanel', () => ({
|
||||
default: () => <div data-testid="github-panel" />,
|
||||
}));
|
||||
vi.mock('../components/Admin/paddle/PaddleRegionsPanel', () => ({
|
||||
default: () => <div data-testid="paddle-regions-panel" />,
|
||||
}));
|
||||
|
||||
// AddonManager is stubbed but keeps its two callbacks reachable — the page owns
|
||||
// the optimistic toggle logic behind them.
|
||||
@@ -225,8 +222,6 @@ describe('AdminPage', () => {
|
||||
fireEvent.click(screen.getByRole('button', { name: /^addons$/i }));
|
||||
|
||||
expect(screen.getByTestId('addon-manager')).toBeInTheDocument();
|
||||
// The paddle water data sit under the addons; the panel hides itself while Tours is off.
|
||||
expect(screen.getByTestId('paddle-regions-panel')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import SchoolHolidayCatalog from '../components/Admin/SchoolHolidayCatalog'
|
||||
import PaddleRegionsPanel from '../components/Admin/paddle/PaddleRegionsPanel'
|
||||
import React, { Fragment } from 'react'
|
||||
import DevNotificationsPanel from '../components/Admin/DevNotificationsPanel'
|
||||
import DefaultUserSettingsTab from '../components/Admin/DefaultUserSettingsTab'
|
||||
@@ -166,10 +165,17 @@ function AdminPageDesktop(): React.ReactElement {
|
||||
onToggleBagTracking={toggleBagTracking}
|
||||
collabFeatures={collabFeatures}
|
||||
onToggleCollabFeature={toggleCollabFeature}
|
||||
// How the integrations reach the world: live flight status, booking mails.
|
||||
aside={<AdminSettingsTab admin={admin} t={t} part="features" />}
|
||||
// Live flight status follows the trips' flights; the booking mail import is
|
||||
// the operator's relay on a managed install.
|
||||
flightLive={{
|
||||
on: admin.flightLive,
|
||||
locked: admin.flightLiveLocked,
|
||||
managed,
|
||||
onToggle: () =>
|
||||
void admin.handleToggleAuthSetting('flight_live_enabled', !admin.flightLive, admin.setFlightLive),
|
||||
}}
|
||||
mailImport={!managed}
|
||||
/>
|
||||
<PaddleRegionsPanel />
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
||||
@@ -576,8 +576,9 @@ describe('JourneyPublicPage', () => {
|
||||
// broken-image glyph on every shared layout (#2341).
|
||||
it('FE-PAGE-PUBLICJOURNEY-023: a shared clip without a poster is a black tile, with a poster its poster', async () => {
|
||||
const user = userEvent.setup();
|
||||
const bare = { id: 200, entry_id: 20, photo_id: 200, provider: 'local', asset_id: null, owner_id: null, file_path: 'journey/a.mp4', thumbnail_path: null, media_type: 'video', caption: null };
|
||||
const withPoster = { id: 201, entry_id: 21, photo_id: 201, provider: 'local', asset_id: null, owner_id: null, file_path: 'journey/b.mp4', thumbnail_path: 'journey/b.jpg', media_type: 'video', caption: null };
|
||||
// The share link carries no storage key: the server says which clip has no poster.
|
||||
const bare = { id: 200, photo_id: 200, media_type: 'video', caption: null, posterless: true };
|
||||
const withPoster = { id: 201, photo_id: 201, media_type: 'video', caption: null, posterless: false };
|
||||
const entry = (id: number, photo: typeof bare) => ({
|
||||
id, title: `Clip ${id}`, story: null, entry_date: '2026-03-15', entry_time: null,
|
||||
location_name: null, location_lat: null, location_lng: null, mood: null, weather: null, pros_cons: null,
|
||||
@@ -587,8 +588,8 @@ describe('JourneyPublicPage', () => {
|
||||
...mockJourneyData,
|
||||
entries: [entry(20, bare), entry(21, withPoster)],
|
||||
gallery: [
|
||||
{ ...bare, journey_id: 1, shared: 1, sort_order: 0, created_at: 0 },
|
||||
{ ...withPoster, journey_id: 1, shared: 1, sort_order: 1, created_at: 0 },
|
||||
{ ...bare, lat: null, lng: null, taken_at: null },
|
||||
{ ...withPoster, lat: null, lng: null, taken_at: null },
|
||||
],
|
||||
stats: { entries: 2, photos: 2, places: 0 },
|
||||
})));
|
||||
|
||||
@@ -39,7 +39,7 @@ vi.mock('../components/Journey/JournalBody', () => ({
|
||||
// ── Fixtures ─────────────────────────────────────────────────────────────────
|
||||
|
||||
function photo(id: number): PublicEntry['photos'][number] {
|
||||
return { id, entry_id: 1, photo_id: id * 10, caption: `caption ${id}`, provider: 'local' };
|
||||
return { id, photo_id: id * 10, caption: `caption ${id}`, posterless: false };
|
||||
}
|
||||
|
||||
function buildEntry(over: Partial<PublicEntry> = {}): PublicEntry {
|
||||
|
||||
@@ -456,7 +456,7 @@ describe('TripPlannerPage', () => {
|
||||
it('shows PackingListPanel after clicking the Lists tab with packing addon enabled', async () => {
|
||||
server.use(
|
||||
http.get('/api/addons', () =>
|
||||
HttpResponse.json({ addons: [{ id: 'packing', type: 'packing' }] })
|
||||
HttpResponse.json({ addons: [{ id: 'packing', type: 'trip', enabled: true }] })
|
||||
)
|
||||
);
|
||||
|
||||
@@ -483,7 +483,7 @@ describe('TripPlannerPage', () => {
|
||||
it('shows CostsPanel after clicking the Costs tab with budget addon enabled', async () => {
|
||||
server.use(
|
||||
http.get('/api/addons', () =>
|
||||
HttpResponse.json({ addons: [{ id: 'budget', type: 'budget' }] })
|
||||
HttpResponse.json({ addons: [{ id: 'budget', type: 'trip', enabled: true }] })
|
||||
)
|
||||
);
|
||||
|
||||
@@ -510,7 +510,7 @@ describe('TripPlannerPage', () => {
|
||||
it('shows FileManager after clicking the Files tab with documents addon enabled', async () => {
|
||||
server.use(
|
||||
http.get('/api/addons', () =>
|
||||
HttpResponse.json({ addons: [{ id: 'documents', type: 'documents' }] })
|
||||
HttpResponse.json({ addons: [{ id: 'documents', type: 'trip', enabled: true }] })
|
||||
)
|
||||
);
|
||||
|
||||
@@ -537,7 +537,7 @@ describe('TripPlannerPage', () => {
|
||||
it('shows CollabPanel after clicking the Collab tab with collab addon enabled', async () => {
|
||||
server.use(
|
||||
http.get('/api/addons', () =>
|
||||
HttpResponse.json({ addons: [{ id: 'collab', type: 'collab' }] })
|
||||
HttpResponse.json({ addons: [{ id: 'collab', type: 'trip', enabled: true }] })
|
||||
)
|
||||
);
|
||||
|
||||
@@ -665,7 +665,7 @@ describe('TripPlannerPage', () => {
|
||||
it('shows TodoListPanel after switching to the Todo subtab inside Lists', async () => {
|
||||
server.use(
|
||||
http.get('/api/addons', () =>
|
||||
HttpResponse.json({ addons: [{ id: 'packing', type: 'packing' }] })
|
||||
HttpResponse.json({ addons: [{ id: 'packing', type: 'trip', enabled: true }] })
|
||||
)
|
||||
);
|
||||
|
||||
@@ -1393,7 +1393,7 @@ describe('TripPlannerPage', () => {
|
||||
it('calls FileManager onUpload/onDelete/onUpdate to cover inline lambda bodies', async () => {
|
||||
server.use(
|
||||
http.get('/api/addons', () =>
|
||||
HttpResponse.json({ addons: [{ id: 'documents', type: 'documents' }] })
|
||||
HttpResponse.json({ addons: [{ id: 'documents', type: 'trip', enabled: true }] })
|
||||
)
|
||||
);
|
||||
|
||||
@@ -1838,7 +1838,7 @@ describe('TripPlannerPage', () => {
|
||||
// road-trip hooks then read their own endpoints, answered empty here.
|
||||
const enterRoadtrip = () => {
|
||||
server.use(
|
||||
http.get('/api/addons', () => HttpResponse.json({ addons: [{ id: 'roadtrip', type: 'roadtrip' }] })),
|
||||
http.get('/api/addons', () => HttpResponse.json({ addons: [{ id: 'roadtrip', type: 'trip', enabled: true }] })),
|
||||
http.get('/api/trips/42/roadtrip/vias', () => HttpResponse.json({ vias: [], tracks: [] })),
|
||||
http.get('/api/trips/42/roadtrip/preferences', () => HttpResponse.json({ tripId: 42, preferences: {} })),
|
||||
);
|
||||
|
||||
@@ -13,13 +13,12 @@ import AdminSettingsTab from './AdminSettingsTab';
|
||||
type Spy = ReturnType<typeof vi.fn>;
|
||||
type Spies = Record<string, Spy> & { toast: Record<string, Spy> };
|
||||
|
||||
/** The three tabs the settings are split into (security, services, features), on one page. */
|
||||
/** The two tabs the settings are split into (security, services), on one page. */
|
||||
function AllParts({ admin, t }: { admin: AdminHook; t: ReturnType<typeof useTranslation>['t'] }) {
|
||||
return (
|
||||
<>
|
||||
<AdminSettingsTab admin={admin} t={t} part="security" />
|
||||
<AdminSettingsTab admin={admin} t={t} part="services" />
|
||||
<AdminSettingsTab admin={admin} t={t} part="features" />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import React from 'react'
|
||||
import {
|
||||
AlertTriangle, CheckCircle, Compass, Eye, EyeOff, FileType, Fingerprint, KeyRound, Loader2, LockKeyhole, LogIn,
|
||||
Plane, RefreshCw, Save, XCircle,
|
||||
RefreshCw, Save, XCircle,
|
||||
} from 'lucide-react'
|
||||
import ToggleSwitch from '../../components/Settings/ToggleSwitch'
|
||||
import CustomSelect from '../../components/shared/CustomSelect'
|
||||
@@ -14,7 +14,6 @@ import GoogleOptions from './GoogleOptions'
|
||||
import GoogleDailyLimitRow from '../../components/Admin/GoogleDailyLimitRow'
|
||||
import ProviderBlock from './ProviderBlock'
|
||||
import TrekApiCard from './TrekApiCard'
|
||||
import MailIngestAdminCard from '../../components/Admin/mailIngest/MailIngestAdminCard'
|
||||
import PlaceContribPanel from '../../components/Admin/PlaceContribPanel'
|
||||
import { useAdminSettingsActions } from '../../components/Admin/useAdminSettingsActions'
|
||||
import { placesGoogleOnlyHint } from '../../utils/placeSource'
|
||||
@@ -25,11 +24,10 @@ interface AdminSettingsTabProps {
|
||||
admin: ReturnType<typeof useAdmin>
|
||||
t: TranslationFn
|
||||
/**
|
||||
* Which tab this renders: sign-in and its safety (security), what the
|
||||
* install talks to outside (services), or the setup of the features the
|
||||
* addons tab switches on (features).
|
||||
* Which tab this renders: sign-in and its safety (security) or what the
|
||||
* install talks to outside (services).
|
||||
*/
|
||||
part: 'security' | 'services' | 'features'
|
||||
part: 'security' | 'services'
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -126,7 +124,6 @@ export default function AdminSettingsTab({ admin, t, part }: AdminSettingsTabPro
|
||||
oidcConfig, setOidcConfig, savingOidc,
|
||||
passwordLogin, setPasswordLogin, passwordRegistration, setPasswordRegistration,
|
||||
oidcLogin, setOidcLogin, oidcRegistration, setOidcRegistration, oidcAutoRedirect, setOidcAutoRedirect,
|
||||
flightLive, setFlightLive, flightLiveLocked,
|
||||
envOverrideOidcOnly, oidcConfigured, requireMfa,
|
||||
passkeyLogin, setPasskeyLogin, passkeyConfigured,
|
||||
webauthnRpId, setWebauthnRpId, webauthnOrigins, setWebauthnOrigins, savingWebauthn, handleSaveWebauthn,
|
||||
@@ -395,34 +392,6 @@ export default function AdminSettingsTab({ admin, t, part }: AdminSettingsTabPro
|
||||
)}
|
||||
</>
|
||||
)
|
||||
const flightCard = (
|
||||
<>
|
||||
{/* Live flight status: open ADS-B data, no key, on by default; the admin may keep it off. */}
|
||||
<SettingsCard icon={Plane} title={t('flightLive.adminTitle')} hint={managed ? t('flightLive.adminHintManaged') : t('flightLive.adminHint')}>
|
||||
<SettingRows>
|
||||
<SettingRow
|
||||
label={t('flightLive.adminToggle')}
|
||||
hint={flightLiveLocked ? t('flightLive.envLocked') : undefined}
|
||||
control={
|
||||
<ToggleSwitch
|
||||
on={flightLive}
|
||||
label={t('flightLive.adminToggle')}
|
||||
disabled={flightLiveLocked}
|
||||
onToggle={() => void handleToggleAuthSetting('flight_live_enabled', !flightLive, setFlightLive)}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</SettingRows>
|
||||
</SettingsCard>
|
||||
</>
|
||||
)
|
||||
const mailCard = (
|
||||
<>
|
||||
{/* Booking mail import: how forwarded booking mails reach this install. On a managed
|
||||
install the operator runs the TREK Cloud relay, so the card is not shown there. */}
|
||||
{!managed && <MailIngestAdminCard />}
|
||||
</>
|
||||
)
|
||||
const servicesCard = (
|
||||
<>
|
||||
{/* Place search and routing: TREK's own services first, then which provider
|
||||
@@ -714,16 +683,9 @@ export default function AdminSettingsTab({ admin, t, part }: AdminSettingsTabPro
|
||||
)
|
||||
|
||||
// What used to be one "Settings" tab, split by what an admin comes for:
|
||||
// who may sign in and how (security), what the install talks to outside
|
||||
// (services), and how the features in the addons tab are set up there.
|
||||
if (part === 'features') {
|
||||
return (
|
||||
<>
|
||||
{flightCard}
|
||||
{mailCard}
|
||||
</>
|
||||
)
|
||||
}
|
||||
// who may sign in and how (security) and what the install talks to outside
|
||||
// (services). Live flight status and the booking mail import are rows of the
|
||||
// addons tab's cards now.
|
||||
if (part === 'services') {
|
||||
// Place search and the services on the left, the keys and file types on the right.
|
||||
return (
|
||||
|
||||
@@ -260,6 +260,13 @@ describe('posterlessVideo (#2341)', () => {
|
||||
expect(posterlessVideo({ provider: 'local', thumbnail_path: null })).toBe(false);
|
||||
expect(posterlessVideo({ media_type: 'video', provider: 'immich', thumbnail_path: null })).toBe(false);
|
||||
});
|
||||
|
||||
it('takes the answer a shared journey sends, which carries no storage key', () => {
|
||||
expect(posterlessVideo({ media_type: 'video', posterless: true })).toBe(true);
|
||||
expect(posterlessVideo({ media_type: 'video', posterless: false })).toBe(false);
|
||||
// The flag wins over the columns, so a public photo never needs them.
|
||||
expect(posterlessVideo({ media_type: 'video', provider: 'local', thumbnail_path: null, posterless: false })).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('fetchRemainingProviderPages (#1587)', () => {
|
||||
|
||||
@@ -95,12 +95,17 @@ export function photoUrl(p: { photo_id: number }, size: 'thumbnail' | 'original'
|
||||
* purpose rather than streaming the whole file, and an <img> pointed at it
|
||||
* shows the broken-image glyph (#2341). A provider clip is not one of these,
|
||||
* its poster comes from the provider whether or not a local path is recorded.
|
||||
*
|
||||
* A shared journey carries no storage keys, so the server answers the question
|
||||
* itself there (`posterless`).
|
||||
*/
|
||||
export function posterlessVideo(p: {
|
||||
media_type?: string | null;
|
||||
provider?: string | null;
|
||||
thumbnail_path?: string | null;
|
||||
posterless?: boolean;
|
||||
}): boolean {
|
||||
if (typeof p.posterless === 'boolean') return p.posterless;
|
||||
return p.media_type === 'video' && p.provider === 'local' && !p.thumbnail_path;
|
||||
}
|
||||
|
||||
|
||||
@@ -4,68 +4,61 @@
|
||||
* presentational page.
|
||||
*/
|
||||
|
||||
/**
|
||||
* An entry as the share link sends it (`journeyPublicEntrySchema` in
|
||||
* @trek/shared). A map-only share leaves out the story fields and the photos.
|
||||
*/
|
||||
export interface PublicEntry {
|
||||
id: number
|
||||
type?: string | null
|
||||
sort_order?: number | null
|
||||
title?: string | null
|
||||
story?: string | null
|
||||
entry_date: string
|
||||
entry_time?: string | null
|
||||
location_name?: string | null
|
||||
location_lat?: number | null
|
||||
location_lng?: number | null
|
||||
mood?: string | null
|
||||
weather?: string | null
|
||||
pros_cons?: { pros: string[]; cons: string[] } | null
|
||||
photos: PublicPhoto[]
|
||||
id: number;
|
||||
type?: string | null;
|
||||
sort_order?: number | null;
|
||||
title?: string | null;
|
||||
story?: string | null;
|
||||
entry_date: string;
|
||||
entry_time?: string | null;
|
||||
location_name?: string | null;
|
||||
location_lat?: number | null;
|
||||
location_lng?: number | null;
|
||||
country_code?: string | null;
|
||||
mood?: string | null;
|
||||
weather?: string | null;
|
||||
tags?: string[];
|
||||
pros_cons?: { pros: string[]; cons: string[] } | null;
|
||||
photos: PublicPhoto[];
|
||||
}
|
||||
|
||||
/**
|
||||
* A photo of a shared journey (`journeyPublicPhotoSchema`). It carries no
|
||||
* storage key or asset id: the bytes are fetched by `photo_id` through the
|
||||
* share token.
|
||||
*/
|
||||
export interface PublicPhoto {
|
||||
id: number
|
||||
entry_id: number
|
||||
photo_id: number
|
||||
provider?: string
|
||||
asset_id?: string | null
|
||||
owner_id?: number | null
|
||||
file_path?: string | null
|
||||
caption?: string | null
|
||||
id: number;
|
||||
photo_id: number;
|
||||
caption?: string | null;
|
||||
// 'image' (default) or 'video' (#823)
|
||||
media_type?: string | null
|
||||
/** Null on a local clip whose poster frame could not be grabbed; the page
|
||||
* draws a marked tile instead of an <img> then (#2341). */
|
||||
thumbnail_path?: string | null
|
||||
duration_ms?: number | null
|
||||
media_type?: string | null;
|
||||
width?: number | null;
|
||||
height?: number | null;
|
||||
duration_ms?: number | null;
|
||||
/** A clip whose poster frame could not be grabbed; the page draws a plain tile instead of an <img> (#2341). */
|
||||
posterless?: boolean;
|
||||
}
|
||||
|
||||
export interface PublicGalleryPhoto {
|
||||
id: number
|
||||
journey_id: number
|
||||
photo_id: number
|
||||
provider?: string
|
||||
asset_id?: string | null
|
||||
owner_id?: number | null
|
||||
file_path?: string | null
|
||||
caption?: string | null
|
||||
// 'image' (default) or 'video' (#823)
|
||||
media_type?: string | null
|
||||
/** Null on a local clip whose poster frame could not be grabbed; the gallery
|
||||
* draws a marked tile instead of an <img> then (#2341). */
|
||||
thumbnail_path?: string | null
|
||||
duration_ms?: number | null
|
||||
/** Where and when the picture was taken (#1614). Absent for most photos, and the
|
||||
export interface PublicGalleryPhoto extends PublicPhoto {
|
||||
/** When and where the picture was taken (#1614). Absent for most photos, and the
|
||||
* coordinates are withheld entirely unless the owner shared the map. */
|
||||
taken_at?: string | null
|
||||
lat?: number | null
|
||||
lng?: number | null
|
||||
taken_at?: string | null;
|
||||
lat?: number | null;
|
||||
lng?: number | null;
|
||||
}
|
||||
|
||||
export function groupByDate(entries: PublicEntry[]): Map<string, PublicEntry[]> {
|
||||
const groups = new Map<string, PublicEntry[]>()
|
||||
const groups = new Map<string, PublicEntry[]>();
|
||||
for (const e of entries) {
|
||||
const d = e.entry_date
|
||||
if (!groups.has(d)) groups.set(d, [])
|
||||
groups.get(d)!.push(e)
|
||||
const d = e.entry_date;
|
||||
if (!groups.has(d)) groups.set(d, []);
|
||||
groups.get(d)!.push(e);
|
||||
}
|
||||
return groups
|
||||
return groups;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import { useEffect, useMemo } from 'react';
|
||||
import { useShallow } from 'zustand/react/shallow';
|
||||
|
||||
import { useTripAddons } from '../../components/Trips/useTripAddons';
|
||||
import { useAddonStore } from '../../store/addonStore';
|
||||
import { tripAddonEnabled } from '../../utils/tripAddons';
|
||||
|
||||
/**
|
||||
* What the planner shows while neither the trip's list nor the instance's is
|
||||
* known (offline on a trip the device never read the addons of): the core
|
||||
* sections on, the rest off, as the planner always guessed.
|
||||
*/
|
||||
const WHEN_UNKNOWN: Readonly<Record<string, boolean>> = {
|
||||
packing: true,
|
||||
budget: true,
|
||||
documents: true,
|
||||
collab: false,
|
||||
roadtrip: false,
|
||||
tours: false,
|
||||
dawarich: false,
|
||||
};
|
||||
|
||||
/**
|
||||
* The addons the trip planner shows for one trip, in both shells: the trip
|
||||
* addons as the trip has them (the owner's choice or the instance switch),
|
||||
* Dawarich (an integration) and the collab sub-features from the instance.
|
||||
* Follows a change of the trip's addons live, so tabs, dock, rail and More
|
||||
* sheet appear and go as the owner switches.
|
||||
*/
|
||||
export function usePlannerAddons(tripId: number) {
|
||||
const tripAddons = useTripAddons(Number.isFinite(tripId) ? tripId : null);
|
||||
const instance = useAddonStore(
|
||||
useShallow((s) => ({ addons: s.addons, known: (s.loaded && !s.failed) || s.addons.length > 0, loaded: s.loaded }))
|
||||
);
|
||||
const collabFeatures = useAddonStore((s) => s.collabFeatures);
|
||||
|
||||
// The app reads the instance list once signed in; a planner opened before that answered asks itself.
|
||||
useEffect(() => {
|
||||
if (!useAddonStore.getState().loaded) void useAddonStore.getState().loadAddons();
|
||||
}, []);
|
||||
|
||||
const enabledAddons = useMemo(() => {
|
||||
const instanceOn = (id: string) =>
|
||||
instance.known ? instance.addons.some((a) => a.id === id && a.enabled) : WHEN_UNKNOWN[id];
|
||||
return Object.fromEntries(
|
||||
Object.keys(WHEN_UNKNOWN).map((id) => [id, tripAddonEnabled(tripAddons.addons, id, instanceOn(id))])
|
||||
) as Record<string, boolean>;
|
||||
}, [tripAddons.addons, instance]);
|
||||
|
||||
// Until then enabledAddons is a guess, and the tab guard must not evict a tab on it.
|
||||
const addonsLoaded = tripAddons.loaded && (tripAddons.addons.length > 0 || instance.loaded);
|
||||
|
||||
return { enabledAddons, addonsLoaded, collabFeatures, toursEnabled: !!enabledAddons.tours };
|
||||
}
|
||||
@@ -29,7 +29,7 @@ const basesOf = (p: Planner, zoom: number | null = null) =>
|
||||
renderHook(() => useTourStageLayers(p, ferrata, zoom)).result.current;
|
||||
|
||||
describe('useTourStageLayers: OpenHikingMap (MAP-01)', () => {
|
||||
beforeEach(() => useAddonStore.setState({ toursHikingMap: true, toursCycleMap: true }));
|
||||
beforeEach(() => useAddonStore.setState({ toursOptions: { wanderer: false, hikingMap: true, cycleMap: true } }));
|
||||
|
||||
it('offers it while a hike is open: planned as a draft, a saved tour in the editor, or an import viewed as it came in', () => {
|
||||
const viewed = { type: 'view-gpx', placeId: 9, tour: { place_id: 9, tour_type: 'hike' } as TourListItem } as const;
|
||||
@@ -54,7 +54,7 @@ describe('useTourStageLayers: OpenHikingMap (MAP-01)', () => {
|
||||
});
|
||||
|
||||
it('not where the admin withdrew it', () => {
|
||||
useAddonStore.setState({ toursHikingMap: false });
|
||||
useAddonStore.setState({ toursOptions: { wanderer: false, hikingMap: false, cycleMap: true } });
|
||||
expect(basesOf(planner({ type: 'new-draft' })).tourLayers.bases).not.toContain('hiking');
|
||||
});
|
||||
|
||||
@@ -67,7 +67,7 @@ describe('useTourStageLayers: OpenHikingMap (MAP-01)', () => {
|
||||
expect(layers.tourLayers.baseHealth).toMatchObject({ base: 'cycle', down: false });
|
||||
}
|
||||
expect(basesOf(planner({ type: 'new-draft' }, 'hike', 'cycle')).baseLayer).toBe('default');
|
||||
useAddonStore.setState({ toursCycleMap: false });
|
||||
useAddonStore.setState({ toursOptions: { wanderer: false, hikingMap: true, cycleMap: false } });
|
||||
expect(basesOf(planner({ type: 'new-draft' }, 'bike', 'cycle')).tourLayers.bases).not.toContain('cycle');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -36,9 +36,10 @@ export function useTourStageLayers(
|
||||
const { mode } = tourPlanner;
|
||||
// MAP-01, BIK-06: a type's own map (OpenHikingMap for a hike, CyclOSM for a bike tour) while a
|
||||
// tour of that type is open, planned or viewed as it came in, never with no tour open, and only
|
||||
// while the admin offers it.
|
||||
const hikingMapAllowed = useAddonStore((state) => state.toursHikingMap);
|
||||
const cycleMapAllowed = useAddonStore((state) => state.toursCycleMap);
|
||||
// while the admin offers it. The options apply wherever Tours is on, the instance switch or the
|
||||
// trip's own, and this stage only shows where it is.
|
||||
const hikingMapAllowed = useAddonStore((state) => state.toursOptions.hikingMap);
|
||||
const cycleMapAllowed = useAddonStore((state) => state.toursOptions.cycleMap);
|
||||
const tourOpen = mode.type !== 'neutral';
|
||||
const openType = mode.type === 'view-gpx' ? mode.tour.tour_type : tourPlanner.tourType;
|
||||
const layerSet = tourMapLayersFor(openType, {
|
||||
|
||||
@@ -70,8 +70,9 @@ export function useTourWorkspace(planner: TripPlanner, canPlaceEdit: boolean, ca
|
||||
tripMembers,
|
||||
upsertTour,
|
||||
} = planner;
|
||||
// wanderer only while the admin allows it under Tours (the store reads Tours being on into it too).
|
||||
const wandererAllowed = useAddonStore((state) => state.toursWanderer);
|
||||
// wanderer only while the admin allows it under Tours, and Tours is on for this trip (the
|
||||
// instance switch or the trip's own).
|
||||
const wandererAllowed = useAddonStore((state) => state.toursOptions.wanderer) && !!enabledAddons.tours;
|
||||
// The workspace is up where its tab is: on a desktop, and in the touch shell on a
|
||||
// large screen (an iPad, an unfolded foldable). The app counts as a phone shell on
|
||||
// every device, so the phone test alone left the tablet's editor switched off.
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user