feat(settings): one look for every user and admin settings page

The settings pages had grown into a mix of styles: folds, dialogs behind
rows, full-width rows next to boxed ones, pills for every figure and buttons
in four sizes. Every page now uses the same kit.

- Cards keep their tinted head band; every part of a card is a rounded block
  with its own small head (SettingsBlock), and rows sit in rounded boxes.
- Nothing folds and nothing hides behind a dialog: the MCP config, OAuth
  scopes, mail how-to, AI privacy note and addon sub-options are all shown.
- Each page is split into two columns balanced by length (SettingsColumns).
- Long explanations moved into an info mark next to the label (HintMark).
- One button size everywhere (text-control); tab names are one word.
- Admin: the old Settings tab is split into Security and Services
  (?tab=settings still opens Security, and the phone keeps its single
  Settings section for both); the Integration group is gone, live flights
  and mail import sit next to the addons they configure.
- Addons: one card per type with rows, no search, filter or fold.
- Quota, TREK API facts, mail import status and Google's daily limit are
  compact lines and strips instead of tiles and pills.
- Language is a select; routing has its own card under the defaults;
  storage saves from the foot of its categories card.
- Unused keys, FoldSummary and the page-width wrapper are removed.
This commit is contained in:
Maurice
2026-11-13 23:18:28 +01:00
parent 5fe3dea4cc
commit 94ac7673a5
138 changed files with 1299 additions and 2188 deletions
+62 -58
View File
@@ -9,9 +9,7 @@ import ConfirmDialog from '../shared/ConfirmDialog'
import { Tooltip } from '../shared/Tooltip'
import { DialogButton, DialogFooter, DialogHeader, DialogShell, DialogTile, FooterSpacer, NEUTRAL_TINT, fs } from '../shared/DialogShell'
import { EditorField, GRID_2, INPUT, PANEL } from '../shared/dialogParts'
import {
SETTINGS_BUTTON, SETTINGS_BUTTON_DANGER, SETTINGS_BUTTON_PRIMARY, SettingRow, SettingRows, SettingsHint, StatusPill,
} from './settingsKit'
import { SETTINGS_BUTTON, SETTINGS_BUTTON_DANGER, SETTINGS_BUTTON_PRIMARY, SettingRow, SettingRows, SettingsHint, StatusPill, SettingsColumns } from './settingsKit'
import { stripTrailingSlashes, useAccountSettings } from './useAccountSettings'
import AccountDemoLock from './AccountDemoLock'
@@ -76,6 +74,10 @@ export default function AccountTab(): React.ReactElement {
<NativeServerSection />
{/* The shared demo account: everything here is shown, nothing can be changed. */}
<AccountDemoLock>
{/* Two columns by length: who you are and the second factor on the left,
the password and passkeys on the right. */}
<SettingsColumns
left={<>
<Section title={t('settings.account')} icon={User}>
{/* Who is signed in: the picture with its two actions, the role and the SSO link. */}
<div className="flex items-center gap-4 rounded-[14px] border border-edge-faint bg-surface-card px-4 py-3.5">
@@ -169,54 +171,6 @@ export default function AccountTab(): React.ReactElement {
</div>
</Section>
{/* Change Password */}
{!oidcOnlyMode && (
<Section title={t('settings.changePassword')} icon={Lock}>
<EditorField label={t('settings.currentPassword')} htmlFor="account-current-password">
<input
id="account-current-password"
type="password"
value={currentPassword}
onChange={e => setCurrentPassword(e.target.value)}
placeholder={t('settings.currentPassword')}
className={INPUT}
/>
</EditorField>
<div className={GRID_2}>
<EditorField label={t('settings.newPassword')} htmlFor="account-new-password">
<input
id="account-new-password"
type="password"
value={newPassword}
onChange={e => setNewPassword(e.target.value)}
placeholder={t('settings.newPassword')}
className={INPUT}
/>
</EditorField>
<EditorField label={t('settings.confirmPassword')} htmlFor="account-confirm-password">
<input
id="account-confirm-password"
type="password"
value={confirmPassword}
onChange={e => setConfirmPassword(e.target.value)}
placeholder={t('settings.confirmPassword')}
className={INPUT}
/>
</EditorField>
</div>
<PasswordChecklist password={newPassword} />
<div className="flex justify-end" style={fs(13, 'body')}>
<button type="button"
onClick={changePassword}
className={SETTINGS_BUTTON}
>
<Lock size={14} />
{t('settings.updatePassword')}
</button>
</div>
</Section>
)}
{/* MFA */}
<Section title={t('settings.mfa.title')} icon={KeyRound}>
{mfaRequiredByPolicy && (
@@ -236,7 +190,6 @@ export default function AccountTab(): React.ReactElement {
disabled={mfaLoading}
onClick={startMfaSetup}
className={SETTINGS_BUTTON}
style={fs(13, 'body')}
>
{mfaLoading ? <span className={SPINNER} /> : <KeyRound size={14} />}
{t('settings.mfa.setup')}
@@ -296,7 +249,7 @@ export default function AccountTab(): React.ReactElement {
{user?.mfa_enabled && (
<div className={PANEL}>
<div>
<p className={EYEBROW} style={fs(10)}>{t('settings.mfa.disableTitle')}</p>
<p className={EYEBROW}>{t('settings.mfa.disableTitle')}</p>
<SettingsHint className="mt-1">{t('settings.mfa.disableHint')}</SettingsHint>
</div>
<div className={GRID_2}>
@@ -319,7 +272,7 @@ export default function AccountTab(): React.ReactElement {
className={`${INPUT} font-geist tabular-nums`}
/>
</div>
<div className="flex justify-end" style={fs(13, 'body')}>
<div className="flex justify-end">
<button
type="button"
disabled={mfaLoading || !mfaDisablePwd || mfaDisableCode.length < 6}
@@ -335,14 +288,14 @@ export default function AccountTab(): React.ReactElement {
{backupCodes && backupCodes.length > 0 && (
<div className={PANEL}>
<div>
<p className="m-0 font-semibold text-content" style={fs(13, 'body')}>{t('settings.mfa.backupTitle')}</p>
<p className="m-0 font-semibold text-content">{t('settings.mfa.backupTitle')}</p>
<SettingsHint className="mt-0.5">{t('settings.mfa.backupDescription')}</SettingsHint>
</div>
<pre className="m-0 max-h-[220px] overflow-auto rounded-[12px] border border-edge-faint bg-surface-card px-3.5 py-3 font-geist tabular-nums leading-relaxed tracking-wide text-content" style={fs(12.5, 'body')}>{backupCodesText}</pre>
<p className="m-0 flex items-center gap-1.5 font-medium text-warning" style={fs(11.5)}>
<pre className="m-0 max-h-[220px] overflow-auto rounded-[12px] border border-edge-faint bg-surface-card px-3.5 py-3 font-geist tabular-nums leading-relaxed tracking-wide text-content">{backupCodesText}</pre>
<p className="m-0 flex items-center gap-1.5 font-medium text-warning">
<AlertTriangle size={13} className="flex-none" />{t('settings.mfa.backupWarning')}
</p>
<div className="flex flex-wrap items-center gap-2" style={fs(12.5, 'body')}>
<div className="flex flex-wrap items-center gap-2">
<button type="button" onClick={copyBackupCodes} className={SETTINGS_BUTTON}>
<Copy size={13} /> {t('settings.mfa.backupCopy')}
</button>
@@ -361,9 +314,60 @@ export default function AccountTab(): React.ReactElement {
)}
</>
</Section>
</>}
right={<>
{/* Change Password */}
{!oidcOnlyMode && (
<Section title={t('settings.changePassword')} icon={Lock}>
<EditorField label={t('settings.currentPassword')} htmlFor="account-current-password">
<input
id="account-current-password"
type="password"
value={currentPassword}
onChange={e => setCurrentPassword(e.target.value)}
placeholder={t('settings.currentPassword')}
className={INPUT}
/>
</EditorField>
<div className={GRID_2}>
<EditorField label={t('settings.newPassword')} htmlFor="account-new-password">
<input
id="account-new-password"
type="password"
value={newPassword}
onChange={e => setNewPassword(e.target.value)}
placeholder={t('settings.newPassword')}
className={INPUT}
/>
</EditorField>
<EditorField label={t('settings.confirmPassword')} htmlFor="account-confirm-password">
<input
id="account-confirm-password"
type="password"
value={confirmPassword}
onChange={e => setConfirmPassword(e.target.value)}
placeholder={t('settings.confirmPassword')}
className={INPUT}
/>
</EditorField>
</div>
<PasswordChecklist password={newPassword} />
<div className="flex justify-end" style={fs(13, 'body')}>
<button type="button"
onClick={changePassword}
className={SETTINGS_BUTTON}
>
<Lock size={14} />
{t('settings.updatePassword')}
</button>
</div>
</Section>
)}
{/* Passkeys */}
<PasskeysSection demoMode={demoMode} />
</>}
/>
</AccountDemoLock>
{/* Delete Account Blocked */}
@@ -6,7 +6,6 @@ import { server } from '../../../tests/helpers/msw/server';
import { resetAllStores } from '../../../tests/helpers/store';
import { ToastContainer } from '../shared/Toast';
import AirTrailConnectionSection from './AirTrailConnectionSection';
import { openSettingsCards } from '../../../tests/helpers/settingsCards';
interface SavedBody {
url: string;
@@ -38,8 +37,6 @@ function toggleNextTo(label: string): HTMLElement {
}
beforeEach(() => {
// The cards start shut; these tests read into them.
openSettingsCards();
resetAllStores();
vi.clearAllMocks();
stubSettings();
@@ -5,7 +5,7 @@ import { useAirTrailSettings } from './useAirTrailSettings'
import AirTrailIcon from '../shared/AirTrailIcon'
import Section from './Section'
import ToggleSwitch from './ToggleSwitch'
import { SETTINGS_BUTTON, SETTINGS_BUTTON_PRIMARY, SettingRow, SettingRows, SettingsHint, StatusPill } from './settingsKit'
import { SETTINGS_BUTTON, SETTINGS_BUTTON_PRIMARY, SettingRow, SettingRows, StatusPill } from './settingsKit'
import { EditorField, GRID_2, INPUT } from '../shared/dialogParts'
import { fs } from '../shared/DialogShell'
@@ -41,9 +41,10 @@ export default function AirTrailConnectionSection(): React.ReactElement {
return (
<Section
id="airtrail"
collapsible
title={t('settings.airtrail.title')}
hint={t('settings.airtrail.hint')}
icon={AirTrailIcon}
iconFill
badge={
<StatusPill tone={connected ? 'success' : 'neutral'} icon={<span className="h-1.5 w-1.5 rounded-full bg-current" />}>
{connected ? t('settings.airtrail.connected') : t('settings.airtrail.notConnected')}
@@ -107,7 +108,6 @@ export default function AirTrailConnectionSection(): React.ReactElement {
</button>
</div>
<SettingsHint>{t('settings.airtrail.hint')}</SettingsHint>
</Section>
)
}
@@ -9,7 +9,6 @@ import { resetAllStores, seedStore } from '../../../tests/helpers/store';
import { buildUser } from '../../../tests/helpers/factories';
import { ToastContainer } from '../shared/Toast';
import ApiKeysSection from './ApiKeysSection';
import { openSettingsCards } from '../../../tests/helpers/settingsCards';
const clipboardWriteText = vi.fn().mockResolvedValue(undefined);
@@ -22,8 +21,6 @@ beforeAll(() => {
});
beforeEach(() => {
// The cards start shut; these tests read into them.
openSettingsCards();
clipboardWriteText.mockReset();
clipboardWriteText.mockResolvedValue(undefined);
resetAllStores();
@@ -239,12 +239,11 @@ export default function ApiKeysSection(): React.ReactElement {
<>
<Section
id="api-keys"
collapsible
title={t('settings.apiKeys.title')}
icon={KeyRound}
badge={keys.length > 0 ? <StatusPill>{keys.length}/{MAX_KEYS}</StatusPill> : undefined}
action={(
<button type="button" onClick={openModal} disabled={atLimit} className={SETTINGS_BUTTON_PRIMARY} style={fs(12.5, 'body')}>
<button type="button" onClick={openModal} disabled={atLimit} className={SETTINGS_BUTTON_PRIMARY}>
<Plus size={14} /> {t('settings.apiKeys.create')}
</button>
)}
@@ -5,7 +5,7 @@ import { DialogSection, fs } from '../shared/DialogShell'
import { Segmented } from '../shared/dialogParts'
import Section from './Section'
import ToggleSwitch from './ToggleSwitch'
import { SETTINGS_BUTTON, SettingRow, SettingRows, StatusPill } from './settingsKit'
import { SETTINGS_BUTTON, SettingRow, SettingRows, SettingsColumns, StatusPill } from './settingsKit'
import { APPEARANCE_SCHEMES, CUSTOM_ACCENT_PRESETS } from '../../theme/schemes'
import { APPEARANCE_SCALE_MIN, APPEARANCE_SCALE_MAX } from '@trek/shared'
import { DESKTOP_GROUPS, MOBILE_GROUPS, isHex } from './appearanceModel'
@@ -44,6 +44,8 @@ export default function AppearanceSettingsTab(): React.ReactElement {
return (
<>
<SettingsColumns
left={<>
{/* ── Theme ───────────────────────────────────────────────── */}
<Section title={tr('settings.appearance.theme', 'Theme')} icon={Paintbrush}>
<SettingRows>
@@ -70,7 +72,8 @@ export default function AppearanceSettingsTab(): React.ReactElement {
{/* Color scheme swatches */}
<SettingRow label={tr('settings.appearance.scheme', 'Color scheme')} stacked>
<div className="grid grid-cols-2 gap-2 sm:grid-cols-4">
{/* As many per line as fit at a width that holds every name in full. */}
<div className="grid grid-cols-[repeat(auto-fill,minmax(140px,1fr))] gap-2">
{APPEARANCE_SCHEMES.map((s) => {
const active = cfg.schemeId === s.id
const dot = isDark ? s.swatch.dark : s.swatch.light
@@ -208,6 +211,8 @@ export default function AppearanceSettingsTab(): React.ReactElement {
</SettingRows>
</Section>
</>}
right={<>
{/* ── Dashboard widgets ───────────────────────────────────── */}
<Section
title={tr('settings.appearance.dashboardWidgets', 'Dashboard widgets')}
@@ -236,12 +241,12 @@ export default function AppearanceSettingsTab(): React.ReactElement {
hint={tr('settings.appearance.sidebarHint', 'The whole right column. Turn off and the dashboard centers.')}
control={<ToggleSwitch on={masterOn} onToggle={() => setWidget('desktop', g.master as string, !masterOn)}
label={tr(`settings.appearance.widget.${g.master}`, WIDGET_LABELS[g.master])} />}
>
{/* Its widgets only matter while the column is shown: dimmed, not hidden, while it is off. */}
<SettingRows className={`bg-surface-secondary transition-opacity ${masterOn ? '' : 'pointer-events-none opacity-40'}`}>
{rows}
</SettingRows>
</SettingRow>
/>
{/* Its widgets, indented under it in the same block. They only matter while the
column is shown: dimmed, not hidden, while it is off. */}
<div className={`divide-y divide-edge-faint ps-6 transition-opacity ${masterOn ? '' : 'pointer-events-none opacity-40'}`}>
{rows}
</div>
</SettingRows>
)
})}
@@ -265,9 +270,11 @@ export default function AppearanceSettingsTab(): React.ReactElement {
</div>
</DialogSection>
</Section>
</>}
/>
<div className="mb-6 flex justify-end">
<button type="button" onClick={resetAll} className={SETTINGS_BUTTON} style={fs(13, 'body')}>
<button type="button" onClick={resetAll} className={SETTINGS_BUTTON}>
<RotateCcw size={14} strokeWidth={2} />
{tr('settings.appearance.reset', 'Reset to defaults')}
</button>
@@ -46,7 +46,6 @@ import { render, screen, waitFor } from '../../../tests/helpers/render';
import { server } from '../../../tests/helpers/msw/server';
import { resetAllStores } from '../../../tests/helpers/store';
import DawarichConnectionSection from './DawarichConnectionSection';
import { openSettingsCards } from '../../../tests/helpers/settingsCards';
const toast = { success: vi.fn(), error: vi.fn(), info: vi.fn(), warning: vi.fn() };
vi.mock('../shared/Toast', () => ({
@@ -157,8 +156,6 @@ function testButton(): HTMLElement {
}
beforeEach(() => {
// The cards start shut; these tests read into them.
openSettingsCards();
resetAllStores();
vi.clearAllMocks();
stubSettings();
@@ -6,7 +6,7 @@ import { useDawarichConnection } from '../../hooks/useDawarichConnection'
import DawarichIcon from '../shared/DawarichIcon'
import Section from './Section'
import ToggleSwitch from './ToggleSwitch'
import { SETTINGS_BUTTON, SETTINGS_BUTTON_DANGER, SETTINGS_BUTTON_PRIMARY, SettingRow, SettingRows, SettingsHint, StatusPill } from './settingsKit'
import { SETTINGS_BUTTON, SETTINGS_BUTTON_DANGER, SETTINGS_BUTTON_PRIMARY, SettingRow, SettingRows, StatusPill } from './settingsKit'
import { EditorField, GRID_2, INPUT } from '../shared/dialogParts'
import { fs } from '../shared/DialogShell'
@@ -30,16 +30,16 @@ export default function DawarichConnectionSection(): React.ReactElement {
return (
<Section
id="dawarich"
collapsible
title={t('dawarich.title')}
hint={t('dawarich.intro')}
icon={DawarichIcon}
iconFill
badge={
<StatusPill tone={S.connected ? 'success' : 'neutral'} icon={<span className="h-1.5 w-1.5 rounded-full bg-current" />}>
{S.connected ? t('dawarich.connected') : t('dawarich.notConnected')}
</StatusPill>
}
>
<SettingsHint>{t('dawarich.intro')}</SettingsHint>
<div className={GRID_2}>
<EditorField label={t('dawarich.url')} htmlFor="dawarich-url">
@@ -1,5 +1,5 @@
// FE-COMP-DISPLAY-001 to FE-COMP-DISPLAY-057
import { render, screen, within, fireEvent } from '../../../tests/helpers/render';
import { render, screen, within } from '../../../tests/helpers/render';
import userEvent from '@testing-library/user-event';
import { http, HttpResponse } from 'msw';
import { server } from '../../../tests/helpers/msw/server';
@@ -57,20 +57,20 @@ describe('DisplaySettingsTab', () => {
expect(screen.getByText(/12h/i)).toBeInTheDocument();
});
it('FE-COMP-DISPLAY-015: clicking a language button calls updateSetting with that language code', async () => {
it('FE-COMP-DISPLAY-015: picking a language in the select calls updateSetting with its code', async () => {
const user = userEvent.setup();
const updateSetting = vi.fn().mockResolvedValue(undefined);
seedStore(useSettingsStore, { settings: buildSettings({ language: 'en' }), updateSetting });
render(<DisplaySettingsTab />);
await user.click(screen.getByText('Deutsch'));
await user.click(screen.getByRole('button', { name: 'Language' }));
await user.click(await screen.findByText('Deutsch'));
expect(updateSetting).toHaveBeenCalledWith('language', 'de');
});
it('FE-COMP-DISPLAY-016: active language button is visually highlighted', () => {
it('FE-COMP-DISPLAY-016: the language select shows the current language', () => {
seedStore(useSettingsStore, { settings: buildSettings({ language: 'en' }) });
render(<DisplaySettingsTab />);
// "English" is on the chip and on the compact trigger; only the chip is a pressed choice.
expect(screen.getByRole('button', { name: 'English', pressed: true })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Language' })).toHaveTextContent('English');
});
it('FE-COMP-DISPLAY-017: shows Temperature section label', () => {
@@ -199,7 +199,7 @@ describe('DisplaySettingsTab – Display currency', () => {
render(<DisplaySettingsTab />);
await user.click(screen.getByRole('button', { name: 'Same as the app' }));
// The language grid shows the same name, so the option is the last one on screen.
// The app language is German here, so the only English on screen is the place option.
const options = await screen.findAllByText('English');
await user.click(options[options.length - 1]);
@@ -232,85 +232,19 @@ describe('DisplaySettingsTab – Display currency', () => {
});
});
// ── Compact language dropdown (035–039) ───────────────────────────────────────
// ── Language errors (037) ─────────────────────────────────────────────────────
function mobileLangWrap(): HTMLElement {
return optionBlock('Language').querySelector('.sm\\:hidden') as HTMLElement;
}
describe('DisplaySettingsTab – Compact language picker', () => {
it('FE-COMP-DISPLAY-035: the compact trigger shows the active language and opens the list', async () => {
const user = userEvent.setup();
render(<DisplaySettingsTab />);
const wrap = mobileLangWrap();
expect(within(wrap).getAllByRole('button')).toHaveLength(1);
expect(within(wrap).getByText('English')).toBeInTheDocument();
await user.click(within(wrap).getByRole('button'));
expect(within(wrap).getAllByRole('button').length).toBeGreaterThan(1);
});
it('FE-COMP-DISPLAY-036: picking a language from the list saves it and closes the list', async () => {
const user = userEvent.setup();
const updateSetting = vi.fn().mockResolvedValue(undefined);
seedStore(useSettingsStore, { settings: buildSettings({ language: 'en' }), updateSetting });
render(<DisplaySettingsTab />);
const wrap = mobileLangWrap();
await user.click(within(wrap).getByRole('button'));
await user.click(within(wrap).getByText('Deutsch').closest('button')!);
expect(updateSetting).toHaveBeenCalledWith('language', 'de');
expect(within(wrap).getAllByRole('button')).toHaveLength(1);
});
it('FE-COMP-DISPLAY-037: a rejected pick from the list surfaces the error', async () => {
const user = userEvent.setup();
seedFailing('Language locked');
render(<><ToastContainer /><DisplaySettingsTab /></>);
const wrap = mobileLangWrap();
await user.click(within(wrap).getByRole('button'));
await user.click(within(wrap).getByText('Deutsch').closest('button')!);
expect(await screen.findByText('Language locked')).toBeInTheDocument();
});
it('FE-COMP-DISPLAY-048: a rejected pick from the desktop grid surfaces the error', async () => {
describe('DisplaySettingsTab – Language select', () => {
it('FE-COMP-DISPLAY-037: a rejected language pick surfaces the error', async () => {
const user = userEvent.setup();
seedFailing('Language locked');
render(<><ToastContainer /><DisplaySettingsTab /></>);
await user.click(screen.getByText('Deutsch'));
await user.click(screen.getByRole('button', { name: 'Language' }));
await user.click(await screen.findByText('Deutsch'));
expect(await screen.findByText('Language locked')).toBeInTheDocument();
});
it('FE-COMP-DISPLAY-038: a mousedown outside the picker closes it', async () => {
const user = userEvent.setup();
render(<DisplaySettingsTab />);
const wrap = mobileLangWrap();
await user.click(within(wrap).getByRole('button'));
expect(within(wrap).getAllByRole('button').length).toBeGreaterThan(1);
fireEvent.mouseDown(document.body);
expect(within(wrap).getAllByRole('button')).toHaveLength(1);
});
it('FE-COMP-DISPLAY-039: a mousedown inside the picker keeps it open', async () => {
const user = userEvent.setup();
render(<DisplaySettingsTab />);
const wrap = mobileLangWrap();
await user.click(within(wrap).getByRole('button'));
fireEvent.mouseDown(within(wrap).getByText('Deutsch'));
expect(within(wrap).getAllByRole('button').length).toBeGreaterThan(1);
});
});
// ── Map & privacy toggles (040–047) ───────────────────────────────────────────
@@ -1,17 +1,14 @@
import React, { useState, useEffect, useRef } from 'react'
import { Languages, Map, ChevronDown, Rocket } from 'lucide-react'
import React, { useState, useEffect } from 'react'
import { Languages, Map, Rocket } from 'lucide-react'
import { SUPPORTED_LANGUAGES, useTranslation } from '../../i18n'
import { DEFAULT_SETTINGS } from '../../store/settingsStore'
import CustomSelect from '../shared/CustomSelect'
import { Segmented } from '../shared/dialogParts'
import { fs } from '../shared/DialogShell'
import { POPOVER } from '../Packing/packingPopoverStyles'
import { PopoverItem } from '../Packing/PackingPopover'
import { preferredNavAppOptions } from '../Planner/placeNavigation'
import { SYMBOLS, currenciesWith } from '../Budget/BudgetPanel.constants'
import Section from './Section'
import ToggleSwitch from './ToggleSwitch'
import { ChoiceChips, SettingRow, SettingRows } from './settingsKit'
import { SettingRow, SettingRows, SettingsColumns } from './settingsKit'
import { useSettingSaver } from './useSettingSaver'
import { TRIP_TAB_IDS, TRIP_TAB_LABEL_KEYS } from '../../constants/tripTabs'
import { DEFAULT_START_PAGE, DEFAULT_START_TRIP_TAB } from '../../utils/startDestination'
@@ -31,18 +28,6 @@ export default function DisplaySettingsTab(): React.ReactElement {
const demoLocked = useDemoAccountLock()
const [tempUnit, setTempUnit] = useState<string>(settings.temperature_unit || DEFAULT_SETTINGS.temperature_unit)
const [distanceUnit, setDistanceUnit] = useState<DistanceUnit>(settings.distance_unit || DEFAULT_SETTINGS.distance_unit)
const [langOpen, setLangOpen] = useState(false)
const langDropdownRef = useRef<HTMLDivElement | null>(null)
useEffect(() => {
if (!langOpen) return
const handler = (e: MouseEvent) => {
if (langDropdownRef.current && !langDropdownRef.current.contains(e.target as Node)) setLangOpen(false)
}
document.addEventListener('mousedown', handler)
return () => document.removeEventListener('mousedown', handler)
}, [langOpen])
useEffect(() => {
setTempUnit(settings.temperature_unit || DEFAULT_SETTINGS.temperature_unit)
}, [settings.temperature_unit])
@@ -55,12 +40,12 @@ export default function DisplaySettingsTab(): React.ReactElement {
const startPage = settings.start_page === 'active_trip' ? 'active_trip' : DEFAULT_START_PAGE
const startTripTab = settings.start_trip_tab || DEFAULT_START_TRIP_TAB
const currentLanguage = SUPPORTED_LANGUAGES.find(o => o.value === settings.language) || SUPPORTED_LANGUAGES[0]
const pickLanguage = (value: string) => save('language', value)
return (
<>
<SettingsColumns
left={<>
<Section title={t('settings.general.startup')} icon={Rocket}>
<SettingRows>
{/* Where opening TREK lands */}
@@ -127,47 +112,23 @@ export default function DisplaySettingsTab(): React.ReactElement {
}
/>
{/* Language: every option at a glance on a wide window, a compact list on a narrow one.
The shared demo account always runs in English. */}
{/* Language: a select like every other choice in this card. The shared
demo account always runs in English. */}
<DemoLock locked={demoLocked} reason={t('demo.lock.language')} size="row">
<SettingRow label={t('settings.language')} stacked>
<div className="hidden sm:block">
<ChoiceChips
label={t('settings.language')}
value={settings.language}
options={SUPPORTED_LANGUAGES.map(opt => ({ value: opt.value, label: opt.label }))}
onChange={pickLanguage}
/>
</div>
<div ref={langDropdownRef} className="relative sm:hidden">
<button
type="button"
onClick={() => setLangOpen(v => !v)}
aria-expanded={langOpen}
className="flex w-full items-center justify-between gap-2 rounded-[10px] border border-edge bg-surface-input px-3 py-2 text-start font-medium text-content"
style={fs(13, 'body')}
>
<span className="min-w-0 truncate">{currentLanguage?.label}</span>
<ChevronDown size={14} className={`flex-none text-content-faint transition-transform ${langOpen ? 'rotate-180' : ''}`} />
</button>
{langOpen && (
<div className="absolute inset-x-0 top-[calc(100%+4px)] z-50 max-h-[280px] overflow-y-auto" style={POPOVER}>
{SUPPORTED_LANGUAGES.map(opt => (
<PopoverItem
key={opt.value}
icon={null}
label={opt.label}
active={settings.language === opt.value}
onClick={async () => {
setLangOpen(false)
await pickLanguage(opt.value)
}}
/>
))}
</div>
)}
</div>
</SettingRow>
<SettingRow
label={t('settings.language')}
control={
<div className={SELECT_BOX}>
<CustomSelect
value={settings.language || SUPPORTED_LANGUAGES[0].value}
onChange={v => void pickLanguage(String(v))}
options={SUPPORTED_LANGUAGES.map(opt => ({ value: opt.value, label: opt.label }))}
searchable
ariaLabel={t('settings.language')}
/>
</div>
}
/>
</DemoLock>
{/* Place names (#1799): searches can answer in another language than the app. */}
@@ -286,6 +247,8 @@ export default function DisplaySettingsTab(): React.ReactElement {
</SettingRows>
</Section>
</>}
right={
<Section title={t('settings.general.travelMap')} icon={Map}>
<SettingRows>
{/* Preferred map app (#2423): opt-in, the picker stays the default */}
@@ -327,7 +290,8 @@ export default function DisplaySettingsTab(): React.ReactElement {
<OnOffSetting label={t('settings.optimizeFromAccommodation')} hint={t('settings.optimizeFromAccommodationHint')} on={settings.optimize_from_accommodation !== false} onChange={value => saveOnOff('optimize_from_accommodation', value)} />
</SettingRows>
</Section>
</>
}
/>
)
}
@@ -10,7 +10,6 @@ import { resetAllStores, seedStore } from '../../../tests/helpers/store';
import { buildUser } from '../../../tests/helpers/factories';
import { ToastContainer } from '../shared/Toast';
import IntegrationsTab from './IntegrationsTab';
import { openSettingsCards } from '../../../tests/helpers/settingsCards';
function enableMcp() {
seedStore(useAddonStore, {
@@ -32,6 +31,11 @@ function mcpEndpointRow() {
return { code: row.querySelector('code')!, copy: row.querySelector('button')! };
}
/** Waits for the MCP card: its endpoint, clients and tokens are on the page, nothing to open. */
async function openMcp() {
await screen.findByText('MCP Endpoint');
}
const clipboardWriteText = vi.fn().mockResolvedValue(undefined);
function enableAddons(ids: string[]) {
@@ -51,8 +55,6 @@ beforeAll(() => {
});
beforeEach(() => {
// The cards start shut; these tests read into them.
openSettingsCards();
clipboardWriteText.mockClear();
resetAllStores();
useAssistantStore.setState({ status: null });
@@ -91,21 +93,18 @@ describe('IntegrationsTab', () => {
it('FE-COMP-INTEGRATIONS-004: MCP endpoint URL is displayed', async () => {
enableMcp();
render(<IntegrationsTab />);
await screen.findByText('MCP Configuration');
await openMcp();
const { code } = mcpEndpointRow();
expect(code).not.toBeNull();
expect(code.textContent).toContain('/mcp');
});
it('FE-COMP-INTEGRATIONS-005: JSON config block is rendered when expanded', async () => {
const user = userEvent.setup();
it('FE-COMP-INTEGRATIONS-005: JSON config block is always rendered', async () => {
enableMcp();
render(<IntegrationsTab />);
await screen.findByText('MCP Configuration');
// Config is collapsed by default — no <pre> yet
expect(document.querySelector('pre')).toBeNull();
// Expand by clicking the "Client Configuration" toggle
await user.click(screen.getByRole('button', { name: /Client Configuration/i }));
await openMcp();
// The client config is always shown: nothing folds away in the settings.
expect(screen.getByText('Client Configuration')).toBeInTheDocument();
const preEl = document.querySelector('pre');
expect(preEl).not.toBeNull();
expect(preEl!.textContent).toContain('mcpServers');
@@ -115,7 +114,7 @@ describe('IntegrationsTab', () => {
const user = userEvent.setup();
enableMcp();
render(<IntegrationsTab />);
await screen.findByText('MCP Configuration');
await openMcp();
await user.click(screen.getByRole('button', { name: /API Tokens/i }));
expect(await screen.findByText('No tokens yet. Create one to connect MCP clients.')).toBeInTheDocument();
});
@@ -134,7 +133,7 @@ describe('IntegrationsTab', () => {
const user = userEvent.setup();
enableMcp();
render(<IntegrationsTab />);
await screen.findByText('MCP Configuration');
await openMcp();
await user.click(screen.getByRole('button', { name: /API Tokens/i }));
await screen.findByText('My Token');
expect(await screen.findByText('Other Token')).toBeInTheDocument();
@@ -144,7 +143,7 @@ describe('IntegrationsTab', () => {
const user = userEvent.setup();
enableMcp();
render(<IntegrationsTab />);
await screen.findByText('MCP Configuration');
await openMcp();
await user.click(screen.getByRole('button', { name: /API Tokens/i }));
const createBtn = screen.getByRole('button', { name: /Create New Token/i });
await user.click(createBtn);
@@ -155,7 +154,7 @@ describe('IntegrationsTab', () => {
const user = userEvent.setup();
enableMcp();
render(<IntegrationsTab />);
await screen.findByText('MCP Configuration');
await openMcp();
await user.click(screen.getByRole('button', { name: /API Tokens/i }));
await user.click(screen.getByRole('button', { name: /Create New Token/i }));
await screen.findByText('Create API Token');
@@ -167,7 +166,7 @@ describe('IntegrationsTab', () => {
const user = userEvent.setup();
enableMcp();
render(<IntegrationsTab />);
await screen.findByText('MCP Configuration');
await openMcp();
await user.click(screen.getByRole('button', { name: /API Tokens/i }));
await user.click(screen.getByRole('button', { name: /Create New Token/i }));
await screen.findByText('Create API Token');
@@ -194,7 +193,7 @@ describe('IntegrationsTab', () => {
const user = userEvent.setup();
enableMcp();
render(<IntegrationsTab />);
await screen.findByText('MCP Configuration');
await openMcp();
await user.click(screen.getByRole('button', { name: /API Tokens/i }));
await user.click(screen.getByRole('button', { name: /Create New Token/i }));
await screen.findByText('Create API Token');
@@ -224,7 +223,7 @@ describe('IntegrationsTab', () => {
const user = userEvent.setup();
enableMcp();
render(<IntegrationsTab />);
await screen.findByText('MCP Configuration');
await openMcp();
await user.click(screen.getByRole('button', { name: /API Tokens/i }));
await user.click(screen.getByRole('button', { name: /Create New Token/i }));
await screen.findByText('Create API Token');
@@ -250,7 +249,7 @@ describe('IntegrationsTab', () => {
const user = userEvent.setup();
enableMcp();
render(<IntegrationsTab />);
await screen.findByText('MCP Configuration');
await openMcp();
await user.click(screen.getByRole('button', { name: /API Tokens/i }));
await screen.findByText('Delete Me');
await user.click(screen.getByLabelText('Delete Token'));
@@ -276,7 +275,7 @@ describe('IntegrationsTab', () => {
const user = userEvent.setup();
enableMcp();
render(<IntegrationsTab />);
await screen.findByText('MCP Configuration');
await openMcp();
await user.click(screen.getByRole('button', { name: /API Tokens/i }));
await screen.findByText('Delete Me');
await user.click(screen.getByLabelText('Delete Token'));
@@ -294,7 +293,7 @@ describe('IntegrationsTab', () => {
const user = userEvent.setup();
enableMcp();
render(<IntegrationsTab />);
await screen.findByText('MCP Configuration');
await openMcp();
// Spy after userEvent.setup() may have replaced navigator.clipboard
const writeSpy = vi.spyOn(navigator.clipboard, 'writeText').mockResolvedValue(undefined);
await user.click(mcpEndpointRow().copy);
@@ -305,7 +304,7 @@ describe('IntegrationsTab', () => {
const user = userEvent.setup();
enableMcp();
render(<IntegrationsTab />);
await screen.findByText('MCP Configuration');
await openMcp();
vi.spyOn(navigator.clipboard, 'writeText').mockResolvedValue(undefined);
const { copy } = mcpEndpointRow();
await user.click(copy);
@@ -334,7 +333,7 @@ describe('IntegrationsTab', () => {
const user = userEvent.setup();
enableMcp();
render(<IntegrationsTab />);
await screen.findByText('MCP Configuration');
await openMcp();
await user.click(screen.getByRole('button', { name: /API Tokens/i }));
await screen.findByText('Cancel Token');
await user.click(screen.getByLabelText('Delete Token'));
@@ -365,7 +364,7 @@ describe('IntegrationsTab', () => {
const user = userEvent.setup();
enableMcp();
render(<IntegrationsTab />);
await screen.findByText('MCP Configuration');
await openMcp();
await user.click(screen.getByRole('button', { name: /API Tokens/i }));
await user.click(screen.getByRole('button', { name: /Create New Token/i }));
await screen.findByText('Create API Token');
@@ -380,7 +379,7 @@ describe('IntegrationsTab', () => {
it('FE-COMP-INTEGRATIONS-019: default tab is OAuth 2.1 Clients — OAuth hint visible, token list hidden', async () => {
enableMcp();
render(<IntegrationsTab />);
await screen.findByText('MCP Configuration');
await openMcp();
// OAuth hint is visible on the default tab
expect(screen.getByText(/Register OAuth 2\.1 clients/i)).toBeInTheDocument();
// API Tokens "no tokens" message is not rendered
@@ -391,7 +390,7 @@ describe('IntegrationsTab', () => {
const user = userEvent.setup();
enableMcp();
render(<IntegrationsTab />);
await screen.findByText('MCP Configuration');
await openMcp();
// Default: OAuth hint visible, token list absent
expect(screen.getByText(/Register OAuth 2\.1 clients/i)).toBeInTheDocument();
expect(screen.queryByText('No tokens yet. Create one to connect MCP clients.')).toBeNull();
@@ -475,7 +474,7 @@ describe('IntegrationsTab', () => {
const user = userEvent.setup();
enableMcp();
render(<IntegrationsTab />);
await screen.findByText('MCP Configuration');
await openMcp();
await user.click(screen.getByRole('button', { name: /New Client/i }));
await screen.findByText('Register OAuth Client');
expect(screen.getByText('Claude.ai')).toBeInTheDocument();
@@ -486,7 +485,7 @@ describe('IntegrationsTab', () => {
const user = userEvent.setup();
enableMcp();
render(<IntegrationsTab />);
await screen.findByText('MCP Configuration');
await openMcp();
await user.click(screen.getByRole('button', { name: /New Client/i }));
await screen.findByText('Register OAuth Client');
// Presets render as buttons — click "Claude.ai" preset
@@ -516,7 +515,7 @@ describe('IntegrationsTab', () => {
);
enableMcp();
render(<IntegrationsTab />);
await screen.findByText('MCP Configuration');
await openMcp();
await user.click(screen.getByRole('button', { name: /New Client/i }));
await screen.findByText('Register OAuth Client');
@@ -550,7 +549,7 @@ describe('IntegrationsTab', () => {
);
enableMcp();
render(<IntegrationsTab />);
await screen.findByText('MCP Configuration');
await openMcp();
await user.click(screen.getByRole('button', { name: /New Client/i }));
await screen.findByText('Register OAuth Client');
await user.type(screen.getByPlaceholderText(/Claude Web, My MCP App/i), 'TC2');
@@ -646,7 +645,7 @@ describe('IntegrationsTab', () => {
const user = userEvent.setup();
enableMcp();
render(<IntegrationsTab />);
await screen.findByText('MCP Configuration');
await openMcp();
await user.click(screen.getByRole('button', { name: /New Client/i }));
await screen.findByText('Register OAuth Client');
const createBtn = screen.getByRole('button', { name: /Register Client/i });
@@ -665,7 +664,7 @@ describe('IntegrationsTab', () => {
);
enableMcp();
render(<><ToastContainer /><IntegrationsTab /></>);
await screen.findByText('MCP Configuration');
await openMcp();
await user.click(screen.getByRole('button', { name: /New Client/i }));
await screen.findByText('Register OAuth Client');
await user.type(screen.getByPlaceholderText(/Claude Web, My MCP App/i), 'Fail Client');
@@ -680,7 +679,7 @@ describe('IntegrationsTab', () => {
server.use(http.post('/api/oauth/clients', () => HttpResponse.error()));
enableMcp();
render(<><ToastContainer /><IntegrationsTab /></>);
await screen.findByText('MCP Configuration');
await openMcp();
await user.click(screen.getByRole('button', { name: /New Client/i }));
await screen.findByText('Register OAuth Client');
await user.type(screen.getByPlaceholderText(/Claude Web, My MCP App/i), 'Fail Client');
@@ -710,7 +709,7 @@ const oneToken = [
];
async function openTokensTab(user: ReturnType<typeof userEvent.setup>) {
await screen.findByText('MCP Configuration');
await openMcp();
await user.click(screen.getByRole('button', { name: /API Tokens/i }));
}
@@ -725,10 +724,9 @@ describe('IntegrationsTab – copy actions and cancels', () => {
const user = userEvent.setup();
enableMcp();
render(<IntegrationsTab />);
await screen.findByText('MCP Configuration');
await openMcp();
const writeSpy = vi.spyOn(navigator.clipboard, 'writeText').mockResolvedValue(undefined);
await user.click(screen.getByRole('button', { name: /Client Configuration/i }));
await user.click(labelledCopyButton());
expect(writeSpy).toHaveBeenCalledWith(expect.stringContaining('mcp'));
@@ -742,7 +740,6 @@ describe('IntegrationsTab – copy actions and cancels', () => {
await openTokensTab(user);
const writeSpy = vi.spyOn(navigator.clipboard, 'writeText').mockResolvedValue(undefined);
await user.click(screen.getByRole('button', { name: /Client Configuration/i }));
await user.click(labelledCopyButton());
expect(writeSpy).toHaveBeenCalledWith(expect.stringContaining('mcp'));
@@ -790,7 +787,7 @@ describe('IntegrationsTab – copy actions and cancels', () => {
const user = userEvent.setup();
enableMcp();
render(<IntegrationsTab />);
await screen.findByText('MCP Configuration');
await openMcp();
await user.click(screen.getByRole('button', { name: /New Client/i }));
await screen.findByText('Register OAuth Client');
@@ -803,7 +800,7 @@ describe('IntegrationsTab – copy actions and cancels', () => {
const user = userEvent.setup();
enableMcp();
render(<IntegrationsTab />);
await screen.findByText('MCP Configuration');
await openMcp();
await user.click(screen.getByRole('button', { name: /New Client/i }));
await screen.findByText('Register OAuth Client');
@@ -834,7 +831,7 @@ describe('IntegrationsTab – copy actions and cancels', () => {
);
enableMcp();
render(<IntegrationsTab />);
await screen.findByText('MCP Configuration');
await openMcp();
await user.click(screen.getByRole('button', { name: /New Client/i }));
await user.type(screen.getByPlaceholderText(/Claude Web, My MCP App/i), 'Copyable');
await user.type(screen.getByPlaceholderText(/https:\/\/your-app/i), 'http://localhost');
@@ -1015,6 +1012,7 @@ describe('IntegrationsTab – failure toasts', () => {
enableAddons(['ai_assistant']);
const { unmount } = render(<IntegrationsTab />);
// Its own card on the page, the connection form open in it.
expect(await screen.findByText('What would you like to chat with?')).toBeInTheDocument();
unmount();
@@ -3,7 +3,7 @@ import React, { useId } from 'react'
import { useTranslation } from '../../i18n'
import { useFormatDate } from '../../hooks/useDateFormat'
import { useToast } from '../shared/Toast'
import { Trash2, Copy, Terminal, Plus, Check, Key, KeyRound, ChevronRight, RefreshCw, AlertTriangle, Link2 } from 'lucide-react'
import { Trash2, Copy, Terminal, Plus, Check, Key, KeyRound, RefreshCw, AlertTriangle, Link2 } from 'lucide-react'
import PhotoProvidersSection from './PhotoProvidersSection'
import AirTrailConnectionSection from './AirTrailConnectionSection'
import MailImportSection from './MailImportSection'
@@ -16,7 +16,7 @@ import ConfirmDialog from '../shared/ConfirmDialog'
import { Tooltip } from '../shared/Tooltip'
import { DialogButton, DialogFooter, DialogHeader, DialogSection, DialogShell, DialogTile, FooterSpacer, NEUTRAL_TINT, fs } from '../shared/DialogShell'
import { EditorField, INPUT, Segmented, TEXTAREA } from '../shared/dialogParts'
import { SETTINGS_BUTTON, SETTINGS_BUTTON_PRIMARY, SETTINGS_ICON_BUTTON, SettingRows, SettingsHint, StatusPill } from './settingsKit'
import { SETTINGS_BUTTON, SETTINGS_BUTTON_PRIMARY, SETTINGS_ICON_BUTTON, SettingRows, SettingsColumns, SettingsHint, StatusPill } from './settingsKit'
import { OAUTH_PRESETS, useMcpIntegration, type OAuthClient } from './useMcpIntegration'
import { useIntegrationGates } from './useIntegrationGates'
import WandererConnectionSection from './WandererConnectionSection'
@@ -29,47 +29,43 @@ export default function IntegrationsTab(): React.ReactElement {
const demoLocked = useDemoAccountLock()
return (
<>
{/* Two columns from xl up, as on the admin settings: what connects your
trips with other services on the left, AI and developer access on the
right. Flex, not a grid: a column with nothing to show (a managed
install without the mail import) is empty and drops out, and the other
takes the whole width instead of leaving a hole. The cards carry their
own bottom margin, so only the gap between the columns is set. */}
<div className="xl:flex xl:items-start xl:gap-5">
<div className="min-w-0 flex-1 empty:hidden">
{/* Forwarded booking mails: hides itself where this server or plan has no import. */}
<MailImportSection />
{/* Immich, Synology Photos and AirTrail all connect to a server the reader
runs themselves. On a managed install there is none, and every one of
these would ask for an address that cannot be reached from here. */}
{!managed && <PhotoProvidersSection />}
{S.airtrailEnabled && !managed && <AirTrailConnectionSection />}
{S.dawarichEnabled && !managed && <DawarichConnectionSection />}
{S.wandererEnabled && !managed && <WandererConnectionSection />}
</div>
<div className="min-w-0 flex-1 empty:hidden">
{/* Which model reads a booking, and what that costs, comes with the instance on
a managed install. The per-user fallback exists for people who supply their
own key, and there nobody does. */}
{/* The assistant in TREK, with the same managed rule as AI parsing: there the
operator decides which model the install talks to. */}
{S.aiConnectionEnabled && !managed && (
<AiConnectionSection assistant={S.aiAssistantEnabled} parsing={S.llmEnabled} />
)}
{S.llmEnabled && S.ownParsing && !managed && <LlmConnectionSection />}
{/* Above MCP on purpose: an API key needs no addon, and someone looking for
one should not have to read past a section about AI assistants. */}
<DemoLock locked={demoLocked} reason={S.t('demo.lock.apiKeys')}>
<ApiKeysSection />
</DemoLock>
{/* TREK inside Claude rides on the MCP server, so it follows that addon. */}
{S.mcpEnabled && (
<DemoLock locked={demoLocked} reason={S.t('demo.lock.mcp')}>
<IntegrationsMcpSection S={S} />
{/* What connects your trips with other services on the left, AI and
developer access on the right, every card open on the page. */}
<SettingsColumns
left={
<>
{/* Forwarded booking mails: hides itself where this server or plan has no import. */}
<MailImportSection />
{/* Immich, Synology Photos and AirTrail all connect to a server the reader
runs themselves. On a managed install there is none, and every one of
these would ask for an address that cannot be reached from here. */}
{!managed && <PhotoProvidersSection />}
{S.airtrailEnabled && !managed && <AirTrailConnectionSection />}
{S.dawarichEnabled && !managed && <DawarichConnectionSection />}
{S.wandererEnabled && !managed && <WandererConnectionSection />}
{/* The assistant and AI parsing: on a managed install the operator decides
which model the install talks to, so neither is offered there. */}
{S.aiConnectionEnabled && !managed && (
<AiConnectionSection assistant={S.aiAssistantEnabled} parsing={S.llmEnabled} />
)}
{S.llmEnabled && S.ownParsing && !managed && <LlmConnectionSection />}
</>
}
right={
<>
{/* An API key needs no addon, so it leads, ahead of the MCP row. */}
<DemoLock locked={demoLocked} reason={S.t('demo.lock.apiKeys')}>
<ApiKeysSection />
</DemoLock>
)}
</div>
</div>
{/* TREK inside Claude rides on the MCP server, so it follows that addon. */}
{S.mcpEnabled && (
<DemoLock locked={demoLocked} reason={S.t('demo.lock.mcp')}>
<IntegrationsMcpSection S={S} />
</DemoLock>
)}
</>
}
/>
<McpTokenModals S={S} />
<OAuthClientModals S={S} />
</>
@@ -151,10 +147,8 @@ function EmptyHint({ children }: { children: React.ReactNode }) {
)
}
/** The mcp-remote snippet, folded away until asked for. */
function ConfigBlock({ open, onToggle, json, hint, copied, onCopy, t }: {
open: boolean
onToggle: () => void
/** The mcp-remote snippet, shown with its copy button. */
function ConfigBlock({ json, hint, copied, onCopy, t }: {
json: string
hint: string
copied: boolean
@@ -163,33 +157,26 @@ function ConfigBlock({ open, onToggle, json, hint, copied, onCopy, t }: {
}) {
return (
<div className="overflow-hidden rounded-[12px] border border-edge-faint bg-surface-card">
<button type="button" onClick={onToggle} aria-expanded={open}
className="flex w-full items-center gap-2 px-3.5 py-2.5 text-start hover:bg-surface-secondary">
<ChevronRight size={15} strokeWidth={2.2} className={`flex-none text-content-faint transition-transform ${open ? 'rotate-90' : ''}`} />
<div className="flex items-center gap-2 px-3.5 py-2.5">
<span className="flex-1 font-medium text-content" style={fs(13, 'body')}>{t('settings.mcp.clientConfig')}</span>
</button>
{open && (
<div className="flex flex-col gap-2 border-t border-edge-faint p-3.5">
<div className="flex justify-end">
<button type="button" onClick={onCopy} className={`${SMALL_BUTTON} hover:text-content`} style={fs(12, 'body')}>
{copied ? <Check size={13} strokeWidth={2.2} className="text-success" /> : <Copy size={13} strokeWidth={2} />}
{copied ? t('settings.mcp.copied') : t('settings.mcp.copy')}
</button>
</div>
<pre className="m-0 max-h-80 overflow-auto rounded-[10px] border border-edge-faint bg-surface-secondary p-3 font-mono leading-relaxed text-content" style={fs(11.5)}>
{json}
</pre>
<SettingsHint>{hint}</SettingsHint>
</div>
)}
<button type="button" onClick={onCopy} className={`${SMALL_BUTTON} hover:text-content`} style={fs(12, 'body')}>
{copied ? <Check size={13} strokeWidth={2.2} className="text-success" /> : <Copy size={13} strokeWidth={2} />}
{copied ? t('settings.mcp.copied') : t('settings.mcp.copy')}
</button>
</div>
<div className="flex flex-col gap-2 border-t border-edge-faint p-3.5">
<pre className="m-0 max-h-80 overflow-auto rounded-[10px] border border-edge-faint bg-surface-secondary p-3 font-mono leading-relaxed text-content" style={fs(11.5)}>
{json}
</pre>
<SettingsHint>{hint}</SettingsHint>
</div>
</div>
)
}
/** One registered OAuth client: what it is, the scopes it may use, and its two actions. */
function OAuthClientRow({ client, S }: { client: OAuthClient; S: IntegrationsState }) {
const { t, formatDate, oauthScopesExpanded, setOauthScopesExpanded, setOauthRotateId, setOauthDeleteId } = S
const expanded = !!oauthScopesExpanded[client.id]
const { t, formatDate, setOauthRotateId, setOauthDeleteId } = S
return (
<div className={`${ROW} items-start`}>
<span className={ROW_TILE}><KeyRound size={15} strokeWidth={2} /></span>
@@ -205,17 +192,10 @@ function OAuthClientRow({ client, S }: { client: OAuthClient; S: IntegrationsSta
<span className="tabular-nums">{t('settings.mcp.tokenCreatedAt')} {formatDate(new Date(client.created_at))}</span>
</div>
<div className="mt-2 flex flex-wrap gap-1" style={fs(10.5)}>
{(expanded ? client.allowed_scopes : client.allowed_scopes.slice(0, 5)).map(s => (
{/* Every scope the client may use, none folded behind a "+N". */}
{client.allowed_scopes.map(s => (
<span key={s} className={CHIP}>{s}</span>
))}
{client.allowed_scopes.length > 5 && (
<button
type="button"
onClick={() => setOauthScopesExpanded(prev => ({ ...prev, [client.id]: !prev[client.id] }))}
className={`${CHIP} tabular-nums hover:text-content`}>
{expanded ? '−' : `+${client.allowed_scopes.length - 5}`}
</button>
)}
</div>
</div>
<div className="flex flex-none items-center gap-1.5">
@@ -233,13 +213,11 @@ function OAuthClientRow({ client, S }: { client: OAuthClient; S: IntegrationsSta
/** The OAuth tab: the snippet, the registered clients and the sessions they hold. */
function OAuthTab({ S }: { S: IntegrationsState }) {
const {
t, formatDate, oauthClients, oauthSessions, setOauthCreateOpen, setOauthNewName, setOauthNewUris, setOauthNewScopes, setOauthCreatedClient, setOauthRevokeId, setOauthIsMachine, configOpenOAuth, setConfigOpenOAuth, copiedKey, mcpJsonConfigOAuth, handleCopy,
t, formatDate, oauthClients, oauthSessions, setOauthCreateOpen, setOauthNewName, setOauthNewUris, setOauthNewScopes, setOauthCreatedClient, setOauthRevokeId, setOauthIsMachine, copiedKey, mcpJsonConfigOAuth, handleCopy,
} = S
return (
<>
<ConfigBlock
open={configOpenOAuth}
onToggle={() => setConfigOpenOAuth(o => !o)}
json={mcpJsonConfigOAuth}
hint={t('settings.mcp.clientConfigHintOAuth')}
copied={copiedKey === 'json-oauth'}
@@ -251,7 +229,7 @@ function OAuthTab({ S }: { S: IntegrationsState }) {
<div className="flex flex-wrap items-center gap-3">
<SettingsHint className="min-w-0 flex-1 basis-64">{t('settings.oauth.clientsHint')}</SettingsHint>
<button type="button" onClick={() => { setOauthCreateOpen(true); setOauthCreatedClient(null); setOauthNewName(''); setOauthNewUris(''); setOauthNewScopes([]); setOauthIsMachine(false) }}
className={SETTINGS_BUTTON_PRIMARY} style={fs(13, 'body')}>
className={SETTINGS_BUTTON_PRIMARY}>
<Plus size={14} strokeWidth={2.2} /> {t('settings.oauth.createClient')}
</button>
</div>
@@ -295,14 +273,12 @@ function OAuthTab({ S }: { S: IntegrationsState }) {
/** The deprecated API tokens tab: the warning, the snippet and the tokens. */
function ApiTokensTab({ S }: { S: IntegrationsState }) {
const { t, formatDate, configOpenToken, setConfigOpenToken, mcpTokens, setMcpModalOpen, setMcpNewName, setMcpCreatedToken, setMcpDeleteId, copiedKey, mcpJsonConfig, handleCopy } = S
const { t, formatDate, mcpTokens, setMcpModalOpen, setMcpNewName, setMcpCreatedToken, setMcpDeleteId, copiedKey, mcpJsonConfig, handleCopy } = S
return (
<>
<WarningNote>{t('settings.mcp.apiTokensDeprecated')}</WarningNote>
<ConfigBlock
open={configOpenToken}
onToggle={() => setConfigOpenToken(o => !o)}
json={mcpJsonConfig}
hint={t('settings.mcp.clientConfigHint')}
copied={copiedKey === 'json-token'}
@@ -312,7 +288,7 @@ function ApiTokensTab({ S }: { S: IntegrationsState }) {
<div className="flex justify-end">
<button type="button" onClick={() => { setMcpModalOpen(true); setMcpCreatedToken(null); setMcpNewName('') }}
className={SETTINGS_BUTTON} style={fs(13, 'body')}>
className={SETTINGS_BUTTON}>
<Plus size={14} strokeWidth={2.2} /> {t('settings.mcp.createToken')}
</button>
</div>
@@ -352,13 +328,12 @@ function IntegrationsMcpSection({ S }: { S: IntegrationsState }) {
return (
<Section
id="mcp"
collapsible
title={t('settings.mcp.title')}
icon={Terminal}
badge={
connected > 0
? <StatusPill tone="success" icon={<span className="h-1.5 w-1.5 rounded-full bg-current" />}>{t('settings.mcp.appsConnected', { count: connected })}</StatusPill>
: <StatusPill>{t('settings.notSetUp')}</StatusPill>
: <StatusPill icon={<span className="h-1.5 w-1.5 rounded-full bg-current" />}>{t('settings.notSetUp')}</StatusPill>
}
>
{/* Endpoint URL */}
@@ -8,7 +8,6 @@ import { useAuthStore } from '../../store/authStore';
import type { Settings } from '../../types';
import { ToastContainer } from '../shared/Toast';
import LlmConnectionSection from './LlmConnectionSection';
import { openSettingsCards } from '../../../tests/helpers/settingsCards';
let loadSettings = vi.fn().mockResolvedValue(undefined);
@@ -51,8 +50,6 @@ async function pickProvider(user: ReturnType<typeof userEvent.setup>, current: R
}
beforeEach(() => {
// The cards start shut; these tests read into them.
openSettingsCards();
resetAllStores();
vi.clearAllMocks();
seedRole('user');
@@ -45,7 +45,6 @@ export default function LlmConnectionSection(): React.ReactElement {
return (
<Section
id="ai-parsing"
collapsible
title={t('settings.aiParsing.title')}
icon={Sparkles}
badge={<ParsingState />}
@@ -117,5 +116,5 @@ function ParsingState() {
const model = useSettingsStore(s => s.settings.llm_model)
return model
? <StatusPill tone="success" icon={<span className="h-1.5 w-1.5 rounded-full bg-current" />}>{model}</StatusPill>
: <StatusPill>{t('settings.notSetUp')}</StatusPill>
: <StatusPill icon={<span className="h-1.5 w-1.5 rounded-full bg-current" />}>{t('settings.notSetUp')}</StatusPill>
}
@@ -1,4 +1,4 @@
import { ChevronRight, Copy, FileUp, Inbox, Loader2, Mail, RefreshCw } from 'lucide-react';
import { Copy, FileUp, Inbox, Loader2, Mail, RefreshCw } from 'lucide-react';
import { useRef, type ReactElement } from 'react';
import { useTranslation } from '../../i18n';
import { openMailInbox } from '../MailIngest/mailInboxOpener';
@@ -31,7 +31,6 @@ export default function MailImportSection(): ReactElement | null {
return (
<Section
id="mail-import"
collapsible
title={t('mailInbox.settings.title')}
icon={Mail}
badge={
@@ -78,21 +77,14 @@ export default function MailImportSection(): ReactElement | null {
</Tooltip>
</div>
<SettingsHint>{t('mailInbox.settings.addressHint')}</SettingsHint>
<details className="group rounded-lg bg-surface-tertiary px-3 py-2 text-body text-content-secondary">
<summary className="flex cursor-pointer list-none items-center gap-1.5 font-medium text-content">
<ChevronRight
size={14}
strokeWidth={2}
className="transition-transform group-open:rotate-90 rtl:-scale-x-100"
/>
{t('mailInbox.settings.howTo')}
</summary>
<div className="rounded-lg bg-surface-tertiary px-3 py-2 text-body text-content-secondary">
<div className="font-medium text-content">{t('mailInbox.settings.howTo')}</div>
<ul className="mt-2 flex list-disc flex-col gap-1.5 ps-5 text-caption">
<li>{t('mailInbox.settings.howToGmail')}</li>
<li>{t('mailInbox.settings.howToOutlook')}</li>
<li>{t('mailInbox.settings.howToManual')}</li>
</ul>
</details>
</div>
</div>
)}
@@ -379,7 +379,6 @@ export default function MapSettingsTab(): React.ReactElement {
onClick={saveMapSettings}
disabled={saving}
className={SETTINGS_BUTTON_PRIMARY}
style={fs(13, 'body')}
>
{saving ? <span className="h-3.5 w-3.5 animate-spin rounded-full border-2 border-current border-t-transparent" /> : <Save size={14} strokeWidth={2} />}
{t('settings.saveMap')}
@@ -119,10 +119,10 @@ export default function NotificationsTab(): React.ReactElement {
aria-label={t('settings.webhookUrl.label')}
className={`${INPUT} min-w-[220px] flex-1`}
/>
<button type="button" onClick={testWebhookUrl} disabled={webhookTestDisabled} className={SETTINGS_BUTTON} style={fs(13, 'body')}>
<button type="button" onClick={testWebhookUrl} disabled={webhookTestDisabled} className={SETTINGS_BUTTON}>
{t('settings.webhookUrl.test')}
</button>
<button type="button" onClick={saveWebhookUrl} disabled={webhookSaving} className={SETTINGS_BUTTON_PRIMARY} style={fs(13, 'body')}>
<button type="button" onClick={saveWebhookUrl} disabled={webhookSaving} className={SETTINGS_BUTTON_PRIMARY}>
{t('common.save')}
</button>
</div>
@@ -164,17 +164,17 @@ export default function NotificationsTab(): React.ReactElement {
className={`${INPUT} flex-1`}
/>
{ntfyTokenIsSet && (
<button type="button" onClick={clearNtfyToken} className={SETTINGS_BUTTON_DANGER} style={fs(13, 'body')}>
<button type="button" onClick={clearNtfyToken} className={SETTINGS_BUTTON_DANGER}>
{t('common.clear')}
</button>
)}
</div>
</EditorField>
<div className="flex flex-wrap items-center justify-end gap-2">
<button type="button" onClick={testNtfySettings} disabled={!ntfyTopic || ntfyTesting} className={SETTINGS_BUTTON} style={fs(13, 'body')}>
<button type="button" onClick={testNtfySettings} disabled={!ntfyTopic || ntfyTesting} className={SETTINGS_BUTTON}>
{t('settings.ntfyUrl.test')}
</button>
<button type="button" onClick={saveNtfySettings} disabled={ntfySaving} className={SETTINGS_BUTTON_PRIMARY} style={fs(13, 'body')}>
<button type="button" onClick={saveNtfySettings} disabled={ntfySaving} className={SETTINGS_BUTTON_PRIMARY}>
{t('common.save')}
</button>
</div>
@@ -198,7 +198,7 @@ export default function NotificationsTab(): React.ReactElement {
{/* Unconfigured is the common case on first use — send them to where the
credentials actually live rather than just naming the place. */}
{!ch.configured && ch.settingsPath && (
<Link to={ch.settingsPath} className={`${SETTINGS_BUTTON_PRIMARY} no-underline`} style={fs(13, 'body')}>
<Link to={ch.settingsPath} className={`${SETTINGS_BUTTON_PRIMARY} no-underline`}>
{t('settings.notificationPreferences.configure')}
</Link>
)}
@@ -206,7 +206,6 @@ export default function NotificationsTab(): React.ReactElement {
onClick={() => testChannel(ch)}
disabled={!ch.configured || channelTesting === ch.id}
className={SETTINGS_BUTTON}
style={fs(13, 'body')}
>
{t('settings.notificationPreferences.sendTest')}
</button>
+47 -43
View File
@@ -14,7 +14,7 @@ import React, { useState } from 'react'
import { RefreshCw, Trash2, Database, CloudOff, Download, Check, GitMerge, Map as MapIcon, AlertTriangle } from 'lucide-react'
import Section from './Section'
import ToggleSwitch from './ToggleSwitch'
import { SettingRow, SettingRows, SettingsHint, StatusPill, SETTINGS_BUTTON, SETTINGS_BUTTON_DANGER } from './settingsKit'
import { SettingRow, SettingRows, SettingsHint, StatusPill, SETTINGS_BUTTON, SETTINGS_BUTTON_DANGER, SettingsColumns } from './settingsKit'
import { useOfflineSettings, offlineNoticeKey, isOfflineNoticeWarning, offlineProgressLabel, offlineRowMeta } from './useOfflineSettings'
import { useTranslation } from '../../i18n'
import CustomSelect from '../shared/CustomSelect'
@@ -49,6 +49,10 @@ export default function OfflineTab(): React.ReactElement {
return (
<div>
{/* Two columns by length: what the mode does and what is cached on the
left, the per-trip choice of what to keep on the right. */}
<SettingsColumns
left={<>
{/* Offline mode + prepare */}
<Section title={t('settings.offline.mode.title')} icon={CloudOff}>
<SettingRows>
@@ -71,7 +75,6 @@ export default function OfflineTab(): React.ReactElement {
onClick={runPrepare}
disabled={preparing || offline}
className={SETTINGS_BUTTON}
style={fs(13, 'body')}
>
{preparing
? <RefreshCw size={14} className="animate-spin" />
@@ -82,7 +85,6 @@ export default function OfflineTab(): React.ReactElement {
onClick={handleResync}
disabled={syncing || offline}
className={SETTINGS_BUTTON}
style={fs(13, 'body')}
>
<RefreshCw size={14} className={syncing ? 'animate-spin' : undefined} />
{syncing ? t('settings.offline.resyncing') : t('settings.offline.resync')}
@@ -130,10 +132,10 @@ export default function OfflineTab(): React.ReactElement {
{t('settings.offline.conflicts.item', { name: conflictName(c) })}
</span>
<div className="flex flex-none gap-2">
<button type="button" onClick={() => resolveConflict(c.id, true)} className={SETTINGS_BUTTON} style={fs(12.5, 'body')}>
<button type="button" onClick={() => resolveConflict(c.id, true)} className={SETTINGS_BUTTON}>
{t('settings.offline.conflicts.keepMine')}
</button>
<button type="button" onClick={() => resolveConflict(c.id, false)} className={SETTINGS_BUTTON} style={fs(12.5, 'body')}>
<button type="button" onClick={() => resolveConflict(c.id, false)} className={SETTINGS_BUTTON}>
{t('settings.offline.conflicts.keepServer')}
</button>
</div>
@@ -163,41 +165,6 @@ export default function OfflineTab(): React.ReactElement {
</Section>
)}
{/* What to store offline */}
<Section title={t('settings.offline.storage.title')} icon={MapIcon}>
<SettingRows>
<SettingRow
label={t('settings.offline.storage.tiles')}
hint={t('settings.offline.storage.tilesHint')}
control={<ToggleSwitch on={prefs.cacheTiles} onToggle={handleToggleTiles} label={t('settings.offline.storage.tiles')} />}
/>
</SettingRows>
{allTrips.length > 0 && (
<div>
<p className={EYEBROW} style={fs(10)}>{t('settings.offline.storage.tripsTitle')}</p>
<SettingRows>
{allTrips.map((trip) => {
const { on, dateEligible } = tripStorageState(trip)
return (
<div key={trip.id} className="flex items-center justify-between gap-4 px-3.5 py-3">
<div className="min-w-0">
<div className="truncate font-medium text-content" style={fs(13, 'body')}>
{trip.title}
</div>
<div className={on ? 'text-success' : 'text-content-faint'} style={fs(11.5)}>
{on ? t('settings.offline.storage.tripOn') : t('settings.offline.storage.tripOff')}
{!dateEligible && `. ${t('settings.offline.storage.tripFinished')}`}
</div>
</div>
<ToggleSwitch on={on} onToggle={() => handleToggleTrip(trip)} label={trip.title} />
</div>
)
})}
</SettingRows>
</div>
)}
</Section>
{/* Cache stats + list + clear */}
<Section
title={t('settings.offline.cache.title')}
@@ -207,7 +174,6 @@ export default function OfflineTab(): React.ReactElement {
onClick={() => setConfirmClear(true)}
disabled={clearing || !canClear}
className={SETTINGS_BUTTON_DANGER}
style={fs(12.5, 'body')}
>
<Trash2 size={14} />
{t('settings.offline.clear')}
@@ -225,11 +191,11 @@ export default function OfflineTab(): React.ReactElement {
<div className="flex flex-wrap items-center justify-between gap-3">
<SettingsHint>{t('settings.offline.failed.hint')}</SettingsHint>
<div className="flex gap-2">
<button type="button" onClick={() => void retryFailed()} disabled={offline} className={SETTINGS_BUTTON} style={fs(12.5, 'body')}>
<button type="button" onClick={() => void retryFailed()} disabled={offline} className={SETTINGS_BUTTON}>
<RefreshCw size={14} />
{t('settings.offline.failed.retry')}
</button>
<button type="button" onClick={() => void discardFailed()} className={SETTINGS_BUTTON_DANGER} style={fs(12.5, 'body')}>
<button type="button" onClick={() => void discardFailed()} className={SETTINGS_BUTTON_DANGER}>
<Trash2 size={14} />
{t('settings.offline.failed.discard')}
</button>
@@ -268,6 +234,44 @@ export default function OfflineTab(): React.ReactElement {
</SettingRows>
)}
</Section>
</>}
right={<>
{/* What to store offline */}
<Section title={t('settings.offline.storage.title')} icon={MapIcon}>
<SettingRows>
<SettingRow
label={t('settings.offline.storage.tiles')}
hint={t('settings.offline.storage.tilesHint')}
control={<ToggleSwitch on={prefs.cacheTiles} onToggle={handleToggleTiles} label={t('settings.offline.storage.tiles')} />}
/>
</SettingRows>
{allTrips.length > 0 && (
<div>
<p className={EYEBROW} style={fs(10)}>{t('settings.offline.storage.tripsTitle')}</p>
<SettingRows>
{allTrips.map((trip) => {
const { on, dateEligible } = tripStorageState(trip)
return (
<div key={trip.id} className="flex items-center justify-between gap-4 px-3.5 py-3">
<div className="min-w-0">
<div className="truncate font-medium text-content" style={fs(13, 'body')}>
{trip.title}
</div>
<div className={on ? 'text-success' : 'text-content-faint'} style={fs(11.5)}>
{on ? t('settings.offline.storage.tripOn') : t('settings.offline.storage.tripOff')}
{!dateEligible && `. ${t('settings.offline.storage.tripFinished')}`}
</div>
</div>
<ToggleSwitch on={on} onToggle={() => handleToggleTrip(trip)} label={trip.title} />
</div>
)
})}
</SettingRows>
</div>
)}
</Section>
</>}
/>
<ConfirmDialog
isOpen={confirmClear}
@@ -30,7 +30,7 @@ export default function PasskeysSection({ demoMode }: { demoMode?: boolean }): R
badge={pk.creds.length > 0 ? <StatusPill>{pk.creds.length}</StatusPill> : undefined}
// The way in sits on the band, like the planner's "add" actions; the step-up opens in the body.
action={pk.canAdd && !pk.addOpen ? (
<button type="button" onClick={() => pk.setAddOpen(true)} className={SETTINGS_BUTTON} style={fs(12.5, 'body')}>
<button type="button" onClick={() => pk.setAddOpen(true)} className={SETTINGS_BUTTON}>
<Plus size={14} />
{t('settings.passkey.add')}
</button>
@@ -9,7 +9,6 @@ import { resetAllStores, seedStore } from '../../../tests/helpers/store';
import { buildUser } from '../../../tests/helpers/factories';
import { ToastContainer } from '../shared/Toast';
import PhotoProvidersSection from './PhotoProvidersSection';
import { openSettingsCards } from '../../../tests/helpers/settingsCards';
const fakeProvider = {
id: 'immich',
@@ -46,8 +45,6 @@ function seedMemoriesEnabled(providers = [fakeProvider]) {
}
beforeEach(() => {
// The cards start shut; these tests read into them.
openSettingsCards();
resetAllStores();
vi.clearAllMocks();
seedStore(useAuthStore, { user: buildUser(), isAuthenticated: true });
@@ -36,7 +36,6 @@ export default function PhotoProvidersSection(): React.ReactElement {
return (
<Section
id={`photos-${provider.id}`}
collapsible
key={provider.id}
title={provider.name || provider.id}
icon={Camera}
@@ -66,8 +66,8 @@ function PluginOAuthSection({ id, state, setState }: {
? <span className="inline-flex items-center gap-1.5"><CheckCircle size={14} className="flex-none text-success" />{t('settings.plugins.oauth.connected')}</span>
: t('settings.plugins.oauth.notConnected')}
control={state.connected
? <button type="button" onClick={disconnect} disabled={busy} className={SETTINGS_BUTTON} style={fs(13, 'body')}><Unlink size={14} />{t('settings.plugins.oauth.disconnect')}</button>
: <button type="button" onClick={connect} disabled={busy} className={SETTINGS_BUTTON_PRIMARY} style={fs(13, 'body')}>{busy ? <Loader2 size={14} className="animate-spin" /> : <Link2 size={14} />}{t('settings.plugins.oauth.connect')}</button>}
? <button type="button" onClick={disconnect} disabled={busy} className={SETTINGS_BUTTON}><Unlink size={14} />{t('settings.plugins.oauth.disconnect')}</button>
: <button type="button" onClick={connect} disabled={busy} className={SETTINGS_BUTTON_PRIMARY}>{busy ? <Loader2 size={14} className="animate-spin" /> : <Link2 size={14} />}{t('settings.plugins.oauth.connect')}</button>}
/>
</SettingRows>
)
@@ -158,7 +158,7 @@ function PluginSettingsForm({ id, name, icon }: { id: string; name: string; icon
</Fragment>
))}
<div className="flex justify-end">
<button type="button" onClick={save} disabled={saving} className={SETTINGS_BUTTON_PRIMARY} style={fs(13, 'body')}>
<button type="button" onClick={save} disabled={saving} className={SETTINGS_BUTTON_PRIMARY}>
{saving ? <Loader2 size={14} className="animate-spin" /> : <Save size={14} />}
{t('common.save')}
</button>
@@ -180,7 +180,6 @@ function PluginSettingsForm({ id, name, icon }: { id: string; name: string; icon
onClick={() => runAction(a)}
disabled={running !== null}
className={a.danger ? SETTINGS_BUTTON_DANGER : SETTINGS_BUTTON}
style={fs(13, 'body')}
>
{running === a.key && <Loader2 size={14} className="animate-spin" />}
{a.label}
+8 -6
View File
@@ -9,22 +9,24 @@ interface SectionProps {
* standing in for a glyph gets sized by the same utilities.
*/
icon: LucideIcon | React.ComponentType<{ className?: string }>
/** The icon is a brand badge that fills its tile instead of a glyph in it. */
iconFill?: boolean
badge?: React.ReactNode
/** One line under the title in the head band. */
hint?: React.ReactNode
/** A control on the right of the head band. */
action?: React.ReactNode
/** Where a link lands and, for a collapsible card, what it is remembered by. */
/** Where a link lands: `#id` scrolls to the card, or opens it from an overview. */
id?: string
/** Shut until its head is clicked, the badge saying its state meanwhile (see settingsKit). */
collapsible?: boolean
children: React.ReactNode
}
/** A settings group: the planner's card with a head band (see settingsKit). */
export default function Section({ title, icon, badge, hint, action, id, collapsible, children }: SectionProps): React.ReactElement {
/**
* A settings group: the planner's card with a head band (see settingsKit).
*/
export default function Section({ title, icon, iconFill, badge, hint, action, id, children }: SectionProps): React.ReactElement {
return (
<SettingsCard icon={icon} title={title} badge={badge} hint={hint} action={action} id={id} collapsible={collapsible}>
<SettingsCard icon={icon} iconFill={iconFill} title={title} badge={badge} hint={hint} action={action} id={id}>
{children}
</SettingsCard>
)
@@ -4,7 +4,6 @@ import { http, HttpResponse } from 'msw';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { server } from '../../../tests/helpers/msw/server';
import { render, screen, waitFor } from '../../../tests/helpers/render';
import { openSettingsCards } from '../../../tests/helpers/settingsCards';
import { resetAllStores } from '../../../tests/helpers/store';
import WandererConnectionSection from './WandererConnectionSection';
@@ -32,8 +31,6 @@ function settingsRoute(state: { current: typeof disconnected }) {
}
beforeEach(() => {
// The cards start shut; these tests read into them.
openSettingsCards();
resetAllStores();
vi.clearAllMocks();
});
@@ -11,7 +11,6 @@ import {
SETTINGS_BUTTON_PRIMARY,
SettingRow,
SettingRows,
SettingsHint,
StatusPill,
} from './settingsKit';
import ToggleSwitch from './ToggleSwitch';
@@ -32,8 +31,8 @@ export default function WandererConnectionSection(): React.ReactElement {
return (
<Section
id="wanderer"
collapsible
title={t('wanderer.title')}
hint={t('wanderer.intro')}
icon={WandererMark}
badge={
<StatusPill
@@ -44,7 +43,6 @@ export default function WandererConnectionSection(): React.ReactElement {
</StatusPill>
}
>
<SettingsHint>{t('wanderer.intro')}</SettingsHint>
<div className={GRID_2}>
<EditorField label={t('wanderer.url')} htmlFor="wanderer-url">
@@ -48,7 +48,6 @@ function HintsButton({ W }: { W: WandererWatchController }) {
onClick={W.openHints}
disabled={count === 0}
className={`${SETTINGS_BUTTON} relative`}
style={fs(12.5, 'body')}
>
<BellRing size={13} strokeWidth={2.2} />
{t('wanderer.watch.hints')}
@@ -32,7 +32,6 @@ export default function WebPushCard(): React.ReactElement {
onClick={push.sendTest}
disabled={!push.canTest}
className={SETTINGS_BUTTON}
style={fs(13, 'body')}
>
{t('settings.notificationPreferences.sendTest')}
</button>
@@ -41,7 +40,6 @@ export default function WebPushCard(): React.ReactElement {
onClick={push.toggle}
disabled={push.busy}
className={push.on ? SETTINGS_BUTTON : SETTINGS_BUTTON_PRIMARY}
style={fs(13, 'body')}
>
{push.switchLabel}
</button>
@@ -1,5 +1,5 @@
import type { AiApiKeyKind, AiConnectionScope, AiParsingPrefill } from '@trek/shared';
import { ChevronRight, KeyRound, Loader2, Server, ShieldCheck } from 'lucide-react';
import { KeyRound, Loader2, Server, ShieldCheck } from 'lucide-react';
import React, { useId, useState } from 'react';
import { useTranslation } from '../../../i18n';
import { useAssistantStore } from '../../../store/assistantStore';
@@ -193,7 +193,6 @@ function KeyForm({ scope, keyConnect }: { scope: AiConnectionScope; keyConnect:
onClick={() => void submit()}
disabled={!kind || testing}
className={`${SETTINGS_BUTTON_PRIMARY} whitespace-nowrap`}
style={fs(13, 'body')}
>
{testing && <Loader2 size={14} className="animate-spin" />}
{testing ? t('assistant.connect.testing') : t('assistant.connect.save')}
@@ -225,7 +224,6 @@ function KeyForm({ scope, keyConnect }: { scope: AiConnectionScope; keyConnect:
onClick={() => void openrouter.start()}
disabled={openrouter.busy}
className={SETTINGS_BUTTON}
style={fs(13, 'body')}
>
{openrouter.busy ? (
<Loader2 size={14} className="animate-spin" />
@@ -298,7 +296,6 @@ function CustomForm({ custom }: { custom: ReturnType<typeof useCustomConnect> })
onClick={() => void custom.submit()}
disabled={!custom.ready || custom.saving}
className={SETTINGS_BUTTON_PRIMARY}
style={fs(13, 'body')}
>
{custom.saving && <Loader2 size={14} className="animate-spin" />}
{custom.saving ? t('assistant.connect.testing') : t('assistant.connect.save')}
@@ -314,7 +311,6 @@ function CustomForm({ custom }: { custom: ReturnType<typeof useCustomConnect> })
*/
function PrivacyNote({ provider }: { provider: string }) {
const { t } = useTranslation();
const [open, setOpen] = useState(false);
return (
<div className="rounded-[12px] bg-surface-tertiary px-3 py-2.5">
{provider && (
@@ -322,28 +318,16 @@ function PrivacyNote({ provider }: { provider: string }) {
{t('assistant.privacy.banner', { provider })}
</p>
)}
<button
type="button"
onClick={() => setOpen((v) => !v)}
aria-expanded={open}
className="inline-flex items-center gap-1.5 font-medium text-content-muted hover:text-content"
style={fs(12, 'body')}
>
{/* Said in full before anything is saved, not folded behind a link. */}
<div className="inline-flex items-center gap-1.5 font-medium text-content-muted" style={fs(12, 'body')}>
<ShieldCheck size={13} strokeWidth={2.2} />
{t('assistant.privacy.what')}
<ChevronRight
size={13}
strokeWidth={2.2}
className={`transition-transform ${open ? 'rotate-90' : 'rtl:rotate-180'}`}
/>
</button>
{open && (
<ul className="m-0 mt-2 flex list-disc flex-col gap-1 ps-5 text-content-faint" style={fs(11.5)}>
<li>{t('assistant.privacy.shared')}</li>
<li>{t('assistant.privacy.notShared')}</li>
{provider && <li>{t('assistant.privacy.provider', { provider })}</li>}
</ul>
)}
</div>
<ul className="m-0 mt-2 flex list-disc flex-col gap-1 ps-5 text-content-faint" style={fs(11.5)}>
<li>{t('assistant.privacy.shared')}</li>
<li>{t('assistant.privacy.notShared')}</li>
{provider && <li>{t('assistant.privacy.provider', { provider })}</li>}
</ul>
</div>
);
}
@@ -4,7 +4,6 @@ import type { AiStatusResponse } from '@trek/shared';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { buildUser } from '../../../../tests/helpers/factories';
import { render, screen } from '../../../../tests/helpers/render';
import { openSettingsCards } from '../../../../tests/helpers/settingsCards';
import { resetAllStores, seedStore } from '../../../../tests/helpers/store';
import { useAddonStore } from '../../../store/addonStore';
import { useAssistantStore } from '../../../store/assistantStore';
@@ -31,8 +30,6 @@ const INSTANCE: AiStatusResponse = {
};
beforeEach(() => {
// The cards start shut; these tests read into them.
openSettingsCards();
resetAllStores();
vi.clearAllMocks();
useAssistantStore.setState({ status: null });
@@ -4,7 +4,6 @@ import type { AiConnectionView, AiStatusResponse } from '@trek/shared';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { buildAdmin, buildUser } from '../../../../tests/helpers/factories';
import { render, screen, waitFor } from '../../../../tests/helpers/render';
import { openSettingsCards } from '../../../../tests/helpers/settingsCards';
import { resetAllStores, seedStore } from '../../../../tests/helpers/store';
import { useAddonStore } from '../../../store/addonStore';
import { useAssistantStore } from '../../../store/assistantStore';
@@ -49,8 +48,6 @@ function status(over: Partial<AiStatusResponse> = {}): AiStatusResponse {
}
beforeEach(() => {
// The cards start shut; these tests read into them.
openSettingsCards();
resetAllStores();
vi.clearAllMocks();
useAssistantStore.setState({ status: null });
@@ -65,7 +65,7 @@ function OpenAssistantButton({ S }: { S: AiConnections }) {
const { t } = useTranslation();
if (!S.canOpen) return null;
return (
<button type="button" onClick={S.openAssistant} className={SETTINGS_BUTTON_PRIMARY} style={fs(13, 'body')}>
<button type="button" onClick={S.openAssistant} className={SETTINGS_BUTTON_PRIMARY}>
<MessageCircle size={14} strokeWidth={2.2} /> {t('assistant.connect.openAssistant')}
</button>
);
@@ -85,7 +85,6 @@ function OwnConnection({ S, own }: { S: AiConnections; own: AiConnectionView })
type="button"
onClick={() => S.repair(repairMode)}
className={SETTINGS_BUTTON_PRIMARY}
style={fs(13, 'body')}
>
{t(repairMode === 'chatgpt' ? 'assistant.errorAction.signIn' : 'assistant.errorAction.replaceKey')}
</button>
@@ -98,7 +97,6 @@ function OwnConnection({ S, own }: { S: AiConnections; own: AiConnectionView })
onClick={() => void signOut()}
disabled={busy}
className={SETTINGS_BUTTON}
style={fs(13, 'body')}
>
<LogOut size={14} strokeWidth={2} /> {t('assistant.connect.signOut')}
</button>
@@ -108,7 +106,6 @@ function OwnConnection({ S, own }: { S: AiConnections; own: AiConnectionView })
onClick={askDisconnect}
disabled={busy}
className={SETTINGS_BUTTON_DANGER}
style={fs(13, 'body')}
>
<Unplug size={14} strokeWidth={2} /> {t('assistant.connect.disconnect')}
</button>
@@ -157,7 +154,7 @@ function InstanceConnection({ S }: { S: AiConnections }) {
>
<OpenAssistantButton S={S} />
{S.status?.canConnectOwn && !S.panel && (
<button type="button" onClick={S.connectOwn} className={SETTINGS_BUTTON} style={fs(13, 'body')}>
<button type="button" onClick={S.connectOwn} className={SETTINGS_BUTTON}>
{t('assistant.errorAction.connectOwn')}
</button>
)}
@@ -213,7 +210,7 @@ function LockedOwnConnection() {
<SettingRow
label={t('demo.lock.aiTitle')}
control={
<button type="button" disabled className={SETTINGS_BUTTON} style={fs(13, 'body')}>
<button type="button" disabled className={SETTINGS_BUTTON}>
{t('assistant.errorAction.connectOwn')}
</button>
}
@@ -230,7 +227,7 @@ function ConnectPanel({ S }: { S: AiConnections }) {
<div className={`flex flex-col gap-3 ${S.view === 'setup' ? '' : 'border-t border-edge-faint pt-4'}`}>
<AiConnectPanel key={S.panelMode ?? 'any'} scope="user" onConnected={S.onConnected} initialMode={S.panelMode} />
{S.view !== 'setup' && (
<button type="button" onClick={S.closePanel} className={`${SETTINGS_BUTTON} self-start`} style={fs(13, 'body')}>
<button type="button" onClick={S.closePanel} className={`${SETTINGS_BUTTON} self-start`}>
{t('common.cancel')}
</button>
)}
@@ -283,7 +280,6 @@ export default function AiConnectionSection({
return (
<Section
id="ai-connection"
collapsible
title={t(text.titleKey)}
icon={Sparkles}
hint={t(text.hintKey)}
@@ -113,7 +113,6 @@ export default function ChatGptPasteStep({
}}
aria-disabled={!flow}
className={`${SETTINGS_BUTTON_PRIMARY} ${flow ? '' : 'pointer-events-none opacity-50'}`}
style={fs(13, 'body')}
>
{flow ? <ExternalLink size={14} strokeWidth={2.2} /> : <Loader2 size={14} className="animate-spin" />}
{t('assistant.connect.chatgptOpen')}
@@ -163,7 +162,6 @@ export default function ChatGptPasteStep({
onClick={() => void submit()}
disabled={busy || !flow}
className={SETTINGS_BUTTON_PRIMARY}
style={fs(13, 'body')}
>
{busy && <Loader2 size={14} className="animate-spin" />}
{t('assistant.connect.save')}
@@ -174,7 +172,6 @@ export default function ChatGptPasteStep({
onClick={pasteFromClipboard}
disabled={!flow}
className={`${SETTINGS_BUTTON} whitespace-nowrap`}
style={fs(13, 'body')}
>
<ClipboardPaste size={14} strokeWidth={2} />
{t('assistant.connect.chatgptPaste')}
@@ -1,65 +0,0 @@
// FE-SETTINGS-KIT-001 to FE-SETTINGS-KIT-004
import { fireEvent, render, screen } from '@testing-library/react';
import { afterEach, describe, expect, it } from 'vitest';
import { SettingsCard, StatusPill, settingsCardOpenKey } from './settingsKit';
function card(props: { collapsible?: boolean; id?: string } = {}) {
return (
<SettingsCard
title="AirTrail"
badge={<StatusPill>Connected</StatusPill>}
action={<button type="button">Sync</button>}
{...props}
>
<label>
Address
<input />
</label>
</SettingsCard>
);
}
afterEach(() => {
window.location.hash = '';
});
describe('SettingsCard', () => {
it('FE-SETTINGS-KIT-001: a collapsible card starts shut, its state still showing in the head', () => {
render(card({ collapsible: true, id: 'airtrail' }));
const head = screen.getByRole('button', { name: 'AirTrail' });
expect(head).toHaveAttribute('aria-expanded', 'false');
expect(screen.getByText('Connected')).toBeVisible();
expect(screen.queryByRole('textbox', { name: 'Address' })).toBeNull();
// The head's own action stays a button of its own.
expect(screen.getByRole('button', { name: 'Sync' })).toBeVisible();
});
it('FE-SETTINGS-KIT-002: the head opens and shuts it, and the browser remembers it open', () => {
const { unmount } = render(card({ collapsible: true, id: 'airtrail' }));
fireEvent.click(screen.getByRole('button', { name: 'AirTrail' }));
expect(screen.getByRole('button', { name: 'AirTrail' })).toHaveAttribute('aria-expanded', 'true');
expect(screen.getByRole('textbox', { name: 'Address' })).toBeVisible();
expect(localStorage.getItem(settingsCardOpenKey('airtrail'))).toBe('1');
unmount();
render(card({ collapsible: true, id: 'airtrail' }));
expect(screen.getByRole('textbox', { name: 'Address' })).toBeVisible();
fireEvent.click(screen.getByRole('button', { name: 'AirTrail' }));
expect(screen.queryByRole('textbox', { name: 'Address' })).toBeNull();
expect(localStorage.getItem(settingsCardOpenKey('airtrail'))).toBe('0');
});
it('FE-SETTINGS-KIT-003: a link to the card opens it', () => {
window.location.hash = '#airtrail';
render(card({ collapsible: true, id: 'airtrail' }));
expect(screen.getByRole('textbox', { name: 'Address' })).toBeVisible();
});
it('FE-SETTINGS-KIT-004: a card that is not collapsible has no toggle and shows its body', () => {
render(card());
expect(screen.queryByRole('button', { name: 'AirTrail' })).toBeNull();
expect(screen.getByRole('heading', { name: 'AirTrail' })).toBeVisible();
expect(screen.getByRole('textbox', { name: 'Address' })).toBeVisible();
});
});
+159 -102
View File
@@ -1,5 +1,6 @@
import { useEffect, useId, useRef, useState, type ReactNode } from 'react'
import { ChevronDown, type LucideIcon } from 'lucide-react'
import { createContext, useContext, type ReactNode } from 'react'
import { Info, type LucideIcon } from 'lucide-react'
import { Tooltip } from '../shared/Tooltip'
import { NEUTRAL_TINT, fs } from '../shared/DialogShell'
/*
@@ -12,6 +13,29 @@ import { NEUTRAL_TINT, fs } from '../shared/DialogShell'
type IconLike = LucideIcon | React.ComponentType<{ className?: string; size?: number; strokeWidth?: number }>
/**
* A card's or a row's icon in its framed tile. A lucide glyph sits in the middle
* at glyph size; a brand mark that is itself a badge (`fill`, as Dawarich's and
* AirTrail's are) fills the tile corner to corner, the way the addon manager
* shows them, instead of floating small inside a second frame.
*/
function IconTile({ icon: Icon, fill = false, tone = 'neutral' }: {
icon: IconLike
fill?: boolean
tone?: 'neutral' | 'danger'
}) {
const box = 'h-8 w-8 rounded-[10px]'
if (fill) {
const Mark = Icon as React.ComponentType<{ fill?: boolean }>
return <span className={`block flex-none overflow-hidden shadow-sm ${box}`}><Mark fill /></span>
}
return (
<span className={`grid flex-none place-items-center bg-surface-card shadow-sm ${box} ${tone === 'danger' ? 'text-danger' : 'text-content-secondary'}`}>
<Icon size={15} strokeWidth={2} />
</span>
)
}
/** The page's own bar: icon tile, title and subtitle on the left, actions on the right. */
export function SettingsHeader({ icon: Icon, title, subtitle, actions }: {
icon: IconLike
@@ -33,56 +57,89 @@ export function SettingsHeader({ icon: Icon, title, subtitle, actions }: {
)
}
/** Where a collapsible card remembers that its reader left it open. */
export const settingsCardOpenKey = (id: string) => `trek-settings-open-${id}`
/** True inside a card's body: a card there is drawn as a block of it (see SettingsCard). */
const CardBodyContext = createContext(false)
/**
* Whether a collapsible card is open. Shut by default, so a page lists what it
* holds instead of everything at once; open when the address names it (a link
* to `#id` lands on it ready to use), or when its reader left it open last time.
* The browser remembers that per card as a convenience: without storage (a
* private window, blocked site data) every card simply starts shut.
* One part of a settings card: a rounded white block with a small head row
* (title, a pill, an action) and its content under a hairline. Every part of a
* card is one of these, so a card reads as separate, labelled pieces.
*/
export function useCardOpen(id: string | undefined, collapsible: boolean): [boolean, () => void] {
const [open, setOpen] = useState(() => {
if (!collapsible) return true
if (id && window.location.hash === `#${id}`) return true
if (!id) return false
try {
return localStorage.getItem(settingsCardOpenKey(id)) === '1'
} catch {
// Storage refused: the card starts shut, as it would on a first visit.
return false
}
})
const toggle = () => {
const next = !open
setOpen(next)
if (!id) return
try {
localStorage.setItem(settingsCardOpenKey(id), next ? '1' : '0')
} catch {
// Storage refused: the card still opens, it is only not remembered.
}
}
return [!collapsible || open, toggle]
export function SettingsBlock({ id, title, hint, badge, action, tone = 'neutral', flush = false, children }: {
id?: string
/** The content runs to the block's edges: for a list of rows, which bring their own padding. */
flush?: boolean
title: ReactNode
hint?: ReactNode
badge?: ReactNode
action?: ReactNode
tone?: 'neutral' | 'danger'
children?: ReactNode
}) {
return (
<section id={id} className="overflow-hidden rounded-[12px] border border-edge-faint bg-surface-card">
{/* A tinted head row, so a block's title reads as its heading. */}
<div className="flex min-w-0 items-center gap-2 bg-surface-secondary px-3.5 py-2.5">
<div className="min-w-0 flex-1">
<div className="flex min-w-0 flex-wrap items-center gap-2">
<h3 className={`m-0 truncate font-semibold ${tone === 'danger' ? 'text-danger' : 'text-content'}`} style={fs(13, 'body')}>{title}</h3>
{badge}
</div>
{hint && <p className="m-0 mt-0.5 leading-snug text-content-faint" style={fs(11.5)}>{hint}</p>}
</div>
{action && <div className="flex flex-none items-center gap-1.5">{action}</div>}
</div>
{children != null && (
// Inside the block its own rows and fields: a card in it is not nested again.
// Its hairline goes with it, so a block whose content renders nothing is its head alone.
<div className={`flex flex-col border-t border-edge-faint empty:hidden ${flush ? 'divide-y divide-edge-faint' : 'gap-3 p-3.5'}`}>
<CardBodyContext.Provider value={false}>{children}</CardBodyContext.Provider>
</div>
)}
</section>
)
}
/**
* A card's head band: icon tile, title with its badge, a short hint under it,
* an action on the right. The same over a card of fields and over a list of
* rows, so every group on a settings page starts the same way.
*/
function CardHead({ icon: Icon, iconFill = false, title, hint, badge, action, tone = 'neutral' }: {
icon?: IconLike
iconFill?: boolean
title: ReactNode
hint?: ReactNode
badge?: ReactNode
action?: ReactNode
tone?: 'neutral' | 'danger'
}) {
const tint = tone === 'danger' ? 'color-mix(in srgb, var(--danger) 9%, transparent)' : NEUTRAL_TINT
return (
<div className="flex items-center gap-3 border-b border-edge-faint px-4 py-3" style={{ background: tint }}>
{Icon && <IconTile icon={Icon} fill={iconFill} tone={tone} />}
<div className="min-w-0 flex-1">
<div className="flex min-w-0 flex-wrap items-center gap-2">
<h2 className="m-0 truncate font-bold text-content" style={fs(14, 'body')}>{title}</h2>
{badge}
</div>
{hint && <p className="m-0 mt-0.5 text-content-faint" style={fs(11.5)}>{hint}</p>}
</div>
{action && <div className="flex flex-none items-center gap-1.5">{action}</div>}
</div>
)
}
/**
* A group of settings: a card with a head band (icon tile, title, an optional
* badge and an action on the right) and its body below. `tone` tints the band:
* neutral for ordinary groups, danger for the destructive ones.
*
* `collapsible` shuts the body until the head is clicked. The badge is then the
* card's state at a glance ("Connected", "Off"), so a shut card still says what
* matters. The title holds the button (a heading inside a button is not valid
* HTML), stretched over the whole head; the badge and the action sit above it
* and stay clickable on their own. The body stays mounted while shut, so
* nothing typed into it is lost. A collapsible card needs an `id` to be linked
* to and remembered.
*/
export function SettingsCard({ icon: Icon, title, hint, badge, action, tone = 'neutral', children, id, bodyClassName, flush = false, collapsible = false }: {
export function SettingsCard({ icon: Icon, iconFill = false, title, hint, badge, action, tone = 'neutral', children, id, bodyClassName, flush = false }: {
icon?: IconLike
/** The icon is a brand badge that fills its tile (see IconTile). */
iconFill?: boolean
title: ReactNode
/** One line under the title in the band. */
hint?: ReactNode
@@ -95,68 +152,47 @@ export function SettingsCard({ icon: Icon, title, hint, badge, action, tone = 'n
bodyClassName?: string
/** Inside another card: no gap below, the parent spaces its children. */
flush?: boolean
/** Shut until its head is clicked; see above. */
collapsible?: boolean
}) {
const tint = tone === 'danger' ? 'color-mix(in srgb, var(--danger) 9%, transparent)' : NEUTRAL_TINT
const [open, toggle] = useCardOpen(id, collapsible)
const bodyId = useId()
const hasBody = children != null
const ref = useRef<HTMLElement>(null)
// A link to `#id` opened this card; bring it into view, as the router does not scroll to an anchor.
useEffect(() => {
if (id && window.location.hash === `#${id}`) ref.current?.scrollIntoView?.({ block: 'start' })
}, [id])
// Inside another card's body a card is a block of it, never a card in a card:
// the rounded white block every part of a card is, with a small head row.
const nested = useContext(CardBodyContext)
if (nested) {
return (
<SettingsBlock id={id} title={title} hint={hint} badge={badge} action={action} tone={tone}>
{children}
</SettingsBlock>
)
}
return (
<section ref={ref} id={id} className={`${flush ? '' : 'mb-5 '}overflow-hidden rounded-2xl border border-edge-faint bg-surface-secondary`}>
<div
className={`relative flex items-center gap-3 px-4 py-3 ${hasBody && open ? 'border-b border-edge-faint' : ''} ${collapsible ? 'transition-colors hover:brightness-[1.03] has-[:focus-visible]:outline has-[:focus-visible]:outline-2 has-[:focus-visible]:-outline-offset-2 has-[:focus-visible]:outline-[color:var(--text-primary)]' : ''}`}
style={{ background: tint }}
>
{Icon && (
<span className={`grid h-8 w-8 flex-none place-items-center rounded-[10px] bg-surface-card shadow-sm ${tone === 'danger' ? 'text-danger' : 'text-content-secondary'}`}>
<Icon size={15} strokeWidth={2} />
</span>
)}
<div className="min-w-0 flex-1">
<div className="flex min-w-0 flex-wrap items-center gap-2">
<h2 className="m-0 truncate font-bold text-content" style={fs(14, 'body')}>
{collapsible ? (
<button
type="button"
onClick={toggle}
aria-expanded={open}
aria-controls={hasBody ? bodyId : undefined}
className="cursor-pointer border-0 bg-transparent p-0 text-start font-[inherit] text-inherit outline-none after:absolute after:inset-0 after:content-['']"
>
{title}
</button>
) : title}
</h2>
{badge && <span className="relative z-[1] inline-flex">{badge}</span>}
</div>
{hint && <p className="m-0 mt-0.5 text-content-faint" style={fs(11.5)}>{hint}</p>}
</div>
{action && <div className="relative z-[1] flex flex-none items-center gap-1.5">{action}</div>}
{collapsible && (
<ChevronDown
size={16}
strokeWidth={2}
aria-hidden
className={`pointer-events-none flex-none text-content-faint transition-transform duration-200 motion-reduce:transition-none ${open ? 'rotate-180' : ''}`}
/>
)}
</div>
{/* The hidden wrapper has no classes of its own: a display utility on it would beat the attribute. */}
{hasBody && (
<div id={bodyId} hidden={!open}>
<div className={bodyClassName ?? 'flex flex-col gap-4 p-4'}>{children}</div>
<section id={id} className={`${flush ? '' : 'mb-5 '}overflow-hidden rounded-2xl border border-edge-faint bg-surface-secondary`}>
<CardHead icon={Icon} iconFill={iconFill} title={title} hint={hint} badge={badge} action={action} tone={tone} />
{children != null && (
<div className={bodyClassName ?? 'flex flex-col gap-4 p-4'}>
<CardBodyContext.Provider value>{children}</CardBodyContext.Provider>
</div>
)}
</section>
)
}
/**
* Two columns from xl up, for a settings page whose cards are mostly "label
* left, control right": on a wide screen one column left the middle empty while
* the page scrolled on. Two explicit columns, grouped by subject, rather than a
* grid over a flat list, which pairs cards row by row and leaves a hole under
* the shorter of two. A column with nothing to show drops out and the other
* takes the whole width. The cards carry their own bottom margin, so only the
* gap between the columns is set.
*/
export function SettingsColumns({ left, right }: { left: ReactNode; right: ReactNode }) {
return (
<div className="xl:flex xl:items-start xl:gap-5">
<div className="min-w-0 flex-1 empty:hidden">{left}</div>
<div className="min-w-0 flex-1 empty:hidden">{right}</div>
</div>
)
}
/** A white box of rows separated by hairlines, the way the bag sidebar lists its bags. */
export function SettingRows({ children, className = '' }: { children: ReactNode; className?: string }) {
return (
@@ -184,12 +220,14 @@ export function SettingRow({ label, hint, control, children, stacked = false, di
htmlFor?: string
}) {
return (
<div className={`px-3.5 py-3 ${dimmed ? 'opacity-60' : ''}`}>
<div className={`px-4 py-3 ${dimmed ? 'opacity-60' : ''}`}>
<div className={stacked ? 'flex flex-col gap-2.5' : 'flex flex-wrap items-center gap-x-4 gap-y-2'}>
{/* The basis only in a row: in the stacked column it would read as a height. */}
<div className={stacked ? 'min-w-0' : 'min-w-0 flex-1 basis-56'}>
<label htmlFor={htmlFor} className="block font-medium text-content" style={fs(13, 'body')}>{label}</label>
{hint && <p className="m-0 mt-0.5 leading-snug text-content-faint" style={fs(11.5)}>{hint}</p>}
<div className="flex min-w-0 items-center gap-1.5">
<label htmlFor={htmlFor} className="font-medium text-content" style={fs(13, 'body')}>{label}</label>
{hint && <HintMark hint={hint} />}
</div>
</div>
{control && <div className={stacked ? 'min-w-0' : 'flex flex-none items-center gap-2'}>{control}</div>}
</div>
@@ -198,6 +236,25 @@ export function SettingRow({ label, hint, control, children, stacked = false, di
)
}
/**
* A row's explanation as a small mark beside its label: the row stays one line,
* the sentence opens on hover or focus. The text is in the page for a screen
* reader all the same, read right after the label.
*/
export function HintMark({ hint }: { hint: ReactNode }) {
const text = typeof hint === 'string' ? hint : ''
return (
<>
<span className="sr-only">{hint}</span>
<Tooltip label={text || ' '} content={text ? undefined : hint} placement="top">
<span aria-hidden className="inline-flex flex-none cursor-help text-content-faint transition-colors hover:text-content-muted">
<Info size={13} strokeWidth={2} />
</span>
</Tooltip>
</>
)
}
/** A quiet line of explanation inside a card body. */
export function SettingsHint({ children, className = '' }: { children: ReactNode; className?: string }) {
return <p className={`m-0 leading-normal text-content-faint ${className}`} style={fs(11.5)}>{children}</p>
@@ -245,9 +302,9 @@ export function StatusPill({ tone = 'neutral', children, icon }: { tone?: 'neutr
)
}
/** The buttons of a settings card, in the dialogs' shapes. */
export const SETTINGS_BUTTON = 'inline-flex items-center justify-center gap-1.5 rounded-[10px] bg-surface-card px-3.5 py-2 font-medium text-content shadow-sm ring-1 ring-edge-faint hover:bg-surface-secondary disabled:cursor-default disabled:opacity-50'
export const SETTINGS_BUTTON_PRIMARY = 'inline-flex items-center justify-center gap-1.5 rounded-[10px] bg-accent px-4 py-2 font-medium text-accent-text hover:opacity-90 disabled:cursor-default disabled:opacity-50'
export const SETTINGS_BUTTON_DANGER = 'inline-flex items-center justify-center gap-1.5 rounded-[10px] bg-danger-soft px-3.5 py-2 font-medium text-danger hover:opacity-90 disabled:cursor-default disabled:opacity-50'
/** The buttons of a settings card, in the dialogs' shapes and one size (text-control) everywhere. */
export const SETTINGS_BUTTON = 'inline-flex items-center justify-center gap-1.5 rounded-[10px] bg-surface-card px-3.5 py-2 font-medium text-content shadow-sm ring-1 ring-edge-faint hover:bg-surface-secondary disabled:cursor-default disabled:opacity-50 text-control'
export const SETTINGS_BUTTON_PRIMARY = 'inline-flex items-center justify-center gap-1.5 rounded-[10px] bg-accent px-4 py-2 font-medium text-accent-text hover:opacity-90 disabled:cursor-default disabled:opacity-50 text-control'
export const SETTINGS_BUTTON_DANGER = 'inline-flex items-center justify-center gap-1.5 rounded-[10px] bg-danger-soft px-3.5 py-2 font-medium text-danger hover:opacity-90 disabled:cursor-default disabled:opacity-50 text-control'
/** A round icon action in a band or a row, named by its tooltip. */
export const SETTINGS_ICON_BUTTON = 'grid h-8 w-8 flex-none place-items-center rounded-[10px] bg-surface-card text-content-muted shadow-sm ring-1 ring-edge-faint hover:text-content disabled:cursor-default disabled:opacity-50'
@@ -108,8 +108,6 @@ export function useMcpIntegration({ enabled, reloadClientsAfterWrite }: McpInteg
// MCP sub-tab state
const [activeMcpTab, setActiveMcpTab] = useState<'oauth' | 'apitokens'>('oauth');
const [configOpenOAuth, setConfigOpenOAuth] = useState(false);
const [configOpenToken, setConfigOpenToken] = useState(false);
// MCP state
const [mcpTokens, setMcpTokens] = useState<McpToken[]>([]);
@@ -327,10 +325,6 @@ export function useMcpIntegration({ enabled, reloadClientsAfterWrite }: McpInteg
setOauthIsMachine,
activeMcpTab,
setActiveMcpTab,
configOpenOAuth,
setConfigOpenOAuth,
configOpenToken,
setConfigOpenToken,
mcpTokens,
mcpModalOpen,
setMcpModalOpen,