mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-04 01:44:13 +00:00
Compare commits
57 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| faaa56eda6 | |||
| 4b54a00d89 | |||
| 00955f0ac5 | |||
| 995e9c435f | |||
| 259d23f971 | |||
| 7196ad30da | |||
| 3945037ff3 | |||
| f10435b42b | |||
| c6a50695d8 | |||
| ea1a2527ab | |||
| 4b7c96f4c5 | |||
| 8ae919c650 | |||
| 75020dd2df | |||
| ca201ab4d0 | |||
| 0f683b0dee | |||
| e54f954f31 | |||
| a2cf911ce1 | |||
| 7a66a54e66 | |||
| bf6a66d52c | |||
| 748434fc47 | |||
| 618f070675 | |||
| 260e1ef023 | |||
| 262741bf89 | |||
| 3438a2aa48 | |||
| dacf19b4d5 | |||
| 103631d5fc | |||
| 00fcb69423 | |||
| dbcdecb6a7 | |||
| 10fecf4e80 | |||
| 12483f618f | |||
| 17c4d69e40 | |||
| d6184559e9 | |||
| 3089aee593 | |||
| 24ddc3e4b0 | |||
| a4cb6c69d8 | |||
| 6e224cb7a4 | |||
| 56b4568a16 | |||
| 756ef14b97 | |||
| e539860530 | |||
| 0d6a432967 | |||
| 89035059ec | |||
| 4ad926aafc | |||
| 60a30afb81 | |||
| b77c246df4 | |||
| 7f4ece2e6f | |||
| a14b6a61e6 | |||
| 871135edeb | |||
| c22c464e68 | |||
| 3c2dc51439 | |||
| 28eea68559 | |||
| 1ff8a814ae | |||
| 0d521f0930 | |||
| 7fc011408a | |||
| 8f20f9f7ea | |||
| 67b65a7647 | |||
| 82b2a530f3 | |||
| 76a3983972 |
@@ -438,10 +438,10 @@ jobs:
|
||||
- name: Lint
|
||||
# Errors fail, and the warnings per rule may not pass
|
||||
# scripts/eslint-baseline.json (src, tests and eslint-disable'd
|
||||
# messages counted apart). Type-aware rules build the src + tests
|
||||
# program, which outgrows Node's default ~4 GB heap on the runner.
|
||||
# messages counted apart). The typed src and test programs can exhaust
|
||||
# an 8 GiB heap. Leave headroom within the runner's 16 GB of RAM.
|
||||
env:
|
||||
NODE_OPTIONS: --max-old-space-size=8192
|
||||
NODE_OPTIONS: --max-old-space-size=10240
|
||||
TREK_LINT_BASE: refs/remotes/lint-base
|
||||
run: cd server && npm run lint:warnings
|
||||
|
||||
@@ -990,7 +990,7 @@ jobs:
|
||||
# Fails on any ESLint error, like lint:check did, and on any rule
|
||||
# whose warning count rises above scripts/eslint-baseline.json.
|
||||
# Typed linting (no-floating-promises, no-misused-promises) loads the
|
||||
# whole TypeScript program, so it gets the heap the server lint gets.
|
||||
# whole TypeScript program, which exceeds Node's default heap.
|
||||
env:
|
||||
NODE_OPTIONS: --max-old-space-size=8192
|
||||
TREK_LINT_BASE: refs/remotes/lint-base
|
||||
|
||||
@@ -11,3 +11,4 @@ e2e/help/media.env
|
||||
# The native apps' address screen (npm run build:native), copied into
|
||||
# android/ and ios/ by `cap sync`
|
||||
native-dist/
|
||||
native-sandbox-dist/
|
||||
|
||||
@@ -102,21 +102,61 @@ object TrekBilling {
|
||||
return offers.firstOrNull { it.offerId == null } ?: offers.firstOrNull()
|
||||
}
|
||||
|
||||
/** Play returns eligible offers. The named offer must be configured with Play's new-customer eligibility. */
|
||||
private fun trialOffer(product: ProductDetails): ProductDetails.SubscriptionOfferDetails? {
|
||||
val base = baseOffer(product)?.takeIf { it.offerId == null } ?: return null
|
||||
val recurring = base.pricingPhases.pricingPhaseList.singleOrNull() ?: return null
|
||||
return product.subscriptionOfferDetails?.firstOrNull { offer ->
|
||||
offer.offerId == TRIAL_OFFER_ID && offer.basePlanId == base.basePlanId &&
|
||||
isSevenDayTrial(offer.pricingPhases.pricingPhaseList, recurring)
|
||||
}
|
||||
}
|
||||
|
||||
private fun isSevenDayTrial(
|
||||
phases: List<ProductDetails.PricingPhase>,
|
||||
recurring: ProductDetails.PricingPhase,
|
||||
): Boolean {
|
||||
if (phases.size != 2) return false
|
||||
val (trial, renewal) = phases
|
||||
val once = trial.recurrenceMode == ProductDetails.RecurrenceMode.NON_RECURRING ||
|
||||
(trial.recurrenceMode == ProductDetails.RecurrenceMode.FINITE_RECURRING && trial.billingCycleCount == 1)
|
||||
return once && trial.priceAmountMicros == 0L && trial.billingPeriod in listOf("P1W", "P7D") &&
|
||||
renewal.recurrenceMode == ProductDetails.RecurrenceMode.INFINITE_RECURRING &&
|
||||
renewal.billingPeriod == recurring.billingPeriod && renewal.priceAmountMicros == recurring.priceAmountMicros &&
|
||||
renewal.priceCurrencyCode == recurring.priceCurrencyCode
|
||||
}
|
||||
|
||||
fun products(context: Context, call: PluginCall) {
|
||||
val ids = call.getArray("ids")?.toList<String>().orEmpty()
|
||||
ready(context) { ok ->
|
||||
val result = JSObject().put("sandbox", BuildConfig.DEBUG)
|
||||
if (!ok) return@ready call.resolve(result.put("products", JSArray()))
|
||||
if (!ok || ids.isEmpty()) return@ready call.resolve(result.put("products", JSArray()))
|
||||
details(context, ids) { found ->
|
||||
val list = JSArray()
|
||||
for (product in found) displayPrice(product)?.let { list.put(JSObject().put("id", product.productId).put("displayPrice", it)) }
|
||||
call.resolve(result.put("products", list))
|
||||
val candidates = found.filter { trialOffer(it) != null }.map { it.productId }.toSet()
|
||||
if (candidates.isEmpty()) {
|
||||
call.resolve(result.put("products", productList(found, emptySet())))
|
||||
return@details
|
||||
}
|
||||
val params = QueryPurchasesParams.newBuilder().setProductType(BillingClient.ProductType.SUBS).build()
|
||||
client(context).queryPurchasesAsync(params) { status, purchases ->
|
||||
val eligible = status.responseCode == BillingClient.BillingResponseCode.OK && purchases.none { purchase ->
|
||||
purchase.products.any { it.startsWith(PREFIX) }
|
||||
}
|
||||
call.resolve(result.put("products", productList(found, if (eligible) candidates else emptySet())))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun productList(products: List<ProductDetails>, freeTrials: Set<String>): JSArray = JSArray().apply {
|
||||
for (product in products) displayPrice(product)?.let { price ->
|
||||
put(JSObject().put("id", product.productId).put("displayPrice", price).put("freeTrial", product.productId in freeTrials))
|
||||
}
|
||||
}
|
||||
|
||||
fun purchase(activity: Activity, call: PluginCall) {
|
||||
val id = call.getString("productId") ?: return call.reject("productId is required")
|
||||
val trialRenewalPrice = call.getString("trialRenewalPrice")
|
||||
ready(activity) { ok ->
|
||||
if (!ok) return@ready call.resolve(JSObject().put("kind", "failed"))
|
||||
// One subscription per Google account: a second plan would run beside the first.
|
||||
@@ -126,19 +166,28 @@ object TrekBilling {
|
||||
client(activity).queryPurchasesAsync(params) { result, purchases ->
|
||||
val held = if (result.responseCode == BillingClient.BillingResponseCode.OK) newest(purchases, PREFIX) else null
|
||||
when {
|
||||
held == null -> launchPurchase(activity, call, id)
|
||||
held.isAcknowledged -> call.resolve(JSObject().put("kind", "subscribed"))
|
||||
else -> call.resolve(receipt(held).put("kind", "bought"))
|
||||
held?.isAcknowledged == true -> call.resolve(JSObject().put("kind", "subscribed"))
|
||||
held != null -> call.resolve(receipt(held).put("kind", "bought"))
|
||||
trialRenewalPrice != null && result.responseCode != BillingClient.BillingResponseCode.OK ->
|
||||
call.resolve(JSObject().put("kind", "offer-changed"))
|
||||
purchases.any { p -> p.purchaseState == Purchase.PurchaseState.PENDING && p.products.any { it.startsWith(PREFIX) } } ->
|
||||
call.resolve(JSObject().put("kind", "pending"))
|
||||
else -> launchPurchase(activity, call, id, trialRenewalPrice)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun launchPurchase(activity: Activity, call: PluginCall, id: String) {
|
||||
private fun launchPurchase(activity: Activity, call: PluginCall, id: String, trialRenewalPrice: String?) {
|
||||
details(activity, listOf(id)) { found ->
|
||||
val product = found.firstOrNull()
|
||||
val offer = product?.let(::baseOffer)
|
||||
if (product == null || offer == null) return@details call.resolve(JSObject().put("kind", "failed"))
|
||||
val offer = product?.let { listed ->
|
||||
if (trialRenewalPrice == null) baseOffer(listed)
|
||||
else trialOffer(listed)?.takeIf { displayPrice(listed) == trialRenewalPrice }
|
||||
}
|
||||
if (product == null || offer == null) {
|
||||
return@details call.resolve(JSObject().put("kind", if (trialRenewalPrice != null) "offer-changed" else "failed"))
|
||||
}
|
||||
pendingPurchase?.resolve(JSObject().put("kind", "cancelled"))
|
||||
pendingPurchase = call
|
||||
pendingProduct = id
|
||||
@@ -275,6 +324,7 @@ object TrekBilling {
|
||||
newest(purchases.filter { !it.isAcknowledged }, prefix)
|
||||
|
||||
private const val PREFIX = "cloud."
|
||||
private const val TRIAL_OFFER_ID = "trek-trial-7-days"
|
||||
|
||||
internal fun newest(purchases: List<Purchase>, prefix: String): Purchase? = purchases
|
||||
.filter { p -> p.purchaseState == Purchase.PurchaseState.PURCHASED && p.products.any { it.startsWith(prefix) } }
|
||||
|
||||
@@ -688,14 +688,40 @@ extension TrekShellPlugin {
|
||||
let ids = call.getArray("ids", String.self) ?? []
|
||||
Task {
|
||||
let sandbox = await Self.buysInSandbox()
|
||||
guard AppStore.canMakePayments, let products = try? await Product.products(for: ids) else {
|
||||
guard !ids.isEmpty, AppStore.canMakePayments, let products = try? await Product.products(for: ids) else {
|
||||
call.resolve(["products": [], "sandbox": sandbox])
|
||||
return
|
||||
}
|
||||
call.resolve(["products": products.map { ["id": $0.id, "displayPrice": $0.displayPrice] }, "sandbox": sandbox])
|
||||
var canStartTrial = false
|
||||
if products.contains(where: Self.hasSevenDayFreeTrial) {
|
||||
canStartTrial = await TrekStore.currentEntitlement(prefix: "cloud.") == nil
|
||||
}
|
||||
var groupEligibility: [String: Bool] = [:]
|
||||
var rows: [[String: Any]] = []
|
||||
for product in products {
|
||||
var freeTrial = false
|
||||
if canStartTrial, Self.hasSevenDayFreeTrial(product), let subscription = product.subscription {
|
||||
let group = subscription.subscriptionGroupID
|
||||
if let cached = groupEligibility[group] {
|
||||
freeTrial = cached
|
||||
} else {
|
||||
freeTrial = await subscription.isEligibleForIntroOffer
|
||||
groupEligibility[group] = freeTrial
|
||||
}
|
||||
}
|
||||
rows.append(["id": product.id, "displayPrice": product.displayPrice, "freeTrial": freeTrial])
|
||||
}
|
||||
call.resolve(["products": rows, "sandbox": sandbox])
|
||||
}
|
||||
}
|
||||
|
||||
private static func hasSevenDayFreeTrial(_ product: Product) -> Bool {
|
||||
guard let offer = product.subscription?.introductoryOffer,
|
||||
offer.paymentMode == .freeTrial, offer.price == 0, offer.periodCount == 1 else { return false }
|
||||
return (offer.period.unit == .week && offer.period.value == 1)
|
||||
|| (offer.period.unit == .day && offer.period.value == 7)
|
||||
}
|
||||
|
||||
/// Whether this build buys in the App Store sandbox: TestFlight, App Review and
|
||||
/// 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,
|
||||
@@ -726,6 +752,7 @@ extension TrekShellPlugin {
|
||||
call.reject("productId is required")
|
||||
return
|
||||
}
|
||||
let trialRenewalPrice = call.getString("trialRenewalPrice")
|
||||
Task {
|
||||
// One subscription per Apple ID: another plan would change it, not add one.
|
||||
// A held one that was delivered stops the purchase here. One that was paid
|
||||
@@ -740,9 +767,18 @@ extension TrekShellPlugin {
|
||||
}
|
||||
do {
|
||||
guard let product = try await Product.products(for: [id]).first else {
|
||||
call.resolve(["kind": "failed"])
|
||||
call.resolve(["kind": trialRenewalPrice == nil ? "failed" : "offer-changed"])
|
||||
return
|
||||
}
|
||||
if let trialRenewalPrice {
|
||||
guard product.displayPrice == trialRenewalPrice, Self.hasSevenDayFreeTrial(product),
|
||||
let subscription = product.subscription,
|
||||
await subscription.isEligibleForIntroOffer else {
|
||||
call.resolve(["kind": "offer-changed"])
|
||||
return
|
||||
}
|
||||
}
|
||||
// StoreKit applies an eligible introductory offer in its purchase sheet.
|
||||
switch try await product.purchase() {
|
||||
case .success(let verification):
|
||||
guard case .verified(let transaction) = verification else {
|
||||
|
||||
+210
-140
@@ -7,14 +7,21 @@ import { PASSWORD_MIN_LENGTH, passwordProblem, passwordRuleStates } from '../../
|
||||
import logoWhite from '../public/logo-light.svg'; // #fff wordmark, for the landscape
|
||||
import { pageUnderStatusBar } from '../src/native/appBoot';
|
||||
import { AUTH_GATE_NAMES, canSignInInApp, type AuthGate } from '../src/native/authGate';
|
||||
import { isNewCloudPlan, opensSoon, planForUnclaimedPurchase, refundedBeforeOpening } from '../src/native/cloudOrders';
|
||||
import { fakeIapClient, getIapClient, productIdFor, type Purchase } from '../src/native/iap';
|
||||
import {
|
||||
isNewCloudPlan,
|
||||
matchesPurchaseAgreement,
|
||||
opensSoon,
|
||||
planForUnclaimedPurchase,
|
||||
refundedBeforeOpening,
|
||||
type CloudPurchaseAgreement,
|
||||
} from '../src/native/cloudOrders';
|
||||
import { fakeIapClient, getIapClient, productIdFor, type IapProduct, type Purchase } from '../src/native/iap';
|
||||
import {
|
||||
APP_STORE_SUBSCRIPTIONS_URL,
|
||||
AUTH_PROXY_DOCS_URL,
|
||||
CLIENT_CERT_DOCS_URL,
|
||||
CLOUD_TERMS_URL,
|
||||
CLOUD_URL,
|
||||
CLOUD_URL as PRODUCTION_CLOUD_URL,
|
||||
PLAY_SUBSCRIPTIONS_URL,
|
||||
PRIVACY_URL,
|
||||
STORE_TERMS_URL,
|
||||
@@ -50,6 +57,13 @@ document.documentElement.dir = directionOf(locale);
|
||||
|
||||
const root = document.getElementById('shell')!;
|
||||
const PROBE_TIMEOUT_MS = 8000;
|
||||
const cloudSandbox = typeof __TREK_STORE_SANDBOX_ORIGIN__ === 'string' ? __TREK_STORE_SANDBOX_ORIGIN__ : undefined;
|
||||
const CLOUD_URL = cloudSandbox ?? PRODUCTION_CLOUD_URL;
|
||||
const cloudHttpOptions = {
|
||||
connectTimeout: PROBE_TIMEOUT_MS,
|
||||
readTimeout: PROBE_TIMEOUT_MS,
|
||||
...(cloudSandbox ? { disableRedirects: true } : {}),
|
||||
};
|
||||
|
||||
const iap = getIapClient();
|
||||
/**
|
||||
@@ -98,6 +112,30 @@ const get: ProbeGet = async (url) => {
|
||||
}
|
||||
};
|
||||
|
||||
// Keep Cloud sandbox requests on their requested host, including during tenant provisioning.
|
||||
const cloudGet: ProbeGet = cloudSandbox ? (url) => CapacitorHttp.get({ url, ...cloudHttpOptions }) : get;
|
||||
|
||||
function isCloudSandboxTenant(address: string, sandboxOrigin: string): boolean {
|
||||
let tenant: URL;
|
||||
try {
|
||||
tenant = new URL(address);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
const suffix = `.${new URL(sandboxOrigin).hostname}`;
|
||||
const slug = tenant.hostname.slice(0, -suffix.length);
|
||||
return (
|
||||
tenant.origin === `https://${tenant.hostname}` &&
|
||||
!tenant.username &&
|
||||
!tenant.password &&
|
||||
tenant.hostname.endsWith(suffix) &&
|
||||
/^[a-z0-9-]+$/.test(slug) &&
|
||||
tenant.pathname === '/' &&
|
||||
!tenant.search &&
|
||||
!tenant.hash
|
||||
);
|
||||
}
|
||||
|
||||
function failureMessage(reason: ProbeFailure): string {
|
||||
switch (reason) {
|
||||
case 'invalid':
|
||||
@@ -151,12 +189,11 @@ const I = {
|
||||
globe: 'M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20M2 12h20M12 2a15 15 0 0 1 0 20 15 15 0 0 1 0-20',
|
||||
image:
|
||||
'M5 3h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2zM8.5 10a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3zM21 15l-5-5L5 21',
|
||||
spark: 'M12 3l1.8 5.2L19 10l-5.2 1.8L12 17l-1.8-5.2L5 10l5.2-1.8z',
|
||||
mail: 'M4 5h16a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2zM3 7l9 6 9-6',
|
||||
people:
|
||||
'M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2M9 11a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM22 21v-2a4 4 0 0 0-3-3.87M16 3.13a4 4 0 0 1 0 7.75',
|
||||
shield: 'M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10',
|
||||
check: 'M20 6 9 17l-5-5',
|
||||
cross: 'M6 6l12 12M18 6 6 18',
|
||||
lock: 'M6 11h12a2 2 0 0 1 2 2v7a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2zM8 11V8a4 4 0 0 1 8 0v3',
|
||||
key: 'M7.5 20a4.5 4.5 0 1 0 0-9 4.5 4.5 0 0 0 0 9zM10.7 12.3 21 2M16 7l3 3M14 9l2 2',
|
||||
alert: 'M12 21.5a9.5 9.5 0 1 0 0-19 9.5 9.5 0 0 0 0 19zM12 7.5v5.5M12 16.5h.01',
|
||||
@@ -315,7 +352,8 @@ function showWelcome(opts: { back?: boolean } = {}): void {
|
||||
const perk = (glyph: string, title: string, sub: string) =>
|
||||
el('div', {}, el('i', {}, icon(glyph, 17)), el('span', {}, el('b', {}, title), el('small', {}, sub)));
|
||||
|
||||
const discover = el('button', { type: 'button', className: 'cta' }, t('native.welcome.discover'));
|
||||
const trial = el('span', { className: 'trial-badge', hidden: true }, t('native.trial.badge'));
|
||||
const discover = el('button', { type: 'button', className: 'cta discover' }, t('native.welcome.discover'), trial);
|
||||
discover.addEventListener('click', () => {
|
||||
void tap();
|
||||
showPlans();
|
||||
@@ -326,7 +364,7 @@ function showWelcome(opts: { back?: boolean } = {}): void {
|
||||
showConnect();
|
||||
});
|
||||
|
||||
show(
|
||||
const screen = show(
|
||||
'welcome',
|
||||
WELCOME_CAMERA,
|
||||
{
|
||||
@@ -351,6 +389,9 @@ function showWelcome(opts: { back?: boolean } = {}): void {
|
||||
},
|
||||
opts
|
||||
);
|
||||
void availableWelcomeTrial().then((available) => {
|
||||
if (screen.node.isConnected) trial.hidden = !available;
|
||||
});
|
||||
}
|
||||
|
||||
// ── Connect (address) ───────────────────────────────────────────────────────
|
||||
@@ -664,7 +705,7 @@ interface CloudPlan {
|
||||
yearlyCents?: number;
|
||||
currency?: 'EUR' | 'USD';
|
||||
aiDocuments: number;
|
||||
aiDocumentLimit?: 0 | null;
|
||||
aiDocumentLimit?: number | null;
|
||||
aiAssistant?: 'planned' | 'included' | 'unavailable';
|
||||
bookingMailImport?: boolean;
|
||||
storageGb: number;
|
||||
@@ -681,24 +722,24 @@ const SAMPLE_PLANS: CloudPlan[] = [
|
||||
{
|
||||
id: 'start',
|
||||
name: 'Start',
|
||||
monthlyCents: 499,
|
||||
monthlyCents: 599,
|
||||
yearlyCents: 4899,
|
||||
currency: 'USD',
|
||||
aiDocuments: 0,
|
||||
aiDocumentLimit: 0,
|
||||
storageGb: 200,
|
||||
storageGb: 50,
|
||||
},
|
||||
{
|
||||
id: 'plus',
|
||||
name: 'Plus',
|
||||
monthlyCents: 999,
|
||||
monthlyCents: 1199,
|
||||
yearlyCents: 9900,
|
||||
currency: 'USD',
|
||||
aiDocuments: 100,
|
||||
aiDocumentLimit: null,
|
||||
aiAssistant: 'planned',
|
||||
aiAssistant: 'included',
|
||||
bookingMailImport: true,
|
||||
storageGb: 200,
|
||||
storageGb: 50,
|
||||
},
|
||||
];
|
||||
|
||||
@@ -706,15 +747,18 @@ interface CloudPlans {
|
||||
plans: CloudPlan[];
|
||||
/** Orders are closed: only a test build may buy, and the store charges it nothing. */
|
||||
closed: boolean;
|
||||
/** Only the live catalogue's explicit opening permits customer trial advertising. */
|
||||
open?: boolean;
|
||||
}
|
||||
|
||||
async function fetchPlans(): Promise<CloudPlans | null> {
|
||||
try {
|
||||
const res = await get(`${CLOUD_URL}/api/plans`);
|
||||
const res = await cloudGet(`${CLOUD_URL}/api/plans`);
|
||||
const data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data;
|
||||
const body = (data ?? {}) as { plans?: CloudPlan[]; ordering?: string };
|
||||
const plans = Array.isArray(body.plans) ? body.plans.filter((plan) => isNewCloudPlan(plan.id)) : [];
|
||||
if (plans.length) return { plans, closed: body.ordering === 'closed' };
|
||||
if (plans.length)
|
||||
return { plans, closed: body.ordering === 'closed', open: res.status === 200 && body.ordering === 'open' };
|
||||
} catch {
|
||||
// Fall through to the preview fallback.
|
||||
}
|
||||
@@ -730,22 +774,44 @@ async function fetchPlans(): Promise<CloudPlans | null> {
|
||||
*/
|
||||
interface Offer {
|
||||
canBuy: boolean;
|
||||
storePrices: Map<string, string> | null;
|
||||
storeProducts: Map<string, IapProduct> | null;
|
||||
canShowTrial: boolean;
|
||||
/** Orders are closed and this is no test build: the plans show, nothing is for sale yet. */
|
||||
opensSoon: boolean;
|
||||
}
|
||||
|
||||
function offerFor(offer: Offer, plan: CloudPlan, interval: 'month' | 'year'): { label: string; buyable: boolean } {
|
||||
if (!offer.canBuy) return { label: '', buyable: false };
|
||||
function offerFor(
|
||||
offer: Offer,
|
||||
plan: CloudPlan,
|
||||
interval: 'month' | 'year'
|
||||
): { label: string; buyable: boolean; freeTrial: boolean } {
|
||||
if (!offer.canBuy) return { label: '', buyable: false, freeTrial: false };
|
||||
if (iap !== fakeIapClient) {
|
||||
const label = offer.storePrices?.get(productIdFor(plan.id, interval)) ?? '';
|
||||
return { label, buyable: label !== '' };
|
||||
const product = offer.storeProducts?.get(productIdFor(plan.id, interval));
|
||||
const label = product?.displayPrice ?? '';
|
||||
return {
|
||||
label,
|
||||
buyable: label !== '',
|
||||
freeTrial: label !== '' && offer.canShowTrial && product?.freeTrial === true,
|
||||
};
|
||||
}
|
||||
const cents = interval === 'year' ? plan.yearlyCents : plan.monthlyCents;
|
||||
const currency = plan.currency ?? 'EUR';
|
||||
const label =
|
||||
typeof cents === 'number' ? new Intl.NumberFormat(locale, { style: 'currency', currency }).format(cents / 100) : '';
|
||||
return { label, buyable: label !== '' };
|
||||
return { label, buyable: label !== '', freeTrial: false };
|
||||
}
|
||||
|
||||
function storeIds(plans: CloudPlan[]): string[] {
|
||||
return plans.flatMap((p) => [productIdFor(p.id, 'month'), productIdFor(p.id, 'year')]);
|
||||
}
|
||||
|
||||
async function availableWelcomeTrial(): Promise<boolean> {
|
||||
if (iap === fakeIapClient || !(await iapReady)) return false;
|
||||
const list = await fetchPlans();
|
||||
if (!list?.open) return false;
|
||||
const products = await iap.products(storeIds(list.plans));
|
||||
return Array.from(products.values()).some((product) => product.freeTrial && product.displayPrice !== '');
|
||||
}
|
||||
|
||||
async function loadOffer(list: CloudPlans): Promise<Offer> {
|
||||
@@ -755,39 +821,61 @@ async function loadOffer(list: CloudPlans): Promise<Offer> {
|
||||
const sandbox = list.closed && !onPlay ? await iap.isSandbox().catch(() => false) : false;
|
||||
const soon = opensSoon({ available, closed: list.closed, sandbox, onPlay });
|
||||
const canBuy = available && !soon;
|
||||
if (!canBuy || iap === fakeIapClient) return { canBuy, storePrices: null, opensSoon: soon };
|
||||
const ids = list.plans.flatMap((p) => [productIdFor(p.id, 'month'), productIdFor(p.id, 'year')]);
|
||||
return { canBuy, storePrices: await iap.prices(ids), opensSoon: soon };
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
/** 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];
|
||||
}
|
||||
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 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: '' };
|
||||
const storage = plan.storageGb >= 1000 ? `${count(plan.storageGb / 1000)} TB` : `${count(plan.storageGb)} GB`;
|
||||
const aiDocuments = plan.aiDocumentLimit === null || (plan.aiDocumentLimit ?? plan.aiDocuments) > 0;
|
||||
return [
|
||||
row(t('native.plans.storage'), storage, I.image),
|
||||
feature(t('native.plans.aiLabel'), aiDocuments),
|
||||
feature(t('native.plans.assistant'), plan.aiAssistant === 'included'),
|
||||
feature(t('native.plans.mailImport'), plan.bookingMailImport === true),
|
||||
row(t('native.plans.unlimitedSub'), t('native.plans.unlimited'), I.people),
|
||||
];
|
||||
}
|
||||
|
||||
function per(interval: 'month' | 'year'): string {
|
||||
return interval === 'year' ? t('native.plans.perYear') : t('native.plans.perMonth');
|
||||
}
|
||||
|
||||
function trialPrice(price: string, interval: 'month' | 'year'): string {
|
||||
return t('native.trial.price', { price, period: per(interval) });
|
||||
}
|
||||
|
||||
function trialCancellation(): string {
|
||||
return t(onPlay ? 'native.trial.cancelPlay' : 'native.trial.cancelApple');
|
||||
}
|
||||
|
||||
/** The restore button of the plans on screen, which redeems a payment that cleared later. */
|
||||
let resumeRestore: (() => void) | null = null;
|
||||
let watchingTransactions = false;
|
||||
/** Where the camera stood on the plan chosen last, for the screens that follow it. */
|
||||
let chosenCamera: Camera = cameraForPlan(1);
|
||||
/** The plan chosen last, so coming back to the plans finds it still chosen. */
|
||||
/** Restore a choice when returning from setup. A fresh entry opens Plus. */
|
||||
let chosenPlanId: string | null = null;
|
||||
let chosenInterval: 'month' | 'year' = 'month';
|
||||
|
||||
@@ -852,14 +940,11 @@ function restoreButton(plans: CloudPlan[]): HTMLButtonElement {
|
||||
function showPlans(opts: { back?: boolean } = {}): void {
|
||||
let interval: 'month' | 'year' = chosenInterval;
|
||||
let plans: CloudPlan[] = [];
|
||||
let offer: Offer = { canBuy: false, storePrices: null, opensSoon: false };
|
||||
let offer: Offer = { canBuy: false, storeProducts: null, canShowTrial: false, opensSoon: false };
|
||||
let selectedId: string | null = null;
|
||||
|
||||
const tiers = el('div', { className: 'tiers', role: 'radiogroup', hidden: true });
|
||||
tiers.setAttribute('aria-label', t('native.plans.title'));
|
||||
const title = el('h1', {});
|
||||
const text = el('p', {});
|
||||
const trip = el('div', { className: 'trip' }, title, text);
|
||||
|
||||
const monthBtn = el('button', { type: 'button', role: 'radio' }, t('native.plans.monthly'));
|
||||
const yearBtn = el('button', { type: 'button', role: 'radio' }, t('native.plans.yearly'));
|
||||
@@ -876,18 +961,20 @@ function showPlans(opts: { back?: boolean } = {}): void {
|
||||
const pricePer = el('span', {});
|
||||
const price = el('div', { className: 'price' }, priceValue, pricePer);
|
||||
const equals = el('div', { className: 'equals' });
|
||||
const pricebox = el('div', { className: 'pricebox' }, cycle, price, equals);
|
||||
const specs = el('div', { className: 'specs' });
|
||||
const trial = el('p', { className: 'trial-price', hidden: true });
|
||||
const pricebox = el('div', { className: 'pricebox' }, cycle, price, equals, trial);
|
||||
const specs = el('ul', { className: 'specs', role: 'list' });
|
||||
const foot = el('div', { className: 'pad', hidden: true });
|
||||
const legal = el('p', { className: 'legal' });
|
||||
|
||||
const loading = el('div', { className: 'loading' }, el('span', { className: 'spin' }));
|
||||
const details = el('div', { className: 'stack', hidden: true }, trip, pricebox, specs);
|
||||
const details = el('div', { className: 'stack', hidden: true }, pricebox, specs);
|
||||
const choose = el('button', { type: 'button', className: 'cta', hidden: true });
|
||||
const dock = el('div', { className: 'dock' }, choose);
|
||||
|
||||
const screen = show(
|
||||
'plain',
|
||||
chosenCamera,
|
||||
opts.back ? chosenCamera : cameraForPlan(1),
|
||||
{
|
||||
back: () => showWelcome({ back: true }),
|
||||
content: [el('div', { className: 'pad lift' }, tiers, loading, details), foot, dock],
|
||||
@@ -934,20 +1021,11 @@ function showPlans(opts: { back?: boolean } = {}): void {
|
||||
yearBtn.setAttribute('aria-checked', String(interval === 'year'));
|
||||
cycle.dataset.year = String(interval === 'year');
|
||||
|
||||
const { title: tripTitle, text: tripText } = tripOf(plan);
|
||||
const recommended = recommendedPlan(plans)?.id === plan.id;
|
||||
title.replaceChildren(
|
||||
tripTitle,
|
||||
...(recommended ? [el('span', { className: 'badge' }, t('native.plans.recommended'))] : [])
|
||||
);
|
||||
text.textContent = tripText;
|
||||
text.hidden = !tripText;
|
||||
|
||||
const { label, buyable } = interval === 'month' ? month : year;
|
||||
// No price yet (orders not open): the plan shows without one rather than with an empty one.
|
||||
price.hidden = !label;
|
||||
const { label, buyable, freeTrial } = interval === 'month' ? month : year;
|
||||
// An introductory offer states the free period and renewal price together.
|
||||
price.hidden = !label || freeTrial;
|
||||
pricePer.textContent = per(interval);
|
||||
if (label) paintPrice(label, animate);
|
||||
if (label && !freeTrial) paintPrice(label, animate);
|
||||
|
||||
// Without a price in either period (orders not open yet) the switch would choose between nothing.
|
||||
pricebox.hidden = !month.label && !year.label;
|
||||
@@ -955,59 +1033,23 @@ function showPlans(opts: { back?: boolean } = {}): void {
|
||||
yearBtn.disabled = !year.label;
|
||||
const yearAmount = amountIn(year.label);
|
||||
equals.textContent =
|
||||
!label || !year.label
|
||||
!label || !year.label || freeTrial
|
||||
? ''
|
||||
: interval === 'month'
|
||||
? t('native.plans.yearlyIs', { price: year.label })
|
||||
: yearAmount
|
||||
? t('native.plans.monthlyIs', { price: yearAmount.render(yearAmount.value / 12) })
|
||||
: '';
|
||||
trial.hidden = !freeTrial;
|
||||
trial.textContent = freeTrial ? trialPrice(label, interval) : '';
|
||||
legal.textContent = freeTrial
|
||||
? trialCancellation()
|
||||
: t(onPlay ? 'native.plans.legalAndroid' : 'native.plans.legal');
|
||||
|
||||
const gb = plan.storageGb >= 1000 ? `${count(plan.storageGb / 1000)} TB` : `${count(plan.storageGb)} GB`;
|
||||
const notIncluded = t('native.plans.aiNone');
|
||||
const included = t('native.plans.included');
|
||||
const assistant = plan.aiAssistant === 'included';
|
||||
const tile = (glyph: string, big: string, small: string, off = false) =>
|
||||
el(
|
||||
'span',
|
||||
{ className: off ? 'spec off' : 'spec' },
|
||||
el('i', {}, icon(glyph, 17)),
|
||||
el('span', {}, el('b', {}, big), el('small', {}, small))
|
||||
);
|
||||
specs.replaceChildren(
|
||||
tile(I.image, gb, t('native.plans.storageFairUse')),
|
||||
plan.aiDocuments > 0
|
||||
? tile(
|
||||
I.spark,
|
||||
plan.aiDocumentLimit === null
|
||||
? t('native.plans.unlimited')
|
||||
: t('native.plans.aiPerMonth', { n: count(plan.aiDocuments) }),
|
||||
t('native.plans.aiLabel')
|
||||
)
|
||||
: tile(I.spark, notIncluded, t('native.plans.aiLabel'), true),
|
||||
tile(
|
||||
I.spark,
|
||||
assistant ? included : plan.aiAssistant === 'planned' ? t('native.plans.planned') : notIncluded,
|
||||
t('native.plans.assistant'),
|
||||
!assistant
|
||||
),
|
||||
tile(
|
||||
I.mail,
|
||||
plan.bookingMailImport ? included : notIncluded,
|
||||
t('native.plans.mailImport'),
|
||||
!plan.bookingMailImport
|
||||
),
|
||||
el(
|
||||
'span',
|
||||
{ className: 'spec wide' },
|
||||
el('i', {}, icon(I.people, 17)),
|
||||
el('span', {}, el('b', {}, t('native.plans.unlimited')), el('small', {}, t('native.plans.unlimitedSub'))),
|
||||
el('em', {}, t('native.plans.inEveryPlan'))
|
||||
)
|
||||
);
|
||||
specs.replaceChildren(...planFeatures(plan));
|
||||
|
||||
choose.hidden = !buyable;
|
||||
choose.textContent = t('native.plans.choose', { trip: tripTitle });
|
||||
choose.textContent = t('native.plans.choose', { plan: plan.name });
|
||||
chosenCamera = cameraForPlan(index);
|
||||
chosenPlanId = plan.id;
|
||||
chosenInterval = interval;
|
||||
@@ -1042,7 +1084,7 @@ function showPlans(opts: { back?: boolean } = {}): void {
|
||||
showSubscribed();
|
||||
return;
|
||||
}
|
||||
showClaim(plan, selectedInterval, price.label);
|
||||
showClaim(plan, selectedInterval, price.label, { freeTrial: price.freeTrial });
|
||||
});
|
||||
|
||||
const load = async () => {
|
||||
@@ -1060,7 +1102,9 @@ function showPlans(opts: { back?: boolean } = {}): void {
|
||||
}
|
||||
offer = await loadOffer(list);
|
||||
plans = list.plans;
|
||||
selectedId = plans.find((p) => p.id === chosenPlanId)?.id ?? recommendedPlan(plans)?.id ?? null;
|
||||
const previousId = opts.back ? chosenPlanId : null;
|
||||
selectedId =
|
||||
plans.find((p) => p.id === previousId)?.id ?? plans.find((p) => p.id === 'plus')?.id ?? plans[0]?.id ?? null;
|
||||
tiers.replaceChildren(
|
||||
...plans.map((p) => {
|
||||
const b = el('button', { type: 'button', role: 'radio', dataset: { plan: p.id } }, p.name);
|
||||
@@ -1083,7 +1127,7 @@ function showPlans(opts: { back?: boolean } = {}): void {
|
||||
);
|
||||
} else {
|
||||
foot.replaceChildren(
|
||||
el('p', { className: 'legal' }, t(onPlay ? 'native.plans.legalAndroid' : 'native.plans.legal')),
|
||||
legal,
|
||||
el(
|
||||
'div',
|
||||
{ className: 'legal-links' },
|
||||
@@ -1105,7 +1149,7 @@ type SlugStatus = 'available' | 'taken' | 'invalid' | 'reserved' | 'error';
|
||||
|
||||
async function slugStatus(slug: string): Promise<SlugStatus> {
|
||||
try {
|
||||
const res = await get(`${CLOUD_URL}/api/slug/check?slug=${encodeURIComponent(slug)}`);
|
||||
const res = await cloudGet(`${CLOUD_URL}/api/slug/check?slug=${encodeURIComponent(slug)}`);
|
||||
const data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data;
|
||||
const status = (data as { status?: string })?.status;
|
||||
if (status === 'available' || status === 'taken' || status === 'invalid' || status === 'reserved') return status;
|
||||
@@ -1120,21 +1164,17 @@ async function slugStatus(slug: string): Promise<SlugStatus> {
|
||||
* (terms § 2 (1a), § 327h BGB), as the control plane words and versions it. The
|
||||
* app shows the server's text, never its own, and sends back the version it showed.
|
||||
*/
|
||||
interface DeviationsConsent {
|
||||
version: string;
|
||||
text: string;
|
||||
}
|
||||
async function fetchConsent(): Promise<DeviationsConsent | null> {
|
||||
async function fetchConsent(): Promise<CloudPurchaseAgreement | null> {
|
||||
try {
|
||||
const res = await CapacitorHttp.get({
|
||||
url: `${CLOUD_URL}/api/iap/consent`,
|
||||
params: { lang: locale === 'de' ? 'de' : 'en' },
|
||||
connectTimeout: PROBE_TIMEOUT_MS,
|
||||
readTimeout: PROBE_TIMEOUT_MS,
|
||||
...cloudHttpOptions,
|
||||
});
|
||||
const data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data;
|
||||
const body = (data ?? {}) as { version?: unknown; deviations?: unknown };
|
||||
const body = (data ?? {}) as { version?: unknown; deviations?: unknown; iapEnvironment?: unknown };
|
||||
if (res.status !== 200 || typeof body.version !== 'string' || typeof body.deviations !== 'string') return null;
|
||||
if (cloudSandbox && body.iapEnvironment !== 'sandbox') return null;
|
||||
if (!body.version || !body.deviations) return null;
|
||||
return { version: body.version, text: body.deviations };
|
||||
} catch {
|
||||
@@ -1162,8 +1202,7 @@ async function redeemPurchase(
|
||||
const res = await CapacitorHttp.post({
|
||||
url: `${CLOUD_URL}/api/iap/redeem`,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
connectTimeout: PROBE_TIMEOUT_MS,
|
||||
readTimeout: PROBE_TIMEOUT_MS,
|
||||
...cloudHttpOptions,
|
||||
// The language of the contract confirmation mail.
|
||||
data: {
|
||||
platform: purchase.platform,
|
||||
@@ -1181,6 +1220,9 @@ async function redeemPurchase(
|
||||
const data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data;
|
||||
const body = (data ?? {}) as { instanceUrl?: string; code?: string; welcome?: string };
|
||||
if ((res.status === 200 || res.status === 201) && typeof body.instanceUrl === 'string') {
|
||||
if (cloudSandbox && !isCloudSandboxTenant(body.instanceUrl, cloudSandbox)) {
|
||||
return { ok: false, code: 'redeem-failed' };
|
||||
}
|
||||
const welcome =
|
||||
typeof body.welcome === 'string' && /^[A-Za-z0-9_-]{43}$/.test(body.welcome) ? body.welcome : undefined;
|
||||
return { ok: true, instanceUrl: body.instanceUrl, ...(welcome ? { welcome } : {}) };
|
||||
@@ -1195,7 +1237,7 @@ function showClaim(
|
||||
plan: Pick<CloudPlan, 'id' | 'name'>,
|
||||
interval: 'month' | 'year',
|
||||
priceLabel: string,
|
||||
opts: { back?: boolean; bought?: Purchase } = {}
|
||||
opts: { back?: boolean; bought?: Purchase; freeTrial?: boolean } = {}
|
||||
): void {
|
||||
/** A purchase that went through but whose redeem did not: a retry redeems it again instead of buying twice. */
|
||||
let bought: Purchase | null = opts.bought ?? null;
|
||||
@@ -1279,7 +1321,7 @@ function showClaim(
|
||||
};
|
||||
|
||||
// The § 327h agreement, asked on its own before anything is bought.
|
||||
let consent: DeviationsConsent | null = null;
|
||||
let consent: CloudPurchaseAgreement | null = null;
|
||||
const consentBox = el('input', { type: 'checkbox' });
|
||||
const consentText = el('span', { className: 'consent-text' }, t('native.claim.consentLoading'));
|
||||
const consentField = el(
|
||||
@@ -1288,19 +1330,26 @@ function showClaim(
|
||||
consentBox,
|
||||
el('span', {}, el('strong', {}, t('native.claim.consentTitle')), consentText)
|
||||
);
|
||||
const loadConsent = async (): Promise<DeviationsConsent | null> => {
|
||||
const showConsent = (current: CloudPurchaseAgreement | null): void => {
|
||||
consent = current;
|
||||
consentBox.checked = false;
|
||||
consentBox.disabled = true;
|
||||
consentText.textContent = t('native.claim.consentLoading');
|
||||
consent = await fetchConsent();
|
||||
consentBox.disabled = consent === null;
|
||||
consentText.textContent = consent ? consent.text : t('native.claim.consentUnavailable');
|
||||
};
|
||||
const loadConsent = async (): Promise<CloudPurchaseAgreement | null> => {
|
||||
consentBox.disabled = true;
|
||||
consentText.textContent = t('native.claim.consentLoading');
|
||||
showConsent(await fetchConsent());
|
||||
return consent;
|
||||
};
|
||||
void loadConsent();
|
||||
|
||||
const subscribeLabel = () =>
|
||||
bought ? t('native.claim.completeSetup') : t('native.claim.subscribe', { price: priceLabel });
|
||||
bought
|
||||
? t('native.claim.completeSetup')
|
||||
: opts.freeTrial
|
||||
? t('native.trial.badge')
|
||||
: t('native.claim.subscribe', { price: priceLabel });
|
||||
const submit = el('button', { type: 'button', className: 'cta' }, subscribeLabel());
|
||||
// What is about to be bought, so nobody pays for a plan they did not mean.
|
||||
const change = el('button', { type: 'button' }, t('native.claim.change'));
|
||||
@@ -1308,19 +1357,25 @@ function showClaim(
|
||||
void tap();
|
||||
showPlans({ back: true });
|
||||
});
|
||||
const planPrice = !priceLabel
|
||||
? null
|
||||
: opts.freeTrial
|
||||
? el('small', {}, trialPrice(priceLabel, interval))
|
||||
: el('small', { dir: 'ltr' }, `${priceLabel} ${per(interval)}`);
|
||||
const planRow = el(
|
||||
'div',
|
||||
{ className: 'plan-row' },
|
||||
el(
|
||||
'span',
|
||||
{},
|
||||
el('b', {}, plan.name),
|
||||
...(priceLabel ? [el('small', { dir: 'ltr' }, `${priceLabel} ${per(interval)}`)] : [])
|
||||
),
|
||||
el('span', {}, el('b', {}, plan.name), ...(planPrice ? [planPrice] : [])),
|
||||
// A purchase already made is not a choice any more.
|
||||
...(bought ? [] : [change])
|
||||
);
|
||||
const error = notice('');
|
||||
const checkoutDock = el(
|
||||
'div',
|
||||
{ className: 'dock' },
|
||||
submit,
|
||||
el('p', { className: 'fine' }, opts.freeTrial ? trialCancellation() : t('native.claim.renews'))
|
||||
);
|
||||
const form = el(
|
||||
'form',
|
||||
{ className: 'pad form', noValidate: true },
|
||||
@@ -1347,10 +1402,7 @@ function showClaim(
|
||||
{
|
||||
back: () => showPlans({ back: true }),
|
||||
overlay: [card.node],
|
||||
content: [
|
||||
form,
|
||||
el('div', { className: 'dock' }, submit, el('p', { className: 'fine' }, t('native.claim.renews'))),
|
||||
],
|
||||
content: [form, checkoutDock],
|
||||
},
|
||||
opts
|
||||
);
|
||||
@@ -1440,7 +1492,8 @@ function showClaim(
|
||||
consentBox.focus();
|
||||
return;
|
||||
}
|
||||
const consentVersion = consent ? consent.version : null;
|
||||
const acceptedConsent = consent;
|
||||
const consentVersion = acceptedConsent?.version ?? null;
|
||||
|
||||
void tap(ImpactStyle.Medium);
|
||||
// The purchase sheet and the progress want the whole screen, not the keyboard.
|
||||
@@ -1460,7 +1513,24 @@ function showClaim(
|
||||
};
|
||||
|
||||
if (!bought) {
|
||||
const outcome = await iap.purchase(productIdFor(plan.id, interval));
|
||||
const currentConsent = await fetchConsent();
|
||||
if (!form.isConnected) return;
|
||||
if (!matchesPurchaseAgreement(acceptedConsent, currentConsent)) {
|
||||
restore();
|
||||
showConsent(currentConsent);
|
||||
setNotice(error, t(currentConsent ? 'native.claim.consentRequired' : 'native.claim.consentUnavailable'));
|
||||
if (currentConsent) consentBox.focus();
|
||||
return;
|
||||
}
|
||||
const trialRenewalPrice = opts.freeTrial ? priceLabel : undefined;
|
||||
const outcome = await iap.purchase(productIdFor(plan.id, interval), trialRenewalPrice);
|
||||
if (outcome.kind === 'offer-changed') {
|
||||
restore();
|
||||
planPrice?.remove();
|
||||
checkoutDock.hidden = true;
|
||||
setNotice(error, t('native.trial.changed'));
|
||||
return;
|
||||
}
|
||||
if (outcome.kind === 'cancelled') {
|
||||
restore();
|
||||
setNotice(error, t('native.claim.cancelled'));
|
||||
@@ -1650,8 +1720,8 @@ function showProvisioning(instanceUrl: string, welcome?: string): void {
|
||||
const deadline = Date.now() + 180_000;
|
||||
const poll = async (): Promise<void> => {
|
||||
if (!view.screen.node.isConnected) return;
|
||||
const result = await probeServer(instanceUrl, get);
|
||||
if (result.ok) {
|
||||
const result = await probeServer(instanceUrl, cloudGet);
|
||||
if (result.ok && (!cloudSandbox || new URL(result.url).origin === new URL(instanceUrl).origin)) {
|
||||
await ready(result.url);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -320,14 +320,14 @@ input {
|
||||
overflow: hidden;
|
||||
background: var(--sea);
|
||||
margin-bottom: -1px;
|
||||
height: min(300px, 36svh);
|
||||
height: max(calc(var(--safe-top) + 68px), min(252px, 30svh));
|
||||
}
|
||||
.hero.tall {
|
||||
height: min(320px, 38svh);
|
||||
}
|
||||
.hero.welcome {
|
||||
height: min(376px, 44.5svh);
|
||||
min-height: 250px;
|
||||
height: min(352px, 42svh);
|
||||
min-height: 236px;
|
||||
}
|
||||
.hero .scenery {
|
||||
position: absolute;
|
||||
@@ -529,7 +529,7 @@ input {
|
||||
}
|
||||
.push {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
min-height: clamp(10px, 2svh, 16px);
|
||||
}
|
||||
h1 {
|
||||
margin: 0;
|
||||
@@ -628,6 +628,39 @@ h1 {
|
||||
font: 700 17px var(--text-face);
|
||||
box-shadow: 0 14px 28px -14px rgba(17, 24, 39, 0.55);
|
||||
}
|
||||
.discover {
|
||||
position: relative;
|
||||
padding-inline: 16px;
|
||||
}
|
||||
.trial-badge,
|
||||
.trial-price {
|
||||
border: 1px solid #bee3d7;
|
||||
background: #e7f6ef;
|
||||
color: #195247;
|
||||
}
|
||||
.trial-badge {
|
||||
position: absolute;
|
||||
inset-block-start: 0;
|
||||
inset-inline: 0;
|
||||
inline-size: max-content;
|
||||
max-inline-size: calc(100% - 20px);
|
||||
margin-inline: auto;
|
||||
padding: 3px 8px;
|
||||
border-radius: 999px;
|
||||
box-shadow: 0 2px 6px #11182720;
|
||||
font: 700 11px/1.4 var(--text-face);
|
||||
transform: translateY(calc(-100% + 6px));
|
||||
}
|
||||
.trial-price {
|
||||
margin: 8px 6px 0;
|
||||
padding: 10px 6px;
|
||||
border-radius: 12px;
|
||||
text-align: center;
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
line-height: 1.4;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.cta2 {
|
||||
min-height: 52px;
|
||||
background: #fff;
|
||||
@@ -715,33 +748,6 @@ h1 {
|
||||
color: var(--ink);
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12);
|
||||
}
|
||||
.trip {
|
||||
min-width: 0;
|
||||
margin-top: 10px;
|
||||
}
|
||||
.trip h1 {
|
||||
font-size: 28px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.trip p {
|
||||
margin: 6px 0 0;
|
||||
color: var(--text);
|
||||
font-size: 14px;
|
||||
line-height: 1.4;
|
||||
}
|
||||
.badge {
|
||||
font-family: var(--text-face);
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.04em;
|
||||
padding: 4px 10px;
|
||||
border-radius: 999px;
|
||||
background: var(--dark);
|
||||
color: #fff;
|
||||
}
|
||||
.pricebox {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
@@ -823,64 +829,52 @@ h1 {
|
||||
display: none;
|
||||
}
|
||||
.specs {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 8px;
|
||||
}
|
||||
.spec {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
min-width: 0;
|
||||
padding: 10px 12px;
|
||||
border-radius: 14px;
|
||||
margin: 0;
|
||||
padding: 0 12px;
|
||||
list-style: none;
|
||||
border-radius: 16px;
|
||||
background: #fff;
|
||||
box-shadow: 0 0 0 1px var(--line);
|
||||
}
|
||||
.spec {
|
||||
display: grid;
|
||||
grid-template-columns: 28px minmax(0, 1.6fr) minmax(0, 1fr);
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
min-height: 44px;
|
||||
padding-block: 8px;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.spec + .spec {
|
||||
border-block-start: 1px solid var(--line-soft);
|
||||
}
|
||||
.spec i {
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
flex: none;
|
||||
border-radius: 10px;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
border-radius: 8px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
background: var(--sand);
|
||||
color: var(--dark);
|
||||
}
|
||||
.spec b {
|
||||
display: block;
|
||||
font-size: 14px;
|
||||
font-weight: 800;
|
||||
line-height: 1.2;
|
||||
white-space: nowrap;
|
||||
font-weight: 700;
|
||||
line-height: 1.35;
|
||||
}
|
||||
.spec small {
|
||||
display: block;
|
||||
font-size: 11.5px;
|
||||
color: var(--muted);
|
||||
font-weight: 600;
|
||||
line-height: 1.25;
|
||||
white-space: nowrap;
|
||||
.spec bdi {
|
||||
justify-self: end;
|
||||
text-align: end;
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
line-height: 1.35;
|
||||
}
|
||||
.spec.off {
|
||||
color: #626672;
|
||||
}
|
||||
.spec.off i {
|
||||
color: var(--faint);
|
||||
}
|
||||
.spec.off b {
|
||||
color: var(--muted);
|
||||
}
|
||||
.spec.wide {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
.spec.wide em {
|
||||
margin-inline-start: auto;
|
||||
font-style: normal;
|
||||
font-size: 11.5px;
|
||||
font-weight: 700;
|
||||
color: var(--text);
|
||||
background: var(--sand);
|
||||
padding: 4px 9px;
|
||||
border-radius: 999px;
|
||||
white-space: nowrap;
|
||||
background: #f0f1f3;
|
||||
color: inherit;
|
||||
}
|
||||
.legal {
|
||||
margin: 2px 0 0;
|
||||
|
||||
+15
-14
@@ -55,13 +55,13 @@
|
||||
"dependencies": {
|
||||
"@assistant-ui/react": "0.15.38",
|
||||
"@capacitor/action-sheet": "^8.1.1",
|
||||
"@capacitor/android": "^8.6.2",
|
||||
"@capacitor/android": "^8.6.3",
|
||||
"@capacitor/app": "^8.1.1",
|
||||
"@capacitor/core": "^8.6.2",
|
||||
"@capacitor/core": "^8.6.3",
|
||||
"@capacitor/dialog": "^8.0.1",
|
||||
"@capacitor/filesystem": "^8.1.3",
|
||||
"@capacitor/filesystem": "^8.1.6",
|
||||
"@capacitor/haptics": "^8.0.2",
|
||||
"@capacitor/ios": "^8.6.2",
|
||||
"@capacitor/ios": "^8.6.3",
|
||||
"@capacitor/keyboard": "^8.0.5",
|
||||
"@capacitor/share": "^8.0.1",
|
||||
"@capacitor/splash-screen": "^8.0.2",
|
||||
@@ -101,6 +101,7 @@
|
||||
"@fontsource/satisfy": "^5.3.0",
|
||||
"@fontsource/shrikhand": "^5.3.0",
|
||||
"@fontsource/yellowtail": "^5.3.0",
|
||||
"@lucide/icons": "1.82.0",
|
||||
"@maplibre/maplibre-gl-leaflet": "0.1.4",
|
||||
"@noble/hashes": "^2.4.0",
|
||||
"@simplewebauthn/browser": "^14.0.0",
|
||||
@@ -112,9 +113,9 @@
|
||||
"heic-to": "^1.6.7",
|
||||
"iso-3166-2": "^1.0.0",
|
||||
"leaflet": "^1.9.4",
|
||||
"lucide-react": "^0.577.0",
|
||||
"lucide-react": "^1.82.0",
|
||||
"mapbox-gl": "3.32.0",
|
||||
"maplibre-gl": "6.19.0",
|
||||
"maplibre-gl": "6.20.0",
|
||||
"modern-screenshot": "4.7.0",
|
||||
"plyr": "^3.8.5",
|
||||
"react": "^19.3.1",
|
||||
@@ -123,7 +124,7 @@
|
||||
"react-leaflet": "^5.0.0",
|
||||
"react-leaflet-cluster": "^4.1.3",
|
||||
"react-markdown": "^10.1.0",
|
||||
"react-router": "^7.18.4",
|
||||
"react-router": "^8.5.3",
|
||||
"rehype-sanitize": "^6.0.0",
|
||||
"remark-breaks": "^4.0.0",
|
||||
"remark-gfm": "^4.0.1",
|
||||
@@ -133,12 +134,12 @@
|
||||
"zustand": "^5.0.15"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@capacitor/cli": "^8.6.2",
|
||||
"@capacitor/cli": "^8.6.3",
|
||||
"@eslint/js": "^10.0.1",
|
||||
"@jscpd/core": "^4.2.5",
|
||||
"@jscpd/tokenizer": "^4.2.6",
|
||||
"@playwright/test": "^1.65.1",
|
||||
"@testing-library/dom": "^10.4.1",
|
||||
"@testing-library/dom": "^10.4.2",
|
||||
"@testing-library/jest-dom": "^8.0.0",
|
||||
"@testing-library/react": "^16.3.3",
|
||||
"@testing-library/user-event": "^14.6.13",
|
||||
@@ -146,22 +147,22 @@
|
||||
"@types/geojson": "^7946.0.16",
|
||||
"@types/leaflet": "^1.9.23",
|
||||
"@types/node": "^26.6.11",
|
||||
"@types/react": "^19.3.2",
|
||||
"@types/react": "^19.3.3",
|
||||
"@types/react-dom": "^19.3.0",
|
||||
"@types/topojson-client": "^3.1.5",
|
||||
"@types/topojson-specification": "^1.0.5",
|
||||
"@vitejs/plugin-react": "^6.2.1",
|
||||
"@vitest/coverage-v8": "^5.1.2",
|
||||
"autoprefixer": "^10.7.0",
|
||||
"autoprefixer": "^10.7.1",
|
||||
"eslint": "^10.11.0",
|
||||
"eslint-config-flat-gitignore": "^2.4.0",
|
||||
"eslint-config-prettier": "^10.1.8",
|
||||
"eslint-config-prettier": "^10.1.9",
|
||||
"eslint-plugin-react-hooks": "^7.1.1",
|
||||
"eslint-plugin-react-refresh": "^0.5.8",
|
||||
"fake-indexeddb": "^6.2.7",
|
||||
"jsdom": "^29.1.1",
|
||||
"msw": "^3.0.8",
|
||||
"postcss": "^8.5.33",
|
||||
"postcss": "^8.5.34",
|
||||
"prettier": "^3.10.1",
|
||||
"prettier-plugin-organize-imports": "^4.3.0",
|
||||
"prettier-plugin-tailwindcss": "^0.8.1",
|
||||
@@ -170,7 +171,7 @@
|
||||
"tailwindcss": "^3.4.19",
|
||||
"typescript": "^6.0.3",
|
||||
"typescript-eslint": "^8.74.0",
|
||||
"vite": "8.3.8",
|
||||
"vite": "8.4.0",
|
||||
"vite-plugin-pwa": "^2.0.0",
|
||||
"vitest": "^5.1.2"
|
||||
}
|
||||
|
||||
@@ -1,21 +1,21 @@
|
||||
{
|
||||
"src": {
|
||||
"@typescript-eslint/no-non-null-assertion": 345,
|
||||
"@typescript-eslint/no-misused-promises": 810,
|
||||
"no-console": 85,
|
||||
"@typescript-eslint/no-non-null-assertion": 338,
|
||||
"@typescript-eslint/no-misused-promises": 750,
|
||||
"no-console": 81,
|
||||
"complexity": 214,
|
||||
"@typescript-eslint/no-explicit-any": 113,
|
||||
"trek/no-swallowed-catch": 124,
|
||||
"max-params": 31,
|
||||
"trek/store-without-selector": 65,
|
||||
"react-hooks/refs": 385,
|
||||
"react-hooks/refs": 380,
|
||||
"react-hooks/set-state-in-effect": 188,
|
||||
"@typescript-eslint/no-floating-promises": 162,
|
||||
"@typescript-eslint/no-floating-promises": 156,
|
||||
"react-hooks/exhaustive-deps": 112,
|
||||
"@typescript-eslint/no-unused-vars": 95,
|
||||
"react-hooks/immutability": 26,
|
||||
"max-lines-per-function": 126,
|
||||
"react-hooks/static-components": 38,
|
||||
"react-hooks/static-components": 35,
|
||||
"react-hooks/preserve-manual-memoization": 12,
|
||||
"no-useless-assignment": 7,
|
||||
"no-empty": 18,
|
||||
@@ -35,7 +35,7 @@
|
||||
},
|
||||
"tests": {
|
||||
"@typescript-eslint/no-explicit-any": 484,
|
||||
"@typescript-eslint/no-non-null-assertion": 1848,
|
||||
"@typescript-eslint/no-non-null-assertion": 1845,
|
||||
"@typescript-eslint/no-misused-promises": 22,
|
||||
"@typescript-eslint/no-unused-vars": 48,
|
||||
"@typescript-eslint/no-floating-promises": 33,
|
||||
|
||||
@@ -227,7 +227,11 @@
|
||||
"src/pages/sharedTrip/SharedBookingsView.tsx",
|
||||
"src/pages/sharedTrip/SharedDayCard.tsx"
|
||||
],
|
||||
"mobile": ["src/mobile/screens/trip/tabs/MBookingsTab.tsx", "src/mobile/screens/trip/tabs/MTransportsTab.tsx"]
|
||||
"mobile": [
|
||||
"src/mobile/screens/trip/tabs/MBookingsTab.tsx",
|
||||
"src/mobile/screens/trip/tabs/MTransportsTab.tsx",
|
||||
"src/mobile/screens/trip/MItineraryBookingCard.tsx"
|
||||
]
|
||||
},
|
||||
{
|
||||
"feature": "Bottom nav context-aware create action",
|
||||
@@ -267,6 +271,12 @@
|
||||
"desktop": ["src/components/Collab/useCollabChat.ts"],
|
||||
"mobile": ["src/mobile/screens/trip/tabs/MCollabChat.tsx"]
|
||||
},
|
||||
{
|
||||
"feature": "Collab links",
|
||||
"hooks": ["src/components/Collab/useCollabLinks.ts"],
|
||||
"desktop": ["src/components/Collab/CollabLinks.tsx"],
|
||||
"mobile": ["src/mobile/screens/trip/tabs/MCollabLinks.tsx"]
|
||||
},
|
||||
{
|
||||
"feature": "Collab notes",
|
||||
"hooks": ["src/components/Collab/useCollabNotesData.ts"],
|
||||
@@ -398,7 +408,7 @@
|
||||
"src/mobile/screens/collections/MCollEditSheet.tsx",
|
||||
"src/mobile/screens/collections/MCollPlaceRow.tsx",
|
||||
"src/mobile/screens/collections/MCollPlaceSheet.tsx",
|
||||
"src/mobile/screens/collections/MCollections.tsx"
|
||||
"src/mobile/screens/collections/MCollSavedFilters.tsx"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -438,7 +448,7 @@
|
||||
"feature": "Costs/budget splitting or totals only: useCostsMode",
|
||||
"hooks": ["src/components/Budget/useCostsMode.ts"],
|
||||
"desktop": ["src/components/Budget/CostsModeCard.tsx"],
|
||||
"mobile": ["src/mobile/screens/trip/tabs/MCostsTab.tsx"]
|
||||
"mobile": ["src/mobile/screens/trip/sheets/MTripSettingsSheet.tsx"]
|
||||
},
|
||||
{
|
||||
"feature": "Costs/budget settle-up payment: useSettlementForm",
|
||||
@@ -600,10 +610,8 @@
|
||||
"src/pages/journeyPublic/useJourneyPublic.ts"
|
||||
],
|
||||
"mobile": [
|
||||
"src/mobile/screens/journey/MJourneyCreateSheet.tsx",
|
||||
"src/mobile/screens/journey/MJourneyDetail.tsx",
|
||||
"src/mobile/screens/journey/MJourneyEntrySheet.tsx",
|
||||
"src/mobile/screens/journey/MJourneySettingsSheet.tsx",
|
||||
"src/mobile/screens/journey/mobileJourneyMeta.ts"
|
||||
]
|
||||
},
|
||||
@@ -776,7 +784,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 +793,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"]
|
||||
},
|
||||
{
|
||||
@@ -864,12 +872,6 @@
|
||||
"desktop": ["src/components/Roadtrip/RoadtripStopPopup.tsx"],
|
||||
"mobile": ["src/mobile/screens/trip/roadtrip/MRtDraftSheet.tsx"]
|
||||
},
|
||||
{
|
||||
"feature": "Road-trip Google Maps route import",
|
||||
"hooks": ["src/components/Roadtrip/useGoogleRouteImport.ts"],
|
||||
"desktop": ["src/components/Roadtrip/GoogleRouteImport.tsx"],
|
||||
"mobile": ["src/mobile/screens/trip/roadtrip/MRtRouteImportSheet.tsx"]
|
||||
},
|
||||
{
|
||||
"feature": "Road-trip stay length draft",
|
||||
"hooks": ["src/components/Roadtrip/useStayDraft.ts"],
|
||||
@@ -1059,11 +1061,13 @@
|
||||
"src/components/Planner/ReservationsPanel.tsx",
|
||||
"src/components/Planner/bookings/BookingDetailHost.tsx"
|
||||
],
|
||||
"mobile": [
|
||||
"src/mobile/screens/trip/sheets/MTransportSheet.tsx",
|
||||
"src/mobile/screens/trip/tabs/MBookingsTab.tsx",
|
||||
"src/mobile/screens/trip/tabs/MTransportsTab.tsx"
|
||||
]
|
||||
"mobile": ["src/mobile/screens/trip/sheets/MTransportSheet.tsx"]
|
||||
},
|
||||
{
|
||||
"feature": "Transit itinerary facts and note formatting",
|
||||
"hooks": ["src/components/Planner/transitJourneyModel.ts"],
|
||||
"desktop": ["src/components/Planner/TransitJourneyModal.tsx"],
|
||||
"mobile": ["src/mobile/screens/trip/sheets/MTransitJourneySheet.tsx"]
|
||||
},
|
||||
{
|
||||
"feature": "Transport booking detail view: transportDetailModel",
|
||||
@@ -1234,6 +1238,7 @@
|
||||
"src/mobile/screens/collections/collectionsMobileModel.ts": "Visual constants only the phone collections screens use (category and status specs, swatches, cover gradient).",
|
||||
"src/mobile/screens/dashboard/MUserMenu.tsx": "Phone avatar menu with a three state theme cycle the desktop navbar does not have.",
|
||||
"src/mobile/screens/journey/MDawarichDaySheet.tsx": "Markup only; the phone frame the Dawarich day sheets (route and stays) render their shared review in.",
|
||||
"src/mobile/screens/journey/MJourneyCreateSheet.tsx": "The phone form receives the journey and trip selection state from MJourney, which shares useJourney with the desktop list.",
|
||||
"src/mobile/screens/journey/MJourneyFeed.tsx": "Markup only; the journey's entries as a feed beside the map on a wide window, with the entries, the active one and the tap handed in through props from useJourneyDetail and useJourneyCarouselSync.",
|
||||
"src/mobile/screens/settings/MAppLockCard.tsx": "Phone only: the app lock exists only in the native app, so there is no desktop setting to share with.",
|
||||
"src/mobile/screens/settings/MClientCertCard.tsx": "Phone only: the client certificate is kept by the native app, so there is no desktop setting to share with.",
|
||||
@@ -1252,7 +1257,26 @@
|
||||
"src/mobile/screens/trip/MTripShellParts.tsx": "Markup only; small pieces of MTripShell's top controls (segment pill, compact toggle, document sync button), with the state and handlers MTripShell hands in.",
|
||||
"src/mobile/screens/trip/dockTabs.ts": "Phone only helper that picks which trip tabs get a seat in the mobile dock.",
|
||||
"src/mobile/screens/trip/useTripTabSwitch.ts": "Phone shell only; switches the section the dock and a notification link open, and the collab part a message link means. The desktop switches through useTripPlanner alone.",
|
||||
"src/mobile/screens/trip/lib/dayNotes.ts": "Phone only helper that splits a leading time off a day note for the plan timeline.",
|
||||
"src/mobile/screens/collections/MCollColorSwatches.tsx": "Shared color chooser for the phone list and tag forms.",
|
||||
"src/mobile/screens/collections/MCollPlaceFields.tsx": "Shared layout of the nullable category, address and description fields in phone add and edit forms.",
|
||||
"src/mobile/screens/collections/MCollToolbar.tsx": "Search, view and filter controls shared by the two phone collection lists.",
|
||||
"src/mobile/screens/journey/MJourneyInviteFrame.tsx": "Phone invitation layout over the shared ContributorInviteDialog controller.",
|
||||
"src/mobile/screens/journey/MJourneyEntryRead.tsx": "Phone journal reader over the shared markdown, photo and entry title models.",
|
||||
"src/mobile/screens/journey/MJourneyVerdict.tsx": "Phone verdict layout shared by the reader and the editor; writes use the shared journey entry form.",
|
||||
"src/mobile/screens/trip/map/MMapExplore.tsx": "Phone entry points and panels for the shared map exploration state.",
|
||||
"src/mobile/screens/trip/map/MMapPlaceFilters.tsx": "Phone sheet presenting map and place visibility controls.",
|
||||
"src/mobile/screens/trip/roadtrip/MRtChoice.tsx": "Phone grid option for the Roadtrip corridor sheets.",
|
||||
"src/mobile/screens/trip/roadtrip/stageBookings.ts": "Places bookings and their approaches within the phone stage timeline using the shared Roadtrip router and stop associations.",
|
||||
"src/mobile/screens/trip/sheets/MBookingImportSheet.tsx": "Phone presentation passed to the shared booking import controller.",
|
||||
"src/mobile/screens/trip/sheets/MDayPickerSheet.tsx": "Searchable phone day picker, separate from the desktop day sidebar.",
|
||||
"src/mobile/screens/trip/sheets/MGpxPreviewFrame.tsx": "Phone GPX preview layout over the shared TourGpxPreviewDialog controller.",
|
||||
"src/mobile/screens/trip/sheets/MIcsSubscribeSheet.tsx": "Phone form for the shared calendar subscription hook.",
|
||||
"src/mobile/screens/trip/sheets/MSubscribeLinks.tsx": "Phone provider and link actions for the shared subscription links hook.",
|
||||
"src/mobile/screens/trip/sheets/MTripOfflinePage.tsx": "Trip-specific offline controls in the phone settings.",
|
||||
"src/mobile/screens/trip/useMTripDayResume.ts": "Restores the last day in the phone's single-day planner.",
|
||||
"src/mobile/screens/trip/tabs/MChecklistCheck.tsx": "Phone checkbox controls shared by trip tasks and packing.",
|
||||
"src/mobile/screens/trip/sheets/MCurrencyPicker.tsx": "Searchable mobile currency picker shared by the dashboard and costs ledger.",
|
||||
"src/mobile/screens/trip/tabs/MReservationList.tsx": "Shared phone shell for the bookings and transport tabs.",
|
||||
"src/mobile/screens/trip/map/MMapArea.tsx": "Phone map stage framing; already shares usePoiExplore and useMergedMapPois with the desktop trip planner.",
|
||||
"src/mobile/screens/trip/places/MPlacesBulkCategorySheet.tsx": "Markup only; categories and the pick handler come through props from MPlacesBrowser.",
|
||||
"src/mobile/screens/trip/places/MPlacesToursModeSwitch.tsx": "Markup only places or tours toggle; value and onChange come through props from MPlacesBrowser.",
|
||||
@@ -1288,7 +1312,7 @@
|
||||
"src/mobile/screens/trip/sheets/PlTags.tsx": "Markup only; the tag picker's state comes through props from MPlaceEditSheet, which runs usePlaceTags, and the chips of the place sheet draw the tags the place carries.",
|
||||
"src/mobile/screens/trip/sheets/PlTimeFields.tsx": "Phone time fields that already share timeCollisions with the desktop PlaceFormModal.",
|
||||
"src/mobile/screens/trip/sheets/tourSheetOpen.ts": "Phone only context for MTourDetailShell: whether the tour sheet is open and the name it carries.",
|
||||
"src/mobile/screens/trip/tabs/MCollabTab.tsx": "Phone collab sub tab router that reuses the desktop CollabLinks component.",
|
||||
"src/mobile/screens/trip/tabs/MCollabTab.tsx": "Phone collab sub-tab router for the chat and boards.",
|
||||
"src/mobile/screens/trip/tabs/MFilesBoard.tsx": "Markup only; the trip's files as tiles and the picked file's preview on a wide window, with the files and their actions handed in through props from MFilesTab.",
|
||||
"src/mobile/screens/trip/tabs/MListsTab.tsx": "Phone router between the packing and to-do bodies, with no logic of its own.",
|
||||
"src/mobile/screens/trip/tabs/MPackingCategorySharingSheet.tsx": "Markup only; the sheet that shares a whole list, with its state from usePackingCategorySharing handed in through props by MPackingListTab.",
|
||||
|
||||
@@ -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",
|
||||
@@ -1331,7 +1330,6 @@
|
||||
"src/mobile/screens/trip/MTripShell.tsx",
|
||||
"src/mobile/screens/trip/dockTabs.test.ts",
|
||||
"src/mobile/screens/trip/dockTabs.ts",
|
||||
"src/mobile/screens/trip/lib/dayNotes.ts",
|
||||
"src/mobile/screens/trip/map/MMapArea.tsx",
|
||||
"src/mobile/screens/trip/places/MPlacesBrowser.tsx",
|
||||
"src/mobile/screens/trip/places/MPlacesBulkCategorySheet.tsx",
|
||||
@@ -1426,7 +1424,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,25 +1,24 @@
|
||||
{
|
||||
"admin.ts": 112,
|
||||
"atlas.ts": 7,
|
||||
"atlas.ts": 6,
|
||||
"backup.ts": 10,
|
||||
"budget.ts": 35,
|
||||
"categories.ts": 1,
|
||||
"collab.ts": 9,
|
||||
"collection.ts": 29,
|
||||
"collection.ts": 27,
|
||||
"common.ts": 6,
|
||||
"dashboard.ts": 64,
|
||||
"dashboard.ts": 60,
|
||||
"dawarich.ts": 15,
|
||||
"dayplan.ts": 17,
|
||||
"docsync.ts": 25,
|
||||
"files.ts": 4,
|
||||
"help.ts": 3,
|
||||
"inspector.ts": 4,
|
||||
"journey.ts": 65,
|
||||
"journey.ts": 64,
|
||||
"login.ts": 1,
|
||||
"map.ts": 5,
|
||||
"memories.ts": 8,
|
||||
"mobileNav.ts": 2,
|
||||
"mobileVacay.ts": 4,
|
||||
"nav.ts": 1,
|
||||
"notif.ts": 7,
|
||||
"notifications.ts": 17,
|
||||
@@ -27,10 +26,10 @@
|
||||
"pdf.ts": 1,
|
||||
"perm.ts": 4,
|
||||
"places.ts": 9,
|
||||
"planner.ts": 52,
|
||||
"reservations.ts": 21,
|
||||
"planner.ts": 49,
|
||||
"reservations.ts": 20,
|
||||
"roadtrip.ts": 36,
|
||||
"settings.ts": 37,
|
||||
"settings.ts": 36,
|
||||
"share.ts": 7,
|
||||
"shared.ts": 2,
|
||||
"storage.ts": 16,
|
||||
|
||||
@@ -28,8 +28,6 @@
|
||||
"src/components/Journey/MobileEntryView.tsx": 1,
|
||||
"src/components/Map/MapView.tsx": 1,
|
||||
"src/components/Map/MapViewGL.tsx": 1,
|
||||
"src/components/Planner/IcsSubscribeModal.tsx": 1,
|
||||
"src/components/Planner/TransitJourneyModal.tsx": 1,
|
||||
"src/components/Planner/TransitSearchPanel.tsx": 1,
|
||||
"src/components/Planner/TripWarningsBanner.tsx": 1,
|
||||
"src/components/Planner/transitDisplay.tsx": 1,
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { basename } from 'node:path';
|
||||
import { test } from 'node:test';
|
||||
import config from '../vite.native.config.js';
|
||||
|
||||
const variable = 'TREK_CLOUD_SANDBOX_ORIGIN';
|
||||
|
||||
function setOrigin(context, origin) {
|
||||
const previous = process.env[variable];
|
||||
process.env[variable] = origin;
|
||||
context.after(() => {
|
||||
if (previous === undefined) delete process.env[variable];
|
||||
else process.env[variable] = previous;
|
||||
});
|
||||
}
|
||||
|
||||
test('isolates the sandbox output and keeps the ordinary app on the production configuration', (context) => {
|
||||
const origin = 'https://store-sandbox.example.com';
|
||||
setOrigin(context, origin);
|
||||
const sandbox = config({ command: 'build', mode: 'store-sandbox' });
|
||||
assert.deepEqual(sandbox.define, { __TREK_STORE_SANDBOX_ORIGIN__: JSON.stringify(origin) });
|
||||
assert.equal(basename(sandbox.build.outDir), 'native-sandbox-dist');
|
||||
|
||||
for (const input of [
|
||||
{ command: 'build', mode: 'production' },
|
||||
{ command: 'serve', mode: 'store-sandbox' },
|
||||
]) {
|
||||
const regular = config(input);
|
||||
assert.deepEqual(regular.define, {});
|
||||
assert.equal(basename(regular.build.outDir), 'native-dist');
|
||||
}
|
||||
});
|
||||
|
||||
for (const origin of [
|
||||
'',
|
||||
'http://qa.example.com',
|
||||
'https://qa.example.com/path',
|
||||
'https://liketrek.com',
|
||||
'https://www.liketrek.com',
|
||||
]) {
|
||||
test(`refuses a sandbox configuration with origin ${JSON.stringify(origin)}`, (context) => {
|
||||
setOrigin(context, origin);
|
||||
assert.throws(() => config({ command: 'build', mode: 'store-sandbox' }), { message: new RegExp(variable) });
|
||||
});
|
||||
}
|
||||
@@ -24,7 +24,6 @@
|
||||
"src/components/Budget/ReceiptPreviewModal.tsx",
|
||||
"src/components/Budget/receiptUploads.ts",
|
||||
"src/components/Collab/CollabChatLinkPreview.tsx",
|
||||
"src/components/Collab/CollabLinks.tsx",
|
||||
"src/components/Collab/CollabNotes.tsx",
|
||||
"src/components/Collab/CollabNotesAuthedImg.tsx",
|
||||
"src/components/Collab/CollabNotesFilePreviewPortal.tsx",
|
||||
|
||||
@@ -13,7 +13,6 @@
|
||||
"components/Journey/JourneyDetailPageGalleryView.tsx": 1,
|
||||
"components/Journey/JourneyDetailPagePhotoGrid.tsx": 1,
|
||||
"components/Journey/JourneyDetailPageProviderPicker.tsx": 1,
|
||||
"components/Journey/JourneyEntryCover.tsx": 1,
|
||||
"components/Journey/JourneyMap.tsx": 1,
|
||||
"components/Journey/JourneyMapGL.tsx": 2,
|
||||
"components/Journey/MobileEntryView.tsx": 1,
|
||||
@@ -76,7 +75,7 @@
|
||||
"hooks/useAnchoredPosition.ts": 3,
|
||||
"hooks/useElementRect.ts": 3,
|
||||
"mobile/components/MSegmented.tsx": 1,
|
||||
"mobile/screens/journey/MJourneyDetail.tsx": 3,
|
||||
"mobile/screens/journey/MJourneyDetail.tsx": 2,
|
||||
"mobile/screens/journey/MJourneyEntrySheet.tsx": 1,
|
||||
"mobile/screens/trip/map/MMapArea.tsx": 3,
|
||||
"mobile/screens/trip/tabs/MFileLightbox.tsx": 2,
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
"components/Studio/LineHandles.tsx": 1,
|
||||
"components/Studio/StudioSelectionChrome.tsx": 2,
|
||||
"components/Studio/inspector/FocalPad.tsx": 1,
|
||||
"components/Tours/TourGpxPreviewDialog.tsx": 1,
|
||||
"mobile/components/trek3d/MascotClip.tsx": 1,
|
||||
"mobile/screens/trip/MTripShell.tsx": 1,
|
||||
"mobile/screens/vacay/MVacay.tsx": 1,
|
||||
|
||||
@@ -4,8 +4,8 @@
|
||||
"src/components/Admin/AdminPluginsPanel.test.tsx": 2704,
|
||||
"src/components/Admin/AdminPluginsPanel.tsx": 1265,
|
||||
"src/components/Budget/CostsPanel.test.tsx": 2725,
|
||||
"src/components/Budget/CostsPanel.tsx": 1607,
|
||||
"src/components/Map/MapView.tsx": 1191,
|
||||
"src/components/Budget/CostsPanel.tsx": 1588,
|
||||
"src/components/Map/MapView.tsx": 1170,
|
||||
"src/components/Map/MapViewGL.test.tsx": 2919,
|
||||
"src/components/Map/MapViewGL.tsx": 2083,
|
||||
"src/components/Planner/DayDetailPanel.test.tsx": 2331,
|
||||
|
||||
@@ -48,7 +48,6 @@
|
||||
"src/components/Planner/DayPlanSidebar.tsx": 52,
|
||||
"src/components/Planner/DayPlanSidebarNoteModal.test.tsx": 1,
|
||||
"src/components/Planner/PlaceFormModal.test.tsx": 3,
|
||||
"src/components/Planner/PlaceFormModal.tsx": 1,
|
||||
"src/components/Planner/PlaceInspector.tsx": 16,
|
||||
"src/components/Planner/PlacesBulkCategoryModal.test.tsx": 1,
|
||||
"src/components/Planner/PlacesSidebar.tsx": 1,
|
||||
@@ -97,7 +96,6 @@
|
||||
"src/hooks/useDawarichSuggestions.test.ts": 1,
|
||||
"src/mobile/screens/admin/MAdminAddonManager.tsx": 2,
|
||||
"src/mobile/screens/admin/MAdminPluginsPanel.tsx": 6,
|
||||
"src/mobile/screens/journey/MJourneySettingsSheet.tsx": 1,
|
||||
"src/mobile/screens/settings/MSettingsAccount.tsx": 1,
|
||||
"src/mobile/screens/trip/MTripShell.tsx": 1,
|
||||
"src/mobile/screens/trip/map/MMapArea.tsx": 1,
|
||||
|
||||
@@ -79,12 +79,10 @@
|
||||
"components/Planner/BookingCostsSection.tsx": 1,
|
||||
"components/Planner/BookingImportModal.tsx": 4,
|
||||
"components/Planner/DayDetailPanel.tsx": 1,
|
||||
"components/Planner/IcsSubscribeModal.tsx": 10,
|
||||
"components/Planner/PlaceInspector.tsx": 1,
|
||||
"components/Planner/PlacesSidebarMobileDayPicker.tsx": 3,
|
||||
"components/Planner/SubscribeLinks.tsx": 5,
|
||||
"components/Planner/SuggestionDropdown.tsx": 1,
|
||||
"components/Planner/TransitJourneyModal.tsx": 4,
|
||||
"components/Planner/TransitSearchPanel.tsx": 2,
|
||||
"components/Planner/TravelerPicker.tsx": 3,
|
||||
"components/Planner/bookings/BookingsTimeline.tsx": 1,
|
||||
@@ -134,7 +132,6 @@
|
||||
"components/shared/TrackColorPicker.tsx": 2,
|
||||
"components/shared/TripLoadingSplash.tsx": 10,
|
||||
"mobile/components/MBadge.tsx": 2,
|
||||
"mobile/components/MBottomNav.tsx": 2,
|
||||
"mobile/components/MChip.tsx": 2,
|
||||
"mobile/components/MDayImpactList.tsx": 4,
|
||||
"mobile/components/MListRow.tsx": 1,
|
||||
@@ -142,7 +139,6 @@
|
||||
"mobile/components/MSheet.tsx": 1,
|
||||
"mobile/components/MStorageTestResult.tsx": 3,
|
||||
"mobile/components/MToastHost.tsx": 2,
|
||||
"mobile/components/MUserPickerList.tsx": 1,
|
||||
"mobile/screens/admin/MAdmin.tsx": 8,
|
||||
"mobile/screens/admin/MAdminAddonManager.tsx": 3,
|
||||
"mobile/screens/admin/MAdminAuditLogPanel.tsx": 15,
|
||||
@@ -162,31 +158,18 @@
|
||||
"mobile/screens/admin/MAdminUi.tsx": 7,
|
||||
"mobile/screens/admin/MAdminUsersSection.tsx": 13,
|
||||
"mobile/screens/admin/MApiProviderBlocks.tsx": 10,
|
||||
"mobile/screens/atlas/MAtlasCountryPopup.tsx": 11,
|
||||
"mobile/screens/atlas/MAtlasStatsCard.tsx": 2,
|
||||
"mobile/screens/collections/MCollAddSheet.tsx": 6,
|
||||
"mobile/screens/collections/MCollCategoryPicker.tsx": 2,
|
||||
"mobile/screens/collections/MCollEditSheet.tsx": 2,
|
||||
"mobile/screens/collections/MCollLabelsSheet.tsx": 6,
|
||||
"mobile/screens/collections/MCollLinksEditor.tsx": 2,
|
||||
"mobile/screens/collections/MCollListPickerSheet.tsx": 3,
|
||||
"mobile/screens/collections/MCollPlaceRow.tsx": 3,
|
||||
"mobile/screens/collections/MCollShareSheet.tsx": 14,
|
||||
"mobile/screens/collections/MCollSheetKit.tsx": 5,
|
||||
"mobile/screens/collections/MCollTripPickerSheet.tsx": 4,
|
||||
"mobile/screens/collections/MCollections.tsx": 9,
|
||||
"mobile/screens/dashboard/MDashWidgets.tsx": 22,
|
||||
"mobile/screens/dashboard/MDashboard.tsx": 30,
|
||||
"mobile/screens/dashboard/MNewTripSheet.tsx": 12,
|
||||
"mobile/screens/collections/MCollShareSheet.tsx": 1,
|
||||
"mobile/screens/collections/MCollSheetKit.tsx": 3,
|
||||
"mobile/screens/collections/MCollections.tsx": 2,
|
||||
"mobile/screens/dashboard/MDashboard.tsx": 25,
|
||||
"mobile/screens/dashboard/MNewTripSheet.tsx": 11,
|
||||
"mobile/screens/dashboard/MUserMenu.tsx": 7,
|
||||
"mobile/screens/journey/MJourney.tsx": 10,
|
||||
"mobile/screens/journey/MJourneyCreateSheet.tsx": 7,
|
||||
"mobile/screens/journey/MJourneyDetail.tsx": 6,
|
||||
"mobile/screens/journey/MJourneyEntrySheet.tsx": 46,
|
||||
"mobile/screens/journey/MJourneySettingsSheet.tsx": 2,
|
||||
"mobile/screens/journey/MJourneyDetail.tsx": 3,
|
||||
"mobile/screens/journey/MJourneyEntrySheet.tsx": 11,
|
||||
"mobile/screens/journey/mobileJourneyMeta.ts": 4,
|
||||
"mobile/screens/notifications/MNotificationRow.tsx": 4,
|
||||
"mobile/screens/notifications/MNotifications.tsx": 3,
|
||||
"mobile/screens/settings/MAirTrailConnectionSection.tsx": 2,
|
||||
"mobile/screens/settings/MConfirmSheet.tsx": 2,
|
||||
"mobile/screens/settings/MDawarichConnectionSection.tsx": 5,
|
||||
@@ -207,75 +190,49 @@
|
||||
"mobile/screens/settings/MSettingsUi.tsx": 10,
|
||||
"mobile/screens/settings/MWebPushCard.tsx": 1,
|
||||
"mobile/screens/trip/MTripLoadingSplash.tsx": 2,
|
||||
"mobile/screens/trip/MTripShell.tsx": 7,
|
||||
"mobile/screens/trip/places/MPlacesBrowser.tsx": 10,
|
||||
"mobile/screens/trip/MTripShell.tsx": 5,
|
||||
"mobile/screens/trip/places/MPlacesBrowser.tsx": 1,
|
||||
"mobile/screens/trip/places/MPlacesBulkCategorySheet.tsx": 2,
|
||||
"mobile/screens/trip/places/MPlacesFilterControls.tsx": 1,
|
||||
"mobile/screens/trip/places/MPlacesSaveToCollectionSheet.tsx": 6,
|
||||
"mobile/screens/trip/places/MPlacesToursModeSwitch.tsx": 1,
|
||||
"mobile/screens/trip/plan/MPlanTimeline.tsx": 12,
|
||||
"mobile/screens/trip/plan/MPlanTimelineRows.tsx": 24,
|
||||
"mobile/screens/trip/roadtrip/MRoadtripRows.tsx": 31,
|
||||
"mobile/screens/trip/roadtrip/MRoadtripTab.tsx": 16,
|
||||
"mobile/screens/trip/roadtrip/MRtAlternativesBar.tsx": 8,
|
||||
"mobile/screens/trip/plan/MPlanTimeline.tsx": 10,
|
||||
"mobile/screens/trip/plan/MPlanTimelineRows.tsx": 12,
|
||||
"mobile/screens/trip/roadtrip/MRoadtripRows.tsx": 18,
|
||||
"mobile/screens/trip/roadtrip/MRoadtripTab.tsx": 11,
|
||||
"mobile/screens/trip/roadtrip/MRtCorridorBar.tsx": 2,
|
||||
"mobile/screens/trip/roadtrip/MRtCorridorSheet.tsx": 7,
|
||||
"mobile/screens/trip/roadtrip/MRtDraftSheet.tsx": 5,
|
||||
"mobile/screens/trip/roadtrip/MRtInfoSheet.tsx": 9,
|
||||
"mobile/screens/trip/roadtrip/MRtKindSheet.tsx": 3,
|
||||
"mobile/screens/trip/roadtrip/MRtStaySheet.tsx": 17,
|
||||
"mobile/screens/trip/roadtrip/MRtStopSheet.tsx": 12,
|
||||
"mobile/screens/trip/sheets/ImpFileStep.tsx": 12,
|
||||
"mobile/screens/trip/sheets/ImpListStep.tsx": 3,
|
||||
"mobile/screens/trip/roadtrip/MRtCorridorSheet.tsx": 4,
|
||||
"mobile/screens/trip/roadtrip/MRtKindSheet.tsx": 2,
|
||||
"mobile/screens/trip/roadtrip/MRtStopSheet.tsx": 3,
|
||||
"mobile/screens/trip/sheets/MAccommodationSheet.tsx": 10,
|
||||
"mobile/screens/trip/sheets/MBookingFields.tsx": 5,
|
||||
"mobile/screens/trip/sheets/MBrowseActionsSheet.tsx": 3,
|
||||
"mobile/screens/trip/sheets/MCostSheet.tsx": 33,
|
||||
"mobile/screens/trip/sheets/MDaySheet.tsx": 22,
|
||||
"mobile/screens/trip/sheets/MDaysSheet.tsx": 4,
|
||||
"mobile/screens/trip/sheets/MExportSheet.tsx": 2,
|
||||
"mobile/screens/trip/sheets/MImportSheet.tsx": 2,
|
||||
"mobile/screens/trip/sheets/MLinkedCosts.tsx": 8,
|
||||
"mobile/screens/trip/sheets/MMehrSheet.tsx": 3,
|
||||
"mobile/screens/trip/sheets/MNoteSheet.tsx": 1,
|
||||
"mobile/screens/trip/sheets/MPlaceEditSheet.tsx": 2,
|
||||
"mobile/screens/trip/sheets/MPlaceSheet.tsx": 23,
|
||||
"mobile/screens/trip/sheets/MReservationSheet.tsx": 2,
|
||||
"mobile/screens/trip/sheets/MTransportFormSheet.tsx": 9,
|
||||
"mobile/screens/trip/sheets/MTransportSheet.tsx": 9,
|
||||
"mobile/screens/trip/sheets/MBookingFields.tsx": 4,
|
||||
"mobile/screens/trip/sheets/MCostSheet.tsx": 23,
|
||||
"mobile/screens/trip/sheets/MDaySheet.tsx": 5,
|
||||
"mobile/screens/trip/sheets/MDaysSheet.tsx": 2,
|
||||
"mobile/screens/trip/sheets/MLinkedCosts.tsx": 7,
|
||||
"mobile/screens/trip/sheets/MPlaceSheet.tsx": 6,
|
||||
"mobile/screens/trip/sheets/MReservationSheet.tsx": 1,
|
||||
"mobile/screens/trip/sheets/MTransportSheet.tsx": 6,
|
||||
"mobile/screens/trip/sheets/MTripSheetUi.tsx": 5,
|
||||
"mobile/screens/trip/sheets/PlCategoryPicker.tsx": 1,
|
||||
"mobile/screens/trip/sheets/PlFileAttach.tsx": 3,
|
||||
"mobile/screens/trip/sheets/PlPlaceSearch.tsx": 6,
|
||||
"mobile/screens/trip/sheets/PlSheetChrome.tsx": 5,
|
||||
"mobile/screens/trip/sheets/PlPlaceSearch.tsx": 2,
|
||||
"mobile/screens/trip/sheets/PlSheetChrome.tsx": 1,
|
||||
"mobile/screens/trip/sheets/PlTimeFields.tsx": 3,
|
||||
"mobile/screens/trip/tabs/MBagsSheet.tsx": 13,
|
||||
"mobile/screens/trip/tabs/MBookingsTab.tsx": 2,
|
||||
"mobile/screens/trip/tabs/MCollabChat.tsx": 22,
|
||||
"mobile/screens/trip/tabs/MCollabNotes.tsx": 19,
|
||||
"mobile/screens/trip/tabs/MCollabPolls.tsx": 18,
|
||||
"mobile/screens/trip/tabs/MCollabChat.tsx": 6,
|
||||
"mobile/screens/trip/tabs/MCollabNotes.tsx": 4,
|
||||
"mobile/screens/trip/tabs/MCollabPolls.tsx": 12,
|
||||
"mobile/screens/trip/tabs/MCollabTab.tsx": 1,
|
||||
"mobile/screens/trip/tabs/MCostsTab.tsx": 70,
|
||||
"mobile/screens/trip/tabs/MDocSyncSheet.tsx": 43,
|
||||
"mobile/screens/trip/tabs/MCostsTab.tsx": 36,
|
||||
"mobile/screens/trip/tabs/MDocSyncSheet.tsx": 30,
|
||||
"mobile/screens/trip/tabs/MFileLightbox.tsx": 11,
|
||||
"mobile/screens/trip/tabs/MFileLinkSheet.tsx": 2,
|
||||
"mobile/screens/trip/tabs/MFileMenuSheet.tsx": 1,
|
||||
"mobile/screens/trip/tabs/MFileTrashSheet.tsx": 4,
|
||||
"mobile/screens/trip/tabs/MFilesTab.tsx": 12,
|
||||
"mobile/screens/trip/tabs/MFilesTab.tsx": 2,
|
||||
"mobile/screens/trip/tabs/MPackItemSheet.tsx": 1,
|
||||
"mobile/screens/trip/tabs/MPackingImportSheet.tsx": 3,
|
||||
"mobile/screens/trip/tabs/MPackingListTab.tsx": 2,
|
||||
"mobile/screens/trip/tabs/MReservationCardParts.tsx": 6,
|
||||
"mobile/screens/trip/tabs/MTaskSheet.tsx": 6,
|
||||
"mobile/screens/trip/tabs/MTodoListTab.tsx": 3,
|
||||
"mobile/screens/trip/tabs/MTransportsTab.tsx": 2,
|
||||
"mobile/screens/trip/tabs/MTaskSheet.tsx": 1,
|
||||
"mobile/screens/trip/tabs/MTodoListTab.tsx": 2,
|
||||
"mobile/screens/trip/tabs/filesModel.ts": 5,
|
||||
"mobile/screens/trip/tabs/tabChrome.tsx": 12,
|
||||
"mobile/screens/vacay/MVacay.tsx": 17,
|
||||
"mobile/screens/vacay/MVacayInviteSheet.tsx": 8,
|
||||
"mobile/screens/vacay/MVacayMonth.tsx": 3,
|
||||
"mobile/screens/vacay/MVacaySettingsSheet.tsx": 34,
|
||||
"mobile/screens/vacay/MVacayShareSheet.tsx": 10,
|
||||
"mobile/screens/trip/tabs/tabChrome.tsx": 3,
|
||||
"mobile/screens/vacay/MVacay.tsx": 1,
|
||||
"mobile/screens/vacay/vacayDayModel.ts": 1,
|
||||
"pages/DashboardPage.tsx": 1,
|
||||
"pages/FilesPage.tsx": 11,
|
||||
|
||||
@@ -59,7 +59,6 @@
|
||||
"mobile/screens/atlas/MAtlasCountryPopup.tsx": 2,
|
||||
"mobile/screens/atlas/hub/MHubTravellers.tsx": 1,
|
||||
"mobile/screens/collections/MCollEditSheet.tsx": 2,
|
||||
"mobile/screens/collections/MCollShareSheet.tsx": 1,
|
||||
"mobile/screens/collections/collectionsMobileModel.ts": 15,
|
||||
"mobile/screens/dashboard/MDashboard.tsx": 3,
|
||||
"mobile/screens/journey/MJourney.tsx": 2,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useState, type ReactNode } from 'react'
|
||||
import {
|
||||
Blocks, AlertTriangle, RefreshCw, Trash2, Download, Bug, ShieldCheck, UploadCloud,
|
||||
ArrowUpCircle, Github, ExternalLink, Check, Search, Link2, KeyRound, ShieldAlert,
|
||||
ArrowUpCircle, ExternalLink, Check, Search, Link2, KeyRound, ShieldAlert,
|
||||
SlidersHorizontal, CircleDot, Database,
|
||||
Globe, History, Puzzle, Bot, Loader2,
|
||||
} from 'lucide-react'
|
||||
@@ -789,7 +789,7 @@ function PluginDetailModal({ item, installed, busy, onInstall, onClose, t, local
|
||||
footer={(
|
||||
<DialogFooter>
|
||||
<Tooltip label={t('admin.plugins.sourceRepo')}>
|
||||
<a href={repoUrl} target="_blank" rel="noreferrer" aria-label={t('admin.plugins.sourceRepo')} className={linkClass}><Github size={15} /></a>
|
||||
<a href={repoUrl} target="_blank" rel="noreferrer" aria-label={t('admin.plugins.sourceRepo')} className={linkClass}><PluginIcon name="Github" size={15} /></a>
|
||||
</Tooltip>
|
||||
<Tooltip label={t('admin.plugins.reportIssue')}>
|
||||
<a href={`${repoUrl}/issues`} target="_blank" rel="noreferrer" aria-label={t('admin.plugins.reportIssue')} className={linkClass}><CircleDot size={15} /></a>
|
||||
|
||||
@@ -210,11 +210,8 @@ describe('BackupPanel', () => {
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('backup-2025-01-15.zip')).toBeInTheDocument()
|
||||
})
|
||||
const trashBtn = Array.from(document.querySelectorAll('button')).find(
|
||||
b => b.querySelector('svg.lucide-trash2'),
|
||||
) as HTMLElement
|
||||
expect(trashBtn).toBeTruthy()
|
||||
await user.click(trashBtn!)
|
||||
const trashBtn = screen.getByRole('button', { name: 'Delete' })
|
||||
await user.click(trashBtn)
|
||||
// The question is the shared confirm dialog now, not window.confirm
|
||||
expect(await screen.findByText('Delete backup "backup-2025-01-15.zip"?')).toBeInTheDocument()
|
||||
const deleteButtons = screen.getAllByRole('button', { name: 'Delete' })
|
||||
@@ -428,9 +425,7 @@ describe('BackupPanel', () => {
|
||||
render(<><ToastContainer /><BackupPanel /></>)
|
||||
await screen.findByText('backup-2025-01-15.zip')
|
||||
|
||||
const trashBtn = Array.from(document.querySelectorAll('button')).find(
|
||||
b => b.querySelector('svg.lucide-trash2'),
|
||||
) as HTMLElement
|
||||
const trashBtn = screen.getByRole('button', { name: 'Delete' })
|
||||
await user.click(trashBtn)
|
||||
await user.click(await screen.findByRole('button', { name: 'Cancel' }))
|
||||
expect(deleteCalls).toBe(0)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { focusRevealedEditor } from '../shared/dialogFocus'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { Plus, Trash2, Pencil, Package, X, Check, ChevronRight, FolderPlus, Loader2 } from 'lucide-react'
|
||||
import { fs } from '../shared/DialogShell'
|
||||
@@ -57,7 +58,7 @@ export default function PackingTemplateManager() {
|
||||
{showCreate && (
|
||||
<div className={COMPOSER_ROW} style={{ boxShadow: COMPOSER.boxShadow }}>
|
||||
<Package size={15} className="flex-none text-content-faint" />
|
||||
<input autoFocus value={createName} onChange={e => setCreateName(e.target.value)}
|
||||
<input ref={focusRevealedEditor} value={createName} onChange={e => setCreateName(e.target.value)}
|
||||
onKeyDown={e => { if (e.key === 'Enter') void handleCreateTemplate(); if (e.key === 'Escape') setShowCreate(false) }}
|
||||
placeholder={t('admin.packingTemplates.namePlaceholder')} className={COMPOSER_INPUT} style={fs(13, 'body')} />
|
||||
<Tooltip label={t('common.save')}>
|
||||
@@ -101,7 +102,7 @@ export default function PackingTemplateManager() {
|
||||
<Package size={15} strokeWidth={1.9} />
|
||||
</span>
|
||||
{editingTemplate === tmpl.id ? (
|
||||
<input autoFocus value={editTemplateName} onChange={e => setEditTemplateName(e.target.value)}
|
||||
<input ref={focusRevealedEditor} value={editTemplateName} onChange={e => setEditTemplateName(e.target.value)}
|
||||
onBlur={() => handleRenameTemplate(tmpl.id)}
|
||||
onKeyDown={e => { if (e.key === 'Enter') void handleRenameTemplate(tmpl.id); if (e.key === 'Escape') setEditingTemplate(null) }}
|
||||
aria-label={t('common.rename')}
|
||||
@@ -132,7 +133,7 @@ export default function PackingTemplateManager() {
|
||||
{/* Category header */}
|
||||
<div data-row="category" className="flex items-center gap-1.5 border-b border-edge-faint bg-surface-tertiary py-1.5 ps-3 pe-1.5">
|
||||
{editingCatId === cat.id ? (
|
||||
<input autoFocus value={editCatName} onChange={e => setEditCatName(e.target.value)}
|
||||
<input ref={focusRevealedEditor} value={editCatName} onChange={e => setEditCatName(e.target.value)}
|
||||
onBlur={() => handleRenameCategory(cat.id)}
|
||||
onKeyDown={e => { if (e.key === 'Enter') void handleRenameCategory(cat.id); if (e.key === 'Escape') setEditingCatId(null) }}
|
||||
aria-label={t('common.rename')}
|
||||
@@ -162,7 +163,7 @@ export default function PackingTemplateManager() {
|
||||
<div key={item.id} data-row="item" className="group flex min-h-[40px] items-center gap-2 py-1.5 ps-3 pe-1.5">
|
||||
{editingItemId === item.id ? (
|
||||
<>
|
||||
<input autoFocus value={editItemName} onChange={e => setEditItemName(e.target.value)}
|
||||
<input ref={focusRevealedEditor} value={editItemName} onChange={e => setEditItemName(e.target.value)}
|
||||
onKeyDown={e => { if (e.key === 'Enter') void handleRenameItem(item.id); if (e.key === 'Escape') setEditingItemId(null) }}
|
||||
aria-label={t('common.rename')}
|
||||
className={`${ROW_INPUT} flex-1`} style={fs(12.5, 'body')} />
|
||||
@@ -219,7 +220,7 @@ export default function PackingTemplateManager() {
|
||||
{/* Add category */}
|
||||
{addingCategory ? (
|
||||
<div className={COMPOSER_ROW} style={{ boxShadow: COMPOSER.boxShadow }}>
|
||||
<input autoFocus value={newCatName} onChange={e => setNewCatName(e.target.value)}
|
||||
<input ref={focusRevealedEditor} value={newCatName} onChange={e => setNewCatName(e.target.value)}
|
||||
onKeyDown={e => { if (e.key === 'Enter') void handleAddCategory(); if (e.key === 'Escape') { setAddingCategory(false); setNewCatName('') } }}
|
||||
placeholder={t('admin.packingTemplates.categoryName')}
|
||||
className={COMPOSER_INPUT} style={fs(13, 'body')} />
|
||||
|
||||
@@ -67,7 +67,7 @@ function Catalog() {
|
||||
}}>
|
||||
<div className={GRID_2}>
|
||||
<EditorField label={t('schoolCatalog.country')} htmlFor={`${fieldId}-name`}>
|
||||
<input id={`${fieldId}-name`} autoFocus required maxLength={100} className={INPUT} value={name} onChange={event => setName(event.target.value)} />
|
||||
<input id={`${fieldId}-name`} data-initial-focus required maxLength={100} className={INPUT} value={name} onChange={event => setName(event.target.value)} />
|
||||
</EditorField>
|
||||
<EditorField label={t('schoolCatalog.code')} htmlFor={`${fieldId}-code`}>
|
||||
<input id={`${fieldId}-code`} required pattern="[A-Z]{2}" maxLength={2} className={`${INPUT} font-geist uppercase tracking-[.08em]`} value={code} onChange={event => setCode(event.target.value.toUpperCase())} placeholder="US" />
|
||||
|
||||
@@ -62,7 +62,7 @@ export default function SchoolHolidayRegionEditor({ region, busy, offline = fals
|
||||
<div className={BODY}>
|
||||
<fieldset disabled={busy || offline} className={`m-0 flex min-w-0 flex-col gap-5 border-0 p-0 ${busy ? 'opacity-60' : ''}`}>
|
||||
<EditorField label={t('schoolCatalog.region')} htmlFor={`${fieldId}-region`}>
|
||||
<input id={`${fieldId}-region`} autoFocus required maxLength={150} className={INPUT} value={name} onChange={event => setName(event.target.value)} />
|
||||
<input id={`${fieldId}-region`} data-initial-focus required maxLength={150} className={INPUT} value={name} onChange={event => setName(event.target.value)} />
|
||||
</EditorField>
|
||||
<SettingsHint>{t('schoolCatalog.periodHint')}</SettingsHint>
|
||||
{holidays.map((holiday, index) => {
|
||||
|
||||
@@ -3,7 +3,6 @@ import {
|
||||
ArrowUpCircle,
|
||||
Bug,
|
||||
CircleDot,
|
||||
Github,
|
||||
Globe,
|
||||
History,
|
||||
Info,
|
||||
@@ -23,6 +22,7 @@ import { createPortal } from 'react-dom';
|
||||
import { POPOVER } from '../../Packing/packingPopoverStyles';
|
||||
import ToggleSwitch from '../../Settings/ToggleSwitch';
|
||||
import { fs } from '../../shared/DialogShell';
|
||||
import { Github } from '../../shared/legacyLucideIcons';
|
||||
import PluginIcon from '../../shared/PluginIcon';
|
||||
import { Tooltip } from '../../shared/Tooltip';
|
||||
import { deriveCaps } from '../pluginCaps';
|
||||
|
||||
@@ -11,12 +11,13 @@
|
||||
import type { AssistantApplied, AssistantChangeEffect, AssistantChangePreview } from '@trek/shared';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { buildAssignment, buildDay, buildPlace, buildTrip } from '../../../tests/helpers/factories';
|
||||
import { act, fireEvent, render, screen } from '../../../tests/helpers/render';
|
||||
import { buildAssignment, buildCategory, buildDay, buildPlace, buildTrip } from '../../../tests/helpers/factories';
|
||||
import { act, fireEvent, render, screen, within } from '../../../tests/helpers/render';
|
||||
import { chatOf, useAssistantStore } from '../../store/assistantStore';
|
||||
import { useTripStore } from '../../store/tripStore';
|
||||
import AssistantChangeCard from './AssistantChangeCard';
|
||||
import AssistantCompareSwitch from './AssistantCompareSwitch';
|
||||
import AssistantDayPreview from './AssistantDayPreview';
|
||||
import type { ChangeItem } from './assistantParts';
|
||||
import { type AssistantView, AssistantViewContext } from './assistantViewContext';
|
||||
|
||||
@@ -168,6 +169,106 @@ describe('AssistantChangeCard: deciding', () => {
|
||||
expect(screen.getByRole('button', { name: 'Apply' })).toBeDisabled();
|
||||
expect(screen.getByRole('button', { name: 'Discard' })).toBeDisabled();
|
||||
});
|
||||
|
||||
it('edits a place proposal in the full place form and previews edits before applying', async () => {
|
||||
plannerHere();
|
||||
const change = {
|
||||
...preview('c1', 'Kinkaku-ji'),
|
||||
verbKey: 'addPlaceToDay' as const,
|
||||
effect: { ...PANTHEON, place: { name: 'Kinkaku-ji', lat: 48, lng: 2, categoryId: 31 } },
|
||||
};
|
||||
const other = { ...change, toolCallId: 'c2', subject: 'Tea house', effect: null };
|
||||
useTripStore.setState({
|
||||
categories: [
|
||||
buildCategory({ id: 31, name: 'Temple', color: '#334455' }),
|
||||
buildCategory({ id: 32, name: 'Garden', color: '#667788' }),
|
||||
],
|
||||
});
|
||||
patchChat({
|
||||
messages: [
|
||||
{
|
||||
id: 'm1',
|
||||
role: 'assistant',
|
||||
status: 'complete',
|
||||
createdAt: new Date().toISOString(),
|
||||
parts: [
|
||||
{
|
||||
type: 'tool-call',
|
||||
toolCallId: 'c1',
|
||||
toolName: 'create_and_assign_place',
|
||||
args: {},
|
||||
approval: { id: 'c1' },
|
||||
},
|
||||
{ type: 'data-trek-change', data: change },
|
||||
{
|
||||
type: 'tool-call',
|
||||
toolCallId: 'c2',
|
||||
toolName: 'create_and_assign_place',
|
||||
args: {},
|
||||
approval: { id: 'c2' },
|
||||
},
|
||||
{ type: 'data-trek-change', data: other },
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
render(<AssistantDayPreview tripId={TRIP} dayId={3} />);
|
||||
renderCard([
|
||||
{ ...pending('c1', 'Kinkaku-ji'), preview: change },
|
||||
{ ...pending('c2', 'Tea house'), preview: other },
|
||||
]);
|
||||
const day = screen.getByRole('list', { name: 'Suggested by the assistant' });
|
||||
|
||||
const [edit] = screen.getAllByRole('button', { name: 'Edit' });
|
||||
fireEvent.click(edit);
|
||||
const dialog = within(await screen.findByRole('dialog', { name: 'Edit Place' }));
|
||||
expect(dialog.getByRole('textbox', { name: /^Name/ })).toHaveValue('Kinkaku-ji');
|
||||
expect(dialog.getByRole('textbox', { name: 'Address' })).toBeVisible();
|
||||
fireEvent.change(dialog.getByRole('textbox', { name: 'Start' }), { target: { value: '12:30' } });
|
||||
fireEvent.change(dialog.getByRole('textbox', { name: 'Notes for this day' }), {
|
||||
target: { value: 'Use the side entrance' },
|
||||
});
|
||||
fireEvent.click(dialog.getByRole('button', { name: /^Category:/ }));
|
||||
fireEvent.click(screen.getByRole('button', { name: /^Garden$/ }));
|
||||
expect(day).toHaveTextContent('12:30');
|
||||
expect(day).toHaveTextContent('Use the side entrance');
|
||||
expect(within(day).getByText('Garden').parentElement).toHaveStyle({ backgroundColor: '#667788' });
|
||||
expect(decide).not.toHaveBeenCalled();
|
||||
fireEvent.click(dialog.getByRole('button', { name: 'Cancel' }));
|
||||
expect(day).toHaveTextContent('10:30');
|
||||
expect(day).toHaveTextContent('Temple');
|
||||
expect(day).not.toHaveTextContent('Use the side entrance');
|
||||
|
||||
fireEvent.click(edit);
|
||||
const reopened = within(await screen.findByRole('dialog', { name: 'Edit Place' }));
|
||||
const time = reopened.getByRole('textbox', { name: 'Start' });
|
||||
expect(time).toHaveValue('10:30');
|
||||
fireEvent.change(time, { target: { value: '11:45' } });
|
||||
fireEvent.change(reopened.getByRole('textbox', { name: /^Name/ }), { target: { value: 'Golden Pavilion' } });
|
||||
fireEvent.change(reopened.getByRole('textbox', { name: 'Address' }), { target: { value: 'Kyoto, Japan' } });
|
||||
expect(day).toHaveTextContent('Golden Pavilion');
|
||||
fireEvent.click(reopened.getByRole('button', { name: 'Save' }));
|
||||
expect(day).toHaveTextContent('11:45');
|
||||
expect(decide).not.toHaveBeenCalled();
|
||||
|
||||
const [include] = screen.getAllByRole('button', { name: 'Include this change' });
|
||||
fireEvent.click(include);
|
||||
expect(day).not.toHaveTextContent('Golden Pavilion');
|
||||
expect(day).toHaveTextContent('Tea house');
|
||||
fireEvent.click(include);
|
||||
expect(day).toHaveTextContent('Golden Pavilion');
|
||||
expect(day).toHaveTextContent('11:45');
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Apply 2' }));
|
||||
expect(decide).toHaveBeenCalledWith(TRIP, [
|
||||
{
|
||||
toolCallId: 'c1',
|
||||
approved: true,
|
||||
planEdits: { startTime: '11:45', place: { name: 'Golden Pavilion', address: 'Kyoto, Japan' } },
|
||||
},
|
||||
{ toolCallId: 'c2', approved: true },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('AssistantChangeCard: the receipt', () => {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Check, CheckCheck, ListChecks, LoaderCircle, MapPin, Undo2 } from 'lucide-react';
|
||||
import { Check, CheckCheck, ChevronDown, ListChecks, LoaderCircle, MapPin, Undo2 } from 'lucide-react';
|
||||
import { type ReactNode, useEffect, useMemo, useState } from 'react';
|
||||
|
||||
import { useTranslation } from '../../i18n';
|
||||
@@ -78,13 +78,21 @@ function dayChangesOf(items: readonly ChangeItem[], excluded: ReadonlySet<string
|
||||
/** The change card's band: tinted green once everything in it is decided, what it holds and its actions. */
|
||||
function CardHead({ open, count, actions }: { open: boolean; count: number; actions?: ReactNode }) {
|
||||
const { t } = useTranslation();
|
||||
const Icon = open ? ListChecks : CheckCheck;
|
||||
return (
|
||||
<CardHeader
|
||||
icon={open ? ListChecks : CheckCheck}
|
||||
icon={Icon}
|
||||
tone={open ? 'info' : 'success'}
|
||||
tint={open ? NEUTRAL_TINT : DONE_TINT}
|
||||
title={t(open ? 'assistant.change.title' : 'assistant.change.doneTitle')}
|
||||
count={count}
|
||||
tile={
|
||||
<span className="relative grid h-8 w-8 shrink-0 place-items-center rounded-[10px] bg-surface-card shadow-sm">
|
||||
<Icon size={15} strokeWidth={2} className={open ? 'text-info' : 'text-success'} aria-hidden="true" />
|
||||
<span className="absolute -end-1 -top-1 inline-flex h-4 min-w-4 items-center justify-center rounded-full bg-surface-card px-1 font-geist text-caption font-bold tabular-nums leading-none text-content-secondary shadow-sm ring-1 ring-edge">
|
||||
{count}
|
||||
</span>
|
||||
</span>
|
||||
}
|
||||
actions={actions}
|
||||
/>
|
||||
);
|
||||
@@ -186,11 +194,23 @@ export default function AssistantChangeCard({ items }: { items: ChangeItem[] })
|
||||
const undone = useAssistantStore((s) => chatOf(s, tripId).undone);
|
||||
const decide = useAssistantStore((s) => s.decide);
|
||||
const undo = useAssistantStore((s) => s.undo);
|
||||
const [excluded, setExcluded] = useChangeExclusions(items);
|
||||
const choices = useAssistantStore((s) => chatOf(s, tripId).changeChoices);
|
||||
const choosePlanChanges = useAssistantStore((s) => s.choosePlanChanges);
|
||||
const excluded = useChangeExclusions(items, choices);
|
||||
const planEdits = useAssistantStore((s) => chatOf(s, tripId).planEdits);
|
||||
const savePlanEdit = useAssistantStore((s) => s.savePlanEdit);
|
||||
const now = useUndoClock(items);
|
||||
|
||||
const pending = items.filter((i) => i.state === 'pending');
|
||||
const chosen = pending.filter((i) => !excluded.has(i.toolCallId)).length;
|
||||
const invalid = pending.some((i) => !excluded.has(i.toolCallId) && planEdits[i.toolCallId]?.noteTitle?.trim() === '');
|
||||
const planDayId = pending[0]?.preview?.dayId;
|
||||
const planDay = useTripStore((s) => (s.trip?.id === tripId ? s.days.find((day) => day.id === planDayId) : undefined));
|
||||
const groupedDay =
|
||||
pending.length > 1 &&
|
||||
pending.length === items.length &&
|
||||
!!planDay &&
|
||||
pending.every((i) => i.preview?.dayId === planDayId);
|
||||
const changes = useMemo(() => dayChangesOf(items, excluded), [items, excluded]);
|
||||
const undoable = items.filter((i) => undoableNow(i, undone, now)).map((i) => i.toolCallId);
|
||||
|
||||
@@ -199,27 +219,17 @@ export default function AssistantChangeCard({ items }: { items: ChangeItem[] })
|
||||
// A plan over a week reads from its grid; the single changes wait behind one line.
|
||||
const folded = week.length > 0 && !showAll;
|
||||
|
||||
const toggleDay = (ids: readonly string[], include: boolean) =>
|
||||
setExcluded((prev) => {
|
||||
const next = new Set(prev);
|
||||
for (const id of ids) {
|
||||
if (include) next.delete(id);
|
||||
else next.add(id);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
|
||||
const toggle = (toolCallId: string) =>
|
||||
setExcluded((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (!next.delete(toolCallId)) next.add(toolCallId);
|
||||
return next;
|
||||
});
|
||||
const toggleDay = (ids: readonly string[], include: boolean) => choosePlanChanges(tripId, ids, include);
|
||||
const toggle = (toolCallId: string) => toggleDay([toolCallId], excluded.has(toolCallId));
|
||||
|
||||
const submit = (applyChosen: boolean) =>
|
||||
decide(
|
||||
tripId,
|
||||
pending.map((i) => ({ toolCallId: i.toolCallId, approved: applyChosen && !excluded.has(i.toolCallId) }))
|
||||
pending.map((i) => {
|
||||
const approved = applyChosen && !excluded.has(i.toolCallId);
|
||||
const edits = approved ? planEdits[i.toolCallId] : undefined;
|
||||
return { toolCallId: i.toolCallId, approved, ...(edits ? { planEdits: edits } : {}) };
|
||||
})
|
||||
);
|
||||
|
||||
// An undone change reads as undone from the store; only what stays needs a word.
|
||||
@@ -230,6 +240,21 @@ export default function AssistantChangeCard({ items }: { items: ChangeItem[] })
|
||||
};
|
||||
|
||||
const open = pending.length > 0;
|
||||
const rows = (
|
||||
<ChangeRows
|
||||
items={items}
|
||||
folded={folded}
|
||||
excluded={excluded}
|
||||
disabled={isRunning}
|
||||
undone={undone}
|
||||
undoable={undoable}
|
||||
onToggle={toggle}
|
||||
onUndo={(toolCallId) => void runUndo(toolCallId)}
|
||||
groupedDay={groupedDay}
|
||||
planEdits={planEdits}
|
||||
onEdit={(id, patch) => savePlanEdit(tripId, id, patch)}
|
||||
/>
|
||||
);
|
||||
return (
|
||||
<section className="trek-popover-enter overflow-hidden rounded-[16px] border border-edge-faint bg-surface-card px-3.5 pb-3 pt-3 shadow-card">
|
||||
<CardHead
|
||||
@@ -249,16 +274,31 @@ export default function AssistantChangeCard({ items }: { items: ChangeItem[] })
|
||||
{t('assistant.week.showAll', { count: pending.length })}
|
||||
</button>
|
||||
)}
|
||||
<ChangeRows
|
||||
items={items}
|
||||
folded={folded}
|
||||
excluded={excluded}
|
||||
disabled={isRunning}
|
||||
undone={undone}
|
||||
undoable={undoable}
|
||||
onToggle={toggle}
|
||||
onUndo={(toolCallId) => void runUndo(toolCallId)}
|
||||
/>
|
||||
{!folded && groupedDay && planDay ? (
|
||||
<details open className="group/day mt-1">
|
||||
<summary className="-mx-1.5 flex min-w-0 cursor-pointer list-none items-center gap-2.5 rounded-xl bg-surface-tertiary py-2 pe-3.5 ps-1.5 text-start hover:bg-surface-hover focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-accent [&::-webkit-details-marker]:hidden">
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className="grid h-8 w-8 shrink-0 place-items-center rounded-[10px] bg-surface-card font-geist text-caption font-bold tabular-nums text-content-muted shadow-sm"
|
||||
>
|
||||
{planDay.day_number}
|
||||
</span>
|
||||
<span className="shrink-0 text-body font-bold text-content">
|
||||
{t('assistant.week.day')} {planDay.day_number}
|
||||
</span>
|
||||
{planDay.title && <bdi className="min-w-0 truncate text-caption text-content-muted">{planDay.title}</bdi>}
|
||||
<ChevronDown
|
||||
size={15}
|
||||
strokeWidth={2}
|
||||
aria-hidden="true"
|
||||
className="ms-auto shrink-0 -rotate-90 text-content-muted group-open/day:rotate-0"
|
||||
/>
|
||||
</summary>
|
||||
{rows}
|
||||
</details>
|
||||
) : (
|
||||
rows
|
||||
)}
|
||||
{open && (
|
||||
<>
|
||||
<p className="sr-only" role="status">
|
||||
@@ -270,7 +310,7 @@ export default function AssistantChangeCard({ items }: { items: ChangeItem[] })
|
||||
</DialogButton>
|
||||
<DialogButton
|
||||
variant="primary"
|
||||
disabled={isRunning || chosen === 0}
|
||||
disabled={isRunning || chosen === 0 || invalid}
|
||||
onClick={() => void submit(true)}
|
||||
icon={<Check size={14} aria-hidden="true" />}
|
||||
>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { AssistantChangeLabelKey, AssistantChangeRow } from '@trek/shared';
|
||||
import type { AssistantChangeLabelKey, AssistantChangeRow, AssistantPlanEdits } from '@trek/shared';
|
||||
import {
|
||||
CalendarClock,
|
||||
CalendarDays,
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
} from 'lucide-react';
|
||||
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { useTripStore } from '../../store/tripStore';
|
||||
import { FactChange } from './cards/parts/CardFacts';
|
||||
|
||||
/**
|
||||
@@ -45,10 +46,42 @@ function shown(row: AssistantChangeRow, value: string | null | undefined, dayWor
|
||||
return value ?? '';
|
||||
}
|
||||
|
||||
export default function AssistantChangeFields({ rows }: { rows: AssistantChangeRow[] }) {
|
||||
export default function AssistantChangeFields({
|
||||
rows,
|
||||
visit = false,
|
||||
edits,
|
||||
}: {
|
||||
rows: AssistantChangeRow[];
|
||||
visit?: boolean;
|
||||
edits?: AssistantPlanEdits;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const categoryName = useTripStore((s) =>
|
||||
edits?.categoryId == null ? undefined : s.categories.find((category) => category.id === edits.categoryId)?.name
|
||||
);
|
||||
const dayWord = t('assistant.week.day');
|
||||
const facts = rows
|
||||
let editedRows = rows;
|
||||
if (visit && edits) {
|
||||
const fields = [
|
||||
['time', edits.startTime],
|
||||
['endTime', edits.endTime],
|
||||
['category', edits.categoryId === null ? null : categoryName],
|
||||
] as const;
|
||||
for (const [labelKey, after] of fields) {
|
||||
if (after === undefined) continue;
|
||||
editedRows = editedRows.filter((row) => row.labelKey !== labelKey);
|
||||
if (after) editedRows.push({ op: 'add', labelKey, before: null, after });
|
||||
}
|
||||
}
|
||||
const end = visit ? editedRows.find((row) => row.labelKey === 'endTime')?.after : undefined;
|
||||
const start = visit ? editedRows.find((row) => row.labelKey === 'time') : undefined;
|
||||
const visible =
|
||||
start?.after && end
|
||||
? editedRows
|
||||
.filter((row) => row.labelKey !== 'endTime')
|
||||
.map((row) => (row === start ? { ...row, after: `${row.after} – ${end}` } : row))
|
||||
: editedRows;
|
||||
const facts = visible
|
||||
.filter((row) => row.labelKey in KEY_FIELDS && row.after)
|
||||
.sort((a, b) => KEY_ORDER.indexOf(a.labelKey) - KEY_ORDER.indexOf(b.labelKey))
|
||||
.slice(0, MAX_FACTS);
|
||||
|
||||
@@ -1,18 +1,28 @@
|
||||
import type { AssistantChangeEffect, AssistantMessage } from '@trek/shared';
|
||||
import { ArrowRightLeft, Minus, Sparkles } from 'lucide-react';
|
||||
import type { AssistantChangePreview, AssistantMessage, AssistantPlanEdits } from '@trek/shared';
|
||||
import { ArrowRightLeft, FileText, MapPin, Minus, type LucideIcon } from 'lucide-react';
|
||||
import { useMemo } from 'react';
|
||||
import { useShallow } from 'zustand/react/shallow';
|
||||
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { changeEffects } from '../../store/assistantMapModel';
|
||||
import { chatOf, useAssistantStore } from '../../store/assistantStore';
|
||||
import { useSettingsStore } from '../../store/settingsStore';
|
||||
import { useTripStore } from '../../store/tripStore';
|
||||
import type { Place } from '../../types';
|
||||
import { formatTime } from '../../utils/formatters';
|
||||
import { TimePill } from '../Planner/planParts';
|
||||
import { getCategoryIcon } from '../shared/categoryIcons';
|
||||
import { isDayNoteProposal, isVisitProposal, planField, proposalNote } from './assistantPlanFieldsModel';
|
||||
|
||||
/** What a waiting change does to one day, as a row of the preview. */
|
||||
interface PreviewRow {
|
||||
toolCallId: string;
|
||||
kind: 'add' | 'in' | 'remove' | 'out';
|
||||
kind: 'add' | 'in' | 'remove' | 'out' | 'note';
|
||||
name: string;
|
||||
categoryId: number | null;
|
||||
categoryName?: string;
|
||||
start?: string;
|
||||
end?: string;
|
||||
detail?: string;
|
||||
}
|
||||
|
||||
/** The changes no one has decided on yet, by their call. */
|
||||
@@ -29,25 +39,77 @@ function waitingCalls(messages: readonly AssistantMessage[]): Set<string> {
|
||||
}
|
||||
|
||||
function rowOf(
|
||||
toolCallId: string,
|
||||
effect: AssistantChangeEffect,
|
||||
preview: AssistantChangePreview,
|
||||
dayId: number,
|
||||
nameOf: (id: number | null) => string | null
|
||||
) {
|
||||
const name = effect.place?.name ?? nameOf(effect.placeId);
|
||||
if (!name) return null;
|
||||
if (effect.dayId === dayId) {
|
||||
const kind = effect.kind === 'remove' ? 'remove' : effect.kind === 'move' ? 'in' : 'add';
|
||||
return { toolCallId, kind, name } satisfies PreviewRow;
|
||||
places: readonly Place[],
|
||||
edits: AssistantPlanEdits | undefined
|
||||
): PreviewRow | null {
|
||||
const { toolCallId, effect, subject } = preview;
|
||||
if (preview.dayId === dayId && isDayNoteProposal(preview)) {
|
||||
return {
|
||||
toolCallId,
|
||||
kind: 'note',
|
||||
name: edits?.noteTitle || planField(preview, 'title') || subject,
|
||||
categoryId: null,
|
||||
detail: proposalNote(preview, edits) ?? undefined,
|
||||
};
|
||||
}
|
||||
if (effect.kind === 'move' && effect.fromDayId === dayId)
|
||||
return { toolCallId, kind: 'out', name } satisfies PreviewRow;
|
||||
return null;
|
||||
const kind = visitKind(preview, dayId);
|
||||
if (!kind) return null;
|
||||
const place = places.find((p) => p.id === effect?.placeId);
|
||||
return { toolCallId, kind, ...visitSubject(preview, place, edits), ...visitDetails(preview, place, edits) };
|
||||
}
|
||||
|
||||
const LOOK: Record<PreviewRow['kind'], { icon: typeof Sparkles; row: string; name: string; badgeKey: string }> = {
|
||||
function visitSubject(
|
||||
preview: AssistantChangePreview,
|
||||
place: Place | undefined,
|
||||
edits: AssistantPlanEdits | undefined
|
||||
) {
|
||||
const proposed = preview.effect?.place;
|
||||
const categoryId = edits?.categoryId;
|
||||
return {
|
||||
name: edits?.place?.name ?? proposed?.name ?? place?.name ?? preview.subject,
|
||||
categoryId: categoryId === undefined ? (proposed?.categoryId ?? place?.category_id ?? null) : categoryId,
|
||||
categoryName: categoryId === undefined ? planField(preview, 'category') : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
function editedText(value: string | null | undefined, original: string | undefined): string | undefined {
|
||||
return value === undefined ? original : (value ?? undefined);
|
||||
}
|
||||
|
||||
function visitDetails(
|
||||
preview: AssistantChangePreview,
|
||||
place: Place | undefined,
|
||||
edits: AssistantPlanEdits | undefined
|
||||
) {
|
||||
return {
|
||||
start: editedText(edits?.startTime, planField(preview, 'time')),
|
||||
end: editedText(edits?.endTime, planField(preview, 'endTime')),
|
||||
detail:
|
||||
editedText(edits?.notes, planField(preview, 'notes')) ||
|
||||
editedText(edits?.place?.description, planField(preview, 'description')) ||
|
||||
place?.description ||
|
||||
editedText(edits?.place?.address, planField(preview, 'address')) ||
|
||||
place?.address ||
|
||||
undefined,
|
||||
};
|
||||
}
|
||||
|
||||
function visitKind(preview: AssistantChangePreview, dayId: number): PreviewRow['kind'] | null {
|
||||
const { effect } = preview;
|
||||
if (!effect) return preview.dayId === dayId && isVisitProposal(preview) ? 'add' : null;
|
||||
if (effect.dayId === dayId) {
|
||||
if (effect.kind === 'remove') return 'remove';
|
||||
if (effect.kind === 'move') return 'in';
|
||||
return 'add';
|
||||
}
|
||||
return effect.kind === 'move' && effect.fromDayId === dayId ? 'out' : null;
|
||||
}
|
||||
|
||||
const LOOK: Record<PreviewRow['kind'], { icon: LucideIcon; row: string; name: string; badgeKey: string }> = {
|
||||
add: {
|
||||
icon: Sparkles,
|
||||
icon: MapPin,
|
||||
row: 'border-dashed border-accent bg-accent-subtle',
|
||||
name: 'text-content',
|
||||
badgeKey: 'assistant.preview.suggested',
|
||||
@@ -70,6 +132,12 @@ const LOOK: Record<PreviewRow['kind'], { icon: typeof Sparkles; row: string; nam
|
||||
name: 'text-content-faint line-through',
|
||||
badgeKey: 'assistant.preview.movedAway',
|
||||
},
|
||||
note: {
|
||||
icon: FileText,
|
||||
row: 'border-dashed border-accent bg-accent-subtle',
|
||||
name: 'text-content',
|
||||
badgeKey: 'assistant.preview.suggested',
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -80,31 +148,45 @@ const LOOK: Record<PreviewRow['kind'], { icon: typeof Sparkles; row: string; nam
|
||||
* here writes; the change card stays the one place a change is applied.
|
||||
*/
|
||||
export default function AssistantDayPreview({ tripId, dayId }: { tripId: number; dayId: number }) {
|
||||
const { t } = useTranslation();
|
||||
const { t, locale } = useTranslation();
|
||||
const timeFormat = useSettingsStore((s) => s.settings.time_format) || '24h';
|
||||
const messages = useAssistantStore((s) => chatOf(s, tripId).messages);
|
||||
const savedEdits = useAssistantStore((s) => chatOf(s, tripId).planEdits);
|
||||
const liveEdit = useAssistantStore((s) => chatOf(s, tripId).planEditPreview);
|
||||
const choices = useAssistantStore((s) => chatOf(s, tripId).changeChoices);
|
||||
const hovered = useAssistantStore((s) => (s.mapLink?.tripId === tripId ? s.mapLink.hoveredId : null));
|
||||
const { setMapHover, open } = useAssistantStore(useShallow((s) => ({ setMapHover: s.setMapHover, open: s.open })));
|
||||
const places = useTripStore((s) => s.places);
|
||||
const categories = useTripStore((s) => s.categories);
|
||||
|
||||
const rows = useMemo(() => {
|
||||
const waiting = waitingCalls(messages);
|
||||
if (waiting.size === 0) return [];
|
||||
const nameOf = (id: number | null) => (id === null ? null : (places.find((p) => p.id === id)?.name ?? null));
|
||||
const out: PreviewRow[] = [];
|
||||
for (const [toolCallId, effect] of changeEffects(messages)) {
|
||||
if (!waiting.has(toolCallId)) continue;
|
||||
const row = rowOf(toolCallId, effect, dayId, nameOf);
|
||||
if (row) out.push(row);
|
||||
}
|
||||
return out;
|
||||
}, [messages, places, dayId]);
|
||||
return messages.flatMap((message) =>
|
||||
message.parts.flatMap((part) => {
|
||||
if (part.type !== 'data-trek-change' || !waiting.delete(part.data.toolCallId)) return [];
|
||||
const id = part.data.toolCallId;
|
||||
if (choices[id] === false) return [];
|
||||
const edits = liveEdit?.toolCallId === id ? liveEdit.edits : savedEdits[id];
|
||||
const row = rowOf(part.data, dayId, places, edits);
|
||||
return row ? [row] : [];
|
||||
})
|
||||
);
|
||||
}, [messages, places, dayId, savedEdits, liveEdit, choices]);
|
||||
|
||||
if (rows.length === 0) return null;
|
||||
return (
|
||||
<ul className="m-0 flex list-none flex-col gap-1 px-3 pb-2 pt-1" aria-label={t('assistant.preview.title')}>
|
||||
{rows.map((row, i) => {
|
||||
const look = LOOK[row.kind];
|
||||
const Icon = look.icon;
|
||||
const category = categories.find((entry) =>
|
||||
row.categoryId ? entry.id === row.categoryId : entry.name === row.categoryName
|
||||
);
|
||||
const Icon = category ? getCategoryIcon(category.icon) : look.icon;
|
||||
const time = [row.start, row.end]
|
||||
.filter((value): value is string => !!value)
|
||||
.map((value) => formatTime(value, locale, timeFormat))
|
||||
.join(' – ');
|
||||
const lit = hovered === row.toolCallId;
|
||||
return (
|
||||
<li
|
||||
@@ -121,11 +203,29 @@ export default function AssistantDayPreview({ tripId, dayId }: { tripId: number;
|
||||
lit ? 'shadow-md ring-2 ring-accent' : 'hover:shadow-sm'
|
||||
}`}
|
||||
>
|
||||
<span className="grid h-6 w-6 flex-shrink-0 place-items-center rounded-lg bg-surface-card text-content-muted shadow-sm">
|
||||
<Icon size={12} aria-hidden="true" />
|
||||
<span
|
||||
className="grid h-8 w-8 flex-shrink-0 place-items-center rounded-full bg-surface-card text-content-muted shadow-sm"
|
||||
style={category?.color ? { backgroundColor: category.color, color: 'white' } : undefined}
|
||||
>
|
||||
<Icon size={14} aria-hidden="true" />
|
||||
{(category?.name || row.categoryName) && (
|
||||
<span className="sr-only">{category?.name ?? row.categoryName}</span>
|
||||
)}
|
||||
</span>
|
||||
<bdi className={`min-w-0 flex-1 truncate text-caption font-medium ${look.name}`}>{row.name}</bdi>
|
||||
<span className="flex-shrink-0 rounded-full bg-surface-card px-2 py-0.5 text-caption text-content-muted shadow-sm">
|
||||
<span className="min-w-0 flex-1">
|
||||
<bdi className={`block truncate text-body font-medium ${look.name}`}>{row.name}</bdi>
|
||||
{time && (
|
||||
<span className="mt-0.5 flex">
|
||||
<TimePill quiet>{time}</TimePill>
|
||||
</span>
|
||||
)}
|
||||
{row.detail && (
|
||||
<bdi className="mt-0.5 line-clamp-2 break-words text-caption text-content-muted">{row.detail}</bdi>
|
||||
)}
|
||||
</span>
|
||||
<span
|
||||
className={row.kind === 'add' || row.kind === 'note' ? 'sr-only' : 'flex-shrink-0 text-content-muted'}
|
||||
>
|
||||
{t(look.badgeKey)}
|
||||
</span>
|
||||
</button>
|
||||
|
||||
@@ -4,10 +4,11 @@
|
||||
* The error line: one sentence, at most one thing to do, and that thing
|
||||
* does what it says.
|
||||
*/
|
||||
import type { AiStatusResponse, AssistantErrorCode } from '@trek/shared';
|
||||
import type { AiStatusResponse, AssistantErrorCode, AssistantMessage } from '@trek/shared';
|
||||
import { Route, Routes } from 'react-router';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { HIKE } from '../../../tests/helpers/assistantTour';
|
||||
import { fireEvent, render, screen } from '../../../tests/helpers/render';
|
||||
import { chatOf, useAssistantStore } from '../../store/assistantStore';
|
||||
import { setForcedOffline } from '../../sync/networkMode';
|
||||
@@ -33,13 +34,17 @@ const retry = vi.fn(async () => {});
|
||||
const continueHere = vi.fn(async () => {});
|
||||
const send = vi.fn(async () => {});
|
||||
|
||||
function withError(error: AssistantErrorCode | null, status: AiStatusResponse = STATUS) {
|
||||
function withError(
|
||||
error: AssistantErrorCode | null,
|
||||
status: AiStatusResponse = STATUS,
|
||||
messages: AssistantMessage[] = []
|
||||
) {
|
||||
useAssistantStore.setState({
|
||||
status,
|
||||
retry,
|
||||
continueHere,
|
||||
send,
|
||||
byTrip: { [TRIP]: { ...chatOf(useAssistantStore.getState(), TRIP), error } },
|
||||
byTrip: { [TRIP]: { ...chatOf(useAssistantStore.getState(), TRIP), error, messages } },
|
||||
});
|
||||
}
|
||||
|
||||
@@ -119,6 +124,25 @@ describe('AssistantError', () => {
|
||||
expect(screen.queryByRole('button')).toBeNull();
|
||||
});
|
||||
|
||||
it('keeps a calculated route distinct from the rate-limited reply', () => {
|
||||
const when = '2026-10-21T08:00:00.000Z';
|
||||
const question: AssistantMessage = { id: 'm1', role: 'user', status: 'complete', parts: [], createdAt: when };
|
||||
const answer: AssistantMessage = {
|
||||
id: 'm2',
|
||||
role: 'assistant',
|
||||
status: 'error',
|
||||
createdAt: when,
|
||||
parts: [{ type: 'data-trek-card', data: { toolCallId: 'hike', card: HIKE } }],
|
||||
};
|
||||
withError('rate_limited', STATUS, [question, answer]);
|
||||
const { unmount } = renderLine();
|
||||
expect(screen.getByRole('status')).toHaveTextContent('The route preview is still available.');
|
||||
unmount();
|
||||
withError('rate_limited', STATUS, [question, answer, { ...question, id: 'm3' }]);
|
||||
renderLine();
|
||||
expect(screen.getByRole('status')).toHaveTextContent('Limit reached at Anthropic. Try again later.');
|
||||
});
|
||||
|
||||
it('FE-AI-ERR-008: waiting changes ask for a decision before a place can be suggested', () => {
|
||||
withError('decide_first');
|
||||
renderLine();
|
||||
|
||||
@@ -4,7 +4,7 @@ import { useNavigate } from 'react-router';
|
||||
import { useNetworkMode } from '../../hooks/useNetworkMode';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { chatOf, useAssistantStore } from '../../store/assistantStore';
|
||||
import { type AssistantErrorActionKind, connectionErrorOf, errorView } from './assistantModel';
|
||||
import { type AssistantErrorActionKind, connectionErrorOf, errorView, hasCurrentTourProposal } from './assistantModel';
|
||||
import { AI_SETTINGS_PATH } from './assistantParts';
|
||||
import { CHATGPT_USAGE_URL, providerLabel } from './providerCatalog';
|
||||
|
||||
@@ -18,6 +18,10 @@ export default function AssistantError({ tripId }: { tripId: number }) {
|
||||
const navigate = useNavigate();
|
||||
const { offline } = useNetworkMode();
|
||||
const error = useAssistantStore((s) => chatOf(s, tripId).error);
|
||||
const hasTourProposal = useAssistantStore((s) => {
|
||||
const chat = chatOf(s, tripId);
|
||||
return chat.error === 'rate_limited' && hasCurrentTourProposal(chat.messages);
|
||||
});
|
||||
const status = useAssistantStore((s) => s.status);
|
||||
const retry = useAssistantStore((s) => s.retry);
|
||||
const continueHere = useAssistantStore((s) => s.continueHere);
|
||||
@@ -28,7 +32,7 @@ export default function AssistantError({ tripId }: { tripId: number }) {
|
||||
|
||||
const effective = status?.effective;
|
||||
const provider = effective ? providerLabel(effective.kind, effective.host) : '';
|
||||
const view = errorView(code, { canConnectOwn: status?.canConnectOwn ?? false, provider });
|
||||
const view = errorView(code, { canConnectOwn: status?.canConnectOwn ?? false, provider, hasTourProposal });
|
||||
|
||||
const run = (kind: AssistantErrorActionKind) => {
|
||||
if (kind === 'retry') void retry(tripId);
|
||||
|
||||
@@ -139,7 +139,8 @@ function Answer({ message }: { message: StoredMessage }) {
|
||||
});
|
||||
const blocks = useMemo(() => messageBlocks(message, writing), [message, writing]);
|
||||
const share = useAssistantShare(tripId, message, writing);
|
||||
const last = blocks[blocks.length - 1];
|
||||
const end = blocks[blocks.length - 1];
|
||||
const last = end?.kind === 'sources' ? blocks[blocks.length - 2] : end;
|
||||
const hasText = blocks.some((b) => b.kind === 'text');
|
||||
const tail = tailStart(blocks);
|
||||
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
import type { AssistantChangePreview, AssistantPlanEdits } from '@trek/shared';
|
||||
import { assistantPlanEditsSchema, parsePlaceHours, placeOpeningHoursSchema } from '@trek/shared';
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
|
||||
import { useIsPhone } from '../../hooks/useIsPhone';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { useAssistantStore } from '../../store/assistantStore';
|
||||
import { useTripStore } from '../../store/tripStore';
|
||||
import PlaceFormModal from '../Planner/PlaceFormModal';
|
||||
import { DEFAULT_FORM, formPin, type PlaceFormData } from '../Planner/PlaceFormModal.helpers';
|
||||
import { planField } from './assistantPlanFieldsModel';
|
||||
import { useAssistantView } from './assistantViewContext';
|
||||
|
||||
type PlacePatch = NonNullable<AssistantPlanEdits['place']>;
|
||||
|
||||
function originalForm(preview: AssistantChangePreview, rawArgs: unknown, categoryId: number | null): PlaceFormData {
|
||||
const args = rawArgs && typeof rawArgs === 'object' ? (rawArgs as Record<string, unknown>) : {};
|
||||
const value = (key: string) => (typeof args[key] === 'string' ? args[key] : '');
|
||||
const point = preview.effect?.place;
|
||||
const coordinate = (key: 'lat' | 'lng') => String(typeof args[key] === 'number' ? args[key] : (point?.[key] ?? ''));
|
||||
const text = (key: 'address' | 'description') => value(key) || planField(preview, key) || '';
|
||||
const hours = placeOpeningHoursSchema.safeParse(args.opening_hours);
|
||||
return {
|
||||
...DEFAULT_FORM,
|
||||
name: value('name') || point?.name || preview.subject,
|
||||
address: text('address'),
|
||||
description: text('description'),
|
||||
lat: coordinate('lat'),
|
||||
lng: coordinate('lng'),
|
||||
category_id: String(categoryId ?? ''),
|
||||
place_time: planField(preview, 'time') ?? '',
|
||||
end_time: planField(preview, 'endTime') ?? '',
|
||||
assignment_notes: planField(preview, 'notes') ?? '',
|
||||
notes: value('place_notes'),
|
||||
google_place_id: value('google_place_id'),
|
||||
google_ftid: value('google_ftid'),
|
||||
osm_id: value('osm_id'),
|
||||
amap_poi_id: value('amap_poi_id'),
|
||||
website: value('website'),
|
||||
phone: value('phone'),
|
||||
email: value('email'),
|
||||
opening_hours: hours.success ? JSON.stringify(hours.data) : '',
|
||||
image_url: value('image_url') || null,
|
||||
tags: Array.isArray(args.tags) ? args.tags.filter((tag): tag is number => Number.isInteger(tag)) : [],
|
||||
};
|
||||
}
|
||||
|
||||
function restoreDraft(form: PlaceFormData, edits: AssistantPlanEdits | undefined): PlaceFormData {
|
||||
const { lat, lng, place_notes, opening_hours, ...place } = edits?.place ?? {};
|
||||
const restored = Object.fromEntries(Object.entries(place).map(([field, value]) => [field, value ?? '']));
|
||||
return {
|
||||
...form,
|
||||
...restored,
|
||||
...(lat === undefined ? {} : { lat: String(lat ?? '') }),
|
||||
...(lng === undefined ? {} : { lng: String(lng ?? '') }),
|
||||
...(place_notes === undefined ? {} : { notes: place_notes ?? '' }),
|
||||
...(opening_hours === undefined ? {} : { opening_hours: opening_hours ? JSON.stringify(opening_hours) : '' }),
|
||||
...visitDraft(edits ?? {}),
|
||||
};
|
||||
}
|
||||
|
||||
function visitDraft({ startTime, endTime, notes, categoryId }: AssistantPlanEdits): Partial<PlaceFormData> {
|
||||
return {
|
||||
...(startTime === undefined ? {} : { place_time: startTime ?? '' }),
|
||||
...(endTime === undefined ? {} : { end_time: endTime ?? '' }),
|
||||
...(notes === undefined ? {} : { assignment_notes: notes ?? '' }),
|
||||
...(categoryId === undefined ? {} : { category_id: String(categoryId ?? '') }),
|
||||
};
|
||||
}
|
||||
|
||||
function placeValues(form: PlaceFormData): PlacePatch {
|
||||
const position = formPin(form);
|
||||
return {
|
||||
name: form.name.trim(),
|
||||
description: form.description || null,
|
||||
address: form.address || null,
|
||||
lat: position?.lat ?? null,
|
||||
lng: position?.lng ?? null,
|
||||
google_place_id: form.google_place_id || null,
|
||||
google_ftid: form.google_ftid || null,
|
||||
osm_id: form.osm_id || null,
|
||||
amap_poi_id: form.amap_poi_id || null,
|
||||
place_notes: form.notes || null,
|
||||
website: form.website.trim() || null,
|
||||
phone: form.phone?.trim() || null,
|
||||
email: form.email?.trim() || null,
|
||||
opening_hours: parsePlaceHours(form.opening_hours),
|
||||
image_url: form.image_url || null,
|
||||
tags: form.tags ?? [],
|
||||
};
|
||||
}
|
||||
|
||||
function changesOf(form: PlaceFormData, original: PlaceFormData, existing: boolean): AssistantPlanEdits {
|
||||
const edits: AssistantPlanEdits = {};
|
||||
if (form.place_time !== original.place_time) edits.startTime = form.place_time || null;
|
||||
if (form.end_time !== original.end_time) edits.endTime = form.end_time || null;
|
||||
if (form.assignment_notes !== original.assignment_notes) edits.notes = form.assignment_notes || null;
|
||||
if (!existing) {
|
||||
if (form.category_id !== original.category_id)
|
||||
edits.categoryId = form.category_id ? Number(form.category_id) : null;
|
||||
const previous = placeValues(original);
|
||||
const changed = Object.entries(placeValues(form)).filter(
|
||||
([field, value]) => JSON.stringify(previous[field as keyof PlacePatch]) !== JSON.stringify(value)
|
||||
);
|
||||
if (changed.length) edits.place = Object.fromEntries(changed);
|
||||
}
|
||||
return edits;
|
||||
}
|
||||
|
||||
export default function AssistantPlaceProposal({
|
||||
preview,
|
||||
args,
|
||||
edits,
|
||||
disabled,
|
||||
onEdit,
|
||||
onClose,
|
||||
}: {
|
||||
preview: AssistantChangePreview;
|
||||
args: unknown;
|
||||
edits: AssistantPlanEdits | undefined;
|
||||
disabled: boolean;
|
||||
onEdit: (edits: AssistantPlanEdits) => void;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const { tripId, variant } = useAssistantView();
|
||||
const phone = useIsPhone();
|
||||
const previewEdit = useAssistantStore((s) => s.previewPlanEdit);
|
||||
const categories = useTripStore((s) => s.categories);
|
||||
const dayAssignments = useTripStore((s) => (preview.dayId == null ? undefined : s.assignments[preview.dayId]));
|
||||
const currentPlace = useTripStore((s) => s.places.find((place) => place.id === preview.effect?.placeId));
|
||||
const existing = preview.verbKey === 'assignPlace';
|
||||
const [original] = useState(() => {
|
||||
const categoryId =
|
||||
preview.effect?.place?.categoryId ??
|
||||
currentPlace?.category_id ??
|
||||
categories.find((category) => category.name === planField(preview, 'category'))?.id ??
|
||||
null;
|
||||
const form = originalForm(preview, args, categoryId);
|
||||
return existing && currentPlace ? { ...form, name: currentPlace.name, address: currentPlace.address ?? '' } : form;
|
||||
});
|
||||
const [initialForm] = useState(() => restoreDraft(original, edits));
|
||||
const { toolCallId } = preview;
|
||||
const onPreview = useCallback(
|
||||
(form: PlaceFormData) => {
|
||||
if (!existing && (form.lat || form.lng) && !formPin(form)) return;
|
||||
const parsed = assistantPlanEditsSchema.safeParse(changesOf(form, original, existing));
|
||||
if (parsed.success) previewEdit(tripId, toolCallId, parsed.data);
|
||||
},
|
||||
[existing, original, previewEdit, toolCallId, tripId]
|
||||
);
|
||||
useEffect(() => () => previewEdit(tripId, toolCallId, null), [previewEdit, toolCallId, tripId]);
|
||||
const onSave = (form: PlaceFormData) => {
|
||||
if (!existing && (form.lat || form.lng) && !formPin(form)) throw new Error(t('places.saveError'));
|
||||
const parsed = assistantPlanEditsSchema.safeParse(changesOf(form, original, existing));
|
||||
if (!parsed.success) throw new Error(t('places.saveError'));
|
||||
onEdit(parsed.data);
|
||||
};
|
||||
|
||||
return (
|
||||
<PlaceFormModal
|
||||
isOpen
|
||||
onClose={onClose}
|
||||
place={null}
|
||||
tripId={tripId}
|
||||
categories={categories}
|
||||
assignmentId={null}
|
||||
dayAssignments={dayAssignments}
|
||||
isMobile={phone || variant === 'fullscreen'}
|
||||
proposal={{ initialForm, existing, dayId: preview.dayId, disabled, onPreview, onSave }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
import type { AssistantChangePreview, AssistantPlanEdits } from '@trek/shared';
|
||||
import { Check, Pencil } from 'lucide-react';
|
||||
import { lazy, Suspense, useEffect, useId, useState } from 'react';
|
||||
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { useAssistantStore } from '../../store/assistantStore';
|
||||
import { EditorField, PANEL, TEXTAREA } from '../shared/dialogParts';
|
||||
import {
|
||||
DialogButton,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogShell,
|
||||
DialogTile,
|
||||
FooterSpacer,
|
||||
NEUTRAL_TINT,
|
||||
} from '../shared/DialogShell';
|
||||
import { Tooltip } from '../shared/Tooltip';
|
||||
import { isVisitProposal, planField, proposalNote } from './assistantPlanFieldsModel';
|
||||
import { useAssistantView } from './assistantViewContext';
|
||||
|
||||
const AssistantPlaceProposal = lazy(() => import('./AssistantPlaceProposal'));
|
||||
|
||||
interface ProposalEditProps {
|
||||
preview: AssistantChangePreview;
|
||||
args?: unknown;
|
||||
edits: AssistantPlanEdits | undefined;
|
||||
disabled: boolean;
|
||||
onEdit: (patch: AssistantPlanEdits) => void;
|
||||
}
|
||||
|
||||
export default function AssistantPlanFields({ preview, args, edits, disabled, onEdit }: ProposalEditProps) {
|
||||
const { t } = useTranslation();
|
||||
const [open, setOpen] = useState(false);
|
||||
return (
|
||||
<>
|
||||
<Tooltip label={t('common.edit')} disabled={disabled}>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t('common.edit')}
|
||||
aria-haspopup="dialog"
|
||||
disabled={disabled}
|
||||
onClick={() => setOpen(true)}
|
||||
className="relative grid h-8 w-8 shrink-0 place-items-center self-start rounded-lg text-content-muted transition-colors focus-visible:ring-2 focus-visible:ring-accent enabled:hover:bg-accent enabled:hover:text-accent-text disabled:opacity-50 [@media(pointer:coarse)]:before:absolute [@media(pointer:coarse)]:before:-inset-1.5"
|
||||
>
|
||||
<Pencil size={14} aria-hidden="true" />
|
||||
</button>
|
||||
</Tooltip>
|
||||
{open &&
|
||||
(isVisitProposal(preview) ? (
|
||||
<Suspense fallback={null}>
|
||||
<AssistantPlaceProposal
|
||||
preview={preview}
|
||||
args={args}
|
||||
edits={edits}
|
||||
disabled={disabled}
|
||||
onEdit={onEdit}
|
||||
onClose={() => setOpen(false)}
|
||||
/>
|
||||
</Suspense>
|
||||
) : (
|
||||
<DayNoteEditDialog
|
||||
preview={preview}
|
||||
edits={edits}
|
||||
disabled={disabled}
|
||||
onEdit={onEdit}
|
||||
onClose={() => setOpen(false)}
|
||||
/>
|
||||
))}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function DayNoteEditDialog({ preview, edits, disabled, onEdit, onClose }: ProposalEditProps & { onClose: () => void }) {
|
||||
const { t } = useTranslation();
|
||||
const { tripId } = useAssistantView();
|
||||
const { toolCallId } = preview;
|
||||
const previewPlanEdit = useAssistantStore((s) => s.previewPlanEdit);
|
||||
const id = useId();
|
||||
const [draft, setDraft] = useState<AssistantPlanEdits>(() => edits ?? {});
|
||||
const change = (patch: AssistantPlanEdits) => setDraft((current) => ({ ...current, ...patch }));
|
||||
const note = proposalNote(preview, draft);
|
||||
const noteTitle = draft.noteTitle ?? planField(preview, 'title') ?? preview.subject;
|
||||
useEffect(() => previewPlanEdit(tripId, toolCallId, draft), [draft, previewPlanEdit, toolCallId, tripId]);
|
||||
useEffect(() => () => previewPlanEdit(tripId, toolCallId, null), [previewPlanEdit, toolCallId, tripId]);
|
||||
const noteLabel = t('assistant.change.label.content');
|
||||
const save = () => {
|
||||
if (Object.keys(draft).length > 0) onEdit(draft);
|
||||
onClose();
|
||||
};
|
||||
|
||||
return (
|
||||
<DialogShell
|
||||
labelledBy={id}
|
||||
width="narrow"
|
||||
onClose={onClose}
|
||||
header={
|
||||
<DialogHeader
|
||||
labelId={id}
|
||||
tint={NEUTRAL_TINT}
|
||||
tile={
|
||||
<DialogTile>
|
||||
<Pencil size={19} aria-hidden="true" />
|
||||
</DialogTile>
|
||||
}
|
||||
eyebrow={t('common.edit')}
|
||||
titleInput={{
|
||||
label: t('assistant.change.label.title'),
|
||||
value: noteTitle,
|
||||
required: true,
|
||||
maxLength: 500,
|
||||
readOnly: disabled,
|
||||
onChange: (noteTitle) => change({ noteTitle }),
|
||||
}}
|
||||
onClose={onClose}
|
||||
/>
|
||||
}
|
||||
footer={
|
||||
<DialogFooter>
|
||||
<FooterSpacer />
|
||||
<DialogButton onClick={onClose}>{t('common.cancel')}</DialogButton>
|
||||
<DialogButton
|
||||
variant="primary"
|
||||
icon={<Check size={15} aria-hidden="true" />}
|
||||
onClick={save}
|
||||
disabled={disabled || !noteTitle.trim()}
|
||||
>
|
||||
{t('common.save')}
|
||||
</DialogButton>
|
||||
</DialogFooter>
|
||||
}
|
||||
>
|
||||
<fieldset disabled={disabled} className={`${PANEL} m-0 min-w-0`}>
|
||||
<EditorField label={noteLabel} htmlFor={`${id}-note`}>
|
||||
<textarea
|
||||
id={`${id}-note`}
|
||||
className={TEXTAREA}
|
||||
rows={4}
|
||||
maxLength={2000}
|
||||
value={note ?? ''}
|
||||
onChange={(e) => change({ noteBody: e.target.value || null })}
|
||||
/>
|
||||
</EditorField>
|
||||
</fieldset>
|
||||
</DialogShell>
|
||||
);
|
||||
}
|
||||
@@ -7,7 +7,7 @@
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { render, screen } from '../../../tests/helpers/render';
|
||||
import { fireEvent, render, screen } from '../../../tests/helpers/render';
|
||||
import AssistantSources from './AssistantSources';
|
||||
import { messageBlocks } from './assistantParts';
|
||||
|
||||
@@ -31,7 +31,8 @@ describe('AssistantSources', () => {
|
||||
expect(screen.getByRole('link', { name: 'example.org' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-AI-SOURCES-002: an answer keeps its sources as a block of their own after its text', () => {
|
||||
it('FE-AI-SOURCES-002: bundles citations from multiple steps below the changes and keeps links with JSON titles', () => {
|
||||
const exa = 'https://exa.ai/library/places?example=test';
|
||||
const blocks = messageBlocks(
|
||||
{
|
||||
id: 'm1',
|
||||
@@ -40,12 +41,46 @@ describe('AssistantSources', () => {
|
||||
createdAt: '2026-10-23T10:00:00.000Z',
|
||||
parts: [
|
||||
{ type: 'tool-call', toolCallId: 'web-1', toolName: 'web_search', args: { query: 'x' }, result: 'searched' },
|
||||
{
|
||||
type: 'data-trek-sources',
|
||||
data: {
|
||||
sources: [
|
||||
{ url: 'https://a.example', title: 'https://a.example' },
|
||||
{ url: exa, title: '{"places":[{"id":"truncated' },
|
||||
],
|
||||
},
|
||||
},
|
||||
{ type: 'text', text: 'Eat at the harbour.' },
|
||||
{ type: 'data-trek-sources', data: { sources: [{ url: 'https://a.example', title: 'A' }] } },
|
||||
{ type: 'tool-call', toolCallId: 'w1', toolName: 'create_todo', args: {}, approval: { id: 'w1' } },
|
||||
{ type: 'data-trek-sources', data: { sources: [{ url: 'https://a.example', title: 'Harbour guide' }] } },
|
||||
],
|
||||
},
|
||||
false
|
||||
);
|
||||
expect(blocks.map((block) => block.kind)).toEqual(['steps', 'text', 'sources']);
|
||||
expect(blocks.map((block) => block.kind)).toEqual(['steps', 'text', 'change', 'sources']);
|
||||
const sources = blocks.find((block) => block.kind === 'sources')?.sources;
|
||||
expect(sources).toEqual([
|
||||
{ url: 'https://a.example', title: 'Harbour guide' },
|
||||
{ url: exa, title: '' },
|
||||
]);
|
||||
render(<AssistantSources sources={sources ?? []} />);
|
||||
expect(screen.getByRole('link', { name: 'exa.ai' })).toHaveAttribute('href', exa);
|
||||
});
|
||||
|
||||
it('shows three links by default and lets the reader expand and collapse the list', () => {
|
||||
render(
|
||||
<AssistantSources
|
||||
sources={['One', 'Two', 'Three', 'Four'].map((title) => ({ title, url: `https://example.org/${title}` }))}
|
||||
/>
|
||||
);
|
||||
expect(screen.getAllByRole('link')).toHaveLength(3);
|
||||
const more = screen.getByRole('button', { name: 'More sources' });
|
||||
expect(more).toHaveAttribute('aria-expanded', 'false');
|
||||
fireEvent.click(more);
|
||||
expect(screen.getAllByRole('link')).toHaveLength(4);
|
||||
const less = screen.getByRole('button', { name: 'Show less' });
|
||||
expect(less).toHaveAttribute('aria-expanded', 'true');
|
||||
fireEvent.click(less);
|
||||
expect(screen.getAllByRole('link')).toHaveLength(3);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
import type { AssistantSources as Sources } from '@trek/shared';
|
||||
import { Globe } from 'lucide-react';
|
||||
import { ChevronDown, Globe } from 'lucide-react';
|
||||
import { useId, useState } from 'react';
|
||||
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { Tooltip } from '../shared/Tooltip';
|
||||
|
||||
const INITIAL_COUNT = 3;
|
||||
|
||||
/** A page's host without "www.", as the chip names it; the whole address where it does not read as one. */
|
||||
function hostOf(url: string): string {
|
||||
@@ -19,30 +23,48 @@ function hostOf(url: string): string {
|
||||
*/
|
||||
export default function AssistantSources({ sources }: { sources: Sources['sources'] }) {
|
||||
const { t } = useTranslation();
|
||||
const id = useId();
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const visible = expanded ? sources : sources.slice(0, INITIAL_COUNT);
|
||||
return (
|
||||
<nav aria-label={t('assistant.sources.title')} className="flex flex-col gap-1.5">
|
||||
<span className="font-geist text-caption font-bold uppercase tracking-[.08em] text-content-faint">
|
||||
{t('assistant.sources.title')}
|
||||
</span>
|
||||
<ul className="m-0 flex list-none flex-wrap gap-1.5 p-0">
|
||||
{sources.map((source) => (
|
||||
<li key={source.url} className="min-w-0 max-w-full">
|
||||
<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,10 @@ const h = vi.hoisted(() => {
|
||||
insets: number[] = [];
|
||||
kicks = 0;
|
||||
disposed = false;
|
||||
static create(opts: GlobeEngineOptions): FakeEngine {
|
||||
return new FakeEngine(opts);
|
||||
}
|
||||
|
||||
constructor(opts: GlobeEngineOptions) {
|
||||
if (state.failNext !== null) {
|
||||
const err = state.failNext;
|
||||
|
||||
@@ -54,7 +54,7 @@ const AtlasGlobe = forwardRef<AtlasGlobeHandle, AtlasGlobeProps>(function AtlasG
|
||||
if (!canvas) return;
|
||||
let engine: GlobeEngine;
|
||||
try {
|
||||
engine = new GlobeEngine({
|
||||
engine = GlobeEngine.create({
|
||||
canvas,
|
||||
fetchJson: (p) => propsRef.current.fetchJson(p),
|
||||
theme: globeTheme(propsRef.current.dark),
|
||||
|
||||
@@ -210,7 +210,7 @@ async function start(o: StartOptions = {}) {
|
||||
onSelect: vi.fn(),
|
||||
onFrame: vi.fn(),
|
||||
};
|
||||
const engine = new mod.GlobeEngine({ canvas, fetchJson, theme: o.theme ?? LIGHT, initial: o.initial, ...cb });
|
||||
const engine = mod.GlobeEngine.create({ canvas, fetchJson, theme: o.theme ?? LIGHT, initial: o.initial, ...cb });
|
||||
engines.push(engine);
|
||||
return {
|
||||
mod,
|
||||
@@ -310,7 +310,7 @@ describe('GlobeEngine boot', () => {
|
||||
const otherFetch = vi.fn(async (): Promise<unknown> => null);
|
||||
const canvas = document.createElement('canvas');
|
||||
const onReady = vi.fn();
|
||||
const second = new first.mod.GlobeEngine({ canvas, fetchJson: otherFetch, theme: LIGHT, onReady });
|
||||
const second = first.mod.GlobeEngine.create({ canvas, fetchJson: otherFetch, theme: LIGHT, onReady });
|
||||
engines.push(second);
|
||||
await flush();
|
||||
expect(otherFetch).not.toHaveBeenCalled();
|
||||
@@ -345,7 +345,7 @@ describe('GlobeEngine boot retries', () => {
|
||||
});
|
||||
const onError = vi.fn();
|
||||
engines.push(
|
||||
new mod.GlobeEngine({ canvas: document.createElement('canvas'), fetchJson: fail, theme: LIGHT, onError })
|
||||
mod.GlobeEngine.create({ canvas: document.createElement('canvas'), fetchJson: fail, theme: LIGHT, onError })
|
||||
);
|
||||
const delays: number[] = [];
|
||||
for (let i = 0; i < 4; i++) {
|
||||
@@ -364,7 +364,7 @@ describe('GlobeEngine boot retries', () => {
|
||||
const ok = vi.fn(async (p: string): Promise<unknown> => files[p]);
|
||||
const onReady = vi.fn();
|
||||
engines.push(
|
||||
new mod.GlobeEngine({ canvas: document.createElement('canvas'), fetchJson: ok, theme: LIGHT, onReady })
|
||||
mod.GlobeEngine.create({ canvas: document.createElement('canvas'), fetchJson: ok, theme: LIGHT, onReady })
|
||||
);
|
||||
await flush();
|
||||
expect(ok).toHaveBeenCalledWith('manifest');
|
||||
@@ -381,7 +381,9 @@ describe('GlobeEngine boot retries', () => {
|
||||
return files[p];
|
||||
});
|
||||
const onReady = vi.fn();
|
||||
engines.push(new mod.GlobeEngine({ canvas: document.createElement('canvas'), fetchJson, theme: LIGHT, onReady }));
|
||||
engines.push(
|
||||
mod.GlobeEngine.create({ canvas: document.createElement('canvas'), fetchJson, theme: LIGHT, onReady })
|
||||
);
|
||||
await flush();
|
||||
expect(pending.map((t) => t.ms)).toEqual([1000]);
|
||||
pending[0].cb();
|
||||
|
||||
@@ -164,7 +164,13 @@ export class GlobeEngine {
|
||||
private sun: [number, number, number] = sunVector(new Date());
|
||||
private sunAt = 0;
|
||||
|
||||
constructor(opts: GlobeEngineOptions) {
|
||||
static create(opts: GlobeEngineOptions): GlobeEngine {
|
||||
const engine = new GlobeEngine(opts);
|
||||
void engine.boot();
|
||||
return engine;
|
||||
}
|
||||
|
||||
private constructor(opts: GlobeEngineOptions) {
|
||||
this.opts = opts;
|
||||
this.theme = opts.theme;
|
||||
Object.assign(this.cam, opts.initial ?? {});
|
||||
@@ -187,7 +193,6 @@ export class GlobeEngine {
|
||||
this.resizeObs.observe(opts.canvas);
|
||||
opts.canvas.addEventListener('webglcontextlost', this.onContextLost);
|
||||
this.resize();
|
||||
void this.boot();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- loading
|
||||
|
||||
@@ -14,7 +14,7 @@ export function hexToRgb(hex: string): Rgb {
|
||||
.map((c) => c + c)
|
||||
.join('')
|
||||
: h.slice(0, 6);
|
||||
const n = parseInt(full, 16);
|
||||
const n = Number.parseInt(full, 16);
|
||||
if (Number.isNaN(n)) return [0.5, 0.5, 0.5];
|
||||
return [((n >> 16) & 255) / 255, ((n >> 8) & 255) / 255, (n & 255) / 255];
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@ import { amountToInputString, currencyDecimals } from '../../utils/formatters'
|
||||
import { localIsoDate } from '../../utils/localDate'
|
||||
import type { ExpensePrefill } from './CostsPanel'
|
||||
import type { BudgetItem } from '../../types'
|
||||
import type { CostsSettlement } from './costsModel'
|
||||
|
||||
// The split and receipt fields guard their own precision on every keystroke, so the
|
||||
// guard has to follow the currency: a three-decimal one (KWD, BHD, …) seeds three
|
||||
@@ -329,3 +330,24 @@ export function expenseEditorFor(
|
||||
if (receipt) return { key: 'receipt', editing: null, prefill: receipt, close: closeReceipt }
|
||||
return null
|
||||
}
|
||||
|
||||
/** Expenses and settle-up payments grouped newest day first in the Costs ledger. */
|
||||
export function groupLedgerByDay(expenses: readonly BudgetItem[], payments: readonly CostsSettlement[], locale: string, noDate: string) {
|
||||
const entries = [
|
||||
...expenses.map(e => ({ kind: 'expense' as const, date: e.expense_date || '', e })),
|
||||
...payments.map(s => ({ kind: 'payment' as const, date: settlementDate(s), s })),
|
||||
].sort((a, b) => b.date.localeCompare(a.date))
|
||||
const groups = new Map<string, typeof entries>()
|
||||
for (const entry of entries) {
|
||||
let label = noDate
|
||||
if (entry.date) {
|
||||
try {
|
||||
label = new Date(entry.date + 'T00:00:00Z').toLocaleDateString(locale, { weekday: 'short', day: 'numeric', month: 'short', timeZone: 'UTC' })
|
||||
} catch { label = entry.date }
|
||||
}
|
||||
const group = groups.get(label)
|
||||
if (group) group.push(entry)
|
||||
else groups.set(label, [entry])
|
||||
}
|
||||
return [...groups].map(([day, entries]) => ({ day, entries }))
|
||||
}
|
||||
|
||||
@@ -944,13 +944,13 @@ describe('CostsPanel — overview', () => {
|
||||
expect(labels).toEqual(['Food & drink', 'Transport'])
|
||||
expect(within(breakdown).getByText('90 €')).toBeInTheDocument()
|
||||
expect(within(breakdown).getByText('30 €')).toBeInTheDocument()
|
||||
})
|
||||
});
|
||||
|
||||
it('FE-W5COSTS-006: an empty trip shows the empty ledger and the empty breakdown', async () => {
|
||||
it('FE-W5COSTS-006: an empty trip shows the empty ledger without a total or category breakdown', async () => {
|
||||
mount([])
|
||||
|
||||
expect(await screen.findByText('No expenses yet. Add your first one.')).toBeInTheDocument()
|
||||
expect(screen.getByText('No expenses yet.')).toBeInTheDocument()
|
||||
expect(await screen.findByText('No expenses yet. Add your first one.')).toBeInTheDocument();
|
||||
expect(screen.queryByRole('region', { name: 'Total trip spend' })).toBeNull();
|
||||
expect(screen.queryByRole('region', { name: 'By category' })).toBeNull();
|
||||
expect(screen.getByText("Everyone's square")).toBeInTheDocument()
|
||||
})
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ import { CustomDatePicker } from '../shared/CustomDateTimePicker'
|
||||
import { useReceiptScan } from './useReceiptScan'
|
||||
import { ReceiptScanModal } from './ReceiptScanModal'
|
||||
import { SPLIT_COLORS } from './BudgetPanel.constants'
|
||||
import { finalBudgetFor, finalBudgetSources, formerParticipantRows, NOTE_MAX, paidByUser, readUserNote, settlementDate } from './CostsPanel.helpers'
|
||||
import { groupLedgerByDay, finalBudgetFor, finalBudgetSources, formerParticipantRows, NOTE_MAX, paidByUser, readUserNote } from './CostsPanel.helpers'
|
||||
import { COST_CATEGORY_LIST, catMeta } from './costsCategories'
|
||||
import {
|
||||
baseTotal as baseTotalOf, booked as bookedAmount, isUnfinished as isUnfinishedModel, lineOf as lineOfModel, memberShareOf,
|
||||
@@ -52,12 +52,6 @@ interface CostsPanelProps {
|
||||
tripMembers?: TripMember[]
|
||||
}
|
||||
|
||||
// One row in the unified Costs ledger — either an expense or a settle-up payment,
|
||||
// carrying the date used to group it by day.
|
||||
type LedgerEntry =
|
||||
| { kind: 'expense'; date: string; e: BudgetItem }
|
||||
| { kind: 'payment'; date: string; s: Settlement }
|
||||
|
||||
const round2 = (n: number) => Math.round(n * 100) / 100
|
||||
const FIELD_H = 40 // shared height for the amount / currency / day row in the modal
|
||||
const COSTS_VIEW_KEY = 'trek:costs-view'
|
||||
@@ -66,6 +60,7 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
const { trip, budgetItems, deleteBudgetItem, loadBudgetItems, addBudgetItem, updateBudgetItem } = useTripStore()
|
||||
const can = useCanDo()
|
||||
const canEdit = can('budget_edit', trip)
|
||||
const hasExpenses = budgetItems.length > 0
|
||||
const receiptScan = useReceiptScan(tripId, canEdit)
|
||||
const toast = useToast()
|
||||
const { t, locale } = useTranslation()
|
||||
@@ -143,27 +138,12 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
// Nobody paid, so nobody owes (#2225).
|
||||
const myShareOf = (e: BudgetItem) => settledShareOf(e, ctx)
|
||||
|
||||
// ── day grouping ─────────────────────────────────────────────────────────
|
||||
const dayGroups = useMemo(() => {
|
||||
const entries: LedgerEntry[] = [
|
||||
...filtered.map(e => ({ kind: 'expense' as const, date: e.expense_date || '', e })),
|
||||
...filteredSettlements.map(s => ({ kind: 'payment' as const, date: settlementDate(s), s })),
|
||||
]
|
||||
const labelOf = (date: string) => {
|
||||
if (!date) return t('costs.noDate')
|
||||
try { return new Date(date + 'T00:00:00Z').toLocaleDateString(locale, { weekday: 'short', day: 'numeric', month: 'short', timeZone: 'UTC' }) } catch { return date }
|
||||
}
|
||||
// Newest day first; within a day, expenses before payments (insertion order).
|
||||
const sorted = entries.slice().sort((a, b) => (b.date || '').localeCompare(a.date || ''))
|
||||
const groups: { day: string; entries: LedgerEntry[] }[] = []
|
||||
for (const en of sorted) {
|
||||
const day = labelOf(en.date)
|
||||
let g = groups.find(x => x.day === day)
|
||||
if (!g) { g = { day, entries: [] }; groups.push(g) }
|
||||
g.entries.push(en)
|
||||
}
|
||||
return groups
|
||||
}, [filtered, filteredSettlements, locale, t])
|
||||
const noDate = t('costs.noDate')
|
||||
const dayGroups = useMemo(() => groupLedgerByDay(filtered, filteredSettlements, locale, noDate), [filtered, filteredSettlements, locale, noDate])
|
||||
const emptyLedger = !hasExpenses && dayGroups.length === 0
|
||||
const mobileEmptyLedger = emptyLedger
|
||||
? <EmptyState scene="costs" title={t('costs.emptyText')} />
|
||||
: <div className="text-content-faint" style={{ textAlign: 'center', padding: '36px 16px', fontSize: 'calc(13px * var(--fs-scale-body, 1))' }}>{search ? t('costs.noMatch') : t('costs.emptyText')}</div>
|
||||
|
||||
// ── filter dropdown options (category + single day) ──────────────────────
|
||||
const categoryOptions = useMemo(() => [
|
||||
@@ -285,8 +265,8 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
}} />
|
||||
|
||||
{/* ── Summary cards; with nothing to split (#2689) the total stands alone ── */}
|
||||
{!splitting ? <div style={{ marginBottom: 36 }}>{totalCard}</div> : (
|
||||
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, minmax(0, 1fr))', gap: 16, marginBottom: 36 }} className="costs-summary">
|
||||
{!splitting ? (hasExpenses && <div style={{ marginBottom: 36 }}>{totalCard}</div>) : (
|
||||
<div style={{ display: 'grid', gridTemplateColumns: hasExpenses ? 'repeat(4, minmax(0, 1fr))' : 'repeat(3, minmax(0, 1fr))', gap: 16, marginBottom: 36 }} className="costs-summary">
|
||||
<SummaryCard label={t('costs.youOwe')} sub={t('costs.youOweSub')} amount={balancesKnown ? totals.owe : null} currency={base} locale={locale}
|
||||
icon={<ArrowDown size={18} />} tone="owe" failed={settlementError}
|
||||
foot={totals.owe > 0.01
|
||||
@@ -302,18 +282,17 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
foot={totals.outstandingCount > 0
|
||||
? <span><b>{totals.outstandingCount}</b> {t('costs.outstandingItems', { count: totals.outstandingCount })}</span>
|
||||
: settledUp && <span className="text-content-faint">{t('costs.allSettled')}</span>} />
|
||||
{totalCard}
|
||||
{hasExpenses && totalCard}
|
||||
</div>)}
|
||||
|
||||
{/* ── Main grid ── */}
|
||||
{/* The same four columns as the cards above: the ledger takes three, the
|
||||
sidebar the last, so it lines up with the total-spend card. */}
|
||||
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, minmax(0, 1fr))', columnGap: 16, rowGap: 32, alignItems: 'start' }} className="costs-grid">
|
||||
{/* expenses */}
|
||||
<div className="costs-main" style={{ gridColumn: 'span 3', minWidth: 0 }}>
|
||||
<div className="costs-main" style={{ gridColumn: emptyLedger ? '1 / -1' : 'span 3', minWidth: 0 }}>
|
||||
|
||||
{dayBanner}
|
||||
{view === 'table' ? (
|
||||
{emptyLedger ? <EmptyState scene="costs" title={t('costs.emptyText')} /> : view === 'table' && hasExpenses ? (
|
||||
filtered.length === 0 && budgetItems.length > 0 ? (
|
||||
<div className="text-content-faint" style={{ textAlign: 'center', padding: '60px 20px' }}>{t('costs.noMatch')}</div>
|
||||
) : (
|
||||
@@ -379,14 +358,14 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
</>}
|
||||
|
||||
{/* by category; the table view sums up four ways instead */}
|
||||
{view === 'table' ? (
|
||||
{hasExpenses && (view === 'table' ? (
|
||||
<CostsTableSummary items={filtered} baseTotal={baseTotal} toBase={booked} fmt={v => fmt(v)} personName={personName} splitting={splitting} />
|
||||
) : (
|
||||
<section aria-label={t('costs.byCategory')} className={SIDE_CARD}>
|
||||
{sideHead(t('costs.byCategory'))}
|
||||
<div className="px-4 py-4">{categoryBars}</div>
|
||||
</section>
|
||||
)}
|
||||
))}
|
||||
<CostsModeCard trip={trip} memberCount={people.length} canEdit={canEdit} className={SIDE_CARD} />
|
||||
</div>
|
||||
</div>
|
||||
@@ -492,8 +471,7 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
function MobileBody() {
|
||||
return (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 16, paddingTop: 8 }}>
|
||||
{/* Total card */}
|
||||
<section style={{ background: 'linear-gradient(135deg,#1f2937,#111827)', color: '#fff', borderRadius: 22, padding: '20px 20px 16px', boxShadow: '0 8px 24px -8px rgba(0,0,0,0.28)' }}>
|
||||
{hasExpenses ? <section style={{ background: 'linear-gradient(135deg,#1f2937,#111827)', color: '#fff', borderRadius: 22, padding: '20px 20px 16px', boxShadow: '0 8px 24px -8px rgba(0,0,0,0.28)' }}>
|
||||
<div style={{ fontSize: 'calc(11.5px * var(--fs-scale-caption, 1))', textTransform: 'uppercase', letterSpacing: '0.12em', color: 'rgba(255,255,255,0.6)', fontWeight: 600 }}>{t('costs.totalSpend')}</div>
|
||||
<div style={{ fontSize: 'calc(44px * var(--fs-scale-title, 1))', fontWeight: 700, letterSpacing: '-0.04em', lineHeight: 1, marginTop: 8, display: 'flex', alignItems: 'baseline' }}>{bigMoney(totals.totalSpend, 24, 'rgba(255,255,255,0.6)')}</div>
|
||||
{splitting && <div style={{ display: 'flex', gap: 18, marginTop: 12, fontSize: 'calc(12px * var(--fs-scale-body, 1))', color: 'rgba(255,255,255,0.6)', flexWrap: 'wrap' }}>
|
||||
@@ -512,7 +490,10 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
<ScanLine size={16} /> {t('costs.scan.button')}
|
||||
</button>
|
||||
)}
|
||||
</section>
|
||||
</section> : <div className="flex flex-wrap justify-end gap-2">
|
||||
{receiptScan.offered && <DialogButton onClick={receiptScan.open}>{t('costs.scan.button')}</DialogButton>}
|
||||
{canEdit && <DialogButton variant="primary" onClick={() => { setEditing(null); setModalOpen(true) }}>{t('costs.addExpense')}</DialogButton>}
|
||||
</div>}
|
||||
|
||||
{/* Owe / Owed, outstanding and settling up: only with something to split (#2689) */}
|
||||
{splitting && <>
|
||||
@@ -583,7 +564,7 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
</div>
|
||||
{dayBanner}
|
||||
{dayGroups.length === 0
|
||||
? <div className="text-content-faint" style={{ textAlign: 'center', padding: '36px 16px', fontSize: 'calc(13px * var(--fs-scale-body, 1))' }}>{search ? t('costs.noMatch') : t('costs.emptyText')}</div>
|
||||
? mobileEmptyLedger
|
||||
: dayGroups.map(g => {
|
||||
const dtot = g.entries.reduce((a, en) => en.kind === 'expense' ? a + baseTotal(en.e) : a, 0)
|
||||
return (
|
||||
@@ -610,11 +591,10 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
</div>
|
||||
</>}
|
||||
|
||||
{/* By category */}
|
||||
<div className={cardCls} style={{ borderRadius: 18, padding: 16 }}>
|
||||
{hasExpenses && <div className={cardCls} style={{ borderRadius: 18, padding: 16 }}>
|
||||
<div className={labelCls} style={{ marginBottom: 14 }}>{t('costs.byCategory')}</div>
|
||||
{categoryBars}
|
||||
</div>
|
||||
</div>}
|
||||
<CostsModeCard trip={trip} memberCount={people.length} canEdit={canEdit} className={`${cardCls} rounded-[18px]`} />
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { focusRevealedEditor } from '../shared/dialogFocus'
|
||||
import { useMemo, useRef, useState, type KeyboardEvent, type ReactNode } from 'react'
|
||||
import { ChevronDown, Lock, Pencil, Plus, Trash2 } from 'lucide-react'
|
||||
import { useTranslation } from '../../i18n'
|
||||
@@ -307,7 +308,7 @@ function TextInput({ value, onSave, onCancel, label, numeric = false }: {
|
||||
if (ev.key === 'Escape') { ev.preventDefault(); ev.stopPropagation(); finish(onCancel) }
|
||||
}
|
||||
return (
|
||||
<input autoFocus type="text" value={draft} aria-label={label} inputMode={numeric ? 'decimal' : undefined}
|
||||
<input ref={focusRevealedEditor} type="text" value={draft} aria-label={label} inputMode={numeric ? 'decimal' : undefined}
|
||||
onChange={ev => setDraft(ev.target.value)} onKeyDown={onKey} onBlur={() => finish(() => onSave(draft))}
|
||||
className={`${INPUT} ${numeric ? 'text-center tabular-nums' : ''}`} />
|
||||
)
|
||||
|
||||
@@ -197,7 +197,7 @@ function FilterMenu(f: CostsFilterProps & { splitting: boolean }) {
|
||||
</button>
|
||||
</Tooltip>
|
||||
{open && (
|
||||
<div role="menu" onKeyDown={e => { if (e.key === 'Escape') close() }} className="absolute end-0 top-11 z-30" style={{ ...POPOVER, width: 310 }}>
|
||||
<div role="menu" tabIndex={-1} onKeyDown={e => { if (e.key === 'Escape') close() }} className="absolute end-0 top-11 z-30" style={{ ...POPOVER, width: 310 }}>
|
||||
{f.splitting && <>
|
||||
<div className="mx-1.5 mb-1 mt-1.5 flex rounded-[10px] bg-surface-tertiary p-[3px]">
|
||||
{owners.map(([o, label]) => (
|
||||
|
||||
@@ -1,30 +1,22 @@
|
||||
import { cloneElement, CSSProperties, FormEvent, ReactElement, useEffect, useId, useRef, useState } from 'react'
|
||||
import type { CollabLink } from '@trek/shared'
|
||||
import { focusRevealedEditor } from '../shared/dialogFocus'
|
||||
import { cloneElement, CSSProperties, FormEvent, ReactElement, useId, useState } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { ExternalLink, Link2, Pencil, Pin, Plus, Trash2, X } from 'lucide-react'
|
||||
import CollabPanelHead, { HEAD_ACTION } from './CollabPanelHead'
|
||||
import { DialogButton, DialogFooter, DialogHeader, DialogShell, DialogTile, FooterSpacer, NEUTRAL_TINT } from '../shared/DialogShell'
|
||||
import { EditorField, INPUT } from '../shared/dialogParts'
|
||||
import { useIsPhone } from '../../mobile/useIsPhone'
|
||||
import { collabApi } from '../../api/client'
|
||||
import { addListener, removeListener } from '../../api/websocket'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { useCanDo } from '../../store/permissionsStore'
|
||||
import { useTripStore } from '../../store/tripStore'
|
||||
import ConfirmDialog from '../shared/ConfirmDialog'
|
||||
import EmptyState from '../shared/EmptyState'
|
||||
import { Tooltip } from '../shared/Tooltip'
|
||||
import { useToast } from '../shared/Toast'
|
||||
import { offlineOr } from '../../utils/needsConnection'
|
||||
import { collabLinkHost, useCollabLinks } from './useCollabLinks'
|
||||
|
||||
const FONT = "var(--font-system)"
|
||||
|
||||
interface CollabLink {
|
||||
id: number
|
||||
title: string
|
||||
url: string
|
||||
pinned: boolean | number
|
||||
}
|
||||
|
||||
// The glyph holds the place until a favicon has really arrived: a host that never
|
||||
// answers, or answers with a blank pixel, left the chip with an empty square.
|
||||
function LinkIcon({ url }: { url: string }) {
|
||||
@@ -55,10 +47,6 @@ function ChipTip({ label, phone, children }: { label: string; phone: boolean; ch
|
||||
return phone ? cloneElement(children, { title: label }) : <Tooltip label={label}>{children}</Tooltip>
|
||||
}
|
||||
|
||||
function hostOf(url: string): string {
|
||||
try { return new URL(url).hostname.replace(/^www\./, '') } catch { return url }
|
||||
}
|
||||
|
||||
/**
|
||||
* The add and edit form as a modal, like the poll and note panels next to it.
|
||||
* Inline it pushed the list down and gave the panel a second header, which is
|
||||
@@ -147,7 +135,7 @@ function LinkModal({ link, onClose, onSave }: { link?: CollabLink; onClose: () =
|
||||
<div style={{ padding: '14px 16px 16px', display: 'flex', flexDirection: 'column', gap: 12 }}>
|
||||
<div>
|
||||
<label htmlFor="collab-link-title" style={{ ...label, display: 'block' }}>{t('collab.links.titlePlaceholder')}</label>
|
||||
<input id="collab-link-title" value={title} onChange={e => setTitle(e.target.value)} placeholder={t('collab.links.titlePlaceholder')} autoFocus style={field} />
|
||||
<input id="collab-link-title" value={title} onChange={e => setTitle(e.target.value)} placeholder={t('collab.links.titlePlaceholder')} ref={focusRevealedEditor} style={field} />
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="collab-link-url" style={{ ...label, display: 'block' }}>{t('collab.links.urlPlaceholder')}</label>
|
||||
@@ -172,101 +160,11 @@ export default function CollabLinks({ tripId }: { tripId: number }) {
|
||||
const isPhone = useIsPhone()
|
||||
const trip = useTripStore(s => s.trip)
|
||||
const canEdit = useCanDo()('collab_edit', trip)
|
||||
const toast = useToast()
|
||||
const [links, setLinks] = useState<CollabLink[]>([])
|
||||
const { links, save, toggle, remove } = useCollabLinks(tripId)
|
||||
const [showForm, setShowForm] = useState(false)
|
||||
const [editing, setEditing] = useState<CollabLink | null>(null)
|
||||
const [pendingDeleteId, setPendingDeleteId] = useState<number | null>(null)
|
||||
|
||||
// Both are new objects on every render, so depending on them would reload the
|
||||
// list after each keystroke and drop a link that was just added back out of it.
|
||||
const toastRef = useRef(toast)
|
||||
toastRef.current = toast
|
||||
const tRef = useRef(t)
|
||||
tRef.current = t
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
collabApi.getLinks(tripId)
|
||||
.then(d => { if (!cancelled) setLinks(d.links || []) })
|
||||
.catch(err => {
|
||||
if (cancelled) return
|
||||
console.error('Failed to load collab links:', err)
|
||||
toastRef.current.error(tRef.current('common.error'))
|
||||
})
|
||||
return () => { cancelled = true }
|
||||
}, [tripId])
|
||||
|
||||
// Live sync, the same shape the notes panel uses. Without it the three
|
||||
// collab:link events the server broadcasts would arrive nowhere and a link
|
||||
// somebody else added would only appear on the next reload.
|
||||
useEffect(() => {
|
||||
if (!tripId) return
|
||||
const handler = (msg: { type?: string; tripId?: number | string; link?: CollabLink; linkId?: number }) => {
|
||||
// The panel is not remounted on a trip change, so an event still in
|
||||
// flight from the trip we just left must not land in this list.
|
||||
if (String(msg?.tripId) !== String(tripId)) return
|
||||
if (msg.type === 'collab:link:created' && msg.link) {
|
||||
setLinks(prev => prev.some(l => l.id === msg.link!.id) ? prev : [msg.link!, ...prev])
|
||||
}
|
||||
if (msg.type === 'collab:link:updated' && msg.link) {
|
||||
setLinks(prev => prev
|
||||
.map(l => l.id === msg.link!.id ? { ...l, ...msg.link! } : l)
|
||||
.sort((a, b) => Number(b.pinned) - Number(a.pinned)))
|
||||
}
|
||||
if (msg.type === 'collab:link:deleted' && msg.linkId) {
|
||||
setLinks(prev => prev.filter(l => l.id !== msg.linkId))
|
||||
}
|
||||
}
|
||||
addListener(handler)
|
||||
return () => removeListener(handler)
|
||||
}, [tripId])
|
||||
|
||||
// Every write says something when it fails. Silence left the pin looking
|
||||
// unchanged and the delete looking ignored, with an unhandled rejection in
|
||||
// the console as the only trace.
|
||||
const add = async (data: { title: string; url: string }) => {
|
||||
try {
|
||||
const d = await collabApi.createLink(tripId, data)
|
||||
setLinks(v => [d.link, ...v])
|
||||
} catch (err) {
|
||||
console.error('Failed to add collab link:', err)
|
||||
toast.error(offlineOr(t, t('common.error')))
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
const toggle = async (link: CollabLink) => {
|
||||
try {
|
||||
const d = await collabApi.updateLink(tripId, link.id, { pinned: !link.pinned })
|
||||
setLinks(v => v.map(x => x.id === link.id ? d.link : x).sort((a, b) => Number(b.pinned) - Number(a.pinned)))
|
||||
} catch (err) {
|
||||
console.error('Failed to pin collab link:', err)
|
||||
toast.error(offlineOr(t, t('common.error')))
|
||||
}
|
||||
}
|
||||
|
||||
const edit = async (link: CollabLink, data: { title: string; url: string }) => {
|
||||
try {
|
||||
const d = await collabApi.updateLink(tripId, link.id, data)
|
||||
setLinks(v => v.map(x => x.id === link.id ? d.link : x))
|
||||
} catch (err) {
|
||||
console.error('Failed to edit collab link:', err)
|
||||
toast.error(offlineOr(t, t('common.error')))
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
const remove = async (id: number) => {
|
||||
try {
|
||||
await collabApi.deleteLink(tripId, id)
|
||||
setLinks(v => v.filter(x => x.id !== id))
|
||||
} catch (err) {
|
||||
console.error('Failed to delete collab link:', err)
|
||||
toast.error(offlineOr(t, t('common.error')))
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={{ height: '100%', display: 'flex', flexDirection: 'column', fontFamily: FONT }}>
|
||||
{/* Header: the desktop's head band; the phone keeps its own */}
|
||||
@@ -315,7 +213,7 @@ export default function CollabLinks({ tripId }: { tripId: number }) {
|
||||
<LinkIcon key={link.url} url={link.url} />
|
||||
<span className="collab-link-chip__text">
|
||||
<span className="collab-link-chip__title">{link.title}</span>
|
||||
<span className="collab-link-chip__host">{hostOf(link.url)}</span>
|
||||
<span className="collab-link-chip__host">{collabLinkHost(link.url)}</span>
|
||||
</span>
|
||||
</a>
|
||||
</ChipTip>
|
||||
@@ -345,8 +243,8 @@ export default function CollabLinks({ tripId }: { tripId: number }) {
|
||||
</div>
|
||||
|
||||
{/* Create and edit modals */}
|
||||
{showForm && <LinkModal onClose={() => setShowForm(false)} onSave={add} />}
|
||||
{editing && <LinkModal key={editing.id} link={editing} onClose={() => setEditing(null)} onSave={data => edit(editing, data)} />}
|
||||
{showForm && <LinkModal onClose={() => setShowForm(false)} onSave={save} />}
|
||||
{editing && <LinkModal key={editing.id} link={editing} onClose={() => setEditing(null)} onSave={data => save(data, editing.id)} />}
|
||||
|
||||
{/* The delete is shared: the link goes for every member, and on the phone the
|
||||
button is a thumb's width from pin. Same guard as the notes panel. */}
|
||||
|
||||
@@ -118,7 +118,7 @@ function CreatePollModal({ onClose, onCreate, t }: CreatePollModalProps) {
|
||||
)}
|
||||
>
|
||||
<EditorField label={t('collab.polls.question')} hint={t('collab.polls.markdownHint')}>
|
||||
<textarea autoFocus rows={4} value={question} onChange={e => setQuestion(e.target.value)} placeholder={t('collab.polls.questionPlaceholder')} className={`${TEXTAREA} resize-y`} />
|
||||
<textarea data-initial-focus rows={4} value={question} onChange={e => setQuestion(e.target.value)} placeholder={t('collab.polls.questionPlaceholder')} className={`${TEXTAREA} resize-y`} />
|
||||
</EditorField>
|
||||
|
||||
<EditorField label={t('collab.polls.options')}>
|
||||
|
||||
@@ -51,6 +51,9 @@ export function useCollabChatData({
|
||||
}: CollabChatDataOptions) {
|
||||
const [messages, setMessages] = useState<ChatMessage[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [loadError, setLoadError] = useState(false);
|
||||
const [loadAttempt, setLoadAttempt] = useState(0);
|
||||
const retryLoad = useCallback(() => setLoadAttempt((attempt) => attempt + 1), []);
|
||||
const [hasMore, setHasMore] = useState(false);
|
||||
const [loadingMore, setLoadingMore] = useState(false);
|
||||
const [text, setText] = useState('');
|
||||
@@ -96,6 +99,7 @@ export function useCollabChatData({
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
setLoading(true);
|
||||
setLoadError(false);
|
||||
collabApi
|
||||
.getMessages(tripId)
|
||||
.then((data: MessagesResponse) => {
|
||||
@@ -107,12 +111,14 @@ export function useCollabChatData({
|
||||
setTimeout(() => scrollToBottom(), 30);
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) setLoading(false);
|
||||
if (cancelled) return;
|
||||
setLoadError(true);
|
||||
setLoading(false);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [tripId, scrollToBottom]);
|
||||
}, [tripId, loadAttempt, scrollToBottom]);
|
||||
|
||||
useEffect(() => {
|
||||
const handler = (event: Record<string, unknown>) => {
|
||||
@@ -259,6 +265,8 @@ export function useCollabChatData({
|
||||
messages,
|
||||
setMessages,
|
||||
loading,
|
||||
loadError,
|
||||
retryLoad,
|
||||
setLoading,
|
||||
hasMore,
|
||||
setHasMore,
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
import type { CollabLink } from '@trek/shared';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { collabLinkRepo, type LinkFields } from '../../repo/collabLinkRepo';
|
||||
import { offlineOr } from '../../utils/needsConnection';
|
||||
import { useToast } from '../shared/Toast';
|
||||
|
||||
type LinksState = { tripId: number; links: CollabLink[]; status: 'loading' | 'ready' | 'error' };
|
||||
|
||||
const EMPTY_LINKS: CollabLink[] = [];
|
||||
|
||||
export function collabLinkHost(url: string): string {
|
||||
try {
|
||||
return new URL(url).hostname.replace(/^www\./, '');
|
||||
} catch {
|
||||
return url;
|
||||
}
|
||||
}
|
||||
|
||||
function insertLink(links: CollabLink[], link: CollabLink): CollabLink[] {
|
||||
return links.some((row) => row.id === link.id) ? links : [link, ...links];
|
||||
}
|
||||
|
||||
function updateLink(links: CollabLink[], link: CollabLink): CollabLink[] {
|
||||
return links
|
||||
.map((row) => (row.id === link.id ? { ...row, ...link } : row))
|
||||
.sort((a, b) => Number(b.pinned) - Number(a.pinned));
|
||||
}
|
||||
|
||||
export function useCollabLinks(tripId: number) {
|
||||
const { t } = useTranslation();
|
||||
const toast = useToast();
|
||||
const [state, setState] = useState<LinksState>({ tripId, links: EMPTY_LINKS, status: 'loading' });
|
||||
const [attempt, setAttempt] = useState(0);
|
||||
const reportLoadError = useRef(() => toast.error(t('common.error')));
|
||||
reportLoadError.current = () => toast.error(t('common.error'));
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
const changes: Array<(links: CollabLink[]) => CollabLink[]> = [];
|
||||
let reading = true;
|
||||
setState((current) => ({
|
||||
tripId,
|
||||
links: current.tripId === tripId ? current.links : EMPTY_LINKS,
|
||||
status: 'loading',
|
||||
}));
|
||||
|
||||
const handler = (msg: { type?: string; tripId?: number | string; link?: CollabLink; linkId?: number }) => {
|
||||
if (String(msg.tripId) !== String(tripId)) return;
|
||||
const { link, linkId } = msg;
|
||||
const change =
|
||||
msg.type === 'collab:link:created' && link
|
||||
? (links: CollabLink[]) => insertLink(links, link)
|
||||
: msg.type === 'collab:link:updated' && link
|
||||
? (links: CollabLink[]) => updateLink(links, link)
|
||||
: msg.type === 'collab:link:deleted' && linkId
|
||||
? (links: CollabLink[]) => links.filter((row) => row.id !== linkId)
|
||||
: null;
|
||||
if (!change) return;
|
||||
if (reading) changes.push(change);
|
||||
setState((current) => (current.tripId === tripId ? { ...current, links: change(current.links) } : current));
|
||||
};
|
||||
|
||||
const unsubscribe = collabLinkRepo.subscribe(handler);
|
||||
void collabLinkRepo.list(tripId).then(
|
||||
(data) => {
|
||||
if (cancelled) return;
|
||||
reading = false;
|
||||
const links = changes.reduce((rows, change) => change(rows), data.links || []);
|
||||
setState({ tripId, links, status: 'ready' });
|
||||
},
|
||||
() => {
|
||||
if (cancelled) return;
|
||||
reading = false;
|
||||
setState((current) => ({ ...current, status: 'error' }));
|
||||
reportLoadError.current();
|
||||
}
|
||||
);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
unsubscribe();
|
||||
};
|
||||
}, [tripId, attempt]);
|
||||
|
||||
const changeLinks = (update: (links: CollabLink[]) => CollabLink[]) =>
|
||||
setState((current) => (current.tripId === tripId ? { ...current, links: update(current.links) } : current));
|
||||
const reportWriteError = () => toast.error(offlineOr(t, t('common.error')));
|
||||
|
||||
const save = async (data: LinkFields, id?: number) => {
|
||||
try {
|
||||
const { link } =
|
||||
id == null ? await collabLinkRepo.create(tripId, data) : await collabLinkRepo.update(tripId, id, data);
|
||||
changeLinks((links) => (id == null ? insertLink(links, link) : updateLink(links, link)));
|
||||
} catch (error) {
|
||||
reportWriteError();
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
const toggle = async (link: CollabLink) => {
|
||||
try {
|
||||
const { link: saved } = await collabLinkRepo.update(tripId, link.id, { pinned: !link.pinned });
|
||||
changeLinks((links) => updateLink(links, saved));
|
||||
} catch {
|
||||
reportWriteError();
|
||||
}
|
||||
};
|
||||
|
||||
const remove = async (id: number) => {
|
||||
try {
|
||||
await collabLinkRepo.remove(tripId, id);
|
||||
changeLinks((links) => links.filter((link) => link.id !== id));
|
||||
} catch {
|
||||
reportWriteError();
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
links: state.tripId === tripId ? state.links : EMPTY_LINKS,
|
||||
status: state.tripId === tripId ? state.status : 'loading',
|
||||
retry: () => setAttempt((value) => value + 1),
|
||||
save,
|
||||
toggle,
|
||||
remove,
|
||||
};
|
||||
}
|
||||
@@ -102,7 +102,6 @@ export default function AddPlaceToCollectionModal({ isOpen, collectionId, collec
|
||||
<div className="relative">
|
||||
<Search size={14} className="pointer-events-none absolute start-3 top-1/2 -translate-y-1/2 text-content-faint" aria-hidden="true" />
|
||||
<input
|
||||
autoFocus
|
||||
data-initial-focus
|
||||
ref={searchRef}
|
||||
type="text"
|
||||
|
||||
@@ -136,6 +136,7 @@ export default function CollectionExportMenu({ onExport, exporting, t }: Collect
|
||||
ref={menuRef}
|
||||
id={menuId}
|
||||
role="menu"
|
||||
tabIndex={-1}
|
||||
aria-label={t('collections.file.exportTitle')}
|
||||
onKeyDown={onMenuKeyDown}
|
||||
className="trek-popover-enter fixed z-[var(--z-toast)] p-1.5 rounded-xl border border-edge bg-surface-card shadow-dropdown"
|
||||
|
||||
@@ -25,6 +25,7 @@ import { placesPath } from '../../utils/placesRoutes';
|
||||
import MarkdownToolbar from '../Journey/MarkdownToolbar';
|
||||
import { getNavigationTargets, navigationTargetLabel, openNavigationTarget } from '../Planner/placeNavigation';
|
||||
import { getCategoryIcon } from '../shared/categoryIcons';
|
||||
import { focusRevealedEditor } from '../shared/dialogFocus';
|
||||
import { DialogShell } from '../shared/DialogShell';
|
||||
import { markdownLinkComponents } from '../shared/markdownLink';
|
||||
import { NavigationMenu } from '../shared/NavigationMenu';
|
||||
@@ -202,7 +203,7 @@ function Cover({
|
||||
value={form.name}
|
||||
onChange={(e) => form.setName(e.target.value)}
|
||||
className="col-detail-name-input min-w-0 flex-1"
|
||||
autoFocus
|
||||
ref={focusRevealedEditor}
|
||||
aria-label={t('common.name')}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -55,7 +55,7 @@ export default function CopyToTripModal({ isOpen, onClose, placeIds, onCopy, car
|
||||
<div className="relative">
|
||||
<Search size={14} className="pointer-events-none absolute start-3 top-1/2 -translate-y-1/2 text-content-faint" aria-hidden="true" />
|
||||
<input
|
||||
autoFocus
|
||||
data-initial-focus
|
||||
value={search}
|
||||
onChange={e => setSearch(e.target.value)}
|
||||
placeholder={t('collections.copyToTripSearch')}
|
||||
|
||||
@@ -122,7 +122,7 @@ describe('DuplicatePairCard', () => {
|
||||
const user = userEvent.setup();
|
||||
const { props, container } = setup({ variant: 'sheet' });
|
||||
const card = within(container).getByRole('article');
|
||||
expect(card.className).toContain('bg-m-sheet');
|
||||
expect(card).toHaveClass('bg-m-ic');
|
||||
expect(screen.getByText('The same name at the same spot')).toBeInTheDocument();
|
||||
await user.click(screen.getAllByRole('button', { name: /Keep this one/ })[1]);
|
||||
expect(props.onMerge).toHaveBeenCalledWith('b');
|
||||
|
||||
@@ -8,7 +8,7 @@ const LOOK = {
|
||||
dialog: {
|
||||
card: 'rounded-xl border border-edge-faint bg-surface-secondary p-3',
|
||||
side: 'flex min-w-0 flex-col gap-1.5 rounded-lg bg-surface-card p-2.5',
|
||||
name: 'text-body font-semibold text-content',
|
||||
name: 'truncate text-body font-semibold text-content',
|
||||
sub: 'text-caption text-content-faint',
|
||||
diff: 'rounded bg-warning-soft px-1 text-content',
|
||||
chip: 'inline-flex max-w-full items-center gap-1 rounded-full border border-edge-faint px-2 py-0.5 text-caption text-content-muted',
|
||||
@@ -18,16 +18,16 @@ const LOOK = {
|
||||
link: 'text-caption font-semibold text-content-muted hover:text-content disabled:opacity-50',
|
||||
},
|
||||
sheet: {
|
||||
card: 'rounded-2xl border border-m-rowbr bg-m-sheet p-3',
|
||||
side: 'flex min-w-0 flex-col gap-1.5 rounded-xl bg-m-sheetop p-2.5',
|
||||
name: 'text-body font-bold text-m-ink',
|
||||
card: 'rounded-[14px] bg-m-ic p-3',
|
||||
side: 'flex min-w-0 flex-col gap-2 rounded-xl border border-m-rowbr bg-m-sheetop p-2.5',
|
||||
name: 'line-clamp-2 break-words text-control font-semibold leading-tight text-m-ink',
|
||||
sub: 'text-caption text-m-muted',
|
||||
diff: 'rounded bg-warning-soft px-1 text-m-ink',
|
||||
chip: 'inline-flex max-w-full items-center gap-1 rounded-full border border-m-rowbr bg-m-ic px-2 py-0.5 text-caption text-m-muted',
|
||||
keep: 'inline-flex items-center justify-center gap-1.5 rounded-full border border-m-rowbr bg-m-ic px-2.5 py-[7px] text-caption font-semibold text-m-ink disabled:opacity-50',
|
||||
keep: 'inline-flex min-h-11 items-center justify-center gap-1.5 rounded-xl bg-m-ic px-2 py-2 text-start text-caption font-semibold leading-tight text-m-ink disabled:opacity-50',
|
||||
reason: 'text-caption font-semibold text-m-muted',
|
||||
note: 'text-caption text-m-faint',
|
||||
link: 'text-caption font-semibold text-m-muted disabled:opacity-50',
|
||||
link: 'min-h-11 rounded-xl px-2 text-start text-control font-medium text-m-muted active:bg-m-sheetop disabled:opacity-50',
|
||||
},
|
||||
} as const;
|
||||
|
||||
@@ -54,7 +54,7 @@ function Side({
|
||||
differing.includes(field) ? <span className={look.diff}>{text}</span> : text;
|
||||
return (
|
||||
<div className={look.side}>
|
||||
<span dir="auto" className={`${look.name} truncate`}>
|
||||
<span dir="auto" className={look.name}>
|
||||
{mark('name', side.name)}
|
||||
</span>
|
||||
{(side.address || differing.includes('address')) && (
|
||||
@@ -77,7 +77,11 @@ function Side({
|
||||
</span>
|
||||
{canMerge && (
|
||||
<button type="button" onClick={onKeep} disabled={busy} className={`mt-auto ${look.keep}`}>
|
||||
{busy ? <Loader2 size={12} className="animate-spin" /> : <Check size={12} />}{' '}
|
||||
{busy ? (
|
||||
<Loader2 size={12} className="flex-none animate-spin" aria-hidden />
|
||||
) : (
|
||||
<Check size={12} className="flex-none" aria-hidden />
|
||||
)}
|
||||
{t('collections.duplicates.keepThis')}
|
||||
</button>
|
||||
)}
|
||||
|
||||
@@ -257,9 +257,14 @@ describe('ListEditorModal', () => {
|
||||
fireEvent.click(screen.getByRole('button', { name: /Search Unsplash/ }))
|
||||
|
||||
expect(await screen.findByRole('button', { name: 'Rin' })).toBeInTheDocument()
|
||||
expect(screen.getByAltText('A street')).toHaveAttribute('title', 'A street')
|
||||
expect(tripsApi.searchCoverImages).toHaveBeenCalledWith('fjord')
|
||||
// A photo without a photographer falls back to the generic label.
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Unsplash' }))
|
||||
const photo = screen.getByRole('button', { name: 'Unsplash' })
|
||||
const thumb = photo.querySelector('img')
|
||||
expect(thumb).toHaveAttribute('alt', '')
|
||||
expect(thumb).not.toHaveAttribute('title')
|
||||
fireEvent.click(photo)
|
||||
expect(document.querySelector('img[src="https://img/full2.jpg"]')).toBeTruthy()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Create' }))
|
||||
|
||||
@@ -126,7 +126,13 @@ export default function ListEditorModal({ target, onClose, onCreated, onRequestD
|
||||
aria-pressed={on}
|
||||
className={`relative h-20 overflow-hidden rounded-[10px] transition-shadow ${on ? 'ring-2 ring-accent' : 'ring-1 ring-edge-faint hover:ring-content-faint'}`}
|
||||
>
|
||||
<img src={photo.thumb} alt={photo.description || ''} loading="lazy" className="h-full w-full object-cover" />
|
||||
<img
|
||||
src={photo.thumb}
|
||||
alt={photo.description || ''}
|
||||
title={photo.description || undefined}
|
||||
loading="lazy"
|
||||
className="h-full w-full object-cover"
|
||||
/>
|
||||
{photo.photographer && <span className={PHOTO_CREDIT} style={fs(10)}>{photo.photographer}</span>}
|
||||
</button>
|
||||
)
|
||||
|
||||
@@ -153,4 +153,9 @@ describe('ListsRail', () => {
|
||||
renderRail({ onSelectLibrary: vi.fn(), libraryCount: null });
|
||||
expect(screen.getByRole('button', { name: /All places/ })).toHaveTextContent(/^All places$/);
|
||||
});
|
||||
|
||||
it('hides All places when the library is known to be empty', () => {
|
||||
renderRail({ onSelectLibrary: vi.fn(), libraryCount: 0 });
|
||||
expect(screen.queryByRole('button', { name: /All places/ })).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -75,7 +75,7 @@ export default function ListsRail(props: ListsRailProps): React.ReactElement {
|
||||
</Tooltip>
|
||||
</div>
|
||||
|
||||
{onSelectLibrary && (
|
||||
{onSelectLibrary && libraryCount !== 0 && (
|
||||
<div className="col-row">
|
||||
<button type="button" onClick={onSelectLibrary} className={`col-row-btn${libraryActive ? ' on' : ''}`} aria-current={libraryActive ? 'page' : undefined}>
|
||||
<span className="ico tile"><Globe2 size={15} /></span>
|
||||
|
||||
@@ -67,7 +67,7 @@ export default function MoveToListModal({ mode, lists, count, onPick, onClose, t
|
||||
<div className="relative">
|
||||
<Search size={14} className="pointer-events-none absolute start-3 top-1/2 -translate-y-1/2 text-content-faint" aria-hidden="true" />
|
||||
<input
|
||||
autoFocus
|
||||
data-initial-focus
|
||||
value={search}
|
||||
onChange={e => setSearch(e.target.value)}
|
||||
placeholder={t('collections.searchLists')}
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import type { PlacesLibraryDetailResponse } from '@trek/shared';
|
||||
import { Bookmark, Eye, Layers, Luggage, NotebookPen, Pencil, PenLine } from 'lucide-react';
|
||||
import React, { useRef } from 'react';
|
||||
import React, { useCallback, useRef } from 'react';
|
||||
import Markdown from 'react-markdown';
|
||||
import remarkBreaks from 'remark-breaks';
|
||||
import remarkGfm from 'remark-gfm';
|
||||
import type { TranslationFn } from '../../types';
|
||||
import MarkdownToolbar from '../Journey/MarkdownToolbar';
|
||||
import { focusRevealedEditor } from '../shared/dialogFocus';
|
||||
import { markdownLinkComponents } from '../shared/markdownLink';
|
||||
import { Tooltip } from '../shared/Tooltip';
|
||||
import PlaceCard from './PlaceCard';
|
||||
@@ -51,6 +52,10 @@ function NoteCard({ note, n, t }: { note: OriginNote; n: Notes; t: TranslationFn
|
||||
*/
|
||||
function NoteEditor({ n, t }: { n: Notes; t: TranslationFn }) {
|
||||
const ref = useRef<HTMLTextAreaElement>(null);
|
||||
const attachEditor = useCallback((element: HTMLTextAreaElement | null) => {
|
||||
ref.current = element;
|
||||
focusRevealedEditor(element);
|
||||
}, []);
|
||||
const current = n.composeTargets.find((x) => x.key === n.editing) ?? n.notes.find((x) => x.key === n.editing);
|
||||
const multi = n.isNew && n.composeTargets.length > 1;
|
||||
return (
|
||||
@@ -111,8 +116,7 @@ function NoteEditor({ n, t }: { n: Notes; t: TranslationFn }) {
|
||||
</div>
|
||||
) : (
|
||||
<textarea
|
||||
ref={ref}
|
||||
autoFocus
|
||||
ref={attachEditor}
|
||||
rows={6}
|
||||
value={n.draft}
|
||||
onChange={(e) => n.setDraft(e.target.value)}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { MapPin } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import type { Category, TranslationFn } from '../../types';
|
||||
import { focusRevealedEditor } from '../shared/dialogFocus';
|
||||
import { NumericInput } from '../shared/NumericInput';
|
||||
import CategoryTileMenu from './CategoryTileMenu';
|
||||
import type { PlaceEditState } from './usePlaceEdit';
|
||||
@@ -36,7 +37,7 @@ export default function PlaceEditForm({
|
||||
/>
|
||||
)}
|
||||
<input
|
||||
autoFocus
|
||||
ref={focusRevealedEditor}
|
||||
value={draft.name}
|
||||
onChange={(e) => edit.set('name', e.target.value)}
|
||||
aria-label={t('common.name')}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Bookmark, Check, Luggage, Plus, Search, Tag, X } from 'lucide-react';
|
||||
import React, { useEffect, useRef } from 'react';
|
||||
import type { TranslationFn } from '../../types';
|
||||
import { focusRevealedEditor } from '../shared/dialogFocus';
|
||||
import PlaceCard from './PlaceCard';
|
||||
import type { PlaceTagsState, TagGroup } from './usePlaceTags';
|
||||
|
||||
@@ -38,7 +39,7 @@ function TagPicker({ tags, group, t }: { tags: PlaceTagsState; group: TagGroup;
|
||||
>
|
||||
<Search size={14} aria-hidden="true" />
|
||||
<input
|
||||
autoFocus
|
||||
ref={focusRevealedEditor}
|
||||
value={tags.query}
|
||||
onChange={(e) => tags.setQuery(e.target.value)}
|
||||
placeholder={t('placeTags.search')}
|
||||
|
||||
@@ -55,7 +55,7 @@ export default function SaveTripPlacesToListModal({ isOpen, tripId, placeIds, on
|
||||
<div className="relative">
|
||||
<Search size={14} className="pointer-events-none absolute start-3 top-1/2 -translate-y-1/2 text-content-faint" aria-hidden="true" />
|
||||
<input
|
||||
autoFocus
|
||||
data-initial-focus
|
||||
value={search}
|
||||
onChange={e => setSearch(e.target.value)}
|
||||
placeholder={t('collections.searchLists')}
|
||||
|
||||
@@ -8,7 +8,9 @@ import { getApiErrorMessage } from '../../utils/apiError';
|
||||
import { useToast } from '../shared/Toast';
|
||||
|
||||
/** A pair's own name: its two keys in a fixed order, so either way round it is one pair. */
|
||||
export const pairKey = (d: Pick<PlacesLibraryDuplicate, 'a' | 'b'>): string => [d.a.key, d.b.key].sort().join('|');
|
||||
export function pairKey({ a, b }: Pick<PlacesLibraryDuplicate, 'a' | 'b'>): string {
|
||||
return a.key <= b.key ? `${a.key}|${b.key}` : `${b.key}|${a.key}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Places that look like the same place (PLC-13), behind the desktop dialog and the
|
||||
|
||||
@@ -85,6 +85,35 @@ describe('parseEntryKey and entryHasPosition', () => {
|
||||
});
|
||||
|
||||
describe('usePlacesLibrary: the first page', () => {
|
||||
it('uses the restored filters on its first request and opens the previous place', async () => {
|
||||
const restoredDetail = libraryDetail(libraryEntry(), []);
|
||||
list.mockResolvedValue(libraryPage([]));
|
||||
detail.mockResolvedValue(restoredDetail);
|
||||
const { result } = renderHook(() =>
|
||||
usePlacesLibrary({
|
||||
t,
|
||||
active: true,
|
||||
initialKey: 'trip:42',
|
||||
initialFilters: {
|
||||
search: 'Coffee',
|
||||
kind: 'trip',
|
||||
categoryId: 3,
|
||||
sort: 'rating',
|
||||
status: 'all',
|
||||
minRating: 4,
|
||||
tagNames: ['Morning'],
|
||||
},
|
||||
})
|
||||
);
|
||||
await waitFor(() => expect(result.current.detail).toBe(restoredDetail));
|
||||
expect(list).toHaveBeenCalledWith(
|
||||
{ q: 'Coffee', kind: 'trip', category_id: 3, sort: 'rating', min_rating: 4, tags: ['Morning'], limit: 60 },
|
||||
expect.any(AbortSignal)
|
||||
);
|
||||
expect(detail).toHaveBeenCalledWith('trip', 42, expect.any(AbortSignal));
|
||||
expect(result.current.search).toBe('Coffee');
|
||||
});
|
||||
|
||||
it('FE-COMP-PLACESLIBHOOK-003: asks nothing while inactive and loads once it becomes active', async () => {
|
||||
list.mockResolvedValue(libraryPage([]));
|
||||
const { rerender, result } = mount(false);
|
||||
|
||||
@@ -17,6 +17,16 @@ import { getApiErrorMessage } from '../../utils/apiError';
|
||||
/** Which origins the overview shows: all, only trip places, only saved ones. */
|
||||
export type LibraryKindFilter = 'all' | PlacesLibraryKind;
|
||||
|
||||
export interface PlacesLibraryFilters {
|
||||
search: string;
|
||||
kind: LibraryKindFilter;
|
||||
categoryId: number | 'all';
|
||||
sort: PlacesLibrarySort;
|
||||
status: CollectionStatus | 'all';
|
||||
minRating: number | 'all';
|
||||
tagNames: string[];
|
||||
}
|
||||
|
||||
const PAGE = 60;
|
||||
/** How long typing settles before the search asks the server. */
|
||||
const SEARCH_SETTLE_MS = 250;
|
||||
@@ -77,17 +87,17 @@ function failureOf(err: unknown, t: TranslationFn): { error: string | null; offl
|
||||
}
|
||||
|
||||
/** The filters of "All places". */
|
||||
function useLibraryFilters() {
|
||||
const [search, setSearch] = useState('');
|
||||
const [query, setQuery] = useState('');
|
||||
const [kind, setKind] = useState<LibraryKindFilter>('all');
|
||||
const [categoryId, setCategoryId] = useState<number | 'all'>('all');
|
||||
const [sort, setSort] = useState<PlacesLibrarySort>('name');
|
||||
const [status, setStatus] = useState<CollectionStatus | 'all'>('all');
|
||||
function useLibraryFilters(initial?: PlacesLibraryFilters) {
|
||||
const [search, setSearch] = useState(initial?.search ?? '');
|
||||
const [query, setQuery] = useState(initial?.search.trim() ?? '');
|
||||
const [kind, setKind] = useState<LibraryKindFilter>(initial?.kind ?? 'all');
|
||||
const [categoryId, setCategoryId] = useState<number | 'all'>(initial?.categoryId ?? 'all');
|
||||
const [sort, setSort] = useState<PlacesLibrarySort>(initial?.sort ?? 'name');
|
||||
const [status, setStatus] = useState<CollectionStatus | 'all'>(initial?.status ?? 'all');
|
||||
// At least this many stars on the average of the votes, as the lists filter; unrated places drop out.
|
||||
const [minRating, setMinRating] = useState<number | 'all'>('all');
|
||||
const [minRating, setMinRating] = useState<number | 'all'>(initial?.minRating ?? 'all');
|
||||
// PLC-21: tag names of the lists and trips, any of which an entry must carry, whatever their case.
|
||||
const [tagNames, setTagNames] = useState<string[]>([]);
|
||||
const [tagNames, setTagNames] = useState<string[]>(initial?.tagNames ?? []);
|
||||
const toggleTagName = useCallback(
|
||||
(name: string) =>
|
||||
setTagNames((names) => {
|
||||
@@ -158,8 +168,8 @@ function useLibraryFilters() {
|
||||
}
|
||||
|
||||
/** The first page for the filters and the pages "more" appends. */
|
||||
function useLibraryPages(active: boolean, reloadSeq: number, t: TranslationFn) {
|
||||
const { filters, controls } = useLibraryFilters();
|
||||
function useLibraryPages(active: boolean, reloadSeq: number, t: TranslationFn, initial?: PlacesLibraryFilters) {
|
||||
const { filters, controls } = useLibraryFilters(initial);
|
||||
const [page, setPage] = useState<PageState>(EMPTY_PAGE);
|
||||
// The request "more" is loading for; another key means the button is free again.
|
||||
const [moreFor, setMoreFor] = useState<string | null>(null);
|
||||
@@ -231,8 +241,13 @@ function useLibraryPages(active: boolean, reloadSeq: number, t: TranslationFn) {
|
||||
}
|
||||
|
||||
/** The entry that is open and what its origins keep. */
|
||||
function useLibraryDetail(entries: readonly PlacesLibraryEntry[], reloadSeq: number, onError: (err: unknown) => void) {
|
||||
const [selectedKey, setSelectedKey] = useState<string | null>(null);
|
||||
function useLibraryDetail(
|
||||
entries: readonly PlacesLibraryEntry[],
|
||||
reloadSeq: number,
|
||||
onError: (err: unknown) => void,
|
||||
initialKey?: string
|
||||
) {
|
||||
const [selectedKey, setSelectedKey] = useState<string | null>(initialKey ?? null);
|
||||
const [loaded, setLoaded] = useState<{ key: string; detail: PlacesLibraryDetailResponse } | null>(null);
|
||||
const [settled, setSettled] = useState<string | null>(null);
|
||||
// Where the open entry is read from, as text so a page arriving later does not ask again.
|
||||
@@ -348,15 +363,25 @@ export function useTagOptions(entries: readonly PlacesLibraryEntry[], picked: re
|
||||
* fresh first page, "more" appends the next one, and opening an entry loads what
|
||||
* each of its origins keeps.
|
||||
*/
|
||||
export function usePlacesLibrary({ active, t }: { active: boolean; t: TranslationFn }) {
|
||||
export function usePlacesLibrary({
|
||||
active,
|
||||
t,
|
||||
initialFilters,
|
||||
initialKey,
|
||||
}: {
|
||||
active: boolean;
|
||||
t: TranslationFn;
|
||||
initialFilters?: PlacesLibraryFilters;
|
||||
initialKey?: string;
|
||||
}) {
|
||||
const [ownSeq, setReloadSeq] = useState(0);
|
||||
// A place saved to a list from here or anywhere else adds an origin: read again then too.
|
||||
const savedVersion = useSaveToCollectionStore((st) => st.version);
|
||||
const reloadSeq = ownSeq + savedVersion;
|
||||
const [detailError, setDetailError] = useState<{ error: string | null; offline: boolean } | null>(null);
|
||||
const pages = useLibraryPages(active, reloadSeq, t);
|
||||
const pages = useLibraryPages(active, reloadSeq, t, initialFilters);
|
||||
const onDetailError = useCallback((err: unknown) => setDetailError(failureOf(err, t)), [t]);
|
||||
const sel = useLibraryDetail(pages.page.entries, reloadSeq, onDetailError);
|
||||
const sel = useLibraryDetail(pages.page.entries, reloadSeq, onDetailError, initialKey);
|
||||
const cover = useLibraryCover(sel.detail);
|
||||
const reload = useCallback(() => {
|
||||
setDetailError(null);
|
||||
|
||||
@@ -440,9 +440,9 @@ describe('DawarichAcceptDialog', () => {
|
||||
phone.value = true
|
||||
const { onConfirm } = open({ trips: TRIPS, daysForTrip })
|
||||
|
||||
expect(screen.getByRole('dialog', { name: 'Add this stay as a place' })).toBeInTheDocument()
|
||||
// The desktop modal's own heading is the tell that the wrong shell rendered.
|
||||
expect(screen.queryByRole('heading', { name: 'Add this stay as a place' })).toBeNull()
|
||||
const sheet = screen.getByRole('dialog', { name: 'Add this stay as a place' })
|
||||
expect(sheet).toHaveAttribute('data-m-sheet', 'open')
|
||||
expect(screen.getByRole('heading', { name: 'Add this stay as a place' })).toBeInTheDocument()
|
||||
|
||||
fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'Reichard' } })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Add place' }))
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { ArrowLeft, ArrowRight, Clock, ExternalLink, Images, RotateCcw } from 'lucide-react';
|
||||
import { lazy, Suspense, useId } from 'react';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { focusRevealedEditor } from '../shared/dialogFocus';
|
||||
import {
|
||||
DialogButton,
|
||||
DialogFooter,
|
||||
@@ -116,7 +117,7 @@ function FooterLinks({ t, onCredits, focusCredits }: { t: Translate; onCredits:
|
||||
<button
|
||||
type="button"
|
||||
onClick={onCredits}
|
||||
autoFocus={focusCredits}
|
||||
ref={focusCredits ? focusRevealedEditor : undefined}
|
||||
className={FOOTER_LINK}
|
||||
style={fs(12.5, 'body')}
|
||||
>
|
||||
|
||||
@@ -106,17 +106,17 @@ export default function DocSyncConnectModal({
|
||||
</Field>
|
||||
))}
|
||||
|
||||
<label className="flex items-start justify-between gap-4 rounded-lg border border-edge bg-surface-secondary px-3 py-2.5">
|
||||
<div className="flex items-start justify-between gap-4 rounded-lg border border-edge bg-surface-secondary px-3 py-2.5">
|
||||
<span className="min-w-0">
|
||||
<span className="block text-body text-content">{t('docsync.allowInsecureTls')}</span>
|
||||
<span className="mt-0.5 block text-caption text-content-muted">
|
||||
<span id={`${labelId}-tls-hint`} className="mt-0.5 block text-caption text-content-muted">
|
||||
{t('docsync.connect.insecureHint')}
|
||||
</span>
|
||||
</span>
|
||||
<span className="shrink-0 pt-0.5">
|
||||
<ToggleSwitch on={form.insecureTls} onToggle={() => form.setInsecureTls(!form.insecureTls)} />
|
||||
<ToggleSwitch on={form.insecureTls} onToggle={() => form.setInsecureTls(!form.insecureTls)} label={t('docsync.allowInsecureTls')} describedBy={`${labelId}-tls-hint`} />
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ConfirmDialog
|
||||
|
||||
@@ -6,6 +6,7 @@ import userEvent from '@testing-library/user-event'
|
||||
import { render, screen, waitFor, act } from '../../../tests/helpers/render'
|
||||
import { server } from '../../../tests/helpers/msw/server'
|
||||
import ContributorInviteDialog from './ContributorInviteDialog'
|
||||
import MJourneyInviteFrame from '../../mobile/screens/journey/MJourneyInviteFrame'
|
||||
|
||||
type ToastKind = 'success' | 'error' | 'warning' | 'info'
|
||||
|
||||
@@ -198,29 +199,22 @@ describe('ContributorInviteDialog on a phone', () => {
|
||||
Object.defineProperty(window, 'innerWidth', { value: width, configurable: true, writable: true })
|
||||
})
|
||||
|
||||
it('FE-JRN-INVITE-013: keeps the panel it had, with the filled role button and the header close', async () => {
|
||||
it('FE-JRN-INVITE-013: uses the mobile sheet with a labelled role selector and close action', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { onClose, onInvited } = mountDialog()
|
||||
const { onClose, onInvited } = mountDialog({ Frame: MJourneyInviteFrame })
|
||||
await screen.findByText('maurice')
|
||||
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
|
||||
expect(screen.getByRole('dialog', { name: 'Invite Contributor' })).toBeInTheDocument()
|
||||
const viewerBtn = screen.getByRole('button', { name: 'Viewer' })
|
||||
const editorBtn = screen.getByRole('button', { name: 'Editor' })
|
||||
expect(viewerBtn.className).toContain('bg-zinc-900')
|
||||
expect(editorBtn.className).not.toContain('bg-zinc-900')
|
||||
expect(viewerBtn).toHaveAttribute('aria-pressed', 'true')
|
||||
expect(editorBtn).toHaveAttribute('aria-pressed', 'false')
|
||||
|
||||
await user.click(editorBtn)
|
||||
expect(editorBtn.className).toContain('bg-zinc-900')
|
||||
expect(viewerBtn.className).not.toContain('bg-zinc-900')
|
||||
expect(editorBtn).toHaveAttribute('aria-pressed', 'true')
|
||||
expect(viewerBtn).toHaveAttribute('aria-pressed', 'false')
|
||||
|
||||
// The header close button carries only an icon, so it is addressed by position.
|
||||
const headerClose = screen.getByRole('heading', { name: 'Invite Contributor' })
|
||||
.parentElement!.querySelector('button')!
|
||||
act(() => { headerClose.click() })
|
||||
expect(onClose).toHaveBeenCalledTimes(1)
|
||||
|
||||
// Escape is the desktop's: the phone panel never had it.
|
||||
await user.keyboard('{Escape}')
|
||||
await user.click(screen.getByRole('button', { name: 'Close' }))
|
||||
expect(onClose).toHaveBeenCalledTimes(1)
|
||||
expect(onInvited).not.toHaveBeenCalled()
|
||||
})
|
||||
@@ -232,7 +226,7 @@ describe('ContributorInviteDialog on a phone', () => {
|
||||
return HttpResponse.json({ ok: true })
|
||||
}))
|
||||
const user = userEvent.setup()
|
||||
const { onInvited } = mountDialog({ existingUserIds: [1] })
|
||||
const { onInvited } = mountDialog({ existingUserIds: [1], Frame: MJourneyInviteFrame })
|
||||
await screen.findByText('julien')
|
||||
|
||||
await user.type(screen.getByPlaceholderText('Username or email...'), 'zzz')
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useId, useState } from 'react'
|
||||
import { useEffect, useId, useState, type ComponentType } from 'react'
|
||||
import { X, Check, UserPlus, Search, Loader2 } from 'lucide-react'
|
||||
import { journeyApi, authApi } from '../../api/client'
|
||||
import { useTranslation } from '../../i18n'
|
||||
@@ -10,37 +10,56 @@ import { TripMemberAvatar } from '../Trips/TripMemberAvatar'
|
||||
import { avatarSrc } from '../../utils/avatarSrc'
|
||||
|
||||
const ROLES = ['viewer', 'editor'] as const
|
||||
type InviteRole = (typeof ROLES)[number]
|
||||
type InviteUser = { id: number; username: string; email?: string; avatar?: string | null }
|
||||
|
||||
export interface ContributorInviteFrameProps {
|
||||
users: InviteUser[]
|
||||
loading: boolean
|
||||
search: string
|
||||
onSearch: (value: string) => void
|
||||
selectedUserId: number | null
|
||||
onSelectUser: (id: number) => void
|
||||
role: InviteRole
|
||||
roles: readonly InviteRole[]
|
||||
onRoleChange: (role: InviteRole) => void
|
||||
sending: boolean
|
||||
onClose: () => void
|
||||
onInvite: () => Promise<void>
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a person to a journey. The desktop draws it in the planner's dialog
|
||||
* frame; the phone, which opens it from its journey screen, keeps the panel it
|
||||
* has always had. Both read and write the same state below.
|
||||
*/
|
||||
export default function ContributorInviteDialog({ journeyId, existingUserIds, onClose, onInvited }: {
|
||||
export default function ContributorInviteDialog({ journeyId, existingUserIds, onClose, onInvited, Frame }: {
|
||||
journeyId: number
|
||||
existingUserIds: number[]
|
||||
onClose: () => void
|
||||
onInvited: () => void
|
||||
Frame?: ComponentType<ContributorInviteFrameProps>
|
||||
}) {
|
||||
const { t } = useTranslation()
|
||||
const phone = useIsPhone()
|
||||
const labelId = useId()
|
||||
const [users, setUsers] = useState<{ id: number; username: string; email?: string; avatar?: string | null }[]>([])
|
||||
const [users, setUsers] = useState<InviteUser[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [search, setSearch] = useState('')
|
||||
const [selectedUserId, setSelectedUserId] = useState<number | null>(null)
|
||||
const [role, setRole] = useState<'editor' | 'viewer'>('viewer')
|
||||
const [role, setRole] = useState<InviteRole>('viewer')
|
||||
const [sending, setSending] = useState(false)
|
||||
const toast = useToast()
|
||||
|
||||
useEffect(() => {
|
||||
authApi.listUsers().then(d => setUsers(d.users || [])).catch(() => {})
|
||||
authApi.listUsers().then(d => setUsers(d.users || [])).catch(() => setUsers([])).finally(() => setLoading(false))
|
||||
}, [])
|
||||
|
||||
// Captured and stopped on the desktop: the dialog is usually opened from the
|
||||
// journey settings, which close on Escape as well, and one key press should
|
||||
// only take back this dialog, not the one under it.
|
||||
useEffect(() => {
|
||||
if (phone) return
|
||||
if (phone || Frame) return
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key !== 'Escape') return
|
||||
e.stopPropagation()
|
||||
@@ -48,7 +67,7 @@ export default function ContributorInviteDialog({ journeyId, existingUserIds, on
|
||||
}
|
||||
document.addEventListener('keydown', onKey, true)
|
||||
return () => document.removeEventListener('keydown', onKey, true)
|
||||
}, [phone, onClose])
|
||||
}, [phone, Frame, onClose])
|
||||
|
||||
const filtered = users.filter(u => {
|
||||
if (existingUserIds.includes(u.id)) return false
|
||||
@@ -59,7 +78,7 @@ export default function ContributorInviteDialog({ journeyId, existingUserIds, on
|
||||
})
|
||||
|
||||
const handleInvite = async () => {
|
||||
if (!selectedUserId) return
|
||||
if (!selectedUserId || sending) return
|
||||
setSending(true)
|
||||
try {
|
||||
await journeyApi.addContributor(journeyId, selectedUserId, role)
|
||||
@@ -72,6 +91,12 @@ export default function ContributorInviteDialog({ journeyId, existingUserIds, on
|
||||
}
|
||||
}
|
||||
|
||||
if (Frame) {
|
||||
return <Frame users={filtered} loading={loading} search={search} onSearch={setSearch}
|
||||
selectedUserId={selectedUserId} onSelectUser={setSelectedUserId} role={role} roles={ROLES}
|
||||
onRoleChange={setRole} sending={sending} onClose={onClose} onInvite={handleInvite} />
|
||||
}
|
||||
|
||||
if (phone) {
|
||||
return (
|
||||
<div className="fixed inset-0 z-[200] flex items-center justify-center p-5 bg-[rgba(9,9,11,0.75)]">
|
||||
@@ -206,7 +231,7 @@ export default function ContributorInviteDialog({ journeyId, existingUserIds, on
|
||||
<div className="relative">
|
||||
<Search size={14} className="pointer-events-none absolute start-3 top-1/2 -translate-y-1/2 text-content-faint" aria-hidden="true" />
|
||||
<input
|
||||
autoFocus
|
||||
data-initial-focus
|
||||
value={search}
|
||||
onChange={e => setSearch(e.target.value)}
|
||||
placeholder={t('journey.contributors.searchPlaceholder')}
|
||||
|
||||
@@ -51,7 +51,7 @@ export function AddTripDialog({ journeyId, existingTripIds, onClose, onAdded }:
|
||||
<div className="relative">
|
||||
<Search size={14} className="pointer-events-none absolute start-3 top-1/2 -translate-y-1/2 text-content-faint" aria-hidden="true" />
|
||||
<input
|
||||
autoFocus
|
||||
data-initial-focus
|
||||
value={search}
|
||||
onChange={e => setSearch(e.target.value)}
|
||||
placeholder={t('journey.trips.searchPlaceholder')}
|
||||
|
||||
@@ -32,6 +32,7 @@ interface Props {
|
||||
publicHint?: boolean;
|
||||
/** Start unfolded, where the thread already has a section of its own. */
|
||||
defaultOpen?: boolean;
|
||||
mobile?: boolean;
|
||||
}
|
||||
|
||||
const GUEST_NAME_KEY = 'trek.journey.guestName';
|
||||
@@ -68,9 +69,10 @@ export default function JourneyEntryComments({
|
||||
onDelete,
|
||||
publicHint,
|
||||
defaultOpen,
|
||||
mobile = false,
|
||||
}: Props) {
|
||||
const { t, locale } = useTranslation();
|
||||
const [open, setOpen] = useState(!!defaultOpen);
|
||||
const [expanded, setExpanded] = useState<boolean | null>(null);
|
||||
const [body, setBody] = useState('');
|
||||
const [name, setName] = useState(guest ? rememberedName : '');
|
||||
const [trap, setTrap] = useState('');
|
||||
@@ -78,6 +80,7 @@ export default function JourneyEntryComments({
|
||||
const [message, setMessage] = useState<string | null>(null);
|
||||
|
||||
if (!canWrite && comments.length === 0) return null;
|
||||
const open = expanded ?? Boolean(defaultOpen || (mobile && comments.length));
|
||||
|
||||
const submit = async (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
@@ -108,9 +111,13 @@ export default function JourneyEntryComments({
|
||||
aria-expanded={open}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
setOpen((shown) => !shown);
|
||||
setExpanded(!open);
|
||||
}}
|
||||
className="inline-flex items-center gap-1.5 self-start text-caption font-medium text-content-faint transition-colors hover:text-content"
|
||||
className={
|
||||
mobile
|
||||
? 'flex min-h-11 w-full items-center gap-2 rounded-xl bg-m-sheetop px-3 text-start text-control font-medium text-m-ink'
|
||||
: 'inline-flex items-center gap-1.5 self-start text-caption font-medium text-content-faint transition-colors hover:text-content'
|
||||
}
|
||||
>
|
||||
<MessageCircle size={13} />
|
||||
{comments.length > 0 ? t('journey.comments.count', { count: comments.length }) : t('journey.comments.write')}
|
||||
@@ -121,7 +128,7 @@ export default function JourneyEntryComments({
|
||||
return (
|
||||
// The thread sits inside clickable cards: a click in it must not open the entry.
|
||||
<div className="flex flex-col gap-3" onClick={(e) => e.stopPropagation()} role="presentation">
|
||||
{!defaultOpen && toggle}
|
||||
{!defaultOpen && !mobile && toggle}
|
||||
{comments.length > 0 && (
|
||||
<ul className="flex flex-col gap-2.5">
|
||||
{comments.map((c) => {
|
||||
@@ -149,7 +156,13 @@ export default function JourneyEntryComments({
|
||||
<p className="mt-0.5 whitespace-pre-wrap break-words text-body text-content-muted">{c.body}</p>
|
||||
</div>
|
||||
{(mayHide || mayDelete) && (
|
||||
<div className="flex flex-none items-center gap-0.5 opacity-40 transition-opacity group-hover:opacity-100">
|
||||
<div
|
||||
className={
|
||||
mobile
|
||||
? 'flex flex-none items-center gap-0.5'
|
||||
: 'flex flex-none items-center gap-0.5 opacity-40 transition-opacity group-hover:opacity-100'
|
||||
}
|
||||
>
|
||||
{mayHide && (
|
||||
<Tooltip
|
||||
label={c.hidden ? t('journey.comments.show') : t('journey.comments.hide')}
|
||||
@@ -159,7 +172,7 @@ export default function JourneyEntryComments({
|
||||
type="button"
|
||||
aria-label={c.hidden ? t('journey.comments.show') : t('journey.comments.hide')}
|
||||
onClick={() => void onHide?.(c.id, !c.hidden)}
|
||||
className="flex h-7 w-7 items-center justify-center rounded-full text-content-faint hover:bg-surface-secondary hover:text-content"
|
||||
className={`flex ${mobile ? 'size-11' : 'size-7'} items-center justify-center rounded-full text-content-faint hover:bg-surface-secondary hover:text-content`}
|
||||
>
|
||||
{c.hidden ? <Eye size={13} /> : <EyeOff size={13} />}
|
||||
</button>
|
||||
@@ -171,7 +184,7 @@ export default function JourneyEntryComments({
|
||||
type="button"
|
||||
aria-label={t('common.delete')}
|
||||
onClick={() => void onDelete?.(c.id)}
|
||||
className="flex h-7 w-7 items-center justify-center rounded-full text-content-faint hover:bg-danger-soft hover:text-danger"
|
||||
className={`flex ${mobile ? 'size-11' : 'size-7'} items-center justify-center rounded-full text-content-faint hover:bg-danger-soft hover:text-danger`}
|
||||
>
|
||||
<Trash2 size={13} />
|
||||
</button>
|
||||
@@ -216,14 +229,22 @@ export default function JourneyEntryComments({
|
||||
rows={1}
|
||||
placeholder={t('journey.comments.write')}
|
||||
aria-label={t('journey.comments.write')}
|
||||
className="max-h-40 min-h-[38px] flex-1 resize-none rounded-xl border border-edge bg-surface px-3 py-2 text-body text-content outline-none [field-sizing:content] placeholder:text-content-faint focus:border-content-faint"
|
||||
className={`max-h-40 min-w-0 flex-1 resize-none rounded-xl border px-3 py-2 text-body outline-none [field-sizing:content] ${
|
||||
mobile
|
||||
? 'min-h-11 border-m-rowbr bg-m-sheetop text-m-ink placeholder:text-m-muted'
|
||||
: 'min-h-[38px] border-edge bg-surface text-content placeholder:text-content-faint focus:border-content-faint'
|
||||
}`}
|
||||
/>
|
||||
<Tooltip label={t('journey.comments.send')} placement="top">
|
||||
<button
|
||||
type="submit"
|
||||
aria-label={t('journey.comments.send')}
|
||||
disabled={busy || !body.trim() || (guest && !name.trim())}
|
||||
className="flex h-[38px] w-[38px] flex-none items-center justify-center rounded-full bg-accent text-accent-text transition-opacity hover:bg-accent-hover disabled:opacity-40"
|
||||
className={`flex flex-none items-center justify-center rounded-full transition-opacity disabled:opacity-40 ${
|
||||
mobile
|
||||
? 'size-11 bg-m-act text-m-actfg'
|
||||
: 'size-[38px] bg-accent text-accent-text hover:bg-accent-hover'
|
||||
}`}
|
||||
>
|
||||
<SendHorizontal size={15} />
|
||||
</button>
|
||||
@@ -231,7 +252,9 @@ export default function JourneyEntryComments({
|
||||
</div>
|
||||
{message && <p className="text-caption text-danger">{message}</p>}
|
||||
{publicHint && !guest && (
|
||||
<p className="text-caption text-content-faint">{t('journey.comments.publicHint')}</p>
|
||||
<p className={`text-caption ${mobile ? 'font-normal text-m-muted' : 'text-content-faint'}`}>
|
||||
{t('journey.comments.publicHint')}
|
||||
</p>
|
||||
)}
|
||||
</form>
|
||||
)}
|
||||
@@ -252,10 +275,12 @@ export function MemberEntryComments({
|
||||
entryId,
|
||||
thread,
|
||||
defaultOpen,
|
||||
mobile,
|
||||
}: {
|
||||
entryId: number;
|
||||
thread: MemberThreadState;
|
||||
defaultOpen?: boolean;
|
||||
mobile?: boolean;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const toast = useToast();
|
||||
@@ -268,6 +293,7 @@ export function MemberEntryComments({
|
||||
comments={thread.byEntry.get(entryId) ?? []}
|
||||
canWrite
|
||||
defaultOpen={defaultOpen}
|
||||
mobile={mobile}
|
||||
canModerate={thread.canModerate}
|
||||
publicHint
|
||||
onAdd={async (body) => ((await thread.add(entryId, body)) ? null : t('journey.comments.failed'))}
|
||||
|
||||
@@ -134,14 +134,13 @@ describe('JourneyEntryCover', () => {
|
||||
expect(container.querySelector('svg.lucide-play')).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-JRN-COVER-011: only the phone draws a card without a photo in the deep day colour, opaque even as a suggestion', () => {
|
||||
it('FE-JRN-COVER-011: the phone shows a neutral surface for suggestions without photos', () => {
|
||||
const entry = buildEntry({ photos: [], type: 'skeleton' })
|
||||
const phone = render(<JourneyEntryCover entry={entry} dayColor="#6366f1" isActive={false} onClick={() => {}} tone="mobile" />)
|
||||
const phoneCard = phone.getByRole('button')
|
||||
// d9, the deep wash (jsdom spells the colour out as rgba)
|
||||
expect(phoneCard.style.backgroundImage).toMatch(/rgba\(99, 102, 241, 0\.85/)
|
||||
expect(phoneCard.className).not.toContain('opacity-90')
|
||||
expect(phone.container.querySelector('svg.lucide-map-pin')?.getAttribute('class')).toContain('-mt-6')
|
||||
expect(phoneCard.style.backgroundImage).toBe('')
|
||||
expect(phoneCard).toHaveClass('bg-m-sheetop', 'text-m-ink')
|
||||
expect(phone.container.querySelector('svg.lucide-map-pin')).not.toBeInTheDocument()
|
||||
phone.unmount()
|
||||
|
||||
// The desktop and shared timelines keep their faint wash and the day-coloured pin.
|
||||
@@ -154,4 +153,12 @@ describe('JourneyEntryCover', () => {
|
||||
expect(pin.getAttribute('class')).not.toContain('-mt-6')
|
||||
expect(pin.style.color).not.toBe('')
|
||||
})
|
||||
|
||||
it('fills a mobile card with its photo and draws the text in white', () => {
|
||||
const { container } = render(<JourneyEntryCover entry={buildEntry()} dayColor="#6366f1" isActive onClick={() => {}} tone="mobile" />)
|
||||
|
||||
expect(container.querySelector('button')).toHaveClass('text-[color:var(--m-viewer-ink)]')
|
||||
expect(container.querySelector('img[src*="/api/photos/"]')).toHaveClass('absolute', 'inset-0', 'size-full', 'object-cover')
|
||||
expect(container.querySelector('.bg-gradient-to-t')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -20,10 +20,8 @@ import type { JourneyEntry } from '../../store/journeyStore'
|
||||
* answers "how many stops into this day am I", which is not a question anyone
|
||||
* asks; the day scrubber above the carousel answers the one they do.
|
||||
*
|
||||
* Two shells draw this card. `tone` picks the surface a card without a photo
|
||||
* falls back to, because the phone shell's tokens are scoped to `.m-root` and
|
||||
* the tablet timeline is outside it. Everything else is a photo and white text,
|
||||
* which needs no tokens at all.
|
||||
* Photos fill the cover. The mobile shell uses a neutral card for entries
|
||||
* without a photo and a lighter active treatment over the map.
|
||||
*/
|
||||
|
||||
/** A card's photo, plus what says whether a clip has a poster to draw (#2341). */
|
||||
@@ -82,7 +80,10 @@ export default function JourneyEntryCover({
|
||||
size = 'regular',
|
||||
}: Props) {
|
||||
const large = size === 'large'
|
||||
const box = large ? 'h-[196px] w-[176px]' : size === 'compact' ? 'h-[112px] w-[124px]' : 'h-[152px] w-[136px]'
|
||||
const mobile = tone === 'mobile'
|
||||
const box = size === 'compact' ? 'h-[112px] w-[124px]'
|
||||
: large ? (mobile ? 'h-[144px] w-[176px]' : 'h-[196px] w-[176px]')
|
||||
: mobile ? 'h-[116px] w-[144px]' : 'h-[152px] w-[136px]'
|
||||
const { t, locale } = useTranslation()
|
||||
const isSuggestion = entry.type === 'skeleton'
|
||||
|
||||
@@ -100,12 +101,44 @@ export default function JourneyEntryCover({
|
||||
const mood = showMood ? moodMeta(entry.mood) : undefined
|
||||
const weather = showWeather ? weatherMeta(entry.weather) : undefined
|
||||
|
||||
const mobile = tone === 'mobile'
|
||||
const emptyGround = mobile ? 'bg-[color:var(--m-sheetop)]' : 'bg-white dark:bg-zinc-800'
|
||||
// The mark of a card without a photo: white and raised clear of the name on the
|
||||
// phone's deep day colour, the day's own colour on the faint wash elsewhere.
|
||||
const emptyIcon = mobile ? '-mt-6 opacity-80' : 'opacity-60'
|
||||
const emptyIconStyle = mobile ? undefined : { color: dayColor }
|
||||
if (mobile) {
|
||||
return (
|
||||
<button type="button" onClick={onClick} aria-current={isActive ? 'true' : undefined}
|
||||
className={`relative isolate flex ${box} flex-none origin-bottom flex-col justify-between overflow-hidden rounded-[18px] border bg-m-sheetop p-2.5 text-start shadow-sm transition-transform motion-reduce:transition-none ${src ? 'text-[color:var(--m-viewer-ink)]' : 'text-m-ink'} ${isActive ? 'z-[1] scale-[1.035]' : 'border-m-rowbr'}`}
|
||||
style={isActive ? { borderColor: dayColor } : undefined}
|
||||
>
|
||||
{src && (
|
||||
<>
|
||||
<img src={src} alt="" loading="lazy" className="absolute inset-0 -z-10 size-full rounded-[inherit] object-cover" />
|
||||
<span className="pointer-events-none absolute inset-x-0 bottom-0 -z-10 h-24 bg-gradient-to-t from-[color:var(--m-viewer-bg)] via-[color:var(--overlay)] to-transparent" />
|
||||
</>
|
||||
)}
|
||||
{isSuggestion && <span className="sr-only">{t('journey.entry.suggestion')}</span>}
|
||||
<span className="flex w-full min-w-0 items-start justify-between gap-1.5">
|
||||
<span className="flex min-w-0 flex-wrap items-center gap-1">
|
||||
<span className={`whitespace-nowrap rounded-md px-1.5 py-0.5 text-caption font-medium ${src ? 'bg-[color:var(--overlay)]' : 'bg-m-ic text-m-muted'}`}>{date}</span>
|
||||
{mood && <mood.icon size={12} style={{ color: mood.color }} />}
|
||||
{weather && <weather.icon size={12} className={src ? undefined : 'text-m-muted'} />}
|
||||
</span>
|
||||
{posterless && (
|
||||
<span className="grid h-9 w-12 flex-none place-items-center rounded-lg bg-m-ic text-m-muted">
|
||||
<Play size={14} fill="currentColor" />
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
<span className="flex w-full min-w-0 flex-col gap-0.5">
|
||||
<bdi className="line-clamp-2 text-control font-semibold leading-tight">{title}</bdi>
|
||||
{place && (
|
||||
<span className={`flex min-w-0 items-center gap-1 text-caption leading-snug ${src ? '' : 'text-m-muted'}`}>
|
||||
{entry.country_code && <span className="flex-none"><CountryFlag code={entry.country_code} size={12} /></span>}
|
||||
<bdi className="truncate">{place}</bdi>
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
// One ground for every corner mark. Dark rather than a white veil: these sit on
|
||||
// whatever photograph the traveller took, and a bright sky swallowed the white one.
|
||||
const badge = 'rounded-full bg-black/45 px-[7px] py-[2px] text-[10px] font-bold whitespace-nowrap text-white backdrop-blur-[2px]'
|
||||
@@ -123,11 +156,9 @@ export default function JourneyEntryCover({
|
||||
// growing its box moved every card after it once a swipe had landed, and the
|
||||
// snap then pulled the strip again, which read as a jolt (carousels keep the
|
||||
// room for it with their gap and top padding).
|
||||
// White on the root: every mark and line on the card is white, over a photo or
|
||||
// over the day's colour alike.
|
||||
className={`relative text-white ${box} flex-none origin-bottom overflow-hidden rounded-[18px] text-start transition-[transform,box-shadow] duration-200 ease-[cubic-bezier(.2,.8,.2,1)] motion-reduce:transition-none ${
|
||||
isActive ? 'z-[1] scale-[1.18] shadow-[0_18px_40px_-16px_rgba(0,0,0,.55)]' : 'scale-100 shadow-[0_10px_24px_-14px_rgba(0,0,0,.5)]'
|
||||
} ${src ? '' : emptyGround} ${isSuggestion && !mobile ? 'opacity-90' : ''}`}
|
||||
} ${src ? '' : 'bg-white dark:bg-zinc-800'} ${isSuggestion ? 'opacity-90' : ''}`}
|
||||
// backgroundImage, not background: the shorthand would drop the opaque colour
|
||||
// the class supplies and leave the map showing through a card that is only a
|
||||
// faint wash of the day's colour.
|
||||
@@ -139,14 +170,7 @@ export default function JourneyEntryCover({
|
||||
// ring lost its top edge to that clip.
|
||||
style={{
|
||||
boxShadow: `inset 0 0 0 ${isActive ? 2.5 : 1.5}px ${dayColor}${isActive ? '' : 'b3'}`,
|
||||
// Without a photograph the phone's card is the day's colour, deep enough to
|
||||
// carry the white name like a photo does, rather than a grey that read as
|
||||
// empty. Its ground stays opaque (no dimming for a suggestion either): it
|
||||
// floats over the map, whose labels read through anything less. The desktop
|
||||
// and shared timelines keep their faint wash of the day.
|
||||
...(src ? null : { backgroundImage: mobile
|
||||
? `linear-gradient(160deg, ${dayColor}d9, ${dayColor}8c 55%, ${dayColor}59)`
|
||||
: `linear-gradient(160deg, ${dayColor}2e, ${dayColor}0d)` }),
|
||||
...(src ? null : { backgroundImage: `linear-gradient(160deg, ${dayColor}2e, ${dayColor}0d)` }),
|
||||
}}
|
||||
>
|
||||
{src ? (
|
||||
@@ -154,8 +178,8 @@ export default function JourneyEntryCover({
|
||||
) : (
|
||||
<span className="absolute inset-0 flex items-center justify-center">
|
||||
{posterless
|
||||
? <Play size={24} strokeWidth={1.8} fill="currentColor" style={emptyIconStyle} className={`ml-0.5 ${emptyIcon}`} />
|
||||
: <MapPin size={24} strokeWidth={1.8} style={emptyIconStyle} className={emptyIcon} />}
|
||||
? <Play size={24} strokeWidth={1.8} fill="currentColor" className="ms-0.5 opacity-60" style={{ color: dayColor }} />
|
||||
: <MapPin size={24} strokeWidth={1.8} className="opacity-60" style={{ color: dayColor }} />}
|
||||
</span>
|
||||
)}
|
||||
|
||||
@@ -196,7 +220,7 @@ export default function JourneyEntryCover({
|
||||
</span>
|
||||
)}
|
||||
{weather && (
|
||||
<span className={`${badgeDot}`}>
|
||||
<span className={badgeDot}>
|
||||
<weather.icon size={11} strokeWidth={2.4} />
|
||||
</span>
|
||||
)}
|
||||
|
||||
@@ -113,9 +113,9 @@ describe('MobileEntryView', () => {
|
||||
const order: string[] = []
|
||||
const onClose = vi.fn(() => { order.push('close') })
|
||||
const onDelete = vi.fn(() => { order.push('delete') })
|
||||
const { container } = renderView(buildEntry(), { onClose, onDelete })
|
||||
renderView(buildEntry(), { onClose, onDelete })
|
||||
|
||||
fireEvent.click(container.querySelector('svg.lucide-trash2')!.closest('button')!)
|
||||
fireEvent.click(screen.getByRole('button', { name: /Delete/ }))
|
||||
|
||||
expect(order).toEqual(['close', 'delete'])
|
||||
})
|
||||
@@ -123,7 +123,7 @@ describe('MobileEntryView', () => {
|
||||
it('FE-COMP-JENTRYVIEW-006: read-only journeys hide the edit and delete actions', () => {
|
||||
const { container } = renderView(buildEntry(), { readOnly: true })
|
||||
expect(screen.queryByRole('button', { name: /Edit/ })).not.toBeInTheDocument()
|
||||
expect(container.querySelector('svg.lucide-trash2')).toBeNull()
|
||||
expect(screen.queryByRole('button', { name: /Delete/ })).not.toBeInTheDocument()
|
||||
// the close button stays
|
||||
expect(container.querySelector('svg.lucide-x')).not.toBeNull()
|
||||
})
|
||||
|
||||
@@ -104,6 +104,7 @@ export default function MobileEntryView({ entry, readOnly, publicPhotoUrl, onClo
|
||||
</button>
|
||||
<button type="button"
|
||||
onClick={() => { onClose(); onDelete(); }}
|
||||
aria-label={t('common.delete')}
|
||||
className="w-8 h-8 rounded-lg flex items-center justify-center text-zinc-400 hover:bg-red-50 hover:text-red-500 dark:hover:bg-red-900/20 dark:hover:text-red-400 transition-colors"
|
||||
>
|
||||
<Trash2 size={15} />
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user