mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-04 01:44:13 +00:00
Compare commits
54 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 995e9c435f | |||
| 259d23f971 | |||
| 7196ad30da | |||
| 3945037ff3 | |||
| f10435b42b | |||
| c6a50695d8 | |||
| ea1a2527ab | |||
| 4b7c96f4c5 | |||
| 8ae919c650 | |||
| 75020dd2df | |||
| ca201ab4d0 | |||
| 0f683b0dee | |||
| e54f954f31 | |||
| a2cf911ce1 | |||
| 7a66a54e66 | |||
| bf6a66d52c | |||
| 748434fc47 | |||
| 618f070675 | |||
| 260e1ef023 | |||
| 262741bf89 | |||
| 3438a2aa48 | |||
| dacf19b4d5 | |||
| 103631d5fc | |||
| 00fcb69423 | |||
| dbcdecb6a7 | |||
| 10fecf4e80 | |||
| 12483f618f | |||
| 17c4d69e40 | |||
| d6184559e9 | |||
| 3089aee593 | |||
| 24ddc3e4b0 | |||
| a4cb6c69d8 | |||
| 6e224cb7a4 | |||
| 56b4568a16 | |||
| 756ef14b97 | |||
| e539860530 | |||
| 0d6a432967 | |||
| 89035059ec | |||
| 4ad926aafc | |||
| 60a30afb81 | |||
| b77c246df4 | |||
| 7f4ece2e6f | |||
| a14b6a61e6 | |||
| 871135edeb | |||
| c22c464e68 | |||
| 3c2dc51439 | |||
| 28eea68559 | |||
| 1ff8a814ae | |||
| 0d521f0930 | |||
| 7fc011408a | |||
| 8f20f9f7ea | |||
| 67b65a7647 | |||
| 82b2a530f3 | |||
| 76a3983972 |
@@ -438,10 +438,10 @@ jobs:
|
||||
- name: Lint
|
||||
# Errors fail, and the warnings per rule may not pass
|
||||
# scripts/eslint-baseline.json (src, tests and eslint-disable'd
|
||||
# messages counted apart). Type-aware rules build the src + tests
|
||||
# program, which outgrows Node's default ~4 GB heap on the runner.
|
||||
# messages counted apart). The typed src and test programs can exhaust
|
||||
# an 8 GiB heap. Leave headroom within the runner's 16 GB of RAM.
|
||||
env:
|
||||
NODE_OPTIONS: --max-old-space-size=8192
|
||||
NODE_OPTIONS: --max-old-space-size=10240
|
||||
TREK_LINT_BASE: refs/remotes/lint-base
|
||||
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
|
||||
# whose warning count rises above scripts/eslint-baseline.json.
|
||||
# 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:
|
||||
NODE_OPTIONS: --max-old-space-size=8192
|
||||
TREK_LINT_BASE: refs/remotes/lint-base
|
||||
|
||||
@@ -11,3 +11,4 @@ e2e/help/media.env
|
||||
# The native apps' address screen (npm run build:native), copied into
|
||||
# android/ and ios/ by `cap sync`
|
||||
native-dist/
|
||||
native-sandbox-dist/
|
||||
|
||||
@@ -102,21 +102,61 @@ object TrekBilling {
|
||||
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) {
|
||||
val ids = call.getArray("ids")?.toList<String>().orEmpty()
|
||||
ready(context) { ok ->
|
||||
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 ->
|
||||
val list = JSArray()
|
||||
for (product in found) displayPrice(product)?.let { list.put(JSObject().put("id", product.productId).put("displayPrice", it)) }
|
||||
call.resolve(result.put("products", list))
|
||||
val candidates = found.filter { trialOffer(it) != null }.map { it.productId }.toSet()
|
||||
if (candidates.isEmpty()) {
|
||||
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) {
|
||||
val id = call.getString("productId") ?: return call.reject("productId is required")
|
||||
val trialRenewalPrice = call.getString("trialRenewalPrice")
|
||||
ready(activity) { ok ->
|
||||
if (!ok) return@ready call.resolve(JSObject().put("kind", "failed"))
|
||||
// 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 ->
|
||||
val held = if (result.responseCode == BillingClient.BillingResponseCode.OK) newest(purchases, PREFIX) else null
|
||||
when {
|
||||
held == null -> launchPurchase(activity, call, id)
|
||||
held.isAcknowledged -> call.resolve(JSObject().put("kind", "subscribed"))
|
||||
else -> call.resolve(receipt(held).put("kind", "bought"))
|
||||
held?.isAcknowledged == true -> call.resolve(JSObject().put("kind", "subscribed"))
|
||||
held != null -> 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 ->
|
||||
val product = found.firstOrNull()
|
||||
val offer = product?.let(::baseOffer)
|
||||
if (product == null || offer == null) return@details call.resolve(JSObject().put("kind", "failed"))
|
||||
val offer = product?.let { listed ->
|
||||
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 = call
|
||||
pendingProduct = id
|
||||
@@ -275,6 +324,7 @@ object TrekBilling {
|
||||
newest(purchases.filter { !it.isAcknowledged }, prefix)
|
||||
|
||||
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
|
||||
.filter { p -> p.purchaseState == Purchase.PurchaseState.PURCHASED && p.products.any { it.startsWith(prefix) } }
|
||||
|
||||
@@ -688,12 +688,38 @@ extension TrekShellPlugin {
|
||||
let ids = call.getArray("ids", String.self) ?? []
|
||||
Task {
|
||||
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])
|
||||
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
|
||||
@@ -726,6 +752,7 @@ extension TrekShellPlugin {
|
||||
call.reject("productId is required")
|
||||
return
|
||||
}
|
||||
let trialRenewalPrice = call.getString("trialRenewalPrice")
|
||||
Task {
|
||||
// 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
|
||||
@@ -740,9 +767,18 @@ extension TrekShellPlugin {
|
||||
}
|
||||
do {
|
||||
guard let product = try await Product.products(for: [id]).first else {
|
||||
call.resolve(["kind": "failed"])
|
||||
call.resolve(["kind": trialRenewalPrice == nil ? "failed" : "offer-changed"])
|
||||
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() {
|
||||
case .success(let verification):
|
||||
guard case .verified(let transaction) = verification else {
|
||||
|
||||
+212
-142
@@ -7,14 +7,21 @@ import { PASSWORD_MIN_LENGTH, passwordProblem, passwordRuleStates } from '../../
|
||||
import logoWhite from '../public/logo-light.svg'; // #fff wordmark, for the landscape
|
||||
import { pageUnderStatusBar } from '../src/native/appBoot';
|
||||
import { AUTH_GATE_NAMES, canSignInInApp, type AuthGate } from '../src/native/authGate';
|
||||
import { isNewCloudPlan, opensSoon, planForUnclaimedPurchase, refundedBeforeOpening } from '../src/native/cloudOrders';
|
||||
import { fakeIapClient, getIapClient, productIdFor, type Purchase } from '../src/native/iap';
|
||||
import {
|
||||
isNewCloudPlan,
|
||||
matchesPurchaseAgreement,
|
||||
opensSoon,
|
||||
planForUnclaimedPurchase,
|
||||
refundedBeforeOpening,
|
||||
type CloudPurchaseAgreement,
|
||||
} from '../src/native/cloudOrders';
|
||||
import { fakeIapClient, getIapClient, productIdFor, type IapProduct, type Purchase } from '../src/native/iap';
|
||||
import {
|
||||
APP_STORE_SUBSCRIPTIONS_URL,
|
||||
AUTH_PROXY_DOCS_URL,
|
||||
CLIENT_CERT_DOCS_URL,
|
||||
CLOUD_TERMS_URL,
|
||||
CLOUD_URL,
|
||||
CLOUD_URL as PRODUCTION_CLOUD_URL,
|
||||
PLAY_SUBSCRIPTIONS_URL,
|
||||
PRIVACY_URL,
|
||||
STORE_TERMS_URL,
|
||||
@@ -50,6 +57,13 @@ document.documentElement.dir = directionOf(locale);
|
||||
|
||||
const root = document.getElementById('shell')!;
|
||||
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();
|
||||
/**
|
||||
@@ -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 {
|
||||
switch (reason) {
|
||||
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',
|
||||
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',
|
||||
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:
|
||||
'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',
|
||||
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',
|
||||
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',
|
||||
@@ -315,7 +352,8 @@ function showWelcome(opts: { back?: boolean } = {}): void {
|
||||
const perk = (glyph: string, title: string, sub: string) =>
|
||||
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', () => {
|
||||
void tap();
|
||||
showPlans();
|
||||
@@ -326,7 +364,7 @@ function showWelcome(opts: { back?: boolean } = {}): void {
|
||||
showConnect();
|
||||
});
|
||||
|
||||
show(
|
||||
const screen = show(
|
||||
'welcome',
|
||||
WELCOME_CAMERA,
|
||||
{
|
||||
@@ -351,6 +389,9 @@ function showWelcome(opts: { back?: boolean } = {}): void {
|
||||
},
|
||||
opts
|
||||
);
|
||||
void availableWelcomeTrial().then((available) => {
|
||||
if (screen.node.isConnected) trial.hidden = !available;
|
||||
});
|
||||
}
|
||||
|
||||
// ── Connect (address) ───────────────────────────────────────────────────────
|
||||
@@ -664,7 +705,7 @@ interface CloudPlan {
|
||||
yearlyCents?: number;
|
||||
currency?: 'EUR' | 'USD';
|
||||
aiDocuments: number;
|
||||
aiDocumentLimit?: 0 | null;
|
||||
aiDocumentLimit?: number | null;
|
||||
aiAssistant?: 'planned' | 'included' | 'unavailable';
|
||||
bookingMailImport?: boolean;
|
||||
storageGb: number;
|
||||
@@ -681,24 +722,24 @@ const SAMPLE_PLANS: CloudPlan[] = [
|
||||
{
|
||||
id: 'start',
|
||||
name: 'Start',
|
||||
monthlyCents: 499,
|
||||
monthlyCents: 599,
|
||||
yearlyCents: 4899,
|
||||
currency: 'USD',
|
||||
aiDocuments: 0,
|
||||
aiDocumentLimit: 0,
|
||||
storageGb: 200,
|
||||
storageGb: 50,
|
||||
},
|
||||
{
|
||||
id: 'plus',
|
||||
name: 'Plus',
|
||||
monthlyCents: 999,
|
||||
monthlyCents: 1199,
|
||||
yearlyCents: 9900,
|
||||
currency: 'USD',
|
||||
aiDocuments: 100,
|
||||
aiDocumentLimit: null,
|
||||
aiAssistant: 'planned',
|
||||
aiAssistant: 'included',
|
||||
bookingMailImport: true,
|
||||
storageGb: 200,
|
||||
storageGb: 50,
|
||||
},
|
||||
];
|
||||
|
||||
@@ -706,15 +747,18 @@ interface CloudPlans {
|
||||
plans: CloudPlan[];
|
||||
/** Orders are closed: only a test build may buy, and the store charges it nothing. */
|
||||
closed: boolean;
|
||||
/** Only the live catalogue's explicit opening permits customer trial advertising. */
|
||||
open?: boolean;
|
||||
}
|
||||
|
||||
async function fetchPlans(): Promise<CloudPlans | null> {
|
||||
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 body = (data ?? {}) as { plans?: CloudPlan[]; ordering?: string };
|
||||
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 {
|
||||
// Fall through to the preview fallback.
|
||||
}
|
||||
@@ -730,22 +774,44 @@ async function fetchPlans(): Promise<CloudPlans | null> {
|
||||
*/
|
||||
interface Offer {
|
||||
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. */
|
||||
opensSoon: boolean;
|
||||
}
|
||||
|
||||
function offerFor(offer: Offer, plan: CloudPlan, interval: 'month' | 'year'): { label: string; buyable: boolean } {
|
||||
if (!offer.canBuy) return { label: '', buyable: false };
|
||||
function offerFor(
|
||||
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) {
|
||||
const label = offer.storePrices?.get(productIdFor(plan.id, interval)) ?? '';
|
||||
return { label, buyable: label !== '' };
|
||||
const product = offer.storeProducts?.get(productIdFor(plan.id, interval));
|
||||
const label = product?.displayPrice ?? '';
|
||||
return {
|
||||
label,
|
||||
buyable: label !== '',
|
||||
freeTrial: label !== '' && offer.canShowTrial && product?.freeTrial === true,
|
||||
};
|
||||
}
|
||||
const cents = interval === 'year' ? plan.yearlyCents : plan.monthlyCents;
|
||||
const currency = plan.currency ?? 'EUR';
|
||||
const label =
|
||||
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> {
|
||||
@@ -755,39 +821,61 @@ async function loadOffer(list: CloudPlans): Promise<Offer> {
|
||||
const sandbox = list.closed && !onPlay ? await iap.isSandbox().catch(() => false) : false;
|
||||
const soon = opensSoon({ available, closed: list.closed, sandbox, onPlay });
|
||||
const canBuy = available && !soon;
|
||||
if (!canBuy || iap === fakeIapClient) return { canBuy, storePrices: null, opensSoon: soon };
|
||||
const ids = list.plans.flatMap((p) => [productIdFor(p.id, 'month'), productIdFor(p.id, 'year')]);
|
||||
return { canBuy, storePrices: await iap.prices(ids), opensSoon: soon };
|
||||
}
|
||||
|
||||
/** The plan the picker starts on and marks: the smallest one with AI documents, the one most trips want. */
|
||||
function recommendedPlan(plans: CloudPlan[]): CloudPlan | undefined {
|
||||
return plans.find((p) => p.aiDocuments > 0) ?? plans[0];
|
||||
}
|
||||
|
||||
/** The kind of trip each plan is for: a weekend away, a round trip, a long journey, the whole world. */
|
||||
const TRIPS: Record<string, { titleKey: string; textKey: string }> = {
|
||||
start: { titleKey: 'native.trip.start.title', textKey: 'native.trip.start.text' },
|
||||
basis: { titleKey: 'native.trip.basis.title', textKey: 'native.trip.basis.text' },
|
||||
plus: { titleKey: 'native.trip.plus.title', textKey: 'native.trip.plus.text' },
|
||||
pro: { titleKey: 'native.trip.pro.title', textKey: 'native.trip.pro.text' },
|
||||
if (!canBuy || iap === fakeIapClient) return { canBuy, storeProducts: null, canShowTrial: false, opensSoon: soon };
|
||||
return {
|
||||
canBuy,
|
||||
storeProducts: await iap.products(storeIds(list.plans)),
|
||||
canShowTrial: list.open === true,
|
||||
opensSoon: soon,
|
||||
};
|
||||
/** A plan's trip, its title and one line; a plan the app does not know keeps its own name. */
|
||||
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 planFeatures(plan: CloudPlan): HTMLLIElement[] {
|
||||
const row = (label: string, value: string, glyph: string, unavailable = false) =>
|
||||
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
|
||||
);
|
||||
|
||||
const storage = plan.storageGb >= 1000 ? `${count(plan.storageGb / 1000)} TB` : `${count(plan.storageGb)} GB`;
|
||||
const aiDocuments = plan.aiDocumentLimit === null || (plan.aiDocumentLimit ?? plan.aiDocuments) > 0;
|
||||
return [
|
||||
row(t('native.plans.storage'), storage, I.image),
|
||||
feature(t('native.plans.aiLabel'), aiDocuments),
|
||||
feature(t('native.plans.assistant'), plan.aiAssistant === 'included'),
|
||||
feature(t('native.plans.mailImport'), plan.bookingMailImport === true),
|
||||
row(t('native.plans.unlimitedSub'), t('native.plans.unlimited'), I.people),
|
||||
];
|
||||
}
|
||||
|
||||
function per(interval: 'month' | 'year'): string {
|
||||
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. */
|
||||
let resumeRestore: (() => void) | null = null;
|
||||
let watchingTransactions = false;
|
||||
/** Where the camera stood on the plan chosen last, for the screens that follow it. */
|
||||
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 chosenInterval: 'month' | 'year' = 'month';
|
||||
|
||||
@@ -852,14 +940,11 @@ function restoreButton(plans: CloudPlan[]): HTMLButtonElement {
|
||||
function showPlans(opts: { back?: boolean } = {}): void {
|
||||
let interval: 'month' | 'year' = chosenInterval;
|
||||
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;
|
||||
|
||||
const tiers = el('div', { className: 'tiers', role: 'radiogroup', hidden: true });
|
||||
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 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 price = el('div', { className: 'price' }, priceValue, pricePer);
|
||||
const equals = el('div', { className: 'equals' });
|
||||
const pricebox = el('div', { className: 'pricebox' }, cycle, price, equals);
|
||||
const specs = el('div', { className: 'specs' });
|
||||
const trial = el('p', { className: 'trial-price', hidden: true });
|
||||
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 legal = el('p', { className: 'legal' });
|
||||
|
||||
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 dock = el('div', { className: 'dock' }, choose);
|
||||
|
||||
const screen = show(
|
||||
'plain',
|
||||
chosenCamera,
|
||||
opts.back ? chosenCamera : cameraForPlan(1),
|
||||
{
|
||||
back: () => showWelcome({ back: true }),
|
||||
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'));
|
||||
cycle.dataset.year = String(interval === 'year');
|
||||
|
||||
const { title: tripTitle, text: tripText } = tripOf(plan);
|
||||
const recommended = recommendedPlan(plans)?.id === plan.id;
|
||||
title.replaceChildren(
|
||||
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;
|
||||
const { label, buyable, freeTrial } = interval === 'month' ? month : year;
|
||||
// An introductory offer states the free period and renewal price together.
|
||||
price.hidden = !label || freeTrial;
|
||||
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.
|
||||
pricebox.hidden = !month.label && !year.label;
|
||||
@@ -955,59 +1033,23 @@ function showPlans(opts: { back?: boolean } = {}): void {
|
||||
yearBtn.disabled = !year.label;
|
||||
const yearAmount = amountIn(year.label);
|
||||
equals.textContent =
|
||||
!label || !year.label
|
||||
!label || !year.label || freeTrial
|
||||
? ''
|
||||
: interval === 'month'
|
||||
? t('native.plans.yearlyIs', { price: year.label })
|
||||
: yearAmount
|
||||
? 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`;
|
||||
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'))
|
||||
)
|
||||
);
|
||||
specs.replaceChildren(...planFeatures(plan));
|
||||
|
||||
choose.hidden = !buyable;
|
||||
choose.textContent = t('native.plans.choose', { trip: tripTitle });
|
||||
choose.textContent = t('native.plans.choose', { plan: plan.name });
|
||||
chosenCamera = cameraForPlan(index);
|
||||
chosenPlanId = plan.id;
|
||||
chosenInterval = interval;
|
||||
@@ -1042,7 +1084,7 @@ function showPlans(opts: { back?: boolean } = {}): void {
|
||||
showSubscribed();
|
||||
return;
|
||||
}
|
||||
showClaim(plan, selectedInterval, price.label);
|
||||
showClaim(plan, selectedInterval, price.label, { freeTrial: price.freeTrial });
|
||||
});
|
||||
|
||||
const load = async () => {
|
||||
@@ -1060,7 +1102,9 @@ function showPlans(opts: { back?: boolean } = {}): void {
|
||||
}
|
||||
offer = await loadOffer(list);
|
||||
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(
|
||||
...plans.map((p) => {
|
||||
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 {
|
||||
foot.replaceChildren(
|
||||
el('p', { className: 'legal' }, t(onPlay ? 'native.plans.legalAndroid' : 'native.plans.legal')),
|
||||
legal,
|
||||
el(
|
||||
'div',
|
||||
{ className: 'legal-links' },
|
||||
@@ -1105,7 +1149,7 @@ type SlugStatus = 'available' | 'taken' | 'invalid' | 'reserved' | 'error';
|
||||
|
||||
async function slugStatus(slug: string): Promise<SlugStatus> {
|
||||
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 status = (data as { status?: string })?.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
|
||||
* app shows the server's text, never its own, and sends back the version it showed.
|
||||
*/
|
||||
interface DeviationsConsent {
|
||||
version: string;
|
||||
text: string;
|
||||
}
|
||||
async function fetchConsent(): Promise<DeviationsConsent | null> {
|
||||
async function fetchConsent(): Promise<CloudPurchaseAgreement | null> {
|
||||
try {
|
||||
const res = await CapacitorHttp.get({
|
||||
url: `${CLOUD_URL}/api/iap/consent`,
|
||||
params: { lang: locale === 'de' ? 'de' : 'en' },
|
||||
connectTimeout: PROBE_TIMEOUT_MS,
|
||||
readTimeout: PROBE_TIMEOUT_MS,
|
||||
...cloudHttpOptions,
|
||||
});
|
||||
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 (cloudSandbox && body.iapEnvironment !== 'sandbox') return null;
|
||||
if (!body.version || !body.deviations) return null;
|
||||
return { version: body.version, text: body.deviations };
|
||||
} catch {
|
||||
@@ -1162,8 +1202,7 @@ async function redeemPurchase(
|
||||
const res = await CapacitorHttp.post({
|
||||
url: `${CLOUD_URL}/api/iap/redeem`,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
connectTimeout: PROBE_TIMEOUT_MS,
|
||||
readTimeout: PROBE_TIMEOUT_MS,
|
||||
...cloudHttpOptions,
|
||||
// The language of the contract confirmation mail.
|
||||
data: {
|
||||
platform: purchase.platform,
|
||||
@@ -1181,6 +1220,9 @@ async function redeemPurchase(
|
||||
const data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data;
|
||||
const body = (data ?? {}) as { instanceUrl?: string; code?: string; welcome?: 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 =
|
||||
typeof body.welcome === 'string' && /^[A-Za-z0-9_-]{43}$/.test(body.welcome) ? body.welcome : undefined;
|
||||
return { ok: true, instanceUrl: body.instanceUrl, ...(welcome ? { welcome } : {}) };
|
||||
@@ -1195,7 +1237,7 @@ function showClaim(
|
||||
plan: Pick<CloudPlan, 'id' | 'name'>,
|
||||
interval: 'month' | 'year',
|
||||
priceLabel: string,
|
||||
opts: { back?: boolean; bought?: Purchase } = {}
|
||||
opts: { back?: boolean; bought?: Purchase; freeTrial?: boolean } = {}
|
||||
): void {
|
||||
/** 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;
|
||||
@@ -1279,7 +1321,7 @@ function showClaim(
|
||||
};
|
||||
|
||||
// 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 consentText = el('span', { className: 'consent-text' }, t('native.claim.consentLoading'));
|
||||
const consentField = el(
|
||||
@@ -1288,19 +1330,26 @@ function showClaim(
|
||||
consentBox,
|
||||
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.disabled = true;
|
||||
consentText.textContent = t('native.claim.consentLoading');
|
||||
consent = await fetchConsent();
|
||||
consentBox.disabled = consent === null;
|
||||
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;
|
||||
};
|
||||
void loadConsent();
|
||||
|
||||
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());
|
||||
// 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'));
|
||||
@@ -1308,19 +1357,25 @@ function showClaim(
|
||||
void tap();
|
||||
showPlans({ back: true });
|
||||
});
|
||||
const planPrice = !priceLabel
|
||||
? null
|
||||
: opts.freeTrial
|
||||
? el('small', {}, trialPrice(priceLabel, interval))
|
||||
: el('small', { dir: 'ltr' }, `${priceLabel} ${per(interval)}`);
|
||||
const planRow = el(
|
||||
'div',
|
||||
{ className: 'plan-row' },
|
||||
el(
|
||||
'span',
|
||||
{},
|
||||
el('b', {}, plan.name),
|
||||
...(priceLabel ? [el('small', { dir: 'ltr' }, `${priceLabel} ${per(interval)}`)] : [])
|
||||
),
|
||||
el('span', {}, el('b', {}, plan.name), ...(planPrice ? [planPrice] : [])),
|
||||
// A purchase already made is not a choice any more.
|
||||
...(bought ? [] : [change])
|
||||
);
|
||||
const error = notice('');
|
||||
const checkoutDock = el(
|
||||
'div',
|
||||
{ className: 'dock' },
|
||||
submit,
|
||||
el('p', { className: 'fine' }, opts.freeTrial ? trialCancellation() : t('native.claim.renews'))
|
||||
);
|
||||
const form = el(
|
||||
'form',
|
||||
{ className: 'pad form', noValidate: true },
|
||||
@@ -1347,10 +1402,7 @@ function showClaim(
|
||||
{
|
||||
back: () => showPlans({ back: true }),
|
||||
overlay: [card.node],
|
||||
content: [
|
||||
form,
|
||||
el('div', { className: 'dock' }, submit, el('p', { className: 'fine' }, t('native.claim.renews'))),
|
||||
],
|
||||
content: [form, checkoutDock],
|
||||
},
|
||||
opts
|
||||
);
|
||||
@@ -1440,7 +1492,8 @@ function showClaim(
|
||||
consentBox.focus();
|
||||
return;
|
||||
}
|
||||
const consentVersion = consent ? consent.version : null;
|
||||
const acceptedConsent = consent;
|
||||
const consentVersion = acceptedConsent?.version ?? null;
|
||||
|
||||
void tap(ImpactStyle.Medium);
|
||||
// The purchase sheet and the progress want the whole screen, not the keyboard.
|
||||
@@ -1460,7 +1513,24 @@ function showClaim(
|
||||
};
|
||||
|
||||
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') {
|
||||
restore();
|
||||
setNotice(error, t('native.claim.cancelled'));
|
||||
@@ -1650,8 +1720,8 @@ function showProvisioning(instanceUrl: string, welcome?: string): void {
|
||||
const deadline = Date.now() + 180_000;
|
||||
const poll = async (): Promise<void> => {
|
||||
if (!view.screen.node.isConnected) return;
|
||||
const result = await probeServer(instanceUrl, get);
|
||||
if (result.ok) {
|
||||
const result = await probeServer(instanceUrl, cloudGet);
|
||||
if (result.ok && (!cloudSandbox || new URL(result.url).origin === new URL(instanceUrl).origin)) {
|
||||
await ready(result.url);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -320,14 +320,14 @@ input {
|
||||
overflow: hidden;
|
||||
background: var(--sea);
|
||||
margin-bottom: -1px;
|
||||
height: min(300px, 36svh);
|
||||
height: max(calc(var(--safe-top) + 68px), min(252px, 30svh));
|
||||
}
|
||||
.hero.tall {
|
||||
height: min(320px, 38svh);
|
||||
}
|
||||
.hero.welcome {
|
||||
height: min(376px, 44.5svh);
|
||||
min-height: 250px;
|
||||
height: min(352px, 42svh);
|
||||
min-height: 236px;
|
||||
}
|
||||
.hero .scenery {
|
||||
position: absolute;
|
||||
@@ -529,7 +529,7 @@ input {
|
||||
}
|
||||
.push {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
min-height: clamp(10px, 2svh, 16px);
|
||||
}
|
||||
h1 {
|
||||
margin: 0;
|
||||
@@ -628,6 +628,39 @@ h1 {
|
||||
font: 700 17px var(--text-face);
|
||||
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 {
|
||||
min-height: 52px;
|
||||
background: #fff;
|
||||
@@ -715,33 +748,6 @@ h1 {
|
||||
color: var(--ink);
|
||||
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 {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
@@ -823,64 +829,52 @@ h1 {
|
||||
display: none;
|
||||
}
|
||||
.specs {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 8px;
|
||||
}
|
||||
.spec {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
min-width: 0;
|
||||
padding: 10px 12px;
|
||||
border-radius: 14px;
|
||||
margin: 0;
|
||||
padding: 0 12px;
|
||||
list-style: none;
|
||||
border-radius: 16px;
|
||||
background: #fff;
|
||||
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 {
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
flex: none;
|
||||
border-radius: 10px;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
border-radius: 8px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
background: var(--sand);
|
||||
color: var(--dark);
|
||||
}
|
||||
.spec b {
|
||||
display: block;
|
||||
font-size: 14px;
|
||||
font-weight: 800;
|
||||
line-height: 1.2;
|
||||
white-space: nowrap;
|
||||
font-weight: 700;
|
||||
line-height: 1.35;
|
||||
}
|
||||
.spec small {
|
||||
display: block;
|
||||
font-size: 11.5px;
|
||||
color: var(--muted);
|
||||
font-weight: 600;
|
||||
line-height: 1.25;
|
||||
white-space: nowrap;
|
||||
.spec bdi {
|
||||
justify-self: end;
|
||||
text-align: end;
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
line-height: 1.35;
|
||||
}
|
||||
.spec.off {
|
||||
color: #626672;
|
||||
}
|
||||
.spec.off i {
|
||||
color: var(--faint);
|
||||
}
|
||||
.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;
|
||||
background: #f0f1f3;
|
||||
color: inherit;
|
||||
}
|
||||
.legal {
|
||||
margin: 2px 0 0;
|
||||
|
||||
+15
-14
@@ -55,13 +55,13 @@
|
||||
"dependencies": {
|
||||
"@assistant-ui/react": "0.15.38",
|
||||
"@capacitor/action-sheet": "^8.1.1",
|
||||
"@capacitor/android": "^8.6.2",
|
||||
"@capacitor/android": "^8.6.3",
|
||||
"@capacitor/app": "^8.1.1",
|
||||
"@capacitor/core": "^8.6.2",
|
||||
"@capacitor/core": "^8.6.3",
|
||||
"@capacitor/dialog": "^8.0.1",
|
||||
"@capacitor/filesystem": "^8.1.3",
|
||||
"@capacitor/filesystem": "^8.1.6",
|
||||
"@capacitor/haptics": "^8.0.2",
|
||||
"@capacitor/ios": "^8.6.2",
|
||||
"@capacitor/ios": "^8.6.3",
|
||||
"@capacitor/keyboard": "^8.0.5",
|
||||
"@capacitor/share": "^8.0.1",
|
||||
"@capacitor/splash-screen": "^8.0.2",
|
||||
@@ -101,6 +101,7 @@
|
||||
"@fontsource/satisfy": "^5.3.0",
|
||||
"@fontsource/shrikhand": "^5.3.0",
|
||||
"@fontsource/yellowtail": "^5.3.0",
|
||||
"@lucide/icons": "1.82.0",
|
||||
"@maplibre/maplibre-gl-leaflet": "0.1.4",
|
||||
"@noble/hashes": "^2.4.0",
|
||||
"@simplewebauthn/browser": "^14.0.0",
|
||||
@@ -112,9 +113,9 @@
|
||||
"heic-to": "^1.6.7",
|
||||
"iso-3166-2": "^1.0.0",
|
||||
"leaflet": "^1.9.4",
|
||||
"lucide-react": "^0.577.0",
|
||||
"lucide-react": "^1.82.0",
|
||||
"mapbox-gl": "3.32.0",
|
||||
"maplibre-gl": "6.19.0",
|
||||
"maplibre-gl": "6.20.0",
|
||||
"modern-screenshot": "4.7.0",
|
||||
"plyr": "^3.8.5",
|
||||
"react": "^19.3.1",
|
||||
@@ -123,7 +124,7 @@
|
||||
"react-leaflet": "^5.0.0",
|
||||
"react-leaflet-cluster": "^4.1.3",
|
||||
"react-markdown": "^10.1.0",
|
||||
"react-router": "^7.18.4",
|
||||
"react-router": "^8.5.3",
|
||||
"rehype-sanitize": "^6.0.0",
|
||||
"remark-breaks": "^4.0.0",
|
||||
"remark-gfm": "^4.0.1",
|
||||
@@ -133,12 +134,12 @@
|
||||
"zustand": "^5.0.15"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@capacitor/cli": "^8.6.2",
|
||||
"@capacitor/cli": "^8.6.3",
|
||||
"@eslint/js": "^10.0.1",
|
||||
"@jscpd/core": "^4.2.5",
|
||||
"@jscpd/tokenizer": "^4.2.6",
|
||||
"@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/react": "^16.3.3",
|
||||
"@testing-library/user-event": "^14.6.13",
|
||||
@@ -146,22 +147,22 @@
|
||||
"@types/geojson": "^7946.0.16",
|
||||
"@types/leaflet": "^1.9.23",
|
||||
"@types/node": "^26.6.11",
|
||||
"@types/react": "^19.3.2",
|
||||
"@types/react": "^19.3.3",
|
||||
"@types/react-dom": "^19.3.0",
|
||||
"@types/topojson-client": "^3.1.5",
|
||||
"@types/topojson-specification": "^1.0.5",
|
||||
"@vitejs/plugin-react": "^6.2.1",
|
||||
"@vitest/coverage-v8": "^5.1.2",
|
||||
"autoprefixer": "^10.7.0",
|
||||
"autoprefixer": "^10.7.1",
|
||||
"eslint": "^10.11.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-refresh": "^0.5.8",
|
||||
"fake-indexeddb": "^6.2.7",
|
||||
"jsdom": "^29.1.1",
|
||||
"msw": "^3.0.8",
|
||||
"postcss": "^8.5.33",
|
||||
"postcss": "^8.5.34",
|
||||
"prettier": "^3.10.1",
|
||||
"prettier-plugin-organize-imports": "^4.3.0",
|
||||
"prettier-plugin-tailwindcss": "^0.8.1",
|
||||
@@ -170,7 +171,7 @@
|
||||
"tailwindcss": "^3.4.19",
|
||||
"typescript": "^6.0.3",
|
||||
"typescript-eslint": "^8.74.0",
|
||||
"vite": "8.3.8",
|
||||
"vite": "8.4.0",
|
||||
"vite-plugin-pwa": "^2.0.0",
|
||||
"vitest": "^5.1.2"
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
"trek/no-swallowed-catch": 124,
|
||||
"max-params": 31,
|
||||
"trek/store-without-selector": 65,
|
||||
"react-hooks/refs": 385,
|
||||
"react-hooks/refs": 384,
|
||||
"react-hooks/set-state-in-effect": 188,
|
||||
"@typescript-eslint/no-floating-promises": 162,
|
||||
"react-hooks/exhaustive-deps": 112,
|
||||
@@ -35,7 +35,7 @@
|
||||
},
|
||||
"tests": {
|
||||
"@typescript-eslint/no-explicit-any": 484,
|
||||
"@typescript-eslint/no-non-null-assertion": 1848,
|
||||
"@typescript-eslint/no-non-null-assertion": 1845,
|
||||
"@typescript-eslint/no-misused-promises": 22,
|
||||
"@typescript-eslint/no-unused-vars": 48,
|
||||
"@typescript-eslint/no-floating-promises": 33,
|
||||
|
||||
@@ -776,7 +776,7 @@
|
||||
{
|
||||
"feature": "Place add/edit form and maps search: usePlaceForm",
|
||||
"hooks": ["src/components/Planner/usePlaceForm.ts"],
|
||||
"desktop": ["src/components/Planner/PlaceFormModal.tsx"],
|
||||
"desktop": ["src/components/Planner/usePlaceFormModal.ts"],
|
||||
"mobile": [
|
||||
"src/mobile/screens/trip/sheets/MPlaceEditSheet.tsx",
|
||||
"src/mobile/screens/trip/sheets/PlCategoryPicker.tsx"
|
||||
@@ -785,13 +785,13 @@
|
||||
{
|
||||
"feature": "Place add/edit form and maps search: usePlaceSearch",
|
||||
"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"]
|
||||
},
|
||||
{
|
||||
"feature": "Place add/edit form: tags",
|
||||
"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"]
|
||||
},
|
||||
{
|
||||
|
||||
@@ -640,7 +640,6 @@
|
||||
"src/components/Planner/PlaceFormModal.helpers.test.ts",
|
||||
"src/components/Planner/PlaceFormModal.helpers.ts",
|
||||
"src/components/Planner/PlaceFormModal.test.tsx",
|
||||
"src/components/Planner/PlaceFormModal.tsx",
|
||||
"src/components/Planner/PlaceInspector.test.tsx",
|
||||
"src/components/Planner/PlaceInspector.tsx",
|
||||
"src/components/Planner/PlacesBulkCategoryModal.test.tsx",
|
||||
@@ -1426,7 +1425,6 @@
|
||||
"src/mobile/screens/vacay/MVacayShareSheet.tsx",
|
||||
"src/mobile/screens/vacay/useMVacay.ts",
|
||||
"src/mobile/screens/vacay/vacayDayModel.ts",
|
||||
"src/mobile/useIsPhone.ts",
|
||||
"src/pages/AdminPage.test.tsx",
|
||||
"src/pages/AdminPage.tsx",
|
||||
"src/pages/AtlasPage.tsx",
|
||||
|
||||
@@ -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) });
|
||||
});
|
||||
}
|
||||
@@ -4,8 +4,8 @@
|
||||
"src/components/Admin/AdminPluginsPanel.test.tsx": 2704,
|
||||
"src/components/Admin/AdminPluginsPanel.tsx": 1265,
|
||||
"src/components/Budget/CostsPanel.test.tsx": 2725,
|
||||
"src/components/Budget/CostsPanel.tsx": 1607,
|
||||
"src/components/Map/MapView.tsx": 1191,
|
||||
"src/components/Budget/CostsPanel.tsx": 1588,
|
||||
"src/components/Map/MapView.tsx": 1170,
|
||||
"src/components/Map/MapViewGL.test.tsx": 2919,
|
||||
"src/components/Map/MapViewGL.tsx": 2083,
|
||||
"src/components/Planner/DayDetailPanel.test.tsx": 2331,
|
||||
|
||||
@@ -48,7 +48,6 @@
|
||||
"src/components/Planner/DayPlanSidebar.tsx": 52,
|
||||
"src/components/Planner/DayPlanSidebarNoteModal.test.tsx": 1,
|
||||
"src/components/Planner/PlaceFormModal.test.tsx": 3,
|
||||
"src/components/Planner/PlaceFormModal.tsx": 1,
|
||||
"src/components/Planner/PlaceInspector.tsx": 16,
|
||||
"src/components/Planner/PlacesBulkCategoryModal.test.tsx": 1,
|
||||
"src/components/Planner/PlacesSidebar.tsx": 1,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useState, type ReactNode } from 'react'
|
||||
import {
|
||||
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,
|
||||
Globe, History, Puzzle, Bot, Loader2,
|
||||
} from 'lucide-react'
|
||||
@@ -789,7 +789,7 @@ function PluginDetailModal({ item, installed, busy, onInstall, onClose, t, local
|
||||
footer={(
|
||||
<DialogFooter>
|
||||
<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 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>
|
||||
|
||||
@@ -210,11 +210,8 @@ describe('BackupPanel', () => {
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('backup-2025-01-15.zip')).toBeInTheDocument()
|
||||
})
|
||||
const trashBtn = Array.from(document.querySelectorAll('button')).find(
|
||||
b => b.querySelector('svg.lucide-trash2'),
|
||||
) as HTMLElement
|
||||
expect(trashBtn).toBeTruthy()
|
||||
await user.click(trashBtn!)
|
||||
const trashBtn = screen.getByRole('button', { name: 'Delete' })
|
||||
await user.click(trashBtn)
|
||||
// The question is the shared confirm dialog now, not window.confirm
|
||||
expect(await screen.findByText('Delete backup "backup-2025-01-15.zip"?')).toBeInTheDocument()
|
||||
const deleteButtons = screen.getAllByRole('button', { name: 'Delete' })
|
||||
@@ -428,9 +425,7 @@ describe('BackupPanel', () => {
|
||||
render(<><ToastContainer /><BackupPanel /></>)
|
||||
await screen.findByText('backup-2025-01-15.zip')
|
||||
|
||||
const trashBtn = Array.from(document.querySelectorAll('button')).find(
|
||||
b => b.querySelector('svg.lucide-trash2'),
|
||||
) as HTMLElement
|
||||
const trashBtn = screen.getByRole('button', { name: 'Delete' })
|
||||
await user.click(trashBtn)
|
||||
await user.click(await screen.findByRole('button', { name: 'Cancel' }))
|
||||
expect(deleteCalls).toBe(0)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { focusRevealedEditor } from '../shared/dialogFocus'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { Plus, Trash2, Pencil, Package, X, Check, ChevronRight, FolderPlus, Loader2 } from 'lucide-react'
|
||||
import { fs } from '../shared/DialogShell'
|
||||
@@ -57,7 +58,7 @@ export default function PackingTemplateManager() {
|
||||
{showCreate && (
|
||||
<div className={COMPOSER_ROW} style={{ boxShadow: COMPOSER.boxShadow }}>
|
||||
<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) }}
|
||||
placeholder={t('admin.packingTemplates.namePlaceholder')} className={COMPOSER_INPUT} style={fs(13, 'body')} />
|
||||
<Tooltip label={t('common.save')}>
|
||||
@@ -101,7 +102,7 @@ export default function PackingTemplateManager() {
|
||||
<Package size={15} strokeWidth={1.9} />
|
||||
</span>
|
||||
{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)}
|
||||
onKeyDown={e => { if (e.key === 'Enter') void handleRenameTemplate(tmpl.id); if (e.key === 'Escape') setEditingTemplate(null) }}
|
||||
aria-label={t('common.rename')}
|
||||
@@ -132,7 +133,7 @@ export default function PackingTemplateManager() {
|
||||
{/* 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">
|
||||
{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)}
|
||||
onKeyDown={e => { if (e.key === 'Enter') void handleRenameCategory(cat.id); if (e.key === 'Escape') setEditingCatId(null) }}
|
||||
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">
|
||||
{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) }}
|
||||
aria-label={t('common.rename')}
|
||||
className={`${ROW_INPUT} flex-1`} style={fs(12.5, 'body')} />
|
||||
@@ -219,7 +220,7 @@ export default function PackingTemplateManager() {
|
||||
{/* Add category */}
|
||||
{addingCategory ? (
|
||||
<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('') } }}
|
||||
placeholder={t('admin.packingTemplates.categoryName')}
|
||||
className={COMPOSER_INPUT} style={fs(13, 'body')} />
|
||||
|
||||
@@ -67,7 +67,7 @@ function Catalog() {
|
||||
}}>
|
||||
<div className={GRID_2}>
|
||||
<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 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" />
|
||||
|
||||
@@ -62,7 +62,7 @@ export default function SchoolHolidayRegionEditor({ region, busy, offline = fals
|
||||
<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' : ''}`}>
|
||||
<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>
|
||||
<SettingsHint>{t('schoolCatalog.periodHint')}</SettingsHint>
|
||||
{holidays.map((holiday, index) => {
|
||||
|
||||
@@ -3,7 +3,6 @@ import {
|
||||
ArrowUpCircle,
|
||||
Bug,
|
||||
CircleDot,
|
||||
Github,
|
||||
Globe,
|
||||
History,
|
||||
Info,
|
||||
@@ -23,6 +22,7 @@ import { createPortal } from 'react-dom';
|
||||
import { POPOVER } from '../../Packing/packingPopoverStyles';
|
||||
import ToggleSwitch from '../../Settings/ToggleSwitch';
|
||||
import { fs } from '../../shared/DialogShell';
|
||||
import { Github } from '../../shared/legacyLucideIcons';
|
||||
import PluginIcon from '../../shared/PluginIcon';
|
||||
import { Tooltip } from '../../shared/Tooltip';
|
||||
import { deriveCaps } from '../pluginCaps';
|
||||
|
||||
@@ -11,12 +11,13 @@
|
||||
import type { AssistantApplied, AssistantChangeEffect, AssistantChangePreview } from '@trek/shared';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { buildAssignment, buildDay, buildPlace, buildTrip } from '../../../tests/helpers/factories';
|
||||
import { act, fireEvent, render, screen } from '../../../tests/helpers/render';
|
||||
import { buildAssignment, buildCategory, buildDay, buildPlace, buildTrip } from '../../../tests/helpers/factories';
|
||||
import { act, fireEvent, render, screen, within } from '../../../tests/helpers/render';
|
||||
import { chatOf, useAssistantStore } from '../../store/assistantStore';
|
||||
import { useTripStore } from '../../store/tripStore';
|
||||
import AssistantChangeCard from './AssistantChangeCard';
|
||||
import AssistantCompareSwitch from './AssistantCompareSwitch';
|
||||
import AssistantDayPreview from './AssistantDayPreview';
|
||||
import type { ChangeItem } from './assistantParts';
|
||||
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: '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', () => {
|
||||
|
||||
@@ -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 { 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. */
|
||||
function CardHead({ open, count, actions }: { open: boolean; count: number; actions?: ReactNode }) {
|
||||
const { t } = useTranslation();
|
||||
const Icon = open ? ListChecks : CheckCheck;
|
||||
return (
|
||||
<CardHeader
|
||||
icon={open ? ListChecks : CheckCheck}
|
||||
icon={Icon}
|
||||
tone={open ? 'info' : 'success'}
|
||||
tint={open ? NEUTRAL_TINT : DONE_TINT}
|
||||
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}
|
||||
/>
|
||||
);
|
||||
@@ -186,11 +194,23 @@ export default function AssistantChangeCard({ items }: { items: ChangeItem[] })
|
||||
const undone = useAssistantStore((s) => chatOf(s, tripId).undone);
|
||||
const decide = useAssistantStore((s) => s.decide);
|
||||
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 pending = items.filter((i) => i.state === 'pending');
|
||||
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 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.
|
||||
const folded = week.length > 0 && !showAll;
|
||||
|
||||
const toggleDay = (ids: readonly string[], include: boolean) =>
|
||||
setExcluded((prev) => {
|
||||
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 toggleDay = (ids: readonly string[], include: boolean) => choosePlanChanges(tripId, ids, include);
|
||||
const toggle = (toolCallId: string) => toggleDay([toolCallId], excluded.has(toolCallId));
|
||||
|
||||
const submit = (applyChosen: boolean) =>
|
||||
decide(
|
||||
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.
|
||||
@@ -230,6 +240,21 @@ export default function AssistantChangeCard({ items }: { items: ChangeItem[] })
|
||||
};
|
||||
|
||||
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 (
|
||||
<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
|
||||
@@ -249,16 +274,31 @@ export default function AssistantChangeCard({ items }: { items: ChangeItem[] })
|
||||
{t('assistant.week.showAll', { count: pending.length })}
|
||||
</button>
|
||||
)}
|
||||
<ChangeRows
|
||||
items={items}
|
||||
folded={folded}
|
||||
excluded={excluded}
|
||||
disabled={isRunning}
|
||||
undone={undone}
|
||||
undoable={undoable}
|
||||
onToggle={toggle}
|
||||
onUndo={(toolCallId) => void runUndo(toolCallId)}
|
||||
{!folded && groupedDay && planDay ? (
|
||||
<details open className="group/day mt-1">
|
||||
<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">
|
||||
<span
|
||||
aria-hidden="true"
|
||||
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"
|
||||
>
|
||||
{planDay.day_number}
|
||||
</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 && (
|
||||
<>
|
||||
<p className="sr-only" role="status">
|
||||
@@ -270,7 +310,7 @@ export default function AssistantChangeCard({ items }: { items: ChangeItem[] })
|
||||
</DialogButton>
|
||||
<DialogButton
|
||||
variant="primary"
|
||||
disabled={isRunning || chosen === 0}
|
||||
disabled={isRunning || chosen === 0 || invalid}
|
||||
onClick={() => void submit(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 {
|
||||
CalendarClock,
|
||||
CalendarDays,
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
} from 'lucide-react';
|
||||
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { useTripStore } from '../../store/tripStore';
|
||||
import { FactChange } from './cards/parts/CardFacts';
|
||||
|
||||
/**
|
||||
@@ -45,10 +46,42 @@ function shown(row: AssistantChangeRow, value: string | null | undefined, dayWor
|
||||
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 categoryName = useTripStore((s) =>
|
||||
edits?.categoryId == null ? undefined : s.categories.find((category) => category.id === edits.categoryId)?.name
|
||||
);
|
||||
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)
|
||||
.sort((a, b) => KEY_ORDER.indexOf(a.labelKey) - KEY_ORDER.indexOf(b.labelKey))
|
||||
.slice(0, MAX_FACTS);
|
||||
|
||||
@@ -1,18 +1,28 @@
|
||||
import type { AssistantChangeEffect, AssistantMessage } from '@trek/shared';
|
||||
import { ArrowRightLeft, Minus, Sparkles } from 'lucide-react';
|
||||
import type { AssistantChangePreview, AssistantMessage, AssistantPlanEdits } from '@trek/shared';
|
||||
import { ArrowRightLeft, FileText, MapPin, Minus, type LucideIcon } from 'lucide-react';
|
||||
import { useMemo } from 'react';
|
||||
import { useShallow } from 'zustand/react/shallow';
|
||||
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { changeEffects } from '../../store/assistantMapModel';
|
||||
import { chatOf, useAssistantStore } from '../../store/assistantStore';
|
||||
import { useSettingsStore } from '../../store/settingsStore';
|
||||
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. */
|
||||
interface PreviewRow {
|
||||
toolCallId: string;
|
||||
kind: 'add' | 'in' | 'remove' | 'out';
|
||||
kind: 'add' | 'in' | 'remove' | 'out' | 'note';
|
||||
name: string;
|
||||
categoryId: number | null;
|
||||
categoryName?: string;
|
||||
start?: string;
|
||||
end?: string;
|
||||
detail?: string;
|
||||
}
|
||||
|
||||
/** The changes no one has decided on yet, by their call. */
|
||||
@@ -29,25 +39,77 @@ function waitingCalls(messages: readonly AssistantMessage[]): Set<string> {
|
||||
}
|
||||
|
||||
function rowOf(
|
||||
toolCallId: string,
|
||||
effect: AssistantChangeEffect,
|
||||
preview: AssistantChangePreview,
|
||||
dayId: number,
|
||||
nameOf: (id: number | null) => string | null
|
||||
) {
|
||||
const name = effect.place?.name ?? nameOf(effect.placeId);
|
||||
if (!name) return null;
|
||||
if (effect.dayId === dayId) {
|
||||
const kind = effect.kind === 'remove' ? 'remove' : effect.kind === 'move' ? 'in' : 'add';
|
||||
return { toolCallId, kind, name } satisfies PreviewRow;
|
||||
places: readonly Place[],
|
||||
edits: AssistantPlanEdits | undefined
|
||||
): PreviewRow | null {
|
||||
const { toolCallId, effect, subject } = preview;
|
||||
if (preview.dayId === dayId && isDayNoteProposal(preview)) {
|
||||
return {
|
||||
toolCallId,
|
||||
kind: 'note',
|
||||
name: edits?.noteTitle || planField(preview, 'title') || subject,
|
||||
categoryId: null,
|
||||
detail: proposalNote(preview, edits) ?? undefined,
|
||||
};
|
||||
}
|
||||
if (effect.kind === 'move' && effect.fromDayId === dayId)
|
||||
return { toolCallId, kind: 'out', name } satisfies PreviewRow;
|
||||
return null;
|
||||
const kind = visitKind(preview, dayId);
|
||||
if (!kind) 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: {
|
||||
icon: Sparkles,
|
||||
icon: MapPin,
|
||||
row: 'border-dashed border-accent bg-accent-subtle',
|
||||
name: 'text-content',
|
||||
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',
|
||||
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.
|
||||
*/
|
||||
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 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 { setMapHover, open } = useAssistantStore(useShallow((s) => ({ setMapHover: s.setMapHover, open: s.open })));
|
||||
const places = useTripStore((s) => s.places);
|
||||
const categories = useTripStore((s) => s.categories);
|
||||
|
||||
const rows = useMemo(() => {
|
||||
const waiting = waitingCalls(messages);
|
||||
if (waiting.size === 0) return [];
|
||||
const nameOf = (id: number | null) => (id === null ? null : (places.find((p) => p.id === id)?.name ?? null));
|
||||
const out: PreviewRow[] = [];
|
||||
for (const [toolCallId, effect] of changeEffects(messages)) {
|
||||
if (!waiting.has(toolCallId)) continue;
|
||||
const row = rowOf(toolCallId, effect, dayId, nameOf);
|
||||
if (row) out.push(row);
|
||||
}
|
||||
return out;
|
||||
}, [messages, places, dayId]);
|
||||
return messages.flatMap((message) =>
|
||||
message.parts.flatMap((part) => {
|
||||
if (part.type !== 'data-trek-change' || !waiting.delete(part.data.toolCallId)) return [];
|
||||
const id = part.data.toolCallId;
|
||||
if (choices[id] === false) return [];
|
||||
const edits = liveEdit?.toolCallId === id ? liveEdit.edits : savedEdits[id];
|
||||
const row = rowOf(part.data, dayId, places, edits);
|
||||
return row ? [row] : [];
|
||||
})
|
||||
);
|
||||
}, [messages, places, dayId, savedEdits, liveEdit, choices]);
|
||||
|
||||
if (rows.length === 0) return null;
|
||||
return (
|
||||
<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) => {
|
||||
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;
|
||||
return (
|
||||
<li
|
||||
@@ -121,11 +203,29 @@ export default function AssistantDayPreview({ tripId, dayId }: { tripId: number;
|
||||
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">
|
||||
<Icon size={12} aria-hidden="true" />
|
||||
<span
|
||||
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>
|
||||
<bdi className={`min-w-0 flex-1 truncate text-caption font-medium ${look.name}`}>{row.name}</bdi>
|
||||
<span className="flex-shrink-0 rounded-full bg-surface-card px-2 py-0.5 text-caption text-content-muted shadow-sm">
|
||||
<span className="min-w-0 flex-1">
|
||||
<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)}
|
||||
</span>
|
||||
</button>
|
||||
|
||||
@@ -4,10 +4,11 @@
|
||||
* The error line: one sentence, at most one thing to do, and that thing
|
||||
* 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 { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { HIKE } from '../../../tests/helpers/assistantTour';
|
||||
import { fireEvent, render, screen } from '../../../tests/helpers/render';
|
||||
import { chatOf, useAssistantStore } from '../../store/assistantStore';
|
||||
import { setForcedOffline } from '../../sync/networkMode';
|
||||
@@ -33,13 +34,17 @@ const retry = vi.fn(async () => {});
|
||||
const continueHere = 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({
|
||||
status,
|
||||
retry,
|
||||
continueHere,
|
||||
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();
|
||||
});
|
||||
|
||||
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', () => {
|
||||
withError('decide_first');
|
||||
renderLine();
|
||||
|
||||
@@ -4,7 +4,7 @@ import { useNavigate } from 'react-router';
|
||||
import { useNetworkMode } from '../../hooks/useNetworkMode';
|
||||
import { useTranslation } from '../../i18n';
|
||||
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 { CHATGPT_USAGE_URL, providerLabel } from './providerCatalog';
|
||||
|
||||
@@ -18,6 +18,10 @@ export default function AssistantError({ tripId }: { tripId: number }) {
|
||||
const navigate = useNavigate();
|
||||
const { offline } = useNetworkMode();
|
||||
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 retry = useAssistantStore((s) => s.retry);
|
||||
const continueHere = useAssistantStore((s) => s.continueHere);
|
||||
@@ -28,7 +32,7 @@ export default function AssistantError({ tripId }: { tripId: number }) {
|
||||
|
||||
const effective = status?.effective;
|
||||
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) => {
|
||||
if (kind === 'retry') void retry(tripId);
|
||||
|
||||
@@ -139,7 +139,8 @@ function Answer({ message }: { message: StoredMessage }) {
|
||||
});
|
||||
const blocks = useMemo(() => messageBlocks(message, writing), [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 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 { render, screen } from '../../../tests/helpers/render';
|
||||
import { fireEvent, render, screen } from '../../../tests/helpers/render';
|
||||
import AssistantSources from './AssistantSources';
|
||||
import { messageBlocks } from './assistantParts';
|
||||
|
||||
@@ -31,7 +31,8 @@ describe('AssistantSources', () => {
|
||||
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(
|
||||
{
|
||||
id: 'm1',
|
||||
@@ -40,12 +41,46 @@ describe('AssistantSources', () => {
|
||||
createdAt: '2026-10-23T10:00:00.000Z',
|
||||
parts: [
|
||||
{ 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: '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
|
||||
);
|
||||
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 { Globe } from 'lucide-react';
|
||||
import { ChevronDown, Globe } from 'lucide-react';
|
||||
import { useId, useState } from 'react';
|
||||
|
||||
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. */
|
||||
function hostOf(url: string): string {
|
||||
@@ -19,30 +23,48 @@ function hostOf(url: string): string {
|
||||
*/
|
||||
export default function AssistantSources({ sources }: { sources: Sources['sources'] }) {
|
||||
const { t } = useTranslation();
|
||||
const id = useId();
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const visible = expanded ? sources : sources.slice(0, INITIAL_COUNT);
|
||||
return (
|
||||
<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">
|
||||
{t('assistant.sources.title')}
|
||||
</span>
|
||||
<ul className="m-0 flex list-none flex-wrap gap-1.5 p-0">
|
||||
{sources.map((source) => (
|
||||
<li key={source.url} className="min-w-0 max-w-full">
|
||||
<ul id={id} className="m-0 flex list-none flex-wrap gap-1.5 p-0">
|
||||
{visible.map(({ url, title }) => {
|
||||
const host = hostOf(url);
|
||||
const label = title && title !== url ? title : host;
|
||||
return (
|
||||
<li key={url} className="min-w-0 max-w-full">
|
||||
<Tooltip label={label} placement="top">
|
||||
<a
|
||||
href={source.url}
|
||||
href={url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer nofollow"
|
||||
title={source.title}
|
||||
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"
|
||||
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"
|
||||
>
|
||||
<Globe size={11} strokeWidth={2.2} aria-hidden="true" className="flex-none text-content-faint" />
|
||||
<span className="flex-none font-medium">{hostOf(source.url)}</span>
|
||||
{source.title && source.title !== source.url && (
|
||||
<bdi className="min-w-0 truncate text-content-muted">{source.title}</bdi>
|
||||
)}
|
||||
<bdi className="min-w-0 truncate font-semibold text-content">{label}</bdi>
|
||||
{label !== host && <bdi className="max-w-[35%] shrink-0 truncate text-content-muted">{host}</bdi>}
|
||||
</a>
|
||||
</Tooltip>
|
||||
</li>
|
||||
))}
|
||||
);
|
||||
})}
|
||||
</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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,8 +2,9 @@ import { ChevronRight } from 'lucide-react';
|
||||
import { useState } from 'react';
|
||||
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { POI_CATEGORIES } from '../Map/poiCategories';
|
||||
import AssistantLiveStep from './AssistantLiveStep';
|
||||
import { toolStepKey } from './assistantModel';
|
||||
import { liveStepText } from './assistantModel';
|
||||
import type { ToolStep } from './assistantParts';
|
||||
|
||||
/**
|
||||
@@ -37,9 +38,20 @@ export default function AssistantToolSteps({ steps }: { steps: ToolStep[] }) {
|
||||
</button>
|
||||
{open && (
|
||||
<ul className="m-0 mt-1 list-none space-y-0.5 border-s border-edge-faint ps-3">
|
||||
{steps.map((step) => (
|
||||
<li key={step.toolCallId}>{t(toolStepKey(step.toolName))}</li>
|
||||
))}
|
||||
{steps.map((step) => {
|
||||
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>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -170,12 +170,18 @@ describe('AssistantWindow', () => {
|
||||
|
||||
it('FE-AI-WIN-014: minimized outside a trip, the round button brings the home chat back', () => {
|
||||
seed({ open: true, minimized: true });
|
||||
render(<AssistantWindow trip={null} />);
|
||||
render(<AssistantWindow trip={null} />, { initialEntries: ['/atlas'] });
|
||||
expect(screen.getByText('chat 0 Your travels')).not.toBeVisible();
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Assistant' }));
|
||||
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', () => {
|
||||
seed({ open: true, minimized: true }, true);
|
||||
render(<AssistantWindow trip={TRIP} />);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import './assistant.css';
|
||||
|
||||
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 { useTranslation } from '../../i18n';
|
||||
@@ -200,6 +200,7 @@ function windowChat(
|
||||
|
||||
export default function AssistantWindow({ trip, onOpen, onFocusDay, onRevealMap }: AssistantWindowProps) {
|
||||
const navigate = useNavigate();
|
||||
const onDashboard = useMatch('/') !== null;
|
||||
const available = useAssistantStore((s) => s.status?.available === true);
|
||||
const open = useAssistantStore((s) => s.window.open);
|
||||
const minimized = useAssistantStore((s) => s.window.minimized);
|
||||
@@ -267,8 +268,9 @@ export default function AssistantWindow({ trip, onOpen, onFocusDay, onRevealMap
|
||||
onOpenTripChat={atHome ? home.openTripChat : undefined}
|
||||
tripSwitch={tripSwitch}
|
||||
/>
|
||||
{/* Hidden while an answer may still come in: the round button brings it back, on any page. */}
|
||||
{minimized && <AssistantLauncher variant="floating" tripId={launcherTrip} focusOnMount />}
|
||||
{minimized && (!onDashboard || !!routeChat) && (
|
||||
<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. */
|
||||
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
|
||||
* 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(
|
||||
code: AssistantErrorCode,
|
||||
opts: { canConnectOwn: boolean; provider?: string }
|
||||
opts: { canConnectOwn: boolean; provider?: string; hasTourProposal?: boolean }
|
||||
): AssistantErrorView {
|
||||
const view = ERRORS[code];
|
||||
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' };
|
||||
return view;
|
||||
}
|
||||
|
||||
@@ -98,6 +98,27 @@ describe('messageBlocks', () => {
|
||||
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', () => {
|
||||
const blocks = messageBlocks(
|
||||
message([
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import {
|
||||
ASSISTANT_FOLLOW_UPS_TOOL,
|
||||
assistantSourceTitle,
|
||||
type AssistantApplied,
|
||||
type AssistantChangeEffect,
|
||||
type AssistantChangeLabelKey,
|
||||
@@ -39,6 +40,8 @@ export interface ToolStep {
|
||||
toolName: string;
|
||||
/** Still waiting for its result while the answer is being written. */
|
||||
running: boolean;
|
||||
query?: string;
|
||||
categories?: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -50,6 +53,7 @@ export type ChangeState = 'pending' | 'applying' | 'applied' | 'failed' | 'disca
|
||||
|
||||
export interface ChangeItem {
|
||||
toolCallId: string;
|
||||
args?: unknown;
|
||||
/** What the card says about it; null until the preview arrived. */
|
||||
preview: AssistantChangePreview | null;
|
||||
/** The receipt of an applied change. */
|
||||
@@ -269,6 +273,7 @@ function changeItemOf(
|
||||
const applied = receipts.get(part.toolCallId) ?? null;
|
||||
return {
|
||||
toolCallId: part.toolCallId,
|
||||
...(preview?.verbKey === 'addPlaceToDay' || preview?.verbKey === 'assignPlace' ? { args: part.args } : {}),
|
||||
preview,
|
||||
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
|
||||
* sat, each place once, without the ones a change the model proposed in the
|
||||
* answer already holds; the weather of all steps joins
|
||||
* into one row where the first look sat. A strip does not split the steps
|
||||
* around it: a step after it joins the row of steps before it.
|
||||
* into one row where the first look sat. The sources of all steps sit together
|
||||
* at the end of the answer.
|
||||
*
|
||||
* 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;
|
||||
@@ -311,6 +316,7 @@ export function messageBlocks(
|
||||
const previews = new Map<string, AssistantChangePreview>();
|
||||
const receipts = new Map<string, AssistantApplied>();
|
||||
const cards = new Map<string, TrekCard>();
|
||||
const sources = new Map<string, AssistantSources['sources'][number]>();
|
||||
const changeIds = new Set<string>();
|
||||
const effects: AssistantChangeEffect[] = [];
|
||||
// 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);
|
||||
if (part.data.effect && !fromStrip.has(part.data.toolCallId)) effects.push(part.data.effect);
|
||||
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-places') lastPlaces = 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 placesHidden =
|
||||
[...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));
|
||||
const blocks: MessageBlock[] = [];
|
||||
message.parts.forEach((part, index) => {
|
||||
@@ -347,10 +361,6 @@ export function messageBlocks(
|
||||
if (strip) blocks.push(strip);
|
||||
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) {
|
||||
blocks.push({ kind: 'weather', key: `weather-${index}`, days: weatherDays(message.parts) });
|
||||
return;
|
||||
@@ -373,18 +383,35 @@ export function messageBlocks(
|
||||
blocks.push({ kind: 'remembered', key: `remembered-${part.toolCallId}`, note });
|
||||
return;
|
||||
}
|
||||
const step: ToolStep = {
|
||||
toolCallId: part.toolCallId,
|
||||
toolName: part.toolName,
|
||||
running: writing && part.result === undefined,
|
||||
};
|
||||
const step = toolStep(part, writing);
|
||||
const steps = openSteps(blocks);
|
||||
if (steps) steps.steps.push(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);
|
||||
}
|
||||
|
||||
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
|
||||
* 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 {
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -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 { Check, Undo2 } from 'lucide-react';
|
||||
import type { AssistantChangePreview, AssistantPlanEdits, TrekCardKind } from '@trek/shared';
|
||||
import { Check, Paperclip, Undo2 } from 'lucide-react';
|
||||
import { Fragment, type ReactNode } from 'react';
|
||||
|
||||
import { useTranslation } from '../../../i18n';
|
||||
import { Tooltip } from '../../shared/Tooltip';
|
||||
import AssistantChangeFields from '../AssistantChangeFields';
|
||||
import type { ChangeItem } from '../assistantParts';
|
||||
import AssistantPlanFields from '../AssistantPlanFields';
|
||||
import { isDayNoteProposal, isVisitProposal, planField, proposalNote } from '../assistantPlanFieldsModel';
|
||||
import { useAssistantView } from '../assistantViewContext';
|
||||
import { useChangeHover } from '../useChangeHover';
|
||||
import { isSingleBookingDraft } from './booking/bookingCardModel';
|
||||
import { TOOL_LABELS, verbLookOf } from './cardLooks';
|
||||
import type { CardView } from './cardTypes';
|
||||
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. */
|
||||
const settledOf = (item: ChangeItem, undone: boolean) =>
|
||||
item.state === 'discarded' || item.state === 'expired' || undone;
|
||||
@@ -164,11 +172,21 @@ function Receipt({
|
||||
const settled = settledOf(item, undone);
|
||||
const statusLabel = t(undone ? 'assistant.change.undone' : receipt.labelKey);
|
||||
const view = item.card ? viewOf(item.card) : null;
|
||||
const inlineBooking = inlineBookingCard(item);
|
||||
return (
|
||||
<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' : ''}`}>
|
||||
{inlineBooking ? (
|
||||
<Slot
|
||||
name="Body"
|
||||
item={item}
|
||||
view={view}
|
||||
fallback={<ChangeHead item={item} view={view} struck={settled} />}
|
||||
/>
|
||||
) : (
|
||||
<ChangeHead item={item} view={view} struck={settled} />
|
||||
)}
|
||||
</div>
|
||||
{applied && <EntityActions applied={applied} card={item.card} />}
|
||||
{canUndo && (
|
||||
@@ -203,67 +221,134 @@ function PendingRow({
|
||||
withChoice,
|
||||
disabled,
|
||||
onToggle,
|
||||
edits,
|
||||
onEdit,
|
||||
groupedDay,
|
||||
}: {
|
||||
item: ChangeItem;
|
||||
excluded: boolean;
|
||||
withChoice: boolean;
|
||||
disabled: boolean;
|
||||
onToggle: () => void;
|
||||
edits: AssistantPlanEdits | undefined;
|
||||
onEdit: (patch: AssistantPlanEdits) => void;
|
||||
groupedDay: boolean;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const { tripId } = useAssistantView();
|
||||
const { litFromMap, handlers } = useChangeHover(tripId, item.preview?.effect ? item.toolCallId : null);
|
||||
const preview = item.preview;
|
||||
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 (
|
||||
<div
|
||||
{...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' : ''
|
||||
} ${litFromMap ? 'bg-surface-hover' : 'hover:bg-surface-hover'}`}
|
||||
>
|
||||
{withChoice && (
|
||||
{withChoice ? (
|
||||
<Tooltip label={t('assistant.change.include')}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onToggle}
|
||||
disabled={disabled}
|
||||
aria-pressed={!excluded}
|
||||
aria-label={t('assistant.change.include')}
|
||||
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 ${
|
||||
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"
|
||||
>
|
||||
{!excluded && <Check size={11} strokeWidth={3} aria-hidden="true" className="text-accent-text" />}
|
||||
</button>
|
||||
)}
|
||||
<Lead item={item} view={view} dimmed={excluded} />
|
||||
<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">
|
||||
<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={preview.rows} />
|
||||
)}
|
||||
{!excluded && (
|
||||
<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" />
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
</Tooltip>
|
||||
) : (
|
||||
!inlineBooking && <Lead item={item} view={view} dimmed={excluded} />
|
||||
)}
|
||||
<div className="min-w-0 flex-1">
|
||||
{inlineBooking ? (
|
||||
<Slot name="Body" item={item} view={view} fallback={<ChangeHead item={item} view={view} struck={false} />} />
|
||||
) : 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" />
|
||||
)}
|
||||
</div>
|
||||
{editable && (
|
||||
<AssistantPlanFields
|
||||
preview={preview}
|
||||
args={item.args}
|
||||
edits={edits}
|
||||
disabled={disabled || excluded}
|
||||
onEdit={onEdit}
|
||||
/>
|
||||
)}
|
||||
</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 {
|
||||
items: readonly ChangeItem[];
|
||||
/** The waiting rows wait behind the week grid. */
|
||||
@@ -274,6 +359,9 @@ interface RowsProps {
|
||||
undoable: readonly string[];
|
||||
onToggle: (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. */
|
||||
@@ -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
|
||||
* 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;
|
||||
// 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.
|
||||
@@ -316,6 +416,9 @@ export function ChangeRows({ items, folded, excluded, disabled, undone, undoable
|
||||
withChoice={pendingCount > 1}
|
||||
disabled={disabled}
|
||||
onToggle={() => onToggle(item.toolCallId)}
|
||||
edits={planEdits[item.toolCallId]}
|
||||
onEdit={(patch) => onEdit(item.toolCallId, patch)}
|
||||
groupedDay={groupedDay}
|
||||
/>
|
||||
) : (
|
||||
<Receipt
|
||||
@@ -325,7 +428,9 @@ export function ChangeRows({ items, folded, excluded, disabled, undone, undoable
|
||||
onUndo={() => onUndo(item.toolCallId)}
|
||||
/>
|
||||
)}
|
||||
{!inlineBookingCard(item) && (
|
||||
<BodySlot item={item} settled={waiting ? excluded.has(item.toolCallId) : settledOf(item, isUndone)} />
|
||||
)}
|
||||
</Fragment>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -25,6 +25,7 @@ import { useAuthStore } from '../../../../store/authStore';
|
||||
import { useSettingsStore } from '../../../../store/settingsStore';
|
||||
import type { ChangeItem } from '../../assistantParts';
|
||||
import { type AssistantView, AssistantViewContext } from '../../assistantViewContext';
|
||||
import { ChangeRows } from '../ChangeCardSlots';
|
||||
import BookingBlock from './BookingBlock';
|
||||
import { BookingChangeBody, BookingChangeFacts } from './BookingChangeSlots';
|
||||
|
||||
@@ -412,4 +413,44 @@ describe('booking cards', () => {
|
||||
expect(screen.queryByRole('button', { name: 'Open the booking' })).not.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 { useAssistantView } from '../../assistantViewContext';
|
||||
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';
|
||||
|
||||
/**
|
||||
@@ -88,11 +97,13 @@ export default function BookingCard({
|
||||
item,
|
||||
card,
|
||||
actions = true,
|
||||
proposal,
|
||||
}: {
|
||||
item: BookingItem;
|
||||
card: Card;
|
||||
/** Off inside a change card, whose row has its own ways to the booking. */
|
||||
actions?: boolean;
|
||||
proposal?: { label: string; notes?: string; reference?: string; receipt?: string };
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const body = item.body;
|
||||
@@ -101,17 +112,33 @@ export default function BookingCard({
|
||||
aria-label={item.title}
|
||||
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} />
|
||||
<div className="px-3 pb-2.5 pt-2">
|
||||
<BookingHead
|
||||
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 && (
|
||||
<p className="m-0 mb-1 text-caption text-content-muted">
|
||||
{t('assistant.card.booking.inTrip', { trip: item.tripTitle })}
|
||||
</p>
|
||||
)}
|
||||
{body.shape === 'ticket' && <TicketBody item={item} body={body} card={card} />}
|
||||
{body.shape === 'stay' && <StayBody item={item} body={body} card={card} />}
|
||||
{body.shape === 'venue' && <VenueBody item={item} body={body} card={card} />}
|
||||
{body.shape === 'stay' &&
|
||||
(proposal ? <StayProposalBody body={body} /> : <StayBody item={item} body={body} 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>
|
||||
</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 type { ChangeItem } from '../../assistantParts';
|
||||
import { verbLookOf } from '../cardLooks';
|
||||
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
|
||||
@@ -17,8 +21,28 @@ interface SlotProps {
|
||||
item: ChangeItem;
|
||||
}
|
||||
|
||||
/** The card under the row; the row itself leads to the booking once it is saved. */
|
||||
export function BookingChangeBody({ card }: SlotProps) {
|
||||
/** New single bookings carry their action in the card head. */
|
||||
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} />;
|
||||
}
|
||||
|
||||
|
||||
@@ -13,6 +13,10 @@ import type { CardEntry } from '../cardTypes';
|
||||
/** A status a booking card names in words. */
|
||||
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
|
||||
* tone, a confirmed booking green, any other (pending, cancelled) amber; none
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
LogOut,
|
||||
MapPin,
|
||||
Moon,
|
||||
Paperclip,
|
||||
Route,
|
||||
Ticket,
|
||||
Wallet,
|
||||
@@ -23,7 +24,16 @@ import {
|
||||
import { useRef, type ReactNode } from 'react';
|
||||
|
||||
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 { SoftPill, TimePill, type PillTone } from '../../../Planner/planParts';
|
||||
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. */
|
||||
function HeadLead({ item }: { item: BookingItem }) {
|
||||
function HeadLead({ item, proposal }: { item: BookingItem; proposal: boolean }) {
|
||||
const { density } = useAssistantView();
|
||||
const compact = density === 'compact';
|
||||
if (item.body.shape === 'stay') {
|
||||
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,
|
||||
* 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 tone = toneOfItem(item);
|
||||
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 (
|
||||
<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 }}
|
||||
>
|
||||
<HeadLead item={item} />
|
||||
<span className="flex min-w-0 flex-1 flex-col gap-0.5">
|
||||
<HeadLead item={item} proposal={proposal} />
|
||||
<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">
|
||||
<bdi
|
||||
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}
|
||||
</bdi>
|
||||
@@ -138,19 +165,192 @@ export function BookingHead({ item, card, actions }: { item: BookingItem; card:
|
||||
{isChanged(card, item, 'title') && <ChangedDot />}
|
||||
{removed && <span className="sr-only">{t('assistant.card.common.willDelete')}</span>}
|
||||
</span>
|
||||
{address && (
|
||||
{address &&
|
||||
(proposal ? (
|
||||
<span className="mt-0.5 flex items-start gap-1.5 text-caption text-content-muted">
|
||||
<MapPin size={12} className="mt-0.5 flex-none" aria-hidden="true" />
|
||||
<bdi title={address} className="line-clamp-2 break-words">
|
||||
{address}
|
||||
</bdi>
|
||||
</span>
|
||||
) : (
|
||||
<bdi title={address} className="line-clamp-2 text-caption text-content-muted">
|
||||
{address}
|
||||
</bdi>
|
||||
)}
|
||||
</span>
|
||||
<StatusMark item={item} />
|
||||
))}
|
||||
</div>
|
||||
{!actionLabel && <StatusMark item={item} />}
|
||||
{isChanged(card, item, 'status') && <ChangedDot />}
|
||||
{actions}
|
||||
</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. */
|
||||
function Pill({
|
||||
icon: Icon,
|
||||
|
||||
@@ -142,6 +142,10 @@ export const STEP_LOOKS: Readonly<Partial<Record<string, StepLook>>> = {
|
||||
stepKey: 'assistant.step.searching',
|
||||
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' } },
|
||||
get_place_details: { stepKey: 'assistant.step.details' },
|
||||
search_nearby_places: {
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
import type { TourRouteCard } from '@trek/shared';
|
||||
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 { act, fireEvent, render, screen } from '../../../../../tests/helpers/render';
|
||||
import { chatOf, useAssistantStore } from '../../../../store/assistantStore';
|
||||
@@ -81,6 +81,34 @@ describe('TourRouteBlock', () => {
|
||||
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', () => {
|
||||
renderBlock(WAYS, { density: 'roomy' });
|
||||
expect(screen.getByRole('radiogroup')).toHaveClass('grid-cols-2');
|
||||
|
||||
@@ -10,7 +10,7 @@ import TourRouteActions from './TourRouteActions';
|
||||
import TourRouteDay from './TourRouteDay';
|
||||
import TourRouteHead, { TourRouteFields } from './TourRouteHead';
|
||||
import { profileSamples } from './tourRouteModel';
|
||||
import { TourRouteProblem, TourRouteWarnings } from './TourRouteNotes';
|
||||
import { TourRouteDetour, TourRouteProblem, TourRouteWarnings } from './TourRouteNotes';
|
||||
import TourRouteProfile from './TourRouteProfile';
|
||||
import TourRouteStops from './TourRouteStops';
|
||||
import { routeName } from './tourRouteWords';
|
||||
@@ -45,6 +45,7 @@ export function TourRouteBody({
|
||||
return (
|
||||
<>
|
||||
<TourRouteFields card={card} />
|
||||
<TourRouteDetour card={card} />
|
||||
{/* A way drawn straight has neither heights nor the line to say so under: no section at all. */}
|
||||
{(samples.length >= 2 || card.routed) && (
|
||||
<CardSection label={t('tours.planner.inspector.elevation')}>
|
||||
|
||||
@@ -5,6 +5,7 @@ import { useTranslation } from '../../../../i18n';
|
||||
import { SoftPill } from '../../../Planner/planParts';
|
||||
import { TourNotice } from '../../../Tours/tourParts';
|
||||
import { useCardFormat } from '../parts/useCardFormat';
|
||||
import { hasLongHikeDetour } from './tourRouteModel';
|
||||
import { PROBLEM_LOOK, WARNING_LOOK } from './tourRouteWords';
|
||||
|
||||
/**
|
||||
@@ -53,3 +54,15 @@ export function TourRouteProblem({ card }: { card: TourRouteCard }) {
|
||||
</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 { useTranslation } from '../../../../i18n';
|
||||
import { preferredRouteEntry } from '../../../../store/assistantRouteModel';
|
||||
import { chatOf, useAssistantStore } from '../../../../store/assistantStore';
|
||||
import { useSettingsStore } from '../../../../store/settingsStore';
|
||||
import type { DistanceUnit } from '../../../../types';
|
||||
@@ -79,7 +80,7 @@ function WayOption({
|
||||
entry: RouteEntry;
|
||||
index: number;
|
||||
chosen: boolean;
|
||||
chosenWay: LegVariant;
|
||||
chosenWay: LegVariant | null;
|
||||
chosenLetter: string;
|
||||
unit: DistanceUnit;
|
||||
onSelect: () => void;
|
||||
@@ -118,8 +119,14 @@ function WayOption({
|
||||
{/* Ways of a ride or a run may differ by profile: each says its own. */}
|
||||
{entry.card.routingProfile && <TourGrade card={entry.card} />}
|
||||
</span>
|
||||
{entry.card.routed ? (
|
||||
<WayFigures way={way} unit={unit} />
|
||||
{!chosen && <WayDelta way={way} chosen={chosenWay} letter={chosenLetter} 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>
|
||||
</button>
|
||||
);
|
||||
@@ -156,7 +163,7 @@ function WaysCard({
|
||||
[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.
|
||||
let columns = '';
|
||||
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[] }) {
|
||||
const { tripId } = useAssistantView();
|
||||
const blockKey = `tour:${entries[0]?.toolCallId ?? ''}`;
|
||||
const picked = useAssistantStore((s) => chatOf(s, tripId).picks[blockKey] ?? null);
|
||||
const index = entries.findIndex((entry) => entry.toolCallId === picked);
|
||||
const chosenIndex = index < 0 ? 0 : index;
|
||||
const chosen = entries[chosenIndex];
|
||||
const picked = useAssistantStore((s) => chatOf(s, tripId).picks[blockKey]);
|
||||
const chosen = preferredRouteEntry(entries, picked);
|
||||
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 { 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. */
|
||||
interface ProfileBand {
|
||||
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 { 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.
|
||||
*/
|
||||
export function useChangeExclusions(
|
||||
items: readonly ChangeItem[]
|
||||
): [ReadonlySet<string>, Dispatch<SetStateAction<ReadonlySet<string>>>] {
|
||||
items: readonly ChangeItem[],
|
||||
choices: Readonly<Record<string, boolean>>
|
||||
): ReadonlySet<string> {
|
||||
const [excluded, setExcluded] = useState<ReadonlySet<string>>(() => new Set(startingOff(items, new Set())));
|
||||
const [seen, setSeen] = useState<ReadonlySet<string>>(() => new Set(arrived(items)));
|
||||
const fresh = arrived(items).filter((id) => !seen.has(id));
|
||||
@@ -31,5 +32,11 @@ export function useChangeExclusions(
|
||||
setSeen(new Set([...seen, ...fresh]));
|
||||
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]
|
||||
);
|
||||
}
|
||||
|
||||
@@ -17,6 +17,10 @@ const h = vi.hoisted(() => {
|
||||
insets: number[] = [];
|
||||
kicks = 0;
|
||||
disposed = false;
|
||||
static create(opts: GlobeEngineOptions): FakeEngine {
|
||||
return new FakeEngine(opts);
|
||||
}
|
||||
|
||||
constructor(opts: GlobeEngineOptions) {
|
||||
if (state.failNext !== null) {
|
||||
const err = state.failNext;
|
||||
|
||||
@@ -54,7 +54,7 @@ const AtlasGlobe = forwardRef<AtlasGlobeHandle, AtlasGlobeProps>(function AtlasG
|
||||
if (!canvas) return;
|
||||
let engine: GlobeEngine;
|
||||
try {
|
||||
engine = new GlobeEngine({
|
||||
engine = GlobeEngine.create({
|
||||
canvas,
|
||||
fetchJson: (p) => propsRef.current.fetchJson(p),
|
||||
theme: globeTheme(propsRef.current.dark),
|
||||
|
||||
@@ -210,7 +210,7 @@ async function start(o: StartOptions = {}) {
|
||||
onSelect: 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);
|
||||
return {
|
||||
mod,
|
||||
@@ -310,7 +310,7 @@ describe('GlobeEngine boot', () => {
|
||||
const otherFetch = vi.fn(async (): Promise<unknown> => null);
|
||||
const canvas = document.createElement('canvas');
|
||||
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);
|
||||
await flush();
|
||||
expect(otherFetch).not.toHaveBeenCalled();
|
||||
@@ -345,7 +345,7 @@ describe('GlobeEngine boot retries', () => {
|
||||
});
|
||||
const onError = vi.fn();
|
||||
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[] = [];
|
||||
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 onReady = vi.fn();
|
||||
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();
|
||||
expect(ok).toHaveBeenCalledWith('manifest');
|
||||
@@ -381,7 +381,9 @@ describe('GlobeEngine boot retries', () => {
|
||||
return files[p];
|
||||
});
|
||||
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();
|
||||
expect(pending.map((t) => t.ms)).toEqual([1000]);
|
||||
pending[0].cb();
|
||||
|
||||
@@ -164,7 +164,13 @@ export class GlobeEngine {
|
||||
private sun: [number, number, number] = sunVector(new Date());
|
||||
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.theme = opts.theme;
|
||||
Object.assign(this.cam, opts.initial ?? {});
|
||||
@@ -187,7 +193,6 @@ export class GlobeEngine {
|
||||
this.resizeObs.observe(opts.canvas);
|
||||
opts.canvas.addEventListener('webglcontextlost', this.onContextLost);
|
||||
this.resize();
|
||||
void this.boot();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- loading
|
||||
|
||||
@@ -14,7 +14,7 @@ export function hexToRgb(hex: string): Rgb {
|
||||
.map((c) => c + c)
|
||||
.join('')
|
||||
: 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];
|
||||
return [((n >> 16) & 255) / 255, ((n >> 8) & 255) / 255, (n & 255) / 255];
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@ import { amountToInputString, currencyDecimals } from '../../utils/formatters'
|
||||
import { localIsoDate } from '../../utils/localDate'
|
||||
import type { ExpensePrefill } from './CostsPanel'
|
||||
import type { BudgetItem } from '../../types'
|
||||
import type { CostsSettlement } from './costsModel'
|
||||
|
||||
// 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
|
||||
@@ -329,3 +330,24 @@ export function expenseEditorFor(
|
||||
if (receipt) return { key: 'receipt', editing: null, prefill: receipt, close: closeReceipt }
|
||||
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 }))
|
||||
}
|
||||
|
||||
@@ -944,13 +944,13 @@ describe('CostsPanel — overview', () => {
|
||||
expect(labels).toEqual(['Food & drink', 'Transport'])
|
||||
expect(within(breakdown).getByText('90 €')).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([])
|
||||
|
||||
expect(await screen.findByText('No expenses yet. Add your first one.')).toBeInTheDocument()
|
||||
expect(screen.getByText('No expenses yet.')).toBeInTheDocument()
|
||||
expect(await screen.findByText('No expenses yet. Add your first one.')).toBeInTheDocument();
|
||||
expect(screen.queryByRole('region', { name: 'Total trip spend' })).toBeNull();
|
||||
expect(screen.queryByRole('region', { name: 'By category' })).toBeNull();
|
||||
expect(screen.getByText("Everyone's square")).toBeInTheDocument()
|
||||
})
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ import { CustomDatePicker } from '../shared/CustomDateTimePicker'
|
||||
import { useReceiptScan } from './useReceiptScan'
|
||||
import { ReceiptScanModal } from './ReceiptScanModal'
|
||||
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 {
|
||||
baseTotal as baseTotalOf, booked as bookedAmount, isUnfinished as isUnfinishedModel, lineOf as lineOfModel, memberShareOf,
|
||||
@@ -52,12 +52,6 @@ interface CostsPanelProps {
|
||||
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 FIELD_H = 40 // shared height for the amount / currency / day row in the modal
|
||||
const COSTS_VIEW_KEY = 'trek:costs-view'
|
||||
@@ -66,6 +60,7 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
const { trip, budgetItems, deleteBudgetItem, loadBudgetItems, addBudgetItem, updateBudgetItem } = useTripStore()
|
||||
const can = useCanDo()
|
||||
const canEdit = can('budget_edit', trip)
|
||||
const hasExpenses = budgetItems.length > 0
|
||||
const receiptScan = useReceiptScan(tripId, canEdit)
|
||||
const toast = useToast()
|
||||
const { t, locale } = useTranslation()
|
||||
@@ -143,27 +138,12 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
// Nobody paid, so nobody owes (#2225).
|
||||
const myShareOf = (e: BudgetItem) => settledShareOf(e, ctx)
|
||||
|
||||
// ── day grouping ─────────────────────────────────────────────────────────
|
||||
const dayGroups = useMemo(() => {
|
||||
const entries: LedgerEntry[] = [
|
||||
...filtered.map(e => ({ kind: 'expense' as const, date: e.expense_date || '', e })),
|
||||
...filteredSettlements.map(s => ({ kind: 'payment' as const, date: settlementDate(s), s })),
|
||||
]
|
||||
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])
|
||||
const noDate = t('costs.noDate')
|
||||
const dayGroups = useMemo(() => groupLedgerByDay(filtered, filteredSettlements, locale, noDate), [filtered, filteredSettlements, locale, noDate])
|
||||
const emptyLedger = !hasExpenses && dayGroups.length === 0
|
||||
const mobileEmptyLedger = emptyLedger
|
||||
? <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>
|
||||
|
||||
// ── filter dropdown options (category + single day) ──────────────────────
|
||||
const categoryOptions = useMemo(() => [
|
||||
@@ -285,8 +265,8 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
}} />
|
||||
|
||||
{/* ── Summary cards; with nothing to split (#2689) the total stands alone ── */}
|
||||
{!splitting ? <div style={{ marginBottom: 36 }}>{totalCard}</div> : (
|
||||
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, minmax(0, 1fr))', gap: 16, marginBottom: 36 }} className="costs-summary">
|
||||
{!splitting ? (hasExpenses && <div style={{ marginBottom: 36 }}>{totalCard}</div>) : (
|
||||
<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}
|
||||
icon={<ArrowDown size={18} />} tone="owe" failed={settlementError}
|
||||
foot={totals.owe > 0.01
|
||||
@@ -302,18 +282,17 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
foot={totals.outstandingCount > 0
|
||||
? <span><b>{totals.outstandingCount}</b> {t('costs.outstandingItems', { count: totals.outstandingCount })}</span>
|
||||
: settledUp && <span className="text-content-faint">{t('costs.allSettled')}</span>} />
|
||||
{totalCard}
|
||||
{hasExpenses && totalCard}
|
||||
</div>)}
|
||||
|
||||
{/* ── Main grid ── */}
|
||||
{/* 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. */}
|
||||
<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: 'span 3', minWidth: 0 }}>
|
||||
<div className="costs-main" style={{ gridColumn: emptyLedger ? '1 / -1' : 'span 3', minWidth: 0 }}>
|
||||
|
||||
{dayBanner}
|
||||
{view === 'table' ? (
|
||||
{emptyLedger ? <EmptyState scene="costs" title={t('costs.emptyText')} /> : view === 'table' && hasExpenses ? (
|
||||
filtered.length === 0 && budgetItems.length > 0 ? (
|
||||
<div className="text-content-faint" style={{ textAlign: 'center', padding: '60px 20px' }}>{t('costs.noMatch')}</div>
|
||||
) : (
|
||||
@@ -379,14 +358,14 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
</>}
|
||||
|
||||
{/* 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} />
|
||||
) : (
|
||||
<section aria-label={t('costs.byCategory')} className={SIDE_CARD}>
|
||||
{sideHead(t('costs.byCategory'))}
|
||||
<div className="px-4 py-4">{categoryBars}</div>
|
||||
</section>
|
||||
)}
|
||||
))}
|
||||
<CostsModeCard trip={trip} memberCount={people.length} canEdit={canEdit} className={SIDE_CARD} />
|
||||
</div>
|
||||
</div>
|
||||
@@ -492,8 +471,7 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
function MobileBody() {
|
||||
return (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 16, paddingTop: 8 }}>
|
||||
{/* Total card */}
|
||||
<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)' }}>
|
||||
{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)' }}>
|
||||
<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>
|
||||
{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 +490,10 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
<ScanLine size={16} /> {t('costs.scan.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) */}
|
||||
{splitting && <>
|
||||
@@ -583,7 +564,7 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
</div>
|
||||
{dayBanner}
|
||||
{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 => {
|
||||
const dtot = g.entries.reduce((a, en) => en.kind === 'expense' ? a + baseTotal(en.e) : a, 0)
|
||||
return (
|
||||
@@ -610,11 +591,10 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
</div>
|
||||
</>}
|
||||
|
||||
{/* By category */}
|
||||
<div className={cardCls} style={{ borderRadius: 18, padding: 16 }}>
|
||||
{hasExpenses && <div className={cardCls} style={{ borderRadius: 18, padding: 16 }}>
|
||||
<div className={labelCls} style={{ marginBottom: 14 }}>{t('costs.byCategory')}</div>
|
||||
{categoryBars}
|
||||
</div>
|
||||
</div>}
|
||||
<CostsModeCard trip={trip} memberCount={people.length} canEdit={canEdit} className={`${cardCls} rounded-[18px]`} />
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { focusRevealedEditor } from '../shared/dialogFocus'
|
||||
import { useMemo, useRef, useState, type KeyboardEvent, type ReactNode } from 'react'
|
||||
import { ChevronDown, Lock, Pencil, Plus, Trash2 } from 'lucide-react'
|
||||
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) }
|
||||
}
|
||||
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))}
|
||||
className={`${INPUT} ${numeric ? 'text-center tabular-nums' : ''}`} />
|
||||
)
|
||||
|
||||
@@ -197,7 +197,7 @@ function FilterMenu(f: CostsFilterProps & { splitting: boolean }) {
|
||||
</button>
|
||||
</Tooltip>
|
||||
{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 && <>
|
||||
<div className="mx-1.5 mb-1 mt-1.5 flex rounded-[10px] bg-surface-tertiary p-[3px]">
|
||||
{owners.map(([o, label]) => (
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { focusRevealedEditor } from '../shared/dialogFocus'
|
||||
import { cloneElement, CSSProperties, FormEvent, ReactElement, useEffect, useId, useRef, useState } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { ExternalLink, Link2, Pencil, Pin, Plus, Trash2, X } from 'lucide-react'
|
||||
@@ -147,7 +148,7 @@ function LinkModal({ link, onClose, onSave }: { link?: CollabLink; onClose: () =
|
||||
<div style={{ padding: '14px 16px 16px', display: 'flex', flexDirection: 'column', gap: 12 }}>
|
||||
<div>
|
||||
<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>
|
||||
<label htmlFor="collab-link-url" style={{ ...label, display: 'block' }}>{t('collab.links.urlPlaceholder')}</label>
|
||||
|
||||
@@ -118,7 +118,7 @@ function CreatePollModal({ onClose, onCreate, t }: CreatePollModalProps) {
|
||||
)}
|
||||
>
|
||||
<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 label={t('collab.polls.options')}>
|
||||
|
||||
@@ -102,7 +102,6 @@ export default function AddPlaceToCollectionModal({ isOpen, collectionId, collec
|
||||
<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" />
|
||||
<input
|
||||
autoFocus
|
||||
data-initial-focus
|
||||
ref={searchRef}
|
||||
type="text"
|
||||
|
||||
@@ -136,6 +136,7 @@ export default function CollectionExportMenu({ onExport, exporting, t }: Collect
|
||||
ref={menuRef}
|
||||
id={menuId}
|
||||
role="menu"
|
||||
tabIndex={-1}
|
||||
aria-label={t('collections.file.exportTitle')}
|
||||
onKeyDown={onMenuKeyDown}
|
||||
className="trek-popover-enter fixed z-[var(--z-toast)] p-1.5 rounded-xl border border-edge bg-surface-card shadow-dropdown"
|
||||
|
||||
@@ -25,6 +25,7 @@ import { placesPath } from '../../utils/placesRoutes';
|
||||
import MarkdownToolbar from '../Journey/MarkdownToolbar';
|
||||
import { getNavigationTargets, navigationTargetLabel, openNavigationTarget } from '../Planner/placeNavigation';
|
||||
import { getCategoryIcon } from '../shared/categoryIcons';
|
||||
import { focusRevealedEditor } from '../shared/dialogFocus';
|
||||
import { DialogShell } from '../shared/DialogShell';
|
||||
import { markdownLinkComponents } from '../shared/markdownLink';
|
||||
import { NavigationMenu } from '../shared/NavigationMenu';
|
||||
@@ -202,7 +203,7 @@ function Cover({
|
||||
value={form.name}
|
||||
onChange={(e) => form.setName(e.target.value)}
|
||||
className="col-detail-name-input min-w-0 flex-1"
|
||||
autoFocus
|
||||
ref={focusRevealedEditor}
|
||||
aria-label={t('common.name')}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -55,7 +55,7 @@ export default function CopyToTripModal({ isOpen, onClose, placeIds, onCopy, car
|
||||
<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" />
|
||||
<input
|
||||
autoFocus
|
||||
data-initial-focus
|
||||
value={search}
|
||||
onChange={e => setSearch(e.target.value)}
|
||||
placeholder={t('collections.copyToTripSearch')}
|
||||
|
||||
@@ -257,9 +257,14 @@ describe('ListEditorModal', () => {
|
||||
fireEvent.click(screen.getByRole('button', { name: /Search Unsplash/ }))
|
||||
|
||||
expect(await screen.findByRole('button', { name: 'Rin' })).toBeInTheDocument()
|
||||
expect(screen.getByAltText('A street')).toHaveAttribute('title', 'A street')
|
||||
expect(tripsApi.searchCoverImages).toHaveBeenCalledWith('fjord')
|
||||
// A photo without a photographer falls back to the generic label.
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Unsplash' }))
|
||||
const photo = screen.getByRole('button', { name: 'Unsplash' })
|
||||
const thumb = photo.querySelector('img')
|
||||
expect(thumb).toHaveAttribute('alt', '')
|
||||
expect(thumb).not.toHaveAttribute('title')
|
||||
fireEvent.click(photo)
|
||||
expect(document.querySelector('img[src="https://img/full2.jpg"]')).toBeTruthy()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Create' }))
|
||||
|
||||
@@ -126,7 +126,13 @@ export default function ListEditorModal({ target, onClose, onCreated, onRequestD
|
||||
aria-pressed={on}
|
||||
className={`relative h-20 overflow-hidden rounded-[10px] transition-shadow ${on ? 'ring-2 ring-accent' : 'ring-1 ring-edge-faint hover:ring-content-faint'}`}
|
||||
>
|
||||
<img src={photo.thumb} alt={photo.description || ''} loading="lazy" className="h-full w-full object-cover" />
|
||||
<img
|
||||
src={photo.thumb}
|
||||
alt={photo.description || ''}
|
||||
title={photo.description || undefined}
|
||||
loading="lazy"
|
||||
className="h-full w-full object-cover"
|
||||
/>
|
||||
{photo.photographer && <span className={PHOTO_CREDIT} style={fs(10)}>{photo.photographer}</span>}
|
||||
</button>
|
||||
)
|
||||
|
||||
@@ -153,4 +153,9 @@ describe('ListsRail', () => {
|
||||
renderRail({ onSelectLibrary: vi.fn(), libraryCount: null });
|
||||
expect(screen.getByRole('button', { name: /All places/ })).toHaveTextContent(/^All places$/);
|
||||
});
|
||||
|
||||
it('hides All places when the library is known to be empty', () => {
|
||||
renderRail({ onSelectLibrary: vi.fn(), libraryCount: 0 });
|
||||
expect(screen.queryByRole('button', { name: /All places/ })).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -75,7 +75,7 @@ export default function ListsRail(props: ListsRailProps): React.ReactElement {
|
||||
</Tooltip>
|
||||
</div>
|
||||
|
||||
{onSelectLibrary && (
|
||||
{onSelectLibrary && libraryCount !== 0 && (
|
||||
<div className="col-row">
|
||||
<button type="button" onClick={onSelectLibrary} className={`col-row-btn${libraryActive ? ' on' : ''}`} aria-current={libraryActive ? 'page' : undefined}>
|
||||
<span className="ico tile"><Globe2 size={15} /></span>
|
||||
|
||||
@@ -67,7 +67,7 @@ export default function MoveToListModal({ mode, lists, count, onPick, onClose, t
|
||||
<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" />
|
||||
<input
|
||||
autoFocus
|
||||
data-initial-focus
|
||||
value={search}
|
||||
onChange={e => setSearch(e.target.value)}
|
||||
placeholder={t('collections.searchLists')}
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import type { PlacesLibraryDetailResponse } from '@trek/shared';
|
||||
import { Bookmark, Eye, Layers, Luggage, NotebookPen, Pencil, PenLine } from 'lucide-react';
|
||||
import React, { useRef } from 'react';
|
||||
import React, { useCallback, useRef } from 'react';
|
||||
import Markdown from 'react-markdown';
|
||||
import remarkBreaks from 'remark-breaks';
|
||||
import remarkGfm from 'remark-gfm';
|
||||
import type { TranslationFn } from '../../types';
|
||||
import MarkdownToolbar from '../Journey/MarkdownToolbar';
|
||||
import { focusRevealedEditor } from '../shared/dialogFocus';
|
||||
import { markdownLinkComponents } from '../shared/markdownLink';
|
||||
import { Tooltip } from '../shared/Tooltip';
|
||||
import PlaceCard from './PlaceCard';
|
||||
@@ -51,6 +52,10 @@ function NoteCard({ note, n, t }: { note: OriginNote; n: Notes; t: TranslationFn
|
||||
*/
|
||||
function NoteEditor({ n, t }: { n: Notes; t: TranslationFn }) {
|
||||
const ref = useRef<HTMLTextAreaElement>(null);
|
||||
const attachEditor = useCallback((element: HTMLTextAreaElement | null) => {
|
||||
ref.current = element;
|
||||
focusRevealedEditor(element);
|
||||
}, []);
|
||||
const current = n.composeTargets.find((x) => x.key === n.editing) ?? n.notes.find((x) => x.key === n.editing);
|
||||
const multi = n.isNew && n.composeTargets.length > 1;
|
||||
return (
|
||||
@@ -111,8 +116,7 @@ function NoteEditor({ n, t }: { n: Notes; t: TranslationFn }) {
|
||||
</div>
|
||||
) : (
|
||||
<textarea
|
||||
ref={ref}
|
||||
autoFocus
|
||||
ref={attachEditor}
|
||||
rows={6}
|
||||
value={n.draft}
|
||||
onChange={(e) => n.setDraft(e.target.value)}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { MapPin } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import type { Category, TranslationFn } from '../../types';
|
||||
import { focusRevealedEditor } from '../shared/dialogFocus';
|
||||
import { NumericInput } from '../shared/NumericInput';
|
||||
import CategoryTileMenu from './CategoryTileMenu';
|
||||
import type { PlaceEditState } from './usePlaceEdit';
|
||||
@@ -36,7 +37,7 @@ export default function PlaceEditForm({
|
||||
/>
|
||||
)}
|
||||
<input
|
||||
autoFocus
|
||||
ref={focusRevealedEditor}
|
||||
value={draft.name}
|
||||
onChange={(e) => edit.set('name', e.target.value)}
|
||||
aria-label={t('common.name')}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Bookmark, Check, Luggage, Plus, Search, Tag, X } from 'lucide-react';
|
||||
import React, { useEffect, useRef } from 'react';
|
||||
import type { TranslationFn } from '../../types';
|
||||
import { focusRevealedEditor } from '../shared/dialogFocus';
|
||||
import PlaceCard from './PlaceCard';
|
||||
import type { PlaceTagsState, TagGroup } from './usePlaceTags';
|
||||
|
||||
@@ -38,7 +39,7 @@ function TagPicker({ tags, group, t }: { tags: PlaceTagsState; group: TagGroup;
|
||||
>
|
||||
<Search size={14} aria-hidden="true" />
|
||||
<input
|
||||
autoFocus
|
||||
ref={focusRevealedEditor}
|
||||
value={tags.query}
|
||||
onChange={(e) => tags.setQuery(e.target.value)}
|
||||
placeholder={t('placeTags.search')}
|
||||
|
||||
@@ -55,7 +55,7 @@ export default function SaveTripPlacesToListModal({ isOpen, tripId, placeIds, on
|
||||
<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" />
|
||||
<input
|
||||
autoFocus
|
||||
data-initial-focus
|
||||
value={search}
|
||||
onChange={e => setSearch(e.target.value)}
|
||||
placeholder={t('collections.searchLists')}
|
||||
|
||||
@@ -8,7 +8,9 @@ import { getApiErrorMessage } from '../../utils/apiError';
|
||||
import { useToast } from '../shared/Toast';
|
||||
|
||||
/** A pair's own name: its two keys in a fixed order, so either way round it is one pair. */
|
||||
export const pairKey = (d: Pick<PlacesLibraryDuplicate, 'a' | 'b'>): string => [d.a.key, d.b.key].sort().join('|');
|
||||
export function pairKey({ a, b }: Pick<PlacesLibraryDuplicate, 'a' | 'b'>): string {
|
||||
return a.key <= b.key ? `${a.key}|${b.key}` : `${b.key}|${a.key}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Places that look like the same place (PLC-13), behind the desktop dialog and the
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { ArrowLeft, ArrowRight, Clock, ExternalLink, Images, RotateCcw } from 'lucide-react';
|
||||
import { lazy, Suspense, useId } from 'react';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { focusRevealedEditor } from '../shared/dialogFocus';
|
||||
import {
|
||||
DialogButton,
|
||||
DialogFooter,
|
||||
@@ -116,7 +117,7 @@ function FooterLinks({ t, onCredits, focusCredits }: { t: Translate; onCredits:
|
||||
<button
|
||||
type="button"
|
||||
onClick={onCredits}
|
||||
autoFocus={focusCredits}
|
||||
ref={focusCredits ? focusRevealedEditor : undefined}
|
||||
className={FOOTER_LINK}
|
||||
style={fs(12.5, 'body')}
|
||||
>
|
||||
|
||||
@@ -106,17 +106,17 @@ export default function DocSyncConnectModal({
|
||||
</Field>
|
||||
))}
|
||||
|
||||
<label className="flex items-start justify-between gap-4 rounded-lg border border-edge bg-surface-secondary px-3 py-2.5">
|
||||
<div className="flex items-start justify-between gap-4 rounded-lg border border-edge bg-surface-secondary px-3 py-2.5">
|
||||
<span className="min-w-0">
|
||||
<span className="block text-body text-content">{t('docsync.allowInsecureTls')}</span>
|
||||
<span className="mt-0.5 block text-caption text-content-muted">
|
||||
<span id={`${labelId}-tls-hint`} className="mt-0.5 block text-caption text-content-muted">
|
||||
{t('docsync.connect.insecureHint')}
|
||||
</span>
|
||||
</span>
|
||||
<span className="shrink-0 pt-0.5">
|
||||
<ToggleSwitch on={form.insecureTls} onToggle={() => form.setInsecureTls(!form.insecureTls)} />
|
||||
<ToggleSwitch on={form.insecureTls} onToggle={() => form.setInsecureTls(!form.insecureTls)} label={t('docsync.allowInsecureTls')} describedBy={`${labelId}-tls-hint`} />
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ConfirmDialog
|
||||
|
||||
@@ -206,7 +206,7 @@ export default function ContributorInviteDialog({ journeyId, existingUserIds, on
|
||||
<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" />
|
||||
<input
|
||||
autoFocus
|
||||
data-initial-focus
|
||||
value={search}
|
||||
onChange={e => setSearch(e.target.value)}
|
||||
placeholder={t('journey.contributors.searchPlaceholder')}
|
||||
|
||||
@@ -51,7 +51,7 @@ export function AddTripDialog({ journeyId, existingTripIds, onClose, onAdded }:
|
||||
<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" />
|
||||
<input
|
||||
autoFocus
|
||||
data-initial-focus
|
||||
value={search}
|
||||
onChange={e => setSearch(e.target.value)}
|
||||
placeholder={t('journey.trips.searchPlaceholder')}
|
||||
|
||||
@@ -113,9 +113,9 @@ describe('MobileEntryView', () => {
|
||||
const order: string[] = []
|
||||
const onClose = vi.fn(() => { order.push('close') })
|
||||
const onDelete = vi.fn(() => { order.push('delete') })
|
||||
const { container } = renderView(buildEntry(), { onClose, onDelete })
|
||||
renderView(buildEntry(), { onClose, onDelete })
|
||||
|
||||
fireEvent.click(container.querySelector('svg.lucide-trash2')!.closest('button')!)
|
||||
fireEvent.click(screen.getByRole('button', { name: /Delete/ }))
|
||||
|
||||
expect(order).toEqual(['close', 'delete'])
|
||||
})
|
||||
@@ -123,7 +123,7 @@ describe('MobileEntryView', () => {
|
||||
it('FE-COMP-JENTRYVIEW-006: read-only journeys hide the edit and delete actions', () => {
|
||||
const { container } = renderView(buildEntry(), { readOnly: true })
|
||||
expect(screen.queryByRole('button', { name: /Edit/ })).not.toBeInTheDocument()
|
||||
expect(container.querySelector('svg.lucide-trash2')).toBeNull()
|
||||
expect(screen.queryByRole('button', { name: /Delete/ })).not.toBeInTheDocument()
|
||||
// the close button stays
|
||||
expect(container.querySelector('svg.lucide-x')).not.toBeNull()
|
||||
})
|
||||
|
||||
@@ -104,6 +104,7 @@ export default function MobileEntryView({ entry, readOnly, publicPhotoUrl, onClo
|
||||
</button>
|
||||
<button type="button"
|
||||
onClick={() => { onClose(); onDelete(); }}
|
||||
aria-label={t('common.delete')}
|
||||
className="w-8 h-8 rounded-lg flex items-center justify-center text-zinc-400 hover:bg-red-50 hover:text-red-500 dark:hover:bg-red-900/20 dark:hover:text-red-400 transition-colors"
|
||||
>
|
||||
<Trash2 size={15} />
|
||||
|
||||
@@ -145,6 +145,53 @@ async function renderMap() {
|
||||
}
|
||||
|
||||
describe('MapView on a real Leaflet map', () => {
|
||||
it('reveals the selected stop inside an island-wide cluster (#3306)', async () => {
|
||||
const island = Array.from({ length: 29 }, (_, index) => ({
|
||||
// The later stops form a second cluster still too large to fan open at street level.
|
||||
...buildPlace({ id: 33060 + index, name: `Mahé stop ${index}` }),
|
||||
lat: -4.62,
|
||||
lng: index < 15 ? 55.44 + index * 0.001 : 55.447 + (index - 14) * 0.00001,
|
||||
category_name: null, category_color: null, category_icon: null,
|
||||
}))
|
||||
const selected = island[7]
|
||||
const view = render(<MapView places={island} center={[-4.62, 55.44]} zoom={8} tileUrl={RASTER} />)
|
||||
const map = maps[maps.length - 1]
|
||||
view.rerender(<MapView places={island} dayPlaces={island} fitKey={1} center={[-4.62, 55.44]} zoom={8} tileUrl={RASTER} />)
|
||||
act(() => { map.setView([-4.62, 55.44], 8, { animate: false }) })
|
||||
await waitFor(() => expect(view.container.querySelector('.marker-cluster-wrapper')).not.toBeNull())
|
||||
expect(view.container.querySelector(`[data-place-name="${selected.name}"]`)).toBeNull()
|
||||
function expectSelectedPin(place: typeof selected) {
|
||||
let selectedPin: HTMLElement | null | undefined
|
||||
map.eachLayer(layer => {
|
||||
if (layer instanceof L.Marker && layer.options.zIndexOffset === 1000 &&
|
||||
layer.getLatLng().equals([place.lat, place.lng])) selectedPin = layer.getElement()
|
||||
})
|
||||
expect(selectedPin).toBeInstanceOf(HTMLElement)
|
||||
}
|
||||
|
||||
view.rerender(<MapView places={island} dayPlaces={island} fitKey={1} center={[-4.62, 55.44]} zoom={8} tileUrl={RASTER}
|
||||
selectedPlaceId={selected.id} hasInspector inspectorHeight={360} />)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(map.getZoom()).toBe(16)
|
||||
expectSelectedPin(selected)
|
||||
expect(view.container.querySelector('.marker-cluster-wrapper')?.textContent).toBe('14')
|
||||
expect(map.latLngToContainerPoint([selected.lat, selected.lng]).y).toBeLessThan(280)
|
||||
})
|
||||
|
||||
// The day's route can finish loading after the user chose a stop from the itinerary.
|
||||
view.rerender(<MapView places={island} dayPlaces={island} fitKey={1} center={[-4.62, 55.44]} zoom={8} tileUrl={RASTER}
|
||||
route={[[[-4.8, 55.5]], [[-4.9, 55.3]]]} selectedPlaceId={selected.id} hasInspector inspectorHeight={360} />)
|
||||
expect(map.getZoom()).toBe(16)
|
||||
|
||||
// At street zoom a switch to an offscreen place pans, with no zoom event to reveal it.
|
||||
await act(() => { map.setView([-4.7, 55.4], 16, { animate: false }) })
|
||||
const next = island[15]
|
||||
view.rerender(<MapView places={island} dayPlaces={island} fitKey={1} center={[-4.62, 55.44]} zoom={8} tileUrl={RASTER}
|
||||
selectedPlaceId={next.id} hasInspector inspectorHeight={360} />)
|
||||
await waitFor(() => expectSelectedPin(next))
|
||||
})
|
||||
|
||||
it('RC-08: previews waypoint drags locally and commits only at pointer up without panning', async () => {
|
||||
const waypoint = { id: 'via-1', lat: 34.689, lng: 135.8398, role: 'via' as const }
|
||||
const waypoints = [waypoint]
|
||||
|
||||
@@ -1282,6 +1282,9 @@ describe('MapView track casing pane (#776)', () => {
|
||||
})
|
||||
|
||||
describe('MapView selection panning (#921)', () => {
|
||||
beforeEach(() => { mapMock.getZoom.mockReturnValue(17) })
|
||||
afterEach(() => { mapMock.getZoom.mockReturnValue(10) })
|
||||
|
||||
it('FE-COMP-MAPVIEW-051: pans to the padding-corrected point when the map can project', () => {
|
||||
const projectable = mapMock as unknown as Record<string, unknown>
|
||||
const add = vi.fn(() => ({ x: 5, y: 6 }))
|
||||
@@ -1292,7 +1295,7 @@ describe('MapView selection panning (#921)', () => {
|
||||
const { rerender } = render(<MapView places={places} selectedPlaceId={null} />)
|
||||
rerender(<MapView places={places} selectedPlaceId={8} />)
|
||||
|
||||
expect(projectable.project).toHaveBeenCalledWith([48, 2])
|
||||
expect(projectable.project).toHaveBeenCalledWith([48, 2], 17)
|
||||
// The offset is half the difference between the two padding corners.
|
||||
expect(add).toHaveBeenCalledWith([0, 0])
|
||||
expect(mapMock.panTo).toHaveBeenCalledWith([49, 4], { animate: true })
|
||||
@@ -1816,14 +1819,12 @@ describe('MapView — picking a stop that shares its coordinates', () => {
|
||||
expect(clusterMock.asked).not.toContain(markerOf(1))
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPVIEW-078: a stop with a pin of its own is left alone, camera included', () => {
|
||||
it('FE-COMP-MAPVIEW-078: focuses a stop with a pin of its own without opening a cluster', () => {
|
||||
clusterMock.stacked = false
|
||||
const { rerender } = render(<MapView places={stacked} />)
|
||||
rerender(<MapView places={stacked} selectedPlaceId={1} />)
|
||||
|
||||
expect(clusterMock.spiderfy).not.toHaveBeenCalled()
|
||||
// The selection still only pans: the zoom belongs to the day fit.
|
||||
expect(mapMock.panTo).toHaveBeenCalled()
|
||||
expect(mapMock.setView).not.toHaveBeenCalled()
|
||||
expect(mapMock.setView).toHaveBeenCalledWith([hotel.lat, hotel.lng], 16, { animate: false })
|
||||
})
|
||||
})
|
||||
|
||||
@@ -6,7 +6,8 @@ import ContainerResizeWatcher, { MapCameraSnapshot, OpeningFrameFit } from './Co
|
||||
import { openingView } from './openingView'
|
||||
import MarkerClusterGroup from 'react-leaflet-cluster'
|
||||
import { makeMarkerDraggable } from './markerDrag'
|
||||
import { CLUSTER_OPTIONS, createClusterIcon, revealInCluster, type ClusterGroupLike } from './markerCluster'
|
||||
import { CLUSTER_OPTIONS, createClusterIcon } from './markerCluster'
|
||||
import { useLeafletClusterSelection } from './useLeafletClusterSelection'
|
||||
import RoadtripViaMarkers from './RoadtripViaMarkers'
|
||||
import PlannerWaypointMarker from './PlannerWaypointMarker'
|
||||
import HazardLayers from './HazardLayers'
|
||||
@@ -268,6 +269,7 @@ interface BoundsControllerProps extends Pick<MapViewProps, 'focusPoints' | 'focu
|
||||
framedOnMount?: boolean
|
||||
/** False while the map is locked (#2010): an arriving route no longer re-fits it. */
|
||||
follow?: boolean
|
||||
selectedPlaceId: number | null
|
||||
}
|
||||
|
||||
/** A padding box as Leaflet's fit options spell it, corner pairs rather than edges. */
|
||||
@@ -278,7 +280,8 @@ function leafletPadding(box: ViewportPadding): L.FitBoundsOptions {
|
||||
}
|
||||
}
|
||||
|
||||
function BoundsController({ places, routeCoords, fitKey, paddingOpts, framedOnMount = false, focusPoints, focusKey, fitPadding, follow = true }: BoundsControllerProps) {
|
||||
function BoundsController({ places, routeCoords, fitKey, paddingOpts, framedOnMount = false,
|
||||
focusPoints, focusKey, fitPadding, follow = true, selectedPlaceId }: BoundsControllerProps) {
|
||||
const map = useMap()
|
||||
const prevFitKey = useRef(-1)
|
||||
const awaitingRoute = useRef(false)
|
||||
@@ -332,6 +335,11 @@ function BoundsController({ places, routeCoords, fitKey, paddingOpts, framedOnMo
|
||||
awaitingRoute.current = true
|
||||
}, [fitKey]) // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
// An explicit stop selection supersedes the pending automatic route fit.
|
||||
useEffect(() => {
|
||||
if (follow && selectedPlaceId != null) awaitingRoute.current = false
|
||||
}, [selectedPlaceId, follow])
|
||||
|
||||
// Once the just-selected day's route is ready, expand the fit to include it.
|
||||
// One-shot per day-fit, so later route-profile toggles don't re-zoom the map.
|
||||
useEffect(() => {
|
||||
@@ -513,7 +521,7 @@ interface MemoMarkerProps {
|
||||
/** Off in read-only trips and on the phone, where HTML5 drag does not exist. */
|
||||
draggable: boolean
|
||||
/** Hands the Leaflet marker up, so a selection can find the bubble it is hiding in. */
|
||||
onRegister: (id: number, marker: unknown) => void
|
||||
onRegister: (id: number, marker: L.Marker | null) => void
|
||||
}
|
||||
|
||||
const MemoMarker = memo(function MemoMarker({
|
||||
@@ -528,7 +536,7 @@ const MemoMarker = memo(function MemoMarker({
|
||||
// every render the marker took part in.
|
||||
const frame = useLngFrame()
|
||||
const position = useMemo<[number, number]>(() => [place.lat, frameLng(frame, place.lng)], [place.lat, place.lng, frame])
|
||||
const register = useCallback((marker: unknown) => { onRegister(place.id, marker) }, [onRegister, place.id])
|
||||
const register = useCallback((marker: L.Marker | null) => { onRegister(place.id, marker) }, [onRegister, place.id])
|
||||
return (
|
||||
<Marker
|
||||
ref={register}
|
||||
@@ -753,39 +761,9 @@ export const MapView = memo(function MapView({
|
||||
// HTML5 drag does not exist — and the day plan is not on screen there anyway.
|
||||
const markersDraggable = !isTouchDevice && !assistant.markersLocked
|
||||
|
||||
/**
|
||||
* Reaching a stop that shares its coordinates with others.
|
||||
*
|
||||
* Such a stop has no pin of its own while the stack is collapsed — it is inside a
|
||||
* cluster bubble — so the z-index that used to lift the selected pin out of the pile
|
||||
* has nothing to lift. Fan the bubble open instead, which leaves the camera alone
|
||||
* (#2344). The registry is what lets a selection find its Leaflet marker at all.
|
||||
*/
|
||||
const clusterGroupRef = useRef<ClusterGroupLike | null>(null)
|
||||
const placeMarkersRef = useRef(new Map<number, unknown>())
|
||||
const registerClusterGroup = useCallback((group: unknown) => {
|
||||
clusterGroupRef.current = (group as ClusterGroupLike | null) ?? null
|
||||
}, [])
|
||||
const registerMarker = useCallback((id: number, marker: unknown) => {
|
||||
if (marker) placeMarkersRef.current.set(id, marker)
|
||||
else placeMarkersRef.current.delete(id)
|
||||
}, [])
|
||||
const assistantMarkerEl = useCallback((id: number) => (placeMarkersRef.current.get(id) as L.Marker | undefined)?.getElement() ?? null, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedPlaceId == null) return
|
||||
let frame: number | null = null
|
||||
const reveal = () => {
|
||||
frame = null
|
||||
revealInCluster(clusterGroupRef.current, placeMarkersRef.current.get(selectedPlaceId))
|
||||
}
|
||||
reveal()
|
||||
// The group takes its markers in on a microtask and adds them in chunks, so a
|
||||
// selection that arrives with the map — a link straight into a day — finds nothing
|
||||
// on the first pass. A second attempt one frame later does.
|
||||
if (typeof requestAnimationFrame === 'function') frame = requestAnimationFrame(reveal)
|
||||
return () => { if (frame !== null) cancelAnimationFrame(frame) }
|
||||
}, [selectedPlaceId, places])
|
||||
const { registerClusterGroup, registerMarker, markerElement: assistantMarkerEl, standalonePlaceId, revealSelectedPlace } =
|
||||
useLeafletClusterSelection(selectedPlaceId, places, mapZoom, followSelection)
|
||||
const standaloneIndex = standalonePlaceId == null ? -1 : places.findIndex(place => place.id === standalonePlaceId)
|
||||
|
||||
const markers = useMemo(() => places.map((place) => {
|
||||
const isSelected = place.id === selectedPlaceId
|
||||
@@ -930,8 +908,9 @@ export const MapView = memo(function MapView({
|
||||
<ContainerResizeWatcher />
|
||||
{initialView.refit && <OpeningFrameFit frame={initialView.refit} />}
|
||||
{hasViewBaseLayer && <MapCameraSnapshot onChange={saveCameraSnapshot} />}
|
||||
<BoundsController places={dayPlaces.length > 0 ? dayPlaces : places} routeCoords={dayPlaces.length > 0 ? routeCoords : []} fitKey={fitKey} paddingOpts={paddingOpts} framedOnMount={initialView.framed} focusPoints={focusPoints} focusKey={focusKey} fitPadding={fitPadding} follow={followSelection} />
|
||||
<SelectionController follow={followSelection} places={places} selectedPlaceId={selectedPlaceId} dayPlaces={dayPlaces} selectedPlace={selectedPlace} paddingBox={paddingBox} />
|
||||
<BoundsController places={dayPlaces.length > 0 ? dayPlaces : places} routeCoords={dayPlaces.length > 0 ? routeCoords : []} fitKey={fitKey} paddingOpts={paddingOpts} framedOnMount={initialView.framed} focusPoints={focusPoints} focusKey={focusKey} fitPadding={fitPadding} follow={followSelection} selectedPlaceId={selectedPlaceId} />
|
||||
<SelectionController follow={followSelection} places={places} selectedPlaceId={selectedPlaceId} dayPlaces={dayPlaces}
|
||||
selectedPlace={selectedPlace} paddingBox={paddingBox} revealSelectedPlace={revealSelectedPlace} />
|
||||
<MapClickHandler onClick={onMapClick} />
|
||||
<MapContextMenuHandler onContextMenu={onMapContextMenu} />
|
||||
<CameraHoverGuard movingRef={mapMovingRef} onMoveStart={clearHover} onZoom={setMapZoom} />
|
||||
@@ -941,8 +920,9 @@ export const MapView = memo(function MapView({
|
||||
<LeafletLocationLayer position={userPosition} mode={trackingMode} />
|
||||
|
||||
<MarkerClusterGroup ref={registerClusterGroup} {...CLUSTER_OPTIONS} iconCreateFunction={createClusterIcon}>
|
||||
{markers}
|
||||
{standaloneIndex < 0 ? markers : markers.filter((_, index) => index !== standaloneIndex)}
|
||||
</MarkerClusterGroup>
|
||||
{markers[standaloneIndex]}
|
||||
|
||||
{/* Apple-Maps style: darker-blue casing under a bright-blue core, rounded.
|
||||
When the route can be reshaped an invisible band wider than both takes the click. */}
|
||||
|
||||
@@ -2279,7 +2279,7 @@ describe('MapViewGL', () => {
|
||||
|
||||
rerender(<MapViewGL places={[broken]} dayPlaces={[dayPlace]} fitKey={1} selectedPlaceId={101} />)
|
||||
await act(async () => {})
|
||||
expect(glMap.flyTo).toHaveBeenCalledWith(expect.objectContaining({ center: [139.69, 35.68], zoom: 14 }))
|
||||
expect(glMap.flyTo).toHaveBeenCalledWith(expect.objectContaining({ center: [139.69, 35.68], zoom: 16 }))
|
||||
|
||||
glMap.flyTo.mockClear()
|
||||
rerender(<MapViewGL places={[broken]} dayPlaces={[dayPlace]} fitKey={1} selectedPlaceId={102} />)
|
||||
|
||||
@@ -1818,7 +1818,6 @@ export function MapViewGL({
|
||||
// The trip's flights in the air, as on the Leaflet map.
|
||||
useFlightAircraftGL(mapRef, mapReady, gl?.Marker, id => onReservationClickRef.current?.(id), reservations)
|
||||
|
||||
// Fit bounds on fitKey change — matches the Leaflet BoundsController
|
||||
const paddingOpts = useMemo(() => {
|
||||
if (isMobile) return { top: 40, right: 20, bottom: 40, left: 20 }
|
||||
const top = 60
|
||||
@@ -1843,9 +1842,7 @@ export function MapViewGL({
|
||||
const map = mapRef.current
|
||||
if (!map) return
|
||||
|
||||
// The map was built framed on these very places, so fitting now would only re-do that —
|
||||
// and its maxZoom would overrule the gentler zoom a single place opens at. Adopt the
|
||||
// current fitKey and stand down; every later fit (picking a day) still runs.
|
||||
// Keep the opening frame, including its gentler single-place zoom. Later day fits still run.
|
||||
if (!fitRanRef.current && framedOnMountRef.current) {
|
||||
fitRanRef.current = true
|
||||
prevFitKey.current = fitKey
|
||||
@@ -1916,6 +1913,9 @@ export function MapViewGL({
|
||||
} catch { /* noop */ }
|
||||
}, [focusPoints, focusKey, fitPaddingKey]) // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
useEffect(() => {
|
||||
if (followSelection && selectedPlaceId != null) pendingRouteFitRef.current = null
|
||||
}, [selectedPlaceId, followSelection])
|
||||
useSelectionCameraGL({
|
||||
mapRef, selectedPlaceId, places, dayPlaces, selectedPlace,
|
||||
follow: followSelection, padding: paddingOpts, enableMapbox3d,
|
||||
|
||||
@@ -6,7 +6,7 @@ import { frameLng } from '../../utils/lngFrame';
|
||||
import type { ViewportPadding } from '../../utils/mapViewport';
|
||||
import { useLngFrame } from './lngFrameContext';
|
||||
import { isUnderChrome } from './mapChromePadding';
|
||||
import { selectedPlaceTarget } from './selectedPlaceTarget';
|
||||
import { PLACE_FOCUS_ZOOM, selectedPlaceTarget } from './selectedPlaceTarget';
|
||||
|
||||
interface SelectionControllerProps {
|
||||
/** False while the traveller locked the map (#2010): a pick changes nothing on it. */
|
||||
@@ -16,6 +16,7 @@ interface SelectionControllerProps {
|
||||
dayPlaces: Place[];
|
||||
selectedPlace: Place | null;
|
||||
paddingBox: ViewportPadding;
|
||||
revealSelectedPlace: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -29,6 +30,7 @@ export function SelectionController({
|
||||
dayPlaces,
|
||||
selectedPlace,
|
||||
paddingBox,
|
||||
revealSelectedPlace,
|
||||
}: SelectionControllerProps) {
|
||||
const map = useMap();
|
||||
const frame = useLngFrame();
|
||||
@@ -39,12 +41,33 @@ export function SelectionController({
|
||||
const lat = target?.lat ?? null;
|
||||
const lng = target?.lng == null ? null : frameLng(frame, target.lng);
|
||||
|
||||
useEffect(() => {
|
||||
if (!follow || selectedPlaceId == null) return;
|
||||
let frame: number | null = null;
|
||||
const revealAfterMove = () => {
|
||||
if (frame !== null) cancelAnimationFrame(frame);
|
||||
frame = requestAnimationFrame(() => revealSelectedPlace());
|
||||
};
|
||||
map.on('moveend', revealAfterMove);
|
||||
return () => {
|
||||
map.off('moveend', revealAfterMove);
|
||||
if (frame !== null) cancelAnimationFrame(frame);
|
||||
};
|
||||
}, [map, follow, selectedPlaceId, revealSelectedPlace]);
|
||||
|
||||
useEffect(() => {
|
||||
const isNew = selectedPlaceId !== prev.current;
|
||||
prev.current = selectedPlaceId;
|
||||
if (!isNew || !follow || !selectedPlaceId || lat == null || lng == null) return;
|
||||
pannedWith.current = paddingBox;
|
||||
panToPlace(map, [lat, lng], paddingBox);
|
||||
const zoom = map.getZoom();
|
||||
const focusZoom = Math.max(zoom, PLACE_FOCUS_ZOOM);
|
||||
const center = paddedCenter(map, [lat, lng], paddingBox, focusZoom);
|
||||
if (zoom < focusZoom) {
|
||||
map.setView(center, focusZoom, { animate: false });
|
||||
} else {
|
||||
map.panTo(center, { animate: true });
|
||||
}
|
||||
}, [selectedPlaceId, follow, lat, lng, map, paddingBox]);
|
||||
|
||||
// The place card only learns its height after it laid out, and grows again when its
|
||||
@@ -56,7 +79,7 @@ export function SelectionController({
|
||||
if (!follow || !selectedPlaceId || lat == null || lng == null) return;
|
||||
if (typeof map.latLngToContainerPoint !== 'function') return;
|
||||
if (isUnderChrome(map.latLngToContainerPoint([lat, lng]), map.getSize(), paddingBox)) {
|
||||
panToPlace(map, [lat, lng], paddingBox);
|
||||
map.panTo(paddedCenter(map, [lat, lng], paddingBox, map.getZoom()), { animate: true });
|
||||
}
|
||||
}, [paddingBox, follow, selectedPlaceId, lat, lng, map]);
|
||||
|
||||
@@ -64,16 +87,19 @@ export function SelectionController({
|
||||
}
|
||||
|
||||
/**
|
||||
* Pan to a place without changing zoom. The centre is offset by the side panels and the
|
||||
* bottom card, so the pin lands in the middle of the *visible* map area rather than the
|
||||
* geometric centre, where the card would cover it.
|
||||
* Offset the centre at the destination zoom so the pin lands in the middle of the
|
||||
* visible map area, above the bottom card and between the side panels.
|
||||
*/
|
||||
function panToPlace(map: L.Map, latlng: [number, number], padding: ViewportPadding): void {
|
||||
function paddedCenter(
|
||||
map: L.Map,
|
||||
latlng: [number, number],
|
||||
padding: ViewportPadding,
|
||||
zoom: number
|
||||
): L.LatLngExpression {
|
||||
if (typeof map.project !== 'function' || typeof map.unproject !== 'function') {
|
||||
map.panTo(latlng, { animate: true });
|
||||
return;
|
||||
return latlng;
|
||||
}
|
||||
const { top, right, bottom, left } = padding;
|
||||
const point = map.project(latlng).add([(right - left) / 2, (bottom - top) / 2]);
|
||||
map.panTo(map.unproject(point), { animate: true });
|
||||
const point = map.project(latlng, zoom).add([(right - left) / 2, (bottom - top) / 2]);
|
||||
return map.unproject(point, zoom);
|
||||
}
|
||||
|
||||
@@ -62,7 +62,7 @@ export const REVEAL_FAN_MAX_CHILDREN = 12
|
||||
* A small bubble always opens. A bigger one only when every stop in it sits on the same
|
||||
* coordinate, the stack no zoom can take apart, which is the case the fan is there for.
|
||||
* Anything else is a pile of ordinary neighbours that zooming in separates, so it stays
|
||||
* closed and the selection is shown by the pan alone.
|
||||
* closed until the camera reaches the place's neighbourhood.
|
||||
*/
|
||||
function fansOpenOnSelect(cluster: RevealableCluster): boolean {
|
||||
if (cluster.getChildCount() <= REVEAL_FAN_MAX_CHILDREN) return true
|
||||
@@ -81,13 +81,21 @@ function isRevealableCluster(layer: unknown): layer is RevealableCluster {
|
||||
* Picking a stop from the places rail used to raise its pin out of the stack with a
|
||||
* z-index. A stop sharing its coordinates now sits in a cluster instead and has no pin
|
||||
* of its own to raise, so the bubble has to open for the selection to be visible at all.
|
||||
* Deliberately not `zoomToShowLayer`: the zoom belongs to the day fit, and the selection
|
||||
* only ever pans. See `fansOpenOnSelect` for which bubbles are opened.
|
||||
* The selection camera handles the zoom, so a cluster's bounds do not override the
|
||||
* place's padded view. See `fansOpenOnSelect` for which bubbles are opened.
|
||||
*/
|
||||
export function revealInCluster(group: ClusterGroupLike | null | undefined, marker: unknown): boolean {
|
||||
export function revealInCluster(
|
||||
group: ClusterGroupLike | null | undefined,
|
||||
marker: unknown,
|
||||
onDenseCluster?: () => void,
|
||||
): boolean {
|
||||
if (!group || !marker || typeof group.getVisibleParent !== 'function') return false
|
||||
const parent = group.getVisibleParent(marker)
|
||||
if (parent === marker || !isRevealableCluster(parent) || !fansOpenOnSelect(parent)) return false
|
||||
if (parent === marker || !isRevealableCluster(parent)) return false
|
||||
if (!fansOpenOnSelect(parent)) {
|
||||
onDenseCluster?.()
|
||||
return false
|
||||
}
|
||||
parent.spiderfy()
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -5,6 +5,9 @@ export interface MapTarget {
|
||||
lng?: number | null
|
||||
}
|
||||
|
||||
/** Street-level zoom separates ordinary neighbours when a place is selected. */
|
||||
export const PLACE_FOCUS_ZOOM = 16
|
||||
|
||||
/**
|
||||
* Where the map goes when a place is selected, the same in both renderers.
|
||||
*
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import type L from 'leaflet';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import type { Place } from '../../types';
|
||||
import { revealInCluster, type ClusterGroupLike } from './markerCluster';
|
||||
import { PLACE_FOCUS_ZOOM } from './selectedPlaceTarget';
|
||||
|
||||
/** Reveals the selected pin while keeping its neighbours clustered. */
|
||||
export function useLeafletClusterSelection(
|
||||
selectedPlaceId: number | null,
|
||||
places: Place[],
|
||||
zoom: number,
|
||||
follow: boolean
|
||||
) {
|
||||
const clusterGroupRef = useRef<ClusterGroupLike | null>(null);
|
||||
const markersRef = useRef(new Map<number, L.Marker>());
|
||||
// Picking the same stop again must check the cluster it sits in now.
|
||||
const selection = useMemo(() => ({ id: selectedPlaceId }), [selectedPlaceId]);
|
||||
const [standaloneSelection, setStandaloneSelection] = useState<typeof selection | null>(null);
|
||||
const canRevealStandalone = follow && zoom >= PLACE_FOCUS_ZOOM;
|
||||
const standalonePlaceId = canRevealStandalone && selection === standaloneSelection ? selectedPlaceId : null;
|
||||
|
||||
const registerClusterGroup = useCallback((group: unknown) => {
|
||||
clusterGroupRef.current = (group as ClusterGroupLike | null) ?? null;
|
||||
}, []);
|
||||
const registerMarker = useCallback((id: number, marker: L.Marker | null) => {
|
||||
if (marker) markersRef.current.set(id, marker);
|
||||
else markersRef.current.delete(id);
|
||||
}, []);
|
||||
const markerElement = useCallback((id: number) => markersRef.current.get(id)?.getElement() ?? null, []);
|
||||
|
||||
const revealSelectedPlace = useCallback(
|
||||
(afterClustering = true) => {
|
||||
const id = selection.id;
|
||||
if (id == null || standalonePlaceId === id) return;
|
||||
revealInCluster(
|
||||
clusterGroupRef.current,
|
||||
markersRef.current.get(id),
|
||||
afterClustering && canRevealStandalone ? () => setStandaloneSelection(selection) : undefined
|
||||
);
|
||||
},
|
||||
[selection, canRevealStandalone, standalonePlaceId]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedPlaceId == null) return;
|
||||
revealSelectedPlace(false);
|
||||
// Let Leaflet finish re-clustering and the marker group's batched updates before
|
||||
// drawing the selected pin by itself. The rest of a dense group keeps its bubble.
|
||||
const frame = requestAnimationFrame(() => revealSelectedPlace());
|
||||
return () => cancelAnimationFrame(frame);
|
||||
}, [selectedPlaceId, places, revealSelectedPlace]);
|
||||
|
||||
return { registerClusterGroup, registerMarker, markerElement, standalonePlaceId, revealSelectedPlace };
|
||||
}
|
||||
@@ -43,10 +43,10 @@ function setup(selectedPlaceId: number, follow = true) {
|
||||
}
|
||||
|
||||
describe('useSelectionCameraGL', () => {
|
||||
it('SELCAM-GL-001: flies to a new selection, padded by the panels, at least to zoom 14', () => {
|
||||
it('SELCAM-GL-001: focuses a new selection at street level with room for the panels (#3306)', () => {
|
||||
const { map } = setup(1);
|
||||
expect(map.flyTo).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ center: [50, 70], zoom: 14, padding: padding(0) })
|
||||
expect.objectContaining({ center: [50, 70], zoom: 16, padding: padding(0) })
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useEffect, useRef } from 'react';
|
||||
import type { ViewportPadding } from '../../utils/mapViewport';
|
||||
import { isUnderChrome } from './mapChromePadding';
|
||||
import { selectedPlaceTarget, type MapTarget } from './selectedPlaceTarget';
|
||||
import { PLACE_FOCUS_ZOOM, selectedPlaceTarget, type MapTarget } from './selectedPlaceTarget';
|
||||
|
||||
/** The part of a MapLibre/Mapbox map the selection camera drives. */
|
||||
interface SelectionCameraMap {
|
||||
@@ -61,7 +61,7 @@ export function useSelectionCameraGL<P extends MapTarget>({
|
||||
try {
|
||||
map.flyTo({
|
||||
center: [lng, lat],
|
||||
zoom: Math.max(map.getZoom(), 14),
|
||||
zoom: Math.max(map.getZoom(), PLACE_FOCUS_ZOOM),
|
||||
pitch: enableMapbox3d ? 45 : 0,
|
||||
duration: 400,
|
||||
padding,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import {
|
||||
stripTrailingSlashes,
|
||||
resolveValhallaProvider,
|
||||
VALHALLA_COSTING,
|
||||
VALHALLA_RELAY_MAX_LOCATIONS,
|
||||
@@ -245,7 +246,7 @@ export function valhallaBase(): string | null {
|
||||
*/
|
||||
function currentProvider(ignoreRest = false): { provider: ValhallaProvider | null; own: string } {
|
||||
const settings = useSettingsStore.getState().settings
|
||||
const own = settings.valhalla_base_url?.trim().replace(/\/+$/, '') ?? ''
|
||||
const own = stripTrailingSlashes(settings.valhalla_base_url?.trim() ?? '')
|
||||
const provider = resolveValhallaProvider({
|
||||
provider: settings.routing_valhalla_provider,
|
||||
valhallaUrl: own,
|
||||
|
||||
@@ -269,7 +269,7 @@ describe('PackingListPanel', () => {
|
||||
const { container } = render(<PackingListPanel tripId={1} items={items} sort="name" />);
|
||||
// Only the category grip stays: the order of the categories is not the A to Z of their items.
|
||||
const draggable = [...container.querySelectorAll('[draggable="true"]')];
|
||||
expect(draggable.map((el) => el.getAttribute('aria-label'))).toEqual(['Drag to reorder the category']);
|
||||
expect(draggable.map((el) => el.getAttribute('title'))).toEqual(['Drag to reorder the category']);
|
||||
});
|
||||
|
||||
it('FE-COMP-PACKING-023: inline edit item name via pencil icon calls PUT', async () => {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { focusRevealedEditor } from '../shared/dialogFocus'
|
||||
import { useState, useRef, useCallback } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { X, Plus } from 'lucide-react'
|
||||
@@ -37,7 +38,7 @@ export function BagCard({ bag, bagItems, totalWeight, pct, tripId, tripMembers,
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: sz.gap }}>
|
||||
<span style={{ width: sz.dot, height: sz.dot, borderRadius: '50%', background: bag.color, flexShrink: 0 }} />
|
||||
{editingName && canEdit ? (
|
||||
<input autoFocus value={nameVal} onChange={e => setNameVal(e.target.value)}
|
||||
<input ref={focusRevealedEditor} value={nameVal} onChange={e => setNameVal(e.target.value)}
|
||||
onBlur={saveName} onKeyDown={e => { if (e.key === 'Enter') saveName(); if (e.key === 'Escape') cancelName() }}
|
||||
style={{ flex: 1, fontSize: sz.name, fontWeight: 600, padding: '1px 4px', borderRadius: 4, border: '1px solid var(--border-primary)', outline: 'none', fontFamily: 'inherit', color: 'var(--text-primary)', background: 'transparent' }} />
|
||||
) : (
|
||||
@@ -101,7 +102,7 @@ export function BagCard({ bag, bagItems, totalWeight, pct, tripId, tripMembers,
|
||||
{editingLimit && canEdit ? (
|
||||
<>
|
||||
<span>/</span>
|
||||
<input autoFocus value={limitVal} onChange={e => setLimitVal(e.target.value)}
|
||||
<input ref={focusRevealedEditor} value={limitVal} onChange={e => setLimitVal(e.target.value)}
|
||||
onBlur={saveLimit}
|
||||
onKeyDown={e => { if (e.key === 'Enter') saveLimit(); if (e.key === 'Escape') cancelLimit() }}
|
||||
inputMode="decimal" aria-label={t('packing.bagLimit')} placeholder={t('packing.bagLimit')}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { focusRevealedEditor } from '../shared/dialogFocus'
|
||||
import { X, Plus } from 'lucide-react'
|
||||
import type { PackingState } from './usePackingListPanel'
|
||||
import { bagFillPct, bagLoadSummary, packedWeight, perPersonLoads } from './packingListPanel.helpers'
|
||||
@@ -72,7 +73,7 @@ export function BagModal(S: PackingState) {
|
||||
{/* Add bag */}
|
||||
{canEdit && (showAddBag ? (
|
||||
<div style={{ display: 'flex', gap: 6, marginTop: 14 }}>
|
||||
<input autoFocus value={newBagName} onChange={e => setNewBagName(e.target.value)}
|
||||
<input ref={focusRevealedEditor} value={newBagName} onChange={e => setNewBagName(e.target.value)}
|
||||
onKeyDown={e => { if (e.key === 'Enter') void handleCreateBag(); if (e.key === 'Escape') { setShowAddBag(false); setNewBagName('') } }}
|
||||
placeholder={t('packing.bagName')}
|
||||
style={{ flex: 1, padding: '8px 12px', borderRadius: 10, border: '1px solid var(--border-primary)', fontSize: 'calc(13px * var(--fs-scale-body, 1))', fontFamily: 'inherit', outline: 'none' }} />
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { focusRevealedEditor } from '../shared/dialogFocus'
|
||||
import { useCallback, useRef } from 'react'
|
||||
import { Briefcase, Plus, X } from 'lucide-react'
|
||||
import type { PackingState } from './usePackingListPanel'
|
||||
@@ -47,7 +48,7 @@ export function BagSidebar(S: PackingState) {
|
||||
{canEdit && showAddBag && (
|
||||
<div ref={composerRef} style={{ ...COMPOSER, margin: '10px 10px 0', paddingBlock: 4, paddingInlineEnd: 4, paddingInlineStart: 10 }}>
|
||||
<span aria-hidden style={{ width: 10, height: 10, borderRadius: '50%', border: '1.5px dashed var(--text-faint)', flexShrink: 0 }} />
|
||||
<input autoFocus value={newBagName} onChange={e => setNewBagName(e.target.value)}
|
||||
<input ref={focusRevealedEditor} value={newBagName} onChange={e => setNewBagName(e.target.value)}
|
||||
onKeyDown={e => { if (e.key === 'Enter') void handleCreateBag(); if (e.key === 'Escape') closeComposer() }}
|
||||
placeholder={t('packing.bagName')}
|
||||
style={{ flex: 1, minWidth: 0, padding: '5px 0', border: 'none', fontSize: 'calc(12.5px * var(--fs-scale-body, 1))', fontWeight: 500, fontFamily: 'inherit', outline: 'none', color: 'var(--text-primary)', background: 'transparent' }} />
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { focusRevealedEditor } from '../shared/dialogFocus'
|
||||
import React, { useState, useRef, useEffect } from 'react'
|
||||
import { useTripStore } from '../../store/tripStore'
|
||||
import { useToast } from '../shared/Toast'
|
||||
@@ -140,7 +141,7 @@ export function KategorieGruppe({ kategorie, items, tripId, allCategories, onRen
|
||||
|
||||
{editingName && canEdit ? (
|
||||
<input
|
||||
autoFocus value={editKatName}
|
||||
ref={focusRevealedEditor} value={editKatName}
|
||||
onChange={e => setEditKatName(e.target.value)}
|
||||
onBlur={handleSaveKatName}
|
||||
onKeyDown={e => { if (e.key === 'Enter') void handleSaveKatName(); if (e.key === 'Escape') { setEditingName(false); setEditKatName(kategorie) } }}
|
||||
@@ -319,7 +320,6 @@ export function KategorieGruppe({ kategorie, items, tripId, allCategories, onRen
|
||||
<span aria-hidden style={{ width: 20, height: 20, borderRadius: 6, border: '1.5px solid var(--text-faint)', flexShrink: 0 }} />
|
||||
<input
|
||||
ref={addItemRef}
|
||||
autoFocus
|
||||
value={newItemName}
|
||||
onChange={e => setNewItemName(e.target.value)}
|
||||
onKeyDown={e => {
|
||||
@@ -404,8 +404,7 @@ function CategoryGrip({ drag, kategorie, label }: { drag?: CategoryDrag; kategor
|
||||
return (
|
||||
<span
|
||||
draggable
|
||||
role="button"
|
||||
aria-label={label}
|
||||
aria-hidden="true"
|
||||
title={label}
|
||||
onDragStart={e => {
|
||||
e.dataTransfer.effectAllowed = 'move'
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { replaceInlineMarkdownLinks } from '@trek/shared'
|
||||
import type { PackingBag, PackingItem } from '../../types'
|
||||
import { KAT_COLORS, PACKING_PLACEHOLDER_NAME } from './packingListPanel.constants'
|
||||
|
||||
@@ -7,7 +8,7 @@ export function katColor(kat: string, allCategories?: string[]): string {
|
||||
if (idx >= 0) return KAT_COLORS[idx % KAT_COLORS.length]
|
||||
// Fallback: hash-based
|
||||
let h = 0
|
||||
for (let i = 0; i < kat.length; i++) h = ((h << 5) - h + (kat.codePointAt(i) ?? 0)) | 0
|
||||
for (let i = 0; i < kat.length; i++) h = Math.imul((h << 5) - h + (kat.codePointAt(i) ?? 0), 1)
|
||||
return KAT_COLORS[Math.abs(h) % KAT_COLORS.length]
|
||||
}
|
||||
|
||||
@@ -148,7 +149,7 @@ const MD_WEIGHT = /\((\d+(?:[.,]\d+)?)\s?(g|kg)\)$/i
|
||||
|
||||
/** Links, emphasis and code marks as plain text: a list copied from a notes app is full of them. */
|
||||
const plainMarkdown = (text: string): string =>
|
||||
text.replace(/\[([^\]]*)\]\([^)]*\)/g, '$1').replace(/\*\*|__|~~|`/g, '').trim()
|
||||
replaceInlineMarkdownLinks(text, (label) => label, true).replace(/\*\*|__|~~|`/g, '').trim()
|
||||
|
||||
/**
|
||||
* Whether pasted text is a Markdown list rather than CSV rows (#875): any heading or
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user