mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-03 01:28:55 +00:00
Compare commits
12 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c8d09fc132 | |||
| f5a510c78e | |||
| 86e98fde65 | |||
| 62a3e63f3f | |||
| 01ad13623c | |||
| 59e5c5a3c9 | |||
| a2cf911ce1 | |||
| 7a66a54e66 | |||
| 748434fc47 | |||
| 618f070675 | |||
| dacf19b4d5 | |||
| 103631d5fc |
@@ -11,4 +11,3 @@ 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,61 +102,21 @@ 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 || ids.isEmpty()) return@ready call.resolve(result.put("products", JSArray()))
|
||||
if (!ok) return@ready call.resolve(result.put("products", JSArray()))
|
||||
details(context, ids) { found ->
|
||||
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())))
|
||||
}
|
||||
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))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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.
|
||||
@@ -166,28 +126,19 @@ object TrekBilling {
|
||||
client(activity).queryPurchasesAsync(params) { result, purchases ->
|
||||
val held = if (result.responseCode == BillingClient.BillingResponseCode.OK) newest(purchases, PREFIX) else null
|
||||
when {
|
||||
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)
|
||||
held == null -> launchPurchase(activity, call, id)
|
||||
held.isAcknowledged -> call.resolve(JSObject().put("kind", "subscribed"))
|
||||
else -> call.resolve(receipt(held).put("kind", "bought"))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun launchPurchase(activity: Activity, call: PluginCall, id: String, trialRenewalPrice: String?) {
|
||||
private fun launchPurchase(activity: Activity, call: PluginCall, id: String) {
|
||||
details(activity, listOf(id)) { found ->
|
||||
val product = found.firstOrNull()
|
||||
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"))
|
||||
}
|
||||
val offer = product?.let(::baseOffer)
|
||||
if (product == null || offer == null) return@details call.resolve(JSObject().put("kind", "failed"))
|
||||
pendingPurchase?.resolve(JSObject().put("kind", "cancelled"))
|
||||
pendingPurchase = call
|
||||
pendingProduct = id
|
||||
@@ -324,7 +275,6 @@ 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,40 +688,14 @@ extension TrekShellPlugin {
|
||||
let ids = call.getArray("ids", String.self) ?? []
|
||||
Task {
|
||||
let sandbox = await Self.buysInSandbox()
|
||||
guard !ids.isEmpty, AppStore.canMakePayments, let products = try? await Product.products(for: ids) else {
|
||||
guard AppStore.canMakePayments, let products = try? await Product.products(for: ids) else {
|
||||
call.resolve(["products": [], "sandbox": sandbox])
|
||||
return
|
||||
}
|
||||
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])
|
||||
call.resolve(["products": products.map { ["id": $0.id, "displayPrice": $0.displayPrice] }, "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
|
||||
/// Xcode builds do, and while TREK Cloud's orders are closed only they may buy.
|
||||
/// The signed app transaction names its environment; the receipt's file name,
|
||||
@@ -752,7 +726,6 @@ 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
|
||||
@@ -767,18 +740,9 @@ extension TrekShellPlugin {
|
||||
}
|
||||
do {
|
||||
guard let product = try await Product.products(for: [id]).first else {
|
||||
call.resolve(["kind": trialRenewalPrice == nil ? "failed" : "offer-changed"])
|
||||
call.resolve(["kind": "failed"])
|
||||
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 {
|
||||
|
||||
+140
-210
@@ -7,21 +7,14 @@ 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,
|
||||
matchesPurchaseAgreement,
|
||||
opensSoon,
|
||||
planForUnclaimedPurchase,
|
||||
refundedBeforeOpening,
|
||||
type CloudPurchaseAgreement,
|
||||
} from '../src/native/cloudOrders';
|
||||
import { fakeIapClient, getIapClient, productIdFor, type IapProduct, type Purchase } from '../src/native/iap';
|
||||
import { isNewCloudPlan, opensSoon, planForUnclaimedPurchase, refundedBeforeOpening } from '../src/native/cloudOrders';
|
||||
import { fakeIapClient, getIapClient, productIdFor, type Purchase } from '../src/native/iap';
|
||||
import {
|
||||
APP_STORE_SUBSCRIPTIONS_URL,
|
||||
AUTH_PROXY_DOCS_URL,
|
||||
CLIENT_CERT_DOCS_URL,
|
||||
CLOUD_TERMS_URL,
|
||||
CLOUD_URL as PRODUCTION_CLOUD_URL,
|
||||
CLOUD_URL,
|
||||
PLAY_SUBSCRIPTIONS_URL,
|
||||
PRIVACY_URL,
|
||||
STORE_TERMS_URL,
|
||||
@@ -57,13 +50,6 @@ 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();
|
||||
/**
|
||||
@@ -112,30 +98,6 @@ 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':
|
||||
@@ -189,11 +151,12 @@ 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',
|
||||
@@ -352,8 +315,7 @@ 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 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);
|
||||
const discover = el('button', { type: 'button', className: 'cta' }, t('native.welcome.discover'));
|
||||
discover.addEventListener('click', () => {
|
||||
void tap();
|
||||
showPlans();
|
||||
@@ -364,7 +326,7 @@ function showWelcome(opts: { back?: boolean } = {}): void {
|
||||
showConnect();
|
||||
});
|
||||
|
||||
const screen = show(
|
||||
show(
|
||||
'welcome',
|
||||
WELCOME_CAMERA,
|
||||
{
|
||||
@@ -389,9 +351,6 @@ function showWelcome(opts: { back?: boolean } = {}): void {
|
||||
},
|
||||
opts
|
||||
);
|
||||
void availableWelcomeTrial().then((available) => {
|
||||
if (screen.node.isConnected) trial.hidden = !available;
|
||||
});
|
||||
}
|
||||
|
||||
// ── Connect (address) ───────────────────────────────────────────────────────
|
||||
@@ -705,7 +664,7 @@ interface CloudPlan {
|
||||
yearlyCents?: number;
|
||||
currency?: 'EUR' | 'USD';
|
||||
aiDocuments: number;
|
||||
aiDocumentLimit?: number | null;
|
||||
aiDocumentLimit?: 0 | null;
|
||||
aiAssistant?: 'planned' | 'included' | 'unavailable';
|
||||
bookingMailImport?: boolean;
|
||||
storageGb: number;
|
||||
@@ -722,24 +681,24 @@ const SAMPLE_PLANS: CloudPlan[] = [
|
||||
{
|
||||
id: 'start',
|
||||
name: 'Start',
|
||||
monthlyCents: 599,
|
||||
monthlyCents: 499,
|
||||
yearlyCents: 4899,
|
||||
currency: 'USD',
|
||||
aiDocuments: 0,
|
||||
aiDocumentLimit: 0,
|
||||
storageGb: 50,
|
||||
storageGb: 200,
|
||||
},
|
||||
{
|
||||
id: 'plus',
|
||||
name: 'Plus',
|
||||
monthlyCents: 1199,
|
||||
monthlyCents: 999,
|
||||
yearlyCents: 9900,
|
||||
currency: 'USD',
|
||||
aiDocuments: 100,
|
||||
aiDocumentLimit: null,
|
||||
aiAssistant: 'included',
|
||||
aiAssistant: 'planned',
|
||||
bookingMailImport: true,
|
||||
storageGb: 50,
|
||||
storageGb: 200,
|
||||
},
|
||||
];
|
||||
|
||||
@@ -747,18 +706,15 @@ 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 cloudGet(`${CLOUD_URL}/api/plans`);
|
||||
const res = await get(`${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', open: res.status === 200 && body.ordering === 'open' };
|
||||
if (plans.length) return { plans, closed: body.ordering === 'closed' };
|
||||
} catch {
|
||||
// Fall through to the preview fallback.
|
||||
}
|
||||
@@ -774,44 +730,22 @@ async function fetchPlans(): Promise<CloudPlans | null> {
|
||||
*/
|
||||
interface Offer {
|
||||
canBuy: boolean;
|
||||
storeProducts: Map<string, IapProduct> | null;
|
||||
canShowTrial: boolean;
|
||||
storePrices: Map<string, string> | null;
|
||||
/** 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; freeTrial: boolean } {
|
||||
if (!offer.canBuy) return { label: '', buyable: false, freeTrial: false };
|
||||
function offerFor(offer: Offer, plan: CloudPlan, interval: 'month' | 'year'): { label: string; buyable: boolean } {
|
||||
if (!offer.canBuy) return { label: '', buyable: false };
|
||||
if (iap !== fakeIapClient) {
|
||||
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 label = offer.storePrices?.get(productIdFor(plan.id, interval)) ?? '';
|
||||
return { label, buyable: label !== '' };
|
||||
}
|
||||
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 !== '', 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 !== '');
|
||||
return { label, buyable: label !== '' };
|
||||
}
|
||||
|
||||
async function loadOffer(list: CloudPlans): Promise<Offer> {
|
||||
@@ -821,61 +755,39 @@ 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, storeProducts: null, canShowTrial: false, opensSoon: soon };
|
||||
return {
|
||||
canBuy,
|
||||
storeProducts: await iap.products(storeIds(list.plans)),
|
||||
canShowTrial: list.open === true,
|
||||
opensSoon: 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 };
|
||||
}
|
||||
|
||||
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
|
||||
);
|
||||
/** 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];
|
||||
}
|
||||
|
||||
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),
|
||||
];
|
||||
/** 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' },
|
||||
};
|
||||
/** 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 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);
|
||||
/** Restore a choice when returning from setup. A fresh entry opens Plus. */
|
||||
/** The plan chosen last, so coming back to the plans finds it still chosen. */
|
||||
let chosenPlanId: string | null = null;
|
||||
let chosenInterval: 'month' | 'year' = 'month';
|
||||
|
||||
@@ -940,11 +852,14 @@ function restoreButton(plans: CloudPlan[]): HTMLButtonElement {
|
||||
function showPlans(opts: { back?: boolean } = {}): void {
|
||||
let interval: 'month' | 'year' = chosenInterval;
|
||||
let plans: CloudPlan[] = [];
|
||||
let offer: Offer = { canBuy: false, storeProducts: null, canShowTrial: false, opensSoon: false };
|
||||
let offer: Offer = { canBuy: false, storePrices: null, 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'));
|
||||
@@ -961,20 +876,18 @@ 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 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 pricebox = el('div', { className: 'pricebox' }, cycle, price, equals);
|
||||
const specs = el('div', { className: 'specs' });
|
||||
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 }, pricebox, specs);
|
||||
const details = el('div', { className: 'stack', hidden: true }, trip, pricebox, specs);
|
||||
const choose = el('button', { type: 'button', className: 'cta', hidden: true });
|
||||
const dock = el('div', { className: 'dock' }, choose);
|
||||
|
||||
const screen = show(
|
||||
'plain',
|
||||
opts.back ? chosenCamera : cameraForPlan(1),
|
||||
chosenCamera,
|
||||
{
|
||||
back: () => showWelcome({ back: true }),
|
||||
content: [el('div', { className: 'pad lift' }, tiers, loading, details), foot, dock],
|
||||
@@ -1021,11 +934,20 @@ function showPlans(opts: { back?: boolean } = {}): void {
|
||||
yearBtn.setAttribute('aria-checked', String(interval === 'year'));
|
||||
cycle.dataset.year = String(interval === 'year');
|
||||
|
||||
const { label, buyable, freeTrial } = interval === 'month' ? month : year;
|
||||
// An introductory offer states the free period and renewal price together.
|
||||
price.hidden = !label || freeTrial;
|
||||
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;
|
||||
pricePer.textContent = per(interval);
|
||||
if (label && !freeTrial) paintPrice(label, animate);
|
||||
if (label) 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;
|
||||
@@ -1033,23 +955,59 @@ function showPlans(opts: { back?: boolean } = {}): void {
|
||||
yearBtn.disabled = !year.label;
|
||||
const yearAmount = amountIn(year.label);
|
||||
equals.textContent =
|
||||
!label || !year.label || freeTrial
|
||||
!label || !year.label
|
||||
? ''
|
||||
: 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');
|
||||
|
||||
specs.replaceChildren(...planFeatures(plan));
|
||||
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'))
|
||||
)
|
||||
);
|
||||
|
||||
choose.hidden = !buyable;
|
||||
choose.textContent = t('native.plans.choose', { plan: plan.name });
|
||||
choose.textContent = t('native.plans.choose', { trip: tripTitle });
|
||||
chosenCamera = cameraForPlan(index);
|
||||
chosenPlanId = plan.id;
|
||||
chosenInterval = interval;
|
||||
@@ -1084,7 +1042,7 @@ function showPlans(opts: { back?: boolean } = {}): void {
|
||||
showSubscribed();
|
||||
return;
|
||||
}
|
||||
showClaim(plan, selectedInterval, price.label, { freeTrial: price.freeTrial });
|
||||
showClaim(plan, selectedInterval, price.label);
|
||||
});
|
||||
|
||||
const load = async () => {
|
||||
@@ -1102,9 +1060,7 @@ function showPlans(opts: { back?: boolean } = {}): void {
|
||||
}
|
||||
offer = await loadOffer(list);
|
||||
plans = list.plans;
|
||||
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;
|
||||
selectedId = plans.find((p) => p.id === chosenPlanId)?.id ?? recommendedPlan(plans)?.id ?? null;
|
||||
tiers.replaceChildren(
|
||||
...plans.map((p) => {
|
||||
const b = el('button', { type: 'button', role: 'radio', dataset: { plan: p.id } }, p.name);
|
||||
@@ -1127,7 +1083,7 @@ function showPlans(opts: { back?: boolean } = {}): void {
|
||||
);
|
||||
} else {
|
||||
foot.replaceChildren(
|
||||
legal,
|
||||
el('p', { className: 'legal' }, t(onPlay ? 'native.plans.legalAndroid' : 'native.plans.legal')),
|
||||
el(
|
||||
'div',
|
||||
{ className: 'legal-links' },
|
||||
@@ -1149,7 +1105,7 @@ type SlugStatus = 'available' | 'taken' | 'invalid' | 'reserved' | 'error';
|
||||
|
||||
async function slugStatus(slug: string): Promise<SlugStatus> {
|
||||
try {
|
||||
const res = await cloudGet(`${CLOUD_URL}/api/slug/check?slug=${encodeURIComponent(slug)}`);
|
||||
const res = await get(`${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;
|
||||
@@ -1164,17 +1120,21 @@ 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.
|
||||
*/
|
||||
async function fetchConsent(): Promise<CloudPurchaseAgreement | null> {
|
||||
interface DeviationsConsent {
|
||||
version: string;
|
||||
text: string;
|
||||
}
|
||||
async function fetchConsent(): Promise<DeviationsConsent | null> {
|
||||
try {
|
||||
const res = await CapacitorHttp.get({
|
||||
url: `${CLOUD_URL}/api/iap/consent`,
|
||||
params: { lang: locale === 'de' ? 'de' : 'en' },
|
||||
...cloudHttpOptions,
|
||||
connectTimeout: PROBE_TIMEOUT_MS,
|
||||
readTimeout: PROBE_TIMEOUT_MS,
|
||||
});
|
||||
const data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data;
|
||||
const body = (data ?? {}) as { version?: unknown; deviations?: unknown; iapEnvironment?: unknown };
|
||||
const body = (data ?? {}) as { version?: unknown; deviations?: 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 {
|
||||
@@ -1202,7 +1162,8 @@ async function redeemPurchase(
|
||||
const res = await CapacitorHttp.post({
|
||||
url: `${CLOUD_URL}/api/iap/redeem`,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
...cloudHttpOptions,
|
||||
connectTimeout: PROBE_TIMEOUT_MS,
|
||||
readTimeout: PROBE_TIMEOUT_MS,
|
||||
// The language of the contract confirmation mail.
|
||||
data: {
|
||||
platform: purchase.platform,
|
||||
@@ -1220,9 +1181,6 @@ 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 } : {}) };
|
||||
@@ -1237,7 +1195,7 @@ function showClaim(
|
||||
plan: Pick<CloudPlan, 'id' | 'name'>,
|
||||
interval: 'month' | 'year',
|
||||
priceLabel: string,
|
||||
opts: { back?: boolean; bought?: Purchase; freeTrial?: boolean } = {}
|
||||
opts: { back?: boolean; bought?: Purchase } = {}
|
||||
): 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;
|
||||
@@ -1321,7 +1279,7 @@ function showClaim(
|
||||
};
|
||||
|
||||
// The § 327h agreement, asked on its own before anything is bought.
|
||||
let consent: CloudPurchaseAgreement | null = null;
|
||||
let consent: DeviationsConsent | null = null;
|
||||
const consentBox = el('input', { type: 'checkbox' });
|
||||
const consentText = el('span', { className: 'consent-text' }, t('native.claim.consentLoading'));
|
||||
const consentField = el(
|
||||
@@ -1330,26 +1288,19 @@ function showClaim(
|
||||
consentBox,
|
||||
el('span', {}, el('strong', {}, t('native.claim.consentTitle')), consentText)
|
||||
);
|
||||
const showConsent = (current: CloudPurchaseAgreement | null): void => {
|
||||
consent = current;
|
||||
const loadConsent = async (): Promise<DeviationsConsent | null> => {
|
||||
consentBox.checked = false;
|
||||
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());
|
||||
consent = await fetchConsent();
|
||||
consentBox.disabled = consent === null;
|
||||
consentText.textContent = consent ? consent.text : t('native.claim.consentUnavailable');
|
||||
return consent;
|
||||
};
|
||||
void loadConsent();
|
||||
|
||||
const subscribeLabel = () =>
|
||||
bought
|
||||
? t('native.claim.completeSetup')
|
||||
: opts.freeTrial
|
||||
? t('native.trial.badge')
|
||||
: t('native.claim.subscribe', { price: priceLabel });
|
||||
bought ? t('native.claim.completeSetup') : 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'));
|
||||
@@ -1357,25 +1308,19 @@ 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), ...(planPrice ? [planPrice] : [])),
|
||||
el(
|
||||
'span',
|
||||
{},
|
||||
el('b', {}, plan.name),
|
||||
...(priceLabel ? [el('small', { dir: 'ltr' }, `${priceLabel} ${per(interval)}`)] : [])
|
||||
),
|
||||
// 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 },
|
||||
@@ -1402,7 +1347,10 @@ function showClaim(
|
||||
{
|
||||
back: () => showPlans({ back: true }),
|
||||
overlay: [card.node],
|
||||
content: [form, checkoutDock],
|
||||
content: [
|
||||
form,
|
||||
el('div', { className: 'dock' }, submit, el('p', { className: 'fine' }, t('native.claim.renews'))),
|
||||
],
|
||||
},
|
||||
opts
|
||||
);
|
||||
@@ -1492,8 +1440,7 @@ function showClaim(
|
||||
consentBox.focus();
|
||||
return;
|
||||
}
|
||||
const acceptedConsent = consent;
|
||||
const consentVersion = acceptedConsent?.version ?? null;
|
||||
const consentVersion = consent ? consent.version : null;
|
||||
|
||||
void tap(ImpactStyle.Medium);
|
||||
// The purchase sheet and the progress want the whole screen, not the keyboard.
|
||||
@@ -1513,24 +1460,7 @@ function showClaim(
|
||||
};
|
||||
|
||||
if (!bought) {
|
||||
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;
|
||||
}
|
||||
const outcome = await iap.purchase(productIdFor(plan.id, interval));
|
||||
if (outcome.kind === 'cancelled') {
|
||||
restore();
|
||||
setNotice(error, t('native.claim.cancelled'));
|
||||
@@ -1720,8 +1650,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, cloudGet);
|
||||
if (result.ok && (!cloudSandbox || new URL(result.url).origin === new URL(instanceUrl).origin)) {
|
||||
const result = await probeServer(instanceUrl, get);
|
||||
if (result.ok) {
|
||||
await ready(result.url);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -320,14 +320,14 @@ input {
|
||||
overflow: hidden;
|
||||
background: var(--sea);
|
||||
margin-bottom: -1px;
|
||||
height: max(calc(var(--safe-top) + 68px), min(252px, 30svh));
|
||||
height: min(300px, 36svh);
|
||||
}
|
||||
.hero.tall {
|
||||
height: min(320px, 38svh);
|
||||
}
|
||||
.hero.welcome {
|
||||
height: min(352px, 42svh);
|
||||
min-height: 236px;
|
||||
height: min(376px, 44.5svh);
|
||||
min-height: 250px;
|
||||
}
|
||||
.hero .scenery {
|
||||
position: absolute;
|
||||
@@ -529,7 +529,7 @@ input {
|
||||
}
|
||||
.push {
|
||||
flex: 1;
|
||||
min-height: clamp(10px, 2svh, 16px);
|
||||
min-height: 0;
|
||||
}
|
||||
h1 {
|
||||
margin: 0;
|
||||
@@ -628,39 +628,6 @@ 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;
|
||||
@@ -748,6 +715,33 @@ 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;
|
||||
@@ -829,52 +823,64 @@ h1 {
|
||||
display: none;
|
||||
}
|
||||
.specs {
|
||||
margin: 0;
|
||||
padding: 0 12px;
|
||||
list-style: none;
|
||||
border-radius: 16px;
|
||||
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;
|
||||
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: 28px;
|
||||
height: 28px;
|
||||
border-radius: 8px;
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
flex: none;
|
||||
border-radius: 10px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
background: var(--sand);
|
||||
color: var(--dark);
|
||||
}
|
||||
.spec b {
|
||||
display: block;
|
||||
font-size: 14px;
|
||||
font-weight: 700;
|
||||
line-height: 1.35;
|
||||
font-weight: 800;
|
||||
line-height: 1.2;
|
||||
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 small {
|
||||
display: block;
|
||||
font-size: 11.5px;
|
||||
color: var(--muted);
|
||||
font-weight: 600;
|
||||
line-height: 1.25;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.spec.off i {
|
||||
background: #f0f1f3;
|
||||
color: inherit;
|
||||
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;
|
||||
}
|
||||
.legal {
|
||||
margin: 2px 0 0;
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -1,45 +0,0 @@
|
||||
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,7 +4,7 @@
|
||||
"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/Budget/CostsPanel.tsx": 1588,
|
||||
"src/components/Map/MapView.tsx": 1191,
|
||||
"src/components/Map/MapViewGL.test.tsx": 2919,
|
||||
"src/components/Map/MapViewGL.tsx": 2083,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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">
|
||||
<a
|
||||
href={source.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"
|
||||
>
|
||||
<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>
|
||||
)}
|
||||
</a>
|
||||
</li>
|
||||
))}
|
||||
<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={url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer nofollow"
|
||||
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" />
|
||||
<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' : ''}`}>
|
||||
<ChangeHead item={item} view={view} struck={settled} />
|
||||
{inlineBooking ? (
|
||||
<Slot
|
||||
name="Body"
|
||||
item={item}
|
||||
view={view}
|
||||
fallback={<ChangeHead item={item} view={view} struck={settled} />}
|
||||
/>
|
||||
) : (
|
||||
<ChangeHead item={item} view={view} struck={settled} />
|
||||
)}
|
||||
</div>
|
||||
{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 && (
|
||||
<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'
|
||||
}`}
|
||||
>
|
||||
{!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 />
|
||||
{withChoice ? (
|
||||
<Tooltip label={t('assistant.change.include')}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onToggle}
|
||||
disabled={disabled}
|
||||
aria-pressed={!excluded}
|
||||
aria-label={t('assistant.change.include')}
|
||||
className="relative grid h-8 w-8 flex-none place-items-center rounded-lg outline-none ring-edge transition-shadow before:absolute before:-inset-1.5 before:rounded-xl hover:ring-1 focus-visible:ring-2 focus-visible:ring-accent disabled:cursor-default"
|
||||
>
|
||||
<Lead item={item} view={view} dimmed={excluded} />
|
||||
{!excluded && (
|
||||
<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>
|
||||
)}
|
||||
<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} />
|
||||
)}
|
||||
</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)}
|
||||
/>
|
||||
)}
|
||||
<BodySlot item={item} settled={waiting ? excluded.has(item.toolCallId) : settledOf(item, isUndone)} />
|
||||
{!inlineBookingCard(item) && (
|
||||
<BodySlot item={item} settled={waiting ? excluded.has(item.toolCallId) : settledOf(item, isUndone)} />
|
||||
)}
|
||||
</Fragment>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -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} />}
|
||||
<BookingFooter item={item} 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 && (
|
||||
<bdi title={address} className="line-clamp-2 text-caption text-content-muted">
|
||||
{address}
|
||||
</bdi>
|
||||
)}
|
||||
</span>
|
||||
<StatusMark item={item} />
|
||||
{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>
|
||||
))}
|
||||
</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>
|
||||
<WayFigures way={way} unit={unit} />
|
||||
{!chosen && <WayDelta way={way} chosen={chosenWay} letter={chosenLetter} unit={unit} />}
|
||||
{entry.card.routed ? (
|
||||
<WayFigures way={way} unit={unit} />
|
||||
) : (
|
||||
<span className="text-caption text-warning">{t('map.overview.notRouted')}</span>
|
||||
)}
|
||||
{!chosen && entry.card.routed && chosenWay && (
|
||||
<WayDelta way={way} chosen={chosenWay} letter={chosenLetter} unit={unit} />
|
||||
)}
|
||||
</span>
|
||||
</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,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>
|
||||
)
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -83,11 +83,11 @@ function DayRowTourPills({ tour, stageKey }: { tour: TourListItem; stageKey?: st
|
||||
}
|
||||
|
||||
// Description line, one line like every stop's.
|
||||
function SublineDescription({ text, isTourPlace }: { text: string; isTourPlace: boolean }) {
|
||||
function SublineDescription({ text, isTourPlace, fade }: { text: string; isTourPlace: boolean; fade: boolean }) {
|
||||
return (
|
||||
<div
|
||||
data-testid={isTourPlace ? 'trip-plan-tour-description' : undefined}
|
||||
className="collab-note-md min-w-0 flex-1 text-content-faint"
|
||||
className={`collab-note-md min-w-0 flex-1 text-content-faint${fade ? 'trek-fade-end' : ''}`}
|
||||
style={{
|
||||
...fs(10.5),
|
||||
overflow: 'hidden',
|
||||
@@ -115,13 +115,15 @@ export function DayPlanPlaceSubline({
|
||||
}: DayPlanPlaceSublineProps) {
|
||||
const { locale } = useTranslation();
|
||||
const dayRowTour = tourTimes?.tour;
|
||||
const wrapTourFacts = !!dayRowTour || hasPlannedTimes(tourTimes);
|
||||
const description = place.description || place.address || cat?.name;
|
||||
if (!(dayRowTour || place.place_time || hasPlannedTimes(tourTimes) || description)) return null;
|
||||
if (!(wrapTourFacts || place.place_time || description)) return null;
|
||||
return (
|
||||
// The description stays on one line and gives way first. The pills wrap rather
|
||||
// than run out of the row: a tour carries a time, its duration and its distance,
|
||||
// and in the narrow day column the last of them used to be cut off unseen.
|
||||
<div className="trek-fade-end mt-0.5 flex min-w-0 flex-wrap items-center gap-x-1.5 gap-y-1 overflow-hidden">
|
||||
// At a regular stop, the time stays readable and only the description gives way.
|
||||
// A tour can wrap its time, duration and distance in the narrow day column.
|
||||
<div
|
||||
className={`mt-0.5 flex min-w-0 items-center gap-x-1.5 overflow-hidden ${wrapTourFacts ? 'trek-fade-end flex-wrap gap-y-1' : 'flex-nowrap'}`}
|
||||
>
|
||||
{place.place_time && dayRowTour && (
|
||||
// TIME-02: a tour's end, typed or worked out from its start and its time.
|
||||
<TimePill quiet>
|
||||
@@ -143,7 +145,7 @@ export function DayPlanPlaceSubline({
|
||||
tourTimes && <PlannedTourPills tourTimes={tourTimes} />
|
||||
)}
|
||||
{dayRowTour && <WalkProgressPill tour={dayRowTour} assignmentId={assignmentId} />}
|
||||
{description && <SublineDescription text={description} isTourPlace={isTourPlace} />}
|
||||
{description && <SublineDescription text={description} isTourPlace={isTourPlace} fade={!wrapTourFacts} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -48,7 +48,7 @@ export function HeaderPills({
|
||||
categories: Category[] | null;
|
||||
categoryId: string;
|
||||
onCategory: (id: string) => void;
|
||||
newCategory: NewCategoryRow;
|
||||
newCategory?: NewCategoryRow;
|
||||
pickedSource: string | null;
|
||||
busy: boolean;
|
||||
/** The place as the form holds it, once it has a position: opens it in a map app (#2178). */
|
||||
@@ -61,14 +61,15 @@ export function HeaderPills({
|
||||
// goes with it, and the focus would drop out of the dialog. It comes back to
|
||||
// the + that opened the field, as a picker's focus comes back to its pill.
|
||||
const plusRef = useRef<HTMLButtonElement | null>(null);
|
||||
const wasOpen = useRef(newCategory.open);
|
||||
const categoryEditorOpen = newCategory?.open ?? false;
|
||||
const wasOpen = useRef(categoryEditorOpen);
|
||||
useEffect(() => {
|
||||
const closed = wasOpen.current && !newCategory.open;
|
||||
wasOpen.current = newCategory.open;
|
||||
const closed = wasOpen.current && !categoryEditorOpen;
|
||||
wasOpen.current = categoryEditorOpen;
|
||||
if (!closed) return;
|
||||
const active = document.activeElement;
|
||||
if (!active || active === document.body || !active.isConnected) plusRef.current?.focus();
|
||||
}, [newCategory.open]);
|
||||
}, [categoryEditorOpen]);
|
||||
|
||||
const noCategory = {
|
||||
label: t('places.noCategory'),
|
||||
@@ -96,7 +97,7 @@ export function HeaderPills({
|
||||
{t(kind.labelKey)}
|
||||
</span>
|
||||
);
|
||||
} else if (newCategory.open) {
|
||||
} else if (newCategory?.open) {
|
||||
lead = <NewCategoryField {...newCategory} t={t} />;
|
||||
} else {
|
||||
lead = (
|
||||
@@ -108,17 +109,19 @@ export function HeaderPills({
|
||||
options={options}
|
||||
fallback={noCategory}
|
||||
/>
|
||||
<Tooltip label={t('places.newCategory')}>
|
||||
<button
|
||||
ref={plusRef}
|
||||
type="button"
|
||||
onClick={() => newCategory.setOpen(true)}
|
||||
aria-label={t('places.newCategory')}
|
||||
className={ROUND_PILL_BUTTON}
|
||||
>
|
||||
<Plus size={13} strokeWidth={2.4} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
{newCategory && (
|
||||
<Tooltip label={t('places.newCategory')}>
|
||||
<button
|
||||
ref={plusRef}
|
||||
type="button"
|
||||
onClick={() => newCategory.setOpen(true)}
|
||||
aria-label={t('places.newCategory')}
|
||||
className={ROUND_PILL_BUTTON}
|
||||
>
|
||||
<Plus size={13} strokeWidth={2.4} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -148,7 +148,9 @@ export type PlacePrefill = {
|
||||
phone?: string
|
||||
osm_id?: string
|
||||
/** A place Google knows, such as one the assistant found: the details column reads it by this id. */
|
||||
google_place_id?: string
|
||||
google_place_id?: string;
|
||||
google_ftid?: string;
|
||||
amap_poi_id?: string;
|
||||
}
|
||||
|
||||
/** A blank form at a prefilled position, with what the POI already knew. */
|
||||
@@ -163,6 +165,8 @@ export function prefillForm(prefill: PlacePrefill, extra: Partial<PlaceFormData>
|
||||
phone: prefill.phone || '',
|
||||
osm_id: prefill.osm_id,
|
||||
google_place_id: prefill.google_place_id,
|
||||
google_ftid: prefill.google_ftid,
|
||||
amap_poi_id: prefill.amap_poi_id,
|
||||
...extra,
|
||||
}
|
||||
}
|
||||
@@ -184,7 +188,9 @@ export function openingDetailsSelection(
|
||||
}
|
||||
}
|
||||
if (prefill) {
|
||||
return { placeId: prefill.google_place_id || prefill.osm_id || undefined, lat: prefill.lat, lng: prefill.lng, name: prefill.name || '' }
|
||||
return {
|
||||
placeId: prefill.google_place_id || prefill.amap_poi_id || prefill.osm_id || undefined,
|
||||
lat: prefill.lat, lng: prefill.lng, name: prefill.name || '' }
|
||||
}
|
||||
return null
|
||||
}
|
||||
@@ -198,11 +204,7 @@ export function openingDetailsSelection(
|
||||
*/
|
||||
export function openingAutoFilled(place: unknown, prefill: PlacePrefill | null | undefined): Set<ResultField> {
|
||||
return new Set(
|
||||
!place && prefill
|
||||
? (['name', 'address', 'lat', 'lng', 'website', 'phone', 'osm_id'] as ResultField[]).filter(
|
||||
(field) => !!prefill[field as keyof PlacePrefill],
|
||||
)
|
||||
: [],
|
||||
!place && prefill ? RESULT_FIELDS.filter((field) => prefill[field] !== undefined && prefill[field] !== '') : []
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -36,7 +36,7 @@ const tint = (color: string, percent: number) => `color-mix(in srgb, ${color} ${
|
||||
* field after them adds a new tag, in a colour picked the same way and shown on
|
||||
* the field as it is typed. The state is usePlaceTags'; this is its markup.
|
||||
*/
|
||||
export function PlaceFormTags({ tags, t }: { tags: PlaceTagsField; t: Translate }) {
|
||||
export function PlaceFormTags({ tags, t, manage = true }: { tags: PlaceTagsField; t: Translate; manage?: boolean }) {
|
||||
// Which palette is open: a tag's id, 'new' for the new tag's colour, or none.
|
||||
const [palette, setPalette] = useState<number | 'new' | null>(null);
|
||||
// The colour a tag shows while its custom colour is being dragged, before it is kept.
|
||||
@@ -46,6 +46,7 @@ export function PlaceFormTags({ tags, t }: { tags: PlaceTagsField; t: Translate
|
||||
setPalette(null);
|
||||
setPreview(null);
|
||||
};
|
||||
if (!manage && tags.options.length === 0) return null;
|
||||
|
||||
return (
|
||||
<div className={PANEL}>
|
||||
@@ -59,15 +60,19 @@ export function PlaceFormTags({ tags, t }: { tags: PlaceTagsField; t: Translate
|
||||
className={`${PILL} ${tag.on ? '' : PILL_OFF}`}
|
||||
style={tag.on ? { background: tint(color, 18), borderColor: tint(color, 55) } : undefined}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t('places.tagColor', { name: tag.name })}
|
||||
aria-expanded={palette === tag.id}
|
||||
onClick={() => (palette === tag.id ? closePalette() : setPalette(tag.id))}
|
||||
className={DOT_BUTTON}
|
||||
>
|
||||
<span aria-hidden="true" className={DOT} style={{ background: color }} />
|
||||
</button>
|
||||
{manage ? (
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t('places.tagColor', { name: tag.name })}
|
||||
aria-expanded={palette === tag.id}
|
||||
onClick={() => (palette === tag.id ? closePalette() : setPalette(tag.id))}
|
||||
className={DOT_BUTTON}
|
||||
>
|
||||
<span aria-hidden="true" className={DOT} style={{ background: color }} />
|
||||
</button>
|
||||
) : (
|
||||
<span aria-hidden="true" className={`${DOT} ms-2`} style={{ background: color }} />
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
aria-pressed={tag.on}
|
||||
@@ -95,55 +100,57 @@ export function PlaceFormTags({ tags, t }: { tags: PlaceTagsField; t: Translate
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
<span
|
||||
className={NEW_TAG}
|
||||
style={{
|
||||
background: tint(tags.newColor, typing ? 14 : 6),
|
||||
borderColor: tint(tags.newColor, typing ? 60 : 35),
|
||||
borderStyle: typing ? 'solid' : 'dashed',
|
||||
}}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t('places.newTagColor')}
|
||||
aria-expanded={palette === 'new'}
|
||||
onClick={() => (palette === 'new' ? closePalette() : setPalette('new'))}
|
||||
className={DOT_BUTTON}
|
||||
{manage && (
|
||||
<span
|
||||
className={NEW_TAG}
|
||||
style={{
|
||||
background: tint(tags.newColor, typing ? 14 : 6),
|
||||
borderColor: tint(tags.newColor, typing ? 60 : 35),
|
||||
borderStyle: typing ? 'solid' : 'dashed',
|
||||
}}
|
||||
>
|
||||
<span aria-hidden="true" className={DOT} style={{ background: tags.newColor }} />
|
||||
</button>
|
||||
<input
|
||||
type="text"
|
||||
value={tags.name}
|
||||
onChange={(e) => tags.setName(e.target.value)}
|
||||
onKeyDown={tags.handleNameKey}
|
||||
maxLength={TRIP_TAG_NAME_MAX}
|
||||
aria-label={t('places.newTag')}
|
||||
placeholder={t('places.newTag')}
|
||||
className={NEW_TAG_INPUT}
|
||||
style={fs(12, 'body')}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void tags.addNew()}
|
||||
disabled={!tags.canAdd}
|
||||
aria-label={t('places.addTag')}
|
||||
className={ADD_BUTTON}
|
||||
style={tags.canAdd ? { background: tags.newColor, color: 'var(--bg-card)' } : undefined}
|
||||
>
|
||||
<Plus size={13} strokeWidth={2.8} />
|
||||
</button>
|
||||
{palette === 'new' && (
|
||||
<TagColorPopover
|
||||
label={t('places.newTagColor')}
|
||||
value={tags.newColor}
|
||||
onPick={tags.setNewColor}
|
||||
onPreview={tags.setNewColor}
|
||||
onClose={closePalette}
|
||||
t={t}
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t('places.newTagColor')}
|
||||
aria-expanded={palette === 'new'}
|
||||
onClick={() => (palette === 'new' ? closePalette() : setPalette('new'))}
|
||||
className={DOT_BUTTON}
|
||||
>
|
||||
<span aria-hidden="true" className={DOT} style={{ background: tags.newColor }} />
|
||||
</button>
|
||||
<input
|
||||
type="text"
|
||||
value={tags.name}
|
||||
onChange={(e) => tags.setName(e.target.value)}
|
||||
onKeyDown={tags.handleNameKey}
|
||||
maxLength={TRIP_TAG_NAME_MAX}
|
||||
aria-label={t('places.newTag')}
|
||||
placeholder={t('places.newTag')}
|
||||
className={NEW_TAG_INPUT}
|
||||
style={fs(12, 'body')}
|
||||
/>
|
||||
)}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void tags.addNew()}
|
||||
disabled={!tags.canAdd}
|
||||
aria-label={t('places.addTag')}
|
||||
className={ADD_BUTTON}
|
||||
style={tags.canAdd ? { background: tags.newColor, color: 'var(--bg-card)' } : undefined}
|
||||
>
|
||||
<Plus size={13} strokeWidth={2.8} />
|
||||
</button>
|
||||
{palette === 'new' && (
|
||||
<TagColorPopover
|
||||
label={t('places.newTagColor')}
|
||||
value={tags.newColor}
|
||||
onPick={tags.setNewColor}
|
||||
onPreview={tags.setNewColor}
|
||||
onClose={closePalette}
|
||||
t={t}
|
||||
/>
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</DialogSection>
|
||||
</div>
|
||||
|
||||
@@ -36,6 +36,7 @@ export function PlaceFormTexts({
|
||||
notes,
|
||||
dayNotes,
|
||||
dayNumber = null,
|
||||
initialTab,
|
||||
onChange,
|
||||
t,
|
||||
}: {
|
||||
@@ -46,10 +47,11 @@ export function PlaceFormTexts({
|
||||
dayNotes: string | null;
|
||||
/** The day that visit is on, to name the tab after it ("Only day 3"). */
|
||||
dayNumber?: number | null;
|
||||
initialTab?: PlaceTextField;
|
||||
onChange: (field: PlaceTextField, value: string) => void;
|
||||
t: Translate;
|
||||
}) {
|
||||
const { tabs, shown, setActive } = usePlaceTextTabs({ description, notes, dayNotes, dayNumber, t });
|
||||
const { tabs, shown, setActive } = usePlaceTextTabs({ description, notes, dayNotes, dayNumber, t, initialTab });
|
||||
const refs = {
|
||||
description: useRef<HTMLTextAreaElement | null>(null),
|
||||
notes: useRef<HTMLTextAreaElement | null>(null),
|
||||
@@ -102,7 +104,7 @@ export function PlaceFormTexts({
|
||||
value={tab.value}
|
||||
onChange={(e) => onChange(tab.field, e.target.value)}
|
||||
rows={3}
|
||||
maxLength={tab.maxLength}
|
||||
maxLength={initialTab && tab.field === 'assignment_notes' ? 500 : tab.maxLength}
|
||||
className={BARE_TEXTAREA}
|
||||
/>
|
||||
{tab.markdown && (
|
||||
|
||||
@@ -32,6 +32,7 @@ type Toast = ReturnType<typeof useToast>;
|
||||
export interface PlaceFormOptions {
|
||||
t: Translate;
|
||||
toast: Toast;
|
||||
initialForm?: PlaceFormData;
|
||||
/** Files and pictures pasted into the form become attachments only for a member who may upload. */
|
||||
canUploadFiles: boolean;
|
||||
}
|
||||
@@ -43,8 +44,8 @@ export interface PlaceFormOptions {
|
||||
* wrote (see mergeResult), the files chosen before the place exists, what the details
|
||||
* column describes, and the duplicate warning a first save of a new place may raise.
|
||||
*/
|
||||
export function usePlaceForm({ t, toast, canUploadFiles }: PlaceFormOptions) {
|
||||
const [form, setForm] = useState<PlaceFormData>(DEFAULT_FORM);
|
||||
export function usePlaceForm({ t, toast, canUploadFiles, initialForm = DEFAULT_FORM }: PlaceFormOptions) {
|
||||
const [form, setForm] = useState<PlaceFormData>(initialForm);
|
||||
// Which fields the last picked search result wrote. Anything in here belongs
|
||||
// to that place and goes when another is picked; anything outside it is the
|
||||
// user's and survives. See mergeResult.
|
||||
|
||||
@@ -0,0 +1,577 @@
|
||||
import type { PlaceClientOrigin, PlaceOpeningHours, RoadtripStopType, TourListItem } from '@trek/shared';
|
||||
import { guessCategoryId } from '@trek/shared';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useLocationBias } from '../../hooks/useLocationBias';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { useAddonStore } from '../../store/addonStore';
|
||||
import { useAuthStore } from '../../store/authStore';
|
||||
import { useCanDo } from '../../store/permissionsStore';
|
||||
import { useSettingsStore } from '../../store/settingsStore';
|
||||
import { useTripAddonEnabled } from '../../store/tripAddonsStore';
|
||||
import { useTripStore } from '../../store/tripStore';
|
||||
import type { Assignment, BudgetItem, Category, Place } from '../../types';
|
||||
import {
|
||||
DEFAULT_SERVICE_KIND,
|
||||
serviceStopChoice,
|
||||
type ServiceStopMode,
|
||||
type ServiceStopPlacement,
|
||||
} from '../Roadtrip/manualStop';
|
||||
import { STOP_KIND_BY_KEY } from '../Roadtrip/stopKinds';
|
||||
import { useToast } from '../shared/Toast';
|
||||
import type { BookingExpenseRequest } from './BookingCostsSection.types';
|
||||
import {
|
||||
DEFAULT_FORM,
|
||||
endsBeforeStart,
|
||||
findDuplicatePlace,
|
||||
formPin,
|
||||
mergeResult,
|
||||
placeEditForm,
|
||||
placeFormPayload,
|
||||
prefillForm,
|
||||
savedCategoryId,
|
||||
type PlaceFormData,
|
||||
type PlaceFormPayload,
|
||||
type PlacePrefill,
|
||||
} from './PlaceFormModal.helpers';
|
||||
import { useNewCategory, usePlaceForm } from './usePlaceForm';
|
||||
import { usePlaceImageField } from './usePlaceImageField';
|
||||
import { usePlaceRefresh } from './usePlaceRefresh';
|
||||
import { usePlaceSearch } from './usePlaceSearch';
|
||||
import { usePlaceTags } from './usePlaceTags';
|
||||
|
||||
interface PlaceSubmitData extends PlaceFormPayload {
|
||||
/**
|
||||
* Where a road-trip service stop belongs on the drive, worked out from the
|
||||
* coordinates being saved. Travels the same way `_pendingFiles` does: the planner
|
||||
* reads it, strips it, and assigns the new place at that position.
|
||||
*/
|
||||
_serviceStop?: ServiceStopPlacement | null;
|
||||
}
|
||||
|
||||
interface PlaceProposal {
|
||||
initialForm: PlaceFormData;
|
||||
existing: boolean;
|
||||
dayId: number | null;
|
||||
disabled: boolean;
|
||||
onPreview: (form: PlaceFormData) => void;
|
||||
onSave: (form: PlaceFormData) => void;
|
||||
}
|
||||
|
||||
interface PlaceFormModalBaseProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
place: Place | null;
|
||||
prefillCoords?:
|
||||
(PlacePrefill & { stop_type?: RoadtripStopType | null; duration_minutes?: number; category?: string }) | null;
|
||||
tripId: number;
|
||||
categories: Category[];
|
||||
onCategoryCreated?: (category: { name: string; color?: string; icon?: string }) => Promise<Category> | undefined;
|
||||
assignmentId: number | null;
|
||||
dayAssignments?: Assignment[];
|
||||
/** Mobile keeps the untouched single-column form; desktop adds the saved-place
|
||||
* picker column when the Collections addon is enabled. Sourced from the trip
|
||||
* planner's useIsPhone(). */
|
||||
isMobile?: boolean;
|
||||
/** Opens the Costs editor for this place's linked expense (#1298) — the same
|
||||
* seam the booking and transport modals use. */
|
||||
onOpenExpense?: (req: BookingExpenseRequest) => void;
|
||||
/**
|
||||
* Turns this into the form a road trip's service stop is added on: the category
|
||||
* control becomes the kind of stop, the costs section goes, and a row asks which leg
|
||||
* of the drive it belongs on. Absent, nothing about the form changes.
|
||||
*/
|
||||
serviceStop?: ServiceStopMode | null;
|
||||
/** Road trip mode is on, where a visit's End is when the drive leaves it. */
|
||||
roadtripActive?: boolean;
|
||||
/** TIME-02: the tour this place is, whose end the time fields work out from its start; absent for a plain place. */
|
||||
tour?: TourListItem | null;
|
||||
}
|
||||
|
||||
export type PlaceFormModalProps = PlaceFormModalBaseProps &
|
||||
(
|
||||
| { proposal: PlaceProposal; onSave?: never }
|
||||
| { proposal?: never; onSave: (data: PlaceSubmitData, files?: File[]) => Promise<{ id: number } | void> | void }
|
||||
);
|
||||
|
||||
/** Place create/edit form state: maps search + Google-URL resolve + autocomplete,
|
||||
* category creation, file attachments and submit. Keeps PlaceFormModal a thin
|
||||
* render over the form fields. */
|
||||
export function usePlaceFormModal(props: PlaceFormModalProps) {
|
||||
const {
|
||||
isOpen,
|
||||
onClose,
|
||||
onSave,
|
||||
place,
|
||||
prefillCoords,
|
||||
tripId,
|
||||
categories,
|
||||
onCategoryCreated,
|
||||
assignmentId,
|
||||
dayAssignments = [],
|
||||
isMobile = false,
|
||||
onOpenExpense,
|
||||
serviceStop = null,
|
||||
proposal,
|
||||
} = props;
|
||||
// Hidden while the addon is off, because the kinds only mean anything to the road trip
|
||||
// rail: on an instance without it they would be six labels that change nothing.
|
||||
const distanceUnit = useSettingsStore((s) => s.settings.distance_unit) || 'metric';
|
||||
const toast = useToast();
|
||||
const { t, locale } = useTranslation();
|
||||
const { placesEnrichEnabled } = useAuthStore();
|
||||
const can = useCanDo();
|
||||
const timeFormat = useSettingsStore((s) => s.settings.time_format) || '24h';
|
||||
const tripObj = useTripStore((s) => s.trip);
|
||||
const canUploadFiles = !proposal && can('file_upload', tripObj);
|
||||
const collectionsEnabled = useAddonStore((s) => s.isEnabled('collections'));
|
||||
const isBudgetEnabled = useTripAddonEnabled(tripId, 'budget');
|
||||
const deleteBudgetItem = useTripStore((s) => s.deleteBudgetItem);
|
||||
const {
|
||||
form,
|
||||
setForm,
|
||||
autoFilledRef,
|
||||
pendingFiles,
|
||||
addFilesFromInput,
|
||||
removeFile,
|
||||
handlePaste,
|
||||
isSaving,
|
||||
setIsSaving,
|
||||
duplicateWarning,
|
||||
detailsSelection,
|
||||
setDetailsSelection,
|
||||
openForm,
|
||||
handleChange: changeField,
|
||||
pickImage,
|
||||
adoptDescription,
|
||||
warnIfDuplicate,
|
||||
pendingImage,
|
||||
stageUpload,
|
||||
stageAttached,
|
||||
removeImage,
|
||||
} = usePlaceForm({ t, toast, canUploadFiles, initialForm: proposal?.initialForm });
|
||||
const image = usePlaceImageField({
|
||||
place,
|
||||
imageUrl: form.image_url,
|
||||
pendingImage,
|
||||
canUploadFiles,
|
||||
stageUpload,
|
||||
stageAttached,
|
||||
removeImage,
|
||||
});
|
||||
const tagField = usePlaceTags({ tripId, place, tags: form.tags, setForm, t, toast });
|
||||
// The index the picked place came from, as its row named it, shown as a pill
|
||||
// in the head band. Null for a place typed by hand or taken from the saved list.
|
||||
const [pickedSource, setPickedSource] = useState<string | null>(null);
|
||||
// Whether the category was preselected from a search result rather than chosen, so
|
||||
// the next pick may replace it and a hand choice is never overwritten (#2282).
|
||||
const categoryGuessedRef = useRef(false);
|
||||
const guessedCategory = (result: Record<string, unknown>): string => {
|
||||
const saved = savedCategoryId(result, categories || []); // a collection's place keeps its own (#3074)
|
||||
const id = saved ? null : guessCategoryId(result, categories || []);
|
||||
categoryGuessedRef.current = id != null;
|
||||
return saved ?? (id != null ? String(id) : '');
|
||||
};
|
||||
// The hours the details column looked up, as a week the contact block can take over (#2472).
|
||||
const [detailsHours, setDetailsHours] = useState<PlaceOpeningHours | null>(null);
|
||||
/**
|
||||
* The leg of the drive the traveller picked, or empty while the projection's own
|
||||
* answer stands. Empty rather than seeded, because there is nothing to project onto
|
||||
* until a place has been chosen and the answer has to follow the coordinates.
|
||||
*/
|
||||
const [serviceStopLeg, setServiceStopLeg] = useState('');
|
||||
const fileRef = useRef(null);
|
||||
// Set right before submit when the user clicked create/edit expense — the
|
||||
// place has to exist before an expense can point at it (see ReservationModal).
|
||||
const expenseIntentRef = useRef<{ editItem?: BudgetItem; create?: boolean } | null>(null);
|
||||
const newCategory = useNewCategory({
|
||||
variant: 'dialog',
|
||||
create: (category) => onCategoryCreated?.(category),
|
||||
onCreated: (categoryId) => setForm((prev) => ({ ...prev, category_id: categoryId })),
|
||||
t,
|
||||
toast,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
categoryGuessedRef.current = false;
|
||||
let next: PlaceFormData;
|
||||
if (proposal) {
|
||||
const { initialForm } = proposal;
|
||||
const pin = formPin(initialForm);
|
||||
const details = pin && {
|
||||
...pin,
|
||||
name: initialForm.name,
|
||||
address: initialForm.address,
|
||||
website: initialForm.website,
|
||||
phone: initialForm.phone,
|
||||
osm_id: initialForm.osm_id,
|
||||
google_place_id: initialForm.google_place_id,
|
||||
google_ftid: initialForm.google_ftid,
|
||||
amap_poi_id: initialForm.amap_poi_id,
|
||||
};
|
||||
openForm(initialForm, null, details);
|
||||
return;
|
||||
} else if (place) {
|
||||
const assignment = assignmentId ? dayAssignments.find((a) => a.id === assignmentId) : null;
|
||||
next = placeEditForm(place, assignment, {
|
||||
// Shown in the contact block now (#2472), so an edit carries what is there.
|
||||
phone: place.phone || '',
|
||||
email: place.email || '',
|
||||
opening_hours: place.opening_hours || '',
|
||||
// Carried through every edit. Without it, opening a fuel stop to fix a typo
|
||||
// submits an empty kind and turns it back into a numbered destination.
|
||||
// duration_minutes deliberately stays out: how long a stay takes belongs to the
|
||||
// rail's own dialog, and sending it from here would overwrite what was set there.
|
||||
stop_type: place.stop_type ?? null,
|
||||
});
|
||||
} else if (prefillCoords) {
|
||||
next = prefillForm(prefillCoords, {
|
||||
category_id: guessedCategory(prefillCoords),
|
||||
stop_type: prefillCoords.stop_type ?? null,
|
||||
duration_minutes: prefillCoords.duration_minutes,
|
||||
});
|
||||
} else if (serviceStop) {
|
||||
// A stop on a drive is a kind and a dwell before it is anything else, so the form
|
||||
// opens on one rather than on nothing: a service stop left without a kind is a
|
||||
// numbered destination that counts in every total, which is the very thing this
|
||||
// path exists to avoid. Read out of the closure rather than watched, because the
|
||||
// mode is fixed for the life of one opening and a rebuilt drive must not reset a
|
||||
// half-filled form.
|
||||
// What the corridor panel was looking for when the button was pressed, because
|
||||
// that is the traveller's own answer to what they are adding; only a panel with
|
||||
// nothing selected falls back to the constant. The dwell follows the kind, the
|
||||
// same way picking one by hand moves it.
|
||||
const kind = serviceStop.defaultKind ?? DEFAULT_SERVICE_KIND;
|
||||
next = {
|
||||
...DEFAULT_FORM,
|
||||
stop_type: kind,
|
||||
duration_minutes: STOP_KIND_BY_KEY[kind].defaultMinutes,
|
||||
};
|
||||
} else {
|
||||
next = DEFAULT_FORM;
|
||||
}
|
||||
// The column follows whatever the dialog was opened with, not only a search
|
||||
// pick: a POI tapped on the map and a right-click place arrive as
|
||||
// prefillCoords, and editing an existing place arrives as `place`.
|
||||
openForm(next, place, prefillCoords);
|
||||
setServiceStopLeg('');
|
||||
setPickedSource(null);
|
||||
// A fresh dialog owns no intention either. The ref is armed by a click on the Costs
|
||||
// section and spent by the save that follows it; a save that never happened leaves it
|
||||
// armed, and the next opening would consume it for a place nobody linked an expense
|
||||
// to. In service-stop mode that opening has no Costs section at all, so the editor
|
||||
// would arrive out of nowhere, on a petrol stop, filed as an activity.
|
||||
expenseIntentRef.current = null;
|
||||
// dayAssignments is a fresh array each render; read it at open-time only and
|
||||
// re-run on identity changes (place/assignmentId/open), not on every render.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [place, prefillCoords, isOpen, assignmentId]);
|
||||
|
||||
const places = useTripStore((s) => s.places);
|
||||
const tripDays = useTripStore((s) => s.days);
|
||||
// Where the trip is happening — the hint that tells the search which of a
|
||||
// thousand identically named places is meant. Autocomplete wants a box, the
|
||||
// search wants a point; both are derived from the same places.
|
||||
const { box: locationBias } = useLocationBias();
|
||||
|
||||
/**
|
||||
* The one point every pick flows through, so the detail column hangs here: a
|
||||
* search row, a suggestion's place, or a place from the saved-place picker.
|
||||
* `label` is the name the picked row's badge carried; a saved place names none.
|
||||
*/
|
||||
const applyPickedPlace = (result: Record<string, unknown>, label: string | null) => {
|
||||
setForm((prev) => {
|
||||
const merged = mergeResult(prev, result, autoFilledRef.current);
|
||||
if (prev.category_id && !categoryGuessedRef.current) return merged;
|
||||
return { ...merged, category_id: guessedCategory(result) };
|
||||
});
|
||||
setPickedSource(label);
|
||||
// A new pick drops whatever hero image belonged to the previous place.
|
||||
const lat = Number(result.lat);
|
||||
const lng = Number(result.lng);
|
||||
if (Number.isFinite(lat) && Number.isFinite(lng)) {
|
||||
setDetailsSelection({
|
||||
placeId: (result.google_place_id || result.amap_poi_id || result.osm_id || undefined) as string | undefined,
|
||||
lat,
|
||||
lng,
|
||||
name: (result.name as string) || '',
|
||||
// Hand the record along: the server needs the same OSM tags, and
|
||||
// looking them up again costs an Overpass round trip it can skip.
|
||||
details: result,
|
||||
});
|
||||
setForm((prev) => ({ ...prev, image_url: undefined }));
|
||||
}
|
||||
};
|
||||
|
||||
const search = usePlaceSearch({
|
||||
variant: 'dialog',
|
||||
locationBias,
|
||||
t,
|
||||
toast,
|
||||
// The planner keeps this dialog mounted while it is closed (the shell only
|
||||
// stops drawing it), so the search block is reset when it closes, apart from
|
||||
// the opening effect above: that one also reruns while the dialog is open, when
|
||||
// a right-click's reverse lookup fills prefillCoords, and must not wipe a
|
||||
// search the user has started since.
|
||||
open: isOpen,
|
||||
onPlace: applyPickedPlace,
|
||||
onSuggestionName: (name) => setForm((prev) => ({ ...prev, name })),
|
||||
onMapLink: (resolved) => {
|
||||
setForm((prev) => ({
|
||||
...prev,
|
||||
name: resolved.name || prev.name,
|
||||
address: resolved.address || prev.address,
|
||||
lat: String(resolved.lat),
|
||||
lng: String(resolved.lng),
|
||||
google_ftid: resolved.google_ftid || prev.google_ftid,
|
||||
}));
|
||||
// The fields are the link's now, not the last picked result's.
|
||||
setPickedSource(null);
|
||||
},
|
||||
});
|
||||
const refresh = usePlaceRefresh({ place, form, language: search.language });
|
||||
|
||||
/**
|
||||
* What a stop on a drive might be a second copy of, said while the form is being filled.
|
||||
*
|
||||
* By the map record and by where it stands, never by its name: two Arals on one
|
||||
* motorway are two petrol stations, and a check that called them one refused the save
|
||||
* the first time it was pressed. This one refuses nothing: it is a note beside the
|
||||
* name, and the reader decides.
|
||||
*/
|
||||
const serviceStopDuplicate = useMemo(() => {
|
||||
if (!serviceStop || place) return null;
|
||||
return findDuplicatePlace(form, places, { byName: false, byOsmId: true })?.name ?? null;
|
||||
}, [serviceStop, place, form, places]);
|
||||
|
||||
const handleChange = (field: string, value: string, origin?: PlaceClientOrigin) => {
|
||||
if (field === 'category_id') categoryGuessedRef.current = false;
|
||||
changeField(field, value, origin);
|
||||
};
|
||||
|
||||
// What is around the pin the form holds (#976).
|
||||
const pin = formPin(form);
|
||||
const handleNearby = () => search.searchNearby(pin);
|
||||
|
||||
/**
|
||||
* The kind of stop, and with it how long that kind usually takes.
|
||||
*
|
||||
* Picking a kind is also picking a dwell, until the user says otherwise: a charge is
|
||||
* not a fuel stop. Only ever called for a kind that is not already on, so a dwell set
|
||||
* by hand survives a second click on the same pill.
|
||||
*/
|
||||
const handleStopKind = useCallback(
|
||||
(kind: RoadtripStopType) => {
|
||||
setForm((prev) => ({ ...prev, stop_type: kind, duration_minutes: STOP_KIND_BY_KEY[kind].defaultMinutes }));
|
||||
},
|
||||
[setForm]
|
||||
);
|
||||
|
||||
const handleStopMinutes = useCallback(
|
||||
(minutes: number) => {
|
||||
setForm((prev) => ({ ...prev, duration_minutes: minutes }));
|
||||
},
|
||||
[setForm]
|
||||
);
|
||||
|
||||
const hasTimeError = !!(place || proposal) && endsBeforeStart(form.place_time, form.end_time);
|
||||
const previewDraft = proposal?.onPreview;
|
||||
useEffect(() => {
|
||||
if (isOpen) previewDraft?.(form);
|
||||
}, [form, isOpen, previewDraft]);
|
||||
|
||||
const saveProposal = (draft: PlaceProposal) => {
|
||||
if (draft.disabled || hasTimeError) return;
|
||||
try {
|
||||
draft.onSave(form);
|
||||
onClose();
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : t('places.saveError'));
|
||||
}
|
||||
};
|
||||
|
||||
const openExpenseAfterSave = (saved: { id: number } | void) => {
|
||||
const intent = expenseIntentRef.current;
|
||||
expenseIntentRef.current = null;
|
||||
const savedId = (saved && 'id' in saved ? saved.id : null) ?? place?.id ?? null;
|
||||
if (!intent || !onOpenExpense || !savedId) return;
|
||||
if (intent.editItem) onOpenExpense({ editItem: intent.editItem });
|
||||
else onOpenExpense({ prefill: { placeId: savedId, name: form.name.trim(), category: 'activities' } });
|
||||
};
|
||||
|
||||
const handleSubmit = async (e?: { preventDefault?: () => void }) => {
|
||||
e?.preventDefault?.();
|
||||
if (!form.name.trim()) {
|
||||
// Nothing was saved, so an expense intent from a previous click is stale —
|
||||
// otherwise the next plain Save would open a Costs editor out of nowhere.
|
||||
expenseIntentRef.current = null;
|
||||
toast.error(t('places.nameRequired'));
|
||||
return;
|
||||
}
|
||||
if (proposal) return saveProposal(proposal);
|
||||
// #1152: only for new places, and only on the first attempt — a second click
|
||||
// (with the warning already showing) is the explicit "add anyway" confirmation.
|
||||
//
|
||||
// Never for a stop on a drive. Most of what that check catches is a repeated name,
|
||||
// and on a motorway a repeated name is the normal case: the second Aral is four
|
||||
// hundred kilometres from the first and is a different petrol station. The popup this
|
||||
// path replaced compared the OSM object for exactly that reason and never gated the
|
||||
// save on it, only noted it. So the note is shown beside the name while the form is
|
||||
// being filled (see serviceStopDuplicate), which is the earlier word anyway, and the
|
||||
// press that saves is the press that saves.
|
||||
if (!place && !serviceStop && !duplicateWarning && warnIfDuplicate(places)) {
|
||||
// Nothing was saved, so an expense intent from a previous click is stale, and
|
||||
// the next plain Save would otherwise open a Costs editor out of nowhere.
|
||||
expenseIntentRef.current = null;
|
||||
return;
|
||||
}
|
||||
setIsSaving(true);
|
||||
try {
|
||||
const ctxAssignment = assignmentId ? dayAssignments.find((a) => a.id === assignmentId) : null;
|
||||
const payload = placeFormPayload(
|
||||
form,
|
||||
pendingFiles,
|
||||
ctxAssignment,
|
||||
(lat, lng) => ({
|
||||
// An explicit null is how a stop stops being a fuel stop; the service reads it
|
||||
// that way rather than as "leave alone", which is what a missing key means.
|
||||
stop_type: form.stop_type || null,
|
||||
// Only on the way in, and only with a kind: it is the popup's suggestion for how
|
||||
// long that kind of pause takes. On an edit it is left out entirely, because the
|
||||
// stay belongs to the rail's dialog and sending it here would overwrite it.
|
||||
...(!place && form.stop_type && form.duration_minutes ? { duration_minutes: form.duration_minutes } : {}),
|
||||
// Where on the drive it goes, worked out HERE and not when the dialog opened: a
|
||||
// stop added by hand has no coordinates at all until a place has been chosen in
|
||||
// it, so the answer has to follow what is actually being saved.
|
||||
...(serviceStop ? { _serviceStop: serviceStopChoice(serviceStop, lat, lng, serviceStopLeg).placement } : {}),
|
||||
}),
|
||||
pendingImage
|
||||
);
|
||||
const saved = await onSave?.(payload);
|
||||
// Open the Costs editor for the saved place when the user asked to
|
||||
// create/edit its linked expense — gated on an id, so a create that the
|
||||
// server refused never opens an editor pointing at nothing (#1298).
|
||||
openExpenseAfterSave(saved);
|
||||
onClose();
|
||||
} catch (err: unknown) {
|
||||
// The save did not happen, so the intent behind it cannot be honoured: the place
|
||||
// the expense would point at does not exist. Left armed it would ride along to
|
||||
// whatever the next press saves.
|
||||
expenseIntentRef.current = null;
|
||||
toast.error(err instanceof Error ? err.message : t('places.saveError'));
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleCreateExpense = () => {
|
||||
expenseIntentRef.current = { create: true };
|
||||
void handleSubmit();
|
||||
};
|
||||
const handleEditExpense = (item: BudgetItem) => {
|
||||
expenseIntentRef.current = { editItem: item };
|
||||
void handleSubmit();
|
||||
};
|
||||
const handleRemoveExpense = async (item: BudgetItem) => {
|
||||
try {
|
||||
await deleteBudgetItem(Number(tripId), item.id);
|
||||
} catch {
|
||||
toast.error(t('common.unknownError'));
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
isOpen,
|
||||
onClose,
|
||||
place,
|
||||
prefillCoords,
|
||||
categories,
|
||||
assignmentId,
|
||||
dayAssignments,
|
||||
dayNumber: proposal
|
||||
? (tripDays.find((day) => day.id === proposal.dayId)?.day_number ?? null)
|
||||
: dayNumberOf(assignmentId, dayAssignments, tripDays),
|
||||
isMobile,
|
||||
collectionsEnabled,
|
||||
form,
|
||||
mapsSearch: search.query,
|
||||
setMapsSearch: search.setQuery,
|
||||
mapsResults: search.results,
|
||||
isSearchingMaps: search.searching,
|
||||
newCategoryName: newCategory.name,
|
||||
setNewCategoryName: newCategory.setName,
|
||||
showNewCategory: newCategory.open,
|
||||
setShowNewCategory: newCategory.setOpen,
|
||||
isSaving,
|
||||
pendingFiles,
|
||||
emptySearch: search.emptySearch,
|
||||
setEmptySearch: search.setEmptySearch,
|
||||
detailsHours,
|
||||
setDetailsHours,
|
||||
fileRef,
|
||||
acSuggestions: search.suggestions,
|
||||
setAcSuggestions: search.setSuggestions,
|
||||
acSource: search.acSource,
|
||||
searchSource: search.searchSource,
|
||||
acHighlight: search.highlight,
|
||||
setAcHighlight: search.setHighlight,
|
||||
t,
|
||||
language: search.language,
|
||||
locale,
|
||||
refresh,
|
||||
timeFormat,
|
||||
googleAnswers: search.googleAnswers,
|
||||
placesEnrichEnabled,
|
||||
canUploadFiles,
|
||||
locationBias,
|
||||
fetchSuggestions: search.fetchSuggestions,
|
||||
sourceLabel: search.sourceLabel,
|
||||
handleChange,
|
||||
handleMapsSearch: search.runSearch,
|
||||
handleNearby,
|
||||
pin,
|
||||
nearbyList: search.nearbyList,
|
||||
distanceUnit,
|
||||
handleSelectMapsResult: search.pickPlace,
|
||||
handleSelectSuggestion: search.selectSuggestion,
|
||||
handleSearchKeyDown: search.handleKeyDown,
|
||||
handleCreateCategory: newCategory.submit,
|
||||
handleFileAdd: addFilesFromInput,
|
||||
handleRemoveFile: removeFile,
|
||||
handlePaste,
|
||||
pickImage,
|
||||
image,
|
||||
tagField,
|
||||
adoptDescription,
|
||||
hasTimeError,
|
||||
handleSubmit,
|
||||
duplicateWarning,
|
||||
pickedSource,
|
||||
detailsSelection,
|
||||
isBudgetEnabled,
|
||||
handleCreateExpense,
|
||||
handleEditExpense,
|
||||
handleRemoveExpense,
|
||||
serviceStop,
|
||||
serviceStopDuplicate,
|
||||
serviceStopLeg,
|
||||
setServiceStopLeg,
|
||||
handleStopKind,
|
||||
handleStopMinutes,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Detail column, form and saved places side by side, inside the scrolling body
|
||||
* rather than as it: a row that scrolled itself would stretch the side columns
|
||||
* to the visible height only, and they would end halfway down the form.
|
||||
*/
|
||||
/** The number of the day the edited visit is on, for the day note's tab; null when it is not known. */
|
||||
function dayNumberOf(
|
||||
assignmentId: number | null,
|
||||
visits: Assignment[],
|
||||
days: { id: number; day_number?: number | null }[]
|
||||
): number | null {
|
||||
if (!assignmentId) return null;
|
||||
const dayId = visits.find((visit) => visit.id === assignmentId)?.day_id;
|
||||
return days.find((day) => day.id === dayId)?.day_number ?? null;
|
||||
}
|
||||
@@ -25,6 +25,7 @@ interface PlaceTextTabsOptions {
|
||||
dayNotes: string | null;
|
||||
/** The day that visit is on, to name the tab after it ("Only day 3"). */
|
||||
dayNumber?: number | null;
|
||||
initialTab?: PlaceTextField;
|
||||
t: Translate;
|
||||
}
|
||||
|
||||
@@ -34,8 +35,15 @@ interface PlaceTextTabsOptions {
|
||||
* The one logic path behind the desktop card and the phone sheet; each draws its
|
||||
* own tabs and field over it.
|
||||
*/
|
||||
export function usePlaceTextTabs({ description, notes, dayNotes, dayNumber = null, t }: PlaceTextTabsOptions) {
|
||||
const [active, setActive] = useState<PlaceTextField>('description');
|
||||
export function usePlaceTextTabs({
|
||||
description,
|
||||
notes,
|
||||
dayNotes,
|
||||
dayNumber = null,
|
||||
t,
|
||||
initialTab = 'description',
|
||||
}: PlaceTextTabsOptions) {
|
||||
const [active, setActive] = useState<PlaceTextField>(initialTab);
|
||||
const tabs: PlaceTextTab[] = [
|
||||
{
|
||||
field: 'description',
|
||||
|
||||
@@ -142,12 +142,12 @@ describe('TripFormModal', () => {
|
||||
const trip = buildTrip({ id: 1, title: 'Iceland Adventure' });
|
||||
render(<TripFormModal {...defaultProps} trip={trip} />);
|
||||
expect(screen.getByDisplayValue('Iceland Adventure')).toBeInTheDocument();
|
||||
expect(screen.getByRole('textbox', { name: 'Title' }).closest('header')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-TRIPFORM-012: shows Title label', () => {
|
||||
it('FE-COMP-TRIPFORM-012: puts the only trip title field in the dialog header', () => {
|
||||
render(<TripFormModal {...defaultProps} />);
|
||||
// dashboard.tripTitle = "Title"
|
||||
expect(screen.getByText('Title')).toBeInTheDocument();
|
||||
expect(screen.getByRole('textbox', { name: 'Title' }).closest('header')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-TRIPFORM-013: shows Cover Image section', () => {
|
||||
|
||||
@@ -513,27 +513,30 @@ export default function TripFormModal({
|
||||
<div className={`${panelCls} flex-1`}>
|
||||
<CardHead
|
||||
icon={<Type size={16} strokeWidth={2} />}
|
||||
title={t('trip.form.aboutTitle')}
|
||||
hint={t('trip.form.aboutHint')}
|
||||
title={embedded ? t('trip.form.aboutTitle') : t('dashboard.tripDescription')}
|
||||
hint={embedded ? t('trip.form.aboutHint') : undefined}
|
||||
/>
|
||||
<div>
|
||||
<label className={labelCls}>
|
||||
{t('dashboard.tripTitle')} <span className="text-danger">*</span>
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={formData.title}
|
||||
onChange={(e) => canEditTrip && update('title', e.target.value)}
|
||||
required
|
||||
readOnly={!canEditTrip}
|
||||
placeholder={t('dashboard.tripTitlePlaceholder')}
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
{embedded && (
|
||||
<div>
|
||||
<label className={labelCls}>
|
||||
{t('dashboard.tripTitle')} <span className="text-danger">*</span>
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={formData.title}
|
||||
onChange={(e) => canEditTrip && update('title', e.target.value)}
|
||||
required
|
||||
readOnly={!canEditTrip}
|
||||
placeholder={t('dashboard.tripTitlePlaceholder')}
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div>
|
||||
<label className={labelCls}>{t('dashboard.tripDescription')}</label>
|
||||
{embedded && <label className={labelCls}>{t('dashboard.tripDescription')}</label>}
|
||||
<textarea
|
||||
aria-label={t('dashboard.tripDescription')}
|
||||
value={formData.description}
|
||||
onChange={(e) => canEditTrip && update('description', e.target.value)}
|
||||
readOnly={!canEditTrip}
|
||||
@@ -830,9 +833,23 @@ export default function TripFormModal({
|
||||
}
|
||||
: onClose
|
||||
}
|
||||
eyebrow={pendingReview ? undefined : isEditing ? t('dashboard.editTrip') : undefined}
|
||||
title={
|
||||
pendingReview ? reviewTitle : isEditing ? trip?.title || t('dashboard.editTrip') : t('dashboard.createTrip')
|
||||
eyebrow={pendingReview ? undefined : t(isEditing ? 'dashboard.editTrip' : 'dashboard.createTrip')}
|
||||
title={pendingReview ? reviewTitle : undefined}
|
||||
titleInput={
|
||||
pendingReview
|
||||
? undefined
|
||||
: {
|
||||
value: formData.title,
|
||||
label: t('dashboard.tripTitle'),
|
||||
placeholder: t('dashboard.tripTitlePlaceholder'),
|
||||
readOnly: !canEditTrip,
|
||||
required: true,
|
||||
onChange: (value) => canEditTrip && update('title', value),
|
||||
onKeyDown: (event) => {
|
||||
if (canEditTrip && !busy && event.key === 'Enter' && !event.nativeEvent.isComposing)
|
||||
void handleSubmit(event);
|
||||
},
|
||||
}
|
||||
}
|
||||
/>
|
||||
}
|
||||
|
||||
@@ -199,7 +199,8 @@ export interface HeaderTitleInput {
|
||||
/** The field's accessible name, e.g. the old "Title *" label. */
|
||||
label: string
|
||||
placeholder?: string
|
||||
autoFocus?: boolean
|
||||
autoFocus?: boolean;
|
||||
readOnly?: boolean;
|
||||
required?: boolean
|
||||
maxLength?: number
|
||||
onKeyDown?: (e: ReactKeyboardEvent<HTMLInputElement>) => void
|
||||
@@ -253,6 +254,7 @@ export function DialogHeader(p: DialogHeaderProps) {
|
||||
aria-label={f.label}
|
||||
placeholder={f.placeholder}
|
||||
ref={f.autoFocus ? focusRevealedEditor : undefined}
|
||||
readOnly={f.readOnly}
|
||||
required={f.required}
|
||||
maxLength={f.maxLength}
|
||||
className="-mx-2 block w-[calc(100%+16px)] rounded-[10px] border-0 bg-transparent px-2 py-0.5 font-bold tracking-[-0.01em] text-content outline-none placeholder:font-semibold placeholder:text-content-faint hover:bg-surface-card focus:bg-surface-card focus:shadow-sm dark:bg-transparent dark:hover:bg-surface-card dark:focus:bg-surface-card"
|
||||
|
||||
@@ -203,13 +203,13 @@ export function AddRowButton({ onClick, disabled, raised = false, children }: {
|
||||
* The head of a card in a dialog: an icon tile, the card's name and a line on
|
||||
* what it is for. The trip settings' cards all open with it.
|
||||
*/
|
||||
export function CardHead({ icon, title, hint }: { icon: ReactNode; title: string; hint: string }) {
|
||||
export function CardHead({ icon, title, hint }: { icon: ReactNode; title: string; hint?: string }) {
|
||||
return (
|
||||
<div className="flex items-start gap-2.5">
|
||||
<span className="grid h-8 w-8 flex-none place-items-center rounded-[10px] bg-surface-card text-content-muted shadow-sm">{icon}</span>
|
||||
<div className="min-w-0">
|
||||
<h3 className="m-0 font-semibold text-content" style={fs(13, 'body')}>{title}</h3>
|
||||
<p className="m-0 mt-0.5 leading-normal text-content-faint" style={fs(11.5)}>{hint}</p>
|
||||
{hint && <p className="m-0 mt-0.5 leading-normal text-content-faint" style={fs(11.5)}>{hint}</p>}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { isNativeApp } from '../native/platform';
|
||||
|
||||
/**
|
||||
* The phone shell's viewport: narrower than the md breakpoint (768px), or a
|
||||
* touch screen short enough to be a phone on its side.
|
||||
*
|
||||
* Width alone flipped a phone into the desktop planner the moment it was
|
||||
* turned: most phones are wider than 767px in landscape. That swapped the
|
||||
* whole route tree, so an open sheet, what was typed into it and the map's
|
||||
* position were gone. A tablet stays where it was, since none is under 500px
|
||||
* tall, and a desktop window keeps following its width, since its pointer is
|
||||
* fine.
|
||||
*
|
||||
* The phone rules in `index.css` repeat this query; keep them in step.
|
||||
*
|
||||
* The app is the exception: inside it the phone shell applies at every size.
|
||||
* An iPad, an iPad in Split View or Stage Manager and a foldable unfolded all
|
||||
* get the touch shell, laid out for their width (see `hooks/sizeClass.ts`), never
|
||||
* the desktop pages. Only that keeps one route tree across a fold, a
|
||||
* rotation or a window resize, so nothing open or typed is lost, and only the
|
||||
* touch shell has the app's own features (Wallet, sharing into a trip, the
|
||||
* edge swipe back).
|
||||
*/
|
||||
export const PHONE_QUERY = '(max-width: 767px), (pointer: coarse) and (max-height: 500px)';
|
||||
|
||||
/** Whether the phone shell applies right now, for code that is not a component. */
|
||||
export function isPhoneViewport(): boolean {
|
||||
if (isNativeApp()) return true;
|
||||
return (
|
||||
typeof window !== 'undefined' && typeof window.matchMedia === 'function' && window.matchMedia(PHONE_QUERY).matches
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* True while the phone shell applies (see {@link PHONE_QUERY}). Reactive:
|
||||
* follows viewport resizes and orientation changes via matchMedia.
|
||||
*/
|
||||
export function useIsPhone(): boolean {
|
||||
const [isPhone, setIsPhone] = useState(isPhoneViewport);
|
||||
|
||||
useEffect(() => {
|
||||
if (isNativeApp()) return;
|
||||
const mq = window.matchMedia(PHONE_QUERY);
|
||||
const handler = (e: MediaQueryListEvent) => setIsPhone(e.matches);
|
||||
setIsPhone(mq.matches);
|
||||
mq.addEventListener('change', handler);
|
||||
return () => mq.removeEventListener('change', handler);
|
||||
}, []);
|
||||
|
||||
return isPhone;
|
||||
}
|
||||
@@ -54,7 +54,7 @@ export default function MCollListNav({
|
||||
'flex w-full items-center gap-[10px] rounded-[11px] p-[10px] text-start outline-none focus-visible:ring-2 focus-visible:ring-[color:var(--m-act)]';
|
||||
return (
|
||||
<>
|
||||
{onSelectLibrary && (
|
||||
{onSelectLibrary && libraryCount !== 0 && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onSelectLibrary}
|
||||
|
||||
@@ -4,7 +4,6 @@ import {
|
||||
LayoutGrid, List, MapPin, Pencil, Plus, RefreshCw, Sparkles, Trash2, Users,
|
||||
} from 'lucide-react'
|
||||
import { useTranslation } from '../../../i18n'
|
||||
import MDancingTrek from '../../components/MDancingTrek'
|
||||
import { useDashboard } from '../../../pages/dashboard/useDashboard'
|
||||
import {
|
||||
type DashboardTrip, MS_PER_DAY, daysUntil, fullDate, getTripStatus,
|
||||
@@ -17,7 +16,7 @@ import type { TripCardBadge } from '../../../api/client'
|
||||
import MDemoWelcome from './MDemoWelcome'
|
||||
import { IcsSubscribeModal } from '../../../components/Planner/IcsSubscribeModal'
|
||||
import PluginWidgets from '../../../components/Plugins/PluginWidgets'
|
||||
import { entityGradient } from '../../../utils/gradients'
|
||||
import { entityGradient } from '../../../utils/gradients';
|
||||
import MGlassBar from '../../components/MGlassBar'
|
||||
import MIconBtn from '../../components/MIconBtn'
|
||||
import MSegmented from '../../components/MSegmented'
|
||||
@@ -174,7 +173,6 @@ export default function MDashboard(): React.ReactElement {
|
||||
|
||||
{showEmpty && (
|
||||
<div className="mt-[10px] flex flex-col items-center rounded-[20px] border border-[color:var(--m-gbr)] bg-[color:var(--m-glass)] px-4 py-8 text-center">
|
||||
<MDancingTrek scene="dashboard" size={96} className="mb-2" />
|
||||
<div className="text-[0.9375rem] font-bold">{t('dashboard.emptyTitle')}</div>
|
||||
<div className="mt-1 font-geist text-[0.6875rem] text-m-muted">{t('dashboard.emptyText')}</div>
|
||||
<button
|
||||
|
||||
@@ -151,8 +151,29 @@ export default function MNewTripSheet({ open, trip: tripProp, onClose, onSave, o
|
||||
<FormSheetHeader
|
||||
icon={Luggage}
|
||||
title={isEditing ? t('dashboard.editTrip') : t('dashboard.createTrip')}
|
||||
subtitle={isEditing ? trip?.title : undefined}
|
||||
onClose={onClose}
|
||||
titleField={
|
||||
<input
|
||||
type="text"
|
||||
value={title}
|
||||
onChange={(e) => {
|
||||
if (canEditTrip) {
|
||||
setError('');
|
||||
setTitle(e.target.value);
|
||||
}
|
||||
}}
|
||||
readOnly={!canEditTrip}
|
||||
required
|
||||
placeholder={t('dashboard.tripTitlePlaceholder')}
|
||||
aria-label={t('dashboard.tripTitle')}
|
||||
className="-ms-1 block min-h-10 w-full min-w-0 rounded-lg bg-transparent px-1 text-subtitle font-bold leading-tight text-m-ink outline-none placeholder:text-m-faint focus:bg-[color:var(--m-ic)] focus-visible:ring-2 focus-visible:ring-accent"
|
||||
onKeyDown={(e) => {
|
||||
if (!canEditTrip || busy || e.key !== 'Enter' || e.nativeEvent.isComposing) return;
|
||||
e.preventDefault();
|
||||
void handleSave();
|
||||
}}
|
||||
/>
|
||||
}
|
||||
onClose={onClose}
|
||||
closeLabel={t('common.cancel')}
|
||||
/>
|
||||
|
||||
@@ -165,16 +186,7 @@ export default function MNewTripSheet({ open, trip: tripProp, onClose, onSave, o
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Eyebrow className="mb-[5px] mt-2 uppercase">{t('dashboard.tripTitle')}</Eyebrow>
|
||||
<input
|
||||
value={title}
|
||||
onChange={e => { if (canEditTrip) { setError(''); setTitle(e.target.value) } }}
|
||||
readOnly={!canEditTrip}
|
||||
placeholder={t('dashboard.tripTitlePlaceholder')}
|
||||
aria-label={t('dashboard.tripTitle')}
|
||||
className={`${FIELD_CLS} font-semibold`}
|
||||
/>
|
||||
<Eyebrow className="mb-[5px] mt-3 uppercase">{t('dashboard.tripDescription')}</Eyebrow>
|
||||
<Eyebrow className="mb-[5px] mt-3 uppercase">{t('dashboard.tripDescription')}</Eyebrow>
|
||||
<textarea
|
||||
value={description}
|
||||
onChange={e => { if (canEditTrip) { setError(''); setDescription(e.target.value) } }}
|
||||
|
||||
@@ -89,7 +89,9 @@ import { SHEET_PRIMARY, SHEET_SECONDARY } from './MTripSheetUi'
|
||||
interface FormSheetHeaderProps {
|
||||
/** 40px rounded icon tile left of the title (place edit / import sheets). */
|
||||
icon?: LucideIcon
|
||||
title: ReactNode
|
||||
title: ReactNode;
|
||||
/** Editable name directly under the sheet actions's title. */
|
||||
titleField?: ReactNode;
|
||||
/** Geist 11.5px subline under the title (note sheet: "Day n · title"). */
|
||||
subtitle?: ReactNode
|
||||
/** Replaces the icon tile, e.g. a back button on the import sub-steps. */
|
||||
@@ -101,7 +103,9 @@ interface FormSheetHeaderProps {
|
||||
}
|
||||
|
||||
/** Form-sheet header: optional tile, 17px/700 title, 34px close. No hairline. */
|
||||
export function FormSheetHeader({ icon: Icon, title, subtitle, leading, trailing, onClose, closeLabel }: FormSheetHeaderProps) {
|
||||
export function FormSheetHeader({ icon: Icon, title,
|
||||
titleField,
|
||||
subtitle, leading, trailing, onClose, closeLabel }: FormSheetHeaderProps) {
|
||||
return (
|
||||
<div className="m-fs-head flex flex-none items-center gap-3 px-[18px] pb-2 pt-4">
|
||||
{leading}
|
||||
@@ -113,7 +117,16 @@ export function FormSheetHeader({ icon: Icon, title, subtitle, leading, trailing
|
||||
<div className="min-w-0 flex-1">
|
||||
{/* Two lines before it ends in an ellipsis: "Редактировать бронирование"
|
||||
and "Eintrag bearbeiten" were cut after one at phone width. */}
|
||||
<div className="line-clamp-2 break-words text-[1.0625rem] font-bold leading-tight text-m-ink">{title}</div>
|
||||
<div
|
||||
className={
|
||||
titleField
|
||||
? 'truncate font-geist text-caption font-bold uppercase tracking-wide text-m-muted'
|
||||
: 'line-clamp-2 break-words text-[1.0625rem] font-bold leading-tight text-m-ink'
|
||||
}
|
||||
>
|
||||
{title}
|
||||
</div>
|
||||
{titleField}
|
||||
{subtitle && <div className="truncate font-geist text-[0.71875rem] text-m-muted">{subtitle}</div>}
|
||||
</div>
|
||||
{trailing}
|
||||
|
||||
@@ -134,31 +134,49 @@ export default function MCostsTab({ planner, shell }: MTabScreenProps) {
|
||||
|
||||
// The summary: what the trip costs and who owes whom. Beside the expenses on
|
||||
// a window with room for two panes, above them everywhere else.
|
||||
const hasExpenses = budgetItems.length > 0;
|
||||
const summary = (
|
||||
<>
|
||||
{/* Hero — "Total Trip Spend" (spec §3.1). Fixed dark card, both themes. */}
|
||||
<div className="rounded-[20px] p-4 shadow-[0_18px_44px_-18px_rgba(0,0,0,.5)]" style={{ background: '#15151A', color: '#F5F5F7' }}>
|
||||
<div className="font-geist text-[0.625rem] font-bold uppercase tracking-[.09em]" style={{ color: 'rgba(245,245,247,.55)' }}>
|
||||
{t('costs.totalSpend')}
|
||||
</div>
|
||||
<div className="mt-1 font-geist text-[1.875rem] font-extrabold tabular-nums tracking-[-0.02em]">
|
||||
{formatMoney(totals.totalSpend, base, locale)}
|
||||
</div>
|
||||
{/* Categories left out below (#2819) leave this total too, which it says. */}
|
||||
{leftOutLabel && <div className="mt-[2px] text-caption opacity-70">{leftOutLabel}</div>}
|
||||
{/* Each figure under its own label, so the two pairs never read as one run.
|
||||
{hasExpenses && (
|
||||
<div
|
||||
className="rounded-[20px] p-4 shadow-[0_18px_44px_-18px_rgba(0,0,0,.5)]"
|
||||
style={{ background: '#15151A', color: '#F5F5F7' }}
|
||||
>
|
||||
<div
|
||||
className="font-geist text-[0.625rem] font-bold uppercase tracking-[.09em]"
|
||||
style={{ color: 'rgba(245,245,247,.55)' }}
|
||||
>
|
||||
{t('costs.totalSpend')}
|
||||
</div>
|
||||
<div className="mt-1 font-geist text-[1.875rem] font-extrabold tabular-nums tracking-[-0.02em]">
|
||||
{formatMoney(totals.totalSpend, base, locale)}
|
||||
</div>
|
||||
{/* Categories left out below (#2819) leave this total too, which it says. */}
|
||||
{leftOutLabel && <div className="mt-[2px] text-caption opacity-70">{leftOutLabel}</div>}
|
||||
{/* Each figure under its own label, so the two pairs never read as one run.
|
||||
Only with something to split (#2689), like everything owed below. */}
|
||||
{splitting && <div className="mt-[8px] flex flex-wrap gap-x-[22px] gap-y-[6px] text-[0.6875rem]" style={{ color: 'rgba(245,245,247,.7)' }}>
|
||||
<span className="flex flex-col">
|
||||
{t('costs.yourShare')}
|
||||
<b className="tabular-nums" style={{ color: '#F5F5F7' }}>{formatMoney(totals.myShare, base, locale)}</b>
|
||||
</span>
|
||||
<span className="flex flex-col">
|
||||
{t('costs.youPaid')}
|
||||
<b className="tabular-nums" style={{ color: '#F5F5F7' }}>{formatMoney(totals.myPaid, base, locale)}</b>
|
||||
</span>
|
||||
</div>}
|
||||
</div>
|
||||
{splitting && (
|
||||
<div
|
||||
className="mt-[8px] flex flex-wrap gap-x-[22px] gap-y-[6px] text-[0.6875rem]"
|
||||
style={{ color: 'rgba(245,245,247,.7)' }}
|
||||
>
|
||||
<span className="flex flex-col">
|
||||
{t('costs.yourShare')}
|
||||
<b className="tabular-nums" style={{ color: '#F5F5F7' }}>
|
||||
{formatMoney(totals.myShare, base, locale)}
|
||||
</b>
|
||||
</span>
|
||||
<span className="flex flex-col">
|
||||
{t('costs.youPaid')}
|
||||
<b className="tabular-nums" style={{ color: '#F5F5F7' }}>
|
||||
{formatMoney(totals.myPaid, base, locale)}
|
||||
</b>
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{splitting && <>
|
||||
{/* You owe / You're owed (spec §3.2). The two tiles stand level and each
|
||||
@@ -315,50 +333,68 @@ export default function MCostsTab({ planner, shell }: MTabScreenProps) {
|
||||
|
||||
{/* By category (spec §3.5). A tap leaves a category out of the totals
|
||||
for a look without it (#2819); the row stays, dimmed. */}
|
||||
<div className="mt-2 rounded-2xl border border-[color:var(--m-rowbr)] bg-m-card p-[13px]">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="font-geist text-[0.625rem] font-bold uppercase tracking-[.09em] text-m-faint">{t('costs.byCategory')}</div>
|
||||
{leftOutLabel && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={countAllCats}
|
||||
className="ms-auto flex flex-none items-center gap-1 rounded-full border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] px-[9px] py-[3px] text-caption font-semibold text-m-muted"
|
||||
>
|
||||
<RotateCcw size={11} strokeWidth={2.2} />
|
||||
{t('costs.breakdown.countAll')}
|
||||
</button>
|
||||
{hasExpenses && (
|
||||
<div className="mt-2 rounded-2xl border border-[color:var(--m-rowbr)] bg-m-card p-[13px]">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="font-geist text-[0.625rem] font-bold uppercase tracking-[.09em] text-m-faint">
|
||||
{t('costs.byCategory')}
|
||||
</div>
|
||||
{leftOutLabel && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={countAllCats}
|
||||
className="ms-auto flex flex-none items-center gap-1 rounded-full border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] px-[9px] py-[3px] text-caption font-semibold text-m-muted"
|
||||
>
|
||||
<RotateCcw size={11} strokeWidth={2.2} />
|
||||
{t('costs.breakdown.countAll')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{/* What is left out is said once, under the total above. */}
|
||||
{!leftOutLabel && catBreakdown.length > 1 && (
|
||||
<p className="mt-1 text-caption text-m-faint">{t('costs.breakdown.hint')}</p>
|
||||
)}
|
||||
{catBreakdown.length === 0 ? (
|
||||
<p className="mt-2 font-geist text-[0.71875rem] text-m-faint">{t('costs.noCategories')}</p>
|
||||
) : (
|
||||
catBreakdown.map((c) => {
|
||||
const meta = COST_CAT_META[c.key];
|
||||
const name = t(meta.labelKey);
|
||||
const action = c.leftOut
|
||||
? t('costs.breakdown.countIn', { category: name })
|
||||
: t('costs.breakdown.leaveOut', { category: name });
|
||||
return (
|
||||
<button
|
||||
key={c.key}
|
||||
type="button"
|
||||
aria-label={action}
|
||||
onClick={() => toggleLeftOutCat(c.key)}
|
||||
className={`block w-full pb-[2px] pt-[6px] text-start ${c.leftOut ? 'opacity-45' : ''}`}
|
||||
>
|
||||
<span className="flex items-center gap-[7px]">
|
||||
<span className="h-2 w-2 flex-none rounded-full" style={{ background: meta.color }} />
|
||||
<span className="min-w-0 flex-1 truncate font-geist text-[0.65625rem] font-semibold text-m-muted">
|
||||
{name}
|
||||
</span>
|
||||
<span
|
||||
dir="ltr"
|
||||
className={`ms-auto flex-none font-geist text-[0.65625rem] font-bold tabular-nums text-m-ink ${c.leftOut ? 'line-through' : ''}`}
|
||||
>
|
||||
{formatMoney(c.amount, base, locale)}
|
||||
</span>
|
||||
</span>
|
||||
<span className="mt-1 block h-1 overflow-hidden rounded-full bg-[color:var(--m-ic)]">
|
||||
<span
|
||||
className="block h-full rounded-full"
|
||||
style={{ width: `${c.widthPct}%`, background: meta.color }}
|
||||
/>
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
{/* What is left out is said once, under the total above. */}
|
||||
{!leftOutLabel && catBreakdown.length > 1 && <p className="mt-1 text-caption text-m-faint">{t('costs.breakdown.hint')}</p>}
|
||||
{catBreakdown.length === 0 ? (
|
||||
<p className="mt-2 font-geist text-[0.71875rem] text-m-faint">{t('costs.noCategories')}</p>
|
||||
) : (
|
||||
catBreakdown.map(c => {
|
||||
const meta = COST_CAT_META[c.key]
|
||||
const name = t(meta.labelKey)
|
||||
const action = c.leftOut ? t('costs.breakdown.countIn', { category: name }) : t('costs.breakdown.leaveOut', { category: name })
|
||||
return (
|
||||
<button
|
||||
key={c.key}
|
||||
type="button"
|
||||
aria-label={action}
|
||||
onClick={() => toggleLeftOutCat(c.key)}
|
||||
className={`block w-full pb-[2px] pt-[6px] text-start ${c.leftOut ? 'opacity-45' : ''}`}
|
||||
>
|
||||
<span className="flex items-center gap-[7px]">
|
||||
<span className="h-2 w-2 flex-none rounded-full" style={{ background: meta.color }} />
|
||||
<span className="min-w-0 flex-1 truncate font-geist text-[0.65625rem] font-semibold text-m-muted">{name}</span>
|
||||
<span dir="ltr" className={`ms-auto flex-none font-geist text-[0.65625rem] font-bold tabular-nums text-m-ink ${c.leftOut ? 'line-through' : ''}`}>{formatMoney(c.amount, base, locale)}</span>
|
||||
</span>
|
||||
<span className="mt-1 block h-1 overflow-hidden rounded-full bg-[color:var(--m-ic)]">
|
||||
<span className="block h-full rounded-full" style={{ width: `${c.widthPct}%`, background: meta.color }} />
|
||||
</span>
|
||||
</button>
|
||||
)
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{costsMode.offered && (
|
||||
<div className="mt-2 flex items-start gap-3 rounded-2xl border border-[color:var(--m-rowbr)] bg-m-card p-[13px]">
|
||||
@@ -382,8 +418,8 @@ export default function MCostsTab({ planner, shell }: MTabScreenProps) {
|
||||
|
||||
return (
|
||||
<>
|
||||
<TabPanes aside={summary} asideLabel={t('budget.title')}>
|
||||
{/* Expenses — header, search, filters (spec §3.6). One block, so on a wide
|
||||
<TabPanes aside={hasExpenses || splitting ? summary : null} asideLabel={t('budget.title')}>
|
||||
{/* Expenses — header, search, filters (spec §3.6). One block, so on a wide
|
||||
window the search field keeps to the column like the heading above it. */}
|
||||
<section aria-label={t('costs.expenses')}>
|
||||
{/* The currency the tab reads the trip in (#1683) sits by the heading, as on the desktop. */}
|
||||
@@ -564,7 +600,8 @@ export default function MCostsTab({ planner, shell }: MTabScreenProps) {
|
||||
)
|
||||
)}
|
||||
</section>
|
||||
</TabPanes>
|
||||
{!hasExpenses && !splitting && costsMode.offered && summary}
|
||||
</TabPanes>
|
||||
|
||||
{/* Add / edit expense — the shared desktop modal (spec §3.9); not rebuilt here. */}
|
||||
{expenseModalOpen && (
|
||||
|
||||
@@ -73,7 +73,7 @@ export function CardGrid({ children }: { children: ReactNode }) {
|
||||
* reader keeps their place: the row at the top of the list stays at the top.
|
||||
*/
|
||||
export function TabPanes({ aside, asideLabel, children }: { aside: ReactNode; asideLabel: string; children: ReactNode }) {
|
||||
const split = useIsSplit()
|
||||
const split = useIsSplit() && aside != null;
|
||||
const body = useRef<HTMLDivElement>(null)
|
||||
const list = useRef<HTMLDivElement>(null)
|
||||
// How far the list has moved under the top edge of its scroll body, read on
|
||||
|
||||
@@ -1,50 +1 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { isNativeApp } from '../native/platform'
|
||||
|
||||
/**
|
||||
* The phone shell's viewport: narrower than the md breakpoint (768px), or a
|
||||
* touch screen short enough to be a phone on its side.
|
||||
*
|
||||
* Width alone flipped a phone into the desktop planner the moment it was
|
||||
* turned: most phones are wider than 767px in landscape. That swapped the
|
||||
* whole route tree, so an open sheet, what was typed into it and the map's
|
||||
* position were gone. A tablet stays where it was, since none is under 500px
|
||||
* tall, and a desktop window keeps following its width, since its pointer is
|
||||
* fine.
|
||||
*
|
||||
* The phone rules in `index.css` repeat this query; keep them in step.
|
||||
*
|
||||
* The app is the exception: inside it the phone shell applies at every size.
|
||||
* An iPad, an iPad in Split View or Stage Manager and a foldable unfolded all
|
||||
* get the touch shell, laid out for their width (see `hooks/sizeClass.ts`), never
|
||||
* the desktop pages. Only that keeps one route tree across a fold, a
|
||||
* rotation or a window resize, so nothing open or typed is lost, and only the
|
||||
* touch shell has the app's own features (Wallet, sharing into a trip, the
|
||||
* edge swipe back).
|
||||
*/
|
||||
export const PHONE_QUERY = '(max-width: 767px), (pointer: coarse) and (max-height: 500px)'
|
||||
|
||||
/** Whether the phone shell applies right now, for code that is not a component. */
|
||||
export function isPhoneViewport(): boolean {
|
||||
if (isNativeApp()) return true
|
||||
return typeof window !== 'undefined' && typeof window.matchMedia === 'function' && window.matchMedia(PHONE_QUERY).matches
|
||||
}
|
||||
|
||||
/**
|
||||
* True while the phone shell applies (see {@link PHONE_QUERY}). Reactive:
|
||||
* follows viewport resizes and orientation changes via matchMedia.
|
||||
*/
|
||||
export function useIsPhone(): boolean {
|
||||
const [isPhone, setIsPhone] = useState(isPhoneViewport)
|
||||
|
||||
useEffect(() => {
|
||||
if (isNativeApp()) return
|
||||
const mq = window.matchMedia(PHONE_QUERY)
|
||||
const handler = (e: MediaQueryListEvent) => setIsPhone(e.matches)
|
||||
setIsPhone(mq.matches)
|
||||
mq.addEventListener('change', handler)
|
||||
return () => mq.removeEventListener('change', handler)
|
||||
}, [])
|
||||
|
||||
return isPhone
|
||||
}
|
||||
export { PHONE_QUERY, isPhoneViewport, useIsPhone } from '../hooks/useIsPhone';
|
||||
|
||||
@@ -1,11 +1,5 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
isNewCloudPlan,
|
||||
matchesPurchaseAgreement,
|
||||
opensSoon,
|
||||
planForUnclaimedPurchase,
|
||||
refundedBeforeOpening,
|
||||
} from './cloudOrders';
|
||||
import { isNewCloudPlan, opensSoon, planForUnclaimedPurchase, refundedBeforeOpening } from './cloudOrders';
|
||||
|
||||
describe('opensSoon', () => {
|
||||
const base = { available: true, closed: true, sandbox: false, onPlay: false };
|
||||
@@ -41,15 +35,6 @@ describe('refundedBeforeOpening', () => {
|
||||
});
|
||||
|
||||
describe('Cloud catalog and purchase recovery', () => {
|
||||
it('only carries the accepted agreement into a new purchase if the current version and text still match', () => {
|
||||
const accepted = { version: '2026-12-01', text: 'Agreed changes' };
|
||||
expect(matchesPurchaseAgreement(accepted, { ...accepted })).toBe(true);
|
||||
expect(matchesPurchaseAgreement(accepted, null)).toBe(false);
|
||||
expect(matchesPurchaseAgreement(null, accepted)).toBe(false);
|
||||
expect(matchesPurchaseAgreement(accepted, { ...accepted, version: '2026-12-02' })).toBe(false);
|
||||
expect(matchesPurchaseAgreement(accepted, { ...accepted, text: 'Changed conditions' })).toBe(false);
|
||||
});
|
||||
|
||||
it('only offers Start and Plus even when the server still lists retired plans', () => {
|
||||
expect(['start', 'basis', 'plus', 'pro'].filter(isNewCloudPlan)).toEqual(['start', 'plus']);
|
||||
});
|
||||
|
||||
@@ -29,21 +29,6 @@ export function isNewCloudPlan(id: string): boolean {
|
||||
return id === 'start' || id === 'plus';
|
||||
}
|
||||
|
||||
export interface CloudPurchaseAgreement {
|
||||
version: string;
|
||||
text: string;
|
||||
}
|
||||
|
||||
/** Recheck the agreement before opening the store sheet. No agreement means no new purchase. */
|
||||
export function matchesPurchaseAgreement(
|
||||
accepted: CloudPurchaseAgreement | null,
|
||||
current: CloudPurchaseAgreement | null
|
||||
): boolean {
|
||||
return (
|
||||
accepted !== null && current !== null && accepted.version === current.version && accepted.text === current.text
|
||||
);
|
||||
}
|
||||
|
||||
const PLAN_NAMES: Record<string, string> = { start: 'Start', basis: 'Basis', plus: 'Plus', pro: 'Pro' };
|
||||
|
||||
/** A verified purchase can predate the current offer and still need its instance set up. */
|
||||
|
||||
@@ -84,22 +84,15 @@ describe('native client', () => {
|
||||
expect(await fakeIapClient.isSandbox()).toBe(true);
|
||||
});
|
||||
|
||||
it('maps the regular price and explicitly confirmed trial by product', async () => {
|
||||
shell.storeProducts.mockResolvedValue({
|
||||
products: [
|
||||
{ id: 'cloud.plus.monthly', displayPrice: '9,99 €', freeTrial: true },
|
||||
{ id: 'cloud.start.monthly', displayPrice: '4,99 €' },
|
||||
],
|
||||
});
|
||||
const ids = ['cloud.plus.monthly', 'cloud.start.monthly', 'cloud.plus.yearly'];
|
||||
const products = await nativeIapClient.products(ids);
|
||||
expect(shell.storeProducts).toHaveBeenCalledWith({ ids });
|
||||
expect(products.get('cloud.plus.monthly')).toEqual({ displayPrice: '9,99 €', freeTrial: true });
|
||||
expect(products.get('cloud.start.monthly')).toEqual({ displayPrice: '4,99 €', freeTrial: false });
|
||||
expect(products.has('cloud.plus.yearly')).toBe(false);
|
||||
it('maps the store price strings by product', async () => {
|
||||
shell.storeProducts.mockResolvedValue({ products: [{ id: 'cloud.plus.monthly', displayPrice: '9,99 €' }] });
|
||||
const prices = await nativeIapClient.prices(['cloud.plus.monthly', 'cloud.pro.monthly']);
|
||||
expect(shell.storeProducts).toHaveBeenCalledWith({ ids: ['cloud.plus.monthly', 'cloud.pro.monthly'] });
|
||||
expect(prices.get('cloud.plus.monthly')).toBe('9,99 €');
|
||||
expect(prices.has('cloud.pro.monthly')).toBe(false);
|
||||
|
||||
shell.storeProducts.mockRejectedValue(new Error('down'));
|
||||
expect((await nativeIapClient.products(['cloud.plus.monthly'])).size).toBe(0);
|
||||
expect((await nativeIapClient.prices(['cloud.plus.monthly'])).size).toBe(0);
|
||||
});
|
||||
|
||||
it('turns a bought transaction into a receipt', async () => {
|
||||
@@ -131,15 +124,6 @@ describe('native client', () => {
|
||||
expect(await nativeIapClient.held()).toBe(false);
|
||||
});
|
||||
|
||||
it('asks the store to preserve an advertised trial and reports a changed offer without retrying as paid', async () => {
|
||||
shell.storePurchase.mockResolvedValue({ kind: 'offer-changed' });
|
||||
expect(await nativeIapClient.purchase('cloud.plus.monthly', '9,99 €')).toEqual({ kind: 'offer-changed' });
|
||||
expect(shell.storePurchase).toHaveBeenCalledExactlyOnceWith({
|
||||
productId: 'cloud.plus.monthly',
|
||||
trialRenewalPrice: '9,99 €',
|
||||
});
|
||||
});
|
||||
|
||||
it('a build without storeHeld counts as holding nothing; the purchase still guards', async () => {
|
||||
shell.storeHeld.mockRejectedValue(new Error('not implemented'));
|
||||
expect(await nativeIapClient.held()).toBe(false);
|
||||
|
||||
+11
-22
@@ -38,23 +38,17 @@ type PurchaseOutcome =
|
||||
| { kind: 'cancelled' }
|
||||
| { kind: 'pending' }
|
||||
| { kind: 'failed' }
|
||||
| { kind: 'offer-changed' }
|
||||
| { kind: 'subscribed' };
|
||||
|
||||
export interface IapProduct {
|
||||
displayPrice: string;
|
||||
/** The store confirms an eligible first week at no charge. */
|
||||
freeTrial: boolean;
|
||||
}
|
||||
|
||||
export interface IapClient {
|
||||
/** Whether this build can take a payment. */
|
||||
isAvailable(): Promise<boolean>;
|
||||
/**
|
||||
* Store pricing and offer eligibility by product id. A missing product cannot
|
||||
* be bought. Empty for the fake, whose prices come from the plan list.
|
||||
* The store's own price strings by product id, in the buyer's currency. A
|
||||
* product missing from the map cannot be bought here. Empty for the fake, whose
|
||||
* prices come from the plan list.
|
||||
*/
|
||||
products(productIds: string[]): Promise<Map<string, IapProduct>>;
|
||||
prices(productIds: string[]): Promise<Map<string, string>>;
|
||||
/** A test build (TestFlight, App Review), whose purchases cost nothing and may go ahead before the opening. */
|
||||
isSandbox(): Promise<boolean>;
|
||||
/**
|
||||
@@ -64,7 +58,7 @@ export interface IapClient {
|
||||
*/
|
||||
held(): Promise<boolean>;
|
||||
/** Runs the platform's purchase sheet for a product and resolves with what became of it. */
|
||||
purchase(productId: string, trialRenewalPrice?: string): Promise<PurchaseOutcome>;
|
||||
purchase(productId: string): Promise<PurchaseOutcome>;
|
||||
/** Tells the store a purchase was delivered, once its instance exists. */
|
||||
finish(purchase: Purchase): Promise<void>;
|
||||
/** The subscription this store account already holds, for a reinstall or a new device. */
|
||||
@@ -100,7 +94,7 @@ export const fakeIapClient: IapClient = {
|
||||
async isAvailable() {
|
||||
return true;
|
||||
},
|
||||
async products() {
|
||||
async prices() {
|
||||
return new Map();
|
||||
},
|
||||
async isSandbox() {
|
||||
@@ -157,10 +151,10 @@ export const nativeIapClient: IapClient = {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
async products(productIds) {
|
||||
async prices(productIds) {
|
||||
try {
|
||||
const { products } = await TrekShell.storeProducts({ ids: productIds });
|
||||
return new Map(products.map((p) => [p.id, { displayPrice: p.displayPrice, freeTrial: p.freeTrial === true }]));
|
||||
return new Map(products.map((p) => [p.id, p.displayPrice]));
|
||||
} catch {
|
||||
return new Map();
|
||||
}
|
||||
@@ -172,9 +166,9 @@ export const nativeIapClient: IapClient = {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
async purchase(productId, trialRenewalPrice) {
|
||||
async purchase(productId) {
|
||||
try {
|
||||
const result = await TrekShell.storePurchase({ productId, ...(trialRenewalPrice ? { trialRenewalPrice } : {}) });
|
||||
const result = await TrekShell.storePurchase({ productId });
|
||||
const receipt = result.jws ?? result.purchaseToken;
|
||||
if (result.kind === 'bought' && receipt && result.transactionId) {
|
||||
return {
|
||||
@@ -187,12 +181,7 @@ export const nativeIapClient: IapClient = {
|
||||
},
|
||||
};
|
||||
}
|
||||
if (
|
||||
result.kind === 'cancelled' ||
|
||||
result.kind === 'pending' ||
|
||||
result.kind === 'subscribed' ||
|
||||
result.kind === 'offer-changed'
|
||||
) {
|
||||
if (result.kind === 'cancelled' || result.kind === 'pending' || result.kind === 'subscribed') {
|
||||
return { kind: result.kind };
|
||||
}
|
||||
return { kind: 'failed' };
|
||||
|
||||
@@ -128,14 +128,14 @@ export interface TrekShellPlugin {
|
||||
/** Feature storeKit (iOS) or playBilling (Android): the store's price strings for the products it knows. */
|
||||
storeProducts(options: {
|
||||
ids: string[];
|
||||
}): Promise<{ products: { id: string; displayPrice: string; freeTrial?: boolean }[]; sandbox?: boolean }>;
|
||||
}): Promise<{ products: { id: string; displayPrice: string }[]; sandbox?: boolean }>;
|
||||
/**
|
||||
* The purchase sheet. Set when bought: on iOS `jws`, the signed transaction; on
|
||||
* Android `purchaseToken`, which the control plane verifies with Google Play.
|
||||
*/
|
||||
storePurchase(options: { productId: string; trialRenewalPrice?: string }): Promise<{
|
||||
storePurchase(options: { productId: string }): Promise<{
|
||||
/** `subscribed`: this store account already holds a delivered subscription, so nothing was bought. */
|
||||
kind: 'bought' | 'cancelled' | 'pending' | 'failed' | 'subscribed' | 'offer-changed';
|
||||
kind: 'bought' | 'cancelled' | 'pending' | 'failed' | 'subscribed';
|
||||
jws?: string;
|
||||
purchaseToken?: string;
|
||||
productId?: string;
|
||||
|
||||
@@ -42,8 +42,17 @@ beforeEach(() => {
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
function mockFinePointer() {
|
||||
const matchMedia = window.matchMedia.bind(window);
|
||||
vi.stubGlobal('matchMedia', (query: string) => {
|
||||
const result = matchMedia(query);
|
||||
return query === '(pointer: fine)' ? { ...result, matches: true } : result;
|
||||
});
|
||||
}
|
||||
|
||||
describe('DashboardPage', () => {
|
||||
describe('FE-PAGE-DASH-001: Unauthenticated user is redirected', () => {
|
||||
it('does not render dashboard content when not authenticated', () => {
|
||||
@@ -100,7 +109,8 @@ describe('DashboardPage', () => {
|
||||
});
|
||||
|
||||
describe('FE-PAGE-DASH-005: Create Trip button opens TripFormModal', () => {
|
||||
it('clicking New Trip button opens the trip form modal', async () => {
|
||||
it.each(['mouse', 'touch'])('PR-3305: opening the trip form sets the right focus for %s', async (pointer) => {
|
||||
if (pointer === 'mouse') mockFinePointer();
|
||||
const user = userEvent.setup();
|
||||
render(<DashboardPage />);
|
||||
|
||||
@@ -110,10 +120,9 @@ describe('DashboardPage', () => {
|
||||
|
||||
await user.click(screen.getAllByRole('button', { name: /new trip/i })[0]);
|
||||
|
||||
// TripFormModal opens — "Create New Trip" appears in heading and submit button
|
||||
await waitFor(() => {
|
||||
expect(screen.getAllByText(/create new trip/i).length).toBeGreaterThan(0);
|
||||
});
|
||||
const dialog = await screen.findByRole('dialog', { name: 'Create New Trip' });
|
||||
const target = pointer === 'mouse' ? within(dialog).getByPlaceholderText(/summer in japan/i) : dialog;
|
||||
expect(target).toHaveFocus();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -253,7 +262,8 @@ describe('DashboardPage', () => {
|
||||
});
|
||||
|
||||
describe('FE-PAGE-DASH-012: Edit trip opens form with pre-filled data', () => {
|
||||
it('clicking edit on a trip card opens TripFormModal with trip title pre-filled', async () => {
|
||||
it('PR-3305: focuses the prefilled title when editing a trip', async () => {
|
||||
mockFinePointer();
|
||||
const user = userEvent.setup();
|
||||
render(<DashboardPage />);
|
||||
|
||||
@@ -266,7 +276,7 @@ describe('DashboardPage', () => {
|
||||
|
||||
await waitFor(() => {
|
||||
const titleInput = screen.getByDisplayValue('Paris Adventure');
|
||||
expect(titleInput).toBeInTheDocument();
|
||||
expect(titleInput).toHaveFocus();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -104,13 +104,18 @@ function DashboardPageDesktop(): React.ReactElement {
|
||||
const {
|
||||
demoMode, locale, t, navigate,
|
||||
spotlight, heroBundle, stats, upcoming, gridTrips, isLoading,
|
||||
showFirstTripPrompt,
|
||||
loadError, retryLoad,
|
||||
tripFilter, setTripFilter, viewMode, toggleViewMode,
|
||||
showForm, setShowForm, editingTrip, setEditingTrip,
|
||||
deleteTrip, setDeleteTrip, copyTrip, setCopyTrip, applyCoverUpdate,
|
||||
handleCreate, handleUpdate, confirmDelete, handleArchive, handleUnarchive, confirmCopy,
|
||||
allSubOpen, setAllSubOpen, search,
|
||||
} = useDashboard()
|
||||
} = useDashboard();
|
||||
const openCreate = () => {
|
||||
setEditingTrip(null);
|
||||
setShowForm(true);
|
||||
};
|
||||
|
||||
// Dashboard widget visibility (from the appearance config). Phones never reach this
|
||||
// component — DashboardPage routes them to MDashboard — so only the desktop set applies.
|
||||
@@ -222,22 +227,18 @@ function DashboardPageDesktop(): React.ReactElement {
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* "No trips yet" only when there really are none — a user whose trips are
|
||||
all finished has a hero, and telling them to create their first trip is
|
||||
simply wrong (#1706). Same condition the mobile dashboard already uses. */}
|
||||
{search.active && gridTrips.length === 0 && (
|
||||
{search.active && gridTrips.length === 0 && (
|
||||
<div className="trips-empty">
|
||||
<EmptyState scene="dashboard" title={t('dashboard.search.empty', { query: search.query.trim() })} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!search.active && gridTrips.length === 0 && !spotlight && tripFilter === 'planned' && !isLoading && !loadError && (
|
||||
<div className="trips-empty">
|
||||
<EmptyState scene="dashboard" title={t('dashboard.emptyTitle')} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className={`trips${viewMode === 'list' ? ' list-view' : ''}`}>
|
||||
{showFirstTripPrompt && (
|
||||
<p className="sr-only" role="status">
|
||||
{t('dashboard.emptyTitle')}
|
||||
</p>
|
||||
)}
|
||||
<div className={`trips${viewMode === 'list' ? ' list-view' : ''}`}>
|
||||
{gridTrips.map(trip => (
|
||||
<TripCard
|
||||
key={trip.id}
|
||||
@@ -260,7 +261,10 @@ function DashboardPageDesktop(): React.ReactElement {
|
||||
</>
|
||||
)}
|
||||
{tripFilter === 'planned' && !search.active && !isLoading && (
|
||||
<button type="button" className="add-trip-card" onClick={() => { setEditingTrip(null); setShowForm(true) }}>
|
||||
<button type="button"
|
||||
className={showFirstTripPrompt ? 'add-trip-card col-span-full' : 'add-trip-card'}
|
||||
onClick={openCreate}
|
||||
>
|
||||
<div>
|
||||
<div className="circ"><Plus size={20} /></div>
|
||||
<div className="ttl">{t('dashboard.newTrip')}</div>
|
||||
@@ -286,8 +290,8 @@ function DashboardPageDesktop(): React.ReactElement {
|
||||
|
||||
<button type="button"
|
||||
className="fab-new-trip"
|
||||
onClick={() => { setEditingTrip(null); setShowForm(true) }}
|
||||
aria-label={t('dashboard.newTrip')}
|
||||
onClick={openCreate}
|
||||
aria-label={t('dashboard.newTrip')}
|
||||
title={t('dashboard.newTrip')}
|
||||
>
|
||||
<Plus size={22} strokeWidth={2.4} />
|
||||
|
||||
@@ -9,14 +9,9 @@ import ForgotPasswordPage from './ForgotPasswordPage'
|
||||
// forgotPassword/useForgotPassword.test.ts). The hook is mocked so the form,
|
||||
// the sent screen and the SMTP hint can each be rendered on demand.
|
||||
|
||||
const mocks = vi.hoisted(() => ({ forgot: {} as Record<string, unknown>, native: false }))
|
||||
const mocks = vi.hoisted(() => ({ forgot: {} as Record<string, unknown> }))
|
||||
|
||||
vi.mock('./forgotPassword/useForgotPassword', () => ({ useForgotPassword: () => mocks.forgot }))
|
||||
vi.mock('../native/platform', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('../native/platform')>()),
|
||||
isNativeApp: () => mocks.native,
|
||||
}))
|
||||
vi.mock('../../native-shell/scenery', () => ({ startScenery: vi.fn(), cameraForPlan: () => [0, 0] }))
|
||||
|
||||
const navigate = vi.fn((_to: string) => {})
|
||||
const setEmail = vi.fn((_v: string) => {})
|
||||
@@ -37,7 +32,6 @@ function setForgot(over: Record<string, unknown> = {}) {
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mocks.native = false
|
||||
setForgot()
|
||||
})
|
||||
|
||||
@@ -130,28 +124,4 @@ describe('ForgotPasswordPage', () => {
|
||||
expect(screen.getByRole('heading', { name: 'Check your email' })).toBeInTheDocument()
|
||||
expect(screen.getByText(/console/i)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('keeps the SMTP warning visible throughout native password recovery', () => {
|
||||
mocks.native = true
|
||||
setForgot({ smtpConfigured: false })
|
||||
const { rerender } = render(<ForgotPasswordPage />)
|
||||
|
||||
expect(screen.getByRole('main')).toHaveClass('al-body')
|
||||
expect(screen.getByRole('textbox', { name: 'Email' })).toHaveAttribute('autocomplete', 'email')
|
||||
expect(screen.getByText(/hasn't configured SMTP/i)).toBeVisible()
|
||||
|
||||
setForgot({ smtpConfigured: false, submitted: true })
|
||||
rerender(<ForgotPasswordPage />)
|
||||
expect(screen.getByText(/hasn't configured SMTP/i)).toBeVisible()
|
||||
expect(screen.queryByRole('heading', { name: 'Check your email' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('lets a native user try again after a requester-wide rate limit', () => {
|
||||
mocks.native = true
|
||||
setForgot({ submitted: true, deliveryIssue: 'rateLimit' })
|
||||
render(<ForgotPasswordPage />)
|
||||
|
||||
expect(screen.getByRole('alert')).toHaveTextContent('Too many attempts')
|
||||
expect(screen.getByRole('button', { name: 'Send reset link' })).toBeEnabled()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
import React, { ChangeEvent } from 'react'
|
||||
import { Mail, ArrowLeft, CheckCircle2, Terminal } from 'lucide-react'
|
||||
import { useTranslation } from '../i18n'
|
||||
import { isNativeApp } from '../native/platform'
|
||||
import AppForgotPassword from './forgotPassword/AppForgotPassword'
|
||||
import { useForgotPassword } from './forgotPassword/useForgotPassword'
|
||||
|
||||
const inputBase: React.CSSProperties = {
|
||||
@@ -15,9 +13,7 @@ const inputBase: React.CSSProperties = {
|
||||
function ForgotPasswordPage() {
|
||||
const { t } = useTranslation()
|
||||
// Page = wiring container: form state, the SMTP probe and submit live in the hook.
|
||||
const forgot = useForgotPassword()
|
||||
const { navigate, email, setEmail, submitted, isLoading, smtpConfigured, handleSubmit } = forgot
|
||||
if (isNativeApp()) return <AppForgotPassword forgot={forgot} />
|
||||
const { navigate, email, setEmail, submitted, isLoading, smtpConfigured, handleSubmit } = useForgotPassword()
|
||||
|
||||
return (
|
||||
<div style={{
|
||||
|
||||
@@ -9,14 +9,9 @@ import ResetPasswordPage from './ResetPasswordPage'
|
||||
// resetPassword/useResetPassword.test.ts). The hook is mocked so the success,
|
||||
// broken-link, password and MFA screens can each be rendered directly.
|
||||
|
||||
const mocks = vi.hoisted(() => ({ reset: {} as Record<string, unknown>, native: false }))
|
||||
const mocks = vi.hoisted(() => ({ reset: {} as Record<string, unknown> }))
|
||||
|
||||
vi.mock('./resetPassword/useResetPassword', () => ({ useResetPassword: () => mocks.reset }))
|
||||
vi.mock('../native/platform', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('../native/platform')>()),
|
||||
isNativeApp: () => mocks.native,
|
||||
}))
|
||||
vi.mock('../../native-shell/scenery', () => ({ startScenery: vi.fn(), cameraForPlan: () => [0, 0] }))
|
||||
|
||||
const navigate = vi.fn((_to: string) => {})
|
||||
const setPw = vi.fn((_v: string) => {})
|
||||
@@ -48,35 +43,10 @@ function setReset(over: Record<string, unknown> = {}) {
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mocks.native = false
|
||||
setReset()
|
||||
})
|
||||
|
||||
describe('ResetPasswordPage', () => {
|
||||
it('announces reset errors and supports backup codes on the native screen', () => {
|
||||
mocks.native = true
|
||||
setReset({ mfaRequired: true, error: 'The security code was rejected' })
|
||||
render(<ResetPasswordPage />)
|
||||
|
||||
expect(screen.getByRole('main')).toHaveClass('al-body')
|
||||
expect(screen.getByRole('alert')).toHaveTextContent('The security code was rejected')
|
||||
const code = screen.getByRole('textbox', { name: '2FA code' })
|
||||
expect(code).toHaveAttribute('autocomplete', 'one-time-code')
|
||||
fireEvent.change(code, { target: { value: 'ABCD-EFGH' } })
|
||||
expect(setMfaCode).toHaveBeenCalledWith('ABCD-EFGH')
|
||||
})
|
||||
|
||||
it('lets the native user request another link when the server rejects the current one', () => {
|
||||
mocks.native = true
|
||||
setReset({ linkInvalid: true })
|
||||
render(<ResetPasswordPage />)
|
||||
|
||||
expect(screen.getByRole('heading', { name: 'Invalid reset link' })).toBeVisible()
|
||||
expect(screen.queryByLabelText('New password')).not.toBeInTheDocument()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Send reset link' }))
|
||||
expect(navigate).toHaveBeenCalledWith('/forgot-password')
|
||||
})
|
||||
|
||||
it('FE-PAGE-RESETUI-001: renders the password form for a valid token', () => {
|
||||
setReset()
|
||||
render(<ResetPasswordPage />)
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
import React, { ChangeEvent } from 'react'
|
||||
import { Lock, KeyRound, CheckCircle2, AlertTriangle, Eye, EyeOff } from 'lucide-react'
|
||||
import { useTranslation } from '../i18n'
|
||||
import { isNativeApp } from '../native/platform'
|
||||
import AppResetPassword from './resetPassword/AppResetPassword'
|
||||
import { useResetPassword } from './resetPassword/useResetPassword'
|
||||
import PasswordChecklist from '../components/shared/PasswordChecklist'
|
||||
|
||||
@@ -16,14 +14,12 @@ const inputBase: React.CSSProperties = {
|
||||
function ResetPasswordPage() {
|
||||
const { t } = useTranslation()
|
||||
// Page = wiring container: token, form state, validation + submit live in the hook.
|
||||
const reset = useResetPassword()
|
||||
const {
|
||||
navigate, token, linkInvalid,
|
||||
navigate, token,
|
||||
pw, setPw, pw2, setPw2, showPw, setShowPw,
|
||||
mfaCode, setMfaCode, mfaRequired, error, success, isLoading,
|
||||
handleSubmit,
|
||||
} = reset
|
||||
if (isNativeApp()) return <AppResetPassword reset={reset} />
|
||||
} = useResetPassword()
|
||||
|
||||
const shell = (inner: React.ReactNode) => (
|
||||
<div style={{
|
||||
@@ -61,7 +57,7 @@ function ResetPasswordPage() {
|
||||
)
|
||||
}
|
||||
|
||||
if (!token || linkInvalid) {
|
||||
if (!token) {
|
||||
return shell(
|
||||
<div style={{ textAlign: 'center', padding: '12px 0' }}>
|
||||
<div style={{
|
||||
|
||||
@@ -39,7 +39,7 @@ export function useCollections() {
|
||||
const navigate = useNavigate()
|
||||
const { id: routeId } = useParams<{ id: string }>()
|
||||
// /places is the overview of every place (PLC-07); the lists live below it.
|
||||
const isLibrary = useMatch({ path: '/places', end: true }) != null
|
||||
const isLibraryRoute = useMatch({ path: '/places', end: true }) != null;
|
||||
const toast = useToast()
|
||||
|
||||
const dm = useSettingsStore(s => s.settings.dark_mode)
|
||||
@@ -100,7 +100,8 @@ export function useCollections() {
|
||||
const [listsLoaded, setListsLoaded] = useState(false)
|
||||
useEffect(() => { loadAll().then(() => setListsLoaded(true), () => setListsLoaded(false)) }, [])
|
||||
// All places and All saved in the rail, each place once; read again when a list changes.
|
||||
const libraryCount = useLibraryCount(collections)
|
||||
const libraryCount = useLibraryCount(collections);
|
||||
const isLibrary = isLibraryRoute && libraryCount?.all !== 0;
|
||||
|
||||
// Central admin-defined categories, for assigning a category to a saved place.
|
||||
const [categories, setCategories] = useState<Category[]>([])
|
||||
|
||||
@@ -232,13 +232,22 @@ export function useDashboard() {
|
||||
const gridTrips = search.active ? search.results
|
||||
: tripFilter === 'archive' ? archivedTrips
|
||||
: tripFilter === 'completed' ? rest.filter(t => getTripStatus(t) === 'past')
|
||||
: rest.filter(t => getTripStatus(t) !== 'past')
|
||||
: rest.filter(t => getTripStatus(t) !== 'past');
|
||||
const showFirstTripPrompt =
|
||||
tripFilter === 'planned' &&
|
||||
!search.active &&
|
||||
!isLoading &&
|
||||
!loadError &&
|
||||
!authCheckFailed &&
|
||||
trips.length === 0 &&
|
||||
archivedTrips.length === 0;
|
||||
|
||||
return {
|
||||
// cross-cutting
|
||||
demoMode, locale, t, navigate,
|
||||
// data + derived
|
||||
spotlight, heroBundle, stats, upcoming, gridTrips, isLoading,
|
||||
showFirstTripPrompt,
|
||||
loadError: loadError || authCheckFailed, retryLoad,
|
||||
// Pull-to-refresh on mobile: the same quiet read, no loading state.
|
||||
refreshQuietly,
|
||||
|
||||
@@ -1,61 +0,0 @@
|
||||
import { CheckCircle2 } from 'lucide-react';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { AppAuthScreen, Field, Notice } from '../login/AppAuthScreen';
|
||||
import type { useForgotPassword } from './useForgotPassword';
|
||||
|
||||
export default function AppForgotPassword({ forgot }: { forgot: ReturnType<typeof useForgotPassword> }) {
|
||||
const { t } = useTranslation();
|
||||
const back = () => void forgot.navigate('/login');
|
||||
const smtpOff = forgot.smtpConfigured === false;
|
||||
const smtpNotice = smtpOff && <Notice tone="warn">{t('login.forgotPasswordSmtpHintOff')}</Notice>;
|
||||
|
||||
return (
|
||||
<AppAuthScreen>
|
||||
{forgot.submitted && !forgot.deliveryIssue ? (
|
||||
<div className="al-form">
|
||||
<div className="al-recovery-feedback" role="status">
|
||||
{!smtpOff && <CheckCircle2 className="al-recovery-icon" size={28} aria-hidden="true" />}
|
||||
<h1 className="al-title">{t(smtpOff ? 'login.forgotPasswordTitle' : 'login.forgotPasswordSentTitle')}</h1>
|
||||
{!smtpOff && <p className="al-sub">{t('login.forgotPasswordSentBody')}</p>}
|
||||
</div>
|
||||
{smtpNotice}
|
||||
<button type="button" className="al-cta" onClick={back}>
|
||||
{t('login.backToLogin')}
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<form className="al-form" onSubmit={(event) => void forgot.handleSubmit(event)}>
|
||||
<h1 className="al-title">{t('login.forgotPasswordTitle')}</h1>
|
||||
<p className="al-sub">{t('login.forgotPasswordBody')}</p>
|
||||
{smtpNotice}
|
||||
{forgot.deliveryIssue && (
|
||||
<Notice>
|
||||
{t(forgot.deliveryIssue === 'rateLimit' ? 'common.tooManyAttempts' : 'native.connect.errorUnreachable')}
|
||||
</Notice>
|
||||
)}
|
||||
<Field
|
||||
label={t('common.email')}
|
||||
name="email"
|
||||
type="email"
|
||||
autoComplete="email"
|
||||
autoCapitalize="none"
|
||||
enterKeyHint="send"
|
||||
value={forgot.email}
|
||||
onChange={(event) => forgot.setEmail(event.target.value)}
|
||||
placeholder={t('login.emailPlaceholder')}
|
||||
required
|
||||
/>
|
||||
<button type="submit" className="al-cta" disabled={forgot.isLoading}>
|
||||
{forgot.isLoading && <span className="al-spin" aria-hidden="true" />}
|
||||
{forgot.isLoading ? t('common.loading') : t('login.forgotPasswordSubmit')}
|
||||
</button>
|
||||
</form>
|
||||
<button type="button" className="al-forgot" onClick={back}>
|
||||
{t('login.backToLogin')}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</AppAuthScreen>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
// FE-PAGE-FORGOT-001 to FE-PAGE-FORGOT-008
|
||||
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||
import { AxiosError } from 'axios';
|
||||
import type { FormEvent } from 'react';
|
||||
import { authApi } from '../../api/client';
|
||||
import { useForgotPassword } from './useForgotPassword';
|
||||
@@ -73,18 +72,6 @@ describe('useForgotPassword', () => {
|
||||
await act(() => result.current.handleSubmit(submitEvent()));
|
||||
|
||||
expect(result.current.submitted).toBe(true);
|
||||
expect(result.current.deliveryIssue).toBeNull();
|
||||
});
|
||||
|
||||
it('distinguishes a lost connection without revealing information about the address', async () => {
|
||||
vi.mocked(authApi.forgotPassword).mockRejectedValueOnce(new AxiosError('Lost connection', 'ERR_NETWORK'));
|
||||
const { result } = renderHook(() => useForgotPassword());
|
||||
|
||||
await act(() => result.current.handleSubmit(submitEvent()));
|
||||
expect(result.current.deliveryIssue).toBe('connection');
|
||||
|
||||
await act(() => result.current.handleSubmit(submitEvent()));
|
||||
expect(result.current.deliveryIssue).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-PAGE-FORGOT-007: ignores a second submit while the first is in flight', async () => {
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { useState, useEffect, type FormEvent } from 'react'
|
||||
import { useNavigate } from 'react-router'
|
||||
import { isAxiosError } from 'axios'
|
||||
import { authApi } from '../../api/client'
|
||||
|
||||
/**
|
||||
@@ -15,7 +14,6 @@ export function useForgotPassword() {
|
||||
const [submitted, setSubmitted] = useState(false)
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
const [smtpConfigured, setSmtpConfigured] = useState<boolean | null>(null)
|
||||
const [deliveryIssue, setDeliveryIssue] = useState<'connection' | 'rateLimit' | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
// Probe whether SMTP is configured so we can warn the user up-front that the
|
||||
@@ -31,21 +29,15 @@ export function useForgotPassword() {
|
||||
const handleSubmit = async (e: FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (isLoading) return
|
||||
setDeliveryIssue(null)
|
||||
setIsLoading(true)
|
||||
try {
|
||||
await authApi.forgotPassword({ email: email.trim() })
|
||||
} catch (error) {
|
||||
// These errors apply to the connection or requester, not to the mailbox.
|
||||
// Keep every other outcome indistinguishable from an accepted request.
|
||||
if (isAxiosError(error)) {
|
||||
if (error.response?.status === 429) setDeliveryIssue('rateLimit')
|
||||
else if (!error.response) setDeliveryIssue('connection')
|
||||
}
|
||||
} catch {
|
||||
// Enumeration-safe: success UX regardless of server outcome.
|
||||
}
|
||||
setSubmitted(true)
|
||||
setIsLoading(false)
|
||||
}
|
||||
|
||||
return { navigate, email, setEmail, submitted, isLoading, smtpConfigured, deliveryIssue, handleSubmit }
|
||||
return { navigate, email, setEmail, submitted, isLoading, smtpConfigured, handleSubmit }
|
||||
}
|
||||
|
||||
@@ -1,87 +0,0 @@
|
||||
import { AlertCircle, Globe, Lock } from 'lucide-react';
|
||||
import { useEffect, useRef, type InputHTMLAttributes, type ReactNode } from 'react';
|
||||
import { useNativeServer } from '../../components/Settings/useNativeServer';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { lightStatusBarIcons } from '../../native/appBoot';
|
||||
import { reportNativeFailure } from '../../native/reportFailure';
|
||||
import './appLogin.css';
|
||||
|
||||
export function AppAuthScreen({ children, leaving }: { children: ReactNode; leaving?: boolean }) {
|
||||
useEffect(() => lightStatusBarIcons(), []);
|
||||
return (
|
||||
<div className={leaving ? 'app-login al-leaving' : 'app-login'}>
|
||||
<AppAuthHero />
|
||||
<main className="al-body">{children}</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function AppAuthHero() {
|
||||
const { t } = useTranslation();
|
||||
const { host, changeServer } = useNativeServer();
|
||||
const hero = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const box = hero.current;
|
||||
if (!box) return;
|
||||
let cancelled = false;
|
||||
// Keep the landscape in the position where the address screen leaves it.
|
||||
void import('../../../native-shell/scenery')
|
||||
.then(({ startScenery, cameraForPlan }) => {
|
||||
if (!cancelled) startScenery(box, { frame: 320, camera: cameraForPlan(1), haze: false });
|
||||
})
|
||||
.catch(reportNativeFailure);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
box.querySelector('canvas.scenery')?.remove();
|
||||
};
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="al-hero" ref={hero}>
|
||||
<img className="al-logo" src="/logo-light.svg" alt="TREK" />
|
||||
{host && (
|
||||
<div className="al-card">
|
||||
<div className="al-card-text">
|
||||
<small>
|
||||
<Lock size={12} strokeWidth={2.6} aria-hidden="true" />
|
||||
{t('native.connect.yourTrek')}
|
||||
</small>
|
||||
<div className="al-host" dir="ltr">
|
||||
<Globe size={17} aria-hidden="true" />
|
||||
<span>{host}</span>
|
||||
</div>
|
||||
</div>
|
||||
<button type="button" className="al-change" onClick={changeServer} aria-label={t('native.changeServer')}>
|
||||
{t('common.change')}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function Notice({ tone, children }: { tone?: 'warn'; children: ReactNode }) {
|
||||
return (
|
||||
<div className={tone ? `al-notice ${tone}` : 'al-notice'} role={tone ? 'status' : 'alert'}>
|
||||
<AlertCircle size={18} aria-hidden="true" />
|
||||
<div>{children}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function Field({
|
||||
label,
|
||||
after,
|
||||
...input
|
||||
}: { label: string; after?: ReactNode } & InputHTMLAttributes<HTMLInputElement>) {
|
||||
return (
|
||||
<div className={after ? 'al-fld-wrap with-after' : 'al-fld-wrap'}>
|
||||
<label className="al-fld">
|
||||
<span className="al-lab">{label}</span>
|
||||
<input {...input} />
|
||||
</label>
|
||||
{after && <span className="al-after">{after}</span>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,8 +1,12 @@
|
||||
import { Eye, EyeOff, Fingerprint, Shield } from 'lucide-react';
|
||||
import { AlertCircle, Eye, EyeOff, Fingerprint, Globe, Lock, Shield } from 'lucide-react';
|
||||
import React, { useEffect, useRef } from 'react';
|
||||
import ToggleSwitch from '../../components/Settings/ToggleSwitch';
|
||||
import { useNativeServer } from '../../components/Settings/useNativeServer';
|
||||
import PasswordChecklist from '../../components/shared/PasswordChecklist';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { AppAuthScreen, Field, Notice } from './AppAuthScreen';
|
||||
import { lightStatusBarIcons } from '../../native/appBoot';
|
||||
import { reportNativeFailure } from '../../native/reportFailure';
|
||||
import './appLogin.css';
|
||||
import { heading as headingOf, oidcLoginHref, oidcOnlyHref, submitLabel, type LoginStep } from './loginModel';
|
||||
import { mfaCodeInputProps } from './mfaCodeInput';
|
||||
import { IDP_LOGIN_URL, type useLogin } from './useLogin';
|
||||
@@ -18,10 +22,14 @@ type Login = ReturnType<typeof useLogin>;
|
||||
* (the device decides, see useLogin) differ.
|
||||
*/
|
||||
export default function AppLogin({ login }: { login: Login }) {
|
||||
useEffect(() => lightStatusBarIcons(), []);
|
||||
return (
|
||||
<AppAuthScreen leaving={login.showTakeoff}>
|
||||
<AppLoginContent login={login} />
|
||||
</AppAuthScreen>
|
||||
<div className={login.showTakeoff ? 'app-login al-leaving' : 'app-login'}>
|
||||
<AppLoginHero />
|
||||
<main className="al-body">
|
||||
<AppLoginContent login={login} />
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -51,6 +59,85 @@ function AppLoginContent({ login }: { login: Login }) {
|
||||
return <Credentials login={login} />;
|
||||
}
|
||||
|
||||
/** The landscape of the address screen, with the server this screen signs in to. */
|
||||
function AppLoginHero() {
|
||||
const { t } = useTranslation();
|
||||
const { host, changeServer } = useNativeServer();
|
||||
const hero = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const box = hero.current;
|
||||
if (!box) return;
|
||||
let cancelled = false;
|
||||
// The same camera the address screen ends on, so the picture holds still
|
||||
// across the change of screens. The scene stops drawing once its canvas
|
||||
// has left the page.
|
||||
void import('../../../native-shell/scenery')
|
||||
.then(({ startScenery, cameraForPlan }) => {
|
||||
if (!cancelled) startScenery(box, { frame: 320, camera: cameraForPlan(1), haze: false });
|
||||
})
|
||||
// Without the landscape the box keeps its plain sea colour.
|
||||
.catch(reportNativeFailure);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
box.querySelector('canvas.scenery')?.remove();
|
||||
};
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="al-hero" ref={hero}>
|
||||
<img className="al-logo" src="/logo-light.svg" alt="TREK" />
|
||||
{host && (
|
||||
<div className="al-card">
|
||||
<div className="al-card-text">
|
||||
<small>
|
||||
<Lock size={12} strokeWidth={2.6} aria-hidden="true" />
|
||||
{t('native.connect.yourTrek')}
|
||||
</small>
|
||||
<div className="al-host" dir="ltr">
|
||||
<Globe size={17} aria-hidden="true" />
|
||||
<span>{host}</span>
|
||||
</div>
|
||||
</div>
|
||||
<button type="button" className="al-change" onClick={changeServer} aria-label={t('native.changeServer')}>
|
||||
{t('common.change')}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Notice({ tone, children }: { tone?: 'warn'; children: React.ReactNode }) {
|
||||
return (
|
||||
<div className={tone ? `al-notice ${tone}` : 'al-notice'} role={tone ? undefined : 'alert'}>
|
||||
<AlertCircle size={18} aria-hidden="true" />
|
||||
<div>{children}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* A field on a white card, the label above the input, as on the address screen.
|
||||
* A control beside the input (the password's eye) sits outside the label, so
|
||||
* the label names the input alone.
|
||||
*/
|
||||
function Field({
|
||||
label,
|
||||
after,
|
||||
...input
|
||||
}: { label: string; after?: React.ReactNode } & React.InputHTMLAttributes<HTMLInputElement>) {
|
||||
return (
|
||||
<div className={after ? 'al-fld-wrap with-after' : 'al-fld-wrap'}>
|
||||
<label className="al-fld">
|
||||
<span className="al-lab">{label}</span>
|
||||
<input {...input} />
|
||||
</label>
|
||||
{after && <span className="al-after">{after}</span>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function OidcOnly({ login }: { login: Login }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* The sign-in and password recovery screens inside the iOS and Android app. The sign-in is the
|
||||
* The sign-in screen inside the iOS and Android app (AppLogin.tsx). It is the
|
||||
* next screen after the app's own address screen (native-shell/), so it wears
|
||||
* that screen's look: the same landscape on top, the same glass card with the
|
||||
* server on it, the same type, fields and buttons on the same warm page. The
|
||||
@@ -295,14 +295,6 @@
|
||||
line-height: 1.5;
|
||||
color: var(--al-text);
|
||||
}
|
||||
.al-recovery-feedback {
|
||||
display: grid;
|
||||
gap: 8px;
|
||||
justify-items: start;
|
||||
}
|
||||
.al-recovery-icon {
|
||||
color: var(--al-good);
|
||||
}
|
||||
|
||||
/* A field on a white card: the label above, the input below it. */
|
||||
.al-fld {
|
||||
|
||||
@@ -1,95 +0,0 @@
|
||||
import { CheckCircle2, Eye, EyeOff } from 'lucide-react';
|
||||
import PasswordChecklist from '../../components/shared/PasswordChecklist';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { AppAuthScreen, Field, Notice } from '../login/AppAuthScreen';
|
||||
import { mfaCodeInputProps } from '../login/mfaCodeInput';
|
||||
import type { useResetPassword } from './useResetPassword';
|
||||
|
||||
type Reset = ReturnType<typeof useResetPassword>;
|
||||
|
||||
export default function AppResetPassword({ reset }: { reset: Reset }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<AppAuthScreen>
|
||||
{reset.success ? (
|
||||
<div className="al-form">
|
||||
<div className="al-recovery-feedback" role="status">
|
||||
<CheckCircle2 className="al-recovery-icon" size={28} aria-hidden="true" />
|
||||
<h1 className="al-title">{t('login.resetPasswordSuccessTitle')}</h1>
|
||||
<p className="al-sub">{t('login.resetPasswordSuccessBody')}</p>
|
||||
</div>
|
||||
<button type="button" className="al-cta" onClick={() => void reset.navigate('/login')}>
|
||||
{t('login.signIn')}
|
||||
</button>
|
||||
</div>
|
||||
) : !reset.token || reset.linkInvalid ? (
|
||||
<div className="al-form">
|
||||
<h1 className="al-title">{t('login.resetPasswordInvalidLink')}</h1>
|
||||
<Notice>{t('login.resetPasswordInvalidLinkBody')}</Notice>
|
||||
<button type="button" className="al-cta" onClick={() => void reset.navigate('/forgot-password')}>
|
||||
{t('login.forgotPasswordSubmit')}
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<ResetForm reset={reset} />
|
||||
)}
|
||||
</AppAuthScreen>
|
||||
);
|
||||
}
|
||||
|
||||
function ResetForm({ reset }: { reset: Reset }) {
|
||||
const { t } = useTranslation();
|
||||
const inputType = reset.showPw ? 'text' : 'password';
|
||||
const title = reset.mfaRequired ? t('login.mfaTitle') : t('login.resetPasswordTitle');
|
||||
const action = reset.mfaRequired ? t('login.resetPasswordVerify') : t('login.resetPasswordSubmit');
|
||||
return (
|
||||
<form className="al-form" onSubmit={(event) => void reset.handleSubmit(event)}>
|
||||
<h1 className="al-title">{title}</h1>
|
||||
<p className="al-sub">{t(reset.mfaRequired ? 'login.resetPasswordMfaBody' : 'login.resetPasswordBody')}</p>
|
||||
{reset.error && <Notice>{reset.error}</Notice>}
|
||||
{reset.mfaRequired ? (
|
||||
<Field
|
||||
label={t('login.mfaCode')}
|
||||
{...mfaCodeInputProps(reset.mfaCode, reset.setMfaCode, t('login.mfaPlaceholder'))}
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
<Field
|
||||
label={t('login.newPassword')}
|
||||
type={inputType}
|
||||
name="new-password"
|
||||
autoComplete="new-password"
|
||||
value={reset.pw}
|
||||
onChange={(event) => reset.setPw(event.target.value)}
|
||||
required
|
||||
after={
|
||||
<button
|
||||
type="button"
|
||||
className="al-eye"
|
||||
aria-label={t('native.claim.showPassword')}
|
||||
aria-pressed={reset.showPw}
|
||||
onClick={() => reset.setShowPw((visible) => !visible)}
|
||||
>
|
||||
{reset.showPw ? <EyeOff size={18} aria-hidden="true" /> : <Eye size={18} aria-hidden="true" />}
|
||||
</button>
|
||||
}
|
||||
/>
|
||||
<PasswordChecklist password={reset.pw} className="al-check" tone="light" />
|
||||
<Field
|
||||
label={t('login.confirmPassword')}
|
||||
type={inputType}
|
||||
name="confirm-password"
|
||||
autoComplete="new-password"
|
||||
value={reset.pw2}
|
||||
onChange={(event) => reset.setPw2(event.target.value)}
|
||||
required
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
<button type="submit" className="al-cta" disabled={reset.isLoading}>
|
||||
{reset.isLoading && <span className="al-spin" aria-hidden="true" />}
|
||||
{reset.isLoading ? t('common.loading') : action}
|
||||
</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -132,32 +132,6 @@ describe('useResetPassword', () => {
|
||||
expect(result.current.success).toBe(false);
|
||||
});
|
||||
|
||||
it.each([
|
||||
'Invalid or expired reset link',
|
||||
'This reset link has already been used',
|
||||
'Reset link has expired. Please request a new one.',
|
||||
])('stops retrying a link refused by the server (%s)', async (error) => {
|
||||
vi.mocked(authApi.resetPassword).mockResolvedValueOnce({ mfa_required: true } as never);
|
||||
vi.mocked(authApi.resetPassword).mockRejectedValueOnce({ response: { data: { error } } });
|
||||
const { result, rerender } = renderHook(() => useResetPassword());
|
||||
|
||||
await submit(result, 'Longenough1!');
|
||||
act(() => result.current.setMfaCode('123456'));
|
||||
await act(() => result.current.handleSubmit(submitEvent()));
|
||||
|
||||
expect(result.current.linkInvalid).toBe(true);
|
||||
expect(result.current.pw).toBe('');
|
||||
expect(result.current.pw2).toBe('');
|
||||
expect(result.current.mfaCode).toBe('');
|
||||
expect(result.current.mfaRequired).toBe(false);
|
||||
await act(() => result.current.handleSubmit(submitEvent()));
|
||||
expect(authApi.resetPassword).toHaveBeenCalledTimes(2);
|
||||
|
||||
search = new URLSearchParams('token=fresh-link');
|
||||
rerender();
|
||||
expect(result.current.linkInvalid).toBe(false);
|
||||
});
|
||||
|
||||
it('FE-PAGE-RESET-011: surfaces a plain Error message as-is', async () => {
|
||||
vi.mocked(authApi.resetPassword).mockRejectedValueOnce(new Error('Network Error'));
|
||||
const { result } = renderHook(() => useResetPassword());
|
||||
|
||||
@@ -5,17 +5,11 @@ import { getApiErrorMessage } from '../../types'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { passwordErrorKey } from '../../utils/passwordError'
|
||||
|
||||
// Published TREK servers report these refusals as messages, without an error code.
|
||||
const unusableLinkErrors = new Set([
|
||||
'Invalid or expired reset link',
|
||||
'This reset link has already been used',
|
||||
'Reset link has expired. Please request a new one.',
|
||||
])
|
||||
|
||||
/**
|
||||
* Reset-password data hook — owns the token lookup, the form state, the
|
||||
* client-side validation and the submit (incl. the MFA step-up branch).
|
||||
* ResetPasswordPage is a pure wiring container.
|
||||
* ResetPasswordPage is a pure wiring container. Behaviour is identical to the
|
||||
* previous in-component logic.
|
||||
*/
|
||||
export function useResetPassword() {
|
||||
const { t } = useTranslation()
|
||||
@@ -29,10 +23,8 @@ export function useResetPassword() {
|
||||
const [mfaCode, setMfaCode] = useState('')
|
||||
const [mfaRequired, setMfaRequired] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
const [unusableToken, setUnusableToken] = useState<string | null>(null)
|
||||
const [success, setSuccess] = useState(false)
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
const linkInvalid = unusableToken === token
|
||||
|
||||
useEffect(() => {
|
||||
if (!token) setError(t('login.resetPasswordInvalidLink'))
|
||||
@@ -42,7 +34,7 @@ export function useResetPassword() {
|
||||
e.preventDefault()
|
||||
if (isLoading) return
|
||||
setError('')
|
||||
if (!token || linkInvalid) return
|
||||
if (!token) return
|
||||
const weak = passwordErrorKey(pw)
|
||||
if (weak) { setError(t(weak)); return }
|
||||
if (pw !== pw2) { setError(t('login.passwordsDontMatch')); return }
|
||||
@@ -62,23 +54,13 @@ export function useResetPassword() {
|
||||
setSuccess(true)
|
||||
}
|
||||
} catch (err) {
|
||||
const message = getApiErrorMessage(err, t('login.resetPasswordFailed'))
|
||||
if (unusableLinkErrors.has(message)) {
|
||||
setUnusableToken(token)
|
||||
setPw('')
|
||||
setPw2('')
|
||||
setShowPw(false)
|
||||
setMfaCode('')
|
||||
setMfaRequired(false)
|
||||
} else {
|
||||
setError(message)
|
||||
}
|
||||
setError(getApiErrorMessage(err, t('login.resetPasswordFailed')))
|
||||
}
|
||||
setIsLoading(false)
|
||||
}
|
||||
|
||||
return {
|
||||
navigate, token, linkInvalid,
|
||||
navigate, token,
|
||||
pw, setPw, pw2, setPw2, showPw, setShowPw,
|
||||
mfaCode, setMfaCode, mfaRequired, error, success, isLoading,
|
||||
handleSubmit,
|
||||
|
||||
@@ -157,7 +157,10 @@ export function useAssistantMapLink(options: MapLinkOptions): AssistantMapProps
|
||||
* on every frame, does not render the whole planner each time.
|
||||
*/
|
||||
function useGhostCandidates(tripId: number): GhostCandidate[] {
|
||||
const signature = useAssistantStore((s) => JSON.stringify(ghostCandidates(chatOf(s, tripId).messages)));
|
||||
const signature = useAssistantStore((s) => {
|
||||
const { messages, planEdits, planEditPreview } = chatOf(s, tripId);
|
||||
return JSON.stringify(ghostCandidates(messages, planEdits, planEditPreview));
|
||||
});
|
||||
return useMemo(() => JSON.parse(signature) as GhostCandidate[], [signature]);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
import type {
|
||||
AssistantActivity,
|
||||
AssistantErrorCode,
|
||||
AssistantFocus,
|
||||
AssistantMention,
|
||||
AssistantMessage,
|
||||
AssistantPlanEdits,
|
||||
AssistantThreadSummary,
|
||||
} from '@trek/shared';
|
||||
import type { Assignment } from '../types';
|
||||
|
||||
export interface AssistantTripChat {
|
||||
/** The open thread; null for a new one the first message creates. */
|
||||
threadId: number | null;
|
||||
/** The user's latest threads in this trip; null until loaded. */
|
||||
threads: AssistantThreadSummary[] | null;
|
||||
messages: AssistantMessage[];
|
||||
isRunning: boolean;
|
||||
/** A thread is being loaded. */
|
||||
loading: boolean;
|
||||
error: AssistantErrorCode | null;
|
||||
/** What the next message is about: a place the user asked from, or the selected day. */
|
||||
focus: AssistantFocus | null;
|
||||
/** What is typed but not sent, kept while the phone screen hops to the map. */
|
||||
draft: string;
|
||||
/** The text of a message the server refused before answering, sent again by retry(). */
|
||||
unsent: string | null;
|
||||
/** Ends the running stream. */
|
||||
abort: AbortController | null;
|
||||
/** What the running step is doing (the place it searches near, the area); streamed only, never stored. */
|
||||
live: { activity: AssistantActivity | null };
|
||||
/** The applied changes taken back in this session, by call. */
|
||||
undone: Record<string, true>;
|
||||
/** "Before" and "after" of the last block of changes applied here; null when there is none to compare. */
|
||||
compare: AssistantCompare | null;
|
||||
/** The days, places and bookings named with @ in the draft. */
|
||||
mentions: AssistantMentionItem[];
|
||||
/** The way picked among the ways a block of cards offers, by block. */
|
||||
picks: Record<string, string>;
|
||||
/** Edits saved in a proposal's dialog, waiting for the batch decision. */
|
||||
planEdits: Readonly<Record<string, AssistantPlanEdits>>;
|
||||
/** The open editor's temporary edits, shown only in the planner preview. */
|
||||
planEditPreview: { toolCallId: string; edits: AssistantPlanEdits } | null;
|
||||
/** Which proposals the user explicitly switched on or off. */
|
||||
changeChoices: Readonly<Record<string, boolean>>;
|
||||
}
|
||||
|
||||
/** A mention as the composer picked it, with the label it wrote into the text. */
|
||||
export type AssistantMentionItem = AssistantMention & { label: string };
|
||||
|
||||
/**
|
||||
* The plan of the days one applied block of changes touched, as it was just
|
||||
* before, so the map can show either side. Lives only in this session.
|
||||
*/
|
||||
export interface AssistantCompare {
|
||||
/** The block it belongs to, `blockKeyOf` its calls. */
|
||||
blockKey: string;
|
||||
mode: 'before' | 'after';
|
||||
/** The affected days' stops before the block ran, by day. */
|
||||
snapshot: Record<number, Assignment[]>;
|
||||
/** The calls of the block that make a new place. */
|
||||
newPlaceCalls: string[];
|
||||
/** The places those calls made, hidden while "before" is on. */
|
||||
addedPlaceIds: number[];
|
||||
}
|
||||
@@ -1,4 +1,11 @@
|
||||
import type { AssistantActivityArea, AssistantApplied, AssistantChangeEffect, AssistantMessage } from '@trek/shared';
|
||||
import {
|
||||
editedPlaceEffect,
|
||||
type AssistantActivityArea,
|
||||
type AssistantApplied,
|
||||
type AssistantChangeEffect,
|
||||
type AssistantMessage,
|
||||
type AssistantPlanEdits,
|
||||
} from '@trek/shared';
|
||||
import type { Assignment, AssignmentsMap } from '../types';
|
||||
|
||||
/**
|
||||
@@ -22,11 +29,18 @@ export function blockKeyOf(toolCallIds: readonly string[]): string {
|
||||
}
|
||||
|
||||
/** The effect each change of the thread has on the day plan, by its call. */
|
||||
export function changeEffects(messages: readonly AssistantMessage[]): Map<string, AssistantChangeEffect> {
|
||||
export function changeEffects(
|
||||
messages: readonly AssistantMessage[],
|
||||
edits: Readonly<Record<string, AssistantPlanEdits>> = {},
|
||||
live?: { toolCallId: string; edits: AssistantPlanEdits } | null
|
||||
): Map<string, AssistantChangeEffect> {
|
||||
const effects = new Map<string, AssistantChangeEffect>();
|
||||
for (const m of messages) {
|
||||
for (const p of m.parts) {
|
||||
if (p.type === 'data-trek-change' && p.data.effect) effects.set(p.data.toolCallId, p.data.effect);
|
||||
if (p.type !== 'data-trek-change') continue;
|
||||
const { toolCallId } = p.data;
|
||||
const effect = editedPlaceEffect(p.data, live?.toolCallId === toolCallId ? live.edits : edits[toolCallId]);
|
||||
if (effect) effects.set(toolCallId, effect);
|
||||
}
|
||||
}
|
||||
return effects;
|
||||
@@ -58,8 +72,9 @@ export interface GhostCandidate {
|
||||
* order of the chat. Discarded, expired and failed changes are not, and
|
||||
* neither is a removal: what goes is already on the map.
|
||||
*/
|
||||
export function ghostCandidates(messages: readonly AssistantMessage[]): GhostCandidate[] {
|
||||
const effects = changeEffects(messages);
|
||||
export function ghostCandidates(...args: Parameters<typeof changeEffects>): GhostCandidate[] {
|
||||
const [messages] = args;
|
||||
const effects = changeEffects(...args);
|
||||
if (effects.size === 0) return [];
|
||||
const receipts = receiptsOf(messages);
|
||||
const candidates: GhostCandidate[] = [];
|
||||
|
||||
@@ -141,6 +141,21 @@ describe('assistantRouteModel', () => {
|
||||
expect(discarded.map((ref) => ref.toolCallId)).toEqual(['call_1', 'call_2']);
|
||||
});
|
||||
|
||||
it('highlights a calculated alternative by default and respects a manual selection', () => {
|
||||
const unplanned = { ...HIKE, routed: false, distanceM: null };
|
||||
const latest = message([...read('a', unplanned), ...read('b', GENTLE)]);
|
||||
const selection = (picks: Readonly<Record<string, string>>) =>
|
||||
routeRefs([latest], picks, NOBODY, LOOK, AS_WAYS).map((ref) => [ref.way, ref.picked]);
|
||||
expect(selection({})).toEqual([
|
||||
['a', false],
|
||||
['b', true],
|
||||
]);
|
||||
expect(selection({ 'tour:a': 'a' })).toEqual([
|
||||
['a', true],
|
||||
['b', false],
|
||||
]);
|
||||
});
|
||||
|
||||
it("FE-AI-ROUTE-003: lines lie in order (replaced way, others, the chosen way, the lit one) in their ways' colours", () => {
|
||||
const previous = { line: flat(HIKE), distanceM: 8000, ascentM: null, minutes: null };
|
||||
const messages = [
|
||||
|
||||
@@ -19,6 +19,15 @@ export interface RouteCardEntry {
|
||||
card: TrekCard;
|
||||
}
|
||||
|
||||
/** Use the first calculated route unless the user chose a particular way. */
|
||||
export function preferredRouteEntry<T extends RouteCardEntry>(entries: readonly T[], picked?: string): T | undefined {
|
||||
return (
|
||||
entries.find((entry) => entry.toolCallId === picked) ??
|
||||
entries.find(({ card }) => card.kind === 'tourRoute' && card.routed) ??
|
||||
entries[0]
|
||||
);
|
||||
}
|
||||
|
||||
/** The letters the ways of one answer go by, in the order the answer gave them. */
|
||||
type RouteWayKey = 'a' | 'b' | 'c';
|
||||
const WAY_KEYS: readonly RouteWayKey[] = ['a', 'b', 'c'];
|
||||
@@ -101,7 +110,7 @@ function standsOnMap(part: ToolCallPart, receipt: AssistantApplied | undefined,
|
||||
/**
|
||||
* The cards of the latest answer that draws any, laid out as the chat lays
|
||||
* them out: a group of several is a choice of ways, each with its letter, the
|
||||
* chosen one (by `picks`, else the first) picked. Older answers drop, and so
|
||||
* chosen one (by `picks`, else the first calculated route) picked. Older answers drop, and so
|
||||
* do the ways of a group once one of them was taken into the trip.
|
||||
*/
|
||||
function lookRefs(
|
||||
@@ -111,7 +120,6 @@ function lookRefs(
|
||||
look: CardMapLook,
|
||||
layout: AnswerLayout
|
||||
): RouteRef[] {
|
||||
const chosenIds = new Set(Object.values(picks));
|
||||
const taken = takenProposals(messages);
|
||||
for (let index = messages.length - 1; index >= 0; index--) {
|
||||
const answers = (messages[index]?.parts ?? []).flatMap((part): RouteCardEntry[] =>
|
||||
@@ -125,7 +133,7 @@ function lookRefs(
|
||||
return layout(answers).flatMap((group) => {
|
||||
if (group.some((entry) => taken.has(entry.toolCallId))) return [];
|
||||
const ways = group.length >= 2;
|
||||
const chosen = group.find((entry) => chosenIds.has(entry.toolCallId)) ?? group[0];
|
||||
const chosen = preferredRouteEntry(group, picks[`tour:${group[0]?.toolCallId ?? ''}`]);
|
||||
return group.flatMap((entry, position): RouteRef[] => {
|
||||
if (!drawn.has(entry.toolCallId)) return [];
|
||||
const way = ways ? (WAY_KEYS[position] ?? null) : null;
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import {
|
||||
ASSISTANT_ERROR_CODES,
|
||||
type AiStatusResponse,
|
||||
type AssistantActivity,
|
||||
type AssistantApplied,
|
||||
type AssistantDecision,
|
||||
type AssistantErrorCode,
|
||||
@@ -9,10 +8,10 @@ import {
|
||||
type AssistantFoundPlace,
|
||||
type AssistantJourneySurface,
|
||||
type AssistantMapView,
|
||||
type AssistantMention,
|
||||
type AssistantMessage,
|
||||
type AssistantMessagePart,
|
||||
type AssistantPageRender,
|
||||
type AssistantPlanEdits,
|
||||
type AssistantThreadSummary,
|
||||
type UiStreamChunk,
|
||||
} from '@trek/shared';
|
||||
@@ -21,12 +20,12 @@ import { AssistantRequestError } from '../api/assistant';
|
||||
import { aiConnectionsRepo } from '../repo/aiConnectionsRepo';
|
||||
import { assistantRepo } from '../repo/assistantRepo';
|
||||
import { OnlineOnlyError } from '../repo/onlineOnly';
|
||||
import type { Assignment } from '../types';
|
||||
import { browserTimeZone } from '../utils/localDate';
|
||||
import { randomId } from '../utils/randomId';
|
||||
import type { RouteProfileFocus } from '../utils/routeGeometry';
|
||||
import { useAddonStore } from './addonStore';
|
||||
import { assistantScopeOf, assistantTargetOf, type AssistantChatKey } from './assistantChatKey';
|
||||
import type { AssistantCompare, AssistantMentionItem, AssistantTripChat } from './assistantChatState';
|
||||
import {
|
||||
blockDays,
|
||||
blockKeyOf,
|
||||
@@ -41,6 +40,8 @@ import { useAuthStore } from './authStore';
|
||||
import { useSettingsStore } from './settingsStore';
|
||||
import { useTripStore } from './tripStore';
|
||||
|
||||
export type { AssistantMentionItem } from './assistantChatState';
|
||||
|
||||
/**
|
||||
* The assistant: whether it can run, whether its window is open, and one
|
||||
* conversation per trip and one per journey (the chat in TREK Studio), each
|
||||
@@ -60,55 +61,6 @@ import { useTripStore } from './tripStore';
|
||||
* thread.
|
||||
*/
|
||||
|
||||
interface AssistantTripChat {
|
||||
/** The open thread; null for a new one the first message creates. */
|
||||
threadId: number | null;
|
||||
/** The user's latest threads in this trip; null until loaded. */
|
||||
threads: AssistantThreadSummary[] | null;
|
||||
messages: AssistantMessage[];
|
||||
isRunning: boolean;
|
||||
/** A thread is being loaded. */
|
||||
loading: boolean;
|
||||
error: AssistantErrorCode | null;
|
||||
/** What the next message is about: a place the user asked from, or the selected day. */
|
||||
focus: AssistantFocus | null;
|
||||
/** What is typed but not sent, kept while the phone screen hops to the map. */
|
||||
draft: string;
|
||||
/** The text of a message the server refused before answering, sent again by retry(). */
|
||||
unsent: string | null;
|
||||
/** Ends the running stream. */
|
||||
abort: AbortController | null;
|
||||
/** What the running step is doing (the place it searches near, the area); streamed only, never stored. */
|
||||
live: { activity: AssistantActivity | null };
|
||||
/** The applied changes taken back in this session, by call. */
|
||||
undone: Record<string, true>;
|
||||
/** "Before" and "after" of the last block of changes applied here; null when there is none to compare. */
|
||||
compare: AssistantCompare | null;
|
||||
/** The days, places and bookings named with @ in the draft. */
|
||||
mentions: AssistantMentionItem[];
|
||||
/** The way picked among the ways a block of cards offers, by block. */
|
||||
picks: Record<string, string>;
|
||||
}
|
||||
|
||||
/** A mention as the composer picked it, with the label it wrote into the text. */
|
||||
export type AssistantMentionItem = AssistantMention & { label: string };
|
||||
|
||||
/**
|
||||
* The plan of the days one applied block of changes touched, as it was just
|
||||
* before, so the map can show either side. Lives only in this session.
|
||||
*/
|
||||
interface AssistantCompare {
|
||||
/** The block it belongs to, `blockKeyOf` its calls. */
|
||||
blockKey: string;
|
||||
mode: 'before' | 'after';
|
||||
/** The affected days' stops before the block ran, by day. */
|
||||
snapshot: Record<number, Assignment[]>;
|
||||
/** The calls of the block that make a new place. */
|
||||
newPlaceCalls: string[];
|
||||
/** The places those calls made, hidden while "before" is on. */
|
||||
addedPlaceIds: number[];
|
||||
}
|
||||
|
||||
/** Where a hover on a change came from: its row in the card, its pin on the map, a found place in the strip. */
|
||||
type AssistantMapSource = 'card' | 'map' | 'strip';
|
||||
|
||||
@@ -199,6 +151,9 @@ interface AssistantState {
|
||||
/** Hands a booking file to a trip's chat, which proposes what it finds in it; does nothing under a journey key. */
|
||||
attach: (key: AssistantChatKey, file: File) => Promise<void>;
|
||||
decide: (key: AssistantChatKey, decisions: AssistantDecision[]) => Promise<void>;
|
||||
savePlanEdit: (key: AssistantChatKey, toolCallId: string, edits: AssistantPlanEdits) => void;
|
||||
previewPlanEdit: (key: AssistantChatKey, toolCallId: string, edits: AssistantPlanEdits | null) => void;
|
||||
choosePlanChanges: (key: AssistantChatKey, toolCallIds: readonly string[], include: boolean) => void;
|
||||
undo: (key: AssistantChatKey, toolCallId: string) => Promise<UndoOutcome>;
|
||||
cancel: (key: AssistantChatKey) => void;
|
||||
/** Sends the last question again: the refused message, or the one whose answer broke off. */
|
||||
@@ -311,6 +266,9 @@ const EMPTY_CHAT: AssistantTripChat = {
|
||||
compare: null,
|
||||
mentions: [],
|
||||
picks: {},
|
||||
planEdits: {},
|
||||
planEditPreview: null,
|
||||
changeChoices: {},
|
||||
};
|
||||
|
||||
/** What the map shows for the cards of a chat, cleared when the chat closes or changes. */
|
||||
@@ -659,9 +617,18 @@ function threadActions(ctx: Ctx) {
|
||||
};
|
||||
|
||||
const openThread = async (tripId: number, threadId: number) => {
|
||||
if (chat(ctx, tripId).isRunning) return;
|
||||
const current = chat(ctx, tripId);
|
||||
if (current.isRunning) return;
|
||||
ctx.set(NO_ROUTE);
|
||||
patch(ctx, tripId, { threadId, loading: true, error: null, unsent: null });
|
||||
patch(ctx, tripId, {
|
||||
threadId,
|
||||
loading: true,
|
||||
error: null,
|
||||
unsent: null,
|
||||
planEdits: current.threadId === threadId ? current.planEdits : {},
|
||||
planEditPreview: null,
|
||||
changeChoices: current.threadId === threadId ? current.changeChoices : {},
|
||||
});
|
||||
try {
|
||||
const { messages } = await assistantRepo.thread(assistantTargetOf(tripId), threadId);
|
||||
// Another thread may have been opened while this one loaded.
|
||||
@@ -695,6 +662,9 @@ function threadActions(ctx: Ctx) {
|
||||
abort: null,
|
||||
live: NO_LIVE,
|
||||
compare: null,
|
||||
planEdits: {},
|
||||
planEditPreview: null,
|
||||
changeChoices: {},
|
||||
});
|
||||
};
|
||||
|
||||
@@ -921,6 +891,17 @@ function turnActions(ctx: Ctx) {
|
||||
return {
|
||||
send: (tripId: number, text: string) => sendMessage(ctx, tripId, text),
|
||||
attach: (tripId: number, file: File) => attachFile(ctx, tripId, file),
|
||||
savePlanEdit: (tripId: number, toolCallId: string, edits: AssistantPlanEdits) =>
|
||||
patch(ctx, tripId, { planEdits: { ...chat(ctx, tripId).planEdits, [toolCallId]: edits } }),
|
||||
previewPlanEdit: (tripId: number, toolCallId: string, edits: AssistantPlanEdits | null) => {
|
||||
if (edits === null && chat(ctx, tripId).planEditPreview?.toolCallId !== toolCallId) return;
|
||||
patch(ctx, tripId, { planEditPreview: edits === null ? null : { toolCallId, edits } });
|
||||
},
|
||||
choosePlanChanges: (tripId: number, toolCallIds: readonly string[], include: boolean) => {
|
||||
const changeChoices = { ...chat(ctx, tripId).changeChoices };
|
||||
for (const id of toolCallIds) changeChoices[id] = include;
|
||||
patch(ctx, tripId, { changeChoices });
|
||||
},
|
||||
decide: async (tripId: number, decisions: AssistantDecision[]) => {
|
||||
const c = chat(ctx, tripId);
|
||||
const threadId = c.threadId;
|
||||
@@ -941,7 +922,20 @@ function turnActions(ctx: Ctx) {
|
||||
},
|
||||
});
|
||||
// Refused before anything ran: there is no "after" to compare with.
|
||||
if (chat(ctx, tripId).error) patch(ctx, tripId, { compare: null });
|
||||
const current = chat(ctx, tripId);
|
||||
if (current.threadId !== threadId) return;
|
||||
if (current.error) {
|
||||
patch(ctx, tripId, { compare: null });
|
||||
return;
|
||||
}
|
||||
if (current.messages === c.messages) return;
|
||||
const planEdits = { ...current.planEdits };
|
||||
const changeChoices = { ...current.changeChoices };
|
||||
for (const { toolCallId } of decisions) {
|
||||
delete planEdits[toolCallId];
|
||||
delete changeChoices[toolCallId];
|
||||
}
|
||||
patch(ctx, tripId, { planEdits, changeChoices });
|
||||
},
|
||||
undo: (tripId: number, toolCallId: string) => undoOne(ctx, tripId, toolCallId),
|
||||
cancel: (tripId: number) => chat(ctx, tripId).abort?.abort(),
|
||||
|
||||
Vendored
-3
@@ -4,9 +4,6 @@
|
||||
/** The version this bundle was built as (client/package.json), set by `define` in vite.config.js. */
|
||||
declare const __TREK_UI_VERSION__: string;
|
||||
|
||||
/** Defined only for the native store-sandbox build. */
|
||||
declare const __TREK_STORE_SANDBOX_ORIGIN__: string | undefined;
|
||||
|
||||
/**
|
||||
* Big Shoulders Display's weights, imported for their stylesheets alone
|
||||
* (components/Studio/bookFontFaces.ts). Its package maps `./*` to `./*.css`
|
||||
|
||||
@@ -264,9 +264,9 @@ describe('MCostsTab', () => {
|
||||
|
||||
it('FE-MOB-COSTT-012: shows the empty panel without any expense', async () => {
|
||||
await renderTab(planner({ budgetItems: [] }))
|
||||
expect(screen.getByText('costs.noCategories')).toBeInTheDocument()
|
||||
expect(screen.queryByText('costs.byCategory')).not.toBeInTheDocument()
|
||||
expect(screen.getByText('costs.emptyText')).toBeInTheDocument()
|
||||
expect(up(screen.getByText('costs.totalSpend'), 1).textContent).toContain('$0.00')
|
||||
expect(screen.queryByText('costs.totalSpend')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-MOB-COSTT-013: groups the expenses by day with a per-day total', async () => {
|
||||
|
||||
@@ -1,165 +0,0 @@
|
||||
import { fireEvent, waitFor } from '@testing-library/react';
|
||||
import { afterEach, expect, it, vi } from 'vitest';
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
agreement: vi.fn(),
|
||||
purchase: vi.fn().mockResolvedValue({ kind: 'cancelled' }),
|
||||
}));
|
||||
|
||||
vi.mock('@capacitor/app', () => ({ App: { addListener: vi.fn() } }));
|
||||
vi.mock('@capacitor/core', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('@capacitor/core')>()),
|
||||
CapacitorHttp: { get: mocks.agreement },
|
||||
}));
|
||||
vi.mock('@capacitor/splash-screen', () => ({ SplashScreen: { hide: vi.fn().mockResolvedValue(undefined) } }));
|
||||
vi.mock('../../../native-shell/scenery', () => ({
|
||||
WELCOME_CAMERA: [0, 0],
|
||||
cameraForPlan: () => [0, 0],
|
||||
startScenery: () => null,
|
||||
}));
|
||||
vi.mock('../../../src/native/trekShell', () => ({
|
||||
TrekShell: {
|
||||
getServer: vi.fn().mockResolvedValue({ url: null }),
|
||||
requestServer: vi.fn(async ({ url }: { url: string }) => ({
|
||||
status: 200,
|
||||
url,
|
||||
data:
|
||||
new URL(url).pathname === '/api/plans'
|
||||
? {
|
||||
ordering: 'open',
|
||||
plans: [{ id: 'plus', name: 'Plus', storageGb: 50, aiDocumentLimit: null }],
|
||||
}
|
||||
: { available: true },
|
||||
})),
|
||||
},
|
||||
}));
|
||||
vi.mock('../../../src/native/iap', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('../../../src/native/iap')>()),
|
||||
getIapClient: () => ({
|
||||
isAvailable: async () => true,
|
||||
products: async () => new Map([['cloud.plus.monthly', { displayPrice: '$11.99', freeTrial: true }]]),
|
||||
held: async () => false,
|
||||
onTransaction: vi.fn(),
|
||||
unfinished: async () => null,
|
||||
purchase: mocks.purchase,
|
||||
}),
|
||||
}));
|
||||
|
||||
const agreement = { status: 200, data: { version: '2026-12-01', deviations: 'First agreement' } };
|
||||
|
||||
function element<T extends HTMLElement>(selector: string): T {
|
||||
const found = document.querySelector<T>(selector);
|
||||
if (!found) throw new Error(`The app did not show ${selector}`);
|
||||
return found;
|
||||
}
|
||||
|
||||
function mountShell(): void {
|
||||
vi.resetModules();
|
||||
vi.stubGlobal('matchMedia', () => ({ matches: false, addEventListener: vi.fn() }));
|
||||
vi.stubGlobal('cancelAnimationFrame', vi.fn());
|
||||
document.body.append(Object.assign(document.createElement('main'), { id: 'shell' }));
|
||||
mocks.agreement.mockReset();
|
||||
mocks.purchase.mockClear();
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
document.body.replaceChildren();
|
||||
});
|
||||
|
||||
it('keeps the store closed for a withdrawn agreement and asks again when the version changes', async () => {
|
||||
mountShell();
|
||||
const changed = { status: 200, data: { version: '2026-12-02', deviations: 'Updated agreement' } };
|
||||
mocks.agreement
|
||||
.mockResolvedValueOnce(agreement)
|
||||
.mockResolvedValueOnce({ status: 503, data: { code: 'ordering-closed' } })
|
||||
.mockResolvedValueOnce(agreement)
|
||||
.mockResolvedValue(changed);
|
||||
|
||||
await import('../../../native-shell/main');
|
||||
await waitFor(() => expect(element<HTMLElement>('.trial-badge').hidden).toBe(false));
|
||||
fireEvent.click(element('button.discover'));
|
||||
await waitFor(() => expect(element<HTMLButtonElement>('.dock button.cta').hidden).toBe(false));
|
||||
fireEvent.click(element('.dock button.cta'));
|
||||
|
||||
const consent = await waitFor(() => {
|
||||
expect(element('.consent-text').textContent).toBe(agreement.data.deviations);
|
||||
return element<HTMLInputElement>('.consent input');
|
||||
});
|
||||
fireEvent.input(element('.form input[type="text"]'), { target: { value: 'sample-journey' } });
|
||||
fireEvent.input(element('.form input[type="email"]'), { target: { value: 'buyer@example.invalid' } });
|
||||
fireEvent.input(element('.form input[type="password"]'), { target: { value: 'Training#Pass123' } });
|
||||
const submit = element<HTMLButtonElement>('.dock button.cta');
|
||||
fireEvent.click(consent);
|
||||
fireEvent.click(submit);
|
||||
await waitFor(() => {
|
||||
expect(consent.disabled).toBe(true);
|
||||
expect(consent.checked).toBe(false);
|
||||
});
|
||||
expect(mocks.purchase).not.toHaveBeenCalled();
|
||||
|
||||
fireEvent.click(submit);
|
||||
await waitFor(() => expect(element('.consent-text').textContent).toBe(agreement.data.deviations));
|
||||
fireEvent.click(consent);
|
||||
fireEvent.click(submit);
|
||||
await waitFor(() => expect(element('.consent-text').textContent).toBe(changed.data.deviations));
|
||||
expect(consent.checked).toBe(false);
|
||||
expect(mocks.purchase).not.toHaveBeenCalled();
|
||||
|
||||
fireEvent.click(consent);
|
||||
fireEvent.click(submit);
|
||||
await waitFor(() => expect(mocks.purchase).toHaveBeenCalledExactlyOnceWith('cloud.plus.monthly', '$11.99'));
|
||||
});
|
||||
|
||||
it('requires a sandbox agreement before presenting a store purchase', async () => {
|
||||
mountShell();
|
||||
const sandbox = 'https://store-sandbox.example.com';
|
||||
vi.stubGlobal('__TREK_STORE_SANDBOX_ORIGIN__', sandbox);
|
||||
const sandboxAgreement = {
|
||||
status: 200,
|
||||
data: { ...agreement.data, iapEnvironment: 'sandbox' },
|
||||
};
|
||||
mocks.agreement.mockImplementation(async ({ url }: { url: string }) => {
|
||||
const path = new URL(url).pathname;
|
||||
if (path === '/api/plans') {
|
||||
return {
|
||||
status: 200,
|
||||
data: { ordering: 'open', plans: [{ id: 'plus', name: 'Plus', storageGb: 50, aiDocumentLimit: null }] },
|
||||
};
|
||||
}
|
||||
if (path === '/api/slug/check') return { status: 200, data: { status: 'available' } };
|
||||
return agreement;
|
||||
});
|
||||
|
||||
await import('../../../native-shell/main');
|
||||
await waitFor(() => expect(element<HTMLElement>('.trial-badge').hidden).toBe(false));
|
||||
fireEvent.click(element('button.discover'));
|
||||
await waitFor(() => expect(element<HTMLButtonElement>('.dock button.cta').hidden).toBe(false));
|
||||
fireEvent.click(element('.dock button.cta'));
|
||||
|
||||
const consent = await waitFor(() => {
|
||||
const input = element<HTMLInputElement>('.consent input');
|
||||
expect(input.disabled).toBe(true);
|
||||
return input;
|
||||
});
|
||||
const submit = element<HTMLButtonElement>('.dock button.cta');
|
||||
fireEvent.input(element('.form input[type="text"]'), { target: { value: 'sample-journey' } });
|
||||
fireEvent.input(element('.form input[type="email"]'), { target: { value: 'buyer@example.invalid' } });
|
||||
fireEvent.input(element('.form input[type="password"]'), { target: { value: 'Training#Pass123' } });
|
||||
fireEvent.click(submit);
|
||||
await waitFor(() => expect(element('.notice').textContent).toBeTruthy());
|
||||
expect(mocks.purchase).not.toHaveBeenCalled();
|
||||
|
||||
mocks.agreement.mockImplementation(async ({ url }: { url: string }) =>
|
||||
new URL(url).pathname === '/api/slug/check' ? { status: 200, data: { status: 'available' } } : sandboxAgreement
|
||||
);
|
||||
fireEvent.click(submit);
|
||||
await waitFor(() => expect(consent.disabled).toBe(false));
|
||||
fireEvent.click(consent);
|
||||
fireEvent.click(submit);
|
||||
await waitFor(() => expect(mocks.purchase).toHaveBeenCalledExactlyOnceWith('cloud.plus.monthly', '$11.99'));
|
||||
for (const [options] of mocks.agreement.mock.calls) {
|
||||
expect(new URL(options.url).origin).toBe(sandbox);
|
||||
expect(options.disableRedirects).toBe(true);
|
||||
}
|
||||
});
|
||||
@@ -1,40 +1,16 @@
|
||||
import { defineConfig, loadEnv } from 'vite'
|
||||
import { defineConfig } from 'vite'
|
||||
import { fileURLToPath } from 'url'
|
||||
|
||||
function sandboxOrigin(mode) {
|
||||
const envDir = fileURLToPath(new URL('.', import.meta.url))
|
||||
const { TREK_CLOUD_SANDBOX_ORIGIN: origin } = loadEnv(mode, envDir, 'TREK_CLOUD_SANDBOX_')
|
||||
const url = URL.canParse(origin) ? new URL(origin) : null
|
||||
// The host must also support a wildcard certificate for its tenant subdomains.
|
||||
const dnsName = /^(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z][a-z0-9-]*[a-z0-9]$/
|
||||
if (
|
||||
url?.origin !== origin ||
|
||||
url?.protocol !== 'https:' ||
|
||||
url.port ||
|
||||
!dnsName.test(url.hostname) ||
|
||||
url.hostname === 'liketrek.com' ||
|
||||
url.hostname === 'www.liketrek.com'
|
||||
) {
|
||||
throw new Error('TREK_CLOUD_SANDBOX_ORIGIN must be a dedicated sandbox HTTPS origin without a path or port')
|
||||
}
|
||||
return origin
|
||||
}
|
||||
|
||||
// The address screen the native apps ship (native-shell/). Everything past it
|
||||
// is the UI of the server the user picks, so this build stays tiny and apart
|
||||
// from the main one: no PWA, no React, only the native strings of each locale.
|
||||
export default defineConfig(({ command, mode }) => {
|
||||
const sandbox = command === 'build' && mode === 'store-sandbox'
|
||||
const output = sandbox ? './native-sandbox-dist' : './native-dist'
|
||||
return {
|
||||
root: fileURLToPath(new URL('./native-shell', import.meta.url)),
|
||||
base: './',
|
||||
publicDir: false,
|
||||
define: sandbox ? { __TREK_STORE_SANDBOX_ORIGIN__: JSON.stringify(sandboxOrigin(mode)) } : {},
|
||||
build: {
|
||||
outDir: fileURLToPath(new URL(output, import.meta.url)),
|
||||
emptyOutDir: true,
|
||||
target: ['es2020', 'safari15', 'chrome100'],
|
||||
},
|
||||
}
|
||||
export default defineConfig({
|
||||
root: fileURLToPath(new URL('./native-shell', import.meta.url)),
|
||||
base: './',
|
||||
publicDir: false,
|
||||
build: {
|
||||
outDir: fileURLToPath(new URL('./native-dist', import.meta.url)),
|
||||
emptyOutDir: true,
|
||||
target: ['es2020', 'safari15', 'chrome100'],
|
||||
},
|
||||
})
|
||||
|
||||
@@ -128,7 +128,6 @@
|
||||
"client/src/components/Journey/JourneyMap.tsx": 2,
|
||||
"client/src/components/Map/mapViewContract.ts": 1,
|
||||
"client/src/components/Map/useTripRouteOverview.ts": 2,
|
||||
"client/src/components/Planner/PlaceFormModal.tsx": 1,
|
||||
"client/src/components/Planner/placeOpenState.ts": 1,
|
||||
"client/src/components/Planner/transportEndpoints.ts": 1,
|
||||
"client/src/components/Planner/useTripExport.ts": 1,
|
||||
@@ -138,7 +137,7 @@
|
||||
"client/src/components/Roadtrip/corridor.ts": 2,
|
||||
"client/src/components/Roadtrip/dayWindow.ts": 3,
|
||||
"client/src/components/Roadtrip/followTrack.ts": 2,
|
||||
"client/src/components/Roadtrip/manualStop.ts": 2,
|
||||
"client/src/components/Roadtrip/manualStop.ts": 1,
|
||||
"client/src/components/Roadtrip/nightSpill.ts": 1,
|
||||
"client/src/components/Roadtrip/refuelSuggestion.ts": 1,
|
||||
"client/src/components/Roadtrip/roadtripModel.ts": 4,
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user