Compare commits

..

97 Commits

Author SHA1 Message Date
Maurice 87107d7cba fix(atlas): keep the cached regions projection typed as unknown
The offline snapshot may contain any legacy value. Explicitly retain its unknown type throughout the queue projection to pass the strict client type check.
2026-12-06 18:09:21 +01:00
Maurice 4516edfdad fix(ci): repair client checks for the audit fixes
Keep tile substitution compatible with ES2020 and refresh confirmed bulk settings without replacing live values. Make the Atlas cache fallback explicit and check that removing the last region clears its map entry.
2026-12-06 18:01:48 +01:00
Maurice 360bea8bf4 fix(atlas): refresh the open globe after offline region removal
Use the same queued Atlas projection for an open globe and for an offline restart.
2026-12-06 17:24:39 +01:00
Maurice e3922b76d8 fix(atlas): reconcile offline country and region changes together
Keep country and region reads in step with queued writes and with the mark source held by the server. Reconcile a delete already applied elsewhere before removing it from the account queue.
2026-12-06 17:24:10 +01:00
Maurice da0ecc3f88 fix(atlas): keep online actions usable when the cache fails
Return successful server responses even when IndexedDB is unavailable. Keep the offline queue in use whenever it is readable, and do not cache a response after the account changes.
2026-12-06 17:20:39 +01:00
Maurice a796383e3f fix(journey): retry unsent follower digests
Record pending entries per follower alongside the in-app announcement. Retry only unsettled deliveries and recheck current sharing and entry visibility before composing mail.
2026-12-06 17:20:10 +01:00
Maurice 36bf9fb223 fix(offline): keep account credentials out of the settings cache
Keep only offline presentation and map preferences and scrub old cached settings on access. Update the cache from successful writes without retaining preferences the server declined.
2026-12-06 16:04:52 +01:00
Maurice bbaedc5aa9 docs: document Atlas tools and OpenRouter routing
Document the Atlas comparison default, the custom trip tag inputs and the OpenRouter upstream setting.
2026-12-06 16:04:32 +01:00
Maurice dcbabe998b fix(map): use stored basemaps for uncached GL raster hosts
Share the service-worker raster match with prefetch and the offline renderer. Keep an allowed custom host online and switch to the stored basemap offline when its tiles are outside the readable cache.
2026-12-06 16:04:31 +01:00
Maurice f394818f40 fix(mail-ingest): create missing IMAP archive parent on demand 2026-12-05 13:27:17 +01:00
Luffy b15cd49833 fix(mail-ingest): enhance header processing to prioritize X-Forwarded-To for IMAP 2026-12-05 13:27:17 +01:00
Luffy a4bd40cb0a fix(externalNotifications): improve clarity of pending booking notification message 2026-12-05 13:27:16 +01:00
Luffy 7713e37a8d fix(mail-ingest): create IMAP archive folders only when needed 2026-12-05 13:27:16 +01:00
Maurice 543af0cbcb Merge pull request #3319 from liketrek/codex/trip-tags-desktop-polish
Add custom trip tags and refine the desktop interface
2026-12-05 13:26:40 +01:00
Maurice 57903738be fix(ci): pass only tag names to the tag key mapper
Use an explicit single-argument callback for tag arrays so the mapper cannot receive an index or array from map.
2026-12-05 13:12:36 +01:00
Maurice 12927a3111 fix(ci): format the trip row helper imports
Apply the server import ordering reported by the formatting check.
2026-12-05 12:52:26 +01:00
Maurice f3bbd1a268 fix(ci): align packing parity and simplify offline sync
Describe bringer input in the shared packing contract and check its trip event against the REST contributor operation. Keep offline map preparation in its own step without changing the order or the sign-out checks.
2026-12-05 12:45:31 +01:00
Maurice 4333020e14 fix(ci): remove unused copy and split trip tag persistence
Remove unused dialog and upload strings from all locales. Move tag encoding and tag updates out of the largest trip files to meet the server size limits.
2026-12-05 12:44:35 +01:00
Maurice fb7169b158 fix(ci): format the updated desktop components
Apply the repository formatter to the files listed by the Client checks formatting step.
2026-12-05 12:36:57 +01:00
Maurice 09567d32c4 fix(packing): serialize bringer and privacy updates
Use the shared write transaction for packing item updates and contributor edits. Remove Common bringers when an item becomes restricted and scope contributor broadcasts to the returned item viewers.
2026-12-05 12:35:18 +01:00
Maurice b79d104349 fix(ios): verify the shell before saving offline trips
Recheck cached assets during explicit offline preparation even when the build is marked warm. Keep the existing start page, trip cache, and pin if this check fails. Keep the ordinary launch fast path for warm builds.

Refs #3318
2026-12-05 12:35:18 +01:00
Maurice 1eddfe3a29 fix(ci): resolve remaining trip UI and contract checks
Match the date badge and spotlight behavior in tests, keep stored tag data out of plugin responses, and handle missing place review text. Lower the ratchets to the counts reported by CI after the simplifications.
2026-12-05 12:31:22 +01:00
Maurice 06ee5a850b feat(mcp): set bringers for a packing item
Let packing editors replace the bringers on a Common item in one write. Use the existing trip roster, item visibility and packing edit policy, and leave the sharing tier and recipients alone.

Closes #3313
2026-12-05 12:30:17 +01:00
Maurice f7c45a2d85 fix(ios): prepare the app shell before finishing offline downloads
Download the app shell as part of explicit offline preparation on iOS. Refuse to mark a build ready if any asset fetch returns an HTTP error, and invalidate success markers recorded by the old logic.

Refs #3318
2026-12-05 12:24:23 +01:00
Maurice 53198b4d58 Align trip tags and desktop UI with CI contracts 2026-12-05 12:24:04 +01:00
Maurice 3cd22b91ff fix(ci): repair trip tag checks and shared booking build
Restore the category label used by shared bookings, keep measured tag-menu positioning, and fix form queries and schema formatting. Collapse the Route label within narrow toolbars.
2026-12-05 01:41:10 +01:00
Maurice 27b736a819 fix(planner): align the day route controls 2026-12-05 01:38:11 +01:00
Maurice 9cfad1d0d2 fix(planner): show rating alongside stop participants 2026-12-05 01:36:30 +01:00
Maurice 87c025024c feat(ui): add trip tag controls and harmonize desktop styling 2026-12-05 01:34:54 +01:00
Maurice c32c17ca17 feat(trips): support custom tags and MCP tag management 2026-12-05 01:34:47 +01:00
Maurice 908e4e1f8b fix(mobile): group checklist progress and filtering
Move packed-item visibility into the packing actions menu. Share an accessible progress display with To-Do and keep count badges only on filters with matching tasks.
2026-12-04 12:14:12 +01:00
Maurice 35b3ff0c9e fix(mobile): refine place headings and segmented tabs
Keep the category icon separately labeled beside the heading and verify both photo and plain headers. Give the five translated place tabs a full-width segmented surface with room for their count badges.
2026-12-04 12:05:14 +01:00
Maurice ef9a6fd7e1 fix(mobile): refine places sheets and restore the round dock
Put the category icon beside place names, shorten translated tab labels, and give tab counts their own badges. Bring the save-to-list dialog and trip badges in line with mobile sheets, and restore the icon-only dock.
2026-12-04 11:56:22 +01:00
Maurice d6527fa2e5 fix(deps): patch audited runtime dependencies
Raise the DOMPurify and Hono adapter security floors within the versions supported by their consumers. Regenerate only the two affected lockfile entries.
2026-12-04 11:41:21 +01:00
Maurice e0dc08214e fix(mobile): sort currency codes explicitly
Use the shared code-unit comparator for dashboard currency options while preserving their existing order.
2026-12-04 11:02:21 +01:00
Maurice aa4573bf0d fix(ci): keep the place editor below the function limit
Move the day label formatter out of the editor. Keep the image spacing and the reduced warning count verified in CI.
2026-12-04 10:46:50 +01:00
Maurice 9599a4d895 chore(lint): lower verified client warning counts
Match the three reduced warning counts reported by GitHub CI. Preserve the existing gap above the place image field and align the extracted settings markup.
2026-12-04 10:37:13 +01:00
Maurice 34b9b7b0d0 fix(ci): repair mobile client checks
Split mobile view logic at existing UI boundaries and keep shared calendar hooks outside component modules. Register the phone-only files and make the sheet gesture and final budget assertions independent of scheduling.
2026-12-04 10:30:11 +01:00
Maurice b06fa93c4a fix(ci): report client warnings without linting twice
Use the completed ESLint results to locate warnings in changed files. Rechecking alternate source versions still exhausted the runner, even in sequence.

Reset transient sheet state without a second render from an effect.
2026-12-04 09:59:06 +01:00
Maurice 814e4f047e fix(ci): repair mobile tests and lint diagnostics
Restore the saved-list filter import and test the actual sheet backdrop. Remove unsafe fixture assertions and apply formatting reported by CI.

Reuse the current lint results and compare base files in sequence so warning diagnostics can finish without exhausting the heap.
2026-12-04 09:48:37 +01:00
Maurice faaa56eda6 fix(mobile): harden back gestures and repair CI regressions
Reflect the drag position in the sheet scrim and match back gestures to the reading direction. Keep Escape on the top overlay and update failing tests for the redesigned forms, navigation, and offline preparation. Remove dead exports and lower obsolete lint counts.
2026-12-03 23:30:26 +01:00
Maurice 4b54a00d89 test(mobile): align transport and formatting checks 2026-12-03 23:16:21 +01:00
Maurice 00955f0ac5 feat(mobile): refine TREK navigation and interfaces 2026-12-03 23:13:10 +01:00
Maurice 995e9c435f fix(ci): align place form pairs and exports
Point the paired-view manifest at the hook that now owns the desktop place form. Keep internals private and lower the unused-types baseline for the types now removed or used.
2026-12-03 12:06:47 +01:00
Maurice 259d23f971 fix(ci): repair strict types and empty dashboard card
Keep the dashboard card class when it spans all columns. Match the place form payload to the service-stop placement type and make dialog card hints optional. Document the independent receipt copy and format the files flagged by CI.
2026-12-03 12:06:47 +01:00
Maurice 7196ad30da fix(ci): repair trip assistant checks
Fix the mobile dashboard import and align the assistant UI with client layer and lint rules. Document the OpenRouter setting, share the reservation status schema, and update coverage for external POI identifiers and the empty costs view.
2026-12-03 12:06:46 +01:00
Maurice 3945037ff3 fix(assistant): improve trip proposals and approvals 2026-12-03 12:06:46 +01:00
Maurice f10435b42b fix(ui): refine trip forms and planner empty states 2026-12-03 12:06:44 +01:00
Maurice c6a50695d8 fix(ai): support optional OpenRouter upstream selection 2026-12-03 12:06:24 +01:00
Maurice ea1a2527ab test(map): match street-level focus in map regressions
Give the Leaflet fixtures definite coordinates for the strict check and update the GL day-only test to expect the street-level zoom.
2026-12-03 11:18:54 +01:00
Maurice 4b7c96f4c5 fix(map): reveal selected places at street level
Use street-level zoom in both renderers while keeping the selected pin between the map panels. Lift the selected Leaflet marker out of a dense group when needed, and keep a late route fit from overriding the selection.

Closes #3306
2026-12-03 11:10:16 +01:00
Maurice 8ae919c650 fix(studio): finish preparing the Journey PDF export
A sandboxed print frame cannot run the callback that bounds the wait for print assets. Run the timer in the app so an already settled SVG image cannot keep the Save as PDF button disabled.

Closes #3309
2026-12-03 11:10:16 +01:00
Maurice 75020dd2df fix(llm-parse): read fenced booking JSON surrounded by prose
Some booking models return a complete JSON code block followed by an explanation. Read the fenced payload when parsing the full answer fails, and leave the existing JSON and JSON5 behavior intact.

Closes #3307
2026-12-03 11:10:15 +01:00
Maurice ca201ab4d0 Merge PR #3300: Native Cloud trials and password recovery 2026-12-03 10:43:03 +01:00
Maurice 0f683b0dee Isolate store purchase rehearsals from TREK Cloud production [skip ci] 2026-12-02 18:38:59 +01:00
Maurice e54f954f31 Recheck the agreement before opening the store purchase sheet [skip ci] 2026-12-02 16:33:34 +01:00
Maurice a2cf911ce1 fix(dashboard): respect pointer type when focusing trip titles
Mark the title through the existing dialog focus mechanism so a
mouse can type right away and touch keeps focus on the dialog.
Cover creating and editing a trip in the dashboard tests.
2026-12-02 14:49:52 +01:00
Luffy 7a66a54e66 fix(dashboard): focus the title in desktop trip forms 2026-12-02 14:46:23 +01:00
Maurice bf6a66d52c Offer a new link when password recovery expires [skip ci] 2026-12-02 13:58:53 +01:00
Maurice 748434fc47 style(server): satisfy accommodation confirmation lint
Keep ordered writes for one linked booking in a single method. Check
that each test fixture exists before using the reservation.
2026-12-02 11:55:45 +01:00
Maurice 618f070675 fix(accommodations): keep booking confirmations in sync
Distinguish omitted references from explicit clears on stays and their
linked bookings. Reserve automatic confirmation for a new reference
with a booking code format. Announce linked changes after booking edits.

Closes #3301
2026-12-02 11:49:33 +01:00
Maurice 260e1ef023 Shorten the German plan label for booking mail [skip ci] 2026-12-02 10:56:55 +01:00
Maurice 262741bf89 fix(ci): narrow the optional cloud checkout price [skip ci]
The strict client check rejected a nullable DOM child when the checkout had no price label. Append the price only when present and retain the standard strict baseline.
2026-12-02 10:54:28 +01:00
Maurice 3438a2aa48 Polish native cloud plans and trial presentation [skip ci] 2026-12-02 10:47:08 +01:00
Maurice dacf19b4d5 style(server): format the assistant proposal guard
The Server lint formatting check rejected the assistant agent and its regression test. Apply the repository Prettier configuration to those two files.
2026-12-02 10:23:11 +01:00
Maurice 103631d5fc Hold identical assistant changes only once per step 2026-12-02 10:23:11 +01:00
Maurice 00fcb69423 Show verified store trials in the native cloud purchase flow [skip ci] 2026-12-02 10:20:28 +01:00
Maurice dbcdecb6a7 Give password recovery the native sign-in layout 2026-12-02 10:20:27 +01:00
Maurice 10fecf4e80 fix(ci): document the exact migration filter
The metadata substring filter only finds candidates. Exact timezone comparison in the migration ensures SQLite and PostgreSQL update the same records.
2026-12-02 09:59:29 +01:00
Maurice 12483f618f fix(journey): give the public gallery a definite width
Keep both centered content layouts from collapsing before Firefox loads gallery thumbnails.

Closes #3296
2026-12-02 09:46:23 +01:00
Maurice 17c4d69e40 fix(airports): use Bahrain time for Bahrain flights
Correct the airport data and repair affected flight endpoints and metadata during upgrade. Preserve stored local flight times and legacy metadata encoding.

Closes #3294
2026-12-02 09:45:20 +01:00
Maurice d6184559e9 fix(assistant): keep OpenRouter turns in one routing session
Pass a stable conversation session to OpenRouter so turns can reuse the same provider route. Namespace locally allocated thread IDs across server processes.

Closes #3298
2026-12-02 09:45:19 +01:00
Maurice 3089aee593 fix(journey): align media validation with server checks
Validate spooled uploads in order with the shared iterator and keep media format detection in a shared utility. Adapt the controller unit fixtures and cover raster signatures, including animated PNG.
2026-12-02 09:29:33 +01:00
Maurice 24ddc3e4b0 fix(journey): validate and safely serve media uploads 2026-12-02 09:21:51 +01:00
Maurice a4cb6c69d8 chore(lint): lower the client ref-warning baseline
The plugin frame permission check now reads the store when needed. GitHub CI reports 384 react-hooks/refs warnings instead of 385.
2026-12-01 22:07:41 +01:00
Maurice 6e224cb7a4 fix(plugins): bind bridge replies to the active document
Keep pending replies tied to their original frame and verify the current permission before returning location data. Release watches when their frame detaches and preserve live replies across host context updates.
2026-12-01 22:00:45 +01:00
Maurice 56b4568a16 test(platform): cover static asset cache boundaries
Exercise the filename and path boundaries used to decide which static assets can be cached permanently, including unhashed Brotli copies.
2026-12-01 21:22:35 +01:00
Maurice 756ef14b97 fix(client): preserve explicit dialog focus and verify accessible controls
Keep the focused search for new places and title fields in explicitly opened dialogs. Assert the native ride badge button and the pointer grip tooltip in the existing tests.
2026-12-01 21:13:35 +01:00
Maurice e539860530 fix(quality): resolve reliability findings on dev
The Sonar quality gate rated new code D. Preserve focus and keyboard interaction through native controls and shared dialog behavior. Replace ambiguous regex scans with bounded parsing and make numeric coercion and initialization explicit.
2026-12-01 21:06:05 +01:00
Maurice 0d6a432967 test(server): type the hosted assistant regression on ES2022
Use the lookup overload for all addresses and drain the stream with the existing TypeScript target. Server types rejected the default lookup overload and Array.fromAsync.
2026-12-01 19:37:29 +01:00
Maurice 89035059ec fix(cloud): route the hosted assistant through its private gateway 2026-12-01 19:28:28 +01:00
Maurice 4ad926aafc fix(ci): give typed server lint more heap and patch audited dependencies
Keep the typed lint rules and ratchet intact after the 8 GiB heap was exhausted on the runner. Resolve the patched Hono adapter and cross-spawn within their existing major versions.
2026-12-01 15:21:50 +01:00
Maurice 60a30afb81 fix(deps): narrow Lucide icon types and lower the lint baseline
Keep the typed icon lookup aligned with the runtime namespace and record the three removed test assertions.
2026-12-01 13:51:32 +01:00
Maurice b77c246df4 fix(deps): keep Lucide SVG markup and Undici tests compatible
Build standalone SVG icons without a React context. Use accessible actions in tests and give the mocked dispatchers the interface the adapter expects.
2026-12-01 13:44:02 +01:00
Maurice 7f4ece2e6f chore(deps): update npm packages and adapt major upgrades
Resolve the MikroORM packages together and use the dispatcher adapter with older built-in fetch implementations. Preserve existing Lucide names and regenerate the Studio and SDK catalogs.
2026-12-01 13:32:28 +01:00
Maurice a14b6a61e6 chore(server): remove resolved plugin type errors from the baseline 2026-12-01 12:29:34 +01:00
Maurice 871135edeb refactor(plugins): generate SDK egress policy from the server 2026-12-01 12:24:32 +01:00
Maurice c22c464e68 fix: keep security checks in sync with their contracts
Mirror the egress policy in the standalone SDK and check its entire shared section. Keep entrypoint assertions aligned with the debug flag and document the mutually exclusive OIDC transactions.
2026-12-01 12:04:55 +01:00
Maurice 3c2dc51439 fix(plugins): validate stable egress options
Keep egress comparisons independent of mutable runtime methods and pass the same normalized options to validation and the socket. Restrict process signaling from plugin workers and disable signal-initiated debugging on standard server starts.
2026-12-01 11:56:24 +01:00
Maurice 28eea68559 fix(media): bound image work before public rendition
Check avatar uploads and raster fallbacks before decoding. Limit compressed bytes, decoded dimensions, GIF frames and the combined TIFF page budget.
2026-12-01 11:56:24 +01:00
Maurice 1ff8a814ae fix(oidc): verify mailbox identity before linking accounts
Preserve the provider mailbox on new accounts. For existing accounts, use the stored issuer and subject or check mailbox identity before linking. Keep the candidate lookup and identity update inside the same transaction.
2026-12-01 11:56:24 +01:00
Maurice 0d521f0930 test(transit): cover long labels in both journey details
Exercise a line with a provider colour and no foreground override on desktop and phone. Confirm that the badge can wrap and leaves room for the rest of the itinerary.
2026-12-01 11:42:31 +01:00
Maurice 7fc011408a test(transit): find mode icons on the line badge
The search test must look for the icon beside the label inside the shared badge.
2026-12-01 11:28:14 +01:00
Maurice 8f20f9f7ea test(transit): check the rendered line badge colours
The booking test checked the nested label after the badge layout changed. Assert the provider colours on the outer badge that sets them.
2026-12-01 11:21:52 +01:00
Maurice 67b65a7647 fix(transit): keep stop names readable beside long route names
Line badges could take the width of a transit row and squeeze its stops. Bound badge width across the itinerary views, wrap full labels in details, and keep compact summaries within their container.

Closes #3287
2026-12-01 11:11:53 +01:00
Luffy 82b2a530f3 fix(places): add titles to Unsplash list cover thumbnails 2026-12-01 15:31:01 +08:00
Maurice 76a3983972 Merge pull request #3284 from liketrek/fix/cloud-store-catalog
fix(native): offer Start and Plus in the TREK Cloud catalog
2026-12-01 01:04:29 +01:00
1376 changed files with 35010 additions and 20927 deletions
+4 -4
View File
@@ -438,10 +438,10 @@ jobs:
- name: Lint - name: Lint
# Errors fail, and the warnings per rule may not pass # Errors fail, and the warnings per rule may not pass
# scripts/eslint-baseline.json (src, tests and eslint-disable'd # scripts/eslint-baseline.json (src, tests and eslint-disable'd
# messages counted apart). Type-aware rules build the src + tests # messages counted apart). The typed src and test programs can exhaust
# program, which outgrows Node's default ~4 GB heap on the runner. # an 8 GiB heap. Leave headroom within the runner's 16 GB of RAM.
env: env:
NODE_OPTIONS: --max-old-space-size=8192 NODE_OPTIONS: --max-old-space-size=10240
TREK_LINT_BASE: refs/remotes/lint-base TREK_LINT_BASE: refs/remotes/lint-base
run: cd server && npm run lint:warnings run: cd server && npm run lint:warnings
@@ -990,7 +990,7 @@ jobs:
# Fails on any ESLint error, like lint:check did, and on any rule # Fails on any ESLint error, like lint:check did, and on any rule
# whose warning count rises above scripts/eslint-baseline.json. # whose warning count rises above scripts/eslint-baseline.json.
# Typed linting (no-floating-promises, no-misused-promises) loads the # Typed linting (no-floating-promises, no-misused-promises) loads the
# whole TypeScript program, so it gets the heap the server lint gets. # whole TypeScript program, which exceeds Node's default heap.
env: env:
NODE_OPTIONS: --max-old-space-size=8192 NODE_OPTIONS: --max-old-space-size=8192
TREK_LINT_BASE: refs/remotes/lint-base TREK_LINT_BASE: refs/remotes/lint-base
+1
View File
@@ -11,3 +11,4 @@ e2e/help/media.env
# The native apps' address screen (npm run build:native), copied into # The native apps' address screen (npm run build:native), copied into
# android/ and ios/ by `cap sync` # android/ and ios/ by `cap sync`
native-dist/ native-dist/
native-sandbox-dist/
@@ -102,21 +102,61 @@ object TrekBilling {
return offers.firstOrNull { it.offerId == null } ?: offers.firstOrNull() return offers.firstOrNull { it.offerId == null } ?: offers.firstOrNull()
} }
/** Play returns eligible offers. The named offer must be configured with Play's new-customer eligibility. */
private fun trialOffer(product: ProductDetails): ProductDetails.SubscriptionOfferDetails? {
val base = baseOffer(product)?.takeIf { it.offerId == null } ?: return null
val recurring = base.pricingPhases.pricingPhaseList.singleOrNull() ?: return null
return product.subscriptionOfferDetails?.firstOrNull { offer ->
offer.offerId == TRIAL_OFFER_ID && offer.basePlanId == base.basePlanId &&
isSevenDayTrial(offer.pricingPhases.pricingPhaseList, recurring)
}
}
private fun isSevenDayTrial(
phases: List<ProductDetails.PricingPhase>,
recurring: ProductDetails.PricingPhase,
): Boolean {
if (phases.size != 2) return false
val (trial, renewal) = phases
val once = trial.recurrenceMode == ProductDetails.RecurrenceMode.NON_RECURRING ||
(trial.recurrenceMode == ProductDetails.RecurrenceMode.FINITE_RECURRING && trial.billingCycleCount == 1)
return once && trial.priceAmountMicros == 0L && trial.billingPeriod in listOf("P1W", "P7D") &&
renewal.recurrenceMode == ProductDetails.RecurrenceMode.INFINITE_RECURRING &&
renewal.billingPeriod == recurring.billingPeriod && renewal.priceAmountMicros == recurring.priceAmountMicros &&
renewal.priceCurrencyCode == recurring.priceCurrencyCode
}
fun products(context: Context, call: PluginCall) { fun products(context: Context, call: PluginCall) {
val ids = call.getArray("ids")?.toList<String>().orEmpty() val ids = call.getArray("ids")?.toList<String>().orEmpty()
ready(context) { ok -> ready(context) { ok ->
val result = JSObject().put("sandbox", BuildConfig.DEBUG) val result = JSObject().put("sandbox", BuildConfig.DEBUG)
if (!ok) return@ready call.resolve(result.put("products", JSArray())) if (!ok || ids.isEmpty()) return@ready call.resolve(result.put("products", JSArray()))
details(context, ids) { found -> details(context, ids) { found ->
val list = JSArray() val candidates = found.filter { trialOffer(it) != null }.map { it.productId }.toSet()
for (product in found) displayPrice(product)?.let { list.put(JSObject().put("id", product.productId).put("displayPrice", it)) } if (candidates.isEmpty()) {
call.resolve(result.put("products", list)) call.resolve(result.put("products", productList(found, emptySet())))
return@details
}
val params = QueryPurchasesParams.newBuilder().setProductType(BillingClient.ProductType.SUBS).build()
client(context).queryPurchasesAsync(params) { status, purchases ->
val eligible = status.responseCode == BillingClient.BillingResponseCode.OK && purchases.none { purchase ->
purchase.products.any { it.startsWith(PREFIX) }
}
call.resolve(result.put("products", productList(found, if (eligible) candidates else emptySet())))
}
} }
} }
} }
private fun productList(products: List<ProductDetails>, freeTrials: Set<String>): JSArray = JSArray().apply {
for (product in products) displayPrice(product)?.let { price ->
put(JSObject().put("id", product.productId).put("displayPrice", price).put("freeTrial", product.productId in freeTrials))
}
}
fun purchase(activity: Activity, call: PluginCall) { fun purchase(activity: Activity, call: PluginCall) {
val id = call.getString("productId") ?: return call.reject("productId is required") val id = call.getString("productId") ?: return call.reject("productId is required")
val trialRenewalPrice = call.getString("trialRenewalPrice")
ready(activity) { ok -> ready(activity) { ok ->
if (!ok) return@ready call.resolve(JSObject().put("kind", "failed")) if (!ok) return@ready call.resolve(JSObject().put("kind", "failed"))
// One subscription per Google account: a second plan would run beside the first. // One subscription per Google account: a second plan would run beside the first.
@@ -126,19 +166,28 @@ object TrekBilling {
client(activity).queryPurchasesAsync(params) { result, purchases -> client(activity).queryPurchasesAsync(params) { result, purchases ->
val held = if (result.responseCode == BillingClient.BillingResponseCode.OK) newest(purchases, PREFIX) else null val held = if (result.responseCode == BillingClient.BillingResponseCode.OK) newest(purchases, PREFIX) else null
when { when {
held == null -> launchPurchase(activity, call, id) held?.isAcknowledged == true -> call.resolve(JSObject().put("kind", "subscribed"))
held.isAcknowledged -> call.resolve(JSObject().put("kind", "subscribed")) held != null -> call.resolve(receipt(held).put("kind", "bought"))
else -> call.resolve(receipt(held).put("kind", "bought")) trialRenewalPrice != null && result.responseCode != BillingClient.BillingResponseCode.OK ->
call.resolve(JSObject().put("kind", "offer-changed"))
purchases.any { p -> p.purchaseState == Purchase.PurchaseState.PENDING && p.products.any { it.startsWith(PREFIX) } } ->
call.resolve(JSObject().put("kind", "pending"))
else -> launchPurchase(activity, call, id, trialRenewalPrice)
} }
} }
} }
} }
private fun launchPurchase(activity: Activity, call: PluginCall, id: String) { private fun launchPurchase(activity: Activity, call: PluginCall, id: String, trialRenewalPrice: String?) {
details(activity, listOf(id)) { found -> details(activity, listOf(id)) { found ->
val product = found.firstOrNull() val product = found.firstOrNull()
val offer = product?.let(::baseOffer) val offer = product?.let { listed ->
if (product == null || offer == null) return@details call.resolve(JSObject().put("kind", "failed")) if (trialRenewalPrice == null) baseOffer(listed)
else trialOffer(listed)?.takeIf { displayPrice(listed) == trialRenewalPrice }
}
if (product == null || offer == null) {
return@details call.resolve(JSObject().put("kind", if (trialRenewalPrice != null) "offer-changed" else "failed"))
}
pendingPurchase?.resolve(JSObject().put("kind", "cancelled")) pendingPurchase?.resolve(JSObject().put("kind", "cancelled"))
pendingPurchase = call pendingPurchase = call
pendingProduct = id pendingProduct = id
@@ -275,6 +324,7 @@ object TrekBilling {
newest(purchases.filter { !it.isAcknowledged }, prefix) newest(purchases.filter { !it.isAcknowledged }, prefix)
private const val PREFIX = "cloud." private const val PREFIX = "cloud."
private const val TRIAL_OFFER_ID = "trek-trial-7-days"
internal fun newest(purchases: List<Purchase>, prefix: String): Purchase? = purchases internal fun newest(purchases: List<Purchase>, prefix: String): Purchase? = purchases
.filter { p -> p.purchaseState == Purchase.PurchaseState.PURCHASED && p.products.any { it.startsWith(prefix) } } .filter { p -> p.purchaseState == Purchase.PurchaseState.PURCHASED && p.products.any { it.startsWith(prefix) } }
+4
View File
@@ -162,6 +162,10 @@ test('the saved hike difficulty dropdown fits above the field and keeps alpine c
const difficulty = page.getByRole('button', { name: 'Maximum trail difficulty', exact: true }); const difficulty = page.getByRole('button', { name: 'Maximum trail difficulty', exact: true });
const difficultyMenu = page.getByRole('group', { name: 'Maximum trail difficulty', exact: true }); const difficultyMenu = page.getByRole('group', { name: 'Maximum trail difficulty', exact: true });
await difficulty.scrollIntoViewIfNeeded(); await difficulty.scrollIntoViewIfNeeded();
await difficulty.evaluate((button) => {
const rail = button.closest('[data-testid="tour-planner-editor-scroll"]');
if (rail) rail.scrollTop += button.getBoundingClientRect().bottom - rail.getBoundingClientRect().bottom + 12;
});
await difficulty.click(); await difficulty.click();
await expectInside(difficultyMenu, scrollArea); await expectInside(difficultyMenu, scrollArea);
await expect(difficultyMenu).toHaveCSS('transform-origin', /px [1-9][0-9.]*px$/); await expect(difficultyMenu).toHaveCSS('transform-origin', /px [1-9][0-9.]*px$/);
+39 -3
View File
@@ -688,14 +688,40 @@ extension TrekShellPlugin {
let ids = call.getArray("ids", String.self) ?? [] let ids = call.getArray("ids", String.self) ?? []
Task { Task {
let sandbox = await Self.buysInSandbox() let sandbox = await Self.buysInSandbox()
guard AppStore.canMakePayments, let products = try? await Product.products(for: ids) else { guard !ids.isEmpty, AppStore.canMakePayments, let products = try? await Product.products(for: ids) else {
call.resolve(["products": [], "sandbox": sandbox]) call.resolve(["products": [], "sandbox": sandbox])
return return
} }
call.resolve(["products": products.map { ["id": $0.id, "displayPrice": $0.displayPrice] }, "sandbox": sandbox]) var canStartTrial = false
if products.contains(where: Self.hasSevenDayFreeTrial) {
canStartTrial = await TrekStore.currentEntitlement(prefix: "cloud.") == nil
}
var groupEligibility: [String: Bool] = [:]
var rows: [[String: Any]] = []
for product in products {
var freeTrial = false
if canStartTrial, Self.hasSevenDayFreeTrial(product), let subscription = product.subscription {
let group = subscription.subscriptionGroupID
if let cached = groupEligibility[group] {
freeTrial = cached
} else {
freeTrial = await subscription.isEligibleForIntroOffer
groupEligibility[group] = freeTrial
}
}
rows.append(["id": product.id, "displayPrice": product.displayPrice, "freeTrial": freeTrial])
}
call.resolve(["products": rows, "sandbox": sandbox])
} }
} }
private static func hasSevenDayFreeTrial(_ product: Product) -> Bool {
guard let offer = product.subscription?.introductoryOffer,
offer.paymentMode == .freeTrial, offer.price == 0, offer.periodCount == 1 else { return false }
return (offer.period.unit == .week && offer.period.value == 1)
|| (offer.period.unit == .day && offer.period.value == 7)
}
/// Whether this build buys in the App Store sandbox: TestFlight, App Review and /// Whether this build buys in the App Store sandbox: TestFlight, App Review and
/// Xcode builds do, and while TREK Cloud's orders are closed only they may buy. /// Xcode builds do, and while TREK Cloud's orders are closed only they may buy.
/// The signed app transaction names its environment; the receipt's file name, /// The signed app transaction names its environment; the receipt's file name,
@@ -726,6 +752,7 @@ extension TrekShellPlugin {
call.reject("productId is required") call.reject("productId is required")
return return
} }
let trialRenewalPrice = call.getString("trialRenewalPrice")
Task { Task {
// One subscription per Apple ID: another plan would change it, not add one. // One subscription per Apple ID: another plan would change it, not add one.
// A held one that was delivered stops the purchase here. One that was paid // A held one that was delivered stops the purchase here. One that was paid
@@ -740,9 +767,18 @@ extension TrekShellPlugin {
} }
do { do {
guard let product = try await Product.products(for: [id]).first else { guard let product = try await Product.products(for: [id]).first else {
call.resolve(["kind": "failed"]) call.resolve(["kind": trialRenewalPrice == nil ? "failed" : "offer-changed"])
return return
} }
if let trialRenewalPrice {
guard product.displayPrice == trialRenewalPrice, Self.hasSevenDayFreeTrial(product),
let subscription = product.subscription,
await subscription.isEligibleForIntroOffer else {
call.resolve(["kind": "offer-changed"])
return
}
}
// StoreKit applies an eligible introductory offer in its purchase sheet.
switch try await product.purchase() { switch try await product.purchase() {
case .success(let verification): case .success(let verification):
guard case .verified(let transaction) = verification else { guard case .verified(let transaction) = verification else {
+210 -140
View File
@@ -7,14 +7,21 @@ import { PASSWORD_MIN_LENGTH, passwordProblem, passwordRuleStates } from '../../
import logoWhite from '../public/logo-light.svg'; // #fff wordmark, for the landscape import logoWhite from '../public/logo-light.svg'; // #fff wordmark, for the landscape
import { pageUnderStatusBar } from '../src/native/appBoot'; import { pageUnderStatusBar } from '../src/native/appBoot';
import { AUTH_GATE_NAMES, canSignInInApp, type AuthGate } from '../src/native/authGate'; import { AUTH_GATE_NAMES, canSignInInApp, type AuthGate } from '../src/native/authGate';
import { isNewCloudPlan, opensSoon, planForUnclaimedPurchase, refundedBeforeOpening } from '../src/native/cloudOrders'; import {
import { fakeIapClient, getIapClient, productIdFor, type Purchase } from '../src/native/iap'; isNewCloudPlan,
matchesPurchaseAgreement,
opensSoon,
planForUnclaimedPurchase,
refundedBeforeOpening,
type CloudPurchaseAgreement,
} from '../src/native/cloudOrders';
import { fakeIapClient, getIapClient, productIdFor, type IapProduct, type Purchase } from '../src/native/iap';
import { import {
APP_STORE_SUBSCRIPTIONS_URL, APP_STORE_SUBSCRIPTIONS_URL,
AUTH_PROXY_DOCS_URL, AUTH_PROXY_DOCS_URL,
CLIENT_CERT_DOCS_URL, CLIENT_CERT_DOCS_URL,
CLOUD_TERMS_URL, CLOUD_TERMS_URL,
CLOUD_URL, CLOUD_URL as PRODUCTION_CLOUD_URL,
PLAY_SUBSCRIPTIONS_URL, PLAY_SUBSCRIPTIONS_URL,
PRIVACY_URL, PRIVACY_URL,
STORE_TERMS_URL, STORE_TERMS_URL,
@@ -50,6 +57,13 @@ document.documentElement.dir = directionOf(locale);
const root = document.getElementById('shell')!; const root = document.getElementById('shell')!;
const PROBE_TIMEOUT_MS = 8000; const PROBE_TIMEOUT_MS = 8000;
const cloudSandbox = typeof __TREK_STORE_SANDBOX_ORIGIN__ === 'string' ? __TREK_STORE_SANDBOX_ORIGIN__ : undefined;
const CLOUD_URL = cloudSandbox ?? PRODUCTION_CLOUD_URL;
const cloudHttpOptions = {
connectTimeout: PROBE_TIMEOUT_MS,
readTimeout: PROBE_TIMEOUT_MS,
...(cloudSandbox ? { disableRedirects: true } : {}),
};
const iap = getIapClient(); const iap = getIapClient();
/** /**
@@ -98,6 +112,30 @@ const get: ProbeGet = async (url) => {
} }
}; };
// Keep Cloud sandbox requests on their requested host, including during tenant provisioning.
const cloudGet: ProbeGet = cloudSandbox ? (url) => CapacitorHttp.get({ url, ...cloudHttpOptions }) : get;
function isCloudSandboxTenant(address: string, sandboxOrigin: string): boolean {
let tenant: URL;
try {
tenant = new URL(address);
} catch {
return false;
}
const suffix = `.${new URL(sandboxOrigin).hostname}`;
const slug = tenant.hostname.slice(0, -suffix.length);
return (
tenant.origin === `https://${tenant.hostname}` &&
!tenant.username &&
!tenant.password &&
tenant.hostname.endsWith(suffix) &&
/^[a-z0-9-]+$/.test(slug) &&
tenant.pathname === '/' &&
!tenant.search &&
!tenant.hash
);
}
function failureMessage(reason: ProbeFailure): string { function failureMessage(reason: ProbeFailure): string {
switch (reason) { switch (reason) {
case 'invalid': case 'invalid':
@@ -151,12 +189,11 @@ const I = {
globe: 'M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20M2 12h20M12 2a15 15 0 0 1 0 20 15 15 0 0 1 0-20', globe: 'M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20M2 12h20M12 2a15 15 0 0 1 0 20 15 15 0 0 1 0-20',
image: image:
'M5 3h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2zM8.5 10a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3zM21 15l-5-5L5 21', 'M5 3h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2zM8.5 10a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3zM21 15l-5-5L5 21',
spark: 'M12 3l1.8 5.2L19 10l-5.2 1.8L12 17l-1.8-5.2L5 10l5.2-1.8z',
mail: 'M4 5h16a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2zM3 7l9 6 9-6',
people: people:
'M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2M9 11a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM22 21v-2a4 4 0 0 0-3-3.87M16 3.13a4 4 0 0 1 0 7.75', 'M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2M9 11a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM22 21v-2a4 4 0 0 0-3-3.87M16 3.13a4 4 0 0 1 0 7.75',
shield: 'M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10', shield: 'M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10',
check: 'M20 6 9 17l-5-5', check: 'M20 6 9 17l-5-5',
cross: 'M6 6l12 12M18 6 6 18',
lock: 'M6 11h12a2 2 0 0 1 2 2v7a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2zM8 11V8a4 4 0 0 1 8 0v3', lock: 'M6 11h12a2 2 0 0 1 2 2v7a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2zM8 11V8a4 4 0 0 1 8 0v3',
key: 'M7.5 20a4.5 4.5 0 1 0 0-9 4.5 4.5 0 0 0 0 9zM10.7 12.3 21 2M16 7l3 3M14 9l2 2', key: 'M7.5 20a4.5 4.5 0 1 0 0-9 4.5 4.5 0 0 0 0 9zM10.7 12.3 21 2M16 7l3 3M14 9l2 2',
alert: 'M12 21.5a9.5 9.5 0 1 0 0-19 9.5 9.5 0 0 0 0 19zM12 7.5v5.5M12 16.5h.01', alert: 'M12 21.5a9.5 9.5 0 1 0 0-19 9.5 9.5 0 0 0 0 19zM12 7.5v5.5M12 16.5h.01',
@@ -315,7 +352,8 @@ function showWelcome(opts: { back?: boolean } = {}): void {
const perk = (glyph: string, title: string, sub: string) => const perk = (glyph: string, title: string, sub: string) =>
el('div', {}, el('i', {}, icon(glyph, 17)), el('span', {}, el('b', {}, title), el('small', {}, sub))); el('div', {}, el('i', {}, icon(glyph, 17)), el('span', {}, el('b', {}, title), el('small', {}, sub)));
const discover = el('button', { type: 'button', className: 'cta' }, t('native.welcome.discover')); const trial = el('span', { className: 'trial-badge', hidden: true }, t('native.trial.badge'));
const discover = el('button', { type: 'button', className: 'cta discover' }, t('native.welcome.discover'), trial);
discover.addEventListener('click', () => { discover.addEventListener('click', () => {
void tap(); void tap();
showPlans(); showPlans();
@@ -326,7 +364,7 @@ function showWelcome(opts: { back?: boolean } = {}): void {
showConnect(); showConnect();
}); });
show( const screen = show(
'welcome', 'welcome',
WELCOME_CAMERA, WELCOME_CAMERA,
{ {
@@ -351,6 +389,9 @@ function showWelcome(opts: { back?: boolean } = {}): void {
}, },
opts opts
); );
void availableWelcomeTrial().then((available) => {
if (screen.node.isConnected) trial.hidden = !available;
});
} }
// ── Connect (address) ─────────────────────────────────────────────────────── // ── Connect (address) ───────────────────────────────────────────────────────
@@ -664,7 +705,7 @@ interface CloudPlan {
yearlyCents?: number; yearlyCents?: number;
currency?: 'EUR' | 'USD'; currency?: 'EUR' | 'USD';
aiDocuments: number; aiDocuments: number;
aiDocumentLimit?: 0 | null; aiDocumentLimit?: number | null;
aiAssistant?: 'planned' | 'included' | 'unavailable'; aiAssistant?: 'planned' | 'included' | 'unavailable';
bookingMailImport?: boolean; bookingMailImport?: boolean;
storageGb: number; storageGb: number;
@@ -681,24 +722,24 @@ const SAMPLE_PLANS: CloudPlan[] = [
{ {
id: 'start', id: 'start',
name: 'Start', name: 'Start',
monthlyCents: 499, monthlyCents: 599,
yearlyCents: 4899, yearlyCents: 4899,
currency: 'USD', currency: 'USD',
aiDocuments: 0, aiDocuments: 0,
aiDocumentLimit: 0, aiDocumentLimit: 0,
storageGb: 200, storageGb: 50,
}, },
{ {
id: 'plus', id: 'plus',
name: 'Plus', name: 'Plus',
monthlyCents: 999, monthlyCents: 1199,
yearlyCents: 9900, yearlyCents: 9900,
currency: 'USD', currency: 'USD',
aiDocuments: 100, aiDocuments: 100,
aiDocumentLimit: null, aiDocumentLimit: null,
aiAssistant: 'planned', aiAssistant: 'included',
bookingMailImport: true, bookingMailImport: true,
storageGb: 200, storageGb: 50,
}, },
]; ];
@@ -706,15 +747,18 @@ interface CloudPlans {
plans: CloudPlan[]; plans: CloudPlan[];
/** Orders are closed: only a test build may buy, and the store charges it nothing. */ /** Orders are closed: only a test build may buy, and the store charges it nothing. */
closed: boolean; closed: boolean;
/** Only the live catalogue's explicit opening permits customer trial advertising. */
open?: boolean;
} }
async function fetchPlans(): Promise<CloudPlans | null> { async function fetchPlans(): Promise<CloudPlans | null> {
try { try {
const res = await get(`${CLOUD_URL}/api/plans`); const res = await cloudGet(`${CLOUD_URL}/api/plans`);
const data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data; const data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data;
const body = (data ?? {}) as { plans?: CloudPlan[]; ordering?: string }; const body = (data ?? {}) as { plans?: CloudPlan[]; ordering?: string };
const plans = Array.isArray(body.plans) ? body.plans.filter((plan) => isNewCloudPlan(plan.id)) : []; const plans = Array.isArray(body.plans) ? body.plans.filter((plan) => isNewCloudPlan(plan.id)) : [];
if (plans.length) return { plans, closed: body.ordering === 'closed' }; if (plans.length)
return { plans, closed: body.ordering === 'closed', open: res.status === 200 && body.ordering === 'open' };
} catch { } catch {
// Fall through to the preview fallback. // Fall through to the preview fallback.
} }
@@ -730,22 +774,44 @@ async function fetchPlans(): Promise<CloudPlans | null> {
*/ */
interface Offer { interface Offer {
canBuy: boolean; canBuy: boolean;
storePrices: Map<string, string> | null; storeProducts: Map<string, IapProduct> | null;
canShowTrial: boolean;
/** Orders are closed and this is no test build: the plans show, nothing is for sale yet. */ /** Orders are closed and this is no test build: the plans show, nothing is for sale yet. */
opensSoon: boolean; opensSoon: boolean;
} }
function offerFor(offer: Offer, plan: CloudPlan, interval: 'month' | 'year'): { label: string; buyable: boolean } { function offerFor(
if (!offer.canBuy) return { label: '', buyable: false }; offer: Offer,
plan: CloudPlan,
interval: 'month' | 'year'
): { label: string; buyable: boolean; freeTrial: boolean } {
if (!offer.canBuy) return { label: '', buyable: false, freeTrial: false };
if (iap !== fakeIapClient) { if (iap !== fakeIapClient) {
const label = offer.storePrices?.get(productIdFor(plan.id, interval)) ?? ''; const product = offer.storeProducts?.get(productIdFor(plan.id, interval));
return { label, buyable: label !== '' }; const label = product?.displayPrice ?? '';
return {
label,
buyable: label !== '',
freeTrial: label !== '' && offer.canShowTrial && product?.freeTrial === true,
};
} }
const cents = interval === 'year' ? plan.yearlyCents : plan.monthlyCents; const cents = interval === 'year' ? plan.yearlyCents : plan.monthlyCents;
const currency = plan.currency ?? 'EUR'; const currency = plan.currency ?? 'EUR';
const label = const label =
typeof cents === 'number' ? new Intl.NumberFormat(locale, { style: 'currency', currency }).format(cents / 100) : ''; typeof cents === 'number' ? new Intl.NumberFormat(locale, { style: 'currency', currency }).format(cents / 100) : '';
return { label, buyable: label !== '' }; return { label, buyable: label !== '', freeTrial: false };
}
function storeIds(plans: CloudPlan[]): string[] {
return plans.flatMap((p) => [productIdFor(p.id, 'month'), productIdFor(p.id, 'year')]);
}
async function availableWelcomeTrial(): Promise<boolean> {
if (iap === fakeIapClient || !(await iapReady)) return false;
const list = await fetchPlans();
if (!list?.open) return false;
const products = await iap.products(storeIds(list.plans));
return Array.from(products.values()).some((product) => product.freeTrial && product.displayPrice !== '');
} }
async function loadOffer(list: CloudPlans): Promise<Offer> { async function loadOffer(list: CloudPlans): Promise<Offer> {
@@ -755,39 +821,61 @@ async function loadOffer(list: CloudPlans): Promise<Offer> {
const sandbox = list.closed && !onPlay ? await iap.isSandbox().catch(() => false) : false; const sandbox = list.closed && !onPlay ? await iap.isSandbox().catch(() => false) : false;
const soon = opensSoon({ available, closed: list.closed, sandbox, onPlay }); const soon = opensSoon({ available, closed: list.closed, sandbox, onPlay });
const canBuy = available && !soon; const canBuy = available && !soon;
if (!canBuy || iap === fakeIapClient) return { canBuy, storePrices: null, opensSoon: soon }; if (!canBuy || iap === fakeIapClient) return { canBuy, storeProducts: null, canShowTrial: false, opensSoon: soon };
const ids = list.plans.flatMap((p) => [productIdFor(p.id, 'month'), productIdFor(p.id, 'year')]); return {
return { canBuy, storePrices: await iap.prices(ids), opensSoon: soon }; canBuy,
storeProducts: await iap.products(storeIds(list.plans)),
canShowTrial: list.open === true,
opensSoon: soon,
};
} }
/** The plan the picker starts on and marks: the smallest one with AI documents, the one most trips want. */ function planFeatures(plan: CloudPlan): HTMLLIElement[] {
function recommendedPlan(plans: CloudPlan[]): CloudPlan | undefined { const row = (label: string, value: string, glyph: string, unavailable = false) =>
return plans.find((p) => p.aiDocuments > 0) ?? plans[0]; el(
} 'li',
{ className: unavailable ? 'spec off' : 'spec' },
el('i', {}, icon(glyph, 16)),
el('b', {}, label),
el('bdi', {}, value)
);
const feature = (label: string, included: boolean) =>
row(
label,
t(included ? 'native.plans.included' : 'native.plans.notIncluded'),
included ? I.check : I.cross,
!included
);
/** The kind of trip each plan is for: a weekend away, a round trip, a long journey, the whole world. */ const storage = plan.storageGb >= 1000 ? `${count(plan.storageGb / 1000)} TB` : `${count(plan.storageGb)} GB`;
const TRIPS: Record<string, { titleKey: string; textKey: string }> = { const aiDocuments = plan.aiDocumentLimit === null || (plan.aiDocumentLimit ?? plan.aiDocuments) > 0;
start: { titleKey: 'native.trip.start.title', textKey: 'native.trip.start.text' }, return [
basis: { titleKey: 'native.trip.basis.title', textKey: 'native.trip.basis.text' }, row(t('native.plans.storage'), storage, I.image),
plus: { titleKey: 'native.trip.plus.title', textKey: 'native.trip.plus.text' }, feature(t('native.plans.aiLabel'), aiDocuments),
pro: { titleKey: 'native.trip.pro.title', textKey: 'native.trip.pro.text' }, feature(t('native.plans.assistant'), plan.aiAssistant === 'included'),
}; feature(t('native.plans.mailImport'), plan.bookingMailImport === true),
/** A plan's trip, its title and one line; a plan the app does not know keeps its own name. */ row(t('native.plans.unlimitedSub'), t('native.plans.unlimited'), I.people),
function tripOf(plan: CloudPlan): { title: string; text: string } { ];
const trip = TRIPS[plan.id];
return trip ? { title: t(trip.titleKey), text: t(trip.textKey) } : { title: plan.name, text: '' };
} }
function per(interval: 'month' | 'year'): string { function per(interval: 'month' | 'year'): string {
return interval === 'year' ? t('native.plans.perYear') : t('native.plans.perMonth'); return interval === 'year' ? t('native.plans.perYear') : t('native.plans.perMonth');
} }
function trialPrice(price: string, interval: 'month' | 'year'): string {
return t('native.trial.price', { price, period: per(interval) });
}
function trialCancellation(): string {
return t(onPlay ? 'native.trial.cancelPlay' : 'native.trial.cancelApple');
}
/** The restore button of the plans on screen, which redeems a payment that cleared later. */ /** The restore button of the plans on screen, which redeems a payment that cleared later. */
let resumeRestore: (() => void) | null = null; let resumeRestore: (() => void) | null = null;
let watchingTransactions = false; let watchingTransactions = false;
/** Where the camera stood on the plan chosen last, for the screens that follow it. */ /** Where the camera stood on the plan chosen last, for the screens that follow it. */
let chosenCamera: Camera = cameraForPlan(1); let chosenCamera: Camera = cameraForPlan(1);
/** The plan chosen last, so coming back to the plans finds it still chosen. */ /** Restore a choice when returning from setup. A fresh entry opens Plus. */
let chosenPlanId: string | null = null; let chosenPlanId: string | null = null;
let chosenInterval: 'month' | 'year' = 'month'; let chosenInterval: 'month' | 'year' = 'month';
@@ -852,14 +940,11 @@ function restoreButton(plans: CloudPlan[]): HTMLButtonElement {
function showPlans(opts: { back?: boolean } = {}): void { function showPlans(opts: { back?: boolean } = {}): void {
let interval: 'month' | 'year' = chosenInterval; let interval: 'month' | 'year' = chosenInterval;
let plans: CloudPlan[] = []; let plans: CloudPlan[] = [];
let offer: Offer = { canBuy: false, storePrices: null, opensSoon: false }; let offer: Offer = { canBuy: false, storeProducts: null, canShowTrial: false, opensSoon: false };
let selectedId: string | null = null; let selectedId: string | null = null;
const tiers = el('div', { className: 'tiers', role: 'radiogroup', hidden: true }); const tiers = el('div', { className: 'tiers', role: 'radiogroup', hidden: true });
tiers.setAttribute('aria-label', t('native.plans.title')); tiers.setAttribute('aria-label', t('native.plans.title'));
const title = el('h1', {});
const text = el('p', {});
const trip = el('div', { className: 'trip' }, title, text);
const monthBtn = el('button', { type: 'button', role: 'radio' }, t('native.plans.monthly')); const monthBtn = el('button', { type: 'button', role: 'radio' }, t('native.plans.monthly'));
const yearBtn = el('button', { type: 'button', role: 'radio' }, t('native.plans.yearly')); const yearBtn = el('button', { type: 'button', role: 'radio' }, t('native.plans.yearly'));
@@ -876,18 +961,20 @@ function showPlans(opts: { back?: boolean } = {}): void {
const pricePer = el('span', {}); const pricePer = el('span', {});
const price = el('div', { className: 'price' }, priceValue, pricePer); const price = el('div', { className: 'price' }, priceValue, pricePer);
const equals = el('div', { className: 'equals' }); const equals = el('div', { className: 'equals' });
const pricebox = el('div', { className: 'pricebox' }, cycle, price, equals); const trial = el('p', { className: 'trial-price', hidden: true });
const specs = el('div', { className: 'specs' }); const pricebox = el('div', { className: 'pricebox' }, cycle, price, equals, trial);
const specs = el('ul', { className: 'specs', role: 'list' });
const foot = el('div', { className: 'pad', hidden: true }); const foot = el('div', { className: 'pad', hidden: true });
const legal = el('p', { className: 'legal' });
const loading = el('div', { className: 'loading' }, el('span', { className: 'spin' })); const loading = el('div', { className: 'loading' }, el('span', { className: 'spin' }));
const details = el('div', { className: 'stack', hidden: true }, trip, pricebox, specs); const details = el('div', { className: 'stack', hidden: true }, pricebox, specs);
const choose = el('button', { type: 'button', className: 'cta', hidden: true }); const choose = el('button', { type: 'button', className: 'cta', hidden: true });
const dock = el('div', { className: 'dock' }, choose); const dock = el('div', { className: 'dock' }, choose);
const screen = show( const screen = show(
'plain', 'plain',
chosenCamera, opts.back ? chosenCamera : cameraForPlan(1),
{ {
back: () => showWelcome({ back: true }), back: () => showWelcome({ back: true }),
content: [el('div', { className: 'pad lift' }, tiers, loading, details), foot, dock], content: [el('div', { className: 'pad lift' }, tiers, loading, details), foot, dock],
@@ -934,20 +1021,11 @@ function showPlans(opts: { back?: boolean } = {}): void {
yearBtn.setAttribute('aria-checked', String(interval === 'year')); yearBtn.setAttribute('aria-checked', String(interval === 'year'));
cycle.dataset.year = String(interval === 'year'); cycle.dataset.year = String(interval === 'year');
const { title: tripTitle, text: tripText } = tripOf(plan); const { label, buyable, freeTrial } = interval === 'month' ? month : year;
const recommended = recommendedPlan(plans)?.id === plan.id; // An introductory offer states the free period and renewal price together.
title.replaceChildren( price.hidden = !label || freeTrial;
tripTitle,
...(recommended ? [el('span', { className: 'badge' }, t('native.plans.recommended'))] : [])
);
text.textContent = tripText;
text.hidden = !tripText;
const { label, buyable } = interval === 'month' ? month : year;
// No price yet (orders not open): the plan shows without one rather than with an empty one.
price.hidden = !label;
pricePer.textContent = per(interval); pricePer.textContent = per(interval);
if (label) paintPrice(label, animate); if (label && !freeTrial) paintPrice(label, animate);
// Without a price in either period (orders not open yet) the switch would choose between nothing. // Without a price in either period (orders not open yet) the switch would choose between nothing.
pricebox.hidden = !month.label && !year.label; pricebox.hidden = !month.label && !year.label;
@@ -955,59 +1033,23 @@ function showPlans(opts: { back?: boolean } = {}): void {
yearBtn.disabled = !year.label; yearBtn.disabled = !year.label;
const yearAmount = amountIn(year.label); const yearAmount = amountIn(year.label);
equals.textContent = equals.textContent =
!label || !year.label !label || !year.label || freeTrial
? '' ? ''
: interval === 'month' : interval === 'month'
? t('native.plans.yearlyIs', { price: year.label }) ? t('native.plans.yearlyIs', { price: year.label })
: yearAmount : yearAmount
? t('native.plans.monthlyIs', { price: yearAmount.render(yearAmount.value / 12) }) ? t('native.plans.monthlyIs', { price: yearAmount.render(yearAmount.value / 12) })
: ''; : '';
trial.hidden = !freeTrial;
trial.textContent = freeTrial ? trialPrice(label, interval) : '';
legal.textContent = freeTrial
? trialCancellation()
: t(onPlay ? 'native.plans.legalAndroid' : 'native.plans.legal');
const gb = plan.storageGb >= 1000 ? `${count(plan.storageGb / 1000)} TB` : `${count(plan.storageGb)} GB`; specs.replaceChildren(...planFeatures(plan));
const notIncluded = t('native.plans.aiNone');
const included = t('native.plans.included');
const assistant = plan.aiAssistant === 'included';
const tile = (glyph: string, big: string, small: string, off = false) =>
el(
'span',
{ className: off ? 'spec off' : 'spec' },
el('i', {}, icon(glyph, 17)),
el('span', {}, el('b', {}, big), el('small', {}, small))
);
specs.replaceChildren(
tile(I.image, gb, t('native.plans.storageFairUse')),
plan.aiDocuments > 0
? tile(
I.spark,
plan.aiDocumentLimit === null
? t('native.plans.unlimited')
: t('native.plans.aiPerMonth', { n: count(plan.aiDocuments) }),
t('native.plans.aiLabel')
)
: tile(I.spark, notIncluded, t('native.plans.aiLabel'), true),
tile(
I.spark,
assistant ? included : plan.aiAssistant === 'planned' ? t('native.plans.planned') : notIncluded,
t('native.plans.assistant'),
!assistant
),
tile(
I.mail,
plan.bookingMailImport ? included : notIncluded,
t('native.plans.mailImport'),
!plan.bookingMailImport
),
el(
'span',
{ className: 'spec wide' },
el('i', {}, icon(I.people, 17)),
el('span', {}, el('b', {}, t('native.plans.unlimited')), el('small', {}, t('native.plans.unlimitedSub'))),
el('em', {}, t('native.plans.inEveryPlan'))
)
);
choose.hidden = !buyable; choose.hidden = !buyable;
choose.textContent = t('native.plans.choose', { trip: tripTitle }); choose.textContent = t('native.plans.choose', { plan: plan.name });
chosenCamera = cameraForPlan(index); chosenCamera = cameraForPlan(index);
chosenPlanId = plan.id; chosenPlanId = plan.id;
chosenInterval = interval; chosenInterval = interval;
@@ -1042,7 +1084,7 @@ function showPlans(opts: { back?: boolean } = {}): void {
showSubscribed(); showSubscribed();
return; return;
} }
showClaim(plan, selectedInterval, price.label); showClaim(plan, selectedInterval, price.label, { freeTrial: price.freeTrial });
}); });
const load = async () => { const load = async () => {
@@ -1060,7 +1102,9 @@ function showPlans(opts: { back?: boolean } = {}): void {
} }
offer = await loadOffer(list); offer = await loadOffer(list);
plans = list.plans; plans = list.plans;
selectedId = plans.find((p) => p.id === chosenPlanId)?.id ?? recommendedPlan(plans)?.id ?? null; const previousId = opts.back ? chosenPlanId : null;
selectedId =
plans.find((p) => p.id === previousId)?.id ?? plans.find((p) => p.id === 'plus')?.id ?? plans[0]?.id ?? null;
tiers.replaceChildren( tiers.replaceChildren(
...plans.map((p) => { ...plans.map((p) => {
const b = el('button', { type: 'button', role: 'radio', dataset: { plan: p.id } }, p.name); const b = el('button', { type: 'button', role: 'radio', dataset: { plan: p.id } }, p.name);
@@ -1083,7 +1127,7 @@ function showPlans(opts: { back?: boolean } = {}): void {
); );
} else { } else {
foot.replaceChildren( foot.replaceChildren(
el('p', { className: 'legal' }, t(onPlay ? 'native.plans.legalAndroid' : 'native.plans.legal')), legal,
el( el(
'div', 'div',
{ className: 'legal-links' }, { className: 'legal-links' },
@@ -1105,7 +1149,7 @@ type SlugStatus = 'available' | 'taken' | 'invalid' | 'reserved' | 'error';
async function slugStatus(slug: string): Promise<SlugStatus> { async function slugStatus(slug: string): Promise<SlugStatus> {
try { try {
const res = await get(`${CLOUD_URL}/api/slug/check?slug=${encodeURIComponent(slug)}`); const res = await cloudGet(`${CLOUD_URL}/api/slug/check?slug=${encodeURIComponent(slug)}`);
const data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data; const data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data;
const status = (data as { status?: string })?.status; const status = (data as { status?: string })?.status;
if (status === 'available' || status === 'taken' || status === 'invalid' || status === 'reserved') return status; if (status === 'available' || status === 'taken' || status === 'invalid' || status === 'reserved') return status;
@@ -1120,21 +1164,17 @@ async function slugStatus(slug: string): Promise<SlugStatus> {
* (terms § 2 (1a), § 327h BGB), as the control plane words and versions it. The * (terms § 2 (1a), § 327h BGB), as the control plane words and versions it. The
* app shows the server's text, never its own, and sends back the version it showed. * app shows the server's text, never its own, and sends back the version it showed.
*/ */
interface DeviationsConsent { async function fetchConsent(): Promise<CloudPurchaseAgreement | null> {
version: string;
text: string;
}
async function fetchConsent(): Promise<DeviationsConsent | null> {
try { try {
const res = await CapacitorHttp.get({ const res = await CapacitorHttp.get({
url: `${CLOUD_URL}/api/iap/consent`, url: `${CLOUD_URL}/api/iap/consent`,
params: { lang: locale === 'de' ? 'de' : 'en' }, params: { lang: locale === 'de' ? 'de' : 'en' },
connectTimeout: PROBE_TIMEOUT_MS, ...cloudHttpOptions,
readTimeout: PROBE_TIMEOUT_MS,
}); });
const data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data; const data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data;
const body = (data ?? {}) as { version?: unknown; deviations?: unknown }; const body = (data ?? {}) as { version?: unknown; deviations?: unknown; iapEnvironment?: unknown };
if (res.status !== 200 || typeof body.version !== 'string' || typeof body.deviations !== 'string') return null; if (res.status !== 200 || typeof body.version !== 'string' || typeof body.deviations !== 'string') return null;
if (cloudSandbox && body.iapEnvironment !== 'sandbox') return null;
if (!body.version || !body.deviations) return null; if (!body.version || !body.deviations) return null;
return { version: body.version, text: body.deviations }; return { version: body.version, text: body.deviations };
} catch { } catch {
@@ -1162,8 +1202,7 @@ async function redeemPurchase(
const res = await CapacitorHttp.post({ const res = await CapacitorHttp.post({
url: `${CLOUD_URL}/api/iap/redeem`, url: `${CLOUD_URL}/api/iap/redeem`,
headers: { 'content-type': 'application/json' }, headers: { 'content-type': 'application/json' },
connectTimeout: PROBE_TIMEOUT_MS, ...cloudHttpOptions,
readTimeout: PROBE_TIMEOUT_MS,
// The language of the contract confirmation mail. // The language of the contract confirmation mail.
data: { data: {
platform: purchase.platform, platform: purchase.platform,
@@ -1181,6 +1220,9 @@ async function redeemPurchase(
const data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data; const data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data;
const body = (data ?? {}) as { instanceUrl?: string; code?: string; welcome?: string }; const body = (data ?? {}) as { instanceUrl?: string; code?: string; welcome?: string };
if ((res.status === 200 || res.status === 201) && typeof body.instanceUrl === 'string') { if ((res.status === 200 || res.status === 201) && typeof body.instanceUrl === 'string') {
if (cloudSandbox && !isCloudSandboxTenant(body.instanceUrl, cloudSandbox)) {
return { ok: false, code: 'redeem-failed' };
}
const welcome = const welcome =
typeof body.welcome === 'string' && /^[A-Za-z0-9_-]{43}$/.test(body.welcome) ? body.welcome : undefined; typeof body.welcome === 'string' && /^[A-Za-z0-9_-]{43}$/.test(body.welcome) ? body.welcome : undefined;
return { ok: true, instanceUrl: body.instanceUrl, ...(welcome ? { welcome } : {}) }; return { ok: true, instanceUrl: body.instanceUrl, ...(welcome ? { welcome } : {}) };
@@ -1195,7 +1237,7 @@ function showClaim(
plan: Pick<CloudPlan, 'id' | 'name'>, plan: Pick<CloudPlan, 'id' | 'name'>,
interval: 'month' | 'year', interval: 'month' | 'year',
priceLabel: string, priceLabel: string,
opts: { back?: boolean; bought?: Purchase } = {} opts: { back?: boolean; bought?: Purchase; freeTrial?: boolean } = {}
): void { ): void {
/** A purchase that went through but whose redeem did not: a retry redeems it again instead of buying twice. */ /** A purchase that went through but whose redeem did not: a retry redeems it again instead of buying twice. */
let bought: Purchase | null = opts.bought ?? null; let bought: Purchase | null = opts.bought ?? null;
@@ -1279,7 +1321,7 @@ function showClaim(
}; };
// The § 327h agreement, asked on its own before anything is bought. // The § 327h agreement, asked on its own before anything is bought.
let consent: DeviationsConsent | null = null; let consent: CloudPurchaseAgreement | null = null;
const consentBox = el('input', { type: 'checkbox' }); const consentBox = el('input', { type: 'checkbox' });
const consentText = el('span', { className: 'consent-text' }, t('native.claim.consentLoading')); const consentText = el('span', { className: 'consent-text' }, t('native.claim.consentLoading'));
const consentField = el( const consentField = el(
@@ -1288,19 +1330,26 @@ function showClaim(
consentBox, consentBox,
el('span', {}, el('strong', {}, t('native.claim.consentTitle')), consentText) el('span', {}, el('strong', {}, t('native.claim.consentTitle')), consentText)
); );
const loadConsent = async (): Promise<DeviationsConsent | null> => { const showConsent = (current: CloudPurchaseAgreement | null): void => {
consent = current;
consentBox.checked = false; consentBox.checked = false;
consentBox.disabled = true;
consentText.textContent = t('native.claim.consentLoading');
consent = await fetchConsent();
consentBox.disabled = consent === null; consentBox.disabled = consent === null;
consentText.textContent = consent ? consent.text : t('native.claim.consentUnavailable'); consentText.textContent = consent ? consent.text : t('native.claim.consentUnavailable');
};
const loadConsent = async (): Promise<CloudPurchaseAgreement | null> => {
consentBox.disabled = true;
consentText.textContent = t('native.claim.consentLoading');
showConsent(await fetchConsent());
return consent; return consent;
}; };
void loadConsent(); void loadConsent();
const subscribeLabel = () => const subscribeLabel = () =>
bought ? t('native.claim.completeSetup') : t('native.claim.subscribe', { price: priceLabel }); bought
? t('native.claim.completeSetup')
: opts.freeTrial
? t('native.trial.badge')
: t('native.claim.subscribe', { price: priceLabel });
const submit = el('button', { type: 'button', className: 'cta' }, subscribeLabel()); const submit = el('button', { type: 'button', className: 'cta' }, subscribeLabel());
// What is about to be bought, so nobody pays for a plan they did not mean. // What is about to be bought, so nobody pays for a plan they did not mean.
const change = el('button', { type: 'button' }, t('native.claim.change')); const change = el('button', { type: 'button' }, t('native.claim.change'));
@@ -1308,19 +1357,25 @@ function showClaim(
void tap(); void tap();
showPlans({ back: true }); showPlans({ back: true });
}); });
const planPrice = !priceLabel
? null
: opts.freeTrial
? el('small', {}, trialPrice(priceLabel, interval))
: el('small', { dir: 'ltr' }, `${priceLabel} ${per(interval)}`);
const planRow = el( const planRow = el(
'div', 'div',
{ className: 'plan-row' }, { className: 'plan-row' },
el( el('span', {}, el('b', {}, plan.name), ...(planPrice ? [planPrice] : [])),
'span',
{},
el('b', {}, plan.name),
...(priceLabel ? [el('small', { dir: 'ltr' }, `${priceLabel} ${per(interval)}`)] : [])
),
// A purchase already made is not a choice any more. // A purchase already made is not a choice any more.
...(bought ? [] : [change]) ...(bought ? [] : [change])
); );
const error = notice(''); const error = notice('');
const checkoutDock = el(
'div',
{ className: 'dock' },
submit,
el('p', { className: 'fine' }, opts.freeTrial ? trialCancellation() : t('native.claim.renews'))
);
const form = el( const form = el(
'form', 'form',
{ className: 'pad form', noValidate: true }, { className: 'pad form', noValidate: true },
@@ -1347,10 +1402,7 @@ function showClaim(
{ {
back: () => showPlans({ back: true }), back: () => showPlans({ back: true }),
overlay: [card.node], overlay: [card.node],
content: [ content: [form, checkoutDock],
form,
el('div', { className: 'dock' }, submit, el('p', { className: 'fine' }, t('native.claim.renews'))),
],
}, },
opts opts
); );
@@ -1440,7 +1492,8 @@ function showClaim(
consentBox.focus(); consentBox.focus();
return; return;
} }
const consentVersion = consent ? consent.version : null; const acceptedConsent = consent;
const consentVersion = acceptedConsent?.version ?? null;
void tap(ImpactStyle.Medium); void tap(ImpactStyle.Medium);
// The purchase sheet and the progress want the whole screen, not the keyboard. // The purchase sheet and the progress want the whole screen, not the keyboard.
@@ -1460,7 +1513,24 @@ function showClaim(
}; };
if (!bought) { if (!bought) {
const outcome = await iap.purchase(productIdFor(plan.id, interval)); const currentConsent = await fetchConsent();
if (!form.isConnected) return;
if (!matchesPurchaseAgreement(acceptedConsent, currentConsent)) {
restore();
showConsent(currentConsent);
setNotice(error, t(currentConsent ? 'native.claim.consentRequired' : 'native.claim.consentUnavailable'));
if (currentConsent) consentBox.focus();
return;
}
const trialRenewalPrice = opts.freeTrial ? priceLabel : undefined;
const outcome = await iap.purchase(productIdFor(plan.id, interval), trialRenewalPrice);
if (outcome.kind === 'offer-changed') {
restore();
planPrice?.remove();
checkoutDock.hidden = true;
setNotice(error, t('native.trial.changed'));
return;
}
if (outcome.kind === 'cancelled') { if (outcome.kind === 'cancelled') {
restore(); restore();
setNotice(error, t('native.claim.cancelled')); setNotice(error, t('native.claim.cancelled'));
@@ -1650,8 +1720,8 @@ function showProvisioning(instanceUrl: string, welcome?: string): void {
const deadline = Date.now() + 180_000; const deadline = Date.now() + 180_000;
const poll = async (): Promise<void> => { const poll = async (): Promise<void> => {
if (!view.screen.node.isConnected) return; if (!view.screen.node.isConnected) return;
const result = await probeServer(instanceUrl, get); const result = await probeServer(instanceUrl, cloudGet);
if (result.ok) { if (result.ok && (!cloudSandbox || new URL(result.url).origin === new URL(instanceUrl).origin)) {
await ready(result.url); await ready(result.url);
return; return;
} }
+69 -75
View File
@@ -320,14 +320,14 @@ input {
overflow: hidden; overflow: hidden;
background: var(--sea); background: var(--sea);
margin-bottom: -1px; margin-bottom: -1px;
height: min(300px, 36svh); height: max(calc(var(--safe-top) + 68px), min(252px, 30svh));
} }
.hero.tall { .hero.tall {
height: min(320px, 38svh); height: min(320px, 38svh);
} }
.hero.welcome { .hero.welcome {
height: min(376px, 44.5svh); height: min(352px, 42svh);
min-height: 250px; min-height: 236px;
} }
.hero .scenery { .hero .scenery {
position: absolute; position: absolute;
@@ -529,7 +529,7 @@ input {
} }
.push { .push {
flex: 1; flex: 1;
min-height: 0; min-height: clamp(10px, 2svh, 16px);
} }
h1 { h1 {
margin: 0; margin: 0;
@@ -628,6 +628,39 @@ h1 {
font: 700 17px var(--text-face); font: 700 17px var(--text-face);
box-shadow: 0 14px 28px -14px rgba(17, 24, 39, 0.55); box-shadow: 0 14px 28px -14px rgba(17, 24, 39, 0.55);
} }
.discover {
position: relative;
padding-inline: 16px;
}
.trial-badge,
.trial-price {
border: 1px solid #bee3d7;
background: #e7f6ef;
color: #195247;
}
.trial-badge {
position: absolute;
inset-block-start: 0;
inset-inline: 0;
inline-size: max-content;
max-inline-size: calc(100% - 20px);
margin-inline: auto;
padding: 3px 8px;
border-radius: 999px;
box-shadow: 0 2px 6px #11182720;
font: 700 11px/1.4 var(--text-face);
transform: translateY(calc(-100% + 6px));
}
.trial-price {
margin: 8px 6px 0;
padding: 10px 6px;
border-radius: 12px;
text-align: center;
font-size: 13px;
font-weight: 700;
line-height: 1.4;
overflow-wrap: anywhere;
}
.cta2 { .cta2 {
min-height: 52px; min-height: 52px;
background: #fff; background: #fff;
@@ -715,33 +748,6 @@ h1 {
color: var(--ink); color: var(--ink);
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12); box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12);
} }
.trip {
min-width: 0;
margin-top: 10px;
}
.trip h1 {
font-size: 28px;
display: flex;
align-items: center;
gap: 10px;
white-space: nowrap;
}
.trip p {
margin: 6px 0 0;
color: var(--text);
font-size: 14px;
line-height: 1.4;
}
.badge {
font-family: var(--text-face);
font-size: 11px;
font-weight: 700;
letter-spacing: 0.04em;
padding: 4px 10px;
border-radius: 999px;
background: var(--dark);
color: #fff;
}
.pricebox { .pricebox {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
@@ -823,64 +829,52 @@ h1 {
display: none; display: none;
} }
.specs { .specs {
display: grid; margin: 0;
grid-template-columns: repeat(2, minmax(0, 1fr)); padding: 0 12px;
gap: 8px; list-style: none;
} border-radius: 16px;
.spec {
display: flex;
align-items: center;
gap: 10px;
min-width: 0;
padding: 10px 12px;
border-radius: 14px;
background: #fff; background: #fff;
box-shadow: 0 0 0 1px var(--line); box-shadow: 0 0 0 1px var(--line);
} }
.spec {
display: grid;
grid-template-columns: 28px minmax(0, 1.6fr) minmax(0, 1fr);
align-items: center;
gap: 8px;
min-height: 44px;
padding-block: 8px;
overflow-wrap: anywhere;
}
.spec + .spec {
border-block-start: 1px solid var(--line-soft);
}
.spec i { .spec i {
width: 32px; width: 28px;
height: 32px; height: 28px;
flex: none; border-radius: 8px;
border-radius: 10px;
display: grid; display: grid;
place-items: center; place-items: center;
background: var(--sand); background: var(--sand);
color: var(--dark); color: var(--dark);
} }
.spec b { .spec b {
display: block;
font-size: 14px; font-size: 14px;
font-weight: 800; font-weight: 700;
line-height: 1.2; line-height: 1.35;
white-space: nowrap;
} }
.spec small { .spec bdi {
display: block; justify-self: end;
font-size: 11.5px; text-align: end;
color: var(--muted); font-size: 13px;
font-weight: 600; font-weight: 700;
line-height: 1.25; line-height: 1.35;
white-space: nowrap; }
.spec.off {
color: #626672;
} }
.spec.off i { .spec.off i {
color: var(--faint); background: #f0f1f3;
} color: inherit;
.spec.off b {
color: var(--muted);
}
.spec.wide {
grid-column: 1 / -1;
}
.spec.wide em {
margin-inline-start: auto;
font-style: normal;
font-size: 11.5px;
font-weight: 700;
color: var(--text);
background: var(--sand);
padding: 4px 9px;
border-radius: 999px;
white-space: nowrap;
} }
.legal { .legal {
margin: 2px 0 0; margin: 2px 0 0;
+15 -14
View File
@@ -55,13 +55,13 @@
"dependencies": { "dependencies": {
"@assistant-ui/react": "0.15.38", "@assistant-ui/react": "0.15.38",
"@capacitor/action-sheet": "^8.1.1", "@capacitor/action-sheet": "^8.1.1",
"@capacitor/android": "^8.6.2", "@capacitor/android": "^8.6.3",
"@capacitor/app": "^8.1.1", "@capacitor/app": "^8.1.1",
"@capacitor/core": "^8.6.2", "@capacitor/core": "^8.6.3",
"@capacitor/dialog": "^8.0.1", "@capacitor/dialog": "^8.0.1",
"@capacitor/filesystem": "^8.1.3", "@capacitor/filesystem": "^8.1.6",
"@capacitor/haptics": "^8.0.2", "@capacitor/haptics": "^8.0.2",
"@capacitor/ios": "^8.6.2", "@capacitor/ios": "^8.6.3",
"@capacitor/keyboard": "^8.0.5", "@capacitor/keyboard": "^8.0.5",
"@capacitor/share": "^8.0.1", "@capacitor/share": "^8.0.1",
"@capacitor/splash-screen": "^8.0.2", "@capacitor/splash-screen": "^8.0.2",
@@ -101,6 +101,7 @@
"@fontsource/satisfy": "^5.3.0", "@fontsource/satisfy": "^5.3.0",
"@fontsource/shrikhand": "^5.3.0", "@fontsource/shrikhand": "^5.3.0",
"@fontsource/yellowtail": "^5.3.0", "@fontsource/yellowtail": "^5.3.0",
"@lucide/icons": "1.82.0",
"@maplibre/maplibre-gl-leaflet": "0.1.4", "@maplibre/maplibre-gl-leaflet": "0.1.4",
"@noble/hashes": "^2.4.0", "@noble/hashes": "^2.4.0",
"@simplewebauthn/browser": "^14.0.0", "@simplewebauthn/browser": "^14.0.0",
@@ -112,9 +113,9 @@
"heic-to": "^1.6.7", "heic-to": "^1.6.7",
"iso-3166-2": "^1.0.0", "iso-3166-2": "^1.0.0",
"leaflet": "^1.9.4", "leaflet": "^1.9.4",
"lucide-react": "^0.577.0", "lucide-react": "^1.82.0",
"mapbox-gl": "3.32.0", "mapbox-gl": "3.32.0",
"maplibre-gl": "6.19.0", "maplibre-gl": "6.20.0",
"modern-screenshot": "4.7.0", "modern-screenshot": "4.7.0",
"plyr": "^3.8.5", "plyr": "^3.8.5",
"react": "^19.3.1", "react": "^19.3.1",
@@ -123,7 +124,7 @@
"react-leaflet": "^5.0.0", "react-leaflet": "^5.0.0",
"react-leaflet-cluster": "^4.1.3", "react-leaflet-cluster": "^4.1.3",
"react-markdown": "^10.1.0", "react-markdown": "^10.1.0",
"react-router": "^7.18.4", "react-router": "^8.5.3",
"rehype-sanitize": "^6.0.0", "rehype-sanitize": "^6.0.0",
"remark-breaks": "^4.0.0", "remark-breaks": "^4.0.0",
"remark-gfm": "^4.0.1", "remark-gfm": "^4.0.1",
@@ -133,12 +134,12 @@
"zustand": "^5.0.15" "zustand": "^5.0.15"
}, },
"devDependencies": { "devDependencies": {
"@capacitor/cli": "^8.6.2", "@capacitor/cli": "^8.6.3",
"@eslint/js": "^10.0.1", "@eslint/js": "^10.0.1",
"@jscpd/core": "^4.2.5", "@jscpd/core": "^4.2.5",
"@jscpd/tokenizer": "^4.2.6", "@jscpd/tokenizer": "^4.2.6",
"@playwright/test": "^1.65.1", "@playwright/test": "^1.65.1",
"@testing-library/dom": "^10.4.1", "@testing-library/dom": "^10.4.2",
"@testing-library/jest-dom": "^8.0.0", "@testing-library/jest-dom": "^8.0.0",
"@testing-library/react": "^16.3.3", "@testing-library/react": "^16.3.3",
"@testing-library/user-event": "^14.6.13", "@testing-library/user-event": "^14.6.13",
@@ -146,22 +147,22 @@
"@types/geojson": "^7946.0.16", "@types/geojson": "^7946.0.16",
"@types/leaflet": "^1.9.23", "@types/leaflet": "^1.9.23",
"@types/node": "^26.6.11", "@types/node": "^26.6.11",
"@types/react": "^19.3.2", "@types/react": "^19.3.3",
"@types/react-dom": "^19.3.0", "@types/react-dom": "^19.3.0",
"@types/topojson-client": "^3.1.5", "@types/topojson-client": "^3.1.5",
"@types/topojson-specification": "^1.0.5", "@types/topojson-specification": "^1.0.5",
"@vitejs/plugin-react": "^6.2.1", "@vitejs/plugin-react": "^6.2.1",
"@vitest/coverage-v8": "^5.1.2", "@vitest/coverage-v8": "^5.1.2",
"autoprefixer": "^10.7.0", "autoprefixer": "^10.7.1",
"eslint": "^10.11.0", "eslint": "^10.11.0",
"eslint-config-flat-gitignore": "^2.4.0", "eslint-config-flat-gitignore": "^2.4.0",
"eslint-config-prettier": "^10.1.8", "eslint-config-prettier": "^10.1.9",
"eslint-plugin-react-hooks": "^7.1.1", "eslint-plugin-react-hooks": "^7.1.1",
"eslint-plugin-react-refresh": "^0.5.8", "eslint-plugin-react-refresh": "^0.5.8",
"fake-indexeddb": "^6.2.7", "fake-indexeddb": "^6.2.7",
"jsdom": "^29.1.1", "jsdom": "^29.1.1",
"msw": "^3.0.8", "msw": "^3.0.8",
"postcss": "^8.5.33", "postcss": "^8.5.34",
"prettier": "^3.10.1", "prettier": "^3.10.1",
"prettier-plugin-organize-imports": "^4.3.0", "prettier-plugin-organize-imports": "^4.3.0",
"prettier-plugin-tailwindcss": "^0.8.1", "prettier-plugin-tailwindcss": "^0.8.1",
@@ -170,7 +171,7 @@
"tailwindcss": "^3.4.19", "tailwindcss": "^3.4.19",
"typescript": "^6.0.3", "typescript": "^6.0.3",
"typescript-eslint": "^8.74.0", "typescript-eslint": "^8.74.0",
"vite": "8.3.8", "vite": "8.4.0",
"vite-plugin-pwa": "^2.0.0", "vite-plugin-pwa": "^2.0.0",
"vitest": "^5.1.2" "vitest": "^5.1.2"
} }
+11 -11
View File
@@ -1,21 +1,21 @@
{ {
"src": { "src": {
"@typescript-eslint/no-non-null-assertion": 345, "@typescript-eslint/no-non-null-assertion": 338,
"@typescript-eslint/no-misused-promises": 810, "@typescript-eslint/no-misused-promises": 750,
"no-console": 85, "no-console": 81,
"complexity": 214, "complexity": 213,
"@typescript-eslint/no-explicit-any": 113, "@typescript-eslint/no-explicit-any": 113,
"trek/no-swallowed-catch": 124, "trek/no-swallowed-catch": 124,
"max-params": 31, "max-params": 31,
"trek/store-without-selector": 65, "trek/store-without-selector": 64,
"react-hooks/refs": 385, "react-hooks/refs": 380,
"react-hooks/set-state-in-effect": 188, "react-hooks/set-state-in-effect": 188,
"@typescript-eslint/no-floating-promises": 162, "@typescript-eslint/no-floating-promises": 156,
"react-hooks/exhaustive-deps": 112, "react-hooks/exhaustive-deps": 112,
"@typescript-eslint/no-unused-vars": 95, "@typescript-eslint/no-unused-vars": 92,
"react-hooks/immutability": 26, "react-hooks/immutability": 26,
"max-lines-per-function": 126, "max-lines-per-function": 125,
"react-hooks/static-components": 38, "react-hooks/static-components": 34,
"react-hooks/preserve-manual-memoization": 12, "react-hooks/preserve-manual-memoization": 12,
"no-useless-assignment": 7, "no-useless-assignment": 7,
"no-empty": 18, "no-empty": 18,
@@ -35,7 +35,7 @@
}, },
"tests": { "tests": {
"@typescript-eslint/no-explicit-any": 484, "@typescript-eslint/no-explicit-any": 484,
"@typescript-eslint/no-non-null-assertion": 1848, "@typescript-eslint/no-non-null-assertion": 1844,
"@typescript-eslint/no-misused-promises": 22, "@typescript-eslint/no-misused-promises": 22,
"@typescript-eslint/no-unused-vars": 48, "@typescript-eslint/no-unused-vars": 48,
"@typescript-eslint/no-floating-promises": 33, "@typescript-eslint/no-floating-promises": 33,
+48 -21
View File
@@ -227,7 +227,11 @@
"src/pages/sharedTrip/SharedBookingsView.tsx", "src/pages/sharedTrip/SharedBookingsView.tsx",
"src/pages/sharedTrip/SharedDayCard.tsx" "src/pages/sharedTrip/SharedDayCard.tsx"
], ],
"mobile": ["src/mobile/screens/trip/tabs/MBookingsTab.tsx", "src/mobile/screens/trip/tabs/MTransportsTab.tsx"] "mobile": [
"src/mobile/screens/trip/tabs/MBookingsTab.tsx",
"src/mobile/screens/trip/tabs/MTransportsTab.tsx",
"src/mobile/screens/trip/MItineraryBookingCard.tsx"
]
}, },
{ {
"feature": "Bottom nav context-aware create action", "feature": "Bottom nav context-aware create action",
@@ -267,6 +271,12 @@
"desktop": ["src/components/Collab/useCollabChat.ts"], "desktop": ["src/components/Collab/useCollabChat.ts"],
"mobile": ["src/mobile/screens/trip/tabs/MCollabChat.tsx"] "mobile": ["src/mobile/screens/trip/tabs/MCollabChat.tsx"]
}, },
{
"feature": "Collab links",
"hooks": ["src/components/Collab/useCollabLinks.ts"],
"desktop": ["src/components/Collab/CollabLinks.tsx"],
"mobile": ["src/mobile/screens/trip/tabs/MCollabLinks.tsx"]
},
{ {
"feature": "Collab notes", "feature": "Collab notes",
"hooks": ["src/components/Collab/useCollabNotesData.ts"], "hooks": ["src/components/Collab/useCollabNotesData.ts"],
@@ -398,7 +408,7 @@
"src/mobile/screens/collections/MCollEditSheet.tsx", "src/mobile/screens/collections/MCollEditSheet.tsx",
"src/mobile/screens/collections/MCollPlaceRow.tsx", "src/mobile/screens/collections/MCollPlaceRow.tsx",
"src/mobile/screens/collections/MCollPlaceSheet.tsx", "src/mobile/screens/collections/MCollPlaceSheet.tsx",
"src/mobile/screens/collections/MCollections.tsx" "src/mobile/screens/collections/MCollSavedFilters.tsx"
] ]
}, },
{ {
@@ -438,7 +448,7 @@
"feature": "Costs/budget splitting or totals only: useCostsMode", "feature": "Costs/budget splitting or totals only: useCostsMode",
"hooks": ["src/components/Budget/useCostsMode.ts"], "hooks": ["src/components/Budget/useCostsMode.ts"],
"desktop": ["src/components/Budget/CostsModeCard.tsx"], "desktop": ["src/components/Budget/CostsModeCard.tsx"],
"mobile": ["src/mobile/screens/trip/tabs/MCostsTab.tsx"] "mobile": ["src/mobile/screens/trip/sheets/MTripSettingsSheet.tsx"]
}, },
{ {
"feature": "Costs/budget settle-up payment: useSettlementForm", "feature": "Costs/budget settle-up payment: useSettlementForm",
@@ -600,10 +610,8 @@
"src/pages/journeyPublic/useJourneyPublic.ts" "src/pages/journeyPublic/useJourneyPublic.ts"
], ],
"mobile": [ "mobile": [
"src/mobile/screens/journey/MJourneyCreateSheet.tsx",
"src/mobile/screens/journey/MJourneyDetail.tsx", "src/mobile/screens/journey/MJourneyDetail.tsx",
"src/mobile/screens/journey/MJourneyEntrySheet.tsx", "src/mobile/screens/journey/MJourneyEntrySheet.tsx",
"src/mobile/screens/journey/MJourneySettingsSheet.tsx",
"src/mobile/screens/journey/mobileJourneyMeta.ts" "src/mobile/screens/journey/mobileJourneyMeta.ts"
] ]
}, },
@@ -776,7 +784,7 @@
{ {
"feature": "Place add/edit form and maps search: usePlaceForm", "feature": "Place add/edit form and maps search: usePlaceForm",
"hooks": ["src/components/Planner/usePlaceForm.ts"], "hooks": ["src/components/Planner/usePlaceForm.ts"],
"desktop": ["src/components/Planner/PlaceFormModal.tsx"], "desktop": ["src/components/Planner/usePlaceFormModal.ts"],
"mobile": [ "mobile": [
"src/mobile/screens/trip/sheets/MPlaceEditSheet.tsx", "src/mobile/screens/trip/sheets/MPlaceEditSheet.tsx",
"src/mobile/screens/trip/sheets/PlCategoryPicker.tsx" "src/mobile/screens/trip/sheets/PlCategoryPicker.tsx"
@@ -785,13 +793,13 @@
{ {
"feature": "Place add/edit form and maps search: usePlaceSearch", "feature": "Place add/edit form and maps search: usePlaceSearch",
"hooks": ["src/components/Planner/usePlaceSearch.ts"], "hooks": ["src/components/Planner/usePlaceSearch.ts"],
"desktop": ["src/components/Planner/PlaceFormModal.tsx"], "desktop": ["src/components/Planner/usePlaceFormModal.ts"],
"mobile": ["src/mobile/screens/trip/sheets/PlPlaceSearch.tsx"] "mobile": ["src/mobile/screens/trip/sheets/PlPlaceSearch.tsx"]
}, },
{ {
"feature": "Place add/edit form: tags", "feature": "Place add/edit form: tags",
"hooks": ["src/components/Planner/usePlaceTags.ts"], "hooks": ["src/components/Planner/usePlaceTags.ts"],
"desktop": ["src/components/Planner/PlaceFormModal.tsx"], "desktop": ["src/components/Planner/usePlaceFormModal.ts"],
"mobile": ["src/mobile/screens/trip/sheets/MPlaceEditSheet.tsx"] "mobile": ["src/mobile/screens/trip/sheets/MPlaceEditSheet.tsx"]
}, },
{ {
@@ -864,12 +872,6 @@
"desktop": ["src/components/Roadtrip/RoadtripStopPopup.tsx"], "desktop": ["src/components/Roadtrip/RoadtripStopPopup.tsx"],
"mobile": ["src/mobile/screens/trip/roadtrip/MRtDraftSheet.tsx"] "mobile": ["src/mobile/screens/trip/roadtrip/MRtDraftSheet.tsx"]
}, },
{
"feature": "Road-trip Google Maps route import",
"hooks": ["src/components/Roadtrip/useGoogleRouteImport.ts"],
"desktop": ["src/components/Roadtrip/GoogleRouteImport.tsx"],
"mobile": ["src/mobile/screens/trip/roadtrip/MRtRouteImportSheet.tsx"]
},
{ {
"feature": "Road-trip stay length draft", "feature": "Road-trip stay length draft",
"hooks": ["src/components/Roadtrip/useStayDraft.ts"], "hooks": ["src/components/Roadtrip/useStayDraft.ts"],
@@ -1059,11 +1061,13 @@
"src/components/Planner/ReservationsPanel.tsx", "src/components/Planner/ReservationsPanel.tsx",
"src/components/Planner/bookings/BookingDetailHost.tsx" "src/components/Planner/bookings/BookingDetailHost.tsx"
], ],
"mobile": [ "mobile": ["src/mobile/screens/trip/sheets/MTransportSheet.tsx"]
"src/mobile/screens/trip/sheets/MTransportSheet.tsx", },
"src/mobile/screens/trip/tabs/MBookingsTab.tsx", {
"src/mobile/screens/trip/tabs/MTransportsTab.tsx" "feature": "Transit itinerary facts and note formatting",
] "hooks": ["src/components/Planner/transitJourneyModel.ts"],
"desktop": ["src/components/Planner/TransitJourneyModal.tsx"],
"mobile": ["src/mobile/screens/trip/sheets/MTransitJourneySheet.tsx"]
}, },
{ {
"feature": "Transport booking detail view: transportDetailModel", "feature": "Transport booking detail view: transportDetailModel",
@@ -1232,8 +1236,10 @@
"src/mobile/screens/collections/MCollListPickerSheet.tsx": "Phone list picker sheet; the move or copy action comes through onPick from useCollections.", "src/mobile/screens/collections/MCollListPickerSheet.tsx": "Phone list picker sheet; the move or copy action comes through onPick from useCollections.",
"src/mobile/screens/collections/MCollSheetKit.tsx": "Phone only sheet UI primitives for the collections screens (header, footer, pill, eyebrow).", "src/mobile/screens/collections/MCollSheetKit.tsx": "Phone only sheet UI primitives for the collections screens (header, footer, pill, eyebrow).",
"src/mobile/screens/collections/collectionsMobileModel.ts": "Visual constants only the phone collections screens use (category and status specs, swatches, cover gradient).", "src/mobile/screens/collections/collectionsMobileModel.ts": "Visual constants only the phone collections screens use (category and status specs, swatches, cover gradient).",
"src/mobile/screens/collections/savedListFilterCount.ts": "Counts the active filters shown on the phone saved-list toolbar and filter sheet.",
"src/mobile/screens/dashboard/MUserMenu.tsx": "Phone avatar menu with a three state theme cycle the desktop navbar does not have.", "src/mobile/screens/dashboard/MUserMenu.tsx": "Phone avatar menu with a three state theme cycle the desktop navbar does not have.",
"src/mobile/screens/journey/MDawarichDaySheet.tsx": "Markup only; the phone frame the Dawarich day sheets (route and stays) render their shared review in.", "src/mobile/screens/journey/MDawarichDaySheet.tsx": "Markup only; the phone frame the Dawarich day sheets (route and stays) render their shared review in.",
"src/mobile/screens/journey/MJourneyCreateSheet.tsx": "The phone form receives the journey and trip selection state from MJourney, which shares useJourney with the desktop list.",
"src/mobile/screens/journey/MJourneyFeed.tsx": "Markup only; the journey's entries as a feed beside the map on a wide window, with the entries, the active one and the tap handed in through props from useJourneyDetail and useJourneyCarouselSync.", "src/mobile/screens/journey/MJourneyFeed.tsx": "Markup only; the journey's entries as a feed beside the map on a wide window, with the entries, the active one and the tap handed in through props from useJourneyDetail and useJourneyCarouselSync.",
"src/mobile/screens/settings/MAppLockCard.tsx": "Phone only: the app lock exists only in the native app, so there is no desktop setting to share with.", "src/mobile/screens/settings/MAppLockCard.tsx": "Phone only: the app lock exists only in the native app, so there is no desktop setting to share with.",
"src/mobile/screens/settings/MClientCertCard.tsx": "Phone only: the client certificate is kept by the native app, so there is no desktop setting to share with.", "src/mobile/screens/settings/MClientCertCard.tsx": "Phone only: the client certificate is kept by the native app, so there is no desktop setting to share with.",
@@ -1252,7 +1258,26 @@
"src/mobile/screens/trip/MTripShellParts.tsx": "Markup only; small pieces of MTripShell's top controls (segment pill, compact toggle, document sync button), with the state and handlers MTripShell hands in.", "src/mobile/screens/trip/MTripShellParts.tsx": "Markup only; small pieces of MTripShell's top controls (segment pill, compact toggle, document sync button), with the state and handlers MTripShell hands in.",
"src/mobile/screens/trip/dockTabs.ts": "Phone only helper that picks which trip tabs get a seat in the mobile dock.", "src/mobile/screens/trip/dockTabs.ts": "Phone only helper that picks which trip tabs get a seat in the mobile dock.",
"src/mobile/screens/trip/useTripTabSwitch.ts": "Phone shell only; switches the section the dock and a notification link open, and the collab part a message link means. The desktop switches through useTripPlanner alone.", "src/mobile/screens/trip/useTripTabSwitch.ts": "Phone shell only; switches the section the dock and a notification link open, and the collab part a message link means. The desktop switches through useTripPlanner alone.",
"src/mobile/screens/trip/lib/dayNotes.ts": "Phone only helper that splits a leading time off a day note for the plan timeline.", "src/mobile/screens/collections/MCollColorSwatches.tsx": "Shared color chooser for the phone list and tag forms.",
"src/mobile/screens/collections/MCollPlaceFields.tsx": "Shared layout of the nullable category, address and description fields in phone add and edit forms.",
"src/mobile/screens/collections/MCollToolbar.tsx": "Search, view and filter controls shared by the two phone collection lists.",
"src/mobile/screens/journey/MJourneyInviteFrame.tsx": "Phone invitation layout over the shared ContributorInviteDialog controller.",
"src/mobile/screens/journey/MJourneyEntryRead.tsx": "Phone journal reader over the shared markdown, photo and entry title models.",
"src/mobile/screens/journey/MJourneyVerdict.tsx": "Phone verdict layout shared by the reader and the editor; writes use the shared journey entry form.",
"src/mobile/screens/trip/map/MMapExplore.tsx": "Phone entry points and panels for the shared map exploration state.",
"src/mobile/screens/trip/map/MMapPlaceFilters.tsx": "Phone sheet presenting map and place visibility controls.",
"src/mobile/screens/trip/roadtrip/MRtChoice.tsx": "Phone grid option for the Roadtrip corridor sheets.",
"src/mobile/screens/trip/roadtrip/stageBookings.ts": "Places bookings and their approaches within the phone stage timeline using the shared Roadtrip router and stop associations.",
"src/mobile/screens/trip/sheets/MBookingImportSheet.tsx": "Phone presentation passed to the shared booking import controller.",
"src/mobile/screens/trip/sheets/MDayPickerSheet.tsx": "Searchable phone day picker, separate from the desktop day sidebar.",
"src/mobile/screens/trip/sheets/MGpxPreviewFrame.tsx": "Phone GPX preview layout over the shared TourGpxPreviewDialog controller.",
"src/mobile/screens/trip/sheets/MIcsSubscribeSheet.tsx": "Phone form for the shared calendar subscription hook.",
"src/mobile/screens/trip/sheets/MSubscribeLinks.tsx": "Phone provider and link actions for the shared subscription links hook.",
"src/mobile/screens/trip/sheets/MTripOfflinePage.tsx": "Trip-specific offline controls in the phone settings.",
"src/mobile/screens/trip/useMTripDayResume.ts": "Restores the last day in the phone's single-day planner.",
"src/mobile/screens/trip/tabs/MChecklistCheck.tsx": "Phone checkbox controls shared by trip tasks and packing.",
"src/mobile/screens/trip/sheets/MCurrencyPicker.tsx": "Searchable mobile currency picker shared by the dashboard and costs ledger.",
"src/mobile/screens/trip/tabs/MReservationList.tsx": "Shared phone shell for the bookings and transport tabs.",
"src/mobile/screens/trip/map/MMapArea.tsx": "Phone map stage framing; already shares usePoiExplore and useMergedMapPois with the desktop trip planner.", "src/mobile/screens/trip/map/MMapArea.tsx": "Phone map stage framing; already shares usePoiExplore and useMergedMapPois with the desktop trip planner.",
"src/mobile/screens/trip/places/MPlacesBulkCategorySheet.tsx": "Markup only; categories and the pick handler come through props from MPlacesBrowser.", "src/mobile/screens/trip/places/MPlacesBulkCategorySheet.tsx": "Markup only; categories and the pick handler come through props from MPlacesBrowser.",
"src/mobile/screens/trip/places/MPlacesToursModeSwitch.tsx": "Markup only places or tours toggle; value and onChange come through props from MPlacesBrowser.", "src/mobile/screens/trip/places/MPlacesToursModeSwitch.tsx": "Markup only places or tours toggle; value and onChange come through props from MPlacesBrowser.",
@@ -1287,8 +1312,9 @@
"src/mobile/screens/trip/sheets/PlSheetChrome.tsx": "Phone form sheet chrome primitives (header, footer, field classes).", "src/mobile/screens/trip/sheets/PlSheetChrome.tsx": "Phone form sheet chrome primitives (header, footer, field classes).",
"src/mobile/screens/trip/sheets/PlTags.tsx": "Markup only; the tag picker's state comes through props from MPlaceEditSheet, which runs usePlaceTags, and the chips of the place sheet draw the tags the place carries.", "src/mobile/screens/trip/sheets/PlTags.tsx": "Markup only; the tag picker's state comes through props from MPlaceEditSheet, which runs usePlaceTags, and the chips of the place sheet draw the tags the place carries.",
"src/mobile/screens/trip/sheets/PlTimeFields.tsx": "Phone time fields that already share timeCollisions with the desktop PlaceFormModal.", "src/mobile/screens/trip/sheets/PlTimeFields.tsx": "Phone time fields that already share timeCollisions with the desktop PlaceFormModal.",
"src/mobile/screens/trip/sheets/formOptionClass.ts": "Phone-only styling for the shared sheet option buttons.",
"src/mobile/screens/trip/sheets/tourSheetOpen.ts": "Phone only context for MTourDetailShell: whether the tour sheet is open and the name it carries.", "src/mobile/screens/trip/sheets/tourSheetOpen.ts": "Phone only context for MTourDetailShell: whether the tour sheet is open and the name it carries.",
"src/mobile/screens/trip/tabs/MCollabTab.tsx": "Phone collab sub tab router that reuses the desktop CollabLinks component.", "src/mobile/screens/trip/tabs/MCollabTab.tsx": "Phone collab sub-tab router for the chat and boards.",
"src/mobile/screens/trip/tabs/MFilesBoard.tsx": "Markup only; the trip's files as tiles and the picked file's preview on a wide window, with the files and their actions handed in through props from MFilesTab.", "src/mobile/screens/trip/tabs/MFilesBoard.tsx": "Markup only; the trip's files as tiles and the picked file's preview on a wide window, with the files and their actions handed in through props from MFilesTab.",
"src/mobile/screens/trip/tabs/MListsTab.tsx": "Phone router between the packing and to-do bodies, with no logic of its own.", "src/mobile/screens/trip/tabs/MListsTab.tsx": "Phone router between the packing and to-do bodies, with no logic of its own.",
"src/mobile/screens/trip/tabs/MPackingCategorySharingSheet.tsx": "Markup only; the sheet that shares a whole list, with its state from usePackingCategorySharing handed in through props by MPackingListTab.", "src/mobile/screens/trip/tabs/MPackingCategorySharingSheet.tsx": "Markup only; the sheet that shares a whole list, with its state from usePackingCategorySharing handed in through props by MPackingListTab.",
@@ -1298,6 +1324,7 @@
"src/mobile/screens/trip/tabs/MTripTabPanel.tsx": "Phone tab router that mounts the per tab screens and plugin frames, with no logic of its own.", "src/mobile/screens/trip/tabs/MTripTabPanel.tsx": "Phone tab router that mounts the per tab screens and plugin frames, with no logic of its own.",
"src/mobile/screens/trip/tabs/collabPanes.ts": "Phone only; decides whether the collab tab shows the chat beside a board on a wide window, a layout question of the touch shell that the desktop planner does not have.", "src/mobile/screens/trip/tabs/collabPanes.ts": "Phone only; decides whether the collab tab shows the chat beside a board on a wide window, a layout question of the touch shell that the desktop planner does not have.",
"src/mobile/screens/trip/tabs/listsModel.ts": "Priority colour and label constants only the phone to-do list and task sheet use.", "src/mobile/screens/trip/tabs/listsModel.ts": "Priority colour and label constants only the phone to-do list and task sheet use.",
"src/mobile/screens/trip/tabs/reservationHeaderTint.ts": "Renders the header tint used by the phone booking and transport cards.",
"src/mobile/screens/trip/tabs/tabChrome.tsx": "Phone tab chrome primitives (scroller, section headers, fields, traveler chips, plugin slots).", "src/mobile/screens/trip/tabs/tabChrome.tsx": "Phone tab chrome primitives (scroller, section headers, fields, traveler chips, plugin slots).",
"src/mobile/screens/trip/tabs/tabModel.ts": "Phone tab prop type and status colour tokens only the phone tabs use.", "src/mobile/screens/trip/tabs/tabModel.ts": "Phone tab prop type and status colour tokens only the phone tabs use.",
"src/mobile/screens/trip/tabs/transportsModel.ts": "Phone transport card readers (metadata, day and time cells) for MTransportsTab and MBookingsTab.", "src/mobile/screens/trip/tabs/transportsModel.ts": "Phone transport card readers (metadata, day and time cells) for MTransportsTab and MBookingsTab.",
-3
View File
@@ -640,7 +640,6 @@
"src/components/Planner/PlaceFormModal.helpers.test.ts", "src/components/Planner/PlaceFormModal.helpers.test.ts",
"src/components/Planner/PlaceFormModal.helpers.ts", "src/components/Planner/PlaceFormModal.helpers.ts",
"src/components/Planner/PlaceFormModal.test.tsx", "src/components/Planner/PlaceFormModal.test.tsx",
"src/components/Planner/PlaceFormModal.tsx",
"src/components/Planner/PlaceInspector.test.tsx", "src/components/Planner/PlaceInspector.test.tsx",
"src/components/Planner/PlaceInspector.tsx", "src/components/Planner/PlaceInspector.tsx",
"src/components/Planner/PlacesBulkCategoryModal.test.tsx", "src/components/Planner/PlacesBulkCategoryModal.test.tsx",
@@ -1331,7 +1330,6 @@
"src/mobile/screens/trip/MTripShell.tsx", "src/mobile/screens/trip/MTripShell.tsx",
"src/mobile/screens/trip/dockTabs.test.ts", "src/mobile/screens/trip/dockTabs.test.ts",
"src/mobile/screens/trip/dockTabs.ts", "src/mobile/screens/trip/dockTabs.ts",
"src/mobile/screens/trip/lib/dayNotes.ts",
"src/mobile/screens/trip/map/MMapArea.tsx", "src/mobile/screens/trip/map/MMapArea.tsx",
"src/mobile/screens/trip/places/MPlacesBrowser.tsx", "src/mobile/screens/trip/places/MPlacesBrowser.tsx",
"src/mobile/screens/trip/places/MPlacesBulkCategorySheet.tsx", "src/mobile/screens/trip/places/MPlacesBulkCategorySheet.tsx",
@@ -1426,7 +1424,6 @@
"src/mobile/screens/vacay/MVacayShareSheet.tsx", "src/mobile/screens/vacay/MVacayShareSheet.tsx",
"src/mobile/screens/vacay/useMVacay.ts", "src/mobile/screens/vacay/useMVacay.ts",
"src/mobile/screens/vacay/vacayDayModel.ts", "src/mobile/screens/vacay/vacayDayModel.ts",
"src/mobile/useIsPhone.ts",
"src/pages/AdminPage.test.tsx", "src/pages/AdminPage.test.tsx",
"src/pages/AdminPage.tsx", "src/pages/AdminPage.tsx",
"src/pages/AtlasPage.tsx", "src/pages/AtlasPage.tsx",
+8 -9
View File
@@ -1,36 +1,35 @@
{ {
"admin.ts": 112, "admin.ts": 112,
"atlas.ts": 7, "atlas.ts": 6,
"backup.ts": 10, "backup.ts": 10,
"budget.ts": 35, "budget.ts": 35,
"categories.ts": 1, "categories.ts": 1,
"collab.ts": 9, "collab.ts": 9,
"collection.ts": 29, "collection.ts": 26,
"common.ts": 6, "common.ts": 6,
"dashboard.ts": 64, "dashboard.ts": 60,
"dawarich.ts": 15, "dawarich.ts": 15,
"dayplan.ts": 17, "dayplan.ts": 17,
"docsync.ts": 25, "docsync.ts": 25,
"files.ts": 4, "files.ts": 4,
"help.ts": 3, "help.ts": 3,
"inspector.ts": 4, "inspector.ts": 4,
"journey.ts": 65, "journey.ts": 64,
"login.ts": 1, "login.ts": 1,
"map.ts": 5, "map.ts": 5,
"memories.ts": 8, "memories.ts": 8,
"mobileNav.ts": 2, "mobileNav.ts": 2,
"mobileVacay.ts": 4,
"nav.ts": 1, "nav.ts": 1,
"notif.ts": 7, "notif.ts": 7,
"notifications.ts": 17, "notifications.ts": 17,
"packing.ts": 6, "packing.ts": 6,
"pdf.ts": 1, "pdf.ts": 1,
"perm.ts": 4, "perm.ts": 4,
"places.ts": 9, "places.ts": 8,
"planner.ts": 52, "planner.ts": 49,
"reservations.ts": 21, "reservations.ts": 20,
"roadtrip.ts": 36, "roadtrip.ts": 36,
"settings.ts": 37, "settings.ts": 36,
"share.ts": 7, "share.ts": 7,
"shared.ts": 2, "shared.ts": 2,
"storage.ts": 16, "storage.ts": 16,
-2
View File
@@ -28,8 +28,6 @@
"src/components/Journey/MobileEntryView.tsx": 1, "src/components/Journey/MobileEntryView.tsx": 1,
"src/components/Map/MapView.tsx": 1, "src/components/Map/MapView.tsx": 1,
"src/components/Map/MapViewGL.tsx": 1, "src/components/Map/MapViewGL.tsx": 1,
"src/components/Planner/IcsSubscribeModal.tsx": 1,
"src/components/Planner/TransitJourneyModal.tsx": 1,
"src/components/Planner/TransitSearchPanel.tsx": 1, "src/components/Planner/TransitSearchPanel.tsx": 1,
"src/components/Planner/TripWarningsBanner.tsx": 1, "src/components/Planner/TripWarningsBanner.tsx": 1,
"src/components/Planner/transitDisplay.tsx": 1, "src/components/Planner/transitDisplay.tsx": 1,
+29 -63
View File
@@ -155,71 +155,37 @@ function gitIn(root, args) {
} }
} }
/** The messages of one rule in one area of a single file's lint result. */
function ofRule(results, rule, area) {
const result = results[0];
if (!result) return [];
const pool =
area === 'suppressed' ? (result.suppressedMessages ?? []) : result.messages.filter((m) => m.severity === 1);
return pool.filter((m) => ruleOf(m) === rule);
}
/** /**
* Where a grown rule's new warnings sit: every file among `keys` (the files * Locate warnings in changed files using the completed lint pass. Linting
* holding the rule now) that differs from `ref` and holds more of the rule * alternate file versions needs extra TypeScript programs and can exhaust
* than it did there, each of its warnings of the rule as `file:line message`. * the runner's heap before it reports the existing warnings.
* The count alone names no file, and the files holding the most are old ones;
* this names the file that tipped it. Null when `ref` is not at hand (a clone
* without it), and the report then keeps to the files holding the most.
*/ */
export async function newWarningsOf({ root, rule, area, keys, lintText, ref = baseRef(), git = gitIn }) { export function changedWarnings(results, root, changed, area, rule) {
const changed = git(root, ['diff', '--name-only', '--relative', ref, '--', '.']); const found = [];
if (changed === null) return null; for (const result of results) {
const differs = new Set(changed.split('\n').filter(Boolean)); const key = toKey(root, result.filePath);
const found = await Promise.all( if (!changed.has(key) || (area !== 'suppressed' && area !== areaOf(key))) continue;
keys const messages =
.filter((key) => differs.has(key)) area === 'suppressed' ? (result.suppressedMessages ?? []) : result.messages.filter((m) => m.severity === 1);
.map(async (key) => { for (const message of messages) {
const path = join(root, key); if (ruleOf(message) === rule) found.push(`${key}:${message.line ?? 0} ${message.message}`);
// A typed rule can trip over a text that is not the file on disk (the }
// base version); then the file's own warnings are told, marked so. }
const lint = async (text) => { return found;
try {
return { messages: ofRule(await lintText(text, path), rule, area) };
} catch {
return null;
}
};
const now = await lint(readText(path));
if (!now) return [];
const before = git(root, ['show', `${ref}:./${key}`]);
const was = before === null ? { messages: [] } : await lint(before);
if (was && now.messages.length <= was.messages.length) return [];
const note = was ? '' : ' (the base version could not be linted)';
return now.messages.map((m) => `${key}:${m.line ?? 0} ${m.message}${note}`);
})
);
return found.flat();
} }
/** Prints, under the grown counts, the files and lines behind each one (see newWarningsOf). */ function reportChanged(grown, { root, error, results }) {
async function reportNew(grown, { root, files, lintText, error }) { if (!grown.length) return;
if (!grown.length || !lintText) return; const ref = baseRef();
const found = await Promise.all( const paths = gitIn(root, ['diff', '--name-only', '--relative', '-z', ref, '--', '.']);
grown.map(({ area, rule }) => newWarningsOf({ root, rule, area, keys: Object.keys(files[area][rule]), lintText })) if (paths === null) return;
); const changed = new Set(paths.split('\0').filter(Boolean));
grown.forEach(({ area, rule }, i) => { for (const { area, rule } of grown) {
const lines = found[i]; const lines = changedWarnings(results, root, changed, area, rule);
if (!lines?.length) return; if (!lines.length) continue;
error(`New ${rule} warning(s) in ${area}, against ${baseRef()}:`); error(`${rule} warning(s) in changed ${area} files, against ${ref}:`);
for (const line of lines) error(` ${line}`); for (const line of lines) error(` ${line}`);
}); }
}
/** Lints one file's text with the client's own config, for newWarningsOf. */
function lintTextClient(root) {
const eslint = new ESLint({ cwd: root });
return (text, filePath) => eslint.lintText(text, { filePath });
} }
const sum = (map) => Object.values(map).reduce((a, b) => a + b, 0); const sum = (map) => Object.values(map).reduce((a, b) => a + b, 0);
@@ -233,12 +199,12 @@ export async function check({
baselinePath = join(root, 'scripts/eslint-baseline.json'), baselinePath = join(root, 'scripts/eslint-baseline.json'),
update = false, update = false,
lint = lintClient, lint = lintClient,
lintText = lint === lintClient ? lintTextClient : null,
log = console.log, log = console.log,
error = console.error, error = console.error,
}) { }) {
let baseline = readBaseline(baselinePath, areaCounts); let baseline = readBaseline(baselinePath, areaCounts);
const { counts, files, errors } = tally(await lint(root), root); const results = await lint(root);
const { counts, files, errors } = tally(results, root);
if (update) { if (update) {
baseline = Object.fromEntries(AREAS.map((area) => [area, lowerCounts(baseline[area], counts[area])])); baseline = Object.fromEntries(AREAS.map((area) => [area, lowerCounts(baseline[area], counts[area])]));
@@ -268,7 +234,7 @@ export async function check({
}); });
stale += fallen.length; stale += fallen.length;
} }
await reportNew(grown, { root, files, lintText: lintText && lintText(root), error }); if (lint === lintClient) reportChanged(grown, { root, error, results });
if (grown.length) { if (grown.length) {
error( error(
'Fix the new warning rather than silencing it: an eslint-disable comment is counted under "suppressed". ' + 'Fix the new warning rather than silencing it: an eslint-disable comment is counted under "suppressed". ' +
@@ -0,0 +1,45 @@
import assert from 'node:assert/strict';
import { basename } from 'node:path';
import { test } from 'node:test';
import config from '../vite.native.config.js';
const variable = 'TREK_CLOUD_SANDBOX_ORIGIN';
function setOrigin(context, origin) {
const previous = process.env[variable];
process.env[variable] = origin;
context.after(() => {
if (previous === undefined) delete process.env[variable];
else process.env[variable] = previous;
});
}
test('isolates the sandbox output and keeps the ordinary app on the production configuration', (context) => {
const origin = 'https://store-sandbox.example.com';
setOrigin(context, origin);
const sandbox = config({ command: 'build', mode: 'store-sandbox' });
assert.deepEqual(sandbox.define, { __TREK_STORE_SANDBOX_ORIGIN__: JSON.stringify(origin) });
assert.equal(basename(sandbox.build.outDir), 'native-sandbox-dist');
for (const input of [
{ command: 'build', mode: 'production' },
{ command: 'serve', mode: 'store-sandbox' },
]) {
const regular = config(input);
assert.deepEqual(regular.define, {});
assert.equal(basename(regular.build.outDir), 'native-dist');
}
});
for (const origin of [
'',
'http://qa.example.com',
'https://qa.example.com/path',
'https://liketrek.com',
'https://www.liketrek.com',
]) {
test(`refuses a sandbox configuration with origin ${JSON.stringify(origin)}`, (context) => {
setOrigin(context, origin);
assert.throws(() => config({ command: 'build', mode: 'store-sandbox' }), { message: new RegExp(variable) });
});
}
-1
View File
@@ -24,7 +24,6 @@
"src/components/Budget/ReceiptPreviewModal.tsx", "src/components/Budget/ReceiptPreviewModal.tsx",
"src/components/Budget/receiptUploads.ts", "src/components/Budget/receiptUploads.ts",
"src/components/Collab/CollabChatLinkPreview.tsx", "src/components/Collab/CollabChatLinkPreview.tsx",
"src/components/Collab/CollabLinks.tsx",
"src/components/Collab/CollabNotes.tsx", "src/components/Collab/CollabNotes.tsx",
"src/components/Collab/CollabNotesAuthedImg.tsx", "src/components/Collab/CollabNotesAuthedImg.tsx",
"src/components/Collab/CollabNotesFilePreviewPortal.tsx", "src/components/Collab/CollabNotesFilePreviewPortal.tsx",
+1 -2
View File
@@ -13,7 +13,6 @@
"components/Journey/JourneyDetailPageGalleryView.tsx": 1, "components/Journey/JourneyDetailPageGalleryView.tsx": 1,
"components/Journey/JourneyDetailPagePhotoGrid.tsx": 1, "components/Journey/JourneyDetailPagePhotoGrid.tsx": 1,
"components/Journey/JourneyDetailPageProviderPicker.tsx": 1, "components/Journey/JourneyDetailPageProviderPicker.tsx": 1,
"components/Journey/JourneyEntryCover.tsx": 1,
"components/Journey/JourneyMap.tsx": 1, "components/Journey/JourneyMap.tsx": 1,
"components/Journey/JourneyMapGL.tsx": 2, "components/Journey/JourneyMapGL.tsx": 2,
"components/Journey/MobileEntryView.tsx": 1, "components/Journey/MobileEntryView.tsx": 1,
@@ -76,7 +75,7 @@
"hooks/useAnchoredPosition.ts": 3, "hooks/useAnchoredPosition.ts": 3,
"hooks/useElementRect.ts": 3, "hooks/useElementRect.ts": 3,
"mobile/components/MSegmented.tsx": 1, "mobile/components/MSegmented.tsx": 1,
"mobile/screens/journey/MJourneyDetail.tsx": 3, "mobile/screens/journey/MJourneyDetail.tsx": 2,
"mobile/screens/journey/MJourneyEntrySheet.tsx": 1, "mobile/screens/journey/MJourneyEntrySheet.tsx": 1,
"mobile/screens/trip/map/MMapArea.tsx": 3, "mobile/screens/trip/map/MMapArea.tsx": 3,
"mobile/screens/trip/tabs/MFileLightbox.tsx": 2, "mobile/screens/trip/tabs/MFileLightbox.tsx": 2,
+1
View File
@@ -5,6 +5,7 @@
"components/Studio/LineHandles.tsx": 1, "components/Studio/LineHandles.tsx": 1,
"components/Studio/StudioSelectionChrome.tsx": 2, "components/Studio/StudioSelectionChrome.tsx": 2,
"components/Studio/inspector/FocalPad.tsx": 1, "components/Studio/inspector/FocalPad.tsx": 1,
"components/Tours/TourGpxPreviewDialog.tsx": 1,
"mobile/components/trek3d/MascotClip.tsx": 1, "mobile/components/trek3d/MascotClip.tsx": 1,
"mobile/screens/trip/MTripShell.tsx": 1, "mobile/screens/trip/MTripShell.tsx": 1,
"mobile/screens/vacay/MVacay.tsx": 1, "mobile/screens/vacay/MVacay.tsx": 1,
+6 -6
View File
@@ -4,22 +4,22 @@
"src/components/Admin/AdminPluginsPanel.test.tsx": 2704, "src/components/Admin/AdminPluginsPanel.test.tsx": 2704,
"src/components/Admin/AdminPluginsPanel.tsx": 1265, "src/components/Admin/AdminPluginsPanel.tsx": 1265,
"src/components/Budget/CostsPanel.test.tsx": 2725, "src/components/Budget/CostsPanel.test.tsx": 2725,
"src/components/Budget/CostsPanel.tsx": 1607, "src/components/Budget/CostsPanel.tsx": 1587,
"src/components/Map/MapView.tsx": 1191, "src/components/Map/MapView.tsx": 1170,
"src/components/Map/MapViewGL.test.tsx": 2919, "src/components/Map/MapViewGL.test.tsx": 2919,
"src/components/Map/MapViewGL.tsx": 2083, "src/components/Map/MapViewGL.tsx": 2083,
"src/components/Planner/DayDetailPanel.test.tsx": 2331, "src/components/Planner/DayDetailPanel.test.tsx": 2331,
"src/components/Planner/DayPlanSidebar.test.tsx": 5349, "src/components/Planner/DayPlanSidebar.test.tsx": 5349,
"src/components/Planner/DayPlanSidebar.tsx": 2908, "src/components/Planner/DayPlanSidebar.tsx": 2895,
"src/components/Planner/PlaceFormModal.test.tsx": 2836, "src/components/Planner/PlaceFormModal.test.tsx": 2833,
"src/components/Planner/PlaceInspector.tsx": 1030, "src/components/Planner/PlaceInspector.tsx": 1014,
"src/components/Studio/TravelElements.tsx": 1332, "src/components/Studio/TravelElements.tsx": 1332,
"src/components/Studio/countryShapes.ts": 2595, "src/components/Studio/countryShapes.ts": 2595,
"src/index.css": 1636, "src/index.css": 1636,
"src/mobile/screens/admin/MAdminPluginsPanel.tsx": 1503, "src/mobile/screens/admin/MAdminPluginsPanel.tsx": 1503,
"src/pages/JourneyDetailPage.test.tsx": 3880, "src/pages/JourneyDetailPage.test.tsx": 3880,
"src/pages/LoginPage.tsx": 1273, "src/pages/LoginPage.tsx": 1273,
"src/pages/TripPlannerPage.tsx": 1127, "src/pages/TripPlannerPage.tsx": 1122,
"src/pages/tripPlanner/useTripPlanner.roadtrip.test.tsx": 3518, "src/pages/tripPlanner/useTripPlanner.roadtrip.test.tsx": 3518,
"src/pages/tripPlanner/useTripPlanner.test.tsx": 3267, "src/pages/tripPlanner/useTripPlanner.test.tsx": 3267,
"src/styles/studio.css": 1918 "src/styles/studio.css": 1918
-2
View File
@@ -48,7 +48,6 @@
"src/components/Planner/DayPlanSidebar.tsx": 52, "src/components/Planner/DayPlanSidebar.tsx": 52,
"src/components/Planner/DayPlanSidebarNoteModal.test.tsx": 1, "src/components/Planner/DayPlanSidebarNoteModal.test.tsx": 1,
"src/components/Planner/PlaceFormModal.test.tsx": 3, "src/components/Planner/PlaceFormModal.test.tsx": 3,
"src/components/Planner/PlaceFormModal.tsx": 1,
"src/components/Planner/PlaceInspector.tsx": 16, "src/components/Planner/PlaceInspector.tsx": 16,
"src/components/Planner/PlacesBulkCategoryModal.test.tsx": 1, "src/components/Planner/PlacesBulkCategoryModal.test.tsx": 1,
"src/components/Planner/PlacesSidebar.tsx": 1, "src/components/Planner/PlacesSidebar.tsx": 1,
@@ -97,7 +96,6 @@
"src/hooks/useDawarichSuggestions.test.ts": 1, "src/hooks/useDawarichSuggestions.test.ts": 1,
"src/mobile/screens/admin/MAdminAddonManager.tsx": 2, "src/mobile/screens/admin/MAdminAddonManager.tsx": 2,
"src/mobile/screens/admin/MAdminPluginsPanel.tsx": 6, "src/mobile/screens/admin/MAdminPluginsPanel.tsx": 6,
"src/mobile/screens/journey/MJourneySettingsSheet.tsx": 1,
"src/mobile/screens/settings/MSettingsAccount.tsx": 1, "src/mobile/screens/settings/MSettingsAccount.tsx": 1,
"src/mobile/screens/trip/MTripShell.tsx": 1, "src/mobile/screens/trip/MTripShell.tsx": 1,
"src/mobile/screens/trip/map/MMapArea.tsx": 1, "src/mobile/screens/trip/map/MMapArea.tsx": 1,
+41 -90
View File
@@ -6,7 +6,7 @@
"components/BackgroundTasks/BackgroundTasksWidget.tsx": 4, "components/BackgroundTasks/BackgroundTasksWidget.tsx": 4,
"components/Budget/BudgetPanel.helpers.ts": 2, "components/Budget/BudgetPanel.helpers.ts": 2,
"components/Budget/BudgetPanelMemberChips.tsx": 4, "components/Budget/BudgetPanelMemberChips.tsx": 4,
"components/Budget/CostsPanel.tsx": 37, "components/Budget/CostsPanel.tsx": 33,
"components/Budget/ReceiptPreviewModal.tsx": 6, "components/Budget/ReceiptPreviewModal.tsx": 6,
"components/Budget/ReceiptScanModal.tsx": 2, "components/Budget/ReceiptScanModal.tsx": 2,
"components/Budget/costsCategories.tsx": 14, "components/Budget/costsCategories.tsx": 14,
@@ -19,7 +19,6 @@
"components/Collab/CollabNotesFilePreviewPortal.tsx": 2, "components/Collab/CollabNotesFilePreviewPortal.tsx": 2,
"components/Collab/CollabPolls.tsx": 3, "components/Collab/CollabPolls.tsx": 3,
"components/Collections/CollectionHero.tsx": 1, "components/Collections/CollectionHero.tsx": 1,
"components/Collections/MSaveToCollectionSheet.tsx": 12,
"components/Collections/StatusBadge.tsx": 4, "components/Collections/StatusBadge.tsx": 4,
"components/Files/FileManagerAvatarChip.tsx": 1, "components/Files/FileManagerAvatarChip.tsx": 1,
"components/Files/FileManagerImageLightbox.tsx": 8, "components/Files/FileManagerImageLightbox.tsx": 8,
@@ -52,7 +51,7 @@
"components/Layout/BottomNav.tsx": 3, "components/Layout/BottomNav.tsx": 3,
"components/Layout/InAppNotificationBell.tsx": 3, "components/Layout/InAppNotificationBell.tsx": 3,
"components/Layout/MobileTopBar.tsx": 51, "components/Layout/MobileTopBar.tsx": 51,
"components/Layout/Navbar.tsx": 21, "components/Layout/Navbar.tsx": 17,
"components/Layout/NewVersionNotice.tsx": 3, "components/Layout/NewVersionNotice.tsx": 3,
"components/Layout/OfflineBanner.tsx": 2, "components/Layout/OfflineBanner.tsx": 2,
"components/Layout/PageSidebar.tsx": 3, "components/Layout/PageSidebar.tsx": 3,
@@ -71,20 +70,15 @@
"components/Map/ratingBadge.ts": 2, "components/Map/ratingBadge.ts": 2,
"components/Map/reservationsMapbox.ts": 1, "components/Map/reservationsMapbox.ts": 1,
"components/Map/switcherRow.ts": 1, "components/Map/switcherRow.ts": 1,
"components/Packing/PackingListPanelBagModal.tsx": 2,
"components/Packing/PackingListPanelCategoryGroup.tsx": 5, "components/Packing/PackingListPanelCategoryGroup.tsx": 5,
"components/Packing/PackingListPanelHeader.tsx": 3, "components/Packing/PackingListPanelHeader.tsx": 3,
"components/Packing/packingPrintDocument.ts": 24, "components/Packing/packingPrintDocument.ts": 24,
"components/Planner/AirTrailImportModal.tsx": 4, "components/Planner/AirTrailImportModal.tsx": 2,
"components/Planner/BookingCostsSection.tsx": 1,
"components/Planner/BookingImportModal.tsx": 4,
"components/Planner/DayDetailPanel.tsx": 1, "components/Planner/DayDetailPanel.tsx": 1,
"components/Planner/IcsSubscribeModal.tsx": 10,
"components/Planner/PlaceInspector.tsx": 1, "components/Planner/PlaceInspector.tsx": 1,
"components/Planner/PlacesSidebarMobileDayPicker.tsx": 3, "components/Planner/PlacesSidebarMobileDayPicker.tsx": 3,
"components/Planner/SubscribeLinks.tsx": 5, "components/Planner/SubscribeLinks.tsx": 5,
"components/Planner/SuggestionDropdown.tsx": 1, "components/Planner/SuggestionDropdown.tsx": 1,
"components/Planner/TransitJourneyModal.tsx": 4,
"components/Planner/TransitSearchPanel.tsx": 2, "components/Planner/TransitSearchPanel.tsx": 2,
"components/Planner/TravelerPicker.tsx": 3, "components/Planner/TravelerPicker.tsx": 3,
"components/Planner/bookings/BookingsTimeline.tsx": 1, "components/Planner/bookings/BookingsTimeline.tsx": 1,
@@ -103,7 +97,7 @@
"components/Studio/printSheets.ts": 5, "components/Studio/printSheets.ts": 5,
"components/Studio/sidebar/contentDrops.ts": 2, "components/Studio/sidebar/contentDrops.ts": 2,
"components/SystemNotices/SystemNoticeBanner.tsx": 28, "components/SystemNotices/SystemNoticeBanner.tsx": 28,
"components/SystemNotices/SystemNoticeModal.tsx": 107, "components/SystemNotices/SystemNoticeModal.tsx": 45,
"components/Todo/TodoListPanel.tsx": 6, "components/Todo/TodoListPanel.tsx": 6,
"components/Todo/todoListModel.ts": 3, "components/Todo/todoListModel.ts": 3,
"components/Trips/TripFormModal.tsx": 6, "components/Trips/TripFormModal.tsx": 6,
@@ -115,13 +109,11 @@
"components/Vacay/VacaySharedCalendars.tsx": 6, "components/Vacay/VacaySharedCalendars.tsx": 6,
"components/Vacay/VacayStats.tsx": 14, "components/Vacay/VacayStats.tsx": 14,
"components/Weather/WeatherWidget.tsx": 4, "components/Weather/WeatherWidget.tsx": 4,
"components/shared/ConfirmDialog.tsx": 8, "components/shared/ConfirmDialog.tsx": 7,
"components/shared/ContextMenu.tsx": 1, "components/shared/ContextMenu.tsx": 1,
"components/shared/CopyTripDialog.tsx": 12,
"components/shared/CustomDateTimePicker.tsx": 1, "components/shared/CustomDateTimePicker.tsx": 1,
"components/shared/CustomSelect.tsx": 1, "components/shared/CustomSelect.tsx": 1,
"components/shared/CustomTimePicker.tsx": 1, "components/shared/CustomTimePicker.tsx": 1,
"components/shared/EmptyState.tsx": 1,
"components/shared/Modal.tsx": 3, "components/shared/Modal.tsx": 3,
"components/shared/NavigationMenu.tsx": 1, "components/shared/NavigationMenu.tsx": 1,
"components/shared/NoteColorPicker.tsx": 2, "components/shared/NoteColorPicker.tsx": 2,
@@ -134,7 +126,6 @@
"components/shared/TrackColorPicker.tsx": 2, "components/shared/TrackColorPicker.tsx": 2,
"components/shared/TripLoadingSplash.tsx": 10, "components/shared/TripLoadingSplash.tsx": 10,
"mobile/components/MBadge.tsx": 2, "mobile/components/MBadge.tsx": 2,
"mobile/components/MBottomNav.tsx": 2,
"mobile/components/MChip.tsx": 2, "mobile/components/MChip.tsx": 2,
"mobile/components/MDayImpactList.tsx": 4, "mobile/components/MDayImpactList.tsx": 4,
"mobile/components/MListRow.tsx": 1, "mobile/components/MListRow.tsx": 1,
@@ -142,7 +133,6 @@
"mobile/components/MSheet.tsx": 1, "mobile/components/MSheet.tsx": 1,
"mobile/components/MStorageTestResult.tsx": 3, "mobile/components/MStorageTestResult.tsx": 3,
"mobile/components/MToastHost.tsx": 2, "mobile/components/MToastHost.tsx": 2,
"mobile/components/MUserPickerList.tsx": 1,
"mobile/screens/admin/MAdmin.tsx": 8, "mobile/screens/admin/MAdmin.tsx": 8,
"mobile/screens/admin/MAdminAddonManager.tsx": 3, "mobile/screens/admin/MAdminAddonManager.tsx": 3,
"mobile/screens/admin/MAdminAuditLogPanel.tsx": 15, "mobile/screens/admin/MAdminAuditLogPanel.tsx": 15,
@@ -162,31 +152,18 @@
"mobile/screens/admin/MAdminUi.tsx": 7, "mobile/screens/admin/MAdminUi.tsx": 7,
"mobile/screens/admin/MAdminUsersSection.tsx": 13, "mobile/screens/admin/MAdminUsersSection.tsx": 13,
"mobile/screens/admin/MApiProviderBlocks.tsx": 10, "mobile/screens/admin/MApiProviderBlocks.tsx": 10,
"mobile/screens/atlas/MAtlasCountryPopup.tsx": 11,
"mobile/screens/atlas/MAtlasStatsCard.tsx": 2, "mobile/screens/atlas/MAtlasStatsCard.tsx": 2,
"mobile/screens/collections/MCollAddSheet.tsx": 6,
"mobile/screens/collections/MCollCategoryPicker.tsx": 2,
"mobile/screens/collections/MCollEditSheet.tsx": 2,
"mobile/screens/collections/MCollLabelsSheet.tsx": 6,
"mobile/screens/collections/MCollLinksEditor.tsx": 2,
"mobile/screens/collections/MCollListPickerSheet.tsx": 3,
"mobile/screens/collections/MCollPlaceRow.tsx": 3, "mobile/screens/collections/MCollPlaceRow.tsx": 3,
"mobile/screens/collections/MCollShareSheet.tsx": 14, "mobile/screens/collections/MCollShareSheet.tsx": 1,
"mobile/screens/collections/MCollSheetKit.tsx": 5, "mobile/screens/collections/MCollSheetKit.tsx": 3,
"mobile/screens/collections/MCollTripPickerSheet.tsx": 4, "mobile/screens/collections/MCollections.tsx": 2,
"mobile/screens/collections/MCollections.tsx": 9, "mobile/screens/dashboard/MDashboard.tsx": 25,
"mobile/screens/dashboard/MDashWidgets.tsx": 22, "mobile/screens/dashboard/MNewTripSheet.tsx": 11,
"mobile/screens/dashboard/MDashboard.tsx": 30,
"mobile/screens/dashboard/MNewTripSheet.tsx": 12,
"mobile/screens/dashboard/MUserMenu.tsx": 7, "mobile/screens/dashboard/MUserMenu.tsx": 7,
"mobile/screens/journey/MJourney.tsx": 10, "mobile/screens/journey/MJourney.tsx": 10,
"mobile/screens/journey/MJourneyCreateSheet.tsx": 7, "mobile/screens/journey/MJourneyDetail.tsx": 3,
"mobile/screens/journey/MJourneyDetail.tsx": 6, "mobile/screens/journey/MJourneyEntrySheet.tsx": 11,
"mobile/screens/journey/MJourneyEntrySheet.tsx": 46,
"mobile/screens/journey/MJourneySettingsSheet.tsx": 2,
"mobile/screens/journey/mobileJourneyMeta.ts": 4, "mobile/screens/journey/mobileJourneyMeta.ts": 4,
"mobile/screens/notifications/MNotificationRow.tsx": 4,
"mobile/screens/notifications/MNotifications.tsx": 3,
"mobile/screens/settings/MAirTrailConnectionSection.tsx": 2, "mobile/screens/settings/MAirTrailConnectionSection.tsx": 2,
"mobile/screens/settings/MConfirmSheet.tsx": 2, "mobile/screens/settings/MConfirmSheet.tsx": 2,
"mobile/screens/settings/MDawarichConnectionSection.tsx": 5, "mobile/screens/settings/MDawarichConnectionSection.tsx": 5,
@@ -207,75 +184,49 @@
"mobile/screens/settings/MSettingsUi.tsx": 10, "mobile/screens/settings/MSettingsUi.tsx": 10,
"mobile/screens/settings/MWebPushCard.tsx": 1, "mobile/screens/settings/MWebPushCard.tsx": 1,
"mobile/screens/trip/MTripLoadingSplash.tsx": 2, "mobile/screens/trip/MTripLoadingSplash.tsx": 2,
"mobile/screens/trip/MTripShell.tsx": 7, "mobile/screens/trip/MTripShell.tsx": 5,
"mobile/screens/trip/places/MPlacesBrowser.tsx": 10, "mobile/screens/trip/places/MPlacesBrowser.tsx": 1,
"mobile/screens/trip/places/MPlacesBulkCategorySheet.tsx": 2, "mobile/screens/trip/places/MPlacesBulkCategorySheet.tsx": 2,
"mobile/screens/trip/places/MPlacesFilterControls.tsx": 1, "mobile/screens/trip/places/MPlacesFilterControls.tsx": 1,
"mobile/screens/trip/places/MPlacesSaveToCollectionSheet.tsx": 6, "mobile/screens/trip/places/MPlacesSaveToCollectionSheet.tsx": 6,
"mobile/screens/trip/places/MPlacesToursModeSwitch.tsx": 1, "mobile/screens/trip/plan/MPlanTimeline.tsx": 10,
"mobile/screens/trip/plan/MPlanTimeline.tsx": 12, "mobile/screens/trip/plan/MPlanTimelineRows.tsx": 12,
"mobile/screens/trip/plan/MPlanTimelineRows.tsx": 24, "mobile/screens/trip/roadtrip/MRoadtripRows.tsx": 18,
"mobile/screens/trip/roadtrip/MRoadtripRows.tsx": 31, "mobile/screens/trip/roadtrip/MRoadtripTab.tsx": 11,
"mobile/screens/trip/roadtrip/MRoadtripTab.tsx": 16,
"mobile/screens/trip/roadtrip/MRtAlternativesBar.tsx": 8,
"mobile/screens/trip/roadtrip/MRtCorridorBar.tsx": 2, "mobile/screens/trip/roadtrip/MRtCorridorBar.tsx": 2,
"mobile/screens/trip/roadtrip/MRtCorridorSheet.tsx": 7, "mobile/screens/trip/roadtrip/MRtCorridorSheet.tsx": 4,
"mobile/screens/trip/roadtrip/MRtDraftSheet.tsx": 5, "mobile/screens/trip/roadtrip/MRtKindSheet.tsx": 2,
"mobile/screens/trip/roadtrip/MRtInfoSheet.tsx": 9, "mobile/screens/trip/roadtrip/MRtStopSheet.tsx": 3,
"mobile/screens/trip/roadtrip/MRtKindSheet.tsx": 3,
"mobile/screens/trip/roadtrip/MRtStaySheet.tsx": 17,
"mobile/screens/trip/roadtrip/MRtStopSheet.tsx": 12,
"mobile/screens/trip/sheets/ImpFileStep.tsx": 12,
"mobile/screens/trip/sheets/ImpListStep.tsx": 3,
"mobile/screens/trip/sheets/MAccommodationSheet.tsx": 10, "mobile/screens/trip/sheets/MAccommodationSheet.tsx": 10,
"mobile/screens/trip/sheets/MBookingFields.tsx": 5, "mobile/screens/trip/sheets/MBookingFields.tsx": 4,
"mobile/screens/trip/sheets/MBrowseActionsSheet.tsx": 3, "mobile/screens/trip/sheets/MCostSheet.tsx": 23,
"mobile/screens/trip/sheets/MCostSheet.tsx": 33, "mobile/screens/trip/sheets/MDaySheet.tsx": 5,
"mobile/screens/trip/sheets/MDaySheet.tsx": 22, "mobile/screens/trip/sheets/MDaysSheet.tsx": 2,
"mobile/screens/trip/sheets/MDaysSheet.tsx": 4, "mobile/screens/trip/sheets/MLinkedCosts.tsx": 7,
"mobile/screens/trip/sheets/MExportSheet.tsx": 2, "mobile/screens/trip/sheets/MPlaceSheet.tsx": 6,
"mobile/screens/trip/sheets/MImportSheet.tsx": 2, "mobile/screens/trip/sheets/MReservationSheet.tsx": 1,
"mobile/screens/trip/sheets/MLinkedCosts.tsx": 8, "mobile/screens/trip/sheets/MTransportSheet.tsx": 6,
"mobile/screens/trip/sheets/MMehrSheet.tsx": 3,
"mobile/screens/trip/sheets/MNoteSheet.tsx": 1,
"mobile/screens/trip/sheets/MPlaceEditSheet.tsx": 2,
"mobile/screens/trip/sheets/MPlaceSheet.tsx": 23,
"mobile/screens/trip/sheets/MReservationSheet.tsx": 2,
"mobile/screens/trip/sheets/MTransportFormSheet.tsx": 9,
"mobile/screens/trip/sheets/MTransportSheet.tsx": 9,
"mobile/screens/trip/sheets/MTripSheetUi.tsx": 5, "mobile/screens/trip/sheets/MTripSheetUi.tsx": 5,
"mobile/screens/trip/sheets/PlCategoryPicker.tsx": 1, "mobile/screens/trip/sheets/PlCategoryPicker.tsx": 1,
"mobile/screens/trip/sheets/PlFileAttach.tsx": 3, "mobile/screens/trip/sheets/PlPlaceSearch.tsx": 2,
"mobile/screens/trip/sheets/PlPlaceSearch.tsx": 6, "mobile/screens/trip/sheets/PlSheetChrome.tsx": 1,
"mobile/screens/trip/sheets/PlSheetChrome.tsx": 5,
"mobile/screens/trip/sheets/PlTimeFields.tsx": 3, "mobile/screens/trip/sheets/PlTimeFields.tsx": 3,
"mobile/screens/trip/tabs/MBagsSheet.tsx": 13, "mobile/screens/trip/tabs/MBagsSheet.tsx": 13,
"mobile/screens/trip/tabs/MBookingsTab.tsx": 2, "mobile/screens/trip/tabs/MCollabChat.tsx": 6,
"mobile/screens/trip/tabs/MCollabChat.tsx": 22, "mobile/screens/trip/tabs/MCollabNotes.tsx": 4,
"mobile/screens/trip/tabs/MCollabNotes.tsx": 19, "mobile/screens/trip/tabs/MCollabPolls.tsx": 12,
"mobile/screens/trip/tabs/MCollabPolls.tsx": 18,
"mobile/screens/trip/tabs/MCollabTab.tsx": 1, "mobile/screens/trip/tabs/MCollabTab.tsx": 1,
"mobile/screens/trip/tabs/MCostsTab.tsx": 70, "mobile/screens/trip/tabs/MCostsTab.tsx": 36,
"mobile/screens/trip/tabs/MDocSyncSheet.tsx": 43, "mobile/screens/trip/tabs/MDocSyncSheet.tsx": 30,
"mobile/screens/trip/tabs/MFileLightbox.tsx": 11, "mobile/screens/trip/tabs/MFileLightbox.tsx": 11,
"mobile/screens/trip/tabs/MFileLinkSheet.tsx": 2, "mobile/screens/trip/tabs/MFilesTab.tsx": 2,
"mobile/screens/trip/tabs/MFileMenuSheet.tsx": 1,
"mobile/screens/trip/tabs/MFileTrashSheet.tsx": 4,
"mobile/screens/trip/tabs/MFilesTab.tsx": 12,
"mobile/screens/trip/tabs/MPackItemSheet.tsx": 1, "mobile/screens/trip/tabs/MPackItemSheet.tsx": 1,
"mobile/screens/trip/tabs/MPackingImportSheet.tsx": 3,
"mobile/screens/trip/tabs/MPackingListTab.tsx": 2, "mobile/screens/trip/tabs/MPackingListTab.tsx": 2,
"mobile/screens/trip/tabs/MReservationCardParts.tsx": 6, "mobile/screens/trip/tabs/MTaskSheet.tsx": 1,
"mobile/screens/trip/tabs/MTaskSheet.tsx": 6, "mobile/screens/trip/tabs/MTodoListTab.tsx": 2,
"mobile/screens/trip/tabs/MTodoListTab.tsx": 3,
"mobile/screens/trip/tabs/MTransportsTab.tsx": 2,
"mobile/screens/trip/tabs/filesModel.ts": 5, "mobile/screens/trip/tabs/filesModel.ts": 5,
"mobile/screens/trip/tabs/tabChrome.tsx": 12, "mobile/screens/trip/tabs/tabChrome.tsx": 3,
"mobile/screens/vacay/MVacay.tsx": 17, "mobile/screens/vacay/MVacay.tsx": 1,
"mobile/screens/vacay/MVacayInviteSheet.tsx": 8,
"mobile/screens/vacay/MVacayMonth.tsx": 3,
"mobile/screens/vacay/MVacaySettingsSheet.tsx": 34,
"mobile/screens/vacay/MVacayShareSheet.tsx": 10,
"mobile/screens/vacay/vacayDayModel.ts": 1, "mobile/screens/vacay/vacayDayModel.ts": 1,
"pages/DashboardPage.tsx": 1, "pages/DashboardPage.tsx": 1,
"pages/FilesPage.tsx": 11, "pages/FilesPage.tsx": 11,
+1 -2
View File
@@ -52,14 +52,13 @@
"components/Studio/travel/badgeLook.ts": 2, "components/Studio/travel/badgeLook.ts": 2,
"components/Trips/TripMemberAvatar.tsx": 2, "components/Trips/TripMemberAvatar.tsx": 2,
"components/Vacay/VacayPersons.tsx": 1, "components/Vacay/VacayPersons.tsx": 1,
"components/shared/DialogShell.tsx": 2, "components/shared/DialogShell.tsx": 1,
"components/shared/PasswordChecklist.tsx": 2, "components/shared/PasswordChecklist.tsx": 2,
"mobile/components/MSheet.tsx": 1, "mobile/components/MSheet.tsx": 1,
"mobile/components/MWalletButton.tsx": 1, "mobile/components/MWalletButton.tsx": 1,
"mobile/screens/atlas/MAtlasCountryPopup.tsx": 2, "mobile/screens/atlas/MAtlasCountryPopup.tsx": 2,
"mobile/screens/atlas/hub/MHubTravellers.tsx": 1, "mobile/screens/atlas/hub/MHubTravellers.tsx": 1,
"mobile/screens/collections/MCollEditSheet.tsx": 2, "mobile/screens/collections/MCollEditSheet.tsx": 2,
"mobile/screens/collections/MCollShareSheet.tsx": 1,
"mobile/screens/collections/collectionsMobileModel.ts": 15, "mobile/screens/collections/collectionsMobileModel.ts": 15,
"mobile/screens/dashboard/MDashboard.tsx": 3, "mobile/screens/dashboard/MDashboard.tsx": 3,
"mobile/screens/journey/MJourney.tsx": 2, "mobile/screens/journey/MJourney.tsx": 2,
@@ -28,7 +28,7 @@ export default function AddonSetupDialog({
icon: ReactNode; icon: ReactNode;
eyebrow: string; eyebrow: string;
title: string; title: string;
sub: string; sub?: string;
onClose: () => void; onClose: () => void;
/** A confirmation stacked on top holds the dialog while it is open. */ /** A confirmation stacked on top holds the dialog while it is open. */
blocked?: boolean; blocked?: boolean;
@@ -1,7 +1,7 @@
import { useState, type ReactNode } from 'react' import { useState, type ReactNode } from 'react'
import { import { Wrench, Link, Info,
Blocks, AlertTriangle, RefreshCw, Trash2, Download, Bug, ShieldCheck, UploadCloud, Blocks, AlertTriangle, RefreshCw, Trash2, Download, Bug, ShieldCheck, UploadCloud,
ArrowUpCircle, Github, ExternalLink, Check, Search, Link2, KeyRound, ShieldAlert, ArrowUpCircle, ExternalLink, Check, Search, Link2, KeyRound, ShieldAlert,
SlidersHorizontal, CircleDot, Database, SlidersHorizontal, CircleDot, Database,
Globe, History, Puzzle, Bot, Loader2, Globe, History, Puzzle, Bot, Loader2,
} from 'lucide-react' } from 'lucide-react'
@@ -711,7 +711,7 @@ function InstanceSettingsDialog({ settings, t }: { settings: ReturnType<typeof u
) )
})} })}
{form.actions.length > 0 && ( {form.actions.length > 0 && (
<DialogSection label={t('admin.plugins.actions')}> <DialogSection icon={SlidersHorizontal} label={t('admin.plugins.actions')}>
{!form.active && <SettingsHint className="mb-2">{t('admin.plugins.actions.inactive')}</SettingsHint>} {!form.active && <SettingsHint className="mb-2">{t('admin.plugins.actions.inactive')}</SettingsHint>}
<SettingRows> <SettingRows>
{form.actions.map(a => { {form.actions.map(a => {
@@ -789,7 +789,7 @@ function PluginDetailModal({ item, installed, busy, onInstall, onClose, t, local
footer={( footer={(
<DialogFooter> <DialogFooter>
<Tooltip label={t('admin.plugins.sourceRepo')}> <Tooltip label={t('admin.plugins.sourceRepo')}>
<a href={repoUrl} target="_blank" rel="noreferrer" aria-label={t('admin.plugins.sourceRepo')} className={linkClass}><Github size={15} /></a> <a href={repoUrl} target="_blank" rel="noreferrer" aria-label={t('admin.plugins.sourceRepo')} className={linkClass}><PluginIcon name="Github" size={15} /></a>
</Tooltip> </Tooltip>
<Tooltip label={t('admin.plugins.reportIssue')}> <Tooltip label={t('admin.plugins.reportIssue')}>
<a href={`${repoUrl}/issues`} target="_blank" rel="noreferrer" aria-label={t('admin.plugins.reportIssue')} className={linkClass}><CircleDot size={15} /></a> <a href={`${repoUrl}/issues`} target="_blank" rel="noreferrer" aria-label={t('admin.plugins.reportIssue')} className={linkClass}><CircleDot size={15} /></a>
@@ -826,7 +826,7 @@ function PluginDetailModal({ item, installed, busy, onInstall, onClose, t, local
)} )}
{manifest && ( {manifest && (
<DialogSection label={t('admin.plugins.accessTitle')}> <DialogSection icon={ShieldCheck} label={t('admin.plugins.accessTitle')}>
{access.length === 0 && !permissions.includes('db:own') ? ( {access.length === 0 && !permissions.includes('db:own') ? (
<SettingsHint>{t('admin.plugins.noAccess')}</SettingsHint> <SettingsHint>{t('admin.plugins.noAccess')}</SettingsHint>
) : ( ) : (
@@ -847,7 +847,7 @@ function PluginDetailModal({ item, installed, busy, onInstall, onClose, t, local
this dialog shows it. An admin approving the grant should read the this dialog shows it. An admin approving the grant should read the
names and descriptions first, not discover them in a chat. */} names and descriptions first, not discover them in a chat. */}
{manifest && (manifest.capabilities?.mcpTools?.length ?? 0) > 0 && ( {manifest && (manifest.capabilities?.mcpTools?.length ?? 0) > 0 && (
<DialogSection label={t('admin.plugins.mcpToolsTitle')}> <DialogSection icon={Wrench} label={t('admin.plugins.mcpToolsTitle')}>
<DialogList> <DialogList>
{(manifest.capabilities?.mcpTools ?? []).map(tool => ( {(manifest.capabilities?.mcpTools ?? []).map(tool => (
<DialogListItem key={tool.name} icon={<Bot size={14} />}> <DialogListItem key={tool.name} icon={<Bot size={14} />}>
@@ -869,7 +869,7 @@ function PluginDetailModal({ item, installed, busy, onInstall, onClose, t, local
itemClassName="text-content-secondary text-[length:calc(13px*var(--fs-scale-body,1))]" /> itemClassName="text-content-secondary text-[length:calc(13px*var(--fs-scale-body,1))]" />
{manifest && (egress.length > 0 || manifest.operatorEgress) && ( {manifest && (egress.length > 0 || manifest.operatorEgress) && (
<DialogSection label={t('admin.plugins.connectsTitle')}> <DialogSection icon={Link} label={t('admin.plugins.connectsTitle')}>
<div className="flex flex-wrap items-center gap-1.5"> <div className="flex flex-wrap items-center gap-1.5">
{egress.map(h => ( {egress.map(h => (
<code key={h} className="rounded-full bg-info-soft px-2.5 py-1 font-mono text-info" style={fs(11.5)}>{h}</code> <code key={h} className="rounded-full bg-info-soft px-2.5 py-1 font-mono text-info" style={fs(11.5)}>{h}</code>
@@ -887,7 +887,7 @@ function PluginDetailModal({ item, installed, busy, onInstall, onClose, t, local
)} )}
{manifest && settings.length > 0 && ( {manifest && settings.length > 0 && (
<DialogSection label={t('admin.plugins.setupTitle')}> <DialogSection icon={SlidersHorizontal} label={t('admin.plugins.setupTitle')}>
<DialogList> <DialogList>
{settings.map(s => ( {settings.map(s => (
<DialogListItem key={s.key} <DialogListItem key={s.key}
@@ -904,7 +904,7 @@ function PluginDetailModal({ item, installed, busy, onInstall, onClose, t, local
</DialogSection> </DialogSection>
)} )}
<DialogSection label={t('admin.plugins.detailsTitle')}> <DialogSection icon={Info} label={t('admin.plugins.detailsTitle')}>
<div className="grid grid-cols-2 gap-2 max-sm:grid-cols-1"> <div className="grid grid-cols-2 gap-2 max-sm:grid-cols-1">
{item.latest && <Meta k={t('admin.plugins.metaVersion')} v={`v${item.latest}`} />} {item.latest && <Meta k={t('admin.plugins.metaVersion')} v={`v${item.latest}`} />}
{sizeKb !== null && <Meta k={t('admin.plugins.metaSize')} v={`${sizeKb} KB`} />} {sizeKb !== null && <Meta k={t('admin.plugins.metaSize')} v={`${sizeKb} KB`} />}
@@ -923,7 +923,7 @@ function PluginDetailModal({ item, installed, busy, onInstall, onClose, t, local
{/* Every published version, installable individually. The compat verdict per {/* Every published version, installable individually. The compat verdict per
version is SERVER-computed — an incompatible one is explained, never offered. */} version is SERVER-computed — an incompatible one is explained, never offered. */}
{(detail?.versions?.length ?? 0) > 1 && ( {(detail?.versions?.length ?? 0) > 1 && (
<DialogSection label={t('admin.plugins.versionsTitle')}> <DialogSection icon={History} label={t('admin.plugins.versionsTitle')}>
<DialogList> <DialogList>
{detail!.versions!.map(v => ( {detail!.versions!.map(v => (
<DialogListItem key={v.version} <DialogListItem key={v.version}
@@ -1105,7 +1105,7 @@ function UpdateConsentDialog({ data, unsigned, t, onApprove, onLater }: {
this informs, it does not block. */} this informs, it does not block. */}
{unsigned && <WarnNote icon={<ShieldAlert size={13} />}>{t('admin.plugins.sig.consentUnsigned')}</WarnNote>} {unsigned && <WarnNote icon={<ShieldAlert size={13} />}>{t('admin.plugins.sig.consentUnsigned')}</WarnNote>}
{data.newPermissions.length > 0 && ( {data.newPermissions.length > 0 && (
<DialogSection label={t('admin.plugins.updateNewPermissions')}> <DialogSection icon={ShieldCheck} label={t('admin.plugins.updateNewPermissions')}>
<DialogList> <DialogList>
{data.newPermissions.map(perm => ( {data.newPermissions.map(perm => (
<DialogListItem key={perm} icon={<Check size={14} className="text-warning" />}><PermLabel perm={perm} t={t} /></DialogListItem> <DialogListItem key={perm} icon={<Check size={14} className="text-warning" />}><PermLabel perm={perm} t={t} /></DialogListItem>
@@ -1114,7 +1114,7 @@ function UpdateConsentDialog({ data, unsigned, t, onApprove, onLater }: {
</DialogSection> </DialogSection>
)} )}
{data.newEgress.length > 0 && ( {data.newEgress.length > 0 && (
<DialogSection label={t('admin.plugins.updateNewEgress')}> <DialogSection icon={Globe} label={t('admin.plugins.updateNewEgress')}>
<div className="flex flex-wrap gap-1.5"> <div className="flex flex-wrap gap-1.5">
{data.newEgress.map(host => ( {data.newEgress.map(host => (
<code key={host} className="rounded-full bg-info-soft px-2.5 py-1 font-mono text-info" style={fs(11.5)}>{host}</code> <code key={host} className="rounded-full bg-info-soft px-2.5 py-1 font-mono text-info" style={fs(11.5)}>{host}</code>
@@ -210,11 +210,8 @@ describe('BackupPanel', () => {
await waitFor(() => { await waitFor(() => {
expect(screen.getByText('backup-2025-01-15.zip')).toBeInTheDocument() expect(screen.getByText('backup-2025-01-15.zip')).toBeInTheDocument()
}) })
const trashBtn = Array.from(document.querySelectorAll('button')).find( const trashBtn = screen.getByRole('button', { name: 'Delete' })
b => b.querySelector('svg.lucide-trash2'), await user.click(trashBtn)
) as HTMLElement
expect(trashBtn).toBeTruthy()
await user.click(trashBtn!)
// The question is the shared confirm dialog now, not window.confirm // The question is the shared confirm dialog now, not window.confirm
expect(await screen.findByText('Delete backup "backup-2025-01-15.zip"?')).toBeInTheDocument() expect(await screen.findByText('Delete backup "backup-2025-01-15.zip"?')).toBeInTheDocument()
const deleteButtons = screen.getAllByRole('button', { name: 'Delete' }) const deleteButtons = screen.getAllByRole('button', { name: 'Delete' })
@@ -428,9 +425,7 @@ describe('BackupPanel', () => {
render(<><ToastContainer /><BackupPanel /></>) render(<><ToastContainer /><BackupPanel /></>)
await screen.findByText('backup-2025-01-15.zip') await screen.findByText('backup-2025-01-15.zip')
const trashBtn = Array.from(document.querySelectorAll('button')).find( const trashBtn = screen.getByRole('button', { name: 'Delete' })
b => b.querySelector('svg.lucide-trash2'),
) as HTMLElement
await user.click(trashBtn) await user.click(trashBtn)
await user.click(await screen.findByRole('button', { name: 'Cancel' })) await user.click(await screen.findByRole('button', { name: 'Cancel' }))
expect(deleteCalls).toBe(0) expect(deleteCalls).toBe(0)
@@ -1,5 +1,5 @@
import { useId } from 'react' import { useId } from 'react'
import { Plus, Pencil, Trash2, Pipette, Tags, Loader2 } from 'lucide-react' import { Shapes, Palette, Eye, Plus, Pencil, Trash2, Pipette, Tags, Loader2 } from 'lucide-react'
import { DialogButton, DialogFooter, DialogHeader, DialogSection, DialogShell, DialogTile, FooterSpacer, NEUTRAL_TINT, fs } from '../shared/DialogShell' import { DialogButton, DialogFooter, DialogHeader, DialogSection, DialogShell, DialogTile, FooterSpacer, NEUTRAL_TINT, fs } from '../shared/DialogShell'
import { Tooltip } from '../shared/Tooltip' import { Tooltip } from '../shared/Tooltip'
import ConfirmDialog from '../shared/ConfirmDialog' import ConfirmDialog from '../shared/ConfirmDialog'
@@ -52,7 +52,7 @@ export default function CategoryManager() {
</DialogFooter> </DialogFooter>
} }
> >
<DialogSection label={t('categories.icon')}> <DialogSection icon={Shapes} label={t('categories.icon')}>
<div className="max-h-52 overflow-y-auto rounded-[14px] border border-edge-faint bg-surface-secondary p-2"> <div className="max-h-52 overflow-y-auto rounded-[14px] border border-edge-faint bg-surface-secondary p-2">
<div className="grid grid-cols-[repeat(auto-fill,minmax(38px,1fr))] gap-1"> <div className="grid grid-cols-[repeat(auto-fill,minmax(38px,1fr))] gap-1">
{ICON_NAMES.map(name => { {ICON_NAMES.map(name => {
@@ -79,7 +79,7 @@ export default function CategoryManager() {
</div> </div>
</DialogSection> </DialogSection>
<DialogSection label={t('categories.color')}> <DialogSection icon={Palette} label={t('categories.color')}>
<div className="flex flex-wrap items-center gap-2"> <div className="flex flex-wrap items-center gap-2">
{PRESET_COLORS.map(color => ( {PRESET_COLORS.map(color => (
<button key={color} type="button" onClick={() => setForm(prev => ({ ...prev, color }))} <button key={color} type="button" onClick={() => setForm(prev => ({ ...prev, color }))}
@@ -116,7 +116,7 @@ export default function CategoryManager() {
</div> </div>
</DialogSection> </DialogSection>
<DialogSection label={t('categories.preview')}> <DialogSection icon={Eye} label={t('categories.preview')}>
<div className="flex items-center rounded-[14px] border border-edge-faint bg-surface-secondary px-3.5 py-3"> <div className="flex items-center rounded-[14px] border border-edge-faint bg-surface-secondary px-3.5 py-3">
<span className="inline-flex min-w-0 max-w-full items-center gap-1.5 truncate rounded-full px-2.5 py-1 font-semibold" <span className="inline-flex min-w-0 max-w-full items-center gap-1.5 truncate rounded-full px-2.5 py-1 font-semibold"
style={{ ...fs(12.5, 'body'), backgroundColor: `${form.color}20`, color: form.color }}> style={{ ...fs(12.5, 'body'), backgroundColor: `${form.color}20`, color: form.color }}>
@@ -1,3 +1,4 @@
import { focusRevealedEditor } from '../shared/dialogFocus'
import { useTranslation } from '../../i18n' import { useTranslation } from '../../i18n'
import { Plus, Trash2, Pencil, Package, X, Check, ChevronRight, FolderPlus, Loader2 } from 'lucide-react' import { Plus, Trash2, Pencil, Package, X, Check, ChevronRight, FolderPlus, Loader2 } from 'lucide-react'
import { fs } from '../shared/DialogShell' import { fs } from '../shared/DialogShell'
@@ -57,7 +58,7 @@ export default function PackingTemplateManager() {
{showCreate && ( {showCreate && (
<div className={COMPOSER_ROW} style={{ boxShadow: COMPOSER.boxShadow }}> <div className={COMPOSER_ROW} style={{ boxShadow: COMPOSER.boxShadow }}>
<Package size={15} className="flex-none text-content-faint" /> <Package size={15} className="flex-none text-content-faint" />
<input autoFocus value={createName} onChange={e => setCreateName(e.target.value)} <input ref={focusRevealedEditor} value={createName} onChange={e => setCreateName(e.target.value)}
onKeyDown={e => { if (e.key === 'Enter') void handleCreateTemplate(); if (e.key === 'Escape') setShowCreate(false) }} onKeyDown={e => { if (e.key === 'Enter') void handleCreateTemplate(); if (e.key === 'Escape') setShowCreate(false) }}
placeholder={t('admin.packingTemplates.namePlaceholder')} className={COMPOSER_INPUT} style={fs(13, 'body')} /> placeholder={t('admin.packingTemplates.namePlaceholder')} className={COMPOSER_INPUT} style={fs(13, 'body')} />
<Tooltip label={t('common.save')}> <Tooltip label={t('common.save')}>
@@ -101,7 +102,7 @@ export default function PackingTemplateManager() {
<Package size={15} strokeWidth={1.9} /> <Package size={15} strokeWidth={1.9} />
</span> </span>
{editingTemplate === tmpl.id ? ( {editingTemplate === tmpl.id ? (
<input autoFocus value={editTemplateName} onChange={e => setEditTemplateName(e.target.value)} <input ref={focusRevealedEditor} value={editTemplateName} onChange={e => setEditTemplateName(e.target.value)}
onBlur={() => handleRenameTemplate(tmpl.id)} onBlur={() => handleRenameTemplate(tmpl.id)}
onKeyDown={e => { if (e.key === 'Enter') void handleRenameTemplate(tmpl.id); if (e.key === 'Escape') setEditingTemplate(null) }} onKeyDown={e => { if (e.key === 'Enter') void handleRenameTemplate(tmpl.id); if (e.key === 'Escape') setEditingTemplate(null) }}
aria-label={t('common.rename')} aria-label={t('common.rename')}
@@ -132,7 +133,7 @@ export default function PackingTemplateManager() {
{/* Category header */} {/* Category header */}
<div data-row="category" className="flex items-center gap-1.5 border-b border-edge-faint bg-surface-tertiary py-1.5 ps-3 pe-1.5"> <div data-row="category" className="flex items-center gap-1.5 border-b border-edge-faint bg-surface-tertiary py-1.5 ps-3 pe-1.5">
{editingCatId === cat.id ? ( {editingCatId === cat.id ? (
<input autoFocus value={editCatName} onChange={e => setEditCatName(e.target.value)} <input ref={focusRevealedEditor} value={editCatName} onChange={e => setEditCatName(e.target.value)}
onBlur={() => handleRenameCategory(cat.id)} onBlur={() => handleRenameCategory(cat.id)}
onKeyDown={e => { if (e.key === 'Enter') void handleRenameCategory(cat.id); if (e.key === 'Escape') setEditingCatId(null) }} onKeyDown={e => { if (e.key === 'Enter') void handleRenameCategory(cat.id); if (e.key === 'Escape') setEditingCatId(null) }}
aria-label={t('common.rename')} aria-label={t('common.rename')}
@@ -162,7 +163,7 @@ export default function PackingTemplateManager() {
<div key={item.id} data-row="item" className="group flex min-h-[40px] items-center gap-2 py-1.5 ps-3 pe-1.5"> <div key={item.id} data-row="item" className="group flex min-h-[40px] items-center gap-2 py-1.5 ps-3 pe-1.5">
{editingItemId === item.id ? ( {editingItemId === item.id ? (
<> <>
<input autoFocus value={editItemName} onChange={e => setEditItemName(e.target.value)} <input ref={focusRevealedEditor} value={editItemName} onChange={e => setEditItemName(e.target.value)}
onKeyDown={e => { if (e.key === 'Enter') void handleRenameItem(item.id); if (e.key === 'Escape') setEditingItemId(null) }} onKeyDown={e => { if (e.key === 'Enter') void handleRenameItem(item.id); if (e.key === 'Escape') setEditingItemId(null) }}
aria-label={t('common.rename')} aria-label={t('common.rename')}
className={`${ROW_INPUT} flex-1`} style={fs(12.5, 'body')} /> className={`${ROW_INPUT} flex-1`} style={fs(12.5, 'body')} />
@@ -219,7 +220,7 @@ export default function PackingTemplateManager() {
{/* Add category */} {/* Add category */}
{addingCategory ? ( {addingCategory ? (
<div className={COMPOSER_ROW} style={{ boxShadow: COMPOSER.boxShadow }}> <div className={COMPOSER_ROW} style={{ boxShadow: COMPOSER.boxShadow }}>
<input autoFocus value={newCatName} onChange={e => setNewCatName(e.target.value)} <input ref={focusRevealedEditor} value={newCatName} onChange={e => setNewCatName(e.target.value)}
onKeyDown={e => { if (e.key === 'Enter') void handleAddCategory(); if (e.key === 'Escape') { setAddingCategory(false); setNewCatName('') } }} onKeyDown={e => { if (e.key === 'Enter') void handleAddCategory(); if (e.key === 'Escape') { setAddingCategory(false); setNewCatName('') } }}
placeholder={t('admin.packingTemplates.categoryName')} placeholder={t('admin.packingTemplates.categoryName')}
className={COMPOSER_INPUT} style={fs(13, 'body')} /> className={COMPOSER_INPUT} style={fs(13, 'body')} />
@@ -50,7 +50,7 @@ export default function PermissionsPanel(): React.ReactElement {
> >
<div className={`flex flex-col gap-5 transition-opacity ${saving ? 'opacity-60' : ''}`}> <div className={`flex flex-col gap-5 transition-opacity ${saving ? 'opacity-60' : ''}`}>
{CATEGORIES.map(cat => ( {CATEGORIES.map(cat => (
<DialogSection key={cat.id} label={t(`perm.cat.${cat.id}`)}> <DialogSection icon={ShieldCheck} key={cat.id} label={t(`perm.cat.${cat.id}`)}>
<SettingRows> <SettingRows>
{cat.keys.map(key => { {cat.keys.map(key => {
const entry = entryMap.get(key) const entry = entryMap.get(key)
@@ -67,7 +67,7 @@ function Catalog() {
}}> }}>
<div className={GRID_2}> <div className={GRID_2}>
<EditorField label={t('schoolCatalog.country')} htmlFor={`${fieldId}-name`}> <EditorField label={t('schoolCatalog.country')} htmlFor={`${fieldId}-name`}>
<input id={`${fieldId}-name`} autoFocus required maxLength={100} className={INPUT} value={name} onChange={event => setName(event.target.value)} /> <input id={`${fieldId}-name`} data-initial-focus required maxLength={100} className={INPUT} value={name} onChange={event => setName(event.target.value)} />
</EditorField> </EditorField>
<EditorField label={t('schoolCatalog.code')} htmlFor={`${fieldId}-code`}> <EditorField label={t('schoolCatalog.code')} htmlFor={`${fieldId}-code`}>
<input id={`${fieldId}-code`} required pattern="[A-Z]{2}" maxLength={2} className={`${INPUT} font-geist uppercase tracking-[.08em]`} value={code} onChange={event => setCode(event.target.value.toUpperCase())} placeholder="US" /> <input id={`${fieldId}-code`} required pattern="[A-Z]{2}" maxLength={2} className={`${INPUT} font-geist uppercase tracking-[.08em]`} value={code} onChange={event => setCode(event.target.value.toUpperCase())} placeholder="US" />
@@ -62,7 +62,7 @@ export default function SchoolHolidayRegionEditor({ region, busy, offline = fals
<div className={BODY}> <div className={BODY}>
<fieldset disabled={busy || offline} className={`m-0 flex min-w-0 flex-col gap-5 border-0 p-0 ${busy ? 'opacity-60' : ''}`}> <fieldset disabled={busy || offline} className={`m-0 flex min-w-0 flex-col gap-5 border-0 p-0 ${busy ? 'opacity-60' : ''}`}>
<EditorField label={t('schoolCatalog.region')} htmlFor={`${fieldId}-region`}> <EditorField label={t('schoolCatalog.region')} htmlFor={`${fieldId}-region`}>
<input id={`${fieldId}-region`} autoFocus required maxLength={150} className={INPUT} value={name} onChange={event => setName(event.target.value)} /> <input id={`${fieldId}-region`} data-initial-focus required maxLength={150} className={INPUT} value={name} onChange={event => setName(event.target.value)} />
</EditorField> </EditorField>
<SettingsHint>{t('schoolCatalog.periodHint')}</SettingsHint> <SettingsHint>{t('schoolCatalog.periodHint')}</SettingsHint>
{holidays.map((holiday, index) => { {holidays.map((holiday, index) => {
@@ -1,4 +1,4 @@
import { Check, Loader2, Sparkles } from 'lucide-react'; import { Check, CreditCard, Loader2, Settings2, Sparkles, Unplug } from 'lucide-react';
import React, { useId, useState } from 'react'; import React, { useId, useState } from 'react';
import { useTranslation } from '../../../i18n'; import { useTranslation } from '../../../i18n';
import ToggleSwitch from '../../Settings/ToggleSwitch'; import ToggleSwitch from '../../Settings/ToggleSwitch';
@@ -11,6 +11,7 @@ import {
DialogButton, DialogButton,
DialogFooter, DialogFooter,
DialogHeader, DialogHeader,
DialogSection,
DialogShell, DialogShell,
DialogTile, DialogTile,
FooterSpacer, FooterSpacer,
@@ -25,17 +26,12 @@ import { POLICY_CHOICES, useAiAdminConfig } from './useAiAdminConfig';
type AiAdmin = ReturnType<typeof useAiAdminConfig>; type AiAdmin = ReturnType<typeof useAiAdminConfig>;
const EYEBROW = 'font-geist font-bold uppercase tracking-[.08em] text-content-faint'; /** The instance's payment policy, with room for each translated option. */
/** Who pays, as three rows to pick one from: the labels are too long for a segmented track in a shelf. */
function PolicyChoice({ A }: { A: AiAdmin }) { function PolicyChoice({ A }: { A: AiAdmin }) {
const { t } = useTranslation(); const { t } = useTranslation();
return ( return (
<div className="flex flex-col gap-2"> <DialogSection icon={CreditCard} label={t('assistant.admin.policy')}>
<span className={EYEBROW} style={fs(9.5)}> <div role="radiogroup" aria-label={t('assistant.admin.policy')} className="grid gap-2 sm:grid-cols-3">
{t('assistant.admin.policy')}
</span>
<div role="radiogroup" aria-label={t('assistant.admin.policy')} className="flex flex-col gap-1.5">
{POLICY_CHOICES.map((choice) => { {POLICY_CHOICES.map((choice) => {
const on = A.policy === choice.value; const on = A.policy === choice.value;
return ( return (
@@ -45,7 +41,7 @@ function PolicyChoice({ A }: { A: AiAdmin }) {
role="radio" role="radio"
aria-checked={on} aria-checked={on}
onClick={() => A.setPolicy(choice.value)} onClick={() => A.setPolicy(choice.value)}
className={`flex items-center gap-2 rounded-[10px] border px-3 py-2 text-start transition-colors ${on ? 'border-[color:var(--text-primary)] bg-surface-card shadow-sm' : 'border-edge bg-surface-card hover:border-edge-secondary'}`} className={`flex min-h-11 items-center gap-2 rounded-xl border bg-surface-input px-3 py-2 text-start transition-colors ${on ? 'border-[color:var(--text-primary)]' : 'border-edge-faint hover:bg-surface-hover'}`}
> >
<span <span
className={`min-w-0 flex-1 font-medium ${on ? 'text-content' : 'text-content-muted'}`} className={`min-w-0 flex-1 font-medium ${on ? 'text-content' : 'text-content-muted'}`}
@@ -58,8 +54,8 @@ function PolicyChoice({ A }: { A: AiAdmin }) {
); );
})} })}
</div> </div>
{A.policyHintKey && <SettingsHint>{t(A.policyHintKey)}</SettingsHint>} {A.policyHintKey && <SettingsHint className="mt-2">{t(A.policyHintKey)}</SettingsHint>}
</div> </DialogSection>
); );
} }
@@ -71,7 +67,7 @@ function LiveConnection({ A }: { A: AiAdmin }) {
const status = CONNECTION_STATUS[live.status]; const status = CONNECTION_STATUS[live.status];
return ( return (
<div <div
className={`flex flex-col gap-3 rounded-[12px] border border-edge-faint bg-surface-card p-3 ${busy ? 'opacity-60' : ''}`} className={`flex flex-col gap-3 rounded-[12px] border border-edge-faint bg-surface-input p-3 ${busy ? 'opacity-60' : ''}`}
> >
<div className="flex items-center gap-2.5"> <div className="flex items-center gap-2.5">
<ProviderMark kind={live.kind} /> <ProviderMark kind={live.kind} />
@@ -114,21 +110,23 @@ function InstanceConnection({ A }: { A: AiAdmin }) {
const { t } = useTranslation(); const { t } = useTranslation();
const { live, connection, replacing, cancelReplace, onConnected } = A.instance; const { live, connection, replacing, cancelReplace, onConnected } = A.instance;
return ( return (
<div className="flex flex-col gap-2.5"> <DialogSection
<span className={EYEBROW} style={fs(9.5)}> icon={Unplug}
{t('assistant.admin.connection')} label={t('assistant.admin.connection')}
</span> action={!live && <StatusPill>{t('assistant.admin.connectionNone')}</StatusPill>}
{!replacing && <LiveConnection A={A} />} >
{!live && <SettingsHint>{t('assistant.admin.connectionNone')}</SettingsHint>} <div className="flex flex-col gap-2.5">
{A.showPanel && ( {!replacing && <LiveConnection A={A} />}
<AiConnectPanel scope="instance" onConnected={onConnected} prefill={connection?.prefill ?? null} /> {A.showPanel && (
)} <AiConnectPanel scope="instance" onConnected={onConnected} prefill={connection?.prefill ?? null} />
{replacing && ( )}
<button type="button" onClick={cancelReplace} className={`${SETTINGS_BUTTON} self-start`}> {replacing && (
{t('common.cancel')} <button type="button" onClick={cancelReplace} className={`${SETTINGS_BUTTON} self-start`}>
</button> {t('common.cancel')}
)} </button>
</div> )}
</div>
</DialogSection>
); );
} }
@@ -229,8 +227,6 @@ export default function AiSettingsDialog({
labelId={labelId} labelId={labelId}
eyebrow={t('admin.addons.ai.name')} eyebrow={t('admin.addons.ai.name')}
title={t('admin.addons.ai.setup')} title={t('admin.addons.ai.setup')}
sub={t('admin.addons.ai.dialogSub')}
subWraps
onClose={onClose} onClose={onClose}
/> />
} }
@@ -258,7 +254,11 @@ export default function AiSettingsDialog({
{A.instancePays && <InstanceConnection A={A} />} {A.instancePays && <InstanceConnection A={A} />}
</div> </div>
)} )}
{shown === 'assistant' && <AssistantLimits A={A} />} {shown === 'assistant' && (
<DialogSection icon={Settings2} label={t('admin.addons.catalog.ai_assistant.name')}>
<AssistantLimits A={A} />
</DialogSection>
)}
{shown === 'parsing' && parsing && ( {shown === 'parsing' && parsing && (
<ParsingSettings addon={parsing} A={A} onOpenConnection={() => setTab('connection')} /> <ParsingSettings addon={parsing} A={A} onOpenConnection={() => setTab('connection')} />
)} )}
@@ -1,5 +1,5 @@
import { asLlmVision, LLM_VISION_MODES, type LlmVision } from '@trek/shared'; import { asLlmVision, LLM_VISION_MODES, type LlmVision } from '@trek/shared';
import { Check, RefreshCw } from 'lucide-react'; import { Bot, Check, Image, RefreshCw } from 'lucide-react';
import React, { useId } from 'react'; import React, { useId } from 'react';
import { useTranslation } from '../../../i18n'; import { useTranslation } from '../../../i18n';
import { ProviderMark } from '../../Settings/ai/AiConnectPanel'; import { ProviderMark } from '../../Settings/ai/AiConnectPanel';
@@ -313,15 +313,15 @@ export default function ParsingSettings({
(P.ownConnection ? P.savedProvider : A.instance.live?.kind === 'custom' ? 'local' : 'cloud') === 'local'; (P.ownConnection ? P.savedProvider : A.instance.live?.kind === 'custom' ? 'local' : 'cloud') === 'local';
return ( return (
<div className="flex flex-col gap-5"> <div className="flex flex-col gap-5">
<DialogSection label={t('admin.addons.ai.parsing.readsWith')}> <DialogSection icon={Bot} label={t('admin.addons.ai.parsing.readsWith')}>
<ParsingSource A={A} P={P} onOpenConnection={onOpenConnection} /> <ParsingSource A={A} P={P} onOpenConnection={onOpenConnection} />
</DialogSection> </DialogSection>
{P.formOpen && ( {P.formOpen && (
<DialogSection label={t('admin.addons.ai.parsing.own')}> <DialogSection icon={Bot} label={t('admin.addons.ai.parsing.own')}>
<OwnConnectionForm P={P} /> <OwnConnectionForm P={P} />
</DialogSection> </DialogSection>
)} )}
<DialogSection label={t('settings.aiParsing.multimodal')}> <DialogSection icon={Image} label={t('settings.aiParsing.multimodal')}>
<Segmented<LlmVision> <Segmented<LlmVision>
label={t('settings.aiParsing.multimodal')} label={t('settings.aiParsing.multimodal')}
value={P.vision} value={P.vision}
@@ -1,11 +1,11 @@
import type { PaddleRegionAutoMode, PaddleRegionPending } from '@trek/shared'; import type { PaddleRegionAutoMode, PaddleRegionPending } from '@trek/shared';
import { Ban, CloudDownload, Hand, Loader2, Power, Sparkles } from 'lucide-react'; import { Ban, CloudDownload, Hand, Inbox, Loader2, Power, Sparkles } from 'lucide-react';
import { useDateFormat } from '../../../hooks/useDateFormat'; import { useDateFormat } from '../../../hooks/useDateFormat';
import { useTranslation } from '../../../i18n'; import { useTranslation } from '../../../i18n';
import { formatDisplayDate } from '../../../utils/dateFormat'; import { formatDisplayDate } from '../../../utils/dateFormat';
import { ChoiceChips, SettingRows, SETTINGS_BUTTON, SettingsHint, StatusPill } from '../../Settings/settingsKit'; import { ChoiceChips, SettingRows, SETTINGS_BUTTON, SettingsHint, StatusPill } from '../../Settings/settingsKit';
import { LABEL, Segmented } from '../../shared/dialogParts'; import { LABEL, Segmented } from '../../shared/dialogParts';
import { fs } from '../../shared/DialogShell'; import { DialogSection, fs } from '../../shared/DialogShell';
import { Tooltip } from '../../shared/Tooltip'; import { Tooltip } from '../../shared/Tooltip';
import { AUTO_LOAD_MODES, autoLoadSizes, formatMegabytes } from './paddleRegionsModel'; import { AUTO_LOAD_MODES, autoLoadSizes, formatMegabytes } from './paddleRegionsModel';
import type { usePaddleRegionsAdmin } from './usePaddleRegionsAdmin'; import type { usePaddleRegionsAdmin } from './usePaddleRegionsAdmin';
@@ -33,39 +33,48 @@ export function AutoLoadSettings({ admin }: { admin: Admin }) {
if (!settings) return null; if (!settings) return null;
const sizes = autoLoadSizes(settings.max_mb); const sizes = autoLoadSizes(settings.max_mb);
return ( return (
<div data-testid="paddle-auto-load" className="flex min-w-0 flex-col gap-2.5"> <div data-testid="paddle-auto-load">
<div className="min-w-0"> <DialogSection icon={CloudDownload} label={t('admin.paddleRegions.auto.title')}>
<span className={LABEL}>{t('admin.paddleRegions.auto.title')}</span> <div className="flex min-w-0 flex-col gap-3">
<fieldset disabled={saving} className="m-0 min-w-0 border-0 p-0"> <div className="min-w-0">
<Segmented<PaddleRegionAutoMode> <fieldset
value={settings.mode} disabled={saving}
onChange={(mode) => void save({ mode })} className="m-0 min-w-0 border-0 p-0 [&>[role=group]]:bg-[color:var(--bg-selected)]"
label={t('admin.paddleRegions.auto.title')} >
fill <Segmented<PaddleRegionAutoMode>
options={AUTO_LOAD_MODES.map((mode) => { value={settings.mode}
const Icon = MODE_ICONS[mode]; onChange={(mode) => void save({ mode })}
return { label={t('admin.paddleRegions.auto.title')}
value: mode, fill
label: t(`admin.paddleRegions.auto.mode.${mode}`), options={AUTO_LOAD_MODES.map((mode) => {
icon: <Icon size={13} strokeWidth={2} aria-hidden="true" />, const Icon = MODE_ICONS[mode];
}; return {
})} value: mode,
/> label: t(`admin.paddleRegions.auto.mode.${mode}`),
</fieldset> icon: <Icon size={13} strokeWidth={2} aria-hidden="true" />,
<SettingsHint className="mt-1.5">{t(`admin.paddleRegions.auto.modeHint.${settings.mode}`)}</SettingsHint> };
</div> })}
{settings.mode === 'auto' && ( />
<fieldset disabled={saving} className="m-0 min-w-0 border-0 p-0"> </fieldset>
<span className={LABEL}>{t('admin.paddleRegions.auto.maxSize')}</span> <SettingsHint className="mt-1.5">{t(`admin.paddleRegions.auto.modeHint.${settings.mode}`)}</SettingsHint>
<ChoiceChips<string> </div>
value={String(settings.max_mb)} {settings.mode === 'auto' && (
label={t('admin.paddleRegions.auto.maxSize')} <fieldset
onChange={(value) => void save({ max_mb: Number(value) })} disabled={saving}
options={sizes.map((mb) => ({ value: String(mb), label: megabytes(mb) }))} className="m-0 min-w-0 border-0 p-0 [&_[aria-pressed=false]]:bg-surface-input [&_[aria-pressed=true]]:bg-accent [&_[aria-pressed=true]]:text-accent-text"
/> >
<SettingsHint className="mt-1.5">{t('admin.paddleRegions.auto.maxSizeHint')}</SettingsHint> <span className={LABEL}>{t('admin.paddleRegions.auto.maxSize')}</span>
</fieldset> <ChoiceChips<string>
)} value={String(settings.max_mb)}
label={t('admin.paddleRegions.auto.maxSize')}
onChange={(value) => void save({ max_mb: Number(value) })}
options={sizes.map((mb) => ({ value: String(mb), label: megabytes(mb) }))}
/>
<SettingsHint className="mt-1.5">{t('admin.paddleRegions.auto.maxSizeHint')}</SettingsHint>
</fieldset>
)}
</div>
</DialogSection>
</div> </div>
); );
} }
@@ -132,16 +141,18 @@ export function RequestList({ admin }: { admin: Admin }) {
const ordered = [...admin.requests].sort((a, b) => Number(a.declined) - Number(b.declined)); const ordered = [...admin.requests].sort((a, b) => Number(a.declined) - Number(b.declined));
const open = admin.requests.filter((request) => !request.declined).length; const open = admin.requests.filter((request) => !request.declined).length;
return ( return (
<div className="flex min-w-0 flex-col gap-2" data-testid="paddle-region-requests"> <div data-testid="paddle-region-requests">
<span className={`${LABEL} mb-0 flex items-center gap-1.5`}> <DialogSection
{t('admin.paddleRegions.requests.title')} icon={Inbox}
{open > 0 && <StatusPill tone="warning">{open}</StatusPill>} label={t('admin.paddleRegions.requests.title')}
</span> action={open > 0 && <StatusPill tone="warning">{open}</StatusPill>}
<SettingRows> >
{ordered.map((request) => ( <SettingRows>
<RequestRow key={request.id} request={request} admin={admin} /> {ordered.map((request) => (
))} <RequestRow key={request.id} request={request} admin={admin} />
</SettingRows> ))}
</SettingRows>
</DialogSection>
</div> </div>
); );
} }
@@ -1,6 +1,18 @@
import type { PaddleRegion, PaddleRegionCatalogEntry } from '@trek/shared'; import type { PaddleRegion, PaddleRegionCatalogEntry } from '@trek/shared';
import { Check, ChevronRight, Loader2, Plus, RefreshCw, Search, Trash2, Waves, WifiOff } from 'lucide-react'; import {
import { useId, useState } from 'react'; Check,
ChevronRight,
Info,
Loader2,
MapPin,
Plus,
RefreshCw,
Search,
Trash2,
Waves,
WifiOff,
} from 'lucide-react';
import { useState } from 'react';
import { useDateFormat } from '../../../hooks/useDateFormat'; import { useDateFormat } from '../../../hooks/useDateFormat';
import { useTranslation } from '../../../i18n'; import { useTranslation } from '../../../i18n';
import { formatDisplayDate } from '../../../utils/dateFormat'; import { formatDisplayDate } from '../../../utils/dateFormat';
@@ -12,8 +24,8 @@ import {
StatusPill, StatusPill,
} from '../../Settings/settingsKit'; } from '../../Settings/settingsKit';
import ConfirmDialog from '../../shared/ConfirmDialog'; import ConfirmDialog from '../../shared/ConfirmDialog';
import { EditorField, INPUT } from '../../shared/dialogParts'; import { INPUT } from '../../shared/dialogParts';
import { fs } from '../../shared/DialogShell'; import { DialogSection, fs } from '../../shared/DialogShell';
import ErrorBoundary from '../../shared/ErrorBoundary'; import ErrorBoundary from '../../shared/ErrorBoundary';
import { Tooltip } from '../../shared/Tooltip'; import { Tooltip } from '../../shared/Tooltip';
import AddonSetupDialog from '../AddonSetupDialog'; import AddonSetupDialog from '../AddonSetupDialog';
@@ -64,7 +76,6 @@ function Panel() {
icon={<Waves size={20} strokeWidth={2} />} icon={<Waves size={20} strokeWidth={2} />}
eyebrow={t('admin.addons.catalog.tours.name')} eyebrow={t('admin.addons.catalog.tours.name')}
title={title} title={title}
sub={t('admin.paddleRegions.hint')}
onClose={close} onClose={close}
blocked={admin.removing !== null} blocked={admin.removing !== null}
> >
@@ -105,10 +116,20 @@ function PanelBody({ admin }: { admin: Admin }) {
<fieldset disabled={admin.offline} className="m-0 flex min-w-0 flex-col gap-4 border-0 p-0"> <fieldset disabled={admin.offline} className="m-0 flex min-w-0 flex-col gap-4 border-0 p-0">
<AutoLoadSettings admin={admin} /> <AutoLoadSettings admin={admin} />
<RequestList admin={admin} /> <RequestList admin={admin} />
<CatalogSearch admin={admin} /> <DialogSection icon={MapPin} label={t('admin.paddleRegions.search')}>
<RegionList admin={admin} /> <div className="flex flex-col gap-3">
<CatalogSearch admin={admin} />
<RegionList admin={admin} />
</div>
</DialogSection>
</fieldset> </fieldset>
<SettingsHint>{t('admin.paddleRegions.attribution')}</SettingsHint> <div role="note" className="flex items-start gap-2.5 px-1">
<Info size={15} className="mt-0.5 shrink-0 text-content-muted" aria-hidden />
<div className="flex flex-col gap-1">
<SettingsHint>{t('admin.paddleRegions.hint')}</SettingsHint>
<SettingsHint>{t('admin.paddleRegions.attribution')}</SettingsHint>
</div>
</div>
<ConfirmDialog <ConfirmDialog
isOpen={admin.removing !== null} isOpen={admin.removing !== null}
onClose={admin.cancelRemove} onClose={admin.cancelRemove}
@@ -138,28 +159,25 @@ function RegionPath({ hit }: { hit: PaddleRegionCatalogEntry }) {
function CatalogSearch({ admin }: { admin: Admin }) { function CatalogSearch({ admin }: { admin: Admin }) {
const { t } = useTranslation(); const { t } = useTranslation();
const id = useId();
const { search } = admin; const { search } = admin;
return ( return (
<div className="flex flex-col gap-2"> <div className="flex flex-col gap-2">
<EditorField label={t('admin.paddleRegions.search')} htmlFor={id}> <div className="relative">
<div className="relative"> <Search
<Search size={14}
size={14} className="pointer-events-none absolute start-3 top-1/2 -translate-y-1/2 text-content-faint"
className="pointer-events-none absolute start-3 top-1/2 -translate-y-1/2 text-content-faint" aria-hidden="true"
aria-hidden="true" />
/> <input
<input type="search"
id={id} aria-label={t('admin.paddleRegions.search')}
type="search" className={`${INPUT} ps-9`}
className={`${INPUT} ps-9`} value={search.query}
value={search.query} onChange={(event) => search.setQuery(event.target.value)}
onChange={(event) => search.setQuery(event.target.value)} placeholder={t('admin.paddleRegions.searchPlaceholder')}
placeholder={t('admin.paddleRegions.searchPlaceholder')} autoComplete="off"
autoComplete="off" />
/> </div>
</div>
</EditorField>
{search.searching && ( {search.searching && (
<p role="status" className="m-0 flex items-center gap-2 text-content-muted" style={fs(12.5, 'body')}> <p role="status" className="m-0 flex items-center gap-2 text-content-muted" style={fs(12.5, 'body')}>
<Loader2 size={14} className="flex-none animate-spin" /> <Loader2 size={14} className="flex-none animate-spin" />
@@ -219,7 +237,7 @@ function RegionList({ admin }: { admin: Admin }) {
} }
if (admin.regions.length === 0) { if (admin.regions.length === 0) {
return ( return (
<div className="rounded-[12px] border border-dashed border-edge px-4 py-5 text-center"> <div className="rounded-xl border border-edge-faint bg-surface-input px-3 py-3">
<SettingsHint>{t('admin.paddleRegions.empty')}</SettingsHint> <SettingsHint>{t('admin.paddleRegions.empty')}</SettingsHint>
</div> </div>
); );
@@ -3,7 +3,6 @@ import {
ArrowUpCircle, ArrowUpCircle,
Bug, Bug,
CircleDot, CircleDot,
Github,
Globe, Globe,
History, History,
Info, Info,
@@ -23,6 +22,7 @@ import { createPortal } from 'react-dom';
import { POPOVER } from '../../Packing/packingPopoverStyles'; import { POPOVER } from '../../Packing/packingPopoverStyles';
import ToggleSwitch from '../../Settings/ToggleSwitch'; import ToggleSwitch from '../../Settings/ToggleSwitch';
import { fs } from '../../shared/DialogShell'; import { fs } from '../../shared/DialogShell';
import { Github } from '../../shared/legacyLucideIcons';
import PluginIcon from '../../shared/PluginIcon'; import PluginIcon from '../../shared/PluginIcon';
import { Tooltip } from '../../shared/Tooltip'; import { Tooltip } from '../../shared/Tooltip';
import { deriveCaps } from '../pluginCaps'; import { deriveCaps } from '../pluginCaps';
@@ -27,7 +27,7 @@ import { relativeTime } from '../../../utils/relativeTime'
import ConfirmDialog from '../../shared/ConfirmDialog' import ConfirmDialog from '../../shared/ConfirmDialog'
import CustomSelect from '../../shared/CustomSelect' import CustomSelect from '../../shared/CustomSelect'
import { Tooltip } from '../../shared/Tooltip' import { Tooltip } from '../../shared/Tooltip'
import { NEUTRAL_TINT, fs } from '../../shared/DialogShell' import { DialogButton, FooterSpacer, NEUTRAL_TINT, fs } from '../../shared/DialogShell'
import Section from '../../Settings/Section' import Section from '../../Settings/Section'
import { SETTINGS_BUTTON, SETTINGS_BUTTON_PRIMARY, SETTINGS_ICON_BUTTON, SettingRows, SettingsHint, StatusPill, SettingsColumns } from '../../Settings/settingsKit' import { SETTINGS_BUTTON, SETTINGS_BUTTON_PRIMARY, SETTINGS_ICON_BUTTON, SettingRows, SettingsHint, StatusPill, SettingsColumns } from '../../Settings/settingsKit'
import BackendForm from './BackendForm' import BackendForm from './BackendForm'
@@ -588,26 +588,11 @@ export default function AdminStoragePanel(): React.ReactElement {
</p> </p>
))} ))}
</div> </div>
<div className="flex flex-wrap items-center gap-2 border-t border-edge-faint px-4 py-3"> <div className="trek-dialog-footer flex flex-wrap items-center gap-2 border-t border-edge-faint px-4 py-3">
<button type="button" <DialogButton onClick={closeMigratePrompt}>{t('storage.migrate.promptCancel')}</DialogButton>
className={SETTINGS_BUTTON} <FooterSpacer />
onClick={closeMigratePrompt} <DialogButton onClick={() => void routeOnlySave()}>{t('storage.migrate.routeOnly')}</DialogButton>
> <DialogButton variant="primary" onClick={() => void moveAndSave()}>{t('storage.migrate.move')}</DialogButton>
{t('storage.migrate.promptCancel')}
</button>
<span className="flex-1" />
<button type="button"
className={SETTINGS_BUTTON}
onClick={() => void routeOnlySave()}
>
{t('storage.migrate.routeOnly')}
</button>
<button type="button"
className={SETTINGS_BUTTON_PRIMARY}
onClick={() => void moveAndSave()}
>
{t('storage.migrate.move')}
</button>
</div> </div>
</div> </div>
)} )}
@@ -1,5 +1,5 @@
import React, { useId } from 'react' import React, { useId } from 'react'
import { HardDrive } from 'lucide-react' import { Server, HardDrive } from 'lucide-react'
import { import {
STORAGE_BACKEND_TYPE_IDS, STORAGE_BACKEND_TYPE_IDS,
type StorageBackend, type StorageBackend,
@@ -199,7 +199,7 @@ export default function BackendForm({
{fields.length > 0 && <div className={GRID_2}>{fields.map(renderField)}</div>} {fields.length > 0 && <div className={GRID_2}>{fields.map(renderField)}</div>}
{mirror && ( {mirror && (
<DialogSection label={t('storage.mirror.targets')}> <DialogSection icon={Server} label={t('storage.mirror.targets')}>
<p className="m-0 mb-2.5 leading-normal text-content-faint" style={fs(11.5)}>{t('storage.mirror.targetsHelp')}</p> <p className="m-0 mb-2.5 leading-normal text-content-faint" style={fs(11.5)}>{t('storage.mirror.targetsHelp')}</p>
{visibleCandidates.length > 0 && ( {visibleCandidates.length > 0 && (
<div className={CHECK_ROWS}> <div className={CHECK_ROWS}>
@@ -11,12 +11,13 @@
import type { AssistantApplied, AssistantChangeEffect, AssistantChangePreview } from '@trek/shared'; import type { AssistantApplied, AssistantChangeEffect, AssistantChangePreview } from '@trek/shared';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { buildAssignment, buildDay, buildPlace, buildTrip } from '../../../tests/helpers/factories'; import { buildAssignment, buildCategory, buildDay, buildPlace, buildTrip } from '../../../tests/helpers/factories';
import { act, fireEvent, render, screen } from '../../../tests/helpers/render'; import { act, fireEvent, render, screen, within } from '../../../tests/helpers/render';
import { chatOf, useAssistantStore } from '../../store/assistantStore'; import { chatOf, useAssistantStore } from '../../store/assistantStore';
import { useTripStore } from '../../store/tripStore'; import { useTripStore } from '../../store/tripStore';
import AssistantChangeCard from './AssistantChangeCard'; import AssistantChangeCard from './AssistantChangeCard';
import AssistantCompareSwitch from './AssistantCompareSwitch'; import AssistantCompareSwitch from './AssistantCompareSwitch';
import AssistantDayPreview from './AssistantDayPreview';
import type { ChangeItem } from './assistantParts'; import type { ChangeItem } from './assistantParts';
import { type AssistantView, AssistantViewContext } from './assistantViewContext'; import { type AssistantView, AssistantViewContext } from './assistantViewContext';
@@ -168,6 +169,106 @@ describe('AssistantChangeCard: deciding', () => {
expect(screen.getByRole('button', { name: 'Apply' })).toBeDisabled(); expect(screen.getByRole('button', { name: 'Apply' })).toBeDisabled();
expect(screen.getByRole('button', { name: 'Discard' })).toBeDisabled(); expect(screen.getByRole('button', { name: 'Discard' })).toBeDisabled();
}); });
it('edits a place proposal in the full place form and previews edits before applying', async () => {
plannerHere();
const change = {
...preview('c1', 'Kinkaku-ji'),
verbKey: 'addPlaceToDay' as const,
effect: { ...PANTHEON, place: { name: 'Kinkaku-ji', lat: 48, lng: 2, categoryId: 31 } },
};
const other = { ...change, toolCallId: 'c2', subject: 'Tea house', effect: null };
useTripStore.setState({
categories: [
buildCategory({ id: 31, name: 'Temple', color: '#334455' }),
buildCategory({ id: 32, name: 'Garden', color: '#667788' }),
],
});
patchChat({
messages: [
{
id: 'm1',
role: 'assistant',
status: 'complete',
createdAt: new Date().toISOString(),
parts: [
{
type: 'tool-call',
toolCallId: 'c1',
toolName: 'create_and_assign_place',
args: {},
approval: { id: 'c1' },
},
{ type: 'data-trek-change', data: change },
{
type: 'tool-call',
toolCallId: 'c2',
toolName: 'create_and_assign_place',
args: {},
approval: { id: 'c2' },
},
{ type: 'data-trek-change', data: other },
],
},
],
});
render(<AssistantDayPreview tripId={TRIP} dayId={3} />);
renderCard([
{ ...pending('c1', 'Kinkaku-ji'), preview: change },
{ ...pending('c2', 'Tea house'), preview: other },
]);
const day = screen.getByRole('list', { name: 'Suggested by the assistant' });
const [edit] = screen.getAllByRole('button', { name: 'Edit' });
fireEvent.click(edit);
const dialog = within(await screen.findByRole('dialog', { name: 'Edit Place' }));
expect(dialog.getByRole('textbox', { name: /^Name/ })).toHaveValue('Kinkaku-ji');
expect(dialog.getByRole('textbox', { name: 'Address' })).toBeVisible();
fireEvent.change(dialog.getByRole('textbox', { name: 'Start' }), { target: { value: '12:30' } });
fireEvent.change(dialog.getByRole('textbox', { name: 'Notes for this day' }), {
target: { value: 'Use the side entrance' },
});
fireEvent.click(dialog.getByRole('button', { name: /^Category:/ }));
fireEvent.click(screen.getByRole('button', { name: /^Garden$/ }));
expect(day).toHaveTextContent('12:30');
expect(day).toHaveTextContent('Use the side entrance');
expect(within(day).getByText('Garden').parentElement).toHaveStyle({ backgroundColor: '#667788' });
expect(decide).not.toHaveBeenCalled();
fireEvent.click(dialog.getByRole('button', { name: 'Cancel' }));
expect(day).toHaveTextContent('10:30');
expect(day).toHaveTextContent('Temple');
expect(day).not.toHaveTextContent('Use the side entrance');
fireEvent.click(edit);
const reopened = within(await screen.findByRole('dialog', { name: 'Edit Place' }));
const time = reopened.getByRole('textbox', { name: 'Start' });
expect(time).toHaveValue('10:30');
fireEvent.change(time, { target: { value: '11:45' } });
fireEvent.change(reopened.getByRole('textbox', { name: /^Name/ }), { target: { value: 'Golden Pavilion' } });
fireEvent.change(reopened.getByRole('textbox', { name: 'Address' }), { target: { value: 'Kyoto, Japan' } });
expect(day).toHaveTextContent('Golden Pavilion');
fireEvent.click(reopened.getByRole('button', { name: 'Save' }));
expect(day).toHaveTextContent('11:45');
expect(decide).not.toHaveBeenCalled();
const [include] = screen.getAllByRole('button', { name: 'Include this change' });
fireEvent.click(include);
expect(day).not.toHaveTextContent('Golden Pavilion');
expect(day).toHaveTextContent('Tea house');
fireEvent.click(include);
expect(day).toHaveTextContent('Golden Pavilion');
expect(day).toHaveTextContent('11:45');
fireEvent.click(screen.getByRole('button', { name: 'Apply 2' }));
expect(decide).toHaveBeenCalledWith(TRIP, [
{
toolCallId: 'c1',
approved: true,
planEdits: { startTime: '11:45', place: { name: 'Golden Pavilion', address: 'Kyoto, Japan' } },
},
{ toolCallId: 'c2', approved: true },
]);
});
}); });
describe('AssistantChangeCard: the receipt', () => { describe('AssistantChangeCard: the receipt', () => {
@@ -1,4 +1,4 @@
import { Check, CheckCheck, ListChecks, LoaderCircle, MapPin, Undo2 } from 'lucide-react'; import { Check, CheckCheck, ChevronDown, ListChecks, LoaderCircle, MapPin, Undo2 } from 'lucide-react';
import { type ReactNode, useEffect, useMemo, useState } from 'react'; import { type ReactNode, useEffect, useMemo, useState } from 'react';
import { useTranslation } from '../../i18n'; import { useTranslation } from '../../i18n';
@@ -78,13 +78,21 @@ function dayChangesOf(items: readonly ChangeItem[], excluded: ReadonlySet<string
/** The change card's band: tinted green once everything in it is decided, what it holds and its actions. */ /** The change card's band: tinted green once everything in it is decided, what it holds and its actions. */
function CardHead({ open, count, actions }: { open: boolean; count: number; actions?: ReactNode }) { function CardHead({ open, count, actions }: { open: boolean; count: number; actions?: ReactNode }) {
const { t } = useTranslation(); const { t } = useTranslation();
const Icon = open ? ListChecks : CheckCheck;
return ( return (
<CardHeader <CardHeader
icon={open ? ListChecks : CheckCheck} icon={Icon}
tone={open ? 'info' : 'success'} tone={open ? 'info' : 'success'}
tint={open ? NEUTRAL_TINT : DONE_TINT} tint={open ? NEUTRAL_TINT : DONE_TINT}
title={t(open ? 'assistant.change.title' : 'assistant.change.doneTitle')} title={t(open ? 'assistant.change.title' : 'assistant.change.doneTitle')}
count={count} tile={
<span className="relative grid h-8 w-8 shrink-0 place-items-center rounded-[10px] bg-surface-card shadow-sm">
<Icon size={15} strokeWidth={2} className={open ? 'text-info' : 'text-success'} aria-hidden="true" />
<span className="absolute -end-1 -top-1 inline-flex h-4 min-w-4 items-center justify-center rounded-full bg-surface-card px-1 font-geist text-caption font-bold tabular-nums leading-none text-content-secondary shadow-sm ring-1 ring-edge">
{count}
</span>
</span>
}
actions={actions} actions={actions}
/> />
); );
@@ -186,11 +194,23 @@ export default function AssistantChangeCard({ items }: { items: ChangeItem[] })
const undone = useAssistantStore((s) => chatOf(s, tripId).undone); const undone = useAssistantStore((s) => chatOf(s, tripId).undone);
const decide = useAssistantStore((s) => s.decide); const decide = useAssistantStore((s) => s.decide);
const undo = useAssistantStore((s) => s.undo); const undo = useAssistantStore((s) => s.undo);
const [excluded, setExcluded] = useChangeExclusions(items); const choices = useAssistantStore((s) => chatOf(s, tripId).changeChoices);
const choosePlanChanges = useAssistantStore((s) => s.choosePlanChanges);
const excluded = useChangeExclusions(items, choices);
const planEdits = useAssistantStore((s) => chatOf(s, tripId).planEdits);
const savePlanEdit = useAssistantStore((s) => s.savePlanEdit);
const now = useUndoClock(items); const now = useUndoClock(items);
const pending = items.filter((i) => i.state === 'pending'); const pending = items.filter((i) => i.state === 'pending');
const chosen = pending.filter((i) => !excluded.has(i.toolCallId)).length; const chosen = pending.filter((i) => !excluded.has(i.toolCallId)).length;
const invalid = pending.some((i) => !excluded.has(i.toolCallId) && planEdits[i.toolCallId]?.noteTitle?.trim() === '');
const planDayId = pending[0]?.preview?.dayId;
const planDay = useTripStore((s) => (s.trip?.id === tripId ? s.days.find((day) => day.id === planDayId) : undefined));
const groupedDay =
pending.length > 1 &&
pending.length === items.length &&
!!planDay &&
pending.every((i) => i.preview?.dayId === planDayId);
const changes = useMemo(() => dayChangesOf(items, excluded), [items, excluded]); const changes = useMemo(() => dayChangesOf(items, excluded), [items, excluded]);
const undoable = items.filter((i) => undoableNow(i, undone, now)).map((i) => i.toolCallId); const undoable = items.filter((i) => undoableNow(i, undone, now)).map((i) => i.toolCallId);
@@ -199,27 +219,17 @@ export default function AssistantChangeCard({ items }: { items: ChangeItem[] })
// A plan over a week reads from its grid; the single changes wait behind one line. // A plan over a week reads from its grid; the single changes wait behind one line.
const folded = week.length > 0 && !showAll; const folded = week.length > 0 && !showAll;
const toggleDay = (ids: readonly string[], include: boolean) => const toggleDay = (ids: readonly string[], include: boolean) => choosePlanChanges(tripId, ids, include);
setExcluded((prev) => { const toggle = (toolCallId: string) => toggleDay([toolCallId], excluded.has(toolCallId));
const next = new Set(prev);
for (const id of ids) {
if (include) next.delete(id);
else next.add(id);
}
return next;
});
const toggle = (toolCallId: string) =>
setExcluded((prev) => {
const next = new Set(prev);
if (!next.delete(toolCallId)) next.add(toolCallId);
return next;
});
const submit = (applyChosen: boolean) => const submit = (applyChosen: boolean) =>
decide( decide(
tripId, tripId,
pending.map((i) => ({ toolCallId: i.toolCallId, approved: applyChosen && !excluded.has(i.toolCallId) })) pending.map((i) => {
const approved = applyChosen && !excluded.has(i.toolCallId);
const edits = approved ? planEdits[i.toolCallId] : undefined;
return { toolCallId: i.toolCallId, approved, ...(edits ? { planEdits: edits } : {}) };
})
); );
// An undone change reads as undone from the store; only what stays needs a word. // An undone change reads as undone from the store; only what stays needs a word.
@@ -230,6 +240,21 @@ export default function AssistantChangeCard({ items }: { items: ChangeItem[] })
}; };
const open = pending.length > 0; const open = pending.length > 0;
const rows = (
<ChangeRows
items={items}
folded={folded}
excluded={excluded}
disabled={isRunning}
undone={undone}
undoable={undoable}
onToggle={toggle}
onUndo={(toolCallId) => void runUndo(toolCallId)}
groupedDay={groupedDay}
planEdits={planEdits}
onEdit={(id, patch) => savePlanEdit(tripId, id, patch)}
/>
);
return ( return (
<section className="trek-popover-enter overflow-hidden rounded-[16px] border border-edge-faint bg-surface-card px-3.5 pb-3 pt-3 shadow-card"> <section className="trek-popover-enter overflow-hidden rounded-[16px] border border-edge-faint bg-surface-card px-3.5 pb-3 pt-3 shadow-card">
<CardHead <CardHead
@@ -249,16 +274,31 @@ export default function AssistantChangeCard({ items }: { items: ChangeItem[] })
{t('assistant.week.showAll', { count: pending.length })} {t('assistant.week.showAll', { count: pending.length })}
</button> </button>
)} )}
<ChangeRows {!folded && groupedDay && planDay ? (
items={items} <details open className="group/day mt-1">
folded={folded} <summary className="-mx-1.5 flex min-w-0 cursor-pointer list-none items-center gap-2.5 rounded-xl bg-surface-tertiary py-2 pe-3.5 ps-1.5 text-start hover:bg-surface-hover focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-accent [&::-webkit-details-marker]:hidden">
excluded={excluded} <span
disabled={isRunning} aria-hidden="true"
undone={undone} className="grid h-8 w-8 shrink-0 place-items-center rounded-[10px] bg-surface-card font-geist text-caption font-bold tabular-nums text-content-muted shadow-sm"
undoable={undoable} >
onToggle={toggle} {planDay.day_number}
onUndo={(toolCallId) => void runUndo(toolCallId)} </span>
/> <span className="shrink-0 text-body font-bold text-content">
{t('assistant.week.day')} {planDay.day_number}
</span>
{planDay.title && <bdi className="min-w-0 truncate text-caption text-content-muted">{planDay.title}</bdi>}
<ChevronDown
size={15}
strokeWidth={2}
aria-hidden="true"
className="ms-auto shrink-0 -rotate-90 text-content-muted group-open/day:rotate-0"
/>
</summary>
{rows}
</details>
) : (
rows
)}
{open && ( {open && (
<> <>
<p className="sr-only" role="status"> <p className="sr-only" role="status">
@@ -270,7 +310,7 @@ export default function AssistantChangeCard({ items }: { items: ChangeItem[] })
</DialogButton> </DialogButton>
<DialogButton <DialogButton
variant="primary" variant="primary"
disabled={isRunning || chosen === 0} disabled={isRunning || chosen === 0 || invalid}
onClick={() => void submit(true)} onClick={() => void submit(true)}
icon={<Check size={14} aria-hidden="true" />} icon={<Check size={14} aria-hidden="true" />}
> >
@@ -1,4 +1,4 @@
import type { AssistantChangeLabelKey, AssistantChangeRow } from '@trek/shared'; import type { AssistantChangeLabelKey, AssistantChangeRow, AssistantPlanEdits } from '@trek/shared';
import { import {
CalendarClock, CalendarClock,
CalendarDays, CalendarDays,
@@ -13,6 +13,7 @@ import {
} from 'lucide-react'; } from 'lucide-react';
import { useTranslation } from '../../i18n'; import { useTranslation } from '../../i18n';
import { useTripStore } from '../../store/tripStore';
import { FactChange } from './cards/parts/CardFacts'; import { FactChange } from './cards/parts/CardFacts';
/** /**
@@ -45,10 +46,42 @@ function shown(row: AssistantChangeRow, value: string | null | undefined, dayWor
return value ?? ''; return value ?? '';
} }
export default function AssistantChangeFields({ rows }: { rows: AssistantChangeRow[] }) { export default function AssistantChangeFields({
rows,
visit = false,
edits,
}: {
rows: AssistantChangeRow[];
visit?: boolean;
edits?: AssistantPlanEdits;
}) {
const { t } = useTranslation(); const { t } = useTranslation();
const categoryName = useTripStore((s) =>
edits?.categoryId == null ? undefined : s.categories.find((category) => category.id === edits.categoryId)?.name
);
const dayWord = t('assistant.week.day'); const dayWord = t('assistant.week.day');
const facts = rows let editedRows = rows;
if (visit && edits) {
const fields = [
['time', edits.startTime],
['endTime', edits.endTime],
['category', edits.categoryId === null ? null : categoryName],
] as const;
for (const [labelKey, after] of fields) {
if (after === undefined) continue;
editedRows = editedRows.filter((row) => row.labelKey !== labelKey);
if (after) editedRows.push({ op: 'add', labelKey, before: null, after });
}
}
const end = visit ? editedRows.find((row) => row.labelKey === 'endTime')?.after : undefined;
const start = visit ? editedRows.find((row) => row.labelKey === 'time') : undefined;
const visible =
start?.after && end
? editedRows
.filter((row) => row.labelKey !== 'endTime')
.map((row) => (row === start ? { ...row, after: `${row.after} – ${end}` } : row))
: editedRows;
const facts = visible
.filter((row) => row.labelKey in KEY_FIELDS && row.after) .filter((row) => row.labelKey in KEY_FIELDS && row.after)
.sort((a, b) => KEY_ORDER.indexOf(a.labelKey) - KEY_ORDER.indexOf(b.labelKey)) .sort((a, b) => KEY_ORDER.indexOf(a.labelKey) - KEY_ORDER.indexOf(b.labelKey))
.slice(0, MAX_FACTS); .slice(0, MAX_FACTS);
@@ -1,18 +1,28 @@
import type { AssistantChangeEffect, AssistantMessage } from '@trek/shared'; import type { AssistantChangePreview, AssistantMessage, AssistantPlanEdits } from '@trek/shared';
import { ArrowRightLeft, Minus, Sparkles } from 'lucide-react'; import { ArrowRightLeft, FileText, MapPin, Minus, type LucideIcon } from 'lucide-react';
import { useMemo } from 'react'; import { useMemo } from 'react';
import { useShallow } from 'zustand/react/shallow'; import { useShallow } from 'zustand/react/shallow';
import { useTranslation } from '../../i18n'; import { useTranslation } from '../../i18n';
import { changeEffects } from '../../store/assistantMapModel';
import { chatOf, useAssistantStore } from '../../store/assistantStore'; import { chatOf, useAssistantStore } from '../../store/assistantStore';
import { useSettingsStore } from '../../store/settingsStore';
import { useTripStore } from '../../store/tripStore'; import { useTripStore } from '../../store/tripStore';
import type { Place } from '../../types';
import { formatTime } from '../../utils/formatters';
import { TimePill } from '../Planner/planParts';
import { getCategoryIcon } from '../shared/categoryIcons';
import { isDayNoteProposal, isVisitProposal, planField, proposalNote } from './assistantPlanFieldsModel';
/** What a waiting change does to one day, as a row of the preview. */ /** What a waiting change does to one day, as a row of the preview. */
interface PreviewRow { interface PreviewRow {
toolCallId: string; toolCallId: string;
kind: 'add' | 'in' | 'remove' | 'out'; kind: 'add' | 'in' | 'remove' | 'out' | 'note';
name: string; name: string;
categoryId: number | null;
categoryName?: string;
start?: string;
end?: string;
detail?: string;
} }
/** The changes no one has decided on yet, by their call. */ /** The changes no one has decided on yet, by their call. */
@@ -29,25 +39,77 @@ function waitingCalls(messages: readonly AssistantMessage[]): Set<string> {
} }
function rowOf( function rowOf(
toolCallId: string, preview: AssistantChangePreview,
effect: AssistantChangeEffect,
dayId: number, dayId: number,
nameOf: (id: number | null) => string | null places: readonly Place[],
) { edits: AssistantPlanEdits | undefined
const name = effect.place?.name ?? nameOf(effect.placeId); ): PreviewRow | null {
if (!name) return null; const { toolCallId, effect, subject } = preview;
if (effect.dayId === dayId) { if (preview.dayId === dayId && isDayNoteProposal(preview)) {
const kind = effect.kind === 'remove' ? 'remove' : effect.kind === 'move' ? 'in' : 'add'; return {
return { toolCallId, kind, name } satisfies PreviewRow; toolCallId,
kind: 'note',
name: edits?.noteTitle || planField(preview, 'title') || subject,
categoryId: null,
detail: proposalNote(preview, edits) ?? undefined,
};
} }
if (effect.kind === 'move' && effect.fromDayId === dayId) const kind = visitKind(preview, dayId);
return { toolCallId, kind: 'out', name } satisfies PreviewRow; if (!kind) return null;
return null; const place = places.find((p) => p.id === effect?.placeId);
return { toolCallId, kind, ...visitSubject(preview, place, edits), ...visitDetails(preview, place, edits) };
} }
const LOOK: Record<PreviewRow['kind'], { icon: typeof Sparkles; row: string; name: string; badgeKey: string }> = { function visitSubject(
preview: AssistantChangePreview,
place: Place | undefined,
edits: AssistantPlanEdits | undefined
) {
const proposed = preview.effect?.place;
const categoryId = edits?.categoryId;
return {
name: edits?.place?.name ?? proposed?.name ?? place?.name ?? preview.subject,
categoryId: categoryId === undefined ? (proposed?.categoryId ?? place?.category_id ?? null) : categoryId,
categoryName: categoryId === undefined ? planField(preview, 'category') : undefined,
};
}
function editedText(value: string | null | undefined, original: string | undefined): string | undefined {
return value === undefined ? original : (value ?? undefined);
}
function visitDetails(
preview: AssistantChangePreview,
place: Place | undefined,
edits: AssistantPlanEdits | undefined
) {
return {
start: editedText(edits?.startTime, planField(preview, 'time')),
end: editedText(edits?.endTime, planField(preview, 'endTime')),
detail:
editedText(edits?.notes, planField(preview, 'notes')) ||
editedText(edits?.place?.description, planField(preview, 'description')) ||
place?.description ||
editedText(edits?.place?.address, planField(preview, 'address')) ||
place?.address ||
undefined,
};
}
function visitKind(preview: AssistantChangePreview, dayId: number): PreviewRow['kind'] | null {
const { effect } = preview;
if (!effect) return preview.dayId === dayId && isVisitProposal(preview) ? 'add' : null;
if (effect.dayId === dayId) {
if (effect.kind === 'remove') return 'remove';
if (effect.kind === 'move') return 'in';
return 'add';
}
return effect.kind === 'move' && effect.fromDayId === dayId ? 'out' : null;
}
const LOOK: Record<PreviewRow['kind'], { icon: LucideIcon; row: string; name: string; badgeKey: string }> = {
add: { add: {
icon: Sparkles, icon: MapPin,
row: 'border-dashed border-accent bg-accent-subtle', row: 'border-dashed border-accent bg-accent-subtle',
name: 'text-content', name: 'text-content',
badgeKey: 'assistant.preview.suggested', badgeKey: 'assistant.preview.suggested',
@@ -70,6 +132,12 @@ const LOOK: Record<PreviewRow['kind'], { icon: typeof Sparkles; row: string; nam
name: 'text-content-faint line-through', name: 'text-content-faint line-through',
badgeKey: 'assistant.preview.movedAway', badgeKey: 'assistant.preview.movedAway',
}, },
note: {
icon: FileText,
row: 'border-dashed border-accent bg-accent-subtle',
name: 'text-content',
badgeKey: 'assistant.preview.suggested',
},
}; };
/** /**
@@ -80,31 +148,45 @@ const LOOK: Record<PreviewRow['kind'], { icon: typeof Sparkles; row: string; nam
* here writes; the change card stays the one place a change is applied. * here writes; the change card stays the one place a change is applied.
*/ */
export default function AssistantDayPreview({ tripId, dayId }: { tripId: number; dayId: number }) { export default function AssistantDayPreview({ tripId, dayId }: { tripId: number; dayId: number }) {
const { t } = useTranslation(); const { t, locale } = useTranslation();
const timeFormat = useSettingsStore((s) => s.settings.time_format) || '24h';
const messages = useAssistantStore((s) => chatOf(s, tripId).messages); const messages = useAssistantStore((s) => chatOf(s, tripId).messages);
const savedEdits = useAssistantStore((s) => chatOf(s, tripId).planEdits);
const liveEdit = useAssistantStore((s) => chatOf(s, tripId).planEditPreview);
const choices = useAssistantStore((s) => chatOf(s, tripId).changeChoices);
const hovered = useAssistantStore((s) => (s.mapLink?.tripId === tripId ? s.mapLink.hoveredId : null)); const hovered = useAssistantStore((s) => (s.mapLink?.tripId === tripId ? s.mapLink.hoveredId : null));
const { setMapHover, open } = useAssistantStore(useShallow((s) => ({ setMapHover: s.setMapHover, open: s.open }))); const { setMapHover, open } = useAssistantStore(useShallow((s) => ({ setMapHover: s.setMapHover, open: s.open })));
const places = useTripStore((s) => s.places); const places = useTripStore((s) => s.places);
const categories = useTripStore((s) => s.categories);
const rows = useMemo(() => { const rows = useMemo(() => {
const waiting = waitingCalls(messages); const waiting = waitingCalls(messages);
if (waiting.size === 0) return []; if (waiting.size === 0) return [];
const nameOf = (id: number | null) => (id === null ? null : (places.find((p) => p.id === id)?.name ?? null)); return messages.flatMap((message) =>
const out: PreviewRow[] = []; message.parts.flatMap((part) => {
for (const [toolCallId, effect] of changeEffects(messages)) { if (part.type !== 'data-trek-change' || !waiting.delete(part.data.toolCallId)) return [];
if (!waiting.has(toolCallId)) continue; const id = part.data.toolCallId;
const row = rowOf(toolCallId, effect, dayId, nameOf); if (choices[id] === false) return [];
if (row) out.push(row); const edits = liveEdit?.toolCallId === id ? liveEdit.edits : savedEdits[id];
} const row = rowOf(part.data, dayId, places, edits);
return out; return row ? [row] : [];
}, [messages, places, dayId]); })
);
}, [messages, places, dayId, savedEdits, liveEdit, choices]);
if (rows.length === 0) return null; if (rows.length === 0) return null;
return ( return (
<ul className="m-0 flex list-none flex-col gap-1 px-3 pb-2 pt-1" aria-label={t('assistant.preview.title')}> <ul className="m-0 flex list-none flex-col gap-1 px-3 pb-2 pt-1" aria-label={t('assistant.preview.title')}>
{rows.map((row, i) => { {rows.map((row, i) => {
const look = LOOK[row.kind]; const look = LOOK[row.kind];
const Icon = look.icon; const category = categories.find((entry) =>
row.categoryId ? entry.id === row.categoryId : entry.name === row.categoryName
);
const Icon = category ? getCategoryIcon(category.icon) : look.icon;
const time = [row.start, row.end]
.filter((value): value is string => !!value)
.map((value) => formatTime(value, locale, timeFormat))
.join(' – ');
const lit = hovered === row.toolCallId; const lit = hovered === row.toolCallId;
return ( return (
<li <li
@@ -121,11 +203,29 @@ export default function AssistantDayPreview({ tripId, dayId }: { tripId: number;
lit ? 'shadow-md ring-2 ring-accent' : 'hover:shadow-sm' lit ? 'shadow-md ring-2 ring-accent' : 'hover:shadow-sm'
}`} }`}
> >
<span className="grid h-6 w-6 flex-shrink-0 place-items-center rounded-lg bg-surface-card text-content-muted shadow-sm"> <span
<Icon size={12} aria-hidden="true" /> className="grid h-8 w-8 flex-shrink-0 place-items-center rounded-full bg-surface-card text-content-muted shadow-sm"
style={category?.color ? { backgroundColor: category.color, color: 'white' } : undefined}
>
<Icon size={14} aria-hidden="true" />
{(category?.name || row.categoryName) && (
<span className="sr-only">{category?.name ?? row.categoryName}</span>
)}
</span> </span>
<bdi className={`min-w-0 flex-1 truncate text-caption font-medium ${look.name}`}>{row.name}</bdi> <span className="min-w-0 flex-1">
<span className="flex-shrink-0 rounded-full bg-surface-card px-2 py-0.5 text-caption text-content-muted shadow-sm"> <bdi className={`block truncate text-body font-medium ${look.name}`}>{row.name}</bdi>
{time && (
<span className="mt-0.5 flex">
<TimePill quiet>{time}</TimePill>
</span>
)}
{row.detail && (
<bdi className="mt-0.5 line-clamp-2 break-words text-caption text-content-muted">{row.detail}</bdi>
)}
</span>
<span
className={row.kind === 'add' || row.kind === 'note' ? 'sr-only' : 'flex-shrink-0 text-content-muted'}
>
{t(look.badgeKey)} {t(look.badgeKey)}
</span> </span>
</button> </button>
@@ -4,10 +4,11 @@
* The error line: one sentence, at most one thing to do, and that thing * The error line: one sentence, at most one thing to do, and that thing
* does what it says. * does what it says.
*/ */
import type { AiStatusResponse, AssistantErrorCode } from '@trek/shared'; import type { AiStatusResponse, AssistantErrorCode, AssistantMessage } from '@trek/shared';
import { Route, Routes } from 'react-router'; import { Route, Routes } from 'react-router';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { HIKE } from '../../../tests/helpers/assistantTour';
import { fireEvent, render, screen } from '../../../tests/helpers/render'; import { fireEvent, render, screen } from '../../../tests/helpers/render';
import { chatOf, useAssistantStore } from '../../store/assistantStore'; import { chatOf, useAssistantStore } from '../../store/assistantStore';
import { setForcedOffline } from '../../sync/networkMode'; import { setForcedOffline } from '../../sync/networkMode';
@@ -33,13 +34,17 @@ const retry = vi.fn(async () => {});
const continueHere = vi.fn(async () => {}); const continueHere = vi.fn(async () => {});
const send = vi.fn(async () => {}); const send = vi.fn(async () => {});
function withError(error: AssistantErrorCode | null, status: AiStatusResponse = STATUS) { function withError(
error: AssistantErrorCode | null,
status: AiStatusResponse = STATUS,
messages: AssistantMessage[] = []
) {
useAssistantStore.setState({ useAssistantStore.setState({
status, status,
retry, retry,
continueHere, continueHere,
send, send,
byTrip: { [TRIP]: { ...chatOf(useAssistantStore.getState(), TRIP), error } }, byTrip: { [TRIP]: { ...chatOf(useAssistantStore.getState(), TRIP), error, messages } },
}); });
} }
@@ -119,6 +124,25 @@ describe('AssistantError', () => {
expect(screen.queryByRole('button')).toBeNull(); expect(screen.queryByRole('button')).toBeNull();
}); });
it('keeps a calculated route distinct from the rate-limited reply', () => {
const when = '2026-10-21T08:00:00.000Z';
const question: AssistantMessage = { id: 'm1', role: 'user', status: 'complete', parts: [], createdAt: when };
const answer: AssistantMessage = {
id: 'm2',
role: 'assistant',
status: 'error',
createdAt: when,
parts: [{ type: 'data-trek-card', data: { toolCallId: 'hike', card: HIKE } }],
};
withError('rate_limited', STATUS, [question, answer]);
const { unmount } = renderLine();
expect(screen.getByRole('status')).toHaveTextContent('The route preview is still available.');
unmount();
withError('rate_limited', STATUS, [question, answer, { ...question, id: 'm3' }]);
renderLine();
expect(screen.getByRole('status')).toHaveTextContent('Limit reached at Anthropic. Try again later.');
});
it('FE-AI-ERR-008: waiting changes ask for a decision before a place can be suggested', () => { it('FE-AI-ERR-008: waiting changes ask for a decision before a place can be suggested', () => {
withError('decide_first'); withError('decide_first');
renderLine(); renderLine();
@@ -4,7 +4,7 @@ import { useNavigate } from 'react-router';
import { useNetworkMode } from '../../hooks/useNetworkMode'; import { useNetworkMode } from '../../hooks/useNetworkMode';
import { useTranslation } from '../../i18n'; import { useTranslation } from '../../i18n';
import { chatOf, useAssistantStore } from '../../store/assistantStore'; import { chatOf, useAssistantStore } from '../../store/assistantStore';
import { type AssistantErrorActionKind, connectionErrorOf, errorView } from './assistantModel'; import { type AssistantErrorActionKind, connectionErrorOf, errorView, hasCurrentTourProposal } from './assistantModel';
import { AI_SETTINGS_PATH } from './assistantParts'; import { AI_SETTINGS_PATH } from './assistantParts';
import { CHATGPT_USAGE_URL, providerLabel } from './providerCatalog'; import { CHATGPT_USAGE_URL, providerLabel } from './providerCatalog';
@@ -18,6 +18,10 @@ export default function AssistantError({ tripId }: { tripId: number }) {
const navigate = useNavigate(); const navigate = useNavigate();
const { offline } = useNetworkMode(); const { offline } = useNetworkMode();
const error = useAssistantStore((s) => chatOf(s, tripId).error); const error = useAssistantStore((s) => chatOf(s, tripId).error);
const hasTourProposal = useAssistantStore((s) => {
const chat = chatOf(s, tripId);
return chat.error === 'rate_limited' && hasCurrentTourProposal(chat.messages);
});
const status = useAssistantStore((s) => s.status); const status = useAssistantStore((s) => s.status);
const retry = useAssistantStore((s) => s.retry); const retry = useAssistantStore((s) => s.retry);
const continueHere = useAssistantStore((s) => s.continueHere); const continueHere = useAssistantStore((s) => s.continueHere);
@@ -28,7 +32,7 @@ export default function AssistantError({ tripId }: { tripId: number }) {
const effective = status?.effective; const effective = status?.effective;
const provider = effective ? providerLabel(effective.kind, effective.host) : ''; const provider = effective ? providerLabel(effective.kind, effective.host) : '';
const view = errorView(code, { canConnectOwn: status?.canConnectOwn ?? false, provider }); const view = errorView(code, { canConnectOwn: status?.canConnectOwn ?? false, provider, hasTourProposal });
const run = (kind: AssistantErrorActionKind) => { const run = (kind: AssistantErrorActionKind) => {
if (kind === 'retry') void retry(tripId); if (kind === 'retry') void retry(tripId);
@@ -1,4 +1,4 @@
import { NotebookPen, Plus } from 'lucide-react'; import { NotebookPen, Plus, Zap } from 'lucide-react';
import { useId, useState } from 'react'; import { useId, useState } from 'react';
import { useTranslation } from '../../i18n'; import { useTranslation } from '../../i18n';
@@ -75,7 +75,7 @@ export default function AssistantMemoryDialog({ tripId, onClose }: { tripId: num
</DialogFooter> </DialogFooter>
} }
> >
<DialogSection label={t('assistant.memory.quick')}> <DialogSection icon={Zap} label={t('assistant.memory.quick')}>
<div className="flex flex-wrap gap-1.5"> <div className="flex flex-wrap gap-1.5">
{QUICK.map((key, i) => { {QUICK.map((key, i) => {
const line = t(`assistant.memory.quick.${key}`); const line = t(`assistant.memory.quick.${key}`);
@@ -96,7 +96,7 @@ export default function AssistantMemoryDialog({ tripId, onClose }: { tripId: num
})} })}
</div> </div>
</DialogSection> </DialogSection>
<DialogSection label={t('assistant.memory.notes')}> <DialogSection icon={NotebookPen} label={t('assistant.memory.notes')}>
<textarea <textarea
aria-label={t('assistant.memory.notes')} aria-label={t('assistant.memory.notes')}
rows={6} rows={6}
@@ -139,7 +139,8 @@ function Answer({ message }: { message: StoredMessage }) {
}); });
const blocks = useMemo(() => messageBlocks(message, writing), [message, writing]); const blocks = useMemo(() => messageBlocks(message, writing), [message, writing]);
const share = useAssistantShare(tripId, message, writing); const share = useAssistantShare(tripId, message, writing);
const last = blocks[blocks.length - 1]; const end = blocks[blocks.length - 1];
const last = end?.kind === 'sources' ? blocks[blocks.length - 2] : end;
const hasText = blocks.some((b) => b.kind === 'text'); const hasText = blocks.some((b) => b.kind === 'text');
const tail = tailStart(blocks); const tail = tailStart(blocks);
@@ -0,0 +1,173 @@
import type { AssistantChangePreview, AssistantPlanEdits } from '@trek/shared';
import { assistantPlanEditsSchema, parsePlaceHours, placeOpeningHoursSchema } from '@trek/shared';
import { useCallback, useEffect, useState } from 'react';
import { useIsPhone } from '../../hooks/useIsPhone';
import { useTranslation } from '../../i18n';
import { useAssistantStore } from '../../store/assistantStore';
import { useTripStore } from '../../store/tripStore';
import PlaceFormModal from '../Planner/PlaceFormModal';
import { DEFAULT_FORM, formPin, type PlaceFormData } from '../Planner/PlaceFormModal.helpers';
import { planField } from './assistantPlanFieldsModel';
import { useAssistantView } from './assistantViewContext';
type PlacePatch = NonNullable<AssistantPlanEdits['place']>;
function originalForm(preview: AssistantChangePreview, rawArgs: unknown, categoryId: number | null): PlaceFormData {
const args = rawArgs && typeof rawArgs === 'object' ? (rawArgs as Record<string, unknown>) : {};
const value = (key: string) => (typeof args[key] === 'string' ? args[key] : '');
const point = preview.effect?.place;
const coordinate = (key: 'lat' | 'lng') => String(typeof args[key] === 'number' ? args[key] : (point?.[key] ?? ''));
const text = (key: 'address' | 'description') => value(key) || planField(preview, key) || '';
const hours = placeOpeningHoursSchema.safeParse(args.opening_hours);
return {
...DEFAULT_FORM,
name: value('name') || point?.name || preview.subject,
address: text('address'),
description: text('description'),
lat: coordinate('lat'),
lng: coordinate('lng'),
category_id: String(categoryId ?? ''),
place_time: planField(preview, 'time') ?? '',
end_time: planField(preview, 'endTime') ?? '',
assignment_notes: planField(preview, 'notes') ?? '',
notes: value('place_notes'),
google_place_id: value('google_place_id'),
google_ftid: value('google_ftid'),
osm_id: value('osm_id'),
amap_poi_id: value('amap_poi_id'),
website: value('website'),
phone: value('phone'),
email: value('email'),
opening_hours: hours.success ? JSON.stringify(hours.data) : '',
image_url: value('image_url') || null,
tags: Array.isArray(args.tags) ? args.tags.filter((tag): tag is number => Number.isInteger(tag)) : [],
};
}
function restoreDraft(form: PlaceFormData, edits: AssistantPlanEdits | undefined): PlaceFormData {
const { lat, lng, place_notes, opening_hours, ...place } = edits?.place ?? {};
const restored = Object.fromEntries(Object.entries(place).map(([field, value]) => [field, value ?? '']));
return {
...form,
...restored,
...(lat === undefined ? {} : { lat: String(lat ?? '') }),
...(lng === undefined ? {} : { lng: String(lng ?? '') }),
...(place_notes === undefined ? {} : { notes: place_notes ?? '' }),
...(opening_hours === undefined ? {} : { opening_hours: opening_hours ? JSON.stringify(opening_hours) : '' }),
...visitDraft(edits ?? {}),
};
}
function visitDraft({ startTime, endTime, notes, categoryId }: AssistantPlanEdits): Partial<PlaceFormData> {
return {
...(startTime === undefined ? {} : { place_time: startTime ?? '' }),
...(endTime === undefined ? {} : { end_time: endTime ?? '' }),
...(notes === undefined ? {} : { assignment_notes: notes ?? '' }),
...(categoryId === undefined ? {} : { category_id: String(categoryId ?? '') }),
};
}
function placeValues(form: PlaceFormData): PlacePatch {
const position = formPin(form);
return {
name: form.name.trim(),
description: form.description || null,
address: form.address || null,
lat: position?.lat ?? null,
lng: position?.lng ?? null,
google_place_id: form.google_place_id || null,
google_ftid: form.google_ftid || null,
osm_id: form.osm_id || null,
amap_poi_id: form.amap_poi_id || null,
place_notes: form.notes || null,
website: form.website.trim() || null,
phone: form.phone?.trim() || null,
email: form.email?.trim() || null,
opening_hours: parsePlaceHours(form.opening_hours),
image_url: form.image_url || null,
tags: form.tags ?? [],
};
}
function changesOf(form: PlaceFormData, original: PlaceFormData, existing: boolean): AssistantPlanEdits {
const edits: AssistantPlanEdits = {};
if (form.place_time !== original.place_time) edits.startTime = form.place_time || null;
if (form.end_time !== original.end_time) edits.endTime = form.end_time || null;
if (form.assignment_notes !== original.assignment_notes) edits.notes = form.assignment_notes || null;
if (!existing) {
if (form.category_id !== original.category_id)
edits.categoryId = form.category_id ? Number(form.category_id) : null;
const previous = placeValues(original);
const changed = Object.entries(placeValues(form)).filter(
([field, value]) => JSON.stringify(previous[field as keyof PlacePatch]) !== JSON.stringify(value)
);
if (changed.length) edits.place = Object.fromEntries(changed);
}
return edits;
}
export default function AssistantPlaceProposal({
preview,
args,
edits,
disabled,
onEdit,
onClose,
}: {
preview: AssistantChangePreview;
args: unknown;
edits: AssistantPlanEdits | undefined;
disabled: boolean;
onEdit: (edits: AssistantPlanEdits) => void;
onClose: () => void;
}) {
const { t } = useTranslation();
const { tripId, variant } = useAssistantView();
const phone = useIsPhone();
const previewEdit = useAssistantStore((s) => s.previewPlanEdit);
const categories = useTripStore((s) => s.categories);
const dayAssignments = useTripStore((s) => (preview.dayId == null ? undefined : s.assignments[preview.dayId]));
const currentPlace = useTripStore((s) => s.places.find((place) => place.id === preview.effect?.placeId));
const existing = preview.verbKey === 'assignPlace';
const [original] = useState(() => {
const categoryId =
preview.effect?.place?.categoryId ??
currentPlace?.category_id ??
categories.find((category) => category.name === planField(preview, 'category'))?.id ??
null;
const form = originalForm(preview, args, categoryId);
return existing && currentPlace ? { ...form, name: currentPlace.name, address: currentPlace.address ?? '' } : form;
});
const [initialForm] = useState(() => restoreDraft(original, edits));
const { toolCallId } = preview;
const onPreview = useCallback(
(form: PlaceFormData) => {
if (!existing && (form.lat || form.lng) && !formPin(form)) return;
const parsed = assistantPlanEditsSchema.safeParse(changesOf(form, original, existing));
if (parsed.success) previewEdit(tripId, toolCallId, parsed.data);
},
[existing, original, previewEdit, toolCallId, tripId]
);
useEffect(() => () => previewEdit(tripId, toolCallId, null), [previewEdit, toolCallId, tripId]);
const onSave = (form: PlaceFormData) => {
if (!existing && (form.lat || form.lng) && !formPin(form)) throw new Error(t('places.saveError'));
const parsed = assistantPlanEditsSchema.safeParse(changesOf(form, original, existing));
if (!parsed.success) throw new Error(t('places.saveError'));
onEdit(parsed.data);
};
return (
<PlaceFormModal
isOpen
onClose={onClose}
place={null}
tripId={tripId}
categories={categories}
assignmentId={null}
dayAssignments={dayAssignments}
isMobile={phone || variant === 'fullscreen'}
proposal={{ initialForm, existing, dayId: preview.dayId, disabled, onPreview, onSave }}
/>
);
}
@@ -0,0 +1,146 @@
import type { AssistantChangePreview, AssistantPlanEdits } from '@trek/shared';
import { Check, Pencil } from 'lucide-react';
import { lazy, Suspense, useEffect, useId, useState } from 'react';
import { useTranslation } from '../../i18n';
import { useAssistantStore } from '../../store/assistantStore';
import { EditorField, PANEL, TEXTAREA } from '../shared/dialogParts';
import {
DialogButton,
DialogFooter,
DialogHeader,
DialogShell,
DialogTile,
FooterSpacer,
NEUTRAL_TINT,
} from '../shared/DialogShell';
import { Tooltip } from '../shared/Tooltip';
import { isVisitProposal, planField, proposalNote } from './assistantPlanFieldsModel';
import { useAssistantView } from './assistantViewContext';
const AssistantPlaceProposal = lazy(() => import('./AssistantPlaceProposal'));
interface ProposalEditProps {
preview: AssistantChangePreview;
args?: unknown;
edits: AssistantPlanEdits | undefined;
disabled: boolean;
onEdit: (patch: AssistantPlanEdits) => void;
}
export default function AssistantPlanFields({ preview, args, edits, disabled, onEdit }: ProposalEditProps) {
const { t } = useTranslation();
const [open, setOpen] = useState(false);
return (
<>
<Tooltip label={t('common.edit')} disabled={disabled}>
<button
type="button"
aria-label={t('common.edit')}
aria-haspopup="dialog"
disabled={disabled}
onClick={() => setOpen(true)}
className="relative grid h-8 w-8 shrink-0 place-items-center self-start rounded-lg text-content-muted transition-colors focus-visible:ring-2 focus-visible:ring-accent enabled:hover:bg-accent enabled:hover:text-accent-text disabled:opacity-50 [@media(pointer:coarse)]:before:absolute [@media(pointer:coarse)]:before:-inset-1.5"
>
<Pencil size={14} aria-hidden="true" />
</button>
</Tooltip>
{open &&
(isVisitProposal(preview) ? (
<Suspense fallback={null}>
<AssistantPlaceProposal
preview={preview}
args={args}
edits={edits}
disabled={disabled}
onEdit={onEdit}
onClose={() => setOpen(false)}
/>
</Suspense>
) : (
<DayNoteEditDialog
preview={preview}
edits={edits}
disabled={disabled}
onEdit={onEdit}
onClose={() => setOpen(false)}
/>
))}
</>
);
}
function DayNoteEditDialog({ preview, edits, disabled, onEdit, onClose }: ProposalEditProps & { onClose: () => void }) {
const { t } = useTranslation();
const { tripId } = useAssistantView();
const { toolCallId } = preview;
const previewPlanEdit = useAssistantStore((s) => s.previewPlanEdit);
const id = useId();
const [draft, setDraft] = useState<AssistantPlanEdits>(() => edits ?? {});
const change = (patch: AssistantPlanEdits) => setDraft((current) => ({ ...current, ...patch }));
const note = proposalNote(preview, draft);
const noteTitle = draft.noteTitle ?? planField(preview, 'title') ?? preview.subject;
useEffect(() => previewPlanEdit(tripId, toolCallId, draft), [draft, previewPlanEdit, toolCallId, tripId]);
useEffect(() => () => previewPlanEdit(tripId, toolCallId, null), [previewPlanEdit, toolCallId, tripId]);
const noteLabel = t('assistant.change.label.content');
const save = () => {
if (Object.keys(draft).length > 0) onEdit(draft);
onClose();
};
return (
<DialogShell
labelledBy={id}
width="narrow"
onClose={onClose}
header={
<DialogHeader
labelId={id}
tint={NEUTRAL_TINT}
tile={
<DialogTile>
<Pencil size={19} aria-hidden="true" />
</DialogTile>
}
eyebrow={t('common.edit')}
titleInput={{
label: t('assistant.change.label.title'),
value: noteTitle,
required: true,
maxLength: 500,
readOnly: disabled,
onChange: (noteTitle) => change({ noteTitle }),
}}
onClose={onClose}
/>
}
footer={
<DialogFooter>
<FooterSpacer />
<DialogButton onClick={onClose}>{t('common.cancel')}</DialogButton>
<DialogButton
variant="primary"
icon={<Check size={15} aria-hidden="true" />}
onClick={save}
disabled={disabled || !noteTitle.trim()}
>
{t('common.save')}
</DialogButton>
</DialogFooter>
}
>
<fieldset disabled={disabled} className={`${PANEL} m-0 min-w-0`}>
<EditorField label={noteLabel} htmlFor={`${id}-note`}>
<textarea
id={`${id}-note`}
className={TEXTAREA}
rows={4}
maxLength={2000}
value={note ?? ''}
onChange={(e) => change({ noteBody: e.target.value || null })}
/>
</EditorField>
</fieldset>
</DialogShell>
);
}
@@ -7,7 +7,7 @@
*/ */
import { describe, expect, it } from 'vitest'; import { describe, expect, it } from 'vitest';
import { render, screen } from '../../../tests/helpers/render'; import { fireEvent, render, screen } from '../../../tests/helpers/render';
import AssistantSources from './AssistantSources'; import AssistantSources from './AssistantSources';
import { messageBlocks } from './assistantParts'; import { messageBlocks } from './assistantParts';
@@ -31,7 +31,8 @@ describe('AssistantSources', () => {
expect(screen.getByRole('link', { name: 'example.org' })).toBeInTheDocument(); expect(screen.getByRole('link', { name: 'example.org' })).toBeInTheDocument();
}); });
it('FE-AI-SOURCES-002: an answer keeps its sources as a block of their own after its text', () => { it('FE-AI-SOURCES-002: bundles citations from multiple steps below the changes and keeps links with JSON titles', () => {
const exa = 'https://exa.ai/library/places?example=test';
const blocks = messageBlocks( const blocks = messageBlocks(
{ {
id: 'm1', id: 'm1',
@@ -40,12 +41,46 @@ describe('AssistantSources', () => {
createdAt: '2026-10-23T10:00:00.000Z', createdAt: '2026-10-23T10:00:00.000Z',
parts: [ parts: [
{ type: 'tool-call', toolCallId: 'web-1', toolName: 'web_search', args: { query: 'x' }, result: 'searched' }, { type: 'tool-call', toolCallId: 'web-1', toolName: 'web_search', args: { query: 'x' }, result: 'searched' },
{
type: 'data-trek-sources',
data: {
sources: [
{ url: 'https://a.example', title: 'https://a.example' },
{ url: exa, title: '{"places":[{"id":"truncated' },
],
},
},
{ type: 'text', text: 'Eat at the harbour.' }, { type: 'text', text: 'Eat at the harbour.' },
{ type: 'data-trek-sources', data: { sources: [{ url: 'https://a.example', title: 'A' }] } }, { type: 'tool-call', toolCallId: 'w1', toolName: 'create_todo', args: {}, approval: { id: 'w1' } },
{ type: 'data-trek-sources', data: { sources: [{ url: 'https://a.example', title: 'Harbour guide' }] } },
], ],
}, },
false false
); );
expect(blocks.map((block) => block.kind)).toEqual(['steps', 'text', 'sources']); expect(blocks.map((block) => block.kind)).toEqual(['steps', 'text', 'change', 'sources']);
const sources = blocks.find((block) => block.kind === 'sources')?.sources;
expect(sources).toEqual([
{ url: 'https://a.example', title: 'Harbour guide' },
{ url: exa, title: '' },
]);
render(<AssistantSources sources={sources ?? []} />);
expect(screen.getByRole('link', { name: 'exa.ai' })).toHaveAttribute('href', exa);
});
it('shows three links by default and lets the reader expand and collapse the list', () => {
render(
<AssistantSources
sources={['One', 'Two', 'Three', 'Four'].map((title) => ({ title, url: `https://example.org/${title}` }))}
/>
);
expect(screen.getAllByRole('link')).toHaveLength(3);
const more = screen.getByRole('button', { name: 'More sources' });
expect(more).toHaveAttribute('aria-expanded', 'false');
fireEvent.click(more);
expect(screen.getAllByRole('link')).toHaveLength(4);
const less = screen.getByRole('button', { name: 'Show less' });
expect(less).toHaveAttribute('aria-expanded', 'true');
fireEvent.click(less);
expect(screen.getAllByRole('link')).toHaveLength(3);
}); });
}); });
@@ -1,7 +1,11 @@
import type { AssistantSources as Sources } from '@trek/shared'; import type { AssistantSources as Sources } from '@trek/shared';
import { Globe } from 'lucide-react'; import { ChevronDown, Globe } from 'lucide-react';
import { useId, useState } from 'react';
import { useTranslation } from '../../i18n'; import { useTranslation } from '../../i18n';
import { Tooltip } from '../shared/Tooltip';
const INITIAL_COUNT = 3;
/** A page's host without "www.", as the chip names it; the whole address where it does not read as one. */ /** A page's host without "www.", as the chip names it; the whole address where it does not read as one. */
function hostOf(url: string): string { function hostOf(url: string): string {
@@ -19,30 +23,48 @@ function hostOf(url: string): string {
*/ */
export default function AssistantSources({ sources }: { sources: Sources['sources'] }) { export default function AssistantSources({ sources }: { sources: Sources['sources'] }) {
const { t } = useTranslation(); const { t } = useTranslation();
const id = useId();
const [expanded, setExpanded] = useState(false);
const visible = expanded ? sources : sources.slice(0, INITIAL_COUNT);
return ( return (
<nav aria-label={t('assistant.sources.title')} className="flex flex-col gap-1.5"> <nav aria-label={t('assistant.sources.title')} className="flex flex-col gap-1.5">
<span className="font-geist text-caption font-bold uppercase tracking-[.08em] text-content-faint"> <span className="font-geist text-caption font-bold uppercase tracking-[.08em] text-content-faint">
{t('assistant.sources.title')} {t('assistant.sources.title')}
</span> </span>
<ul className="m-0 flex list-none flex-wrap gap-1.5 p-0"> <ul id={id} className="m-0 flex list-none flex-wrap gap-1.5 p-0">
{sources.map((source) => ( {visible.map(({ url, title }) => {
<li key={source.url} className="min-w-0 max-w-full"> const host = hostOf(url);
<a const label = title && title !== url ? title : host;
href={source.url} return (
target="_blank" <li key={url} className="min-w-0 max-w-full">
rel="noopener noreferrer nofollow" <Tooltip label={label} placement="top">
title={source.title} <a
className="flex min-w-0 max-w-[16rem] items-center gap-1.5 rounded-full border border-edge-faint bg-surface-secondary px-2.5 py-1 text-caption text-content-secondary no-underline transition-colors hover:bg-surface-hover hover:text-content" href={url}
> target="_blank"
<Globe size={11} strokeWidth={2.2} aria-hidden="true" className="flex-none text-content-faint" /> rel="noopener noreferrer nofollow"
<span className="flex-none font-medium">{hostOf(source.url)}</span> className="flex min-w-0 max-w-[18rem] items-center gap-1.5 rounded-full border border-edge-faint bg-surface-secondary px-2.5 py-1 text-caption no-underline transition-colors hover:bg-surface-hover focus-visible:ring-2 focus-visible:ring-accent"
{source.title && source.title !== source.url && ( >
<bdi className="min-w-0 truncate text-content-muted">{source.title}</bdi> <Globe size={11} strokeWidth={2.2} aria-hidden="true" className="flex-none text-content-faint" />
)} <bdi className="min-w-0 truncate font-semibold text-content">{label}</bdi>
</a> {label !== host && <bdi className="max-w-[35%] shrink-0 truncate text-content-muted">{host}</bdi>}
</li> </a>
))} </Tooltip>
</li>
);
})}
</ul> </ul>
{sources.length > INITIAL_COUNT && (
<button
type="button"
aria-expanded={expanded}
aria-controls={id}
onClick={() => setExpanded(!expanded)}
className="inline-flex min-h-7 items-center gap-1 self-start rounded-md px-1.5 text-caption font-medium text-content-muted transition-colors hover:bg-surface-hover hover:text-content focus-visible:ring-2 focus-visible:ring-accent"
>
{t(expanded ? 'common.showLess' : 'assistant.sources.more')}
<ChevronDown size={13} aria-hidden="true" className={expanded ? 'rotate-180' : ''} />
</button>
)}
</nav> </nav>
); );
} }
@@ -2,8 +2,9 @@ import { ChevronRight } from 'lucide-react';
import { useState } from 'react'; import { useState } from 'react';
import { useTranslation } from '../../i18n'; import { useTranslation } from '../../i18n';
import { POI_CATEGORIES } from '../Map/poiCategories';
import AssistantLiveStep from './AssistantLiveStep'; import AssistantLiveStep from './AssistantLiveStep';
import { toolStepKey } from './assistantModel'; import { liveStepText } from './assistantModel';
import type { ToolStep } from './assistantParts'; import type { ToolStep } from './assistantParts';
/** /**
@@ -37,9 +38,20 @@ export default function AssistantToolSteps({ steps }: { steps: ToolStep[] }) {
</button> </button>
{open && ( {open && (
<ul className="m-0 mt-1 list-none space-y-0.5 border-s border-edge-faint ps-3"> <ul className="m-0 mt-1 list-none space-y-0.5 border-s border-edge-faint ps-3">
{steps.map((step) => ( {steps.map((step) => {
<li key={step.toolCallId}>{t(toolStepKey(step.toolName))}</li> const labels = step.categories?.flatMap((key) => {
))} const category = POI_CATEGORIES.find((entry) => entry.key === key);
return category ? [t(category.labelKey)] : [];
});
const { key, params } = labels?.length
? { key: 'assistant.step.searchingFor', params: { query: labels.join(', ') } }
: liveStepText(step.toolName, step.query ?? null);
return (
<li key={step.toolCallId} dir="auto" className="break-words">
{t(key, params)}
</li>
);
})}
</ul> </ul>
)} )}
</div> </div>
@@ -170,12 +170,18 @@ describe('AssistantWindow', () => {
it('FE-AI-WIN-014: minimized outside a trip, the round button brings the home chat back', () => { it('FE-AI-WIN-014: minimized outside a trip, the round button brings the home chat back', () => {
seed({ open: true, minimized: true }); seed({ open: true, minimized: true });
render(<AssistantWindow trip={null} />); render(<AssistantWindow trip={null} />, { initialEntries: ['/atlas'] });
expect(screen.getByText('chat 0 Your travels')).not.toBeVisible(); expect(screen.getByText('chat 0 Your travels')).not.toBeVisible();
fireEvent.click(screen.getByRole('button', { name: 'Assistant' })); fireEvent.click(screen.getByRole('button', { name: 'Assistant' }));
expect(useAssistantStore.getState().window.minimized).toBe(false); expect(useAssistantStore.getState().window.minimized).toBe(false);
}); });
it('hides the minimized launcher on the dashboard', () => {
seed({ open: true, minimized: true });
render(<AssistantWindow trip={null} />);
expect(screen.queryByRole('button', { name: 'Assistant' })).not.toBeInTheDocument();
});
it('FE-AI-WIN-005: closed while writing, the chat stays mounted and the round button breathes until it is opened', () => { it('FE-AI-WIN-005: closed while writing, the chat stays mounted and the round button breathes until it is opened', () => {
seed({ open: true, minimized: true }, true); seed({ open: true, minimized: true }, true);
render(<AssistantWindow trip={TRIP} />); render(<AssistantWindow trip={TRIP} />);
@@ -1,7 +1,7 @@
import './assistant.css'; import './assistant.css';
import { type CSSProperties, type KeyboardEvent, useCallback, useEffect, useRef, useState } from 'react'; import { type CSSProperties, type KeyboardEvent, useCallback, useEffect, useRef, useState } from 'react';
import { useNavigate } from 'react-router'; import { useMatch, useNavigate } from 'react-router';
import type { WindowRect } from '../../hooks/useDragResize'; import type { WindowRect } from '../../hooks/useDragResize';
import { useTranslation } from '../../i18n'; import { useTranslation } from '../../i18n';
@@ -200,6 +200,7 @@ function windowChat(
export default function AssistantWindow({ trip, onOpen, onFocusDay, onRevealMap }: AssistantWindowProps) { export default function AssistantWindow({ trip, onOpen, onFocusDay, onRevealMap }: AssistantWindowProps) {
const navigate = useNavigate(); const navigate = useNavigate();
const onDashboard = useMatch('/') !== null;
const available = useAssistantStore((s) => s.status?.available === true); const available = useAssistantStore((s) => s.status?.available === true);
const open = useAssistantStore((s) => s.window.open); const open = useAssistantStore((s) => s.window.open);
const minimized = useAssistantStore((s) => s.window.minimized); const minimized = useAssistantStore((s) => s.window.minimized);
@@ -267,8 +268,9 @@ export default function AssistantWindow({ trip, onOpen, onFocusDay, onRevealMap
onOpenTripChat={atHome ? home.openTripChat : undefined} onOpenTripChat={atHome ? home.openTripChat : undefined}
tripSwitch={tripSwitch} tripSwitch={tripSwitch}
/> />
{/* Hidden while an answer may still come in: the round button brings it back, on any page. */} {minimized && (!onDashboard || !!routeChat) && (
{minimized && <AssistantLauncher variant="floating" tripId={launcherTrip} focusOnMount />} <AssistantLauncher variant="floating" tripId={launcherTrip} focusOnMount />
)}
</> </>
); );
} }
@@ -118,6 +118,20 @@ const ERRORS: Record<AssistantErrorCode, AssistantErrorView> = {
/** The limits a provider sets; the line names the provider instead of guessing at its plan. */ /** The limits a provider sets; the line names the provider instead of guessing at its plan. */
const PROVIDER_LIMITS: ReadonlySet<AssistantErrorCode> = new Set(['rate_limited', 'usage_limit']); const PROVIDER_LIMITS: ReadonlySet<AssistantErrorCode> = new Set(['rate_limited', 'usage_limit']);
/** A route produced for the latest question can still be inspected after an interrupted answer. */
export function hasCurrentTourProposal(messages: readonly AssistantMessage[]): boolean {
for (let index = messages.length - 1; index >= 0; index--) {
const message = messages[index];
if (!message || message.role === 'user') break;
const hasRoute = message.parts.some((part) => {
const card = part.type === 'data-trek-card' ? part.data.card : null;
return card?.kind === 'tourRoute' && card.source === 'proposal' && card.routed;
});
if (hasRoute) return true;
}
return false;
}
/** /**
* The line an error shows and its one action. The daily limit only offers * The line an error shows and its one action. The daily limit only offers
* connecting an own provider where the policy allows one. A provider's limit * connecting an own provider where the policy allows one. A provider's limit
@@ -126,10 +140,13 @@ const PROVIDER_LIMITS: ReadonlySet<AssistantErrorCode> = new Set(['rate_limited'
*/ */
export function errorView( export function errorView(
code: AssistantErrorCode, code: AssistantErrorCode,
opts: { canConnectOwn: boolean; provider?: string } opts: { canConnectOwn: boolean; provider?: string; hasTourProposal?: boolean }
): AssistantErrorView { ): AssistantErrorView {
const view = ERRORS[code]; const view = ERRORS[code];
if (code === 'daily_limit' && !opts.canConnectOwn) return { ...view, action: null }; if (code === 'daily_limit' && !opts.canConnectOwn) return { ...view, action: null };
if (code === 'rate_limited' && opts.provider && opts.hasTourProposal) {
return { ...view, messageKey: 'assistant.error.providerLimitAfterRoute' };
}
if (PROVIDER_LIMITS.has(code) && opts.provider) return { ...view, messageKey: 'assistant.error.providerLimit' }; if (PROVIDER_LIMITS.has(code) && opts.provider) return { ...view, messageKey: 'assistant.error.providerLimit' };
return view; return view;
} }
@@ -98,6 +98,27 @@ describe('messageBlocks', () => {
expect(messageBlocks(message(parts), false)[0]).toMatchObject({ steps: [{ running: false }] }); expect(messageBlocks(message(parts), false)[0]).toMatchObject({ steps: [{ running: false }] });
}); });
it('keeps the query and categories of completed searches for their step labels', () => {
const searches = [
{ toolCallId: 'r1', toolName: 'search_place', args: { query: ' Hachikō\n statue ' } },
{ toolCallId: 'r2', toolName: 'search_places_via_plugins', args: { query: 'Shibuya Sky' } },
{ toolCallId: 'r3', toolName: 'search_pois', args: { category: ['restaurant', 'cafe'] } },
];
const parts = searches.map((search): AssistantMessagePart => ({
...search,
type: 'tool-call',
result: 'searched',
}));
expect(messageBlocks(message(parts), false)[0]).toMatchObject({
kind: 'steps',
steps: [
{ toolCallId: 'r1', query: 'Hachikō statue', running: false },
{ toolCallId: 'r2', query: 'Shibuya Sky', running: false },
{ toolCallId: 'r3', categories: ['restaurant', 'cafe'], running: false },
],
});
});
it('FE-AI-PARTS-003: the changes of one step share a card, each with its preview, wherever the preview sits', () => { it('FE-AI-PARTS-003: the changes of one step share a card, each with its preview, wherever the preview sits', () => {
const blocks = messageBlocks( const blocks = messageBlocks(
message([ message([
@@ -1,5 +1,6 @@
import { import {
ASSISTANT_FOLLOW_UPS_TOOL, ASSISTANT_FOLLOW_UPS_TOOL,
assistantSourceTitle,
type AssistantApplied, type AssistantApplied,
type AssistantChangeEffect, type AssistantChangeEffect,
type AssistantChangeLabelKey, type AssistantChangeLabelKey,
@@ -39,6 +40,8 @@ export interface ToolStep {
toolName: string; toolName: string;
/** Still waiting for its result while the answer is being written. */ /** Still waiting for its result while the answer is being written. */
running: boolean; running: boolean;
query?: string;
categories?: string[];
} }
/** /**
@@ -50,6 +53,7 @@ export type ChangeState = 'pending' | 'applying' | 'applied' | 'failed' | 'disca
export interface ChangeItem { export interface ChangeItem {
toolCallId: string; toolCallId: string;
args?: unknown;
/** What the card says about it; null until the preview arrived. */ /** What the card says about it; null until the preview arrived. */
preview: AssistantChangePreview | null; preview: AssistantChangePreview | null;
/** The receipt of an applied change. */ /** The receipt of an applied change. */
@@ -269,6 +273,7 @@ function changeItemOf(
const applied = receipts.get(part.toolCallId) ?? null; const applied = receipts.get(part.toolCallId) ?? null;
return { return {
toolCallId: part.toolCallId, toolCallId: part.toolCallId,
...(preview?.verbKey === 'addPlaceToDay' || preview?.verbKey === 'assignPlace' ? { args: part.args } : {}),
preview, preview,
applied, applied,
state: changeState(part, applied), state: changeState(part, applied),
@@ -295,8 +300,8 @@ function changeState(part: ToolCallPart, applied: AssistantApplied | null): Chan
* The places of all its searches join into one strip where the newest search * The places of all its searches join into one strip where the newest search
* sat, each place once, without the ones a change the model proposed in the * sat, each place once, without the ones a change the model proposed in the
* answer already holds; the weather of all steps joins * answer already holds; the weather of all steps joins
* into one row where the first look sat. A strip does not split the steps * into one row where the first look sat. The sources of all steps sit together
* around it: a step after it joins the row of steps before it. * at the end of the answer.
* *
* A reading tool's card joins the cards block of its group (by `rules`, the * A reading tool's card joins the cards block of its group (by `rules`, the
* kinds' looks unless a test hands others) when only steps lie between them; * kinds' looks unless a test hands others) when only steps lie between them;
@@ -311,6 +316,7 @@ export function messageBlocks(
const previews = new Map<string, AssistantChangePreview>(); const previews = new Map<string, AssistantChangePreview>();
const receipts = new Map<string, AssistantApplied>(); const receipts = new Map<string, AssistantApplied>();
const cards = new Map<string, TrekCard>(); const cards = new Map<string, TrekCard>();
const sources = new Map<string, AssistantSources['sources'][number]>();
const changeIds = new Set<string>(); const changeIds = new Set<string>();
const effects: AssistantChangeEffect[] = []; const effects: AssistantChangeEffect[] = [];
// A place the user suggested from the strip stays on it, marked as suggested. // A place the user suggested from the strip stays on it, marked as suggested.
@@ -324,6 +330,11 @@ export function messageBlocks(
previews.set(part.data.toolCallId, part.data); previews.set(part.data.toolCallId, part.data);
if (part.data.effect && !fromStrip.has(part.data.toolCallId)) effects.push(part.data.effect); if (part.data.effect && !fromStrip.has(part.data.toolCallId)) effects.push(part.data.effect);
changeIds.add(part.data.toolCallId); changeIds.add(part.data.toolCallId);
} else if (part.type === 'data-trek-sources') {
for (const { url, title } of part.data.sources) {
const previous = sources.get(url);
if (!previous?.title || previous.title === url) sources.set(url, { url, title: assistantSourceTitle(title) });
}
} else if (part.type === 'data-trek-applied') receipts.set(part.data.toolCallId, part.data); } else if (part.type === 'data-trek-applied') receipts.set(part.data.toolCallId, part.data);
else if (part.type === 'data-trek-places') lastPlaces = index; else if (part.type === 'data-trek-places') lastPlaces = index;
else if (part.type === 'data-trek-weather' && firstWeather < 0) firstWeather = index; else if (part.type === 'data-trek-weather' && firstWeather < 0) firstWeather = index;
@@ -335,6 +346,9 @@ export function messageBlocks(
const changeCards = message.parts.flatMap((p) => (p.type === 'data-trek-change' && p.data.card ? [p.data.card] : [])); const changeCards = message.parts.flatMap((p) => (p.type === 'data-trek-change' && p.data.card ? [p.data.card] : []));
const placesHidden = const placesHidden =
[...cards.values(), ...changeCards].some((card) => rules.hidesFoundPlaces?.(card) === true) || [...cards.values(), ...changeCards].some((card) => rules.hidesFoundPlaces?.(card) === true) ||
[...previews.values()].some(
(preview) => preview.verbKey === 'addPlaceToDay' || preview.verbKey === 'assignPlace'
) ||
message.parts.some((p) => p.type === 'tool-call' && TOUR_PLANNING_TOOLS.has(p.toolName)); message.parts.some((p) => p.type === 'tool-call' && TOUR_PLANNING_TOOLS.has(p.toolName));
const blocks: MessageBlock[] = []; const blocks: MessageBlock[] = [];
message.parts.forEach((part, index) => { message.parts.forEach((part, index) => {
@@ -347,10 +361,6 @@ export function messageBlocks(
if (strip) blocks.push(strip); if (strip) blocks.push(strip);
return; return;
} }
if (part.type === 'data-trek-sources') {
blocks.push({ kind: 'sources', key: `sources-${index}`, sources: part.data.sources });
return;
}
if (part.type === 'data-trek-weather' && index === firstWeather) { if (part.type === 'data-trek-weather' && index === firstWeather) {
blocks.push({ kind: 'weather', key: `weather-${index}`, days: weatherDays(message.parts) }); blocks.push({ kind: 'weather', key: `weather-${index}`, days: weatherDays(message.parts) });
return; return;
@@ -373,18 +383,35 @@ export function messageBlocks(
blocks.push({ kind: 'remembered', key: `remembered-${part.toolCallId}`, note }); blocks.push({ kind: 'remembered', key: `remembered-${part.toolCallId}`, note });
return; return;
} }
const step: ToolStep = { const step = toolStep(part, writing);
toolCallId: part.toolCallId,
toolName: part.toolName,
running: writing && part.result === undefined,
};
const steps = openSteps(blocks); const steps = openSteps(blocks);
if (steps) steps.steps.push(step); if (steps) steps.steps.push(step);
else blocks.push({ kind: 'steps', key: `steps-${part.toolCallId}`, steps: [step] }); else blocks.push({ kind: 'steps', key: `steps-${part.toolCallId}`, steps: [step] });
}); });
if (sources.size > 0) blocks.push({ kind: 'sources', key: 'sources', sources: [...sources.values()] });
return withoutYielded(blocks, rules); return withoutYielded(blocks, rules);
} }
function toolStep(part: ToolCallPart, writing: boolean): ToolStep {
const { toolCallId, toolName, args } = part;
const step = { toolCallId, toolName, running: writing && part.result === undefined };
if (!args || typeof args !== 'object') return step;
if (toolName === 'search_place' || toolName === 'search_places_via_plugins' || toolName === 'web_search') {
const { query } = args as { query?: unknown };
if (typeof query === 'string' && query.trim()) {
return { ...step, query: query.trim().replace(/\s+/g, ' ').slice(0, 200) };
}
}
if (toolName === 'search_pois') {
const { category } = args as { category?: unknown };
const categories = (Array.isArray(category) ? category : [category])
.filter((entry): entry is string => typeof entry === 'string')
.slice(0, 8);
if (categories.length) return { ...step, categories };
}
return step;
}
/** /**
* Whether "+ Day" was already pressed on this found place in the answer: a * Whether "+ Day" was already pressed on this found place in the answer: a
* suggestion from the strip names the trip's place by its id, a new one by * suggestion from the strip names the trip's place by its id, a new one by
@@ -477,6 +504,10 @@ export const CHANGE_LABELS: Record<AssistantChangeLabelKey, { labelKey: string }
*/ */
export function tailStart(blocks: MessageBlock[]): number { export function tailStart(blocks: MessageBlock[]): number {
let i = blocks.length; let i = blocks.length;
while (i > 0 && (blocks[i - 1].kind === 'text' || blocks[i - 1].kind === 'change')) i -= 1; while (
i > 0 &&
(blocks[i - 1].kind === 'text' || blocks[i - 1].kind === 'change' || blocks[i - 1].kind === 'sources')
)
i -= 1;
return i; return i;
} }
@@ -0,0 +1,27 @@
import type { AssistantChangeLabelKey, AssistantChangePreview, AssistantPlanEdits } from '@trek/shared';
export function isVisitProposal(preview: AssistantChangePreview | null | undefined) {
return preview?.verbKey === 'addPlaceToDay' || preview?.verbKey === 'assignPlace';
}
export function isDayNoteProposal(preview: AssistantChangePreview | null | undefined) {
return preview?.verbKey === 'addDayNote' || preview?.verbKey === 'updateDayNote';
}
export function planField(preview: AssistantChangePreview, field: AssistantChangeLabelKey) {
return preview.rows.find((row) => row.labelKey === field)?.after;
}
function dayNoteBody(preview: AssistantChangePreview) {
return planField(preview, 'content') ?? (preview.verbKey === 'addDayNote' ? planField(preview, 'time') : undefined);
}
export function proposalNote(preview: AssistantChangePreview, edits: AssistantPlanEdits | undefined) {
return isVisitProposal(preview)
? edits?.notes === undefined
? planField(preview, 'notes')
: edits.notes
: edits?.noteBody === undefined
? dayNoteBody(preview)
: edits.noteBody;
}
@@ -1,13 +1,16 @@
import type { AssistantChangePreview, TrekCardKind } from '@trek/shared'; import type { AssistantChangePreview, AssistantPlanEdits, TrekCardKind } from '@trek/shared';
import { Check, Undo2 } from 'lucide-react'; import { Check, Paperclip, Undo2 } from 'lucide-react';
import { Fragment, type ReactNode } from 'react'; import { Fragment, type ReactNode } from 'react';
import { useTranslation } from '../../../i18n'; import { useTranslation } from '../../../i18n';
import { Tooltip } from '../../shared/Tooltip'; import { Tooltip } from '../../shared/Tooltip';
import AssistantChangeFields from '../AssistantChangeFields'; import AssistantChangeFields from '../AssistantChangeFields';
import type { ChangeItem } from '../assistantParts'; import type { ChangeItem } from '../assistantParts';
import AssistantPlanFields from '../AssistantPlanFields';
import { isDayNoteProposal, isVisitProposal, planField, proposalNote } from '../assistantPlanFieldsModel';
import { useAssistantView } from '../assistantViewContext'; import { useAssistantView } from '../assistantViewContext';
import { useChangeHover } from '../useChangeHover'; import { useChangeHover } from '../useChangeHover';
import { isSingleBookingDraft } from './booking/bookingCardModel';
import { TOOL_LABELS, verbLookOf } from './cardLooks'; import { TOOL_LABELS, verbLookOf } from './cardLooks';
import type { CardView } from './cardTypes'; import type { CardView } from './cardTypes';
import { viewOf } from './cardViews'; import { viewOf } from './cardViews';
@@ -140,6 +143,11 @@ function BodySlot({ item, settled }: { item: ChangeItem; settled: boolean }) {
); );
} }
function inlineBookingCard(item: ChangeItem): boolean {
const card = item.card;
return card?.kind === 'booking' && isSingleBookingDraft(card);
}
/** A decided change that no longer stands: discarded, expired or taken back. */ /** A decided change that no longer stands: discarded, expired or taken back. */
const settledOf = (item: ChangeItem, undone: boolean) => const settledOf = (item: ChangeItem, undone: boolean) =>
item.state === 'discarded' || item.state === 'expired' || undone; item.state === 'discarded' || item.state === 'expired' || undone;
@@ -164,11 +172,21 @@ function Receipt({
const settled = settledOf(item, undone); const settled = settledOf(item, undone);
const statusLabel = t(undone ? 'assistant.change.undone' : receipt.labelKey); const statusLabel = t(undone ? 'assistant.change.undone' : receipt.labelKey);
const view = item.card ? viewOf(item.card) : null; const view = item.card ? viewOf(item.card) : null;
const inlineBooking = inlineBookingCard(item);
return ( return (
<div className="trek-assistant-enter flex items-center gap-2.5 py-1.5"> <div className="trek-assistant-enter flex items-center gap-2.5 py-1.5">
<Lead item={item} view={view} dimmed={settled} /> {!inlineBooking && <Lead item={item} view={view} dimmed={settled} />}
<div className={`min-w-0 flex-1 ${settled ? 'opacity-60' : ''}`}> <div className={`min-w-0 flex-1 ${settled ? 'opacity-60' : ''}`}>
<ChangeHead item={item} view={view} struck={settled} /> {inlineBooking ? (
<Slot
name="Body"
item={item}
view={view}
fallback={<ChangeHead item={item} view={view} struck={settled} />}
/>
) : (
<ChangeHead item={item} view={view} struck={settled} />
)}
</div> </div>
{applied && <EntityActions applied={applied} card={item.card} />} {applied && <EntityActions applied={applied} card={item.card} />}
{canUndo && ( {canUndo && (
@@ -203,67 +221,134 @@ function PendingRow({
withChoice, withChoice,
disabled, disabled,
onToggle, onToggle,
edits,
onEdit,
groupedDay,
}: { }: {
item: ChangeItem; item: ChangeItem;
excluded: boolean; excluded: boolean;
withChoice: boolean; withChoice: boolean;
disabled: boolean; disabled: boolean;
onToggle: () => void; onToggle: () => void;
edits: AssistantPlanEdits | undefined;
onEdit: (patch: AssistantPlanEdits) => void;
groupedDay: boolean;
}) { }) {
const { t } = useTranslation(); const { t } = useTranslation();
const { tripId } = useAssistantView(); const { tripId } = useAssistantView();
const { litFromMap, handlers } = useChangeHover(tripId, item.preview?.effect ? item.toolCallId : null); const { litFromMap, handlers } = useChangeHover(tripId, item.preview?.effect ? item.toolCallId : null);
const preview = item.preview; const preview = item.preview;
const view = item.card ? viewOf(item.card) : null; const view = item.card ? viewOf(item.card) : null;
const aside = <Slot item={item} view={view} name="Aside" />; const inlineBooking = inlineBookingCard(item);
const editable = preview && (isVisitProposal(preview) || isDayNoteProposal(preview));
return ( return (
<div <div
{...handlers} {...handlers}
className={`-mx-1.5 flex items-center gap-2.5 rounded-[12px] px-1.5 py-2 transition-[opacity,background-color] ${ className={`-mx-1.5 flex ${inlineBooking ? 'items-start' : 'items-center'} gap-2.5 rounded-[12px] px-1.5 py-2 transition-[opacity,background-color] ${
excluded ? 'opacity-50' : '' excluded ? 'opacity-50' : ''
} ${litFromMap ? 'bg-surface-hover' : 'hover:bg-surface-hover'}`} } ${litFromMap ? 'bg-surface-hover' : 'hover:bg-surface-hover'}`}
> >
{withChoice && ( {withChoice ? (
<button <Tooltip label={t('assistant.change.include')}>
type="button" <button
onClick={onToggle} type="button"
disabled={disabled} onClick={onToggle}
aria-pressed={!excluded} disabled={disabled}
aria-label={t('assistant.change.include')} aria-pressed={!excluded}
className={`grid h-[18px] w-[18px] flex-none place-items-center rounded-full outline-none transition-colors focus-visible:ring-2 focus-visible:ring-accent disabled:opacity-50 ${ aria-label={t('assistant.change.include')}
excluded ? 'border-[1.5px] border-edge bg-surface-card' : 'bg-accent' className="relative grid h-8 w-8 flex-none place-items-center rounded-lg outline-none ring-edge transition-shadow before:absolute before:-inset-1.5 before:rounded-xl hover:ring-1 focus-visible:ring-2 focus-visible:ring-accent disabled:cursor-default"
}`} >
> <Lead item={item} view={view} dimmed={excluded} />
{!excluded && <Check size={11} strokeWidth={3} aria-hidden="true" className="text-accent-text" />} {!excluded && (
</button> <span className="pointer-events-none absolute -bottom-0.5 -end-0.5 grid h-3.5 w-3.5 place-items-center rounded-full bg-accent text-accent-text ring-2 ring-surface-card">
)} <Check size={9} strokeWidth={3} aria-hidden="true" />
<Lead item={item} view={view} dimmed={excluded} /> </span>
<div className="min-w-0 flex-1">
{preview ? (
<>
{view?.ownsSubject ? (
aside
) : (
<SubjectLine subject={preview.subject} struck={false} aside={view?.Aside && aside} block />
)} )}
<span className="mt-1 flex min-w-0 flex-wrap items-center gap-x-1.5 gap-y-1 text-caption text-content-faint"> </button>
<span className="me-0.5 min-w-0 truncate">{verbLabel(preview, t)}</span> </Tooltip>
<DomainChip domain={preview.domain} /> ) : (
{view?.Facts ? ( !inlineBooking && <Lead item={item} view={view} dimmed={excluded} />
<Slot item={item} view={view} name="Facts" fallback={<AssistantChangeFields rows={preview.rows} />} /> )}
) : ( <div className="min-w-0 flex-1">
<AssistantChangeFields rows={preview.rows} /> {inlineBooking ? (
)} <Slot name="Body" item={item} view={view} fallback={<ChangeHead item={item} view={view} struck={false} />} />
</span> ) : preview ? (
</> <PendingDetails item={item} preview={preview} view={view} edits={edits} groupedDay={groupedDay} />
) : ( ) : (
<span className="trek-skeleton inline-block h-4 w-40" aria-hidden="true" /> <span className="trek-skeleton inline-block h-4 w-40" aria-hidden="true" />
)} )}
</div> </div>
{editable && (
<AssistantPlanFields
preview={preview}
args={item.args}
edits={edits}
disabled={disabled || excluded}
onEdit={onEdit}
/>
)}
</div> </div>
); );
} }
function PendingDetails({
item,
preview,
view,
edits,
groupedDay,
}: {
item: ChangeItem;
preview: AssistantChangePreview;
view: View | null;
edits: AssistantPlanEdits | undefined;
groupedDay: boolean;
}) {
const { t } = useTranslation();
const aside = <Slot item={item} view={view} name="Aside" />;
const visit = isVisitProposal(preview);
const dayNote = isDayNoteProposal(preview);
const note = visit || dayNote ? proposalNote(preview, edits) : null;
const receipt = preview.verbKey === 'importBooking' ? planField(preview, 'attachedTo') : undefined;
const rows = preview.rows.filter(
(row) => !(groupedDay && row.labelKey === 'day') && !(dayNote && row.labelKey === 'time')
);
return (
<>
{view?.ownsSubject ? (
aside
) : (
<SubjectLine
subject={edits?.place?.name ?? edits?.noteTitle ?? preview.subject}
struck={false}
aside={view?.Aside && aside}
block
/>
)}
<span className="mt-1 flex min-w-0 flex-wrap items-center gap-x-1.5 gap-y-1 text-caption text-content-faint">
{!visit && <span className="me-0.5 min-w-0 truncate">{verbLabel(preview, t)}</span>}
<DomainChip domain={preview.domain} />
{view?.Facts ? (
<Slot item={item} view={view} name="Facts" fallback={<AssistantChangeFields rows={preview.rows} />} />
) : (
<AssistantChangeFields rows={rows} visit={visit} edits={edits} />
)}
</span>
{receipt && (
<div
className="mt-1 flex min-w-0 items-center gap-1.5 text-caption text-content-muted"
title={t('assistant.attach.chip.keepWithBooking')}
>
<Paperclip size={13} className="flex-none" aria-hidden="true" />
<span className="sr-only">{t('assistant.attach.chip.keepWithBooking')}</span>
<bdi className="truncate">{receipt}</bdi>
</div>
)}
{note && <bdi className="mt-1 block truncate text-caption text-content-muted">{note}</bdi>}
</>
);
}
interface RowsProps { interface RowsProps {
items: readonly ChangeItem[]; items: readonly ChangeItem[];
/** The waiting rows wait behind the week grid. */ /** The waiting rows wait behind the week grid. */
@@ -274,6 +359,9 @@ interface RowsProps {
undoable: readonly string[]; undoable: readonly string[];
onToggle: (toolCallId: string) => void; onToggle: (toolCallId: string) => void;
onUndo: (toolCallId: string) => void; onUndo: (toolCallId: string) => void;
planEdits: Readonly<Record<string, AssistantPlanEdits>>;
onEdit: (toolCallId: string, patch: AssistantPlanEdits) => void;
groupedDay: boolean;
} }
/** Consecutive changes of one kind of card; a change without a card stands alone. */ /** Consecutive changes of one kind of card; a change without a card stands alone. */
@@ -299,7 +387,19 @@ function runnable(item: ChangeItem, view: View | null): boolean {
* `Group` before and after it, and two or more waiting rows its view can * `Group` before and after it, and two or more waiting rows its view can
* take together are drawn as one `Run` instead. * take together are drawn as one `Run` instead.
*/ */
export function ChangeRows({ items, folded, excluded, disabled, undone, undoable, onToggle, onUndo }: RowsProps) { export function ChangeRows({
items,
folded,
excluded,
disabled,
undone,
undoable,
onToggle,
onUndo,
planEdits,
onEdit,
groupedDay,
}: RowsProps) {
const pendingCount = items.filter((i) => i.state === 'pending').length; const pendingCount = items.filter((i) => i.state === 'pending').length;
// The body stands beside the row, in the same place whether the change waits or is decided, so a body that holds // The body stands beside the row, in the same place whether the change waits or is decided, so a body that holds
// what the user chose (the pages of a book design) keeps it, and draws on, as the change starts to apply. // what the user chose (the pages of a book design) keeps it, and draws on, as the change starts to apply.
@@ -316,6 +416,9 @@ export function ChangeRows({ items, folded, excluded, disabled, undone, undoable
withChoice={pendingCount > 1} withChoice={pendingCount > 1}
disabled={disabled} disabled={disabled}
onToggle={() => onToggle(item.toolCallId)} onToggle={() => onToggle(item.toolCallId)}
edits={planEdits[item.toolCallId]}
onEdit={(patch) => onEdit(item.toolCallId, patch)}
groupedDay={groupedDay}
/> />
) : ( ) : (
<Receipt <Receipt
@@ -325,7 +428,9 @@ export function ChangeRows({ items, folded, excluded, disabled, undone, undoable
onUndo={() => onUndo(item.toolCallId)} onUndo={() => onUndo(item.toolCallId)}
/> />
)} )}
<BodySlot item={item} settled={waiting ? excluded.has(item.toolCallId) : settledOf(item, isUndone)} /> {!inlineBookingCard(item) && (
<BodySlot item={item} settled={waiting ? excluded.has(item.toolCallId) : settledOf(item, isUndone)} />
)}
</Fragment> </Fragment>
); );
}; };
@@ -25,6 +25,7 @@ import { useAuthStore } from '../../../../store/authStore';
import { useSettingsStore } from '../../../../store/settingsStore'; import { useSettingsStore } from '../../../../store/settingsStore';
import type { ChangeItem } from '../../assistantParts'; import type { ChangeItem } from '../../assistantParts';
import { type AssistantView, AssistantViewContext } from '../../assistantViewContext'; import { type AssistantView, AssistantViewContext } from '../../assistantViewContext';
import { ChangeRows } from '../ChangeCardSlots';
import BookingBlock from './BookingBlock'; import BookingBlock from './BookingBlock';
import { BookingChangeBody, BookingChangeFacts } from './BookingChangeSlots'; import { BookingChangeBody, BookingChangeFacts } from './BookingChangeSlots';
@@ -412,4 +413,44 @@ describe('booking cards', () => {
expect(screen.queryByRole('button', { name: 'Open the booking' })).not.toBeInTheDocument(); expect(screen.queryByRole('button', { name: 'Open the booking' })).not.toBeInTheDocument();
expect(screen.getByText('Frankfurt to New York')).toBeInTheDocument(); expect(screen.getByText('Frankfurt to New York')).toBeInTheDocument();
}); });
it.each(['pending', 'failed'] as const)(
'shows a single %s booking as one card with its structured reference',
(state) => {
const card = cardOf([{ ...DINNER, reservationId: null, status: 'confirmed', hasReference: true }], 'create');
const item = changeItem(card);
item.state = state;
if (!item.preview) throw new Error('Booking preview fixture is missing');
item.preview.verbKey = 'addReservation';
item.preview.rows = [
{ op: 'add', labelKey: 'confirmation', before: null, after: 'ABC-12345' },
{ op: 'add', labelKey: 'notes', before: null, after: 'Use the side entrance. Booking code: ABC-12345.' },
];
inView(
<ChangeRows
items={[item]}
folded={false}
excluded={new Set()}
disabled={false}
undone={{}}
undoable={[]}
onToggle={vi.fn()}
onUndo={vi.fn()}
planEdits={{}}
onEdit={vi.fn()}
groupedDay={false}
/>,
{ variant: 'fullscreen', density: 'compact' }
);
const booking = within(screen.getByRole('region', { name: DINNER.title }));
expect(booking.getByText('Add booking')).toHaveClass('uppercase');
expect(screen.getAllByText('Add booking')).toHaveLength(1);
expect(booking.getByText('Start time').closest('dt')?.nextElementSibling).toHaveTextContent('19:00');
expect(booking.getByText('End time').closest('dt')?.nextElementSibling).toHaveTextContent('21:30');
expect(booking.getByText('Confirmed')).toBeInTheDocument();
expect(booking.getByText('Booking Code').closest('dt')?.nextElementSibling).toHaveTextContent('ABC-12345');
expect(booking.getByText('Use the side entrance.')).toBeInTheDocument();
expect(booking.queryByText(/Booking code: ABC-12345/)).toBeNull();
}
);
}); });
@@ -5,7 +5,16 @@ import { useTranslation } from '../../../../i18n';
import { Tooltip } from '../../../shared/Tooltip'; import { Tooltip } from '../../../shared/Tooltip';
import { useAssistantView } from '../../assistantViewContext'; import { useAssistantView } from '../../assistantViewContext';
import type { EntityTarget } from '../cardTypes'; import type { EntityTarget } from '../cardTypes';
import { BookingFooter, BookingHead, StayBody, TicketBody, VenueBody } from './bookingCardParts'; import {
BookingFooter,
BookingHead,
BookingProposalFooter,
StayBody,
StayProposalBody,
TicketBody,
VenueBody,
VenueProposalBody,
} from './bookingCardParts';
import { bookingSpotOf, bookingTarget } from './bookingLook'; import { bookingSpotOf, bookingTarget } from './bookingLook';
/** /**
@@ -88,11 +97,13 @@ export default function BookingCard({
item, item,
card, card,
actions = true, actions = true,
proposal,
}: { }: {
item: BookingItem; item: BookingItem;
card: Card; card: Card;
/** Off inside a change card, whose row has its own ways to the booking. */ /** Off inside a change card, whose row has its own ways to the booking. */
actions?: boolean; actions?: boolean;
proposal?: { label: string; notes?: string; reference?: string; receipt?: string };
}) { }) {
const { t } = useTranslation(); const { t } = useTranslation();
const body = item.body; const body = item.body;
@@ -101,17 +112,33 @@ export default function BookingCard({
aria-label={item.title} aria-label={item.title}
className={`trek-assistant-enter group overflow-hidden rounded-xl border bg-surface-card shadow-card ${FRAME[card.change]}`} className={`trek-assistant-enter group overflow-hidden rounded-xl border bg-surface-card shadow-card ${FRAME[card.change]}`}
> >
<BookingHead item={item} card={card} actions={actions ? <CardActions item={item} /> : null} /> <BookingHead
<div className="px-3 pb-2.5 pt-2"> item={item}
card={card}
actionLabel={proposal?.label}
actions={actions ? <CardActions item={item} /> : null}
/>
<div className={proposal ? 'flex flex-col gap-3 bg-surface-secondary p-3' : 'px-3 pb-2.5 pt-2'}>
{item.tripTitle && ( {item.tripTitle && (
<p className="m-0 mb-1 text-caption text-content-muted"> <p className="m-0 mb-1 text-caption text-content-muted">
{t('assistant.card.booking.inTrip', { trip: item.tripTitle })} {t('assistant.card.booking.inTrip', { trip: item.tripTitle })}
</p> </p>
)} )}
{body.shape === 'ticket' && <TicketBody item={item} body={body} card={card} />} {body.shape === 'ticket' && <TicketBody item={item} body={body} card={card} />}
{body.shape === 'stay' && <StayBody item={item} body={body} card={card} />} {body.shape === 'stay' &&
{body.shape === 'venue' && <VenueBody item={item} body={body} card={card} />} (proposal ? <StayProposalBody body={body} /> : <StayBody item={item} body={body} card={card} />)}
<BookingFooter item={item} card={card} /> {body.shape === 'venue' &&
(proposal ? <VenueProposalBody body={body} /> : <VenueBody item={item} body={body} card={card} />)}
{proposal ? (
<BookingProposalFooter
item={item}
notes={proposal.notes}
reference={proposal.reference}
receipt={proposal.receipt}
/>
) : (
<BookingFooter item={item} card={card} />
)}
</div> </div>
</section> </section>
); );
@@ -1,8 +1,12 @@
import type { TrekCardOf } from '@trek/shared'; import { withoutRepeatedBookingReference, type TrekCardOf } from '@trek/shared';
import { useTranslation } from '../../../../i18n';
import AssistantChangeFields from '../../AssistantChangeFields'; import AssistantChangeFields from '../../AssistantChangeFields';
import type { ChangeItem } from '../../assistantParts'; import type { ChangeItem } from '../../assistantParts';
import { verbLookOf } from '../cardLooks';
import { BookingList } from './BookingBlock'; import { BookingList } from './BookingBlock';
import BookingCard from './BookingCard';
import { isSingleBookingDraft } from './bookingCardModel';
/** /**
* The booking card inside a change row. The row keeps its choice, its tile * The booking card inside a change row. The row keeps its choice, its tile
@@ -17,8 +21,28 @@ interface SlotProps {
item: ChangeItem; item: ChangeItem;
} }
/** The card under the row; the row itself leads to the booking once it is saved. */ /** New single bookings carry their action in the card head. */
export function BookingChangeBody({ card }: SlotProps) { export function BookingChangeBody({ card, item }: SlotProps) {
const { t } = useTranslation();
const booking = card.items[0];
if (booking && isSingleBookingDraft(card)) {
const preview = item.preview;
const reference = preview?.rows.find((row) => row.labelKey === 'confirmation')?.after.trim() || undefined;
const notes = preview?.rows.find((row) => row.labelKey === 'notes')?.after ?? '';
return (
<BookingCard
item={booking}
card={card}
actions={false}
proposal={{
label: t(verbLookOf(preview?.verbKey ?? 'addReservation').labelKey),
notes: withoutRepeatedBookingReference(notes, reference),
reference,
receipt: preview?.rows.find((row) => row.labelKey === 'attachedTo')?.after,
}}
/>
);
}
return <BookingList items={card.items} more={card.more} card={card} actions={false} />; return <BookingList items={card.items} more={card.more} card={card} actions={false} />;
} }
@@ -13,6 +13,10 @@ import type { CardEntry } from '../cardTypes';
/** A status a booking card names in words. */ /** A status a booking card names in words. */
type BookingStatus = NonNullable<BookingItem['status']>; type BookingStatus = NonNullable<BookingItem['status']>;
export function isSingleBookingDraft(card: BookingCard): boolean {
return card.change === 'create' && card.items.length === 1 && card.more === 0;
}
/** /**
* The planner's tone of a booking (its `toneOf`): a transit hop in the info * The planner's tone of a booking (its `toneOf`): a transit hop in the info
* tone, a confirmed booking green, any other (pending, cancelled) amber; none * tone, a confirmed booking green, any other (pending, cancelled) amber; none
@@ -15,6 +15,7 @@ import {
LogOut, LogOut,
MapPin, MapPin,
Moon, Moon,
Paperclip,
Route, Route,
Ticket, Ticket,
Wallet, Wallet,
@@ -23,7 +24,16 @@ import {
import { useRef, type ReactNode } from 'react'; import { useRef, type ReactNode } from 'react';
import { useTranslation } from '../../../../i18n'; import { useTranslation } from '../../../../i18n';
import { ReviewPill, toneColor, toneTint, TypeTile } from '../../../Planner/bookings/bookingParts'; import {
Block,
BOX,
Eyebrow,
fs,
ReviewPill,
toneColor,
toneTint,
TypeTile,
} from '../../../Planner/bookings/bookingParts';
import { typeInfo } from '../../../Planner/bookings/bookingsModel'; import { typeInfo } from '../../../Planner/bookings/bookingsModel';
import { SoftPill, TimePill, type PillTone } from '../../../Planner/planParts'; import { SoftPill, TimePill, type PillTone } from '../../../Planner/planParts';
import { Tooltip } from '../../../shared/Tooltip'; import { Tooltip } from '../../../shared/Tooltip';
@@ -101,13 +111,13 @@ function StayPhoto({ item, body, size, tile }: { item: BookingItem; body: Bookin
} }
/** The lead of the head band: a stay's photo (56, 44 when compact), else the type tile. */ /** The lead of the head band: a stay's photo (56, 44 when compact), else the type tile. */
function HeadLead({ item }: { item: BookingItem }) { function HeadLead({ item, proposal }: { item: BookingItem; proposal: boolean }) {
const { density } = useAssistantView(); const { density } = useAssistantView();
const compact = density === 'compact'; const compact = density === 'compact';
if (item.body.shape === 'stay') { if (item.body.shape === 'stay') {
return <StayPhoto item={item} body={item.body} size={compact ? 44 : 56} tile={compact ? 32 : 40} />; return <StayPhoto item={item} body={item.body} size={compact ? 44 : 56} tile={compact ? 32 : 40} />;
} }
return <TypeTile type={item.type} size={compact ? 24 : 28} />; return <TypeTile type={item.type} size={proposal ? 34 : compact ? 24 : 28} />;
} }
/** /**
@@ -115,22 +125,39 @@ function HeadLead({ item }: { item: BookingItem }) {
* title), the title, the review mark, the status dot and the card's actions, * title), the title, the review mark, the status dot and the card's actions,
* on the tint of the status as on the planner's booking cards. * on the tint of the status as on the planner's booking cards.
*/ */
export function BookingHead({ item, card, actions }: { item: BookingItem; card: Card; actions?: ReactNode }) { export function BookingHead({
item,
card,
actions,
actionLabel,
}: {
item: BookingItem;
card: Card;
actions?: ReactNode;
actionLabel?: string;
}) {
const { t } = useTranslation(); const { t } = useTranslation();
const tone = toneOfItem(item); const tone = toneOfItem(item);
const removed = card.change === 'remove'; const removed = card.change === 'remove';
const address = item.body.shape === 'stay' ? item.body.address : null; const proposal = !!actionLabel;
const address =
item.body.shape === 'stay'
? item.body.address
: proposal && item.body.shape === 'venue'
? item.body.location
: null;
return ( return (
<div <div
className="flex items-center gap-2 border-b border-edge-faint px-3 py-2" className={`flex items-center gap-2.5 border-b border-edge-faint px-3 ${actionLabel ? 'py-3' : 'py-2'}`}
style={{ background: tone ? toneTint(tone) : undefined }} style={{ background: tone ? toneTint(tone) : undefined }}
> >
<HeadLead item={item} /> <HeadLead item={item} proposal={proposal} />
<span className="flex min-w-0 flex-1 flex-col gap-0.5"> <div className="flex min-w-0 flex-1 flex-col gap-0.5">
{actionLabel && <Eyebrow>{actionLabel}</Eyebrow>}
<span className="flex min-w-0 items-center gap-1.5"> <span className="flex min-w-0 items-center gap-1.5">
<bdi <bdi
title={item.title} title={item.title}
className={`line-clamp-2 text-body font-semibold leading-tight text-content ${removed ? 'line-through' : ''}`} className={`line-clamp-2 text-body leading-tight text-content ${proposal ? 'font-bold' : 'font-semibold'} ${removed ? 'line-through' : ''}`}
> >
{item.title} {item.title}
</bdi> </bdi>
@@ -138,19 +165,192 @@ export function BookingHead({ item, card, actions }: { item: BookingItem; card:
{isChanged(card, item, 'title') && <ChangedDot />} {isChanged(card, item, 'title') && <ChangedDot />}
{removed && <span className="sr-only">{t('assistant.card.common.willDelete')}</span>} {removed && <span className="sr-only">{t('assistant.card.common.willDelete')}</span>}
</span> </span>
{address && ( {address &&
<bdi title={address} className="line-clamp-2 text-caption text-content-muted"> (proposal ? (
{address} <span className="mt-0.5 flex items-start gap-1.5 text-caption text-content-muted">
</bdi> <MapPin size={12} className="mt-0.5 flex-none" aria-hidden="true" />
)} <bdi title={address} className="line-clamp-2 break-words">
</span> {address}
<StatusMark item={item} /> </bdi>
</span>
) : (
<bdi title={address} className="line-clamp-2 text-caption text-content-muted">
{address}
</bdi>
))}
</div>
{!actionLabel && <StatusMark item={item} />}
{isChanged(card, item, 'status') && <ChangedDot />} {isChanged(card, item, 'status') && <ChangedDot />}
{actions} {actions}
</div> </div>
); );
} }
/** A proposal shows the facts in the same order as the booking editor. */
const PROPOSAL_FACTS = 'm-0 grid grid-cols-[repeat(auto-fit,minmax(min(100%,8.5rem),1fr))] gap-2';
const PROPOSAL_FIELD_TEXT = fs(12.5, 'body');
function ProposalFact({ label, children }: { label: string; children: ReactNode }) {
return (
<div className="min-w-0">
<dt className="mb-[3px]">
<Eyebrow>{label}</Eyebrow>
</dt>
<dd
className={`${BOX} m-0 flex min-h-9 flex-wrap items-center gap-x-1.5 gap-y-0.5 break-words px-2.5 py-[7px] font-semibold tabular-nums text-content`}
style={PROPOSAL_FIELD_TEXT}
>
{children}
</dd>
</div>
);
}
export function VenueProposalBody({ body }: { body: BookingVenue }) {
const { t } = useTranslation();
const format = useBookingFormat();
const day = format.day(body.day);
const dayNumber = format.dayNumber(body.day);
return (
(day || body.starts || body.ends) && (
<dl className={PROPOSAL_FACTS}>
{day && (
<ProposalFact label={t(body.day?.date ? 'reservations.date' : 'reservations.timeline.day')}>
<bdi>{day}</bdi>
{dayNumber && <span className="text-caption font-normal text-content-muted">{dayNumber}</span>}
</ProposalFact>
)}
{body.starts && (
<ProposalFact label={t('reservations.startTime')}>
<bdi>{format.clock(body.starts)}</bdi>
</ProposalFact>
)}
{body.ends && (
<ProposalFact label={t('reservations.endTime')}>
<bdi>{format.clock(body.ends)}</bdi>
</ProposalFact>
)}
</dl>
)
);
}
export function StayProposalBody({ body }: { body: BookingStay }) {
const { t } = useTranslation();
const format = useBookingFormat();
const checkIn = body.checkIn;
const checkOut = body.checkOut;
return (
<>
{(checkIn || checkOut) && (
<dl className={PROPOSAL_FACTS}>
{checkIn && (
<ProposalFact label={t('assistant.change.label.checkIn')}>
<bdi>{format.day(checkIn.day)}</bdi>
{checkIn.from && (
<bdi className="text-caption">
{format.clock(checkIn.from)}
{checkIn.until ? ` – ${format.clock(checkIn.until)}` : ''}
</bdi>
)}
</ProposalFact>
)}
{checkOut && (
<ProposalFact label={t('assistant.change.label.checkOut')}>
<bdi>{format.day(checkOut.day)}</bdi>
{checkOut.by && <bdi className="text-caption">{format.clock(checkOut.by)}</bdi>}
</ProposalFact>
)}
</dl>
)}
{!!body.nights && (
<p className="m-0 flex items-center gap-1.5 text-body text-content-secondary">
<Moon size={14} aria-hidden="true" />
{t('assistant.card.booking.nights', { count: body.nights })}
</p>
)}
</>
);
}
export function BookingProposalFooter({
item,
notes,
reference,
receipt,
}: {
item: BookingItem;
notes?: string;
reference?: string;
receipt?: string;
}) {
const { t } = useTranslation();
const format = useBookingFormat();
const tone = toneOfItem(item);
return (
<>
{reference && (
<dl className="m-0">
<ProposalFact label={t('reservations.confirmationCode')}>
<bdi dir="ltr" className="min-w-0 break-all font-geist">
{reference}
</bdi>
</ProposalFact>
</dl>
)}
{notes && (
<Block label={t('assistant.change.label.notes')}>
<p
className={`${BOX} m-0 whitespace-pre-wrap break-words px-2.5 py-[7px] text-content-secondary`}
style={PROPOSAL_FIELD_TEXT}
>
<bdi>{notes}</bdi>
</p>
</Block>
)}
{receipt && (
<Block label={t('assistant.change.label.attachedTo')}>
<span
className={`${BOX} flex min-w-0 items-center gap-1.5 px-2.5 py-[7px] text-content-secondary`}
style={PROPOSAL_FIELD_TEXT}
>
<Paperclip size={14} aria-hidden="true" className="flex-none" />
<bdi className="min-w-0 break-words">{receipt}</bdi>
</span>
</Block>
)}
<div className="flex flex-wrap items-center gap-x-3 gap-y-2 border-t border-edge-faint pt-2.5 text-caption text-content-secondary">
<span className="font-semibold">{t(typeInfo(item.type).labelKey)}</span>
{item.status && tone && (
<span className="inline-flex items-center gap-1.5">
<span
className="h-2 w-2 flex-none rounded-full"
style={{ background: toneColor(tone) }}
aria-hidden="true"
/>
{t(STATUS_LABEL[item.status].labelKey)}
</span>
)}
{item.hasReference && !reference && (
<span className="inline-flex items-center gap-1.5">
<BadgeCheck size={14} aria-hidden="true" className="flex-none text-success" />
{t('reservations.confirmationCode')}
</span>
)}
{item.price && (
<bdi className="ms-auto font-semibold tabular-nums text-content">{format.money(item.price)}</bdi>
)}
{item.travelers.length > 0 && (
<span className="flex flex-none items-center gap-1">
<PeopleStack people={item.travelers} />
{item.moreTravelers > 0 && <span className="font-semibold tabular-nums">+{item.moreTravelers}</span>}
</span>
)}
</div>
</>
);
}
/** A fact as a white soft pill with its glyph, the accent dot when an update changes it. */ /** A fact as a white soft pill with its glyph, the accent dot when an update changes it. */
function Pill({ function Pill({
icon: Icon, icon: Icon,
@@ -142,6 +142,10 @@ export const STEP_LOOKS: Readonly<Partial<Record<string, StepLook>>> = {
stepKey: 'assistant.step.searching', stepKey: 'assistant.step.searching',
live: { liveKey: 'assistant.step.searchingFor', param: 'query' }, live: { liveKey: 'assistant.step.searchingFor', param: 'query' },
}, },
search_places_via_plugins: {
stepKey: 'assistant.step.searching',
live: { liveKey: 'assistant.step.searchingFor', param: 'query' },
},
search_pois: { stepKey: 'assistant.step.searching', live: { liveKey: 'assistant.step.nearbyAt', param: 'place' } }, search_pois: { stepKey: 'assistant.step.searching', live: { liveKey: 'assistant.step.nearbyAt', param: 'place' } },
get_place_details: { stepKey: 'assistant.step.details' }, get_place_details: { stepKey: 'assistant.step.details' },
search_nearby_places: { search_nearby_places: {
@@ -10,7 +10,7 @@
import type { TourRouteCard } from '@trek/shared'; import type { TourRouteCard } from '@trek/shared';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { GENTLE, HIKE, SAVED } from '../../../../../tests/helpers/assistantTour'; import { GENTLE, HIKE, SAVED, tourStop } from '../../../../../tests/helpers/assistantTour';
import { buildTrip, buildUser } from '../../../../../tests/helpers/factories'; import { buildTrip, buildUser } from '../../../../../tests/helpers/factories';
import { act, fireEvent, render, screen } from '../../../../../tests/helpers/render'; import { act, fireEvent, render, screen } from '../../../../../tests/helpers/render';
import { chatOf, useAssistantStore } from '../../../../store/assistantStore'; import { chatOf, useAssistantStore } from '../../../../store/assistantStore';
@@ -81,6 +81,34 @@ describe('TourRouteBlock', () => {
expect(document.querySelector('[data-profile-compare="call_1"]')).not.toBeNull(); expect(document.querySelector('[data-profile-compare="call_1"]')).not.toBeNull();
}); });
it('preselects the calculated way and keeps the failed way available for diagnosis', () => {
const failed: TourRouteCard = {
...HIKE,
routed: false,
distanceM: null,
problem: { why: 'point_off_the_way', position: 2, snappedM: 494 },
};
renderBlock([{ toolCallId: 'call_1', card: failed }, WAYS[1]]);
const first = screen.getByRole('radio', { name: 'Way A' });
expect(first).toHaveTextContent('not routed');
expect(first).not.toHaveTextContent('0 m');
expect(screen.getByRole('radio', { name: 'Long and gentle' })).toHaveAttribute('aria-checked', 'true');
expect(screen.getByRole('button', { name: 'Plan way B' })).toBeEnabled();
expect(screen.queryByTestId('leg-variant-delta')).not.toBeInTheDocument();
fireEvent.click(first);
expect(screen.getByText('Point 2 is too far from any path')).toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Plan way A' })).not.toBeInTheDocument();
});
it('warns about a long detour on an open hike while keeping the route available', () => {
const start = tourStop({ role: 'start', lat: 35.3969, lng: 138.7345 });
const end = tourStop({ role: 'end', lat: 35.3606, lng: 138.7274, atM: 35_856 });
renderBlock([{ toolCallId: 'detour', card: { ...HIKE, distanceM: 35_856, stops: [start, end] } }]);
expect(screen.getByText(/takes a long detour/)).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'On map' })).toBeInTheDocument();
});
it('FE-AI-TOUR-031: the ways stand side by side in a roomy window and stay rows on the phone', () => { it('FE-AI-TOUR-031: the ways stand side by side in a roomy window and stay rows on the phone', () => {
renderBlock(WAYS, { density: 'roomy' }); renderBlock(WAYS, { density: 'roomy' });
expect(screen.getByRole('radiogroup')).toHaveClass('grid-cols-2'); expect(screen.getByRole('radiogroup')).toHaveClass('grid-cols-2');
@@ -10,7 +10,7 @@ import TourRouteActions from './TourRouteActions';
import TourRouteDay from './TourRouteDay'; import TourRouteDay from './TourRouteDay';
import TourRouteHead, { TourRouteFields } from './TourRouteHead'; import TourRouteHead, { TourRouteFields } from './TourRouteHead';
import { profileSamples } from './tourRouteModel'; import { profileSamples } from './tourRouteModel';
import { TourRouteProblem, TourRouteWarnings } from './TourRouteNotes'; import { TourRouteDetour, TourRouteProblem, TourRouteWarnings } from './TourRouteNotes';
import TourRouteProfile from './TourRouteProfile'; import TourRouteProfile from './TourRouteProfile';
import TourRouteStops from './TourRouteStops'; import TourRouteStops from './TourRouteStops';
import { routeName } from './tourRouteWords'; import { routeName } from './tourRouteWords';
@@ -45,6 +45,7 @@ export function TourRouteBody({
return ( return (
<> <>
<TourRouteFields card={card} /> <TourRouteFields card={card} />
<TourRouteDetour card={card} />
{/* A way drawn straight has neither heights nor the line to say so under: no section at all. */} {/* A way drawn straight has neither heights nor the line to say so under: no section at all. */}
{(samples.length >= 2 || card.routed) && ( {(samples.length >= 2 || card.routed) && (
<CardSection label={t('tours.planner.inspector.elevation')}> <CardSection label={t('tours.planner.inspector.elevation')}>
@@ -5,6 +5,7 @@ import { useTranslation } from '../../../../i18n';
import { SoftPill } from '../../../Planner/planParts'; import { SoftPill } from '../../../Planner/planParts';
import { TourNotice } from '../../../Tours/tourParts'; import { TourNotice } from '../../../Tours/tourParts';
import { useCardFormat } from '../parts/useCardFormat'; import { useCardFormat } from '../parts/useCardFormat';
import { hasLongHikeDetour } from './tourRouteModel';
import { PROBLEM_LOOK, WARNING_LOOK } from './tourRouteWords'; import { PROBLEM_LOOK, WARNING_LOOK } from './tourRouteWords';
/** /**
@@ -53,3 +54,15 @@ export function TourRouteProblem({ card }: { card: TourRouteCard }) {
</div> </div>
); );
} }
export function TourRouteDetour({ card }: { card: TourRouteCard }) {
const { t } = useTranslation();
if (!hasLongHikeDetour(card)) return null;
return (
<div className="mt-2">
<TourNotice tone="warning" icon={<AlertTriangle size={12} strokeWidth={2} aria-hidden="true" />}>
{t('assistant.card.tour.longDetour')}
</TourNotice>
</div>
);
}
@@ -3,6 +3,7 @@ import { Route as RouteIcon } from 'lucide-react';
import { useMemo } from 'react'; import { useMemo } from 'react';
import { useTranslation } from '../../../../i18n'; import { useTranslation } from '../../../../i18n';
import { preferredRouteEntry } from '../../../../store/assistantRouteModel';
import { chatOf, useAssistantStore } from '../../../../store/assistantStore'; import { chatOf, useAssistantStore } from '../../../../store/assistantStore';
import { useSettingsStore } from '../../../../store/settingsStore'; import { useSettingsStore } from '../../../../store/settingsStore';
import type { DistanceUnit } from '../../../../types'; import type { DistanceUnit } from '../../../../types';
@@ -79,7 +80,7 @@ function WayOption({
entry: RouteEntry; entry: RouteEntry;
index: number; index: number;
chosen: boolean; chosen: boolean;
chosenWay: LegVariant; chosenWay: LegVariant | null;
chosenLetter: string; chosenLetter: string;
unit: DistanceUnit; unit: DistanceUnit;
onSelect: () => void; onSelect: () => void;
@@ -118,8 +119,14 @@ function WayOption({
{/* Ways of a ride or a run may differ by profile: each says its own. */} {/* Ways of a ride or a run may differ by profile: each says its own. */}
{entry.card.routingProfile && <TourGrade card={entry.card} />} {entry.card.routingProfile && <TourGrade card={entry.card} />}
</span> </span>
<WayFigures way={way} unit={unit} /> {entry.card.routed ? (
{!chosen && <WayDelta way={way} chosen={chosenWay} letter={chosenLetter} unit={unit} />} <WayFigures way={way} unit={unit} />
) : (
<span className="text-caption text-warning">{t('map.overview.notRouted')}</span>
)}
{!chosen && entry.card.routed && chosenWay && (
<WayDelta way={way} chosen={chosenWay} letter={chosenLetter} unit={unit} />
)}
</span> </span>
</button> </button>
); );
@@ -156,7 +163,7 @@ function WaysCard({
[entries, chosenIndex] [entries, chosenIndex]
); );
const chosenWay = legVariantOf(chosen.card, chosenKey); const chosenWay = chosen.card.routed ? legVariantOf(chosen.card, chosenKey) : null;
// Side by side where the window is roomy; on the phone the ways stay rows, so a finger scrubs the profile freely. // Side by side where the window is roomy; on the phone the ways stay rows, so a finger scrubs the profile freely.
let columns = ''; let columns = '';
if (density === 'roomy' && variant !== 'fullscreen') columns = entries.length >= 3 ? 'grid-cols-3' : 'grid-cols-2'; if (density === 'roomy' && variant !== 'fullscreen') columns = entries.length >= 3 ? 'grid-cols-3' : 'grid-cols-2';
@@ -216,10 +223,8 @@ function WaysCard({
export default function TourWays({ entries }: { entries: readonly RouteEntry[] }) { export default function TourWays({ entries }: { entries: readonly RouteEntry[] }) {
const { tripId } = useAssistantView(); const { tripId } = useAssistantView();
const blockKey = `tour:${entries[0]?.toolCallId ?? ''}`; const blockKey = `tour:${entries[0]?.toolCallId ?? ''}`;
const picked = useAssistantStore((s) => chatOf(s, tripId).picks[blockKey] ?? null); const picked = useAssistantStore((s) => chatOf(s, tripId).picks[blockKey]);
const index = entries.findIndex((entry) => entry.toolCallId === picked); const chosen = preferredRouteEntry(entries, picked);
const chosenIndex = index < 0 ? 0 : index;
const chosen = entries[chosenIndex];
if (!chosen) return null; if (!chosen) return null;
return <WaysCard entries={entries} chosen={chosen} chosenIndex={chosenIndex} blockKey={blockKey} />; return <WaysCard entries={entries} chosen={chosen} chosenIndex={entries.indexOf(chosen)} blockKey={blockKey} />;
} }
@@ -1,4 +1,4 @@
import { cumulativeMetres, type TourRouteCard, type TourRouteStop } from '@trek/shared'; import { cumulativeMetres, haversineMetres, type TourRouteCard, type TourRouteStop } from '@trek/shared';
import type { DistanceIndexedProfileSample } from '../../../../utils/routeGeometry'; import type { DistanceIndexedProfileSample } from '../../../../utils/routeGeometry';
import { hikePaintCss } from '../../../Tours/hike/hikePaint'; import { hikePaintCss } from '../../../Tours/hike/hikePaint';
@@ -84,6 +84,17 @@ export function profileSamples(card: TourRouteCard): DistanceIndexedProfileSampl
})); }));
} }
/** Flag a long detour on an open hike without intermediate waypoints. */
export function hasLongHikeDetour(card: TourRouteCard): boolean {
if (!card.routed || card.source !== 'proposal' || card.activity !== 'hike' || card.distanceM === null) return false;
const waypoints = card.stops.filter((stop) => stop.role !== 'along');
const [start, end] = waypoints;
if (waypoints.length !== 2 || start?.role !== 'start' || end?.role !== 'end') return false;
const directM = haversineMetres(start.lat, start.lng, end.lat, end.lng);
// Loops and short switchbacks are expected to cover much more than their direct distance.
return directM >= 1_000 && card.distanceM >= Math.max(4 * directM, directM + 10_000);
}
/** A stretch to tint behind the profile, in metres along the route. */ /** A stretch to tint behind the profile, in metres along the route. */
interface ProfileBand { interface ProfileBand {
fromM: number; fromM: number;
@@ -1,4 +1,4 @@
import { type Dispatch, type SetStateAction, useState } from 'react'; import { useMemo, useState } from 'react';
import type { ChangeItem } from '../assistantParts'; import type { ChangeItem } from '../assistantParts';
import { viewOf } from './cardViews'; import { viewOf } from './cardViews';
@@ -21,8 +21,9 @@ const arrived = (items: readonly ChangeItem[]) => items.flatMap((item) => (item.
* its preview arrives; after that only the user switches it. * its preview arrives; after that only the user switches it.
*/ */
export function useChangeExclusions( export function useChangeExclusions(
items: readonly ChangeItem[] items: readonly ChangeItem[],
): [ReadonlySet<string>, Dispatch<SetStateAction<ReadonlySet<string>>>] { choices: Readonly<Record<string, boolean>>
): ReadonlySet<string> {
const [excluded, setExcluded] = useState<ReadonlySet<string>>(() => new Set(startingOff(items, new Set()))); const [excluded, setExcluded] = useState<ReadonlySet<string>>(() => new Set(startingOff(items, new Set())));
const [seen, setSeen] = useState<ReadonlySet<string>>(() => new Set(arrived(items))); const [seen, setSeen] = useState<ReadonlySet<string>>(() => new Set(arrived(items)));
const fresh = arrived(items).filter((id) => !seen.has(id)); const fresh = arrived(items).filter((id) => !seen.has(id));
@@ -31,5 +32,11 @@ export function useChangeExclusions(
setSeen(new Set([...seen, ...fresh])); setSeen(new Set([...seen, ...fresh]));
if (off.length > 0) setExcluded((prev) => new Set([...prev, ...off])); if (off.length > 0) setExcluded((prev) => new Set([...prev, ...off]));
} }
return [excluded, setExcluded]; return useMemo(
() =>
new Set(
items.flatMap(({ toolCallId }) => ((choices[toolCallId] ?? !excluded.has(toolCallId)) ? [] : [toolCallId]))
),
[items, choices, excluded]
);
} }
@@ -1,5 +1,5 @@
import type { TourActivityTotals, TourTypeKey } from '@trek/shared'; import type { TourActivityTotals, TourTypeKey } from '@trek/shared';
import { Footprints } from 'lucide-react'; import { ChartBar, Footprints, Route } from 'lucide-react';
import { createElement, useId } from 'react'; import { createElement, useId } from 'react';
import { useTranslation } from '../../../i18n'; import { useTranslation } from '../../../i18n';
import type { DistanceUnit } from '../../../types'; import type { DistanceUnit } from '../../../types';
@@ -91,7 +91,7 @@ function StatsBody({ stats }: { stats: TourActivityStats }) {
</div> </div>
</div> </div>
{showTypes && ( {showTypes && (
<DialogSection label={t('tours.stats.byType')}> <DialogSection icon={ChartBar} label={t('tours.stats.byType')}>
<ul className="m-0 flex list-none flex-col gap-1 p-0"> <ul className="m-0 flex list-none flex-col gap-1 p-0">
{summary.types.map(({ type, ...totals }) => ( {summary.types.map(({ type, ...totals }) => (
<TypeLine key={type} type={type} totals={totals} /> <TypeLine key={type} type={type} totals={totals} />
@@ -100,6 +100,7 @@ function StatsBody({ stats }: { stats: TourActivityStats }) {
</DialogSection> </DialogSection>
)} )}
<DialogSection <DialogSection
icon={Route}
label={t('tours.mode.tours')} label={t('tours.mode.tours')}
action={ action={
<span className="font-geist tabular-nums text-content-faint" style={fs(11)}> <span className="font-geist tabular-nums text-content-faint" style={fs(11)}>
@@ -17,6 +17,10 @@ const h = vi.hoisted(() => {
insets: number[] = []; insets: number[] = [];
kicks = 0; kicks = 0;
disposed = false; disposed = false;
static create(opts: GlobeEngineOptions): FakeEngine {
return new FakeEngine(opts);
}
constructor(opts: GlobeEngineOptions) { constructor(opts: GlobeEngineOptions) {
if (state.failNext !== null) { if (state.failNext !== null) {
const err = state.failNext; const err = state.failNext;
@@ -54,7 +54,7 @@ const AtlasGlobe = forwardRef<AtlasGlobeHandle, AtlasGlobeProps>(function AtlasG
if (!canvas) return; if (!canvas) return;
let engine: GlobeEngine; let engine: GlobeEngine;
try { try {
engine = new GlobeEngine({ engine = GlobeEngine.create({
canvas, canvas,
fetchJson: (p) => propsRef.current.fetchJson(p), fetchJson: (p) => propsRef.current.fetchJson(p),
theme: globeTheme(propsRef.current.dark), theme: globeTheme(propsRef.current.dark),
@@ -210,7 +210,7 @@ async function start(o: StartOptions = {}) {
onSelect: vi.fn(), onSelect: vi.fn(),
onFrame: vi.fn(), onFrame: vi.fn(),
}; };
const engine = new mod.GlobeEngine({ canvas, fetchJson, theme: o.theme ?? LIGHT, initial: o.initial, ...cb }); const engine = mod.GlobeEngine.create({ canvas, fetchJson, theme: o.theme ?? LIGHT, initial: o.initial, ...cb });
engines.push(engine); engines.push(engine);
return { return {
mod, mod,
@@ -310,7 +310,7 @@ describe('GlobeEngine boot', () => {
const otherFetch = vi.fn(async (): Promise<unknown> => null); const otherFetch = vi.fn(async (): Promise<unknown> => null);
const canvas = document.createElement('canvas'); const canvas = document.createElement('canvas');
const onReady = vi.fn(); const onReady = vi.fn();
const second = new first.mod.GlobeEngine({ canvas, fetchJson: otherFetch, theme: LIGHT, onReady }); const second = first.mod.GlobeEngine.create({ canvas, fetchJson: otherFetch, theme: LIGHT, onReady });
engines.push(second); engines.push(second);
await flush(); await flush();
expect(otherFetch).not.toHaveBeenCalled(); expect(otherFetch).not.toHaveBeenCalled();
@@ -345,7 +345,7 @@ describe('GlobeEngine boot retries', () => {
}); });
const onError = vi.fn(); const onError = vi.fn();
engines.push( engines.push(
new mod.GlobeEngine({ canvas: document.createElement('canvas'), fetchJson: fail, theme: LIGHT, onError }) mod.GlobeEngine.create({ canvas: document.createElement('canvas'), fetchJson: fail, theme: LIGHT, onError })
); );
const delays: number[] = []; const delays: number[] = [];
for (let i = 0; i < 4; i++) { for (let i = 0; i < 4; i++) {
@@ -364,7 +364,7 @@ describe('GlobeEngine boot retries', () => {
const ok = vi.fn(async (p: string): Promise<unknown> => files[p]); const ok = vi.fn(async (p: string): Promise<unknown> => files[p]);
const onReady = vi.fn(); const onReady = vi.fn();
engines.push( engines.push(
new mod.GlobeEngine({ canvas: document.createElement('canvas'), fetchJson: ok, theme: LIGHT, onReady }) mod.GlobeEngine.create({ canvas: document.createElement('canvas'), fetchJson: ok, theme: LIGHT, onReady })
); );
await flush(); await flush();
expect(ok).toHaveBeenCalledWith('manifest'); expect(ok).toHaveBeenCalledWith('manifest');
@@ -381,7 +381,9 @@ describe('GlobeEngine boot retries', () => {
return files[p]; return files[p];
}); });
const onReady = vi.fn(); const onReady = vi.fn();
engines.push(new mod.GlobeEngine({ canvas: document.createElement('canvas'), fetchJson, theme: LIGHT, onReady })); engines.push(
mod.GlobeEngine.create({ canvas: document.createElement('canvas'), fetchJson, theme: LIGHT, onReady })
);
await flush(); await flush();
expect(pending.map((t) => t.ms)).toEqual([1000]); expect(pending.map((t) => t.ms)).toEqual([1000]);
pending[0].cb(); pending[0].cb();
@@ -164,7 +164,13 @@ export class GlobeEngine {
private sun: [number, number, number] = sunVector(new Date()); private sun: [number, number, number] = sunVector(new Date());
private sunAt = 0; private sunAt = 0;
constructor(opts: GlobeEngineOptions) { static create(opts: GlobeEngineOptions): GlobeEngine {
const engine = new GlobeEngine(opts);
void engine.boot();
return engine;
}
private constructor(opts: GlobeEngineOptions) {
this.opts = opts; this.opts = opts;
this.theme = opts.theme; this.theme = opts.theme;
Object.assign(this.cam, opts.initial ?? {}); Object.assign(this.cam, opts.initial ?? {});
@@ -187,7 +193,6 @@ export class GlobeEngine {
this.resizeObs.observe(opts.canvas); this.resizeObs.observe(opts.canvas);
opts.canvas.addEventListener('webglcontextlost', this.onContextLost); opts.canvas.addEventListener('webglcontextlost', this.onContextLost);
this.resize(); this.resize();
void this.boot();
} }
// ---------------------------------------------------------------- loading // ---------------------------------------------------------------- loading
@@ -14,7 +14,7 @@ export function hexToRgb(hex: string): Rgb {
.map((c) => c + c) .map((c) => c + c)
.join('') .join('')
: h.slice(0, 6); : h.slice(0, 6);
const n = parseInt(full, 16); const n = Number.parseInt(full, 16);
if (Number.isNaN(n)) return [0.5, 0.5, 0.5]; if (Number.isNaN(n)) return [0.5, 0.5, 0.5];
return [((n >> 16) & 255) / 255, ((n >> 8) & 255) / 255, (n & 255) / 255]; return [((n >> 16) & 255) / 255, ((n >> 8) & 255) / 255, (n & 255) / 255];
} }
@@ -27,7 +27,7 @@ export function CostsCurrencyPicker({
options={options} options={options}
size="sm" size="sm"
searchable searchable
menuFit="content" menuWidth={220}
style={{ width: '100%' }} style={{ width: '100%' }}
/> />
</div> </div>
@@ -17,6 +17,7 @@ import { amountToInputString, currencyDecimals } from '../../utils/formatters'
import { localIsoDate } from '../../utils/localDate' import { localIsoDate } from '../../utils/localDate'
import type { ExpensePrefill } from './CostsPanel' import type { ExpensePrefill } from './CostsPanel'
import type { BudgetItem } from '../../types' import type { BudgetItem } from '../../types'
import type { CostsSettlement } from './costsModel'
// The split and receipt fields guard their own precision on every keystroke, so the // The split and receipt fields guard their own precision on every keystroke, so the
// guard has to follow the currency: a three-decimal one (KWD, BHD, …) seeds three // guard has to follow the currency: a three-decimal one (KWD, BHD, …) seeds three
@@ -329,3 +330,24 @@ export function expenseEditorFor(
if (receipt) return { key: 'receipt', editing: null, prefill: receipt, close: closeReceipt } if (receipt) return { key: 'receipt', editing: null, prefill: receipt, close: closeReceipt }
return null return null
} }
/** Expenses and settle-up payments grouped newest day first in the Costs ledger. */
export function groupLedgerByDay(expenses: readonly BudgetItem[], payments: readonly CostsSettlement[], locale: string, noDate: string) {
const entries = [
...expenses.map(e => ({ kind: 'expense' as const, date: e.expense_date || '', e })),
...payments.map(s => ({ kind: 'payment' as const, date: settlementDate(s), s })),
].sort((a, b) => b.date.localeCompare(a.date))
const groups = new Map<string, typeof entries>()
for (const entry of entries) {
let label = noDate
if (entry.date) {
try {
label = new Date(entry.date + 'T00:00:00Z').toLocaleDateString(locale, { weekday: 'short', day: 'numeric', month: 'short', timeZone: 'UTC' })
} catch { label = entry.date }
}
const group = groups.get(label)
if (group) group.push(entry)
else groups.set(label, [entry])
}
return [...groups].map(([day, entries]) => ({ day, entries }))
}
@@ -173,7 +173,7 @@ describe('CostsPanel — settlements in the ledger', () => {
) )
render(<CostsPanel tripId={1} tripMembers={tripMembers} />) render(<CostsPanel tripId={1} tripMembers={tripMembers} />)
await screen.findByText('Hotel') await screen.findByText('Hotel')
expect(screen.getByText('Unfinished')).toBeInTheDocument() expect(screen.getByRole('img', { name: 'Unfinished' })).toBeInTheDocument()
}) })
// ── Notes on an expense (#1658) ──────────────────────────────────────────── // ── Notes on an expense (#1658) ────────────────────────────────────────────
@@ -944,13 +944,13 @@ describe('CostsPanel — overview', () => {
expect(labels).toEqual(['Food & drink', 'Transport']) expect(labels).toEqual(['Food & drink', 'Transport'])
expect(within(breakdown).getByText('90 €')).toBeInTheDocument() expect(within(breakdown).getByText('90 €')).toBeInTheDocument()
expect(within(breakdown).getByText('30 €')).toBeInTheDocument() expect(within(breakdown).getByText('30 €')).toBeInTheDocument()
}) });
it('FE-W5COSTS-006: an empty trip shows the empty ledger and the empty breakdown', async () => { it('FE-W5COSTS-006: an empty trip shows the empty ledger without a total or category breakdown', async () => {
mount([]) mount([])
expect(await screen.findByText('No expenses yet. Add your first one.')).toBeInTheDocument();
expect(await screen.findByText('No expenses yet. Add your first one.')).toBeInTheDocument() expect(screen.queryByRole('region', { name: 'Total trip spend' })).toBeNull();
expect(screen.getByText('No expenses yet.')).toBeInTheDocument() expect(screen.queryByRole('region', { name: 'By category' })).toBeNull();
expect(screen.getByText("Everyone's square")).toBeInTheDocument() expect(screen.getByText("Everyone's square")).toBeInTheDocument()
}) })
@@ -2138,7 +2138,7 @@ describe('CostsPanel — negative amounts (#2176)', () => {
mount([expense({ id: 320, name: 'Pending refund', category: 'misc', total_price: -50, payers: [], members: [{ user_id: 1, username: 'alice' }] })]) mount([expense({ id: 320, name: 'Pending refund', category: 'misc', total_price: -50, payers: [], members: [{ user_id: 1, username: 'alice' }] })])
await screen.findByText('Pending refund') await screen.findByText('Pending refund')
expect(screen.getByText('Unfinished')).toBeInTheDocument() expect(screen.getByRole('img', { name: 'Unfinished' })).toBeInTheDocument()
}) })
it('FE-W5COSTS-070: the category breakdown nets refunds and keeps a net-negative category listed', async () => { it('FE-W5COSTS-070: the category breakdown nets refunds and keeps a net-negative category listed', async () => {
@@ -2443,7 +2443,7 @@ describe('CostsPanel: a bill entered in the display currency (#2525)', () => {
const card = (await screen.findByRole('region', { name: 'Final budget' })) as HTMLElement const card = (await screen.findByRole('region', { name: 'Final budget' })) as HTMLElement
await user.click(await within(card).findByRole('button', { name: /You/ })) await user.click(await within(card).findByRole('button', { name: /You/ }))
expect(within(card).getAllByText('+$791.55')).toHaveLength(2) await waitFor(() => expect(within(card).getAllByText('+$791.55')).toHaveLength(2))
expect(within(card).getByText('Aparthotel Silver')).toBeInTheDocument() expect(within(card).getByText('Aparthotel Silver')).toBeInTheDocument()
expect(within(card).getByText('$801.76')).toBeInTheDocument() expect(within(card).getByText('$801.76')).toBeInTheDocument()
}) })
+68 -88
View File
@@ -1,5 +1,5 @@
import { Fragment, useState, useMemo, useCallback, useId, type ReactNode } from 'react' import { Fragment, useState, useMemo, useCallback, useId, type ReactNode } from 'react'
import { ArrowDown, ArrowUp, BarChart3, Plus, Search, ArrowRight, ArrowLeftRight, Check, RotateCcw, Pencil, Trash2, AlertCircle, Download, ChevronDown, Receipt, ScanLine, Users } from 'lucide-react' import { Banknote, NotebookPen, Wallet, Split, ArrowDown, ArrowUp, BarChart3, Plus, Search, ArrowRight, ArrowLeftRight, Check, RotateCcw, Pencil, Trash2, AlertCircle, Download, ChevronDown, Receipt, ScanLine, Users } from 'lucide-react'
import { useTripStore } from '../../store/tripStore' import { useTripStore } from '../../store/tripStore'
import { useCanDo } from '../../store/permissionsStore' import { useCanDo } from '../../store/permissionsStore'
import { useToast } from '../shared/Toast' import { useToast } from '../shared/Toast'
@@ -7,13 +7,12 @@ import { useTranslation } from '../../i18n'
import { splitShareLabel } from './expenseFx' import { splitShareLabel } from './expenseFx'
import { useIsMobile } from '../../hooks/useIsMobile' import { useIsMobile } from '../../hooks/useIsMobile'
import { formatMoney, amountToInputString, currencyDecimals, currencyLocale, localizeAmountInput, zeroAmountInput } from '../../utils/formatters' import { formatMoney, amountToInputString, currencyDecimals, currencyLocale, localizeAmountInput, zeroAmountInput } from '../../utils/formatters'
import { openFile } from '../../utils/fileDownload'
import CustomSelect from '../shared/CustomSelect' import CustomSelect from '../shared/CustomSelect'
import { CustomDatePicker } from '../shared/CustomDateTimePicker' import { CustomDatePicker } from '../shared/CustomDateTimePicker'
import { useReceiptScan } from './useReceiptScan' import { useReceiptScan } from './useReceiptScan'
import { ReceiptScanModal } from './ReceiptScanModal' import { ReceiptScanModal } from './ReceiptScanModal'
import { SPLIT_COLORS } from './BudgetPanel.constants' import { SPLIT_COLORS } from './BudgetPanel.constants'
import { finalBudgetFor, finalBudgetSources, formerParticipantRows, NOTE_MAX, paidByUser, readUserNote, settlementDate } from './CostsPanel.helpers' import { groupLedgerByDay, finalBudgetFor, finalBudgetSources, formerParticipantRows, NOTE_MAX, paidByUser, readUserNote } from './CostsPanel.helpers'
import { COST_CATEGORY_LIST, catMeta } from './costsCategories' import { COST_CATEGORY_LIST, catMeta } from './costsCategories'
import { import {
baseTotal as baseTotalOf, booked as bookedAmount, isUnfinished as isUnfinishedModel, lineOf as lineOfModel, memberShareOf, baseTotal as baseTotalOf, booked as bookedAmount, isUnfinished as isUnfinishedModel, lineOf as lineOfModel, memberShareOf,
@@ -52,12 +51,6 @@ interface CostsPanelProps {
tripMembers?: TripMember[] tripMembers?: TripMember[]
} }
// One row in the unified Costs ledger — either an expense or a settle-up payment,
// carrying the date used to group it by day.
type LedgerEntry =
| { kind: 'expense'; date: string; e: BudgetItem }
| { kind: 'payment'; date: string; s: Settlement }
const round2 = (n: number) => Math.round(n * 100) / 100 const round2 = (n: number) => Math.round(n * 100) / 100
const FIELD_H = 40 // shared height for the amount / currency / day row in the modal const FIELD_H = 40 // shared height for the amount / currency / day row in the modal
const COSTS_VIEW_KEY = 'trek:costs-view' const COSTS_VIEW_KEY = 'trek:costs-view'
@@ -66,6 +59,7 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
const { trip, budgetItems, deleteBudgetItem, loadBudgetItems, addBudgetItem, updateBudgetItem } = useTripStore() const { trip, budgetItems, deleteBudgetItem, loadBudgetItems, addBudgetItem, updateBudgetItem } = useTripStore()
const can = useCanDo() const can = useCanDo()
const canEdit = can('budget_edit', trip) const canEdit = can('budget_edit', trip)
const hasExpenses = budgetItems.length > 0
const receiptScan = useReceiptScan(tripId, canEdit) const receiptScan = useReceiptScan(tripId, canEdit)
const toast = useToast() const toast = useToast()
const { t, locale } = useTranslation() const { t, locale } = useTranslation()
@@ -143,27 +137,12 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
// Nobody paid, so nobody owes (#2225). // Nobody paid, so nobody owes (#2225).
const myShareOf = (e: BudgetItem) => settledShareOf(e, ctx) const myShareOf = (e: BudgetItem) => settledShareOf(e, ctx)
// ── day grouping ───────────────────────────────────────────────────────── const noDate = t('costs.noDate')
const dayGroups = useMemo(() => { const dayGroups = useMemo(() => groupLedgerByDay(filtered, filteredSettlements, locale, noDate), [filtered, filteredSettlements, locale, noDate])
const entries: LedgerEntry[] = [ const emptyLedger = !hasExpenses && dayGroups.length === 0
...filtered.map(e => ({ kind: 'expense' as const, date: e.expense_date || '', e })), const mobileEmptyLedger = emptyLedger
...filteredSettlements.map(s => ({ kind: 'payment' as const, date: settlementDate(s), s })), ? <EmptyState scene="costs" title={t('costs.emptyText')} />
] : <div className="text-content-faint" style={{ textAlign: 'center', padding: '36px 16px', fontSize: 'calc(13px * var(--fs-scale-body, 1))' }}>{search ? t('costs.noMatch') : t('costs.emptyText')}</div>
const labelOf = (date: string) => {
if (!date) return t('costs.noDate')
try { return new Date(date + 'T00:00:00Z').toLocaleDateString(locale, { weekday: 'short', day: 'numeric', month: 'short', timeZone: 'UTC' }) } catch { return date }
}
// Newest day first; within a day, expenses before payments (insertion order).
const sorted = entries.slice().sort((a, b) => (b.date || '').localeCompare(a.date || ''))
const groups: { day: string; entries: LedgerEntry[] }[] = []
for (const en of sorted) {
const day = labelOf(en.date)
let g = groups.find(x => x.day === day)
if (!g) { g = { day, entries: [] }; groups.push(g) }
g.entries.push(en)
}
return groups
}, [filtered, filteredSettlements, locale, t])
// ── filter dropdown options (category + single day) ────────────────────── // ── filter dropdown options (category + single day) ──────────────────────
const categoryOptions = useMemo(() => [ const categoryOptions = useMemo(() => [
@@ -285,8 +264,8 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
}} /> }} />
{/* ── Summary cards; with nothing to split (#2689) the total stands alone ── */} {/* ── Summary cards; with nothing to split (#2689) the total stands alone ── */}
{!splitting ? <div style={{ marginBottom: 36 }}>{totalCard}</div> : ( {!splitting ? (hasExpenses && <div style={{ marginBottom: 36 }}>{totalCard}</div>) : (
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, minmax(0, 1fr))', gap: 16, marginBottom: 36 }} className="costs-summary"> <div style={{ display: 'grid', gridTemplateColumns: hasExpenses ? 'repeat(4, minmax(0, 1fr))' : 'repeat(3, minmax(0, 1fr))', gap: 16, marginBottom: 36 }} className="costs-summary">
<SummaryCard label={t('costs.youOwe')} sub={t('costs.youOweSub')} amount={balancesKnown ? totals.owe : null} currency={base} locale={locale} <SummaryCard label={t('costs.youOwe')} sub={t('costs.youOweSub')} amount={balancesKnown ? totals.owe : null} currency={base} locale={locale}
icon={<ArrowDown size={18} />} tone="owe" failed={settlementError} icon={<ArrowDown size={18} />} tone="owe" failed={settlementError}
foot={totals.owe > 0.01 foot={totals.owe > 0.01
@@ -302,18 +281,17 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
foot={totals.outstandingCount > 0 foot={totals.outstandingCount > 0
? <span><b>{totals.outstandingCount}</b> {t('costs.outstandingItems', { count: totals.outstandingCount })}</span> ? <span><b>{totals.outstandingCount}</b> {t('costs.outstandingItems', { count: totals.outstandingCount })}</span>
: settledUp && <span className="text-content-faint">{t('costs.allSettled')}</span>} /> : settledUp && <span className="text-content-faint">{t('costs.allSettled')}</span>} />
{totalCard} {hasExpenses && totalCard}
</div>)} </div>)}
{/* ── Main grid ── */} {/* ── Main grid ── */}
{/* The same four columns as the cards above: the ledger takes three, the {/* The same four columns as the cards above: the ledger takes three, the
sidebar the last, so it lines up with the total-spend card. */} sidebar the last, so it lines up with the total-spend card. */}
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, minmax(0, 1fr))', columnGap: 16, rowGap: 32, alignItems: 'start' }} className="costs-grid"> <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, minmax(0, 1fr))', columnGap: 16, rowGap: 32, alignItems: 'start' }} className="costs-grid">
{/* expenses */} <div className="costs-main" style={{ gridColumn: emptyLedger ? '1 / -1' : 'span 3', minWidth: 0 }}>
<div className="costs-main" style={{ gridColumn: 'span 3', minWidth: 0 }}>
{dayBanner} {dayBanner}
{view === 'table' ? ( {emptyLedger ? <EmptyState scene="costs" title={t('costs.emptyText')} /> : view === 'table' && hasExpenses ? (
filtered.length === 0 && budgetItems.length > 0 ? ( filtered.length === 0 && budgetItems.length > 0 ? (
<div className="text-content-faint" style={{ textAlign: 'center', padding: '60px 20px' }}>{t('costs.noMatch')}</div> <div className="text-content-faint" style={{ textAlign: 'center', padding: '60px 20px' }}>{t('costs.noMatch')}</div>
) : ( ) : (
@@ -379,14 +357,14 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
</>} </>}
{/* by category; the table view sums up four ways instead */} {/* by category; the table view sums up four ways instead */}
{view === 'table' ? ( {hasExpenses && (view === 'table' ? (
<CostsTableSummary items={filtered} baseTotal={baseTotal} toBase={booked} fmt={v => fmt(v)} personName={personName} splitting={splitting} /> <CostsTableSummary items={filtered} baseTotal={baseTotal} toBase={booked} fmt={v => fmt(v)} personName={personName} splitting={splitting} />
) : ( ) : (
<section aria-label={t('costs.byCategory')} className={SIDE_CARD}> <section aria-label={t('costs.byCategory')} className={SIDE_CARD}>
{sideHead(t('costs.byCategory'))} {sideHead(t('costs.byCategory'))}
<div className="px-4 py-4">{categoryBars}</div> <div className="px-4 py-4">{categoryBars}</div>
</section> </section>
)} ))}
<CostsModeCard trip={trip} memberCount={people.length} canEdit={canEdit} className={SIDE_CARD} /> <CostsModeCard trip={trip} memberCount={people.length} canEdit={canEdit} className={SIDE_CARD} />
</div> </div>
</div> </div>
@@ -492,8 +470,7 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
function MobileBody() { function MobileBody() {
return ( return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 16, paddingTop: 8 }}> <div style={{ display: 'flex', flexDirection: 'column', gap: 16, paddingTop: 8 }}>
{/* Total card */} {hasExpenses ? <section style={{ background: 'linear-gradient(135deg,#1f2937,#111827)', color: '#fff', borderRadius: 22, padding: '20px 20px 16px', boxShadow: '0 8px 24px -8px rgba(0,0,0,0.28)' }}>
<section style={{ background: 'linear-gradient(135deg,#1f2937,#111827)', color: '#fff', borderRadius: 22, padding: '20px 20px 16px', boxShadow: '0 8px 24px -8px rgba(0,0,0,0.28)' }}>
<div style={{ fontSize: 'calc(11.5px * var(--fs-scale-caption, 1))', textTransform: 'uppercase', letterSpacing: '0.12em', color: 'rgba(255,255,255,0.6)', fontWeight: 600 }}>{t('costs.totalSpend')}</div> <div style={{ fontSize: 'calc(11.5px * var(--fs-scale-caption, 1))', textTransform: 'uppercase', letterSpacing: '0.12em', color: 'rgba(255,255,255,0.6)', fontWeight: 600 }}>{t('costs.totalSpend')}</div>
<div style={{ fontSize: 'calc(44px * var(--fs-scale-title, 1))', fontWeight: 700, letterSpacing: '-0.04em', lineHeight: 1, marginTop: 8, display: 'flex', alignItems: 'baseline' }}>{bigMoney(totals.totalSpend, 24, 'rgba(255,255,255,0.6)')}</div> <div style={{ fontSize: 'calc(44px * var(--fs-scale-title, 1))', fontWeight: 700, letterSpacing: '-0.04em', lineHeight: 1, marginTop: 8, display: 'flex', alignItems: 'baseline' }}>{bigMoney(totals.totalSpend, 24, 'rgba(255,255,255,0.6)')}</div>
{splitting && <div style={{ display: 'flex', gap: 18, marginTop: 12, fontSize: 'calc(12px * var(--fs-scale-body, 1))', color: 'rgba(255,255,255,0.6)', flexWrap: 'wrap' }}> {splitting && <div style={{ display: 'flex', gap: 18, marginTop: 12, fontSize: 'calc(12px * var(--fs-scale-body, 1))', color: 'rgba(255,255,255,0.6)', flexWrap: 'wrap' }}>
@@ -512,7 +489,10 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
<ScanLine size={16} /> {t('costs.scan.button')} <ScanLine size={16} /> {t('costs.scan.button')}
</button> </button>
)} )}
</section> </section> : <div className="flex flex-wrap justify-end gap-2">
{receiptScan.offered && <DialogButton onClick={receiptScan.open}>{t('costs.scan.button')}</DialogButton>}
{canEdit && <DialogButton variant="primary" onClick={() => { setEditing(null); setModalOpen(true) }}>{t('costs.addExpense')}</DialogButton>}
</div>}
{/* Owe / Owed, outstanding and settling up: only with something to split (#2689) */} {/* Owe / Owed, outstanding and settling up: only with something to split (#2689) */}
{splitting && <> {splitting && <>
@@ -583,7 +563,7 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
</div> </div>
{dayBanner} {dayBanner}
{dayGroups.length === 0 {dayGroups.length === 0
? <div className="text-content-faint" style={{ textAlign: 'center', padding: '36px 16px', fontSize: 'calc(13px * var(--fs-scale-body, 1))' }}>{search ? t('costs.noMatch') : t('costs.emptyText')}</div> ? mobileEmptyLedger
: dayGroups.map(g => { : dayGroups.map(g => {
const dtot = g.entries.reduce((a, en) => en.kind === 'expense' ? a + baseTotal(en.e) : a, 0) const dtot = g.entries.reduce((a, en) => en.kind === 'expense' ? a + baseTotal(en.e) : a, 0)
return ( return (
@@ -610,11 +590,10 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
</div> </div>
</>} </>}
{/* By category */} {hasExpenses && <div className={cardCls} style={{ borderRadius: 18, padding: 16 }}>
<div className={cardCls} style={{ borderRadius: 18, padding: 16 }}>
<div className={labelCls} style={{ marginBottom: 14 }}>{t('costs.byCategory')}</div> <div className={labelCls} style={{ marginBottom: 14 }}>{t('costs.byCategory')}</div>
{categoryBars} {categoryBars}
</div> </div>}
<CostsModeCard trip={trip} memberCount={people.length} canEdit={canEdit} className={`${cardCls} rounded-[18px]`} /> <CostsModeCard trip={trip} memberCount={people.length} canEdit={canEdit} className={`${cardCls} rounded-[18px]`} />
</div> </div>
) )
@@ -692,10 +671,9 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
<span className="text-content" style={{ fontSize: 'calc(15px * var(--fs-scale-subtitle, 1))', fontWeight: 600, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{e.name}</span> <span className="text-content" style={{ fontSize: 'calc(15px * var(--fs-scale-subtitle, 1))', fontWeight: 600, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{e.name}</span>
{unfinished && !isMobile && ( {unfinished && !isMobile && (
<Tooltip label={t('costs.unfinishedHint')}> <Tooltip label={t('costs.unfinishedHint')}>
<span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, padding: '2px 8px 2px 6px', borderRadius: 999, background: 'rgba(217,119,6,0.14)', color: '#d97706', fontSize: 'calc(11px * var(--fs-scale-caption, 1))', fontWeight: 700, flexShrink: 0 }}> <span role="img" aria-label={t('costs.unfinished')} className="grid size-5 shrink-0 place-items-center rounded-full bg-warning-soft text-warning">
<span style={{ width: 14, height: 14, borderRadius: '50%', background: '#d97706', color: '#fff', display: 'grid', placeItems: 'center', fontSize: 'calc(10px * var(--fs-scale-caption, 1))', fontWeight: 800 }}>!</span> <AlertCircle size={13} strokeWidth={2.2} aria-hidden="true" />
{t('costs.unfinished')} </span>
</span>
</Tooltip> </Tooltip>
)} )}
{(e.receipts || []).length > 0 && ( {(e.receipts || []).length > 0 && (
@@ -1056,7 +1034,7 @@ export function ExpenseModal({ tripId, base, people, me, editing, prefill, onClo
} }
const payerSection = ( const payerSection = (
<DialogSection <DialogSection icon={Wallet}
label={t('costs.whoPaid')} label={t('costs.whoPaid')}
className={GROUP} tallAction className={GROUP} tallAction
action={( action={(
@@ -1130,7 +1108,7 @@ export function ExpenseModal({ tripId, base, people, me, editing, prefill, onClo
) )
const splitSection = ( const splitSection = (
<DialogSection <DialogSection icon={Split}
label={t('costs.split') || 'Split'} label={t('costs.split') || 'Split'}
className={GROUP} tallAction className={GROUP} tallAction
action={( action={(
@@ -1325,53 +1303,55 @@ export function ExpenseModal({ tripId, base, people, me, editing, prefill, onClo
</DialogFooter> </DialogFooter>
)} )}
> >
<div className={`${GROUP} flex flex-col gap-3`}> <DialogSection icon={Banknote} label={t('costs.amount')} className={GROUP}>
<div className={isMobile ? 'flex flex-col gap-5' : 'grid grid-cols-[minmax(0,1.3fr)_minmax(0,1fr)_minmax(0,1fr)] items-start gap-3'}> <div className="flex flex-col gap-3">
<EditorField label={t('costs.totalAmount')}> <div className={isMobile ? 'flex flex-col gap-5' : 'grid grid-cols-[minmax(0,1.3fr)_minmax(0,1fr)_minmax(0,1fr)] items-start gap-3'}>
<div className="flex items-center rounded-[10px] border border-edge bg-surface-input px-3" style={{ height: FIELD_H, opacity: isTicketMode ? 0.6 : 1 }}> <EditorField label={t('costs.totalAmount')}>
<span className="text-content-faint" style={fs(15, 'subtitle')}>{sym(currency)}</span> <div className="flex items-center rounded-[10px] border border-edge bg-surface-input px-3" style={{ height: FIELD_H, opacity: isTicketMode ? 0.6 : 1 }}>
<NumericInput mode="signed-decimal" placeholder={zeroAmountInput(currency)} value={localizeAmountInput(isTicketMode ? amountToInputString(ticketInfo.total, currency) : total, currency)} <span className="text-content-faint" style={fs(15, 'subtitle')}>{sym(currency)}</span>
onValueChange={onTotalChange} <NumericInput mode="signed-decimal" placeholder={zeroAmountInput(currency)} value={localizeAmountInput(isTicketMode ? amountToInputString(ticketInfo.total, currency) : total, currency)}
signToggleLabel={t('costs.toggleSign')} onValueChange={onTotalChange}
disabled={isTicketMode} signToggleLabel={t('costs.toggleSign')}
className="w-full flex-1 border-0 bg-transparent ps-1.5 font-semibold text-content outline-none dark:bg-transparent" style={fs(15, 'subtitle')} /> disabled={isTicketMode}
className="w-full flex-1 border-0 bg-transparent ps-1.5 font-semibold text-content outline-none dark:bg-transparent" style={fs(15, 'subtitle')} />
</div>
</EditorField>
<EditorField label={t('costs.currency')}>
<CustomSelect value={currency} onChange={v => setCurrency(String(v))} searchable
options={currencyChoices}
style={{ width: '100%' }} />
</EditorField>
<EditorField label={t('costs.day')}>
<CustomDatePicker value={day} onChange={setDay} style={{ width: '100%' }} />
</EditorField>
</div> </div>
</EditorField>
<EditorField label={t('costs.currency')}>
<CustomSelect value={currency} onChange={v => setCurrency(String(v))} searchable
options={currencyChoices}
style={{ width: '100%' }} />
</EditorField>
<EditorField label={t('costs.day')}>
<CustomDatePicker value={day} onChange={setDay} style={{ width: '100%' }} />
</EditorField>
</div>
{fx && ( {fx && (
<div className="flex flex-wrap items-center gap-1.5 text-content-faint" style={fs(12, 'body')}> <div className="flex flex-wrap items-center gap-1.5 text-content-faint" style={fs(12, 'body')}>
{badge(formatMoney(totalNum, currency, locale))} {badge(formatMoney(totalNum, currency, locale))}
{fx.inTrip != null && <> {fx.inTrip != null && <>
<span>→</span> <span>→</span>
{badge(formatMoney(fx.inTrip, tripCur, locale))} {badge(formatMoney(fx.inTrip, tripCur, locale))}
</>} </>}
{fx.shown != null && <> {fx.shown != null && <>
<span>≈</span> <span>≈</span>
{badge(formatMoney(fx.shown, base, locale))} {badge(formatMoney(fx.shown, base, locale))}
<span>{t('costs.liveRate')}</span> <span>{t('costs.liveRate')}</span>
</>} </>}
</div>
)}
</div> </div>
)} </DialogSection>
</div>
{showSplit && payerSection} {showSplit && payerSection}
{showSplit && splitSection} {showSplit && splitSection}
{/* Side by side the two panels share one height. */} {/* Side by side the two panels share one height. */}
<div className={isMobile ? 'flex flex-col gap-5' : 'grid grid-cols-2 gap-3'}> <div className={isMobile ? 'flex flex-col gap-5' : 'grid grid-cols-2 gap-3'}>
<EditorField label={t('costs.note')} htmlFor="expense-note" className={GROUP}> <DialogSection icon={NotebookPen} label={<label htmlFor={`${titleId}-note`}>{t('costs.note')}</label>} className={GROUP}>
<textarea id="expense-note" value={note} onChange={e => setNote(e.target.value)} rows={3} <textarea id={`${titleId}-note`} value={note} onChange={e => setNote(e.target.value)} rows={3}
placeholder={t('costs.notePlaceholder')} maxLength={NOTE_MAX} className={`${TEXTAREA} resize-y`} /> placeholder={t('costs.notePlaceholder')} maxLength={NOTE_MAX} className={`${TEXTAREA} resize-y`} />
</EditorField> </DialogSection>
<ExpenseReceiptsSection className={GROUP} receipts={receipts} pendingFiles={pendingReceiptFiles} uploading={uploadingReceipt} <ExpenseReceiptsSection className={GROUP} receipts={receipts} pendingFiles={pendingReceiptFiles} uploading={uploadingReceipt}
linkable={linkableFiles} onPick={handleReceiptFileSelect} onLink={handleLinkReceipt} linkable={linkableFiles} onPick={handleReceiptFileSelect} onLink={handleLinkReceipt}
onPreview={index => setModalPreviewReceipts({ receipts, initialIndex: index })} onPreview={index => setModalPreviewReceipts({ receipts, initialIndex: index })}
+2 -1
View File
@@ -1,3 +1,4 @@
import { focusRevealedEditor } from '../shared/dialogFocus'
import { useMemo, useRef, useState, type KeyboardEvent, type ReactNode } from 'react' import { useMemo, useRef, useState, type KeyboardEvent, type ReactNode } from 'react'
import { ChevronDown, Lock, Pencil, Plus, Trash2 } from 'lucide-react' import { ChevronDown, Lock, Pencil, Plus, Trash2 } from 'lucide-react'
import { useTranslation } from '../../i18n' import { useTranslation } from '../../i18n'
@@ -307,7 +308,7 @@ function TextInput({ value, onSave, onCancel, label, numeric = false }: {
if (ev.key === 'Escape') { ev.preventDefault(); ev.stopPropagation(); finish(onCancel) } if (ev.key === 'Escape') { ev.preventDefault(); ev.stopPropagation(); finish(onCancel) }
} }
return ( return (
<input autoFocus type="text" value={draft} aria-label={label} inputMode={numeric ? 'decimal' : undefined} <input ref={focusRevealedEditor} type="text" value={draft} aria-label={label} inputMode={numeric ? 'decimal' : undefined}
onChange={ev => setDraft(ev.target.value)} onKeyDown={onKey} onBlur={() => finish(() => onSave(draft))} onChange={ev => setDraft(ev.target.value)} onKeyDown={onKey} onBlur={() => finish(() => onSave(draft))}
className={`${INPUT} ${numeric ? 'text-center tabular-nums' : ''}`} /> className={`${INPUT} ${numeric ? 'text-center tabular-nums' : ''}`} />
) )
@@ -197,7 +197,7 @@ function FilterMenu(f: CostsFilterProps & { splitting: boolean }) {
</button> </button>
</Tooltip> </Tooltip>
{open && ( {open && (
<div role="menu" onKeyDown={e => { if (e.key === 'Escape') close() }} className="absolute end-0 top-11 z-30" style={{ ...POPOVER, width: 310 }}> <div role="menu" tabIndex={-1} onKeyDown={e => { if (e.key === 'Escape') close() }} className="absolute end-0 top-11 z-30" style={{ ...POPOVER, width: 310 }}>
{f.splitting && <> {f.splitting && <>
<div className="mx-1.5 mb-1 mt-1.5 flex rounded-[10px] bg-surface-tertiary p-[3px]"> <div className="mx-1.5 mb-1 mt-1.5 flex rounded-[10px] bg-surface-tertiary p-[3px]">
{owners.map(([o, label]) => ( {owners.map(([o, label]) => (
@@ -46,6 +46,7 @@ export function ExpenseReceiptsSection({
return ( return (
<DialogSection <DialogSection
icon={Receipt}
label={t('costs.receiptsTitle')} label={t('costs.receiptsTitle')}
className={className} className={className}
action={ action={
@@ -1,6 +1,8 @@
import { useState, useEffect } from 'react' import { useState, useEffect, useId } from 'react'
import { createPortal } from 'react-dom' import { createPortal } from 'react-dom'
import { ExternalLink, Download, X, FileText, ChevronLeft, ChevronRight, FileImage } from 'lucide-react' import { ExternalLink, Download, X, FileText, ChevronLeft, ChevronRight, FileImage } from 'lucide-react'
import { useIsPhone } from '../../hooks/useIsPhone'
import { DialogHeader, DialogTile, NEUTRAL_TINT, PILL } from '../shared/DialogShell'
import { useTranslation } from '../../i18n' import { useTranslation } from '../../i18n'
import { getAuthUrl } from '../../api/authUrl' import { getAuthUrl } from '../../api/authUrl'
import { openFile as openFileUrl } from '../../utils/fileDownload' import { openFile as openFileUrl } from '../../utils/fileDownload'
@@ -15,6 +17,8 @@ interface ReceiptPreviewModalProps {
export function ReceiptPreviewModal({ receipts, initialIndex = 0, onClose }: ReceiptPreviewModalProps) { export function ReceiptPreviewModal({ receipts, initialIndex = 0, onClose }: ReceiptPreviewModalProps) {
const { t } = useTranslation() const { t } = useTranslation()
const isPhone = useIsPhone()
const labelId = useId()
const [index, setIndex] = useState(Math.max(0, Math.min(initialIndex, receipts.length - 1))) const [index, setIndex] = useState(Math.max(0, Math.min(initialIndex, receipts.length - 1)))
const [signedUrl, setSignedUrl] = useState('') const [signedUrl, setSignedUrl] = useState('')
const [loading, setLoading] = useState(false) const [loading, setLoading] = useState(false)
@@ -92,13 +96,16 @@ export function ReceiptPreviewModal({ receipts, initialIndex = 0, onClose }: Rec
}} }}
> >
<div <div
role="presentation" role="dialog"
aria-modal="true"
aria-labelledby={isPhone ? undefined : labelId}
aria-label={isPhone ? current.original_name : undefined}
style={{ style={{
width: '100%', width: '100%',
maxWidth: 950, maxWidth: 950,
height: '94vh', height: '94vh',
background: 'var(--bg-card)', background: 'var(--bg-card)',
borderRadius: 12, borderRadius: isPhone ? 12 : 22,
overflow: 'hidden', overflow: 'hidden',
display: 'flex', display: 'flex',
flexDirection: 'column', flexDirection: 'column',
@@ -106,95 +113,115 @@ export function ReceiptPreviewModal({ receipts, initialIndex = 0, onClose }: Rec
}} }}
onClick={e => e.stopPropagation()} onClick={e => e.stopPropagation()}
> >
{/* Header - identical to PdfPreviewModal */} {isPhone ? (
<div <div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
padding: '10px 16px',
borderBottom: '1px solid var(--border-primary)',
flexShrink: 0,
}}
>
<span
style={{ style={{
fontSize: 'calc(13px * var(--fs-scale-body, 1))', display: 'flex',
fontWeight: 600, alignItems: 'center',
color: 'var(--text-primary)', justifyContent: 'space-between',
overflow: 'hidden', padding: '10px 16px',
textOverflow: 'ellipsis', borderBottom: '1px solid var(--border-primary)',
whiteSpace: 'nowrap', flexShrink: 0,
flex: 1,
}} }}
> >
{current.original_name} <span
</span>
<div style={{ display: 'flex', alignItems: 'center', gap: 8, flexShrink: 0 }}>
<button
type="button"
onClick={handleOpenTab}
style={{ style={{
display: 'flex', fontSize: 'calc(13px * var(--fs-scale-body, 1))',
alignItems: 'center', fontWeight: 600,
gap: 4, color: 'var(--text-primary)',
fontSize: 'calc(12px * var(--fs-scale-body, 1))', overflow: 'hidden',
color: 'var(--text-muted)', textOverflow: 'ellipsis',
background: 'none', whiteSpace: 'nowrap',
border: 'none', flex: 1,
cursor: 'pointer',
textDecoration: 'none',
padding: '4px 8px',
borderRadius: 6,
transition: 'color 0.15s',
}} }}
onMouseEnter={e => (e.currentTarget.style.color = 'var(--text-primary)')}
onMouseLeave={e => (e.currentTarget.style.color = 'var(--text-muted)')}
> >
<ExternalLink size={13} /> {t('files.openTab')} {current.original_name}
</button> </span>
<button <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexShrink: 0 }}>
type="button" <button
onClick={handleDownload} type="button"
style={{ onClick={handleOpenTab}
display: 'flex', style={{
alignItems: 'center', display: 'flex',
gap: 4, alignItems: 'center',
fontSize: 'calc(12px * var(--fs-scale-body, 1))', gap: 4,
color: 'var(--text-muted)', fontSize: 'calc(12px * var(--fs-scale-body, 1))',
background: 'none', color: 'var(--text-muted)',
border: 'none', background: 'none',
cursor: 'pointer', border: 'none',
textDecoration: 'none', cursor: 'pointer',
padding: '4px 8px', textDecoration: 'none',
borderRadius: 6, padding: '4px 8px',
transition: 'color 0.15s', borderRadius: 6,
}} transition: 'color 0.15s',
onMouseEnter={e => (e.currentTarget.style.color = 'var(--text-primary)')} }}
onMouseLeave={e => (e.currentTarget.style.color = 'var(--text-muted)')} onMouseEnter={e => (e.currentTarget.style.color = 'var(--text-primary)')}
> onMouseLeave={e => (e.currentTarget.style.color = 'var(--text-muted)')}
<Download size={13} /> {t('files.download') || 'Download'} >
</button> <ExternalLink size={13} /> {t('files.openTab')}
<button </button>
type="button" <button
onClick={onClose} type="button"
style={{ onClick={handleDownload}
background: 'none', style={{
border: 'none', display: 'flex',
cursor: 'pointer', alignItems: 'center',
color: 'var(--text-faint)', gap: 4,
display: 'flex', fontSize: 'calc(12px * var(--fs-scale-body, 1))',
padding: 4, color: 'var(--text-muted)',
borderRadius: 6, background: 'none',
transition: 'color 0.15s', border: 'none',
}} cursor: 'pointer',
onMouseEnter={e => (e.currentTarget.style.color = 'var(--text-primary)')} textDecoration: 'none',
onMouseLeave={e => (e.currentTarget.style.color = 'var(--text-faint)')} padding: '4px 8px',
> borderRadius: 6,
<X size={18} /> transition: 'color 0.15s',
</button> }}
onMouseEnter={e => (e.currentTarget.style.color = 'var(--text-primary)')}
onMouseLeave={e => (e.currentTarget.style.color = 'var(--text-muted)')}
>
<Download size={13} /> {t('files.download') || 'Download'}
</button>
<button
type="button"
onClick={onClose}
aria-label={t('common.close')}
style={{
background: 'none',
border: 'none',
cursor: 'pointer',
color: 'var(--text-faint)',
display: 'flex',
padding: 4,
borderRadius: 6,
transition: 'color 0.15s',
}}
onMouseEnter={e => (e.currentTarget.style.color = 'var(--text-primary)')}
onMouseLeave={e => (e.currentTarget.style.color = 'var(--text-faint)')}
>
<X size={18} />
</button>
</div>
</div> </div>
</div> ) : (
<DialogHeader
tile={<DialogTile><FileText size={20} className="text-content-muted" /></DialogTile>}
tint={NEUTRAL_TINT}
labelId={labelId}
onClose={onClose}
title={current.original_name}
pills={(
<>
<button type="button" onClick={handleOpenTab} className={`${PILL} hover:bg-surface-hover`}>
<ExternalLink size={14} /> {t('files.openTab')}
</button>
<button type="button" onClick={handleDownload} className={`${PILL} hover:bg-surface-hover`}>
<Download size={14} /> {t('files.download')}
</button>
</>
)}
/>
)}
{/* Tab strip if multiple receipts */} {/* Tab strip if multiple receipts */}
{receipts.length > 1 && ( {receipts.length > 1 && (
@@ -241,6 +268,7 @@ export function ReceiptPreviewModal({ receipts, initialIndex = 0, onClose }: Rec
{r.original_name} {r.original_name}
</span> </span>
<span <span
aria-hidden="true"
style={{ style={{
fontSize: 'calc(10px * var(--fs-scale-caption, 1))', fontSize: 'calc(10px * var(--fs-scale-caption, 1))',
opacity: active ? 0.8 : 0.5, opacity: active ? 0.8 : 0.5,
@@ -4,6 +4,7 @@ import { ScanLine, X } from 'lucide-react'
import { useTranslation } from '../../i18n' import { useTranslation } from '../../i18n'
import { useIsPhone } from '../../mobile/useIsPhone' import { useIsPhone } from '../../mobile/useIsPhone'
import { DialogButton, DialogFooter, DialogHeader, DialogShell, DialogTile, FooterSpacer, NEUTRAL_TINT, fs } from '../shared/DialogShell' import { DialogButton, DialogFooter, DialogHeader, DialogShell, DialogTile, FooterSpacer, NEUTRAL_TINT, fs } from '../shared/DialogShell'
import { PANEL } from '../shared/dialogParts'
import { RECEIPT_PHOTO_ACCEPT, type ReceiptScan } from './useReceiptScan' import { RECEIPT_PHOTO_ACCEPT, type ReceiptScan } from './useReceiptScan'
/** /**
@@ -42,6 +43,7 @@ export function ReceiptScanModal({ scan }: { scan: ReceiptScan }) {
onClose={scan.close} onClose={scan.close}
labelledBy={labelId} labelledBy={labelId}
width="narrow" width="narrow"
front
header={( header={(
<DialogHeader <DialogHeader
tile={<DialogTile><ScanLine size={20} strokeWidth={1.9} className="text-content-muted" /></DialogTile>} tile={<DialogTile><ScanLine size={20} strokeWidth={1.9} className="text-content-muted" /></DialogTile>}
@@ -49,8 +51,6 @@ export function ReceiptScanModal({ scan }: { scan: ReceiptScan }) {
labelId={labelId} labelId={labelId}
onClose={scan.close} onClose={scan.close}
title={t('costs.scan.title')} title={t('costs.scan.title')}
sub={t('costs.scan.accepted')}
subWraps
/> />
)} )}
footer={( footer={(
@@ -63,19 +63,23 @@ export function ReceiptScanModal({ scan }: { scan: ReceiptScan }) {
</DialogFooter> </DialogFooter>
)} )}
> >
{picker} <div className={PANEL}>
<button type="button" onClick={() => inputRef.current?.click()} {...dropHandlers} {picker}
className={`flex min-h-[132px] w-full flex-col items-center justify-center gap-2 rounded-2xl border-2 border-dashed px-4 py-5 text-center transition-colors ${dragOver ? 'border-content-muted bg-surface-tertiary' : 'border-edge bg-surface-secondary hover:border-content-faint'}`}> <button type="button" onClick={() => inputRef.current?.click()} {...dropHandlers}
<span className="pointer-events-none grid h-10 w-10 place-items-center rounded-full bg-surface-card shadow-sm"> aria-describedby={`${labelId}-formats`}
<ScanLine size={18} strokeWidth={1.9} className={dragOver ? 'text-content' : 'text-content-muted'} /> className={`trek-form-control flex min-h-24 [--form-control-min-height:96px] w-full flex-col items-center justify-center gap-2 rounded-[10px] border border-dashed p-4 text-center transition-colors ${dragOver ? 'border-content-muted bg-surface-tertiary' : 'border-edge bg-surface-input hover:border-content-faint'}`}>
</span> <span className="pointer-events-none grid h-10 w-10 place-items-center rounded-full bg-surface-card shadow-sm">
<span className={`pointer-events-none break-all font-semibold ${scan.photo ? 'text-content' : 'text-content-muted'}`} style={fs(13, 'body')}> <ScanLine size={18} strokeWidth={1.9} className={dragOver ? 'text-content' : 'text-content-muted'} />
{dragOver ? t('costs.scan.dropActive') : scan.photo ? scan.photo.name : t('costs.scan.dropHere')} </span>
</span> <span className={`pointer-events-none break-all font-semibold ${scan.photo ? 'text-content' : 'text-content-muted'}`} style={fs(13, 'body')}>
</button> {dragOver ? t('costs.scan.dropActive') : scan.photo ? scan.photo.name : t('costs.scan.dropHere')}
{scan.error && ( </span>
<div role="alert" className="rounded-[12px] bg-danger-soft px-3 py-2.5 text-danger" style={fs(12, 'body')}>{scan.error}</div> </button>
)} <p id={`${labelId}-formats`} className="m-0 text-caption text-content-muted">{t('costs.scan.accepted')}</p>
{scan.error && (
<div role="alert" className="rounded-[12px] bg-danger-soft px-3 py-2.5 text-danger" style={fs(12, 'body')}>{scan.error}</div>
)}
</div>
</DialogShell> </DialogShell>
) )
@@ -55,7 +55,7 @@ describe('CollabLinks', () => {
render(<CollabLinks tripId={1} />); render(<CollabLinks tripId={1} />);
const heading = await screen.findByRole('heading', { level: 3 }); const heading = await screen.findByRole('heading', { level: 3 });
expect(heading).toHaveTextContent(/links/i); expect(heading).toHaveTextContent(/links/i);
expect(heading).toHaveClass('uppercase'); expect(heading).toHaveClass('font-semibold');
expect(screen.getByRole('button', { name: /add link|collab\.links\.add/i })).toBeInTheDocument(); expect(screen.getByRole('button', { name: /add link|collab\.links\.add/i })).toBeInTheDocument();
}); });
+9 -111
View File
@@ -1,30 +1,22 @@
import { cloneElement, CSSProperties, FormEvent, ReactElement, useEffect, useId, useRef, useState } from 'react' import type { CollabLink } from '@trek/shared'
import { focusRevealedEditor } from '../shared/dialogFocus'
import { cloneElement, CSSProperties, FormEvent, ReactElement, useId, useState } from 'react'
import { createPortal } from 'react-dom' import { createPortal } from 'react-dom'
import { ExternalLink, Link2, Pencil, Pin, Plus, Trash2, X } from 'lucide-react' import { ExternalLink, Link2, Pencil, Pin, Plus, Trash2, X } from 'lucide-react'
import CollabPanelHead, { HEAD_ACTION } from './CollabPanelHead' import CollabPanelHead, { HEAD_ACTION } from './CollabPanelHead'
import { DialogButton, DialogFooter, DialogHeader, DialogShell, DialogTile, FooterSpacer, NEUTRAL_TINT } from '../shared/DialogShell' import { DialogButton, DialogFooter, DialogHeader, DialogShell, DialogTile, FooterSpacer, NEUTRAL_TINT } from '../shared/DialogShell'
import { EditorField, INPUT } from '../shared/dialogParts' import { EditorField, INPUT } from '../shared/dialogParts'
import { useIsPhone } from '../../mobile/useIsPhone' import { useIsPhone } from '../../mobile/useIsPhone'
import { collabApi } from '../../api/client'
import { addListener, removeListener } from '../../api/websocket'
import { useTranslation } from '../../i18n' import { useTranslation } from '../../i18n'
import { useCanDo } from '../../store/permissionsStore' import { useCanDo } from '../../store/permissionsStore'
import { useTripStore } from '../../store/tripStore' import { useTripStore } from '../../store/tripStore'
import ConfirmDialog from '../shared/ConfirmDialog' import ConfirmDialog from '../shared/ConfirmDialog'
import EmptyState from '../shared/EmptyState' import EmptyState from '../shared/EmptyState'
import { Tooltip } from '../shared/Tooltip' import { Tooltip } from '../shared/Tooltip'
import { useToast } from '../shared/Toast' import { collabLinkHost, useCollabLinks } from './useCollabLinks'
import { offlineOr } from '../../utils/needsConnection'
const FONT = "var(--font-system)" const FONT = "var(--font-system)"
interface CollabLink {
id: number
title: string
url: string
pinned: boolean | number
}
// The glyph holds the place until a favicon has really arrived: a host that never // The glyph holds the place until a favicon has really arrived: a host that never
// answers, or answers with a blank pixel, left the chip with an empty square. // answers, or answers with a blank pixel, left the chip with an empty square.
function LinkIcon({ url }: { url: string }) { function LinkIcon({ url }: { url: string }) {
@@ -55,10 +47,6 @@ function ChipTip({ label, phone, children }: { label: string; phone: boolean; ch
return phone ? cloneElement(children, { title: label }) : <Tooltip label={label}>{children}</Tooltip> return phone ? cloneElement(children, { title: label }) : <Tooltip label={label}>{children}</Tooltip>
} }
function hostOf(url: string): string {
try { return new URL(url).hostname.replace(/^www\./, '') } catch { return url }
}
/** /**
* The add and edit form as a modal, like the poll and note panels next to it. * The add and edit form as a modal, like the poll and note panels next to it.
* Inline it pushed the list down and gave the panel a second header, which is * Inline it pushed the list down and gave the panel a second header, which is
@@ -147,7 +135,7 @@ function LinkModal({ link, onClose, onSave }: { link?: CollabLink; onClose: () =
<div style={{ padding: '14px 16px 16px', display: 'flex', flexDirection: 'column', gap: 12 }}> <div style={{ padding: '14px 16px 16px', display: 'flex', flexDirection: 'column', gap: 12 }}>
<div> <div>
<label htmlFor="collab-link-title" style={{ ...label, display: 'block' }}>{t('collab.links.titlePlaceholder')}</label> <label htmlFor="collab-link-title" style={{ ...label, display: 'block' }}>{t('collab.links.titlePlaceholder')}</label>
<input id="collab-link-title" value={title} onChange={e => setTitle(e.target.value)} placeholder={t('collab.links.titlePlaceholder')} autoFocus style={field} /> <input id="collab-link-title" value={title} onChange={e => setTitle(e.target.value)} placeholder={t('collab.links.titlePlaceholder')} ref={focusRevealedEditor} style={field} />
</div> </div>
<div> <div>
<label htmlFor="collab-link-url" style={{ ...label, display: 'block' }}>{t('collab.links.urlPlaceholder')}</label> <label htmlFor="collab-link-url" style={{ ...label, display: 'block' }}>{t('collab.links.urlPlaceholder')}</label>
@@ -172,101 +160,11 @@ export default function CollabLinks({ tripId }: { tripId: number }) {
const isPhone = useIsPhone() const isPhone = useIsPhone()
const trip = useTripStore(s => s.trip) const trip = useTripStore(s => s.trip)
const canEdit = useCanDo()('collab_edit', trip) const canEdit = useCanDo()('collab_edit', trip)
const toast = useToast() const { links, save, toggle, remove } = useCollabLinks(tripId)
const [links, setLinks] = useState<CollabLink[]>([])
const [showForm, setShowForm] = useState(false) const [showForm, setShowForm] = useState(false)
const [editing, setEditing] = useState<CollabLink | null>(null) const [editing, setEditing] = useState<CollabLink | null>(null)
const [pendingDeleteId, setPendingDeleteId] = useState<number | null>(null) const [pendingDeleteId, setPendingDeleteId] = useState<number | null>(null)
// Both are new objects on every render, so depending on them would reload the
// list after each keystroke and drop a link that was just added back out of it.
const toastRef = useRef(toast)
toastRef.current = toast
const tRef = useRef(t)
tRef.current = t
useEffect(() => {
let cancelled = false
collabApi.getLinks(tripId)
.then(d => { if (!cancelled) setLinks(d.links || []) })
.catch(err => {
if (cancelled) return
console.error('Failed to load collab links:', err)
toastRef.current.error(tRef.current('common.error'))
})
return () => { cancelled = true }
}, [tripId])
// Live sync, the same shape the notes panel uses. Without it the three
// collab:link events the server broadcasts would arrive nowhere and a link
// somebody else added would only appear on the next reload.
useEffect(() => {
if (!tripId) return
const handler = (msg: { type?: string; tripId?: number | string; link?: CollabLink; linkId?: number }) => {
// The panel is not remounted on a trip change, so an event still in
// flight from the trip we just left must not land in this list.
if (String(msg?.tripId) !== String(tripId)) return
if (msg.type === 'collab:link:created' && msg.link) {
setLinks(prev => prev.some(l => l.id === msg.link!.id) ? prev : [msg.link!, ...prev])
}
if (msg.type === 'collab:link:updated' && msg.link) {
setLinks(prev => prev
.map(l => l.id === msg.link!.id ? { ...l, ...msg.link! } : l)
.sort((a, b) => Number(b.pinned) - Number(a.pinned)))
}
if (msg.type === 'collab:link:deleted' && msg.linkId) {
setLinks(prev => prev.filter(l => l.id !== msg.linkId))
}
}
addListener(handler)
return () => removeListener(handler)
}, [tripId])
// Every write says something when it fails. Silence left the pin looking
// unchanged and the delete looking ignored, with an unhandled rejection in
// the console as the only trace.
const add = async (data: { title: string; url: string }) => {
try {
const d = await collabApi.createLink(tripId, data)
setLinks(v => [d.link, ...v])
} catch (err) {
console.error('Failed to add collab link:', err)
toast.error(offlineOr(t, t('common.error')))
throw err
}
}
const toggle = async (link: CollabLink) => {
try {
const d = await collabApi.updateLink(tripId, link.id, { pinned: !link.pinned })
setLinks(v => v.map(x => x.id === link.id ? d.link : x).sort((a, b) => Number(b.pinned) - Number(a.pinned)))
} catch (err) {
console.error('Failed to pin collab link:', err)
toast.error(offlineOr(t, t('common.error')))
}
}
const edit = async (link: CollabLink, data: { title: string; url: string }) => {
try {
const d = await collabApi.updateLink(tripId, link.id, data)
setLinks(v => v.map(x => x.id === link.id ? d.link : x))
} catch (err) {
console.error('Failed to edit collab link:', err)
toast.error(offlineOr(t, t('common.error')))
throw err
}
}
const remove = async (id: number) => {
try {
await collabApi.deleteLink(tripId, id)
setLinks(v => v.filter(x => x.id !== id))
} catch (err) {
console.error('Failed to delete collab link:', err)
toast.error(offlineOr(t, t('common.error')))
}
}
return ( return (
<div style={{ height: '100%', display: 'flex', flexDirection: 'column', fontFamily: FONT }}> <div style={{ height: '100%', display: 'flex', flexDirection: 'column', fontFamily: FONT }}>
{/* Header: the desktop's head band; the phone keeps its own */} {/* Header: the desktop's head band; the phone keeps its own */}
@@ -315,7 +213,7 @@ export default function CollabLinks({ tripId }: { tripId: number }) {
<LinkIcon key={link.url} url={link.url} /> <LinkIcon key={link.url} url={link.url} />
<span className="collab-link-chip__text"> <span className="collab-link-chip__text">
<span className="collab-link-chip__title">{link.title}</span> <span className="collab-link-chip__title">{link.title}</span>
<span className="collab-link-chip__host">{hostOf(link.url)}</span> <span className="collab-link-chip__host">{collabLinkHost(link.url)}</span>
</span> </span>
</a> </a>
</ChipTip> </ChipTip>
@@ -345,8 +243,8 @@ export default function CollabLinks({ tripId }: { tripId: number }) {
</div> </div>
{/* Create and edit modals */} {/* Create and edit modals */}
{showForm && <LinkModal onClose={() => setShowForm(false)} onSave={add} />} {showForm && <LinkModal onClose={() => setShowForm(false)} onSave={save} />}
{editing && <LinkModal key={editing.id} link={editing} onClose={() => setEditing(null)} onSave={data => edit(editing, data)} />} {editing && <LinkModal key={editing.id} link={editing} onClose={() => setEditing(null)} onSave={data => save(data, editing.id)} />}
{/* The delete is shared: the link goes for every member, and on the phone the {/* The delete is shared: the link goes for every member, and on the phone the
button is a thumb's width from pin. Same guard as the notes panel. */} button is a thumb's width from pin. Same guard as the notes panel. */}
+6 -6
View File
@@ -3,8 +3,8 @@ import Markdown from 'react-markdown'
import remarkGfm from 'remark-gfm' import remarkGfm from 'remark-gfm'
import remarkBreaks from 'remark-breaks' import remarkBreaks from 'remark-breaks'
import { sanitizedMarkdownComponents, sanitizedMarkdownPlugins } from '../shared/markdownSanitize' import { sanitizedMarkdownComponents, sanitizedMarkdownPlugins } from '../shared/markdownSanitize'
import { Plus, Pencil, StickyNote, Settings, ExternalLink } from 'lucide-react' import { Text, Link, Paperclip, Plus, Pencil, StickyNote, Settings, ExternalLink } from 'lucide-react'
import CollabPanelHead, { HEAD_ACTION } from './CollabPanelHead' import CollabPanelHead, { HEAD_ACTION, HEAD_ICON_ACTION } from './CollabPanelHead'
import { Tooltip } from '../shared/Tooltip' import { Tooltip } from '../shared/Tooltip'
import { DialogButton, DialogFooter, DialogHeader, DialogSection, DialogShell, DialogTile, FooterSpacer, NEUTRAL_TINT, PILL, fs } from '../shared/DialogShell' import { DialogButton, DialogFooter, DialogHeader, DialogSection, DialogShell, DialogTile, FooterSpacer, NEUTRAL_TINT, PILL, fs } from '../shared/DialogShell'
import { collabApi } from '../../api/client' import { collabApi } from '../../api/client'
@@ -252,7 +252,7 @@ function CollabNotesHeader({ t, canEdit, setShowSettings, setShowNewModal, notes
<> <>
<Tooltip label={t('collab.notes.categorySettings')}> <Tooltip label={t('collab.notes.categorySettings')}>
<button type="button" onClick={() => setShowSettings(true)} aria-label={t('collab.notes.categorySettings')} <button type="button" onClick={() => setShowSettings(true)} aria-label={t('collab.notes.categorySettings')}
className="grid h-7 w-7 place-items-center rounded-full bg-surface-card text-content-muted shadow-sm hover:text-content"> className={HEAD_ICON_ACTION}>
<Settings size={13} /> <Settings size={13} />
</button> </button>
</Tooltip> </Tooltip>
@@ -371,13 +371,13 @@ function ViewNoteModal(S: NotesState) {
</DialogFooter> </DialogFooter>
) : undefined} ) : undefined}
> >
<DialogSection label={t('collab.notes.content')}> <DialogSection icon={Text} label={t('collab.notes.content')}>
<div className="collab-note-md-full text-content" style={{ ...fs(14, 'body'), lineHeight: 1.7 }}> <div className="collab-note-md-full text-content" style={{ ...fs(14, 'body'), lineHeight: 1.7 }}>
<Markdown remarkPlugins={[remarkGfm, remarkBreaks]} rehypePlugins={sanitizedMarkdownPlugins} components={sanitizedMarkdownComponents}>{viewingNote.content || ''}</Markdown> <Markdown remarkPlugins={[remarkGfm, remarkBreaks]} rehypePlugins={sanitizedMarkdownPlugins} components={sanitizedMarkdownComponents}>{viewingNote.content || ''}</Markdown>
</div> </div>
</DialogSection> </DialogSection>
{websiteHref && ( {websiteHref && (
<DialogSection label={t('collab.notes.website')}> <DialogSection icon={Link} label={t('collab.notes.website')}>
<a href={websiteHref} target="_blank" rel="noopener noreferrer" <a href={websiteHref} target="_blank" rel="noopener noreferrer"
className="inline-flex max-w-full items-center gap-1.5 rounded-full bg-surface-secondary px-3 py-1.5 font-semibold text-content no-underline hover:opacity-80" style={fs(12, 'body')}> className="inline-flex max-w-full items-center gap-1.5 rounded-full bg-surface-secondary px-3 py-1.5 font-semibold text-content no-underline hover:opacity-80" style={fs(12, 'body')}>
<ExternalLink size={13} className="flex-none text-content-muted" /> <ExternalLink size={13} className="flex-none text-content-muted" />
@@ -386,7 +386,7 @@ function ViewNoteModal(S: NotesState) {
</DialogSection> </DialogSection>
)} )}
{attachments.length > 0 && ( {attachments.length > 0 && (
<DialogSection label={t('files.title')}> <DialogSection icon={Paperclip} label={t('files.title')}>
<div className="flex flex-wrap gap-2.5"> <div className="flex flex-wrap gap-2.5">
{attachments.map(a => { {attachments.map(a => {
const isImage = a.mime_type?.startsWith('image/') const isImage = a.mime_type?.startsWith('image/')
@@ -1,5 +1,5 @@
import { useId, useState } from 'react' import { useId, useState } from 'react'
import { Plus, Tags, Trash2 } from 'lucide-react' import { Shapes, Plus, Tags, Trash2 } from 'lucide-react'
import { NOTE_COLORS } from './CollabNotes.constants' import { NOTE_COLORS } from './CollabNotes.constants'
import { EditableCatName } from './CollabNotesEditableCatName' import { EditableCatName } from './CollabNotesEditableCatName'
import { originalCategoryName } from './CollabNotes.helpers' import { originalCategoryName } from './CollabNotes.helpers'
@@ -96,7 +96,7 @@ export function CategorySettingsModal({ onClose, categories, categoryColors, onS
</DialogFooter> </DialogFooter>
)} )}
> >
<DialogSection label={t('collab.notes.category')}> <DialogSection icon={Shapes} label={t('collab.notes.category')}>
{allCats.length === 0 ? ( {allCats.length === 0 ? (
<p className="m-0 rounded-[12px] bg-surface-secondary px-4 py-5 text-center text-content-faint" style={fs(12.5, 'body')}> <p className="m-0 rounded-[12px] bg-surface-secondary px-4 py-5 text-center text-content-faint" style={fs(12.5, 'body')}>
{t('collab.notes.noCategoriesYet') || 'No categories yet'} {t('collab.notes.noCategoriesYet') || 'No categories yet'}
@@ -16,7 +16,7 @@ describe('CollabPanelHead', () => {
const { rerender } = render(<CollabPanelHead icon={StickyNote} title="Notes" count={0} />); const { rerender } = render(<CollabPanelHead icon={StickyNote} title="Notes" count={0} />);
expect(screen.queryByText('0')).toBeNull(); expect(screen.queryByText('0')).toBeNull();
rerender(<CollabPanelHead icon={StickyNote} title="Notes" />); rerender(<CollabPanelHead icon={StickyNote} title="Notes" />);
expect(screen.getByRole('heading', { name: 'Notes' }).parentElement?.querySelectorAll('span')).toHaveLength(0); expect(screen.getByRole('heading', { name: 'Notes' }).parentElement?.querySelectorAll('span.rounded-full')).toHaveLength(0);
}); });
it('FE-COLLAB-PANELHEAD-003: its actions sit on the right and work', async () => { it('FE-COLLAB-PANELHEAD-003: its actions sit on the right and work', async () => {
@@ -3,11 +3,13 @@ import type { LucideIcon } from 'lucide-react'
import { NEUTRAL_TINT, fs } from '../shared/DialogShell' import { NEUTRAL_TINT, fs } from '../shared/DialogShell'
/** A panel's add action: a soft card pill on the head band. */ /** A panel's add action: a soft card pill on the head band. */
export const HEAD_ACTION = 'inline-flex items-center gap-1 whitespace-nowrap rounded-full bg-surface-card px-2.5 py-1 font-semibold text-content-muted shadow-sm hover:text-content' const HEAD_CONTROL = 'inline-flex h-7 flex-none items-center justify-center rounded-full bg-surface-card text-content-muted shadow-sm hover:text-content'
export const HEAD_ACTION = `${HEAD_CONTROL} gap-1 whitespace-nowrap px-2.5 font-semibold`
export const HEAD_ICON_ACTION = `${HEAD_CONTROL} w-7`
/** /**
* The head band every Collab panel opens with, the same one the cards of the * The head band every Collab panel opens with, the same one the cards of the
* other trip tabs carry: its icon and name in small capitals, how many there * other trip tabs carry: its icon, name and how many there
* are, and its actions on the right. * are, and its actions on the right.
*/ */
export default function CollabPanelHead({ icon: Icon, title, count, actions }: { export default function CollabPanelHead({ icon: Icon, title, count, actions }: {
@@ -18,8 +20,10 @@ export default function CollabPanelHead({ icon: Icon, title, count, actions }: {
}) { }) {
return ( return (
<div className="flex min-h-[50px] flex-none items-center gap-2 border-b border-edge-faint px-4 py-2" style={{ background: NEUTRAL_TINT }}> <div className="flex min-h-[50px] flex-none items-center gap-2 border-b border-edge-faint px-4 py-2" style={{ background: NEUTRAL_TINT }}>
<Icon size={14} strokeWidth={2} className="flex-none text-content-faint" /> <span className="grid size-8 flex-none place-items-center rounded-[10px] bg-surface-input text-content-muted">
<h3 className="m-0 font-geist font-bold uppercase tracking-[.08em] text-content-faint" style={fs(11)}>{title}</h3> <Icon size={16} strokeWidth={1.9} aria-hidden />
</span>
<h3 className="m-0 font-semibold text-content" style={fs(14, 'body')}>{title}</h3>
{count != null && count > 0 && ( {count != null && count > 0 && (
<span className="rounded-full bg-surface-card px-2 py-[2px] font-geist font-bold text-content-muted" style={fs(10)}>{count}</span> <span className="rounded-full bg-surface-card px-2 py-[2px] font-geist font-bold text-content-muted" style={fs(10)}>{count}</span>
)} )}
+1 -1
View File
@@ -118,7 +118,7 @@ function CreatePollModal({ onClose, onCreate, t }: CreatePollModalProps) {
)} )}
> >
<EditorField label={t('collab.polls.question')} hint={t('collab.polls.markdownHint')}> <EditorField label={t('collab.polls.question')} hint={t('collab.polls.markdownHint')}>
<textarea autoFocus rows={4} value={question} onChange={e => setQuestion(e.target.value)} placeholder={t('collab.polls.questionPlaceholder')} className={`${TEXTAREA} resize-y`} /> <textarea data-initial-focus rows={4} value={question} onChange={e => setQuestion(e.target.value)} placeholder={t('collab.polls.questionPlaceholder')} className={`${TEXTAREA} resize-y`} />
</EditorField> </EditorField>
<EditorField label={t('collab.polls.options')}> <EditorField label={t('collab.polls.options')}>
@@ -51,6 +51,9 @@ export function useCollabChatData({
}: CollabChatDataOptions) { }: CollabChatDataOptions) {
const [messages, setMessages] = useState<ChatMessage[]>([]); const [messages, setMessages] = useState<ChatMessage[]>([]);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [loadError, setLoadError] = useState(false);
const [loadAttempt, setLoadAttempt] = useState(0);
const retryLoad = useCallback(() => setLoadAttempt((attempt) => attempt + 1), []);
const [hasMore, setHasMore] = useState(false); const [hasMore, setHasMore] = useState(false);
const [loadingMore, setLoadingMore] = useState(false); const [loadingMore, setLoadingMore] = useState(false);
const [text, setText] = useState(''); const [text, setText] = useState('');
@@ -96,6 +99,7 @@ export function useCollabChatData({
useEffect(() => { useEffect(() => {
let cancelled = false; let cancelled = false;
setLoading(true); setLoading(true);
setLoadError(false);
collabApi collabApi
.getMessages(tripId) .getMessages(tripId)
.then((data: MessagesResponse) => { .then((data: MessagesResponse) => {
@@ -107,12 +111,14 @@ export function useCollabChatData({
setTimeout(() => scrollToBottom(), 30); setTimeout(() => scrollToBottom(), 30);
}) })
.catch(() => { .catch(() => {
if (!cancelled) setLoading(false); if (cancelled) return;
setLoadError(true);
setLoading(false);
}); });
return () => { return () => {
cancelled = true; cancelled = true;
}; };
}, [tripId, scrollToBottom]); }, [tripId, loadAttempt, scrollToBottom]);
useEffect(() => { useEffect(() => {
const handler = (event: Record<string, unknown>) => { const handler = (event: Record<string, unknown>) => {
@@ -259,6 +265,8 @@ export function useCollabChatData({
messages, messages,
setMessages, setMessages,
loading, loading,
loadError,
retryLoad,
setLoading, setLoading,
hasMore, hasMore,
setHasMore, setHasMore,
@@ -0,0 +1,126 @@
import type { CollabLink } from '@trek/shared';
import { useEffect, useRef, useState } from 'react';
import { useTranslation } from '../../i18n';
import { collabLinkRepo, type LinkFields } from '../../repo/collabLinkRepo';
import { offlineOr } from '../../utils/needsConnection';
import { useToast } from '../shared/Toast';
type LinksState = { tripId: number; links: CollabLink[]; status: 'loading' | 'ready' | 'error' };
const EMPTY_LINKS: CollabLink[] = [];
export function collabLinkHost(url: string): string {
try {
return new URL(url).hostname.replace(/^www\./, '');
} catch {
return url;
}
}
function insertLink(links: CollabLink[], link: CollabLink): CollabLink[] {
return links.some((row) => row.id === link.id) ? links : [link, ...links];
}
function updateLink(links: CollabLink[], link: CollabLink): CollabLink[] {
return links
.map((row) => (row.id === link.id ? { ...row, ...link } : row))
.sort((a, b) => Number(b.pinned) - Number(a.pinned));
}
export function useCollabLinks(tripId: number) {
const { t } = useTranslation();
const toast = useToast();
const [state, setState] = useState<LinksState>({ tripId, links: EMPTY_LINKS, status: 'loading' });
const [attempt, setAttempt] = useState(0);
const reportLoadError = useRef(() => toast.error(t('common.error')));
reportLoadError.current = () => toast.error(t('common.error'));
useEffect(() => {
let cancelled = false;
const changes: Array<(links: CollabLink[]) => CollabLink[]> = [];
let reading = true;
setState((current) => ({
tripId,
links: current.tripId === tripId ? current.links : EMPTY_LINKS,
status: 'loading',
}));
const handler = (msg: { type?: string; tripId?: number | string; link?: CollabLink; linkId?: number }) => {
if (String(msg.tripId) !== String(tripId)) return;
const { link, linkId } = msg;
const change =
msg.type === 'collab:link:created' && link
? (links: CollabLink[]) => insertLink(links, link)
: msg.type === 'collab:link:updated' && link
? (links: CollabLink[]) => updateLink(links, link)
: msg.type === 'collab:link:deleted' && linkId
? (links: CollabLink[]) => links.filter((row) => row.id !== linkId)
: null;
if (!change) return;
if (reading) changes.push(change);
setState((current) => (current.tripId === tripId ? { ...current, links: change(current.links) } : current));
};
const unsubscribe = collabLinkRepo.subscribe(handler);
void collabLinkRepo.list(tripId).then(
(data) => {
if (cancelled) return;
reading = false;
const links = changes.reduce((rows, change) => change(rows), data.links || []);
setState({ tripId, links, status: 'ready' });
},
() => {
if (cancelled) return;
reading = false;
setState((current) => ({ ...current, status: 'error' }));
reportLoadError.current();
}
);
return () => {
cancelled = true;
unsubscribe();
};
}, [tripId, attempt]);
const changeLinks = (update: (links: CollabLink[]) => CollabLink[]) =>
setState((current) => (current.tripId === tripId ? { ...current, links: update(current.links) } : current));
const reportWriteError = () => toast.error(offlineOr(t, t('common.error')));
const save = async (data: LinkFields, id?: number) => {
try {
const { link } =
id == null ? await collabLinkRepo.create(tripId, data) : await collabLinkRepo.update(tripId, id, data);
changeLinks((links) => (id == null ? insertLink(links, link) : updateLink(links, link)));
} catch (error) {
reportWriteError();
throw error;
}
};
const toggle = async (link: CollabLink) => {
try {
const { link: saved } = await collabLinkRepo.update(tripId, link.id, { pinned: !link.pinned });
changeLinks((links) => updateLink(links, saved));
} catch {
reportWriteError();
}
};
const remove = async (id: number) => {
try {
await collabLinkRepo.remove(tripId, id);
changeLinks((links) => links.filter((link) => link.id !== id));
} catch {
reportWriteError();
}
};
return {
links: state.tripId === tripId ? state.links : EMPTY_LINKS,
status: state.tripId === tripId ? state.status : 'loading',
retry: () => setAttempt((value) => value + 1),
save,
toggle,
remove,
};
}
@@ -2,7 +2,7 @@ import React, { useId, useRef } from 'react'
import Markdown from 'react-markdown' import Markdown from 'react-markdown'
import remarkGfm from 'remark-gfm' import remarkGfm from 'remark-gfm'
import remarkBreaks from 'remark-breaks' import remarkBreaks from 'remark-breaks'
import { Bookmark, Search, MapPin, MapPinned, Loader2, Trash2, Check, X } from 'lucide-react' import { Text, Link, Bookmark, Search, MapPin, MapPinned, Loader2, Trash2, Check, X } from 'lucide-react'
import { DialogButton, DialogFooter, DialogHeader, DialogSection, DialogShell, DialogTile, FooterSpacer, NEUTRAL_TINT, fs } from '../shared/DialogShell' import { DialogButton, DialogFooter, DialogHeader, DialogSection, DialogShell, DialogTile, FooterSpacer, NEUTRAL_TINT, fs } from '../shared/DialogShell'
import { AddRowButton, EditorField, INPUT, Segmented, TEXTAREA } from '../shared/dialogParts' import { AddRowButton, EditorField, INPUT, Segmented, TEXTAREA } from '../shared/dialogParts'
import NoteFormatToolbar from '../shared/NoteFormatToolbar' import NoteFormatToolbar from '../shared/NoteFormatToolbar'
@@ -102,7 +102,6 @@ export default function AddPlaceToCollectionModal({ isOpen, collectionId, collec
<div className="relative"> <div className="relative">
<Search size={14} className="pointer-events-none absolute start-3 top-1/2 -translate-y-1/2 text-content-faint" aria-hidden="true" /> <Search size={14} className="pointer-events-none absolute start-3 top-1/2 -translate-y-1/2 text-content-faint" aria-hidden="true" />
<input <input
autoFocus
data-initial-focus data-initial-focus
ref={searchRef} ref={searchRef}
type="text" type="text"
@@ -177,7 +176,7 @@ export default function AddPlaceToCollectionModal({ isOpen, collectionId, collec
/> />
</EditorField> </EditorField>
<DialogSection <DialogSection icon={Text}
label={<label htmlFor={`${fieldId}-description`}>{t('collections.description')}</label>} label={<label htmlFor={`${fieldId}-description`}>{t('collections.description')}</label>}
action={<NoteFormatToolbar textareaRef={descRef} onChange={setDescription} compact customTooltips />} action={<NoteFormatToolbar textareaRef={descRef} onChange={setDescription} compact customTooltips />}
> >
@@ -197,7 +196,7 @@ export default function AddPlaceToCollectionModal({ isOpen, collectionId, collec
)} )}
</DialogSection> </DialogSection>
<DialogSection label={t('collections.links')}> <DialogSection icon={Link} label={t('collections.links')}>
<div className="flex flex-col gap-2"> <div className="flex flex-col gap-2">
{links.map((l, i) => ( {links.map((l, i) => (
<div key={i} className="flex items-center gap-2"> <div key={i} className="flex items-center gap-2">
@@ -136,6 +136,7 @@ export default function CollectionExportMenu({ onExport, exporting, t }: Collect
ref={menuRef} ref={menuRef}
id={menuId} id={menuId}
role="menu" role="menu"
tabIndex={-1}
aria-label={t('collections.file.exportTitle')} aria-label={t('collections.file.exportTitle')}
onKeyDown={onMenuKeyDown} onKeyDown={onMenuKeyDown}
className="trek-popover-enter fixed z-[var(--z-toast)] p-1.5 rounded-xl border border-edge bg-surface-card shadow-dropdown" className="trek-popover-enter fixed z-[var(--z-toast)] p-1.5 rounded-xl border border-edge bg-surface-card shadow-dropdown"
@@ -228,7 +228,7 @@ export default function CollectionPicker({ bias, onSelect, t }: CollectionPicker
// of different widths flanking one form read as a mistake rather than a // of different widths flanking one form read as a mistake rather than a
// hierarchy, and neither of them is the more important one. // hierarchy, and neither of them is the more important one.
<aside className={`${SIDE_COLUMN} sm:w-80`}> <aside className={`${SIDE_COLUMN} sm:w-80`}>
<ColumnHead icon={<Bookmark size={13} strokeWidth={2.2} />}>{t('collections.picker.title')}</ColumnHead> <ColumnHead icon={<Bookmark size={16} strokeWidth={2} />}>{t('collections.picker.title')}</ColumnHead>
<div className="flex flex-none flex-col gap-2 px-3 pb-2.5"> <div className="flex flex-none flex-col gap-2 px-3 pb-2.5">
<EditorField label={t('common.search')} htmlFor={searchId}> <EditorField label={t('common.search')} htmlFor={searchId}>
<div className="relative"> <div className="relative">
@@ -25,6 +25,7 @@ import { placesPath } from '../../utils/placesRoutes';
import MarkdownToolbar from '../Journey/MarkdownToolbar'; import MarkdownToolbar from '../Journey/MarkdownToolbar';
import { getNavigationTargets, navigationTargetLabel, openNavigationTarget } from '../Planner/placeNavigation'; import { getNavigationTargets, navigationTargetLabel, openNavigationTarget } from '../Planner/placeNavigation';
import { getCategoryIcon } from '../shared/categoryIcons'; import { getCategoryIcon } from '../shared/categoryIcons';
import { focusRevealedEditor } from '../shared/dialogFocus';
import { DialogShell } from '../shared/DialogShell'; import { DialogShell } from '../shared/DialogShell';
import { markdownLinkComponents } from '../shared/markdownLink'; import { markdownLinkComponents } from '../shared/markdownLink';
import { NavigationMenu } from '../shared/NavigationMenu'; import { NavigationMenu } from '../shared/NavigationMenu';
@@ -202,7 +203,7 @@ function Cover({
value={form.name} value={form.name}
onChange={(e) => form.setName(e.target.value)} onChange={(e) => form.setName(e.target.value)}
className="col-detail-name-input min-w-0 flex-1" className="col-detail-name-input min-w-0 flex-1"
autoFocus ref={focusRevealedEditor}
aria-label={t('common.name')} aria-label={t('common.name')}
/> />
</div> </div>
@@ -55,7 +55,7 @@ export default function CopyToTripModal({ isOpen, onClose, placeIds, onCopy, car
<div className="relative"> <div className="relative">
<Search size={14} className="pointer-events-none absolute start-3 top-1/2 -translate-y-1/2 text-content-faint" aria-hidden="true" /> <Search size={14} className="pointer-events-none absolute start-3 top-1/2 -translate-y-1/2 text-content-faint" aria-hidden="true" />
<input <input
autoFocus data-initial-focus
value={search} value={search}
onChange={e => setSearch(e.target.value)} onChange={e => setSearch(e.target.value)}
placeholder={t('collections.copyToTripSearch')} placeholder={t('collections.copyToTripSearch')}
@@ -122,7 +122,7 @@ describe('DuplicatePairCard', () => {
const user = userEvent.setup(); const user = userEvent.setup();
const { props, container } = setup({ variant: 'sheet' }); const { props, container } = setup({ variant: 'sheet' });
const card = within(container).getByRole('article'); const card = within(container).getByRole('article');
expect(card.className).toContain('bg-m-sheet'); expect(card).toHaveClass('bg-m-ic');
expect(screen.getByText('The same name at the same spot')).toBeInTheDocument(); expect(screen.getByText('The same name at the same spot')).toBeInTheDocument();
await user.click(screen.getAllByRole('button', { name: /Keep this one/ })[1]); await user.click(screen.getAllByRole('button', { name: /Keep this one/ })[1]);
expect(props.onMerge).toHaveBeenCalledWith('b'); expect(props.onMerge).toHaveBeenCalledWith('b');
@@ -8,7 +8,7 @@ const LOOK = {
dialog: { dialog: {
card: 'rounded-xl border border-edge-faint bg-surface-secondary p-3', card: 'rounded-xl border border-edge-faint bg-surface-secondary p-3',
side: 'flex min-w-0 flex-col gap-1.5 rounded-lg bg-surface-card p-2.5', side: 'flex min-w-0 flex-col gap-1.5 rounded-lg bg-surface-card p-2.5',
name: 'text-body font-semibold text-content', name: 'truncate text-body font-semibold text-content',
sub: 'text-caption text-content-faint', sub: 'text-caption text-content-faint',
diff: 'rounded bg-warning-soft px-1 text-content', diff: 'rounded bg-warning-soft px-1 text-content',
chip: 'inline-flex max-w-full items-center gap-1 rounded-full border border-edge-faint px-2 py-0.5 text-caption text-content-muted', chip: 'inline-flex max-w-full items-center gap-1 rounded-full border border-edge-faint px-2 py-0.5 text-caption text-content-muted',
@@ -18,16 +18,16 @@ const LOOK = {
link: 'text-caption font-semibold text-content-muted hover:text-content disabled:opacity-50', link: 'text-caption font-semibold text-content-muted hover:text-content disabled:opacity-50',
}, },
sheet: { sheet: {
card: 'rounded-2xl border border-m-rowbr bg-m-sheet p-3', card: 'rounded-[14px] bg-m-ic p-3',
side: 'flex min-w-0 flex-col gap-1.5 rounded-xl bg-m-sheetop p-2.5', side: 'flex min-w-0 flex-col gap-2 rounded-xl border border-m-rowbr bg-m-sheetop p-2.5',
name: 'text-body font-bold text-m-ink', name: 'line-clamp-2 break-words text-control font-semibold leading-tight text-m-ink',
sub: 'text-caption text-m-muted', sub: 'text-caption text-m-muted',
diff: 'rounded bg-warning-soft px-1 text-m-ink', diff: 'rounded bg-warning-soft px-1 text-m-ink',
chip: 'inline-flex max-w-full items-center gap-1 rounded-full border border-m-rowbr bg-m-ic px-2 py-0.5 text-caption text-m-muted', chip: 'inline-flex max-w-full items-center gap-1 rounded-full border border-m-rowbr bg-m-ic px-2 py-0.5 text-caption text-m-muted',
keep: 'inline-flex items-center justify-center gap-1.5 rounded-full border border-m-rowbr bg-m-ic px-2.5 py-[7px] text-caption font-semibold text-m-ink disabled:opacity-50', keep: 'inline-flex min-h-11 items-center justify-center gap-1.5 rounded-xl bg-m-ic px-2 py-2 text-start text-caption font-semibold leading-tight text-m-ink disabled:opacity-50',
reason: 'text-caption font-semibold text-m-muted', reason: 'text-caption font-semibold text-m-muted',
note: 'text-caption text-m-faint', note: 'text-caption text-m-faint',
link: 'text-caption font-semibold text-m-muted disabled:opacity-50', link: 'min-h-11 rounded-xl px-2 text-start text-control font-medium text-m-muted active:bg-m-sheetop disabled:opacity-50',
}, },
} as const; } as const;
@@ -54,7 +54,7 @@ function Side({
differing.includes(field) ? <span className={look.diff}>{text}</span> : text; differing.includes(field) ? <span className={look.diff}>{text}</span> : text;
return ( return (
<div className={look.side}> <div className={look.side}>
<span dir="auto" className={`${look.name} truncate`}> <span dir="auto" className={look.name}>
{mark('name', side.name)} {mark('name', side.name)}
</span> </span>
{(side.address || differing.includes('address')) && ( {(side.address || differing.includes('address')) && (
@@ -77,7 +77,11 @@ function Side({
</span> </span>
{canMerge && ( {canMerge && (
<button type="button" onClick={onKeep} disabled={busy} className={`mt-auto ${look.keep}`}> <button type="button" onClick={onKeep} disabled={busy} className={`mt-auto ${look.keep}`}>
{busy ? <Loader2 size={12} className="animate-spin" /> : <Check size={12} />}{' '} {busy ? (
<Loader2 size={12} className="flex-none animate-spin" aria-hidden />
) : (
<Check size={12} className="flex-none" aria-hidden />
)}
{t('collections.duplicates.keepThis')} {t('collections.duplicates.keepThis')}
</button> </button>
)} )}

Some files were not shown because too many files have changed in this diff Show More