diff --git a/client/android/app/src/main/java/com/liketrek/trek/MainActivity.java b/client/android/app/src/main/java/com/liketrek/trek/MainActivity.java index e284ee944..0904afd5e 100644 --- a/client/android/app/src/main/java/com/liketrek/trek/MainActivity.java +++ b/client/android/app/src/main/java/com/liketrek/trek/MainActivity.java @@ -26,6 +26,9 @@ public class MainActivity extends BridgeActivity { /** The share sheet (share/ShareActivity.kt) left an item for the import. */ public static final String ACTION_SHARE_HANDOFF = "com.liketrek.trek.SHARE_HANDOFF"; + /** The page colour of the address screen (native-shell/shell.css --page). */ + private static final int SHELL_PAGE = 0xFFFFFAF5; + @Override protected void onCreate(Bundle savedInstanceState) { registerPlugin(TrekShellPlugin.class); @@ -57,6 +60,15 @@ public class MainActivity extends BridgeActivity { // and Chrome honours that, but the WebView draws the stretch on its root // scroller natively. It scales the whole view, top bar and bottom dock included. bridge.getWebView().setOverScrollMode(View.OVER_SCROLL_NEVER); + // The address screen, and the step from it to the server just picked: + // the warm ground of the first screens behind everything, so the + // restart and the page's first frames do not flash white. The window's + // colour is also what an older WebView shows under the status bar, + // where it lays the page out between the bars (native/appBoot.ts). + if (!onServer || restarting) { + getWindow().getDecorView().setBackgroundColor(SHELL_PAGE); + bridge.getWebView().setBackgroundColor(SHELL_PAGE); + } // Set before any WebView callback can run: they are posted to this thread. if (onServer) { bridge.setWebViewClient( diff --git a/client/native-shell/main.ts b/client/native-shell/main.ts index 4f1324d78..1bd1e6c9f 100644 --- a/client/native-shell/main.ts +++ b/client/native-shell/main.ts @@ -5,6 +5,7 @@ import { SplashScreen } from '@capacitor/splash-screen'; import { StatusBar, Style } from '@capacitor/status-bar'; import { PASSWORD_MIN_LENGTH, passwordProblem, passwordRuleStates } from '../../shared/src/auth/password-policy'; import logoWhite from '../public/logo-light.svg'; // #fff wordmark, for the landscape +import { pageUnderStatusBar } from '../src/native/appBoot'; import { AUTH_GATE_NAMES, canSignInInApp, type AuthGate } from '../src/native/authGate'; import { opensSoon, refundedBeforeOpening } from '../src/native/cloudOrders'; import { fakeIapClient, getIapClient, productIdFor, type Purchase } from '../src/native/iap'; @@ -1705,7 +1706,9 @@ function showUnreachable(server: string, cert?: ClientCertDemand, failure?: stri */ async function paintStatusBar(): Promise { try { - await StatusBar.setStyle({ style: Style.Dark }); + // Below the bar on an older Android WebView the page stops, and the bar + // stands on the window's light colour instead: dark icons there. + await StatusBar.setStyle({ style: pageUnderStatusBar() ? Style.Dark : Style.Light }); if (wideLayout.matches) await StatusBar.hide(); else await StatusBar.show(); } catch { diff --git a/client/public/theme-boot.js b/client/public/theme-boot.js index 05a9a963a..6c266efd4 100644 --- a/client/public/theme-boot.js +++ b/client/public/theme-boot.js @@ -12,6 +12,16 @@ (function () { try { var raw = localStorage.getItem('trek_appearance'); + // Inside the iOS and Android app, before anyone signed in on this server + // from here: the page carries on the address screen's colour until the + // sign-in screen is up (native/appBoot.ts), instead of flashing white. + // The app's bridge is in place before this script runs. + var w = window; + var inApp = !!(w.androidBridge || (w.webkit && w.webkit.messageHandlers && w.webkit.messageHandlers.bridge)); + if (inApp && !raw) { + document.documentElement.setAttribute('data-app-boot', ''); + document.documentElement.style.backgroundColor = '#fffaf5'; + } if (!raw) return; var s = JSON.parse(raw); if (!s || s.v !== 1) return; diff --git a/client/src/App.tsx b/client/src/App.tsx index b18fff2a5..f60363385 100644 --- a/client/src/App.tsx +++ b/client/src/App.tsx @@ -1,4 +1,4 @@ -import React, { useEffect, useState, useRef, ReactNode, Suspense } from 'react' +import React, { useEffect, useLayoutEffect, useState, useRef, ReactNode, Suspense } from 'react' import { Routes, Route, Navigate, useLocation, useNavigationType } from 'react-router' import { useAuthStore } from './store/authStore' import { useSettingsStore } from './store/settingsStore' @@ -17,6 +17,8 @@ import BackgroundTasksWidget from './components/BackgroundTasks/BackgroundTasksW import MobileShell from './mobile/MobileShell' import MRouteFallback from './mobile/components/MRouteFallback' import ErrorBoundary from './components/shared/ErrorBoundary' +import AppBootScreen from './components/shared/AppBootScreen' +import { endAppBoot, isAppBoot } from './native/appBoot' import { lazyWithRetry } from './utils/lazyWithRetry' import { reconcileAppVersion } from './utils/versionHandover' import { useServerVersionStore } from './store/serverVersionStore' @@ -113,6 +115,7 @@ function ProtectedRoute({ children, adminRequired = false, addonId }: ProtectedR const isPhone = useIsPhone() if (isLoading) { + if (isAppBoot()) return return (
@@ -286,6 +289,7 @@ function RootRedirect() { }, [isLoading, isAuthenticated, settingsLoaded, settingsGaveUp, settings, target]) if (isLoading || (isAuthenticated && !target)) { + if (isAppBoot()) return return (
@@ -306,6 +310,7 @@ function RouteFallback() { // on a phone the desktop spinner on bg-surface would be a foreign white sheet // in front of the mobile screen. const isPhone = useIsPhone() + if (isAppBoot()) return if (isPhone) return return (
@@ -398,6 +403,12 @@ export default function App() { const location = useLocation() const isSharedPage = location.pathname.startsWith('/shared/') + // Inside the app: the handover from its address screen ends once a signed-in + // screen is up, before it paints, so it can rise in (native/appBoot.ts). + useLayoutEffect(() => { + if (isAuthenticated && location.pathname !== '/' && location.pathname !== '/login') endAppBoot() + }, [isAuthenticated, location.pathname]) + useEffect(() => { const run = () => applyAppearance({ diff --git a/client/src/components/Settings/NativeServerSection.test.tsx b/client/src/components/Settings/NativeServerSection.test.tsx index bd188af77..2f1f89bae 100644 --- a/client/src/components/Settings/NativeServerSection.test.tsx +++ b/client/src/components/Settings/NativeServerSection.test.tsx @@ -1,10 +1,9 @@ -// FE-SETTINGS-NATIVE-SERVER-001 to FE-SETTINGS-NATIVE-SERVER-008 +// FE-SETTINGS-NATIVE-SERVER-001 to FE-SETTINGS-NATIVE-SERVER-006 import { beforeEach, describe, expect, it, vi } from 'vitest'; import { fireEvent, render, screen } from '../../../tests/helpers/render'; import MSettingsServer from '../../mobile/screens/settings/MSettingsServer'; import { nativeServerHost } from '../../native/platform'; import { TrekShell } from '../../native/trekShell'; -import NativeServerLink from '../../pages/login/NativeServerLink'; import NativeServerSection from './NativeServerSection'; vi.mock('../../native/platform', () => ({ nativeServerHost: vi.fn() })); @@ -40,18 +39,3 @@ describe.each([ expect(link).toHaveAttribute('target', '_blank'); }); }); - -describe('the sign-in screen link', () => { - it('renders nothing in a browser', () => { - vi.mocked(nativeServerHost).mockReturnValue(null); - const { container } = render(); - expect(container).toBeEmptyDOMElement(); - }); - - it('leads back to the address screen in the app', () => { - vi.mocked(nativeServerHost).mockReturnValue('trek.example.com'); - render(); - fireEvent.click(screen.getByRole('button', { name: 'Change server' })); - expect(TrekShell.resetServer).toHaveBeenCalled(); - }); -}); diff --git a/client/src/components/shared/AppBootScreen.tsx b/client/src/components/shared/AppBootScreen.tsx new file mode 100644 index 000000000..2a0120830 --- /dev/null +++ b/client/src/components/shared/AppBootScreen.tsx @@ -0,0 +1,15 @@ +import { useTranslation } from '../../i18n'; + +/** + * What the waiting states show while the app hands over from its address + * screen (native/appBoot.ts): that screen's ground and its spinner, which only + * comes up when the wait is long enough to notice. Styled in native/nativeApp.css. + */ +export default function AppBootScreen() { + const { t } = useTranslation(); + return ( +
+
+ ); +} diff --git a/client/src/native/appBoot.test.ts b/client/src/native/appBoot.test.ts new file mode 100644 index 000000000..73c3b0f8f --- /dev/null +++ b/client/src/native/appBoot.test.ts @@ -0,0 +1,110 @@ +// FE-NATIVE-APPBOOT-001 to FE-NATIVE-APPBOOT-006 +import { StatusBar, Style } from '@capacitor/status-bar'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { endAppBoot, handOverToApp, isAppBoot, lightStatusBarIcons, pageUnderStatusBar } from './appBoot'; +import { isNativeAndroid, isNativeApp } from './platform'; + +vi.mock('./platform', () => ({ isNativeApp: vi.fn(), isNativeAndroid: vi.fn() })); +vi.mock('@capacitor/status-bar', () => ({ + StatusBar: { setStyle: vi.fn(async () => {}) }, + Style: { Dark: 'DARK', Light: 'LIGHT' }, +})); + +const root = document.documentElement; +const realAgent = Object.getOwnPropertyDescriptor(window.navigator, 'userAgent'); + +function webViewVersion(major: number) { + Object.defineProperty(window.navigator, 'userAgent', { + configurable: true, + get: () => `Mozilla/5.0 (Linux; Android 16; wv) AppleWebKit/537.36 Chrome/${major}.0.0.0 Mobile Safari/537.36`, + }); +} + +beforeEach(() => { + vi.mocked(isNativeApp).mockReturnValue(true); + vi.mocked(isNativeAndroid).mockReturnValue(false); + vi.mocked(StatusBar.setStyle).mockClear(); +}); + +afterEach(() => { + vi.useRealTimers(); + for (const name of ['data-app-boot', 'data-app-handover', 'data-app-enter']) root.removeAttribute(name); + root.style.removeProperty('background-color'); + root.classList.remove('dark'); + if (realAgent) Object.defineProperty(window.navigator, 'userAgent', realAgent); +}); + +describe('appBoot', () => { + it('FE-NATIVE-APPBOOT-001: ends the handover colour once someone is signed in', () => { + root.setAttribute('data-app-boot', ''); + root.style.backgroundColor = '#fffaf5'; + expect(isAppBoot()).toBe(true); + + endAppBoot(); + expect(isAppBoot()).toBe(false); + expect(root.style.backgroundColor).toBe(''); + }); + + it('FE-NATIVE-APPBOOT-002: leaves a page alone that never was in the handover', () => { + root.style.backgroundColor = 'red'; + endAppBoot(); + expect(root.style.backgroundColor).toBe('red'); + }); + + it('FE-NATIVE-APPBOOT-003: lets the app rise in after the sign-in screen stepped back', async () => { + vi.useFakeTimers(); + const go = vi.fn(); + const done = handOverToApp(Promise.resolve(), go); + + await vi.advanceTimersByTimeAsync(400); + expect(go).not.toHaveBeenCalled(); + await vi.advanceTimersByTimeAsync(100); + await done; + expect(go).toHaveBeenCalledTimes(1); + + endAppBoot(); + expect(root.hasAttribute('data-app-enter')).toBe(true); + expect(root.style.backgroundColor).not.toBe(''); + await vi.advanceTimersByTimeAsync(600); + expect(root.hasAttribute('data-app-enter')).toBe(false); + expect(root.style.backgroundColor).toBe(''); + }); + + it('FE-NATIVE-APPBOOT-004: does not wait for settings that never come, nor stop on ones that fail', async () => { + vi.useFakeTimers(); + vi.spyOn(console, 'warn').mockImplementation(() => {}); + const hanging = vi.fn(); + void handOverToApp(new Promise(() => {}), hanging); + await vi.advanceTimersByTimeAsync(1600); + expect(hanging).toHaveBeenCalled(); + + const failing = vi.fn(); + void handOverToApp(Promise.reject(new Error('offline')), failing); + await vi.advanceTimersByTimeAsync(500); + expect(failing).toHaveBeenCalled(); + }); + + it('FE-NATIVE-APPBOOT-005: knows where the page reaches under the status bar', () => { + expect(pageUnderStatusBar()).toBe(true); + vi.mocked(isNativeAndroid).mockReturnValue(true); + webViewVersion(133); + expect(pageUnderStatusBar()).toBe(false); + webViewVersion(142); + expect(pageUnderStatusBar()).toBe(true); + }); + + it('FE-NATIVE-APPBOOT-006: turns the status bar icons light over the landscape and back after', () => { + root.classList.add('dark'); + const restore = lightStatusBarIcons(); + expect(StatusBar.setStyle).toHaveBeenLastCalledWith({ style: Style.Dark }); + root.classList.remove('dark'); + restore(); + expect(StatusBar.setStyle).toHaveBeenLastCalledWith({ style: Style.Light }); + + vi.mocked(StatusBar.setStyle).mockClear(); + vi.mocked(isNativeAndroid).mockReturnValue(true); + webViewVersion(133); + lightStatusBarIcons()(); + expect(StatusBar.setStyle).not.toHaveBeenCalled(); + }); +}); diff --git a/client/src/native/appBoot.ts b/client/src/native/appBoot.ts new file mode 100644 index 000000000..310bbb694 --- /dev/null +++ b/client/src/native/appBoot.ts @@ -0,0 +1,108 @@ +import { StatusBar, Style } from '@capacitor/status-bar'; +import { isNativeAndroid, isNativeApp } from './platform'; + +/** + * The handover from the app's address screen to this server's UI. + * + * The app picks a server, restarts its view on it, and the page then needs a + * moment for its scripts, the session check and the sign-in chunk. Each of + * those used to paint its own surface (a blank page, a grey spinner, an empty + * fallback), so the step from the warm address screen to the sign-in screen + * flashed white several times. public/theme-boot.js marks with + * data-app-boot before the first paint, when the page runs inside the app and + * nobody has signed in on this server from here yet (no appearance snapshot): + * the page then starts on the address screen's own colour, the waiting states + * show the address screen's spinner on it (AppBootScreen), and the sign-in + * screen fades in on the same ground. The mark goes once someone is signed in, + * and the UI's own appearance takes over. + */ +const ATTRIBUTE = 'data-app-boot'; + +export function isAppBoot(): boolean { + return typeof document !== 'undefined' && document.documentElement.hasAttribute(ATTRIBUTE); +} + +/** Set once the sign-in screen hands over, so the app rises in instead of cutting in. */ +const HANDOVER = 'data-app-handover'; +/** Set while the app rises in (native/nativeApp.css). */ +const ENTER = 'data-app-enter'; +/** The sign-in screen stepping back (appLogin.css .al-leaving). */ +const LEAVE_MS = 420; +/** How long the handover waits for the settings before it goes anyway. */ +const SETTINGS_WAIT_MS = 1500; +const ENTER_MS = 520; +/** The address screen's page colour (native-shell/shell.css --page), as public/theme-boot.js paints it. */ +const PAGE_COLOUR = '#fffaf5'; + +const wait = (ms: number): Promise => new Promise((resolve) => window.setTimeout(resolve, ms)); + +/** + * Signed in from the app's sign-in screen: it steps back into the page colour + * while the settings load (the start page depends on them), then `go` opens + * the app, which rises in once its first screen is there (endAppBoot). + */ +export function handOverToApp(settings: Promise, go: () => void): Promise { + const ready = Promise.race([settings, wait(SETTINGS_WAIT_MS)]).then( + () => undefined, + (err: unknown) => console.warn('Settings not ready for the handover:', err) + ); + return Promise.all([ready, wait(LEAVE_MS)]).then(() => { + document.documentElement.setAttribute(HANDOVER, ''); + go(); + }); +} + +/** + * Back to the UI's own appearance, once a signed-in screen is up. + * theme-boot.js painted the page itself, so this clears that too; after a + * handover the app first rises in on the page colour. + */ +export function endAppBoot(): void { + const root = document.documentElement; + const handover = root.hasAttribute(HANDOVER); + if (!isAppBoot() && !handover) return; + root.removeAttribute(ATTRIBUTE); + if (!handover) { + root.style.removeProperty('background-color'); + return; + } + // The page colour stays under the app while it rises in, whatever scheme the + // account brings, so nothing flashes between the two. + root.removeAttribute(HANDOVER); + root.style.backgroundColor = PAGE_COLOUR; + root.setAttribute(ENTER, ''); + window.setTimeout(() => { + root.removeAttribute(ENTER); + root.style.removeProperty('background-color'); + }, ENTER_MS); +} + +/** + * Whether the page reaches under the status bar. iOS always lays it out there. + * Android does once the system WebView is 140 or newer (Capacitor's SystemBars + * hands the insets through from that version on); an older one sits between + * the bars, on the window's plain colour (MainActivity), where light icons + * would vanish. Shared with the address screen (native-shell/main.ts). + */ +export function pageUnderStatusBar(): boolean { + if (!isNativeAndroid()) return true; + const chrome = /Chrome\/(\d+)/.exec(navigator.userAgent); + return !!chrome && Number(chrome[1]) >= ANDROID_WEBVIEW_UNDER_BARS; +} +const ANDROID_WEBVIEW_UNDER_BARS = 140; + +/** + * The sign-in screen has the landscape under the status bar, as the address + * screen does, so the clock and icons turn light while it is up. The returned + * function puts them back to the scheme's own (native/nativeApp.ts keeps them + * following it from then on). Where the page stops below the bar, the icons + * stay as they are, readable on the plain colour there. + */ +export function lightStatusBarIcons(): () => void { + if (!isNativeApp() || !pageUnderStatusBar()) return () => undefined; + void StatusBar.setStyle({ style: Style.Dark }); + return () => { + const dark = document.documentElement.classList.contains('dark'); + void StatusBar.setStyle({ style: dark ? Style.Dark : Style.Light }); + }; +} diff --git a/client/src/native/nativeApp.css b/client/src/native/nativeApp.css index 750655104..0503acf2b 100644 --- a/client/src/native/nativeApp.css +++ b/client/src/native/nativeApp.css @@ -81,3 +81,50 @@ html[data-touch-input] --tw-ring-offset-shadow: 0 0 #0000; --tw-ring-shadow: 0 0 #0000; } + +/* The handover from the app's address screen to this server's UI + (native/appBoot.ts): the waiting states stand on that screen's colour, with + its spinner, which fades in only once the wait is long enough to notice. */ +html[data-app-boot] .app-boot { + position: fixed; + inset: 0; + display: grid; + place-items: center; + background: #fffaf5; +} +html[data-app-boot] .app-boot span { + width: 24px; + height: 24px; + border-radius: 50%; + border: 2.5px solid #6b5f57; + border-top-color: transparent; + animation: + trek-boot-spin 0.8s linear infinite, + trek-image-in 0.3s ease-out 0.6s both; +} +@keyframes trek-boot-spin { + to { + transform: rotate(360deg); + } +} + +/* Signed in from the app's sign-in screen: the app rises in on the page + colour instead of cutting in (native/appBoot.ts endAppBoot). */ +html[data-app-enter] #root { + animation: trek-app-enter 0.5s cubic-bezier(0.2, 0.8, 0.2, 1) both; +} +@keyframes trek-app-enter { + from { + opacity: 0; + transform: scale(0.97); + } + to { + opacity: 1; + transform: none; + } +} +@media (prefers-reduced-motion: reduce) { + html[data-app-enter] #root { + animation-duration: 0.01s; + } +} diff --git a/client/src/pages/LoginPage.native.test.tsx b/client/src/pages/LoginPage.native.test.tsx new file mode 100644 index 000000000..d92d8ee49 --- /dev/null +++ b/client/src/pages/LoginPage.native.test.tsx @@ -0,0 +1,27 @@ +// FE-PAGE-LOGIN-NATIVE-001: LoginPage inside the iOS/Android app +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { render, screen, waitFor } from '../../tests/helpers/render'; +import { resetAllStores } from '../../tests/helpers/store'; +import LoginPage from './LoginPage'; + +vi.mock('../native/platform', async (importOriginal) => ({ + ...(await importOriginal()), + isNativeApp: () => true, + nativeServerHost: () => 'trek.example.com', +})); +vi.mock('../../native-shell/scenery', () => ({ startScenery: vi.fn(), cameraForPlan: () => [0, 0] })); + +beforeEach(() => { + resetAllStores(); +}); + +describe('LoginPage in the app', () => { + it('FE-PAGE-LOGIN-NATIVE-001: shows the app sign-in screen, without the language menu or the web layout', async () => { + const { container } = render(); + await waitFor(() => expect(screen.getByLabelText('Email')).toBeInTheDocument()); + expect(container.querySelector('.app-login')).toBeInTheDocument(); + expect(screen.getByText('trek.example.com')).toBeInTheDocument(); + expect(screen.queryByRole('button', { name: 'Change language' })).not.toBeInTheDocument(); + expect(container.querySelector('.lg-panel')).not.toBeInTheDocument(); + }); +}); diff --git a/client/src/pages/LoginPage.tsx b/client/src/pages/LoginPage.tsx index 0c6e12669..eddf02e46 100644 --- a/client/src/pages/LoginPage.tsx +++ b/client/src/pages/LoginPage.tsx @@ -16,7 +16,7 @@ import ToggleSwitch from '../components/Settings/ToggleSwitch'; import { SUPPORTED_LANGUAGES, useTranslation } from '../i18n'; import { IDP_LOGIN_URL, useLogin } from './login/useLogin'; import LoginWorld from './login/LoginWorld'; -import NativeServerLink from './login/NativeServerLink'; +import AppLogin from './login/AppLogin'; import MfaCodeStep from './login/MfaCodeStep'; import { LANGUAGE_CORNER_CLASS } from './login/languageCorner'; import PasswordChecklist from '../components/shared/PasswordChecklist'; @@ -44,8 +44,10 @@ const STARFIELD = [ export default function LoginPage(): React.ReactElement { const { t, language } = useTranslation(); // Page = wiring container: the whole auth surface lives in the useLogin hook. + const login = useLogin(); const { navigate, + nativeApp, mode, setMode, username, @@ -87,7 +89,7 @@ export default function LoginPage(): React.ReactElement { idpSlow, idpName, handleDemoLogin, handleSubmit, handlePasskeyLogin, handleSsoClick, - } = useLogin(); + } = login; const oidcButtonShown = !!(appConfig?.oidc_configured && appConfig?.oidc_login && !oidcOnly); const passkeyAvailable = !!( @@ -115,7 +117,7 @@ export default function LoginPage(): React.ReactElement { transition: 'border-color 0.15s', }; - if (showTakeoff) { + if (showTakeoff && !nativeApp) { return (
; + return (
@@ -1222,7 +1228,6 @@ export default function LoginPage(): React.ReactElement { {t('login.demoHint')} )} -
diff --git a/client/src/pages/login/AppLogin.test.tsx b/client/src/pages/login/AppLogin.test.tsx new file mode 100644 index 000000000..8db7ab9d8 --- /dev/null +++ b/client/src/pages/login/AppLogin.test.tsx @@ -0,0 +1,224 @@ +// FE-LOGIN-APP-001 to FE-LOGIN-APP-011: the sign-in screen inside the iOS/Android app +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { buildAppConfig } from '../../../tests/helpers/factories'; +import { fireEvent, render, screen } from '../../../tests/helpers/render'; +import { resetAllStores } from '../../../tests/helpers/store'; +import { nativeServerHost } from '../../native/platform'; +import { TrekShell } from '../../native/trekShell'; +import AppLogin from './AppLogin'; +import type { useLogin } from './useLogin'; + +type Login = ReturnType; + +vi.mock('../../native/platform', async (importOriginal) => ({ + ...(await importOriginal()), + nativeServerHost: vi.fn(), +})); +vi.mock('../../native/trekShell', () => ({ TrekShell: { resetServer: vi.fn() } })); +// The landscape is a WebGL loop, which jsdom cannot draw. +vi.mock('../../../native-shell/scenery', () => ({ startScenery: vi.fn(), cameraForPlan: () => [0, 0] })); + +function buildLogin(overrides: Partial = {}): Login { + const login = { + navigate: vi.fn(), + nativeApp: true, + mode: 'login', + setMode: vi.fn(), + username: '', + setUsername: vi.fn(), + email: '', + setEmail: vi.fn(), + password: '', + setPassword: vi.fn(), + rememberMe: true, + setRememberMe: vi.fn(), + showPassword: false, + setShowPassword: vi.fn(), + isLoading: false, + error: '', + setError: vi.fn(), + insecureCookie: false, + appConfig: buildAppConfig({ has_users: true }), + inviteToken: '', + langDropdownOpen: false, + setLangDropdownOpen: vi.fn(), + setLanguageLocal: vi.fn(), + showTakeoff: false, + mfaStep: false, + setMfaStep: vi.fn(), + mfaToken: '', + setMfaToken: vi.fn(), + mfaCode: '', + setMfaCode: vi.fn(), + passwordChangeStep: false, + newPassword: '', + setNewPassword: vi.fn(), + confirmPassword: '', + setConfirmPassword: vi.fn(), + noRedirect: false, + showRegisterOption: false, + oidcOnly: false, + redirectScreen: false, + configWait: false, + idpSlow: false, + idpName: 'SSO', + handleDemoLogin: vi.fn(), + handleSubmit: vi.fn((e: React.FormEvent) => e.preventDefault()), + handlePasskeyLogin: vi.fn(), + handleSsoClick: vi.fn(), + ...overrides, + }; + return login as unknown as Login; +} + +beforeEach(() => { + resetAllStores(); + vi.mocked(nativeServerHost).mockReturnValue('trek.example.com'); + vi.mocked(TrekShell.resetServer).mockReset().mockResolvedValue(); +}); + +describe('AppLogin', () => { + it('FE-LOGIN-APP-001: shows the server it signs in to, no language menu, and leads back to the address screen', () => { + render(); + expect(screen.getByText('trek.example.com')).toBeInTheDocument(); + expect(screen.queryByRole('button', { name: 'Change language' })).not.toBeInTheDocument(); + expect(screen.queryByRole('listbox')).not.toBeInTheDocument(); + + fireEvent.click(screen.getByRole('button', { name: 'Change server' })); + expect(TrekShell.resetServer).toHaveBeenCalled(); + }); + + it('FE-LOGIN-APP-002: signs in with email and password, with the fields password managers fill', () => { + const login = buildLogin(); + render(); + + expect(screen.getByRole('heading', { name: 'Sign In' })).toBeInTheDocument(); + expect(screen.queryByText('Welcome back')).not.toBeInTheDocument(); + const email = screen.getByLabelText('Email'); + const password = screen.getByLabelText('Password'); + expect(email).toHaveAttribute('autocomplete', 'username'); + expect(password).toHaveAttribute('autocomplete', 'current-password'); + + fireEvent.change(email, { target: { value: 'me@example.com' } }); + fireEvent.change(password, { target: { value: 'secret' } }); + expect(login.setEmail).toHaveBeenCalledWith('me@example.com'); + expect(login.setPassword).toHaveBeenCalledWith('secret'); + + fireEvent.click(screen.getByRole('button', { name: 'Sign In' })); + expect(login.handleSubmit).toHaveBeenCalled(); + }); + + it('FE-LOGIN-APP-003: shows the password, remembers the login and keeps the way to a new password last', () => { + const login = buildLogin(); + render(); + + fireEvent.click(screen.getByRole('button', { name: 'Show password' })); + expect(login.setShowPassword).toHaveBeenCalled(); + fireEvent.click(screen.getByRole('button', { name: 'Remember me' })); + expect(login.setRememberMe).toHaveBeenCalledWith(false); + + const forgot = screen.getByRole('button', { name: 'Forgot password?' }); + const buttons = screen.getAllByRole('button'); + expect(buttons[buttons.length - 1]).toBe(forgot); + fireEvent.click(forgot); + expect(login.navigate).toHaveBeenCalledWith('/forgot-password'); + }); + + it('FE-LOGIN-APP-004: offers SSO beside the password, carrying the remember-me choice', () => { + const login = buildLogin({ + rememberMe: false, + appConfig: buildAppConfig({ + has_users: true, + oidc_configured: true, + oidc_login: true, + oidc_display_name: 'Pocket ID', + }), + }); + render(); + + const sso = screen.getByRole('link', { name: 'Sign in with Pocket ID' }); + expect(sso).toHaveAttribute('href', '/api/auth/oidc/login?remember=0'); + fireEvent.click(sso); + expect(login.handleSsoClick).toHaveBeenCalled(); + }); + + it('FE-LOGIN-APP-005: offers only SSO on an OIDC-only install', () => { + render( + + ); + expect(screen.getByRole('link', { name: 'Sign in with Authentik' })).toHaveAttribute( + 'href', + '/api/auth/oidc/login?invite=abc&remember=1' + ); + expect(screen.queryByLabelText('Password')).not.toBeInTheDocument(); + }); + + it('FE-LOGIN-APP-006: offers a passkey where the server allows one', () => { + const login = buildLogin({ + appConfig: buildAppConfig({ has_users: true, passkey_login: true, passkey_configured: true }), + }); + render(); + fireEvent.click(screen.getByRole('button', { name: 'Sign in with a passkey' })); + expect(login.handlePasskeyLogin).toHaveBeenCalled(); + }); + + it('FE-LOGIN-APP-007: asks for the one-time code in the second step, with the way back', () => { + const login = buildLogin({ mfaStep: true, email: 'me@example.com' }); + render(); + + expect(screen.queryByLabelText('Password')).not.toBeInTheDocument(); + const code = document.getElementById('totp') as HTMLInputElement; + expect(code).toHaveAttribute('autocomplete', 'one-time-code'); + fireEvent.change(code, { target: { value: 'ab12cd' } }); + expect(login.setMfaCode).toHaveBeenCalledWith('AB12CD'); + + fireEvent.click(screen.getByRole('button', { name: '← Back to sign in' })); + expect(login.setMfaStep).toHaveBeenCalledWith(false); + expect(login.setMfaCode).toHaveBeenCalledWith(''); + }); + + it('FE-LOGIN-APP-008: sets a new password when the account must change it', () => { + const login = buildLogin({ passwordChangeStep: true }); + render(); + fireEvent.change(screen.getByLabelText('New password'), { target: { value: 'Abcdefgh1!' } }); + fireEvent.change(screen.getByLabelText('Confirm new password'), { target: { value: 'Abcdefgh1!' } }); + expect(login.setNewPassword).toHaveBeenCalledWith('Abcdefgh1!'); + expect(login.setConfirmPassword).toHaveBeenCalledWith('Abcdefgh1!'); + expect(screen.queryByRole('button', { name: 'Forgot password?' })).not.toBeInTheDocument(); + }); + + it('FE-LOGIN-APP-009: switches to registering where the server allows it', () => { + const login = buildLogin({ showRegisterOption: true }); + const { rerender } = render(); + fireEvent.click(screen.getByRole('button', { name: 'Register' })); + expect(login.setMode).toHaveBeenCalled(); + + rerender(); + expect(screen.getByLabelText('Username')).toBeInTheDocument(); + expect(screen.getByLabelText('Password')).toHaveAttribute('autocomplete', 'new-password'); + }); + + it('FE-LOGIN-APP-010: shows errors and waits in the address screen style', () => { + const { rerender } = render(); + expect(screen.getByRole('alert')).toHaveTextContent('Invalid credentials'); + + rerender(); + expect(screen.getByRole('status')).toHaveTextContent('Authentik'); + expect(screen.queryByLabelText('Email')).not.toBeInTheDocument(); + + rerender(); + expect(screen.getByRole('status', { name: 'Loading...' })).toBeInTheDocument(); + }); + + it('FE-LOGIN-APP-011: steps back once signed in instead of playing the takeoff', () => { + const { container } = render(); + expect(container.querySelector('.app-login')).toHaveClass('al-leaving'); + expect(container.querySelector('.takeoff-overlay')).not.toBeInTheDocument(); + }); +}); diff --git a/client/src/pages/login/AppLogin.tsx b/client/src/pages/login/AppLogin.tsx new file mode 100644 index 000000000..a66dd1d5d --- /dev/null +++ b/client/src/pages/login/AppLogin.tsx @@ -0,0 +1,403 @@ +import { AlertCircle, Eye, EyeOff, Fingerprint, Globe, Lock, Shield } from 'lucide-react'; +import React, { useEffect, useRef } from 'react'; +import ToggleSwitch from '../../components/Settings/ToggleSwitch'; +import { useNativeServer } from '../../components/Settings/useNativeServer'; +import PasswordChecklist from '../../components/shared/PasswordChecklist'; +import { useTranslation } from '../../i18n'; +import { lightStatusBarIcons } from '../../native/appBoot'; +import './appLogin.css'; +import { headingKeys, oidcLoginHref, oidcOnlyHref, submitKey, type LoginStep } from './loginModel'; +import { mfaCodeInputProps } from './MfaCodeStep'; +import { IDP_LOGIN_URL, type useLogin } from './useLogin'; + +type Login = ReturnType; + +/** + * The sign-in screen inside the iOS and Android app. It follows the app's own + * address screen (native-shell/), so it continues it instead of looking like a + * web page: the same landscape on top, the card with the server just connected + * to, the same fields and buttons. Everything it does comes from useLogin, as + * on the browser's LoginPage; only the look and the missing language menu + * (the device decides, see useLogin) differ. + */ +export default function AppLogin({ login }: { login: Login }) { + useEffect(() => lightStatusBarIcons(), []); + return ( +
+ +
+ +
+
+ ); +} + +function AppLoginContent({ login }: { login: Login }) { + const { t } = useTranslation(); + if (login.redirectScreen) { + return ( +
+
+ ); + } + if (login.configWait) { + return ( +
+
+ ); + } + if (login.oidcOnly) return ; + return ; +} + +/** The landscape of the address screen, with the server this screen signs in to. */ +function AppLoginHero() { + const { t } = useTranslation(); + const { host, changeServer } = useNativeServer(); + const hero = useRef(null); + + useEffect(() => { + const box = hero.current; + if (!box) return; + let cancelled = false; + // The same camera the address screen ends on, so the picture holds still + // across the change of screens. The scene stops drawing once its canvas + // has left the page. + void import('../../../native-shell/scenery') + .then(({ startScenery, cameraForPlan }) => { + if (!cancelled) startScenery(box, { frame: 320, camera: cameraForPlan(1), haze: false }); + }) + .catch((err: unknown) => console.warn('Landscape unavailable:', err)); + return () => { + cancelled = true; + box.querySelector('canvas.scenery')?.remove(); + }; + }, []); + + return ( +
+ TREK + {host && ( +
+
+ + +
+
+
+ +
+ )} +
+ ); +} + +function Notice({ tone, children }: { tone?: 'warn'; children: React.ReactNode }) { + return ( +
+
+ ); +} + +/** + * A field on a white card, the label above the input, as on the address screen. + * A control beside the input (the password's eye) sits outside the label, so + * the label names the input alone. + */ +function Field({ + label, + after, + ...input +}: { label: string; after?: React.ReactNode } & React.InputHTMLAttributes) { + return ( +
+ + {after && {after}} +
+ ); +} + +function OidcOnly({ login }: { login: Login }) { + const { t } = useTranslation(); + return ( +
+

{t('login.title')}

+

{login.noRedirect ? t('login.oidcLoggedOut') : t('login.oidcOnly')}

+ {login.error && {login.error}} + + +
+ ); +} + +function stepOf(login: Login): LoginStep { + return { + mode: login.mode, + mfaStep: login.mfaStep, + passwordChangeStep: login.passwordChangeStep, + hasUsers: !!login.appConfig?.has_users, + }; +} + +function Credentials({ login }: { login: Login }) { + const { t } = useTranslation(); + const step = stepOf(login); + const heading = headingKeys(step); + const onMfa = login.mode === 'login' && login.mfaStep && !login.passwordChangeStep; + const onAccount = !(login.mode === 'login' && login.mfaStep) && !login.passwordChangeStep; + return ( + <> +
+

{t(heading.title)}

+ {/* The plain sign-in needs no line under its heading; the other steps say what they ask for. */} + {heading.subtitle !== 'login.subtitle' &&

{t(heading.subtitle)}

} + + {login.passwordChangeStep && } + {onMfa && } + {onAccount && } + + + + + {login.mode === 'login' && onAccount && ( + + )} + + ); +} + +function Notices({ login }: { login: Login }) { + const { t } = useTranslation(); + return ( + <> + {login.error && {login.error}} + {login.insecureCookie && !login.appConfig?.managed && ( + + {t('login.insecureCookie.title')} + {t('login.insecureCookie.body')} +
+ + {t('login.insecureCookie.link')} + +
+ )} + {login.passwordChangeStep && {t('settings.mustChangePassword')}} + + ); +} + +function NewPassword({ login }: { login: Login }) { + const { t } = useTranslation(); + return ( + <> + login.setNewPassword(e.target.value)} + required + /> + + login.setConfirmPassword(e.target.value)} + required + /> + + ); +} + +function MfaCode({ login }: { login: Login }) { + const { t } = useTranslation(); + const back = () => { + login.setMfaStep(false); + login.setMfaToken(''); + login.setMfaCode(''); + login.setError(''); + }; + return ( + <> + {/* The account the code belongs to, for password managers (see MfaCodeStep). */} + + +

{t('login.mfaHint')}

+ + + ); +} + +function Account({ login }: { login: Login }) { + const { t } = useTranslation(); + const registering = login.mode === 'register'; + return ( + <> + {registering && ( + login.setUsername(e.target.value)} + required + placeholder="admin" + /> + )} + login.setEmail(e.target.value)} + required + placeholder={t('login.emailPlaceholder')} + /> + login.setPassword(e.target.value)} + required + placeholder="••••••••" + after={ + + } + /> + {registering && } + {!registering && } + + ); +} + +function LoginOptions({ login }: { login: Login }) { + const { t } = useTranslation(); + const toggle = () => login.setRememberMe(!login.rememberMe); + return ( +
+
+ + {/* The caption repeats the switch's own name; a tap on it is a shortcut for the switch. */} + +
+
+ ); +} + +/** SSO, a passkey and the demo: the ways in besides the password. */ +function OtherWays({ login }: { login: Login }) { + const { t } = useTranslation(); + const config = login.appConfig; + const sso = !!(config?.oidc_configured && config?.oidc_login && !login.oidcOnly); + const passkey = !!( + config?.passkey_login && + config?.passkey_configured && + login.mode === 'login' && + !login.mfaStep && + !login.passwordChangeStep + ); + if (!sso && !passkey && !config?.demo_mode) return null; + return ( +
+ {(sso || passkey) &&
{t('common.or')}
} + {sso && ( + + + )} + {passkey && ( + + )} + {config?.demo_mode && ( + + )} +
+ ); +} + +function ModeSwitch({ login }: { login: Login }) { + const { t } = useTranslation(); + const config = login.appConfig; + if (!login.showRegisterOption || !config?.has_users || config?.demo_mode || login.passwordChangeStep) return null; + const toggle = () => { + login.setMode((m) => (m === 'login' ? 'register' : 'login')); + login.setError(''); + login.setMfaStep(false); + login.setMfaToken(''); + login.setMfaCode(''); + }; + return ( +

+ {t(login.mode === 'login' ? 'login.noAccount' : 'login.hasAccount')}{' '} + +

+ ); +} diff --git a/client/src/pages/login/MfaCodeStep.tsx b/client/src/pages/login/MfaCodeStep.tsx index 364f21d1d..e672028f0 100644 --- a/client/src/pages/login/MfaCodeStep.tsx +++ b/client/src/pages/login/MfaCodeStep.tsx @@ -11,6 +11,35 @@ interface MfaCodeStepProps { onBack: () => void; } +/** + * The one-time code field, for this step and the app's sign-in screen alike. + * Text, not numeric: backup codes carry letters. The hints are set here rather + * than left to native/keyboardFields.ts, because autoFocus gives the field + * focus before any touch could prepare it. + */ +export function mfaCodeInputProps( + code: string, + onCode: (code: string) => void, + placeholder: string +): React.InputHTMLAttributes { + return { + type: 'text', + id: 'totp', + name: 'totp', + inputMode: 'text', + autoComplete: 'one-time-code', + autoCapitalize: 'characters', + autoCorrect: 'off', + spellCheck: false, + enterKeyHint: 'go', + value: code, + onChange: (e: React.ChangeEvent) => onCode(e.target.value.toUpperCase().slice(0, 24)), + placeholder, + required: true, + autoFocus: true, + }; +} + /** The login's second step: the one-time or backup code, and the way back. */ export default function MfaCodeStep({ email, code, onCode, inputStyle, onBack }: MfaCodeStepProps) { const { t } = useTranslation(); @@ -53,23 +82,7 @@ export default function MfaCodeStep({ email, code, onCode, inputStyle, onBack }: }} /> ) => onCode(e.target.value.toUpperCase().slice(0, 24))} - placeholder={t('login.mfaPlaceholder')} - required - autoFocus + {...mfaCodeInputProps(code, onCode, t('login.mfaPlaceholder'))} style={inputStyle} onFocus={(e: React.FocusEvent) => (e.target.style.borderColor = '#111827')} onBlur={(e: React.FocusEvent) => (e.target.style.borderColor = '#e5e7eb')} diff --git a/client/src/pages/login/NativeServerLink.tsx b/client/src/pages/login/NativeServerLink.tsx deleted file mode 100644 index fa68e15ee..000000000 --- a/client/src/pages/login/NativeServerLink.tsx +++ /dev/null @@ -1,18 +0,0 @@ -import { useNativeServer } from '../../components/Settings/useNativeServer'; -import { useTranslation } from '../../i18n'; - -/** Inside the iOS/Android app only: the way from the sign-in screen back to the address screen. */ -export default function NativeServerLink() { - const { t } = useTranslation(); - const { host, changeServer } = useNativeServer(); - if (!host) return null; - return ( - - ); -} diff --git a/client/src/pages/login/appLogin.css b/client/src/pages/login/appLogin.css new file mode 100644 index 000000000..34c34a09f --- /dev/null +++ b/client/src/pages/login/appLogin.css @@ -0,0 +1,652 @@ +/* + * The sign-in screen inside the iOS and Android app (AppLogin.tsx). It is the + * next screen after the app's own address screen (native-shell/), so it wears + * that screen's look: the same landscape on top, the same glass card with the + * server on it, the same type, fields and buttons on the same warm page. The + * values mirror native-shell/shell.css; keep the two in step. + * + * Light on purpose, like the screens before it: the user's appearance is not + * known before signing in. The tokens the shared controls read (ToggleSwitch, + * PasswordChecklist) are pinned to the light values inside the screen, so a + * dark scheme left on the device does not reach into it. + * + * Every side is a logical one, so Arabic mirrors the layout on its own. + */ + +/* + * The text face of the address screen, from the same files it bundles. Loaded + * only once a letter of the range is on this screen; Cyrillic and the scripts + * it does not cover fall back to the app's own face. + */ +@font-face { + font-family: 'Plus Jakarta Sans'; + font-style: normal; + font-weight: 500; + font-display: swap; + src: url('../../../native-shell/fonts/plus-jakarta-sans-latin-500.woff2') format('woff2'); + unicode-range: + U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, + U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; +} +@font-face { + font-family: 'Plus Jakarta Sans'; + font-style: normal; + font-weight: 600; + font-display: swap; + src: url('../../../native-shell/fonts/plus-jakarta-sans-latin-600.woff2') format('woff2'); + unicode-range: + U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, + U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; +} +@font-face { + font-family: 'Plus Jakarta Sans'; + font-style: normal; + font-weight: 700; + font-display: swap; + src: url('../../../native-shell/fonts/plus-jakarta-sans-latin-700.woff2') format('woff2'); + unicode-range: + U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, + U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; +} +@font-face { + font-family: 'Plus Jakarta Sans'; + font-style: normal; + font-weight: 500; + font-display: swap; + src: url('../../../native-shell/fonts/plus-jakarta-sans-latin-ext-500.woff2') format('woff2'); + unicode-range: + U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, + U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF; +} +@font-face { + font-family: 'Plus Jakarta Sans'; + font-style: normal; + font-weight: 600; + font-display: swap; + src: url('../../../native-shell/fonts/plus-jakarta-sans-latin-ext-600.woff2') format('woff2'); + unicode-range: + U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, + U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF; +} +@font-face { + font-family: 'Plus Jakarta Sans'; + font-style: normal; + font-weight: 700; + font-display: swap; + src: url('../../../native-shell/fonts/plus-jakarta-sans-latin-ext-700.woff2') format('woff2'); + unicode-range: + U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, + U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF; +} + +.app-login { + --al-page: #fffaf5; + --al-ink: #1f1a17; + --al-text: #6b5f57; + --al-muted: #8a7b6f; + --al-faint: #b9ab9e; + --al-line: #efe4d8; + --al-line-soft: #f3ebe1; + --al-sand: #f6efe6; + --al-dark: #111827; + --al-good: #1d7a46; + --al-bad: #b42318; + --al-bad-soft: #fbeeec; + --al-bad-ink: #8f2a1d; + --al-warn-soft: #fdf3e2; + --al-warn-ink: #8a5a12; + --al-sea: #cfe3ef; + --al-text-face: 'Plus Jakarta Sans', var(--font-system); + --al-display: 'Poppins', system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif; + --al-safe-top: max(env(safe-area-inset-top, 0px), var(--safe-area-inset-top, 0px), var(--trek-native-safe-top, 0px)); + --al-safe-bottom: max( + env(safe-area-inset-bottom, 0px), + var(--safe-area-inset-bottom, 0px), + var(--trek-native-safe-bottom, 0px) + ); + --al-safe-start: max( + env(safe-area-inset-left, 0px), + var(--safe-area-inset-left, 0px), + var(--trek-native-safe-left, 0px) + ); + --al-safe-end: max( + env(safe-area-inset-right, 0px), + var(--safe-area-inset-right, 0px), + var(--trek-native-safe-right, 0px) + ); + + /* What the shared controls inside read. */ + --accent: var(--al-dark); + --accent-text: #fff; + --text-primary: var(--al-ink); + --border-primary: #e6dccf; + --bg-card: #fff; + + position: fixed; + inset: 0; + overflow-x: hidden; + overflow-y: auto; + overscroll-behavior: none; + scrollbar-width: none; + display: flex; + flex-direction: column; + background: var(--al-page); + color: var(--al-ink); + color-scheme: light; + font-family: var(--al-text-face); + -webkit-tap-highlight-color: transparent; + animation: al-in 0.42s cubic-bezier(0.2, 0.8, 0.2, 1) both; +} +.app-login::-webkit-scrollbar { + display: none; +} +.app-login *, +.app-login *::before, +.app-login *::after { + box-sizing: border-box; +} +@keyframes al-in { + from { + opacity: 0; + } + to { + opacity: 1; + } +} + +/* ── The landscape and the server card on it ── */ +.al-hero { + position: relative; + flex: none; + overflow: hidden; + height: min(272px, 33svh); + min-height: 200px; + margin-bottom: -1px; + background: var(--al-sea); +} +.al-hero .scenery { + position: absolute; + inset: 0; + width: 100%; + height: 100%; + animation: al-in 0.6s ease-out both; +} +/* The status bar's clock and icons stay readable on the sea. */ +.al-hero::before { + content: ''; + position: absolute; + z-index: 1; + inset-inline: 0; + top: 0; + height: calc(var(--al-safe-top) + 36px); + background: linear-gradient(180deg, rgba(8, 24, 40, 0.28), rgba(8, 24, 40, 0)); + pointer-events: none; +} +.al-hero::after { + content: ''; + position: absolute; + inset-inline: 0; + bottom: -2px; + height: 110px; + background: linear-gradient(180deg, rgba(255, 250, 245, 0) 0%, rgba(255, 250, 245, 0.8) 55%, #fffaf5 82%); + pointer-events: none; +} +.al-logo { + position: absolute; + z-index: 2; + top: calc(var(--al-safe-top) + 10px); + inset-inline-start: calc(24px + var(--al-safe-start)); + height: 40px; + filter: drop-shadow(0 1px 6px rgba(7, 40, 70, 0.45)); +} +.al-card { + position: absolute; + z-index: 2; + inset-inline: calc(20px + var(--al-safe-start)) calc(20px + var(--al-safe-end)); + bottom: 44px; + display: flex; + align-items: center; + gap: 12px; + padding-block: 12px 13px; + padding-inline: 16px 12px; + border-radius: 18px; + background: rgba(255, 255, 255, 0.8); + -webkit-backdrop-filter: blur(16px) saturate(1.5); + backdrop-filter: blur(16px) saturate(1.5); + box-shadow: + 0 18px 36px -18px rgba(17, 24, 39, 0.55), + inset 0 0 0 1px rgba(255, 255, 255, 0.6); +} +.al-card-text { + flex: 1; + min-width: 0; +} +.al-card small { + display: flex; + align-items: center; + gap: 6px; + font-size: 11px; + font-weight: 700; + letter-spacing: 0.1em; + text-transform: uppercase; + color: var(--al-good); +} +.al-host { + display: flex; + align-items: center; + gap: 8px; + margin-top: 5px; + min-width: 0; + font-family: var(--al-display); + font-size: 20px; + font-weight: 600; + letter-spacing: -0.02em; + color: var(--al-dark); +} +.al-host svg { + flex: none; +} +.al-host span { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.al-change { + flex: none; + min-height: 36px; + padding: 0 13px; + border: 0; + border-radius: 11px; + background: #fff; + color: var(--al-dark); + font: 700 13.5px var(--al-text-face); + cursor: pointer; + box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12); +} + +/* ── The content ── */ +.al-body { + position: relative; + z-index: 2; + flex: 1; + display: flex; + flex-direction: column; + padding-block: 6px calc(28px + var(--al-safe-bottom)); + padding-inline: calc(24px + var(--al-safe-start)) calc(24px + var(--al-safe-end)); +} +.al-form { + display: flex; + flex-direction: column; + gap: 12px; +} +.al-title { + margin: 0; + font-family: var(--al-display); + font-size: calc(28px * var(--fs-scale-title, 1)); + font-weight: 600; + letter-spacing: -0.02em; + line-height: 1.12; + text-wrap: balance; +} +.al-sub { + margin: 4px 0 6px; + font-size: calc(15px * var(--fs-scale-body, 1)); + line-height: 1.5; + color: var(--al-text); +} + +/* A field on a white card: the label above, the input below it. */ +.al-fld { + position: relative; + display: flex; + flex-direction: column; + gap: 2px; + padding: 10px 16px 11px; + border-radius: 16px; + background: #fff; + box-shadow: 0 0 0 1px var(--al-line); + cursor: text; + transition: box-shadow 0.2s; +} +.al-fld:focus-within { + box-shadow: 0 0 0 2px var(--al-dark); +} +.al-lab { + font-size: calc(12px * var(--fs-scale-body, 1)); + font-weight: 700; + color: var(--al-muted); +} +.al-fld-wrap { + position: relative; +} +.al-fld-wrap.with-after .al-fld input { + padding-inline-end: 40px; +} +.al-after { + position: absolute; + inset-inline-end: 8px; + bottom: 4px; +} +.al-fld input { + flex: 1; + min-width: 0; + width: 100%; + border: 0; + outline: none; + background: transparent; + padding: 0; + /* 16 px or more, or iOS zooms into the field on focus. */ + font: 600 16px var(--al-text-face); + color: var(--al-ink); +} +.al-fld input::placeholder { + color: var(--al-faint); + font-weight: 500; +} +.al-eye { + display: grid; + place-items: center; + width: 44px; + height: 44px; + border: 0; + border-radius: 10px; + background: transparent; + color: var(--al-muted); + cursor: pointer; +} +.al-check { + margin-top: -4px; +} + +.al-options { + display: flex; + align-items: center; + gap: 12px; + min-height: 44px; +} +.al-remember { + display: flex; + align-items: center; + gap: 10px; + min-width: 0; + font-size: calc(14px * var(--fs-scale-body, 1)); + font-weight: 600; + color: var(--al-text); + cursor: pointer; + user-select: none; +} +.al-forgot { + align-self: center; + min-height: 44px; + margin-top: 6px; + padding: 0 8px; + border: 0; + background: none; + color: var(--al-text); + font: 600 calc(14px * var(--fs-scale-body, 1)) var(--al-text-face); + cursor: pointer; +} + +/* ── Buttons ── */ +.al-cta, +.al-cta2 { + width: 100%; + border: 0; + border-radius: 16px; + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; + gap: 10px; + text-align: center; + text-decoration: none; + transition: + transform 0.15s, + opacity 0.15s; +} +.al-cta { + min-height: 56px; + margin-top: 4px; + background: var(--al-dark); + color: #fff; + font: 700 calc(17px * var(--fs-scale-body, 1)) var(--al-text-face); + box-shadow: 0 14px 28px -14px rgba(17, 24, 39, 0.55); +} +.al-cta2 { + min-height: 52px; + background: #fff; + color: var(--al-dark); + font: 700 calc(16px * var(--fs-scale-body, 1)) var(--al-text-face); + box-shadow: 0 0 0 1.5px var(--al-line); +} +.al-cta:active, +.al-cta2:active { + transform: scale(0.985); +} +.al-cta:disabled, +.al-cta2:disabled { + opacity: 0.7; + cursor: default; +} +.al-demo { + background: linear-gradient(135deg, #f59e0b, #d97706); + color: #451a03; + box-shadow: 0 10px 24px -14px rgba(217, 119, 6, 0.7); +} +.al-spin { + width: 18px; + height: 18px; + border-radius: 50%; + border: 2px solid currentColor; + border-top-color: transparent; + animation: al-spin 0.8s linear infinite; +} +@keyframes al-spin { + to { + transform: rotate(360deg); + } +} + +.al-or { + display: flex; + align-items: center; + gap: 12px; + margin: 10px 0 2px; + font-size: calc(13px * var(--fs-scale-body, 1)); + font-weight: 600; + color: var(--al-faint); +} +.al-or::before, +.al-or::after { + content: ''; + flex: 1; + height: 1px; + background: var(--al-line); +} +.al-alt { + display: flex; + flex-direction: column; + gap: 10px; + margin-top: 10px; +} + +.al-switch { + margin: 16px 0 0; + text-align: center; + font-size: calc(14px * var(--fs-scale-body, 1)); + color: var(--al-muted); +} +.al-switch button { + min-height: 44px; + padding: 0 4px; + border: 0; + background: none; + color: var(--al-ink); + font: 700 calc(14px * var(--fs-scale-body, 1)) var(--al-text-face); + cursor: pointer; +} + +/* ── Messages ── */ +.al-notice { + display: flex; + gap: 10px; + align-items: flex-start; + margin: 0; + padding: 12px 14px; + border-radius: 14px; + background: var(--al-bad-soft); + color: var(--al-bad-ink); + font-size: calc(13.5px * var(--fs-scale-body, 1)); + font-weight: 600; + line-height: 1.45; +} +.al-notice svg { + flex: none; + margin-top: 1px; +} +.al-notice.warn { + background: var(--al-warn-soft); + color: var(--al-warn-ink); +} +.al-notice b { + display: block; + margin-bottom: 2px; +} +.al-notice a { + display: inline-block; + margin-top: 4px; + color: inherit; + font-weight: 700; +} +.al-hint { + margin: 0; + font-size: calc(12.5px * var(--fs-scale-body, 1)); + line-height: 1.5; + color: var(--al-muted); +} +.al-back { + align-self: flex-start; + min-height: 40px; + padding: 0; + border: 0; + background: none; + color: var(--al-text); + font: 600 calc(14px * var(--fs-scale-body, 1)) var(--al-text-face); + cursor: pointer; +} + +/* Waiting: on the way to the sign-in provider, or for the server's settings. */ +.al-wait { + flex: 1; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 14px; + min-height: 180px; + padding-bottom: 40px; + text-align: center; + color: var(--al-text); +} +.al-wait .al-spin { + width: 24px; + height: 24px; + border-width: 2.5px; +} +.al-wait p { + margin: 0; + font-size: calc(16px * var(--fs-scale-body, 1)); + font-weight: 600; + color: var(--al-ink); +} +.al-wait a { + font-size: calc(14px * var(--fs-scale-body, 1)); + color: var(--al-text); +} + +.app-login :focus-visible { + outline: 2px solid var(--al-dark); + outline-offset: 2px; +} + +/* + * An iPad, an unfolded phone, a phone on its side: the landscape fills one side + * and the form stands in a column of its own beside it, as on the address screen. + */ +@media (min-width: 900px), (orientation: landscape) and (max-height: 500px) { + .app-login { + flex-direction: row; + overflow: hidden; + } + .al-hero { + flex: 1 1 auto; + height: 100%; + min-height: 0; + margin: 0; + } + .al-hero::after { + display: none; + } + .al-card { + inset-inline: calc(32px + var(--al-safe-start)) auto; + width: min(420px, calc(100% - 64px)); + bottom: 40px; + } + .al-logo { + top: calc(var(--al-safe-top) + 24px); + inset-inline-start: calc(32px + var(--al-safe-start)); + height: 46px; + } + .al-body { + flex: none; + width: 460px; + height: 100%; + overflow-x: hidden; + overflow-y: auto; + scrollbar-width: none; + justify-content: center; + padding-block: calc(var(--al-safe-top) + 32px) calc(32px + var(--al-safe-bottom)); + padding-inline: 32px calc(32px + var(--al-safe-end)); + background: var(--al-page); + box-shadow: -1px 0 0 rgba(31, 26, 23, 0.06); + } +} +@media (orientation: landscape) and (max-height: 500px) { + .al-body { + width: min(420px, 52vw); + justify-content: flex-start; + padding-top: calc(var(--al-safe-top) + 20px); + } +} + +@media (prefers-reduced-motion: reduce) { + .app-login, + .app-login * { + animation: none !important; + transition: none !important; + } + .al-spin { + animation: al-spin 1.6s linear infinite !important; + } +} + +/* Signed in: the screen steps back into the page colour, and the app rises in + from it (native/appBoot.ts handOverToApp). */ +.app-login.al-leaving .al-body { + animation: al-leave-body 0.34s cubic-bezier(0.4, 0, 1, 1) both; +} +.app-login.al-leaving .al-hero { + animation: al-leave-hero 0.42s ease-in both; +} +@keyframes al-leave-body { + to { + opacity: 0; + transform: translateY(14px); + } +} +@keyframes al-leave-hero { + to { + opacity: 0; + } +} diff --git a/client/src/pages/login/loginModel.test.ts b/client/src/pages/login/loginModel.test.ts new file mode 100644 index 000000000..6f671da87 --- /dev/null +++ b/client/src/pages/login/loginModel.test.ts @@ -0,0 +1,43 @@ +// FE-LOGIN-MODEL-001 to FE-LOGIN-MODEL-004 +import { describe, expect, it } from 'vitest'; +import { headingKeys, oidcLoginHref, oidcOnlyHref, submitKey, type LoginStep } from './loginModel'; + +const step = (overrides: Partial = {}): LoginStep => ({ + mode: 'login', + mfaStep: false, + passwordChangeStep: false, + hasUsers: true, + ...overrides, +}); + +describe('loginModel', () => { + it('FE-LOGIN-MODEL-001: names each step of the sign-in', () => { + expect(headingKeys(step())).toEqual({ title: 'login.title', subtitle: 'login.subtitle' }); + expect(headingKeys(step({ mfaStep: true })).title).toBe('login.mfaTitle'); + expect(headingKeys(step({ passwordChangeStep: true, mfaStep: true })).title).toBe('login.setNewPassword'); + expect(headingKeys(step({ mode: 'register' })).title).toBe('login.createAccount'); + expect(headingKeys(step({ mode: 'register', hasUsers: false })).title).toBe('login.createAdmin'); + }); + + it('FE-LOGIN-MODEL-002: labels the submit button for the step and while it runs', () => { + expect(submitKey(step(), false)).toBe('login.signIn'); + expect(submitKey(step(), true)).toBe('login.signingIn'); + expect(submitKey(step({ mfaStep: true }), true)).toBe('login.mfaVerify'); + expect(submitKey(step({ mode: 'register' }), false)).toBe('login.createAccount'); + expect(submitKey(step({ mode: 'register' }), true)).toBe('login.creating'); + expect(submitKey(step({ passwordChangeStep: true }), true)).toBe('settings.updatePassword'); + }); + + it('FE-LOGIN-MODEL-003: carries the invite and the remember-me choice to SSO, only when signing in', () => { + expect(oidcLoginHref('', 'login', true)).toBe('/api/auth/oidc/login?remember=1'); + expect(oidcLoginHref('', 'login', false)).toBe('/api/auth/oidc/login?remember=0'); + expect(oidcLoginHref('a b', 'login', true)).toBe('/api/auth/oidc/login?invite=a%20b&remember=1'); + expect(oidcLoginHref('', 'register', true)).toBe('/api/auth/oidc/login'); + expect(oidcLoginHref('tok', 'register', false)).toBe('/api/auth/oidc/login?invite=tok'); + }); + + it('FE-LOGIN-MODEL-004: always asks for the remembered session on an OIDC-only install', () => { + expect(oidcOnlyHref('')).toBe('/api/auth/oidc/login?remember=1'); + expect(oidcOnlyHref('tok')).toBe('/api/auth/oidc/login?invite=tok&remember=1'); + }); +}); diff --git a/client/src/pages/login/loginModel.ts b/client/src/pages/login/loginModel.ts new file mode 100644 index 000000000..9ebfdd501 --- /dev/null +++ b/client/src/pages/login/loginModel.ts @@ -0,0 +1,51 @@ +// What the sign-in screens say and where their buttons lead, shared by the +// browser's LoginPage and the app's AppLogin, so the two cannot drift apart. + +export type LoginMode = 'login' | 'register'; + +export interface LoginStep { + mode: LoginMode; + mfaStep: boolean; + passwordChangeStep: boolean; + /** False on a fresh install, where the first account becomes the admin. */ + hasUsers: boolean; +} + +/** The heading and the line under it, as translation keys. */ +export function headingKeys(step: LoginStep): { title: string; subtitle: string } { + if (step.passwordChangeStep) return { title: 'login.setNewPassword', subtitle: 'login.setNewPasswordHint' }; + if (step.mode === 'login' && step.mfaStep) return { title: 'login.mfaTitle', subtitle: 'login.mfaSubtitle' }; + if (step.mode === 'register') { + return step.hasUsers + ? { title: 'login.createAccount', subtitle: 'login.createAccountHint' } + : { title: 'login.createAdmin', subtitle: 'login.createAdminHint' }; + } + return { title: 'login.title', subtitle: 'login.subtitle' }; +} + +/** The submit button's label, as a translation key; another while the request runs. */ +export function submitKey(step: LoginStep, loading: boolean): string { + if (step.passwordChangeStep) return 'settings.updatePassword'; + if (step.mode === 'register') return loading ? 'login.creating' : 'login.createAccount'; + if (step.mfaStep) return 'login.mfaVerify'; + return loading ? 'login.signingIn' : 'login.signIn'; +} + +/** + * The SSO button beside the password form. The remember-me switch only shows in + * login mode; in register mode the parameter stays off so the server default applies. + */ +export function oidcLoginHref(inviteToken: string, mode: LoginMode, rememberMe: boolean): string { + const params: string[] = []; + if (inviteToken) params.push('invite=' + encodeURIComponent(inviteToken)); + if (mode === 'login') params.push('remember=' + (rememberMe ? '1' : '0')); + return '/api/auth/oidc/login' + (params.length ? '?' + params.join('&') : ''); +} + +/** + * The only button in OIDC-only mode. No remember-me switch there: the IdP owns + * the session policy, so it always asks for the remembered lifetime (#1927). + */ +export function oidcOnlyHref(inviteToken: string): string { + return `/api/auth/oidc/login${inviteToken ? '?invite=' + encodeURIComponent(inviteToken) + '&' : '?'}remember=1`; +} diff --git a/client/src/pages/login/useLogin.native.test.tsx b/client/src/pages/login/useLogin.native.test.tsx index cbcd4f355..1b21317b8 100644 --- a/client/src/pages/login/useLogin.native.test.tsx +++ b/client/src/pages/login/useLogin.native.test.tsx @@ -1,4 +1,4 @@ -// FE-LOGIN-NATIVE-001 to FE-LOGIN-NATIVE-008: useLogin inside the iOS/Android app +// FE-LOGIN-NATIVE-001 to FE-LOGIN-NATIVE-011: useLogin inside the iOS/Android app import { startAuthentication } from '@simplewebauthn/browser'; import { http, HttpResponse } from 'msw'; import React from 'react'; @@ -11,7 +11,9 @@ import { act, renderHook, waitFor } from '../../../tests/helpers/render'; import { resetAllStores } from '../../../tests/helpers/store'; import { TranslationProvider } from '../../i18n/TranslationContext'; import { BrowserSignInCancelled, resumeBrowserSignIn, signInThroughBrowser } from '../../native/browserSignIn'; +import { toastHaptic } from '../../native/haptics'; import { useAuthStore } from '../../store/authStore'; +import { useSettingsStore } from '../../store/settingsStore'; import { markSignedOut, wasSignedOut } from '../../utils/signedOut'; import { useLogin } from './useLogin'; @@ -23,12 +25,18 @@ vi.mock('react-router', async () => { }); vi.mock('@simplewebauthn/browser', () => ({ startAuthentication: vi.fn() })); vi.mock('../../native/platform', () => ({ isNativeApp: () => true })); +vi.mock('../../native/haptics', () => ({ toastHaptic: vi.fn() })); vi.mock('../../native/browserSignIn', async () => { const actual = await vi.importActual('../../native/browserSignIn'); return { ...actual, signInThroughBrowser: vi.fn(), resumeBrowserSignIn: vi.fn() }; }); const realLocation = window.location; +const realLanguages = Object.getOwnPropertyDescriptor(window.navigator, 'languages'); + +function deviceLanguages(languages: string[]) { + Object.defineProperty(window.navigator, 'languages', { configurable: true, get: () => languages }); +} const loadUser = vi.fn(async () => {}); function renderLogin() { @@ -61,6 +69,9 @@ beforeEach(() => { afterEach(() => { vi.useRealTimers(); + if (realLanguages) Object.defineProperty(window.navigator, 'languages', realLanguages); + else delete (window.navigator as { languages?: readonly string[] }).languages; + localStorage.removeItem('app_language'); Object.defineProperty(window, 'location', { configurable: true, writable: true, value: realLocation }); }); @@ -152,4 +163,28 @@ describe('useLogin in the native app', () => { await waitFor(() => expect(result.current.error).toBe('Signing in did not work. Please try again.')); expect(result.current.showTakeoff).toBe(false); }); + + it('FE-LOGIN-NATIVE-009: speaks the device language, over a language once picked on this page', async () => { + localStorage.setItem('app_language', 'fr'); + deviceLanguages(['de-DE', 'en-US']); + renderLogin(); + await waitFor(() => expect(useSettingsStore.getState().settings.language).toBe('de')); + }); + + it('FE-LOGIN-NATIVE-010: falls back to English on a device language TREK has no translation for', async () => { + deviceLanguages(['pt-PT']); + useSettingsStore.setState((state) => ({ settings: { ...state.settings, language: 'fr' } })); + renderLogin(); + await waitFor(() => expect(useSettingsStore.getState().settings.language).toBe('en')); + }); + + it('FE-LOGIN-NATIVE-011: opens the app after signing in without the takeoff, with the success tap', async () => { + vi.mocked(resumeBrowserSignIn).mockResolvedValue(true); + mockNavigate.mockClear(); + const { result } = renderLogin(); + + await waitFor(() => expect(result.current.showTakeoff).toBe(true)); + expect(toastHaptic).toHaveBeenCalledWith('success'); + await waitFor(() => expect(mockNavigate).toHaveBeenCalledWith('/'), { timeout: 2500 }); + }); }); diff --git a/client/src/pages/login/useLogin.ts b/client/src/pages/login/useLogin.ts index 0aa7550c9..26f022efa 100644 --- a/client/src/pages/login/useLogin.ts +++ b/client/src/pages/login/useLogin.ts @@ -9,6 +9,8 @@ import { authApi, configApi } from '../../api/client' import { getApiErrorMessage } from '../../types' import { START_DESTINATION_ROUTE } from '../../utils/startDestination' import { passwordErrorKey } from '../../utils/passwordError' +import { handOverToApp } from '../../native/appBoot' +import { toastHaptic } from '../../native/haptics' import { isNativeApp } from '../../native/platform' import { BrowserSignInCancelled, @@ -164,6 +166,13 @@ export function useLogin() { */ const takeOff = (): void => { setShowTakeoff(true) + if (nativeApp) { + // The app has no takeoff: the sign-in screen steps back and the app rises in + // as soon as the settings are there (native/appBoot.ts). + toastHaptic('success') + void handOverToApp(loadSettings(), () => navigate(redirectTarget)) + return + } loadSettings() setTimeout(() => navigate(redirectTarget), 2600) } @@ -289,7 +298,15 @@ export function useLogin() { // 2. Browser/OS language (navigator.languages) // 3. Server default (DEFAULT_LANGUAGE env var) // 4. 'en' → hardcoded fallback already in store + // Inside the iOS and Android app the sign-in screen has no language menu: it + // speaks the device's language, as the address screen before it does, and + // English where TREK has no translation for it. The account's own language + // takes over once signed in. useEffect(() => { + if (nativeApp) { + setLanguageTransient(detectBrowserLanguage() ?? 'en') + return + } if (hasStoredLanguage()) return const detected = detectBrowserLanguage() @@ -301,7 +318,7 @@ export function useLogin() { configApi.getPublicConfig() .then(({ defaultLanguage }) => { if (defaultLanguage) setLanguageTransient(defaultLanguage) }) .catch((err) => console.warn('Failed to fetch default language config:', err)) - }, [setLanguageTransient]) + }, [setLanguageTransient, nativeApp]) useEffect(() => { if (!langDropdownOpen) return @@ -457,7 +474,7 @@ export function useLogin() { const oidcOnly = !appConfig?.password_login && appConfig?.oidc_login && appConfig?.oidc_configured return { - navigate, + navigate, nativeApp, mode, setMode, username, setUsername, email, setEmail, password, setPassword, rememberMe, setRememberMe, showPassword, setShowPassword, isLoading, error, setError, insecureCookie, appConfig, inviteToken,