From 91630dd811ead0b2847c71b0641dfd6693260d0a Mon Sep 17 00:00:00 2001 From: Maurice Date: Thu, 5 Nov 2026 12:15:53 +0100 Subject: [PATCH 001/589] fix(planner): let a timed booking stay where it is dropped when only other bookings stand against its time A booking dropped against another booking's time went back to the nearest slot its own time allowed. With a 06:30 flight listed below the day's untimed stops, every slot among them was against the flight, so a 13:00 transit dropped between two stops went back behind the flight on every drop, and the flight's legs cannot be dragged out of the way. The dropped row now stays where it was dropped and the other timed bookings it puts out of order move next to it, the earlier ones ahead of it and the later ones behind. Timed stops and notes never move: against one of those the row is still seated by its time as before (#2631). The phone's move applies the same rule before it refuses a move. Closes #2983 --- .../screens/trip/plan/useMPlanTimeline.ts | 15 +++-- client/src/utils/dayMerge.test.ts | 48 ++++++++++++- client/src/utils/dayMerge.ts | 67 ++++++++++++++++--- .../unit/mobile/trip/useMPlanTimeline.test.ts | 37 +++++++++- 4 files changed, 151 insertions(+), 16 deletions(-) diff --git a/client/src/mobile/screens/trip/plan/useMPlanTimeline.ts b/client/src/mobile/screens/trip/plan/useMPlanTimeline.ts index 1c88767e3..92ea3ee91 100644 --- a/client/src/mobile/screens/trip/plan/useMPlanTimeline.ts +++ b/client/src/mobile/screens/trip/plan/useMPlanTimeline.ts @@ -7,7 +7,7 @@ import { toDisplayTemp } from '../../../../components/Planner/dayDetailModel' import { getDayBookendHotels } from '../../../../utils/dayOrder' import { dayWeatherAnchor } from '../../../../utils/dayWeather' import { metadataWithLegPositions, planMergedOrder, withTransportPositions } from '../../../../utils/mergedOrder' -import { getDisplayTimeForDay, getMergedItems, getTransportForDay, hasCarrierEndpointOnDay, isCarrierTransport, stopDayIds } from '../../../../utils/dayMerge' +import { getDisplayTimeForDay, getMergedItems, getTransportForDay, hasCarrierEndpointOnDay, isCarrierTransport, stopDayIds, yieldTimedBookings } from '../../../../utils/dayMerge' import { dayCoMapsUrl, dayExportStops, dayGoogleMapsUrl, optimizeDayOrder, type DayCarrier } from '../../../../components/Planner/dayRoute' import type { PlannedTransitLeg, TransitLeg } from '../../../../components/Planner/transitLeg' import { useTransitLegPlanner } from '../../../../components/Planner/useTransitLegPlanner' @@ -208,10 +208,17 @@ export function useMPlanTimeline(planner: TripPlanner) { const newOrder = [...merged] newOrder.splice(idx, 1) newOrder.splice(toIndex, 0, item) - // Same guard as the desktop arrow buttons: a TIMED item may not jump past - // other timed items (untimed items move freely and keep their neighbours). + // A TIMED item may not jump past other timed items (untimed items move freely and + // keep their neighbours). Bookings it passes make room when they can, as on a desktop + // drop (#2983); a timed stop or note in the way, or a move that leaves the day as it + // was, is refused. if (itemHasTime(item, day.id) && breaksChronology(newOrder, day.id, getDisplayTimeForDay)) { - toast.info(t('dayplan.cannotBreakChronology')) + const yielded = yieldTimedBookings(newOrder, toIndex, day.id, getDisplayTimeForDay) + if (!yielded || yielded.every((it, i) => it === merged[i])) { + toast.info(t('dayplan.cannotBreakChronology')) + return + } + void applyMergedOrder(day.id, yielded) return } void applyMergedOrder(day.id, newOrder) diff --git a/client/src/utils/dayMerge.test.ts b/client/src/utils/dayMerge.test.ts index b62be0286..71c6307df 100644 --- a/client/src/utils/dayMerge.test.ts +++ b/client/src/utils/dayMerge.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from 'vitest' -import { parseTimeToMinutes, getSpanPhase, hidesOnMiddleDay, getTransportRouteEndpoints, getDisplayTimeForDay, getTransportForDay, getAssignmentReservations, pinnedAway, stopDayIds, getPlaceBookings, getMergedItems, chronoKeyOf, nightRowsOf, rideSeatKey, seatTimedDrop, stayStartingOn, storedRideSlot, timedSlot, type MergedItem } from './dayMerge' +import { parseTimeToMinutes, getSpanPhase, hidesOnMiddleDay, getTransportRouteEndpoints, getDisplayTimeForDay, getTransportForDay, getAssignmentReservations, pinnedAway, stopDayIds, getPlaceBookings, getMergedItems, chronoKeyOf, nightRowsOf, rideSeatKey, seatTimedDrop, yieldTimedBookings, stayStartingOn, storedRideSlot, timedSlot, type MergedItem } from './dayMerge' import { planMergedOrder, withTransportPositions } from './mergedOrder' describe('parseTimeToMinutes', () => { @@ -646,6 +646,52 @@ describe('seatTimedDrop', () => { const order = draw(setup()) expect(seatTimedDrop(order, 1, DAY)).toEqual(order) }) + + // #2983: a flight listed below the day's untimed stops held every slot among them. + const untimedDay = (rides: ReturnType[]): Day => ({ + stops: [stop(1, 'Hotel'), stop(2, 'Shrine'), stop(3, 'Crossing'), stop(4, 'Tower')].map((a, i) => ({ ...a, order_index: i })), + rides, + notes: [], + }) + + it('a ride dropped among untimed stops stays there, and an earlier booking below them makes room ahead of it', () => { + const day = untimedDay([ride(101, '06:30', 3.5), ride(102, '13:00', 3.6)]) + expect(draw(day).map(label)).toEqual(['Hotel', 'Shrine', 'Crossing', 'Tower', 'ride 06:30', 'ride 13:00']) + const { seated, drawn } = drop(day, isRide(102), isStop('Shrine')) + expect(drawn).toEqual(seated) + expect(drawn).toEqual(['Hotel', 'Shrine', 'ride 06:30', 'ride 13:00', 'Crossing', 'Tower']) + }) + + it('a later booking ahead of the drop moves behind it, and the stops keep their order', () => { + const day = untimedDay([ride(101, '09:00', -0.5), ride(102, '18:00', 1.5)]) + expect(draw(day).map(label)).toEqual(['ride 09:00', 'Hotel', 'Shrine', 'ride 18:00', 'Crossing', 'Tower']) + const { seated, drawn } = drop(day, isRide(101), isStop('Tower')) + expect(drawn).toEqual(seated) + expect(drawn).toEqual(['Hotel', 'Shrine', 'Crossing', 'Tower', 'ride 09:00', 'ride 18:00']) + }) + + it('a timed stop in the way still sends the ride back to its time, the bookings stay put', () => { + const day = untimedDay([ride(101, '06:30', 3.5), ride(102, '13:00', 3.6)]) + day.stops[2] = { ...day.stops[2], place: { name: 'Crossing', place_time: '12:00' } } + expect(draw(day).map(label)).toEqual(['Hotel', 'Shrine', 'ride 06:30', 'Crossing', 'Tower', 'ride 13:00']) + const { seated, drawn } = drop(day, isRide(102), isStop('Shrine')) + expect(drawn).toEqual(seated) + expect(drawn).toEqual(['Hotel', 'Shrine', 'ride 06:30', 'Crossing', 'ride 13:00', 'Tower']) + }) +}) + +describe('yieldTimedBookings', () => { + const DAY = 1 + const row = (type: MergedItem['type'], data: Record): MergedItem => ({ type, sortKey: 0, data }) + const place = (id: number) => row('place', { id, place: { place_time: null } }) + const booking = (id: number, time: string | null) => row('transport', { id, day_id: DAY, reservation_time: time }) + + it('leaves an untimed row, a stop and an order without a booking out of place to the caller', () => { + const order = [place(1), booking(2, null), booking(3, '2026-11-20T08:00')] + expect(yieldTimedBookings(order, 1, DAY)).toBeNull() + expect(yieldTimedBookings(order, 0, DAY)).toBeNull() + expect(yieldTimedBookings(order, 2, DAY)).toBeNull() + }) }) diff --git a/client/src/utils/dayMerge.ts b/client/src/utils/dayMerge.ts index 83a8036c4..b6d143b79 100644 --- a/client/src/utils/dayMerge.ts +++ b/client/src/utils/dayMerge.ts @@ -428,20 +428,65 @@ function zonedClockSlots( return slots } +/** Whether the list draws `order` as it stands. */ +function drawnAsIs(order: readonly MergedItem[], dayId: number, getDisplayTime: DisplayTimeOf): boolean { + return applyChronoOrder([...order], dayId, getDisplayTime).every((it, i) => it === order[i]) +} + +/** + * A day order with the row at `index` kept where it is, and the other timed bookings it + * puts out of time order moved next to it: the ones due earlier right ahead of it, the + * later ones right behind it, each group in the order it had. Stops and notes never move. + * Null when the row has no time, when no booking is out of order, or when the result is + * still not the order the list draws, which is when a timed stop or note stands against it. + * + * A booking nobody can drag otherwise blocks every slot on its far side: with a 06:30 + * flight listed below the day's untimed stops, a 13:00 transit dropped between two of + * them went back behind the flight on every drop (#2983). + */ +export function yieldTimedBookings( + order: readonly MergedItem[], + index: number, + dayId: number, + getDisplayTime: DisplayTimeOf = getDisplayTimeForDay +): MergedItem[] | null { + const moved = order[index] + if (!moved || moved.type === 'place') return null + const keyOf = chronoKeyOf(order, dayId, getDisplayTime) + const own = keyOf(moved) + if (own === null) return null + const ahead: MergedItem[] = [] + const behind: MergedItem[] = [] + order.forEach((it, i) => { + if (it === moved || it.type !== 'transport') return + const key = keyOf(it) + if (key === null) return + if (i > index && key < own) ahead.push(it) + else if (i < index && key > own) behind.push(it) + }) + if (!ahead.length && !behind.length) return null + const yielding = new Set([...ahead, ...behind]) + const kept = order.filter(it => !yielding.has(it)) + const at = kept.indexOf(moved) + const result = [...kept.slice(0, at), ...ahead, moved, ...behind, ...kept.slice(at + 1)] + return drawnAsIs(result, dayId, getDisplayTime) ? result : null +} + /** * A day order with a dragged booking or note at `index`, moved to the nearest slot the * list draws it in. A row with a time is drawn by it, and the untimed rows behind it * take that time too. Dropped against its time, a train went back to its time on the * next render and took every untimed stop behind the drop with it, and the next drag - * stored that order (#2631). So it lands as close to the drop as its time allows and - * nothing else moves. A row without a time, or one the list draws where it was - * dropped, is returned as it came. + * stored that order (#2631). So it stays where it was dropped when only other bookings + * stand against its time, and they make room (`yieldTimedBookings`); against a timed + * stop or note it lands as close to the drop as its time allows and nothing else moves. + * A row without a time, or one the list draws where it was dropped, is returned as it came. */ export function seatTimedDrop( order: readonly MergedItem[], index: number, dayId: number, - getDisplayTime: (r: MergedItem['data'], dayId: number) => string | null = getDisplayTimeForDay + getDisplayTime: DisplayTimeOf = getDisplayTimeForDay ): MergedItem[] { const moved = order[index] if (!moved || moved.type === 'place') return [...order] @@ -449,16 +494,18 @@ export function seatTimedDrop( ? parseTimeToMinutes(moved.data?.time) : parseTimeToMinutes(getDisplayTime(moved.data, dayId)) if (minutes === null) return [...order] + if (drawnAsIs(order, dayId, getDisplayTime)) return [...order] + const yielded = yieldTimedBookings(order, index, dayId, getDisplayTime) + if (yielded) return yielded const rest = order.filter((_, i) => i !== index) - const drawnAsIs = (at: number): MergedItem[] | null => { + const seatAt = (at: number): MergedItem[] | null => { const candidate = [...rest.slice(0, at), moved, ...rest.slice(at)] - const drawn = applyChronoOrder(candidate, dayId, getDisplayTime) - return drawn.every((it, i) => it === candidate[i]) ? candidate : null + return drawnAsIs(candidate, dayId, getDisplayTime) ? candidate : null } - for (let dist = 0; dist <= rest.length; dist++) { - for (const at of dist === 0 ? [index] : [index - dist, index + dist]) { + for (let dist = 1; dist <= rest.length; dist++) { + for (const at of [index - dist, index + dist]) { if (at < 0 || at > rest.length) continue - const seated = drawnAsIs(at) + const seated = seatAt(at) if (seated) return seated } } diff --git a/client/tests/unit/mobile/trip/useMPlanTimeline.test.ts b/client/tests/unit/mobile/trip/useMPlanTimeline.test.ts index f71a29709..4e4b24599 100644 --- a/client/tests/unit/mobile/trip/useMPlanTimeline.test.ts +++ b/client/tests/unit/mobile/trip/useMPlanTimeline.test.ts @@ -12,7 +12,7 @@ import { buildPlanner, buildTripActions } from '../../../helpers/mobileTrip' import { resetAllStores, seedStore } from '../../../helpers/store' import { act, renderHook, waitFor } from '../../../helpers/render' -// FE-MOB-PLTL-001 to FE-MOB-PLTL-052 +// FE-MOB-PLTL-001 to FE-MOB-PLTL-054 // The connector calculation is its own hook with real OSRM calls — stubbed here so // the timeline sees exactly the legs a test wants to match against. @@ -337,6 +337,41 @@ describe('useMPlanTimeline', () => { expect(planner.toast.info).not.toHaveBeenCalled() }) + // #2983: a 06:30 flight listed below the day's untimed stops blocked every slot of a + // 13:00 transit among them. The flight makes room ahead of the transit instead. + const FLIGHT_EARLY = buildReservation({ + id: 61, type: 'flight', title: 'Flight', day_id: 2, reservation_time: '2026-05-02T06:30', day_positions: { 2: 1.5 }, + }) + const TRANSIT_NOON = buildReservation({ + id: 62, type: 'transit', title: 'Transit', day_id: 2, reservation_time: '2026-05-02T13:00', day_positions: { 2: 1.6 }, + }) + + it('FE-MOB-PLTL-053: keeps a timed booking where it was moved and lets an earlier booking make room', async () => { + seedStore(useTripStore, { reservations: [FLIGHT_EARLY, TRANSIT_NOON] }) + const planner = makePlanner({ assignments: { '2': [A_MUSEUM, A_PARK] }, reservations: [FLIGHT_EARLY, TRANSIT_NOON] }) + const { result } = await renderTimeline(planner) + expect(result.current.merged.map(m => m.data.id)).toEqual([11, 12, 61, 62]) + + await act(async () => { result.current.moveRowTo(result.current.merged[3], 1) }) + + await waitFor(() => expect(planner.tripActions.updateReservationPositions).toHaveBeenCalledWith( + 1, [{ id: 61, day_plan_position: 1 / 3 }, { id: 62, day_plan_position: 2 / 3 }], 2, + )) + expect(planner.tripActions.reorderAssignments).toHaveBeenCalledWith(1, 2, [11, 12]) + expect(planner.toast.info).not.toHaveBeenCalled() + }) + + it('FE-MOB-PLTL-054: still refuses a move the earlier booking would only undo', async () => { + seedStore(useTripStore, { reservations: [FLIGHT_EARLY, TRANSIT_NOON] }) + const planner = makePlanner({ assignments: { '2': [A_MUSEUM, A_PARK] }, reservations: [FLIGHT_EARLY, TRANSIT_NOON] }) + const { result } = await renderTimeline(planner) + + await act(async () => { result.current.moveRow(result.current.merged[3], 'up') }) + + expect(planner.toast.info).toHaveBeenCalledWith('dayplan.cannotBreakChronology') + expect(planner.tripActions.updateReservationPositions).not.toHaveBeenCalled() + }) + it('FE-MOB-PLTL-021: persists note and transport positions alongside the reorder', async () => { const bus = buildReservation({ id: 51, type: 'bus', title: 'Bus 13A', day_id: 2, day_positions: { 2: 1.5 }, From d2c7d8325613c49174aa9289aa956cdaec29236e Mon Sep 17 00:00:00 2001 From: Maurice Date: Thu, 5 Nov 2026 12:19:45 +0100 Subject: [PATCH 002/589] fix(collections): keep a place's name readable next to long labels A place row was a three-column grid whose last column held the labels, the category and the status, none of which could shrink. With two or three long labels the name got what was left, often one letter or nothing, and the status pill ran out of the card. The row now wraps: the name keeps at least 11rem, and when the labels, category and status do not fit beside it they go to a line of their own under it and wrap there. A label or category too long for its chip ends in an ellipsis instead of being cut mid-letter. Kept tours use the same row and get the same layout. Closes #2981 --- client/e2e/collection-row-names-2981.spec.ts | 92 +++++++++++++++++++ .../components/Collections/CollectionList.tsx | 4 +- client/src/styles/collections.css | 14 ++- 3 files changed, 105 insertions(+), 5 deletions(-) create mode 100644 client/e2e/collection-row-names-2981.spec.ts diff --git a/client/e2e/collection-row-names-2981.spec.ts b/client/e2e/collection-row-names-2981.spec.ts new file mode 100644 index 000000000..4c5857193 --- /dev/null +++ b/client/e2e/collection-row-names-2981.spec.ts @@ -0,0 +1,92 @@ +import { expect, test, type Locator } from '@playwright/test'; + +// #2981: labels, category and status took the whole row, so a place with two or +// three long labels showed one letter of its name or none, and the status pill +// ran out of the card. Measured in a real browser because the layout is the bug. +const PLACES = [ + { name: 'Oceanario de Lisboa', labels: ['Core shortlist', 'Heritage specialist', 'Pair with another stop'] }, + { name: 'Cove of Ursa', labels: ['Heritage specialist', 'Pair with another stop'] }, + { name: 'A Vida Portuguesa', labels: ['Flagship', 'Market', 'Core shortlist', 'Pair with another stop'] }, + { name: 'Torre de Belem', labels: [] as string[] }, +]; + +async function expectInside(row: Locator) { + const escapes = await row.evaluate((el) => { + const box = el.getBoundingClientRect(); + return Array.from(el.querySelectorAll('*')).filter((child) => { + const r = child.getBoundingClientRect(); + return r.width > 0 && (r.left < box.left - 0.5 || r.right > box.right + 0.5); + }).length; + }); + expect(escapes).toBe(0); +} + +for (const viewport of [ + { width: 1400, height: 900 }, + { width: 1024, height: 800 }, +]) { + test(`place names stay readable next to long labels at ${viewport.width}px`, async ({ page }) => { + await page.setViewportSize(viewport); + const addonsResponse = await page.request.get('/api/admin/addons'); + expect(addonsResponse.ok()).toBeTruthy(); + const { addons } = await addonsResponse.json(); + const original = addons.find((addon: { id: string }) => addon.id === 'collections'); + expect(original).toBeDefined(); + let collectionId: number | undefined; + + try { + expect((await page.request.put('/api/admin/addons/collections', { data: { enabled: true } })).ok()).toBeTruthy(); + const created = await page.request.post('/api/addons/collections', { data: { name: `Rows ${viewport.width}` } }); + expect(created.ok()).toBeTruthy(); + const body = await created.json(); + collectionId = (body.collection ?? body).id as number; + + const labelIds = new Map(); + for (const name of new Set(PLACES.flatMap((p) => p.labels))) { + const res = await page.request.post('/api/addons/collections/labels', { + data: { collection_id: collectionId, name, color: '#2563eb' }, + }); + expect(res.ok(), `label ${name}`).toBeTruthy(); + const label = await res.json(); + labelIds.set(name, (label.label ?? label).id); + } + for (const place of PLACES) { + const res = await page.request.post('/api/addons/collections/places', { + data: { + collection_id: collectionId, + name: place.name, + address: 'Rua Anchieta 11, 1200-023 Lisboa, Portugal', + lat: 38.71, + lng: -9.14, + }, + }); + expect(res.ok(), `place ${place.name}`).toBeTruthy(); + const saved = await res.json(); + if (!place.labels.length) continue; + const assign = await page.request.post('/api/addons/collections/labels/assign', { + data: { label_ids: place.labels.map((l) => labelIds.get(l)), place_ids: [(saved.place ?? saved).id] }, + }); + expect(assign.ok()).toBeTruthy(); + } + + await page.goto(`/collections/${collectionId}`); + const rows = page.locator('.col-lrow'); + await expect(rows).toHaveCount(PLACES.length); + for (const place of PLACES) { + const row = rows.filter({ hasText: place.name }); + const name = row.locator('.li .t'); + await expect(name).toHaveText(place.name); + // The whole name fits: it is not cut to an ellipsis. + expect(await name.evaluate((el) => el.scrollWidth <= el.clientWidth + 1)).toBe(true); + await expectInside(row); + } + } finally { + if (collectionId !== undefined) { + expect((await page.request.delete(`/api/addons/collections/${collectionId}`)).ok()).toBeTruthy(); + } + expect( + (await page.request.put('/api/admin/addons/collections', { data: { enabled: !!original.enabled } })).ok() + ).toBeTruthy(); + } + }); +} diff --git a/client/src/components/Collections/CollectionList.tsx b/client/src/components/Collections/CollectionList.tsx index 1ba3f50b0..d7dfc3019 100644 --- a/client/src/components/Collections/CollectionList.tsx +++ b/client/src/components/Collections/CollectionList.tsx @@ -70,7 +70,7 @@ export default function CollectionList({
{placeLabels.slice(0, 2).map(l => ( - {l.name} + {l.name} ))} {placeLabels.length > 2 && l.name).join(', ')}>+{placeLabels.length - 2}} @@ -79,7 +79,7 @@ export default function CollectionList({ return ( <> - {place.category.name} + {place.category.name} diff --git a/client/src/styles/collections.css b/client/src/styles/collections.css index 9533458b7..391be0f35 100644 --- a/client/src/styles/collections.css +++ b/client/src/styles/collections.css @@ -254,8 +254,12 @@ /* ----------------- list view ----------------- */ .trek-dash .col-listview { display: flex; flex-direction: column; gap: 7px; } +/* A row is the place's tile, its name and address, and an end group of labels, category + and status. The name keeps at least 11rem; when the end group does not fit beside it, + the group goes to a line of its own and wraps there, so a place with long labels still + shows which place it is and its status stays inside the card (#2981). */ .trek-dash .col-lrow { - display: grid; grid-template-columns: 40px minmax(0, 1fr) auto; gap: 14px; align-items: center; + display: flex; flex-wrap: wrap; column-gap: 14px; row-gap: 8px; align-items: center; padding: 10px 14px; border-radius: var(--r-md); background: var(--glass-bg); border: 1px solid var(--glass-border); box-shadow: var(--sh-xs); cursor: pointer; transition: transform .12s, box-shadow .15s, border-color .15s; @@ -265,15 +269,19 @@ .trek-dash .col-lrow:hover { transform: translateX(3px); box-shadow: var(--sh-sm); } /* Inset ring so the highlight is never clipped by the column's overflow. */ .trek-dash .col-lrow.sel { border-color: var(--accent); box-shadow: inset 0 0 0 1.5px var(--accent); } -.trek-dash .col-lrow .li { min-width: 0; } +.trek-dash .col-lrow > :first-child { flex: none; } +/* The select box is narrower than a tile; the margin keeps the names lined up. */ +.trek-dash .col-lrow > .col-lcheck { margin-inline-end: 18px; } +.trek-dash .col-lrow .li { flex: 1 1 11rem; min-width: 0; } .trek-dash .col-lrow .li .t { font-size: 14px; font-weight: 600; color: var(--ink); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .trek-dash .col-lrow .li .s { font-size: 12px; color: var(--ink-3); margin-top: 2px; display: flex; align-items: center; gap: 5px; overflow: hidden; } .trek-dash .col-lrow .li .s span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } /* The pin before the address must not be squeezed by a long address. */ .trek-dash .col-lrow .li .s svg { flex-shrink: 0; } -.trek-dash .col-lrow-end { display: flex; align-items: center; gap: 8px; flex-shrink: 0; } +.trek-dash .col-lrow-end { display: flex; flex-wrap: wrap; justify-content: flex-end; align-items: center; gap: 6px 8px; flex: 0 1 auto; max-width: 100%; min-width: 0; margin-inline-start: auto; } .trek-dash .col-lrow-cat { display: inline-flex; align-items: center; gap: 5px; max-width: 130px; padding: 3px 9px; border-radius: 999px; font-size: 11px; font-weight: 600; white-space: nowrap; overflow: hidden; color: var(--cat, var(--accent)); background: color-mix(in oklch, var(--cat, var(--accent)) 14%, transparent); } .trek-dash .col-lrow-cat svg { flex-shrink: 0; } +.trek-dash .col-lrow-txt { min-width: 0; overflow: hidden; text-overflow: ellipsis; } .trek-dash .col-lrow-div { width: 1px; height: 18px; flex-shrink: 0; background: var(--line-2); } /* A kept tour (LIB-03) is a row of the same list: its grade tile stands where From 1c54d7d6c1acbb7daf0e4964ef416fd012d4cbf6 Mon Sep 17 00:00:00 2001 From: Maurice Date: Thu, 5 Nov 2026 12:46:16 +0100 Subject: [PATCH 003/589] fix(collections): give place rows two fixed lines and fit labels to the room The first fix let a row wrap freely, which on a list beside the map put the status on a line of its own and broke every row differently. A row is now laid out the same way each time: on a list narrower than 760px the name, address and status take the first line and the category and labels one line below; a wider list keeps them on one line. The row shows as many labels as it has room for, category first, and a "+N" chip names the rest in its tooltip, so a wide screen shows every label. Chips that cut a name short say it in full in their tooltip. The label strip over the map hid the labels that did not fit behind a scroll with no scrollbar. It now folds into a "Labels" button that opens them as a list when the bar has no room for all of them, and unfolds again when the room is back. The filter row stays on one line on a desktop, a dropdown at its default keeping only its icon when narrow, and the select bar's actions keep their icons with the words in a tooltip when the bar is too narrow for them. --- client/e2e/collection-row-names-2981.spec.ts | 13 ++ .../Collections/CollectionFilterBar.tsx | 2 +- .../Collections/CollectionLabelFilter.tsx | 168 ++++++++++++++---- .../components/Collections/CollectionList.tsx | 24 +-- .../Collections/CollectionPlaceTags.tsx | 145 +++++++++++++++ client/src/pages/CollectionsPage.tsx | 20 +-- client/src/styles/collections.css | 87 +++++++-- 7 files changed, 380 insertions(+), 79 deletions(-) create mode 100644 client/src/components/Collections/CollectionPlaceTags.tsx diff --git a/client/e2e/collection-row-names-2981.spec.ts b/client/e2e/collection-row-names-2981.spec.ts index 4c5857193..cbdd76e0e 100644 --- a/client/e2e/collection-row-names-2981.spec.ts +++ b/client/e2e/collection-row-names-2981.spec.ts @@ -14,6 +14,8 @@ async function expectInside(row: Locator) { const escapes = await row.evaluate((el) => { const box = el.getBoundingClientRect(); return Array.from(el.querySelectorAll('*')).filter((child) => { + // The strip's hidden measuring copy is meant to run past the bar. + if (child.closest('[aria-hidden="true"]')) return false; const r = child.getBoundingClientRect(); return r.width > 0 && (r.left < box.left - 0.5 || r.right > box.right + 0.5); }).length; @@ -22,6 +24,7 @@ async function expectInside(row: Locator) { } for (const viewport of [ + { width: 1920, height: 1000 }, { width: 1400, height: 900 }, { width: 1024, height: 800 }, ]) { @@ -79,7 +82,17 @@ for (const viewport of [ // The whole name fits: it is not cut to an ellipsis. expect(await name.evaluate((el) => el.scrollWidth <= el.clientWidth + 1)).toBe(true); await expectInside(row); + // Every label is either on the row or counted by its "+N" chip. + const shown = await row.locator('.col-lrow-label').count(); + const more = await row + .locator('.col-lrow-more') + .textContent() + .catch(() => null); + expect(shown + (more ? Number(more.replace('+', '')) : 0)).toBe(place.labels.length); } + // The map's label strip stays inside the map: whole, or folded into its button. + const topbar = page.locator('.col-map-topbar'); + if (await topbar.count()) await expectInside(topbar); } finally { if (collectionId !== undefined) { expect((await page.request.delete(`/api/addons/collections/${collectionId}`)).ok()).toBeTruthy(); diff --git a/client/src/components/Collections/CollectionFilterBar.tsx b/client/src/components/Collections/CollectionFilterBar.tsx index 266539383..1293b236e 100644 --- a/client/src/components/Collections/CollectionFilterBar.tsx +++ b/client/src/components/Collections/CollectionFilterBar.tsx @@ -35,7 +35,7 @@ function Dropdown({ current, options, onSelect, lead }: { const cur = options.find(o => o.key === current) ?? options[0] return (
- + ) + })} + + ) +} + +/** + * Whether the map strip has to fold into its button: true once its chips need more room + * than the slot beside the map's other controls. Measured on a hidden copy, so the strip + * unfolds again as soon as the room comes back. + */ +function useFolds(enabled: boolean) { + const slotRef = useRef(null) + const measureRef = useRef(null) + const [folded, setFolded] = useState(false) + useLayoutEffect(() => { + const slot = slotRef.current + const measure = measureRef.current + if (!enabled || !slot || !measure) return + const check = () => setFolded(measure.scrollWidth > slot.clientWidth + 1) + check() + if (typeof ResizeObserver === 'undefined') return + const observer = new ResizeObserver(check) + observer.observe(slot) + observer.observe(measure) + return () => observer.disconnect() + }, [enabled]) + return { slotRef, measureRef, folded } +} + +/** Open state of the folded strip's list: closed by a click beside it or Escape, like the filter row's dropdowns. */ +function useFoldList(ref: React.RefObject) { + const [open, setOpen] = useState(false) + useEffect(() => { + if (!open) return + const onDoc = (e: MouseEvent) => { if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false) } + const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') setOpen(false) } + document.addEventListener('mousedown', onDoc) + document.addEventListener('keydown', onKey) + return () => { document.removeEventListener('mousedown', onDoc); document.removeEventListener('keydown', onKey) } + }, [open, ref]) + return { open, setOpen } +} + /** * The label filter, in one place because it has two homes. * * Labels are an axis of their own next to status, category and rating, so they * are grouped into a tray instead of joining the row as more loose buttons. On - * a desktop it rides in the map's top bar, where there is room to spare; the - * filter row keeps it whenever no map is on screen, so it never becomes - * unreachable. + * a desktop it rides in the map's top bar; when the bar has no room for every + * label it folds into one button that opens them as a list, instead of hiding + * the last ones behind a scroll nobody sees. The filter row keeps it whenever + * no map is on screen, so it never becomes unreachable. */ export default function CollectionLabelFilter({ labelOptions, labelFilter, onLabelFilter, canManageLabels = false, onManageLabels, variant = 'bar', t, }: CollectionLabelFilterProps): React.ReactElement { - return ( -
+ const onMap = variant === 'map' + const { slotRef, measureRef, folded } = useFolds(onMap) + const fold = useFoldList(slotRef) + const toggle = (id: number) => onLabelFilter(labelFilter.includes(id) ? labelFilter.filter(x => x !== id) : [...labelFilter, id]) + const manageLabel = labelOptions.length ? t('collections.labels.manage') : t('collections.labels.add') + const manage = canManageLabels && onManageLabels && ( + + ) + + const tray = ( +
+ ) + if (!onMap) return tray + + const active = labelFilter.filter(id => labelOptions.some(l => l.id === id)).length + return ( +
+ {!folded ? tray : ( + <> - ) - })} - {canManageLabels && onManageLabels && ( - + {fold.open && ( +
+ {labelOptions.map(l => { + const on = labelFilter.includes(l.id) + return ( + + ) + })} + {canManageLabels && onManageLabels && ( + + )} +
+ )} + )} +
) } diff --git a/client/src/components/Collections/CollectionList.tsx b/client/src/components/Collections/CollectionList.tsx index d7dfc3019..af34ec6fd 100644 --- a/client/src/components/Collections/CollectionList.tsx +++ b/client/src/components/Collections/CollectionList.tsx @@ -3,8 +3,8 @@ import { Check, MapPin } from 'lucide-react' import type { CollectionPlace, CollectionStatus, CollectionLabel } from '@trek/shared' import type { TranslationFn } from '../../types' import PlaceAvatar from '../shared/PlaceAvatar' -import { getCategoryIcon } from '../shared/categoryIcons' import StatusBadge from './StatusBadge' +import CollectionPlaceTags from './CollectionPlaceTags' interface CollectionListProps { places: CollectionPlace[] @@ -51,7 +51,7 @@ export default function CollectionList({ tabIndex={0} onClick={() => (selectMode ? onToggleSelect(place.id) : onOpenPlace(place.id))} onKeyDown={e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); if (selectMode) onToggleSelect(place.id); else onOpenPlace(place.id) } }} - className={`col-lrow${active || selected ? ' sel' : ''}`} + className={`col-lrow col-lrow-place${active || selected ? ' sel' : ''}`} > {selectMode ? ( {selected && } @@ -67,24 +67,8 @@ export default function CollectionList({
)}
-
- {placeLabels.slice(0, 2).map(l => ( - - {l.name} - - ))} - {placeLabels.length > 2 && l.name).join(', ')}>+{placeLabels.length - 2}} - {place.category?.name && (() => { - const CatIcon = getCategoryIcon(place.category.icon ?? undefined) - return ( - <> - - {place.category.name} - - - - ) - })()} + +
onStatusChange(place.id, next)} t={t} />
diff --git a/client/src/components/Collections/CollectionPlaceTags.tsx b/client/src/components/Collections/CollectionPlaceTags.tsx new file mode 100644 index 000000000..983bcc16f --- /dev/null +++ b/client/src/components/Collections/CollectionPlaceTags.tsx @@ -0,0 +1,145 @@ +import type { CollectionLabel, CollectionPlace } from '@trek/shared'; +import React, { useEffect, useLayoutEffect, useRef, useState } from 'react'; +import { getCategoryIcon } from '../shared/categoryIcons'; +import { Tooltip } from '../shared/Tooltip'; + +/** + * One observer for every row and chip of a list, so a list of hundreds of places does + * not hold one per element. + */ +const sizeWatch = new Map void>(); +let sizeObserver: ResizeObserver | null = null; +function watchSize(el: Element, onResize: () => void): () => void { + if (typeof ResizeObserver === 'undefined') return () => {}; + sizeObserver ??= new ResizeObserver((entries) => { + for (const entry of entries) sizeWatch.get(entry.target)?.(); + }); + sizeWatch.set(el, onResize); + sizeObserver.observe(el); + return () => { + sizeWatch.delete(el); + sizeObserver?.unobserve(el); + }; +} + +/** + * The tooltip of a label or category chip: only while the chip cuts its name short, + * since one repeating the words on screen says nothing. + */ +function ChipTooltip({ + label, + children, +}: { + label: string; + children: React.ReactElement & React.RefAttributes>; +}): React.ReactElement { + const [cut, setCut] = useState(false); + const ref = useRef(null); + useEffect(() => { + const text = ref.current?.querySelector('.col-lrow-txt'); + if (!text) return undefined; + return watchSize(text, () => setCut(text.scrollWidth > text.clientWidth + 1)); + }, []); + return ( + + {React.cloneElement(children, { ref })} + + ); +} + +/** The room a "+N" chip takes, held free while the labels are fitted. */ +const MORE_CHIP = 34; + +/** + * How many labels fit beside the category in `row`, measured with every label drawn at + * its own width: as many as the row holds with room left for the "+N" chip, and at + * least one, which then shortens its name. + */ +function labelsThatFit(row: HTMLElement): number { + const gap = parseFloat(getComputedStyle(row).columnGap) || 0; + const labels = Array.from(row.querySelectorAll('.col-lrow-label')); + const fixed = Array.from(row.querySelectorAll('.col-lrow-cat, .col-lrow-div')) + .filter((el) => el.offsetWidth > 0) + .reduce((sum, el) => sum + el.offsetWidth + gap, 0); + let used = fixed; + let fit = 0; + for (let i = 0; i < labels.length; i++) { + const left = labels.length - i - 1; + const need = used + labels[i].offsetWidth + (left > 0 ? gap + MORE_CHIP : 0); + if (need > row.clientWidth && i > 0) break; + used += labels[i].offsetWidth + gap; + fit = i + 1; + } + return fit; +} + +/** + * A place row's category and labels, on one line that never wraps (#2981). The category + * comes first, then as many labels as the row has room for, then a "+N" chip naming the + * rest in its tooltip, so a wide list shows every label and a narrow one the first. + */ +export default function CollectionPlaceTags({ + place, + labels, +}: { + place: CollectionPlace; + labels: CollectionLabel[]; +}): React.ReactElement | null { + const ref = useRef(null); + const [fit, setFit] = useState(labels.length); + const [measuring, setMeasuring] = useState(true); + const labelKey = labels.map((l) => `${l.id}:${l.name}`).join('|'); + const category = place.category?.name ? place.category : null; + + useLayoutEffect(() => { + setMeasuring(true); + }, [labelKey, category?.name]); + + useLayoutEffect(() => { + const row = ref.current; + if (!measuring || !row) return; + setFit(labelsThatFit(row)); + setMeasuring(false); + }, [measuring]); + + useEffect(() => { + const row = ref.current; + if (!row) return undefined; + let width = row.clientWidth; + return watchSize(row, () => { + if (row.clientWidth === width) return; + width = row.clientWidth; + setMeasuring(true); + }); + }, []); + + if (!labels.length && !category) return null; + const shown = measuring ? labels : labels.slice(0, Math.max(1, fit)); + const hidden = labels.slice(shown.length); + const CatIcon = category ? getCategoryIcon(category.icon ?? undefined) : null; + + return ( +
+ {category && CatIcon && ( + + + {category.name} + + + )} + {shown.map((l) => ( + + + {l.name} + + + ))} + {hidden.length > 0 && ( + l.name).join(', ')} placement="top"> + +{hidden.length} + + )} + +
+ ); +} diff --git a/client/src/pages/CollectionsPage.tsx b/client/src/pages/CollectionsPage.tsx index 5118b19e2..2d40dcf99 100644 --- a/client/src/pages/CollectionsPage.tsx +++ b/client/src/pages/CollectionsPage.tsx @@ -294,24 +294,24 @@ function CollectionsPageDesktop(): React.ReactElement { {t('collections.selectedCount', { count: c.selectedIds.length })}
{c.canEdit && isRealList && ( - )} {c.canDelete && ( - )} - - {c.canDelete && ( - )} ); + const button = screen.getByRole('button', { name: 'Go' }); + + fireEvent.pointerDown(button, { pointerType: 'mouse', button: 0, clientX: 100, clientY: 100 }); + fireEvent.pointerMove(window, { pointerType: 'mouse', clientX: 100, clientY: 140 }); + fireEvent.pointerMove(window, { pointerType: 'mouse', clientX: 100, clientY: 300 }); + expect(dialog.style.transform).toBe('translateY(160px)'); + fireEvent.pointerUp(window, { pointerType: 'mouse', clientX: 100, clientY: 300 }); + fireEvent.click(button); + + expect(onClose).toHaveBeenCalledTimes(1); + expect(pressed).not.toHaveBeenCalled(); + }); + + it('FE-MOB-SHEET-028: a plain click on a button in the sheet still presses it', () => { + const pressed = vi.fn(); + renderBottom(vi.fn(), ); + const button = screen.getByRole('button', { name: 'Go' }); + + fireEvent.pointerDown(button, { pointerType: 'mouse', button: 0, clientX: 100, clientY: 100 }); + fireEvent.pointerUp(window, { pointerType: 'mouse', clientX: 100, clientY: 101 }); + fireEvent.click(button); + + expect(pressed).toHaveBeenCalledTimes(1); + }); + it('FE-MOB-SHEET-026: the docked sheet rises from below, the card pops in place', () => { const { dialog } = renderBottom(); expect(dialog.className).toContain('m-sheet-up'); From b07b38b5b74d0c6eb5c339f61bd81059ec5f4af2 Mon Sep 17 00:00:00 2001 From: Maurice Date: Fri, 6 Nov 2026 12:25:29 +0100 Subject: [PATCH 054/589] feat(map): never leave an offline map grey, whatever the basemap Offline, a Mapbox map, another OpenFreeMap style or a raster template the device cannot serve now switches to the stored OpenFreeMap basemap, light or dark with the colour scheme, keeping every marker, route and track, with a small Offline map pill. It switches back once the connection returns. "Prepare for offline" stores that basemap's region for every trip, whatever the provider, and both styles' sprites and glyphs, including the scripts a trip in East or South Asia labels its places in. The vector prefetch keeps to OpenFreeMap's download rules (four requests at a time, 50 MB per run), raster tiles are no longer prefetched from OpenStreetMap's own servers, which their policy forbids, nor inside the iOS app, which has no service worker to serve them. --- .../Map/MapViewAuto.offline.test.tsx | 123 ++++++++++++++++++ client/src/components/Map/MapViewAuto.tsx | 61 +++++++-- client/src/components/Map/MapViewGL.tsx | 5 +- .../src/components/Map/offlineBasemap.test.ts | 33 +++++ client/src/components/Map/offlineBasemap.ts | 54 ++++++++ client/src/sync/glPrefetcher.ts | 114 ++++++++++++---- client/src/sync/tilePrefetcher.ts | 38 +++++- client/tests/unit/sync/tilePrefetcher.test.ts | 57 ++++++++ shared/src/i18n/ar/map.ts | 1 + shared/src/i18n/az/map.ts | 1 + shared/src/i18n/br/map.ts | 1 + shared/src/i18n/ca/map.ts | 1 + shared/src/i18n/cs/map.ts | 1 + shared/src/i18n/de/map.ts | 1 + shared/src/i18n/en/map.ts | 1 + shared/src/i18n/es/map.ts | 1 + shared/src/i18n/et/map.ts | 1 + shared/src/i18n/fr/map.ts | 1 + shared/src/i18n/gr/map.ts | 1 + shared/src/i18n/he/map.ts | 1 + shared/src/i18n/hu/map.ts | 1 + shared/src/i18n/id/map.ts | 1 + shared/src/i18n/it/map.ts | 1 + shared/src/i18n/ja/map.ts | 1 + shared/src/i18n/ko/map.ts | 1 + shared/src/i18n/nl/map.ts | 1 + shared/src/i18n/pl/map.ts | 1 + shared/src/i18n/ru/map.ts | 1 + shared/src/i18n/sk/map.ts | 1 + shared/src/i18n/sv/map.ts | 1 + shared/src/i18n/th/map.ts | 1 + shared/src/i18n/tr/map.ts | 1 + shared/src/i18n/uk/map.ts | 1 + shared/src/i18n/vi/map.ts | 1 + shared/src/i18n/zh-TW/map.ts | 1 + shared/src/i18n/zh/map.ts | 1 + 36 files changed, 473 insertions(+), 40 deletions(-) create mode 100644 client/src/components/Map/MapViewAuto.offline.test.tsx create mode 100644 client/src/components/Map/offlineBasemap.test.ts create mode 100644 client/src/components/Map/offlineBasemap.ts diff --git a/client/src/components/Map/MapViewAuto.offline.test.tsx b/client/src/components/Map/MapViewAuto.offline.test.tsx new file mode 100644 index 000000000..885aef6d1 --- /dev/null +++ b/client/src/components/Map/MapViewAuto.offline.test.tsx @@ -0,0 +1,123 @@ +/** + * The trip map offline (FE-COMP-MAPAUTO-OFFLINE-*). + * + * Whatever basemap the user picked, offline the map never goes grey: a basemap + * with nothing stored switches to the stored OpenFreeMap one, with the same + * markers and routes, and says so. + */ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { render, screen } from '../../../tests/helpers/render'; +import { resetAllStores, seedStore } from '../../../tests/helpers/store'; +import { OFM_DARK, OFM_POSITRON } from '../../constants/mapDefaults'; +import { useSettingsStore } from '../../store/settingsStore'; +import { resetWebGLProbe } from '../../utils/webgl'; +import { MapViewAuto } from './MapViewAuto'; + +const env = vi.hoisted(() => ({ offline: false, dark: false })); +const seen = vi.hoisted(() => ({ + leaflet: null as null | { tileUrl?: string }, + gl: null as null | { engine: string; glProvider?: string; styleOverride?: string }, +})); + +vi.mock('./MapView', () => ({ + MapView: (props: { tileUrl?: string }) => { + seen.leaflet = props; + return
; + }, +})); +vi.mock('./glLazy', () => ({ + MapViewGLMaplibre: (props: { glProvider?: string; styleOverride?: string }) => { + seen.gl = { engine: 'maplibre', ...props }; + return
; + }, + MapViewGLMapbox: (props: { glProvider?: string; styleOverride?: string }) => { + seen.gl = { engine: 'mapbox', ...props }; + return
; + }, +})); +vi.mock('./useRoadtripHazards', () => ({ useRoadtripHazards: () => ({ feed: null }) })); +vi.mock('../../hooks/useNetworkMode', () => ({ + useNetworkMode: () => ({ offline: env.offline, forced: false, setForced: () => {} }), +})); +vi.mock('../../hooks/useIsDark', () => ({ useIsDark: () => env.dark })); +vi.mock('../../native/platform', async (importOriginal) => ({ + ...(await importOriginal()), + isNativeIos: () => false, +})); + +const realGetContext = HTMLCanvasElement.prototype.getContext; + +beforeEach(() => { + resetAllStores(); + resetWebGLProbe(); + env.offline = false; + env.dark = false; + seen.leaflet = null; + seen.gl = null; + const ctx = { getExtension: () => ({ loseContext: () => {} }) }; + HTMLCanvasElement.prototype.getContext = vi.fn((type: string) => + type === 'webgl2' ? ctx : null + ) as unknown as typeof realGetContext; +}); + +afterEach(() => { + HTMLCanvasElement.prototype.getContext = realGetContext; + resetWebGLProbe(); +}); + +const pill = () => screen.queryByRole('status'); + +describe('MapViewAuto offline', () => { + it('FE-COMP-MAPAUTO-OFFLINE-001: a Mapbox map online stays Mapbox, with no pill', async () => { + seedStore(useSettingsStore, { settings: { map_provider: 'mapbox-gl', mapbox_access_token: 'pk.test' } }); + + render(); + + await screen.findByTestId('gl-map'); + expect(seen.gl).toMatchObject({ engine: 'mapbox', glProvider: 'mapbox-gl', styleOverride: undefined }); + expect(pill()).not.toBeInTheDocument(); + }); + + it('FE-COMP-MAPAUTO-OFFLINE-002: offline, a Mapbox map draws the stored basemap with MapLibre and says so', async () => { + seedStore(useSettingsStore, { settings: { map_provider: 'mapbox-gl', mapbox_access_token: 'pk.test' } }); + env.offline = true; + env.dark = true; + + render(); + + await screen.findByTestId('gl-map'); + expect(seen.gl).toMatchObject({ engine: 'maplibre', glProvider: 'maplibre-gl', styleOverride: OFM_DARK }); + expect(pill()).toBeInTheDocument(); + }); + + it('FE-COMP-MAPAUTO-OFFLINE-003: a MapLibre map already on a stored style stays as it is', async () => { + seedStore(useSettingsStore, { settings: { map_provider: 'maplibre-gl', maplibre_style: OFM_POSITRON } }); + env.offline = true; + + render(); + + await screen.findByTestId('gl-map'); + expect(seen.gl?.styleOverride).toBeUndefined(); + expect(pill()).not.toBeInTheDocument(); + }); + + it('FE-COMP-MAPAUTO-OFFLINE-004: offline, Leaflet on OpenStreetMap tiles switches to the stored basemap', () => { + seedStore(useSettingsStore, { settings: { map_provider: 'leaflet' } }); + env.offline = true; + + render(); + + expect(seen.leaflet?.tileUrl).toBe(OFM_POSITRON); + expect(pill()).toBeInTheDocument(); + }); + + it('FE-COMP-MAPAUTO-OFFLINE-005: offline, a raster template the service worker stored stays', () => { + seedStore(useSettingsStore, { settings: { map_provider: 'leaflet' } }); + env.offline = true; + + render(); + + expect(seen.leaflet?.tileUrl).toBe('https://tiles.example.com/{z}/{x}/{y}.png'); + expect(pill()).not.toBeInTheDocument(); + }); +}); diff --git a/client/src/components/Map/MapViewAuto.tsx b/client/src/components/Map/MapViewAuto.tsx index 28d670417..878334835 100644 --- a/client/src/components/Map/MapViewAuto.tsx +++ b/client/src/components/Map/MapViewAuto.tsx @@ -1,5 +1,5 @@ import { Suspense } from 'react' -import { AlertTriangle, Clock, Info } from 'lucide-react' +import { AlertTriangle, Clock, CloudOff, Info } from 'lucide-react' import { Tooltip } from '../shared/Tooltip' import { useSettingsStore } from '../../store/settingsStore' import { MapView } from './MapView' @@ -9,15 +9,21 @@ import { useGlRenderer } from './glSupport' import { useRoadtripHazards } from './useRoadtripHazards' import { useTranslation } from '../../i18n/TranslationContext' import type { MapViewAutoProps, MapViewProps } from './mapViewContract' +import { useNetworkMode } from '../../hooks/useNetworkMode' +import { useIsDark } from '../../hooks/useIsDark' +import { OFM_POSITRON } from '../../constants/mapDefaults' +import { glWorksOffline, leafletWorksOffline, offlineStyleFor } from './offlineBasemap' // Auto-selects the map renderer based on user settings. Keeps the existing // Leaflet MapView untouched so the Mapbox GL variant can mature iteratively // behind a toggle. Atlas is not affected — it imports Leaflet directly. // -// Offline maps: only the Leaflet renderer supports full pre-download (raster -// tiles via sync/tilePrefetcher.ts). GL maps are best-effort offline — their -// vector tiles are cached opportunistically by the Service Worker as you view -// them online (see the GL tile rules in vite.config.js), not prefetched. +// Offline maps: "prepare for offline" stores the OpenFreeMap basemap for every +// trip, whatever the provider (sync/tilePrefetcher.ts). Offline, a map whose own +// basemap cannot be drawn from storage (Mapbox, another OpenFreeMap style, a +// raster template the device cannot serve) switches to that stored basemap, +// with the same markers, routes and tracks, and says so with a small pill. It +// switches back once the connection returns. See offlineBasemap.ts. export function MapViewAuto(props: MapViewAutoProps) { const { t } = useTranslation() const hazards = useRoadtripHazards(props.tripId, !!props.clusterLoosely) @@ -32,7 +38,17 @@ export function MapViewAuto(props: MapViewAutoProps) { // Fall back to Leaflet when Mapbox is selected but no token is set, or when the // browser has no WebGL2 (both GL engines need it), so the trip planner never // shows an empty map or one that fails to start. - const glProvider = useGlRenderer(provider, token) + const configuredGl = useGlRenderer(provider, token) + const maplibreStyle = useSettingsStore(s => s.settings.maplibre_style) + const { offline } = useNetworkMode() + const dark = useIsDark() + const offlineStyle = offlineStyleFor(dark) + // Offline on a basemap that has nothing stored: draw the stored one with MapLibre. + const glFallback = !!configuredGl && offline && !glWorksOffline(configuredGl, maplibreStyle) + const glProvider = glFallback ? 'maplibre-gl' : configuredGl + const leafletFallback = !configuredGl && offline && !leafletWorksOffline(mapProps.tileUrl ?? OFM_POSITRON) + if (leafletFallback) mapProps.tileUrl = offlineStyle + const pill = (glFallback || leafletFallback) && // One chunk per engine: picking the binding here is what keeps mapbox-gl and // maplibre-gl out of each other's downloads. const MapViewGL = glProvider === 'maplibre-gl' ? MapViewGLMaplibre : MapViewGLMapbox @@ -45,12 +61,33 @@ export function MapViewAuto(props: MapViewAutoProps) { // to Leaflet keeps a usable map instead of an error card. // resetKeys: with two engine chunks, a failure under one provider must not // keep showing Leaflet after the user switches to the other. - }> - }> - - - + <> + }> + }> + + + + {pill} + ) } - return + return ( + <> + + {pill} + + ) +} + +/** Says the map on screen is the stored offline basemap, not the user's own. */ +function OfflineBasemapPill({ label }: { label: string }) { + return ( +
+
+ ) } diff --git a/client/src/components/Map/MapViewGL.tsx b/client/src/components/Map/MapViewGL.tsx index 9ccae95f7..95402c9ed 100644 --- a/client/src/components/Map/MapViewGL.tsx +++ b/client/src/components/Map/MapViewGL.tsx @@ -100,6 +100,8 @@ const NO_DAYS: Day[] = [] /** The GL renderer: the shared map contract plus the engine it is bound to. */ interface Props extends MapViewProps { glProvider?: GlMapProvider + /** Draws this style instead of the user's: the offline basemap (offlineBasemap.ts). */ + styleOverride?: string /** * The GL engine, injected instead of imported. Both SDKs used to be pulled in * statically here, so a single 2.8 MB chunk carried mapbox-gl and maplibre-gl @@ -482,6 +484,7 @@ export function MapViewGL({ onRemoveVia, onViewportChange, glProvider = 'mapbox-gl', + styleOverride, gl, onMapReady, ...assistant @@ -506,7 +509,7 @@ export function MapViewGL({ const showEndpointLabels = useSettingsStore(s => s.settings.map_booking_labels) === true const mapLang = useSettingsStore(s => s.settings.language) const isMapLibre = glProvider === 'maplibre-gl' - const glStyle = styleForActiveProvider(glProvider, rawMapboxStyle, rawMaplibreStyle) + const glStyle = styleOverride ?? styleForActiveProvider(glProvider, rawMapboxStyle, rawMaplibreStyle) const enableMapbox3d = !isMapLibre && mapbox3d const [mapReady, setMapReady] = useState(false) const [readyMap, setReadyMap] = useState(null) // the ready map, read without touching mapRef diff --git a/client/src/components/Map/offlineBasemap.test.ts b/client/src/components/Map/offlineBasemap.test.ts new file mode 100644 index 000000000..3901fe722 --- /dev/null +++ b/client/src/components/Map/offlineBasemap.test.ts @@ -0,0 +1,33 @@ +import { describe, expect, it } from 'vitest'; +import { OFM_DARK, OFM_POSITRON } from '../../constants/mapDefaults'; +import { glWorksOffline, isOfflineForbiddenTemplate, leafletWorksOffline, offlineStyleFor } from './offlineBasemap'; + +describe('offlineBasemap', () => { + it('picks the stored style for the colour scheme', () => { + expect(offlineStyleFor(false)).toBe(OFM_POSITRON); + expect(offlineStyleFor(true)).toBe(OFM_DARK); + }); + + it('knows OpenStreetMap standard tiles may not be stored, sharded or not', () => { + expect(isOfflineForbiddenTemplate('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png')).toBe(true); + expect(isOfflineForbiddenTemplate('https://tile.openstreetmap.org/{z}/{x}/{y}.png')).toBe(true); + expect(isOfflineForbiddenTemplate('https://tile.openstreetmap.de/{z}/{x}/{y}.png')).toBe(false); + expect(isOfflineForbiddenTemplate('not a url')).toBe(false); + }); + + it('lets only MapLibre on a stored style draw offline as configured', () => { + expect(glWorksOffline('maplibre-gl', OFM_POSITRON)).toBe(true); + expect(glWorksOffline('maplibre-gl', OFM_DARK)).toBe(true); + // The default MapLibre style is Liberty, whose sprite and glyphs are not stored. + expect(glWorksOffline('maplibre-gl', '')).toBe(false); + expect(glWorksOffline('mapbox-gl', OFM_POSITRON)).toBe(false); + }); + + it('keeps a stored raster template on the web, never in the iOS app or for OSM', () => { + expect(leafletWorksOffline(OFM_POSITRON, true)).toBe(true); + expect(leafletWorksOffline('https://tiles.openfreemap.org/styles/liberty', false)).toBe(false); + expect(leafletWorksOffline('https://tiles.example.com/{z}/{x}/{y}.png', false)).toBe(true); + expect(leafletWorksOffline('https://tiles.example.com/{z}/{x}/{y}.png', true)).toBe(false); + expect(leafletWorksOffline('https://tile.openstreetmap.org/{z}/{x}/{y}.png', false)).toBe(false); + }); +}); diff --git a/client/src/components/Map/offlineBasemap.ts b/client/src/components/Map/offlineBasemap.ts new file mode 100644 index 000000000..a89b59099 --- /dev/null +++ b/client/src/components/Map/offlineBasemap.ts @@ -0,0 +1,54 @@ +import { OFM_DARK, OFM_POSITRON } from '../../constants/mapDefaults'; +import { isNativeIos } from '../../native/platform'; +import { isVectorStyle } from '../../utils/tileUrl'; +import { normalizeStyleForProvider, type GlMapProvider } from './glProviders'; + +/** + * The basemap a map falls back to offline, so that whatever the user picked + * online (Mapbox, a raster template, another OpenFreeMap style) they never + * face a grey map once the connection goes. + * + * The two OpenFreeMap styles below are the ones "prepare for offline" stores + * for every trip, whatever the configured provider (sync/tilePrefetcher.ts): + * both share one planet tile set, so the dark one only adds its style, sprite + * and glyphs. A fallback has to be exactly a style that was stored, or its + * sprite and labels are missing offline. + */ +export const OFFLINE_STYLES: readonly string[] = [OFM_POSITRON, OFM_DARK]; + +/** The stored style that matches the colour scheme. */ +export function offlineStyleFor(dark: boolean): string { + return dark ? OFM_DARK : OFM_POSITRON; +} + +/** Hosts whose tiles may not be stored for offline use at all (OSM tile usage policy). */ +const NO_OFFLINE_HOSTS = ['tile.openstreetmap.org']; + +export function isOfflineForbiddenTemplate(template: string): boolean { + try { + const host = new URL(template.replace(/\{s\}/g, 'a')).hostname; + return NO_OFFLINE_HOSTS.some((h) => host === h || host.endsWith(`.${h}`)); + } catch { + return false; + } +} + +/** + * Whether a GL map can be drawn offline as configured. Only MapLibre on one of + * the stored styles can: Mapbox has nothing stored to draw from, and another + * OpenFreeMap style lacks its sprite and glyphs offline. + */ +export function glWorksOffline(provider: GlMapProvider, maplibreStyle: string | null | undefined): boolean { + return provider === 'maplibre-gl' && OFFLINE_STYLES.includes(normalizeStyleForProvider('maplibre-gl', maplibreStyle)); +} + +/** + * Whether the Leaflet map's basemap can be drawn offline as configured. A + * stored vector style can. A raster template can where the service worker + * serves the prefetched tiles, which the iOS app's WebView does not run for a + * self-hosted server, and never for a host whose tiles may not be stored. + */ +export function leafletWorksOffline(tileUrl: string, nativeIos: boolean = isNativeIos()): boolean { + if (isVectorStyle(tileUrl)) return OFFLINE_STYLES.includes(tileUrl); + return !nativeIos && !isOfflineForbiddenTemplate(tileUrl); +} diff --git a/client/src/sync/glPrefetcher.ts b/client/src/sync/glPrefetcher.ts index be9e0090b..5ce99624e 100644 --- a/client/src/sync/glPrefetcher.ts +++ b/client/src/sync/glPrefetcher.ts @@ -25,8 +25,15 @@ const VECTOR_MAX_ZOOM = 14 // The low zooms cost a few dozen tiles at most. const VECTOR_MIN_ZOOM = 0 -/** Requests in flight, kept low for the same reason the raster side keeps it low. */ -const CONCURRENCY = 6 +/** + * Requests in flight. OpenFreeMap allows offline downloads with at most four + * parallel requests, at most 3000 tiles and at most 50 MB each + * (openfreemap.org/tos), so the run keeps under all three. + */ +const CONCURRENCY = 4 + +/** Byte budget per run, the 50 MB OpenFreeMap allows for one download. */ +const MAX_RUN_BYTES = 50 * 1024 * 1024 /** * Hard cap on vector tiles per run. Each is far larger than a raster tile but @@ -38,12 +45,52 @@ const MAX_VECTOR_TILES = 2000 export const VECTOR_CACHE = 'gl-map-offline' /** - * Latin glyph ranges. A label needs the range its codepoints fall in, and Latin - * text lives in the first few; asking for all 256 ranges would download megabytes - * of CJK nobody on this map is going to render. + * Glyph ranges every map needs: Latin, Greek, Cyrillic, Hebrew, Arabic and the + * punctuation blocks. A label needs the range its codepoints fall in; asking for + * all 256 ranges would download megabytes of scripts nobody on this map renders. */ const GLYPH_RANGES = ['0-255', '256-511', '512-767', '768-1023', '1024-1279', '1280-1535', '1536-1791', '8192-8447', '8448-8703'] +/** One range string per 256 codepoints from `from` up to `to`. */ +function rangesBetween(from: number, to: number): string[] { + const out: string[] = [] + for (let start = from - (from % 256); start <= to; start += 256) out.push(`${start}-${start + 255}`) + return out +} + +/** + * Scripts whose labels a trip in that part of the world shows in the local + * name, so a trip there gets their ranges too, or its labels render blank + * offline. Boxes are generous [minLng, minLat, maxLng, maxLat]. + */ +const REGIONAL_GLYPHS: { box: [number, number, number, number]; ranges: string[] }[] = [ + // China, Japan, Korea, Taiwan: kana and CJK punctuation, unified ideographs, Hangul, full-width forms. + { + box: [73, 18, 146, 54], + ranges: [...rangesBetween(0x3000, 0x30ff), ...rangesBetween(0x4e00, 0x9fff), ...rangesBetween(0xac00, 0xd7af), ...rangesBetween(0xff00, 0xffef)], + }, + // Thailand, Laos, Cambodia, Myanmar. + { box: [92, 5, 110, 28], ranges: rangesBetween(0x0e00, 0x0eff).concat(rangesBetween(0x1000, 0x109f), rangesBetween(0x1780, 0x17ff)) }, + // India, Nepal, Bangladesh, Sri Lanka: Devanagari through Malayalam, Sinhala. + { box: [60, 5, 98, 36], ranges: rangesBetween(0x0900, 0x0dff) }, + // Georgia and Armenia. + { box: [39, 38, 47, 44], ranges: rangesBetween(0x0530, 0x058f).concat(rangesBetween(0x10a0, 0x10ff)) }, + // Ethiopia and Eritrea. + { box: [33, 3, 48, 18], ranges: rangesBetween(0x1200, 0x139f) }, +] + +/** The glyph ranges a map of `bbox` needs: the common ones plus its region's scripts. */ +export function glyphRangesFor(bbox: TileBbox | null): string[] { + const out = new Set(GLYPH_RANGES) + if (bbox) { + for (const { box, ranges } of REGIONAL_GLYPHS) { + const overlaps = bbox.minLng <= box[2] && bbox.maxLng >= box[0] && bbox.minLat <= box[3] && bbox.maxLat >= box[1] + if (overlaps) for (const r of ranges) out.add(r) + } + } + return [...out] +} + interface StyleSource { type?: string url?: string @@ -96,15 +143,18 @@ function fontStacks(style: StyleDoc): string[] { * the Service Worker's handler, so a repeated or resumed run over a warm cache * costs almost nothing. Same reasoning as the raster side. */ -async function warm(cache: Cache | null, url: string): Promise { +async function warm(cache: Cache | null, url: string): Promise { try { - if (cache && (await cache.match(url))) return false + if (cache && (await cache.match(url))) return 0 const res = await fetch(url, { mode: 'cors' }) - if (!res.ok) return false - await cache?.put(url, res.clone()) - return true + if (!res.ok) return 0 + // The length header when the server sends one; otherwise the body itself. + const header = Number(res.headers.get('content-length')) + const size = header > 0 ? header : (await res.clone().blob()).size || 1 + await cache?.put(url, res) + return size } catch { - return false + return 0 } } @@ -178,11 +228,11 @@ async function readTileSources(style: StyleDoc, cache: Cache | null): Promise { - return (await prefetchStyle(styleUrl))?.[0]?.template ?? null +export async function prefetchStyleAssets(styleUrl: string, bbox: TileBbox | null = null): Promise { + return (await prefetchStyle(styleUrl, bbox))?.[0]?.template ?? null } -async function prefetchStyle(styleUrl: string): Promise { +async function prefetchStyle(styleUrl: string, bbox: TileBbox | null = null): Promise { const cache = await openVectorCache() const style = await fetchJson(styleUrl) if (!style) return null @@ -199,14 +249,14 @@ async function prefetchStyle(styleUrl: string): Promise { } if (style.glyphs) { - const stacks = fontStacks(style) - await Promise.all( - stacks.flatMap(stack => - GLYPH_RANGES.map(range => - warm(cache, style.glyphs!.replace('{fontstack}', encodeURIComponent(stack)).replace('{range}', range)), - ), + // Through the same pool as the tiles: a trip in East Asia asks for a few + // hundred glyph ranges, and OpenFreeMap allows four requests at a time. + const urls = fontStacks(style).flatMap(stack => + glyphRangesFor(bbox).map(range => + style.glyphs!.replace('{fontstack}', encodeURIComponent(stack)).replace('{range}', range), ), ) + await inPool(urls, url => warm(cache, url)) } return readTileSources(style, cache) @@ -233,7 +283,7 @@ export async function prefetchVectorForPlaces( const bbox = computeBbox(places) if (!bbox) return { tiles: 0, template: null } - const sources = await prefetchStyle(styleUrl) + const sources = await prefetchStyle(styleUrl, bbox) const template = sources?.[0]?.template ?? null if (!sources?.length || isCancelled()) return { tiles: 0, template } @@ -242,13 +292,18 @@ export async function prefetchVectorForPlaces( let cursor = 0 let fetched = 0 + let bytes = 0 async function worker(): Promise { while (cursor < urls.length) { - if (isCancelled() || !navigator.onLine) return + if (isCancelled() || !navigator.onLine || bytes >= MAX_RUN_BYTES) return const url = urls[cursor++] if (!url) return - if (await warm(cache, url)) fetched++ + const size = await warm(cache, url) + if (size > 0) { + fetched++ + bytes += size + } } } @@ -256,6 +311,19 @@ export async function prefetchVectorForPlaces( return { tiles: fetched, template } } +/** Runs `task` over `items`, CONCURRENCY at a time. */ +async function inPool(items: T[], task: (item: T) => Promise): Promise { + let cursor = 0 + async function worker(): Promise { + while (cursor < items.length) { + const item = items[cursor++] + if (item === undefined) return + await task(item) + } + } + await Promise.all(Array.from({ length: CONCURRENCY }, () => worker())) +} + /** Drop the offline vector basemap, alongside the raster cache. */ export async function clearVectorCache(): Promise { try { diff --git a/client/src/sync/tilePrefetcher.ts b/client/src/sync/tilePrefetcher.ts index 120c054cb..4a1416bd6 100644 --- a/client/src/sync/tilePrefetcher.ts +++ b/client/src/sync/tilePrefetcher.ts @@ -28,8 +28,10 @@ import { offlineDb, upsertSyncMeta } from '../db/offlineDb' import { isAuthed } from './authGate' import { isStoragePersisted } from './persistentStorage' import { isVectorStyle, normalizeTileUrl, resolveTileUrl, withTileApiKey } from '../utils/tileUrl' -import { OFM_POSITRON } from '../constants/mapDefaults' -import { clearVectorCache, prefetchVectorForPlaces } from './glPrefetcher' +import { OFM_DARK, OFM_POSITRON } from '../constants/mapDefaults' +import { clearVectorCache, prefetchStyleAssets, prefetchVectorForPlaces } from './glPrefetcher' +import { isOfflineForbiddenTemplate } from '../components/Map/offlineBasemap' +import { isNativeIos } from '../native/platform' // ── Constants ───────────────────────────────────────────────────────────────── @@ -385,6 +387,21 @@ function sameBbox(a: [number, number, number, number], b: TileBbox): boolean { ) } +/** The OpenFreeMap styles the offline fallback draws; they share one tile set. */ +const OFFLINE_BASEMAPS: readonly string[] = [OFM_POSITRON, OFM_DARK] + +/** + * The trip's region of the offline basemap: the light style's tiles, style, + * sprite and glyphs, and the dark style's own style, sprite and glyphs on top, + * whose tiles are the same ones. + */ +async function prefetchOfflineBasemap(places: Place[], template: string, cancelled: () => boolean): Promise { + const light = template === OFM_DARK ? OFM_DARK : OFM_POSITRON + const other = light === OFM_DARK ? OFM_POSITRON : OFM_DARK + await prefetchVectorForPlaces(places, light, cancelled).catch(console.error) + if (!cancelled()) await prefetchStyleAssets(other, computeBbox(places)).catch(console.error) +} + /** * Full pipeline: compute bbox → guard → prefetch → update syncMeta. * Designed to be called fire-and-forget from tripSyncManager. @@ -415,8 +432,16 @@ export async function prefetchTilesForTrip( // The default basemap is a vector style, and walking a {z}/{x}/{y} template // over one would fetch nothing the map ever asks for. A user who configured // their own raster template keeps the path below unchanged. + const cancelled = () => !navigator.onLine || !isAuthed() + // Whatever the map is set to, the trip's region of the offline basemap goes + // along: offline, a Mapbox map or one the device cannot serve switches to it + // (components/Map/offlineBasemap.ts). + await prefetchOfflineBasemap(places, template, cancelled) + if (isVectorStyle(template)) { - const { tiles } = await prefetchVectorForPlaces(places, template, () => !navigator.onLine || !isAuthed()) + const { tiles } = OFFLINE_BASEMAPS.includes(template) + ? { tiles: 0 } + : await prefetchVectorForPlaces(places, template, cancelled) const meta = await offlineDb.syncMeta.get(tripId) if (meta) { await upsertSyncMeta({ @@ -447,7 +472,12 @@ export async function prefetchTilesForTrip( // dozen tiles (#2180); the deep ones are the volume, and they are what the // user loses rather than the ability to start the app at all (#2228). const maxZoom = isStoragePersisted() ? 16 : UNPERSISTED_MAX_ZOOM - const fetched = await prefetchTiles(bbox, template, 0, maxZoom, cartoKey) + // Not for a host whose tiles may not be stored (OSM's tile usage policy), and + // not inside the iOS app, whose WebView runs no service worker to serve them: + // the offline basemap above stands in there. + const fetched = isOfflineForbiddenTemplate(template) || isNativeIos() + ? 0 + : await prefetchTiles(bbox, template, 0, maxZoom, cartoKey) // Update syncMeta with bbox and tile count const meta = await offlineDb.syncMeta.get(tripId) diff --git a/client/tests/unit/sync/tilePrefetcher.test.ts b/client/tests/unit/sync/tilePrefetcher.test.ts index f3fb5a059..96b3f3e8b 100644 --- a/client/tests/unit/sync/tilePrefetcher.test.ts +++ b/client/tests/unit/sync/tilePrefetcher.test.ts @@ -26,6 +26,21 @@ import { offlineDb, clearAll, upsertSyncMeta } from '../../../src/db/offlineDb'; import { requestPersistentStorage, _resetPersistentStorage } from '../../../src/sync/persistentStorage'; import { setAuthed } from '../../../src/sync/authGate'; import { buildPlace } from '../../helpers/factories'; +import { prefetchStyleAssets, prefetchVectorForPlaces } from '../../../src/sync/glPrefetcher'; +import { isNativeIos } from '../../../src/native/platform'; +import { OFM_DARK, OFM_POSITRON } from '../../../src/constants/mapDefaults'; + +// The vector basemap has its own tests (glPrefetcher.test.ts). Here it is a seam, +// so the raster runs below count only their own tile requests. +vi.mock('../../../src/sync/glPrefetcher', async importOriginal => ({ + ...(await importOriginal()), + prefetchVectorForPlaces: vi.fn(async () => ({ tiles: 0, template: null })), + prefetchStyleAssets: vi.fn(async () => null), +})); +vi.mock('../../../src/native/platform', async importOriginal => ({ + ...(await importOriginal()), + isNativeIos: vi.fn(() => false), +})); beforeEach(async () => { await clearAll(); @@ -406,6 +421,48 @@ describe('prefetchTilesForTrip', () => { }); }); +// ── the offline basemap ─────────────────────────────────────────────────────── + +describe('prefetchTilesForTrip — the offline basemap', () => { + const places = [buildPlace({ trip_id: 1, lat: 35.68, lng: 139.76 })]; + + beforeEach(async () => { + await upsertSyncMeta({ tripId: 1, lastSyncedAt: Date.now(), status: 'idle', tilesBbox: null, filesCachedCount: 0 }); + vi.mocked(prefetchVectorForPlaces).mockClear(); + vi.mocked(prefetchStyleAssets).mockClear(); + vi.mocked(isNativeIos).mockReturnValue(false); + }); + + it('stores the light and dark OpenFreeMap styles for a trip on any provider', async () => { + await prefetchTilesForTrip(1, places, 'https://{s}.example.com/{z}/{x}/{y}.png'); + + expect(vi.mocked(prefetchVectorForPlaces).mock.calls.map(c => c[1])).toEqual([OFM_POSITRON]); + expect(vi.mocked(prefetchStyleAssets).mock.calls.map(c => c[0])).toEqual([OFM_DARK]); + }); + + it('does not walk the stored style twice when it is the configured one', async () => { + await prefetchTilesForTrip(1, places, OFM_POSITRON); + + expect(vi.mocked(prefetchVectorForPlaces)).toHaveBeenCalledTimes(1); + }); + + it('never prefetches OpenStreetMap standard tiles, which their policy forbids', async () => { + await prefetchTilesForTrip(1, places, 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'); + + expect(vi.mocked(fetch).mock.calls.some(c => String(c[0]).includes('tile.openstreetmap.org'))).toBe(false); + expect(vi.mocked(prefetchVectorForPlaces)).toHaveBeenCalled(); + }); + + it('skips raster tiles inside the iOS app, which has no service worker to serve them', async () => { + vi.mocked(isNativeIos).mockReturnValue(true); + + await prefetchTilesForTrip(1, places, 'https://{s}.example.com/{z}/{x}/{y}.png'); + + expect(vi.mocked(fetch)).not.toHaveBeenCalled(); + expect(vi.mocked(prefetchVectorForPlaces)).toHaveBeenCalled(); + }); +}); + // ── repeat runs ─────────────────────────────────────────────────────────────── describe('prefetchTilesForTrip — repeat runs', () => { diff --git a/shared/src/i18n/ar/map.ts b/shared/src/i18n/ar/map.ts index 4595bf8c2..572c62cf9 100644 --- a/shared/src/i18n/ar/map.ts +++ b/shared/src/i18n/ar/map.ts @@ -52,5 +52,6 @@ const map: TranslationStrings = { 'map.webgl2.fallback': 'لا يوفّر هذا المتصفح WebGL2 الذي تحتاجه خرائط GL، لذا تُعرض الخرائط باستخدام Leaflet بدلًا منها.', 'map.webgl2.terrain': 'يحتاج العرض ثلاثي الأبعاد إلى WebGL2، وهذا المتصفح لا يوفّره. تبقى الخريطة ثنائية الأبعاد.', + 'map.offlineBasemap': 'خريطة دون اتصال', }; export default map; diff --git a/shared/src/i18n/az/map.ts b/shared/src/i18n/az/map.ts index b8e228698..6f00aa0ca 100644 --- a/shared/src/i18n/az/map.ts +++ b/shared/src/i18n/az/map.ts @@ -50,6 +50,7 @@ const map: TranslationStrings = { 'map.webgl2.fallback': 'Bu brauzer GL xəritələrinin ehtiyac duyduğu WebGL2-ni təqdim etmir, ona görə xəritələr Leaflet ilə göstərilir.', 'map.webgl2.terrain': '3D üçün WebGL2 lazımdır, bu brauzer isə onu təqdim etmir. Xəritə 2D olaraq qalır.', + 'map.offlineBasemap': 'Oflayn xəritə', }; export default map; diff --git a/shared/src/i18n/br/map.ts b/shared/src/i18n/br/map.ts index 96b01ba14..bf433284d 100644 --- a/shared/src/i18n/br/map.ts +++ b/shared/src/i18n/br/map.ts @@ -47,5 +47,6 @@ const map: TranslationStrings = { 'map.webgl2.fallback': 'Este navegador não oferece WebGL2, necessário para os mapas GL, por isso os mapas são exibidos com o Leaflet.', 'map.webgl2.terrain': 'O 3D precisa de WebGL2, que este navegador não oferece. O mapa continua em 2D.', + 'map.offlineBasemap': 'Mapa offline', }; export default map; diff --git a/shared/src/i18n/ca/map.ts b/shared/src/i18n/ca/map.ts index 15f66e8a3..502acda19 100644 --- a/shared/src/i18n/ca/map.ts +++ b/shared/src/i18n/ca/map.ts @@ -45,5 +45,6 @@ const map: TranslationStrings = { 'map.webgl2.fallback': 'Aquest navegador no ofereix WebGL2, que necessiten els mapes GL, així que els mapes es mostren amb Leaflet.', 'map.webgl2.terrain': 'El 3D necessita WebGL2, que aquest navegador no ofereix. El mapa es queda en 2D.', + 'map.offlineBasemap': 'Mapa fora de línia', }; export default map; diff --git a/shared/src/i18n/cs/map.ts b/shared/src/i18n/cs/map.ts index 0139c1030..407292af7 100644 --- a/shared/src/i18n/cs/map.ts +++ b/shared/src/i18n/cs/map.ts @@ -46,5 +46,6 @@ const map: TranslationStrings = { 'map.webgl2.fallback': 'Tento prohlížeč nenabízí WebGL2, které mapy GL potřebují, proto se mapy zobrazují pomocí Leafletu.', 'map.webgl2.terrain': '3D potřebuje WebGL2, které tento prohlížeč nenabízí. Mapa zůstává ve 2D.', + 'map.offlineBasemap': 'Offline mapa', }; export default map; diff --git a/shared/src/i18n/de/map.ts b/shared/src/i18n/de/map.ts index c8df7a83b..951536543 100644 --- a/shared/src/i18n/de/map.ts +++ b/shared/src/i18n/de/map.ts @@ -47,5 +47,6 @@ const map: TranslationStrings = { 'map.webgl2.fallback': 'Dieser Browser bietet kein WebGL2, das GL-Karten brauchen. Karten werden deshalb mit Leaflet angezeigt.', 'map.webgl2.terrain': '3D braucht WebGL2, das dieser Browser nicht bietet. Die Karte bleibt in 2D.', + 'map.offlineBasemap': 'Offline-Karte', }; export default map; diff --git a/shared/src/i18n/en/map.ts b/shared/src/i18n/en/map.ts index 03a8767e9..531d0252b 100644 --- a/shared/src/i18n/en/map.ts +++ b/shared/src/i18n/en/map.ts @@ -45,5 +45,6 @@ const map: TranslationStrings = { 'map.webgl2.fallback': 'This browser does not offer WebGL2, which GL maps need, so maps are shown with Leaflet instead.', 'map.webgl2.terrain': '3D needs WebGL2, which this browser does not offer. The map stays in 2D.', + 'map.offlineBasemap': 'Offline map', }; export default map; diff --git a/shared/src/i18n/es/map.ts b/shared/src/i18n/es/map.ts index 5eca743c0..974495e1c 100644 --- a/shared/src/i18n/es/map.ts +++ b/shared/src/i18n/es/map.ts @@ -44,5 +44,6 @@ const map: TranslationStrings = { 'map.webgl2.fallback': 'Este navegador no ofrece WebGL2, que necesitan los mapas GL, así que los mapas se muestran con Leaflet.', 'map.webgl2.terrain': 'El 3D necesita WebGL2, que este navegador no ofrece. El mapa se queda en 2D.', + 'map.offlineBasemap': 'Mapa sin conexión', }; export default map; diff --git a/shared/src/i18n/et/map.ts b/shared/src/i18n/et/map.ts index 552dc0cec..8871e8086 100644 --- a/shared/src/i18n/et/map.ts +++ b/shared/src/i18n/et/map.ts @@ -43,5 +43,6 @@ const map: TranslationStrings = { 'map.baseLayer.topo': 'Topograafiline', 'map.webgl2.fallback': 'See brauser ei paku WebGL2-te, mida GL-kaardid vajavad, seega kuvatakse kaardid Leafletiga.', 'map.webgl2.terrain': '3D vajab WebGL2-te, mida see brauser ei paku. Kaart jääb 2D-vaatesse.', + 'map.offlineBasemap': 'Võrguühenduseta kaart', }; export default map; diff --git a/shared/src/i18n/fr/map.ts b/shared/src/i18n/fr/map.ts index af8170e26..316f4adbf 100644 --- a/shared/src/i18n/fr/map.ts +++ b/shared/src/i18n/fr/map.ts @@ -46,5 +46,6 @@ const map: TranslationStrings = { 'map.webgl2.fallback': 'Ce navigateur ne propose pas WebGL2, nécessaire aux cartes GL : les cartes s’affichent donc avec Leaflet.', 'map.webgl2.terrain': 'La 3D nécessite WebGL2, que ce navigateur ne propose pas. La carte reste en 2D.', + 'map.offlineBasemap': 'Carte hors ligne', }; export default map; diff --git a/shared/src/i18n/gr/map.ts b/shared/src/i18n/gr/map.ts index 4bc53c6e6..22b24e22b 100644 --- a/shared/src/i18n/gr/map.ts +++ b/shared/src/i18n/gr/map.ts @@ -46,5 +46,6 @@ const map: TranslationStrings = { 'Αυτό το πρόγραμμα περιήγησης δεν προσφέρει WebGL2, που χρειάζονται οι χάρτες GL, οπότε οι χάρτες εμφανίζονται με το Leaflet.', 'map.webgl2.terrain': 'Το 3D χρειάζεται WebGL2, που αυτό το πρόγραμμα περιήγησης δεν προσφέρει. Ο χάρτης μένει σε 2D.', + 'map.offlineBasemap': 'Χάρτης εκτός σύνδεσης', }; export default map; diff --git a/shared/src/i18n/he/map.ts b/shared/src/i18n/he/map.ts index 94f674e24..ec7c202a4 100644 --- a/shared/src/i18n/he/map.ts +++ b/shared/src/i18n/he/map.ts @@ -45,6 +45,7 @@ const map: TranslationStrings = { 'map.baseLayer.topo': 'טופוגרפית', 'map.webgl2.fallback': 'הדפדפן הזה לא תומך ב-WebGL2, שמפות GL צריכות, ולכן המפות מוצגות עם Leaflet.', 'map.webgl2.terrain': 'תלת-ממד דורש WebGL2, והדפדפן הזה לא תומך בו. המפה נשארת בדו-ממד.', + 'map.offlineBasemap': 'מפה לא מקוונת', }; export default map; diff --git a/shared/src/i18n/hu/map.ts b/shared/src/i18n/hu/map.ts index f526a44fa..bfd29efff 100644 --- a/shared/src/i18n/hu/map.ts +++ b/shared/src/i18n/hu/map.ts @@ -44,5 +44,6 @@ const map: TranslationStrings = { 'map.webgl2.fallback': 'Ez a böngésző nem kínál WebGL2-t, amelyre a GL-térképeknek szükségük van, ezért a térképek Leaflettel jelennek meg.', 'map.webgl2.terrain': 'A 3D-hez WebGL2 kell, amelyet ez a böngésző nem kínál. A térkép 2D-ben marad.', + 'map.offlineBasemap': 'Offline térkép', }; export default map; diff --git a/shared/src/i18n/id/map.ts b/shared/src/i18n/id/map.ts index 3feb67b3b..46a4dd820 100644 --- a/shared/src/i18n/id/map.ts +++ b/shared/src/i18n/id/map.ts @@ -43,5 +43,6 @@ const map: TranslationStrings = { 'map.webgl2.fallback': 'Browser ini tidak menyediakan WebGL2 yang dibutuhkan peta GL, jadi peta ditampilkan dengan Leaflet.', 'map.webgl2.terrain': '3D membutuhkan WebGL2, yang tidak disediakan browser ini. Peta tetap dalam 2D.', + 'map.offlineBasemap': 'Peta offline', }; export default map; diff --git a/shared/src/i18n/it/map.ts b/shared/src/i18n/it/map.ts index 89687a927..91a345d17 100644 --- a/shared/src/i18n/it/map.ts +++ b/shared/src/i18n/it/map.ts @@ -47,5 +47,6 @@ const map: TranslationStrings = { 'map.webgl2.fallback': 'Questo browser non offre WebGL2, necessario alle mappe GL, quindi le mappe vengono mostrate con Leaflet.', 'map.webgl2.terrain': 'Il 3D richiede WebGL2, che questo browser non offre. La mappa resta in 2D.', + 'map.offlineBasemap': 'Mappa offline', }; export default map; diff --git a/shared/src/i18n/ja/map.ts b/shared/src/i18n/ja/map.ts index 6c778b8bc..af4a2b1cb 100644 --- a/shared/src/i18n/ja/map.ts +++ b/shared/src/i18n/ja/map.ts @@ -43,5 +43,6 @@ const map: TranslationStrings = { 'map.webgl2.fallback': 'このブラウザーは GL マップに必要な WebGL2 に対応していないため、地図は Leaflet で表示されます。', 'map.webgl2.terrain': '3D には WebGL2 が必要ですが、このブラウザーは対応していません。地図は 2D のままです。', + 'map.offlineBasemap': 'オフライン地図', }; export default map; diff --git a/shared/src/i18n/ko/map.ts b/shared/src/i18n/ko/map.ts index b4a5c2f26..544b39650 100644 --- a/shared/src/i18n/ko/map.ts +++ b/shared/src/i18n/ko/map.ts @@ -42,5 +42,6 @@ const map: TranslationStrings = { 'map.baseLayer.topo': '지형도', 'map.webgl2.fallback': '이 브라우저는 GL 지도에 필요한 WebGL2를 지원하지 않아 지도를 Leaflet으로 표시합니다.', 'map.webgl2.terrain': '3D에는 WebGL2가 필요하지만 이 브라우저는 지원하지 않습니다. 지도는 2D로 유지됩니다.', + 'map.offlineBasemap': '오프라인 지도', }; export default map; diff --git a/shared/src/i18n/nl/map.ts b/shared/src/i18n/nl/map.ts index 486bbdd2e..bca23f52b 100644 --- a/shared/src/i18n/nl/map.ts +++ b/shared/src/i18n/nl/map.ts @@ -46,5 +46,6 @@ const map: TranslationStrings = { 'map.webgl2.fallback': 'Deze browser biedt geen WebGL2, dat GL-kaarten nodig hebben, dus kaarten worden met Leaflet getoond.', 'map.webgl2.terrain': '3D heeft WebGL2 nodig, dat deze browser niet biedt. De kaart blijft in 2D.', + 'map.offlineBasemap': 'Offline kaart', }; export default map; diff --git a/shared/src/i18n/pl/map.ts b/shared/src/i18n/pl/map.ts index 74c943dde..126d4d7c8 100644 --- a/shared/src/i18n/pl/map.ts +++ b/shared/src/i18n/pl/map.ts @@ -49,5 +49,6 @@ const map: TranslationStrings = { 'map.webgl2.fallback': 'Ta przeglądarka nie obsługuje WebGL2, którego potrzebują mapy GL, więc mapy są wyświetlane za pomocą Leaflet.', 'map.webgl2.terrain': 'Tryb 3D wymaga WebGL2, którego ta przeglądarka nie obsługuje. Mapa pozostaje w 2D.', + 'map.offlineBasemap': 'Mapa offline', }; export default map; diff --git a/shared/src/i18n/ru/map.ts b/shared/src/i18n/ru/map.ts index e054bb65a..6114a6b49 100644 --- a/shared/src/i18n/ru/map.ts +++ b/shared/src/i18n/ru/map.ts @@ -50,5 +50,6 @@ const map: TranslationStrings = { 'map.webgl2.fallback': 'Этот браузер не поддерживает WebGL2, нужный картам GL, поэтому карты показываются через Leaflet.', 'map.webgl2.terrain': 'Для 3D нужен WebGL2, а этот браузер его не поддерживает. Карта остаётся в 2D.', + 'map.offlineBasemap': 'Офлайн-карта', }; export default map; diff --git a/shared/src/i18n/sk/map.ts b/shared/src/i18n/sk/map.ts index 565b82971..231d5d0dc 100644 --- a/shared/src/i18n/sk/map.ts +++ b/shared/src/i18n/sk/map.ts @@ -46,5 +46,6 @@ const map: TranslationStrings = { 'map.webgl2.fallback': 'Tento prehliadač neponúka WebGL2, ktoré mapy GL potrebujú, preto sa mapy zobrazujú pomocou Leafletu.', 'map.webgl2.terrain': '3D potrebuje WebGL2, ktoré tento prehliadač neponúka. Mapa zostáva v 2D.', + 'map.offlineBasemap': 'Offline mapa', }; export default map; diff --git a/shared/src/i18n/sv/map.ts b/shared/src/i18n/sv/map.ts index 9386ee555..7cde3cfb1 100644 --- a/shared/src/i18n/sv/map.ts +++ b/shared/src/i18n/sv/map.ts @@ -44,5 +44,6 @@ const map: TranslationStrings = { 'map.webgl2.fallback': 'Den här webbläsaren erbjuder inte WebGL2, som GL-kartor behöver, så kartorna visas med Leaflet i stället.', 'map.webgl2.terrain': '3D kräver WebGL2, som den här webbläsaren inte erbjuder. Kartan stannar i 2D.', + 'map.offlineBasemap': 'Offlinekarta', }; export default map; diff --git a/shared/src/i18n/th/map.ts b/shared/src/i18n/th/map.ts index c4e3f027f..288de9af7 100644 --- a/shared/src/i18n/th/map.ts +++ b/shared/src/i18n/th/map.ts @@ -41,5 +41,6 @@ const map: TranslationStrings = { 'map.baseLayer.topo': 'ภูมิประเทศ', 'map.webgl2.fallback': 'เบราว์เซอร์นี้ไม่รองรับ WebGL2 ที่แผนที่ GL ต้องใช้ จึงแสดงแผนที่ด้วย Leaflet แทน', 'map.webgl2.terrain': 'โหมด 3D ต้องใช้ WebGL2 ซึ่งเบราว์เซอร์นี้ไม่รองรับ แผนที่จึงยังคงเป็น 2D', + 'map.offlineBasemap': 'แผนที่ออฟไลน์', }; export default map; diff --git a/shared/src/i18n/tr/map.ts b/shared/src/i18n/tr/map.ts index 62374c2c8..70b1df378 100644 --- a/shared/src/i18n/tr/map.ts +++ b/shared/src/i18n/tr/map.ts @@ -44,5 +44,6 @@ const map: TranslationStrings = { 'map.webgl2.fallback': "Bu tarayıcı GL haritalarının ihtiyaç duyduğu WebGL2'yi sunmuyor, bu yüzden haritalar Leaflet ile gösteriliyor.", 'map.webgl2.terrain': '3D için WebGL2 gerekir, bu tarayıcı ise onu sunmuyor. Harita 2D olarak kalır.', + 'map.offlineBasemap': 'Çevrimdışı harita', }; export default map; diff --git a/shared/src/i18n/uk/map.ts b/shared/src/i18n/uk/map.ts index c6566c57d..4db23d21f 100644 --- a/shared/src/i18n/uk/map.ts +++ b/shared/src/i18n/uk/map.ts @@ -48,5 +48,6 @@ const map: TranslationStrings = { 'map.baseLayer.topo': 'Топо', 'map.webgl2.fallback': 'Цей браузер не підтримує WebGL2, потрібний картам GL, тому карти показуються через Leaflet.', 'map.webgl2.terrain': 'Для 3D потрібен WebGL2, а цей браузер його не підтримує. Карта залишається у 2D.', + 'map.offlineBasemap': 'Офлайн-карта', }; export default map; diff --git a/shared/src/i18n/vi/map.ts b/shared/src/i18n/vi/map.ts index 7124d6d27..34ce24447 100644 --- a/shared/src/i18n/vi/map.ts +++ b/shared/src/i18n/vi/map.ts @@ -44,5 +44,6 @@ const map: TranslationStrings = { 'map.baseLayer.topo': 'Địa hình', 'map.webgl2.fallback': 'Trình duyệt này không hỗ trợ WebGL2 mà bản đồ GL cần, nên bản đồ được hiển thị bằng Leaflet.', 'map.webgl2.terrain': 'Chế độ 3D cần WebGL2, nhưng trình duyệt này không hỗ trợ. Bản đồ vẫn ở dạng 2D.', + 'map.offlineBasemap': 'Bản đồ ngoại tuyến', }; export default map; diff --git a/shared/src/i18n/zh-TW/map.ts b/shared/src/i18n/zh-TW/map.ts index 9868dce15..9c00df569 100644 --- a/shared/src/i18n/zh-TW/map.ts +++ b/shared/src/i18n/zh-TW/map.ts @@ -40,5 +40,6 @@ const map: TranslationStrings = { 'map.baseLayer.topo': '地形圖', 'map.webgl2.fallback': '此瀏覽器不支援 GL 地圖所需的 WebGL2,因此地圖改用 Leaflet 顯示。', 'map.webgl2.terrain': '3D 需要 WebGL2,而此瀏覽器不支援。地圖維持 2D。', + 'map.offlineBasemap': '離線地圖', }; export default map; diff --git a/shared/src/i18n/zh/map.ts b/shared/src/i18n/zh/map.ts index 5605cb727..bef81a9de 100644 --- a/shared/src/i18n/zh/map.ts +++ b/shared/src/i18n/zh/map.ts @@ -40,5 +40,6 @@ const map: TranslationStrings = { 'map.baseLayer.topo': '地形图', 'map.webgl2.fallback': '此浏览器不支持 GL 地图所需的 WebGL2,因此地图改用 Leaflet 显示。', 'map.webgl2.terrain': '3D 需要 WebGL2,而此浏览器不支持。地图保持 2D。', + 'map.offlineBasemap': '离线地图', }; export default map; From 01ddcc63bb6315c634675a89c6bb1a3e675db33e Mon Sep 17 00:00:00 2001 From: Maurice Date: Fri, 6 Nov 2026 12:31:57 +0100 Subject: [PATCH 055/589] feat(mobile): two calm round controls a side on the map, no extra buttons The phone map stacked four controls on the right and one on the left, in three different looks. Now each side has two at most, all in one frosted style, 20px off the edge and 8px apart: the whole-trip overview and locate on the right, the base layer and the Dawarich route on the left, with the compass appearing only while the map is turned off north. The map's own places filter button and sheet are gone: the places tab carries the same filter, and the map's pins follow it. The jump-to-today button beside the day rail is gone too, since today's chip is already marked. Also fixes a leftover of the segmented-control change that broke the parse. --- client/src/components/Map/LocationButton.tsx | 9 +- .../components/Map/MapCompassPill.test.tsx | 16 ++- client/src/components/Map/MapCompassPill.tsx | 9 +- client/src/mobile/components/MSegmented.tsx | 3 - client/src/mobile/screens/trip/MTripShell.tsx | 28 +--- .../src/mobile/screens/trip/map/MMapArea.tsx | 56 ++++---- .../screens/trip/map/MPlacesFilterPill.tsx | 31 ----- .../trip/places/MPlacesFilterSheet.tsx | 96 ------------- .../screens/trip/sheets/MTripSheets.tsx | 8 -- .../tests/unit/mobile/trip/MMapArea.test.tsx | 32 +---- .../mobile/trip/MPlacesFilterSheet.test.tsx | 128 ------------------ .../unit/mobile/trip/MTripSheets.test.tsx | 13 +- .../unit/mobile/trip/MTripShell.test.tsx | 18 +-- 13 files changed, 73 insertions(+), 374 deletions(-) delete mode 100644 client/src/mobile/screens/trip/map/MPlacesFilterPill.tsx delete mode 100644 client/src/mobile/screens/trip/places/MPlacesFilterSheet.tsx delete mode 100644 client/tests/unit/mobile/trip/MPlacesFilterSheet.test.tsx diff --git a/client/src/components/Map/LocationButton.tsx b/client/src/components/Map/LocationButton.tsx index f2591b192..d5fe5f4e2 100644 --- a/client/src/components/Map/LocationButton.tsx +++ b/client/src/components/Map/LocationButton.tsx @@ -69,14 +69,19 @@ export default function LocationButton({ mode, error, errorCode, onClick, bottom style={{ position: 'absolute', bottom: bottomOffset, - right: 12, + // The map's base-layer switcher sits 20px off the left edge; this mirrors it. + right: 20, zIndex: 1000, width: 42, height: 42, borderRadius: '50%', border: 'none', cursor: 'pointer', - background: isActive ? '#3b82f6' : 'var(--bg-card, white)', + // Off, it wears the same frosted glass as the map's other round controls; + // on, the location blue says it is tracking. + background: isActive ? '#3b82f6' : 'var(--sidebar-bg)', + backdropFilter: isActive ? undefined : 'blur(20px) saturate(180%)', + WebkitBackdropFilter: isActive ? undefined : 'blur(20px) saturate(180%)', color: isActive ? 'white' : (error ? '#ef4444' : 'var(--text-muted, #6b7280)'), boxShadow: MAP_CONTROL_SHADOW, display: 'flex', diff --git a/client/src/components/Map/MapCompassPill.test.tsx b/client/src/components/Map/MapCompassPill.test.tsx index 23128f0da..9a77479a7 100644 --- a/client/src/components/Map/MapCompassPill.test.tsx +++ b/client/src/components/Map/MapCompassPill.test.tsx @@ -1,4 +1,4 @@ -// FE-COMP-MAPCOMPASS-001 to FE-COMP-MAPCOMPASS-006 +// FE-COMP-MAPCOMPASS-001 to FE-COMP-MAPCOMPASS-007 import React from 'react' import { describe, it, expect, vi } from 'vitest' import { render, screen, fireEvent, act } from '../../../tests/helpers/render' @@ -86,3 +86,17 @@ describe('MapCompassPill', () => { expect(button.style.background).toBe('transparent') }) }) + +describe('MapCompassPill on the phone map', () => { + it('FE-COMP-MAPCOMPASS-007: appears only while the map is turned off north', () => { + const { map, rotateTo } = fakeCompassMap(0) + render() + expect(screen.queryByRole('button', { name: 'Reset north' })).not.toBeInTheDocument() + + rotateTo(30) + expect(screen.getByRole('button', { name: 'Reset north' })).toBeInTheDocument() + + rotateTo(0) + expect(screen.queryByRole('button', { name: 'Reset north' })).not.toBeInTheDocument() + }) +}) diff --git a/client/src/components/Map/MapCompassPill.tsx b/client/src/components/Map/MapCompassPill.tsx index 056018676..d83699cd8 100644 --- a/client/src/components/Map/MapCompassPill.tsx +++ b/client/src/components/Map/MapCompassPill.tsx @@ -15,7 +15,12 @@ export interface CompassMap { * (GL only) and built as the SAME frosted shell (padding 4 around a 34px button) * so its height and transparency match the POI pill exactly. */ -export function MapCompassPill({ map }: { map: CompassMap }) { +export function MapCompassPill({ map, onlyWhenRotated = false }: { + map: CompassMap + /** Shown only while the map is turned off north, the way a native map's compass + * appears when it has something to undo (the phone map, where room is short). */ + onlyWhenRotated?: boolean +}) { const [bearing, setBearing] = useState(() => map.getBearing()) useEffect(() => { @@ -25,6 +30,8 @@ export function MapCompassPill({ map }: { map: CompassMap }) { return () => { map.off('rotate', update) } }, [map]) + if (onlyWhenRotated && Math.abs(bearing) < 0.5) return null + return (
({ const trackRef = useRef(null) const pill = useActivePill(trackRef, '[data-active="true"]', [value, options.length]) - return () => ro.disconnect() - }, [value, options.length]) - return (
mobileTabs.find(tab => tab.id === id)?.label ?? id - // While the trip runs, today's chip carries a ring and a button jumps back to it - // from wherever the rail was scrolled (#2392). Null outside the trip's dates. + // While the trip runs, today's chip carries a ring and a dot (#2392). That mark + // is the whole of it: a second button beside the rail only crowded the chrome. + // Null outside the trip's dates. const todayDayId = findTodayDayId(days) - const jumpToToday = () => { - if (todayDayId == null || todayDayId === planner.selectedDayId) return - if (view === 'map') selectDayOnMap(todayDayId) - else planner.handleSelectDay(todayDayId, true) - } const onDayChipTap = (dayId: number) => { if (dayId === planner.selectedDayId) openSheet('day', { dayId }) @@ -542,20 +538,6 @@ export default function MTripShell({ ) })}
- {/* Back to today from anywhere on the rail (#2392). Mounted for the whole - running trip and dimmed while today is already open, so it never - appears under the thumb and shoves the rail aside. */} - {todayDayId != null && ( - - )} {/* Drop the day filter and show the whole trip (#2257). Map only: the plan timeline and the road trip chain are both single-day, so there is nothing to widen there. Stays mounted while a day is active rather than diff --git a/client/src/mobile/screens/trip/map/MMapArea.tsx b/client/src/mobile/screens/trip/map/MMapArea.tsx index 299b5f479..0e973ba91 100644 --- a/client/src/mobile/screens/trip/map/MMapArea.tsx +++ b/client/src/mobile/screens/trip/map/MMapArea.tsx @@ -4,7 +4,6 @@ import { MapCompassPill, type CompassMap } from '../../../../components/Map/MapC import { MAP_LAYER_SWITCHER_INSET, MAP_ROUND_CONTROL_SIZE } from '../../../../components/Map/MapLayerSwitcher' import { TripRouteOverviewPill, TripRouteOverviewPanel } from '../../../../components/Map/TripRouteOverview' import { DawarichTrailPill } from '../../../../components/Map/DawarichTrailPill' -import { MPlacesFilterPill } from './MPlacesFilterPill' import PoiCategoryPill from '../../../../components/Map/PoiCategoryPill' import { usePoiExplore } from '../../../../components/Map/usePoiExplore' import { useMergedMapPois } from '../../../../components/Map/useMergedMapPois' @@ -453,27 +452,38 @@ export default function MMapArea({ planner, shell }: MMapAreaProps) {
)} - {/* Compass, GL maps only (Leaflet cannot rotate). Both engines draw the base-layer - switcher in the bottom left corner, so the compass stands on top of it, on the - same left edge: beside it the two read as one crowded row next to the dock. - The offsets are inline because they are computed from the switcher's own - numbers. */} - {mapActive && glMap && ( -
- + {/* The left column, over the base-layer switcher both engines draw in the bottom + left corner: the recorded Dawarich route, and the compass, which only shows + while the map is turned off north. Two round controls a side at most, one + frosted style and one 8px gap, so neither corner crowds the dock. The offsets + are inline because they are computed from the switcher's own numbers. */} + {mapActive && (glMap || planner.dawarichEnabled) && ( +
+ {/* Kept in road-trip mode: the recorded route beside the planned one is + exactly the comparison a drive invites. */} + {!onStage && planner.dawarichEnabled && ( + + )} + {glMap && }
)} - {/* Whole-trip overview (#1736): the stages stack above their toggle on the right, - clear of the round-controls band below it and of the base-layer switcher and - the compass, which both sit bottom left. The offset is Tailwind rather than - inline because the compass band is identified by being the one element with - an inline --bottom-nav-h, and a second would make that ambiguous. The places - filter closes the stack, under the toggles, so the overview card stays - right above its own toggle: it decides which pins the plan map shows, so it is - there whatever else is; the stage draws its own pins and has no use for it. */} + {/* The right column: the whole-trip overview (#1736) over the locate button, its + stages stacking above their toggle. 20px off the edge and 8px over the locate + button, mirroring the left column. The places filter has no button here: it + is set in the places tab, whose filter the map's pins follow. The offset is + Tailwind rather than inline because the compass band is identified by being + the one element with an inline --bottom-nav-h, and a second would make that + ambiguous. */} {mapActive && !onStage && ( -
+
{!planner.roadtripActive && planner.overviewActive && ( )} - {/* Kept in road-trip mode: the recorded route beside the planned one is - exactly the comparison a drive invites. */} - {planner.dawarichEnabled && ( - - )} - shell.openSheet('placesFilter')} />
)}
diff --git a/client/src/mobile/screens/trip/map/MPlacesFilterPill.tsx b/client/src/mobile/screens/trip/map/MPlacesFilterPill.tsx deleted file mode 100644 index 4a57109dd..000000000 --- a/client/src/mobile/screens/trip/map/MPlacesFilterPill.tsx +++ /dev/null @@ -1,31 +0,0 @@ -import { SlidersHorizontal } from 'lucide-react' -import { MapTogglePill } from '../../../../components/Map/MapTogglePill' -import { useTripStore } from '../../../../store/tripStore' -import { countActivePlacesFilters } from '../../../../utils/placesFilter' -import { useTranslation } from '../../../../i18n' - -/** - * The phone map's way into the places filter: a round control in the right-hand - * stack, lit and badged with how many filters are narrowing the markers. The sheet - * it opens is the shell's 'placesFilter' sheet, so the button announces a dialog - * rather than a pressed state. - */ -export function MPlacesFilterPill({ onOpen }: { onOpen: () => void }) { - const { t } = useTranslation() - const filter = useTripStore(s => s.placesFilter) - const categoryFilters = useTripStore(s => s.placesCategoryFilter) - const ratingFilter = useTripStore(s => s.placesRatingFilter) - const count = countActivePlacesFilters({ filter, categoryFilters, ratingFilter }) - const label = count > 0 ? `${t('places.filters')} (${count})` : t('places.filters') - return ( - 0} - onToggle={onOpen} - label={label} - badge={count} - testId="places-filter-pill" - opensDialog - icon={} - /> - ) -} diff --git a/client/src/mobile/screens/trip/places/MPlacesFilterSheet.tsx b/client/src/mobile/screens/trip/places/MPlacesFilterSheet.tsx deleted file mode 100644 index c25998d23..000000000 --- a/client/src/mobile/screens/trip/places/MPlacesFilterSheet.tsx +++ /dev/null @@ -1,96 +0,0 @@ -import { RotateCcw, X } from 'lucide-react' -import MSheet from '../../../components/MSheet' -import MIconBtn from '../../../components/MIconBtn' -import MChip from '../../../components/MChip' -import { useTripStore } from '../../../../store/tripStore' -import { countActivePlacesFilters } from '../../../../utils/placesFilter' -import { useTranslation } from '../../../../i18n' -import type { Category, Place } from '../../../../types' -import { MCategoryFilterList, MRatingFloorChips } from './MPlacesFilterControls' -import { placesFilterTabs, poolHasTracks } from '../../../../components/Planner/usePlacesPool' - -interface MPlacesFilterSheetProps { - open: boolean - onClose: () => void - places: Place[] - categories: Category[] - toursEnabled: boolean -} - -/** Uppercase eyebrow over each group of the sheet. */ -function SectionTitle({ children }: { children: string }) { - return ( -
{children}
- ) -} - -/** - * The places filter, opened from the phone map: which pool to show, a minimum - * rating and the trip's categories, with one button that lifts them all. Every - * choice lands in the trip store at once, so the markers behind the sheet and the - * places list change with it (#1541). Routed as shell sheet 'placesFilter'. - */ -export default function MPlacesFilterSheet({ open, onClose, places, categories, toursEnabled }: MPlacesFilterSheetProps) { - const { t } = useTranslation() - const filter = useTripStore(s => s.placesFilter) - const categoryFilters = useTripStore(s => s.placesCategoryFilter) - const ratingFilter = useTripStore(s => s.placesRatingFilter) - const setFilter = useTripStore(s => s.setPlacesFilter) - const resetPlacesFilters = useTripStore(s => s.resetPlacesFilters) - const activeCount = countActivePlacesFilters({ filter, categoryFilters, ratingFilter }) - - const pools = placesFilterTabs(t, poolHasTracks(places, toursEnabled)) - const hasCategoryChoice = categories.length > 0 || places.some(p => p.category_id == null) - - return ( - // Opaque: the sheet opens over the map, and the default bar glass let the map's - // place names show through the chips and category rows (seen at 390px wide). - -
-
{t('places.filters')}
- - - -
- -
-
- {t('places.filterShow')} -
- {pools.map(pool => ( - setFilter(pool.id)}> - {pool.label} - - ))} -
-
- -
- {t('places.filterByRating')} - -
- - {hasCategoryChoice && ( -
- {t('categories.title')} -
- -
-
- )} -
- -
- -
-
- ) -} diff --git a/client/src/mobile/screens/trip/sheets/MTripSheets.tsx b/client/src/mobile/screens/trip/sheets/MTripSheets.tsx index fdfcfdcbf..a67bc01ee 100644 --- a/client/src/mobile/screens/trip/sheets/MTripSheets.tsx +++ b/client/src/mobile/screens/trip/sheets/MTripSheets.tsx @@ -27,7 +27,6 @@ import MMehrSheet from './MMehrSheet' import MTripSettingsSheet from './MTripSettingsSheet' import MNewTripSheet from '../../dashboard/MNewTripSheet' import MAssistantScreen from '../assistant/MAssistantScreen' -import MPlacesFilterSheet from '../places/MPlacesFilterSheet' import MRtStopSheet from '../roadtrip/MRtStopSheet' import MRtStaySheet from '../roadtrip/MRtStaySheet' import MRtKindSheet from '../roadtrip/MRtKindSheet' @@ -145,13 +144,6 @@ export default function MTripSheets({ planner, shell }: MTripSheetsProps) { onClose={shell.closeSheet} /> - {/* ── Planner-flag editors (also serve ?create= and the import review) ── */} diff --git a/client/tests/unit/mobile/trip/MMapArea.test.tsx b/client/tests/unit/mobile/trip/MMapArea.test.tsx index 07de56a65..4b1400a2f 100644 --- a/client/tests/unit/mobile/trip/MMapArea.test.tsx +++ b/client/tests/unit/mobile/trip/MMapArea.test.tsx @@ -954,39 +954,9 @@ describe('MMapArea and a booked night at the edge of the stage', () => { }) describe('MMapArea — places filter', () => { - it('FE-MOB-MAPAREA-046: the plan map offers the places filter, and a tap opens its sheet', () => { - const { shell } = renderArea({ trTab: 'plan' }) - const pill = screen.getByTestId('places-filter-pill') - expect(pill).toHaveAccessibleName('Filters') - // It opens a sheet: a dialog to announce, not an on/off state. - expect(pill).toHaveAttribute('aria-haspopup', 'dialog') - expect(pill).not.toHaveAttribute('aria-pressed') - act(() => { pill.click() }) - expect(shell.openSheet).toHaveBeenCalledWith('placesFilter') - }) - - it('FE-MOB-MAPAREA-047: the pill lights up and counts the filters narrowing the pins', () => { + it('FE-MOB-MAPAREA-046: the map has no filter button of its own; the places tab sets the filter its pins follow', () => { seedStore(useTripStore, { placesFilter: 'unplanned', placesRatingFilter: 4 }) renderArea({ trTab: 'plan' }) - const pill = screen.getByTestId('places-filter-pill') - expect(pill).toHaveClass('text-accent') - expect(pill).not.toHaveAttribute('aria-pressed') - expect(pill).toHaveAttribute('aria-haspopup', 'dialog') - expect(pill).toHaveAccessibleName('Filters (2)') - expect(screen.getByText('2')).toHaveAttribute('aria-hidden', 'true') - }) - - it('FE-MOB-MAPAREA-049: a road trip keeps the places filter on its plan map, Dawarich or not', () => { - // The stack used to stand down in road-trip mode unless Dawarich had a pill in - // it; the plan map still shows the trip's places there, so its filter stays. - renderArea({ trTab: 'plan' }, { roadtripActive: true, dawarichEnabled: false }) - expect(screen.getByTestId('places-filter-pill')).toBeInTheDocument() - }) - - it('FE-MOB-MAPAREA-048: the stage draws its own pins, so it has no places filter, and neither has a covered map', () => { - renderArea({ trTab: 'roadtrip', mapFront: true }) - expect(screen.queryByTestId('places-filter-pill')).not.toBeInTheDocument() - renderArea({ view: 'plan', mapFront: false }) expect(screen.queryByTestId('places-filter-pill')).not.toBeInTheDocument() }) }) diff --git a/client/tests/unit/mobile/trip/MPlacesFilterSheet.test.tsx b/client/tests/unit/mobile/trip/MPlacesFilterSheet.test.tsx deleted file mode 100644 index cc237db43..000000000 --- a/client/tests/unit/mobile/trip/MPlacesFilterSheet.test.tsx +++ /dev/null @@ -1,128 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import { fireEvent, render, screen, within } from '../../../helpers/render' -import MPlacesFilterSheet from '../../../../src/mobile/screens/trip/places/MPlacesFilterSheet' -import { useTripStore } from '../../../../src/store/tripStore' -import { resetAllStores, seedStore } from '../../../helpers/store' -import { buildPlace } from '../../../helpers/factories' -import type { Category, Place } from '../../../../src/types' - -// FE-MOB-PFSHEET-001 to FE-MOB-PFSHEET-009 - -const CATEGORIES = [ - { id: 1, name: 'Sights', color: '#123456', icon: 'landmark' }, - { id: 2, name: 'Food', color: '', icon: 'utensils' }, -] as unknown as Category[] - -const TAGGED = buildPlace({ id: 1, category_id: 1 }) -const BARE = buildPlace({ id: 2, category_id: null }) -const TRACK = buildPlace({ id: 3, category_id: 2, route_geometry: '[[1,2],[3,4]]' }) - -function renderSheet({ places = [TAGGED, BARE], categories = CATEGORIES, open = true, toursEnabled = false }: { - places?: Place[] - categories?: Category[] - open?: boolean - toursEnabled?: boolean -} = {}) { - const onClose = vi.fn() - render() - return { onClose } -} - -const group = (name: string) => screen.getByRole('group', { name }) - -describe('MPlacesFilterSheet', () => { - beforeEach(() => { - resetAllStores() - }) - - it('FE-MOB-PFSHEET-001: shows the pool, the rating floors and the categories under one title', async () => { - renderSheet() - const sheet = await screen.findByRole('dialog', { name: 'Filters' }) - expect(within(sheet).getByText('Show')).toBeInTheDocument() - expect(within(group('Show')).getAllByRole('button').map(b => b.textContent)).toEqual(['All', 'Unplanned', 'Planned']) - expect(within(group('Filter by rating')).getAllByRole('button').map(b => b.textContent)) - .toEqual(['All', '5+', '4+', '3+', '2+', '1+']) - expect(screen.getByRole('checkbox', { name: 'Sights' })).toBeInTheDocument() - expect(screen.getByRole('checkbox', { name: 'Food' })).toBeInTheDocument() - expect(screen.getByRole('checkbox', { name: 'No Category' })).toBeInTheDocument() - }) - - it('FE-MOB-PFSHEET-002: the tracks pool only shows once a place carries a track', async () => { - renderSheet({ places: [TAGGED, TRACK] }) - await screen.findByRole('dialog', { name: 'Filters' }) - expect(within(group('Show')).getByRole('button', { name: 'Tracks' })).toBeInTheDocument() - expect(screen.queryByRole('checkbox', { name: 'No Category' })).not.toBeInTheDocument() - }) - - it('hides Tracks from the map filter while Tours is enabled', async () => { - const tourTrack = buildPlace({ id: 4, route_geometry: '[[5,6],[7,8]]' }) - renderSheet({ places: [TAGGED, TRACK, tourTrack], toursEnabled: true }) - await screen.findByRole('dialog', { name: 'Filters' }) - expect(within(group('Show')).queryByRole('button', { name: 'Tracks' })).not.toBeInTheDocument() - }) - - it('FE-MOB-PFSHEET-003: picking a pool writes it to the trip store', async () => { - renderSheet() - await screen.findByRole('dialog', { name: 'Filters' }) - const show = group('Show') - expect(within(show).getByRole('button', { name: 'All' })).toHaveAttribute('aria-pressed', 'true') - fireEvent.click(within(show).getByRole('button', { name: 'Unplanned' })) - expect(useTripStore.getState().placesFilter).toBe('unplanned') - // The chosen chip says so to a screen reader, and only that one. - expect(within(show).getByRole('button', { name: 'Unplanned' })).toHaveAttribute('aria-pressed', 'true') - expect(within(show).getByRole('button', { name: 'All' })).toHaveAttribute('aria-pressed', 'false') - }) - - it('FE-MOB-PFSHEET-004: picking a floor writes the rating filter to the trip store', async () => { - renderSheet() - await screen.findByRole('dialog', { name: 'Filters' }) - const floors = group('Filter by rating') - fireEvent.click(within(floors).getByRole('button', { name: '3+' })) - expect(useTripStore.getState().placesRatingFilter).toBe(3) - expect(within(floors).getByRole('button', { name: '3+' })).toHaveAttribute('aria-pressed', 'true') - expect(within(floors).getByRole('button', { name: 'All' })).toHaveAttribute('aria-pressed', 'false') - }) - - it('FE-MOB-PFSHEET-005: categories toggle in and out of the shared set, "no category" included', async () => { - renderSheet() - await screen.findByRole('dialog', { name: 'Filters' }) - fireEvent.click(screen.getByRole('checkbox', { name: 'Food' })) - fireEvent.click(screen.getByRole('checkbox', { name: 'No Category' })) - expect([...useTripStore.getState().placesCategoryFilter]).toEqual(['2', 'uncategorized']) - expect(screen.getByRole('checkbox', { name: 'Food' })).toHaveAttribute('aria-checked', 'true') - fireEvent.click(screen.getByRole('checkbox', { name: 'Food' })) - expect([...useTripStore.getState().placesCategoryFilter]).toEqual(['uncategorized']) - }) - - it('FE-MOB-PFSHEET-006: reset lifts every filter, and stays off while nothing filters', async () => { - seedStore(useTripStore, { placesFilter: 'planned', placesCategoryFilter: new Set(['1']), placesRatingFilter: 5 }) - renderSheet() - await screen.findByRole('dialog', { name: 'Filters' }) - const reset = screen.getByRole('button', { name: 'Reset' }) - expect(reset).toBeEnabled() - fireEvent.click(reset) - const s = useTripStore.getState() - expect(s.placesFilter).toBe('all') - expect(s.placesCategoryFilter.size).toBe(0) - expect(s.placesRatingFilter).toBe('all') - expect(screen.getByRole('button', { name: 'Reset' })).toBeDisabled() - }) - - it('FE-MOB-PFSHEET-007: without any category to choose, the categories section is left out', async () => { - renderSheet({ places: [TAGGED], categories: [] }) - const sheet = await screen.findByRole('dialog', { name: 'Filters' }) - expect(within(sheet).queryByText('Categories')).not.toBeInTheDocument() - expect(screen.queryByRole('checkbox')).not.toBeInTheDocument() - }) - - it('FE-MOB-PFSHEET-008: the close button hands back to the caller', async () => { - const { onClose } = renderSheet() - fireEvent.click(within(await screen.findByRole('dialog', { name: 'Filters' })).getByRole('button', { name: 'Close' })) - expect(onClose).toHaveBeenCalledTimes(1) - }) - - it('FE-MOB-PFSHEET-009: nothing is rendered while closed', () => { - renderSheet({ open: false }) - expect(screen.queryByRole('dialog', { name: 'Filters' })).not.toBeInTheDocument() - }) -}) diff --git a/client/tests/unit/mobile/trip/MTripSheets.test.tsx b/client/tests/unit/mobile/trip/MTripSheets.test.tsx index 2c939d709..d5d3edb14 100644 --- a/client/tests/unit/mobile/trip/MTripSheets.test.tsx +++ b/client/tests/unit/mobile/trip/MTripSheets.test.tsx @@ -11,7 +11,7 @@ import { useSettingsStore } from '../../../../src/store/settingsStore' import { useTripStore } from '../../../../src/store/tripStore' import { buildPlanner, buildShell } from '../../../helpers/mobileTrip' import { resetAllStores, seedStore } from '../../../helpers/store' -import { fireEvent, render, screen, waitFor, within } from '../../../helpers/render' +import { fireEvent, render, screen, waitFor } from '../../../helpers/render' // FE-MOB-SHOST-001 to FE-MOB-SHOST-029 and FE-MOB-SHOST-032 to FE-MOB-SHOST-034 (030 and 031 live in MTripSheets.members.test.tsx) // @@ -240,15 +240,8 @@ describe('MTripSheets', () => { } }) - it('FE-MOB-SHOST-033: the map\'s places filter opens for its own id and closes through the shell', async () => { - const { shell } = renderHost({}, { sheet: { id: 'placesFilter' } }) - const sheet = await screen.findByRole('dialog', { name: 'Filters' }) - fireEvent.click(within(sheet).getByRole('button', { name: 'Close' })) - expect(shell.closeSheet).toHaveBeenCalledTimes(1) - }) - - it('FE-MOB-SHOST-033b: no places filter while another sheet is open', () => { - renderHost({}, { sheet: { id: 'day' } }) + it('FE-MOB-SHOST-033: hosts no places filter of its own any more; the places tab carries it', () => { + renderHost({}, { sheet: { id: 'placesFilter' } }) expect(screen.queryByRole('dialog', { name: 'Filters' })).not.toBeInTheDocument() }) diff --git a/client/tests/unit/mobile/trip/MTripShell.test.tsx b/client/tests/unit/mobile/trip/MTripShell.test.tsx index 085e79b57..36275a99f 100644 --- a/client/tests/unit/mobile/trip/MTripShell.test.tsx +++ b/client/tests/unit/mobile/trip/MTripShell.test.tsx @@ -668,31 +668,25 @@ describe('MTripShell', () => { { id: 22, day_number: 2, date: todayIso() }, { id: 23, day_number: 3, date: shift(1) }, ] as unknown as Day[] - const jump = () => screen.getByRole('button', { name: 'mobileTrip.jumpToToday' }) + const jump = () => screen.queryByRole('button', { name: 'mobileTrip.jumpToToday' }) - it('FE-MOB-SHELL-090: marks today and jumps back to it from another day', () => { - const { planner, container } = renderShell({ days: running(), selectedDayId: 21 } as Partial) + it('FE-MOB-SHELL-090: marks today on its chip, and puts no extra button beside the rail', () => { + const { container } = renderShell({ days: running(), selectedDayId: 21 } as Partial) const marked = container.querySelectorAll('[data-today]') expect(marked).toHaveLength(1) expect(marked[0].className).toContain('ring-inset') expect(marked[0]).toHaveTextContent('mobileTrip.today') - - expect(jump()).toBeEnabled() - fireEvent.click(jump()) - expect(planner.handleSelectDay).toHaveBeenLastCalledWith(22, true) + expect(jump()).toBeNull() }) - it('FE-MOB-SHELL-091: with today open the button stays, dimmed, so the rail does not move', () => { + it('FE-MOB-SHELL-091: with today open the active chip keeps its own look, the dot says which day is today', () => { const { container } = renderShell({ days: running(), selectedDayId: 22 } as Partial) - expect(jump()).toBeDisabled() - // The active chip keeps its own look; the dot still says which day is today. expect(container.querySelector('[data-today]')?.className).not.toContain('ring-inset') }) - it('FE-MOB-SHELL-092: outside the trip dates there is no today and no button', () => { + it('FE-MOB-SHELL-092: outside the trip dates there is no today', () => { const { container } = renderShell() expect(container.querySelector('[data-today]')).toBeNull() - expect(screen.queryByRole('button', { name: 'mobileTrip.jumpToToday' })).toBeNull() }) }) From 6d093d1102596025b601b4fd0aaf7adc7122e298 Mon Sep 17 00:00:00 2001 From: Maurice Date: Fri, 6 Nov 2026 12:37:00 +0100 Subject: [PATCH 056/589] feat(mobile): one glass language across the day plan's controls - The rename and reorder controls beside the day's name, and the day and weather chips on the timeline card, are now round or pill glass controls of one height, so they read as tappable; the stay chips follow. - A leg between two stops is one pill, as on the desktop: the mode, the time in full weight and the distance beside it, larger and without a dot. - The timeline flows under the up-next card at a fixed 12px, whatever its height, instead of an offset that left a gap when the stop has no address. - The places bar on the map wears the day rail's glass at its 36px height. - A context menu stays inside all four edges of the screen, measured at its real size rather than mid-animation, and scrolls when taller than it. --- .../components/Map/PoiCategoryPill.test.tsx | 11 +++++ client/src/components/Map/PoiCategoryPill.tsx | 25 ++++++++-- .../shared/ContextMenu.extra.test.tsx | 23 +++++++-- client/src/components/shared/ContextMenu.tsx | 24 ++++++--- .../src/mobile/screens/trip/map/MMapArea.tsx | 1 + .../screens/trip/plan/MPlanTimeline.tsx | 49 ++++++++++++------- .../screens/trip/plan/MPlanTimelineRows.tsx | 28 +++++------ .../unit/mobile/trip/MPlanTimeline.test.tsx | 14 ++++-- .../mobile/trip/MPlanTimelineRows.test.tsx | 7 ++- 9 files changed, 129 insertions(+), 53 deletions(-) diff --git a/client/src/components/Map/PoiCategoryPill.test.tsx b/client/src/components/Map/PoiCategoryPill.test.tsx index 669255198..31aaffd7f 100644 --- a/client/src/components/Map/PoiCategoryPill.test.tsx +++ b/client/src/components/Map/PoiCategoryPill.test.tsx @@ -146,6 +146,17 @@ describe('PoiCategoryPill', () => { } }) + it('FE-COMP-POIPILL-013b: in the phone chrome the bar wears the day rail glass at its 36px height', () => { + pill({ categories: WITH_PLUGINS, fullWidth: true, phoneChrome: true }) + for (const button of screen.getAllByRole('button')) { + expect(button.style.minWidth).toBe('34px') + expect(button.style.height).toBe('28px') + } + const bar = screen.getAllByRole('button')[0].closest('[style*="overflow"]') as HTMLElement + expect(bar.style.padding).toBe('3px') + expect(bar.style.background).toBe('var(--m-glass)') + }) + it('FE-COMP-POIPILL-014: a desktop segment keeps its 34px instead of shrinking in a narrow corridor', () => { pill({ categories: WITH_PLUGINS }) for (const button of screen.getAllByRole('button')) { diff --git a/client/src/components/Map/PoiCategoryPill.tsx b/client/src/components/Map/PoiCategoryPill.tsx index a9a623b3f..d4e1c8faf 100644 --- a/client/src/components/Map/PoiCategoryPill.tsx +++ b/client/src/components/Map/PoiCategoryPill.tsx @@ -18,10 +18,23 @@ interface Props { * The phone map gives it the full width between the screen margins; on * desktop it floats, so it stays content-width there. */ fullWidth?: boolean + /** The phone shell's chrome: the glass, hairline and 36px height of the day rail + * and the tab switch above it, so the three bars read as one set. */ + phoneChrome?: boolean } // The touch target every segment keeps, however many categories there are. const SEGMENT = 34 +// On the phone the segment is as tall as a day chip; it keeps its width. +const PHONE_SEGMENT_HEIGHT = 28 + +/** The phone shell's glass, as the day rail draws it (bg/border --m-glass/--m-gbr). */ +const PHONE_GLASS: React.CSSProperties = { + background: 'var(--m-glass)', + border: '1px solid var(--m-gbr)', + backdropFilter: 'blur(24px) saturate(170%)', + WebkitBackdropFilter: 'blur(24px) saturate(170%)', +} // How far one wheel step moves the bar. Firefox counts a mouse wheel in lines and // some drivers in pages; a line moves about one segment, a page one bar width. @@ -50,10 +63,11 @@ interface SegmentProps { loading: boolean failed: boolean fullWidth?: boolean + phoneChrome?: boolean onToggle: (key: string) => void } -function Segment({ cat, on, loading, failed, fullWidth, onToggle }: Readonly) { +function Segment({ cat, on, loading, failed, fullWidth, phoneChrome, onToggle }: Readonly) { return ( )} @@ -476,15 +481,23 @@ function TimelineHeader({ tl, dayLabel, openLabel, weatherLabel, onOpenDay, onOp the browser's: while the chips overflow they pan first, and the pager takes over at their end or when they fit. */} + {/* 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. */} {tl.hotelChips.map(chip => ( :
{inner}
diff --git a/client/tests/unit/mobile/trip/MPlanTimeline.test.tsx b/client/tests/unit/mobile/trip/MPlanTimeline.test.tsx index e348b4996..02db2ac9e 100644 --- a/client/tests/unit/mobile/trip/MPlanTimeline.test.tsx +++ b/client/tests/unit/mobile/trip/MPlanTimeline.test.tsx @@ -176,14 +176,19 @@ describe('MPlanTimeline', () => { expect(screen.queryByText('Museum Rd 1')).not.toBeInTheDocument() }) - it('FE-MOB-PLTL-004: collapses the reserved space when the day has no up next', () => { + it('FE-MOB-PLTL-004: the timeline follows the up-next card in one column, and starts at the top without one', () => { const { container, unmount } = renderTimeline() - expect(card(container).style.top).toContain('216px') + // The card flows under the up-next card at a fixed gap, whatever its height, + // rather than at an offset that assumed an address line (a gap without one). + const upNext = screen.getByText('mobileTrip.upNext').closest('button') as HTMLElement + expect(upNext.nextElementSibling).toBe(card(container)) + expect(card(container).parentElement).toHaveClass('flex-col', 'gap-3') + expect(card(container).style.top).toBe('') unmount() const empty = renderTimeline({ upNext: null, rows: [], merged: [] }) expect(screen.queryByText('mobileTrip.upNext')).not.toBeInTheDocument() - expect(card(empty.container).style.top).toContain('102px') + expect(card(empty.container).previousElementSibling).toBeNull() }) }) @@ -532,7 +537,8 @@ describe('MPlanTimeline', () => { const { container } = renderTimeline({}, {}, { mode: 'edit' }) expect(screen.queryByText('mobileTrip.upNext')).not.toBeInTheDocument() - expect(card(container).style.top).toContain('140px') + // The edit header takes the up-next card's place, the timeline right under it. + expect(card(container).previousElementSibling).toContainElement(screen.getByLabelText('mobileTrip.renameDay')) }) it('FE-MOB-PLTL-026: splits the day title into city pills', () => { diff --git a/client/tests/unit/mobile/trip/MPlanTimelineRows.test.tsx b/client/tests/unit/mobile/trip/MPlanTimelineRows.test.tsx index 230d077d1..c4f60b9e3 100644 --- a/client/tests/unit/mobile/trip/MPlanTimelineRows.test.tsx +++ b/client/tests/unit/mobile/trip/MPlanTimelineRows.test.tsx @@ -390,7 +390,10 @@ describe('ConnRow', () => { const { container } = render() expect(screen.getByText('14 min')).toBeInTheDocument() - expect(screen.getByText('· 5.4 km')).toBeInTheDocument() + // The distance sits in the same pill as the time, with no dot between them. + expect(screen.getByText('5.4 km')).toBeInTheDocument() + expect(screen.getByText('14 min').parentElement).toBe(screen.getByText('5.4 km').parentElement) + expect(container.textContent).not.toContain('·') expect(container.querySelector('button')).toBeNull() }) @@ -448,7 +451,7 @@ describe('HotelConnRow', () => { expect(top.children[0].textContent).toBe('Hotel Sacher') expect(top.children[1].textContent).toContain('14 min') - expect(top.children[1].textContent).toContain('· 5.4 km') + expect(top.children[1].textContent).toContain('5.4 km') unmount() const bottom = render() From c5cb39c27b7ea611e387435dc8d6b31da950ceee Mon Sep 17 00:00:00 2001 From: Maurice Date: Fri, 6 Nov 2026 12:41:57 +0100 Subject: [PATCH 057/589] feat(mobile): one Maps button for every map app, actions as one glass group The day plan offered Google Maps and CoMaps as two tiles. One Maps button now opens the day in whichever app the traveller picks: Google Maps, Apple Maps with the stops between as waypoints, CoMaps, Waze and on Android any other map app, the last two to the first stop, which they say. The preferred map app from the settings opens straight away. The day's actions sit together on one glass surface as round icons over their labels, and the up-next card wears the same surface as the timeline card under it. --- .../components/Planner/dayRouteApps.test.ts | 49 +++++++++++ client/src/components/Planner/dayRouteApps.ts | 87 +++++++++++++++++++ .../screens/trip/plan/MPlanTimeline.tsx | 57 +++++++----- .../screens/trip/plan/MRouteAppsSheet.tsx | 63 ++++++++++++++ .../screens/trip/plan/useMPlanTimeline.ts | 14 ++- .../screens/trip/roadtrip/MRoadtripTab.tsx | 2 +- .../unit/mobile/trip/MPlanTimeline.test.tsx | 43 +++++++-- .../unit/mobile/trip/useMPlanTimeline.test.ts | 7 ++ shared/src/i18n/ar/mobileTrip.ts | 3 + shared/src/i18n/az/mobileTrip.ts | 3 + shared/src/i18n/br/mobileTrip.ts | 3 + shared/src/i18n/ca/mobileTrip.ts | 3 + shared/src/i18n/cs/mobileTrip.ts | 3 + shared/src/i18n/de/mobileTrip.ts | 3 + shared/src/i18n/en/mobileTrip.ts | 3 + shared/src/i18n/es/mobileTrip.ts | 3 + shared/src/i18n/et/mobileTrip.ts | 3 + shared/src/i18n/fr/mobileTrip.ts | 3 + shared/src/i18n/gr/mobileTrip.ts | 3 + shared/src/i18n/he/mobileTrip.ts | 3 + shared/src/i18n/hu/mobileTrip.ts | 3 + shared/src/i18n/id/mobileTrip.ts | 3 + shared/src/i18n/it/mobileTrip.ts | 3 + shared/src/i18n/ja/mobileTrip.ts | 3 + shared/src/i18n/ko/mobileTrip.ts | 3 + shared/src/i18n/nl/mobileTrip.ts | 3 + shared/src/i18n/pl/mobileTrip.ts | 3 + shared/src/i18n/ru/mobileTrip.ts | 3 + shared/src/i18n/sk/mobileTrip.ts | 3 + shared/src/i18n/sv/mobileTrip.ts | 3 + shared/src/i18n/th/mobileTrip.ts | 3 + shared/src/i18n/tr/mobileTrip.ts | 3 + shared/src/i18n/uk/mobileTrip.ts | 3 + shared/src/i18n/vi/mobileTrip.ts | 3 + shared/src/i18n/zh-TW/mobileTrip.ts | 3 + shared/src/i18n/zh/mobileTrip.ts | 3 + 36 files changed, 378 insertions(+), 28 deletions(-) create mode 100644 client/src/components/Planner/dayRouteApps.test.ts create mode 100644 client/src/components/Planner/dayRouteApps.ts create mode 100644 client/src/mobile/screens/trip/plan/MRouteAppsSheet.tsx diff --git a/client/src/components/Planner/dayRouteApps.test.ts b/client/src/components/Planner/dayRouteApps.test.ts new file mode 100644 index 000000000..44eb9aecc --- /dev/null +++ b/client/src/components/Planner/dayRouteApps.test.ts @@ -0,0 +1,49 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { dayRouteTargets, generateAppleMapsUrl, generateGeoUrl, generateWazeUrl } from './dayRouteApps'; + +const A = { lat: 35.71, lng: 139.79, name: 'Senso-ji' }; +const B = { lat: 35.72, lng: 139.77, name: 'Ueno Park' }; +const C = { lat: 35.66, lng: 139.7, name: 'Shibuya' }; + +function userAgent(ua: string) { + vi.spyOn(navigator, 'userAgent', 'get').mockReturnValue(ua); +} + +afterEach(() => vi.restoreAllMocks()); + +describe('dayRouteApps', () => { + it('opens one stop in Apple Maps as a named pin', () => { + expect(generateAppleMapsUrl([A])).toBe('https://maps.apple.com/?ll=35.71,139.79&q=Senso-ji'); + }); + + it('hands Apple Maps the whole day, the stops between as waypoints, in the travel mode', () => { + expect(generateAppleMapsUrl([A, B, C], 'walking')).toBe( + 'https://maps.apple.com/directions?source=35.71,139.79&destination=35.66,139.7&waypoint=35.72,139.77&mode=walking' + ); + }); + + it('sends Waze and geo: to the first stop, since they take one place', () => { + expect(generateWazeUrl([A, B])).toBe('https://waze.com/ul?ll=35.71,139.79&navigate=yes'); + expect(generateGeoUrl([A, B])).toBe('geo:35.71,139.79?q=35.71,139.79(Senso-ji)'); + expect(generateWazeUrl([])).toBeNull(); + }); + + it('offers Apple Maps on an iPhone and marks the one-place apps for a multi-stop day', () => { + userAgent('Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X)'); + const targets = dayRouteTargets([A, B], 'driving'); + expect(targets.map((t) => t.id)).toEqual(['google', 'apple', 'comaps', 'waze']); + expect(targets.find((t) => t.id === 'waze')?.firstStopOnly).toBe(true); + expect(targets.find((t) => t.id === 'google')?.firstStopOnly).toBeUndefined(); + }); + + it('offers the generic map-app link on Android instead of Apple Maps', () => { + userAgent('Mozilla/5.0 (Linux; Android 15)'); + expect(dayRouteTargets([A], 'driving').map((t) => t.id)).toEqual(['google', 'comaps', 'waze', 'geo']); + // A single stop is the whole day, so nothing is cut short. + expect(dayRouteTargets([A], 'driving').some((t) => t.firstStopOnly)).toBe(false); + }); + + it('offers nothing for a day without a located stop', () => { + expect(dayRouteTargets([], 'driving')).toEqual([]); + }); +}); diff --git a/client/src/components/Planner/dayRouteApps.ts b/client/src/components/Planner/dayRouteApps.ts new file mode 100644 index 000000000..9501eaf4d --- /dev/null +++ b/client/src/components/Planner/dayRouteApps.ts @@ -0,0 +1,87 @@ +import { + generateCoMapsUrl, + generateGoogleMapsUrl, + type NamedWaypoint, + type RouteProfileKey, +} from '../Map/RouteCalculator'; +import { showsAppleMaps, showsGeoUri, type NavigationAppId } from './placeNavigation'; + +/** + * The map apps a day's route can be handed to, behind the plan's one Maps + * button. Same stops as every other export (dayExportStops), so the app shows + * the day the plan shows. + * + * Not every app takes a whole route. Google Maps, Apple Maps and CoMaps do (each + * in its own way, see the builders); Waze and the generic geo: link navigate to + * one place only, so they lead to the first stop and say so rather than quietly + * dropping the rest of the day. + */ +export interface DayRouteTarget { + id: NavigationAppId; + /** Product name, never translated; the generic entry carries labelKey instead. */ + label: string; + labelKey?: string; + url: string; + /** True when the app only gets the first stop, not the whole route. */ + firstStopOnly?: boolean; +} + +/** Apple Maps' directions modes. Cycling exists there; anything else drives. */ +function appleMode(profile: RouteProfileKey): string { + if (profile === 'walking') return 'walking'; + if (profile === 'cycling') return 'cycling'; + return 'driving'; +} + +const point = (p: NamedWaypoint) => `${p.lat},${p.lng}`; +const label = (p: NamedWaypoint) => encodeURIComponent(p.name?.trim() || point(p)); + +/** + * Apple Maps for a day: one stop opens as a pin with its name, more go as + * directions with the stops between as waypoints (Apple's unified Maps URLs, + * which iOS, macOS and the web version all read). + */ +export function generateAppleMapsUrl(places: NamedWaypoint[], profile: RouteProfileKey = 'driving'): string | null { + const valid = places.filter((p) => p.lat != null && p.lng != null); + if (valid.length === 0) return null; + if (valid.length === 1) return `https://maps.apple.com/?ll=${point(valid[0])}&q=${label(valid[0])}`; + const [first, ...rest] = valid; + const last = rest[rest.length - 1]; + const between = rest + .slice(0, -1) + .map((p) => `&waypoint=${point(p)}`) + .join(''); + return `https://maps.apple.com/directions?source=${point(first)}&destination=${point(last)}${between}&mode=${appleMode(profile)}`; +} + +/** Waze navigates to one place; the day's first stop is where the drive starts. */ +export function generateWazeUrl(places: NamedWaypoint[]): string | null { + const first = places.find((p) => p.lat != null && p.lng != null); + return first ? `https://waze.com/ul?ll=${point(first)}&navigate=yes` : null; +} + +/** The generic Android link, handed to whichever map app is installed; one place too. */ +export function generateGeoUrl(places: NamedWaypoint[]): string | null { + const first = places.find((p) => p.lat != null && p.lng != null); + return first ? `geo:${point(first)}?q=${point(first)}(${label(first)})` : null; +} + +/** Every app the day can be opened in on this device, in the order they are offered. */ +export function dayRouteTargets(stops: NamedWaypoint[], profile: RouteProfileKey): DayRouteTarget[] { + const out: DayRouteTarget[] = []; + const push = (target: Omit, url: string | null) => { + if (url) out.push({ ...target, url }); + }; + push({ id: 'google', label: 'Google Maps' }, generateGoogleMapsUrl(stops)); + if (showsAppleMaps()) push({ id: 'apple', label: 'Apple Maps' }, generateAppleMapsUrl(stops, profile)); + push({ id: 'comaps', label: 'CoMaps' }, generateCoMapsUrl(stops, profile)); + const located = stops.filter((p) => p.lat != null && p.lng != null).length; + push({ id: 'waze', label: 'Waze', firstStopOnly: located > 1 }, generateWazeUrl(stops)); + if (showsGeoUri()) { + push( + { id: 'geo', label: 'geo:', labelKey: 'inspector.otherMapApp', firstStopOnly: located > 1 }, + generateGeoUrl(stops) + ); + } + return out; +} diff --git a/client/src/mobile/screens/trip/plan/MPlanTimeline.tsx b/client/src/mobile/screens/trip/plan/MPlanTimeline.tsx index 6b3fbb88d..b286fba16 100644 --- a/client/src/mobile/screens/trip/plan/MPlanTimeline.tsx +++ b/client/src/mobile/screens/trip/plan/MPlanTimeline.tsx @@ -1,5 +1,5 @@ import { useEffect, useState, type MouseEvent } from 'react' -import { ArrowRight, BedDouble, CalendarDays, CalendarRange, ChevronRight, Compass, LogIn, LogOut, MapPin, Pencil, PencilLine, Route, Ticket, TrainFront, Undo2 } from 'lucide-react' +import { ArrowRight, BedDouble, CalendarDays, CalendarRange, ChevronRight, LogIn, LogOut, Map as MapIcon, MapPin, Pencil, PencilLine, Route, Ticket, TrainFront, Undo2 } from 'lucide-react' import type { LucideIcon } from 'lucide-react' import { useContextMenu, ContextMenu } from '../../../../components/shared/ContextMenu' import MarkdownText from '../../../../components/shared/MarkdownText' @@ -22,8 +22,9 @@ import type { MPlanTimelineProps } from '../MTripShell' import type { MergedItem } from '../../../../utils/dayMerge' import type { RouteSegment } from '../../../../types' import type { Assignment } from '../../../../types' -import type { ComponentType, ReactNode } from 'react' -import GoogleMapsIcon from '../../../../components/shared/GoogleMapsIcon' +import type { ReactNode } from 'react' +import { useSettingsStore } from '../../../../store/settingsStore' +import MRouteAppsSheet, { openRouteTarget } from './MRouteAppsSheet' import MDayPager from '../../../components/MDayPager' /** @@ -181,11 +182,23 @@ function PlanDayPage({ planner, shell, dayId: pageDayId, active, editing, legMen const chrome = { editing, t, language: tl.language, timeFormat: tl.timeFormat } + // One Maps button for every app the day can be opened in: the preferred app + // from settings (#2423) opens straight away, otherwise the sheet asks. + const [mapsOpen, setMapsOpen] = useState(false) + const preferredNavApp = useSettingsStore(s => s.settings.preferred_nav_app) + const openMaps = () => { + const preferred = preferredNavApp ? tl.routeTargets.find(target => target.id === preferredNavApp) : undefined + if (preferred) openRouteTarget(preferred) + else setMapsOpen(true) + } + return ( - // One column under the day chips: the UP-NEXT card (go mode) or the edit - // header, then the timeline card filling the rest, 12px apart whatever height - // the card above it has. A day without an up-next starts the timeline right - // under the chips. + <> + setMapsOpen(false)} targets={tl.routeTargets} t={t} /> + {/* One column under the day chips: the UP-NEXT card (go mode) or the edit + header, then the timeline card filling the rest, 12px apart whatever height + the card above it has. A day without an up-next starts the timeline right + under the chips. */}
{!editing && } {editing && } @@ -308,7 +321,9 @@ function PlanDayPage({ planner, shell, dayId: pageDayId, active, editing, legMen )} {editing && ( -
+ // The day's actions as one group on one glass surface, the way iOS groups + // its controls: each a round icon over its label. +
void tl.optimize()} /> - {tl.canExportRoute && ( - <> - - - + {tl.canExportRoute && tl.routeTargets.length > 0 && ( + )}
)}
+ ) } @@ -347,7 +360,9 @@ function UpNextCard({ tl, t, onOpen }: { ) } diff --git a/client/src/mobile/screens/trip/plan/MRouteAppsSheet.tsx b/client/src/mobile/screens/trip/plan/MRouteAppsSheet.tsx new file mode 100644 index 000000000..dc668620e --- /dev/null +++ b/client/src/mobile/screens/trip/plan/MRouteAppsSheet.tsx @@ -0,0 +1,63 @@ +import { ChevronRight, MapPinned } from 'lucide-react'; +import type { DayRouteTarget } from '../../../../components/Planner/dayRouteApps'; +import type { TranslationFn } from '../../../../types'; +import MSheet from '../../../components/MSheet'; + +/** Opens a target: a web link in a new tab (the app takes it over), geo: in place. */ +export function openRouteTarget(target: DayRouteTarget): void { + if (target.url.startsWith('geo:')) window.location.assign(target.url); + else window.open(target.url, '_blank', 'noopener,noreferrer'); +} + +/** + * The plan's one Maps button, asked: which app should get the day. A docked + * sheet of the apps this device can open, each a full-width row; the ones that + * take a single place say they only get the first stop. + */ +export default function MRouteAppsSheet({ + open, + onClose, + targets, + t, +}: { + open: boolean; + onClose: () => void; + targets: DayRouteTarget[]; + t: TranslationFn; +}) { + return ( + +
+
+
+
+ {targets.map((target) => ( + + ))} +
+
+
+ ); +} diff --git a/client/src/mobile/screens/trip/plan/useMPlanTimeline.ts b/client/src/mobile/screens/trip/plan/useMPlanTimeline.ts index 45a4aad42..37c8f4ca0 100644 --- a/client/src/mobile/screens/trip/plan/useMPlanTimeline.ts +++ b/client/src/mobile/screens/trip/plan/useMPlanTimeline.ts @@ -9,6 +9,7 @@ import { dayWeatherAnchor } from '../../../../utils/dayWeather' import { metadataWithLegPositions, planMergedOrder, withTransportPositions } from '../../../../utils/mergedOrder' import { getDisplayTimeForDay, getMergedItems, getTransportForDay, hasCarrierEndpointOnDay, isCarrierTransport, stopDayIds, yieldTimedBookings } from '../../../../utils/dayMerge' import { dayCoMapsUrl, dayExportStops, dayGoogleMapsUrl, optimizeDayOrder, type DayCarrier } from '../../../../components/Planner/dayRoute' +import { dayRouteTargets } from '../../../../components/Planner/dayRouteApps' import type { PlannedTransitLeg, TransitLeg } from '../../../../components/Planner/transitLeg' import { useTransitLegPlanner } from '../../../../components/Planner/useTransitLegPlanner' import { dayItemOverrun } from '../../../../components/Tours/tourDayTime' @@ -316,6 +317,17 @@ export function useMPlanTimeline(planner: TripPlanner, forDayId?: number | null) [day, days, dayAssignments, tripAccommodations, settings, dayCarrier], ) + // The apps behind the plan's one Maps button, with the same bookended stops. + const routeTargets = useMemo( + () => (day + ? dayRouteTargets( + dayExportStops(day, days, dayAssignments, tripAccommodations, settings.optimize_from_accommodation !== false, dayCarrier), + day.default_transport_mode ?? routeProfile, + ) + : []), + [day, days, dayAssignments, tripAccommodations, settings, dayCarrier, routeProfile], + ) + const exportGoogleMaps = useCallback(() => { if (!day) return // Bookend the exported route with the day's accommodation the same way the @@ -401,7 +413,7 @@ export function useMPlanTimeline(planner: TripPlanner, forDayId?: number | null) moveRow, removeAssignment, editAssignment, editTransport, openTransitJourney, moveRowTo, addPlace, addBooking, addTransport, - optimize, canExportRoute, exportGoogleMaps, exportCoMaps, renameDay, fullPlaceOf, + optimize, canExportRoute, routeTargets, exportGoogleMaps, exportCoMaps, renameDay, fullPlaceOf, routeModeOptions, setLegMode, transitLegFor, planTransitLeg, journeyLate, tourOverrun, } } diff --git a/client/src/mobile/screens/trip/roadtrip/MRoadtripTab.tsx b/client/src/mobile/screens/trip/roadtrip/MRoadtripTab.tsx index f925cc5ea..44d7f7b66 100644 --- a/client/src/mobile/screens/trip/roadtrip/MRoadtripTab.tsx +++ b/client/src/mobile/screens/trip/roadtrip/MRoadtripTab.tsx @@ -401,7 +401,7 @@ function UpNext({ planner, shell, rt, stageDayId, onOpen }: { const targets = place ? getNavigationTargets(place) : [] return ( -
+
+ )} + {/* No retry for a dead chunk — React.lazy would throw again immediately. */} + {!isChunkError && ( + + )} +
-
- {/* No retry for a dead chunk — React.lazy would throw again immediately. */} - {!isChunkError && ( - - )} - {(!isPanel || isChunkError) && ( - + {/* Kept, folded away: TREK is self-hosted, so the person seeing this is + often the same person who will paste it into an issue. */} + {message && ( +
+ {t('common.errorDetails')} + {message} +
)}
@@ -193,30 +212,42 @@ export function ErrorFallback({ error, reset, isChunkError, level, variant, labe */ export function RootErrorFallback({ error, isChunkError }: FallbackState) { const message = error instanceof Error ? error.message : null + const Icon = isChunkError ? Sparkles : AlertTriangle return (
- -

- {isChunkError ? 'A new version is available' : 'TREK could not start'} -

-

- {isChunkError - ? 'TREK was updated while this tab was open. Reload to get the new version.' - : 'Reloading usually fixes this. Your data is safe.'} -

- {message && {message}} - +
+ + + +
+

+ {isChunkError ? 'A new version is available' : 'TREK could not start'} +

+

+ {isChunkError + ? 'TREK was updated while this tab was open. Reload to get the new version.' + : 'Reloading usually fixes this. Your data is safe.'} +

+
+ + {message && ( +
+ Details + {message} +
+ )} +
) } diff --git a/shared/src/i18n/ar/common.ts b/shared/src/i18n/ar/common.ts index 19ef27314..c85429084 100644 --- a/shared/src/i18n/ar/common.ts +++ b/shared/src/i18n/ar/common.ts @@ -88,5 +88,6 @@ const common: TranslationStrings = { 'common.errorUpdateBody': 'تم تحديث TREK أثناء فتح علامة التبويب هذه. أعد التحميل للحصول على الإصدار الجديد.', 'common.errorPluginTitle': 'تعذّر عرض هذه الإضافة', 'common.needsConnection': 'يتطلب هذا اتصالاً. حاول مرة أخرى عندما يعود TREK للاتصال.', + 'common.errorDetails': 'التفاصيل', }; export default common; diff --git a/shared/src/i18n/az/common.ts b/shared/src/i18n/az/common.ts index d7885f85d..2314046fc 100644 --- a/shared/src/i18n/az/common.ts +++ b/shared/src/i18n/az/common.ts @@ -80,5 +80,6 @@ const common: TranslationStrings = { 'common.errorUpdateBody': 'Bu səhifə açıq olarkən TREK yeniləndi. Yeni versiyanı əldə etmək üçün səhifəni yenilə.', 'common.errorPluginTitle': 'Bu plagini göstərmək mümkün olmadı', 'common.needsConnection': 'Bunun üçün bağlantı lazımdır. TREK yenidən onlayn olduqda bir daha cəhd edin.', + 'common.errorDetails': 'Təfərrüatlar', }; export default common; diff --git a/shared/src/i18n/br/common.ts b/shared/src/i18n/br/common.ts index 270345466..f481d817a 100644 --- a/shared/src/i18n/br/common.ts +++ b/shared/src/i18n/br/common.ts @@ -81,5 +81,6 @@ const common: TranslationStrings = { 'O TREK foi atualizado enquanto esta aba estava aberta. Recarregue para obter a nova versão.', 'common.errorPluginTitle': 'Não foi possível exibir este plugin', 'common.needsConnection': 'Isso precisa de conexão. Tente de novo quando o TREK voltar a ficar online.', + 'common.errorDetails': 'Detalhes', }; export default common; diff --git a/shared/src/i18n/ca/common.ts b/shared/src/i18n/ca/common.ts index fe21f0503..7ade04072 100644 --- a/shared/src/i18n/ca/common.ts +++ b/shared/src/i18n/ca/common.ts @@ -82,5 +82,6 @@ const common: TranslationStrings = { "TREK s'ha actualitzat mentre aquesta pestanya era oberta. Torna a carregar per obtenir la versió nova.", 'common.errorPluginTitle': "No s'ha pogut mostrar aquest connector", 'common.needsConnection': 'Això necessita connexió. Torna-ho a provar quan TREK torni a estar en línia.', + 'common.errorDetails': 'Detalls', }; export default common; diff --git a/shared/src/i18n/cs/common.ts b/shared/src/i18n/cs/common.ts index da0ad2eb4..692475251 100644 --- a/shared/src/i18n/cs/common.ts +++ b/shared/src/i18n/cs/common.ts @@ -82,5 +82,6 @@ const common: TranslationStrings = { 'common.errorUpdateBody': 'TREK byl aktualizován, zatímco byla tato karta otevřená. Načtěte znovu pro novou verzi.', 'common.errorPluginTitle': 'Tento plugin se nepodařilo zobrazit', 'common.needsConnection': 'Na tohle je potřeba připojení. Zkus to znovu, až bude TREK zase online.', + 'common.errorDetails': 'Podrobnosti', }; export default common; diff --git a/shared/src/i18n/de/common.ts b/shared/src/i18n/de/common.ts index c68a9c007..870504e85 100644 --- a/shared/src/i18n/de/common.ts +++ b/shared/src/i18n/de/common.ts @@ -81,5 +81,6 @@ const common: TranslationStrings = { 'TREK wurde aktualisiert, während dieser Tab offen war. Lade neu, um die neue Version zu erhalten.', 'common.errorPluginTitle': 'Dieses Plugin konnte nicht angezeigt werden', 'common.needsConnection': 'Dafür braucht es eine Verbindung. Versuch es noch einmal, sobald TREK wieder online ist.', + 'common.errorDetails': 'Details', // same-as-en }; export default common; diff --git a/shared/src/i18n/en/common.ts b/shared/src/i18n/en/common.ts index 6ad3fbd85..0472d156f 100644 --- a/shared/src/i18n/en/common.ts +++ b/shared/src/i18n/en/common.ts @@ -80,5 +80,6 @@ const common: TranslationStrings = { 'common.errorUpdateBody': 'TREK was updated while this tab was open. Reload to get the new version.', 'common.errorPluginTitle': 'This plugin could not be shown', 'common.needsConnection': 'This needs a connection. Try again once TREK is back online.', + 'common.errorDetails': 'Details', }; export default common; diff --git a/shared/src/i18n/es/common.ts b/shared/src/i18n/es/common.ts index 3ff33b65b..82604fc62 100644 --- a/shared/src/i18n/es/common.ts +++ b/shared/src/i18n/es/common.ts @@ -81,5 +81,6 @@ const common: TranslationStrings = { 'TREK se actualizó mientras esta pestaña estaba abierta. Recarga para obtener la nueva versión.', 'common.errorPluginTitle': 'No se pudo mostrar este plugin', 'common.needsConnection': 'Esto necesita conexión. Vuelve a intentarlo cuando TREK esté de nuevo en línea.', + 'common.errorDetails': 'Detalles', }; export default common; diff --git a/shared/src/i18n/et/common.ts b/shared/src/i18n/et/common.ts index 3acd1c202..3db16b6f4 100644 --- a/shared/src/i18n/et/common.ts +++ b/shared/src/i18n/et/common.ts @@ -81,5 +81,6 @@ const common: TranslationStrings = { 'TREKi uuendati ajal, kui see vahekaart oli avatud. Uue versiooni kasutamiseks laadi leht uuesti.', 'common.errorPluginTitle': 'Seda pluginat ei saanud kuvada', 'common.needsConnection': 'Selleks on vaja ühendust. Proovi uuesti, kui TREK on taas võrgus.', + 'common.errorDetails': 'Üksikasjad', }; export default common; diff --git a/shared/src/i18n/fr/common.ts b/shared/src/i18n/fr/common.ts index 986c3db63..019e90a62 100644 --- a/shared/src/i18n/fr/common.ts +++ b/shared/src/i18n/fr/common.ts @@ -81,5 +81,6 @@ const common: TranslationStrings = { 'TREK a été mis à jour pendant que cet onglet était ouvert. Rechargez pour obtenir la nouvelle version.', 'common.errorPluginTitle': "Ce plugin n'a pas pu être affiché", 'common.needsConnection': 'Cela nécessite une connexion. Réessaie dès que TREK sera de nouveau en ligne.', + 'common.errorDetails': 'Détails', }; export default common; diff --git a/shared/src/i18n/gr/common.ts b/shared/src/i18n/gr/common.ts index 5600be833..c10fa5d15 100644 --- a/shared/src/i18n/gr/common.ts +++ b/shared/src/i18n/gr/common.ts @@ -81,5 +81,6 @@ const common: TranslationStrings = { 'Το TREK ενημερώθηκε ενώ αυτή η καρτέλα ήταν ανοιχτή. Κάντε επαναφόρτωση για τη νέα έκδοση.', 'common.errorPluginTitle': 'Δεν ήταν δυνατή η εμφάνιση αυτού του πρόσθετου', 'common.needsConnection': 'Αυτό χρειάζεται σύνδεση. Δοκίμασε ξανά μόλις το TREK συνδεθεί ξανά.', + 'common.errorDetails': 'Λεπτομέρειες', }; export default common; diff --git a/shared/src/i18n/he/common.ts b/shared/src/i18n/he/common.ts index 83645741e..887da8c75 100644 --- a/shared/src/i18n/he/common.ts +++ b/shared/src/i18n/he/common.ts @@ -82,6 +82,7 @@ const common: TranslationStrings = { 'common.errorUpdateBody': 'TREK עודכן בזמן שהלשונית הייתה פתוחה. רעננו כדי לקבל את הגרסה החדשה.', 'common.errorPluginTitle': 'לא ניתן להציג את התוסף הזה', 'common.needsConnection': 'הפעולה הזו דורשת חיבור. נסו שוב כש-TREK יחזור לרשת.', + 'common.errorDetails': 'פרטים', }; export default common; diff --git a/shared/src/i18n/hu/common.ts b/shared/src/i18n/hu/common.ts index b5d987c8e..6b2f1bc09 100644 --- a/shared/src/i18n/hu/common.ts +++ b/shared/src/i18n/hu/common.ts @@ -80,5 +80,6 @@ const common: TranslationStrings = { 'common.errorUpdateBody': 'A TREK frissült, amíg ez a lap nyitva volt. Töltse újra az új verzióért.', 'common.errorPluginTitle': 'Ezt a bővítményt nem sikerült megjeleníteni', 'common.needsConnection': 'Ehhez kapcsolat kell. Próbáld újra, amint a TREK újra online lesz.', + 'common.errorDetails': 'Részletek', }; export default common; diff --git a/shared/src/i18n/id/common.ts b/shared/src/i18n/id/common.ts index 5c38fe1a8..39471b441 100644 --- a/shared/src/i18n/id/common.ts +++ b/shared/src/i18n/id/common.ts @@ -78,5 +78,6 @@ const common: TranslationStrings = { 'common.errorUpdateBody': 'TREK diperbarui saat tab ini terbuka. Muat ulang untuk mendapatkan versi baru.', 'common.errorPluginTitle': 'Plugin ini tidak dapat ditampilkan', 'common.needsConnection': 'Ini memerlukan koneksi. Coba lagi begitu TREK kembali online.', + 'common.errorDetails': 'Detail', }; export default common; diff --git a/shared/src/i18n/it/common.ts b/shared/src/i18n/it/common.ts index 76ec7a8c0..ab8bc996e 100644 --- a/shared/src/i18n/it/common.ts +++ b/shared/src/i18n/it/common.ts @@ -81,5 +81,6 @@ const common: TranslationStrings = { 'TREK è stato aggiornato mentre questa scheda era aperta. Ricarica per ottenere la nuova versione.', 'common.errorPluginTitle': 'Impossibile mostrare questo plugin', 'common.needsConnection': 'Serve una connessione. Riprova quando TREK tornerà online.', + 'common.errorDetails': 'Dettagli', }; export default common; diff --git a/shared/src/i18n/ja/common.ts b/shared/src/i18n/ja/common.ts index 726a34ab4..6c80a03a1 100644 --- a/shared/src/i18n/ja/common.ts +++ b/shared/src/i18n/ja/common.ts @@ -79,5 +79,6 @@ const common: TranslationStrings = { 'このタブを開いている間に TREK が更新されました。再読み込みして新しいバージョンを取得してください。', 'common.errorPluginTitle': 'このプラグインを表示できませんでした', 'common.needsConnection': 'この操作には接続が必要です。TREK がオンラインに戻ってから、もう一度お試しください。', + 'common.errorDetails': '詳細', }; export default common; diff --git a/shared/src/i18n/ko/common.ts b/shared/src/i18n/ko/common.ts index 180192442..bf1cadf28 100644 --- a/shared/src/i18n/ko/common.ts +++ b/shared/src/i18n/ko/common.ts @@ -78,5 +78,6 @@ const common: TranslationStrings = { 'common.errorUpdateBody': '이 탭이 열려 있는 동안 TREK이 업데이트되었습니다. 새로고침하여 새 버전을 받으세요.', 'common.errorPluginTitle': '이 플러그인을 표시할 수 없습니다', 'common.needsConnection': '연결이 필요한 작업입니다. TREK가 다시 온라인이 되면 다시 시도하세요.', + 'common.errorDetails': '세부 정보', }; export default common; diff --git a/shared/src/i18n/nl/common.ts b/shared/src/i18n/nl/common.ts index 1fa9af6df..97e3de8d7 100644 --- a/shared/src/i18n/nl/common.ts +++ b/shared/src/i18n/nl/common.ts @@ -81,5 +81,6 @@ const common: TranslationStrings = { 'TREK is bijgewerkt terwijl dit tabblad open stond. Herlaad om de nieuwe versie te krijgen.', 'common.errorPluginTitle': 'Deze plug-in kon niet worden getoond', 'common.needsConnection': 'Hiervoor is een verbinding nodig. Probeer het opnieuw zodra TREK weer online is.', + 'common.errorDetails': 'Details', // same-as-en }; export default common; diff --git a/shared/src/i18n/pl/common.ts b/shared/src/i18n/pl/common.ts index 8e9e780a7..3f7e57a28 100644 --- a/shared/src/i18n/pl/common.ts +++ b/shared/src/i18n/pl/common.ts @@ -84,5 +84,6 @@ const common: TranslationStrings = { 'common.errorUpdateBody': 'TREK został zaktualizowany, gdy ta karta była otwarta. Odśwież, aby pobrać nową wersję.', 'common.errorPluginTitle': 'Nie udało się wyświetlić tej wtyczki', 'common.needsConnection': 'To wymaga połączenia. Spróbuj ponownie, gdy TREK znów będzie online.', + 'common.errorDetails': 'Szczegóły', }; export default common; diff --git a/shared/src/i18n/ru/common.ts b/shared/src/i18n/ru/common.ts index 121c0b336..c175439cb 100644 --- a/shared/src/i18n/ru/common.ts +++ b/shared/src/i18n/ru/common.ts @@ -85,5 +85,6 @@ const common: TranslationStrings = { 'TREK обновился, пока эта вкладка была открыта. Обновите страницу, чтобы получить новую версию.', 'common.errorPluginTitle': 'Не удалось показать этот плагин', 'common.needsConnection': 'Для этого нужно подключение. Попробуйте ещё раз, когда TREK снова будет онлайн.', + 'common.errorDetails': 'Подробности', }; export default common; diff --git a/shared/src/i18n/sk/common.ts b/shared/src/i18n/sk/common.ts index ed39b4fab..b29ee14a1 100644 --- a/shared/src/i18n/sk/common.ts +++ b/shared/src/i18n/sk/common.ts @@ -83,5 +83,6 @@ const common: TranslationStrings = { 'TREK bol aktualizovaný, kým bola táto karta otvorená. Znova načítajte stránku pre novú verziu.', 'common.errorPluginTitle': 'Tento plugin sa nepodarilo zobraziť', 'common.needsConnection': 'Na toto je potrebné pripojenie. Skús to znova, keď bude TREK opäť online.', + 'common.errorDetails': 'Podrobnosti', }; export default common; diff --git a/shared/src/i18n/sv/common.ts b/shared/src/i18n/sv/common.ts index 8cfe0c27e..76641a24d 100644 --- a/shared/src/i18n/sv/common.ts +++ b/shared/src/i18n/sv/common.ts @@ -81,5 +81,6 @@ const common: TranslationStrings = { 'TREK uppdaterades medan den här fliken var öppen. Ladda om för att hämta den nya versionen.', 'common.errorPluginTitle': 'Det här tillägget kunde inte visas', 'common.needsConnection': 'Det här kräver en anslutning. Försök igen när TREK är online igen.', + 'common.errorDetails': 'Detaljer', }; export default common; diff --git a/shared/src/i18n/th/common.ts b/shared/src/i18n/th/common.ts index 9e5e0d43f..041082dcd 100644 --- a/shared/src/i18n/th/common.ts +++ b/shared/src/i18n/th/common.ts @@ -78,5 +78,6 @@ const common: TranslationStrings = { 'common.errorUpdateBody': 'TREK ได้รับการอัปเดตขณะที่แท็บนี้เปิดอยู่ โหลดซ้ำเพื่อรับเวอร์ชันใหม่', 'common.errorPluginTitle': 'ไม่สามารถแสดงปลั๊กอินนี้ได้', 'common.needsConnection': 'การทำงานนี้ต้องใช้การเชื่อมต่อ ลองอีกครั้งเมื่อ TREK กลับมาออนไลน์', + 'common.errorDetails': 'รายละเอียด', }; export default common; diff --git a/shared/src/i18n/tr/common.ts b/shared/src/i18n/tr/common.ts index 6367c32c9..7123d1e96 100644 --- a/shared/src/i18n/tr/common.ts +++ b/shared/src/i18n/tr/common.ts @@ -80,5 +80,6 @@ const common: TranslationStrings = { 'common.errorUpdateBody': 'Bu sekme açıkken TREK güncellendi. Yeni sürümü almak için sayfayı yenileyin.', 'common.errorPluginTitle': 'Bu eklenti gösterilemedi', 'common.needsConnection': 'Bunun için bağlantı gerekiyor. TREK yeniden çevrimiçi olduğunda tekrar dene.', + 'common.errorDetails': 'Ayrıntılar', }; export default common; diff --git a/shared/src/i18n/uk/common.ts b/shared/src/i18n/uk/common.ts index d5fbee423..efe5cf022 100644 --- a/shared/src/i18n/uk/common.ts +++ b/shared/src/i18n/uk/common.ts @@ -84,5 +84,6 @@ const common: TranslationStrings = { 'common.errorUpdateBody': 'TREK оновився, поки ця вкладка була відкрита. Перезавантажте, щоб отримати нову версію.', 'common.errorPluginTitle': 'Не вдалося показати цей плагін', 'common.needsConnection': "Для цього потрібне з'єднання. Спробуйте ще раз, коли TREK знову буде онлайн.", + 'common.errorDetails': 'Подробиці', }; export default common; diff --git a/shared/src/i18n/vi/common.ts b/shared/src/i18n/vi/common.ts index de07531b7..2097e039c 100644 --- a/shared/src/i18n/vi/common.ts +++ b/shared/src/i18n/vi/common.ts @@ -78,5 +78,6 @@ const common: TranslationStrings = { 'common.errorUpdateBody': 'TREK đã được cập nhật trong khi thẻ này đang mở. Hãy tải lại để nhận phiên bản mới.', 'common.errorPluginTitle': 'Không thể hiển thị plugin này', 'common.needsConnection': 'Thao tác này cần kết nối. Hãy thử lại khi TREK trực tuyến trở lại.', + 'common.errorDetails': 'Chi tiết', }; export default common; diff --git a/shared/src/i18n/zh-TW/common.ts b/shared/src/i18n/zh-TW/common.ts index 4183d6bcb..f3d3009df 100644 --- a/shared/src/i18n/zh-TW/common.ts +++ b/shared/src/i18n/zh-TW/common.ts @@ -78,5 +78,6 @@ const common: TranslationStrings = { 'common.errorUpdateBody': '此分頁開啟期間 TREK 已更新。請重新載入以取得新版本。', 'common.errorPluginTitle': '無法顯示此外掛程式', 'common.needsConnection': '此操作需要網路連線。請在 TREK 恢復連線後再試一次。', + 'common.errorDetails': '詳細資訊', }; export default common; diff --git a/shared/src/i18n/zh/common.ts b/shared/src/i18n/zh/common.ts index db84f34ca..d17ede4b1 100644 --- a/shared/src/i18n/zh/common.ts +++ b/shared/src/i18n/zh/common.ts @@ -78,5 +78,6 @@ const common: TranslationStrings = { 'common.errorUpdateBody': '此标签页打开期间 TREK 已更新。请重新加载以获取新版本。', 'common.errorPluginTitle': '无法显示此插件', 'common.needsConnection': '此操作需要网络连接。请在 TREK 恢复联网后重试。', + 'common.errorDetails': '详细信息', }; export default common; From 1c15c33cf9fd2a2453f052de2a15193aeaf0fb3a Mon Sep 17 00:00:00 2001 From: Maurice Date: Fri, 6 Nov 2026 12:48:51 +0100 Subject: [PATCH 060/589] chore(i18n): drop the strings the removed map and today buttons used The jump-to-today button and the Google Maps and CoMaps tiles are gone, so their strings reached nothing and would fail the i18n key check. --- shared/src/i18n/ar/mobileTrip.ts | 3 --- shared/src/i18n/az/mobileTrip.ts | 3 --- shared/src/i18n/br/mobileTrip.ts | 3 --- shared/src/i18n/ca/mobileTrip.ts | 3 --- shared/src/i18n/cs/mobileTrip.ts | 3 --- shared/src/i18n/de/mobileTrip.ts | 3 --- shared/src/i18n/en/mobileTrip.ts | 3 --- shared/src/i18n/es/mobileTrip.ts | 3 --- shared/src/i18n/et/mobileTrip.ts | 3 --- shared/src/i18n/fr/mobileTrip.ts | 3 --- shared/src/i18n/gr/mobileTrip.ts | 3 --- shared/src/i18n/he/mobileTrip.ts | 3 --- shared/src/i18n/hu/mobileTrip.ts | 3 --- shared/src/i18n/id/mobileTrip.ts | 3 --- shared/src/i18n/it/mobileTrip.ts | 3 --- shared/src/i18n/ja/mobileTrip.ts | 3 --- shared/src/i18n/ko/mobileTrip.ts | 3 --- shared/src/i18n/nl/mobileTrip.ts | 3 --- shared/src/i18n/pl/mobileTrip.ts | 3 --- shared/src/i18n/ru/mobileTrip.ts | 3 --- shared/src/i18n/sk/mobileTrip.ts | 3 --- shared/src/i18n/sv/mobileTrip.ts | 3 --- shared/src/i18n/th/mobileTrip.ts | 3 --- shared/src/i18n/tr/mobileTrip.ts | 3 --- shared/src/i18n/uk/mobileTrip.ts | 3 --- shared/src/i18n/vi/mobileTrip.ts | 3 --- shared/src/i18n/zh-TW/mobileTrip.ts | 3 --- shared/src/i18n/zh/mobileTrip.ts | 3 --- 28 files changed, 84 deletions(-) diff --git a/shared/src/i18n/ar/mobileTrip.ts b/shared/src/i18n/ar/mobileTrip.ts index 6fc3590d5..49f0ea53a 100644 --- a/shared/src/i18n/ar/mobileTrip.ts +++ b/shared/src/i18n/ar/mobileTrip.ts @@ -8,7 +8,6 @@ const mobileTrip: TranslationStrings = { 'mobileTrip.addTransportShort': 'النقل', 'mobileTrip.allDays': 'كل الأيام', 'mobileTrip.today': 'اليوم', - 'mobileTrip.jumpToToday': 'الانتقال إلى اليوم', 'mobileTrip.assignedDays': 'الأيام المخصصة', 'mobileTrip.assignmentNotes': 'ملاحظات خاصة باليوم', 'mobileTrip.bookingsEmpty': 'لا توجد حجوزات بعد', @@ -20,8 +19,6 @@ const mobileTrip: TranslationStrings = { 'mobileTrip.filesEmpty': 'لا توجد ملفات بعد', 'mobileTrip.filesNext': 'الملف التالي', 'mobileTrip.filesPrev': 'الملف السابق', - 'mobileTrip.googleMaps': 'Google Maps', - 'mobileTrip.coMaps': 'CoMaps', 'mobileTrip.icsDownload': 'تنزيل .ics', 'mobileTrip.icsSubscribe': 'الاشتراك في التقويم', 'mobileTrip.icsSubscribeSub': 'تحديث تلقائي في تطبيق التقويم لديك', diff --git a/shared/src/i18n/az/mobileTrip.ts b/shared/src/i18n/az/mobileTrip.ts index fe9ab48ab..4ecd25ab4 100644 --- a/shared/src/i18n/az/mobileTrip.ts +++ b/shared/src/i18n/az/mobileTrip.ts @@ -8,7 +8,6 @@ const mobileTrip: TranslationStrings = { 'mobileTrip.addTransportShort': 'Nəqliyyat', 'mobileTrip.allDays': 'Bütün günlər', 'mobileTrip.today': 'Bu gün', - 'mobileTrip.jumpToToday': 'Bu günə keç', 'mobileTrip.assignedDays': 'Təyin edilmiş günlər', 'mobileTrip.assignmentNotes': 'Günə aid qeydlər', 'mobileTrip.bookingsEmpty': 'Hələ rezervasiya yoxdur', @@ -20,8 +19,6 @@ const mobileTrip: TranslationStrings = { 'mobileTrip.filesEmpty': 'Hələ fayl yoxdur', 'mobileTrip.filesNext': 'Növbəti fayl', 'mobileTrip.filesPrev': 'Əvvəlki fayl', - 'mobileTrip.googleMaps': 'Google Maps', - 'mobileTrip.coMaps': 'CoMaps', 'mobileTrip.icsDownload': '.ics faylını endir', 'mobileTrip.icsSubscribe': 'Təqvimə abunə ol', 'mobileTrip.icsSubscribeSub': 'Təqvim tətbiqinizdə avtomatik yenilənir', diff --git a/shared/src/i18n/br/mobileTrip.ts b/shared/src/i18n/br/mobileTrip.ts index 659949f52..8d6d5b963 100644 --- a/shared/src/i18n/br/mobileTrip.ts +++ b/shared/src/i18n/br/mobileTrip.ts @@ -8,7 +8,6 @@ const mobileTrip: TranslationStrings = { 'mobileTrip.addTransportShort': 'Transporte', 'mobileTrip.allDays': 'Todos os dias', 'mobileTrip.today': 'Hoje', - 'mobileTrip.jumpToToday': 'Ir para hoje', 'mobileTrip.assignedDays': 'Dias atribuídos', 'mobileTrip.assignmentNotes': 'Notas específicas do dia', 'mobileTrip.bookingsEmpty': 'Nenhuma reserva ainda', @@ -20,8 +19,6 @@ const mobileTrip: TranslationStrings = { 'mobileTrip.filesEmpty': 'Nenhum arquivo ainda', 'mobileTrip.filesNext': 'Próximo arquivo', 'mobileTrip.filesPrev': 'Arquivo anterior', - 'mobileTrip.googleMaps': 'Google Maps', - 'mobileTrip.coMaps': 'CoMaps', 'mobileTrip.icsDownload': 'Baixar .ics', 'mobileTrip.icsSubscribe': 'Assinar calendário', 'mobileTrip.icsSubscribeSub': 'Atualiza automaticamente no seu app de calendário', diff --git a/shared/src/i18n/ca/mobileTrip.ts b/shared/src/i18n/ca/mobileTrip.ts index 19aca7b7a..7d9e4a7d2 100644 --- a/shared/src/i18n/ca/mobileTrip.ts +++ b/shared/src/i18n/ca/mobileTrip.ts @@ -8,7 +8,6 @@ const mobileTrip: TranslationStrings = { 'mobileTrip.addTransportShort': 'Transport', // same-as-en 'mobileTrip.allDays': 'Tots els dies', 'mobileTrip.today': 'Avui', - 'mobileTrip.jumpToToday': 'Ves a avui', 'mobileTrip.assignedDays': 'Dies assignats', 'mobileTrip.assignmentNotes': 'Notes específiques del dia', 'mobileTrip.bookingsEmpty': 'Encara no hi ha reserves', @@ -20,8 +19,6 @@ const mobileTrip: TranslationStrings = { 'mobileTrip.filesEmpty': 'Encara no hi ha fitxers', 'mobileTrip.filesNext': 'Fitxer següent', 'mobileTrip.filesPrev': 'Fitxer anterior', - 'mobileTrip.googleMaps': 'Google Maps', - 'mobileTrip.coMaps': 'CoMaps', 'mobileTrip.icsDownload': 'Baixa .ics', 'mobileTrip.icsSubscribe': 'Subscriu-te al calendari', 'mobileTrip.icsSubscribeSub': "S'actualitza automàticament a la teva app de calendari", diff --git a/shared/src/i18n/cs/mobileTrip.ts b/shared/src/i18n/cs/mobileTrip.ts index 1ebf856db..38478960d 100644 --- a/shared/src/i18n/cs/mobileTrip.ts +++ b/shared/src/i18n/cs/mobileTrip.ts @@ -8,7 +8,6 @@ const mobileTrip: TranslationStrings = { 'mobileTrip.addTransportShort': 'Doprava', 'mobileTrip.allDays': 'Všechny dny', 'mobileTrip.today': 'Dnes', - 'mobileTrip.jumpToToday': 'Přejít na dnešek', 'mobileTrip.assignedDays': 'Přiřazené dny', 'mobileTrip.assignmentNotes': 'Poznámky ke dni', 'mobileTrip.bookingsEmpty': 'Zatím žádné rezervace', @@ -20,8 +19,6 @@ const mobileTrip: TranslationStrings = { 'mobileTrip.filesEmpty': 'Zatím žádné soubory', 'mobileTrip.filesNext': 'Další soubor', 'mobileTrip.filesPrev': 'Předchozí soubor', - 'mobileTrip.googleMaps': 'Google Maps', - 'mobileTrip.coMaps': 'CoMaps', 'mobileTrip.icsDownload': 'Stáhnout .ics', 'mobileTrip.icsSubscribe': 'Přihlásit se k odběru kalendáře', 'mobileTrip.icsSubscribeSub': 'Automaticky se aktualizuje ve vaší kalendářové aplikaci', diff --git a/shared/src/i18n/de/mobileTrip.ts b/shared/src/i18n/de/mobileTrip.ts index 9406d26e7..061996f87 100644 --- a/shared/src/i18n/de/mobileTrip.ts +++ b/shared/src/i18n/de/mobileTrip.ts @@ -8,7 +8,6 @@ const mobileTrip: TranslationStrings = { 'mobileTrip.addTransportShort': 'Transport', // same-as-en 'mobileTrip.allDays': 'Alle Tage', 'mobileTrip.today': 'Heute', - 'mobileTrip.jumpToToday': 'Zu heute springen', 'mobileTrip.assignedDays': 'Zugewiesene Tage', 'mobileTrip.assignmentNotes': 'Tagesspezifische Notizen', 'mobileTrip.bookingsEmpty': 'Noch keine Buchungen', @@ -20,8 +19,6 @@ const mobileTrip: TranslationStrings = { 'mobileTrip.filesEmpty': 'Keine Dateien vorhanden', 'mobileTrip.filesNext': 'Nächste Datei', 'mobileTrip.filesPrev': 'Vorherige Datei', - 'mobileTrip.googleMaps': 'Google Maps', - 'mobileTrip.coMaps': 'CoMaps', 'mobileTrip.icsDownload': '.ics herunterladen', 'mobileTrip.icsSubscribe': 'Kalender abonnieren', 'mobileTrip.icsSubscribeSub': 'Aktualisiert sich automatisch in deiner Kalender-App', diff --git a/shared/src/i18n/en/mobileTrip.ts b/shared/src/i18n/en/mobileTrip.ts index 0817aeff0..0d4a2903a 100644 --- a/shared/src/i18n/en/mobileTrip.ts +++ b/shared/src/i18n/en/mobileTrip.ts @@ -8,7 +8,6 @@ const mobileTrip: TranslationStrings = { 'mobileTrip.addTransportShort': 'Transport', 'mobileTrip.allDays': 'All Days', 'mobileTrip.today': 'Today', - 'mobileTrip.jumpToToday': 'Jump to today', 'mobileTrip.assignedDays': 'Assigned Days', 'mobileTrip.assignmentNotes': 'Day-specific notes', 'mobileTrip.bookingsEmpty': 'No bookings yet', @@ -20,8 +19,6 @@ const mobileTrip: TranslationStrings = { 'mobileTrip.filesEmpty': 'No files yet', 'mobileTrip.filesNext': 'Next file', 'mobileTrip.filesPrev': 'Previous file', - 'mobileTrip.googleMaps': 'Google Maps', - 'mobileTrip.coMaps': 'CoMaps', 'mobileTrip.icsDownload': 'Download .ics', 'mobileTrip.icsSubscribe': 'Subscribe to calendar', 'mobileTrip.icsSubscribeSub': 'Auto-updates in your calendar app', diff --git a/shared/src/i18n/es/mobileTrip.ts b/shared/src/i18n/es/mobileTrip.ts index 87237fc5e..4d5a681dd 100644 --- a/shared/src/i18n/es/mobileTrip.ts +++ b/shared/src/i18n/es/mobileTrip.ts @@ -8,7 +8,6 @@ const mobileTrip: TranslationStrings = { 'mobileTrip.addTransportShort': 'Transporte', 'mobileTrip.allDays': 'Todos los días', 'mobileTrip.today': 'Hoy', - 'mobileTrip.jumpToToday': 'Ir a hoy', 'mobileTrip.assignedDays': 'Días asignados', 'mobileTrip.assignmentNotes': 'Notas específicas del día', 'mobileTrip.bookingsEmpty': 'Aún no hay reservas', @@ -20,8 +19,6 @@ const mobileTrip: TranslationStrings = { 'mobileTrip.filesEmpty': 'Aún no hay archivos', 'mobileTrip.filesNext': 'Archivo siguiente', 'mobileTrip.filesPrev': 'Archivo anterior', - 'mobileTrip.googleMaps': 'Google Maps', - 'mobileTrip.coMaps': 'CoMaps', 'mobileTrip.icsDownload': 'Descargar .ics', 'mobileTrip.icsSubscribe': 'Suscribirse al calendario', 'mobileTrip.icsSubscribeSub': 'Se actualiza automáticamente en tu app de calendario', diff --git a/shared/src/i18n/et/mobileTrip.ts b/shared/src/i18n/et/mobileTrip.ts index ea48e0010..464c21885 100644 --- a/shared/src/i18n/et/mobileTrip.ts +++ b/shared/src/i18n/et/mobileTrip.ts @@ -8,7 +8,6 @@ const mobileTrip: TranslationStrings = { 'mobileTrip.addTransportShort': 'Transport', // same-as-en 'mobileTrip.allDays': 'Kõik päevad', 'mobileTrip.today': 'Täna', - 'mobileTrip.jumpToToday': 'Mine tänasele päevale', 'mobileTrip.assignedDays': 'Määratud päevad', 'mobileTrip.assignmentNotes': 'Päevapõhised märkmed', 'mobileTrip.bookingsEmpty': 'Broneeringuid veel pole', @@ -20,8 +19,6 @@ const mobileTrip: TranslationStrings = { 'mobileTrip.filesEmpty': 'Faile veel pole', 'mobileTrip.filesNext': 'Järgmine fail', 'mobileTrip.filesPrev': 'Eelmine fail', - 'mobileTrip.googleMaps': 'Google Maps', - 'mobileTrip.coMaps': 'CoMaps', 'mobileTrip.icsDownload': 'Laadi alla .ics', 'mobileTrip.icsSubscribe': 'Telli kalender', 'mobileTrip.icsSubscribeSub': 'Uueneb sinu kalendrirakenduses automaatselt', diff --git a/shared/src/i18n/fr/mobileTrip.ts b/shared/src/i18n/fr/mobileTrip.ts index 5544601ac..0789c0ad0 100644 --- a/shared/src/i18n/fr/mobileTrip.ts +++ b/shared/src/i18n/fr/mobileTrip.ts @@ -8,7 +8,6 @@ const mobileTrip: TranslationStrings = { 'mobileTrip.addTransportShort': 'Transport', // same-as-en 'mobileTrip.allDays': 'Tous les jours', 'mobileTrip.today': "Aujourd'hui", - 'mobileTrip.jumpToToday': "Aller à aujourd'hui", 'mobileTrip.assignedDays': 'Jours assignés', 'mobileTrip.assignmentNotes': 'Notes propres au jour', 'mobileTrip.bookingsEmpty': 'Aucune réservation', @@ -20,8 +19,6 @@ const mobileTrip: TranslationStrings = { 'mobileTrip.filesEmpty': 'Aucun fichier', 'mobileTrip.filesNext': 'Fichier suivant', 'mobileTrip.filesPrev': 'Fichier précédent', - 'mobileTrip.googleMaps': 'Google Maps', - 'mobileTrip.coMaps': 'CoMaps', 'mobileTrip.icsDownload': 'Télécharger le .ics', 'mobileTrip.icsSubscribe': "S'abonner au calendrier", 'mobileTrip.icsSubscribeSub': 'Se met à jour automatiquement dans votre application calendrier', diff --git a/shared/src/i18n/gr/mobileTrip.ts b/shared/src/i18n/gr/mobileTrip.ts index b3fdb550b..e51ccf7aa 100644 --- a/shared/src/i18n/gr/mobileTrip.ts +++ b/shared/src/i18n/gr/mobileTrip.ts @@ -8,7 +8,6 @@ const mobileTrip: TranslationStrings = { 'mobileTrip.addTransportShort': 'Μεταφορά', 'mobileTrip.allDays': 'Όλες οι Ημέρες', 'mobileTrip.today': 'Σήμερα', - 'mobileTrip.jumpToToday': 'Μετάβαση στο σήμερα', 'mobileTrip.assignedDays': 'Ανατεθειμένες ημέρες', 'mobileTrip.assignmentNotes': 'Σημειώσεις ημέρας', 'mobileTrip.bookingsEmpty': 'Δεν υπάρχουν κρατήσεις ακόμη', @@ -20,8 +19,6 @@ const mobileTrip: TranslationStrings = { 'mobileTrip.filesEmpty': 'Δεν υπάρχουν αρχεία ακόμη', 'mobileTrip.filesNext': 'Επόμενο αρχείο', 'mobileTrip.filesPrev': 'Προηγούμενο αρχείο', - 'mobileTrip.googleMaps': 'Google Maps', - 'mobileTrip.coMaps': 'CoMaps', 'mobileTrip.icsDownload': 'Λήψη .ics', 'mobileTrip.icsSubscribe': 'Εγγραφή στο ημερολόγιο', 'mobileTrip.icsSubscribeSub': 'Ενημερώνεται αυτόματα στην εφαρμογή ημερολογίου σας', diff --git a/shared/src/i18n/he/mobileTrip.ts b/shared/src/i18n/he/mobileTrip.ts index 20215a23e..e4d530f48 100644 --- a/shared/src/i18n/he/mobileTrip.ts +++ b/shared/src/i18n/he/mobileTrip.ts @@ -8,7 +8,6 @@ const mobileTrip: TranslationStrings = { 'mobileTrip.addTransportShort': 'תחבורה', 'mobileTrip.allDays': 'כל הימים', 'mobileTrip.today': 'היום', - 'mobileTrip.jumpToToday': 'קפיצה להיום', 'mobileTrip.assignedDays': 'ימים משויכים', 'mobileTrip.assignmentNotes': 'הערות ליום ספציפי', 'mobileTrip.bookingsEmpty': 'עדיין אין הזמנות', @@ -20,8 +19,6 @@ const mobileTrip: TranslationStrings = { 'mobileTrip.filesEmpty': 'עדיין אין קבצים', 'mobileTrip.filesNext': 'הקובץ הבא', 'mobileTrip.filesPrev': 'הקובץ הקודם', - 'mobileTrip.googleMaps': 'Google Maps', - 'mobileTrip.coMaps': 'CoMaps', 'mobileTrip.icsDownload': 'הורדת ‎.ics', 'mobileTrip.icsSubscribe': 'הרשמה ליומן', 'mobileTrip.icsSubscribeSub': 'מתעדכן אוטומטית באפליקציית היומן', diff --git a/shared/src/i18n/hu/mobileTrip.ts b/shared/src/i18n/hu/mobileTrip.ts index 3cd73c013..2a76b64a6 100644 --- a/shared/src/i18n/hu/mobileTrip.ts +++ b/shared/src/i18n/hu/mobileTrip.ts @@ -8,7 +8,6 @@ const mobileTrip: TranslationStrings = { 'mobileTrip.addTransportShort': 'Közlekedés', 'mobileTrip.allDays': 'Minden nap', 'mobileTrip.today': 'Ma', - 'mobileTrip.jumpToToday': 'Ugrás a mai napra', 'mobileTrip.assignedDays': 'Hozzárendelt napok', 'mobileTrip.assignmentNotes': 'Napra szóló jegyzetek', 'mobileTrip.bookingsEmpty': 'Még nincsenek foglalások', @@ -20,8 +19,6 @@ const mobileTrip: TranslationStrings = { 'mobileTrip.filesEmpty': 'Még nincsenek fájlok', 'mobileTrip.filesNext': 'Következő fájl', 'mobileTrip.filesPrev': 'Előző fájl', - 'mobileTrip.googleMaps': 'Google Maps', - 'mobileTrip.coMaps': 'CoMaps', 'mobileTrip.icsDownload': '.ics letöltése', 'mobileTrip.icsSubscribe': 'Feliratkozás a naptárra', 'mobileTrip.icsSubscribeSub': 'Automatikusan frissül a naptáralkalmazásodban', diff --git a/shared/src/i18n/id/mobileTrip.ts b/shared/src/i18n/id/mobileTrip.ts index b4745298a..282fe2bed 100644 --- a/shared/src/i18n/id/mobileTrip.ts +++ b/shared/src/i18n/id/mobileTrip.ts @@ -8,7 +8,6 @@ const mobileTrip: TranslationStrings = { 'mobileTrip.addTransportShort': 'Transportasi', 'mobileTrip.allDays': 'Semua Hari', 'mobileTrip.today': 'Hari ini', - 'mobileTrip.jumpToToday': 'Lompat ke hari ini', 'mobileTrip.assignedDays': 'Hari yang ditetapkan', 'mobileTrip.assignmentNotes': 'Catatan khusus hari', 'mobileTrip.bookingsEmpty': 'Belum ada reservasi', @@ -20,8 +19,6 @@ const mobileTrip: TranslationStrings = { 'mobileTrip.filesEmpty': 'Belum ada file', 'mobileTrip.filesNext': 'File berikutnya', 'mobileTrip.filesPrev': 'File sebelumnya', - 'mobileTrip.googleMaps': 'Google Maps', - 'mobileTrip.coMaps': 'CoMaps', 'mobileTrip.icsDownload': 'Unduh .ics', 'mobileTrip.icsSubscribe': 'Berlangganan kalender', 'mobileTrip.icsSubscribeSub': 'Otomatis diperbarui di aplikasi kalender kamu', diff --git a/shared/src/i18n/it/mobileTrip.ts b/shared/src/i18n/it/mobileTrip.ts index 2d5c4d26e..8c1b08aab 100644 --- a/shared/src/i18n/it/mobileTrip.ts +++ b/shared/src/i18n/it/mobileTrip.ts @@ -8,7 +8,6 @@ const mobileTrip: TranslationStrings = { 'mobileTrip.addTransportShort': 'Trasporto', 'mobileTrip.allDays': 'Tutti i giorni', 'mobileTrip.today': 'Oggi', - 'mobileTrip.jumpToToday': 'Vai a oggi', 'mobileTrip.assignedDays': 'Giorni assegnati', 'mobileTrip.assignmentNotes': 'Note specifiche del giorno', 'mobileTrip.bookingsEmpty': 'Ancora nessuna prenotazione', @@ -20,8 +19,6 @@ const mobileTrip: TranslationStrings = { 'mobileTrip.filesEmpty': 'Ancora nessun file', 'mobileTrip.filesNext': 'File successivo', 'mobileTrip.filesPrev': 'File precedente', - 'mobileTrip.googleMaps': 'Google Maps', - 'mobileTrip.coMaps': 'CoMaps', 'mobileTrip.icsDownload': 'Scarica .ics', 'mobileTrip.icsSubscribe': 'Abbonati al calendario', 'mobileTrip.icsSubscribeSub': 'Si aggiorna automaticamente nella tua app calendario', diff --git a/shared/src/i18n/ja/mobileTrip.ts b/shared/src/i18n/ja/mobileTrip.ts index 2b0bb90bc..3868188f8 100644 --- a/shared/src/i18n/ja/mobileTrip.ts +++ b/shared/src/i18n/ja/mobileTrip.ts @@ -8,7 +8,6 @@ const mobileTrip: TranslationStrings = { 'mobileTrip.addTransportShort': '移動', 'mobileTrip.allDays': 'すべての日', 'mobileTrip.today': '今日', - 'mobileTrip.jumpToToday': '今日へ移動', 'mobileTrip.assignedDays': '割り当てられた日', 'mobileTrip.assignmentNotes': '日別メモ', 'mobileTrip.bookingsEmpty': '予約はまだありません', @@ -20,8 +19,6 @@ const mobileTrip: TranslationStrings = { 'mobileTrip.filesEmpty': 'ファイルはまだありません', 'mobileTrip.filesNext': '次のファイル', 'mobileTrip.filesPrev': '前のファイル', - 'mobileTrip.googleMaps': 'Google Maps', - 'mobileTrip.coMaps': 'CoMaps', 'mobileTrip.icsDownload': '.ics をダウンロード', 'mobileTrip.icsSubscribe': 'カレンダーを購読', 'mobileTrip.icsSubscribeSub': 'カレンダーアプリで自動的に更新されます', diff --git a/shared/src/i18n/ko/mobileTrip.ts b/shared/src/i18n/ko/mobileTrip.ts index fda1d4b58..1ad9e90d1 100644 --- a/shared/src/i18n/ko/mobileTrip.ts +++ b/shared/src/i18n/ko/mobileTrip.ts @@ -8,7 +8,6 @@ const mobileTrip: TranslationStrings = { 'mobileTrip.addTransportShort': '교통', 'mobileTrip.allDays': '모든 날', 'mobileTrip.today': '오늘', - 'mobileTrip.jumpToToday': '오늘로 이동', 'mobileTrip.assignedDays': '배정된 날짜', 'mobileTrip.assignmentNotes': '날짜별 메모', 'mobileTrip.bookingsEmpty': '아직 예약이 없습니다', @@ -20,8 +19,6 @@ const mobileTrip: TranslationStrings = { 'mobileTrip.filesEmpty': '아직 파일이 없습니다', 'mobileTrip.filesNext': '다음 파일', 'mobileTrip.filesPrev': '이전 파일', - 'mobileTrip.googleMaps': 'Google Maps', - 'mobileTrip.coMaps': 'CoMaps', 'mobileTrip.icsDownload': '.ics 다운로드', 'mobileTrip.icsSubscribe': '캘린더 구독', 'mobileTrip.icsSubscribeSub': '캘린더 앱에서 자동으로 업데이트됩니다', diff --git a/shared/src/i18n/nl/mobileTrip.ts b/shared/src/i18n/nl/mobileTrip.ts index 4d4db40b4..e90292924 100644 --- a/shared/src/i18n/nl/mobileTrip.ts +++ b/shared/src/i18n/nl/mobileTrip.ts @@ -8,7 +8,6 @@ const mobileTrip: TranslationStrings = { 'mobileTrip.addTransportShort': 'Transport', // same-as-en 'mobileTrip.allDays': 'Alle dagen', 'mobileTrip.today': 'Vandaag', - 'mobileTrip.jumpToToday': 'Naar vandaag', 'mobileTrip.assignedDays': 'Toegewezen dagen', 'mobileTrip.assignmentNotes': 'Dagspecifieke notities', 'mobileTrip.bookingsEmpty': 'Nog geen boekingen', @@ -20,8 +19,6 @@ const mobileTrip: TranslationStrings = { 'mobileTrip.filesEmpty': 'Nog geen bestanden', 'mobileTrip.filesNext': 'Volgend bestand', 'mobileTrip.filesPrev': 'Vorig bestand', - 'mobileTrip.googleMaps': 'Google Maps', - 'mobileTrip.coMaps': 'CoMaps', 'mobileTrip.icsDownload': '.ics downloaden', 'mobileTrip.icsSubscribe': 'Abonneren op kalender', 'mobileTrip.icsSubscribeSub': 'Wordt automatisch bijgewerkt in je agenda-app', diff --git a/shared/src/i18n/pl/mobileTrip.ts b/shared/src/i18n/pl/mobileTrip.ts index 6b2bc20ae..593123d21 100644 --- a/shared/src/i18n/pl/mobileTrip.ts +++ b/shared/src/i18n/pl/mobileTrip.ts @@ -8,7 +8,6 @@ const mobileTrip: TranslationStrings = { 'mobileTrip.addTransportShort': 'Transport', // same-as-en 'mobileTrip.allDays': 'Wszystkie dni', 'mobileTrip.today': 'Dziś', - 'mobileTrip.jumpToToday': 'Przejdź do dziś', 'mobileTrip.assignedDays': 'Przypisane dni', 'mobileTrip.assignmentNotes': 'Notatki dla dnia', 'mobileTrip.bookingsEmpty': 'Brak rezerwacji', @@ -20,8 +19,6 @@ const mobileTrip: TranslationStrings = { 'mobileTrip.filesEmpty': 'Brak plików', 'mobileTrip.filesNext': 'Następny plik', 'mobileTrip.filesPrev': 'Poprzedni plik', - 'mobileTrip.googleMaps': 'Google Maps', - 'mobileTrip.coMaps': 'CoMaps', 'mobileTrip.icsDownload': 'Pobierz .ics', 'mobileTrip.icsSubscribe': 'Subskrybuj kalendarz', 'mobileTrip.icsSubscribeSub': 'Automatycznie aktualizuje się w aplikacji kalendarza', diff --git a/shared/src/i18n/ru/mobileTrip.ts b/shared/src/i18n/ru/mobileTrip.ts index 6bd6d0fe3..8e6638ae3 100644 --- a/shared/src/i18n/ru/mobileTrip.ts +++ b/shared/src/i18n/ru/mobileTrip.ts @@ -8,7 +8,6 @@ const mobileTrip: TranslationStrings = { 'mobileTrip.addTransportShort': 'Транспорт', 'mobileTrip.allDays': 'Все дни', 'mobileTrip.today': 'Сегодня', - 'mobileTrip.jumpToToday': 'Перейти к сегодня', 'mobileTrip.assignedDays': 'Назначенные дни', 'mobileTrip.assignmentNotes': 'Заметки на день', 'mobileTrip.bookingsEmpty': 'Пока нет бронирований', @@ -20,8 +19,6 @@ const mobileTrip: TranslationStrings = { 'mobileTrip.filesEmpty': 'Файлов пока нет', 'mobileTrip.filesNext': 'Следующий файл', 'mobileTrip.filesPrev': 'Предыдущий файл', - 'mobileTrip.googleMaps': 'Google Maps', - 'mobileTrip.coMaps': 'CoMaps', 'mobileTrip.icsDownload': 'Скачать .ics', 'mobileTrip.icsSubscribe': 'Подписаться на календарь', 'mobileTrip.icsSubscribeSub': 'Автоматически обновляется в вашем календаре', diff --git a/shared/src/i18n/sk/mobileTrip.ts b/shared/src/i18n/sk/mobileTrip.ts index d17d3e9ba..801e6760e 100644 --- a/shared/src/i18n/sk/mobileTrip.ts +++ b/shared/src/i18n/sk/mobileTrip.ts @@ -8,7 +8,6 @@ const mobileTrip: TranslationStrings = { 'mobileTrip.addTransportShort': 'Doprava', 'mobileTrip.allDays': 'Všetky dni', 'mobileTrip.today': 'Dnes', - 'mobileTrip.jumpToToday': 'Prejsť na dnešok', 'mobileTrip.assignedDays': 'Priradené dni', 'mobileTrip.assignmentNotes': 'Poznámky ku konkrétnemu dňu', 'mobileTrip.bookingsEmpty': 'Zatiaľ žiadne rezervácie', @@ -20,8 +19,6 @@ const mobileTrip: TranslationStrings = { 'mobileTrip.filesEmpty': 'Zatiaľ žiadne súbory', 'mobileTrip.filesNext': 'Ďalší súbor', 'mobileTrip.filesPrev': 'Predchádzajúci súbor', - 'mobileTrip.googleMaps': 'Google Maps', - 'mobileTrip.coMaps': 'CoMaps', 'mobileTrip.icsDownload': 'Stiahnuť .ics', 'mobileTrip.icsSubscribe': 'Prihlásiť sa na odber kalendára', 'mobileTrip.icsSubscribeSub': 'Automaticky sa aktualizuje vo vašej kalendárovej aplikácii', diff --git a/shared/src/i18n/sv/mobileTrip.ts b/shared/src/i18n/sv/mobileTrip.ts index d3d2c215c..af2c8bb5f 100644 --- a/shared/src/i18n/sv/mobileTrip.ts +++ b/shared/src/i18n/sv/mobileTrip.ts @@ -8,7 +8,6 @@ const mobileTrip: TranslationStrings = { 'mobileTrip.addTransportShort': 'Transport', // same-as-en 'mobileTrip.allDays': 'Alla dagar', 'mobileTrip.today': 'Idag', - 'mobileTrip.jumpToToday': 'Gå till idag', 'mobileTrip.assignedDays': 'Tilldelade dagar', 'mobileTrip.assignmentNotes': 'Dagsspecifika anteckningar', 'mobileTrip.bookingsEmpty': 'Inga bokningar än', @@ -20,8 +19,6 @@ const mobileTrip: TranslationStrings = { 'mobileTrip.filesEmpty': 'Inga filer ännu', 'mobileTrip.filesNext': 'Nästa fil', 'mobileTrip.filesPrev': 'Föregående fil', - 'mobileTrip.googleMaps': 'Google Maps', - 'mobileTrip.coMaps': 'CoMaps', 'mobileTrip.icsDownload': 'Ladda ner .ics', 'mobileTrip.icsSubscribe': 'Prenumerera på kalender', 'mobileTrip.icsSubscribeSub': 'Uppdateras automatiskt i din kalenderapp', diff --git a/shared/src/i18n/th/mobileTrip.ts b/shared/src/i18n/th/mobileTrip.ts index 2bed51a26..aa3039d10 100644 --- a/shared/src/i18n/th/mobileTrip.ts +++ b/shared/src/i18n/th/mobileTrip.ts @@ -8,7 +8,6 @@ const mobileTrip: TranslationStrings = { 'mobileTrip.addTransportShort': 'ขนส่ง', 'mobileTrip.allDays': 'ทุกวัน', 'mobileTrip.today': 'วันนี้', - 'mobileTrip.jumpToToday': 'ไปที่วันนี้', 'mobileTrip.assignedDays': 'วันที่ได้รับมอบหมาย', 'mobileTrip.assignmentNotes': 'บันทึกเฉพาะวัน', 'mobileTrip.bookingsEmpty': 'ยังไม่มีการจอง', @@ -20,8 +19,6 @@ const mobileTrip: TranslationStrings = { 'mobileTrip.filesEmpty': 'ยังไม่มีไฟล์', 'mobileTrip.filesNext': 'ไฟล์ถัดไป', 'mobileTrip.filesPrev': 'ไฟล์ก่อนหน้า', - 'mobileTrip.googleMaps': 'Google แผนที่', - 'mobileTrip.coMaps': 'โคแมปส์', 'mobileTrip.icsDownload': 'ดาวน์โหลด .ics', 'mobileTrip.icsSubscribe': 'สมัครสมาชิกปฏิทิน', 'mobileTrip.icsSubscribeSub': 'อัปเดตอัตโนมัติในแอปปฏิทินของคุณ', diff --git a/shared/src/i18n/tr/mobileTrip.ts b/shared/src/i18n/tr/mobileTrip.ts index cd21a93a5..8b859e840 100644 --- a/shared/src/i18n/tr/mobileTrip.ts +++ b/shared/src/i18n/tr/mobileTrip.ts @@ -8,7 +8,6 @@ const mobileTrip: TranslationStrings = { 'mobileTrip.addTransportShort': 'Ulaşım', 'mobileTrip.allDays': 'Tüm Günler', 'mobileTrip.today': 'Bugün', - 'mobileTrip.jumpToToday': 'Bugüne git', 'mobileTrip.assignedDays': 'Atanan Günler', 'mobileTrip.assignmentNotes': 'Güne özel notlar', 'mobileTrip.bookingsEmpty': 'Henüz rezervasyon yok', @@ -20,8 +19,6 @@ const mobileTrip: TranslationStrings = { 'mobileTrip.filesEmpty': 'Henüz dosya yok', 'mobileTrip.filesNext': 'Sonraki dosya', 'mobileTrip.filesPrev': 'Önceki dosya', - 'mobileTrip.googleMaps': 'Google Maps', - 'mobileTrip.coMaps': 'CoMaps', 'mobileTrip.icsDownload': '.ics indir', 'mobileTrip.icsSubscribe': 'Takvime abone ol', 'mobileTrip.icsSubscribeSub': 'Takvim uygulamanızda otomatik güncellenir', diff --git a/shared/src/i18n/uk/mobileTrip.ts b/shared/src/i18n/uk/mobileTrip.ts index 4c2697c29..912e2d175 100644 --- a/shared/src/i18n/uk/mobileTrip.ts +++ b/shared/src/i18n/uk/mobileTrip.ts @@ -8,7 +8,6 @@ const mobileTrip: TranslationStrings = { 'mobileTrip.addTransportShort': 'Транспорт', 'mobileTrip.allDays': 'Усі дні', 'mobileTrip.today': 'Сьогодні', - 'mobileTrip.jumpToToday': 'Перейти до сьогодні', 'mobileTrip.assignedDays': 'Призначені дні', 'mobileTrip.assignmentNotes': 'Нотатки на день', 'mobileTrip.bookingsEmpty': 'Поки немає бронювань', @@ -20,8 +19,6 @@ const mobileTrip: TranslationStrings = { 'mobileTrip.filesEmpty': 'Файлів поки немає', 'mobileTrip.filesNext': 'Наступний файл', 'mobileTrip.filesPrev': 'Попередній файл', - 'mobileTrip.googleMaps': 'Google Maps', - 'mobileTrip.coMaps': 'CoMaps', 'mobileTrip.icsDownload': 'Завантажити .ics', 'mobileTrip.icsSubscribe': 'Підписатися на календар', 'mobileTrip.icsSubscribeSub': 'Автоматично оновлюється у вашому календарі', diff --git a/shared/src/i18n/vi/mobileTrip.ts b/shared/src/i18n/vi/mobileTrip.ts index 09fd71dbb..11118443e 100644 --- a/shared/src/i18n/vi/mobileTrip.ts +++ b/shared/src/i18n/vi/mobileTrip.ts @@ -8,7 +8,6 @@ const mobileTrip: TranslationStrings = { 'mobileTrip.addTransportShort': 'Di chuyển', 'mobileTrip.allDays': 'Tất cả các ngày', 'mobileTrip.today': 'Hôm nay', - 'mobileTrip.jumpToToday': 'Đến hôm nay', 'mobileTrip.assignedDays': 'Ngày được gán', 'mobileTrip.assignmentNotes': 'Ghi chú theo ngày', 'mobileTrip.bookingsEmpty': 'Chưa có đặt chỗ nào', @@ -20,8 +19,6 @@ const mobileTrip: TranslationStrings = { 'mobileTrip.filesEmpty': 'Chưa có tập tin nào', 'mobileTrip.filesNext': 'Tập tin tiếp theo', 'mobileTrip.filesPrev': 'Tập tin trước', - 'mobileTrip.googleMaps': 'Google Maps', - 'mobileTrip.coMaps': 'CoMaps', 'mobileTrip.icsDownload': 'Tải xuống .ics', 'mobileTrip.icsSubscribe': 'Đăng ký lịch', 'mobileTrip.icsSubscribeSub': 'Tự động cập nhật trong ứng dụng lịch của bạn', diff --git a/shared/src/i18n/zh-TW/mobileTrip.ts b/shared/src/i18n/zh-TW/mobileTrip.ts index 836fe6330..d30685ea4 100644 --- a/shared/src/i18n/zh-TW/mobileTrip.ts +++ b/shared/src/i18n/zh-TW/mobileTrip.ts @@ -8,7 +8,6 @@ const mobileTrip: TranslationStrings = { 'mobileTrip.addTransportShort': '交通', 'mobileTrip.allDays': '所有天', 'mobileTrip.today': '今天', - 'mobileTrip.jumpToToday': '跳到今天', 'mobileTrip.assignedDays': '已分配的天數', 'mobileTrip.assignmentNotes': '按天備註', 'mobileTrip.bookingsEmpty': '暫無預訂', @@ -20,8 +19,6 @@ const mobileTrip: TranslationStrings = { 'mobileTrip.filesEmpty': '暫無檔案', 'mobileTrip.filesNext': '下一個檔案', 'mobileTrip.filesPrev': '上一個檔案', - 'mobileTrip.googleMaps': 'Google Maps', - 'mobileTrip.coMaps': 'CoMaps', 'mobileTrip.icsDownload': '下載 .ics', 'mobileTrip.icsSubscribe': '訂閱行事曆', 'mobileTrip.icsSubscribeSub': '在你的行事曆應用程式中自動更新', diff --git a/shared/src/i18n/zh/mobileTrip.ts b/shared/src/i18n/zh/mobileTrip.ts index 67be1380b..b171f8e6a 100644 --- a/shared/src/i18n/zh/mobileTrip.ts +++ b/shared/src/i18n/zh/mobileTrip.ts @@ -8,7 +8,6 @@ const mobileTrip: TranslationStrings = { 'mobileTrip.addTransportShort': '交通', 'mobileTrip.allDays': '所有天', 'mobileTrip.today': '今天', - 'mobileTrip.jumpToToday': '跳到今天', 'mobileTrip.assignedDays': '已分配的天数', 'mobileTrip.assignmentNotes': '按天备注', 'mobileTrip.bookingsEmpty': '暂无预订', @@ -20,8 +19,6 @@ const mobileTrip: TranslationStrings = { 'mobileTrip.filesEmpty': '暂无文件', 'mobileTrip.filesNext': '下一个文件', 'mobileTrip.filesPrev': '上一个文件', - 'mobileTrip.googleMaps': 'Google Maps', - 'mobileTrip.coMaps': 'CoMaps', 'mobileTrip.icsDownload': '下载 .ics', 'mobileTrip.icsSubscribe': '订阅日历', 'mobileTrip.icsSubscribeSub': '在你的日历应用中自动更新', From 496c85e6e55b73e6800c795ee2ce9a1e2edb6363 Mon Sep 17 00:00:00 2001 From: Maurice Date: Fri, 6 Nov 2026 12:52:28 +0100 Subject: [PATCH 061/589] feat(mobile): one shape for the atlas header buttons Planned was a label with a switch in a pill of its own beside the full-width wishlist button, and with Dawarich on the row grew cramped. Wishlist, Dawarich and Planned are now buttons of one shape, equal width and the phone shell's glass; Planned fills while the planned countries show. --- client/src/mobile/screens/atlas/MAtlas.tsx | 35 ++++++++++++------- .../tests/unit/mobile/atlas/MAtlas.test.tsx | 9 ++--- 2 files changed, 28 insertions(+), 16 deletions(-) diff --git a/client/src/mobile/screens/atlas/MAtlas.tsx b/client/src/mobile/screens/atlas/MAtlas.tsx index b505ea67f..cb3f07f78 100644 --- a/client/src/mobile/screens/atlas/MAtlas.tsx +++ b/client/src/mobile/screens/atlas/MAtlas.tsx @@ -1,6 +1,6 @@ import { useEffect, useMemo, useState } from 'react' import { useSearchParams } from 'react-router' -import { X } from 'lucide-react' +import { CalendarClock, X } from 'lucide-react' import { useAtlas } from '../../../pages/atlas/useAtlas' import MIconBtn from '../../components/MIconBtn' import MSheet from '../../components/MSheet' @@ -9,13 +9,16 @@ import MAtlasStatsCard from './MAtlasStatsCard' import MAtlasSearch from './MAtlasSearch' import MAtlasCountryPopup from './MAtlasCountryPopup' import MAtlasBucketSheet from './MAtlasBucketSheet' -import MToggle from '../../components/MToggle' import DawarichIcon from '../../../components/shared/DawarichIcon' import DawarichAtlasDialog from '../../../components/Dawarich/DawarichAtlasDialog' import { useAddonStore } from '../../../store/addonStore' import { countryStatus } from '../../../pages/atlas/atlasModel' import AtlasCountryPlaces from '../../../components/Atlas/AtlasCountryPlaces' +/** The atlas header's buttons: one shape, equal widths, the phone shell's glass. */ +const HEADER_BUTTON = 'flex h-[38px] min-w-0 flex-1 items-center justify-center gap-2 rounded-full border px-3 text-[0.78125rem] font-bold transition-transform active:scale-[.97]' +const HEADER_IDLE = 'border-[color:var(--m-gbr)] bg-[color:var(--m-glass)] text-m-ink shadow-[0_5px_12px_-8px_rgba(0,0,0,.18)] backdrop-blur-[24px] backdrop-saturate-[1.7]' + const removeBtnCls = 'mt-4 w-full rounded-full bg-[rgba(214,39,59,.12)] py-[11px] text-center text-[0.8125rem] font-bold text-[color:var(--m-st-danger)]' // theme-lint-disable — fixed status-danger tint /** @@ -121,7 +124,7 @@ export default function MAtlas() { @@ -134,20 +137,28 @@ export default function MAtlas() { type="button" onClick={() => setDawarichOpen(true)} aria-label={t('dawarich.title')} - className="flex h-[38px] min-w-0 flex-1 items-center justify-center gap-2 rounded-full border border-[color:var(--m-gbr)] bg-[color:var(--m-sheet)] px-3 shadow-[0_5px_12px_-8px_rgba(0,0,0,.18)]" + className={`${HEADER_BUTTON} ${HEADER_IDLE}`} > - - + + - {t('dawarich.title')} + {t('dawarich.title')} )} - {/* Only worth the space once there is something planned to reveal. */} + {/* Only worth the space once there is something planned to reveal. A + button of the same shape as its neighbours, filled while the planned + countries show, rather than a label with a switch in a pill of its own. */} {plannedCount > 0 && ( -
- {t('atlas.planned')} - togglePlanned()} ariaLabel={t('atlas.showPlanned')} /> -
+ )}
diff --git a/client/tests/unit/mobile/atlas/MAtlas.test.tsx b/client/tests/unit/mobile/atlas/MAtlas.test.tsx index 159d61aa7..b16832df5 100644 --- a/client/tests/unit/mobile/atlas/MAtlas.test.tsx +++ b/client/tests/unit/mobile/atlas/MAtlas.test.tsx @@ -225,11 +225,11 @@ describe('MAtlas', () => { it('FE-MOB-ATLASSCR-017: the planned pill stays away while nothing is planned', () => { render(); - expect(screen.queryByRole('switch')).not.toBeInTheDocument(); + expect(screen.queryByRole('button', { name: 'atlas.showPlanned' })).not.toBeInTheDocument(); expect(screen.queryByText('atlas.planned')).not.toBeInTheDocument(); }); - it('FE-MOB-ATLASSCR-018: a planned country brings up the pill and its switch flips the layer', () => { + it('FE-MOB-ATLASSCR-018: a planned country brings up a header button that flips the layer', () => { const atlas = setAtlas({ data: buildAtlasData({ stats: { totalTrips: 4, totalPlaces: 21, totalCountries: 7, totalDays: 30, totalCities: 9, totalCountriesPlanned: 2 }, @@ -238,8 +238,9 @@ describe('MAtlas', () => { render(); expect(screen.getByText('atlas.planned')).toBeInTheDocument(); - const toggle = screen.getByRole('switch', { name: 'atlas.showPlanned' }); - expect(toggle).toHaveAttribute('aria-checked', 'false'); + // A button of the same shape as the wishlist one, pressed while the layer shows. + const toggle = screen.getByRole('button', { name: 'atlas.showPlanned' }); + expect(toggle).toHaveAttribute('aria-pressed', 'false'); fireEvent.click(toggle); expect(atlas.togglePlanned).toHaveBeenCalled(); From 117af0f9b11ea666033f1cf546edc2faf8a19c09 Mon Sep 17 00:00:00 2001 From: Maurice Date: Fri, 6 Nov 2026 12:57:49 +0100 Subject: [PATCH 062/589] feat(mobile): swipe through Vacay's months and years, people and legend in sheets In the editor the months of the leave year page like the trip's days, the neighbour sliding in with the finger; in the overview the plan's years do the same (only between years the plan has, the arrows still create one). The day pager now pages anything with an id and can sit in a page's flow. The row of person and legend chips is two compact pills now: People opens a sheet to pick the member and show or hide shared calendars, Legend opens one that explains the company days and holiday calendars, which were never a choice. --- client/src/mobile/components/MDayPager.tsx | 18 +- client/src/mobile/screens/vacay/MVacay.tsx | 194 +++++++++++++----- client/src/mobile/screens/vacay/useMVacay.ts | 18 +- .../tests/unit/mobile/vacay/MVacay.test.tsx | 77 +++++-- .../unit/mobile/vacay/useMVacay.test.tsx | 13 ++ shared/src/i18n/ar/mobileVacay.ts | 2 + shared/src/i18n/az/mobileVacay.ts | 2 + shared/src/i18n/br/mobileVacay.ts | 2 + shared/src/i18n/ca/mobileVacay.ts | 2 + shared/src/i18n/cs/mobileVacay.ts | 2 + shared/src/i18n/de/mobileVacay.ts | 2 + shared/src/i18n/en/mobileVacay.ts | 2 + shared/src/i18n/es/mobileVacay.ts | 2 + shared/src/i18n/et/mobileVacay.ts | 2 + shared/src/i18n/fr/mobileVacay.ts | 2 + shared/src/i18n/gr/mobileVacay.ts | 2 + shared/src/i18n/he/mobileVacay.ts | 2 + shared/src/i18n/hu/mobileVacay.ts | 2 + shared/src/i18n/id/mobileVacay.ts | 2 + shared/src/i18n/it/mobileVacay.ts | 2 + shared/src/i18n/ja/mobileVacay.ts | 2 + shared/src/i18n/ko/mobileVacay.ts | 2 + shared/src/i18n/nl/mobileVacay.ts | 2 + shared/src/i18n/pl/mobileVacay.ts | 2 + shared/src/i18n/ru/mobileVacay.ts | 2 + shared/src/i18n/sk/mobileVacay.ts | 2 + shared/src/i18n/sv/mobileVacay.ts | 2 + shared/src/i18n/th/mobileVacay.ts | 2 + shared/src/i18n/tr/mobileVacay.ts | 2 + shared/src/i18n/uk/mobileVacay.ts | 2 + shared/src/i18n/vi/mobileVacay.ts | 2 + shared/src/i18n/zh-TW/mobileVacay.ts | 2 + shared/src/i18n/zh/mobileVacay.ts | 2 + 33 files changed, 299 insertions(+), 77 deletions(-) diff --git a/client/src/mobile/components/MDayPager.tsx b/client/src/mobile/components/MDayPager.tsx index fc0fffc5b..b40d80478 100644 --- a/client/src/mobile/components/MDayPager.tsx +++ b/client/src/mobile/components/MDayPager.tsx @@ -27,8 +27,11 @@ const SETTLE_MS = 90; /** How close to a page edge counts as resting on it. */ const REST_PX = 2; +/** Anything with an id pages: trip days, a leave year's months, the plan's years. */ +export type PagerItem = Pick; + export interface MDayPagerProps { - days: Day[]; + days: PagerItem[]; selectedDayId: number | null; onSelectDay: (dayId: number) => void; /** Draws one day. Pages other than the current one are inert and hidden @@ -38,6 +41,12 @@ export interface MDayPagerProps { locked?: boolean; /** Live-region text after a swipe lands on a day. */ describeDay: (index: number, total: number) => string; + /** + * In the page's flow instead of filling a positioned parent: the strip takes + * the height of its tallest page, for content that sits in a scrolling column + * (Vacay's month editor and year grid) rather than over the whole screen. + */ + inFlow?: boolean; } interface Page { @@ -49,7 +58,7 @@ interface Page { /** The window of pages around the selection. A selection that points at no * day (the whole-trip view, or a day deleted remotely) still gets its page, * with the first day next to it as a way back. */ -export function pagesFor(days: Day[], selectedDayId: number | null): Page[] { +export function pagesFor(days: PagerItem[], selectedDayId: number | null): Page[] { const i = days.findIndex((d) => d.id === selectedDayId); if (i < 0) { const first = days[0]; @@ -74,6 +83,7 @@ export default function MDayPager({ renderDay, locked = false, describeDay, + inFlow = false, }: MDayPagerProps) { const stripRef = useRef(null); const [announcement, setAnnouncement] = useState(''); @@ -177,7 +187,7 @@ export default function MDayPager({
{pages.map((page) => (
{renderDay(page.dayId, page.active)}
diff --git a/client/src/mobile/screens/vacay/MVacay.tsx b/client/src/mobile/screens/vacay/MVacay.tsx index 455d4d9e1..c751a4783 100644 --- a/client/src/mobile/screens/vacay/MVacay.tsx +++ b/client/src/mobile/screens/vacay/MVacay.tsx @@ -1,8 +1,9 @@ -import { Building2, ChevronLeft, ChevronRight, Eye, Minus, PenLine, Pencil, Plus, Settings2, Share2, ShieldCheck, Trash2, Unlink, UserPlus } from 'lucide-react' +import { Building2, Check, ChevronDown, ChevronLeft, ChevronRight, Eye, EyeOff, Minus, PenLine, Pencil, Plus, Settings2, Share2, ShieldCheck, Trash2, Unlink, UserPlus } from 'lucide-react' import type { LucideIcon } from 'lucide-react' import MSheet from '../../components/MSheet' import MIconBtn from '../../components/MIconBtn' import MProgress from '../../components/MProgress' +import MDayPager from '../../components/MDayPager' import { useTranslation } from '../../../i18n' import { useMVacay } from './useMVacay' import MVacayMonth from './MVacayMonth' @@ -12,6 +13,11 @@ import MVacayShareSheet from './MVacayShareSheet' import { FALLBACK_PERSON_COLOR } from './vacayDayModel' import { fmtDays } from '../../../components/Vacay/vacayFormat' +/** The company-holiday tint the calendar cells use (vacayDayModel). */ +const COMPANY_COLOR = '#F5D9A6' // theme-lint-disable: the cells' fixed company-day tint +const GLASS_PILL_BUTTON = 'inline-flex h-8 flex-none items-center gap-2 rounded-full border border-[color:var(--m-gbr)] bg-[color:var(--m-glass)] px-3 text-[0.75rem] font-bold text-m-ink backdrop-blur-[24px] backdrop-saturate-[1.7] transition-transform active:scale-[.97]' +const SHEET_ROW = 'flex items-center gap-3 rounded-[16px] border border-[color:var(--m-gbr)] bg-[color:var(--m-glass)] px-4 py-3 text-start text-[0.875rem] font-bold transition-transform active:scale-[.98]' + const WEEKDAY_KEYS_MONDAY = ['vacay.mon', 'vacay.tue', 'vacay.wed', 'vacay.thu', 'vacay.fri', 'vacay.sat', 'vacay.sun'] as const const WEEKDAY_KEYS_SUNDAY = ['vacay.sun', 'vacay.mon', 'vacay.tue', 'vacay.wed', 'vacay.thu', 'vacay.fri', 'vacay.sat'] as const @@ -41,6 +47,14 @@ export default function MVacay() { ? (stat.remaining < 0 ? 'var(--m-st-danger)' : 'var(--m-st-pending)') : v.selectedColor const weekdayKeys = v.weekStart === 0 ? WEEKDAY_KEYS_SUNDAY : WEEKDAY_KEYS_MONDAY + // People to pick between: fused members, or shared calendars to show or hide. + const peopleChoosable = v.users.length > 1 || v.incomingShares.length > 0 + const legendItems = [ + ...(v.companyHolidaysEnabled ? [{ key: 'company', color: COMPANY_COLOR, label: t('mobileVacay.companyLegend') }] : []), + ...(v.holidaysEnabled ? (v.plan?.holiday_calendars ?? []).map(cal => ({ key: `cal-${cal.id}`, color: cal.color, label: cal.label || cal.region })) : []), + ] + const yearPages = v.years.map(year => ({ id: year })) + const monthPages = v.months.map((_, slot) => ({ id: slot })) return ( // h-dvh, not h-full: the shell stopped providing a definite height (#1809). @@ -121,56 +135,64 @@ export default function MVacay() {
)} - {/* Person + legend chips */} -
- {v.users.map(u => { - const color = u.color || FALLBACK_PERSON_COLOR - const active = u.id === v.selectedUserId - return ( + {/* Who the calendar is for, and what its colours mean: two compact pills + instead of a row of chips. Only the people are a choice; the legend is + explanation, so it waits behind its own pill. */} + {(peopleChoosable || legendItems.length > 0) && ( +
+ {peopleChoosable && ( - ) - })} - {/* Shared read-only calendars: tap toggles that person's ring overlay. */} - {v.incomingShares.map(s => ( - - ))} - {v.companyHolidaysEnabled && ( - - )} - {v.holidaysEnabled && (v.plan?.holiday_calendars ?? []).map(cal => ( - - ))} -
+ )} + {legendItems.length > 0 && ( + + )} +
+ )} {/* Year grid */} + {/* Swipe between the plan's years, like pages. The neighbouring year + draws its calendar at once; its entries arrive once it lands. */} {!edit && ( + String(v.years[i] ?? '')} + renderDay={pageYear => (
{/* Twelve months from the window start (#737) — Jan–Dec on a calendar year, Jul–Jun once the leave year is shifted. */} - {v.months.map(({ year, month }, slot) => ( + {v.monthsFor(pageYear ?? v.selectedYear).map(({ year, month }, slot) => (
{/* The month name is the comfortable way into the editor: the mini cells below it are ~21px on a phone, precise enough to navigate @@ -196,6 +218,8 @@ export default function MVacay() {
))}
+ )} + /> )} {/* Edit view: month quick nav + single month */} @@ -219,12 +243,23 @@ export default function MVacay() { ))}
+ {/* Swipe between the months of the window, like pages. */} + v.monthNameLongFor(i)} + renderDay={pageSlot => { + const slot = pageSlot ?? v.monthSlot + const m = v.months[slot] ?? v.activeMonth + return (
- {v.monthNameLong} + {v.monthNameLongFor(slot)} @@ -235,8 +270,8 @@ export default function MVacay() { ))}
+ ) + }} + /> )}
@@ -338,6 +376,66 @@ export default function MVacay() { v.setSheet(null)} /> v.setSheet(null)} /> v.setSheet(null)} /> + v.setSheet(null)} variant="bottom" ariaLabel={t('mobileVacay.people')}> +
+
{t('mobileVacay.people')}
+
+ {v.users.map(u => { + const color = u.color || FALLBACK_PERSON_COLOR + const active = u.id === v.selectedUserId + return ( + + ) + })} +
+ {/* Shared read-only calendars: a tap shows or hides that person's ring overlay. */} + {v.incomingShares.length > 0 && ( + <> +
{t('vacay.sharedCalendars')}
+
+ {v.incomingShares.map(sh => ( + + ))} +
+ + )} +
+
+ v.setSheet(null)} variant="bottom" ariaLabel={t('mobileVacay.legend')}> +
+
{t('mobileVacay.legend')}
+
+ {legendItems.map(item => ( +
+ + {item.label} +
+ ))} +
+
+
- - {label} - - ) -} /** Forced Fusion-request card — stays open until accepted or declined. */ function MVacayIncomingInvite({ invites, onAccept, onDecline }: { diff --git a/client/src/mobile/screens/vacay/useMVacay.ts b/client/src/mobile/screens/vacay/useMVacay.ts index 8f7e5bea7..5026b051a 100644 --- a/client/src/mobile/screens/vacay/useMVacay.ts +++ b/client/src/mobile/screens/vacay/useMVacay.ts @@ -14,7 +14,7 @@ import { export type MVacayView = 'grid' | 'edit' export type MVacayMode = VacayMode -export type MVacaySheet = 'invite' | 'settings' | 'share' | null +export type MVacaySheet = 'invite' | 'settings' | 'share' | 'people' | 'legend' | null /** * Screen state of the mobile Vacay experience. Data loading, WebSocket sync @@ -96,6 +96,14 @@ export function useMVacay() { [locale, activeMonth], ) + // The pagers draw the neighbours of the open month and year too: the long name + // of any slot of the window, and the twelve months of any year. + const monthNameLongFor = useCallback((slot: number) => { + const m = months[slot] ?? months[0] + return new Intl.DateTimeFormat(locale, { month: 'long' }).format(new Date(m.year, m.month, 1)) + }, [locale, months]) + const monthsFor = useCallback((year: number) => windowMonths(year, yearSettings), [yearSettings]) + const selectedUser = users.find(u => u.id === selectedUserId) const selectedColor = selectedUser?.color || FALLBACK_PERSON_COLOR const selectedStat = stats.find(s => s.user_id === selectedUserId) @@ -156,6 +164,12 @@ export function useMVacay() { else { await handleAddPrevYear(); setSelectedYear(selectedYear - 1) } }, [years, selectedYear, setSelectedYear, handleAddPrevYear]) + // A swipe only moves between years the plan already has; creating one stays + // with the arrows, where it is a deliberate step. + const selectYear = useCallback((year: number) => { + if (years.includes(year)) setSelectedYear(year) + }, [years, setSelectedYear]) + const nextYear = useCallback(async () => { const idx = years.indexOf(selectedYear) if (idx >= 0 && idx < years.length - 1) setSelectedYear(years[idx + 1]) @@ -172,7 +186,7 @@ export function useMVacay() { const tripDotColor = users.find(u => u.id === currentUser?.id)?.color || 'var(--m-st-info)' return { - loading, plan, selectedYear, + loading, plan, selectedYear, years, selectYear, monthsFor, monthNameLongFor, users, isFused, currentUser, incomingInvites, acceptInvite, declineInvite, incomingShares, toggleShareHidden, diff --git a/client/tests/unit/mobile/vacay/MVacay.test.tsx b/client/tests/unit/mobile/vacay/MVacay.test.tsx index 0f8ccb968..ae7bfe9bb 100644 --- a/client/tests/unit/mobile/vacay/MVacay.test.tsx +++ b/client/tests/unit/mobile/vacay/MVacay.test.tsx @@ -45,6 +45,14 @@ const dayCtx: DayVisualContext = { }; const MONTHS_SHORT = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; +const MONTHS_LONG = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; + +// The paging itself is MDayPager's, tested there. This draws only the current +// page, so the year grid and the month editor under test are the ones on screen. +vi.mock('../../../../src/mobile/components/MDayPager', () => ({ + default: (props: { selectedDayId: number | null; renderDay: (id: number | null, active: boolean) => unknown }) => + props.renderDay(props.selectedDayId, true), +})); /** The screen flips the modifier flags with an updater, so the mock has to run it. */ function boolSetter() { @@ -58,6 +66,10 @@ function buildV(over: Record = {}): Record { loading: false, plan: { id: 1, holiday_calendars: [] }, selectedYear: 2026, + years: [2026], + selectYear: vi.fn((_year: number) => undefined), + monthsFor: (_year: number) => Array.from({ length: 12 }, (_, m) => ({ year: 2026, month: m })), + monthNameLongFor: (slot: number) => MONTHS_LONG[slot], users: [ { id: 1, username: 'alice', color: '#3b82f6' }, { id: 2, username: 'bob', color: null }, @@ -218,19 +230,30 @@ describe('MVacay', () => { expect(screen.queryByRole('button', { name: 'Increase allowance' })).not.toBeInTheDocument(); }); - it('FE-MOB-MVACSCR-010: person chips select their member and fall back on the shared color', () => { + it('FE-MOB-MVACSCR-010: the people pill opens the people sheet, where a member is picked', () => { render(); - - const bobChip = screen.getByRole('button', { name: 'bob' }); - const swatch = bobChip.querySelector('span') as HTMLElement; - expect(swatch.style.background).toBe('rgb(99, 102, 241)'); - - fireEvent.click(bobChip); - expect(mocks.v.selectPerson).toHaveBeenCalledWith(2); + fireEvent.click(screen.getByRole('button', { name: /People/ })); + expect(mocks.v.setSheet).toHaveBeenCalledWith('people'); }); - it('FE-MOB-MVACSCR-011: shared chips toggle their overlay and report their state', () => { + it('FE-MOB-MVACSCR-010b: in the people sheet a member is picked, falling back on the shared color', async () => { + mocks.v = buildV({ sheet: 'people' }); + render(); + + const sheet = await screen.findByRole('dialog', { name: 'People' }); + const bobRow = within(sheet).getByRole('button', { name: 'bob' }); + const swatch = bobRow.querySelector('span') as HTMLElement; + expect(swatch.style.background).toBe('rgb(99, 102, 241)'); + expect(within(sheet).getByRole('button', { name: 'alice' })).toHaveAttribute('aria-pressed', 'true'); + + fireEvent.click(bobRow); + expect(mocks.v.selectPerson).toHaveBeenCalledWith(2); + expect(mocks.v.setSheet).toHaveBeenLastCalledWith(null); + }); + + it('FE-MOB-MVACSCR-011: shared calendars toggle their overlay from the people sheet and report their state', async () => { mocks.v = buildV({ + sheet: 'people', incomingShares: [ { id: 7, owner_id: 3, username: 'carol', color: '#f59e0b', hidden: false }, { id: 8, owner_id: 4, username: 'dan', color: '#10b981', hidden: true }, @@ -238,8 +261,9 @@ describe('MVacay', () => { }); render(); - const carol = screen.getByRole('button', { name: 'carol' }); - const dan = screen.getByRole('button', { name: 'dan' }); + const sheet = await screen.findByRole('dialog', { name: 'People' }); + const carol = within(sheet).getByRole('button', { name: 'carol' }); + const dan = within(sheet).getByRole('button', { name: 'dan' }); expect(carol).toHaveAttribute('aria-pressed', 'true'); expect(dan).toHaveAttribute('aria-pressed', 'false'); @@ -249,8 +273,14 @@ describe('MVacay', () => { expect(mocks.v.toggleShareHidden).toHaveBeenNthCalledWith(2, 8, false); }); - it('FE-MOB-MVACSCR-012: shows the company legend and every enabled holiday calendar', () => { - mocks.v = buildV({ + it('FE-MOB-MVACSCR-011b: a single member with nothing shared gets no people pill', () => { + mocks.v = buildV({ users: [{ id: 1, username: 'alice', color: '#3b82f6' }] }); + render(); + expect(screen.queryByRole('button', { name: /People/ })).not.toBeInTheDocument(); + }); + + it('FE-MOB-MVACSCR-012: the legend waits behind its pill and lists the company days and every holiday calendar', async () => { + const holidays = { holidaysEnabled: true, plan: { id: 1, @@ -259,12 +289,21 @@ describe('MVacay', () => { { id: 2, region: 'NL', label: null, color: '#bbf7d0' }, ], }, - }); - render(); + }; + mocks.v = buildV(holidays); + const { unmount } = render(); + // Not on screen until asked for. + expect(screen.queryByText('Germany')).not.toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: /Legend/ })); + expect(mocks.v.setSheet).toHaveBeenCalledWith('legend'); + unmount(); - expect(screen.getByText('Company days')).toBeInTheDocument(); - expect(screen.getByText('Germany')).toBeInTheDocument(); - expect(screen.getByText('NL')).toBeInTheDocument(); + mocks.v = buildV({ ...holidays, sheet: 'legend' }); + render(); + const sheet = await screen.findByRole('dialog', { name: 'Legend' }); + expect(within(sheet).getByText('Company days')).toBeInTheDocument(); + expect(within(sheet).getByText('Germany')).toBeInTheDocument(); + expect(within(sheet).getByText('NL')).toBeInTheDocument(); }); it('FE-MOB-MVACSCR-013: the year grid shows twelve month cards and reports day taps', () => { @@ -315,7 +354,7 @@ describe('MVacay', () => { mocks.v = buildV({ view: 'edit' }); render(); - // The person chip row carries the same name; the mode switch comes last. + // The mode switch carries the selected person's name. const person = screen.getAllByRole('button', { name: 'alice' }); fireEvent.click(person[person.length - 1]); expect(mocks.v.setMode).toHaveBeenLastCalledWith('vacation'); diff --git a/client/tests/unit/mobile/vacay/useMVacay.test.tsx b/client/tests/unit/mobile/vacay/useMVacay.test.tsx index 8e166b177..cdad4612e 100644 --- a/client/tests/unit/mobile/vacay/useMVacay.test.tsx +++ b/client/tests/unit/mobile/vacay/useMVacay.test.tsx @@ -250,6 +250,19 @@ describe('useMVacay', () => { expect(result.current.monthSlot).toBe(11); }); + it('FE-MOB-MVAC-012b: a swipe selects only years the plan has, and names any slot and any year', async () => { + const setSelectedYear = vi.fn((_year: number) => undefined); + mocks.vacay = buildVacay({ years: [2025, 2026], setSelectedYear }); + const { result } = await mount(); + + act(() => { result.current.selectYear(2025); }); + act(() => { result.current.selectYear(2031); }); + expect(setSelectedYear.mock.calls).toEqual([[2025]]); + + expect(result.current.monthsFor(2025)[0]).toEqual({ year: 2025, month: 0 }); + expect(result.current.monthNameLongFor(0)).toMatch(/jan/i); + }); + it('FE-MOB-MVAC-013: only a fused plan allows selecting another member', async () => { const { result } = await mount(); diff --git a/shared/src/i18n/ar/mobileVacay.ts b/shared/src/i18n/ar/mobileVacay.ts index aaebeb9ff..0329c4966 100644 --- a/shared/src/i18n/ar/mobileVacay.ts +++ b/shared/src/i18n/ar/mobileVacay.ts @@ -24,6 +24,8 @@ const mobileVacay: TranslationStrings = { 'mobileVacay.companyLegend': 'أيام الشركة', 'mobileVacay.editCalendar': 'تحرير التقويم', 'mobileVacay.viewYear': 'عرض السنة', + 'mobileVacay.people': 'الأشخاص', + 'mobileVacay.legend': 'المفتاح', }; export default mobileVacay; diff --git a/shared/src/i18n/az/mobileVacay.ts b/shared/src/i18n/az/mobileVacay.ts index 249261164..33d6ef107 100644 --- a/shared/src/i18n/az/mobileVacay.ts +++ b/shared/src/i18n/az/mobileVacay.ts @@ -16,6 +16,8 @@ const mobileVacay: TranslationStrings = { 'mobileVacay.companyLegend': 'Şirkət günləri', 'mobileVacay.editCalendar': 'Təqvimi redaktə et', 'mobileVacay.viewYear': 'İlə bax', + 'mobileVacay.people': 'İnsanlar', + 'mobileVacay.legend': 'İzahat', }; export default mobileVacay; diff --git a/shared/src/i18n/br/mobileVacay.ts b/shared/src/i18n/br/mobileVacay.ts index ed69348ce..3271db235 100644 --- a/shared/src/i18n/br/mobileVacay.ts +++ b/shared/src/i18n/br/mobileVacay.ts @@ -16,6 +16,8 @@ const mobileVacay: TranslationStrings = { 'mobileVacay.companyLegend': 'Férias coletivas', 'mobileVacay.editCalendar': 'Editar calendário', 'mobileVacay.viewYear': 'Ver ano', + 'mobileVacay.people': 'Pessoas', + 'mobileVacay.legend': 'Legenda', }; export default mobileVacay; diff --git a/shared/src/i18n/ca/mobileVacay.ts b/shared/src/i18n/ca/mobileVacay.ts index 4961b99cd..6aa28db1a 100644 --- a/shared/src/i18n/ca/mobileVacay.ts +++ b/shared/src/i18n/ca/mobileVacay.ts @@ -16,6 +16,8 @@ const mobileVacay: TranslationStrings = { 'mobileVacay.companyLegend': "Dies d'empresa", 'mobileVacay.editCalendar': 'Edita el calendari', 'mobileVacay.viewYear': "Mostra l'any", + 'mobileVacay.people': 'Persones', + 'mobileVacay.legend': 'Llegenda', }; export default mobileVacay; diff --git a/shared/src/i18n/cs/mobileVacay.ts b/shared/src/i18n/cs/mobileVacay.ts index a3232de99..83e62e370 100644 --- a/shared/src/i18n/cs/mobileVacay.ts +++ b/shared/src/i18n/cs/mobileVacay.ts @@ -18,6 +18,8 @@ const mobileVacay: TranslationStrings = { 'mobileVacay.companyLegend': 'Firemní dny', 'mobileVacay.editCalendar': 'Upravit kalendář', 'mobileVacay.viewYear': 'Zobrazit rok', + 'mobileVacay.people': 'Lidé', + 'mobileVacay.legend': 'Legenda', }; export default mobileVacay; diff --git a/shared/src/i18n/de/mobileVacay.ts b/shared/src/i18n/de/mobileVacay.ts index fd054e67c..03c0c7f07 100644 --- a/shared/src/i18n/de/mobileVacay.ts +++ b/shared/src/i18n/de/mobileVacay.ts @@ -16,6 +16,8 @@ const mobileVacay: TranslationStrings = { 'mobileVacay.companyLegend': 'Betriebsferien', 'mobileVacay.editCalendar': 'Kalender bearbeiten', 'mobileVacay.viewYear': 'Jahr ansehen', + 'mobileVacay.people': 'Personen', + 'mobileVacay.legend': 'Legende', }; export default mobileVacay; diff --git a/shared/src/i18n/en/mobileVacay.ts b/shared/src/i18n/en/mobileVacay.ts index b2565fc77..1841709db 100644 --- a/shared/src/i18n/en/mobileVacay.ts +++ b/shared/src/i18n/en/mobileVacay.ts @@ -16,6 +16,8 @@ const mobileVacay: TranslationStrings = { 'mobileVacay.companyLegend': 'Company days', 'mobileVacay.editCalendar': 'Edit calendar', 'mobileVacay.viewYear': 'View year', + 'mobileVacay.people': 'People', + 'mobileVacay.legend': 'Legend', }; export default mobileVacay; diff --git a/shared/src/i18n/es/mobileVacay.ts b/shared/src/i18n/es/mobileVacay.ts index 933391afc..267c3c4bc 100644 --- a/shared/src/i18n/es/mobileVacay.ts +++ b/shared/src/i18n/es/mobileVacay.ts @@ -16,6 +16,8 @@ const mobileVacay: TranslationStrings = { 'mobileVacay.companyLegend': 'Días de empresa', 'mobileVacay.editCalendar': 'Editar calendario', 'mobileVacay.viewYear': 'Ver año', + 'mobileVacay.people': 'Personas', + 'mobileVacay.legend': 'Leyenda', }; export default mobileVacay; diff --git a/shared/src/i18n/et/mobileVacay.ts b/shared/src/i18n/et/mobileVacay.ts index d341518ca..cf8b8fd40 100644 --- a/shared/src/i18n/et/mobileVacay.ts +++ b/shared/src/i18n/et/mobileVacay.ts @@ -16,6 +16,8 @@ const mobileVacay: TranslationStrings = { 'mobileVacay.companyLegend': 'Ettevõtte puhkepäevad', 'mobileVacay.editCalendar': 'Muuda kalendrit', 'mobileVacay.viewYear': 'Vaata aastat', + 'mobileVacay.people': 'Inimesed', + 'mobileVacay.legend': 'Legend', // same-as-en }; export default mobileVacay; diff --git a/shared/src/i18n/fr/mobileVacay.ts b/shared/src/i18n/fr/mobileVacay.ts index 0bc4cabce..919d2ad91 100644 --- a/shared/src/i18n/fr/mobileVacay.ts +++ b/shared/src/i18n/fr/mobileVacay.ts @@ -16,6 +16,8 @@ const mobileVacay: TranslationStrings = { 'mobileVacay.companyLegend': "Congés d'entreprise", 'mobileVacay.editCalendar': 'Modifier le calendrier', 'mobileVacay.viewYear': "Voir l'année", + 'mobileVacay.people': 'Personnes', + 'mobileVacay.legend': 'Légende', }; export default mobileVacay; diff --git a/shared/src/i18n/gr/mobileVacay.ts b/shared/src/i18n/gr/mobileVacay.ts index 7802b19f4..2b6369512 100644 --- a/shared/src/i18n/gr/mobileVacay.ts +++ b/shared/src/i18n/gr/mobileVacay.ts @@ -16,6 +16,8 @@ const mobileVacay: TranslationStrings = { 'mobileVacay.companyLegend': 'Άδεια εταιρείας', 'mobileVacay.editCalendar': 'Επεξεργασία ημερολογίου', 'mobileVacay.viewYear': 'Προβολή έτους', + 'mobileVacay.people': 'Άτομα', + 'mobileVacay.legend': 'Υπόμνημα', }; export default mobileVacay; diff --git a/shared/src/i18n/he/mobileVacay.ts b/shared/src/i18n/he/mobileVacay.ts index 4f2415e43..3bfa97fca 100644 --- a/shared/src/i18n/he/mobileVacay.ts +++ b/shared/src/i18n/he/mobileVacay.ts @@ -18,6 +18,8 @@ const mobileVacay: TranslationStrings = { 'mobileVacay.companyLegend': 'ימי חברה', 'mobileVacay.editCalendar': 'עריכת לוח שנה', 'mobileVacay.viewYear': 'תצוגת שנה', + 'mobileVacay.people': 'אנשים', + 'mobileVacay.legend': 'מקרא', }; export default mobileVacay; diff --git a/shared/src/i18n/hu/mobileVacay.ts b/shared/src/i18n/hu/mobileVacay.ts index 63440a3c1..8c31fc916 100644 --- a/shared/src/i18n/hu/mobileVacay.ts +++ b/shared/src/i18n/hu/mobileVacay.ts @@ -16,6 +16,8 @@ const mobileVacay: TranslationStrings = { 'mobileVacay.companyLegend': 'Céges szabadság', 'mobileVacay.editCalendar': 'Naptár szerkesztése', 'mobileVacay.viewYear': 'Év megtekintése', + 'mobileVacay.people': 'Személyek', + 'mobileVacay.legend': 'Jelmagyarázat', }; export default mobileVacay; diff --git a/shared/src/i18n/id/mobileVacay.ts b/shared/src/i18n/id/mobileVacay.ts index 42e2bc676..503abf46b 100644 --- a/shared/src/i18n/id/mobileVacay.ts +++ b/shared/src/i18n/id/mobileVacay.ts @@ -14,6 +14,8 @@ const mobileVacay: TranslationStrings = { 'mobileVacay.companyLegend': 'Libur perusahaan', 'mobileVacay.editCalendar': 'Edit kalender', 'mobileVacay.viewYear': 'Lihat tahun', + 'mobileVacay.people': 'Orang', + 'mobileVacay.legend': 'Keterangan', }; export default mobileVacay; diff --git a/shared/src/i18n/it/mobileVacay.ts b/shared/src/i18n/it/mobileVacay.ts index 17fcf7bf4..8a6bfae96 100644 --- a/shared/src/i18n/it/mobileVacay.ts +++ b/shared/src/i18n/it/mobileVacay.ts @@ -16,6 +16,8 @@ const mobileVacay: TranslationStrings = { 'mobileVacay.companyLegend': 'Ferie aziendali', 'mobileVacay.editCalendar': 'Modifica calendario', 'mobileVacay.viewYear': 'Visualizza anno', + 'mobileVacay.people': 'Persone', + 'mobileVacay.legend': 'Legenda', }; export default mobileVacay; diff --git a/shared/src/i18n/ja/mobileVacay.ts b/shared/src/i18n/ja/mobileVacay.ts index 62d5d1732..6e0d5ec8c 100644 --- a/shared/src/i18n/ja/mobileVacay.ts +++ b/shared/src/i18n/ja/mobileVacay.ts @@ -14,6 +14,8 @@ const mobileVacay: TranslationStrings = { 'mobileVacay.companyLegend': '会社の休業日', 'mobileVacay.editCalendar': 'カレンダーを編集', 'mobileVacay.viewYear': '年間を表示', + 'mobileVacay.people': 'メンバー', + 'mobileVacay.legend': '凡例', }; export default mobileVacay; diff --git a/shared/src/i18n/ko/mobileVacay.ts b/shared/src/i18n/ko/mobileVacay.ts index 6a48063a0..60777d6b1 100644 --- a/shared/src/i18n/ko/mobileVacay.ts +++ b/shared/src/i18n/ko/mobileVacay.ts @@ -14,6 +14,8 @@ const mobileVacay: TranslationStrings = { 'mobileVacay.companyLegend': '회사 지정 휴무', 'mobileVacay.editCalendar': '캘린더 편집', 'mobileVacay.viewYear': '연간 보기', + 'mobileVacay.people': '사람', + 'mobileVacay.legend': '범례', }; export default mobileVacay; diff --git a/shared/src/i18n/nl/mobileVacay.ts b/shared/src/i18n/nl/mobileVacay.ts index 67135af90..739ebce19 100644 --- a/shared/src/i18n/nl/mobileVacay.ts +++ b/shared/src/i18n/nl/mobileVacay.ts @@ -16,6 +16,8 @@ const mobileVacay: TranslationStrings = { 'mobileVacay.companyLegend': 'Bedrijfsverlof', 'mobileVacay.editCalendar': 'Kalender bewerken', 'mobileVacay.viewYear': 'Jaar bekijken', + 'mobileVacay.people': 'Personen', + 'mobileVacay.legend': 'Legenda', }; export default mobileVacay; diff --git a/shared/src/i18n/pl/mobileVacay.ts b/shared/src/i18n/pl/mobileVacay.ts index b98b36d47..b3f061683 100644 --- a/shared/src/i18n/pl/mobileVacay.ts +++ b/shared/src/i18n/pl/mobileVacay.ts @@ -20,6 +20,8 @@ const mobileVacay: TranslationStrings = { 'mobileVacay.companyLegend': 'Dni firmowe', 'mobileVacay.editCalendar': 'Edytuj kalendarz', 'mobileVacay.viewYear': 'Zobacz rok', + 'mobileVacay.people': 'Osoby', + 'mobileVacay.legend': 'Legenda', }; export default mobileVacay; diff --git a/shared/src/i18n/ru/mobileVacay.ts b/shared/src/i18n/ru/mobileVacay.ts index c75599a48..5a7260bfa 100644 --- a/shared/src/i18n/ru/mobileVacay.ts +++ b/shared/src/i18n/ru/mobileVacay.ts @@ -20,6 +20,8 @@ const mobileVacay: TranslationStrings = { 'mobileVacay.companyLegend': 'Корпоративные дни', 'mobileVacay.editCalendar': 'Изменить календарь', 'mobileVacay.viewYear': 'Просмотр года', + 'mobileVacay.people': 'Люди', + 'mobileVacay.legend': 'Легенда', }; export default mobileVacay; diff --git a/shared/src/i18n/sk/mobileVacay.ts b/shared/src/i18n/sk/mobileVacay.ts index 609a16a8c..640bc26cb 100644 --- a/shared/src/i18n/sk/mobileVacay.ts +++ b/shared/src/i18n/sk/mobileVacay.ts @@ -18,6 +18,8 @@ const mobileVacay: TranslationStrings = { 'mobileVacay.companyLegend': 'Firemné dni', 'mobileVacay.editCalendar': 'Upraviť kalendár', 'mobileVacay.viewYear': 'Zobraziť rok', + 'mobileVacay.people': 'Ľudia', + 'mobileVacay.legend': 'Legenda', }; export default mobileVacay; diff --git a/shared/src/i18n/sv/mobileVacay.ts b/shared/src/i18n/sv/mobileVacay.ts index bcb540d87..38a2cc30f 100644 --- a/shared/src/i18n/sv/mobileVacay.ts +++ b/shared/src/i18n/sv/mobileVacay.ts @@ -16,6 +16,8 @@ const mobileVacay: TranslationStrings = { 'mobileVacay.companyLegend': 'Företagsledighet', 'mobileVacay.editCalendar': 'Redigera kalender', 'mobileVacay.viewYear': 'Visa år', + 'mobileVacay.people': 'Personer', + 'mobileVacay.legend': 'Teckenförklaring', }; export default mobileVacay; diff --git a/shared/src/i18n/th/mobileVacay.ts b/shared/src/i18n/th/mobileVacay.ts index 28cef054e..0e3ac0e70 100644 --- a/shared/src/i18n/th/mobileVacay.ts +++ b/shared/src/i18n/th/mobileVacay.ts @@ -14,6 +14,8 @@ const mobileVacay: TranslationStrings = { 'mobileVacay.companyLegend': 'วันของบริษัท', 'mobileVacay.editCalendar': 'แก้ไขปฏิทิน', 'mobileVacay.viewYear': 'ดูปี', + 'mobileVacay.people': 'บุคคล', + 'mobileVacay.legend': 'คำอธิบายสัญลักษณ์', }; export default mobileVacay; diff --git a/shared/src/i18n/tr/mobileVacay.ts b/shared/src/i18n/tr/mobileVacay.ts index a20e491d4..f162e4708 100644 --- a/shared/src/i18n/tr/mobileVacay.ts +++ b/shared/src/i18n/tr/mobileVacay.ts @@ -16,6 +16,8 @@ const mobileVacay: TranslationStrings = { 'mobileVacay.companyLegend': 'Şirket tatili', 'mobileVacay.editCalendar': 'Takvimi düzenle', 'mobileVacay.viewYear': 'Yılı görüntüle', + 'mobileVacay.people': 'Kişiler', + 'mobileVacay.legend': 'Açıklama', }; export default mobileVacay; diff --git a/shared/src/i18n/uk/mobileVacay.ts b/shared/src/i18n/uk/mobileVacay.ts index 02b5ca519..72526230a 100644 --- a/shared/src/i18n/uk/mobileVacay.ts +++ b/shared/src/i18n/uk/mobileVacay.ts @@ -20,6 +20,8 @@ const mobileVacay: TranslationStrings = { 'mobileVacay.companyLegend': 'Корпоративні дні', 'mobileVacay.editCalendar': 'Редагувати календар', 'mobileVacay.viewYear': 'Переглянути рік', + 'mobileVacay.people': 'Люди', + 'mobileVacay.legend': 'Легенда', }; export default mobileVacay; diff --git a/shared/src/i18n/vi/mobileVacay.ts b/shared/src/i18n/vi/mobileVacay.ts index bde6b7f24..97821937f 100644 --- a/shared/src/i18n/vi/mobileVacay.ts +++ b/shared/src/i18n/vi/mobileVacay.ts @@ -14,6 +14,8 @@ const mobileVacay: TranslationStrings = { 'mobileVacay.companyLegend': 'Ngày nghỉ công ty', 'mobileVacay.editCalendar': 'Sửa lịch', 'mobileVacay.viewYear': 'Xem năm', + 'mobileVacay.people': 'Mọi người', + 'mobileVacay.legend': 'Chú thích', }; export default mobileVacay; diff --git a/shared/src/i18n/zh-TW/mobileVacay.ts b/shared/src/i18n/zh-TW/mobileVacay.ts index ed6327a9c..e05176de6 100644 --- a/shared/src/i18n/zh-TW/mobileVacay.ts +++ b/shared/src/i18n/zh-TW/mobileVacay.ts @@ -14,6 +14,8 @@ const mobileVacay: TranslationStrings = { 'mobileVacay.companyLegend': '公司假期', 'mobileVacay.editCalendar': '編輯日曆', 'mobileVacay.viewYear': '檢視年度', + 'mobileVacay.people': '成員', + 'mobileVacay.legend': '圖例', }; export default mobileVacay; diff --git a/shared/src/i18n/zh/mobileVacay.ts b/shared/src/i18n/zh/mobileVacay.ts index a8defcdbd..1236336c0 100644 --- a/shared/src/i18n/zh/mobileVacay.ts +++ b/shared/src/i18n/zh/mobileVacay.ts @@ -14,6 +14,8 @@ const mobileVacay: TranslationStrings = { 'mobileVacay.companyLegend': '公司假期', 'mobileVacay.editCalendar': '编辑日历', 'mobileVacay.viewYear': '查看年度', + 'mobileVacay.people': '成员', + 'mobileVacay.legend': '图例', }; export default mobileVacay; From c7a369a0cacb9a6b84f08046343d182337fd3c6d Mon Sep 17 00:00:00 2001 From: Maurice Date: Fri, 6 Nov 2026 12:59:28 +0100 Subject: [PATCH 063/589] feat(mobile): Vacay's people and legend pills share the row equally --- client/src/mobile/screens/vacay/MVacay.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/client/src/mobile/screens/vacay/MVacay.tsx b/client/src/mobile/screens/vacay/MVacay.tsx index c751a4783..0cef3ff9e 100644 --- a/client/src/mobile/screens/vacay/MVacay.tsx +++ b/client/src/mobile/screens/vacay/MVacay.tsx @@ -15,7 +15,7 @@ import { fmtDays } from '../../../components/Vacay/vacayFormat' /** The company-holiday tint the calendar cells use (vacayDayModel). */ const COMPANY_COLOR = '#F5D9A6' // theme-lint-disable: the cells' fixed company-day tint -const GLASS_PILL_BUTTON = 'inline-flex h-8 flex-none items-center gap-2 rounded-full border border-[color:var(--m-gbr)] bg-[color:var(--m-glass)] px-3 text-[0.75rem] font-bold text-m-ink backdrop-blur-[24px] backdrop-saturate-[1.7] transition-transform active:scale-[.97]' +const GLASS_PILL_BUTTON = 'inline-flex h-8 min-w-0 flex-1 basis-0 items-center justify-center gap-2 rounded-full border border-[color:var(--m-gbr)] bg-[color:var(--m-glass)] px-3 text-[0.75rem] font-bold text-m-ink backdrop-blur-[24px] backdrop-saturate-[1.7] transition-transform active:scale-[.97]' const SHEET_ROW = 'flex items-center gap-3 rounded-[16px] border border-[color:var(--m-gbr)] bg-[color:var(--m-glass)] px-4 py-3 text-start text-[0.875rem] font-bold transition-transform active:scale-[.98]' const WEEKDAY_KEYS_MONDAY = ['vacay.mon', 'vacay.tue', 'vacay.wed', 'vacay.thu', 'vacay.fri', 'vacay.sat', 'vacay.sun'] as const @@ -165,7 +165,7 @@ export default function MVacay() { type="button" onClick={() => v.setSheet('legend')} aria-haspopup="dialog" - className={`${GLASS_PILL_BUTTON} ms-auto`} + className={GLASS_PILL_BUTTON} > {legendItems.slice(0, 3).map(item => ( From 7b29a5d34e13c5a0a8c99668545cb477ea410ee6 Mon Sep 17 00:00:00 2001 From: Maurice Date: Fri, 6 Nov 2026 13:00:58 +0100 Subject: [PATCH 064/589] feat(mobile): Vacay's month picker and month heads in glass The editor's twelve month chips were twelve grey boxes; they sit on one glass surface now, the picked month under a pill that glides to it across both rows. The month heads in the year overview are glass pills too. --- client/src/mobile/components/useActivePill.ts | 25 ++++++--- client/src/mobile/screens/vacay/MVacay.tsx | 52 ++++++++++++------- 2 files changed, 50 insertions(+), 27 deletions(-) diff --git a/client/src/mobile/components/useActivePill.ts b/client/src/mobile/components/useActivePill.ts index a23946a32..1b3ddcc4d 100644 --- a/client/src/mobile/components/useActivePill.ts +++ b/client/src/mobile/components/useActivePill.ts @@ -17,9 +17,12 @@ export function useActivePill( /** The track, as a ref or as the element itself (a callback-ref'd rail). */ trackRef: RefObject | HTMLElement | null, selector: string, - deps: DependencyList + deps: DependencyList, + /** Follow the item across rows too (a grid of chips): the pill then also takes + * the item's top and height, and the caller leaves top/bottom unset. */ + rows = false ): CSSProperties | null { - const [box, setBox] = useState<{ left: number; width: number; animate: boolean } | null>(null); + const [box, setBox] = useState<{ left: number; top: number; width: number; height: number; animate: boolean } | null>(null); useLayoutEffect(() => { const track = trackRef && 'current' in trackRef ? trackRef.current : trackRef; @@ -30,7 +33,13 @@ export function useActivePill( setBox(null); return; } - setBox((prev) => ({ left: active.offsetLeft, width: active.offsetWidth, animate: prev !== null })); + setBox((prev) => ({ + left: active.offsetLeft, + top: active.offsetTop, + width: active.offsetWidth, + height: active.offsetHeight, + animate: prev !== null, + })); }; measure(); if (typeof ResizeObserver === 'undefined') return; @@ -42,9 +51,9 @@ export function useActivePill( }, deps); if (!box) return null; - return { - width: box.width, - transform: `translateX(${box.left}px)`, - transition: box.animate ? 'transform 320ms var(--ease-drawer), width 320ms var(--ease-drawer)' : 'none', - }; + const transition = box.animate ? 'transform 320ms var(--ease-drawer), width 320ms var(--ease-drawer)' : 'none'; + if (rows) { + return { top: 0, width: box.width, height: box.height, transform: `translate(${box.left}px, ${box.top}px)`, transition }; + } + return { width: box.width, transform: `translateX(${box.left}px)`, transition }; } diff --git a/client/src/mobile/screens/vacay/MVacay.tsx b/client/src/mobile/screens/vacay/MVacay.tsx index 0cef3ff9e..165e4b0d5 100644 --- a/client/src/mobile/screens/vacay/MVacay.tsx +++ b/client/src/mobile/screens/vacay/MVacay.tsx @@ -1,9 +1,11 @@ +import { useRef } from 'react' import { Building2, Check, ChevronDown, ChevronLeft, ChevronRight, Eye, EyeOff, Minus, PenLine, Pencil, Plus, Settings2, Share2, ShieldCheck, Trash2, Unlink, UserPlus } from 'lucide-react' import type { LucideIcon } from 'lucide-react' import MSheet from '../../components/MSheet' import MIconBtn from '../../components/MIconBtn' import MProgress from '../../components/MProgress' import MDayPager from '../../components/MDayPager' +import { useActivePill } from '../../components/useActivePill' import { useTranslation } from '../../../i18n' import { useMVacay } from './useMVacay' import MVacayMonth from './MVacayMonth' @@ -201,7 +203,7 @@ export default function MVacay() { @@ -225,24 +227,9 @@ export default function MVacay() { {/* Edit view: month quick nav + single month */} {edit && ( <> -
-
- {v.monthNamesShort.map((name, slot) => ( - - ))} -
-
+ {/* One glass surface for the twelve months, the picked one under a pill + that glides to it, across the rows too. */} + {/* Swipe between the months of the window, like pages. */} ) } + +/** The editor's month picker: the window's twelve months on one glass surface. */ +function MonthQuickNav({ names, slot, onPick }: { names: string[]; slot: number; onPick: (slot: number) => void }) { + const trackRef = useRef(null) + const pill = useActivePill(trackRef, '[data-active="true"]', [slot, names.length], true) + return ( +
+
+ {pill &&
+
+ ) +} From f92aea80a7fdb5b636a078fd30ca18dd8343a9f2 Mon Sep 17 00:00:00 2001 From: Maurice Date: Fri, 6 Nov 2026 13:08:39 +0100 Subject: [PATCH 065/589] feat(native): a capability handshake between the app binary and the server's UI The UI ships with the server and the binary through the stores, so the two drift. TrekShell.getCapabilities now reports the binary's shell API, version and native features by name (iOS and Android), and the UI turns each native feature on only where the binary has it; a binary from before the handshake counts as shell API 1 with none. The other way round, the server names the oldest binary its UI works with (minNativeShellApi), and an app below it is asked to update with a link to its store. --- .../com/liketrek/trek/TrekShellPlugin.java | 31 ++++++ client/ios/App/App/TrekShellPlugin.swift | 19 ++++ client/src/App.tsx | 2 + .../Layout/NativeUpdateNotice.test.tsx | 46 ++++++++ .../components/Layout/NativeUpdateNotice.tsx | 54 ++++++++++ client/src/native/capabilities.test.ts | 77 +++++++++++++ client/src/native/capabilities.ts | 102 ++++++++++++++++++ client/src/native/nativeApp.test.ts | 7 ++ client/src/native/nativeApp.ts | 11 ++ client/src/native/trekShell.ts | 3 + server/src/nest/health/features.controller.ts | 4 + .../unit/nest/features.controller.test.ts | 6 ++ shared/src/i18n/ar/native.ts | 3 + shared/src/i18n/az/native.ts | 3 + shared/src/i18n/br/native.ts | 3 + shared/src/i18n/ca/native.ts | 3 + shared/src/i18n/cs/native.ts | 3 + shared/src/i18n/de/native.ts | 3 + shared/src/i18n/en/native.ts | 3 + shared/src/i18n/es/native.ts | 3 + shared/src/i18n/et/native.ts | 3 + shared/src/i18n/fr/native.ts | 3 + shared/src/i18n/gr/native.ts | 3 + shared/src/i18n/he/native.ts | 3 + shared/src/i18n/hu/native.ts | 3 + shared/src/i18n/id/native.ts | 3 + shared/src/i18n/it/native.ts | 3 + shared/src/i18n/ja/native.ts | 3 + shared/src/i18n/ko/native.ts | 3 + shared/src/i18n/nl/native.ts | 3 + shared/src/i18n/pl/native.ts | 3 + shared/src/i18n/ru/native.ts | 3 + shared/src/i18n/sk/native.ts | 3 + shared/src/i18n/sv/native.ts | 3 + shared/src/i18n/th/native.ts | 3 + shared/src/i18n/tr/native.ts | 3 + shared/src/i18n/uk/native.ts | 3 + shared/src/i18n/vi/native.ts | 3 + shared/src/i18n/zh-TW/native.ts | 3 + shared/src/i18n/zh/native.ts | 3 + 40 files changed, 446 insertions(+) create mode 100644 client/src/components/Layout/NativeUpdateNotice.test.tsx create mode 100644 client/src/components/Layout/NativeUpdateNotice.tsx create mode 100644 client/src/native/capabilities.test.ts create mode 100644 client/src/native/capabilities.ts diff --git a/client/android/app/src/main/java/com/liketrek/trek/TrekShellPlugin.java b/client/android/app/src/main/java/com/liketrek/trek/TrekShellPlugin.java index d59271a03..a12975fcd 100644 --- a/client/android/app/src/main/java/com/liketrek/trek/TrekShellPlugin.java +++ b/client/android/app/src/main/java/com/liketrek/trek/TrekShellPlugin.java @@ -24,6 +24,37 @@ public class TrekShellPlugin extends Plugin { private boolean authBrowserOpen; private final Handler handler = new Handler(Looper.getMainLooper()); + /** + * What this binary offers the server's UI, raised with every native feature + * an older binary lacks. The UI asks before it calls (native/capabilities.ts), + * and a server can require a minimum (minNativeShellApi in /api/health/features). + */ + static final int SHELL_API = 2; + /** The native features by name, so the UI can turn each on by itself. */ + static final String[] FEATURES = { "capabilities" }; + + @PluginMethod + public void getCapabilities(PluginCall call) { + JSObject result = new JSObject(); + result.put("shellApi", SHELL_API); + result.put("platform", "android"); + String version = ""; + String build = ""; + try { + android.content.pm.PackageInfo info = getContext().getPackageManager().getPackageInfo(getContext().getPackageName(), 0); + version = info.versionName == null ? "" : info.versionName; + build = String.valueOf(androidx.core.content.pm.PackageInfoCompat.getLongVersionCode(info)); + } catch (android.content.pm.PackageManager.NameNotFoundException ignored) { + // Our own package is always there; the fields simply stay empty. + } + result.put("appVersion", version); + result.put("build", build); + com.getcapacitor.JSArray features = new com.getcapacitor.JSArray(); + for (String feature : FEATURES) features.put(feature); + result.put("features", features); + call.resolve(result); + } + @PluginMethod public void getServer(PluginCall call) { String url = TrekServerStore.getUrl(getContext()); diff --git a/client/ios/App/App/TrekShellPlugin.swift b/client/ios/App/App/TrekShellPlugin.swift index 0414b3598..b5d944939 100644 --- a/client/ios/App/App/TrekShellPlugin.swift +++ b/client/ios/App/App/TrekShellPlugin.swift @@ -16,8 +16,27 @@ public class TrekShellPlugin: CAPPlugin, CAPBridgedPlugin, ASWebAuthenticationPr CAPPluginMethod(name: "authenticate", returnType: CAPPluginReturnPromise), CAPPluginMethod(name: "refreshOfflineCopy", returnType: CAPPluginReturnPromise), CAPPluginMethod(name: "openOfflineCopy", returnType: CAPPluginReturnPromise), + CAPPluginMethod(name: "getCapabilities", returnType: CAPPluginReturnPromise), ] + /// What this binary offers the server's UI, raised with every native feature + /// an older binary lacks. The UI asks before it calls (native/capabilities.ts), + /// and a server can require a minimum (minNativeShellApi in /api/health/features). + static let shellApi = 2 + /// The native features by name, so the UI can turn each on by itself. + static let features: [String] = ["capabilities"] + + @objc func getCapabilities(_ call: CAPPluginCall) { + let info = Bundle.main.infoDictionary + call.resolve([ + "shellApi": TrekShellPlugin.shellApi, + "platform": "ios", + "appVersion": info?["CFBundleShortVersionString"] as? String ?? "", + "build": info?["CFBundleVersion"] as? String ?? "", + "features": TrekShellPlugin.features, + ]) + } + private var authSession: ASWebAuthenticationSession? @objc func getServer(_ call: CAPPluginCall) { diff --git a/client/src/App.tsx b/client/src/App.tsx index 39500bbd7..7699d0c4c 100644 --- a/client/src/App.tsx +++ b/client/src/App.tsx @@ -32,6 +32,7 @@ import { useRoadtripPreferencesSync } from './hooks/useRoadtripPreferencesSync' import { registerSyncTriggers, unregisterSyncTriggers } from './sync/syncTriggers' import OfflineBanner from './components/Layout/OfflineBanner' import NewVersionNotice from './components/Layout/NewVersionNotice' +import NativeUpdateNotice from './components/Layout/NativeUpdateNotice' import { SystemNoticeHost } from './components/SystemNotices/SystemNoticeHost.js' import HelpPanel from './components/Help/HelpPanel' // Notice action registrations (side-effect imports): @@ -442,6 +443,7 @@ export default function App() { )} + {/* One boundary for all route chunks, above so it stays mounted across navigations. react-router runs location updates inside a transition, so a mounted boundary keeps the current page on screen instead of flashing diff --git a/client/src/components/Layout/NativeUpdateNotice.test.tsx b/client/src/components/Layout/NativeUpdateNotice.test.tsx new file mode 100644 index 000000000..0aca7480a --- /dev/null +++ b/client/src/components/Layout/NativeUpdateNotice.test.tsx @@ -0,0 +1,46 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { act, fireEvent, render, screen } from '../../../tests/helpers/render'; +import { _resetNativeCapabilities, checkAppUpdate, loadNativeCapabilities } from '../../native/capabilities'; +import { isNativeApp } from '../../native/platform'; +import { TrekShell } from '../../native/trekShell'; +import NativeUpdateNotice from './NativeUpdateNotice'; + +vi.mock('../../native/platform', () => ({ isNativeApp: vi.fn(), isNativeIos: vi.fn(() => false) })); +vi.mock('../../native/trekShell', () => ({ + TrekShell: { getCapabilities: vi.fn() }, + isUnimplemented: () => false, +})); + +beforeEach(() => { + _resetNativeCapabilities(); + vi.mocked(isNativeApp).mockReturnValue(true); + vi.mocked(TrekShell.getCapabilities).mockResolvedValue({ + shellApi: 2, + platform: 'android', + appVersion: '5.2.0', + build: '3', + features: [], + } as never); +}); + +describe('NativeUpdateNotice', () => { + it('stays away while the binary is new enough', async () => { + render(); + await act(async () => { + await checkAppUpdate(async () => ({ minNativeShellApi: 2 })); + }); + expect(screen.queryByRole('status')).not.toBeInTheDocument(); + }); + + it('leads to the store when the server needs a newer binary, and can be dismissed', async () => { + render(); + await act(async () => { + await loadNativeCapabilities(); + await checkAppUpdate(async () => ({ minNativeShellApi: 3 })); + }); + const link = screen.getByRole('link'); + expect(link).toHaveAttribute('href', 'https://play.google.com/store/apps/details?id=com.liketrek.trek'); + fireEvent.click(screen.getByRole('button')); + expect(screen.queryByRole('status')).not.toBeInTheDocument(); + }); +}); diff --git a/client/src/components/Layout/NativeUpdateNotice.tsx b/client/src/components/Layout/NativeUpdateNotice.tsx new file mode 100644 index 000000000..d23a8129e --- /dev/null +++ b/client/src/components/Layout/NativeUpdateNotice.tsx @@ -0,0 +1,54 @@ +/** + * NativeUpdateNotice: this server's UI needs a newer app binary than the one + * installed (native/capabilities.ts, minNativeShellApi). The UI updates with + * the server, the binary only through the store, so the two can drift; the + * notice says so and leads to the store instead of leaving native calls to + * fail one by one. Rendered once in App, inside the app only. + */ +import { Download, X } from 'lucide-react'; +import React, { useState } from 'react'; +import { useTranslation } from '../../i18n'; +import { useNativeCapabilities } from '../../native/capabilities'; + +const STORE_URL = { + ios: 'https://apps.apple.com/app/id6831237775', + android: 'https://play.google.com/store/apps/details?id=com.liketrek.trek', +} as const; + +export default function NativeUpdateNotice(): React.ReactElement | null { + const { t } = useTranslation(); + const { caps, updateRequired } = useNativeCapabilities(); + const [dismissed, setDismissed] = useState(false); + if (!updateRequired || dismissed || caps.platform === 'web') return null; + const store = caps.platform === 'android' ? STORE_URL.android : STORE_URL.ios; + + return ( +
+
+ ); +} diff --git a/client/src/native/capabilities.test.ts b/client/src/native/capabilities.test.ts new file mode 100644 index 000000000..510673e08 --- /dev/null +++ b/client/src/native/capabilities.test.ts @@ -0,0 +1,77 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { + _resetNativeCapabilities, + appUpdateRequired, + checkAppUpdate, + hasNativeFeature, + loadNativeCapabilities, + nativeCapabilities, +} from './capabilities'; +import { isNativeApp } from './platform'; +import { TrekShell } from './trekShell'; + +vi.mock('./platform', () => ({ isNativeApp: vi.fn() })); +vi.mock('./trekShell', () => ({ + TrekShell: { getCapabilities: vi.fn() }, + isUnimplemented: (err: unknown) => (err as { code?: string })?.code === 'UNIMPLEMENTED', +})); + +const CAPS = { shellApi: 2, platform: 'ios', appVersion: '5.2.0', build: '12', features: ['capabilities', 'edgeBack'] }; + +beforeEach(() => { + _resetNativeCapabilities(); + vi.mocked(isNativeApp).mockReturnValue(true); + vi.mocked(TrekShell.getCapabilities) + .mockReset() + .mockResolvedValue(CAPS as never); +}); + +afterEach(() => vi.unstubAllGlobals()); + +describe('native capabilities', () => { + it('asks the binary once and answers features by name', async () => { + await loadNativeCapabilities(); + await loadNativeCapabilities(); + expect(TrekShell.getCapabilities).toHaveBeenCalledTimes(1); + expect(hasNativeFeature('edgeBack')).toBe(true); + expect(hasNativeFeature('tileCache')).toBe(false); + expect(nativeCapabilities().appVersion).toBe('5.2.0'); + }); + + it('counts a binary from before the handshake as shell API 1 with no features', async () => { + vi.mocked(TrekShell.getCapabilities).mockRejectedValue({ code: 'UNIMPLEMENTED' }); + const caps = await loadNativeCapabilities(); + expect(caps.shellApi).toBe(1); + expect(hasNativeFeature('capabilities')).toBe(false); + }); + + it('reports a real failure but still settles on the legacy answer', async () => { + const report = vi.fn(); + vi.stubGlobal('reportError', report); + vi.mocked(TrekShell.getCapabilities).mockRejectedValue(new Error('bridge down')); + expect((await loadNativeCapabilities()).shellApi).toBe(1); + expect(report).toHaveBeenCalled(); + }); + + it('asks nothing in a browser', async () => { + vi.mocked(isNativeApp).mockReturnValue(false); + expect((await loadNativeCapabilities()).platform).toBe('web'); + expect(TrekShell.getCapabilities).not.toHaveBeenCalled(); + expect(await checkAppUpdate(async () => ({ minNativeShellApi: 9 }))).toBe(false); + }); + + it('asks for an update only when the server needs a newer binary', async () => { + expect(await checkAppUpdate(async () => ({ minNativeShellApi: 2 }))).toBe(false); + expect(await checkAppUpdate(async () => ({ minNativeShellApi: 3 }))).toBe(true); + expect(appUpdateRequired()).toBe(true); + }); + + it('requires nothing from a server that names no minimum, or cannot be asked', async () => { + expect(await checkAppUpdate(async () => ({}))).toBe(false); + expect( + await checkAppUpdate(async () => { + throw new Error('offline'); + }) + ).toBe(false); + }); +}); diff --git a/client/src/native/capabilities.ts b/client/src/native/capabilities.ts new file mode 100644 index 000000000..ec7b01085 --- /dev/null +++ b/client/src/native/capabilities.ts @@ -0,0 +1,102 @@ +import { useSyncExternalStore } from 'react'; +import { isNativeApp } from './platform'; +import { reportNativeFailure } from './reportFailure'; +import { TrekShell, isUnimplemented } from './trekShell'; + +/** + * What the installed app binary offers the UI this server delivers. + * + * The two update on their own clocks: the UI ships with the server, the binary + * through the stores. So the UI asks before it calls into anything native the + * binary may predate, and turns each feature on by name (hasNativeFeature). A + * binary from before this handshake answers UNIMPLEMENTED and counts as shell + * API 1 with no named features, which is exactly what it can do. + * + * The other direction runs through the server's features: minNativeShellApi + * names the oldest binary its UI works with, and an app below it is asked to + * update (appUpdateRequired) rather than left calling methods it lacks. + */ +export interface NativeCapabilities { + shellApi: number; + platform: 'ios' | 'android' | 'web'; + appVersion: string; + build: string; + features: string[]; +} + +const WEB: NativeCapabilities = { shellApi: 0, platform: 'web', appVersion: '', build: '', features: [] }; +const LEGACY_APP: NativeCapabilities = { shellApi: 1, platform: 'web', appVersion: '', build: '', features: [] }; + +let current: NativeCapabilities = WEB; +let updateRequired = false; +let loading: Promise | null = null; +const listeners = new Set<() => void>(); + +function emit(): void { + for (const listener of listeners) listener(); +} + +/** Asks the binary once and keeps the answer for the session. */ +export function loadNativeCapabilities(): Promise { + if (!isNativeApp()) return Promise.resolve(WEB); + loading ??= TrekShell.getCapabilities() + .then( + (caps) => caps, + (err: unknown) => { + if (!isUnimplemented(err)) reportNativeFailure(err); + return LEGACY_APP; + } + ) + .then((caps) => { + current = caps; + emit(); + return caps; + }); + return loading; +} + +/** Whether the installed binary has a native feature, as far as it is known yet. */ +export function hasNativeFeature(feature: string): boolean { + return current.features.includes(feature); +} + +export function nativeCapabilities(): NativeCapabilities { + return current; +} + +/** + * Compares the binary with the oldest one this server's UI works with. A + * server that says nothing (older than the handshake) requires nothing. + */ +export async function checkAppUpdate(fetchFeatures: () => Promise<{ minNativeShellApi?: unknown }>): Promise { + if (!isNativeApp()) return false; + const [caps, features] = await Promise.all([loadNativeCapabilities(), fetchFeatures().catch(() => ({}))]); + const min = typeof features.minNativeShellApi === 'number' ? features.minNativeShellApi : 0; + updateRequired = caps.shellApi < min; + emit(); + return updateRequired; +} + +export function appUpdateRequired(): boolean { + return updateRequired; +} + +function subscribe(listener: () => void): () => void { + listeners.add(listener); + return () => listeners.delete(listener); +} + +/** Re-renders when the capabilities arrive or the update check answers. */ +export function useNativeCapabilities(): { caps: NativeCapabilities; updateRequired: boolean } { + const caps = useSyncExternalStore(subscribe, nativeCapabilities, nativeCapabilities); + const required = useSyncExternalStore(subscribe, appUpdateRequired, appUpdateRequired); + return { caps, updateRequired: required }; +} + +/** Test helper: forget what was asked. */ +export function _resetNativeCapabilities(): void { + current = WEB; + updateRequired = false; + loading = null; + listeners.clear(); +} diff --git a/client/src/native/nativeApp.test.ts b/client/src/native/nativeApp.test.ts index 7710c502e..1dbb85a58 100644 --- a/client/src/native/nativeApp.test.ts +++ b/client/src/native/nativeApp.test.ts @@ -4,6 +4,7 @@ import { SplashScreen } from '@capacitor/splash-screen'; import { StatusBar, Style } from '@capacitor/status-bar'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { isEffectivelyOffline } from '../sync/networkMode'; +import { checkAppUpdate } from './capabilities'; import { startNativeApp } from './nativeApp'; import { keepOfflineShellFresh } from './offlineShell'; import { isNativeApp, isNativeIos } from './platform'; @@ -15,6 +16,7 @@ vi.mock('@capacitor/status-bar', () => ({ StatusBar: { setStyle: vi.fn() }, Styl vi.mock('./platform', () => ({ isNativeApp: vi.fn(), isNativeIos: vi.fn() })); vi.mock('./offlineShell', () => ({ keepOfflineShellFresh: vi.fn() })); vi.mock('../sync/networkMode', () => ({ isEffectivelyOffline: vi.fn() })); +vi.mock('./capabilities', () => ({ checkAppUpdate: vi.fn(async () => false) })); function backButtonHandler(): (event: { canGoBack: boolean }) => void { const call = vi.mocked(App.addListener).mock.calls.find(([name]) => name === 'backButton'); @@ -44,6 +46,11 @@ describe('startNativeApp', () => { expect(StatusBar.setStyle).not.toHaveBeenCalled(); }); + it('asks the binary what it can do and the server which binary it needs', () => { + startNativeApp(); + expect(checkAppUpdate).toHaveBeenCalledWith(expect.any(Function)); + }); + it('hides the splash after the first frame', () => { startNativeApp(); vi.runOnlyPendingTimers(); diff --git a/client/src/native/nativeApp.ts b/client/src/native/nativeApp.ts index ba57310d6..c4ead14a4 100644 --- a/client/src/native/nativeApp.ts +++ b/client/src/native/nativeApp.ts @@ -3,6 +3,7 @@ import { Keyboard } from '@capacitor/keyboard'; import { SplashScreen } from '@capacitor/splash-screen'; import { StatusBar, Style } from '@capacitor/status-bar'; import { isEffectivelyOffline } from '../sync/networkMode'; +import { checkAppUpdate } from './capabilities'; import { keepOfflineShellFresh } from './offlineShell'; import { isNativeApp, isNativeIos } from './platform'; import { reportNativeFailure } from './reportFailure'; @@ -20,6 +21,9 @@ export function startNativeApp(): void { followThemeInStatusBar(); + // What this binary can do, and whether this server's UI needs a newer one. + void checkAppUpdate(fetchServerFeatures); + // Android's back gesture: through the app's own history first, and only // then out of the app, the way a browser tab would behave. void App.addListener('backButton', ({ canGoBack }) => { @@ -58,3 +62,10 @@ function followThemeInStatusBar(): void { apply(); new MutationObserver(apply).observe(root, { attributes: true, attributeFilter: ['class'] }); } + +/** The server's feature flags, bounded so a slow server cannot hold anything up. */ +async function fetchServerFeatures(): Promise<{ minNativeShellApi?: unknown }> { + const res = await fetch('/api/health/features', { credentials: 'same-origin', signal: AbortSignal.timeout(8000) }); + if (!res.ok) return {}; + return (await res.json()) as { minNativeShellApi?: unknown }; +} diff --git a/client/src/native/trekShell.ts b/client/src/native/trekShell.ts index 548f12183..90d645f0e 100644 --- a/client/src/native/trekShell.ts +++ b/client/src/native/trekShell.ts @@ -1,4 +1,5 @@ import { registerPlugin } from '@capacitor/core'; +import type { NativeCapabilities } from './capabilities'; /** * The app's own native plugin, implemented in @@ -29,6 +30,8 @@ export interface TrekShellPlugin { refreshOfflineCopy(): Promise<{ saved: boolean }>; /** iOS: loads that copy under the server's origin. False when there is none. */ openOfflineCopy(): Promise<{ opened: boolean }>; + /** What this binary offers the UI (native/capabilities.ts). Missing before shell API 2. */ + getCapabilities(): Promise; } export const TrekShell = registerPlugin('TrekShell'); diff --git a/server/src/nest/health/features.controller.ts b/server/src/nest/health/features.controller.ts index 93dfb022e..a1d67d934 100644 --- a/server/src/nest/health/features.controller.ts +++ b/server/src/nest/health/features.controller.ts @@ -70,6 +70,10 @@ export class FeaturesController { // routes, the shell bridge in the served UI). Raised only for a change an // older app cannot follow; the app refuses a server below its minimum. nativeApi: 1, + // The other way round: the oldest app binary this server's UI works with, + // as the shell API the app reports (TrekShell.getCapabilities). An app + // below it is asked to update instead of running native calls it lacks. + minNativeShellApi: 1, }; } } diff --git a/server/tests/unit/nest/features.controller.test.ts b/server/tests/unit/nest/features.controller.test.ts index 26038ea8f..0babcd507 100644 --- a/server/tests/unit/nest/features.controller.test.ts +++ b/server/tests/unit/nest/features.controller.test.ts @@ -38,6 +38,7 @@ describe('FeaturesController (GET /api/health/features)', () => { aiAssistant: true, nativeApp: true, nativeApi: 1, + minNativeShellApi: 1, }); }); @@ -49,6 +50,7 @@ describe('FeaturesController (GET /api/health/features)', () => { aiAssistant: false, nativeApp: true, nativeApi: 1, + minNativeShellApi: 1, }); }); @@ -59,6 +61,7 @@ describe('FeaturesController (GET /api/health/features)', () => { aiAssistant: false, nativeApp: true, nativeApi: 1, + minNativeShellApi: 1, }); expect(await make(false, true).controller.features()).toEqual({ bookingImport: false, @@ -66,6 +69,7 @@ describe('FeaturesController (GET /api/health/features)', () => { aiAssistant: true, nativeApp: true, nativeApi: 1, + minNativeShellApi: 1, }); }); @@ -91,6 +95,8 @@ describe('FeaturesController (GET /api/health/features)', () => { const features = await make(false, false).controller.features(); expect(features.nativeApp).toBe(true); expect(features.nativeApi).toBe(1); + // And which app binaries its UI still works with. + expect(features.minNativeShellApi).toBe(1); }); it('FEAT-005: bookingImport is read live, not cached at construction', async () => { diff --git a/shared/src/i18n/ar/native.ts b/shared/src/i18n/ar/native.ts index 8ab139c79..b0acf4595 100644 --- a/shared/src/i18n/ar/native.ts +++ b/shared/src/i18n/ar/native.ts @@ -71,6 +71,9 @@ const native: TranslationStrings = { 'native.provisioning.failedTitle': 'شارف على الجهوزية', 'native.provisioning.failedSub': 'TREK الخاص بك في الطريق. حاول مرة أخرى بعد قليل، أو افتح التطبيق لاحقًا.', 'native.provisioning.retry': 'حاول الآن', + 'native.update.title': 'حدّث تطبيق TREK', + 'native.update.body': 'يحتاج هذا الخادم إلى إصدار أحدث من التطبيق ليعمل كل شيء.', + 'native.update.open': 'تحديث', }; export default native; diff --git a/shared/src/i18n/az/native.ts b/shared/src/i18n/az/native.ts index 4740b6759..3e4c663e5 100644 --- a/shared/src/i18n/az/native.ts +++ b/shared/src/i18n/az/native.ts @@ -72,6 +72,9 @@ const native: TranslationStrings = { 'native.provisioning.failedTitle': 'Demək olar ki hazırdır', 'native.provisioning.failedSub': 'TREK-iniz yoldadır. Bir azdan yenidən cəhd edin və ya tətbiqi sonra açın.', 'native.provisioning.retry': 'İndi cəhd edin', + 'native.update.title': 'TREK tətbiqini yeniləyin', + 'native.update.body': 'Hər şeyin işləməsi üçün bu server tətbiqin daha yeni versiyasını tələb edir.', + 'native.update.open': 'Yenilə', }; export default native; diff --git a/shared/src/i18n/br/native.ts b/shared/src/i18n/br/native.ts index c429a9ae9..8b266344d 100644 --- a/shared/src/i18n/br/native.ts +++ b/shared/src/i18n/br/native.ts @@ -72,6 +72,9 @@ const native: TranslationStrings = { 'native.provisioning.failedTitle': 'Quase pronto', 'native.provisioning.failedSub': 'Seu TREK está a caminho. Tente novamente em instantes ou abra o app mais tarde.', 'native.provisioning.retry': 'Tentar agora', + 'native.update.title': 'Atualize o app TREK', + 'native.update.body': 'Este servidor precisa de uma versão mais nova do app para tudo funcionar.', + 'native.update.open': 'Atualizar', }; export default native; diff --git a/shared/src/i18n/ca/native.ts b/shared/src/i18n/ca/native.ts index c44e5885e..5a3d79f8d 100644 --- a/shared/src/i18n/ca/native.ts +++ b/shared/src/i18n/ca/native.ts @@ -72,6 +72,9 @@ const native: TranslationStrings = { 'native.provisioning.failedTitle': 'Gairebé a punt', 'native.provisioning.failedSub': 'El teu TREK està en camí. Torna-ho a provar en un moment o obre l’app més tard.', 'native.provisioning.retry': 'Prova-ho ara', + 'native.update.title': 'Actualitza l’app TREK', + 'native.update.body': 'Aquest servidor necessita una versió més nova de l’app perquè tot funcioni.', + 'native.update.open': 'Actualitza', }; export default native; diff --git a/shared/src/i18n/cs/native.ts b/shared/src/i18n/cs/native.ts index 029fec1d8..4a5df0cc8 100644 --- a/shared/src/i18n/cs/native.ts +++ b/shared/src/i18n/cs/native.ts @@ -72,6 +72,9 @@ const native: TranslationStrings = { 'native.provisioning.failedTitle': 'Téměř hotovo', 'native.provisioning.failedSub': 'Váš TREK je na cestě. Zkuste to za chvíli znovu nebo otevřete aplikaci později.', 'native.provisioning.retry': 'Zkusit teď', + 'native.update.title': 'Aktualizujte aplikaci TREK', + 'native.update.body': 'Tento server potřebuje novější verzi aplikace, aby vše fungovalo.', + 'native.update.open': 'Aktualizovat', }; export default native; diff --git a/shared/src/i18n/de/native.ts b/shared/src/i18n/de/native.ts index 812db3277..f4f3c38d0 100644 --- a/shared/src/i18n/de/native.ts +++ b/shared/src/i18n/de/native.ts @@ -73,6 +73,9 @@ const native: TranslationStrings = { 'native.provisioning.failedTitle': 'Gleich fertig', 'native.provisioning.failedSub': 'Deine TREK ist unterwegs. Versuch es gleich noch einmal oder öffne die App später.', 'native.provisioning.retry': 'Jetzt versuchen', + 'native.update.title': 'TREK-App aktualisieren', + 'native.update.body': 'Dieser Server braucht eine neuere App-Version, damit alles funktioniert.', + 'native.update.open': 'Aktualisieren', }; export default native; diff --git a/shared/src/i18n/en/native.ts b/shared/src/i18n/en/native.ts index eaa9a517f..944bf5367 100644 --- a/shared/src/i18n/en/native.ts +++ b/shared/src/i18n/en/native.ts @@ -72,6 +72,9 @@ const native: TranslationStrings = { 'native.provisioning.failedTitle': 'Almost ready', 'native.provisioning.failedSub': 'Your TREK is on its way. Try again in a moment, or open the app later.', 'native.provisioning.retry': 'Try now', + 'native.update.title': 'Update the TREK app', + 'native.update.body': 'This server needs a newer version of the app for everything to work.', + 'native.update.open': 'Update', }; export default native; diff --git a/shared/src/i18n/es/native.ts b/shared/src/i18n/es/native.ts index c01135a1b..acca41415 100644 --- a/shared/src/i18n/es/native.ts +++ b/shared/src/i18n/es/native.ts @@ -73,6 +73,9 @@ const native: TranslationStrings = { 'native.provisioning.failedTitle': 'Casi listo', 'native.provisioning.failedSub': 'Tu TREK está en camino. Inténtalo en un momento o abre la app más tarde.', 'native.provisioning.retry': 'Probar ahora', + 'native.update.title': 'Actualiza la app TREK', + 'native.update.body': 'Este servidor necesita una versión más reciente de la app para que todo funcione.', + 'native.update.open': 'Actualizar', }; export default native; diff --git a/shared/src/i18n/et/native.ts b/shared/src/i18n/et/native.ts index 032006784..caf028739 100644 --- a/shared/src/i18n/et/native.ts +++ b/shared/src/i18n/et/native.ts @@ -72,6 +72,9 @@ const native: TranslationStrings = { 'native.provisioning.failedTitle': 'Peaaegu valmis', 'native.provisioning.failedSub': 'Sinu TREK on teel. Proovi hetke pärast uuesti või ava rakendus hiljem.', 'native.provisioning.retry': 'Proovi nüüd', + 'native.update.title': 'Uuenda TREK-i rakendust', + 'native.update.body': 'See server vajab kõige toimimiseks rakenduse uuemat versiooni.', + 'native.update.open': 'Uuenda', }; export default native; diff --git a/shared/src/i18n/fr/native.ts b/shared/src/i18n/fr/native.ts index a7f705205..df103e932 100644 --- a/shared/src/i18n/fr/native.ts +++ b/shared/src/i18n/fr/native.ts @@ -73,6 +73,9 @@ const native: TranslationStrings = { 'native.provisioning.failedTitle': 'Presque prêt', 'native.provisioning.failedSub': 'Votre TREK arrive. Réessayez dans un instant ou rouvrez l’app plus tard.', 'native.provisioning.retry': 'Réessayer', + 'native.update.title': 'Mettez à jour l’app TREK', + 'native.update.body': 'Ce serveur a besoin d’une version plus récente de l’app pour que tout fonctionne.', + 'native.update.open': 'Mettre à jour', }; export default native; diff --git a/shared/src/i18n/gr/native.ts b/shared/src/i18n/gr/native.ts index ad49162a6..d284e878a 100644 --- a/shared/src/i18n/gr/native.ts +++ b/shared/src/i18n/gr/native.ts @@ -75,6 +75,9 @@ const native: TranslationStrings = { 'native.provisioning.failedTitle': 'Σχεδόν έτοιμο', 'native.provisioning.failedSub': 'Το TREK σας έρχεται. Δοκιμάστε ξανά σε λίγο ή ανοίξτε την εφαρμογή αργότερα.', 'native.provisioning.retry': 'Δοκιμάστε τώρα', + 'native.update.title': 'Ενημερώστε την εφαρμογή TREK', + 'native.update.body': 'Αυτός ο διακομιστής χρειάζεται νεότερη έκδοση της εφαρμογής για να λειτουργούν όλα.', + 'native.update.open': 'Ενημέρωση', }; export default native; diff --git a/shared/src/i18n/he/native.ts b/shared/src/i18n/he/native.ts index bc376a049..c815a9a88 100644 --- a/shared/src/i18n/he/native.ts +++ b/shared/src/i18n/he/native.ts @@ -71,6 +71,9 @@ const native: TranslationStrings = { 'native.provisioning.failedTitle': 'כמעט מוכן', 'native.provisioning.failedSub': 'ה-TREK שלכם בדרך. נסו שוב עוד רגע, או פתחו את האפליקציה מאוחר יותר.', 'native.provisioning.retry': 'נסו עכשיו', + 'native.update.title': 'עדכנו את אפליקציית TREK', + 'native.update.body': 'השרת הזה צריך גרסה חדשה יותר של האפליקציה כדי שהכול יעבוד.', + 'native.update.open': 'עדכון', }; export default native; diff --git a/shared/src/i18n/hu/native.ts b/shared/src/i18n/hu/native.ts index ffa880b6c..b11ba037c 100644 --- a/shared/src/i18n/hu/native.ts +++ b/shared/src/i18n/hu/native.ts @@ -74,6 +74,9 @@ const native: TranslationStrings = { 'native.provisioning.failedSub': 'A TREK-ed úton van. Próbáld újra egy pillanat múlva, vagy nyisd meg az appot később.', 'native.provisioning.retry': 'Próbáld most', + 'native.update.title': 'Frissítsd a TREK alkalmazást', + 'native.update.body': 'Ehhez a szerverhez az alkalmazás újabb verziója kell, hogy minden működjön.', + 'native.update.open': 'Frissítés', }; export default native; diff --git a/shared/src/i18n/id/native.ts b/shared/src/i18n/id/native.ts index c97ccef07..0a6a48f81 100644 --- a/shared/src/i18n/id/native.ts +++ b/shared/src/i18n/id/native.ts @@ -73,6 +73,9 @@ const native: TranslationStrings = { 'native.provisioning.failedSub': 'TREK Anda sedang dalam perjalanan. Coba lagi sebentar lagi, atau buka aplikasi nanti.', 'native.provisioning.retry': 'Coba sekarang', + 'native.update.title': 'Perbarui aplikasi TREK', + 'native.update.body': 'Server ini memerlukan versi aplikasi yang lebih baru agar semuanya berfungsi.', + 'native.update.open': 'Perbarui', }; export default native; diff --git a/shared/src/i18n/it/native.ts b/shared/src/i18n/it/native.ts index ac316f7eb..e84b4433f 100644 --- a/shared/src/i18n/it/native.ts +++ b/shared/src/i18n/it/native.ts @@ -73,6 +73,9 @@ const native: TranslationStrings = { 'native.provisioning.failedTitle': 'Quasi pronto', 'native.provisioning.failedSub': 'Il tuo TREK sta arrivando. Riprova tra poco o riapri l’app più tardi.', 'native.provisioning.retry': 'Riprova', + 'native.update.title': 'Aggiorna l’app TREK', + 'native.update.body': 'Questo server richiede una versione più recente dell’app perché tutto funzioni.', + 'native.update.open': 'Aggiorna', }; export default native; diff --git a/shared/src/i18n/ja/native.ts b/shared/src/i18n/ja/native.ts index 7ef40096b..98b465367 100644 --- a/shared/src/i18n/ja/native.ts +++ b/shared/src/i18n/ja/native.ts @@ -73,6 +73,9 @@ const native: TranslationStrings = { 'native.provisioning.failedSub': 'TREKはまもなく準備できます。少ししてからもう一度試すか、後でアプリを開いてください。', 'native.provisioning.retry': '今すぐ試す', + 'native.update.title': 'TREKアプリを更新してください', + 'native.update.body': 'すべての機能を使うには、このサーバーに対応した新しいバージョンのアプリが必要です。', + 'native.update.open': '更新', }; export default native; diff --git a/shared/src/i18n/ko/native.ts b/shared/src/i18n/ko/native.ts index 76d5bedc0..7af517085 100644 --- a/shared/src/i18n/ko/native.ts +++ b/shared/src/i18n/ko/native.ts @@ -71,6 +71,9 @@ const native: TranslationStrings = { 'native.provisioning.failedTitle': '거의 준비됐어요', 'native.provisioning.failedSub': 'TREK이 곧 준비됩니다. 잠시 후 다시 시도하거나 나중에 앱을 열어 보세요.', 'native.provisioning.retry': '지금 시도', + 'native.update.title': 'TREK 앱을 업데이트하세요', + 'native.update.body': '모든 기능을 사용하려면 이 서버에 맞는 최신 앱 버전이 필요합니다.', + 'native.update.open': '업데이트', }; export default native; diff --git a/shared/src/i18n/nl/native.ts b/shared/src/i18n/nl/native.ts index 525bf24c8..567f58b32 100644 --- a/shared/src/i18n/nl/native.ts +++ b/shared/src/i18n/nl/native.ts @@ -72,6 +72,9 @@ const native: TranslationStrings = { 'native.provisioning.failedTitle': 'Bijna klaar', 'native.provisioning.failedSub': 'Je TREK is onderweg. Probeer het zo opnieuw of open de app later.', 'native.provisioning.retry': 'Nu proberen', + 'native.update.title': 'Werk de TREK-app bij', + 'native.update.body': 'Deze server heeft een nieuwere versie van de app nodig om alles te laten werken.', + 'native.update.open': 'Bijwerken', }; export default native; diff --git a/shared/src/i18n/pl/native.ts b/shared/src/i18n/pl/native.ts index 2556a5d13..de910bc79 100644 --- a/shared/src/i18n/pl/native.ts +++ b/shared/src/i18n/pl/native.ts @@ -72,6 +72,9 @@ const native: TranslationStrings = { 'native.provisioning.failedTitle': 'Już prawie', 'native.provisioning.failedSub': 'Twój TREK jest w drodze. Spróbuj za chwilę lub otwórz aplikację później.', 'native.provisioning.retry': 'Spróbuj teraz', + 'native.update.title': 'Zaktualizuj aplikację TREK', + 'native.update.body': 'Ten serwer wymaga nowszej wersji aplikacji, aby wszystko działało.', + 'native.update.open': 'Aktualizuj', }; export default native; diff --git a/shared/src/i18n/ru/native.ts b/shared/src/i18n/ru/native.ts index 34c723abd..acabe6cc2 100644 --- a/shared/src/i18n/ru/native.ts +++ b/shared/src/i18n/ru/native.ts @@ -73,6 +73,9 @@ const native: TranslationStrings = { 'native.provisioning.failedSub': 'Ваш TREK уже в пути. Повторите попытку через мгновение или откройте приложение позже.', 'native.provisioning.retry': 'Повторить сейчас', + 'native.update.title': 'Обновите приложение TREK', + 'native.update.body': 'Для полной работы этому серверу нужна более новая версия приложения.', + 'native.update.open': 'Обновить', }; export default native; diff --git a/shared/src/i18n/sk/native.ts b/shared/src/i18n/sk/native.ts index 3df71215f..581df2052 100644 --- a/shared/src/i18n/sk/native.ts +++ b/shared/src/i18n/sk/native.ts @@ -72,6 +72,9 @@ const native: TranslationStrings = { 'native.provisioning.failedTitle': 'Takmer hotovo', 'native.provisioning.failedSub': 'Váš TREK je na ceste. Skúste to o chvíľu znova alebo otvorte aplikáciu neskôr.', 'native.provisioning.retry': 'Skúsiť teraz', + 'native.update.title': 'Aktualizujte aplikáciu TREK', + 'native.update.body': 'Tento server potrebuje novšiu verziu aplikácie, aby všetko fungovalo.', + 'native.update.open': 'Aktualizovať', }; export default native; diff --git a/shared/src/i18n/sv/native.ts b/shared/src/i18n/sv/native.ts index 2531be4aa..7e4858a53 100644 --- a/shared/src/i18n/sv/native.ts +++ b/shared/src/i18n/sv/native.ts @@ -73,6 +73,9 @@ const native: TranslationStrings = { 'native.provisioning.failedTitle': 'Snart klart', 'native.provisioning.failedSub': 'Din TREK är på väg. Försök igen om en stund eller öppna appen senare.', 'native.provisioning.retry': 'Försök nu', + 'native.update.title': 'Uppdatera TREK-appen', + 'native.update.body': 'Den här servern behöver en nyare version av appen för att allt ska fungera.', + 'native.update.open': 'Uppdatera', }; export default native; diff --git a/shared/src/i18n/th/native.ts b/shared/src/i18n/th/native.ts index f0a2222c3..ce9054a23 100644 --- a/shared/src/i18n/th/native.ts +++ b/shared/src/i18n/th/native.ts @@ -71,6 +71,9 @@ const native: TranslationStrings = { 'native.provisioning.failedTitle': 'เกือบเสร็จแล้ว', 'native.provisioning.failedSub': 'TREK ของคุณกำลังมา ลองอีกครั้งในอีกสักครู่ หรือเปิดแอปในภายหลัง', 'native.provisioning.retry': 'ลองตอนนี้', + 'native.update.title': 'อัปเดตแอป TREK', + 'native.update.body': 'เซิร์ฟเวอร์นี้ต้องใช้แอปเวอร์ชันใหม่กว่าเพื่อให้ทุกอย่างทำงานได้', + 'native.update.open': 'อัปเดต', }; export default native; diff --git a/shared/src/i18n/tr/native.ts b/shared/src/i18n/tr/native.ts index dd52b1ddc..4f4099805 100644 --- a/shared/src/i18n/tr/native.ts +++ b/shared/src/i18n/tr/native.ts @@ -73,6 +73,9 @@ const native: TranslationStrings = { 'native.provisioning.failedTitle': 'Neredeyse hazır', 'native.provisioning.failedSub': 'TREK’iniz yolda. Birazdan tekrar deneyin ya da uygulamayı sonra açın.', 'native.provisioning.retry': 'Şimdi dene', + 'native.update.title': 'TREK uygulamasını güncelleyin', + 'native.update.body': 'Her şeyin çalışması için bu sunucu uygulamanın daha yeni bir sürümüne ihtiyaç duyuyor.', + 'native.update.open': 'Güncelle', }; export default native; diff --git a/shared/src/i18n/uk/native.ts b/shared/src/i18n/uk/native.ts index 892e98e8f..c03987d00 100644 --- a/shared/src/i18n/uk/native.ts +++ b/shared/src/i18n/uk/native.ts @@ -72,6 +72,9 @@ const native: TranslationStrings = { 'native.provisioning.failedTitle': 'Майже готово', 'native.provisioning.failedSub': 'Ваш TREK уже в дорозі. Повторіть спробу за мить або відкрийте застосунок пізніше.', 'native.provisioning.retry': 'Повторити зараз', + 'native.update.title': 'Оновіть застосунок TREK', + 'native.update.body': 'Для повної роботи цьому серверу потрібна новіша версія застосунку.', + 'native.update.open': 'Оновити', }; export default native; diff --git a/shared/src/i18n/vi/native.ts b/shared/src/i18n/vi/native.ts index 0e019bac6..612f88226 100644 --- a/shared/src/i18n/vi/native.ts +++ b/shared/src/i18n/vi/native.ts @@ -73,6 +73,9 @@ const native: TranslationStrings = { 'native.provisioning.failedTitle': 'Gần xong', 'native.provisioning.failedSub': 'TREK của bạn đang trên đường. Hãy thử lại sau giây lát, hoặc mở ứng dụng sau.', 'native.provisioning.retry': 'Thử ngay', + 'native.update.title': 'Cập nhật ứng dụng TREK', + 'native.update.body': 'Máy chủ này cần phiên bản ứng dụng mới hơn để mọi thứ hoạt động.', + 'native.update.open': 'Cập nhật', }; export default native; diff --git a/shared/src/i18n/zh-TW/native.ts b/shared/src/i18n/zh-TW/native.ts index d5e630fc6..1779c58d5 100644 --- a/shared/src/i18n/zh-TW/native.ts +++ b/shared/src/i18n/zh-TW/native.ts @@ -71,6 +71,9 @@ const native: TranslationStrings = { 'native.provisioning.failedTitle': '即將就緒', 'native.provisioning.failedSub': '你的 TREK 即將就緒。請稍後重試,或稍後開啟應用程式。', 'native.provisioning.retry': '立即重試', + 'native.update.title': '請更新 TREK 應用程式', + 'native.update.body': '此伺服器需要較新版本的應用程式才能正常使用所有功能。', + 'native.update.open': '更新', }; export default native; diff --git a/shared/src/i18n/zh/native.ts b/shared/src/i18n/zh/native.ts index 9d2d0c009..0bbce90b9 100644 --- a/shared/src/i18n/zh/native.ts +++ b/shared/src/i18n/zh/native.ts @@ -71,6 +71,9 @@ const native: TranslationStrings = { 'native.provisioning.failedTitle': '即将就绪', 'native.provisioning.failedSub': '你的 TREK 正在路上。请稍后重试,或稍后打开应用。', 'native.provisioning.retry': '立即重试', + 'native.update.title': '请更新 TREK 应用', + 'native.update.body': '此服务器需要更新版本的应用才能正常使用全部功能。', + 'native.update.open': '更新', }; export default native; From d859e23879401d87ba826239fc3a22d4f18a43d6 Mon Sep 17 00:00:00 2001 From: Maurice Date: Fri, 6 Nov 2026 13:10:39 +0100 Subject: [PATCH 066/589] feat(native): the app's own swipe back, and a way back closes the sheet on top first WebKit's swipe from the left edge slid away a screenshot of the whole page, closed no sheet and took every drag near the edge from the UI. Binaries from this one turn it off and report an edgeBack feature, and the UI draws its own: the page follows the finger, a release past a third or a flick slides it off and goes back, anything else springs it home, with a light detent. Open sheets now register in one overlay stack, so a way back closes the one on top first, through its own close path (unsaved changes still ask): the edge swipe on iOS and Android's back gesture alike. --- .../App/App/TrekBridgeViewController.swift | 8 +- client/ios/App/App/TrekShellPlugin.swift | 2 +- client/src/mobile/MobileShell.tsx | 12 +- .../src/mobile/components/MEdgeBack.test.tsx | 100 +++++++++++++++ client/src/mobile/components/MEdgeBack.tsx | 118 ++++++++++++++++++ client/src/mobile/components/MSheet.tsx | 5 + client/src/mobile/overlayStack.test.ts | 36 ++++++ client/src/mobile/overlayStack.ts | 43 +++++++ client/src/native/nativeApp.test.ts | 13 ++ client/src/native/nativeApp.ts | 3 + client/tests/unit/mobile/MSheet.test.tsx | 18 +++ 11 files changed, 352 insertions(+), 6 deletions(-) create mode 100644 client/src/mobile/components/MEdgeBack.test.tsx create mode 100644 client/src/mobile/components/MEdgeBack.tsx create mode 100644 client/src/mobile/overlayStack.test.ts create mode 100644 client/src/mobile/overlayStack.ts diff --git a/client/ios/App/App/TrekBridgeViewController.swift b/client/ios/App/App/TrekBridgeViewController.swift index 9236553cb..65d6477b3 100644 --- a/client/ios/App/App/TrekBridgeViewController.swift +++ b/client/ios/App/App/TrekBridgeViewController.swift @@ -19,9 +19,11 @@ class TrekBridgeViewController: CAPBridgeViewController { override func capacitorDidLoad() { bridge?.registerPluginInstance(TrekShellPlugin()) - // The swipe from the left edge that goes back in every iOS app. It walks - // the SPA's history, the same entries Android's back button uses. - webView?.allowsBackForwardNavigationGestures = true + // WebKit's own swipe back slides away a screenshot of the whole page, + // closes no sheet and takes every drag near the edge from the UI. The UI + // draws its own (mobile/components/MEdgeBack.tsx, feature "edgeBack"): + // the page follows the finger and an open sheet closes first. + webView?.allowsBackForwardNavigationGestures = false } } diff --git a/client/ios/App/App/TrekShellPlugin.swift b/client/ios/App/App/TrekShellPlugin.swift index b5d944939..2cae368b1 100644 --- a/client/ios/App/App/TrekShellPlugin.swift +++ b/client/ios/App/App/TrekShellPlugin.swift @@ -24,7 +24,7 @@ public class TrekShellPlugin: CAPPlugin, CAPBridgedPlugin, ASWebAuthenticationPr /// and a server can require a minimum (minNativeShellApi in /api/health/features). static let shellApi = 2 /// The native features by name, so the UI can turn each on by itself. - static let features: [String] = ["capabilities"] + static let features: [String] = ["capabilities", "edgeBack"] @objc func getCapabilities(_ call: CAPPluginCall) { let info = Bundle.main.infoDictionary diff --git a/client/src/mobile/MobileShell.tsx b/client/src/mobile/MobileShell.tsx index e04e2ca95..2b7cd3704 100644 --- a/client/src/mobile/MobileShell.tsx +++ b/client/src/mobile/MobileShell.tsx @@ -1,9 +1,12 @@ -import { ReactNode } from 'react' +import { ReactNode, useRef } from 'react' import { useMatch } from 'react-router' import BottomNav from '../components/Layout/BottomNav' import ErrorBoundary from '../components/shared/ErrorBoundary' import MBottomNav from './components/MBottomNav' import MToastHost from './components/MToastHost' +import MEdgeBack from './components/MEdgeBack' +import { useNativeCapabilities } from '../native/capabilities' +import { isNativeIos } from '../native/platform' import './mobile.css' interface MobileShellProps { @@ -32,6 +35,10 @@ export default function MobileShell({ isPhone, children }: MobileShellProps) { // on iOS Safari a position:fixed nav paints THROUGH the trip overlay's higher // stacking context, so the wrong (global) bar shows on top of the trip screen. const inTripPlanner = useMatch('/trips/:id') + // The app's own edge swipe back, where the binary has turned WebKit's off. + const { caps } = useNativeCapabilities() + const pageRef = useRef(null) + const edgeBack = isNativeIos() && caps.features.includes('edgeBack') if (!isPhone) { return ( @@ -59,7 +66,8 @@ export default function MobileShell({ isPhone, children }: MobileShellProps) { layer to be visible, body must not paint over it, which index.css handles for this breakpoint. */}
-
{children}
+
{children}
+ {!inTripPlanner && }
diff --git a/client/src/mobile/components/MEdgeBack.test.tsx b/client/src/mobile/components/MEdgeBack.test.tsx new file mode 100644 index 000000000..4963dc3a3 --- /dev/null +++ b/client/src/mobile/components/MEdgeBack.test.tsx @@ -0,0 +1,100 @@ +import { render } from '@testing-library/react'; +import { useRef } from 'react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { tickHaptic } from '../../native/haptics'; +import { closeTopOverlay, hasOpenOverlay } from '../overlayStack'; +import MEdgeBack from './MEdgeBack'; + +vi.mock('../overlayStack', () => ({ closeTopOverlay: vi.fn(), hasOpenOverlay: vi.fn(() => false) })); +vi.mock('../../native/haptics', () => ({ tickHaptic: vi.fn() })); + +function Host({ enabled = true }: { enabled?: boolean }) { + const ref = useRef(null); + return ( + <> +
+ + + ); +} + +function touch(type: string, x: number, y = 300, t = 0) { + const e = new Event(type, { bubbles: true, cancelable: true }) as Event & Record; + Object.defineProperty(e, 'touches', { value: type === 'touchend' ? [] : [{ clientX: x, clientY: y }] }); + Object.defineProperty(e, 'changedTouches', { value: [{ clientX: x, clientY: y }] }); + Object.defineProperty(e, 'timeStamp', { value: t }); + document.dispatchEvent(e); +} + +beforeEach(() => { + vi.useFakeTimers(); + vi.mocked(hasOpenOverlay).mockReturnValue(false); + window.history.replaceState({ idx: 2 }, ''); + Object.defineProperty(window, 'innerWidth', { configurable: true, value: 400 }); +}); +afterEach(() => { + vi.useRealTimers(); + vi.clearAllMocks(); +}); + +describe('MEdgeBack', () => { + it('drags the page with a finger from the left edge, and goes back past a third', () => { + const back = vi.spyOn(window.history, 'back').mockImplementation(() => {}); + const { getByTestId } = render(); + touch('touchstart', 5, 300, 0); + touch('touchmove', 40, 302, 50); + touch('touchmove', 200, 304, 400); + expect(getByTestId('page').style.transform).toBe('translateX(195px)'); + touch('touchend', 200, 304, 900); + vi.advanceTimersByTime(250); + expect(back).toHaveBeenCalledTimes(1); + expect(tickHaptic).toHaveBeenCalled(); + }); + + it('springs back on a short, slow drag', () => { + const back = vi.spyOn(window.history, 'back').mockImplementation(() => {}); + const { getByTestId } = render(); + touch('touchstart', 5, 300, 0); + touch('touchmove', 30, 300, 200); + touch('touchmove', 60, 300, 800); + touch('touchend', 60, 300, 1600); + vi.advanceTimersByTime(300); + expect(back).not.toHaveBeenCalled(); + expect(getByTestId('page').style.transform).toBe(''); + }); + + it('closes an open sheet first and leaves the page where it is', () => { + vi.mocked(hasOpenOverlay).mockReturnValue(true); + const back = vi.spyOn(window.history, 'back').mockImplementation(() => {}); + const { getByTestId } = render(); + touch('touchstart', 5, 300, 0); + touch('touchmove', 200, 300, 100); + expect(getByTestId('page').style.transform).toBe(''); + touch('touchend', 200, 300, 200); + expect(closeTopOverlay).toHaveBeenCalledTimes(1); + expect(back).not.toHaveBeenCalled(); + }); + + it('ignores a touch away from the edge, a vertical scroll, the first page and a binary without the feature', () => { + const back = vi.spyOn(window.history, 'back').mockImplementation(() => {}); + const { unmount } = render(); + touch('touchstart', 120); + touch('touchmove', 300); + touch('touchend', 300, 300, 100); + touch('touchstart', 5, 300); + touch('touchmove', 8, 400); + touch('touchend', 8, 400, 100); + window.history.replaceState({ idx: 0 }, ''); + touch('touchstart', 5); + touch('touchmove', 300); + touch('touchend', 300, 300, 100); + unmount(); + window.history.replaceState({ idx: 2 }, ''); + render(); + touch('touchstart', 5); + touch('touchmove', 300); + touch('touchend', 300, 300, 100); + vi.advanceTimersByTime(300); + expect(back).not.toHaveBeenCalled(); + }); +}); diff --git a/client/src/mobile/components/MEdgeBack.tsx b/client/src/mobile/components/MEdgeBack.tsx new file mode 100644 index 000000000..abb43fa4f --- /dev/null +++ b/client/src/mobile/components/MEdgeBack.tsx @@ -0,0 +1,118 @@ +import type { RefObject } from 'react'; +import { useEffect } from 'react'; +import { tickHaptic } from '../../native/haptics'; +import { closeTopOverlay, hasOpenOverlay } from '../overlayStack'; + +/** + * The swipe from the left edge that goes back, the way every iOS app has it. + * + * WebKit's own version slides away a screenshot of the whole page, closes no + * sheet and fights every gesture near the edge (the day pager, swipe rows), so + * the app turns it off (TrekBridgeViewController) and this takes over: the + * page follows the finger, and a release past a third of the screen or a flick + * slides it off and goes back. An open sheet closes first instead, the same + * order Android's back gesture follows. Mounted only where the binary reports + * the `edgeBack` feature, so an older binary keeps WebKit's. + */ + +/** A touch has to start this close to the left edge. */ +const EDGE_PX = 22; +/** Sideways must clearly beat vertical before the gesture is claimed. */ +const CLAIM_PX = 10; +const AXIS_BIAS = 1.5; +const COMMIT_SHARE = 0.33; +const FLICK_V = 0.5; + +/** react-router keeps its position in the session history on history.state. */ +function canGoBack(): boolean { + const idx = (window.history.state as { idx?: number } | null)?.idx; + return typeof idx === 'number' && idx > 0; +} + +export default function MEdgeBack({ target, enabled }: { target: RefObject; enabled: boolean }) { + useEffect(() => { + if (!enabled) return; + let start: { x: number; y: number; t: number } | null = null; + let claimed = false; + let overlay = false; + let last = { x: 0, t: 0 }; + + const move = (x: number, transition: string) => { + const el = target.current; + if (!el) return; + el.style.transition = transition; + el.style.transform = x ? `translateX(${x}px)` : ''; + el.style.boxShadow = x ? '-16px 0 40px -12px rgba(0,0,0,.35)' : ''; + }; + + const onStart = (e: TouchEvent) => { + claimed = false; + start = null; + if (e.touches.length !== 1) return; + const t = e.touches[0]; + if (t.clientX > EDGE_PX) return; + overlay = hasOpenOverlay(); + if (!overlay && !canGoBack()) return; + start = { x: t.clientX, y: t.clientY, t: e.timeStamp }; + last = { x: t.clientX, t: e.timeStamp }; + }; + + const onMove = (e: TouchEvent) => { + if (!start || e.touches.length !== 1) return; + const t = e.touches[0]; + const dx = t.clientX - start.x; + const dy = t.clientY - start.y; + if (!claimed) { + if (Math.abs(dy) > CLAIM_PX && Math.abs(dy) > Math.abs(dx)) { + start = null; + return; + } + if (dx < CLAIM_PX || dx < Math.abs(dy) * AXIS_BIAS) return; + claimed = true; + } + if (e.cancelable) e.preventDefault(); + last = { x: t.clientX, t: e.timeStamp }; + // An open sheet closes on release; the page itself stays put under it. + if (!overlay) move(Math.max(0, dx), 'none'); + }; + + const onEnd = (e: TouchEvent) => { + const s = start; + start = null; + if (!s || !claimed) return; + const x = e.changedTouches[0]?.clientX ?? last.x; + const dx = Math.max(0, x - s.x); + const v = (x - last.x) / Math.max(1, e.timeStamp - last.t) || dx / Math.max(1, e.timeStamp - s.t); + const width = window.innerWidth; + const commit = dx > width * COMMIT_SHARE || v > FLICK_V; + if (!commit) { + move(0, 'transform 260ms var(--ease-drawer), box-shadow 260ms'); + return; + } + tickHaptic(); + if (overlay) { + closeTopOverlay(); + return; + } + move(width, 'transform 200ms cubic-bezier(0.2, 0.8, 0.2, 1)'); + window.setTimeout(() => { + window.history.back(); + // The page that comes back takes the place without a slide of its own. + requestAnimationFrame(() => move(0, 'none')); + }, 190); + }; + + document.addEventListener('touchstart', onStart, { passive: true }); + document.addEventListener('touchmove', onMove, { passive: false }); + document.addEventListener('touchend', onEnd, { passive: true }); + document.addEventListener('touchcancel', onEnd, { passive: true }); + return () => { + document.removeEventListener('touchstart', onStart); + document.removeEventListener('touchmove', onMove); + document.removeEventListener('touchend', onEnd); + document.removeEventListener('touchcancel', onEnd); + move(0, 'none'); + }; + }, [enabled, target]); + return null; +} diff --git a/client/src/mobile/components/MSheet.tsx b/client/src/mobile/components/MSheet.tsx index e1ebea5ce..cc76d23b4 100644 --- a/client/src/mobile/components/MSheet.tsx +++ b/client/src/mobile/components/MSheet.tsx @@ -5,6 +5,7 @@ import { useTranslation } from '../../i18n' import { useDiscardGuard } from '../../components/shared/useDiscardGuard' import { keepTabInside, useModalFocus } from './modalFocus' import { useSheetDrag } from './useSheetDrag' +import { useOverlay } from '../overlayStack' export type MSheetVariant = 'card' | 'bottom' | 'drawer' export type MSheetMaterial = 'glass' | 'bar-glass' | 'opaque' @@ -151,6 +152,10 @@ export default function MSheet({ return lockBodyScroll() }, [open]) + // A way back (the edge swipe, Android's back gesture) closes the sheet on top + // first, through the same path as the scrim, so unsaved changes still ask. + useOverlay(open && rendered, requestClose) + // Move focus into the dialog on open, hand it back on close. useModalFocus(panelRef, open && rendered) diff --git a/client/src/mobile/overlayStack.test.ts b/client/src/mobile/overlayStack.test.ts new file mode 100644 index 000000000..0824e16e9 --- /dev/null +++ b/client/src/mobile/overlayStack.test.ts @@ -0,0 +1,36 @@ +import { renderHook } from '@testing-library/react'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { _resetOverlayStack, closeTopOverlay, hasOpenOverlay, useOverlay } from './overlayStack'; + +beforeEach(() => _resetOverlayStack()); + +describe('overlayStack', () => { + it('closes the newest open overlay first, and reports when none is left', () => { + const first = vi.fn(); + const second = vi.fn(); + const a = renderHook(({ open }) => useOverlay(open, first), { initialProps: { open: true } }); + renderHook(({ open }) => useOverlay(open, second), { initialProps: { open: true } }); + expect(hasOpenOverlay()).toBe(true); + + expect(closeTopOverlay()).toBe(true); + expect(second).toHaveBeenCalledTimes(1); + expect(first).not.toHaveBeenCalled(); + + a.rerender({ open: false }); + a.unmount(); + }); + + it('forgets an overlay once it closes, and uses its latest close path', () => { + const old = vi.fn(); + const fresh = vi.fn(); + const h = renderHook(({ open, close }) => useOverlay(open, close), { initialProps: { open: true, close: old } }); + h.rerender({ open: true, close: fresh }); + closeTopOverlay(); + expect(fresh).toHaveBeenCalledTimes(1); + expect(old).not.toHaveBeenCalled(); + + h.rerender({ open: false, close: fresh }); + expect(hasOpenOverlay()).toBe(false); + expect(closeTopOverlay()).toBe(false); + }); +}); diff --git a/client/src/mobile/overlayStack.ts b/client/src/mobile/overlayStack.ts new file mode 100644 index 000000000..0703b2718 --- /dev/null +++ b/client/src/mobile/overlayStack.ts @@ -0,0 +1,43 @@ +import { useEffect, useRef } from 'react'; + +/** + * The overlays open on screen, newest last, so a way back closes the one on + * top before it leaves the page: the iOS edge swipe (MEdgeBack) and Android's + * back gesture (native/nativeApp.ts) both ask here first. Each entry is the + * overlay's own close path, so an unsaved-changes question still asks. + */ +type Close = () => void; +const stack: { id: number; close: () => void }[] = []; +let nextId = 1; + +/** Closes the overlay on top. False when none is open, so the caller goes back instead. */ +export function closeTopOverlay(): boolean { + const top = stack[stack.length - 1]; + if (!top) return false; + top.close(); + return true; +} + +export function hasOpenOverlay(): boolean { + return stack.length > 0; +} + +/** Registers an overlay while `open`, with the way it closes. */ +export function useOverlay(open: boolean, close: Close): void { + const closeRef = useRef(close); + closeRef.current = close; + useEffect(() => { + if (!open) return; + const entry = { id: nextId++, close: () => closeRef.current() }; + stack.push(entry); + return () => { + const i = stack.findIndex((e) => e.id === entry.id); + if (i >= 0) stack.splice(i, 1); + }; + }, [open]); +} + +/** Test helper. */ +export function _resetOverlayStack(): void { + stack.length = 0; +} diff --git a/client/src/native/nativeApp.test.ts b/client/src/native/nativeApp.test.ts index 1dbb85a58..3d1afb3b7 100644 --- a/client/src/native/nativeApp.test.ts +++ b/client/src/native/nativeApp.test.ts @@ -3,6 +3,7 @@ import { Keyboard } from '@capacitor/keyboard'; import { SplashScreen } from '@capacitor/splash-screen'; import { StatusBar, Style } from '@capacitor/status-bar'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { closeTopOverlay } from '../mobile/overlayStack'; import { isEffectivelyOffline } from '../sync/networkMode'; import { checkAppUpdate } from './capabilities'; import { startNativeApp } from './nativeApp'; @@ -17,6 +18,7 @@ vi.mock('./platform', () => ({ isNativeApp: vi.fn(), isNativeIos: vi.fn() })); vi.mock('./offlineShell', () => ({ keepOfflineShellFresh: vi.fn() })); vi.mock('../sync/networkMode', () => ({ isEffectivelyOffline: vi.fn() })); vi.mock('./capabilities', () => ({ checkAppUpdate: vi.fn(async () => false) })); +vi.mock('../mobile/overlayStack', () => ({ closeTopOverlay: vi.fn(() => false) })); function backButtonHandler(): (event: { canGoBack: boolean }) => void { const call = vi.mocked(App.addListener).mock.calls.find(([name]) => name === 'backButton'); @@ -46,6 +48,17 @@ describe('startNativeApp', () => { expect(StatusBar.setStyle).not.toHaveBeenCalled(); }); + it("Android's back gesture closes an open sheet before it leaves the page", () => { + const back = vi.spyOn(window.history, 'back').mockImplementation(() => {}); + vi.mocked(closeTopOverlay).mockReturnValueOnce(true); + startNativeApp(); + backButtonHandler()({ canGoBack: true }); + expect(back).not.toHaveBeenCalled(); + backButtonHandler()({ canGoBack: true }); + expect(back).toHaveBeenCalledTimes(1); + back.mockRestore(); + }); + it('asks the binary what it can do and the server which binary it needs', () => { startNativeApp(); expect(checkAppUpdate).toHaveBeenCalledWith(expect.any(Function)); diff --git a/client/src/native/nativeApp.ts b/client/src/native/nativeApp.ts index c4ead14a4..c77333dba 100644 --- a/client/src/native/nativeApp.ts +++ b/client/src/native/nativeApp.ts @@ -2,6 +2,7 @@ import { App } from '@capacitor/app'; import { Keyboard } from '@capacitor/keyboard'; import { SplashScreen } from '@capacitor/splash-screen'; import { StatusBar, Style } from '@capacitor/status-bar'; +import { closeTopOverlay } from '../mobile/overlayStack'; import { isEffectivelyOffline } from '../sync/networkMode'; import { checkAppUpdate } from './capabilities'; import { keepOfflineShellFresh } from './offlineShell'; @@ -27,6 +28,8 @@ export function startNativeApp(): void { // Android's back gesture: through the app's own history first, and only // then out of the app, the way a browser tab would behave. void App.addListener('backButton', ({ canGoBack }) => { + // An open sheet closes first, as on iOS's edge swipe. + if (closeTopOverlay()) return; if (canGoBack) window.history.back(); else void App.minimizeApp(); }); diff --git a/client/tests/unit/mobile/MSheet.test.tsx b/client/tests/unit/mobile/MSheet.test.tsx index 2ba3c0197..e7b1bf8c1 100644 --- a/client/tests/unit/mobile/MSheet.test.tsx +++ b/client/tests/unit/mobile/MSheet.test.tsx @@ -2,6 +2,7 @@ import React from 'react'; import { describe, it, expect, vi, afterEach } from 'vitest'; import { render, screen, fireEvent, act } from '@testing-library/react'; import MSheet from '../../../src/mobile/components/MSheet'; +import { closeTopOverlay } from '../../../src/mobile/overlayStack'; // FE-MOB-SHEET-001 onwards @@ -293,6 +294,23 @@ describe('MSheet', () => { expect(baseCalls).toEqual([]); }); + it('FE-MOB-SHEET-030: a way back (edge swipe, Android back) closes the open sheet first', () => { + const onClose = vi.fn(); + const { rerender } = render( + + Sheet content + , + ); + expect(closeTopOverlay()).toBe(true); + expect(onClose).toHaveBeenCalledTimes(1); + rerender( + + Sheet content + , + ); + expect(closeTopOverlay()).toBe(false); + }); + describe('dragging the docked sheet', () => { const touch = (y: number, x = 100) => ({ touches: [{ clientX: x, clientY: y }], changedTouches: [{ clientX: x, clientY: y }] }); From dec6babe1d19220dec07bdc5feefa31411b2ea02 Mon Sep 17 00:00:00 2001 From: Maurice Date: Fri, 6 Nov 2026 13:17:25 +0100 Subject: [PATCH 067/589] feat(native): an iOS map tile store, so viewed maps keep working offline WKWebView runs no service worker for a self-hosted server, so on iOS nothing kept a map tile once it scrolled away. Binaries with the tileCache feature answer a trek-tile:// scheme from a store on disk: a tile viewed once is served from there for up to 30 days (Mapbox's limit for a device cache, applied to every provider), then fetched anew; the store keeps under 250 MB, dropping the least recently used tiles first, sends a unique app User-Agent, and never prefetches. Mapbox's own resources (style, tiles, glyphs, sprites) and Leaflet's raster tiles go through it, telemetry never does. Offline, a Mapbox map in such an app now stays Mapbox where it was viewed, and the pill offers the stored trip region instead. The offline settings show what the store takes against its limit, with a way to empty it. --- .../App/App/TrekBridgeViewController.swift | 228 ++++++++++++++++++ client/ios/App/App/TrekShellPlugin.swift | 17 +- .../src/components/Journey/JourneyMapGL.tsx | 4 + client/src/components/Map/MapView.tsx | 3 +- .../Map/MapViewAuto.offline.test.tsx | 32 ++- client/src/components/Map/MapViewAuto.tsx | 53 +++- client/src/components/Map/MapViewGL.tsx | 4 + .../screens/settings/MSettingsOffline.tsx | 3 + .../screens/settings/MTileCacheUsage.test.tsx | 37 +++ .../screens/settings/MTileCacheUsage.tsx | 55 +++++ client/src/native/tileCache.test.ts | 58 +++++ client/src/native/tileCache.ts | 57 +++++ client/src/native/trekShell.ts | 4 + shared/src/i18n/ar/map.ts | 1 + shared/src/i18n/ar/settings.ts | 3 + shared/src/i18n/az/map.ts | 1 + shared/src/i18n/az/settings.ts | 3 + shared/src/i18n/br/map.ts | 1 + shared/src/i18n/br/settings.ts | 3 + shared/src/i18n/ca/map.ts | 1 + shared/src/i18n/ca/settings.ts | 3 + shared/src/i18n/cs/map.ts | 1 + shared/src/i18n/cs/settings.ts | 3 + shared/src/i18n/de/map.ts | 1 + shared/src/i18n/de/settings.ts | 3 + shared/src/i18n/en/map.ts | 1 + shared/src/i18n/en/settings.ts | 3 + shared/src/i18n/es/map.ts | 1 + shared/src/i18n/es/settings.ts | 3 + shared/src/i18n/et/map.ts | 1 + shared/src/i18n/et/settings.ts | 3 + shared/src/i18n/fr/map.ts | 1 + shared/src/i18n/fr/settings.ts | 3 + shared/src/i18n/gr/map.ts | 1 + shared/src/i18n/gr/settings.ts | 3 + shared/src/i18n/he/map.ts | 1 + shared/src/i18n/he/settings.ts | 3 + shared/src/i18n/hu/map.ts | 1 + shared/src/i18n/hu/settings.ts | 3 + shared/src/i18n/id/map.ts | 1 + shared/src/i18n/id/settings.ts | 3 + shared/src/i18n/it/map.ts | 1 + shared/src/i18n/it/settings.ts | 3 + shared/src/i18n/ja/map.ts | 1 + shared/src/i18n/ja/settings.ts | 3 + shared/src/i18n/ko/map.ts | 1 + shared/src/i18n/ko/settings.ts | 3 + shared/src/i18n/nl/map.ts | 1 + shared/src/i18n/nl/settings.ts | 3 + shared/src/i18n/pl/map.ts | 1 + shared/src/i18n/pl/settings.ts | 3 + shared/src/i18n/ru/map.ts | 1 + shared/src/i18n/ru/settings.ts | 3 + shared/src/i18n/sk/map.ts | 1 + shared/src/i18n/sk/settings.ts | 3 + shared/src/i18n/sv/map.ts | 1 + shared/src/i18n/sv/settings.ts | 3 + shared/src/i18n/th/map.ts | 1 + shared/src/i18n/th/settings.ts | 3 + shared/src/i18n/tr/map.ts | 1 + shared/src/i18n/tr/settings.ts | 3 + shared/src/i18n/uk/map.ts | 1 + shared/src/i18n/uk/settings.ts | 3 + shared/src/i18n/vi/map.ts | 1 + shared/src/i18n/vi/settings.ts | 3 + shared/src/i18n/zh-TW/map.ts | 1 + shared/src/i18n/zh-TW/settings.ts | 3 + shared/src/i18n/zh/map.ts | 1 + shared/src/i18n/zh/settings.ts | 3 + 69 files changed, 652 insertions(+), 15 deletions(-) create mode 100644 client/src/mobile/screens/settings/MTileCacheUsage.test.tsx create mode 100644 client/src/mobile/screens/settings/MTileCacheUsage.tsx create mode 100644 client/src/native/tileCache.test.ts create mode 100644 client/src/native/tileCache.ts diff --git a/client/ios/App/App/TrekBridgeViewController.swift b/client/ios/App/App/TrekBridgeViewController.swift index 65d6477b3..f5fe90324 100644 --- a/client/ios/App/App/TrekBridgeViewController.swift +++ b/client/ios/App/App/TrekBridgeViewController.swift @@ -1,5 +1,7 @@ import UIKit import Capacitor +import CryptoKit +import WebKit /// Points the WebView at the TREK server the user picked instead of the bundled /// address screen. The UI then comes from that server, in the version it runs, @@ -17,7 +19,18 @@ class TrekBridgeViewController: CAPBridgeViewController { return descriptor } + /// The map tile store answers trek-tile:// (TrekTileSchemeHandler below). A + /// scheme handler can only be set on the configuration the WebView is built from. + private let tileHandler = TrekTileSchemeHandler() + + override func webViewConfiguration(for instanceConfiguration: InstanceConfiguration) -> WKWebViewConfiguration { + let configuration = super.webViewConfiguration(for: instanceConfiguration) + configuration.setURLSchemeHandler(tileHandler, forURLScheme: TrekTileSchemeHandler.scheme) + return configuration + } + override func capacitorDidLoad() { + TrekTileStore.shared.prune() bridge?.registerPluginInstance(TrekShellPlugin()) // WebKit's own swipe back slides away a screenshot of the whole page, // closes no sheet and takes every drag near the edge from the UI. The UI @@ -44,3 +57,218 @@ enum TrekServerStore { return support.appendingPathComponent("offline-start-page.html") } } + +// MARK: - Tile store (trek-tile://) + +/// Map tiles the user looked at, on disk, for the WebView's maps +/// (client/src/native/tileCache.ts). WKWebView runs no service worker for a +/// self-hosted server, so without this nothing kept a tile once the app closed. +/// +/// Each tile lives as `.bin` with its content type in `.type`. +/// A tile older than 30 days is never served again (Mapbox's limit for a device +/// cache, applied to every provider) and is fetched anew. The store keeps under +/// 250 MB: past that, the tiles used least recently go first. It sits in Caches, +/// which iOS may empty under storage pressure and never backs up. +final class TrekTileStore { + static let shared = TrekTileStore() + static let maxAge: TimeInterval = 30 * 24 * 60 * 60 + static let maxBytes: Int64 = 250 * 1024 * 1024 + /// Pruning brings the store down to this share of the limit, so it does not + /// run again on the very next tile. + static let pruneTarget = 0.8 + + let directory: URL + let queue = DispatchQueue(label: "com.liketrek.trek.tiles", qos: .utility) + private var writesSincePrune = 0 + + private init() { + let caches = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0] + directory = caches.appendingPathComponent("trek-tiles", isDirectory: true) + try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + } + + /// The tile's identity without what changes per user or session: tokens and + /// keys come out, the rest of the query is sorted. + static func key(for url: URL) -> String { + var components = URLComponents(url: url, resolvingAgainstBaseURL: false) + let dropped: Set = ["access_token", "sku", "key", "api_key", "apikey"] + let kept = components?.queryItems? + .filter { !dropped.contains($0.name.lowercased()) } + .sorted { $0.name < $1.name } + components?.queryItems = (kept?.isEmpty ?? true) ? nil : kept + let identity = components?.string ?? url.absoluteString + return SHA256.hash(data: Data(identity.utf8)).map { String(format: "%02x", $0) }.joined() + } + + private func dataURL(_ key: String) -> URL { directory.appendingPathComponent(key + ".bin") } + private func typeURL(_ key: String) -> URL { directory.appendingPathComponent(key + ".type") } + + /// A stored tile younger than 30 days, marked as just used. Call on `queue`. + func read(_ key: String) -> (data: Data, type: String)? { + let file = dataURL(key) + guard let attributes = try? FileManager.default.attributesOfItem(atPath: file.path), + let created = attributes[.creationDate] as? Date else { return nil } + if Date().timeIntervalSince(created) > TrekTileStore.maxAge { + remove(key) + return nil + } + guard let data = try? Data(contentsOf: file) else { return nil } + let type = (try? String(contentsOf: typeURL(key), encoding: .utf8)) ?? "application/octet-stream" + try? FileManager.default.setAttributes([.modificationDate: Date()], ofItemAtPath: file.path) + return (data, type) + } + + func write(_ key: String, data: Data, type: String) { + queue.async { + try? data.write(to: self.dataURL(key), options: .atomic) + try? type.write(to: self.typeURL(key), atomically: true, encoding: .utf8) + self.writesSincePrune += 1 + if self.writesSincePrune >= 200 { self.pruneNow() } + } + } + + private func remove(_ key: String) { + try? FileManager.default.removeItem(at: dataURL(key)) + try? FileManager.default.removeItem(at: typeURL(key)) + } + + private struct Entry { + let key: String + let size: Int64 + let used: Date + let created: Date + } + + private func entries() -> [Entry] { + let keys: [URLResourceKey] = [.fileSizeKey, .contentModificationDateKey, .creationDateKey] + let files = (try? FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: keys)) ?? [] + return files.filter { $0.pathExtension == "bin" }.compactMap { file in + guard let values = try? file.resourceValues(forKeys: Set(keys)) else { return nil } + return Entry( + key: file.deletingPathExtension().lastPathComponent, + size: Int64(values.fileSize ?? 0), + used: values.contentModificationDate ?? .distantPast, + created: values.creationDate ?? .distantPast + ) + } + } + + /// Drops what is past 30 days, then the least recently used tiles while the + /// store is over its limit. + func prune() { queue.async { self.pruneNow() } } + + private func pruneNow() { + writesSincePrune = 0 + let now = Date() + var live: [Entry] = [] + for entry in entries() { + if now.timeIntervalSince(entry.created) > TrekTileStore.maxAge { remove(entry.key) } else { live.append(entry) } + } + var total = live.reduce(Int64(0)) { $0 + $1.size } + guard total > TrekTileStore.maxBytes else { return } + let target = Int64(Double(TrekTileStore.maxBytes) * TrekTileStore.pruneTarget) + for entry in live.sorted(by: { $0.used < $1.used }) { + if total <= target { break } + remove(entry.key) + total -= entry.size + } + } + + func usage(_ done: @escaping (Int64) -> Void) { + queue.async { done(self.entries().reduce(Int64(0)) { $0 + $1.size }) } + } + + func clear(_ done: @escaping () -> Void) { + queue.async { + try? FileManager.default.removeItem(at: self.directory) + try? FileManager.default.createDirectory(at: self.directory, withIntermediateDirectories: true) + done() + } + } +} + +/// Serves trek-tile://host/path from the store, or from https://host/path when +/// it has no fresh copy, storing what comes back. Offline and not stored, the +/// map gets an error and draws nothing there, as it would for a missing tile. +final class TrekTileSchemeHandler: NSObject, WKURLSchemeHandler { + static let scheme = "trek-tile" + + /// Tasks WebKit still wants an answer for. Touched on the main thread only: + /// start and stop arrive there, and every answer is posted back there. + private var active = Set() + + private let session: URLSession = { + let configuration = URLSessionConfiguration.default + configuration.requestCachePolicy = .reloadIgnoringLocalCacheData + configuration.timeoutIntervalForRequest = 20 + configuration.httpMaximumConnectionsPerHost = 4 + let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "0" + // A unique app User-Agent, as OpenFreeMap and OpenStreetMap ask of apps. + configuration.httpAdditionalHeaders = ["User-Agent": "TREK-App/\(version) (iOS; +https://liketrek.com)"] + return URLSession(configuration: configuration) + }() + + func webView(_ webView: WKWebView, start urlSchemeTask: WKURLSchemeTask) { + let id = ObjectIdentifier(urlSchemeTask) + guard let url = urlSchemeTask.request.url, + var components = URLComponents(url: url, resolvingAgainstBaseURL: false) else { + urlSchemeTask.didFailWithError(URLError(.badURL)) + return + } + components.scheme = "https" + guard let remote = components.url else { + urlSchemeTask.didFailWithError(URLError(.badURL)) + return + } + active.insert(id) + let key = TrekTileStore.key(for: remote) + let store = TrekTileStore.shared + let accept = urlSchemeTask.request.value(forHTTPHeaderField: "Accept") + store.queue.async { + if let hit = store.read(key) { + DispatchQueue.main.async { + self.respond(urlSchemeTask, id: id, url: url, status: 200, type: hit.type, data: hit.data) + } + return + } + var request = URLRequest(url: remote) + if let accept { request.setValue(accept, forHTTPHeaderField: "Accept") } + self.session.dataTask(with: request) { data, response, _ in + guard let data, let http = response as? HTTPURLResponse else { + DispatchQueue.main.async { + self.respond(urlSchemeTask, id: id, url: url, status: 504, type: "text/plain", data: Data()) + } + return + } + let type = http.value(forHTTPHeaderField: "Content-Type") ?? "application/octet-stream" + if http.statusCode == 200, !data.isEmpty { store.write(key, data: data, type: type) } + DispatchQueue.main.async { + self.respond(urlSchemeTask, id: id, url: url, status: http.statusCode, type: type, data: data) + } + }.resume() + } + } + + func webView(_ webView: WKWebView, stop urlSchemeTask: WKURLSchemeTask) { + active.remove(ObjectIdentifier(urlSchemeTask)) + } + + /// Answers once, and never after WebKit stopped the task: that would throw. + private func respond(_ task: WKURLSchemeTask, id: ObjectIdentifier, url: URL, status: Int, type: String, data: Data) { + guard active.remove(id) != nil else { return } + let headers = [ + "Content-Type": type, + "Content-Length": String(data.count), + // The page's origin is the user's server; WebGL reads tiles cross-origin. + "Access-Control-Allow-Origin": "*", + "Cache-Control": "no-store", + ] + guard let response = HTTPURLResponse(url: url, statusCode: status, httpVersion: "HTTP/1.1", headerFields: headers) else { + task.didFailWithError(URLError(.badServerResponse)) + return + } + task.didReceive(response) + task.didReceive(data) + task.didFinish() + } +} diff --git a/client/ios/App/App/TrekShellPlugin.swift b/client/ios/App/App/TrekShellPlugin.swift index 2cae368b1..20690db8b 100644 --- a/client/ios/App/App/TrekShellPlugin.swift +++ b/client/ios/App/App/TrekShellPlugin.swift @@ -17,6 +17,8 @@ public class TrekShellPlugin: CAPPlugin, CAPBridgedPlugin, ASWebAuthenticationPr CAPPluginMethod(name: "refreshOfflineCopy", returnType: CAPPluginReturnPromise), CAPPluginMethod(name: "openOfflineCopy", returnType: CAPPluginReturnPromise), CAPPluginMethod(name: "getCapabilities", returnType: CAPPluginReturnPromise), + CAPPluginMethod(name: "getTileCacheUsage", returnType: CAPPluginReturnPromise), + CAPPluginMethod(name: "clearTileCache", returnType: CAPPluginReturnPromise), ] /// What this binary offers the server's UI, raised with every native feature @@ -24,7 +26,20 @@ public class TrekShellPlugin: CAPPlugin, CAPBridgedPlugin, ASWebAuthenticationPr /// and a server can require a minimum (minNativeShellApi in /api/health/features). static let shellApi = 2 /// The native features by name, so the UI can turn each on by itself. - static let features: [String] = ["capabilities", "edgeBack"] + static let features: [String] = ["capabilities", "edgeBack", "tileCache"] + + // MARK: - Map tile store + + /// How much the stored map tiles take on disk, for the offline settings. + @objc func getTileCacheUsage(_ call: CAPPluginCall) { + TrekTileStore.shared.usage { bytes in + call.resolve(["bytes": bytes, "limit": TrekTileStore.maxBytes]) + } + } + + @objc func clearTileCache(_ call: CAPPluginCall) { + TrekTileStore.shared.clear { call.resolve() } + } @objc func getCapabilities(_ call: CAPPluginCall) { let info = Bundle.main.infoDictionary diff --git a/client/src/components/Journey/JourneyMapGL.tsx b/client/src/components/Journey/JourneyMapGL.tsx index ccb39fe98..7d03ef8b7 100644 --- a/client/src/components/Journey/JourneyMapGL.tsx +++ b/client/src/components/Journey/JourneyMapGL.tsx @@ -4,6 +4,7 @@ import { useSettingsStore } from '../../store/settingsStore' import { isStandardFamily, supportsCustom3d, wantsTerrain, addCustom3dBuildings, addTerrainAndSky } from '../Map/mapboxSetup' import { MAPBOX_DEFAULT_STYLE, styleForActiveProvider, basemapLanguage, type GlMapProvider } from '../Map/glProviders' import { buildGlMap, initialMapStyle } from '../Map/glSupport' +import { mapboxTileCacheRequest, tileCacheActive } from '../../native/tileCache' import type { JourneyTrack } from '@trek/shared' import { SHOT_INDEX_ATTR, ensureJourneyPopupStyle, formatMarkerDate, journeyPopupHtml } from './journeyMapPopup' import { clusterPhotos, photoMarkerHtml, type MapPhoto } from './journeyPhotoLayer' @@ -395,6 +396,9 @@ function JourneyMapGL( antialias: mapboxQuality, } if (!isMapLibre) mapOptions.projection = mapboxQuality ? 'globe' : 'mercator' + // In the iOS app, Mapbox's own resources go through the app's tile store, so + // what was viewed stays on the device for up to 30 days (native/tileCache.ts). + if (!isMapLibre && tileCacheActive()) mapOptions.transformRequest = mapboxTileCacheRequest // MapLibre's around-center mouse rotate ping-pongs near mid-screen (#1545) // — see MapViewGL. Keep the plain dx-based rotate everywhere. if (isMapLibre) mapOptions.aroundCenter = false diff --git a/client/src/components/Map/MapView.tsx b/client/src/components/Map/MapView.tsx index 194fbd70c..4d7311268 100644 --- a/client/src/components/Map/MapView.tsx +++ b/client/src/components/Map/MapView.tsx @@ -68,6 +68,7 @@ import { tileHealthHandlers, tourRasterBaseOf } from './tourRasterBases' import { crsForBasemap } from './gcj02Crs' import { isGcj02Basemap, resolveBasemap } from '../../utils/tileUrl' import VectorBasemap from './VectorBasemap' +import { nativeRasterTemplate } from '../../native/tileCache' import { useSettingsStore } from '../../store/settingsStore' import { TourMapLayersLeaflet } from './RasterOverlayLeaflet' import { MapLayerSwitcher, TourMapLayerSwitcher, MAP_LAYER_SWITCHER_INSET, type TourBaseLayer } from './MapLayerSwitcher' @@ -938,7 +939,7 @@ export const MapView = memo(function MapView({ ) : ( ({ offline: false, dark: false })); +const env = vi.hoisted(() => ({ offline: false, dark: false, tileStore: false })); const seen = vi.hoisted(() => ({ leaflet: null as null | { tileUrl?: string }, gl: null as null | { engine: string; glProvider?: string; styleOverride?: string }, @@ -40,6 +40,7 @@ vi.mock('../../hooks/useNetworkMode', () => ({ useNetworkMode: () => ({ offline: env.offline, forced: false, setForced: () => {} }), })); vi.mock('../../hooks/useIsDark', () => ({ useIsDark: () => env.dark })); +vi.mock('../../native/tileCache', () => ({ tileCacheActive: () => env.tileStore })); vi.mock('../../native/platform', async (importOriginal) => ({ ...(await importOriginal()), isNativeIos: () => false, @@ -52,6 +53,7 @@ beforeEach(() => { resetWebGLProbe(); env.offline = false; env.dark = false; + env.tileStore = false; seen.leaflet = null; seen.gl = null; const ctx = { getExtension: () => ({ loseContext: () => {} }) }; @@ -120,4 +122,30 @@ describe('MapViewAuto offline', () => { expect(seen.leaflet?.tileUrl).toBe('https://tiles.example.com/{z}/{x}/{y}.png'); expect(pill()).not.toBeInTheDocument(); }); + + it('FE-COMP-MAPAUTO-OFFLINE-006: in the iOS app with its tile store, Mapbox stays offline and the pill switches to the stored map', async () => { + seedStore(useSettingsStore, { settings: { map_provider: 'mapbox-gl', mapbox_access_token: 'pk.test' } }); + env.offline = true; + env.tileStore = true; + + render(); + + await screen.findByTestId('gl-map'); + expect(seen.gl).toMatchObject({ engine: 'mapbox', styleOverride: undefined }); + const toggle = screen.getByRole('button', { pressed: false }); + fireEvent.click(toggle); + await screen.findByTestId('gl-map'); + expect(seen.gl).toMatchObject({ engine: 'maplibre', styleOverride: OFM_POSITRON }); + expect(screen.getByRole('button', { pressed: true })).toBeInTheDocument(); + }); + + it('FE-COMP-MAPAUTO-OFFLINE-007: with the tile store, a raster template stays offline in the app too', () => { + seedStore(useSettingsStore, { settings: { map_provider: 'leaflet' } }); + env.offline = true; + env.tileStore = true; + + render(); + + expect(seen.leaflet?.tileUrl).toBe('https://tiles.example.com/{z}/{x}/{y}.png'); + }); }); diff --git a/client/src/components/Map/MapViewAuto.tsx b/client/src/components/Map/MapViewAuto.tsx index 878334835..37308e04c 100644 --- a/client/src/components/Map/MapViewAuto.tsx +++ b/client/src/components/Map/MapViewAuto.tsx @@ -1,4 +1,4 @@ -import { Suspense } from 'react' +import { Suspense, useState } from 'react' import { AlertTriangle, Clock, CloudOff, Info } from 'lucide-react' import { Tooltip } from '../shared/Tooltip' import { useSettingsStore } from '../../store/settingsStore' @@ -13,6 +13,7 @@ import { useNetworkMode } from '../../hooks/useNetworkMode' import { useIsDark } from '../../hooks/useIsDark' import { OFM_POSITRON } from '../../constants/mapDefaults' import { glWorksOffline, leafletWorksOffline, offlineStyleFor } from './offlineBasemap' +import { tileCacheActive } from '../../native/tileCache' // Auto-selects the map renderer based on user settings. Keeps the existing // Leaflet MapView untouched so the Mapbox GL variant can mature iteratively @@ -43,12 +44,26 @@ export function MapViewAuto(props: MapViewAutoProps) { const { offline } = useNetworkMode() const dark = useIsDark() const offlineStyle = offlineStyleFor(dark) - // Offline on a basemap that has nothing stored: draw the stored one with MapLibre. - const glFallback = !!configuredGl && offline && !glWorksOffline(configuredGl, maplibreStyle) + // In the iOS app with its tile store, a Mapbox map keeps what was viewed for 30 + // days, so offline it stays Mapbox, and the pill offers the stored trip region + // instead for the places never looked at. Everywhere else a basemap with + // nothing stored is swapped for the stored one straight away. + const nativeStore = tileCacheActive() + const [preferStored, setPreferStored] = useState(false) + const mapboxKept = configuredGl === 'mapbox-gl' && nativeStore + const glFallback = !!configuredGl && offline && !glWorksOffline(configuredGl, maplibreStyle) && (!mapboxKept || preferStored) const glProvider = glFallback ? 'maplibre-gl' : configuredGl - const leafletFallback = !configuredGl && offline && !leafletWorksOffline(mapProps.tileUrl ?? OFM_POSITRON) + const leafletFallback = !configuredGl && offline && !leafletWorksOffline(mapProps.tileUrl ?? OFM_POSITRON, nativeIosWithoutStore(nativeStore)) if (leafletFallback) mapProps.tileUrl = offlineStyle - const pill = (glFallback || leafletFallback) && + const pill = offline && mapboxKept + ? ( + setPreferStored(v => !v)} + /> + ) + : (glFallback || leafletFallback) && // One chunk per engine: picking the binding here is what keeps mapbox-gl and // maplibre-gl out of each other's downloads. const MapViewGL = glProvider === 'maplibre-gl' ? MapViewGLMaplibre : MapViewGLMapbox @@ -79,13 +94,29 @@ export function MapViewAuto(props: MapViewAutoProps) { ) } -/** Says the map on screen is the stored offline basemap, not the user's own. */ -function OfflineBasemapPill({ label }: { label: string }) { +/** A raster template cannot be served offline in the iOS app unless it has its tile store. */ +function nativeIosWithoutStore(nativeStore: boolean): boolean | undefined { + return nativeStore ? false : undefined +} + +const PILL = 'absolute left-1/2 z-[5] flex -translate-x-1/2 items-center gap-1.5 rounded-full border border-edge bg-surface-card px-3 py-1 text-caption font-semibold text-content-secondary shadow-sm backdrop-blur-md bottom-[calc(var(--bottom-nav-h,0px)+12px)]' + +/** + * Says the map on screen is the stored offline basemap, not the user's own. With + * onToggle it is a switch between the user's map (as far as it was viewed and + * stored) and the stored trip region. + */ +function OfflineBasemapPill({ label, pressed, onToggle }: { label: string; pressed?: boolean; onToggle?: () => void }) { + if (onToggle) { + return ( + + ) + } return ( -
+
diff --git a/client/src/components/Map/MapViewGL.tsx b/client/src/components/Map/MapViewGL.tsx index 95402c9ed..34a0b329c 100644 --- a/client/src/components/Map/MapViewGL.tsx +++ b/client/src/components/Map/MapViewGL.tsx @@ -27,6 +27,7 @@ import { visibleRouteReservations } from '../../utils/reservationRoutes' import { safeHexColor } from '../../utils/safeColor' import { MAPBOX_DEFAULT_STYLE, styleForActiveProvider, basemapLanguage, type GlMapProvider } from './glProviders' import { buildGlMap, initialMapStyle } from './glSupport' +import { mapboxTileCacheRequest, tileCacheActive } from '../../native/tileCache' import LocationButton from './LocationButton' import { useIsPhone } from '../../mobile/useIsPhone' import { useGeolocation } from '../../hooks/useGeolocation' @@ -1018,6 +1019,9 @@ export function MapViewGL({ antialias: mapboxQuality, } if (!isMapLibre) mapOptions.projection = mapboxQuality ? 'globe' : 'mercator' + // In the iOS app, Mapbox's own resources go through the app's tile store, so + // what was viewed stays on the device for up to 30 days (native/tileCache.ts). + if (!isMapLibre && tileCacheActive()) mapOptions.transformRequest = mapboxTileCacheRequest // MapLibre's around-center rotate ping-pongs near mid-screen (#1545); false is mapbox-gl's dx rotate. if (isMapLibre) mapOptions.aroundCenter = false diff --git a/client/src/mobile/screens/settings/MSettingsOffline.tsx b/client/src/mobile/screens/settings/MSettingsOffline.tsx index 4daad0175..c615b1cde 100644 --- a/client/src/mobile/screens/settings/MSettingsOffline.tsx +++ b/client/src/mobile/screens/settings/MSettingsOffline.tsx @@ -16,6 +16,7 @@ import type { QueuedMutation } from '../../../db/offlineDb' import { MSetCard, MSetEyebrow, MSetRow, MSetSegments, MSetButton } from './MSettingsUi' import MToggle from '../../components/MToggle' import MConfirmSheet from './MConfirmSheet' +import MTileCacheUsage from './MTileCacheUsage' function conflictName(m: QueuedMutation): string { const body = (m.body ?? {}) as { name?: unknown } @@ -159,6 +160,8 @@ export default function MSettingsOffline() { sub={t('settings.offline.storage.tilesHint')} trailing={} /> + {/* The iOS app's own store of the map tiles looked at, beside the trip regions above. */} +
{allTrips.length > 0 && (
diff --git a/client/src/mobile/screens/settings/MTileCacheUsage.test.tsx b/client/src/mobile/screens/settings/MTileCacheUsage.test.tsx new file mode 100644 index 000000000..768d90746 --- /dev/null +++ b/client/src/mobile/screens/settings/MTileCacheUsage.test.tsx @@ -0,0 +1,37 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { fireEvent, render, screen, waitFor } from '../../../../tests/helpers/render'; +import { tileCacheActive } from '../../../native/tileCache'; +import { TrekShell } from '../../../native/trekShell'; +import MTileCacheUsage from './MTileCacheUsage'; + +vi.mock('../../../native/tileCache', () => ({ tileCacheActive: vi.fn() })); +vi.mock('../../../native/trekShell', () => ({ + TrekShell: { getTileCacheUsage: vi.fn(), clearTileCache: vi.fn() }, +})); + +beforeEach(() => { + vi.mocked(tileCacheActive).mockReturnValue(true); + vi.mocked(TrekShell.getTileCacheUsage) + .mockReset() + .mockResolvedValue({ bytes: 84 * 1024 * 1024, limit: 250 * 1024 * 1024 }); + vi.mocked(TrekShell.clearTileCache).mockReset().mockResolvedValue(); +}); + +describe('MTileCacheUsage', () => { + it('shows what the map tile store takes against its limit, and empties it', async () => { + render(); + expect(await screen.findByText(/84/)).toHaveTextContent(/250/); + + vi.mocked(TrekShell.getTileCacheUsage).mockResolvedValue({ bytes: 0, limit: 250 * 1024 * 1024 }); + fireEvent.click(screen.getByRole('button')); + await waitFor(() => expect(TrekShell.clearTileCache).toHaveBeenCalledTimes(1)); + await waitFor(() => expect(screen.getByRole('button')).toBeDisabled()); + }); + + it('renders nothing outside a binary with the store', () => { + vi.mocked(tileCacheActive).mockReturnValue(false); + const { container } = render(); + expect(container).toBeEmptyDOMElement(); + expect(TrekShell.getTileCacheUsage).not.toHaveBeenCalled(); + }); +}); diff --git a/client/src/mobile/screens/settings/MTileCacheUsage.tsx b/client/src/mobile/screens/settings/MTileCacheUsage.tsx new file mode 100644 index 000000000..4c381f581 --- /dev/null +++ b/client/src/mobile/screens/settings/MTileCacheUsage.tsx @@ -0,0 +1,55 @@ +import { Trash2 } from 'lucide-react'; +import { useCallback, useEffect, useState } from 'react'; +import { useTranslation } from '../../../i18n'; +import { reportNativeFailure } from '../../../native/reportFailure'; +import { tileCacheActive } from '../../../native/tileCache'; +import { TrekShell } from '../../../native/trekShell'; +import { formatBytes } from '../../../utils/formatBytes'; +import { MSetButton, MSetRow } from './MSettingsUi'; + +/** + * How much room the iOS app's map tile store takes (native/tileCache.ts), with + * a way to empty it. The store keeps itself under its limit and drops tiles + * older than 30 days on its own; this is for seeing it and taking the room back + * by hand. Renders nothing outside a binary that has the store. + */ +export default function MTileCacheUsage() { + const { t } = useTranslation(); + const active = tileCacheActive(); + const [usage, setUsage] = useState<{ bytes: number; limit: number } | null>(null); + const [clearing, setClearing] = useState(false); + + const refresh = useCallback(() => { + TrekShell.getTileCacheUsage().then(setUsage, reportNativeFailure); + }, []); + + useEffect(() => { + if (active) refresh(); + }, [active, refresh]); + + if (!active || !usage) return null; + + const clear = async () => { + setClearing(true); + try { + await TrekShell.clearTileCache(); + } catch (err) { + reportNativeFailure(err); + } + setClearing(false); + refresh(); + }; + + return ( + void clear()}> + + {t('settings.offline.tileStore.clear')} + + } + /> + ); +} diff --git a/client/src/native/tileCache.test.ts b/client/src/native/tileCache.test.ts new file mode 100644 index 000000000..ba310056f --- /dev/null +++ b/client/src/native/tileCache.test.ts @@ -0,0 +1,58 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { hasNativeFeature } from './capabilities'; +import { isNativeIos } from './platform'; +import { mapboxTileCacheRequest, nativeRasterTemplate, tileCacheActive, toTileCacheUrl } from './tileCache'; + +vi.mock('./platform', () => ({ isNativeIos: vi.fn() })); +vi.mock('./capabilities', () => ({ hasNativeFeature: vi.fn() })); + +beforeEach(() => { + vi.mocked(isNativeIos).mockReturnValue(true); + vi.mocked(hasNativeFeature).mockReturnValue(true); +}); + +describe('tileCache', () => { + it('is on only in an iOS binary that has the store', () => { + expect(tileCacheActive()).toBe(true); + vi.mocked(hasNativeFeature).mockReturnValue(false); + expect(tileCacheActive()).toBe(false); + vi.mocked(hasNativeFeature).mockReturnValue(true); + vi.mocked(isNativeIos).mockReturnValue(false); + expect(tileCacheActive()).toBe(false); + }); + + it('swaps only the scheme, so the store knows where the tile lives', () => { + expect(toTileCacheUrl('https://a.tile.example.com/1/2/3.png?k=v')).toBe( + 'trek-tile://a.tile.example.com/1/2/3.png?k=v' + ); + expect(toTileCacheUrl('http://insecure.example.com/x')).toBe('http://insecure.example.com/x'); + }); + + it('routes Leaflet raster templates through the store only where there is one', () => { + expect(nativeRasterTemplate('https://{s}.tiles.example.com/{z}/{x}/{y}.png')).toBe( + 'trek-tile://{s}.tiles.example.com/{z}/{x}/{y}.png' + ); + vi.mocked(hasNativeFeature).mockReturnValue(false); + expect(nativeRasterTemplate('https://{s}.tiles.example.com/{z}/{x}/{y}.png')).toBe( + 'https://{s}.tiles.example.com/{z}/{x}/{y}.png' + ); + }); + + it('sends what a Mapbox map draws through the store, never its telemetry', () => { + expect( + mapboxTileCacheRequest('https://api.mapbox.com/styles/v1/mapbox/streets-v12?access_token=pk', 'Style').url + ).toBe('trek-tile://api.mapbox.com/styles/v1/mapbox/streets-v12?access_token=pk'); + expect(mapboxTileCacheRequest('https://a.tiles.mapbox.com/v4/x/1/2/3.vector.pbf', 'Tile').url).toMatch( + /^trek-tile:/ + ); + expect(mapboxTileCacheRequest('https://events.mapbox.com/events/v2', 'Unknown').url).toBe( + 'https://events.mapbox.com/events/v2' + ); + expect(mapboxTileCacheRequest('https://api.mapbox.com/map-sessions/v1', 'Unknown').url).toBe( + 'https://api.mapbox.com/map-sessions/v1' + ); + expect(mapboxTileCacheRequest('https://tiles.openfreemap.org/planet/1/2/3.pbf', 'Tile').url).toBe( + 'https://tiles.openfreemap.org/planet/1/2/3.pbf' + ); + }); +}); diff --git a/client/src/native/tileCache.ts b/client/src/native/tileCache.ts new file mode 100644 index 000000000..d698376dc --- /dev/null +++ b/client/src/native/tileCache.ts @@ -0,0 +1,57 @@ +import { hasNativeFeature } from './capabilities'; +import { isNativeIos } from './platform'; + +/** + * The iOS app's own tile store (TrekTileSchemeHandler.swift), reached through + * the trek-tile:// scheme. + * + * WKWebView runs no service worker for a self-hosted server, so on iOS nothing + * kept the map tiles a user had looked at. Binaries that report the tileCache + * feature serve every trek-tile:// request from a store on disk, filled as the + * tiles are viewed and kept for at most 30 days (Mapbox's limit for a device + * cache, applied to every provider alike), and from the network otherwise. The + * URL keeps its host and path, only the scheme changes, so the handler knows + * where the tile really lives. + * + * Nothing is prefetched through here: Mapbox forbids bulk downloads, and the + * OpenFreeMap region a trip stores goes through Cache Storage (offlineTiles.ts). + */ +export const TILE_CACHE_SCHEME = 'trek-tile'; + +export function tileCacheActive(): boolean { + return isNativeIos() && hasNativeFeature('tileCache'); +} + +/** https://host/path?query -> trek-tile://host/path?query. Anything else stays. */ +export function toTileCacheUrl(url: string): string { + return url.startsWith('https://') ? `${TILE_CACHE_SCHEME}://${url.slice('https://'.length)}` : url; +} + +/** A raster tile template for Leaflet, through the store where the app has one. */ +export function nativeRasterTemplate(template: string): string { + return tileCacheActive() ? toTileCacheUrl(template) : template; +} + +const MAPBOX_HOST = /^https:\/\/(?:api\.mapbox\.com|[a-z0-9-]+\.tiles\.mapbox\.com)\//i; +/** What a map draws; telemetry and anything else keeps going straight out. */ +const CACHED_RESOURCES = new Set([ + 'Style', + 'Source', + 'Tile', + 'Glyphs', + 'SpriteImage', + 'SpriteJSON', + 'Image', + 'Iconset', + 'Model', +]); + +/** + * Mapbox GL's transformRequest for the iOS app: the map's own resources from + * Mapbox's servers go through the store, events and sessions never do. + */ +export function mapboxTileCacheRequest(url: string, resourceType?: string): { url: string } { + if (!MAPBOX_HOST.test(url)) return { url }; + if (resourceType && !CACHED_RESOURCES.has(resourceType)) return { url }; + return { url: toTileCacheUrl(url) }; +} diff --git a/client/src/native/trekShell.ts b/client/src/native/trekShell.ts index 90d645f0e..834ea9e85 100644 --- a/client/src/native/trekShell.ts +++ b/client/src/native/trekShell.ts @@ -32,6 +32,10 @@ export interface TrekShellPlugin { openOfflineCopy(): Promise<{ opened: boolean }>; /** What this binary offers the UI (native/capabilities.ts). Missing before shell API 2. */ getCapabilities(): Promise; + /** iOS, feature tileCache: what the map tile store takes on disk, and its limit. */ + getTileCacheUsage(): Promise<{ bytes: number; limit: number }>; + /** iOS, feature tileCache: empties the map tile store. */ + clearTileCache(): Promise; } export const TrekShell = registerPlugin('TrekShell'); diff --git a/shared/src/i18n/ar/map.ts b/shared/src/i18n/ar/map.ts index 572c62cf9..06218393b 100644 --- a/shared/src/i18n/ar/map.ts +++ b/shared/src/i18n/ar/map.ts @@ -53,5 +53,6 @@ const map: TranslationStrings = { 'لا يوفّر هذا المتصفح WebGL2 الذي تحتاجه خرائط GL، لذا تُعرض الخرائط باستخدام Leaflet بدلًا منها.', 'map.webgl2.terrain': 'يحتاج العرض ثلاثي الأبعاد إلى WebGL2، وهذا المتصفح لا يوفّره. تبقى الخريطة ثنائية الأبعاد.', 'map.offlineBasemap': 'خريطة دون اتصال', + 'map.offlineShowStored': 'عرض الخريطة دون اتصال', }; export default map; diff --git a/shared/src/i18n/ar/settings.ts b/shared/src/i18n/ar/settings.ts index b37685a2e..ab4e2ed52 100644 --- a/shared/src/i18n/ar/settings.ts +++ b/shared/src/i18n/ar/settings.ts @@ -686,6 +686,9 @@ const settings: TranslationStrings = { 'settings.apiKeys.modal.done': 'تم', 'settings.mcp.deprecated': 'مهجور', 'settings.offline.cache.dateRange': 'من {start} إلى {end}', + 'settings.offline.tileStore.title': 'مربعات الخريطة المعروضة', + 'settings.offline.tileStore.usage': '{used} من {limit} على هذا الجهاز، تُحفظ حتى 30 يومًا', + 'settings.offline.tileStore.clear': 'مسح', }; export default settings; diff --git a/shared/src/i18n/az/map.ts b/shared/src/i18n/az/map.ts index 6f00aa0ca..79b04eba4 100644 --- a/shared/src/i18n/az/map.ts +++ b/shared/src/i18n/az/map.ts @@ -51,6 +51,7 @@ const map: TranslationStrings = { 'Bu brauzer GL xəritələrinin ehtiyac duyduğu WebGL2-ni təqdim etmir, ona görə xəritələr Leaflet ilə göstərilir.', 'map.webgl2.terrain': '3D üçün WebGL2 lazımdır, bu brauzer isə onu təqdim etmir. Xəritə 2D olaraq qalır.', 'map.offlineBasemap': 'Oflayn xəritə', + 'map.offlineShowStored': 'Oflayn xəritəni göstər', }; export default map; diff --git a/shared/src/i18n/az/settings.ts b/shared/src/i18n/az/settings.ts index abbfdf920..ceda56b20 100644 --- a/shared/src/i18n/az/settings.ts +++ b/shared/src/i18n/az/settings.ts @@ -728,6 +728,9 @@ const settings: TranslationStrings = { 'settings.apiKeys.modal.done': 'Hazır', 'settings.mcp.deprecated': 'Köhnəlmiş', 'settings.offline.cache.dateRange': '{start} tarixindən {end} tarixinədək', + 'settings.offline.tileStore.title': 'Baxılmış xəritə kafelləri', + 'settings.offline.tileStore.usage': 'Bu cihazda {limit}-dən {used}, 30 günə qədər saxlanılır', + 'settings.offline.tileStore.clear': 'Təmizlə', }; export default settings; diff --git a/shared/src/i18n/br/map.ts b/shared/src/i18n/br/map.ts index bf433284d..bacb8299b 100644 --- a/shared/src/i18n/br/map.ts +++ b/shared/src/i18n/br/map.ts @@ -48,5 +48,6 @@ const map: TranslationStrings = { 'Este navegador não oferece WebGL2, necessário para os mapas GL, por isso os mapas são exibidos com o Leaflet.', 'map.webgl2.terrain': 'O 3D precisa de WebGL2, que este navegador não oferece. O mapa continua em 2D.', 'map.offlineBasemap': 'Mapa offline', + 'map.offlineShowStored': 'Mostrar mapa offline', }; export default map; diff --git a/shared/src/i18n/br/settings.ts b/shared/src/i18n/br/settings.ts index 284764810..0fd635625 100644 --- a/shared/src/i18n/br/settings.ts +++ b/shared/src/i18n/br/settings.ts @@ -675,6 +675,9 @@ const settings: TranslationStrings = { 'settings.apiKeys.modal.done': 'Concluído', 'settings.mcp.deprecated': 'Obsoleto', 'settings.offline.cache.dateRange': '{start} a {end}', + 'settings.offline.tileStore.title': 'Blocos de mapa vistos', + 'settings.offline.tileStore.usage': '{used} de {limit} neste aparelho, guardados por até 30 dias', + 'settings.offline.tileStore.clear': 'Limpar', }; export default settings; diff --git a/shared/src/i18n/ca/map.ts b/shared/src/i18n/ca/map.ts index 502acda19..e464df183 100644 --- a/shared/src/i18n/ca/map.ts +++ b/shared/src/i18n/ca/map.ts @@ -46,5 +46,6 @@ const map: TranslationStrings = { 'Aquest navegador no ofereix WebGL2, que necessiten els mapes GL, així que els mapes es mostren amb Leaflet.', 'map.webgl2.terrain': 'El 3D necessita WebGL2, que aquest navegador no ofereix. El mapa es queda en 2D.', 'map.offlineBasemap': 'Mapa fora de línia', + 'map.offlineShowStored': 'Mostra el mapa fora de línia', }; export default map; diff --git a/shared/src/i18n/ca/settings.ts b/shared/src/i18n/ca/settings.ts index 45241b6fa..e13ffa9a8 100644 --- a/shared/src/i18n/ca/settings.ts +++ b/shared/src/i18n/ca/settings.ts @@ -677,6 +677,9 @@ const settings: TranslationStrings = { 'settings.apiKeys.modal.done': 'Fet', 'settings.mcp.deprecated': 'Obsolet', 'settings.offline.cache.dateRange': 'del {start} al {end}', + 'settings.offline.tileStore.title': 'Tessel·les de mapa vistes', + 'settings.offline.tileStore.usage': '{used} de {limit} en aquest dispositiu, es guarden fins a 30 dies', + 'settings.offline.tileStore.clear': 'Buida', }; export default settings; diff --git a/shared/src/i18n/cs/map.ts b/shared/src/i18n/cs/map.ts index 407292af7..43c300a5d 100644 --- a/shared/src/i18n/cs/map.ts +++ b/shared/src/i18n/cs/map.ts @@ -47,5 +47,6 @@ const map: TranslationStrings = { 'Tento prohlížeč nenabízí WebGL2, které mapy GL potřebují, proto se mapy zobrazují pomocí Leafletu.', 'map.webgl2.terrain': '3D potřebuje WebGL2, které tento prohlížeč nenabízí. Mapa zůstává ve 2D.', 'map.offlineBasemap': 'Offline mapa', + 'map.offlineShowStored': 'Zobrazit offline mapu', }; export default map; diff --git a/shared/src/i18n/cs/settings.ts b/shared/src/i18n/cs/settings.ts index 5a291b6e4..09c9f69d5 100644 --- a/shared/src/i18n/cs/settings.ts +++ b/shared/src/i18n/cs/settings.ts @@ -671,6 +671,9 @@ const settings: TranslationStrings = { 'settings.apiKeys.modal.done': 'Hotovo', 'settings.mcp.deprecated': 'Zastaralé', 'settings.offline.cache.dateRange': '{start} až {end}', + 'settings.offline.tileStore.title': 'Zobrazené dlaždice mapy', + 'settings.offline.tileStore.usage': '{used} z {limit} v tomto zařízení, uchovává se až 30 dní', + 'settings.offline.tileStore.clear': 'Vymazat', }; export default settings; diff --git a/shared/src/i18n/de/map.ts b/shared/src/i18n/de/map.ts index 951536543..1e1a31a69 100644 --- a/shared/src/i18n/de/map.ts +++ b/shared/src/i18n/de/map.ts @@ -48,5 +48,6 @@ const map: TranslationStrings = { 'Dieser Browser bietet kein WebGL2, das GL-Karten brauchen. Karten werden deshalb mit Leaflet angezeigt.', 'map.webgl2.terrain': '3D braucht WebGL2, das dieser Browser nicht bietet. Die Karte bleibt in 2D.', 'map.offlineBasemap': 'Offline-Karte', + 'map.offlineShowStored': 'Offline-Karte zeigen', }; export default map; diff --git a/shared/src/i18n/de/settings.ts b/shared/src/i18n/de/settings.ts index fd86690c7..ba6e69654 100644 --- a/shared/src/i18n/de/settings.ts +++ b/shared/src/i18n/de/settings.ts @@ -682,6 +682,9 @@ const settings: TranslationStrings = { 'settings.apiKeys.modal.done': 'Fertig', 'settings.mcp.deprecated': 'Veraltet', 'settings.offline.cache.dateRange': '{start} bis {end}', + 'settings.offline.tileStore.title': 'Angesehene Kartenkacheln', + 'settings.offline.tileStore.usage': '{used} von {limit} auf diesem Gerät, höchstens 30 Tage gespeichert', + 'settings.offline.tileStore.clear': 'Leeren', }; export default settings; diff --git a/shared/src/i18n/en/map.ts b/shared/src/i18n/en/map.ts index 531d0252b..fafd383e7 100644 --- a/shared/src/i18n/en/map.ts +++ b/shared/src/i18n/en/map.ts @@ -46,5 +46,6 @@ const map: TranslationStrings = { 'This browser does not offer WebGL2, which GL maps need, so maps are shown with Leaflet instead.', 'map.webgl2.terrain': '3D needs WebGL2, which this browser does not offer. The map stays in 2D.', 'map.offlineBasemap': 'Offline map', + 'map.offlineShowStored': 'Show offline map', }; export default map; diff --git a/shared/src/i18n/en/settings.ts b/shared/src/i18n/en/settings.ts index f7c5cd17e..a28fa726d 100644 --- a/shared/src/i18n/en/settings.ts +++ b/shared/src/i18n/en/settings.ts @@ -662,6 +662,9 @@ const settings: TranslationStrings = { 'settings.apiKeys.modal.done': 'Done', 'settings.mcp.deprecated': 'Deprecated', 'settings.offline.cache.dateRange': '{start} to {end}', + 'settings.offline.tileStore.title': 'Viewed map tiles', + 'settings.offline.tileStore.usage': '{used} of {limit} on this device, kept for up to 30 days', + 'settings.offline.tileStore.clear': 'Clear', }; export default settings; diff --git a/shared/src/i18n/es/map.ts b/shared/src/i18n/es/map.ts index 974495e1c..126c8aac5 100644 --- a/shared/src/i18n/es/map.ts +++ b/shared/src/i18n/es/map.ts @@ -45,5 +45,6 @@ const map: TranslationStrings = { 'Este navegador no ofrece WebGL2, que necesitan los mapas GL, así que los mapas se muestran con Leaflet.', 'map.webgl2.terrain': 'El 3D necesita WebGL2, que este navegador no ofrece. El mapa se queda en 2D.', 'map.offlineBasemap': 'Mapa sin conexión', + 'map.offlineShowStored': 'Mostrar mapa sin conexión', }; export default map; diff --git a/shared/src/i18n/es/settings.ts b/shared/src/i18n/es/settings.ts index 9b3034354..548afc3d8 100644 --- a/shared/src/i18n/es/settings.ts +++ b/shared/src/i18n/es/settings.ts @@ -678,6 +678,9 @@ const settings: TranslationStrings = { 'settings.apiKeys.modal.done': 'Listo', 'settings.mcp.deprecated': 'Obsoleto', 'settings.offline.cache.dateRange': 'del {start} al {end}', + 'settings.offline.tileStore.title': 'Teselas de mapa vistas', + 'settings.offline.tileStore.usage': '{used} de {limit} en este dispositivo, se guardan hasta 30 días', + 'settings.offline.tileStore.clear': 'Vaciar', }; export default settings; diff --git a/shared/src/i18n/et/map.ts b/shared/src/i18n/et/map.ts index 8871e8086..24fe3f1ab 100644 --- a/shared/src/i18n/et/map.ts +++ b/shared/src/i18n/et/map.ts @@ -44,5 +44,6 @@ const map: TranslationStrings = { 'map.webgl2.fallback': 'See brauser ei paku WebGL2-te, mida GL-kaardid vajavad, seega kuvatakse kaardid Leafletiga.', 'map.webgl2.terrain': '3D vajab WebGL2-te, mida see brauser ei paku. Kaart jääb 2D-vaatesse.', 'map.offlineBasemap': 'Võrguühenduseta kaart', + 'map.offlineShowStored': 'Näita võrguühenduseta kaarti', }; export default map; diff --git a/shared/src/i18n/et/settings.ts b/shared/src/i18n/et/settings.ts index 2f4324684..e89e8d55d 100644 --- a/shared/src/i18n/et/settings.ts +++ b/shared/src/i18n/et/settings.ts @@ -669,6 +669,9 @@ const settings: TranslationStrings = { 'settings.apiKeys.modal.done': 'Valmis', 'settings.mcp.deprecated': 'Aegunud', 'settings.offline.cache.dateRange': '{start} kuni {end}', + 'settings.offline.tileStore.title': 'Vaadatud kaardiruudud', + 'settings.offline.tileStore.usage': '{used} / {limit} selles seadmes, hoitakse kuni 30 päeva', + 'settings.offline.tileStore.clear': 'Tühjenda', }; export default settings; diff --git a/shared/src/i18n/fr/map.ts b/shared/src/i18n/fr/map.ts index 316f4adbf..79736b9db 100644 --- a/shared/src/i18n/fr/map.ts +++ b/shared/src/i18n/fr/map.ts @@ -47,5 +47,6 @@ const map: TranslationStrings = { 'Ce navigateur ne propose pas WebGL2, nécessaire aux cartes GL : les cartes s’affichent donc avec Leaflet.', 'map.webgl2.terrain': 'La 3D nécessite WebGL2, que ce navigateur ne propose pas. La carte reste en 2D.', 'map.offlineBasemap': 'Carte hors ligne', + 'map.offlineShowStored': 'Afficher la carte hors ligne', }; export default map; diff --git a/shared/src/i18n/fr/settings.ts b/shared/src/i18n/fr/settings.ts index 5d178c14c..191d3fddb 100644 --- a/shared/src/i18n/fr/settings.ts +++ b/shared/src/i18n/fr/settings.ts @@ -686,6 +686,9 @@ const settings: TranslationStrings = { 'settings.apiKeys.modal.done': 'Terminé', 'settings.mcp.deprecated': 'Obsolète', 'settings.offline.cache.dateRange': 'du {start} au {end}', + 'settings.offline.tileStore.title': 'Tuiles de carte consultées', + 'settings.offline.tileStore.usage': '{used} sur {limit} sur cet appareil, conservées jusqu’à 30 jours', + 'settings.offline.tileStore.clear': 'Vider', }; export default settings; diff --git a/shared/src/i18n/gr/map.ts b/shared/src/i18n/gr/map.ts index 22b24e22b..7a43ca92e 100644 --- a/shared/src/i18n/gr/map.ts +++ b/shared/src/i18n/gr/map.ts @@ -47,5 +47,6 @@ const map: TranslationStrings = { 'map.webgl2.terrain': 'Το 3D χρειάζεται WebGL2, που αυτό το πρόγραμμα περιήγησης δεν προσφέρει. Ο χάρτης μένει σε 2D.', 'map.offlineBasemap': 'Χάρτης εκτός σύνδεσης', + 'map.offlineShowStored': 'Εμφάνιση χάρτη εκτός σύνδεσης', }; export default map; diff --git a/shared/src/i18n/gr/settings.ts b/shared/src/i18n/gr/settings.ts index 5e9dacfcf..68f36ed64 100644 --- a/shared/src/i18n/gr/settings.ts +++ b/shared/src/i18n/gr/settings.ts @@ -692,6 +692,9 @@ const settings: TranslationStrings = { 'settings.apiKeys.modal.done': 'Έτοιμο', 'settings.mcp.deprecated': 'Απαρχαιωμένο', 'settings.offline.cache.dateRange': 'από {start} έως {end}', + 'settings.offline.tileStore.title': 'Πλακίδια χάρτη που προβλήθηκαν', + 'settings.offline.tileStore.usage': '{used} από {limit} σε αυτή τη συσκευή, φυλάσσονται έως 30 ημέρες', + 'settings.offline.tileStore.clear': 'Εκκαθάριση', }; export default settings; diff --git a/shared/src/i18n/he/map.ts b/shared/src/i18n/he/map.ts index ec7c202a4..64a950374 100644 --- a/shared/src/i18n/he/map.ts +++ b/shared/src/i18n/he/map.ts @@ -46,6 +46,7 @@ const map: TranslationStrings = { 'map.webgl2.fallback': 'הדפדפן הזה לא תומך ב-WebGL2, שמפות GL צריכות, ולכן המפות מוצגות עם Leaflet.', 'map.webgl2.terrain': 'תלת-ממד דורש WebGL2, והדפדפן הזה לא תומך בו. המפה נשארת בדו-ממד.', 'map.offlineBasemap': 'מפה לא מקוונת', + 'map.offlineShowStored': 'הצגת מפה לא מקוונת', }; export default map; diff --git a/shared/src/i18n/he/settings.ts b/shared/src/i18n/he/settings.ts index f72977f12..7c6218138 100644 --- a/shared/src/i18n/he/settings.ts +++ b/shared/src/i18n/he/settings.ts @@ -644,6 +644,9 @@ const settings: TranslationStrings = { 'settings.apiKeys.modal.done': 'סיום', 'settings.mcp.deprecated': 'מיושן', 'settings.offline.cache.dateRange': '{start} עד {end}', + 'settings.offline.tileStore.title': 'אריחי מפה שנצפו', + 'settings.offline.tileStore.usage': '{used} מתוך {limit} במכשיר הזה, נשמרים עד 30 יום', + 'settings.offline.tileStore.clear': 'ניקוי', }; export default settings; diff --git a/shared/src/i18n/hu/map.ts b/shared/src/i18n/hu/map.ts index bfd29efff..c9d1c6ca0 100644 --- a/shared/src/i18n/hu/map.ts +++ b/shared/src/i18n/hu/map.ts @@ -45,5 +45,6 @@ const map: TranslationStrings = { 'Ez a böngésző nem kínál WebGL2-t, amelyre a GL-térképeknek szükségük van, ezért a térképek Leaflettel jelennek meg.', 'map.webgl2.terrain': 'A 3D-hez WebGL2 kell, amelyet ez a böngésző nem kínál. A térkép 2D-ben marad.', 'map.offlineBasemap': 'Offline térkép', + 'map.offlineShowStored': 'Offline térkép megjelenítése', }; export default map; diff --git a/shared/src/i18n/hu/settings.ts b/shared/src/i18n/hu/settings.ts index 47550ba27..da3481da7 100644 --- a/shared/src/i18n/hu/settings.ts +++ b/shared/src/i18n/hu/settings.ts @@ -677,6 +677,9 @@ const settings: TranslationStrings = { 'settings.apiKeys.modal.done': 'Kész', 'settings.mcp.deprecated': 'Elavult', 'settings.offline.cache.dateRange': '{start} és {end} között', + 'settings.offline.tileStore.title': 'Megtekintett térképcsempék', + 'settings.offline.tileStore.usage': '{used} / {limit} ezen az eszközön, legfeljebb 30 napig őrizve', + 'settings.offline.tileStore.clear': 'Ürítés', }; export default settings; diff --git a/shared/src/i18n/id/map.ts b/shared/src/i18n/id/map.ts index 46a4dd820..aa7fc0d42 100644 --- a/shared/src/i18n/id/map.ts +++ b/shared/src/i18n/id/map.ts @@ -44,5 +44,6 @@ const map: TranslationStrings = { 'Browser ini tidak menyediakan WebGL2 yang dibutuhkan peta GL, jadi peta ditampilkan dengan Leaflet.', 'map.webgl2.terrain': '3D membutuhkan WebGL2, yang tidak disediakan browser ini. Peta tetap dalam 2D.', 'map.offlineBasemap': 'Peta offline', + 'map.offlineShowStored': 'Tampilkan peta offline', }; export default map; diff --git a/shared/src/i18n/id/settings.ts b/shared/src/i18n/id/settings.ts index 76ae644b9..4c5ee6f8b 100644 --- a/shared/src/i18n/id/settings.ts +++ b/shared/src/i18n/id/settings.ts @@ -665,6 +665,9 @@ const settings: TranslationStrings = { 'settings.apiKeys.modal.done': 'Selesai', 'settings.mcp.deprecated': 'Usang', 'settings.offline.cache.dateRange': '{start} sampai {end}', + 'settings.offline.tileStore.title': 'Ubin peta yang dilihat', + 'settings.offline.tileStore.usage': '{used} dari {limit} di perangkat ini, disimpan hingga 30 hari', + 'settings.offline.tileStore.clear': 'Kosongkan', }; export default settings; diff --git a/shared/src/i18n/it/map.ts b/shared/src/i18n/it/map.ts index 91a345d17..0529319a2 100644 --- a/shared/src/i18n/it/map.ts +++ b/shared/src/i18n/it/map.ts @@ -48,5 +48,6 @@ const map: TranslationStrings = { 'Questo browser non offre WebGL2, necessario alle mappe GL, quindi le mappe vengono mostrate con Leaflet.', 'map.webgl2.terrain': 'Il 3D richiede WebGL2, che questo browser non offre. La mappa resta in 2D.', 'map.offlineBasemap': 'Mappa offline', + 'map.offlineShowStored': 'Mostra mappa offline', }; export default map; diff --git a/shared/src/i18n/it/settings.ts b/shared/src/i18n/it/settings.ts index a1a334352..968d3e272 100644 --- a/shared/src/i18n/it/settings.ts +++ b/shared/src/i18n/it/settings.ts @@ -675,6 +675,9 @@ const settings: TranslationStrings = { 'settings.apiKeys.modal.done': 'Fatto', 'settings.mcp.deprecated': 'Obsoleto', 'settings.offline.cache.dateRange': 'dal {start} al {end}', + 'settings.offline.tileStore.title': 'Tessere di mappa visualizzate', + 'settings.offline.tileStore.usage': '{used} di {limit} su questo dispositivo, conservate fino a 30 giorni', + 'settings.offline.tileStore.clear': 'Svuota', }; export default settings; diff --git a/shared/src/i18n/ja/map.ts b/shared/src/i18n/ja/map.ts index af4a2b1cb..501acbf7e 100644 --- a/shared/src/i18n/ja/map.ts +++ b/shared/src/i18n/ja/map.ts @@ -44,5 +44,6 @@ const map: TranslationStrings = { 'このブラウザーは GL マップに必要な WebGL2 に対応していないため、地図は Leaflet で表示されます。', 'map.webgl2.terrain': '3D には WebGL2 が必要ですが、このブラウザーは対応していません。地図は 2D のままです。', 'map.offlineBasemap': 'オフライン地図', + 'map.offlineShowStored': 'オフライン地図を表示', }; export default map; diff --git a/shared/src/i18n/ja/settings.ts b/shared/src/i18n/ja/settings.ts index b3cfa3afe..07f40ccac 100644 --- a/shared/src/i18n/ja/settings.ts +++ b/shared/src/i18n/ja/settings.ts @@ -636,6 +636,9 @@ const settings: TranslationStrings = { 'settings.apiKeys.modal.done': '完了', 'settings.mcp.deprecated': '非推奨', 'settings.offline.cache.dateRange': '{start}から{end}', + 'settings.offline.tileStore.title': '表示した地図タイル', + 'settings.offline.tileStore.usage': 'この端末で {limit} 中 {used}、最長30日間保存', + 'settings.offline.tileStore.clear': '消去', }; export default settings; diff --git a/shared/src/i18n/ko/map.ts b/shared/src/i18n/ko/map.ts index 544b39650..c6f19f231 100644 --- a/shared/src/i18n/ko/map.ts +++ b/shared/src/i18n/ko/map.ts @@ -43,5 +43,6 @@ const map: TranslationStrings = { 'map.webgl2.fallback': '이 브라우저는 GL 지도에 필요한 WebGL2를 지원하지 않아 지도를 Leaflet으로 표시합니다.', 'map.webgl2.terrain': '3D에는 WebGL2가 필요하지만 이 브라우저는 지원하지 않습니다. 지도는 2D로 유지됩니다.', 'map.offlineBasemap': '오프라인 지도', + 'map.offlineShowStored': '오프라인 지도 보기', }; export default map; diff --git a/shared/src/i18n/ko/settings.ts b/shared/src/i18n/ko/settings.ts index c67a4e024..bf41114ef 100644 --- a/shared/src/i18n/ko/settings.ts +++ b/shared/src/i18n/ko/settings.ts @@ -646,6 +646,9 @@ const settings: TranslationStrings = { 'settings.apiKeys.modal.done': '완료', 'settings.mcp.deprecated': '지원 중단 예정', 'settings.offline.cache.dateRange': '{start}부터 {end}까지', + 'settings.offline.tileStore.title': '본 지도 타일', + 'settings.offline.tileStore.usage': '이 기기에서 {limit} 중 {used}, 최대 30일간 보관', + 'settings.offline.tileStore.clear': '비우기', }; export default settings; diff --git a/shared/src/i18n/nl/map.ts b/shared/src/i18n/nl/map.ts index bca23f52b..fb5b906bd 100644 --- a/shared/src/i18n/nl/map.ts +++ b/shared/src/i18n/nl/map.ts @@ -47,5 +47,6 @@ const map: TranslationStrings = { 'Deze browser biedt geen WebGL2, dat GL-kaarten nodig hebben, dus kaarten worden met Leaflet getoond.', 'map.webgl2.terrain': '3D heeft WebGL2 nodig, dat deze browser niet biedt. De kaart blijft in 2D.', 'map.offlineBasemap': 'Offline kaart', + 'map.offlineShowStored': 'Offline kaart tonen', }; export default map; diff --git a/shared/src/i18n/nl/settings.ts b/shared/src/i18n/nl/settings.ts index 23c16bd51..1ab31febb 100644 --- a/shared/src/i18n/nl/settings.ts +++ b/shared/src/i18n/nl/settings.ts @@ -678,6 +678,9 @@ const settings: TranslationStrings = { 'settings.apiKeys.modal.done': 'Klaar', 'settings.mcp.deprecated': 'Verouderd', 'settings.offline.cache.dateRange': '{start} tot {end}', + 'settings.offline.tileStore.title': 'Bekeken kaarttegels', + 'settings.offline.tileStore.usage': '{used} van {limit} op dit apparaat, maximaal 30 dagen bewaard', + 'settings.offline.tileStore.clear': 'Wissen', }; export default settings; diff --git a/shared/src/i18n/pl/map.ts b/shared/src/i18n/pl/map.ts index 126d4d7c8..de5378232 100644 --- a/shared/src/i18n/pl/map.ts +++ b/shared/src/i18n/pl/map.ts @@ -50,5 +50,6 @@ const map: TranslationStrings = { 'Ta przeglądarka nie obsługuje WebGL2, którego potrzebują mapy GL, więc mapy są wyświetlane za pomocą Leaflet.', 'map.webgl2.terrain': 'Tryb 3D wymaga WebGL2, którego ta przeglądarka nie obsługuje. Mapa pozostaje w 2D.', 'map.offlineBasemap': 'Mapa offline', + 'map.offlineShowStored': 'Pokaż mapę offline', }; export default map; diff --git a/shared/src/i18n/pl/settings.ts b/shared/src/i18n/pl/settings.ts index f600860c8..5a3afd4e3 100644 --- a/shared/src/i18n/pl/settings.ts +++ b/shared/src/i18n/pl/settings.ts @@ -692,6 +692,9 @@ const settings: TranslationStrings = { 'settings.apiKeys.modal.done': 'Gotowe', 'settings.mcp.deprecated': 'Przestarzałe', 'settings.offline.cache.dateRange': '{start} do {end}', + 'settings.offline.tileStore.title': 'Obejrzane kafelki mapy', + 'settings.offline.tileStore.usage': '{used} z {limit} na tym urządzeniu, przechowywane do 30 dni', + 'settings.offline.tileStore.clear': 'Wyczyść', }; export default settings; diff --git a/shared/src/i18n/ru/map.ts b/shared/src/i18n/ru/map.ts index 6114a6b49..bac76e60f 100644 --- a/shared/src/i18n/ru/map.ts +++ b/shared/src/i18n/ru/map.ts @@ -51,5 +51,6 @@ const map: TranslationStrings = { 'Этот браузер не поддерживает WebGL2, нужный картам GL, поэтому карты показываются через Leaflet.', 'map.webgl2.terrain': 'Для 3D нужен WebGL2, а этот браузер его не поддерживает. Карта остаётся в 2D.', 'map.offlineBasemap': 'Офлайн-карта', + 'map.offlineShowStored': 'Показать офлайн-карту', }; export default map; diff --git a/shared/src/i18n/ru/settings.ts b/shared/src/i18n/ru/settings.ts index 1a7510161..604c5f24b 100644 --- a/shared/src/i18n/ru/settings.ts +++ b/shared/src/i18n/ru/settings.ts @@ -694,6 +694,9 @@ const settings: TranslationStrings = { 'settings.apiKeys.modal.done': 'Готово', 'settings.mcp.deprecated': 'Устарело', 'settings.offline.cache.dateRange': 'с {start} по {end}', + 'settings.offline.tileStore.title': 'Просмотренные тайлы карты', + 'settings.offline.tileStore.usage': '{used} из {limit} на этом устройстве, хранятся до 30 дней', + 'settings.offline.tileStore.clear': 'Очистить', }; export default settings; diff --git a/shared/src/i18n/sk/map.ts b/shared/src/i18n/sk/map.ts index 231d5d0dc..da9835631 100644 --- a/shared/src/i18n/sk/map.ts +++ b/shared/src/i18n/sk/map.ts @@ -47,5 +47,6 @@ const map: TranslationStrings = { 'Tento prehliadač neponúka WebGL2, ktoré mapy GL potrebujú, preto sa mapy zobrazujú pomocou Leafletu.', 'map.webgl2.terrain': '3D potrebuje WebGL2, ktoré tento prehliadač neponúka. Mapa zostáva v 2D.', 'map.offlineBasemap': 'Offline mapa', + 'map.offlineShowStored': 'Zobraziť offline mapu', }; export default map; diff --git a/shared/src/i18n/sk/settings.ts b/shared/src/i18n/sk/settings.ts index c98d2859a..05f1c1cb6 100644 --- a/shared/src/i18n/sk/settings.ts +++ b/shared/src/i18n/sk/settings.ts @@ -678,6 +678,9 @@ const settings: TranslationStrings = { 'settings.apiKeys.modal.done': 'Hotovo', 'settings.mcp.deprecated': 'Zastarané', 'settings.offline.cache.dateRange': '{start} až {end}', + 'settings.offline.tileStore.title': 'Zobrazené dlaždice mapy', + 'settings.offline.tileStore.usage': '{used} z {limit} v tomto zariadení, uchováva sa až 30 dní', + 'settings.offline.tileStore.clear': 'Vymazať', }; export default settings; diff --git a/shared/src/i18n/sv/map.ts b/shared/src/i18n/sv/map.ts index 7cde3cfb1..bea606c3c 100644 --- a/shared/src/i18n/sv/map.ts +++ b/shared/src/i18n/sv/map.ts @@ -45,5 +45,6 @@ const map: TranslationStrings = { 'Den här webbläsaren erbjuder inte WebGL2, som GL-kartor behöver, så kartorna visas med Leaflet i stället.', 'map.webgl2.terrain': '3D kräver WebGL2, som den här webbläsaren inte erbjuder. Kartan stannar i 2D.', 'map.offlineBasemap': 'Offlinekarta', + 'map.offlineShowStored': 'Visa offlinekarta', }; export default map; diff --git a/shared/src/i18n/sv/settings.ts b/shared/src/i18n/sv/settings.ts index 1b50e4045..ac1cceca1 100644 --- a/shared/src/i18n/sv/settings.ts +++ b/shared/src/i18n/sv/settings.ts @@ -668,6 +668,9 @@ const settings: TranslationStrings = { 'settings.apiKeys.modal.done': 'Klar', 'settings.mcp.deprecated': 'Utfasad', 'settings.offline.cache.dateRange': '{start} till {end}', + 'settings.offline.tileStore.title': 'Visade kartrutor', + 'settings.offline.tileStore.usage': '{used} av {limit} på den här enheten, sparas i upp till 30 dagar', + 'settings.offline.tileStore.clear': 'Rensa', }; export default settings; diff --git a/shared/src/i18n/th/map.ts b/shared/src/i18n/th/map.ts index 288de9af7..c04a36f22 100644 --- a/shared/src/i18n/th/map.ts +++ b/shared/src/i18n/th/map.ts @@ -42,5 +42,6 @@ const map: TranslationStrings = { 'map.webgl2.fallback': 'เบราว์เซอร์นี้ไม่รองรับ WebGL2 ที่แผนที่ GL ต้องใช้ จึงแสดงแผนที่ด้วย Leaflet แทน', 'map.webgl2.terrain': 'โหมด 3D ต้องใช้ WebGL2 ซึ่งเบราว์เซอร์นี้ไม่รองรับ แผนที่จึงยังคงเป็น 2D', 'map.offlineBasemap': 'แผนที่ออฟไลน์', + 'map.offlineShowStored': 'แสดงแผนที่ออฟไลน์', }; export default map; diff --git a/shared/src/i18n/th/settings.ts b/shared/src/i18n/th/settings.ts index 2ec94c623..995172967 100644 --- a/shared/src/i18n/th/settings.ts +++ b/shared/src/i18n/th/settings.ts @@ -648,6 +648,9 @@ const settings: TranslationStrings = { 'settings.apiKeys.copyFailed': 'ไม่สามารถคัดลอกได้ เลือกข้อความและคัดลอกด้วยตนเอง', 'settings.mcp.deprecated': 'เลิกใช้แล้ว', 'settings.offline.cache.dateRange': '{start} ถึง {end}', + 'settings.offline.tileStore.title': 'ไทล์แผนที่ที่ดูแล้ว', + 'settings.offline.tileStore.usage': '{used} จาก {limit} บนอุปกรณ์นี้ เก็บไว้สูงสุด 30 วัน', + 'settings.offline.tileStore.clear': 'ล้าง', }; export default settings; diff --git a/shared/src/i18n/tr/map.ts b/shared/src/i18n/tr/map.ts index 70b1df378..6e0372f24 100644 --- a/shared/src/i18n/tr/map.ts +++ b/shared/src/i18n/tr/map.ts @@ -45,5 +45,6 @@ const map: TranslationStrings = { "Bu tarayıcı GL haritalarının ihtiyaç duyduğu WebGL2'yi sunmuyor, bu yüzden haritalar Leaflet ile gösteriliyor.", 'map.webgl2.terrain': '3D için WebGL2 gerekir, bu tarayıcı ise onu sunmuyor. Harita 2D olarak kalır.', 'map.offlineBasemap': 'Çevrimdışı harita', + 'map.offlineShowStored': 'Çevrimdışı haritayı göster', }; export default map; diff --git a/shared/src/i18n/tr/settings.ts b/shared/src/i18n/tr/settings.ts index faee2cffc..4eaef29bb 100644 --- a/shared/src/i18n/tr/settings.ts +++ b/shared/src/i18n/tr/settings.ts @@ -671,6 +671,9 @@ const settings: TranslationStrings = { 'settings.apiKeys.modal.done': 'Tamam', 'settings.mcp.deprecated': 'Kullanımdan kalkıyor', 'settings.offline.cache.dateRange': '{start} ile {end} arası', + 'settings.offline.tileStore.title': 'Görüntülenen harita karoları', + 'settings.offline.tileStore.usage': 'Bu cihazda {limit} içinden {used}, 30 güne kadar saklanır', + 'settings.offline.tileStore.clear': 'Temizle', }; export default settings; diff --git a/shared/src/i18n/uk/map.ts b/shared/src/i18n/uk/map.ts index 4db23d21f..eab483232 100644 --- a/shared/src/i18n/uk/map.ts +++ b/shared/src/i18n/uk/map.ts @@ -49,5 +49,6 @@ const map: TranslationStrings = { 'map.webgl2.fallback': 'Цей браузер не підтримує WebGL2, потрібний картам GL, тому карти показуються через Leaflet.', 'map.webgl2.terrain': 'Для 3D потрібен WebGL2, а цей браузер його не підтримує. Карта залишається у 2D.', 'map.offlineBasemap': 'Офлайн-карта', + 'map.offlineShowStored': 'Показати офлайн-карту', }; export default map; diff --git a/shared/src/i18n/uk/settings.ts b/shared/src/i18n/uk/settings.ts index 96c359b37..d6ded955d 100644 --- a/shared/src/i18n/uk/settings.ts +++ b/shared/src/i18n/uk/settings.ts @@ -692,6 +692,9 @@ const settings: TranslationStrings = { 'settings.apiKeys.modal.done': 'Готово', 'settings.mcp.deprecated': 'Застаріло', 'settings.offline.cache.dateRange': 'з {start} по {end}', + 'settings.offline.tileStore.title': 'Переглянуті плитки карти', + 'settings.offline.tileStore.usage': '{used} з {limit} на цьому пристрої, зберігаються до 30 днів', + 'settings.offline.tileStore.clear': 'Очистити', }; export default settings; diff --git a/shared/src/i18n/vi/map.ts b/shared/src/i18n/vi/map.ts index 34ce24447..731a18c57 100644 --- a/shared/src/i18n/vi/map.ts +++ b/shared/src/i18n/vi/map.ts @@ -45,5 +45,6 @@ const map: TranslationStrings = { 'map.webgl2.fallback': 'Trình duyệt này không hỗ trợ WebGL2 mà bản đồ GL cần, nên bản đồ được hiển thị bằng Leaflet.', 'map.webgl2.terrain': 'Chế độ 3D cần WebGL2, nhưng trình duyệt này không hỗ trợ. Bản đồ vẫn ở dạng 2D.', 'map.offlineBasemap': 'Bản đồ ngoại tuyến', + 'map.offlineShowStored': 'Hiện bản đồ ngoại tuyến', }; export default map; diff --git a/shared/src/i18n/vi/settings.ts b/shared/src/i18n/vi/settings.ts index 0e802fccc..9cf6c62be 100644 --- a/shared/src/i18n/vi/settings.ts +++ b/shared/src/i18n/vi/settings.ts @@ -665,6 +665,9 @@ const settings: TranslationStrings = { 'settings.apiKeys.modal.done': 'Xong', 'settings.mcp.deprecated': 'Không còn được khuyến nghị', 'settings.offline.cache.dateRange': '{start} đến {end}', + 'settings.offline.tileStore.title': 'Ô bản đồ đã xem', + 'settings.offline.tileStore.usage': '{used} trên {limit} trên thiết bị này, lưu tối đa 30 ngày', + 'settings.offline.tileStore.clear': 'Xóa', }; export default settings; diff --git a/shared/src/i18n/zh-TW/map.ts b/shared/src/i18n/zh-TW/map.ts index 9c00df569..3d859e318 100644 --- a/shared/src/i18n/zh-TW/map.ts +++ b/shared/src/i18n/zh-TW/map.ts @@ -41,5 +41,6 @@ const map: TranslationStrings = { 'map.webgl2.fallback': '此瀏覽器不支援 GL 地圖所需的 WebGL2,因此地圖改用 Leaflet 顯示。', 'map.webgl2.terrain': '3D 需要 WebGL2,而此瀏覽器不支援。地圖維持 2D。', 'map.offlineBasemap': '離線地圖', + 'map.offlineShowStored': '顯示離線地圖', }; export default map; diff --git a/shared/src/i18n/zh-TW/settings.ts b/shared/src/i18n/zh-TW/settings.ts index 1f5d2f930..c37747090 100644 --- a/shared/src/i18n/zh-TW/settings.ts +++ b/shared/src/i18n/zh-TW/settings.ts @@ -616,6 +616,9 @@ const settings: TranslationStrings = { 'settings.apiKeys.modal.done': '完成', 'settings.mcp.deprecated': '已棄用', 'settings.offline.cache.dateRange': '{start} 至 {end}', + 'settings.offline.tileStore.title': '已檢視的地圖圖磚', + 'settings.offline.tileStore.usage': '本裝置已使用 {used},上限 {limit},最多保存 30 天', + 'settings.offline.tileStore.clear': '清除', }; export default settings; diff --git a/shared/src/i18n/zh/map.ts b/shared/src/i18n/zh/map.ts index bef81a9de..cb0be528e 100644 --- a/shared/src/i18n/zh/map.ts +++ b/shared/src/i18n/zh/map.ts @@ -41,5 +41,6 @@ const map: TranslationStrings = { 'map.webgl2.fallback': '此浏览器不支持 GL 地图所需的 WebGL2,因此地图改用 Leaflet 显示。', 'map.webgl2.terrain': '3D 需要 WebGL2,而此浏览器不支持。地图保持 2D。', 'map.offlineBasemap': '离线地图', + 'map.offlineShowStored': '显示离线地图', }; export default map; diff --git a/shared/src/i18n/zh/settings.ts b/shared/src/i18n/zh/settings.ts index 93516cc68..5d8aff183 100644 --- a/shared/src/i18n/zh/settings.ts +++ b/shared/src/i18n/zh/settings.ts @@ -614,6 +614,9 @@ const settings: TranslationStrings = { 'settings.apiKeys.modal.done': '完成', 'settings.mcp.deprecated': '已弃用', 'settings.offline.cache.dateRange': '{start} 至 {end}', + 'settings.offline.tileStore.title': '已查看的地图瓦片', + 'settings.offline.tileStore.usage': '本设备上已用 {used},上限 {limit},最多保存 30 天', + 'settings.offline.tileStore.clear': '清除', }; export default settings; From 017f229cfc8b5617c5ac30ed79a258da6525b0bd Mon Sep 17 00:00:00 2001 From: Maurice Date: Fri, 6 Nov 2026 13:21:19 +0100 Subject: [PATCH 068/589] feat(native): an app lock with Face ID, Touch ID or the device passcode A switch in the account settings, inside the app on a device that can unlock that way (iOS LocalAuthentication, Android BiometricPrompt with the screen lock as fallback). Turning it on asks once, so nobody locks themselves out. With it on, TREK asks at launch and after half a minute in the background before showing anything, and the app switcher shows a blurred cover (iOS) or no snapshot (Android) instead of the screen. The setting stays on the device, not the account. --- client/android/app/build.gradle | 1 + .../com/liketrek/trek/TrekShellPlugin.java | 68 +++++++++++++++- client/ios/App/App/Info.plist | 2 + client/ios/App/App/SceneDelegate.swift | 36 +++++++++ client/ios/App/App/TrekShellPlugin.swift | 45 ++++++++++- client/src/App.tsx | 2 + .../components/Layout/AppLockGate.test.tsx | 63 +++++++++++++++ client/src/components/Layout/AppLockGate.tsx | 80 +++++++++++++++++++ .../screens/settings/MAppLockCard.test.tsx | 55 +++++++++++++ .../mobile/screens/settings/MAppLockCard.tsx | 54 +++++++++++++ .../screens/settings/MSettingsAccount.tsx | 4 + client/src/native/appLock.test.ts | 53 ++++++++++++ client/src/native/appLock.ts | 63 +++++++++++++++ client/src/native/trekShell.ts | 6 ++ shared/src/i18n/ar/native.ts | 6 ++ shared/src/i18n/az/native.ts | 7 ++ shared/src/i18n/br/native.ts | 7 ++ shared/src/i18n/ca/native.ts | 7 ++ shared/src/i18n/cs/native.ts | 7 ++ shared/src/i18n/de/native.ts | 7 ++ shared/src/i18n/en/native.ts | 7 ++ shared/src/i18n/es/native.ts | 7 ++ shared/src/i18n/et/native.ts | 7 ++ shared/src/i18n/fr/native.ts | 7 ++ shared/src/i18n/gr/native.ts | 7 ++ shared/src/i18n/he/native.ts | 6 ++ shared/src/i18n/hu/native.ts | 7 ++ shared/src/i18n/id/native.ts | 7 ++ shared/src/i18n/it/native.ts | 7 ++ shared/src/i18n/ja/native.ts | 7 ++ shared/src/i18n/ko/native.ts | 7 ++ shared/src/i18n/nl/native.ts | 7 ++ shared/src/i18n/pl/native.ts | 7 ++ shared/src/i18n/ru/native.ts | 7 ++ shared/src/i18n/sk/native.ts | 7 ++ shared/src/i18n/sv/native.ts | 7 ++ shared/src/i18n/th/native.ts | 6 ++ shared/src/i18n/tr/native.ts | 7 ++ shared/src/i18n/uk/native.ts | 7 ++ shared/src/i18n/vi/native.ts | 7 ++ shared/src/i18n/zh-TW/native.ts | 6 ++ shared/src/i18n/zh/native.ts | 6 ++ 42 files changed, 721 insertions(+), 2 deletions(-) create mode 100644 client/src/components/Layout/AppLockGate.test.tsx create mode 100644 client/src/components/Layout/AppLockGate.tsx create mode 100644 client/src/mobile/screens/settings/MAppLockCard.test.tsx create mode 100644 client/src/mobile/screens/settings/MAppLockCard.tsx create mode 100644 client/src/native/appLock.test.ts create mode 100644 client/src/native/appLock.ts diff --git a/client/android/app/build.gradle b/client/android/app/build.gradle index 38c23a189..d936d41a0 100644 --- a/client/android/app/build.gradle +++ b/client/android/app/build.gradle @@ -56,6 +56,7 @@ dependencies { implementation "androidx.coordinatorlayout:coordinatorlayout:$androidxCoordinatorLayoutVersion" implementation "androidx.core:core-splashscreen:$coreSplashScreenVersion" implementation "androidx.browser:browser:$androidxBrowserVersion" + implementation "androidx.biometric:biometric:1.1.0" implementation project(':capacitor-android') testImplementation "junit:junit:$junitVersion" androidTestImplementation "androidx.test.ext:junit:$androidxJunitVersion" diff --git a/client/android/app/src/main/java/com/liketrek/trek/TrekShellPlugin.java b/client/android/app/src/main/java/com/liketrek/trek/TrekShellPlugin.java index a12975fcd..b5ee2ec61 100644 --- a/client/android/app/src/main/java/com/liketrek/trek/TrekShellPlugin.java +++ b/client/android/app/src/main/java/com/liketrek/trek/TrekShellPlugin.java @@ -31,7 +31,7 @@ public class TrekShellPlugin extends Plugin { */ static final int SHELL_API = 2; /** The native features by name, so the UI can turn each on by itself. */ - static final String[] FEATURES = { "capabilities" }; + static final String[] FEATURES = { "capabilities", "biometricLock" }; @PluginMethod public void getCapabilities(PluginCall call) { @@ -55,6 +55,72 @@ public class TrekShellPlugin extends Plugin { call.resolve(result); } + // ---- App lock ---- + + private static final int AUTHENTICATORS = + androidx.biometric.BiometricManager.Authenticators.BIOMETRIC_WEAK + | androidx.biometric.BiometricManager.Authenticators.DEVICE_CREDENTIAL; + + /** Which biometry the device offers for the app lock, if any. */ + @PluginMethod + public void biometryInfo(PluginCall call) { + int status = androidx.biometric.BiometricManager.from(getContext()).canAuthenticate(AUTHENTICATORS); + JSObject result = new JSObject(); + result.put("available", status == androidx.biometric.BiometricManager.BIOMETRIC_SUCCESS); + result.put("type", "biometric"); + call.resolve(result); + } + + /** The system biometric prompt with the screen lock as the way out. */ + @PluginMethod + public void authenticateBiometric(PluginCall call) { + String reason = call.getString("reason", "Unlock TREK"); + getActivity().runOnUiThread(() -> { + androidx.fragment.app.FragmentActivity activity = (androidx.fragment.app.FragmentActivity) getActivity(); + androidx.biometric.BiometricPrompt prompt = new androidx.biometric.BiometricPrompt( + activity, + androidx.core.content.ContextCompat.getMainExecutor(getContext()), + new androidx.biometric.BiometricPrompt.AuthenticationCallback() { + @Override + public void onAuthenticationSucceeded(androidx.biometric.BiometricPrompt.AuthenticationResult result) { + JSObject ok = new JSObject(); + ok.put("ok", true); + call.resolve(ok); + } + + @Override + public void onAuthenticationError(int code, CharSequence message) { + boolean cancelled = code == androidx.biometric.BiometricPrompt.ERROR_USER_CANCELED + || code == androidx.biometric.BiometricPrompt.ERROR_NEGATIVE_BUTTON + || code == androidx.biometric.BiometricPrompt.ERROR_CANCELED; + call.reject(message.toString(), cancelled ? "CANCELLED" : "FAILED"); + } + } + ); + androidx.biometric.BiometricPrompt.PromptInfo info = new androidx.biometric.BiometricPrompt.PromptInfo.Builder() + .setTitle(reason) + .setAllowedAuthenticators(AUTHENTICATORS) + .build(); + prompt.authenticate(info); + }); + } + + /** While on, the recent-apps screen shows no snapshot of the app. */ + @PluginMethod + public void setPrivacyCover(PluginCall call) { + boolean enabled = Boolean.TRUE.equals(call.getBoolean("enabled", false)); + getActivity().runOnUiThread(() -> { + if (android.os.Build.VERSION.SDK_INT >= 33) { + getActivity().setRecentsScreenshotEnabled(!enabled); + } else if (enabled) { + getActivity().getWindow().addFlags(android.view.WindowManager.LayoutParams.FLAG_SECURE); + } else { + getActivity().getWindow().clearFlags(android.view.WindowManager.LayoutParams.FLAG_SECURE); + } + }); + call.resolve(); + } + @PluginMethod public void getServer(PluginCall call) { String url = TrekServerStore.getUrl(getContext()); diff --git a/client/ios/App/App/Info.plist b/client/ios/App/App/Info.plist index b4d095119..88d841452 100644 --- a/client/ios/App/App/Info.plist +++ b/client/ios/App/App/Info.plist @@ -71,6 +71,8 @@ NSPhotoLibraryAddUsageDescription TREK saves photos and exports you download from your trips back to your photo library. + NSFaceIDUsageDescription + TREK uses Face ID to unlock the app when you turn on the app lock. NSLocationWhenInUseUsageDescription TREK uses your location to centre the map on you and to find places near you. + + + + + + + + + + CFBundleDocumentTypes + + + CFBundleTypeName + Booking document + CFBundleTypeRole + Viewer + LSHandlerRank + Alternate + LSItemContentTypes + + com.adobe.pdf + com.apple.ical.ics + com.apple.pkpass + com.apple.mail.email + public.email-message + + + + LSSupportsOpeningDocumentsInPlace + CFBundleURLTypes diff --git a/client/ios/App/App/SceneDelegate.swift b/client/ios/App/App/SceneDelegate.swift index 53978bc7d..f81a497d6 100644 --- a/client/ios/App/App/SceneDelegate.swift +++ b/client/ios/App/App/SceneDelegate.swift @@ -11,6 +11,10 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { window?.rootViewController = TrekBridgeViewController() window?.makeKeyAndVisible() + // Launched by "Open in TREK" on a booking document. + for context in connectionOptions.urlContexts where context.url.isFileURL { + TrekSharedFiles.receive(context.url) + } SceneDelegateProxy.shared.scene(scene, willConnectTo: session, options: connectionOptions) } @@ -25,7 +29,12 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { } func scene(_ scene: UIScene, openURLContexts URLContexts: Set) { - SceneDelegateProxy.shared.scene(scene, openURLContexts: URLContexts) + // A booking document shared to TREK goes to the UI's import; anything + // else (the sign-in callback) stays with Capacitor. + let files = URLContexts.filter { $0.url.isFileURL } + for context in files { TrekSharedFiles.receive(context.url) } + let others = URLContexts.subtracting(files) + if !others.isEmpty { SceneDelegateProxy.shared.scene(scene, openURLContexts: others) } } func scene(_ scene: UIScene, continue userActivity: NSUserActivity) { @@ -58,3 +67,41 @@ enum TrekPrivacyCover { cover = nil } } + +/// Booking documents shared to TREK ("Open in TREK"), held until the UI takes +/// them (TrekShell.takeSharedFile) and announced if it is already running. +enum TrekSharedFiles { + /// Above this the file is not a booking confirmation, and base64 over the + /// bridge would only stall the app. + static let maxBytes = 15 * 1024 * 1024 + private(set) static var pending: [String: Any]? + static var onReceive: (([String: Any]) -> Void)? + + static func receive(_ url: URL) { + let scoped = url.startAccessingSecurityScopedResource() + defer { if scoped { url.stopAccessingSecurityScopedResource() } } + guard let data = try? Data(contentsOf: url), data.count <= maxBytes else { return } + let file: [String: Any] = [ + "name": url.lastPathComponent, + "mimeType": mimeType(for: url.pathExtension.lowercased()), + "data": data.base64EncodedString(), + ] + pending = file + onReceive?(file) + } + + static func take() -> [String: Any]? { + defer { pending = nil } + return pending + } + + private static func mimeType(for ext: String) -> String { + switch ext { + case "pdf": return "application/pdf" + case "ics": return "text/calendar" + case "pkpass": return "application/vnd.apple.pkpass" + case "eml": return "message/rfc822" + default: return "application/octet-stream" + } + } +} diff --git a/client/ios/App/App/TrekShellPlugin.swift b/client/ios/App/App/TrekShellPlugin.swift index d5f79bad2..e1c6f2a5f 100644 --- a/client/ios/App/App/TrekShellPlugin.swift +++ b/client/ios/App/App/TrekShellPlugin.swift @@ -26,6 +26,7 @@ public class TrekShellPlugin: CAPPlugin, CAPBridgedPlugin, ASWebAuthenticationPr CAPPluginMethod(name: "setPrivacyCover", returnType: CAPPluginReturnPromise), CAPPluginMethod(name: "startLocation", returnType: CAPPluginReturnPromise), CAPPluginMethod(name: "stopLocation", returnType: CAPPluginReturnPromise), + CAPPluginMethod(name: "takeSharedFile", returnType: CAPPluginReturnPromise), ] /// What this binary offers the server's UI, raised with every native feature @@ -33,7 +34,24 @@ public class TrekShellPlugin: CAPPlugin, CAPBridgedPlugin, ASWebAuthenticationPr /// and a server can require a minimum (minNativeShellApi in /api/health/features). static let shellApi = 2 /// The native features by name, so the UI can turn each on by itself. - static let features: [String] = ["capabilities", "edgeBack", "tileCache", "biometricLock", "geolocation"] + static let features: [String] = ["capabilities", "edgeBack", "tileCache", "biometricLock", "geolocation", "sharedFiles"] + + // MARK: - Shared booking documents + + override public func load() { + TrekSharedFiles.onReceive = { [weak self] file in + DispatchQueue.main.async { self?.notifyListeners("sharedFile", data: file) } + } + } + + /// The document shared to TREK before the UI was there to hear of it. + @objc func takeSharedFile(_ call: CAPPluginCall) { + if let file = TrekSharedFiles.take() { + call.resolve(["file": file]) + } else { + call.resolve(["file": NSNull()]) + } + } // MARK: - Location diff --git a/client/src/App.tsx b/client/src/App.tsx index bc335d8b5..303af78fd 100644 --- a/client/src/App.tsx +++ b/client/src/App.tsx @@ -34,6 +34,7 @@ import OfflineBanner from './components/Layout/OfflineBanner' import NewVersionNotice from './components/Layout/NewVersionNotice' import NativeUpdateNotice from './components/Layout/NativeUpdateNotice' import AppLockGate from './components/Layout/AppLockGate' +import NativeImportSheet from './components/Layout/NativeImportSheet' import { SystemNoticeHost } from './components/SystemNotices/SystemNoticeHost.js' import HelpPanel from './components/Help/HelpPanel' // Notice action registrations (side-effect imports): @@ -446,6 +447,7 @@ export default function App() { + {/* One boundary for all route chunks, above so it stays mounted across navigations. react-router runs location updates inside a transition, so a mounted boundary keeps the current page on screen instead of flashing diff --git a/client/src/components/Layout/NativeImportSheet.test.tsx b/client/src/components/Layout/NativeImportSheet.test.tsx new file mode 100644 index 000000000..74ed44ec7 --- /dev/null +++ b/client/src/components/Layout/NativeImportSheet.test.tsx @@ -0,0 +1,43 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { act, fireEvent, render, screen } from '../../../tests/helpers/render'; +import { tripsApi } from '../../api/client'; +import { useSharedImportStore } from '../../native/sharedFiles'; +import NativeImportSheet from './NativeImportSheet'; + +const navigate = vi.hoisted(() => vi.fn()); +vi.mock('react-router', async (importOriginal) => ({ + ...(await importOriginal()), + useNavigate: () => navigate, +})); + +beforeEach(() => { + navigate.mockReset(); + useSharedImportStore.setState({ file: null, tripId: null }); + vi.spyOn(tripsApi, 'list').mockResolvedValue({ + trips: [ + { id: 1, title: 'Past trip', start_date: '2020-01-01', end_date: '2020-01-05' }, + { id: 2, title: 'Japan', start_date: '2099-03-01', end_date: '2099-03-10' }, + ], + }); +}); + +describe('NativeImportSheet', () => { + it('asks which trip a shared document goes to, upcoming trips first, and opens it there', async () => { + render(); + act(() => useSharedImportStore.getState().setFile(new File(['x'], 'booking.pdf', { type: 'application/pdf' }))); + + const rows = await screen.findAllByRole('button', { name: /Japan|Past trip/ }); + expect(rows.map((r) => r.textContent)).toEqual(['Japan', 'Past trip']); + expect(screen.getByText('booking.pdf')).toBeInTheDocument(); + + fireEvent.click(rows[0]); + expect(useSharedImportStore.getState().tripId).toBe(2); + expect(navigate).toHaveBeenCalledWith('/trips/2'); + }); + + it('stays closed with nothing shared', () => { + render(); + expect(screen.queryByRole('dialog')).not.toBeInTheDocument(); + expect(tripsApi.list).not.toHaveBeenCalled(); + }); +}); diff --git a/client/src/components/Layout/NativeImportSheet.tsx b/client/src/components/Layout/NativeImportSheet.tsx new file mode 100644 index 000000000..c91a1e936 --- /dev/null +++ b/client/src/components/Layout/NativeImportSheet.tsx @@ -0,0 +1,80 @@ +/** + * NativeImportSheet: a booking document was shared to TREK (native/sharedFiles.ts), + * so this asks which trip it belongs to and opens that trip's booking import with + * the file already chosen. Trips still ahead come first, the ones that ended after. + */ +import { ChevronRight, FileText } from 'lucide-react'; +import React, { useEffect, useState } from 'react'; +import { useNavigate } from 'react-router'; +import { tripsApi } from '../../api/client'; +import { useTranslation } from '../../i18n'; +import MSheet from '../../mobile/components/MSheet'; +import { useSharedImportStore } from '../../native/sharedFiles'; + +interface TripRow { + id: number; + title: string; + start_date?: string | null; + end_date?: string | null; +} + +export default function NativeImportSheet(): React.ReactElement | null { + const { t } = useTranslation(); + const navigate = useNavigate(); + const file = useSharedImportStore((s) => s.file); + const tripId = useSharedImportStore((s) => s.tripId); + const chooseTrip = useSharedImportStore((s) => s.chooseTrip); + const setFile = useSharedImportStore((s) => s.setFile); + const [trips, setTrips] = useState([]); + + const open = !!file && tripId == null; + + useEffect(() => { + if (!open) return; + tripsApi.list().then( + (data: { trips?: TripRow[] }) => { + const today = new Date().toISOString().slice(0, 10); + const list = [...(data.trips ?? [])]; + const ahead = (trip: TripRow) => (trip.end_date ?? '9999') >= today; + list.sort( + (a, b) => Number(ahead(b)) - Number(ahead(a)) || (a.start_date ?? '').localeCompare(b.start_date ?? '') + ); + setTrips(list); + }, + () => setTrips([]) + ); + }, [open]); + + const pick = (id: number) => { + chooseTrip(id); + navigate(`/trips/${id}`); + }; + + return ( + setFile(null)} variant="bottom" ariaLabel={t('native.share.title')}> +
+
{t('native.share.title')}
+ {file && ( +
+
+ )} +
+ {trips.map((trip) => ( + + ))} + {trips.length === 0 &&

{t('native.share.noTrips')}

} +
+
+
+ ); +} diff --git a/client/src/components/Planner/BookingImportModal.tsx b/client/src/components/Planner/BookingImportModal.tsx index aa84b9eef..8955e12ce 100644 --- a/client/src/components/Planner/BookingImportModal.tsx +++ b/client/src/components/Planner/BookingImportModal.tsx @@ -1,4 +1,5 @@ import { createPortal } from 'react-dom' +import { useSharedImportStore } from '../../native/sharedFiles' import { useState, useRef, useEffect } from 'react' import { Upload, X } from 'lucide-react' import { useTranslation } from '../../i18n' @@ -35,6 +36,12 @@ export default function BookingImportModal({ isOpen, onClose, tripId, kind }: Bo const mouseDownTarget = useRef(null) const [files, setFiles] = useState([]) + // A booking document shared to TREK lands here already chosen. + useEffect(() => { + if (!isOpen) return + const shared = useSharedImportStore.getState().file + if (shared) setFiles([useSharedImportStore.getState().take() ?? shared]) + }, [isOpen]) const [isDragOver, setIsDragOver] = useState(false) const [loading, setLoading] = useState(false) const [error, setError] = useState('') diff --git a/client/src/mobile/screens/trip/MTripShell.tsx b/client/src/mobile/screens/trip/MTripShell.tsx index cc69e8551..95526dd92 100644 --- a/client/src/mobile/screens/trip/MTripShell.tsx +++ b/client/src/mobile/screens/trip/MTripShell.tsx @@ -9,6 +9,7 @@ import { pickDockTabs } from './dockTabs' import MBadge from '../../components/MBadge' import MIconBtn from '../../components/MIconBtn' import { useActivePill } from '../../components/useActivePill' +import { useSharedImportStore } from '../../../native/sharedFiles' import MPlanTimeline from './plan/MPlanTimeline' import MMapArea from './map/MMapArea' import MPlacesBrowser from './places/MPlacesBrowser' @@ -291,6 +292,14 @@ export default function MTripShell({ }) }, [planner.selectedDayId, days, dayRail]) // The active day's pill glides to the next chip rather than jumping there. + // A booking document shared to TREK, and this trip picked for it: open the import. + const sharedTripId = useSharedImportStore(s => s.tripId) + useEffect(() => { + if (sharedTripId == null || sharedTripId !== Number(tripId)) return + planner.setBookingImportKind('bookings') + planner.setShowBookingImport(true) + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [sharedTripId, tripId]) const dayPill = useActivePill(dayRail, '[aria-current="true"]', [planner.selectedDayId, days, dayRail, language]) const trTab = planner.activeTab diff --git a/client/src/native/nativeApp.test.ts b/client/src/native/nativeApp.test.ts index ba0cae970..f85b54f9d 100644 --- a/client/src/native/nativeApp.test.ts +++ b/client/src/native/nativeApp.test.ts @@ -23,6 +23,7 @@ vi.mock('./capabilities', () => ({ loadNativeCapabilities: vi.fn(async () => ({})), })); vi.mock('./geolocation', () => ({ installNativeGeolocation: vi.fn() })); +vi.mock('./sharedFiles', () => ({ startSharedFiles: vi.fn(async () => {}) })); vi.mock('../mobile/overlayStack', () => ({ closeTopOverlay: vi.fn(() => false) })); function backButtonHandler(): (event: { canGoBack: boolean }) => void { diff --git a/client/src/native/nativeApp.ts b/client/src/native/nativeApp.ts index efe7feff8..091d439bf 100644 --- a/client/src/native/nativeApp.ts +++ b/client/src/native/nativeApp.ts @@ -9,6 +9,7 @@ import { installNativeGeolocation } from './geolocation'; import { keepOfflineShellFresh } from './offlineShell'; import { isNativeApp, isNativeIos } from './platform'; import { reportNativeFailure } from './reportFailure'; +import { startSharedFiles } from './sharedFiles'; import { isUnimplemented } from './trekShell'; /** Long enough that the warm-up never competes with the first screen's requests. */ @@ -27,6 +28,8 @@ export function startNativeApp(): void { void checkAppUpdate(fetchServerFeatures); // The app's own location under navigator.geolocation, where the binary has it. void loadNativeCapabilities().then(() => installNativeGeolocation()); + // Booking documents shared to TREK, waiting for a trip to import into. + void startSharedFiles(); // A tap on the status bar scrolls the list under it back to the top, as in // every iOS app (the status-bar plugin fires statusTap on iOS). diff --git a/client/src/native/sharedFiles.test.ts b/client/src/native/sharedFiles.test.ts new file mode 100644 index 000000000..e7b41566d --- /dev/null +++ b/client/src/native/sharedFiles.test.ts @@ -0,0 +1,53 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { hasNativeFeature } from './capabilities'; +import { startSharedFiles, toFile, useSharedImportStore } from './sharedFiles'; +import { TrekShell } from './trekShell'; + +vi.mock('./capabilities', () => ({ hasNativeFeature: vi.fn(), loadNativeCapabilities: vi.fn(async () => ({})) })); +vi.mock('./trekShell', () => ({ + TrekShell: { addListener: vi.fn(async () => ({ remove: async () => {} })), takeSharedFile: vi.fn() }, + isUnimplemented: () => false, +})); + +const PDF = { name: 'booking.pdf', mimeType: 'application/pdf', data: btoa('%PDF-1.4 hello') }; + +beforeEach(() => { + useSharedImportStore.setState({ file: null, tripId: null }); + vi.mocked(hasNativeFeature).mockReturnValue(true); + vi.mocked(TrekShell.takeSharedFile).mockReset().mockResolvedValue({ file: null }); +}); + +describe('shared booking documents', () => { + it('turns the base64 the native side sends into a File', async () => { + const file = toFile(PDF); + expect(file.name).toBe('booking.pdf'); + expect(file.type).toBe('application/pdf'); + expect(await file.text()).toBe('%PDF-1.4 hello'); + }); + + it('picks up a document shared before the UI ran, and the next ones as they come', async () => { + vi.mocked(TrekShell.takeSharedFile).mockResolvedValue({ file: PDF }); + await startSharedFiles(); + expect(useSharedImportStore.getState().file?.name).toBe('booking.pdf'); + + const listener = vi.mocked(TrekShell.addListener).mock.calls[0][1] as (p: typeof PDF) => void; + listener({ ...PDF, name: 'train.ics', mimeType: 'text/calendar' }); + expect(useSharedImportStore.getState().file?.name).toBe('train.ics'); + }); + + it('hands the file over once a trip is picked, and empties the queue', () => { + useSharedImportStore.getState().setFile(toFile(PDF)); + useSharedImportStore.getState().chooseTrip(7); + expect(useSharedImportStore.getState().tripId).toBe(7); + expect(useSharedImportStore.getState().take()?.name).toBe('booking.pdf'); + expect(useSharedImportStore.getState()).toMatchObject({ file: null, tripId: null }); + }); + + it('does nothing in a binary without the feature', async () => { + vi.mocked(hasNativeFeature).mockReturnValue(false); + vi.mocked(TrekShell.addListener).mockClear(); + await startSharedFiles(); + expect(TrekShell.addListener).not.toHaveBeenCalled(); + expect(TrekShell.takeSharedFile).not.toHaveBeenCalled(); + }); +}); diff --git a/client/src/native/sharedFiles.ts b/client/src/native/sharedFiles.ts new file mode 100644 index 000000000..830b9c00f --- /dev/null +++ b/client/src/native/sharedFiles.ts @@ -0,0 +1,55 @@ +import { create } from 'zustand'; +import { hasNativeFeature, loadNativeCapabilities } from './capabilities'; +import { reportNativeFailure } from './reportFailure'; +import { TrekShell, isUnimplemented, type SharedFilePayload } from './trekShell'; + +/** + * Booking documents shared to TREK ("Open in TREK" on a PDF, a calendar entry, + * a Wallet pass or a mail). The native side hands them over as base64 + * (TrekShell.takeSharedFile and the sharedFile event); here they become a File + * waiting for a trip: NativeImportSheet asks which one, and the trip's booking + * import opens with the file already chosen (BookingImportModal). + */ +interface SharedImportState { + file: File | null; + /** The trip the user picked for it; the planner of that trip takes it from here. */ + tripId: number | null; + setFile: (file: File | null) => void; + chooseTrip: (tripId: number) => void; + /** The booking import took the file: the queue is empty again. */ + take: () => File | null; +} + +export const useSharedImportStore = create((set, get) => ({ + file: null, + tripId: null, + setFile: (file) => set({ file, tripId: null }), + chooseTrip: (tripId) => set({ tripId }), + take: () => { + const { file } = get(); + set({ file: null, tripId: null }); + return file; + }, +})); + +export function toFile(payload: SharedFilePayload): File { + const binary = atob(payload.data); + const bytes = new Uint8Array(binary.length); + for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i); + return new File([bytes], payload.name || 'booking', { type: payload.mimeType || 'application/octet-stream' }); +} + +/** Picks up a document shared before the UI ran, and listens for the next ones. */ +export async function startSharedFiles(): Promise { + await loadNativeCapabilities(); + if (!hasNativeFeature('sharedFiles')) return; + const accept = (payload: SharedFilePayload | null) => { + if (payload?.data) useSharedImportStore.getState().setFile(toFile(payload)); + }; + void TrekShell.addListener('sharedFile', accept); + try { + accept((await TrekShell.takeSharedFile()).file); + } catch (err) { + if (!isUnimplemented(err)) reportNativeFailure(err); + } +} diff --git a/client/src/native/trekShell.ts b/client/src/native/trekShell.ts index afe9c0ad9..097323b60 100644 --- a/client/src/native/trekShell.ts +++ b/client/src/native/trekShell.ts @@ -49,6 +49,20 @@ export interface TrekShellPlugin { event: 'location', listener: (payload: NativeLocationPayload) => void ): Promise<{ remove: () => Promise }>; + addListener( + event: 'sharedFile', + listener: (payload: SharedFilePayload) => void + ): Promise<{ remove: () => Promise }>; + /** Feature sharedFiles: the booking document shared to TREK before the UI ran. */ + takeSharedFile(): Promise<{ file: SharedFilePayload | null }>; +} + +/** A document shared to TREK, as the native side reads it. */ +export interface SharedFilePayload { + name: string; + mimeType: string; + /** base64 */ + data: string; } /** A position, or an error shaped like GeolocationPositionError (1 denied, 2 unavailable). */ diff --git a/shared/src/i18n/ar/native.ts b/shared/src/i18n/ar/native.ts index f445c5288..0ded8f83f 100644 --- a/shared/src/i18n/ar/native.ts +++ b/shared/src/i18n/ar/native.ts @@ -80,6 +80,8 @@ const native: TranslationStrings = { 'native.lock.settingTitle': 'قفل التطبيق', 'native.lock.setting': 'القفل باستخدام Face ID أو رمز المرور', 'native.lock.settingHint': 'يطلب ذلك عند فتح TREK وبعد نصف دقيقة في الخلفية، ويخفي التطبيق في مبدّل التطبيقات.', + 'native.share.title': 'الاستيراد إلى أي رحلة؟', + 'native.share.noTrips': 'لا توجد رحلة بعد. أنشئ رحلة أولًا ثم شارك المستند مجددًا.', }; export default native; diff --git a/shared/src/i18n/az/native.ts b/shared/src/i18n/az/native.ts index aeba3db30..1c5b8b7f5 100644 --- a/shared/src/i18n/az/native.ts +++ b/shared/src/i18n/az/native.ts @@ -82,6 +82,8 @@ const native: TranslationStrings = { 'native.lock.setting': 'Face ID və ya kodla kilidlə', 'native.lock.settingHint': 'TREK açılanda və arxa fonda yarım dəqiqədən sonra soruşur, tətbiqi tətbiq dəyişdiricisində gizlədir.', + 'native.share.title': 'Hansı səyahətə idxal edilsin?', + 'native.share.noTrips': 'Hələ səyahət yoxdur. Əvvəlcə birini yaradın, sonra sənədi yenidən paylaşın.', }; export default native; diff --git a/shared/src/i18n/br/native.ts b/shared/src/i18n/br/native.ts index 6005fb0b4..7a540640d 100644 --- a/shared/src/i18n/br/native.ts +++ b/shared/src/i18n/br/native.ts @@ -82,6 +82,8 @@ const native: TranslationStrings = { 'native.lock.setting': 'Bloquear com Face ID ou código', 'native.lock.settingHint': 'Pede ao abrir o TREK e após meio minuto em segundo plano, e oculta o app no seletor de apps.', + 'native.share.title': 'Importar para qual viagem?', + 'native.share.noTrips': 'Ainda não há viagens. Crie uma primeiro e compartilhe o documento de novo.', }; export default native; diff --git a/shared/src/i18n/ca/native.ts b/shared/src/i18n/ca/native.ts index 6f7420077..c007e6386 100644 --- a/shared/src/i18n/ca/native.ts +++ b/shared/src/i18n/ca/native.ts @@ -82,6 +82,8 @@ const native: TranslationStrings = { 'native.lock.setting': 'Bloqueja amb Face ID o codi', 'native.lock.settingHint': 'Ho demana en obrir TREK i després de mig minut en segon pla, i amaga l’app al selector d’apps.', + 'native.share.title': 'A quin viatge vols importar-ho?', + 'native.share.noTrips': 'Encara no hi ha cap viatge. Crea’n un i torna a compartir el document.', }; export default native; diff --git a/shared/src/i18n/cs/native.ts b/shared/src/i18n/cs/native.ts index b063a899f..73fba6fa8 100644 --- a/shared/src/i18n/cs/native.ts +++ b/shared/src/i18n/cs/native.ts @@ -82,6 +82,8 @@ const native: TranslationStrings = { 'native.lock.setting': 'Zamknout pomocí Face ID nebo kódu', 'native.lock.settingHint': 'Zeptá se při otevření TREK a po půl minutě na pozadí a skryje aplikaci v přepínači aplikací.', + 'native.share.title': 'Importovat do které cesty?', + 'native.share.noTrips': 'Zatím žádná cesta. Nejdřív nějakou vytvořte a pak dokument sdílejte znovu.', }; export default native; diff --git a/shared/src/i18n/de/native.ts b/shared/src/i18n/de/native.ts index 4aac52592..39444941e 100644 --- a/shared/src/i18n/de/native.ts +++ b/shared/src/i18n/de/native.ts @@ -83,6 +83,8 @@ const native: TranslationStrings = { 'native.lock.setting': 'Mit Face ID oder Code sperren', 'native.lock.settingHint': 'Fragt beim Öffnen und nach einer halben Minute im Hintergrund nach und verbirgt TREK im App-Umschalter.', + 'native.share.title': 'In welchen Trip importieren?', + 'native.share.noTrips': 'Noch kein Trip. Lege zuerst einen an und teile das Dokument dann erneut.', }; export default native; diff --git a/shared/src/i18n/en/native.ts b/shared/src/i18n/en/native.ts index 31f603099..35b668677 100644 --- a/shared/src/i18n/en/native.ts +++ b/shared/src/i18n/en/native.ts @@ -82,6 +82,8 @@ const native: TranslationStrings = { 'native.lock.setting': 'Lock with Face ID or passcode', 'native.lock.settingHint': 'Asks when TREK opens and after half a minute in the background, and hides the app in the app switcher.', + 'native.share.title': 'Import into which trip?', + 'native.share.noTrips': 'No trip yet. Create one first, then share the document again.', }; export default native; diff --git a/shared/src/i18n/es/native.ts b/shared/src/i18n/es/native.ts index 4279a01f8..d54810e8a 100644 --- a/shared/src/i18n/es/native.ts +++ b/shared/src/i18n/es/native.ts @@ -83,6 +83,8 @@ const native: TranslationStrings = { 'native.lock.setting': 'Bloquear con Face ID o código', 'native.lock.settingHint': 'Lo pide al abrir TREK y tras medio minuto en segundo plano, y oculta la app en el selector de apps.', + 'native.share.title': '¿En qué viaje importar?', + 'native.share.noTrips': 'Aún no hay viajes. Crea uno primero y vuelve a compartir el documento.', }; export default native; diff --git a/shared/src/i18n/et/native.ts b/shared/src/i18n/et/native.ts index 39facd3c5..98ecfb60b 100644 --- a/shared/src/i18n/et/native.ts +++ b/shared/src/i18n/et/native.ts @@ -82,6 +82,8 @@ const native: TranslationStrings = { 'native.lock.setting': 'Lukusta Face ID või pääsukoodiga', 'native.lock.settingHint': 'Küsib TREK-i avamisel ja pärast poolt minutit taustal ning peidab rakenduse rakenduste vahetajas.', + 'native.share.title': 'Millisesse reisi importida?', + 'native.share.noTrips': 'Reise veel pole. Loo esmalt üks ja jaga dokumenti uuesti.', }; export default native; diff --git a/shared/src/i18n/fr/native.ts b/shared/src/i18n/fr/native.ts index 5329ee437..4a4fd48d7 100644 --- a/shared/src/i18n/fr/native.ts +++ b/shared/src/i18n/fr/native.ts @@ -83,6 +83,8 @@ const native: TranslationStrings = { 'native.lock.setting': 'Verrouiller avec Face ID ou code', 'native.lock.settingHint': 'Le demande à l’ouverture de TREK et après une demi-minute en arrière-plan, et masque l’app dans le sélecteur d’apps.', + 'native.share.title': 'Importer dans quel voyage ?', + 'native.share.noTrips': 'Pas encore de voyage. Créez-en un, puis partagez à nouveau le document.', }; export default native; diff --git a/shared/src/i18n/gr/native.ts b/shared/src/i18n/gr/native.ts index 312b9dbbb..f666f08ee 100644 --- a/shared/src/i18n/gr/native.ts +++ b/shared/src/i18n/gr/native.ts @@ -85,6 +85,8 @@ const native: TranslationStrings = { 'native.lock.setting': 'Κλείδωμα με Face ID ή κωδικό', 'native.lock.settingHint': 'Ζητείται κατά το άνοιγμα του TREK και μετά από μισό λεπτό στο παρασκήνιο, και η εφαρμογή κρύβεται στην εναλλαγή εφαρμογών.', + 'native.share.title': 'Εισαγωγή σε ποιο ταξίδι;', + 'native.share.noTrips': 'Δεν υπάρχει ακόμα ταξίδι. Δημιουργήστε ένα πρώτα και κοινοποιήστε ξανά το έγγραφο.', }; export default native; diff --git a/shared/src/i18n/he/native.ts b/shared/src/i18n/he/native.ts index e201b220d..da74576c8 100644 --- a/shared/src/i18n/he/native.ts +++ b/shared/src/i18n/he/native.ts @@ -80,6 +80,8 @@ const native: TranslationStrings = { 'native.lock.settingTitle': 'נעילת אפליקציה', 'native.lock.setting': 'נעילה עם Face ID או קוד', 'native.lock.settingHint': 'מבקש בעת פתיחת TREK ואחרי חצי דקה ברקע, ומסתיר את האפליקציה במחליף האפליקציות.', + 'native.share.title': 'לייבא לאיזה טיול?', + 'native.share.noTrips': 'אין עדיין טיול. צרו טיול ואז שתפו את המסמך שוב.', }; export default native; diff --git a/shared/src/i18n/hu/native.ts b/shared/src/i18n/hu/native.ts index 29dec6f7e..194b29540 100644 --- a/shared/src/i18n/hu/native.ts +++ b/shared/src/i18n/hu/native.ts @@ -84,6 +84,8 @@ const native: TranslationStrings = { 'native.lock.setting': 'Zárolás Face ID-val vagy kóddal', 'native.lock.settingHint': 'Rákérdez a TREK megnyitásakor és fél perc háttérben töltött idő után, és elrejti az alkalmazást az alkalmazásváltóban.', + 'native.share.title': 'Melyik utazásba importáljuk?', + 'native.share.noTrips': 'Még nincs utazás. Előbb hozz létre egyet, aztán oszd meg újra a dokumentumot.', }; export default native; diff --git a/shared/src/i18n/id/native.ts b/shared/src/i18n/id/native.ts index 8df8c449d..47e658e33 100644 --- a/shared/src/i18n/id/native.ts +++ b/shared/src/i18n/id/native.ts @@ -83,6 +83,8 @@ const native: TranslationStrings = { 'native.lock.setting': 'Kunci dengan Face ID atau kode sandi', 'native.lock.settingHint': 'Meminta saat TREK dibuka dan setelah setengah menit di latar belakang, serta menyembunyikan aplikasi di pengalih aplikasi.', + 'native.share.title': 'Impor ke perjalanan mana?', + 'native.share.noTrips': 'Belum ada perjalanan. Buat satu dulu, lalu bagikan dokumennya lagi.', }; export default native; diff --git a/shared/src/i18n/it/native.ts b/shared/src/i18n/it/native.ts index f245287a4..7891b8ec8 100644 --- a/shared/src/i18n/it/native.ts +++ b/shared/src/i18n/it/native.ts @@ -83,6 +83,8 @@ const native: TranslationStrings = { 'native.lock.setting': 'Blocca con Face ID o codice', 'native.lock.settingHint': 'Lo chiede all’apertura di TREK e dopo mezzo minuto in background, e nasconde l’app nel selettore delle app.', + 'native.share.title': 'Importare in quale viaggio?', + 'native.share.noTrips': 'Ancora nessun viaggio. Creane uno, poi condividi di nuovo il documento.', }; export default native; diff --git a/shared/src/i18n/ja/native.ts b/shared/src/i18n/ja/native.ts index 47c78932e..1c87a190d 100644 --- a/shared/src/i18n/ja/native.ts +++ b/shared/src/i18n/ja/native.ts @@ -83,6 +83,8 @@ const native: TranslationStrings = { 'native.lock.setting': 'Face IDまたはパスコードでロック', 'native.lock.settingHint': 'TREKを開いたときと、バックグラウンドで30秒経過したあとに確認し、アプリスイッチャーでは内容を隠します。', + 'native.share.title': 'どの旅行に取り込みますか?', + 'native.share.noTrips': 'まだ旅行がありません。先に作成してから、もう一度ドキュメントを共有してください。', }; export default native; diff --git a/shared/src/i18n/ko/native.ts b/shared/src/i18n/ko/native.ts index 806778b9c..522ba27aa 100644 --- a/shared/src/i18n/ko/native.ts +++ b/shared/src/i18n/ko/native.ts @@ -81,6 +81,8 @@ const native: TranslationStrings = { 'native.lock.setting': 'Face ID 또는 암호로 잠금', 'native.lock.settingHint': 'TREK을 열 때와 백그라운드에서 30초가 지난 후에 확인하며, 앱 전환기에서는 내용을 숨깁니다.', + 'native.share.title': '어느 여행으로 가져올까요?', + 'native.share.noTrips': '아직 여행이 없습니다. 먼저 여행을 만든 뒤 문서를 다시 공유하세요.', }; export default native; diff --git a/shared/src/i18n/nl/native.ts b/shared/src/i18n/nl/native.ts index 77194910e..430a3bbef 100644 --- a/shared/src/i18n/nl/native.ts +++ b/shared/src/i18n/nl/native.ts @@ -82,6 +82,8 @@ const native: TranslationStrings = { 'native.lock.setting': 'Vergrendelen met Face ID of toegangscode', 'native.lock.settingHint': 'Vraagt erom bij het openen van TREK en na een halve minuut op de achtergrond, en verbergt de app in de appkiezer.', + 'native.share.title': 'In welke reis importeren?', + 'native.share.noTrips': 'Nog geen reis. Maak er eerst een aan en deel het document dan opnieuw.', }; export default native; diff --git a/shared/src/i18n/pl/native.ts b/shared/src/i18n/pl/native.ts index 31c9153de..8b17f18f1 100644 --- a/shared/src/i18n/pl/native.ts +++ b/shared/src/i18n/pl/native.ts @@ -82,6 +82,8 @@ const native: TranslationStrings = { 'native.lock.setting': 'Blokuj za pomocą Face ID lub kodu', 'native.lock.settingHint': 'Pyta przy otwieraniu TREK i po pół minuty w tle oraz ukrywa aplikację w przełączniku aplikacji.', + 'native.share.title': 'Do której podróży zaimportować?', + 'native.share.noTrips': 'Nie ma jeszcze podróży. Najpierw utwórz podróż, a potem udostępnij dokument ponownie.', }; export default native; diff --git a/shared/src/i18n/ru/native.ts b/shared/src/i18n/ru/native.ts index f08233c3e..976e0a0dd 100644 --- a/shared/src/i18n/ru/native.ts +++ b/shared/src/i18n/ru/native.ts @@ -83,6 +83,8 @@ const native: TranslationStrings = { 'native.lock.setting': 'Блокировать с Face ID или кодом', 'native.lock.settingHint': 'Запрашивается при открытии TREK и через полминуты в фоне, а в переключателе приложений содержимое скрыто.', + 'native.share.title': 'В какую поездку импортировать?', + 'native.share.noTrips': 'Поездок пока нет. Сначала создайте поездку, затем снова поделитесь документом.', }; export default native; diff --git a/shared/src/i18n/sk/native.ts b/shared/src/i18n/sk/native.ts index 85a19799d..a140f0352 100644 --- a/shared/src/i18n/sk/native.ts +++ b/shared/src/i18n/sk/native.ts @@ -82,6 +82,8 @@ const native: TranslationStrings = { 'native.lock.setting': 'Zamknúť pomocou Face ID alebo kódu', 'native.lock.settingHint': 'Opýta sa pri otvorení TREK a po pol minúte na pozadí a skryje aplikáciu v prepínači aplikácií.', + 'native.share.title': 'Importovať do ktorej cesty?', + 'native.share.noTrips': 'Zatiaľ žiadna cesta. Najprv nejakú vytvorte a potom dokument zdieľajte znova.', }; export default native; diff --git a/shared/src/i18n/sv/native.ts b/shared/src/i18n/sv/native.ts index 51c460c96..fe3787c79 100644 --- a/shared/src/i18n/sv/native.ts +++ b/shared/src/i18n/sv/native.ts @@ -83,6 +83,8 @@ const native: TranslationStrings = { 'native.lock.setting': 'Lås med Face ID eller lösenkod', 'native.lock.settingHint': 'Frågar när TREK öppnas och efter en halv minut i bakgrunden, och döljer appen i appväxlaren.', + 'native.share.title': 'Importera till vilken resa?', + 'native.share.noTrips': 'Ingen resa ännu. Skapa en först och dela sedan dokumentet igen.', }; export default native; diff --git a/shared/src/i18n/th/native.ts b/shared/src/i18n/th/native.ts index 176131319..5d11811cb 100644 --- a/shared/src/i18n/th/native.ts +++ b/shared/src/i18n/th/native.ts @@ -80,6 +80,8 @@ const native: TranslationStrings = { 'native.lock.settingTitle': 'ล็อกแอป', 'native.lock.setting': 'ล็อกด้วย Face ID หรือรหัส', 'native.lock.settingHint': 'ถามเมื่อเปิด TREK และหลังจากอยู่เบื้องหลังครึ่งนาที และซ่อนแอปในตัวสลับแอป', + 'native.share.title': 'นำเข้าไปยังทริปไหน', + 'native.share.noTrips': 'ยังไม่มีทริป สร้างทริปก่อนแล้วแชร์เอกสารอีกครั้ง', }; export default native; diff --git a/shared/src/i18n/tr/native.ts b/shared/src/i18n/tr/native.ts index 06e87ba05..deebeaf4e 100644 --- a/shared/src/i18n/tr/native.ts +++ b/shared/src/i18n/tr/native.ts @@ -83,6 +83,8 @@ const native: TranslationStrings = { 'native.lock.setting': 'Face ID veya parola ile kilitle', 'native.lock.settingHint': 'TREK açılırken ve arka planda yarım dakika sonra sorar, uygulamayı uygulama değiştiricide gizler.', + 'native.share.title': 'Hangi geziye aktarılsın?', + 'native.share.noTrips': 'Henüz gezi yok. Önce bir gezi oluşturun, sonra belgeyi yeniden paylaşın.', }; export default native; diff --git a/shared/src/i18n/uk/native.ts b/shared/src/i18n/uk/native.ts index 64dc63398..d2bb8f289 100644 --- a/shared/src/i18n/uk/native.ts +++ b/shared/src/i18n/uk/native.ts @@ -82,6 +82,8 @@ const native: TranslationStrings = { 'native.lock.setting': 'Блокувати за допомогою Face ID або коду', 'native.lock.settingHint': 'Запитує під час відкриття TREK і після пів хвилини у фоні, а в перемикачі застосунків вміст приховано.', + 'native.share.title': 'До якої подорожі імпортувати?', + 'native.share.noTrips': 'Подорожей ще немає. Спершу створіть подорож, а потім знову поділіться документом.', }; export default native; diff --git a/shared/src/i18n/vi/native.ts b/shared/src/i18n/vi/native.ts index 5902d6590..c8134c429 100644 --- a/shared/src/i18n/vi/native.ts +++ b/shared/src/i18n/vi/native.ts @@ -83,6 +83,8 @@ const native: TranslationStrings = { 'native.lock.setting': 'Khóa bằng Face ID hoặc mật mã', 'native.lock.settingHint': 'Hỏi khi mở TREK và sau nửa phút chạy nền, đồng thời ẩn ứng dụng trong trình chuyển ứng dụng.', + 'native.share.title': 'Nhập vào chuyến đi nào?', + 'native.share.noTrips': 'Chưa có chuyến đi nào. Hãy tạo một chuyến trước rồi chia sẻ lại tài liệu.', }; export default native; diff --git a/shared/src/i18n/zh-TW/native.ts b/shared/src/i18n/zh-TW/native.ts index 71ba73f2c..e781ff8f3 100644 --- a/shared/src/i18n/zh-TW/native.ts +++ b/shared/src/i18n/zh-TW/native.ts @@ -80,6 +80,8 @@ const native: TranslationStrings = { 'native.lock.settingTitle': 'App 鎖定', 'native.lock.setting': '使用 Face ID 或密碼鎖定', 'native.lock.settingHint': '開啟 TREK 時以及在背景停留半分鐘後會要求驗證,並在 App 切換器中隱藏內容。', + 'native.share.title': '要匯入到哪個行程?', + 'native.share.noTrips': '還沒有行程。請先建立一個,然後再次分享該文件。', }; export default native; diff --git a/shared/src/i18n/zh/native.ts b/shared/src/i18n/zh/native.ts index b7f9e74ec..3e6a8cc2d 100644 --- a/shared/src/i18n/zh/native.ts +++ b/shared/src/i18n/zh/native.ts @@ -80,6 +80,8 @@ const native: TranslationStrings = { 'native.lock.settingTitle': '应用锁', 'native.lock.setting': '使用面容 ID 或密码锁定', 'native.lock.settingHint': '打开 TREK 时以及在后台停留半分钟后会要求验证,并在应用切换器中隐藏内容。', + 'native.share.title': '导入到哪个行程?', + 'native.share.noTrips': '还没有行程。请先创建一个,然后再次分享该文档。', }; export default native; From 30158cddc302e251ce2c0b628019aa6d992c0aa4 Mon Sep 17 00:00:00 2001 From: Maurice Date: Fri, 6 Nov 2026 13:33:57 +0100 Subject: [PATCH 071/589] feat(push): accept the TREK apps' push relay as a push service The apps subscribe to Web Push like a browser, with their own key pair, but with an endpoint on liketrek's relay: only liketrek holds the apps' APNs and FCM keys. The server encrypts exactly as for a browser (RFC 8291), so the relay hands on ciphertext it cannot read and the device decrypts it. Lookalike hosts stay refused. --- .../src/nest/notifications/push/push-subscription.helpers.ts | 5 +++++ .../nest/notifications/push-subscriptions.service.test.ts | 4 ++++ 2 files changed, 9 insertions(+) diff --git a/server/src/nest/notifications/push/push-subscription.helpers.ts b/server/src/nest/notifications/push/push-subscription.helpers.ts index 08ab050fc..4979ad3f7 100644 --- a/server/src/nest/notifications/push/push-subscription.helpers.ts +++ b/server/src/nest/notifications/push/push-subscription.helpers.ts @@ -20,6 +20,11 @@ export const PUSH_SERVICE_HOSTS: readonly string[] = [ 'push.services.mozilla.com', // Safari on macOS, and Home Screen apps on iOS and iPadOS 16.4+. 'web.push.apple.com', + // The TREK apps' push relay. The app subscribes with its own key pair, the + // server encrypts exactly as for a browser, and the relay hands the ciphertext + // to Apple or Google, so it never reads a notification. Only liketrek holds + // the apps' APNs and FCM keys, which is why every server goes through it. + 'push.liketrek.com', ]; /** Services that hand out per-region or per-cluster hosts under one domain. */ diff --git a/server/tests/unit/nest/notifications/push-subscriptions.service.test.ts b/server/tests/unit/nest/notifications/push-subscriptions.service.test.ts index 5226d3fad..f3506c190 100644 --- a/server/tests/unit/nest/notifications/push-subscriptions.service.test.ts +++ b/server/tests/unit/nest/notifications/push-subscriptions.service.test.ts @@ -80,6 +80,8 @@ describe('checkPushEndpoint / checkPushSubscription', () => { 'https://web.push.apple.com/QGx9', 'https://api.push.apple.com/3/device/x', 'https://wns2-par02p.notify.windows.com/w/?token=BQYAAA', + // The TREK apps' relay, which hands the ciphertext on to Apple or Google. + 'https://push.liketrek.com/v1/apns/production/abc123', ]) { expect(checkPushEndpoint(endpoint), endpoint).toBe('ok'); expect(isPushServiceEndpoint(endpoint)).toBe(true); @@ -117,6 +119,8 @@ describe('checkPushEndpoint / checkPushSubscription', () => { 'https://evilnotify.windows.com/x', 'https://.notify.windows.com/x', 'https://push.apple.com/x', + 'https://push.liketrek.com.evil.test/v1/apns/x', + 'https://evilpush.liketrek.com/v1/apns/x', ]) { expect(checkPushEndpoint(endpoint), endpoint).not.toBe('ok'); } From ad69bbf4a96e90e8a4566e9b78c75eca8f81cacf Mon Sep 17 00:00:00 2001 From: Maurice Date: Fri, 6 Nov 2026 13:37:59 +0100 Subject: [PATCH 072/589] feat(native): push inside the iOS app, through an encrypted relay The app subscribes to Web Push like a browser, only the app makes the subscription: it asks for permission, registers with APNs and keeps its own P-256 key pair and auth secret in a keychain group a notification extension can share. The endpoint is liketrek's relay for this device's token, so the server encrypts exactly as for a browser and nobody on the way can read the notification. The settings card, the test push, sign-in resync and the logout teardown all take this path where the binary has nativePush; a tapped notification opens the place it points at, also from a cold start. The App ID has push enabled, the app carries the aps-environment and keychain-group entitlements. --- client/ios/App/App/App.entitlements | 6 + client/ios/App/App/AppDelegate.swift | 29 +++- client/ios/App/App/TrekShellPlugin.swift | 176 ++++++++++++++++++++++- client/src/native/nativeApp.test.ts | 1 + client/src/native/nativeApp.ts | 3 + client/src/native/push.test.ts | 79 ++++++++++ client/src/native/push.ts | 84 +++++++++++ client/src/native/trekShell.ts | 8 ++ client/src/push/webPush.native.test.ts | 80 +++++++++++ client/src/push/webPush.ts | 42 ++++++ 10 files changed, 505 insertions(+), 3 deletions(-) create mode 100644 client/src/native/push.test.ts create mode 100644 client/src/native/push.ts create mode 100644 client/src/push/webPush.native.test.ts diff --git a/client/ios/App/App/App.entitlements b/client/ios/App/App/App.entitlements index 6631ffa6f..438bb014e 100644 --- a/client/ios/App/App/App.entitlements +++ b/client/ios/App/App/App.entitlements @@ -2,5 +2,11 @@ + aps-environment + production + keychain-access-groups + + $(AppIdentifierPrefix)com.liketrek.trek.shared + diff --git a/client/ios/App/App/AppDelegate.swift b/client/ios/App/App/AppDelegate.swift index fec95acae..28851fe93 100644 --- a/client/ios/App/App/AppDelegate.swift +++ b/client/ios/App/App/AppDelegate.swift @@ -1,16 +1,41 @@ import UIKit import Capacitor +import UserNotifications @UIApplicationMain -class AppDelegate: UIResponder, UIApplicationDelegate { +class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { - // Override point for customization after application launch. + // Taps on a TREK notification, and banners while the app is open. + UNUserNotificationCenter.current().delegate = self return true } + // MARK: - Push (TrekPush in TrekShellPlugin.swift) + + func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { + TrekPush.shared.didRegister(token: deviceToken) + } + + func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { + TrekPush.shared.didFail(error) + } + + func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, + withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { + completionHandler([.banner, .list, .sound]) + } + + func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, + withCompletionHandler completionHandler: @escaping () -> Void) { + if let url = response.notification.request.content.userInfo["url"] as? String { + TrekPush.shared.opened(url: url) + } + completionHandler() + } + func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. diff --git a/client/ios/App/App/TrekShellPlugin.swift b/client/ios/App/App/TrekShellPlugin.swift index e1c6f2a5f..7e6c620ed 100644 --- a/client/ios/App/App/TrekShellPlugin.swift +++ b/client/ios/App/App/TrekShellPlugin.swift @@ -1,6 +1,9 @@ import AuthenticationServices import Capacitor import CoreLocation +import CryptoKit +import Security +import UserNotifications import LocalAuthentication import UIKit import WebKit @@ -27,6 +30,8 @@ public class TrekShellPlugin: CAPPlugin, CAPBridgedPlugin, ASWebAuthenticationPr CAPPluginMethod(name: "startLocation", returnType: CAPPluginReturnPromise), CAPPluginMethod(name: "stopLocation", returnType: CAPPluginReturnPromise), CAPPluginMethod(name: "takeSharedFile", returnType: CAPPluginReturnPromise), + CAPPluginMethod(name: "registerPush", returnType: CAPPluginReturnPromise), + CAPPluginMethod(name: "takeOpenedPush", returnType: CAPPluginReturnPromise), ] /// What this binary offers the server's UI, raised with every native feature @@ -34,7 +39,7 @@ public class TrekShellPlugin: CAPPlugin, CAPBridgedPlugin, ASWebAuthenticationPr /// and a server can require a minimum (minNativeShellApi in /api/health/features). static let shellApi = 2 /// The native features by name, so the UI can turn each on by itself. - static let features: [String] = ["capabilities", "edgeBack", "tileCache", "biometricLock", "geolocation", "sharedFiles"] + static let features: [String] = ["capabilities", "edgeBack", "tileCache", "biometricLock", "geolocation", "sharedFiles", "nativePush"] // MARK: - Shared booking documents @@ -42,6 +47,35 @@ public class TrekShellPlugin: CAPPlugin, CAPBridgedPlugin, ASWebAuthenticationPr TrekSharedFiles.onReceive = { [weak self] file in DispatchQueue.main.async { self?.notifyListeners("sharedFile", data: file) } } + TrekPush.shared.onOpen = { [weak self] url in + DispatchQueue.main.async { self?.notifyListeners("pushOpened", data: ["url": url]) } + } + } + + // MARK: - Push + + /// Asks for permission, registers with APNs and answers with a Web Push + /// subscription the server stores like a browser's (native/push.ts): the + /// relay endpoint for this device's token, and this device's keys, which the + /// notification extension uses to decrypt. + @objc func registerPush(_ call: CAPPluginCall) { + TrekPush.shared.register { result in + switch result { + case .success(let subscription): call.resolve(subscription) + case .failure(let error): + let code = (error as? TrekPush.PushError) == .denied ? "DENIED" : "FAILED" + call.reject(error.localizedDescription, code) + } + } + } + + /// The notification the app was opened from, before the UI was there to hear of it. + @objc func takeOpenedPush(_ call: CAPPluginCall) { + if let url = TrekPush.shared.takeOpened() { + call.resolve(["url": url]) + } else { + call.resolve(["url": NSNull()]) + } } /// The document shared to TREK before the UI was there to hear of it. @@ -330,3 +364,143 @@ final class TrekLocation: NSObject, CLLocationManagerDelegate { emit(["error": ["code": code, "message": message]]) } } + +/// The app's side of TREK push: an APNs token, the device's Web Push keys in the +/// keychain group the notification extension shares, and the relay endpoint +/// that ties them together. +final class TrekPush { + static let shared = TrekPush() + static let relay = "https://push.liketrek.com/v1/apns" + /// The keychain group the notification extension reads the keys from. + static let keychainGroup = "com.liketrek.trek.shared" + + enum PushError: Error, Equatable { case denied, failed } + + private var pending: [(Result<[String: Any], Error>) -> Void] = [] + private var openedURL: String? + var onOpen: ((String) -> Void)? + + func register(_ done: @escaping (Result<[String: Any], Error>) -> Void) { + UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, _ in + guard granted else { + done(.failure(PushError.denied)) + return + } + DispatchQueue.main.async { + self.pending.append(done) + UIApplication.shared.registerForRemoteNotifications() + } + } + } + + func didRegister(token: Data) { + let hex = token.map { String(format: "%02x", $0) }.joined() + #if DEBUG + let environment = "sandbox" + #else + let environment = "production" + #endif + let result: Result<[String: Any], Error> + if let keys = TrekPushKeys.loadOrCreate() { + result = .success([ + "endpoint": "\(TrekPush.relay)/\(environment)/\(hex)", + "keys": ["p256dh": keys.publicKey, "auth": keys.auth], + ]) + } else { + result = .failure(PushError.failed) + } + let waiting = pending + pending.removeAll() + waiting.forEach { $0(result) } + } + + func didFail(_ error: Error) { + let waiting = pending + pending.removeAll() + waiting.forEach { $0(.failure(error)) } + } + + func opened(url: String) { + if let onOpen { onOpen(url) } else { openedURL = url } + } + + func takeOpened() -> String? { + defer { openedURL = nil } + return openedURL + } +} + +/// The device's Web Push key pair (P-256) and auth secret, kept in the shared +/// keychain group so the notification extension can decrypt what the server +/// encrypted for them (RFC 8291). Base64url without padding, as the server reads them. +enum TrekPushKeys { + private static let privateKeyAccount = "push.privateKey" + private static let authAccount = "push.auth" + + static func loadOrCreate() -> (publicKey: String, auth: String)? { + if let raw = read(privateKeyAccount), let auth = read(authAccount), + let key = try? P256.KeyAgreement.PrivateKey(rawRepresentation: raw) { + return (base64url(key.publicKey.x963Representation), base64url(auth)) + } + let key = P256.KeyAgreement.PrivateKey() + var auth = Data(count: 16) + let status = auth.withUnsafeMutableBytes { SecRandomCopyBytes(kSecRandomDefault, 16, $0.baseAddress!) } + guard status == errSecSuccess, write(privateKeyAccount, key.rawRepresentation), write(authAccount, auth) else { return nil } + return (base64url(key.publicKey.x963Representation), base64url(auth)) + } + + private static func query(_ account: String) -> [String: Any] { + [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: "com.liketrek.trek.push", + kSecAttrAccount as String: account, + kSecAttrAccessGroup as String: accessGroup, + ] + } + + /// The team-prefixed group, read from the app's own entitlement at runtime. + private static var accessGroup: String { + let probe: [String: Any] = [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrAccount as String: "push.groupProbe", + kSecAttrService as String: "com.liketrek.trek.push", + kSecReturnAttributes as String: true, + ] + var result: CFTypeRef? + var status = SecItemCopyMatching(probe as CFDictionary, &result) + if status == errSecItemNotFound { + var add = probe + add.removeValue(forKey: kSecReturnAttributes as String) + add[kSecValueData as String] = Data() + SecItemAdd(add as CFDictionary, nil) + status = SecItemCopyMatching(probe as CFDictionary, &result) + } + // The default group is the first one in the entitlement: "TEAMID.com.liketrek.trek.shared". + if status == errSecSuccess, let attributes = result as? [String: Any], + let group = attributes[kSecAttrAccessGroup as String] as? String, + let prefix = group.split(separator: ".").first { + return "\(prefix).\(TrekPush.keychainGroup)" + } + return TrekPush.keychainGroup + } + + private static func read(_ account: String) -> Data? { + var q = query(account) + q[kSecReturnData as String] = true + var result: CFTypeRef? + return SecItemCopyMatching(q as CFDictionary, &result) == errSecSuccess ? result as? Data : nil + } + + private static func write(_ account: String, _ data: Data) -> Bool { + SecItemDelete(query(account) as CFDictionary) + var q = query(account) + q[kSecValueData as String] = data + q[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlock + return SecItemAdd(q as CFDictionary, nil) == errSecSuccess + } + + static func base64url(_ data: Data) -> String { + data.base64EncodedString().replacingOccurrences(of: "+", with: "-").replacingOccurrences(of: "/", with: "_") + .replacingOccurrences(of: "=", with: "") + } +} diff --git a/client/src/native/nativeApp.test.ts b/client/src/native/nativeApp.test.ts index f85b54f9d..885c05bfa 100644 --- a/client/src/native/nativeApp.test.ts +++ b/client/src/native/nativeApp.test.ts @@ -24,6 +24,7 @@ vi.mock('./capabilities', () => ({ })); vi.mock('./geolocation', () => ({ installNativeGeolocation: vi.fn() })); vi.mock('./sharedFiles', () => ({ startSharedFiles: vi.fn(async () => {}) })); +vi.mock('./push', () => ({ startNativePush: vi.fn(async () => {}) })); vi.mock('../mobile/overlayStack', () => ({ closeTopOverlay: vi.fn(() => false) })); function backButtonHandler(): (event: { canGoBack: boolean }) => void { diff --git a/client/src/native/nativeApp.ts b/client/src/native/nativeApp.ts index 091d439bf..dd50fd6f1 100644 --- a/client/src/native/nativeApp.ts +++ b/client/src/native/nativeApp.ts @@ -8,6 +8,7 @@ import { checkAppUpdate, loadNativeCapabilities } from './capabilities'; import { installNativeGeolocation } from './geolocation'; import { keepOfflineShellFresh } from './offlineShell'; import { isNativeApp, isNativeIos } from './platform'; +import { startNativePush } from './push'; import { reportNativeFailure } from './reportFailure'; import { startSharedFiles } from './sharedFiles'; import { isUnimplemented } from './trekShell'; @@ -30,6 +31,8 @@ export function startNativeApp(): void { void loadNativeCapabilities().then(() => installNativeGeolocation()); // Booking documents shared to TREK, waiting for a trip to import into. void startSharedFiles(); + // Taps on TREK notifications open the place they point at. + void loadNativeCapabilities().then(() => startNativePush()); // A tap on the status bar scrolls the list under it back to the top, as in // every iOS app (the status-bar plugin fires statusTap on iOS). diff --git a/client/src/native/push.test.ts b/client/src/native/push.test.ts new file mode 100644 index 000000000..ff903e8a0 --- /dev/null +++ b/client/src/native/push.test.ts @@ -0,0 +1,79 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { hasNativeFeature } from './capabilities'; +import { isNativeIos } from './platform'; +import { + NativePushDenied, + forgetNativePush, + nativePushActive, + nativePushEndpoint, + openPushTarget, + registerNativePush, + startNativePush, +} from './push'; +import { TrekShell } from './trekShell'; + +vi.mock('./platform', () => ({ isNativeIos: vi.fn() })); +vi.mock('./capabilities', () => ({ hasNativeFeature: vi.fn() })); +vi.mock('./trekShell', () => ({ + TrekShell: { + registerPush: vi.fn(), + takeOpenedPush: vi.fn(), + addListener: vi.fn(async () => ({ remove: async () => {} })), + }, +})); + +const SUB = { + endpoint: 'https://push.liketrek.com/v1/apns/production/abcd', + keys: { p256dh: 'BPk', auth: 'aa' }, +}; + +beforeEach(() => { + window.localStorage.clear(); + vi.mocked(isNativeIos).mockReturnValue(true); + vi.mocked(hasNativeFeature).mockReturnValue(true); + vi.mocked(TrekShell.registerPush).mockReset().mockResolvedValue(SUB); + vi.mocked(TrekShell.takeOpenedPush).mockReset().mockResolvedValue({ url: null }); + window.history.replaceState({}, '', '/dashboard'); +}); + +describe('native push', () => { + it('is on only in an iOS binary that has it', () => { + expect(nativePushActive()).toBe(true); + vi.mocked(hasNativeFeature).mockReturnValue(false); + expect(nativePushActive()).toBe(false); + }); + + it('remembers the relay endpoint it subscribed with, and forgets it again', async () => { + expect(await registerNativePush()).toEqual(SUB); + expect(nativePushEndpoint()).toBe(SUB.endpoint); + forgetNativePush(); + expect(nativePushEndpoint()).toBeNull(); + }); + + it('tells a refused permission apart from a failure', async () => { + vi.mocked(TrekShell.registerPush).mockRejectedValue({ code: 'DENIED' }); + await expect(registerNativePush()).rejects.toBeInstanceOf(NativePushDenied); + vi.mocked(TrekShell.registerPush).mockRejectedValue(new Error('apns down')); + await expect(registerNativePush()).rejects.toThrow('apns down'); + expect(nativePushEndpoint()).toBeNull(); + }); + + it('opens a tapped notification inside the app, and never another origin', () => { + const pops = vi.fn(); + window.addEventListener('popstate', pops); + openPushTarget('/trips/12?tab=chat'); + expect(window.location.pathname).toBe('/trips/12'); + expect(window.location.search).toBe('?tab=chat'); + openPushTarget('https://evil.example/phish'); + expect(window.location.pathname).toBe('/trips/12'); + expect(pops).toHaveBeenCalledTimes(1); + window.removeEventListener('popstate', pops); + }); + + it('follows the notification the app was opened from', async () => { + vi.mocked(TrekShell.takeOpenedPush).mockResolvedValue({ url: '/trips/3' }); + await startNativePush(); + expect(window.location.pathname).toBe('/trips/3'); + expect(TrekShell.addListener).toHaveBeenCalledWith('pushOpened', expect.any(Function)); + }); +}); diff --git a/client/src/native/push.ts b/client/src/native/push.ts new file mode 100644 index 000000000..628d125df --- /dev/null +++ b/client/src/native/push.ts @@ -0,0 +1,84 @@ +import type { PushSubscriptionInput } from '@trek/shared'; +import { hasNativeFeature } from './capabilities'; +import { isNativeIos } from './platform'; +import { reportNativeFailure } from './reportFailure'; +import { TrekShell } from './trekShell'; + +/** + * Push inside the app: the same Web Push subscription a browser makes, only + * the app makes it (TrekShell.registerPush). Its endpoint is liketrek's relay + * for this device's APNs token and its keys live on the device, so the server + * encrypts exactly as for a browser and the relay hands on ciphertext that the + * app's notification extension decrypts. push/webPush.ts takes this path + * wherever the binary reports the nativePush feature; the settings card, the + * test push and the logout teardown stay what they are. + * + * The endpoint is remembered on the device, the way a browser remembers its + * subscription, so the card can say on or off and the logout can name it. + */ +const KEY = 'trek.nativePushEndpoint'; + +export function nativePushActive(): boolean { + return isNativeIos() && hasNativeFeature('nativePush'); +} + +export function nativePushEndpoint(): string | null { + try { + return window.localStorage.getItem(KEY); + } catch { + return null; + } +} + +function rememberEndpoint(endpoint: string | null): void { + try { + if (endpoint) window.localStorage.setItem(KEY, endpoint); + else window.localStorage.removeItem(KEY); + } catch { + // Storage refused: the card then reads off and offers to switch it on again. + } +} + +export class NativePushDenied extends Error {} + +/** Permission, APNs and the device keys, as a subscription the server can store. */ +export async function registerNativePush(): Promise { + try { + const subscription = await TrekShell.registerPush(); + rememberEndpoint(subscription.endpoint); + return subscription; + } catch (err) { + if ((err as { code?: string } | null)?.code === 'DENIED') throw new NativePushDenied(); + throw err; + } +} + +export function forgetNativePush(): void { + rememberEndpoint(null); +} + +/** Opens the place a tapped notification points at, inside the app's own routing. */ +export function openPushTarget(url: string): void { + let target: URL; + try { + target = new URL(url, window.location.origin); + } catch { + return; + } + // Only this server's pages: a notification never navigates the app elsewhere. + if (target.origin !== window.location.origin) return; + window.history.pushState({}, '', `${target.pathname}${target.search}${target.hash}`); + window.dispatchEvent(new PopStateEvent('popstate')); +} + +/** Follows taps on notifications, including the one the app was opened from. */ +export async function startNativePush(): Promise { + if (!nativePushActive()) return; + void TrekShell.addListener('pushOpened', ({ url }) => openPushTarget(url)); + try { + const { url } = await TrekShell.takeOpenedPush(); + if (url) openPushTarget(url); + } catch (err) { + reportNativeFailure(err); + } +} diff --git a/client/src/native/trekShell.ts b/client/src/native/trekShell.ts index 097323b60..3d2d044e7 100644 --- a/client/src/native/trekShell.ts +++ b/client/src/native/trekShell.ts @@ -55,6 +55,14 @@ export interface TrekShellPlugin { ): Promise<{ remove: () => Promise }>; /** Feature sharedFiles: the booking document shared to TREK before the UI ran. */ takeSharedFile(): Promise<{ file: SharedFilePayload | null }>; + /** Feature nativePush: permission, APNs and the device keys, as a Web Push subscription. Rejects with DENIED. */ + registerPush(): Promise<{ endpoint: string; keys: { p256dh: string; auth: string } }>; + /** Feature nativePush: the notification the app was opened from, before the UI ran. */ + takeOpenedPush(): Promise<{ url: string | null }>; + addListener( + event: 'pushOpened', + listener: (payload: { url: string }) => void + ): Promise<{ remove: () => Promise }>; } /** A document shared to TREK, as the native side reads it. */ diff --git a/client/src/push/webPush.native.test.ts b/client/src/push/webPush.native.test.ts new file mode 100644 index 000000000..5119fbc9d --- /dev/null +++ b/client/src/push/webPush.native.test.ts @@ -0,0 +1,80 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { pushApi } from '../api/push'; +import { + NativePushDenied, + forgetNativePush, + nativePushActive, + nativePushEndpoint, + registerNativePush, +} from '../native/push'; +import { + WebPushError, + disableWebPush, + enableWebPush, + forgetPushDeviceOnLogout, + getWebPushSupport, + readWebPushDeviceState, +} from './webPush'; + +vi.mock('../native/push', () => { + class NativePushDenied extends Error {} + return { + NativePushDenied, + nativePushActive: vi.fn(), + nativePushEndpoint: vi.fn(), + registerNativePush: vi.fn(), + forgetNativePush: vi.fn(), + }; +}); +vi.mock('../api/push', () => ({ pushApi: { subscribe: vi.fn(), unsubscribe: vi.fn(), getPublicKey: vi.fn() } })); + +const SUB = { endpoint: 'https://push.liketrek.com/v1/apns/production/abcd', keys: { p256dh: 'BPk', auth: 'aa' } }; + +beforeEach(() => { + vi.clearAllMocks(); + vi.mocked(nativePushActive).mockReturnValue(true); + vi.mocked(nativePushEndpoint).mockReturnValue(null); + vi.mocked(registerNativePush).mockResolvedValue(SUB); + vi.mocked(pushApi.subscribe).mockResolvedValue(undefined as never); + vi.mocked(pushApi.unsubscribe).mockResolvedValue(undefined as never); + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response(null, { status: 204 })) + ); +}); + +describe('web push inside the app', () => { + it('counts as supported without a service worker, and reads on or off from the remembered endpoint', async () => { + expect(getWebPushSupport()).toEqual({ supported: true, reason: null }); + expect(await readWebPushDeviceState()).toBe('off'); + vi.mocked(nativePushEndpoint).mockReturnValue(SUB.endpoint); + expect(await readWebPushDeviceState()).toBe('on'); + }); + + it('switches on with the app subscription, and rolls it back when the server refuses', async () => { + await enableWebPush('server-key'); + expect(pushApi.subscribe).toHaveBeenCalledWith(SUB); + + vi.mocked(pushApi.subscribe).mockRejectedValueOnce(new Error('400')); + await expect(enableWebPush('server-key')).rejects.toBeInstanceOf(WebPushError); + expect(forgetNativePush).toHaveBeenCalled(); + }); + + it('reads a refused permission as denied', async () => { + vi.mocked(registerNativePush).mockRejectedValue(new NativePushDenied()); + await expect(enableWebPush('server-key')).rejects.toMatchObject({ code: 'denied' }); + }); + + it('switches off and forgets the device at logout through the endpoint it remembers', async () => { + vi.mocked(nativePushEndpoint).mockReturnValue(SUB.endpoint); + await disableWebPush(); + expect(pushApi.unsubscribe).toHaveBeenCalledWith(SUB.endpoint); + expect(forgetNativePush).toHaveBeenCalled(); + + await forgetPushDeviceOnLogout(500); + expect(fetch).toHaveBeenCalledWith( + '/api/notifications/push/subscriptions', + expect.objectContaining({ method: 'DELETE' }) + ); + }); +}); diff --git a/client/src/push/webPush.ts b/client/src/push/webPush.ts index b394cb810..c470be6d1 100644 --- a/client/src/push/webPush.ts +++ b/client/src/push/webPush.ts @@ -2,6 +2,7 @@ import type { PushSubscriptionInput, PushUnsubscribeRequest } from '@trek/shared import { pushApi } from '../api/push' import { isEffectivelyOffline } from '../sync/networkMode' import { isIosDevice, isIosStandalone } from '../utils/iosDevice' +import { NativePushDenied, forgetNativePush, nativePushActive, nativePushEndpoint, registerNativePush } from '../native/push' /** * Web Push on this device: whether it can work here, and switching it on and @@ -72,6 +73,9 @@ function hasPushApis(): boolean { */ export function getWebPushSupport(): WebPushSupport { if (typeof window === 'undefined') return unsupported('unsupported') + // Inside the app the app makes the subscription (native/push.ts), with no + // service worker and no Notification API in the WebView. + if (nativePushActive()) return { supported: true, reason: null } // A service worker, and push with it, exists only in a secure context: HTTPS, // or localhost while developing. A plain http LAN address never gets one. if (window.isSecureContext === false) return unsupported('insecure') @@ -175,6 +179,7 @@ export async function loadPushPublicKey(): Promise { /** What the settings card shows for this device. Never rejects. */ export async function readWebPushDeviceState(): Promise { + if (nativePushActive()) return nativePushEndpoint() ? 'on' : 'off' const { reason } = getWebPushSupport() if (reason) return reason if (getPushPermission() === 'denied') return 'denied' @@ -215,6 +220,7 @@ async function subscribeWithKey( * spend it. The permission request is therefore the first thing that runs. */ export async function enableWebPush(publicKey: string, registration?: ServiceWorkerRegistration | null): Promise { + if (nativePushActive()) return enableNativePush() const permission = Notification.permission === 'granted' ? 'granted' : await Notification.requestPermission() if (permission === 'denied') throw new WebPushError('denied') @@ -247,6 +253,12 @@ export async function enableWebPush(publicKey: string, registration?: ServiceWor * push service answers 404 or 410 for on its next send. */ export async function disableWebPush(): Promise { + if (nativePushActive()) { + const endpoint = nativePushEndpoint() + if (endpoint) await bestEffort('forgetting the device on the server', () => pushApi.unsubscribe(endpoint)) + forgetNativePush() + return + } const subscription = await currentPushSubscription() if (!subscription) return await bestEffort('forgetting the device on the server', () => pushApi.unsubscribe(subscription.endpoint)) @@ -265,6 +277,12 @@ export async function disableWebPush(): Promise { * to switch it on. Never rejects. */ export async function resyncPushSubscription(): Promise { + if (nativePushActive()) { + // The app's subscription carries no server key, so only the row is restored. + if (!nativePushEndpoint() || isEffectivelyOffline()) return + await bestEffort('re-registering this device', async () => pushApi.subscribe(await registerNativePush())) + return + } if (!getWebPushSupport().supported || getPushPermission() !== 'granted' || isEffectivelyOffline()) return await bestEffort('re-registering this device', async () => { const registration = await existingRegistration() @@ -325,6 +343,14 @@ async function forgetOnServerAtLogout(endpoint: string, timeoutMs: number): Prom * or 410. */ export async function forgetPushDeviceOnLogout(timeoutMs = LOGOUT_PUSH_TIMEOUT_MS): Promise { + if (nativePushActive()) { + const endpoint = nativePushEndpoint() + forgetNativePush() + if (endpoint) { + await withTimeout(bestEffort('forgetting this device at logout', () => forgetOnServerAtLogout(endpoint, timeoutMs)), timeoutMs, undefined) + } + return + } if (!hasPushApis()) return const teardown = bestEffort('forgetting this device at logout', async () => { const subscription = await currentPushSubscription() @@ -336,3 +362,19 @@ export async function forgetPushDeviceOnLogout(timeoutMs = LOGOUT_PUSH_TIMEOUT_M }) await withTimeout(teardown, timeoutMs, undefined) } + +/** Push on for the app: its own subscription, then the server, rolled back if the server refuses. */ +async function enableNativePush(): Promise { + let subscription: PushSubscriptionInput + try { + subscription = await registerNativePush() + } catch (err) { + throw new WebPushError(err instanceof NativePushDenied ? 'denied' : 'failed', err) + } + try { + await pushApi.subscribe(subscription) + } catch (err) { + forgetNativePush() + throw err instanceof WebPushError ? err : new WebPushError('failed', err) + } +} From c6f91716a464434a0a833ac0fcf28ed1082f6d32 Mon Sep 17 00:00:00 2001 From: Maurice Date: Fri, 6 Nov 2026 13:41:42 +0100 Subject: [PATCH 073/589] feat(native): a notification extension that decrypts TREK pushes on the device The relay hands APNs the encrypted record with a placeholder text and mutable-content set; the new Notification Service Extension opens it with the device's Web Push keys from the shared keychain group (RFC 8291 on CryptoKit) and shows the real title, text and link. Without the keys the placeholder stays, so a notification arrives either way and nothing on the way reads it. The target came in through ios/scripts/add-extension.rb (kept, idempotent), its App ID is registered, and the release lane signs every target with its own App Store profile. Web Push payloads now stop at 2800 bytes so the encrypted, base64-encoded record still fits Apple's 4 KB. --- .github/workflows/native.yml | 2 +- client/fastlane/Fastfile | 46 +++-- client/ios/App/App.xcodeproj/project.pbxproj | 180 +++++++++++++++++- client/ios/App/NotificationService/Info.plist | 31 +++ .../NotificationService.entitlements | 10 + .../NotificationService.swift | 109 +++++++++++ client/ios/scripts/add-extension.rb | 74 +++++++ .../transports/web-push.service.ts | 6 +- 8 files changed, 436 insertions(+), 22 deletions(-) create mode 100644 client/ios/App/NotificationService/Info.plist create mode 100644 client/ios/App/NotificationService/NotificationService.entitlements create mode 100644 client/ios/App/NotificationService/NotificationService.swift create mode 100644 client/ios/scripts/add-extension.rb diff --git a/.github/workflows/native.yml b/.github/workflows/native.yml index a76946f3e..8c3a94cbc 100644 --- a/.github/workflows/native.yml +++ b/.github/workflows/native.yml @@ -103,7 +103,7 @@ jobs: xcodebuild -version - name: Check the property lists - run: plutil -lint client/ios/App/App/Info.plist client/ios/ExportOptions.plist + run: plutil -lint client/ios/App/App/Info.plist client/ios/ExportOptions.plist client/ios/App/NotificationService/Info.plist client/ios/App/NotificationService/NotificationService.entitlements client/ios/App/App/App.entitlements - uses: actions/setup-node@v6 with: diff --git a/client/fastlane/Fastfile b/client/fastlane/Fastfile index ac8b49b1a..4a867a8cf 100644 --- a/client/fastlane/Fastfile +++ b/client/fastlane/Fastfile @@ -18,6 +18,14 @@ default_platform(:ios) APP_IDENTIFIER = "com.liketrek.trek" PROJECT = "ios/App/App.xcodeproj" +# Every signed target with its bundle identifier: the app and its extensions +# (ios/scripts/add-extension.rb put them in the project). Each gets its own App +# Store profile, created or reused through the API key like the app's. +SIGNED_TARGETS = { + "App" => APP_IDENTIFIER, + "NotificationService" => "com.liketrek.trek.notifications", +} + platform :ios do desc "Build the signed Release app and upload it to TestFlight (internal testing)." lane :beta do @@ -54,23 +62,27 @@ platform :ios do keychain_path: keychain_path, keychain_password: keychain_password, ) - get_provisioning_profile( - api_key: key, - app_identifier: APP_IDENTIFIER, - development: false, - ) + profiles = {} + SIGNED_TARGETS.each do |target, identifier| + get_provisioning_profile( + api_key: key, + app_identifier: identifier, + development: false, + ) + profiles[identifier] = lane_context[SharedValues::SIGH_NAME] - # Pin the project to that profile for this build; automatic signing stays the default - # a developer sees when they open the project in Xcode. - update_code_signing_settings( - path: PROJECT, - use_automatic_signing: false, - team_id: ENV.fetch("APPLE_TEAM_ID"), - code_sign_identity: "Apple Distribution", - bundle_identifier: APP_IDENTIFIER, - profile_name: lane_context[SharedValues::SIGH_NAME], - targets: ["App"], - ) + # Pin each target to its profile for this build; automatic signing stays the + # default a developer sees when they open the project in Xcode. + update_code_signing_settings( + path: PROJECT, + use_automatic_signing: false, + team_id: ENV.fetch("APPLE_TEAM_ID"), + code_sign_identity: "Apple Distribution", + bundle_identifier: identifier, + profile_name: profiles[identifier], + targets: [target], + ) + end build_app( project: PROJECT, @@ -84,7 +96,7 @@ platform :ios do ].join(" "), export_options: { signingStyle: "manual", - provisioningProfiles: { APP_IDENTIFIER => lane_context[SharedValues::SIGH_NAME] }, + provisioningProfiles: profiles, }, ) diff --git a/client/ios/App/App.xcodeproj/project.pbxproj b/client/ios/App/App.xcodeproj/project.pbxproj index d2dc88309..ea319b7f2 100644 --- a/client/ios/App/App.xcodeproj/project.pbxproj +++ b/client/ios/App/App.xcodeproj/project.pbxproj @@ -7,6 +7,7 @@ objects = { /* Begin PBXBuildFile section */ + 2CFE220A73ACB585F3D4CB8F /* UserNotifications.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 2EE43D236E661AA975612A4B /* UserNotifications.framework */; }; 2FAD9763203C412B000D30F8 /* config.xml in Resources */ = {isa = PBXBuildFile; fileRef = 2FAD9762203C412B000D30F8 /* config.xml */; }; 4D22ABE92AF431CB00220026 /* CapApp-SPM in Frameworks */ = {isa = PBXBuildFile; productRef = 4D22ABE82AF431CB00220026 /* CapApp-SPM */; }; 50379B232058CBB4000EE86E /* capacitor.config.json in Resources */ = {isa = PBXBuildFile; fileRef = 50379B222058CBB4000EE86E /* capacitor.config.json */; }; @@ -15,14 +16,43 @@ 504EC30F1FED79650016851F /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 504EC30E1FED79650016851F /* Assets.xcassets */; }; 504EC3121FED79650016851F /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 504EC3101FED79650016851F /* LaunchScreen.storyboard */; }; 50B271D11FEDC1A000F3C39B /* public in Resources */ = {isa = PBXBuildFile; fileRef = 50B271D01FEDC1A000F3C39B /* public */; }; - 9582B6832FE993A70072D4E8 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9582B6822FE993A50072D4E8 /* SceneDelegate.swift */; }; 7A1E00032C0000000000A003 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = 7A1E00022C0000000000A002 /* PrivacyInfo.xcprivacy */; }; 7A1E00052C0000000000A005 /* TrekBridgeViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7A1E00042C0000000000A004 /* TrekBridgeViewController.swift */; }; 7A1E00072C0000000000A007 /* TrekShellPlugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7A1E00062C0000000000A006 /* TrekShellPlugin.swift */; }; + 84EB79E4B677229481809933 /* NotificationService.appex in Embed Foundation Extensions */ = {isa = PBXBuildFile; fileRef = A03A384FE54FAD1ED68E12DC /* NotificationService.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; }; + 9582B6832FE993A70072D4E8 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9582B6822FE993A50072D4E8 /* SceneDelegate.swift */; }; + A8FDD4DBE3F078BF935CC4B9 /* NotificationService.swift in Sources */ = {isa = PBXBuildFile; fileRef = FFA8802204810ED580DE46F3 /* NotificationService.swift */; }; /* End PBXBuildFile section */ +/* Begin PBXContainerItemProxy section */ + 3BB8A38B2B2C8614B24CF2AD /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 504EC2FC1FED79650016851F /* Project object */; + proxyType = 1; + remoteGlobalIDString = 9480DFBC2C2A112973DA468A; + remoteInfo = NotificationService; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + A8F12B42B22FCA041C6AA0DA /* Embed Foundation Extensions */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 13; + files = ( + 84EB79E4B677229481809933 /* NotificationService.appex in Embed Foundation Extensions */, + ); + name = "Embed Foundation Extensions"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + /* Begin PBXFileReference section */ + 1E7522315D47F086145DC4B8 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 2EE43D236E661AA975612A4B /* UserNotifications.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UserNotifications.framework; path = System/Library/Frameworks/UserNotifications.framework; sourceTree = SDKROOT; }; 2FAD9762203C412B000D30F8 /* config.xml */ = {isa = PBXFileReference; lastKnownFileType = text.xml; path = config.xml; sourceTree = ""; }; + 3DF4F4305878F949DD09193F /* NotificationService.entitlements */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.entitlements; path = NotificationService.entitlements; sourceTree = ""; }; 50379B222058CBB4000EE86E /* capacitor.config.json */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.json; path = capacitor.config.json; sourceTree = ""; }; 504EC3041FED79650016851F /* App.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = App.app; sourceTree = BUILT_PRODUCTS_DIR; }; 504EC3071FED79650016851F /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; @@ -31,12 +61,14 @@ 504EC3111FED79650016851F /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; 504EC3131FED79650016851F /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 50B271D01FEDC1A000F3C39B /* public */ = {isa = PBXFileReference; lastKnownFileType = folder; path = public; sourceTree = ""; }; - 9582B6822FE993A50072D4E8 /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = ""; }; - 958DCC722DB07C7200EA8C5F /* debug.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = debug.xcconfig; path = ../debug.xcconfig; sourceTree = SOURCE_ROOT; }; 7A1E00012C0000000000A001 /* App.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = App.entitlements; sourceTree = ""; }; 7A1E00022C0000000000A002 /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = PrivacyInfo.xcprivacy; sourceTree = ""; }; 7A1E00042C0000000000A004 /* TrekBridgeViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TrekBridgeViewController.swift; sourceTree = ""; }; 7A1E00062C0000000000A006 /* TrekShellPlugin.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TrekShellPlugin.swift; sourceTree = ""; }; + 9582B6822FE993A50072D4E8 /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = ""; }; + 958DCC722DB07C7200EA8C5F /* debug.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = debug.xcconfig; path = ../debug.xcconfig; sourceTree = SOURCE_ROOT; }; + A03A384FE54FAD1ED68E12DC /* NotificationService.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = NotificationService.appex; sourceTree = BUILT_PRODUCTS_DIR; }; + FFA8802204810ED580DE46F3 /* NotificationService.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = NotificationService.swift; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -48,15 +80,32 @@ ); runOnlyForDeploymentPostprocessing = 0; }; + C9AA4ADC0D397C620A35B6A3 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 2CFE220A73ACB585F3D4CB8F /* UserNotifications.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ + 0FC8613857BD976EB58ECE0B /* iOS */ = { + isa = PBXGroup; + children = ( + ); + name = iOS; + sourceTree = ""; + }; 504EC2FB1FED79650016851F = { isa = PBXGroup; children = ( 958DCC722DB07C7200EA8C5F /* debug.xcconfig */, 504EC3061FED79650016851F /* App */, 504EC3051FED79650016851F /* Products */, + 5198C9768EB9762A60701C92 /* Frameworks */, + 74C1FC6022E562372A71EEC9 /* NotificationService */, ); sourceTree = ""; }; @@ -64,6 +113,7 @@ isa = PBXGroup; children = ( 504EC3041FED79650016851F /* App.app */, + A03A384FE54FAD1ED68E12DC /* NotificationService.appex */, ); name = Products; sourceTree = ""; @@ -88,6 +138,26 @@ path = App; sourceTree = ""; }; + 5198C9768EB9762A60701C92 /* Frameworks */ = { + isa = PBXGroup; + children = ( + 0FC8613857BD976EB58ECE0B /* iOS */, + 2EE43D236E661AA975612A4B /* UserNotifications.framework */, + ); + name = Frameworks; + sourceTree = ""; + }; + 74C1FC6022E562372A71EEC9 /* NotificationService */ = { + isa = PBXGroup; + children = ( + 1E7522315D47F086145DC4B8 /* Info.plist */, + 3DF4F4305878F949DD09193F /* NotificationService.entitlements */, + FFA8802204810ED580DE46F3 /* NotificationService.swift */, + ); + name = NotificationService; + path = NotificationService; + sourceTree = ""; + }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ @@ -98,10 +168,12 @@ 504EC3001FED79650016851F /* Sources */, 504EC3011FED79650016851F /* Frameworks */, 504EC3021FED79650016851F /* Resources */, + A8F12B42B22FCA041C6AA0DA /* Embed Foundation Extensions */, ); buildRules = ( ); dependencies = ( + E23A0A46599B8EE7A5B74F45 /* PBXTargetDependency */, ); name = App; packageProductDependencies = ( @@ -111,6 +183,23 @@ productReference = 504EC3041FED79650016851F /* App.app */; productType = "com.apple.product-type.application"; }; + 9480DFBC2C2A112973DA468A /* NotificationService */ = { + isa = PBXNativeTarget; + buildConfigurationList = 4E3E5FA93A15425251E22D48 /* Build configuration list for PBXNativeTarget "NotificationService" */; + buildPhases = ( + 1EA0B85A2E70AC56F83C09C9 /* Sources */, + C9AA4ADC0D397C620A35B6A3 /* Frameworks */, + 9706E0B1D8DD6E0542723B5D /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = NotificationService; + productName = NotificationService; + productReference = A03A384FE54FAD1ED68E12DC /* NotificationService.appex */; + productType = "com.apple.product-type.app-extension"; + }; /* End PBXNativeTarget section */ /* Begin PBXProject section */ @@ -149,6 +238,7 @@ projectRoot = ""; targets = ( 504EC3031FED79650016851F /* App */, + 9480DFBC2C2A112973DA468A /* NotificationService */, ); }; /* End PBXProject section */ @@ -168,9 +258,24 @@ ); runOnlyForDeploymentPostprocessing = 0; }; + 9706E0B1D8DD6E0542723B5D /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; /* End PBXResourcesBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ + 1EA0B85A2E70AC56F83C09C9 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + A8FDD4DBE3F078BF935CC4B9 /* NotificationService.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; 504EC3001FED79650016851F /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; @@ -184,6 +289,15 @@ }; /* End PBXSourcesBuildPhase section */ +/* Begin PBXTargetDependency section */ + E23A0A46599B8EE7A5B74F45 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = NotificationService; + target = 9480DFBC2C2A112973DA468A /* NotificationService */; + targetProxy = 3BB8A38B2B2C8614B24CF2AD /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + /* Begin PBXVariantGroup section */ 504EC30B1FED79650016851F /* Main.storyboard */ = { isa = PBXVariantGroup; @@ -359,9 +473,69 @@ }; name = Release; }; + 686FA31AEC6FE5BA3EF95E99 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CLANG_ENABLE_OBJC_WEAK = NO; + CODE_SIGN_ENTITLEMENTS = NotificationService/NotificationService.entitlements; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = NO; + INFOPLIST_FILE = NotificationService/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@executable_path/../../Frameworks", + ); + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.liketrek.trek.notifications; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + A475CD70019910612C4D523B /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CLANG_ENABLE_OBJC_WEAK = NO; + CODE_SIGN_ENTITLEMENTS = NotificationService/NotificationService.entitlements; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = NO; + INFOPLIST_FILE = NotificationService/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@executable_path/../../Frameworks", + ); + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.liketrek.trek.notifications; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ + 4E3E5FA93A15425251E22D48 /* Build configuration list for PBXNativeTarget "NotificationService" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + A475CD70019910612C4D523B /* Release */, + 686FA31AEC6FE5BA3EF95E99 /* Debug */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; 504EC2FF1FED79650016851F /* Build configuration list for PBXProject "App" */ = { isa = XCConfigurationList; buildConfigurations = ( diff --git a/client/ios/App/NotificationService/Info.plist b/client/ios/App/NotificationService/Info.plist new file mode 100644 index 000000000..bf8948615 --- /dev/null +++ b/client/ios/App/NotificationService/Info.plist @@ -0,0 +1,31 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleDisplayName + TREK Notifications + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + $(PRODUCT_BUNDLE_PACKAGE_TYPE) + CFBundleShortVersionString + $(MARKETING_VERSION) + CFBundleVersion + $(CURRENT_PROJECT_VERSION) + NSExtension + + NSExtensionPointIdentifier + com.apple.usernotifications.service + NSExtensionPrincipalClass + $(PRODUCT_MODULE_NAME).NotificationService + + + diff --git a/client/ios/App/NotificationService/NotificationService.entitlements b/client/ios/App/NotificationService/NotificationService.entitlements new file mode 100644 index 000000000..6b6566872 --- /dev/null +++ b/client/ios/App/NotificationService/NotificationService.entitlements @@ -0,0 +1,10 @@ + + + + + keychain-access-groups + + $(AppIdentifierPrefix)com.liketrek.trek.shared + + + diff --git a/client/ios/App/NotificationService/NotificationService.swift b/client/ios/App/NotificationService/NotificationService.swift new file mode 100644 index 000000000..3d0bd919f --- /dev/null +++ b/client/ios/App/NotificationService/NotificationService.swift @@ -0,0 +1,109 @@ +import CryptoKit +import Security +import UserNotifications + +/// Decrypts a TREK push before iOS shows it. +/// +/// The user's server encrypts each notification for this device exactly as Web +/// Push does for a browser (RFC 8291, aes128gcm), and liketrek's relay hands the +/// ciphertext to APNs as `enc`, with a placeholder text and mutable-content set. +/// Here the device's keys (the app made them, TrekPushKeys in the app target) +/// open it, and the real title, text and link replace the placeholder. Without +/// the keys, or if anything does not add up, the placeholder stays: a +/// notification arrives either way, and nothing on the way could read it. +final class NotificationService: UNNotificationServiceExtension { + private var contentHandler: ((UNNotificationContent) -> Void)? + private var content: UNMutableNotificationContent? + + override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) { + self.contentHandler = contentHandler + let content = (request.content.mutableCopy() as? UNMutableNotificationContent) ?? UNMutableNotificationContent() + self.content = content + if let encoded = request.content.userInfo["enc"] as? String, + let record = Data(base64Encoded: encoded), + let keys = PushKeys.load(), + let plaintext = WebPushRecord.open(record, keys: keys), + let payload = try? JSONSerialization.jsonObject(with: plaintext) as? [String: Any] { + if let title = payload["title"] as? String, !title.isEmpty { content.title = title } + if let body = payload["body"] as? String { content.body = body } + if let url = payload["url"] as? String { content.userInfo["url"] = url } + if let tag = payload["tag"] as? String { content.threadIdentifier = tag } + } + contentHandler(content) + } + + override func serviceExtensionTimeWillExpire() { + if let contentHandler, let content { contentHandler(content) } + } +} + +/// The device's Web Push keys, from the keychain group it shares with the app. +struct PushKeys { + let privateKey: P256.KeyAgreement.PrivateKey + let auth: Data + + static func load() -> PushKeys? { + guard let raw = read("push.privateKey"), let auth = read("push.auth"), + let key = try? P256.KeyAgreement.PrivateKey(rawRepresentation: raw) else { return nil } + return PushKeys(privateKey: key, auth: auth) + } + + private static func read(_ account: String) -> Data? { + // No access group named: the extension's first keychain group is the + // shared one (its entitlements list only that), where the app stored them. + let query: [String: Any] = [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: "com.liketrek.trek.push", + kSecAttrAccount as String: account, + kSecReturnData as String: true, + ] + var result: CFTypeRef? + return SecItemCopyMatching(query as CFDictionary, &result) == errSecSuccess ? result as? Data : nil + } +} + +/// One aes128gcm record (RFC 8188) with Web Push keys (RFC 8291), opened. +enum WebPushRecord { + static func open(_ record: Data, keys: PushKeys) -> Data? { + let bytes = [UInt8](record) + // salt (16) | record size (4) | key id length (1) | key id (the sender's public key) + guard bytes.count > 21 else { return nil } + let salt = Data(bytes[0..<16]) + let idLength = Int(bytes[20]) + guard bytes.count > 21 + idLength + 16 else { return nil } + let senderKeyBytes = Data(bytes[21..<(21 + idLength)]) + let ciphertext = Data(bytes[(21 + idLength)...]) + + guard let senderKey = try? P256.KeyAgreement.PublicKey(x963Representation: senderKeyBytes), + let shared = try? keys.privateKey.sharedSecretFromKeyAgreement(with: senderKey) else { return nil } + let sharedBytes = shared.withUnsafeBytes { Data($0) } + let receiverKey = keys.privateKey.publicKey.x963Representation + + // IKM = HKDF(auth, ecdh, "WebPush: info" 0 receiver sender, 32) + var keyInfo = Data("WebPush: info".utf8) + keyInfo.append(0) + keyInfo.append(receiverKey) + keyInfo.append(senderKeyBytes) + let prkKey = HKDF.extract(inputKeyMaterial: SymmetricKey(data: sharedBytes), salt: keys.auth) + let ikm = HKDF.expand(pseudoRandomKey: prkKey, info: keyInfo, outputByteCount: 32) + + let prk = HKDF.extract(inputKeyMaterial: ikm, salt: salt) + var cekInfo = Data("Content-Encoding: aes128gcm".utf8) + cekInfo.append(0) + var nonceInfo = Data("Content-Encoding: nonce".utf8) + nonceInfo.append(0) + let cek = HKDF.expand(pseudoRandomKey: prk, info: cekInfo, outputByteCount: 16) + let nonceKey = HKDF.expand(pseudoRandomKey: prk, info: nonceInfo, outputByteCount: 12) + let nonceBytes = nonceKey.withUnsafeBytes { Data($0) } + + guard let nonce = try? AES.GCM.Nonce(data: nonceBytes), + let box = try? AES.GCM.SealedBox(nonce: nonce, ciphertext: ciphertext.dropLast(16), tag: ciphertext.suffix(16)), + let padded = try? AES.GCM.open(box, using: cek) else { return nil } + + // The last record ends in 0x02 and optional zero padding. + var end = padded.count + while end > 0 && padded[padded.startIndex + end - 1] == 0 { end -= 1 } + guard end > 0, padded[padded.startIndex + end - 1] == 2 else { return nil } + return padded.prefix(end - 1) + } +} diff --git a/client/ios/scripts/add-extension.rb b/client/ios/scripts/add-extension.rb new file mode 100644 index 000000000..40f8798c6 --- /dev/null +++ b/client/ios/scripts/add-extension.rb @@ -0,0 +1,74 @@ +# Adds an app extension target to App.xcodeproj and embeds it in the app. +# +# ruby ios/scripts/add-extension.rb [extra frameworks...] +# +# type is "notification" (Notification Service Extension) or "widget" (WidgetKit, +# which also carries the Live Activities). The extension's sources live in +# ios/App// with an Info.plist and .entitlements next to them. The +# project file stays checked in, so the targets show in Xcode like any other; +# this script is how they got there, and running it again changes nothing. +require 'xcodeproj' + +name, bundle_id, type, *frameworks = ARGV +abort 'usage: add-extension.rb [frameworks...]' unless name && bundle_id && type + +project_path = File.expand_path('../App/App.xcodeproj', __dir__) +project = Xcodeproj::Project.open(project_path) +app = project.targets.find { |t| t.name == 'App' } or abort 'no App target' + +if project.targets.any? { |t| t.name == name } + puts "#{name} is already in the project" + exit 0 +end + +target = project.new_target(:app_extension, name, :ios, '15.0', nil, :swift) +# new_target links Foundation by a path into one SDK version; it is linked +# implicitly anyway, and a pinned SDK path breaks on the next Xcode. +target.frameworks_build_phase.files.select { |f| f.display_name.to_s.include?('Foundation') }.each do |f| + ref = f.file_ref + f.remove_from_project + ref&.remove_from_project +end + +group = project.main_group.find_subpath(name, true) +group.set_source_tree('') +group.set_path(name) +sources = Dir.children(File.expand_path("../App/#{name}", __dir__)).sort +sources.each do |file| + ref = group.new_reference(file) + target.add_file_references([ref]) if file.end_with?('.swift') +end + +frameworks.each do |framework| + ref = project.frameworks_group.new_file("System/Library/Frameworks/#{framework}.framework", :sdk_root) + target.frameworks_build_phase.add_file_reference(ref, true) +end + +app_settings = app.build_configurations.first.build_settings +target.build_configurations.each do |config| + s = config.build_settings + s['PRODUCT_BUNDLE_IDENTIFIER'] = bundle_id + s['PRODUCT_NAME'] = '$(TARGET_NAME)' + s['INFOPLIST_FILE'] = "#{name}/Info.plist" + s['GENERATE_INFOPLIST_FILE'] = 'NO' + s['CODE_SIGN_ENTITLEMENTS'] = "#{name}/#{name}.entitlements" + s['CODE_SIGN_STYLE'] = 'Automatic' + s['DEVELOPMENT_TEAM'] = app_settings['DEVELOPMENT_TEAM'] if app_settings['DEVELOPMENT_TEAM'] + s['SWIFT_VERSION'] = '5.0' + s['TARGETED_DEVICE_FAMILY'] = '1,2' + s['IPHONEOS_DEPLOYMENT_TARGET'] = type == 'widget' ? '16.2' : '15.0' + s['MARKETING_VERSION'] = app_settings['MARKETING_VERSION'] || '1.0' + s['CURRENT_PROJECT_VERSION'] = app_settings['CURRENT_PROJECT_VERSION'] || '1' + s['SKIP_INSTALL'] = 'YES' + s['LD_RUNPATH_SEARCH_PATHS'] = ['$(inherited)', '@executable_path/Frameworks', '@executable_path/../../Frameworks'] +end + +embed = app.copy_files_build_phases.find { |p| p.name == 'Embed Foundation Extensions' } || + app.new_copy_files_build_phase('Embed Foundation Extensions') +embed.symbol_dst_subfolder_spec = :plug_ins +build_file = embed.add_file_reference(target.product_reference, true) +build_file.settings = { 'ATTRIBUTES' => ['RemoveHeadersOnCopy'] } +app.add_dependency(target) + +project.save +puts "added #{name} (#{bundle_id})" diff --git a/server/src/nest/notifications/transports/web-push.service.ts b/server/src/nest/notifications/transports/web-push.service.ts index 62e75b10c..a0cb4d39a 100644 --- a/server/src/nest/notifications/transports/web-push.service.ts +++ b/server/src/nest/notifications/transports/web-push.service.ts @@ -14,8 +14,12 @@ import type { ChannelTestResult, PushPayload } from '@trek/shared'; * Ceiling for the JSON the service worker receives. A single aes128gcm record * can carry just under 4 KB and some push services refuse anything larger, so * the payload stays well clear of that and the body gives way first. + * + * The apps' relay (push.liketrek.com) is the tightest: it carries the encrypted + * record base64-encoded inside an APNs payload, which Apple caps at 4096 bytes. + * 2800 bytes of JSON become about 3870 there, with room for the APNs envelope. */ -export const MAX_PUSH_PAYLOAD_BYTES = 3000; +export const MAX_PUSH_PAYLOAD_BYTES = 2800; const TITLE_MAX_CHARS = 120; /** A navigate target is an app path like /trips/12; anything longer is not one. */ From f35b189ca2304ece09ca63c86ce3cadd8e812a0c Mon Sep 17 00:00:00 2001 From: Maurice Date: Fri, 6 Nov 2026 13:52:52 +0100 Subject: [PATCH 074/589] feat(native): home-screen widget and travel-day Live Activity on iOS A WidgetKit extension (TREKWidgets) with two parts: the next trip on the home screen, with a countdown before it starts and today's day and next stops while it runs, and a Live Activity for the travel day on the lock screen and in the Dynamic Island showing the next timed stop and the day's progress. The web app builds both from the trips stored offline on the device (native/widgets.ts) and hands them over through TrekShell (setWidgetSnapshot, syncTripDay, endTripDay). The texts are already translated, so the widget needs no localisation of its own. The snapshot lives in the keychain group the app shares with its extensions, so no App Group is needed. Taps open com.liketrek.trek://navigate/. NativeWidgetsSync refreshes on start, on returning to the foreground and every quarter hour. Both parts are gated behind the widgets / liveActivity capabilities, so older binaries and the PWA are unaffected. --- .github/workflows/native.yml | 2 +- client/fastlane/Fastfile | 1 + client/ios/App/App.xcodeproj/project.pbxproj | 164 ++++++++++++++++++ client/ios/App/App/Info.plist | 2 + client/ios/App/App/TrekShellPlugin.swift | 110 ++++++++++-- client/ios/App/TREKWidgets/Info.plist | 29 ++++ .../ios/App/TREKWidgets/NextTripWidget.swift | 118 +++++++++++++ .../App/TREKWidgets/TREKWidgets.entitlements | 10 ++ .../App/TREKWidgets/TREKWidgetsBundle.swift | 12 ++ .../App/TREKWidgets/TripDayAttributes.swift | 24 +++ .../App/TREKWidgets/TripDayLiveActivity.swift | 55 ++++++ .../ios/App/TREKWidgets/WidgetSnapshot.swift | 71 ++++++++ client/ios/scripts/share-with-app.rb | 24 +++ client/src/App.tsx | 2 + .../components/Layout/NativeWidgetsSync.tsx | 70 ++++++++ client/src/native/nativeApp.test.ts | 2 +- client/src/native/nativeApp.ts | 10 +- client/src/native/trekShell.ts | 13 ++ client/src/native/widgets.test.ts | 129 ++++++++++++++ client/src/native/widgets.ts | 123 +++++++++++++ shared/src/i18n/ar/native.ts | 7 + shared/src/i18n/az/native.ts | 7 + shared/src/i18n/br/native.ts | 7 + shared/src/i18n/ca/native.ts | 7 + shared/src/i18n/cs/native.ts | 7 + shared/src/i18n/de/native.ts | 7 + shared/src/i18n/en/native.ts | 7 + shared/src/i18n/es/native.ts | 7 + shared/src/i18n/et/native.ts | 7 + shared/src/i18n/fr/native.ts | 7 + shared/src/i18n/gr/native.ts | 7 + shared/src/i18n/he/native.ts | 7 + shared/src/i18n/hu/native.ts | 7 + shared/src/i18n/id/native.ts | 7 + shared/src/i18n/it/native.ts | 7 + shared/src/i18n/ja/native.ts | 7 + shared/src/i18n/ko/native.ts | 7 + shared/src/i18n/nl/native.ts | 7 + shared/src/i18n/pl/native.ts | 7 + shared/src/i18n/ru/native.ts | 7 + shared/src/i18n/sk/native.ts | 7 + shared/src/i18n/sv/native.ts | 7 + shared/src/i18n/th/native.ts | 7 + shared/src/i18n/tr/native.ts | 7 + shared/src/i18n/uk/native.ts | 7 + shared/src/i18n/vi/native.ts | 7 + shared/src/i18n/zh-TW/native.ts | 7 + shared/src/i18n/zh/native.ts | 7 + 48 files changed, 1148 insertions(+), 19 deletions(-) create mode 100644 client/ios/App/TREKWidgets/Info.plist create mode 100644 client/ios/App/TREKWidgets/NextTripWidget.swift create mode 100644 client/ios/App/TREKWidgets/TREKWidgets.entitlements create mode 100644 client/ios/App/TREKWidgets/TREKWidgetsBundle.swift create mode 100644 client/ios/App/TREKWidgets/TripDayAttributes.swift create mode 100644 client/ios/App/TREKWidgets/TripDayLiveActivity.swift create mode 100644 client/ios/App/TREKWidgets/WidgetSnapshot.swift create mode 100644 client/ios/scripts/share-with-app.rb create mode 100644 client/src/components/Layout/NativeWidgetsSync.tsx create mode 100644 client/src/native/widgets.test.ts create mode 100644 client/src/native/widgets.ts diff --git a/.github/workflows/native.yml b/.github/workflows/native.yml index 8c3a94cbc..8ee1272f2 100644 --- a/.github/workflows/native.yml +++ b/.github/workflows/native.yml @@ -103,7 +103,7 @@ jobs: xcodebuild -version - name: Check the property lists - run: plutil -lint client/ios/App/App/Info.plist client/ios/ExportOptions.plist client/ios/App/NotificationService/Info.plist client/ios/App/NotificationService/NotificationService.entitlements client/ios/App/App/App.entitlements + run: plutil -lint client/ios/App/App/Info.plist client/ios/ExportOptions.plist client/ios/App/NotificationService/Info.plist client/ios/App/NotificationService/NotificationService.entitlements client/ios/App/App/App.entitlements client/ios/App/TREKWidgets/Info.plist client/ios/App/TREKWidgets/TREKWidgets.entitlements - uses: actions/setup-node@v6 with: diff --git a/client/fastlane/Fastfile b/client/fastlane/Fastfile index 4a867a8cf..b477cb0cb 100644 --- a/client/fastlane/Fastfile +++ b/client/fastlane/Fastfile @@ -24,6 +24,7 @@ PROJECT = "ios/App/App.xcodeproj" SIGNED_TARGETS = { "App" => APP_IDENTIFIER, "NotificationService" => "com.liketrek.trek.notifications", + "TREKWidgets" => "com.liketrek.trek.widgets", } platform :ios do diff --git a/client/ios/App/App.xcodeproj/project.pbxproj b/client/ios/App/App.xcodeproj/project.pbxproj index ea319b7f2..92edde628 100644 --- a/client/ios/App/App.xcodeproj/project.pbxproj +++ b/client/ios/App/App.xcodeproj/project.pbxproj @@ -7,8 +7,14 @@ objects = { /* Begin PBXBuildFile section */ + 01FD437981FC32C2C2C5BDCE /* TREKWidgets.appex in Embed Foundation Extensions */ = {isa = PBXBuildFile; fileRef = 702D0DF4A7E323CEA94CA03F /* TREKWidgets.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; }; + 0C2D60A4950D7293E1F282CB /* TripDayAttributes.swift in Sources */ = {isa = PBXBuildFile; fileRef = 337775CD9091673D0ADDF325 /* TripDayAttributes.swift */; }; + 2162CD349AFFDF070C16A58A /* SwiftUI.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6E901288FC198E4D33BE754F /* SwiftUI.framework */; }; 2CFE220A73ACB585F3D4CB8F /* UserNotifications.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 2EE43D236E661AA975612A4B /* UserNotifications.framework */; }; 2FAD9763203C412B000D30F8 /* config.xml in Resources */ = {isa = PBXBuildFile; fileRef = 2FAD9762203C412B000D30F8 /* config.xml */; }; + 32797E66C09CF7579AC323FD /* TREKWidgetsBundle.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8C2E47D0B005674C2B4ADA56 /* TREKWidgetsBundle.swift */; }; + 3FB1872A25267A8E88FCBE3C /* WidgetKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = BC64330AC19625949E8DC05A /* WidgetKit.framework */; }; + 492FA24FBB57059B0B5007CE /* TripDayAttributes.swift in Sources */ = {isa = PBXBuildFile; fileRef = 337775CD9091673D0ADDF325 /* TripDayAttributes.swift */; }; 4D22ABE92AF431CB00220026 /* CapApp-SPM in Frameworks */ = {isa = PBXBuildFile; productRef = 4D22ABE82AF431CB00220026 /* CapApp-SPM */; }; 50379B232058CBB4000EE86E /* capacitor.config.json in Resources */ = {isa = PBXBuildFile; fileRef = 50379B222058CBB4000EE86E /* capacitor.config.json */; }; 504EC3081FED79650016851F /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 504EC3071FED79650016851F /* AppDelegate.swift */; }; @@ -19,9 +25,13 @@ 7A1E00032C0000000000A003 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = 7A1E00022C0000000000A002 /* PrivacyInfo.xcprivacy */; }; 7A1E00052C0000000000A005 /* TrekBridgeViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7A1E00042C0000000000A004 /* TrekBridgeViewController.swift */; }; 7A1E00072C0000000000A007 /* TrekShellPlugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7A1E00062C0000000000A006 /* TrekShellPlugin.swift */; }; + 7FB730DC35C234816EAE65AF /* WidgetSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = DBF6D74B7888714BF264E0E6 /* WidgetSnapshot.swift */; }; 84EB79E4B677229481809933 /* NotificationService.appex in Embed Foundation Extensions */ = {isa = PBXBuildFile; fileRef = A03A384FE54FAD1ED68E12DC /* NotificationService.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; }; 9582B6832FE993A70072D4E8 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9582B6822FE993A50072D4E8 /* SceneDelegate.swift */; }; A8FDD4DBE3F078BF935CC4B9 /* NotificationService.swift in Sources */ = {isa = PBXBuildFile; fileRef = FFA8802204810ED580DE46F3 /* NotificationService.swift */; }; + B4C0FC386F71D849E141C91E /* NextTripWidget.swift in Sources */ = {isa = PBXBuildFile; fileRef = C7064A9DA92FCC8ACAA4F22A /* NextTripWidget.swift */; }; + B65B7CFC62EEFF443491EA64 /* ActivityKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 192E69C7E66646BC39566925 /* ActivityKit.framework */; }; + DF633789F2F667C4CF264C9E /* TripDayLiveActivity.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3259F6C40216CECEBAC6F307 /* TripDayLiveActivity.swift */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -32,6 +42,13 @@ remoteGlobalIDString = 9480DFBC2C2A112973DA468A; remoteInfo = NotificationService; }; + B8BBE7F7A64678D780A7F3D1 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 504EC2FC1FED79650016851F /* Project object */; + proxyType = 1; + remoteGlobalIDString = A3BE5653156025C97CA62C68; + remoteInfo = TREKWidgets; + }; /* End PBXContainerItemProxy section */ /* Begin PBXCopyFilesBuildPhase section */ @@ -42,6 +59,7 @@ dstSubfolderSpec = 13; files = ( 84EB79E4B677229481809933 /* NotificationService.appex in Embed Foundation Extensions */, + 01FD437981FC32C2C2C5BDCE /* TREKWidgets.appex in Embed Foundation Extensions */, ); name = "Embed Foundation Extensions"; runOnlyForDeploymentPostprocessing = 0; @@ -49,9 +67,12 @@ /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ + 192E69C7E66646BC39566925 /* ActivityKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = ActivityKit.framework; path = System/Library/Frameworks/ActivityKit.framework; sourceTree = SDKROOT; }; 1E7522315D47F086145DC4B8 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 2EE43D236E661AA975612A4B /* UserNotifications.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UserNotifications.framework; path = System/Library/Frameworks/UserNotifications.framework; sourceTree = SDKROOT; }; 2FAD9762203C412B000D30F8 /* config.xml */ = {isa = PBXFileReference; lastKnownFileType = text.xml; path = config.xml; sourceTree = ""; }; + 3259F6C40216CECEBAC6F307 /* TripDayLiveActivity.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = TripDayLiveActivity.swift; sourceTree = ""; }; + 337775CD9091673D0ADDF325 /* TripDayAttributes.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = TripDayAttributes.swift; sourceTree = ""; }; 3DF4F4305878F949DD09193F /* NotificationService.entitlements */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.entitlements; path = NotificationService.entitlements; sourceTree = ""; }; 50379B222058CBB4000EE86E /* capacitor.config.json */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.json; path = capacitor.config.json; sourceTree = ""; }; 504EC3041FED79650016851F /* App.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = App.app; sourceTree = BUILT_PRODUCTS_DIR; }; @@ -61,17 +82,35 @@ 504EC3111FED79650016851F /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; 504EC3131FED79650016851F /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 50B271D01FEDC1A000F3C39B /* public */ = {isa = PBXFileReference; lastKnownFileType = folder; path = public; sourceTree = ""; }; + 6E901288FC198E4D33BE754F /* SwiftUI.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = SwiftUI.framework; path = System/Library/Frameworks/SwiftUI.framework; sourceTree = SDKROOT; }; + 702D0DF4A7E323CEA94CA03F /* TREKWidgets.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = TREKWidgets.appex; sourceTree = BUILT_PRODUCTS_DIR; }; 7A1E00012C0000000000A001 /* App.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = App.entitlements; sourceTree = ""; }; 7A1E00022C0000000000A002 /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = PrivacyInfo.xcprivacy; sourceTree = ""; }; 7A1E00042C0000000000A004 /* TrekBridgeViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TrekBridgeViewController.swift; sourceTree = ""; }; 7A1E00062C0000000000A006 /* TrekShellPlugin.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TrekShellPlugin.swift; sourceTree = ""; }; + 8C2E47D0B005674C2B4ADA56 /* TREKWidgetsBundle.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = TREKWidgetsBundle.swift; sourceTree = ""; }; 9582B6822FE993A50072D4E8 /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = ""; }; 958DCC722DB07C7200EA8C5F /* debug.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = debug.xcconfig; path = ../debug.xcconfig; sourceTree = SOURCE_ROOT; }; A03A384FE54FAD1ED68E12DC /* NotificationService.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = NotificationService.appex; sourceTree = BUILT_PRODUCTS_DIR; }; + BBB2E19CD540AB30B44BECCA /* TREKWidgets.entitlements */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.entitlements; path = TREKWidgets.entitlements; sourceTree = ""; }; + BC64330AC19625949E8DC05A /* WidgetKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = WidgetKit.framework; path = System/Library/Frameworks/WidgetKit.framework; sourceTree = SDKROOT; }; + BE41D7212DCB0C78E00A8462 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + C7064A9DA92FCC8ACAA4F22A /* NextTripWidget.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = NextTripWidget.swift; sourceTree = ""; }; + DBF6D74B7888714BF264E0E6 /* WidgetSnapshot.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = WidgetSnapshot.swift; sourceTree = ""; }; FFA8802204810ED580DE46F3 /* NotificationService.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = NotificationService.swift; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ + 0A579FBACE2CF30B89370F8E /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 3FB1872A25267A8E88FCBE3C /* WidgetKit.framework in Frameworks */, + 2162CD349AFFDF070C16A58A /* SwiftUI.framework in Frameworks */, + B65B7CFC62EEFF443491EA64 /* ActivityKit.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; 504EC3011FED79650016851F /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; @@ -106,6 +145,7 @@ 504EC3051FED79650016851F /* Products */, 5198C9768EB9762A60701C92 /* Frameworks */, 74C1FC6022E562372A71EEC9 /* NotificationService */, + FB9226BC82835538BCE3DC0A /* TREKWidgets */, ); sourceTree = ""; }; @@ -114,6 +154,7 @@ children = ( 504EC3041FED79650016851F /* App.app */, A03A384FE54FAD1ED68E12DC /* NotificationService.appex */, + 702D0DF4A7E323CEA94CA03F /* TREKWidgets.appex */, ); name = Products; sourceTree = ""; @@ -143,6 +184,9 @@ children = ( 0FC8613857BD976EB58ECE0B /* iOS */, 2EE43D236E661AA975612A4B /* UserNotifications.framework */, + BC64330AC19625949E8DC05A /* WidgetKit.framework */, + 6E901288FC198E4D33BE754F /* SwiftUI.framework */, + 192E69C7E66646BC39566925 /* ActivityKit.framework */, ); name = Frameworks; sourceTree = ""; @@ -158,6 +202,21 @@ path = NotificationService; sourceTree = ""; }; + FB9226BC82835538BCE3DC0A /* TREKWidgets */ = { + isa = PBXGroup; + children = ( + BE41D7212DCB0C78E00A8462 /* Info.plist */, + C7064A9DA92FCC8ACAA4F22A /* NextTripWidget.swift */, + BBB2E19CD540AB30B44BECCA /* TREKWidgets.entitlements */, + 8C2E47D0B005674C2B4ADA56 /* TREKWidgetsBundle.swift */, + 337775CD9091673D0ADDF325 /* TripDayAttributes.swift */, + 3259F6C40216CECEBAC6F307 /* TripDayLiveActivity.swift */, + DBF6D74B7888714BF264E0E6 /* WidgetSnapshot.swift */, + ); + name = TREKWidgets; + path = TREKWidgets; + sourceTree = ""; + }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ @@ -174,6 +233,7 @@ ); dependencies = ( E23A0A46599B8EE7A5B74F45 /* PBXTargetDependency */, + 4CD7F5AF02CB806E4189489A /* PBXTargetDependency */, ); name = App; packageProductDependencies = ( @@ -200,6 +260,23 @@ productReference = A03A384FE54FAD1ED68E12DC /* NotificationService.appex */; productType = "com.apple.product-type.app-extension"; }; + A3BE5653156025C97CA62C68 /* TREKWidgets */ = { + isa = PBXNativeTarget; + buildConfigurationList = 9DE86AC1D6A95987925D7982 /* Build configuration list for PBXNativeTarget "TREKWidgets" */; + buildPhases = ( + 92D923C146596E50655B451D /* Sources */, + 0A579FBACE2CF30B89370F8E /* Frameworks */, + 04A03741C8AD60E63D4B11E7 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = TREKWidgets; + productName = TREKWidgets; + productReference = 702D0DF4A7E323CEA94CA03F /* TREKWidgets.appex */; + productType = "com.apple.product-type.app-extension"; + }; /* End PBXNativeTarget section */ /* Begin PBXProject section */ @@ -239,11 +316,19 @@ targets = ( 504EC3031FED79650016851F /* App */, 9480DFBC2C2A112973DA468A /* NotificationService */, + A3BE5653156025C97CA62C68 /* TREKWidgets */, ); }; /* End PBXProject section */ /* Begin PBXResourcesBuildPhase section */ + 04A03741C8AD60E63D4B11E7 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; 504EC3021FED79650016851F /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; @@ -284,12 +369,31 @@ 9582B6832FE993A70072D4E8 /* SceneDelegate.swift in Sources */, 7A1E00052C0000000000A005 /* TrekBridgeViewController.swift in Sources */, 7A1E00072C0000000000A007 /* TrekShellPlugin.swift in Sources */, + 0C2D60A4950D7293E1F282CB /* TripDayAttributes.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 92D923C146596E50655B451D /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + B4C0FC386F71D849E141C91E /* NextTripWidget.swift in Sources */, + 32797E66C09CF7579AC323FD /* TREKWidgetsBundle.swift in Sources */, + 492FA24FBB57059B0B5007CE /* TripDayAttributes.swift in Sources */, + DF633789F2F667C4CF264C9E /* TripDayLiveActivity.swift in Sources */, + 7FB730DC35C234816EAE65AF /* WidgetSnapshot.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXSourcesBuildPhase section */ /* Begin PBXTargetDependency section */ + 4CD7F5AF02CB806E4189489A /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = TREKWidgets; + target = A3BE5653156025C97CA62C68 /* TREKWidgets */; + targetProxy = B8BBE7F7A64678D780A7F3D1 /* PBXContainerItemProxy */; + }; E23A0A46599B8EE7A5B74F45 /* PBXTargetDependency */ = { isa = PBXTargetDependency; name = NotificationService; @@ -318,6 +422,31 @@ /* End PBXVariantGroup section */ /* Begin XCBuildConfiguration section */ + 3ECF3537A139DB5CAC23E502 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CLANG_ENABLE_OBJC_WEAK = NO; + CODE_SIGN_ENTITLEMENTS = TREKWidgets/TREKWidgets.entitlements; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = NO; + INFOPLIST_FILE = TREKWidgets/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 16.2; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@executable_path/../../Frameworks", + ); + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.liketrek.trek.widgets; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; 504EC3141FED79650016851F /* Debug */ = { isa = XCBuildConfiguration; baseConfigurationReference = 958DCC722DB07C7200EA8C5F /* debug.xcconfig */; @@ -524,6 +653,32 @@ }; name = Release; }; + C5621F5D75100AAEBB1BD22A /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CLANG_ENABLE_OBJC_WEAK = NO; + CODE_SIGN_ENTITLEMENTS = TREKWidgets/TREKWidgets.entitlements; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = NO; + INFOPLIST_FILE = TREKWidgets/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 16.2; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@executable_path/../../Frameworks", + ); + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.liketrek.trek.widgets; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ @@ -554,6 +709,15 @@ defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; + 9DE86AC1D6A95987925D7982 /* Build configuration list for PBXNativeTarget "TREKWidgets" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + C5621F5D75100AAEBB1BD22A /* Release */, + 3ECF3537A139DB5CAC23E502 /* Debug */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; /* End XCConfigurationList section */ /* Begin XCLocalSwiftPackageReference section */ diff --git a/client/ios/App/App/Info.plist b/client/ios/App/App/Info.plist index 8eaff77ba..db57f50f3 100644 --- a/client/ios/App/App/Info.plist +++ b/client/ios/App/App/Info.plist @@ -71,6 +71,8 @@ NSPhotoLibraryAddUsageDescription TREK saves photos and exports you download from your trips back to your photo library. + NSSupportsLiveActivities + NSFaceIDUsageDescription TREK uses Face ID to unlock the app when you turn on the app lock. NSLocationWhenInUseUsageDescription diff --git a/client/ios/App/App/TrekShellPlugin.swift b/client/ios/App/App/TrekShellPlugin.swift index 7e6c620ed..9a2fcaefe 100644 --- a/client/ios/App/App/TrekShellPlugin.swift +++ b/client/ios/App/App/TrekShellPlugin.swift @@ -4,6 +4,10 @@ import CoreLocation import CryptoKit import Security import UserNotifications +import WidgetKit +#if canImport(ActivityKit) +import ActivityKit +#endif import LocalAuthentication import UIKit import WebKit @@ -32,6 +36,9 @@ public class TrekShellPlugin: CAPPlugin, CAPBridgedPlugin, ASWebAuthenticationPr CAPPluginMethod(name: "takeSharedFile", returnType: CAPPluginReturnPromise), CAPPluginMethod(name: "registerPush", returnType: CAPPluginReturnPromise), CAPPluginMethod(name: "takeOpenedPush", returnType: CAPPluginReturnPromise), + CAPPluginMethod(name: "setWidgetSnapshot", returnType: CAPPluginReturnPromise), + CAPPluginMethod(name: "syncTripDay", returnType: CAPPluginReturnPromise), + CAPPluginMethod(name: "endTripDay", returnType: CAPPluginReturnPromise), ] /// What this binary offers the server's UI, raised with every native feature @@ -39,7 +46,7 @@ public class TrekShellPlugin: CAPPlugin, CAPBridgedPlugin, ASWebAuthenticationPr /// and a server can require a minimum (minNativeShellApi in /api/health/features). static let shellApi = 2 /// The native features by name, so the UI can turn each on by itself. - static let features: [String] = ["capabilities", "edgeBack", "tileCache", "biometricLock", "geolocation", "sharedFiles", "nativePush"] + static let features: [String] = ["capabilities", "edgeBack", "tileCache", "biometricLock", "geolocation", "sharedFiles", "nativePush", "widgets", "liveActivity"] // MARK: - Shared booking documents @@ -52,6 +59,69 @@ public class TrekShellPlugin: CAPPlugin, CAPBridgedPlugin, ASWebAuthenticationPr } } + // MARK: - Widgets and the travel-day Live Activity + + /// Stores what the home-screen widget shows (native/widgets.ts builds it, texts + /// already translated) where the widget extension reads it, and redraws it. + @objc func setWidgetSnapshot(_ call: CAPPluginCall) { + guard let json = call.getString("json"), let data = json.data(using: .utf8) else { + call.reject("json is required") + return + } + TrekSharedKeychain.write("widget.snapshot", data) + WidgetCenter.shared.reloadAllTimelines() + call.resolve() + } + + /// Starts the travel day's Live Activity, or updates the one running. + @objc func syncTripDay(_ call: CAPPluginCall) { + guard let title = call.getString("tripTitle"), let path = call.getString("path"), + let dayLabel = call.getString("dayLabel"), let nextName = call.getString("nextName") else { + call.reject("tripTitle, path, dayLabel and nextName are required") + return + } + #if canImport(ActivityKit) + if #available(iOS 16.2, *) { + guard ActivityAuthorizationInfo().areActivitiesEnabled else { + call.resolve(["running": false]) + return + } + let state = TripDayAttributes.ContentState( + dayLabel: dayLabel, + nextName: nextName, + nextTime: call.getString("nextTime"), + done: call.getInt("done") ?? 0, + total: call.getInt("total") ?? 0 + ) + // Stale at the end of the day, so a forgotten one fades out on its own. + let stale = Calendar.current.startOfDay(for: Date().addingTimeInterval(86_400)) + let content = ActivityContent(state: state, staleDate: stale) + if let running = Activity.activities.first(where: { $0.attributes.path == path }) { + Task { await running.update(content) } + } else { + for other in Activity.activities { + Task { await other.end(nil, dismissalPolicy: .immediate) } + } + _ = try? Activity.request(attributes: TripDayAttributes(tripTitle: title, path: path), content: content) + } + call.resolve(["running": true]) + return + } + #endif + call.resolve(["running": false]) + } + + @objc func endTripDay(_ call: CAPPluginCall) { + #if canImport(ActivityKit) + if #available(iOS 16.2, *) { + for activity in Activity.activities { + Task { await activity.end(nil, dismissalPolicy: .immediate) } + } + } + #endif + call.resolve() + } + // MARK: - Push /// Asks for permission, registers with APNs and answers with a Web Push @@ -438,32 +508,46 @@ enum TrekPushKeys { private static let authAccount = "push.auth" static func loadOrCreate() -> (publicKey: String, auth: String)? { - if let raw = read(privateKeyAccount), let auth = read(authAccount), + if let raw = TrekSharedKeychain.read(privateKeyAccount), let auth = TrekSharedKeychain.read(authAccount), let key = try? P256.KeyAgreement.PrivateKey(rawRepresentation: raw) { return (base64url(key.publicKey.x963Representation), base64url(auth)) } let key = P256.KeyAgreement.PrivateKey() var auth = Data(count: 16) let status = auth.withUnsafeMutableBytes { SecRandomCopyBytes(kSecRandomDefault, 16, $0.baseAddress!) } - guard status == errSecSuccess, write(privateKeyAccount, key.rawRepresentation), write(authAccount, auth) else { return nil } + guard status == errSecSuccess, + TrekSharedKeychain.write(privateKeyAccount, key.rawRepresentation), + TrekSharedKeychain.write(authAccount, auth) else { return nil } return (base64url(key.publicKey.x963Representation), base64url(auth)) } + static func base64url(_ data: Data) -> String { + data.base64EncodedString().replacingOccurrences(of: "+", with: "-").replacingOccurrences(of: "/", with: "_") + .replacingOccurrences(of: "=", with: "") + } +} + +/// Items the app shares with its extensions (the notification extension, the +/// widgets) through one keychain group, so no App Group is needed: the push keys +/// and the widget snapshot. +enum TrekSharedKeychain { + static let service = "com.liketrek.trek.push" + private static func query(_ account: String) -> [String: Any] { [ kSecClass as String: kSecClassGenericPassword, - kSecAttrService as String: "com.liketrek.trek.push", + kSecAttrService as String: service, kSecAttrAccount as String: account, kSecAttrAccessGroup as String: accessGroup, ] } - /// The team-prefixed group, read from the app's own entitlement at runtime. - private static var accessGroup: String { + /// The team-prefixed shared group, read off a probe item in the default group. + static var accessGroup: String = { let probe: [String: Any] = [ kSecClass as String: kSecClassGenericPassword, kSecAttrAccount as String: "push.groupProbe", - kSecAttrService as String: "com.liketrek.trek.push", + kSecAttrService as String: service, kSecReturnAttributes as String: true, ] var result: CFTypeRef? @@ -482,25 +566,21 @@ enum TrekPushKeys { return "\(prefix).\(TrekPush.keychainGroup)" } return TrekPush.keychainGroup - } + }() - private static func read(_ account: String) -> Data? { + static func read(_ account: String) -> Data? { var q = query(account) q[kSecReturnData as String] = true var result: CFTypeRef? return SecItemCopyMatching(q as CFDictionary, &result) == errSecSuccess ? result as? Data : nil } - private static func write(_ account: String, _ data: Data) -> Bool { + @discardableResult + static func write(_ account: String, _ data: Data) -> Bool { SecItemDelete(query(account) as CFDictionary) var q = query(account) q[kSecValueData as String] = data q[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlock return SecItemAdd(q as CFDictionary, nil) == errSecSuccess } - - static func base64url(_ data: Data) -> String { - data.base64EncodedString().replacingOccurrences(of: "+", with: "-").replacingOccurrences(of: "/", with: "_") - .replacingOccurrences(of: "=", with: "") - } } diff --git a/client/ios/App/TREKWidgets/Info.plist b/client/ios/App/TREKWidgets/Info.plist new file mode 100644 index 000000000..9cc2043e3 --- /dev/null +++ b/client/ios/App/TREKWidgets/Info.plist @@ -0,0 +1,29 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleDisplayName + TREK + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + $(PRODUCT_BUNDLE_PACKAGE_TYPE) + CFBundleShortVersionString + $(MARKETING_VERSION) + CFBundleVersion + $(CURRENT_PROJECT_VERSION) + NSExtension + + NSExtensionPointIdentifier + com.apple.widgetkit-extension + + + diff --git a/client/ios/App/TREKWidgets/NextTripWidget.swift b/client/ios/App/TREKWidgets/NextTripWidget.swift new file mode 100644 index 000000000..e77f3615f --- /dev/null +++ b/client/ios/App/TREKWidgets/NextTripWidget.swift @@ -0,0 +1,118 @@ +import SwiftUI +import WidgetKit + +/// "Next trip" on the home screen: the trip and how far off it is, or while it +/// runs, today's day and the next stops (medium size). +struct NextTripEntry: TimelineEntry { + let date: Date + let snapshot: WidgetSnapshot? +} + +struct NextTripProvider: TimelineProvider { + func placeholder(in context: Context) -> NextTripEntry { + NextTripEntry(date: Date(), snapshot: nil) + } + + func getSnapshot(in context: Context, completion: @escaping (NextTripEntry) -> Void) { + completion(NextTripEntry(date: Date(), snapshot: WidgetSnapshot.load())) + } + + /// The app reloads the timeline whenever it writes a new snapshot; past + /// midnight the countdown moves on by itself. + func getTimeline(in context: Context, completion: @escaping (Timeline) -> Void) { + let now = Date() + let midnight = Calendar.current.startOfDay(for: now.addingTimeInterval(86_400)) + let entry = NextTripEntry(date: now, snapshot: WidgetSnapshot.load()) + completion(Timeline(entries: [entry], policy: .after(midnight))) + } +} + +struct NextTripWidgetView: View { + @Environment(\.widgetFamily) private var family + let entry: NextTripEntry + + var body: some View { + content + .widgetURL(entry.snapshot?.trip.flatMap { WidgetSnapshot.link($0.path) }) + .modifier(WidgetBackground()) + } + + @ViewBuilder + private var content: some View { + if let snapshot = entry.snapshot, let trip = snapshot.trip { + VStack(alignment: .leading, spacing: 4) { + Text(snapshot.today == nil ? snapshot.labels.nextTrip : snapshot.labels.today) + .font(.caption2.weight(.semibold)) + .foregroundStyle(.secondary) + .textCase(.uppercase) + Text(trip.title) + .font(.headline) + .lineLimit(2) + if let today = snapshot.today { + Text(today.dayLabel) + .font(.caption.weight(.semibold)) + .foregroundStyle(.secondary) + if family != .systemSmall { + stops(today.stops, nothing: snapshot.labels.nothingPlanned) + } + } else if let days = snapshot.daysUntilStart(from: entry.date), days > 0 { + Spacer(minLength: 0) + Text(days == 1 ? snapshot.labels.tomorrow : snapshot.labels.inDays.replacingOccurrences(of: "{n}", with: String(days))) + .font(.title3.weight(.bold)) + } + Spacer(minLength: 0) + } + .frame(maxWidth: .infinity, alignment: .leading) + } else { + VStack(alignment: .leading, spacing: 6) { + Text("TREK").font(.headline) + Text(entry.snapshot?.labels.noTrip ?? "") + .font(.caption) + .foregroundStyle(.secondary) + Spacer(minLength: 0) + } + .frame(maxWidth: .infinity, alignment: .leading) + } + } + + @ViewBuilder + private func stops(_ stops: [WidgetSnapshot.Stop], nothing: String) -> some View { + if stops.isEmpty { + Text(nothing).font(.caption).foregroundStyle(.secondary) + } else { + VStack(alignment: .leading, spacing: 2) { + ForEach(Array(stops.prefix(3).enumerated()), id: \.offset) { _, stop in + HStack(spacing: 6) { + Text(stop.time ?? "") + .font(.caption2.monospacedDigit().weight(.semibold)) + .foregroundStyle(.secondary) + .frame(minWidth: 36, alignment: .leading) + Text(stop.name).font(.caption).lineLimit(1) + } + } + } + } + } +} + +/// The system background on iOS 17 and later, the plain one before. +struct WidgetBackground: ViewModifier { + func body(content: Content) -> some View { + if #available(iOSApplicationExtension 17.0, *) { + content.containerBackground(.fill.tertiary, for: .widget) + } else { + content.padding() + } + } +} + +struct NextTripWidget: Widget { + var body: some WidgetConfiguration { + StaticConfiguration(kind: "NextTrip", provider: NextTripProvider()) { entry in + NextTripWidgetView(entry: entry) + } + .configurationDisplayName("TREK") + .description("Your next trip, and today's plan while you travel.") + .supportedFamilies([.systemSmall, .systemMedium]) + } +} diff --git a/client/ios/App/TREKWidgets/TREKWidgets.entitlements b/client/ios/App/TREKWidgets/TREKWidgets.entitlements new file mode 100644 index 000000000..6b6566872 --- /dev/null +++ b/client/ios/App/TREKWidgets/TREKWidgets.entitlements @@ -0,0 +1,10 @@ + + + + + keychain-access-groups + + $(AppIdentifierPrefix)com.liketrek.trek.shared + + + diff --git a/client/ios/App/TREKWidgets/TREKWidgetsBundle.swift b/client/ios/App/TREKWidgets/TREKWidgetsBundle.swift new file mode 100644 index 000000000..3db6222e0 --- /dev/null +++ b/client/ios/App/TREKWidgets/TREKWidgetsBundle.swift @@ -0,0 +1,12 @@ +import SwiftUI +import WidgetKit + +/// The TREK widgets: the next trip on the home screen, and the travel day as a +/// Live Activity. +@main +struct TREKWidgetsBundle: WidgetBundle { + var body: some Widget { + NextTripWidget() + TripDayLiveActivity() + } +} diff --git a/client/ios/App/TREKWidgets/TripDayAttributes.swift b/client/ios/App/TREKWidgets/TripDayAttributes.swift new file mode 100644 index 000000000..1fe7076ff --- /dev/null +++ b/client/ios/App/TREKWidgets/TripDayAttributes.swift @@ -0,0 +1,24 @@ +import ActivityKit +import Foundation + +/// The Live Activity for a travel day: which trip and day, and the next stop. +/// Compiled into both the app (which starts and updates it, TrekShellPlugin) +/// and the widget extension (which draws it, TripDayLiveActivity). +@available(iOS 16.1, *) +struct TripDayAttributes: ActivityAttributes { + struct ContentState: Codable, Hashable { + /// "Day 2 of 5", already in the user's language. + var dayLabel: String + /// The next stop, or the label for "all done" once the day's stops are behind. + var nextName: String + /// The next stop's time as the user formats it, if it has one. + var nextTime: String? + /// Stops behind, out of the day's stops. + var done: Int + var total: Int + } + + var tripTitle: String + /// The app path a tap opens. + var path: String +} diff --git a/client/ios/App/TREKWidgets/TripDayLiveActivity.swift b/client/ios/App/TREKWidgets/TripDayLiveActivity.swift new file mode 100644 index 000000000..4d8d97a7d --- /dev/null +++ b/client/ios/App/TREKWidgets/TripDayLiveActivity.swift @@ -0,0 +1,55 @@ +import ActivityKit +import SwiftUI +import WidgetKit + +/// A travel day on the lock screen and in the Dynamic Island: the next stop and +/// its time, and how much of the day is behind. +struct TripDayLiveActivity: Widget { + var body: some WidgetConfiguration { + ActivityConfiguration(for: TripDayAttributes.self) { context in + VStack(alignment: .leading, spacing: 6) { + HStack { + Text(context.attributes.tripTitle).font(.caption.weight(.semibold)).foregroundStyle(.secondary) + Spacer() + Text(context.state.dayLabel).font(.caption.weight(.semibold)).foregroundStyle(.secondary) + } + HStack(alignment: .firstTextBaseline) { + Image(systemName: "mappin.circle.fill") + Text(context.state.nextName).font(.headline).lineLimit(1) + Spacer() + if let time = context.state.nextTime { + Text(time).font(.headline.monospacedDigit()) + } + } + ProgressView(value: Double(context.state.done), total: Double(max(context.state.total, 1))) + } + .padding() + .widgetURL(WidgetSnapshot.link(context.attributes.path)) + } dynamicIsland: { context in + DynamicIsland { + DynamicIslandExpandedRegion(.leading) { + Label(context.state.dayLabel, systemImage: "map").font(.caption) + } + DynamicIslandExpandedRegion(.trailing) { + if let time = context.state.nextTime { + Text(time).font(.caption.monospacedDigit()) + } + } + DynamicIslandExpandedRegion(.bottom) { + VStack(alignment: .leading, spacing: 4) { + Text(context.state.nextName).font(.headline).lineLimit(1) + ProgressView(value: Double(context.state.done), total: Double(max(context.state.total, 1))) + } + } + } compactLeading: { + Image(systemName: "mappin.circle.fill") + } compactTrailing: { + Text(context.state.nextTime ?? "\(context.state.done)/\(context.state.total)") + .font(.caption2.monospacedDigit()) + } minimal: { + Image(systemName: "mappin.circle.fill") + } + .widgetURL(WidgetSnapshot.link(context.attributes.path)) + } + } +} diff --git a/client/ios/App/TREKWidgets/WidgetSnapshot.swift b/client/ios/App/TREKWidgets/WidgetSnapshot.swift new file mode 100644 index 000000000..54789ee8f --- /dev/null +++ b/client/ios/App/TREKWidgets/WidgetSnapshot.swift @@ -0,0 +1,71 @@ +import Foundation +import Security + +/// What the app last told the widgets (native/widgets.ts writes it through +/// TrekShell.setWidgetSnapshot into the keychain group the app and its +/// extensions share). Texts arrive already translated, so the widget needs no +/// localisation of its own and always speaks the language the app does. +struct WidgetSnapshot: Codable { + struct Trip: Codable { + var title: String + var start: String + var end: String + var path: String + } + + struct Stop: Codable, Hashable { + var time: String? + var name: String + } + + struct Today: Codable { + var dayLabel: String + var stops: [Stop] + } + + struct Labels: Codable { + var nextTrip: String + var today: String + var noTrip: String + /// Contains "{n}". + var inDays: String + var tomorrow: String + var nothingPlanned: String + } + + var trip: Trip? + var today: Today? + var labels: Labels + + static func load() -> WidgetSnapshot? { + let query: [String: Any] = [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: "com.liketrek.trek.push", + kSecAttrAccount as String: "widget.snapshot", + kSecReturnData as String: true, + ] + var result: CFTypeRef? + guard SecItemCopyMatching(query as CFDictionary, &result) == errSecSuccess, let data = result as? Data else { return nil } + return try? JSONDecoder().decode(WidgetSnapshot.self, from: data) + } + + /// Whole days from today to the trip's start, in the device's calendar. + func daysUntilStart(from now: Date = Date()) -> Int? { + guard let trip, let start = WidgetSnapshot.day(trip.start) else { return nil } + let calendar = Calendar.current + return calendar.dateComponents([.day], from: calendar.startOfDay(for: now), to: start).day + } + + static func day(_ iso: String) -> Date? { + let formatter = DateFormatter() + formatter.calendar = Calendar(identifier: .gregorian) + formatter.locale = Locale(identifier: "en_US_POSIX") + formatter.dateFormat = "yyyy-MM-dd" + return formatter.date(from: String(iso.prefix(10))) + } + + /// The app link a tap opens: com.liketrek.trek://navigate. + static func link(_ path: String) -> URL? { + URL(string: "com.liketrek.trek://navigate\(path.hasPrefix("/") ? path : "/" + path)") + } +} diff --git a/client/ios/scripts/share-with-app.rb b/client/ios/scripts/share-with-app.rb new file mode 100644 index 000000000..f269d0549 --- /dev/null +++ b/client/ios/scripts/share-with-app.rb @@ -0,0 +1,24 @@ +# Compiles a source file of an extension into the App target too. +# +# ruby ios/scripts/share-with-app.rb +# +# For types both sides need: the Live Activity's attributes are started by the +# app and drawn by the widget extension, so both must know them. Running it +# again changes nothing. +require 'xcodeproj' + +group_name, file = ARGV +abort 'usage: share-with-app.rb ' unless group_name && file + +project = Xcodeproj::Project.open(File.expand_path('../App/App.xcodeproj', __dir__)) +app = project.targets.find { |t| t.name == 'App' } or abort 'no App target' +group = project.main_group[group_name] or abort "no group #{group_name}" +ref = group.files.find { |f| f.path == file } or abort "no #{file} in #{group_name}" + +if app.source_build_phase.files_references.include?(ref) + puts "#{file} is already in App" +else + app.add_file_references([ref]) + project.save + puts "#{file} now compiles into App too" +end diff --git a/client/src/App.tsx b/client/src/App.tsx index 303af78fd..bcf5cad6a 100644 --- a/client/src/App.tsx +++ b/client/src/App.tsx @@ -35,6 +35,7 @@ import NewVersionNotice from './components/Layout/NewVersionNotice' import NativeUpdateNotice from './components/Layout/NativeUpdateNotice' import AppLockGate from './components/Layout/AppLockGate' import NativeImportSheet from './components/Layout/NativeImportSheet' +import NativeWidgetsSync from './components/Layout/NativeWidgetsSync' import { SystemNoticeHost } from './components/SystemNotices/SystemNoticeHost.js' import HelpPanel from './components/Help/HelpPanel' // Notice action registrations (side-effect imports): @@ -448,6 +449,7 @@ export default function App() { + {/* One boundary for all route chunks, above so it stays mounted across navigations. react-router runs location updates inside a transition, so a mounted boundary keeps the current page on screen instead of flashing diff --git a/client/src/components/Layout/NativeWidgetsSync.tsx b/client/src/components/Layout/NativeWidgetsSync.tsx new file mode 100644 index 000000000..3062c21f6 --- /dev/null +++ b/client/src/components/Layout/NativeWidgetsSync.tsx @@ -0,0 +1,70 @@ +/** + * NativeWidgetsSync: keeps the iOS home-screen widget and the travel-day Live + * Activity in step with the trips stored on this device (native/widgets.ts). + * Runs at start, whenever the app comes back to the foreground and every + * quarter hour while it is open, so the next stop moves on through the day. + * Renders nothing; outside an iOS binary with the widgets it does nothing. + */ +import { App } from '@capacitor/app'; +import { useEffect } from 'react'; +import { offlineDb } from '../../db/offlineDb'; +import { useTranslation } from '../../i18n'; +import { useNativeCapabilities } from '../../native/capabilities'; +import { buildSnapshot, pickTrip, publishWidgets, todayOf, tripDayState, widgetsActive } from '../../native/widgets'; +import { useSettingsStore } from '../../store/settingsStore'; +import { formatTime } from '../../utils/formatters'; +import { localDateStr } from '../../vacay/monthGrid'; + +const REFRESH_MS = 15 * 60 * 1000; + +export default function NativeWidgetsSync(): null { + const { t, language } = useTranslation(); + const { caps } = useNativeCapabilities(); + const timeFormat = useSettingsStore((s) => s.settings.time_format); + + useEffect(() => { + if (!widgetsActive()) return; + let cancelled = false; + + const sync = async () => { + const now = new Date(); + const today = localDateStr(now.getFullYear(), now.getMonth(), now.getDate()); + const trips = await offlineDb.trips.toArray(); + const trip = pickTrip(trips, today); + const days = trip ? await offlineDb.days.where('trip_id').equals(trip.id).toArray() : []; + const day = trip + ? todayOf( + trip, + days, + today, + (n, m) => t('native.widget.dayOf', { n, m }), + (time) => formatTime(time, language, timeFormat) + ) + : null; + if (cancelled) return; + const snapshot = buildSnapshot(trip, day, { + nextTrip: t('dashboard.nextTrip'), + today: t('native.widget.today'), + noTrip: t('native.widget.noTrip'), + inDays: t('native.widget.inDays'), + tomorrow: t('native.widget.tomorrow'), + nothingPlanned: t('native.widget.nothingPlanned'), + }); + const live = day ? tripDayState(day, now.getHours() * 60 + now.getMinutes(), t('native.widget.dayDone')) : null; + await publishWidgets(snapshot, live); + }; + + void sync(); + const timer = window.setInterval(() => void sync(), REFRESH_MS); + const listener = App.addListener('appStateChange', ({ isActive }) => { + if (isActive) void sync(); + }); + return () => { + cancelled = true; + window.clearInterval(timer); + void listener.then((handle) => handle.remove()); + }; + }, [caps, t, language, timeFormat]); + + return null; +} diff --git a/client/src/native/nativeApp.test.ts b/client/src/native/nativeApp.test.ts index 885c05bfa..6f5b531be 100644 --- a/client/src/native/nativeApp.test.ts +++ b/client/src/native/nativeApp.test.ts @@ -24,7 +24,7 @@ vi.mock('./capabilities', () => ({ })); vi.mock('./geolocation', () => ({ installNativeGeolocation: vi.fn() })); vi.mock('./sharedFiles', () => ({ startSharedFiles: vi.fn(async () => {}) })); -vi.mock('./push', () => ({ startNativePush: vi.fn(async () => {}) })); +vi.mock('./push', () => ({ startNativePush: vi.fn(async () => {}), openPushTarget: vi.fn() })); vi.mock('../mobile/overlayStack', () => ({ closeTopOverlay: vi.fn(() => false) })); function backButtonHandler(): (event: { canGoBack: boolean }) => void { diff --git a/client/src/native/nativeApp.ts b/client/src/native/nativeApp.ts index dd50fd6f1..059f1c231 100644 --- a/client/src/native/nativeApp.ts +++ b/client/src/native/nativeApp.ts @@ -8,10 +8,10 @@ import { checkAppUpdate, loadNativeCapabilities } from './capabilities'; import { installNativeGeolocation } from './geolocation'; import { keepOfflineShellFresh } from './offlineShell'; import { isNativeApp, isNativeIos } from './platform'; -import { startNativePush } from './push'; +import { openPushTarget, startNativePush } from './push'; import { reportNativeFailure } from './reportFailure'; import { startSharedFiles } from './sharedFiles'; -import { isUnimplemented } from './trekShell'; +import { APP_URL_SCHEME, isUnimplemented } from './trekShell'; /** Long enough that the warm-up never competes with the first screen's requests. */ const OFFLINE_SHELL_DELAY_MS = 15_000; @@ -34,6 +34,12 @@ export function startNativeApp(): void { // Taps on TREK notifications open the place they point at. void loadNativeCapabilities().then(() => startNativePush()); + // A widget or Live Activity tap opens com.liketrek.trek://navigate/. + void App.addListener('appUrlOpen', ({ url }) => { + const prefix = `${APP_URL_SCHEME}://navigate`; + if (url.startsWith(prefix)) openPushTarget(url.slice(prefix.length) || '/'); + }); + // A tap on the status bar scrolls the list under it back to the top, as in // every iOS app (the status-bar plugin fires statusTap on iOS). window.addEventListener('statusTap', scrollToTop); diff --git a/client/src/native/trekShell.ts b/client/src/native/trekShell.ts index 3d2d044e7..0229e2b87 100644 --- a/client/src/native/trekShell.ts +++ b/client/src/native/trekShell.ts @@ -59,6 +59,19 @@ export interface TrekShellPlugin { registerPush(): Promise<{ endpoint: string; keys: { p256dh: string; auth: string } }>; /** Feature nativePush: the notification the app was opened from, before the UI ran. */ takeOpenedPush(): Promise<{ url: string | null }>; + /** Feature widgets: what the home-screen widget shows (native/widgets.ts), as JSON. */ + setWidgetSnapshot(options: { json: string }): Promise; + /** Feature liveActivity: starts the travel day's Live Activity, or updates the running one. */ + syncTripDay(options: { + tripTitle: string; + path: string; + dayLabel: string; + nextName: string; + nextTime?: string; + done: number; + total: number; + }): Promise<{ running: boolean }>; + endTripDay(): Promise; addListener( event: 'pushOpened', listener: (payload: { url: string }) => void diff --git a/client/src/native/widgets.test.ts b/client/src/native/widgets.test.ts new file mode 100644 index 000000000..e830a53fc --- /dev/null +++ b/client/src/native/widgets.test.ts @@ -0,0 +1,129 @@ +import { describe, expect, it, vi } from 'vitest'; +import type { Day, Trip } from '../types'; + +vi.mock('./platform', () => ({ isNativeIos: vi.fn(() => true) })); +vi.mock('./capabilities', () => ({ hasNativeFeature: vi.fn(() => true) })); +vi.mock('./reportFailure', () => ({ reportNativeFailure: vi.fn() })); +vi.mock('./trekShell', () => ({ + TrekShell: { + setWidgetSnapshot: vi.fn(async () => {}), + syncTripDay: vi.fn(async () => ({ running: true })), + endTripDay: vi.fn(async () => {}), + }, +})); + +import { TrekShell } from './trekShell'; +import { buildSnapshot, pickTrip, publishWidgets, todayOf, tripDayState } from './widgets'; + +const trip = (id: number, start: string | null, end: string | null, archived = 0) => + ({ id, title: `Trip ${id}`, start_date: start, end_date: end, is_archived: archived }) as unknown as Trip; + +const day = (id: number, n: number, date: string, places: { name: string; time?: string }[]) => + ({ + id, + trip_id: 1, + day_number: n, + date, + assignments: places.map((p, i) => ({ + id: id * 10 + i, + order_index: i, + place: { name: p.name, place_time: p.time ?? null }, + })), + }) as unknown as Day; + +const labels = { + nextTrip: 'Next', + today: 'Today', + noTrip: 'None', + inDays: 'in {n} days', + tomorrow: 'Tomorrow', + nothingPlanned: '-', +}; + +describe('pickTrip', () => { + it('prefers the running trip, then the next upcoming one', () => { + const trips = [ + trip(1, '2026-12-01', '2026-12-05'), + trip(2, '2026-11-20', '2026-11-25'), + trip(3, '2026-11-01', '2026-11-10'), + ]; + expect(pickTrip(trips, '2026-11-06')?.id).toBe(3); + expect(pickTrip(trips, '2026-11-12')?.id).toBe(2); + }); + + it('skips undated, archived and finished trips', () => { + expect( + pickTrip( + [trip(1, null, null), trip(2, '2026-12-01', '2026-12-02', 1), trip(3, '2026-01-01', '2026-01-02')], + '2026-11-06' + ) + ).toBeNull(); + }); +}); + +describe('todayOf and tripDayState', () => { + const days = [ + day(2, 2, '2026-11-07', []), + day(1, 1, '2026-11-06', [{ name: 'Museum', time: '09:00' }, { name: 'Walk' }, { name: 'Dinner', time: '19:30' }]), + ]; + + it('finds today in day order and keeps the plan order', () => { + const today = todayOf( + trip(1, '2026-11-06', '2026-11-07'), + days, + '2026-11-06', + (n, m) => `${n}/${m}`, + (t) => `T${t}` + ); + expect(today?.dayLabel).toBe('1/2'); + expect(today?.stops.map((s) => s.name)).toEqual(['Museum', 'Walk', 'Dinner']); + expect(today?.stops[0]).toMatchObject({ time: 'T09:00', minutes: 540 }); + }); + + it('is null on a day outside the trip', () => { + expect( + todayOf( + trip(1, '2026-11-06', '2026-11-07'), + days, + '2026-11-09', + () => '', + (t) => t + ) + ).toBeNull(); + }); + + it('names the next timed stop and counts the ones behind', () => { + const today = todayOf( + trip(1, '2026-11-06', '2026-11-07'), + days, + '2026-11-06', + () => 'D', + (t) => t + )!; + expect(tripDayState(today, 8 * 60, 'done')).toMatchObject({ nextName: 'Museum', done: 0, total: 2 }); + expect(tripDayState(today, 12 * 60, 'done')).toMatchObject({ nextName: 'Dinner', nextTime: '19:30', done: 1 }); + expect(tripDayState(today, 22 * 60, 'done')).toMatchObject({ nextName: 'done', done: 2, nextTime: undefined }); + }); +}); + +describe('publishWidgets', () => { + it('writes the snapshot without the internal minutes and ends the activity on a day without times', async () => { + const snapshot = buildSnapshot( + trip(1, '2026-11-06', '2026-11-07'), + { tripTitle: 'Trip 1', path: '/trips/1', dayLabel: 'D', stops: [{ name: 'Walk', time: null, minutes: null }] }, + labels + ); + expect(snapshot.today?.stops[0]).toEqual({ name: 'Walk', time: null }); + await publishWidgets(snapshot, { + tripTitle: 'Trip 1', + path: '/trips/1', + dayLabel: 'D', + nextName: 'x', + done: 0, + total: 0, + }); + expect(JSON.parse(vi.mocked(TrekShell.setWidgetSnapshot).mock.calls[0][0].json).trip.path).toBe('/trips/1'); + expect(TrekShell.endTripDay).toHaveBeenCalled(); + expect(TrekShell.syncTripDay).not.toHaveBeenCalled(); + }); +}); diff --git a/client/src/native/widgets.ts b/client/src/native/widgets.ts new file mode 100644 index 000000000..d4453def9 --- /dev/null +++ b/client/src/native/widgets.ts @@ -0,0 +1,123 @@ +import type { Day, Trip } from '../types'; +import { hasNativeFeature } from './capabilities'; +import { isNativeIos } from './platform'; +import { reportNativeFailure } from './reportFailure'; +import { TrekShell } from './trekShell'; + +/** + * What the home-screen widget and the travel-day Live Activity show, built from + * the trips this device keeps offline (db/offlineDb) and handed to the app + * (TrekShell.setWidgetSnapshot, syncTripDay). The texts go along translated, so + * the widget speaks the app's language without localising anything itself. + */ +export interface WidgetLabels { + nextTrip: string; + today: string; + noTrip: string; + /** Contains "{n}". */ + inDays: string; + tomorrow: string; + nothingPlanned: string; +} + +export interface WidgetStop { + time: string | null; + name: string; + /** Minutes after midnight, for picking the next stop; not sent to the widget. */ + minutes: number | null; +} + +export interface WidgetSnapshot { + trip: { title: string; start: string; end: string; path: string } | null; + today: { dayLabel: string; stops: { time: string | null; name: string }[] } | null; + labels: WidgetLabels; +} + +export interface TripDay { + tripTitle: string; + path: string; + dayLabel: string; + stops: WidgetStop[]; +} + +export function widgetsActive(): boolean { + return isNativeIos() && hasNativeFeature('widgets'); +} + +function minutesOf(time: string | null | undefined): number | null { + const m = /^(\d{1,2}):(\d{2})/.exec(time ?? ''); + return m ? Number(m[1]) * 60 + Number(m[2]) : null; +} + +/** + * The running trip if there is one, else the next to start. Trips without dates + * and trips already over are not candidates. + */ +export function pickTrip(trips: Trip[], today: string): Trip | null { + const dated = trips.filter((t) => t.start_date && t.end_date && !t.is_archived); + const running = dated.find((t) => t.start_date! <= today && t.end_date! >= today); + if (running) return running; + const upcoming = dated + .filter((t) => t.start_date! > today) + .sort((a, b) => a.start_date!.localeCompare(b.start_date!)); + return upcoming[0] ?? null; +} + +/** Today's day of the trip with its stops in plan order, if the trip runs today. */ +export function todayOf( + trip: Trip, + days: Day[], + today: string, + dayLabel: (index: number, total: number) => string, + formatTime: (time: string) => string +): TripDay | null { + const ordered = days.filter((d) => d.trip_id === trip.id).sort((a, b) => (a.day_number ?? 0) - (b.day_number ?? 0)); + const index = ordered.findIndex((d) => (d.date ?? '').slice(0, 10) === today); + if (index < 0) return null; + const day = ordered[index]; + const stops = [...(day.assignments ?? [])] + .sort((a, b) => (a.order_index ?? 0) - (b.order_index ?? 0)) + .filter((a) => a.place?.name) + .map((a) => ({ + name: a.place!.name, + time: a.place?.place_time ? formatTime(a.place.place_time.slice(0, 5)) : null, + minutes: minutesOf(a.place?.place_time), + })); + return { tripTitle: trip.title, path: `/trips/${trip.id}`, dayLabel: dayLabel(index + 1, ordered.length), stops }; +} + +export function buildSnapshot(trip: Trip | null, day: TripDay | null, labels: WidgetLabels): WidgetSnapshot { + return { + trip: trip ? { title: trip.title, start: trip.start_date!, end: trip.end_date!, path: `/trips/${trip.id}` } : null, + today: day ? { dayLabel: day.dayLabel, stops: day.stops.map(({ time, name }) => ({ time, name })) } : null, + labels, + }; +} + +/** The Live Activity's state: the first stop whose time is still ahead, else the last. */ +export function tripDayState(day: TripDay, nowMinutes: number, allDone: string) { + const timed = day.stops.filter((s) => s.minutes != null); + const nextIndex = day.stops.findIndex((s) => s.minutes != null && s.minutes >= nowMinutes); + const done = nextIndex < 0 ? timed.length : day.stops.slice(0, nextIndex).filter((s) => s.minutes != null).length; + const next = nextIndex >= 0 ? day.stops[nextIndex] : null; + return { + tripTitle: day.tripTitle, + path: day.path, + dayLabel: day.dayLabel, + nextName: next?.name ?? allDone, + nextTime: next?.time ?? undefined, + done, + total: timed.length, + }; +} + +export async function publishWidgets( + snapshot: WidgetSnapshot, + liveDay: ReturnType | null +): Promise { + if (!widgetsActive()) return; + await TrekShell.setWidgetSnapshot({ json: JSON.stringify(snapshot) }).catch(reportNativeFailure); + if (!hasNativeFeature('liveActivity')) return; + if (liveDay && liveDay.total > 0) await TrekShell.syncTripDay(liveDay).catch(reportNativeFailure); + else await TrekShell.endTripDay().catch(reportNativeFailure); +} diff --git a/shared/src/i18n/ar/native.ts b/shared/src/i18n/ar/native.ts index 0ded8f83f..3f010b3c7 100644 --- a/shared/src/i18n/ar/native.ts +++ b/shared/src/i18n/ar/native.ts @@ -82,6 +82,13 @@ const native: TranslationStrings = { 'native.lock.settingHint': 'يطلب ذلك عند فتح TREK وبعد نصف دقيقة في الخلفية، ويخفي التطبيق في مبدّل التطبيقات.', 'native.share.title': 'الاستيراد إلى أي رحلة؟', 'native.share.noTrips': 'لا توجد رحلة بعد. أنشئ رحلة أولًا ثم شارك المستند مجددًا.', + 'native.widget.dayOf': 'اليوم {n} من {m}', + 'native.widget.today': 'اليوم', + 'native.widget.noTrip': 'لا توجد رحلة مخططة بعد', + 'native.widget.inDays': 'بعد {n} أيام', + 'native.widget.tomorrow': 'غدًا', + 'native.widget.nothingPlanned': 'لا شيء مخطط لليوم', + 'native.widget.dayDone': 'انتهى كل شيء لليوم', }; export default native; diff --git a/shared/src/i18n/az/native.ts b/shared/src/i18n/az/native.ts index 1c5b8b7f5..e341a8638 100644 --- a/shared/src/i18n/az/native.ts +++ b/shared/src/i18n/az/native.ts @@ -84,6 +84,13 @@ const native: TranslationStrings = { 'TREK açılanda və arxa fonda yarım dəqiqədən sonra soruşur, tətbiqi tətbiq dəyişdiricisində gizlədir.', 'native.share.title': 'Hansı səyahətə idxal edilsin?', 'native.share.noTrips': 'Hələ səyahət yoxdur. Əvvəlcə birini yaradın, sonra sənədi yenidən paylaşın.', + 'native.widget.dayOf': '{m} gündən {n}-ci gün', + 'native.widget.today': 'Bu gün', + 'native.widget.noTrip': 'Hələ planlanmış səyahət yoxdur', + 'native.widget.inDays': '{n} gün sonra', + 'native.widget.tomorrow': 'Sabah', + 'native.widget.nothingPlanned': 'Bu gün üçün plan yoxdur', + 'native.widget.dayDone': 'Bu gün üçün hər şey bitdi', }; export default native; diff --git a/shared/src/i18n/br/native.ts b/shared/src/i18n/br/native.ts index 7a540640d..1fefd02e2 100644 --- a/shared/src/i18n/br/native.ts +++ b/shared/src/i18n/br/native.ts @@ -84,6 +84,13 @@ const native: TranslationStrings = { 'Pede ao abrir o TREK e após meio minuto em segundo plano, e oculta o app no seletor de apps.', 'native.share.title': 'Importar para qual viagem?', 'native.share.noTrips': 'Ainda não há viagens. Crie uma primeiro e compartilhe o documento de novo.', + 'native.widget.dayOf': 'Dia {n} de {m}', + 'native.widget.today': 'Hoje', + 'native.widget.noTrip': 'Nenhuma viagem planejada ainda', + 'native.widget.inDays': 'em {n} dias', + 'native.widget.tomorrow': 'Amanhã', + 'native.widget.nothingPlanned': 'Nada planejado para hoje', + 'native.widget.dayDone': 'Tudo feito por hoje', }; export default native; diff --git a/shared/src/i18n/ca/native.ts b/shared/src/i18n/ca/native.ts index c007e6386..e83fea149 100644 --- a/shared/src/i18n/ca/native.ts +++ b/shared/src/i18n/ca/native.ts @@ -84,6 +84,13 @@ const native: TranslationStrings = { 'Ho demana en obrir TREK i després de mig minut en segon pla, i amaga l’app al selector d’apps.', 'native.share.title': 'A quin viatge vols importar-ho?', 'native.share.noTrips': 'Encara no hi ha cap viatge. Crea’n un i torna a compartir el document.', + 'native.widget.dayOf': 'Dia {n} de {m}', + 'native.widget.today': 'Avui', + 'native.widget.noTrip': 'Encara no hi ha cap viatge planificat', + 'native.widget.inDays': 'd’aquí a {n} dies', + 'native.widget.tomorrow': 'Demà', + 'native.widget.nothingPlanned': 'Res planificat per avui', + 'native.widget.dayDone': 'Tot fet per avui', }; export default native; diff --git a/shared/src/i18n/cs/native.ts b/shared/src/i18n/cs/native.ts index 73fba6fa8..71e0feaf2 100644 --- a/shared/src/i18n/cs/native.ts +++ b/shared/src/i18n/cs/native.ts @@ -84,6 +84,13 @@ const native: TranslationStrings = { 'Zeptá se při otevření TREK a po půl minutě na pozadí a skryje aplikaci v přepínači aplikací.', 'native.share.title': 'Importovat do které cesty?', 'native.share.noTrips': 'Zatím žádná cesta. Nejdřív nějakou vytvořte a pak dokument sdílejte znovu.', + 'native.widget.dayOf': 'Den {n} z {m}', + 'native.widget.today': 'Dnes', + 'native.widget.noTrip': 'Zatím žádná naplánovaná cesta', + 'native.widget.inDays': 'za {n} dní', + 'native.widget.tomorrow': 'Zítra', + 'native.widget.nothingPlanned': 'Na dnešek nic naplánováno', + 'native.widget.dayDone': 'Na dnešek hotovo', }; export default native; diff --git a/shared/src/i18n/de/native.ts b/shared/src/i18n/de/native.ts index 39444941e..2ede2c96e 100644 --- a/shared/src/i18n/de/native.ts +++ b/shared/src/i18n/de/native.ts @@ -85,6 +85,13 @@ const native: TranslationStrings = { 'Fragt beim Öffnen und nach einer halben Minute im Hintergrund nach und verbirgt TREK im App-Umschalter.', 'native.share.title': 'In welchen Trip importieren?', 'native.share.noTrips': 'Noch kein Trip. Lege zuerst einen an und teile das Dokument dann erneut.', + 'native.widget.dayOf': 'Tag {n} von {m}', + 'native.widget.today': 'Heute', + 'native.widget.noTrip': 'Noch keine Reise geplant', + 'native.widget.inDays': 'in {n} Tagen', + 'native.widget.tomorrow': 'Morgen', + 'native.widget.nothingPlanned': 'Für heute nichts geplant', + 'native.widget.dayDone': 'Für heute alles geschafft', }; export default native; diff --git a/shared/src/i18n/en/native.ts b/shared/src/i18n/en/native.ts index 35b668677..a18ea2194 100644 --- a/shared/src/i18n/en/native.ts +++ b/shared/src/i18n/en/native.ts @@ -84,6 +84,13 @@ const native: TranslationStrings = { 'Asks when TREK opens and after half a minute in the background, and hides the app in the app switcher.', 'native.share.title': 'Import into which trip?', 'native.share.noTrips': 'No trip yet. Create one first, then share the document again.', + 'native.widget.dayOf': 'Day {n} of {m}', + 'native.widget.today': 'Today', + 'native.widget.noTrip': 'No trip planned yet', + 'native.widget.inDays': 'in {n} days', + 'native.widget.tomorrow': 'Tomorrow', + 'native.widget.nothingPlanned': 'Nothing planned for today', + 'native.widget.dayDone': 'All done for today', }; export default native; diff --git a/shared/src/i18n/es/native.ts b/shared/src/i18n/es/native.ts index d54810e8a..3e362472b 100644 --- a/shared/src/i18n/es/native.ts +++ b/shared/src/i18n/es/native.ts @@ -85,6 +85,13 @@ const native: TranslationStrings = { 'Lo pide al abrir TREK y tras medio minuto en segundo plano, y oculta la app en el selector de apps.', 'native.share.title': '¿En qué viaje importar?', 'native.share.noTrips': 'Aún no hay viajes. Crea uno primero y vuelve a compartir el documento.', + 'native.widget.dayOf': 'Día {n} de {m}', + 'native.widget.today': 'Hoy', + 'native.widget.noTrip': 'Aún no hay ningún viaje planeado', + 'native.widget.inDays': 'en {n} días', + 'native.widget.tomorrow': 'Mañana', + 'native.widget.nothingPlanned': 'Nada planeado para hoy', + 'native.widget.dayDone': 'Todo hecho por hoy', }; export default native; diff --git a/shared/src/i18n/et/native.ts b/shared/src/i18n/et/native.ts index 98ecfb60b..5df69255f 100644 --- a/shared/src/i18n/et/native.ts +++ b/shared/src/i18n/et/native.ts @@ -84,6 +84,13 @@ const native: TranslationStrings = { 'Küsib TREK-i avamisel ja pärast poolt minutit taustal ning peidab rakenduse rakenduste vahetajas.', 'native.share.title': 'Millisesse reisi importida?', 'native.share.noTrips': 'Reise veel pole. Loo esmalt üks ja jaga dokumenti uuesti.', + 'native.widget.dayOf': 'Päev {n}/{m}', + 'native.widget.today': 'Täna', + 'native.widget.noTrip': 'Reisi pole veel planeeritud', + 'native.widget.inDays': '{n} päeva pärast', + 'native.widget.tomorrow': 'Homme', + 'native.widget.nothingPlanned': 'Tänaseks pole midagi planeeritud', + 'native.widget.dayDone': 'Tänaseks kõik tehtud', }; export default native; diff --git a/shared/src/i18n/fr/native.ts b/shared/src/i18n/fr/native.ts index 4a4fd48d7..ce7c71376 100644 --- a/shared/src/i18n/fr/native.ts +++ b/shared/src/i18n/fr/native.ts @@ -85,6 +85,13 @@ const native: TranslationStrings = { 'Le demande à l’ouverture de TREK et après une demi-minute en arrière-plan, et masque l’app dans le sélecteur d’apps.', 'native.share.title': 'Importer dans quel voyage ?', 'native.share.noTrips': 'Pas encore de voyage. Créez-en un, puis partagez à nouveau le document.', + 'native.widget.dayOf': 'Jour {n} sur {m}', + 'native.widget.today': 'Aujourd’hui', + 'native.widget.noTrip': 'Aucun voyage prévu pour l’instant', + 'native.widget.inDays': 'dans {n} jours', + 'native.widget.tomorrow': 'Demain', + 'native.widget.nothingPlanned': 'Rien de prévu aujourd’hui', + 'native.widget.dayDone': 'Tout est fait pour aujourd’hui', }; export default native; diff --git a/shared/src/i18n/gr/native.ts b/shared/src/i18n/gr/native.ts index f666f08ee..0b814fa2e 100644 --- a/shared/src/i18n/gr/native.ts +++ b/shared/src/i18n/gr/native.ts @@ -87,6 +87,13 @@ const native: TranslationStrings = { 'Ζητείται κατά το άνοιγμα του TREK και μετά από μισό λεπτό στο παρασκήνιο, και η εφαρμογή κρύβεται στην εναλλαγή εφαρμογών.', 'native.share.title': 'Εισαγωγή σε ποιο ταξίδι;', 'native.share.noTrips': 'Δεν υπάρχει ακόμα ταξίδι. Δημιουργήστε ένα πρώτα και κοινοποιήστε ξανά το έγγραφο.', + 'native.widget.dayOf': 'Ημέρα {n} από {m}', + 'native.widget.today': 'Σήμερα', + 'native.widget.noTrip': 'Δεν υπάρχει ακόμα προγραμματισμένο ταξίδι', + 'native.widget.inDays': 'σε {n} ημέρες', + 'native.widget.tomorrow': 'Αύριο', + 'native.widget.nothingPlanned': 'Τίποτα προγραμματισμένο για σήμερα', + 'native.widget.dayDone': 'Όλα έγιναν για σήμερα', }; export default native; diff --git a/shared/src/i18n/he/native.ts b/shared/src/i18n/he/native.ts index da74576c8..4d3aacec9 100644 --- a/shared/src/i18n/he/native.ts +++ b/shared/src/i18n/he/native.ts @@ -82,6 +82,13 @@ const native: TranslationStrings = { 'native.lock.settingHint': 'מבקש בעת פתיחת TREK ואחרי חצי דקה ברקע, ומסתיר את האפליקציה במחליף האפליקציות.', 'native.share.title': 'לייבא לאיזה טיול?', 'native.share.noTrips': 'אין עדיין טיול. צרו טיול ואז שתפו את המסמך שוב.', + 'native.widget.dayOf': 'יום {n} מתוך {m}', + 'native.widget.today': 'היום', + 'native.widget.noTrip': 'עדיין לא תוכנן טיול', + 'native.widget.inDays': 'בעוד {n} ימים', + 'native.widget.tomorrow': 'מחר', + 'native.widget.nothingPlanned': 'אין תוכניות להיום', + 'native.widget.dayDone': 'הכול הושלם להיום', }; export default native; diff --git a/shared/src/i18n/hu/native.ts b/shared/src/i18n/hu/native.ts index 194b29540..6094fecfc 100644 --- a/shared/src/i18n/hu/native.ts +++ b/shared/src/i18n/hu/native.ts @@ -86,6 +86,13 @@ const native: TranslationStrings = { 'Rákérdez a TREK megnyitásakor és fél perc háttérben töltött idő után, és elrejti az alkalmazást az alkalmazásváltóban.', 'native.share.title': 'Melyik utazásba importáljuk?', 'native.share.noTrips': 'Még nincs utazás. Előbb hozz létre egyet, aztán oszd meg újra a dokumentumot.', + 'native.widget.dayOf': '{m}/{n}. nap', + 'native.widget.today': 'Ma', + 'native.widget.noTrip': 'Még nincs tervezett utazás', + 'native.widget.inDays': '{n} nap múlva', + 'native.widget.tomorrow': 'Holnap', + 'native.widget.nothingPlanned': 'Mára nincs semmi tervezve', + 'native.widget.dayDone': 'Mára minden kész', }; export default native; diff --git a/shared/src/i18n/id/native.ts b/shared/src/i18n/id/native.ts index 47e658e33..b67667526 100644 --- a/shared/src/i18n/id/native.ts +++ b/shared/src/i18n/id/native.ts @@ -85,6 +85,13 @@ const native: TranslationStrings = { 'Meminta saat TREK dibuka dan setelah setengah menit di latar belakang, serta menyembunyikan aplikasi di pengalih aplikasi.', 'native.share.title': 'Impor ke perjalanan mana?', 'native.share.noTrips': 'Belum ada perjalanan. Buat satu dulu, lalu bagikan dokumennya lagi.', + 'native.widget.dayOf': 'Hari {n} dari {m}', + 'native.widget.today': 'Hari ini', + 'native.widget.noTrip': 'Belum ada perjalanan yang direncanakan', + 'native.widget.inDays': '{n} hari lagi', + 'native.widget.tomorrow': 'Besok', + 'native.widget.nothingPlanned': 'Tidak ada rencana hari ini', + 'native.widget.dayDone': 'Semua selesai hari ini', }; export default native; diff --git a/shared/src/i18n/it/native.ts b/shared/src/i18n/it/native.ts index 7891b8ec8..6e50651b6 100644 --- a/shared/src/i18n/it/native.ts +++ b/shared/src/i18n/it/native.ts @@ -85,6 +85,13 @@ const native: TranslationStrings = { 'Lo chiede all’apertura di TREK e dopo mezzo minuto in background, e nasconde l’app nel selettore delle app.', 'native.share.title': 'Importare in quale viaggio?', 'native.share.noTrips': 'Ancora nessun viaggio. Creane uno, poi condividi di nuovo il documento.', + 'native.widget.dayOf': 'Giorno {n} di {m}', + 'native.widget.today': 'Oggi', + 'native.widget.noTrip': 'Nessun viaggio ancora in programma', + 'native.widget.inDays': 'tra {n} giorni', + 'native.widget.tomorrow': 'Domani', + 'native.widget.nothingPlanned': 'Niente in programma oggi', + 'native.widget.dayDone': 'Tutto fatto per oggi', }; export default native; diff --git a/shared/src/i18n/ja/native.ts b/shared/src/i18n/ja/native.ts index 1c87a190d..aa9ba5d2f 100644 --- a/shared/src/i18n/ja/native.ts +++ b/shared/src/i18n/ja/native.ts @@ -85,6 +85,13 @@ const native: TranslationStrings = { 'TREKを開いたときと、バックグラウンドで30秒経過したあとに確認し、アプリスイッチャーでは内容を隠します。', 'native.share.title': 'どの旅行に取り込みますか?', 'native.share.noTrips': 'まだ旅行がありません。先に作成してから、もう一度ドキュメントを共有してください。', + 'native.widget.dayOf': '{m}日中{n}日目', + 'native.widget.today': '今日', + 'native.widget.noTrip': 'まだ予定している旅行はありません', + 'native.widget.inDays': 'あと{n}日', + 'native.widget.tomorrow': '明日', + 'native.widget.nothingPlanned': '今日の予定はありません', + 'native.widget.dayDone': '今日の予定はすべて完了', }; export default native; diff --git a/shared/src/i18n/ko/native.ts b/shared/src/i18n/ko/native.ts index 522ba27aa..5dc34ca2b 100644 --- a/shared/src/i18n/ko/native.ts +++ b/shared/src/i18n/ko/native.ts @@ -83,6 +83,13 @@ const native: TranslationStrings = { 'TREK을 열 때와 백그라운드에서 30초가 지난 후에 확인하며, 앱 전환기에서는 내용을 숨깁니다.', 'native.share.title': '어느 여행으로 가져올까요?', 'native.share.noTrips': '아직 여행이 없습니다. 먼저 여행을 만든 뒤 문서를 다시 공유하세요.', + 'native.widget.dayOf': '{m}일 중 {n}일째', + 'native.widget.today': '오늘', + 'native.widget.noTrip': '아직 계획된 여행이 없습니다', + 'native.widget.inDays': '{n}일 후', + 'native.widget.tomorrow': '내일', + 'native.widget.nothingPlanned': '오늘은 계획이 없습니다', + 'native.widget.dayDone': '오늘 일정 완료', }; export default native; diff --git a/shared/src/i18n/nl/native.ts b/shared/src/i18n/nl/native.ts index 430a3bbef..0157d5b64 100644 --- a/shared/src/i18n/nl/native.ts +++ b/shared/src/i18n/nl/native.ts @@ -84,6 +84,13 @@ const native: TranslationStrings = { 'Vraagt erom bij het openen van TREK en na een halve minuut op de achtergrond, en verbergt de app in de appkiezer.', 'native.share.title': 'In welke reis importeren?', 'native.share.noTrips': 'Nog geen reis. Maak er eerst een aan en deel het document dan opnieuw.', + 'native.widget.dayOf': 'Dag {n} van {m}', + 'native.widget.today': 'Vandaag', + 'native.widget.noTrip': 'Nog geen reis gepland', + 'native.widget.inDays': 'over {n} dagen', + 'native.widget.tomorrow': 'Morgen', + 'native.widget.nothingPlanned': 'Niets gepland voor vandaag', + 'native.widget.dayDone': 'Alles gedaan voor vandaag', }; export default native; diff --git a/shared/src/i18n/pl/native.ts b/shared/src/i18n/pl/native.ts index 8b17f18f1..febfdb2aa 100644 --- a/shared/src/i18n/pl/native.ts +++ b/shared/src/i18n/pl/native.ts @@ -84,6 +84,13 @@ const native: TranslationStrings = { 'Pyta przy otwieraniu TREK i po pół minuty w tle oraz ukrywa aplikację w przełączniku aplikacji.', 'native.share.title': 'Do której podróży zaimportować?', 'native.share.noTrips': 'Nie ma jeszcze podróży. Najpierw utwórz podróż, a potem udostępnij dokument ponownie.', + 'native.widget.dayOf': 'Dzień {n} z {m}', + 'native.widget.today': 'Dziś', + 'native.widget.noTrip': 'Nie zaplanowano jeszcze żadnej podróży', + 'native.widget.inDays': 'za {n} dni', + 'native.widget.tomorrow': 'Jutro', + 'native.widget.nothingPlanned': 'Na dziś nic nie zaplanowano', + 'native.widget.dayDone': 'Na dziś wszystko zrobione', }; export default native; diff --git a/shared/src/i18n/ru/native.ts b/shared/src/i18n/ru/native.ts index 976e0a0dd..0e9fbf726 100644 --- a/shared/src/i18n/ru/native.ts +++ b/shared/src/i18n/ru/native.ts @@ -85,6 +85,13 @@ const native: TranslationStrings = { 'Запрашивается при открытии TREK и через полминуты в фоне, а в переключателе приложений содержимое скрыто.', 'native.share.title': 'В какую поездку импортировать?', 'native.share.noTrips': 'Поездок пока нет. Сначала создайте поездку, затем снова поделитесь документом.', + 'native.widget.dayOf': 'День {n} из {m}', + 'native.widget.today': 'Сегодня', + 'native.widget.noTrip': 'Поездок пока не запланировано', + 'native.widget.inDays': 'через {n} дн.', + 'native.widget.tomorrow': 'Завтра', + 'native.widget.nothingPlanned': 'На сегодня ничего не запланировано', + 'native.widget.dayDone': 'На сегодня всё', }; export default native; diff --git a/shared/src/i18n/sk/native.ts b/shared/src/i18n/sk/native.ts index a140f0352..cc1e2aa81 100644 --- a/shared/src/i18n/sk/native.ts +++ b/shared/src/i18n/sk/native.ts @@ -84,6 +84,13 @@ const native: TranslationStrings = { 'Opýta sa pri otvorení TREK a po pol minúte na pozadí a skryje aplikáciu v prepínači aplikácií.', 'native.share.title': 'Importovať do ktorej cesty?', 'native.share.noTrips': 'Zatiaľ žiadna cesta. Najprv nejakú vytvorte a potom dokument zdieľajte znova.', + 'native.widget.dayOf': 'Deň {n} z {m}', + 'native.widget.today': 'Dnes', + 'native.widget.noTrip': 'Zatiaľ žiadna naplánovaná cesta', + 'native.widget.inDays': 'o {n} dní', + 'native.widget.tomorrow': 'Zajtra', + 'native.widget.nothingPlanned': 'Na dnes nič naplánované', + 'native.widget.dayDone': 'Na dnes hotovo', }; export default native; diff --git a/shared/src/i18n/sv/native.ts b/shared/src/i18n/sv/native.ts index fe3787c79..ad4b3bfad 100644 --- a/shared/src/i18n/sv/native.ts +++ b/shared/src/i18n/sv/native.ts @@ -85,6 +85,13 @@ const native: TranslationStrings = { 'Frågar när TREK öppnas och efter en halv minut i bakgrunden, och döljer appen i appväxlaren.', 'native.share.title': 'Importera till vilken resa?', 'native.share.noTrips': 'Ingen resa ännu. Skapa en först och dela sedan dokumentet igen.', + 'native.widget.dayOf': 'Dag {n} av {m}', + 'native.widget.today': 'I dag', + 'native.widget.noTrip': 'Ingen resa planerad ännu', + 'native.widget.inDays': 'om {n} dagar', + 'native.widget.tomorrow': 'I morgon', + 'native.widget.nothingPlanned': 'Inget planerat i dag', + 'native.widget.dayDone': 'Allt klart för i dag', }; export default native; diff --git a/shared/src/i18n/th/native.ts b/shared/src/i18n/th/native.ts index 5d11811cb..43969865a 100644 --- a/shared/src/i18n/th/native.ts +++ b/shared/src/i18n/th/native.ts @@ -82,6 +82,13 @@ const native: TranslationStrings = { 'native.lock.settingHint': 'ถามเมื่อเปิด TREK และหลังจากอยู่เบื้องหลังครึ่งนาที และซ่อนแอปในตัวสลับแอป', 'native.share.title': 'นำเข้าไปยังทริปไหน', 'native.share.noTrips': 'ยังไม่มีทริป สร้างทริปก่อนแล้วแชร์เอกสารอีกครั้ง', + 'native.widget.dayOf': 'วันที่ {n} จาก {m}', + 'native.widget.today': 'วันนี้', + 'native.widget.noTrip': 'ยังไม่มีทริปที่วางแผนไว้', + 'native.widget.inDays': 'อีก {n} วัน', + 'native.widget.tomorrow': 'พรุ่งนี้', + 'native.widget.nothingPlanned': 'วันนี้ไม่มีแผน', + 'native.widget.dayDone': 'วันนี้เสร็จหมดแล้ว', }; export default native; diff --git a/shared/src/i18n/tr/native.ts b/shared/src/i18n/tr/native.ts index deebeaf4e..b73212b1d 100644 --- a/shared/src/i18n/tr/native.ts +++ b/shared/src/i18n/tr/native.ts @@ -85,6 +85,13 @@ const native: TranslationStrings = { 'TREK açılırken ve arka planda yarım dakika sonra sorar, uygulamayı uygulama değiştiricide gizler.', 'native.share.title': 'Hangi geziye aktarılsın?', 'native.share.noTrips': 'Henüz gezi yok. Önce bir gezi oluşturun, sonra belgeyi yeniden paylaşın.', + 'native.widget.dayOf': '{m} günün {n}. günü', + 'native.widget.today': 'Bugün', + 'native.widget.noTrip': 'Henüz planlanmış gezi yok', + 'native.widget.inDays': '{n} gün sonra', + 'native.widget.tomorrow': 'Yarın', + 'native.widget.nothingPlanned': 'Bugün için plan yok', + 'native.widget.dayDone': 'Bugünlük her şey tamam', }; export default native; diff --git a/shared/src/i18n/uk/native.ts b/shared/src/i18n/uk/native.ts index d2bb8f289..f9842f27c 100644 --- a/shared/src/i18n/uk/native.ts +++ b/shared/src/i18n/uk/native.ts @@ -84,6 +84,13 @@ const native: TranslationStrings = { 'Запитує під час відкриття TREK і після пів хвилини у фоні, а в перемикачі застосунків вміст приховано.', 'native.share.title': 'До якої подорожі імпортувати?', 'native.share.noTrips': 'Подорожей ще немає. Спершу створіть подорож, а потім знову поділіться документом.', + 'native.widget.dayOf': 'День {n} з {m}', + 'native.widget.today': 'Сьогодні', + 'native.widget.noTrip': 'Подорожей ще не заплановано', + 'native.widget.inDays': 'через {n} дн.', + 'native.widget.tomorrow': 'Завтра', + 'native.widget.nothingPlanned': 'На сьогодні нічого не заплановано', + 'native.widget.dayDone': 'На сьогодні все', }; export default native; diff --git a/shared/src/i18n/vi/native.ts b/shared/src/i18n/vi/native.ts index c8134c429..3d307bcf1 100644 --- a/shared/src/i18n/vi/native.ts +++ b/shared/src/i18n/vi/native.ts @@ -85,6 +85,13 @@ const native: TranslationStrings = { 'Hỏi khi mở TREK và sau nửa phút chạy nền, đồng thời ẩn ứng dụng trong trình chuyển ứng dụng.', 'native.share.title': 'Nhập vào chuyến đi nào?', 'native.share.noTrips': 'Chưa có chuyến đi nào. Hãy tạo một chuyến trước rồi chia sẻ lại tài liệu.', + 'native.widget.dayOf': 'Ngày {n}/{m}', + 'native.widget.today': 'Hôm nay', + 'native.widget.noTrip': 'Chưa có chuyến đi nào được lên kế hoạch', + 'native.widget.inDays': 'còn {n} ngày', + 'native.widget.tomorrow': 'Ngày mai', + 'native.widget.nothingPlanned': 'Hôm nay không có kế hoạch', + 'native.widget.dayDone': 'Hôm nay đã xong', }; export default native; diff --git a/shared/src/i18n/zh-TW/native.ts b/shared/src/i18n/zh-TW/native.ts index e781ff8f3..879e28189 100644 --- a/shared/src/i18n/zh-TW/native.ts +++ b/shared/src/i18n/zh-TW/native.ts @@ -82,6 +82,13 @@ const native: TranslationStrings = { 'native.lock.settingHint': '開啟 TREK 時以及在背景停留半分鐘後會要求驗證,並在 App 切換器中隱藏內容。', 'native.share.title': '要匯入到哪個行程?', 'native.share.noTrips': '還沒有行程。請先建立一個,然後再次分享該文件。', + 'native.widget.dayOf': '第 {n} 天,共 {m} 天', + 'native.widget.today': '今天', + 'native.widget.noTrip': '還沒有計畫中的行程', + 'native.widget.inDays': '{n} 天後', + 'native.widget.tomorrow': '明天', + 'native.widget.nothingPlanned': '今天沒有安排', + 'native.widget.dayDone': '今天的行程已全部完成', }; export default native; diff --git a/shared/src/i18n/zh/native.ts b/shared/src/i18n/zh/native.ts index 3e6a8cc2d..07c2e2ee9 100644 --- a/shared/src/i18n/zh/native.ts +++ b/shared/src/i18n/zh/native.ts @@ -82,6 +82,13 @@ const native: TranslationStrings = { 'native.lock.settingHint': '打开 TREK 时以及在后台停留半分钟后会要求验证,并在应用切换器中隐藏内容。', 'native.share.title': '导入到哪个行程?', 'native.share.noTrips': '还没有行程。请先创建一个,然后再次分享该文档。', + 'native.widget.dayOf': '第 {n} 天,共 {m} 天', + 'native.widget.today': '今天', + 'native.widget.noTrip': '还没有计划中的行程', + 'native.widget.inDays': '{n} 天后', + 'native.widget.tomorrow': '明天', + 'native.widget.nothingPlanned': '今天没有安排', + 'native.widget.dayDone': '今天的行程已全部完成', }; export default native; From 3c4c880c315f6bb159742d7099591bb2486dd1b2 Mon Sep 17 00:00:00 2001 From: Maurice Date: Fri, 6 Nov 2026 14:25:57 +0100 Subject: [PATCH 075/589] feat(native): push notifications on Android through the relay The Android app now subscribes like the iOS one: TrekShell.registerPush asks for the notification permission (Android 13+), creates the device's P-256 Web Push keys and returns the relay endpoint for its FCM token (push.liketrek.com/v1/fcm/). TrekPushService receives the relay's data message, decrypts the record (RFC 8291, TrekWebPush) and shows the notification. A tap opens the linked page, also when it starts the app. The keys are sealed with an AES key kept in the Android Keystore. Firebase is configured from res/values/firebase.xml, so no google-services plugin is needed. The decryption is tested against the RFC 8291 example, and the native workflow now runs the Android unit tests. On the web side push is no longer limited to iOS: it follows the nativePush capability on both platforms. --- .github/workflows/native.yml | 2 +- client/android/app/build.gradle | 3 + .../android/app/src/main/AndroidManifest.xml | 11 ++ .../java/com/liketrek/trek/TrekPushKeys.java | 139 ++++++++++++++++++ .../com/liketrek/trek/TrekPushService.java | 101 +++++++++++++ .../com/liketrek/trek/TrekShellPlugin.java | 93 +++++++++++- .../java/com/liketrek/trek/TrekWebPush.java | 84 +++++++++++ .../src/main/res/drawable/ic_stat_trek.xml | 13 ++ .../app/src/main/res/values/firebase.xml | 13 ++ .../app/src/main/res/values/strings.xml | 3 + .../com/liketrek/trek/TrekWebPushTest.java | 63 ++++++++ client/src/native/push.test.ts | 6 +- client/src/native/push.ts | 11 +- 13 files changed, 531 insertions(+), 11 deletions(-) create mode 100644 client/android/app/src/main/java/com/liketrek/trek/TrekPushKeys.java create mode 100644 client/android/app/src/main/java/com/liketrek/trek/TrekPushService.java create mode 100644 client/android/app/src/main/java/com/liketrek/trek/TrekWebPush.java create mode 100644 client/android/app/src/main/res/drawable/ic_stat_trek.xml create mode 100644 client/android/app/src/main/res/values/firebase.xml create mode 100644 client/android/app/src/test/java/com/liketrek/trek/TrekWebPushTest.java diff --git a/.github/workflows/native.yml b/.github/workflows/native.yml index 8ee1272f2..bb2fe5a13 100644 --- a/.github/workflows/native.yml +++ b/.github/workflows/native.yml @@ -80,7 +80,7 @@ jobs: # unsigned: the upload key only exists in native-release.yml. - name: Assemble debug and release APKs working-directory: client/android - run: ./gradlew assembleDebug assembleRelease lintDebug --no-daemon + run: ./gradlew assembleDebug assembleRelease lintDebug testDebugUnitTest --no-daemon - uses: actions/upload-artifact@v6 with: diff --git a/client/android/app/build.gradle b/client/android/app/build.gradle index d936d41a0..aca4e544e 100644 --- a/client/android/app/build.gradle +++ b/client/android/app/build.gradle @@ -57,6 +57,9 @@ dependencies { implementation "androidx.core:core-splashscreen:$coreSplashScreenVersion" implementation "androidx.browser:browser:$androidxBrowserVersion" implementation "androidx.biometric:biometric:1.1.0" + // Push through liketrek's relay. No google-services plugin: Firebase reads + // its project from res/values/firebase.xml, the strings the plugin would generate. + implementation "com.google.firebase:firebase-messaging:24.1.2" implementation project(':capacitor-android') testImplementation "junit:junit:$junitVersion" androidTestImplementation "androidx.test.ext:junit:$androidxJunitVersion" diff --git a/client/android/app/src/main/AndroidManifest.xml b/client/android/app/src/main/AndroidManifest.xml index e395c86a0..56b0297cd 100644 --- a/client/android/app/src/main/AndroidManifest.xml +++ b/client/android/app/src/main/AndroidManifest.xml @@ -60,6 +60,15 @@ + + + + + + + + + diff --git a/client/android/app/src/main/java/com/liketrek/trek/TrekPushKeys.java b/client/android/app/src/main/java/com/liketrek/trek/TrekPushKeys.java new file mode 100644 index 000000000..6882da9ec --- /dev/null +++ b/client/android/app/src/main/java/com/liketrek/trek/TrekPushKeys.java @@ -0,0 +1,139 @@ +package com.liketrek.trek; + +import android.content.Context; +import android.content.SharedPreferences; +import android.security.keystore.KeyGenParameterSpec; +import android.security.keystore.KeyProperties; +import android.util.Base64; +import java.math.BigInteger; +import java.security.KeyFactory; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.KeyStore; +import java.security.interfaces.ECPrivateKey; +import java.security.interfaces.ECPublicKey; +import java.security.spec.ECGenParameterSpec; +import java.security.spec.PKCS8EncodedKeySpec; +import java.security.SecureRandom; +import javax.crypto.Cipher; +import javax.crypto.KeyGenerator; +import javax.crypto.SecretKey; +import javax.crypto.spec.GCMParameterSpec; + +/** + * The device's Web Push key pair (P-256) and auth secret (RFC 8291). The server + * encrypts every notification for these, and TrekPushService decrypts with + * them. They are kept in the app's preferences, sealed with an AES key that + * never leaves the Android Keystore, so a copy of the preferences alone opens + * nothing. + */ +final class TrekPushKeys { + + private static final String PREFS = "trek_push"; + private static final String WRAP_ALIAS = "trek_push_wrap"; + private static final String PRIVATE = "private"; + private static final String PUBLIC = "public"; + private static final String AUTH = "auth"; + + final ECPrivateKey privateKey; + /** Uncompressed point, 65 bytes, as the server reads p256dh. */ + final byte[] publicKey; + final byte[] auth; + + TrekPushKeys(ECPrivateKey privateKey, byte[] publicKey, byte[] auth) { + this.privateKey = privateKey; + this.publicKey = publicKey; + this.auth = auth; + } + + /** The stored keys, or null when the app never subscribed. */ + static synchronized TrekPushKeys load(Context context) throws Exception { + SharedPreferences prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE); + String sealedPrivate = prefs.getString(PRIVATE, null); + String publicKey = prefs.getString(PUBLIC, null); + String sealedAuth = prefs.getString(AUTH, null); + if (sealedPrivate == null || publicKey == null || sealedAuth == null) return null; + byte[] pkcs8 = unseal(sealedPrivate); + ECPrivateKey key = (ECPrivateKey) KeyFactory.getInstance("EC").generatePrivate(new PKCS8EncodedKeySpec(pkcs8)); + return new TrekPushKeys(key, Base64.decode(publicKey, Base64.NO_WRAP), unseal(sealedAuth)); + } + + static synchronized TrekPushKeys loadOrCreate(Context context) throws Exception { + TrekPushKeys existing; + try { + existing = load(context); + } catch (Exception unreadable) { + // The Keystore key is gone (backup restored to another device, data + // cleared): start over, the next subscription carries the new keys. + existing = null; + } + if (existing != null) return existing; + + KeyPairGenerator generator = KeyPairGenerator.getInstance("EC"); + generator.initialize(new ECGenParameterSpec("secp256r1")); + KeyPair pair = generator.generateKeyPair(); + byte[] publicKey = uncompressed((ECPublicKey) pair.getPublic()); + byte[] auth = new byte[16]; + new SecureRandom().nextBytes(auth); + context.getSharedPreferences(PREFS, Context.MODE_PRIVATE) + .edit() + .putString(PRIVATE, seal(pair.getPrivate().getEncoded())) + .putString(PUBLIC, Base64.encodeToString(publicKey, Base64.NO_WRAP)) + .putString(AUTH, seal(auth)) + .apply(); + return new TrekPushKeys((ECPrivateKey) pair.getPrivate(), publicKey, auth); + } + + static String base64url(byte[] data) { + return Base64.encodeToString(data, Base64.URL_SAFE | Base64.NO_WRAP | Base64.NO_PADDING); + } + + static byte[] uncompressed(ECPublicKey key) { + byte[] out = new byte[65]; + out[0] = 0x04; + copyFixed(key.getW().getAffineX(), out, 1); + copyFixed(key.getW().getAffineY(), out, 33); + return out; + } + + /** A coordinate as exactly 32 bytes: BigInteger adds a sign byte or drops leading zeros. */ + private static void copyFixed(BigInteger value, byte[] out, int offset) { + byte[] raw = value.toByteArray(); + int start = Math.max(0, raw.length - 32); + int length = raw.length - start; + System.arraycopy(raw, start, out, offset + 32 - length, length); + } + + private static SecretKey wrapKey() throws Exception { + KeyStore store = KeyStore.getInstance("AndroidKeyStore"); + store.load(null); + if (store.containsAlias(WRAP_ALIAS)) return ((KeyStore.SecretKeyEntry) store.getEntry(WRAP_ALIAS, null)).getSecretKey(); + KeyGenerator generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore"); + generator.init( + new KeyGenParameterSpec.Builder(WRAP_ALIAS, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT) + .setBlockModes(KeyProperties.BLOCK_MODE_GCM) + .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE) + .setKeySize(256) + .build() + ); + return generator.generateKey(); + } + + private static String seal(byte[] plain) throws Exception { + Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); + cipher.init(Cipher.ENCRYPT_MODE, wrapKey()); + byte[] iv = cipher.getIV(); + byte[] sealed = cipher.doFinal(plain); + byte[] out = new byte[iv.length + sealed.length]; + System.arraycopy(iv, 0, out, 0, iv.length); + System.arraycopy(sealed, 0, out, iv.length, sealed.length); + return Base64.encodeToString(out, Base64.NO_WRAP); + } + + private static byte[] unseal(String value) throws Exception { + byte[] in = Base64.decode(value, Base64.NO_WRAP); + Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); + cipher.init(Cipher.DECRYPT_MODE, wrapKey(), new GCMParameterSpec(128, in, 0, 12)); + return cipher.doFinal(in, 12, in.length - 12); + } +} diff --git a/client/android/app/src/main/java/com/liketrek/trek/TrekPushService.java b/client/android/app/src/main/java/com/liketrek/trek/TrekPushService.java new file mode 100644 index 000000000..8724aa750 --- /dev/null +++ b/client/android/app/src/main/java/com/liketrek/trek/TrekPushService.java @@ -0,0 +1,101 @@ +package com.liketrek.trek; + +import android.Manifest; +import android.app.NotificationChannel; +import android.app.NotificationManager; +import android.app.PendingIntent; +import android.content.Context; +import android.content.Intent; +import android.content.pm.PackageManager; +import android.os.Build; +import android.util.Base64; +import androidx.annotation.NonNull; +import androidx.core.app.NotificationCompat; +import androidx.core.app.NotificationManagerCompat; +import androidx.core.content.ContextCompat; +import com.google.firebase.messaging.FirebaseMessagingService; +import com.google.firebase.messaging.RemoteMessage; +import java.nio.charset.StandardCharsets; +import org.json.JSONObject; + +/** + * Receives the relay's data messages ({enc}: the server's encrypted Web Push + * record), decrypts them with the device's keys and shows the notification. + * Without the keys, or when the record does not open, it shows the same + * neutral text the iOS extension falls back to, never the ciphertext. + */ +public class TrekPushService extends FirebaseMessagingService { + + static final String CHANNEL = "trek"; + static final String EXTRA_URL = "trek.pushUrl"; + + @Override + public void onMessageReceived(@NonNull RemoteMessage message) { + String enc = message.getData().get("enc"); + if (enc == null) return; + String title = getString(R.string.push_fallback_title); + String body = getString(R.string.push_fallback_body); + String url = null; + String tag = null; + try { + TrekPushKeys keys = TrekPushKeys.load(this); + if (keys != null) { + byte[] plain = TrekWebPush.decrypt(Base64.decode(enc, Base64.DEFAULT), keys); + JSONObject payload = new JSONObject(new String(plain, StandardCharsets.UTF_8)); + if (!payload.optString("title").isEmpty()) title = payload.optString("title"); + body = payload.optString("body", body); + url = payload.optString("url", null); + tag = payload.optString("tag", null); + } + } catch (Exception unreadable) { + // Shown with the neutral text: the tap still opens the app. + } + show(this, title, body, url, tag); + } + + /** A new token means a new endpoint; the UI re-registers on its next start (resyncPushSubscription). */ + @Override + public void onNewToken(@NonNull String token) {} + + static void ensureChannel(Context context) { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return; + NotificationManager manager = context.getSystemService(NotificationManager.class); + if (manager == null || manager.getNotificationChannel(CHANNEL) != null) return; + NotificationChannel channel = new NotificationChannel( + CHANNEL, + context.getString(R.string.push_channel_name), + NotificationManager.IMPORTANCE_DEFAULT + ); + manager.createNotificationChannel(channel); + } + + private static void show(Context context, String title, String body, String url, String tag) { + ensureChannel(context); + Intent open = new Intent(context, MainActivity.class) + .setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP); + if (url != null) open.putExtra(EXTRA_URL, url); + int id = tag != null ? tag.hashCode() : (int) (System.currentTimeMillis() & 0x7fffffff); + PendingIntent tap = PendingIntent.getActivity( + context, + id, + open, + PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE + ); + NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL) + .setSmallIcon(R.drawable.ic_stat_trek) + .setContentTitle(title) + .setContentText(body) + .setStyle(new NotificationCompat.BigTextStyle().bigText(body)) + .setAutoCancel(true) + .setContentIntent(tap); + if (Build.VERSION.SDK_INT >= 33 + && ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) { + return; + } + try { + NotificationManagerCompat.from(context).notify(tag, id, builder.build()); + } catch (SecurityException notAllowed) { + // Notifications switched off for the app since it subscribed. + } + } +} diff --git a/client/android/app/src/main/java/com/liketrek/trek/TrekShellPlugin.java b/client/android/app/src/main/java/com/liketrek/trek/TrekShellPlugin.java index c365cecdf..8c3ff7840 100644 --- a/client/android/app/src/main/java/com/liketrek/trek/TrekShellPlugin.java +++ b/client/android/app/src/main/java/com/liketrek/trek/TrekShellPlugin.java @@ -1,19 +1,29 @@ package com.liketrek.trek; +import android.Manifest; import android.content.Intent; import android.net.Uri; +import android.os.Build; import android.os.Handler; import android.os.Looper; import androidx.browser.customtabs.CustomTabsIntent; +import androidx.core.app.NotificationManagerCompat; import com.getcapacitor.JSObject; +import com.getcapacitor.PermissionState; import com.getcapacitor.Plugin; import com.getcapacitor.PluginCall; import com.getcapacitor.PluginMethod; import com.getcapacitor.annotation.CapacitorPlugin; +import com.getcapacitor.annotation.Permission; +import com.getcapacitor.annotation.PermissionCallback; +import com.google.firebase.messaging.FirebaseMessaging; import org.json.JSONObject; /** The native half of client/src/native/trekShell.ts. */ -@CapacitorPlugin(name = "TrekShell") +@CapacitorPlugin( + name = "TrekShell", + permissions = { @Permission(strings = { Manifest.permission.POST_NOTIFICATIONS }, alias = "notifications") } +) public class TrekShellPlugin extends Plugin { /** How long to wait after returning from the browser for the redirect to land. */ @@ -31,7 +41,13 @@ public class TrekShellPlugin extends Plugin { */ static final int SHELL_API = 2; /** The native features by name, so the UI can turn each on by itself. */ - static final String[] FEATURES = { "capabilities", "biometricLock", "sharedFiles" }; + static final String[] FEATURES = { "capabilities", "biometricLock", "sharedFiles", "nativePush" }; + + /** liketrek's push relay: the endpoint for this device's FCM token (trek-hosted push-relay.ts). */ + static final String PUSH_RELAY = "https://push.liketrek.com/v1/fcm/"; + + /** The notification the app was started from, until the UI asks for it. */ + private String openedPushUrl; @PluginMethod public void getCapabilities(PluginCall call) { @@ -60,6 +76,71 @@ public class TrekShellPlugin extends Plugin { @Override public void load() { TrekSharedFiles.setListener(file -> notifyListeners("sharedFile", file)); + if (getActivity() != null && getActivity().getIntent() != null) { + openedPushUrl = getActivity().getIntent().getStringExtra(TrekPushService.EXTRA_URL); + getActivity().getIntent().removeExtra(TrekPushService.EXTRA_URL); + } + } + + // ---- Push ---- + + /** + * Permission, the FCM token and the device keys, as the Web Push subscription + * the server stores (native/push.ts). Rejects with DENIED when the user + * refuses notifications, as on iOS. + */ + @PluginMethod + public void registerPush(PluginCall call) { + if (Build.VERSION.SDK_INT >= 33 && getPermissionState("notifications") != PermissionState.GRANTED) { + requestPermissionForAlias("notifications", call, "pushPermissionAnswered"); + return; + } + subscribePush(call); + } + + @PermissionCallback + private void pushPermissionAnswered(PluginCall call) { + if (getPermissionState("notifications") != PermissionState.GRANTED) { + call.reject("Notifications are not allowed", "DENIED"); + return; + } + subscribePush(call); + } + + private void subscribePush(PluginCall call) { + if (!NotificationManagerCompat.from(getContext()).areNotificationsEnabled()) { + call.reject("Notifications are not allowed", "DENIED"); + return; + } + TrekPushService.ensureChannel(getContext()); + final TrekPushKeys keys; + try { + keys = TrekPushKeys.loadOrCreate(getContext()); + } catch (Exception e) { + call.reject("Could not create the push keys", e); + return; + } + FirebaseMessaging.getInstance().getToken().addOnCompleteListener(task -> { + if (!task.isSuccessful() || task.getResult() == null) { + call.reject("Could not get a push token", task.getException()); + return; + } + JSObject subscription = new JSObject(); + subscription.put("endpoint", PUSH_RELAY + task.getResult()); + JSObject keyObject = new JSObject(); + keyObject.put("p256dh", TrekPushKeys.base64url(keys.publicKey)); + keyObject.put("auth", TrekPushKeys.base64url(keys.auth)); + subscription.put("keys", keyObject); + call.resolve(subscription); + }); + } + + @PluginMethod + public void takeOpenedPush(PluginCall call) { + JSObject result = new JSObject(); + result.put("url", openedPushUrl == null ? JSONObject.NULL : openedPushUrl); + openedPushUrl = null; + call.resolve(result); } /** The document shared to TREK before the UI was there to hear of it. */ @@ -200,6 +281,14 @@ public class TrekShellPlugin extends Plugin { @Override protected void handleOnNewIntent(Intent intent) { super.handleOnNewIntent(intent); + String pushUrl = intent.getStringExtra(TrekPushService.EXTRA_URL); + if (pushUrl != null) { + intent.removeExtra(TrekPushService.EXTRA_URL); + JSObject opened = new JSObject(); + opened.put("url", pushUrl); + notifyListeners("pushOpened", opened); + return; + } Uri data = intent.getData(); PluginCall call = pendingAuthCall(); if (call == null || data == null || !authScheme.equals(data.getScheme())) return; diff --git a/client/android/app/src/main/java/com/liketrek/trek/TrekWebPush.java b/client/android/app/src/main/java/com/liketrek/trek/TrekWebPush.java new file mode 100644 index 000000000..759231eaa --- /dev/null +++ b/client/android/app/src/main/java/com/liketrek/trek/TrekWebPush.java @@ -0,0 +1,84 @@ +package com.liketrek.trek; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.KeyFactory; +import java.security.interfaces.ECPrivateKey; +import java.security.interfaces.ECPublicKey; +import java.security.spec.ECPoint; +import java.security.spec.ECPublicKeySpec; +import java.util.Arrays; +import javax.crypto.Cipher; +import javax.crypto.KeyAgreement; +import javax.crypto.Mac; +import javax.crypto.spec.GCMParameterSpec; +import javax.crypto.spec.SecretKeySpec; + +/** + * Decrypts a Web Push record (RFC 8291, aes128gcm content coding of RFC 8188): + * the same thing a browser does, and the counterpart of the iOS notification + * extension's WebPushRecord. One record, as TREK's server always sends. + */ +final class TrekWebPush { + + private TrekWebPush() {} + + static byte[] decrypt(byte[] record, TrekPushKeys keys) throws Exception { + if (record.length < 21) throw new IllegalArgumentException("record too short"); + byte[] salt = Arrays.copyOfRange(record, 0, 16); + int idLength = record[20] & 0xff; + if (idLength != 65 || record.length < 21 + idLength + 17) throw new IllegalArgumentException("unexpected header"); + byte[] senderKey = Arrays.copyOfRange(record, 21, 21 + idLength); + byte[] ciphertext = Arrays.copyOfRange(record, 21 + idLength, record.length); + + KeyAgreement agreement = KeyAgreement.getInstance("ECDH"); + agreement.init(keys.privateKey); + agreement.doPhase(publicKeyFrom(senderKey, keys.privateKey), true); + byte[] shared = agreement.generateSecret(); + + byte[] keyInfo = concat("WebPush: info\0".getBytes(StandardCharsets.US_ASCII), keys.publicKey, senderKey); + byte[] ikm = hkdf(keys.auth, shared, keyInfo, 32); + byte[] cek = hkdf(salt, ikm, "Content-Encoding: aes128gcm\0".getBytes(StandardCharsets.US_ASCII), 16); + byte[] nonce = hkdf(salt, ikm, "Content-Encoding: nonce\0".getBytes(StandardCharsets.US_ASCII), 12); + + Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); + cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(cek, "AES"), new GCMParameterSpec(128, nonce)); + byte[] padded = cipher.doFinal(ciphertext); + + // Padding: the content, one delimiter (2 for the last record), then zeros. + int end = padded.length - 1; + while (end >= 0 && padded[end] == 0) end--; + if (end < 0 || padded[end] != 2) throw new IllegalArgumentException("bad padding"); + return Arrays.copyOf(padded, end); + } + + private static ECPublicKey publicKeyFrom(byte[] point, ECPrivateKey onCurve) throws Exception { + if (point[0] != 0x04) throw new IllegalArgumentException("compressed key"); + BigInteger x = new BigInteger(1, Arrays.copyOfRange(point, 1, 33)); + BigInteger y = new BigInteger(1, Arrays.copyOfRange(point, 33, 65)); + return (ECPublicKey) KeyFactory.getInstance("EC").generatePublic(new ECPublicKeySpec(new ECPoint(x, y), onCurve.getParams())); + } + + /** HKDF-SHA256 (RFC 5869) for outputs of at most one block. */ + private static byte[] hkdf(byte[] salt, byte[] ikm, byte[] info, int length) throws Exception { + Mac mac = Mac.getInstance("HmacSHA256"); + mac.init(new SecretKeySpec(salt, "HmacSHA256")); + byte[] prk = mac.doFinal(ikm); + mac.init(new SecretKeySpec(prk, "HmacSHA256")); + mac.update(info); + mac.update((byte) 1); + return Arrays.copyOf(mac.doFinal(), length); + } + + private static byte[] concat(byte[]... parts) { + int length = 0; + for (byte[] part : parts) length += part.length; + byte[] out = new byte[length]; + int offset = 0; + for (byte[] part : parts) { + System.arraycopy(part, 0, out, offset, part.length); + offset += part.length; + } + return out; + } +} diff --git a/client/android/app/src/main/res/drawable/ic_stat_trek.xml b/client/android/app/src/main/res/drawable/ic_stat_trek.xml new file mode 100644 index 000000000..3f7b9155f --- /dev/null +++ b/client/android/app/src/main/res/drawable/ic_stat_trek.xml @@ -0,0 +1,13 @@ + + + + + diff --git a/client/android/app/src/main/res/values/firebase.xml b/client/android/app/src/main/res/values/firebase.xml new file mode 100644 index 000000000..9615c5484 --- /dev/null +++ b/client/android/app/src/main/res/values/firebase.xml @@ -0,0 +1,13 @@ + + + + 1:1074454522965:android:3ff2fe270a27a73051b8dc + 1074454522965 + AIzaSyB2VYXmZ90BZuksHhHR_n2W8naNE_vJAJA + AIzaSyB2VYXmZ90BZuksHhHR_n2W8naNE_vJAJA + trek-9392e + trek-9392e.firebasestorage.app + diff --git a/client/android/app/src/main/res/values/strings.xml b/client/android/app/src/main/res/values/strings.xml index 768fe05ff..e66821104 100644 --- a/client/android/app/src/main/res/values/strings.xml +++ b/client/android/app/src/main/res/values/strings.xml @@ -4,4 +4,7 @@ TREK com.liketrek.trek com.liketrek.trek + Notifications + TREK + New notification diff --git a/client/android/app/src/test/java/com/liketrek/trek/TrekWebPushTest.java b/client/android/app/src/test/java/com/liketrek/trek/TrekWebPushTest.java new file mode 100644 index 000000000..de31a29e1 --- /dev/null +++ b/client/android/app/src/test/java/com/liketrek/trek/TrekWebPushTest.java @@ -0,0 +1,63 @@ +package com.liketrek.trek; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.KeyFactory; +import java.security.KeyPairGenerator; +import java.security.interfaces.ECPrivateKey; +import java.security.interfaces.ECPublicKey; +import java.security.spec.ECGenParameterSpec; +import java.security.spec.ECPrivateKeySpec; +import java.util.Base64; +import org.junit.Test; + +/** The decryption against the worked example in RFC 8291, section 5. */ +public class TrekWebPushTest { + + private static byte[] b64(String value) { + return Base64.getUrlDecoder().decode(value); + } + + private static TrekPushKeys rfcKeys() throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("EC"); + generator.initialize(new ECGenParameterSpec("secp256r1")); + ECPublicKey anyKey = (ECPublicKey) generator.generateKeyPair().getPublic(); + BigInteger d = new BigInteger(1, b64("q1dXpw3UpT5VOmu_cf_v6ih07Aems3njxI-JWgLcM94")); + ECPrivateKey privateKey = (ECPrivateKey) KeyFactory.getInstance("EC").generatePrivate(new ECPrivateKeySpec(d, anyKey.getParams())); + return new TrekPushKeys( + privateKey, + b64("BCVxsr7N_eNgVRqvHtD0zTZsEc6-VV-JvLexhqUzORcxaOzi6-AYWXvTBHm4bjyPjs7Vd8pZGH6SRpkNtoIAiw4"), + b64("BTBZMqHH6r4Tts7J_aSIgg") + ); + } + + private static final String RECORD = + "DGv6ra1nlYgDCS1FRnbzlwAAEABBBP4z9KsN6nGRTbVYI_c7VJSPQTBtkgcy27mlmlMoZIIgDll6e3vCYLocInmYWAmS6TlzAC8wEqKK6PBru3jl7A_yl95bQpu6cVPTpK4Mqgkf1CXztLVBSt2Ks3oZwbuwXPXLWyouBWLVWGNWQexSgSxsj_Qulcy4a-fN"; + + @Test + public void decryptsTheRfcExample() throws Exception { + byte[] plain = TrekWebPush.decrypt(b64(RECORD), rfcKeys()); + assertEquals("When I grow up, I want to be a watermelon", new String(plain, StandardCharsets.UTF_8)); + } + + @Test + public void refusesATamperedRecord() throws Exception { + byte[] record = b64(RECORD); + record[record.length - 1] ^= 1; + assertThrows(Exception.class, () -> TrekWebPush.decrypt(record, rfcKeys())); + } + + @Test + public void writesThePublicKeyAsAFixedLengthPoint() throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("EC"); + generator.initialize(new ECGenParameterSpec("secp256r1")); + for (int i = 0; i < 20; i++) { + byte[] point = TrekPushKeys.uncompressed((ECPublicKey) generator.generateKeyPair().getPublic()); + assertEquals(65, point.length); + assertEquals(4, point[0]); + } + } +} diff --git a/client/src/native/push.test.ts b/client/src/native/push.test.ts index ff903e8a0..4c2add3e0 100644 --- a/client/src/native/push.test.ts +++ b/client/src/native/push.test.ts @@ -1,6 +1,6 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; import { hasNativeFeature } from './capabilities'; -import { isNativeIos } from './platform'; +import { isNativeApp } from './platform'; import { NativePushDenied, forgetNativePush, @@ -12,7 +12,7 @@ import { } from './push'; import { TrekShell } from './trekShell'; -vi.mock('./platform', () => ({ isNativeIos: vi.fn() })); +vi.mock('./platform', () => ({ isNativeApp: vi.fn() })); vi.mock('./capabilities', () => ({ hasNativeFeature: vi.fn() })); vi.mock('./trekShell', () => ({ TrekShell: { @@ -29,7 +29,7 @@ const SUB = { beforeEach(() => { window.localStorage.clear(); - vi.mocked(isNativeIos).mockReturnValue(true); + vi.mocked(isNativeApp).mockReturnValue(true); vi.mocked(hasNativeFeature).mockReturnValue(true); vi.mocked(TrekShell.registerPush).mockReset().mockResolvedValue(SUB); vi.mocked(TrekShell.takeOpenedPush).mockReset().mockResolvedValue({ url: null }); diff --git a/client/src/native/push.ts b/client/src/native/push.ts index 628d125df..056b0183b 100644 --- a/client/src/native/push.ts +++ b/client/src/native/push.ts @@ -1,15 +1,16 @@ import type { PushSubscriptionInput } from '@trek/shared'; import { hasNativeFeature } from './capabilities'; -import { isNativeIos } from './platform'; +import { isNativeApp } from './platform'; import { reportNativeFailure } from './reportFailure'; import { TrekShell } from './trekShell'; /** * Push inside the app: the same Web Push subscription a browser makes, only * the app makes it (TrekShell.registerPush). Its endpoint is liketrek's relay - * for this device's APNs token and its keys live on the device, so the server - * encrypts exactly as for a browser and the relay hands on ciphertext that the - * app's notification extension decrypts. push/webPush.ts takes this path + * for this device's APNs or FCM token and its keys live on the device, so the + * server encrypts exactly as for a browser and the relay hands on ciphertext + * that the app decrypts (iOS: the notification extension, Android: + * TrekPushService). push/webPush.ts takes this path * wherever the binary reports the nativePush feature; the settings card, the * test push and the logout teardown stay what they are. * @@ -19,7 +20,7 @@ import { TrekShell } from './trekShell'; const KEY = 'trek.nativePushEndpoint'; export function nativePushActive(): boolean { - return isNativeIos() && hasNativeFeature('nativePush'); + return isNativeApp() && hasNativeFeature('nativePush'); } export function nativePushEndpoint(): string | null { From 6835fd7bf303394fff90af49f33d592c2da8a3d6 Mon Sep 17 00:00:00 2001 From: Maurice Date: Fri, 6 Nov 2026 14:49:26 +0100 Subject: [PATCH 076/589] feat(mobile): page transitions, pull-to-refresh, share sheet and haptics Page transitions: on the phone, pages move like a native navigation stack, built on the View Transitions API (mobile/routeTransition.ts). A page opened from another slides in from the trailing edge, back slides it away, and switching between the dock's sections cross-fades while the dock stands still. Lazy routes do not flash their skeleton: the swap waits, behind the frozen snapshot, until the new page rendered. The edge-swipe back gesture already moves the page and skips the transition. RTL mirrors the motion, reduced motion and desktop get none. Pull-to-refresh on the mobile dashboard: the page follows the finger with resistance, ticks once past the threshold and re-reads trips and notifications quietly, without a loading state. Share: trip share and invite links and the journey link get a share button next to copy, opening the system share sheet (Capacitor Share in the apps, Web Share in browsers that have it). Haptics: a selection click for switches and segmented controls, a tick when a sheet is flung closed, and a firmer bump for the chat's long press. Theme lint: this branch's new screens use the type and z-index tokens, the Vacay company tint is a token, and the baseline is lowered to the new counts. --- client/scripts/theme-baseline.json | 10 +- client/src/App.tsx | 8 +- client/src/components/Layout/AppLockGate.tsx | 2 +- .../components/Layout/NativeImportSheet.tsx | 16 ++- .../components/Layout/NativeUpdateNotice.tsx | 2 +- .../src/components/Settings/ToggleSwitch.tsx | 3 +- client/src/mobile/components/MBottomNav.tsx | 2 +- client/src/mobile/components/MEdgeBack.tsx | 2 + .../src/mobile/components/MPullIndicator.tsx | 29 +++++ .../src/mobile/components/MRouteFallback.tsx | 2 +- client/src/mobile/components/MSegmented.tsx | 6 +- client/src/mobile/components/MSheet.tsx | 2 + client/src/mobile/components/MToggle.tsx | 6 +- client/src/mobile/mobile.css | 66 ++++++++++ client/src/mobile/routeTransition.test.tsx | 70 ++++++++++ client/src/mobile/routeTransition.ts | 93 +++++++++++++ .../mobile/screens/dashboard/MDashboard.tsx | 13 +- .../screens/journey/MJourneySettingsSheet.tsx | 13 +- .../screens/trip/plan/MRouteAppsSheet.tsx | 6 +- .../trip/sheets/MTripSettingsSheet.tsx | 12 ++ .../mobile/screens/trip/tabs/MCollabChat.tsx | 2 + client/src/mobile/screens/vacay/MVacay.tsx | 20 +-- client/src/mobile/usePullToRefresh.test.tsx | 83 ++++++++++++ client/src/mobile/usePullToRefresh.ts | 123 ++++++++++++++++++ client/src/native/haptics.test.ts | 21 ++- client/src/native/haptics.ts | 18 +++ client/src/native/shareLink.test.ts | 40 ++++++ client/src/native/shareLink.ts | 33 +++++ client/src/pages/dashboard/useDashboard.ts | 7 +- shared/src/i18n/ar/common.ts | 1 + shared/src/i18n/az/common.ts | 1 + shared/src/i18n/br/common.ts | 1 + shared/src/i18n/ca/common.ts | 1 + shared/src/i18n/cs/common.ts | 1 + shared/src/i18n/de/common.ts | 3 +- shared/src/i18n/en/common.ts | 1 + shared/src/i18n/es/common.ts | 1 + shared/src/i18n/et/common.ts | 1 + shared/src/i18n/fr/common.ts | 1 + shared/src/i18n/gr/common.ts | 1 + shared/src/i18n/he/common.ts | 1 + shared/src/i18n/hu/common.ts | 1 + shared/src/i18n/id/common.ts | 1 + shared/src/i18n/it/common.ts | 1 + shared/src/i18n/ja/common.ts | 1 + shared/src/i18n/ko/common.ts | 1 + shared/src/i18n/nl/common.ts | 3 +- shared/src/i18n/pl/common.ts | 1 + shared/src/i18n/ru/common.ts | 1 + shared/src/i18n/sk/common.ts | 1 + shared/src/i18n/sv/common.ts | 1 + shared/src/i18n/th/common.ts | 1 + shared/src/i18n/tr/common.ts | 1 + shared/src/i18n/uk/common.ts | 1 + shared/src/i18n/vi/common.ts | 1 + shared/src/i18n/zh-TW/common.ts | 1 + shared/src/i18n/zh/common.ts | 1 + 57 files changed, 699 insertions(+), 43 deletions(-) create mode 100644 client/src/mobile/components/MPullIndicator.tsx create mode 100644 client/src/mobile/routeTransition.test.tsx create mode 100644 client/src/mobile/routeTransition.ts create mode 100644 client/src/mobile/usePullToRefresh.test.tsx create mode 100644 client/src/mobile/usePullToRefresh.ts create mode 100644 client/src/native/shareLink.test.ts create mode 100644 client/src/native/shareLink.ts diff --git a/client/scripts/theme-baseline.json b/client/scripts/theme-baseline.json index e9a007d72..198f830c4 100644 --- a/client/scripts/theme-baseline.json +++ b/client/scripts/theme-baseline.json @@ -125,7 +125,6 @@ "components/shared/CustomSelect.tsx": 1, "components/shared/CustomTimePicker.tsx": 1, "components/shared/EmptyState.tsx": 1, - "components/shared/ErrorBoundary.tsx": 2, "components/shared/Modal.tsx": 3, "components/shared/NavigationMenu.tsx": 1, "components/shared/NoteColorPicker.tsx": 2, @@ -166,7 +165,7 @@ "mobile/screens/admin/MAdminUi.tsx": 10, "mobile/screens/admin/MAdminUsersSection.tsx": 14, "mobile/screens/admin/MApiProviderBlocks.tsx": 10, - "mobile/screens/atlas/MAtlas.tsx": 7, + "mobile/screens/atlas/MAtlas.tsx": 5, "mobile/screens/atlas/MAtlasBucketSheet.tsx": 16, "mobile/screens/atlas/MAtlasCountryPopup.tsx": 11, "mobile/screens/atlas/MAtlasSearch.tsx": 5, @@ -219,11 +218,10 @@ "mobile/screens/trip/places/MPlacesBrowser.tsx": 10, "mobile/screens/trip/places/MPlacesBulkCategorySheet.tsx": 4, "mobile/screens/trip/places/MPlacesFilterControls.tsx": 1, - "mobile/screens/trip/places/MPlacesFilterSheet.tsx": 3, "mobile/screens/trip/places/MPlacesSaveToCollectionSheet.tsx": 7, "mobile/screens/trip/places/MPlacesToursModeSwitch.tsx": 1, - "mobile/screens/trip/plan/MPlanTimeline.tsx": 14, - "mobile/screens/trip/plan/MPlanTimelineRows.tsx": 26, + "mobile/screens/trip/plan/MPlanTimeline.tsx": 12, + "mobile/screens/trip/plan/MPlanTimelineRows.tsx": 24, "mobile/screens/trip/roadtrip/MRoadtripRows.tsx": 31, "mobile/screens/trip/roadtrip/MRoadtripTab.tsx": 16, "mobile/screens/trip/roadtrip/MRtAlternativesBar.tsx": 8, @@ -281,7 +279,7 @@ "mobile/screens/trip/tabs/MTransportsTab.tsx": 2, "mobile/screens/trip/tabs/filesModel.ts": 5, "mobile/screens/trip/tabs/tabChrome.tsx": 12, - "mobile/screens/vacay/MVacay.tsx": 23, + "mobile/screens/vacay/MVacay.tsx": 17, "mobile/screens/vacay/MVacayInviteSheet.tsx": 9, "mobile/screens/vacay/MVacayMonth.tsx": 3, "mobile/screens/vacay/MVacaySettingsSheet.tsx": 35, diff --git a/client/src/App.tsx b/client/src/App.tsx index bcf5cad6a..316dd808f 100644 --- a/client/src/App.tsx +++ b/client/src/App.tsx @@ -1,5 +1,5 @@ import React, { useEffect, useState, useRef, ReactNode, Suspense } from 'react' -import { Routes, Route, Navigate, useLocation } from 'react-router' +import { Routes, Route, Navigate, useLocation, useNavigationType } from 'react-router' import { useAuthStore } from './store/authStore' import { useSettingsStore } from './store/settingsStore' import { applyAppearance } from './theme/applyAppearance' @@ -21,6 +21,7 @@ import { lazyWithRetry } from './utils/lazyWithRetry' import { reconcileAppVersion } from './utils/versionHandover' import { useServerVersionStore } from './store/serverVersionStore' import { useIsPhone } from './mobile/useIsPhone' +import { useRouteTransition } from './mobile/routeTransition' import { TranslationProvider, useTranslation } from './i18n' import { authApi, isAuthPublicPath } from './api/client' import { tripRepo } from './repo/tripRepo' @@ -411,6 +412,9 @@ export default function App() { }, [settings.dark_mode, settings.appearance, isSharedPage]) const isPhone = useIsPhone() + // On the phone, pages slide like a native navigation stack (mobile/routeTransition.ts). + const navigationType = useNavigationType() + const routedLocation = useRouteTransition(location, navigationType, isPhone) const keepingTour = useSaveToCollectionStore(s => s.tour !== null) const isAuthPage = location.pathname.startsWith('/login') || location.pathname.startsWith('/register') @@ -455,7 +459,7 @@ export default function App() { so a mounted boundary keeps the current page on screen instead of flashing a spinner on every jump — the spinner is for the first paint of a deep link. */} }> - + } /> } /> } /> diff --git a/client/src/components/Layout/AppLockGate.tsx b/client/src/components/Layout/AppLockGate.tsx index 45498c8b7..094f08e6f 100644 --- a/client/src/components/Layout/AppLockGate.tsx +++ b/client/src/components/Layout/AppLockGate.tsx @@ -62,7 +62,7 @@ export default function AppLockGate(): React.ReactElement | null { role="dialog" aria-modal="true" aria-label={t('native.lock.title')} - className="fixed inset-0 z-[100001] flex flex-col items-center justify-center gap-5 bg-surface p-8 text-center backdrop-blur-2xl" + className="fixed inset-0 z-[calc(var(--z-toast)+1)] flex flex-col items-center justify-center gap-5 bg-surface p-8 text-center backdrop-blur-2xl" >