feat(mobile): the admin services section gets what the desktop tab has

- Place search and routing as one card, as on the desktop: TREK's own
  services, today's allowance with a new identity behind a confirm sheet
  (MAdminServiceQuota), sharing place details (MAdminPlaceContrib), the transit
  backend and the place search provider as TREK selects, and the search log.
- The key card holds Google (with its options and the daily request cap,
  MAdminGoogleDailyLimit), Unsplash and Amap, in the desktop order.
- The logic both views need moves into one place: the transit switch into
  useAdminSettingsActions, the allowance figures into serviceIdentityModel,
  and the share-place-details panel into usePlaceContribPanel.
- MAdminSettingsSection renders each section in a function of its own.
- Tests follow the split admin sections (Save order, 2FA label, field marker).
This commit is contained in:
Maurice
2026-11-14 11:09:22 +01:00
parent dbda2d7d7c
commit a3620f9e05
19 changed files with 1027 additions and 260 deletions
@@ -1,26 +1,16 @@
import type { PlaceContribField, PlaceContribState } from '@trek/shared';
import type { PlaceContribState } from '@trek/shared';
import { HeartHandshake, Undo2 } from 'lucide-react';
import { useState } from 'react';
import { useTranslation } from '../../i18n';
import type { TranslationFn } from '../../types';
import { getApiErrorMessage } from '../../utils/apiError';
import { SettingsCard, StatusPill } from '../Settings/settingsKit';
import ToggleSwitch from '../Settings/ToggleSwitch';
import ConfirmDialog from '../shared/ConfirmDialog';
import { fs } from '../shared/DialogShell';
import { useToast } from '../shared/Toast';
import { FigureBadge } from '../Tours/paddle/FigureBadge';
import PlaceContribLog from './PlaceContribLog';
import {
contribNote,
contribStatus,
fieldEntries,
fieldLabel,
refusalReason,
type ContribStatus,
} from './placeContribModel';
import { contribNote, fieldEntries, fieldLabel, type ContribStatus } from './placeContribModel';
import PlaceContribPrompt from './PlaceContribPrompt';
import { usePlaceContrib } from './usePlaceContrib';
import { usePlaceContribPanel } from './usePlaceContribPanel';
const PILL_TONE: Record<ContribStatus, 'success' | 'warning' | 'neutral'> = {
active: 'success',
@@ -61,54 +51,12 @@ function Figures({ state, t }: { state: PlaceContribState; t: TranslationFn }) {
* way to take everything back. Turning it on for the first time opens the same
* prompt an admin gets on the first visit, so an agreement always comes from it.
*/
/**
* Standing alone (managed settings), a card that can only say "not available"
* because the operator switched sharing off is a dead end.
*/
function hiddenAlone(state: PlaceContribState, alone: boolean): boolean {
return alone && state.ineligibleReason === 'env_off';
}
export default function PlaceContribPanel({ hideWhenSwitchedOff = false }: { hideWhenSwitchedOff?: boolean } = {}) {
const { t } = useTranslation();
const toast = useToast();
const contrib = usePlaceContrib();
const { state } = contrib;
const [prompting, setPrompting] = useState<boolean | null>(null);
const [confirm, setConfirm] = useState<'off' | 'withdraw' | null>(null);
const panel = usePlaceContribPanel({ hideWhenSwitchedOff });
const { contrib, state, status, on, confirm, setConfirm, toggleField, withdraw } = panel;
if (!state) return null;
if (hiddenAlone(state, hideWhenSwitchedOff)) return null;
const status = contribStatus(state);
const agreed = state.consent.decision === 'agreed' && state.consent.termsVersion === state.termsVersion;
// The prompt opens by itself once per visit while the server asks for it.
const showPrompt = prompting ?? state.showPrompt;
const fail = (err: unknown) => {
const reason = refusalReason(err);
toast.error(
reason === 'terms_outdated' || reason === 'no_field'
? t(`admin.contribute.refused.${reason}`)
: getApiErrorMessage(err, t('common.error'))
);
};
const toggleField = (field: PlaceContribField) => {
const fields = { ...state.consent.fields, [field]: !state.consent.fields[field] };
if (!Object.values(fields).some(Boolean)) {
setConfirm('off');
return;
}
contrib.decide({ action: 'fields', fields }).catch(fail);
};
const withdraw = () => {
setConfirm(null);
contrib.withdraw().then((r) => {
const total = Object.values(r.withdrawn).reduce((a, b) => a + b, 0);
toast.success(t('admin.contribute.withdrawn', { total }));
}, fail);
};
if (panel.hidden || !state || !status) return null;
return (
<SettingsCard
@@ -119,15 +67,15 @@ export default function PlaceContribPanel({ hideWhenSwitchedOff = false }: { hid
hint={contribNote(t, state)}
action={
<ToggleSwitch
on={agreed && state.consent.enabled}
on={on}
label={t('admin.contribute.title')}
disabled={!state.eligible || contrib.busy}
onToggle={() => (agreed && state.consent.enabled ? setConfirm('off') : setPrompting(true))}
onToggle={panel.toggleMain}
/>
}
bodyClassName="flex flex-col gap-3 p-4"
>
{agreed && state.consent.enabled && (
{on && (
<>
<Figures state={state} t={t} />
<ul className="m-0 grid list-none grid-cols-2 gap-1.5 p-0 max-sm:grid-cols-1">
@@ -151,7 +99,7 @@ export default function PlaceContribPanel({ hideWhenSwitchedOff = false }: { hid
</>
)}
{(agreed || state.consent.decision === 'off') && (
{panel.showLog && (
<div className="overflow-hidden rounded-[12px] border border-edge-faint bg-surface-card">
{/* A plain section head: the settings fold nothing away. */}
<div className="flex items-center gap-2.5 px-3.5 py-2.5">
@@ -175,16 +123,11 @@ export default function PlaceContribPanel({ hideWhenSwitchedOff = false }: { hid
</div>
)}
{showPrompt && state.eligible && (
<PlaceContribPrompt state={state} contrib={contrib} onClose={() => setPrompting(false)} />
)}
{panel.showPrompt && <PlaceContribPrompt state={state} contrib={contrib} onClose={panel.closePrompt} />}
<ConfirmDialog
isOpen={confirm === 'off'}
onClose={() => setConfirm(null)}
onConfirm={() => {
setConfirm(null);
contrib.decide({ action: 'off' }).catch(fail);
}}
onConfirm={panel.switchOff}
title={t('admin.contribute.offTitle')}
message={t('admin.contribute.offMessage')}
confirmLabel={t('admin.contribute.offConfirm')}
@@ -1,15 +1,22 @@
import type { ServiceAllowance, ServiceIdentityState, ServiceIdentityStatus, ServiceQuotaView } from '@trek/shared';
import type { ServiceAllowance, ServiceIdentityState } from '@trek/shared';
import { MapPin, RefreshCw, Route, Search, Signal, type LucideIcon } from 'lucide-react';
import { useRef, useState } from 'react';
import { useTranslation } from '../../i18n';
import { useSettingsStore } from '../../store/settingsStore';
import type { TranslationFn } from '../../types';
import { getApiErrorMessage } from '../../utils/apiError';
import { formatClockTime } from '../../utils/formatters';
import { SettingsCard } from '../Settings/settingsKit';
import ConfirmDialog from '../shared/ConfirmDialog';
import { useToast } from '../shared/Toast';
import { FigureBadge } from '../Tours/paddle/FigureBadge';
import {
allowanceNote,
canRegenerateKey,
identityHint,
quotaLevel,
quotaResetClock,
quotaShare,
type QuotaLevel,
} from './serviceIdentityModel';
import { useServiceIdentity } from './useServiceIdentity';
const STATE_DOT: Record<ServiceIdentityState, string> = {
@@ -23,32 +30,8 @@ const STATE_DOT: Record<ServiceIdentityState, string> = {
const SERVICE_ICON: Record<string, LucideIcon> = { places: MapPin, photon: Search, valhalla: Route };
/** Below a tenth of the day left the bar turns amber, at nothing left red. */
function barTone(quota: ServiceQuotaView): string {
if (quota.remaining === 0) return 'bg-danger';
return quota.remaining < quota.limit / 10 ? 'bg-warning' : 'bg-accent';
}
function figureTone(quota: ServiceQuotaView): string {
if (quota.remaining === 0) return 'text-danger';
return quota.remaining < quota.limit / 10 ? 'text-warning' : 'text-content';
}
/** The clock time the counts start again, in the user's format; one for all services, which share the day. */
function useResetTime(status: ServiceIdentityStatus | null): string | null {
const is12h = useSettingsStore((s) => s.settings.time_format === '12h');
const at = status?.services.find((s) => s.quota)?.quota?.resetAt;
if (!at) return null;
const reset = new Date(at);
return formatClockTime(
`${String(reset.getHours()).padStart(2, '0')}:${String(reset.getMinutes()).padStart(2, '0')}`,
is12h
);
}
function tileNote(t: TranslationFn, allowance: ServiceAllowance): string | null {
if (!allowance.inUse) return t('admin.trekApi.quota.notInUse');
return allowance.quota ? null : t('admin.trekApi.quota.unavailable');
}
const BAR_TONE: Record<QuotaLevel, string> = { ok: 'bg-accent', low: 'bg-warning', out: 'bg-danger' };
const FIGURE_TONE: Record<QuotaLevel, string> = { ok: 'text-content', low: 'text-warning', out: 'text-danger' };
/**
* One service under the key, as a tile: what is left today as the figure that
@@ -59,10 +42,10 @@ function ServiceTile({ allowance }: { allowance: ServiceAllowance }) {
const { t, locale } = useTranslation();
const number = new Intl.NumberFormat(locale);
const name = t(`admin.trekApi.quota.service.${allowance.service}`);
const note = tileNote(t, allowance);
const note = allowanceNote(t, allowance);
const quota = allowance.quota;
const Icon = SERVICE_ICON[allowance.service] ?? MapPin;
const share = quota && quota.limit > 0 ? Math.min(100, (quota.used / quota.limit) * 100) : 100;
const share = quota ? quotaShare(quota) : 100;
// One row per service: its name, the day's use as a bar, used of the limit.
return (
@@ -83,7 +66,7 @@ function ServiceTile({ allowance }: { allowance: ServiceAllowance }) {
className="h-1.5 min-w-0 flex-1 overflow-hidden rounded-full bg-surface-tertiary"
>
<div
className={`h-full rounded-full transition-[width] duration-500 ${barTone(quota)}`}
className={`h-full rounded-full transition-[width] duration-500 ${BAR_TONE[quotaLevel(quota)]}`}
style={{ width: `${share}%` }}
/>
</div>
@@ -91,7 +74,7 @@ function ServiceTile({ allowance }: { allowance: ServiceAllowance }) {
className="flex-none text-caption tabular-nums text-content-faint"
title={`${t('admin.trekApi.quota.remaining')}: ${number.format(quota.remaining)}`}
>
<span className={`font-semibold ${figureTone(quota)}`}>{number.format(quota.used)}</span>
<span className={`font-semibold ${FIGURE_TONE[quotaLevel(quota)]}`}>{number.format(quota.used)}</span>
{' / '}
{number.format(quota.limit)}
</span>
@@ -103,11 +86,6 @@ function ServiceTile({ allowance }: { allowance: ServiceAllowance }) {
);
}
function stateHint(t: TranslationFn, status: ServiceIdentityStatus | null, failed: boolean): string | null {
if (!status) return failed ? t('admin.trekApi.quota.unavailable') : null;
return status.state === 'connected' ? null : t(`admin.trekApi.quota.hint.${status.state}`);
}
/**
* How this installation stands with the TREK services: whether it has its key,
* and for place search, address search and routing today's allowance against
@@ -121,7 +99,8 @@ export default function ServiceIdentityPanel({ managed = false }: { managed?: bo
const panel = useRef<HTMLDivElement>(null);
const { status, failed, regenerating, regenerate } = useServiceIdentity(panel);
const [confirming, setConfirming] = useState(false);
const resetAt = useResetTime(status);
const is12h = useSettingsStore((s) => s.settings.time_format === '12h');
const resetAt = quotaResetClock(status, is12h);
const confirmRegenerate = async () => {
setConfirming(false);
@@ -133,8 +112,8 @@ export default function ServiceIdentityPanel({ managed = false }: { managed?: bo
}
};
const hint = stateHint(t, status, failed);
const canRegenerate = !managed && status !== null && status.keySource !== 'env' && status.state !== 'off';
const hint = identityHint(t, status, failed);
const canRegenerate = canRegenerateKey(status, managed);
return (
<div ref={panel}>
@@ -0,0 +1,71 @@
// FE-ADMIN-SVCMODEL-001 to FE-ADMIN-SVCMODEL-006
import type { ServiceIdentityStatus } from '@trek/shared';
import { describe, expect, it } from 'vitest';
import {
allowanceNote,
canRegenerateKey,
identityHint,
quotaLevel,
quotaResetClock,
quotaShare,
} from './serviceIdentityModel';
const t = (key: string) => key;
const quota = (used: number, limit: number) => ({
used,
limit,
remaining: limit - used,
resetAt: '2026-11-15T01:30:00',
});
const STATUS: ServiceIdentityStatus = {
state: 'connected',
tier: 'std',
keySource: 'registered',
services: [
{ service: 'places', inUse: true, quota: quota(10, 100) },
{ service: 'photon', inUse: false, quota: null },
],
lastSeenAt: null,
} as ServiceIdentityStatus;
describe('serviceIdentityModel', () => {
it('FE-ADMIN-SVCMODEL-001: a day is ok, low below a tenth left, out at nothing left', () => {
expect(quotaLevel(quota(10, 100))).toBe('ok');
expect(quotaLevel(quota(95, 100))).toBe('low');
expect(quotaLevel(quota(100, 100))).toBe('out');
});
it('FE-ADMIN-SVCMODEL-002: the bar share is capped at the whole and full without a limit', () => {
expect(quotaShare(quota(25, 100))).toBe(25);
expect(quotaShare({ used: 150, limit: 100, remaining: 0, resetAt: '' })).toBe(100);
expect(quotaShare({ used: 0, limit: 0, remaining: 0, resetAt: '' })).toBe(100);
});
it('FE-ADMIN-SVCMODEL-003: the reset reads from the first counted service, in the user format', () => {
expect(quotaResetClock(STATUS, false)).toBe('01:30');
expect(quotaResetClock(STATUS, true)).toMatch(/1:30/);
expect(quotaResetClock(null, false)).toBeNull();
expect(quotaResetClock({ ...STATUS, services: [] }, false)).toBeNull();
});
it('FE-ADMIN-SVCMODEL-004: a service out of use, or without a count, says so', () => {
expect(allowanceNote(t, STATUS.services[1])).toBe('admin.trekApi.quota.notInUse');
expect(allowanceNote(t, { service: 'places', inUse: true, quota: null })).toBe('admin.trekApi.quota.unavailable');
expect(allowanceNote(t, STATUS.services[0])).toBeNull();
});
it('FE-ADMIN-SVCMODEL-005: the identity line is quiet when connected', () => {
expect(identityHint(t, STATUS, false)).toBeNull();
expect(identityHint(t, { ...STATUS, state: 'revoked' }, false)).toBe('admin.trekApi.quota.hint.revoked');
expect(identityHint(t, null, true)).toBe('admin.trekApi.quota.unavailable');
expect(identityHint(t, null, false)).toBeNull();
});
it('FE-ADMIN-SVCMODEL-006: a new key only where the admin holds the key', () => {
expect(canRegenerateKey(STATUS, false)).toBe(true);
expect(canRegenerateKey(STATUS, true)).toBe(false);
expect(canRegenerateKey({ ...STATUS, keySource: 'env' }, false)).toBe(false);
expect(canRegenerateKey({ ...STATUS, state: 'off' }, false)).toBe(false);
expect(canRegenerateKey(null, false)).toBe(false);
});
});
@@ -0,0 +1,49 @@
import type { ServiceAllowance, ServiceIdentityStatus, ServiceQuotaView } from '@trek/shared';
import type { TranslationFn } from '../../types';
import { formatClockTime } from '../../utils/formatters';
/**
* What the allowance panels (desktop ServiceIdentityPanel, phone MAdminServiceQuota)
* read from the service identity status. Pure, so both views show the same thing.
*/
/** How much of a service's day is left: plenty, below a tenth, or nothing. */
export type QuotaLevel = 'ok' | 'low' | 'out';
export function quotaLevel(quota: ServiceQuotaView): QuotaLevel {
if (quota.remaining === 0) return 'out';
return quota.remaining < quota.limit / 10 ? 'low' : 'ok';
}
/** The share of the day used, for the bar; a quota without a limit reads as full. */
export function quotaShare(quota: ServiceQuotaView): number {
return quota.limit > 0 ? Math.min(100, (quota.used / quota.limit) * 100) : 100;
}
/** The clock time the counts start again, in the user's format; one for all services, which share the day. */
export function quotaResetClock(status: ServiceIdentityStatus | null, is12h: boolean): string | null {
const at = status?.services.find((s) => s.quota)?.quota?.resetAt;
if (!at) return null;
const reset = new Date(at);
return formatClockTime(
`${String(reset.getHours()).padStart(2, '0')}:${String(reset.getMinutes()).padStart(2, '0')}`,
is12h
);
}
/** A service that is not in use, or whose count the service did not report, says so under its row. */
export function allowanceNote(t: TranslationFn, allowance: ServiceAllowance): string | null {
if (!allowance.inUse) return t('admin.trekApi.quota.notInUse');
return allowance.quota ? null : t('admin.trekApi.quota.unavailable');
}
/** A line about the identity itself, when it is not simply connected (or could not be read). */
export function identityHint(t: TranslationFn, status: ServiceIdentityStatus | null, failed: boolean): string | null {
if (!status) return failed ? t('admin.trekApi.quota.unavailable') : null;
return status.state === 'connected' ? null : t(`admin.trekApi.quota.hint.${status.state}`);
}
/** A new key can be asked for unless the operator holds it (managed, environment) or the services are off. */
export function canRegenerateKey(status: ServiceIdentityStatus | null, managed: boolean): boolean {
return !managed && status !== null && status.keySource !== 'env' && status.state !== 'off';
}
@@ -13,6 +13,7 @@ const api = vi.hoisted(() => ({
updatePlacesDetails: vi.fn(),
updatePlacesEnrich: vi.fn(),
updatePlaceShadow: vi.fn(),
updateTransitProvider: vi.fn(),
}));
vi.mock('../../api/client', () => ({
adminApi: {
@@ -22,6 +23,7 @@ vi.mock('../../api/client', () => ({
updatePlacesDetails: api.updatePlacesDetails,
updatePlacesEnrich: api.updatePlacesEnrich,
updatePlaceShadow: api.updatePlaceShadow,
updateTransitProvider: api.updateTransitProvider,
},
authApi: { updateAppSettings: api.updateAppSettings },
}));
@@ -51,6 +53,9 @@ function host(over: Record<string, unknown> = {}) {
setPlacesEnrichEnabled: vi.fn(),
setPlaceShadowEnabledState: vi.fn(),
setPlaceShadowEnabled: vi.fn(),
transitProvider: 'transitous' as const,
setTransitProviderState: vi.fn(),
setTransitGoogleKeySource: vi.fn(),
...over,
};
}
@@ -140,4 +145,30 @@ describe('useAdminSettingsActions', () => {
expect(admin.setPlacesDetailsEnabledState).toHaveBeenCalledWith(false);
expect(admin.setPlacesEnrichEnabled).toHaveBeenCalledWith(false);
});
it('FE-HOOK-ADMSETACT-T01: switching the transit backend shows it at once and keeps the key source the server reports', async () => {
api.updateTransitProvider.mockResolvedValueOnce({ provider: 'google', googleKeySource: 'instance' });
const { admin, actions } = mount();
await act(() => actions.changeTransitProvider('google'));
expect(admin.setTransitProviderState).toHaveBeenCalledWith('google');
expect(api.updateTransitProvider).toHaveBeenCalledWith('google');
expect(admin.setTransitGoogleKeySource).toHaveBeenCalledWith('instance');
});
it('FE-HOOK-ADMSETACT-T02: picking the backend already set writes nothing', async () => {
api.updateTransitProvider.mockClear();
const { admin, actions } = mount();
await act(() => actions.changeTransitProvider('transitous'));
expect(api.updateTransitProvider).not.toHaveBeenCalled();
expect(admin.setTransitProviderState).not.toHaveBeenCalled();
});
it('FE-HOOK-ADMSETACT-T03: a failed save puts the previous backend back and says why', async () => {
api.updateTransitProvider.mockRejectedValueOnce(new Error('down'));
const { admin, actions } = mount();
await act(() => actions.changeTransitProvider('google'));
expect(admin.setTransitProviderState).toHaveBeenNthCalledWith(1, 'google');
expect(admin.setTransitProviderState).toHaveBeenNthCalledWith(2, 'transitous');
expect(admin.toast.error).toHaveBeenCalled();
});
});
@@ -1,3 +1,4 @@
import type { TransitKeySource, TransitProvider } from '@trek/shared';
import { adminApi, authApi } from '../../api/client';
import type { TranslationFn } from '../../types';
import { getApiErrorMessage } from '../../types';
@@ -28,6 +29,9 @@ interface SettingsActionsHost {
setPlacesEnrichEnabled: Flag;
setPlaceShadowEnabledState: Flag;
setPlaceShadowEnabled: Flag;
transitProvider: TransitProvider;
setTransitProviderState: (provider: TransitProvider) => void;
setTransitGoogleKeySource: (source: TransitKeySource) => void;
}
/**
@@ -86,9 +90,29 @@ export function useAdminSettingsActions(admin: SettingsActionsHost, t: Translati
};
};
/**
* The transit backend (#1699): shown at once, and back to the previous one with a
* word when the save fails, so a select that springs back does not read as broken.
* A pick of the provider already selected writes nothing: the route is audited.
*/
const changeTransitProvider = async (value: string) => {
if (value === admin.transitProvider) return;
const next: TransitProvider = value === 'google' ? 'google' : 'transitous';
const previous = admin.transitProvider;
admin.setTransitProviderState(next);
try {
const saved = await adminApi.updateTransitProvider(next);
admin.setTransitGoogleKeySource(saved.googleKeySource);
} catch (err: unknown) {
admin.setTransitProviderState(previous);
toast.error(getApiErrorMessage(err, t('common.error')));
}
};
return {
saveOidc,
saveFileTypes,
changeTransitProvider,
togglePlacesPhotos: placeSwitch(admin.setPlacesPhotosEnabledState, admin.setPlacesPhotosEnabled, (enabled) =>
adminApi.updatePlacesPhotos(enabled)
),
@@ -0,0 +1,79 @@
import type { PlaceContribField } from '@trek/shared';
import { useState } from 'react';
import { useTranslation } from '../../i18n';
import { getApiErrorMessage } from '../../utils/apiError';
import { useToast } from '../shared/Toast';
import { contribStatus, refusalReason } from './placeContribModel';
import { usePlaceContrib } from './usePlaceContrib';
/**
* What the share-place-details panels (desktop PlaceContribPanel, phone
* MAdminPlaceContrib) do: the main switch (on asks for consent first, off asks
* to confirm), one switch per field (switching the last one off is switching the
* whole thing off), withdrawing what was shared, and the words for a refusal.
*/
export function usePlaceContribPanel({ hideWhenSwitchedOff = false }: { hideWhenSwitchedOff?: boolean } = {}) {
const { t } = useTranslation();
const toast = useToast();
const contrib = usePlaceContrib();
const { state } = contrib;
const [prompting, setPrompting] = useState<boolean | null>(null);
const [confirm, setConfirm] = useState<'off' | 'withdraw' | null>(null);
const fail = (err: unknown) => {
const reason = refusalReason(err);
toast.error(
reason === 'terms_outdated' || reason === 'no_field'
? t(`admin.contribute.refused.${reason}`)
: getApiErrorMessage(err, t('common.error'))
);
};
// Shown on its own (a managed install), a switch the environment turned off is
// no decision of the admin's, so the panel stays away.
const hidden = !state || (hideWhenSwitchedOff && state.ineligibleReason === 'env_off');
const agreed = !!state && state.consent.decision === 'agreed' && state.consent.termsVersion === state.termsVersion;
const on = agreed && !!state?.consent.enabled;
const toggleField = (field: PlaceContribField) => {
if (!state) return;
const fields = { ...state.consent.fields, [field]: !state.consent.fields[field] };
if (!Object.values(fields).some(Boolean)) {
setConfirm('off');
return;
}
contrib.decide({ action: 'fields', fields }).catch(fail);
};
const switchOff = () => {
setConfirm(null);
contrib.decide({ action: 'off' }).catch(fail);
};
const withdraw = () => {
setConfirm(null);
contrib.withdraw().then((r) => {
const total = Object.values(r.withdrawn).reduce((a, b) => a + b, 0);
toast.success(t('admin.contribute.withdrawn', { total }));
}, fail);
};
return {
contrib,
state,
hidden,
status: state ? contribStatus(state) : null,
agreed,
on,
/** The log and the withdraw action: once agreed, and still after switching off. */
showLog: agreed || state?.consent.decision === 'off',
showPrompt: !!state && (prompting ?? state.showPrompt) && state.eligible,
toggleMain: () => (on ? setConfirm('off') : setPrompting(true)),
closePrompt: () => setPrompting(false),
confirm,
setConfirm,
toggleField,
switchOff,
withdraw,
};
}
@@ -0,0 +1,63 @@
import { Check } from 'lucide-react';
import { useGoogleQuota } from '../../../components/Admin/useGoogleQuota';
import { NumericInput } from '../../../components/shared/NumericInput';
import { useTranslation } from '../../../i18n';
import MHintLabel from '../../components/MHintLabel';
import { MAdminButton } from './MAdminUi';
/**
* The daily cap on Google requests, the phone's form of the desktop
* GoogleDailyLimitRow: today's count under the name (in the warning colour once
* the day is used up), the cap in a small field, and a save while it differs.
*/
export default function MAdminGoogleDailyLimit() {
const { t } = useTranslation();
const { status, draft, setDraft, dirty, saving, save } = useGoogleQuota();
let today: string | null = null;
if (status) {
if (status.exhausted) today = t('admin.googleQuota.reached', { used: status.used_today });
else if (status.daily_limit == null) today = t('admin.googleQuota.usedToday', { used: status.used_today });
else today = t('admin.googleQuota.usedOfLimit', { used: status.used_today, limit: status.daily_limit });
}
return (
<div
className={`flex items-center gap-3 border-t border-[color:var(--m-rowbr)] py-[11px] ${saving ? 'opacity-60' : ''}`}
>
<div className="min-w-0 flex-1">
<MHintLabel label={t('admin.googleQuota.title')} hint={t('admin.googleQuota.subtitle')} />
{today && (
<p
className={`mt-[1px] font-geist text-[length:calc(10px*var(--fs-scale-caption,1))] tabular-nums ${
status?.exhausted ? 'text-[color:var(--m-st-pending)]' : 'text-m-muted'
}`}
>
{today}
</p>
)}
</div>
<NumericInput
aria-label={t('admin.googleQuota.title')}
mode="integer"
value={draft}
onValueChange={setDraft}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault();
void save();
}
}}
placeholder={t('admin.googleQuota.placeholder')}
disabled={status === null || saving}
className="h-[34px] w-[88px] flex-none rounded-full border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] px-3 text-end font-geist text-[length:calc(12.5px*var(--fs-scale-body,1))] tabular-nums text-m-ink outline-none placeholder:text-m-faint"
/>
{dirty && (
<MAdminButton busy={saving} onClick={() => void save()}>
{!saving && <Check size={12} strokeWidth={2.4} />}
{t('common.save')}
</MAdminButton>
)}
</div>
);
}
@@ -0,0 +1,124 @@
import { Undo2 } from 'lucide-react';
import PlaceContribLog from '../../../components/Admin/PlaceContribLog';
import PlaceContribPrompt from '../../../components/Admin/PlaceContribPrompt';
import { contribNote, fieldEntries, fieldLabel, type ContribStatus } from '../../../components/Admin/placeContribModel';
import { usePlaceContribPanel } from '../../../components/Admin/usePlaceContribPanel';
import { useTranslation } from '../../../i18n';
import MToggle from '../../components/MToggle';
import MConfirmSheet from '../settings/MConfirmSheet';
import { MAdminButton, MAdminNote, MAdminRow } from './MAdminUi';
const STATUS_TONE: Record<ContribStatus, string> = {
active: 'text-[color:var(--m-st-confirmed)]',
paused: 'text-[color:var(--m-st-pending)]',
off: 'text-m-muted',
unavailable: 'text-m-muted',
};
/**
* Sharing place details with the TREK Places API, the phone's form of the
* desktop PlaceContribPanel: one switch for the installation (on asks for
* consent first), one per field, the figures, the transmission log and the way
* to take everything back. The logic is usePlaceContribPanel, shared with it.
*/
export default function MAdminPlaceContrib({ hideWhenSwitchedOff = false }: { hideWhenSwitchedOff?: boolean }) {
const { t, locale } = useTranslation();
const panel = usePlaceContribPanel({ hideWhenSwitchedOff });
const { contrib, state, status, on, confirm, setConfirm } = panel;
if (panel.hidden || !state || !status) return null;
const number = new Intl.NumberFormat(locale);
const last = state.lastSuccessDay
? new Intl.DateTimeFormat(locale, { day: 'numeric', month: 'short' }).format(
new Date(`${state.lastSuccessDay}T12:00:00`)
)
: t('admin.contribute.never');
return (
<div className="rounded-[16px] border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] px-[14px] py-1">
<MAdminRow
first
title={
<span className="inline-flex max-w-full items-center gap-[6px]">
<span className="min-w-0">{t('admin.contribute.title')}</span>
<span
className={`flex-none font-geist text-[length:calc(10px*var(--fs-scale-caption,1))] font-bold ${STATUS_TONE[status]}`}
>
{t(`admin.contribute.status.${status}`)}
</span>
</span>
}
hint={contribNote(t, state)}
trailing={
<MToggle
checked={on}
ariaLabel={t('admin.contribute.title')}
disabled={!state.eligible || contrib.busy}
onChange={panel.toggleMain}
/>
}
/>
{on && (
<>
<MAdminNote>
{[
`${t('admin.contribute.figure.accepted')} ${number.format(state.counts.accepted)}`,
`${t('admin.contribute.figure.queue')} ${number.format(state.queue.size)}`,
`${t('admin.contribute.figure.last')} ${last}`,
].join(', ')}
</MAdminNote>
{state.queue.full && <MAdminNote warn>{t('admin.contribute.figure.queueFull')}</MAdminNote>}
{fieldEntries(state.consent.fields).map(([field, fieldOn]) => (
<MAdminRow
key={field}
title={fieldLabel(t, field)}
trailing={
<MToggle
checked={fieldOn}
ariaLabel={fieldLabel(t, field)}
disabled={contrib.busy}
onChange={() => panel.toggleField(field)}
/>
}
/>
))}
</>
)}
{panel.showLog && (
<div className="space-y-2 border-t border-[color:var(--m-rowbr)] py-[11px]">
<div className="text-[length:calc(12.5px*var(--fs-scale-body,1))] font-bold text-m-ink">
{t('admin.contribute.log.title')}
</div>
<PlaceContribLog />
<MAdminButton variant="ghost" disabled={contrib.busy} onClick={() => setConfirm('withdraw')}>
<Undo2 size={12} strokeWidth={2.2} />
{t('admin.contribute.withdraw')}
</MAdminButton>
</div>
)}
{panel.showPrompt && <PlaceContribPrompt state={state} contrib={contrib} onClose={panel.closePrompt} />}
<MConfirmSheet
open={confirm === 'off'}
onClose={() => setConfirm(null)}
title={t('admin.contribute.offTitle')}
message={t('admin.contribute.offMessage')}
confirmLabel={t('admin.contribute.offConfirm')}
cancelLabel={t('common.cancel')}
onConfirm={panel.switchOff}
/>
<MConfirmSheet
open={confirm === 'withdraw'}
onClose={() => setConfirm(null)}
title={t('admin.contribute.withdrawTitle')}
message={t('admin.contribute.withdrawMessage')}
confirmLabel={t('admin.contribute.withdraw')}
cancelLabel={t('common.cancel')}
danger
onConfirm={panel.withdraw}
/>
</div>
);
}
@@ -0,0 +1,170 @@
import type { ServiceAllowance, ServiceIdentityState, ServiceIdentityStatus } from '@trek/shared';
import { MapPin, RefreshCw, Route, Search, type LucideIcon } from 'lucide-react';
import { useRef, useState } from 'react';
import {
allowanceNote,
canRegenerateKey,
identityHint,
quotaLevel,
quotaResetClock,
quotaShare,
type QuotaLevel,
} from '../../../components/Admin/serviceIdentityModel';
import { useServiceIdentity } from '../../../components/Admin/useServiceIdentity';
import { useToast } from '../../../components/shared/Toast';
import { useTranslation } from '../../../i18n';
import { useSettingsStore } from '../../../store/settingsStore';
import type { TranslationFn } from '../../../types';
import { getApiErrorMessage } from '../../../utils/apiError';
import MConfirmSheet from '../settings/MConfirmSheet';
import { MAdminButton } from './MAdminUi';
const STATE_DOT: Record<ServiceIdentityState, string> = {
connected: 'bg-[color:var(--m-st-confirmed)]',
registering: 'bg-[color:var(--m-st-pending)] motion-safe:animate-pulse',
legacy: 'bg-[color:var(--m-faint)]',
off: 'bg-[color:var(--m-faint)]',
revoked: 'bg-[color:var(--m-st-danger)]',
};
const BAR: Record<QuotaLevel, string> = {
ok: 'bg-m-act',
low: 'bg-[color:var(--m-st-pending)]',
out: 'bg-[color:var(--m-st-danger)]',
};
const FIGURE: Record<QuotaLevel, string> = {
ok: 'text-m-ink',
low: 'text-[color:var(--m-st-pending)]',
out: 'text-[color:var(--m-st-danger)]',
};
const SERVICE_ICON: Record<string, LucideIcon> = { places: MapPin, photon: Search, valhalla: Route };
/** The tier, an operator key from the environment and the reset, as one quiet line (the desktop's badges). */
function quotaMeta(t: TranslationFn, status: ServiceIdentityStatus | null, resetAt: string | null): string {
if (!status) return '';
const parts = [
status.tier ? t(`admin.trekApi.quota.tier.${status.tier}`) : null,
status.keySource === 'env' ? `${t('admin.trekApi.quota.key')}: TREK_SERVICES_KEY` : null,
resetAt ? `${t('admin.trekApi.quota.resets')} ${resetAt}` : null,
];
return parts.filter(Boolean).join(', ');
}
function MQuotaRow({ allowance }: { allowance: ServiceAllowance }) {
const { t, locale } = useTranslation();
const number = new Intl.NumberFormat(locale);
const name = t(`admin.trekApi.quota.service.${allowance.service}`);
const note = allowanceNote(t, allowance);
const quota = allowance.quota;
const Icon = SERVICE_ICON[allowance.service] ?? MapPin;
return (
<li className={`py-[9px] ${allowance.inUse ? '' : 'opacity-60'}`}>
<div className="flex items-center gap-2">
<Icon size={13} strokeWidth={2} aria-hidden className="flex-none text-m-faint" />
<span className="min-w-0 flex-1 truncate text-[length:calc(12px*var(--fs-scale-body,1))] font-bold text-m-ink">
{name}
</span>
{quota && (
<span className="flex-none font-geist text-[length:calc(10.5px*var(--fs-scale-caption,1))] tabular-nums text-m-faint">
<span className={`font-bold ${FIGURE[quotaLevel(quota)]}`}>{number.format(quota.used)}</span>
{' / '}
{number.format(quota.limit)}
</span>
)}
</div>
{quota && (
<div
role="progressbar"
aria-label={name}
aria-valuemin={0}
aria-valuemax={quota.limit}
aria-valuenow={quota.used}
className="mt-[6px] h-[5px] overflow-hidden rounded-full bg-[color:var(--m-rowbr)]"
>
<div className={`h-full rounded-full ${BAR[quotaLevel(quota)]}`} style={{ width: `${quotaShare(quota)}%` }} />
</div>
)}
{note && (
<p className="mt-[3px] font-geist text-[length:calc(10px*var(--fs-scale-caption,1))] leading-snug text-m-muted">
{note}
</p>
)}
</li>
);
}
/**
* How this installation stands with the TREK services, the phone's form of the
* desktop ServiceIdentityPanel: its state, today's use per service against the
* allowance, when the count starts again, and a new key when the old one leaked.
* Read while in view and refreshed every 30 seconds (useServiceIdentity).
*/
export default function MAdminServiceQuota({ managed = false }: { managed?: boolean }) {
const { t } = useTranslation();
const toast = useToast();
const panel = useRef<HTMLDivElement>(null);
const { status, failed, regenerating, regenerate } = useServiceIdentity(panel);
const [confirming, setConfirming] = useState(false);
const is12h = useSettingsStore((s) => s.settings.time_format === '12h');
const resetAt = quotaResetClock(status, is12h);
const hint = identityHint(t, status, failed);
const meta = quotaMeta(t, status, resetAt);
const confirmRegenerate = async () => {
setConfirming(false);
try {
await regenerate();
toast.success(t('admin.trekApi.quota.regenerated'));
} catch (err) {
toast.error(getApiErrorMessage(err, t('common.error')));
}
};
return (
<div
ref={panel}
className="rounded-[16px] border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] px-[14px] py-3"
>
<div className="flex items-center gap-2">
<span className="min-w-0 flex-1 truncate text-[length:calc(13px*var(--fs-scale-body,1))] font-bold text-m-ink">
{t('admin.trekApi.quota.title')}
</span>
<span className="inline-flex flex-none items-center gap-[5px] rounded-full bg-[color:var(--m-sheetop)] px-2 py-[2px] font-geist text-[length:calc(10px*var(--fs-scale-caption,1))] font-bold text-m-ink">
<span aria-hidden className={`h-[7px] w-[7px] rounded-full ${STATE_DOT[status?.state ?? 'off']}`} />
{status ? t(`admin.trekApi.quota.state.${status.state}`) : '…'}
</span>
</div>
{meta && (
<p className="mt-[3px] font-geist text-[length:calc(10px*var(--fs-scale-caption,1))] text-m-muted">{meta}</p>
)}
{status && status.services.length > 0 && (
<ul aria-label={t('admin.trekApi.quota.title')} className="mt-1 divide-y divide-[color:var(--m-rowbr)]">
{status.services.map((allowance) => (
<MQuotaRow key={allowance.service} allowance={allowance} />
))}
</ul>
)}
{hint && (
<p className="mt-1 font-geist text-[length:calc(10px*var(--fs-scale-caption,1))] leading-snug text-m-muted">
{hint}
</p>
)}
{canRegenerateKey(status, managed) && (
<div className="mt-2 flex justify-end">
<MAdminButton variant="ghost" busy={regenerating} onClick={() => setConfirming(true)}>
{!regenerating && <RefreshCw size={12} strokeWidth={2.2} />}
{t('admin.trekApi.quota.regenerate')}
</MAdminButton>
</div>
)}
<MConfirmSheet
open={confirming}
onClose={() => setConfirming(false)}
title={t('admin.trekApi.quota.regenerateTitle')}
message={t('admin.trekApi.quota.regenerateBody')}
confirmLabel={t('admin.trekApi.quota.regenerate')}
cancelLabel={t('common.cancel')}
onConfirm={() => void confirmRegenerate()}
/>
</div>
);
}
@@ -1,5 +1,4 @@
import { useState } from 'react'
import { AlertTriangle, ChevronDown, RefreshCw } from 'lucide-react'
import { AlertTriangle, RefreshCw } from 'lucide-react'
import { useAdminSettingsActions } from '../../../components/Admin/useAdminSettingsActions'
import { placesGoogleOnlyHint } from '../../../utils/placeSource'
import type { TranslationFn } from '../../../types'
@@ -8,15 +7,19 @@ import MToggle from '../../components/MToggle'
import { MBlockDisclosure, MProviderBlock, MTrekApiBlock } from './MApiProviderBlocks'
import MAdminOidcCard from './MAdminOidcCard'
import MMailIngestAdminCard from './MMailIngestAdminCard'
import MSetPickerSheet from '../settings/MSetPickerSheet'
import MAdminGoogleDailyLimit from './MAdminGoogleDailyLimit'
import MAdminPlaceContrib from './MAdminPlaceContrib'
import MAdminServiceQuota from './MAdminServiceQuota'
import {
MAdminButton,
MAdminCard,
MAdminCardHead,
MAdminField,
MAdminInput,
MAdminNote,
MAdminRow,
MAdminSecretInput,
MAdminSelect,
} from './MAdminUi'
interface MAdminSettingsSectionProps {
@@ -30,52 +33,50 @@ interface MAdminSettingsSectionProps {
part: 'security' | 'services' | 'features'
}
// The admin's security, services and feature setup sections as phone cards.
// All state and mutations come from useAdmin.
type PartProps = Omit<MAdminSettingsSectionProps, 'part'>
// The admin's security, services and feature setup sections as phone cards,
// one function each. All state and mutations come from useAdmin.
export default function MAdminSettingsSection({ admin, t, part }: MAdminSettingsSectionProps) {
const [providerPickerOpen, setProviderPickerOpen] = useState(false)
if (part === 'features') return <FeaturesPart admin={admin} t={t} />
if (part === 'security') return <SecurityPart admin={admin} t={t} />
return <ServicesPart admin={admin} t={t} />
}
/** Live flights and booking mails: how the integrations of the addons tab reach the world. */
function FeaturesPart({ admin, t }: PartProps) {
const { managed, flightLive, setFlightLive, flightLiveLocked, handleToggleAuthSetting } = admin
return (
<div className="space-y-3">
{/* Live flight status: open ADS-B data, no key, on by default (desktop parity). */}
<FlightLiveCard
t={t}
managed={!!managed}
on={flightLive}
locked={flightLiveLocked}
onChange={(v) => void handleToggleAuthSetting('flight_live_enabled', v, setFlightLive)}
/>
{/* Booking mail import: self-hosted only, the operator runs the TREK Cloud relay (desktop parity). */}
{!managed && <MMailIngestAdminCard />}
</div>
)
}
/** Who may sign in and what it takes, with the one destructive action last. */
function SecurityPart({ admin, t }: PartProps) {
const {
placesPhotosEnabled, placesAutocompleteEnabled, placesDetailsEnabled, placesEnrichEnabled,
placesGoogleOnly, handleTogglePlacesGoogleOnly,
placeShadowEnabled,
passwordLogin, setPasswordLogin, passwordRegistration, setPasswordRegistration,
oidcLogin, setOidcLogin, oidcRegistration, setOidcRegistration, oidcAutoRedirect, setOidcAutoRedirect,
flightLive, setFlightLive, flightLiveLocked,
envOverrideOidcOnly, oidcConfigured, requireMfa,
passkeyLogin, setPasskeyLogin, passkeyConfigured,
webauthnRpId, setWebauthnRpId, webauthnOrigins, setWebauthnOrigins, savingWebauthn, handleSaveWebauthn,
allowedFileTypes, setAllowedFileTypes, savingFileTypes,
mapsKey, setMapsKey, unsplashKey, setUnsplashKey, amapKey, setAmapKey, hasMapsKey, hasAmapKey, keyInputProps, mapsKeyTestable, savingKeys, validating, validation,
placesProvider, savingPlacesProvider, handleSavePlacesProvider,
managed,
setShowRotateJwtModal,
handleToggleAuthSetting, handleToggleRequireMfa,
handleSaveApiKeys, handleValidateKey,
} = admin
const { saveOidc } = useAdminSettingsActions(admin, t)
const {
saveOidc, saveFileTypes, togglePlacesPhotos, togglePlacesAutocomplete, togglePlacesDetails, togglePlacesEnrich,
togglePlaceShadow,
} = useAdminSettingsActions(admin, t)
if (part === 'features') {
return (
<div className="space-y-3">
{/* Live flight status: open ADS-B data, no key, on by default (desktop parity). */}
<FlightLiveCard
t={t}
managed={!!managed}
on={flightLive}
locked={flightLiveLocked}
onChange={(v) => void handleToggleAuthSetting('flight_live_enabled', v, setFlightLive)}
/>
{/* Booking mail import: self-hosted only, the operator runs the TREK Cloud relay (desktop parity). */}
{!managed && <MMailIngestAdminCard />}
</div>
)
}
if (part === 'security') return (
return (
<div className="space-y-3">
{/* Authentication methods, with the passkey switch and the 2FA rule: they are ways in too. */}
<MAdminCard>
@@ -230,30 +231,117 @@ export default function MAdminSettingsSection({ admin, t, part }: MAdminSettings
)}
</div>
)
}
// Services: what the install talks to outside, and the file types it takes.
/** What the install talks to outside: place search and routing, the keys, the file types. */
function ServicesPart({ admin, t }: PartProps) {
const {
placesPhotosEnabled, placesAutocompleteEnabled, placesDetailsEnabled, placesEnrichEnabled,
placesGoogleOnly, handleTogglePlacesGoogleOnly,
placeShadowEnabled,
transitProvider, transitGoogleKeySource,
allowedFileTypes, setAllowedFileTypes, savingFileTypes,
mapsKey, setMapsKey, unsplashKey, setUnsplashKey, amapKey, setAmapKey, hasMapsKey, hasAmapKey, keyInputProps, mapsKeyTestable, savingKeys, validating, validation,
placesProvider, savingPlacesProvider, handleSavePlacesProvider,
managed,
handleSaveApiKeys, handleValidateKey,
} = admin
const {
saveFileTypes, togglePlacesPhotos, togglePlacesAutocomplete, togglePlacesDetails, togglePlacesEnrich,
togglePlaceShadow, changeTransitProvider,
} = useAdminSettingsActions(admin, t)
// Services, cut like the desktop tab: place search and routing (TREK's own
// services, which provider answers what, the search log), then the keys for
// the keyed providers, then the file types.
const providerMissingKey = (placesProvider === 'google' && !hasMapsKey) || (placesProvider === 'amap' && !hasAmapKey)
return (
<div className="space-y-3">
{/* API keys, place search and routing: the operator's on a managed install,
same as the desktop tab, so the whole card is left out. Unlike the desktop
tab, the phone has no share place details section for a managed install. */}
{/* On a managed install place search and routing are the operator's, but
sharing place details stays the admin's decision, as on the desktop. */}
{managed && <MAdminPlaceContrib hideWhenSwitchedOff />}
{!managed && (
<MAdminCard>
<MAdminCardHead title={t('admin.servicesCard.title')} hint={t('admin.servicesCard.hint')} />
<div className="space-y-3">
<MTrekApiBlock />
<MAdminServiceQuota />
<MAdminPlaceContrib />
{/* Transit backend (#1699): Transitous has no GTFS for much of Asia, so an
install can send transit search to Google on the same key. */}
<MAdminField label={t('admin.transitProvider.title')} hint={t('admin.transitProvider.subtitle')}>
<MAdminSelect
title={t('admin.transitProvider.title')}
value={transitProvider}
onChange={(value) => void changeTransitProvider(value)}
options={[
{ value: 'transitous', label: t('admin.transitProvider.transitous') },
{ value: 'google', label: t('admin.transitProvider.google') },
]}
/>
<MAdminNote>
{transitProvider === 'google' ? t('admin.transitProvider.googleHint') : t('admin.transitProvider.transitousHint')}
</MAdminNote>
{/* Google without a key that resolves changes nothing, and a personal key
serves this admin alone: the request-time fallback is silent, so here
is the only place to say it. */}
{transitProvider === 'google' && transitGoogleKeySource === null && (
<MAdminNote warn>{t('admin.transitProvider.noKeyWarning')}</MAdminNote>
)}
{transitProvider === 'google' && transitGoogleKeySource === 'user-row' && (
<MAdminNote warn>{t('admin.transitProvider.personalKeyWarning')}</MAdminNote>
)}
</MAdminField>
{/* Which keyed provider answers place search. */}
<MAdminField label={t('admin.placesProvider.title')} hint={t('admin.placesProvider.subtitle')}>
<MAdminSelect
title={t('admin.placesProvider.title')}
value={placesProvider}
disabled={savingPlacesProvider}
onChange={(value) => void handleSavePlacesProvider(value)}
options={[
{ value: 'auto', label: t('admin.placesProvider.auto') },
{ value: 'google', label: t('admin.placesProvider.google') },
{ value: 'amap', label: t('admin.placesProvider.amap') },
{ value: 'openstreetmap', label: t('admin.placesProvider.openstreetmap') },
]}
/>
{/* From app-config, like the desktop card: the key fields are empty
on a managed install and on an operator key set by environment. */}
{providerMissingKey && <MAdminNote warn>{t('admin.placesProvider.missingKey')}</MAdminNote>}
</MAdminField>
{/* The instance's own search log, which is not Google's to spend. */}
<div>
<MAdminRow
first
title={t('admin.placeShadow.title')}
hint={t('admin.placeShadow.subtitle')}
trailing={
<MToggle
checked={placeShadowEnabled}
ariaLabel={t('admin.placeShadow.title')}
onChange={togglePlaceShadow}
/>
}
/>
</div>
</div>
</MAdminCard>
)}
{/* The keys of the keyed providers, in the desktop order: Google, Unsplash, Amap. */}
{!managed && (
<MAdminCard>
<MAdminCardHead title={t('admin.apiKeys')} hint={t('admin.apiKeysHint')} />
<div className="space-y-3">
{/* Comparable blocks in the order we would have somebody choose them,
matching the desktop tab: the free source first, the keys after it.
The recommendation used to sit on the Google field here, which told
a phone admin the opposite of what the same setting says on a
laptop. */}
<MTrekApiBlock />
<MProviderBlock title={t('admin.mapsKey')} badge={t('admin.googleCaveat.badge')} tone="caution">
{/* Said before the field, not after it: somebody about to paste a key
should read this while deciding, not once they already have. */}
<p className="font-geist text-[0.625rem] leading-relaxed text-m-faint">
{t('admin.mapsKeyHintShort')}
</p>
<MAdminNote>{t('admin.mapsKeyHintShort')}</MAdminNote>
<div className="flex gap-2">
<div className="min-w-0 flex-1">
<MAdminSecretInput
@@ -274,18 +362,17 @@ export default function MAdminSettingsSection({ admin, t, part }: MAdminSettings
</MAdminButton>
</div>
{validation.maps === true && (
<p className="font-geist text-[0.625rem] font-bold text-[color:var(--m-st-confirmed)]">
<p className="font-geist text-[length:calc(10px*var(--fs-scale-caption,1))] font-bold text-[color:var(--m-st-confirmed)]">
{t('admin.keyValid')}
</p>
)}
{validation.maps === false && (
<p className="font-geist text-[0.625rem] font-bold text-[color:var(--m-st-danger)]">
<p className="font-geist text-[length:calc(10px*var(--fs-scale-caption,1))] font-bold text-[color:var(--m-st-danger)]">
{t('admin.keyInvalid')}
</p>
)}
{/* What the key is allowed to be spent on. Under the key rather than
loose at the foot of the card: every one of them is a Google
request, and none of them mean anything without it. */}
{/* What the key may be spent on, and how much of it a day. Under the key:
every one of them is a Google request. */}
<MBlockDisclosure label={t('admin.placesUsageTitle')}>
<MAdminRow
title={t('admin.placesPhotos.title')}
@@ -342,23 +429,12 @@ export default function MAdminSettingsSection({ admin, t, part }: MAdminSettings
/>
}
/>
<MAdminGoogleDailyLimit />
</MBlockDisclosure>
</MProviderBlock>
{/* No Test button, same as the desktop tab: /auth/validate-keys only
knows how to probe Google Places and OpenWeatherMap. */}
<MProviderBlock title={t('admin.amapKey')}>
<p className="font-geist text-[0.625rem] leading-relaxed text-m-faint">{t('admin.amapKeyHintShort')}</p>
<MAdminSecretInput
aria-label={t('admin.amapKey')}
value={amapKey}
onChange={(e) => setAmapKey(e.target.value)}
{...keyInputProps('amap')}
/>
</MProviderBlock>
<MProviderBlock title={t('admin.unsplashKey')}>
<p className="font-geist text-[0.625rem] leading-relaxed text-m-faint">{t('admin.unsplashKeyHint')}</p>
<MAdminNote>{t('admin.unsplashKeyHint')}</MAdminNote>
<MAdminSecretInput
aria-label={t('admin.unsplashKey')}
value={unsplashKey}
@@ -367,56 +443,17 @@ export default function MAdminSettingsSection({ admin, t, part }: MAdminSettings
/>
</MProviderBlock>
<MAdminField label={t('admin.placesProvider.title')} hint={t('admin.placesProvider.subtitle')}>
{/* The app's own picker rather than a bare <select>: a native one is
drawn by the operating system and was the one control on this page
that did not belong to TREK. Same sheet the settings selects use. */}
<button
type="button"
disabled={savingPlacesProvider}
onClick={() => setProviderPickerOpen(true)}
className="flex h-[42px] w-full items-center gap-2 rounded-xl border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] px-3 text-start text-[0.84375rem] text-m-ink disabled:opacity-50"
>
<span className="min-w-0 flex-1 truncate">{t(`admin.placesProvider.${placesProvider}`)}</span>
<ChevronDown size={15} strokeWidth={2.2} className="flex-none text-m-faint" aria-hidden />
</button>
<MSetPickerSheet
open={providerPickerOpen}
onClose={() => setProviderPickerOpen(false)}
title={t('admin.placesProvider.title')}
value={placesProvider}
onSelect={(value) => { if (value !== placesProvider) void handleSavePlacesProvider(value) }}
options={[
{ value: 'auto', label: t('admin.placesProvider.auto') },
{ value: 'google', label: t('admin.placesProvider.google') },
{ value: 'amap', label: t('admin.placesProvider.amap') },
{ value: 'openstreetmap', label: t('admin.placesProvider.openstreetmap') },
]}
{/* No Test button, same as the desktop tab: /auth/validate-keys only
knows how to probe Google Places and OpenWeatherMap. */}
<MProviderBlock title={t('admin.amapKey')}>
<MAdminNote>{t('admin.amapKeyHintShort')}</MAdminNote>
<MAdminSecretInput
aria-label={t('admin.amapKey')}
value={amapKey}
onChange={(e) => setAmapKey(e.target.value)}
{...keyInputProps('amap')}
/>
{/* From app-config, like the desktop card: the key fields are empty
on a managed install and on an operator key set by environment. */}
{((placesProvider === 'google' && !hasMapsKey) || (placesProvider === 'amap' && !hasAmapKey)) && (
<p className="mt-1 font-geist text-[0.625rem] font-bold text-[color:var(--m-st-pending)]">
{t('admin.placesProvider.missingKey')}
</p>
)}
</MAdminField>
<div>
{/* The instance's own search log, which is not Google's to spend. */}
<MAdminRow
first
title={t('admin.placeShadow.title')}
hint={t('admin.placeShadow.subtitle')}
trailing={
<MToggle
checked={placeShadowEnabled}
ariaLabel={t('admin.placeShadow.title')}
onChange={togglePlaceShadow}
/>
}
/>
</div>
</MProviderBlock>
<MAdminButton busy={savingKeys} onClick={handleSaveApiKeys}>
{t('common.save')}
+14 -1
View File
@@ -80,10 +80,23 @@ export function MAdminClampedText({ children, className = '' }: { children: stri
)
}
/** A short line in a card body: a fact under a control, or (warn) what a setting will not do as things stand. */
export function MAdminNote({ warn = false, children }: { warn?: boolean; children: ReactNode }) {
return (
<p
className={`mt-[5px] font-geist text-[length:calc(10px*var(--fs-scale-caption,1))] leading-relaxed ${
warn ? 'font-bold text-[color:var(--m-st-pending)]' : 'text-m-muted'
}`}
>
{children}
</p>
)
}
/** Labelled form field; its hint waits behind the label's info mark. */
export function MAdminField({ label, hint, children }: { label: ReactNode; hint?: ReactNode; children: ReactNode }) {
return (
<div>
<div data-m-field="">
<div className="mb-[5px]">
<MHintLabel
label={label}
@@ -100,7 +100,7 @@ describe('AdminSettingsTab', () => {
expect(screen.getByRole('heading', { name: 'Authentication Methods' })).toBeInTheDocument();
expect(screen.getByRole('heading', { name: 'Passkey login' })).toBeInTheDocument();
// Requiring two-factor is a switch of the sign-in card now, not a card of its own.
expect(screen.getByText(/require two-factor/i)).toBeInTheDocument();
expect(screen.getByText(/require 2fa/i)).toBeInTheDocument();
expect(screen.getByRole('heading', { name: 'Allowed File Types' })).toBeInTheDocument();
expect(screen.getByRole('heading', { name: 'API Keys' })).toBeInTheDocument();
expect(screen.getByRole('heading', { name: /single sign-on/i })).toBeInTheDocument();
+4 -24
View File
@@ -1,6 +1,4 @@
import React from 'react'
import { adminApi } from '../../api/client'
import { getApiErrorMessage } from '../../types'
import {
AlertTriangle, CheckCircle, Compass, Eye, EyeOff, FileType, Fingerprint, KeyRound, Loader2, LockKeyhole, LogIn,
Plane, RefreshCw, Save, XCircle,
@@ -120,11 +118,10 @@ function SaveBar({ onClick, saving, label }: { onClick: () => void; saving: bool
// "Settings" tab. Pure layout around the useAdmin hook.
export default function AdminSettingsTab({ admin, t, part }: AdminSettingsTabProps): React.ReactElement {
const {
toast,
placesPhotosEnabled, placesAutocompleteEnabled, placesDetailsEnabled, placesEnrichEnabled,
placesGoogleOnly, handleTogglePlacesGoogleOnly,
transitProvider, setTransitProviderState,
transitGoogleKeySource, setTransitGoogleKeySource,
transitProvider,
transitGoogleKeySource,
placeShadowEnabled,
oidcConfig, setOidcConfig, savingOidc,
passwordLogin, setPasswordLogin, passwordRegistration, setPasswordRegistration,
@@ -143,7 +140,7 @@ export default function AdminSettingsTab({ admin, t, part }: AdminSettingsTabPro
} = admin
const {
saveOidc, saveFileTypes, togglePlacesPhotos, togglePlacesAutocomplete, togglePlacesDetails, togglePlacesEnrich,
togglePlaceShadow,
togglePlaceShadow, changeTransitProvider,
} = useAdminSettingsActions(admin, t)
const passwordLoginLocked = !passwordLogin && !oidcLogin
@@ -452,24 +449,7 @@ export default function AdminSettingsTab({ admin, t, part }: AdminSettingsTabPro
the body, which is what lets it escape the card's overflow-hidden. */}
<CustomSelect
value={transitProvider}
onChange={async value => {
// A native select stayed silent when the option already selected was
// picked again; this one reports every pick, and a no-op PUT is still
// a write on an audited settings route.
if (value === transitProvider) return
const next = value === 'google' ? 'google' : 'transitous'
const previous = transitProvider
setTransitProviderState(next)
try {
const saved = await adminApi.updateTransitProvider(next)
setTransitGoogleKeySource(saved.googleKeySource)
} catch (err: unknown) {
// The select springs back on its own; without a word that reads
// as a broken control, not as a save that failed.
setTransitProviderState(previous)
toast.error(getApiErrorMessage(err, t('common.error')))
}
}}
onChange={value => void changeTransitProvider(String(value))}
options={[
{ value: 'transitous', label: t('admin.transitProvider.transitous') },
{ value: 'google', label: t('admin.transitProvider.google') },