π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
feat(appLock):code-restructured
Aswin Asokffa0f9c5f813
diff --git a/web/apps/photos/.env b/web/apps/photos/.envindex ff749bb0a6..0f355bb6bc 100644--- a/web/apps/photos/.env+++ b/web/apps/photos/.env@@ -80,3 +80,4 @@# NEXT_PUBLIC_ENTE_TEST_EXPECTED_JSON = {}NEXT_TELEMETRY_DISABLED = 1+NEXT_PUBLIC_ENTE_ENABLE_APP_LOCK = truediff --git a/web/apps/photos/src/components/app-lock/LockScreenContents.tsx b/web/apps/photos/src/components/app-lock/LockScreenContents.tsxnew file mode 100644index 0000000000..ed934060d3--- /dev/null+++ b/web/apps/photos/src/components/app-lock/LockScreenContents.tsx@@ -0,0 +1,59 @@+import { Box } from "@mui/material";+import { EnteLogo } from "ente-base/components/EnteLogo";+import { FocusVisibleButton } from "ente-base/components/mui/FocusVisibleButton";+import { AppLockPrompt } from "ente-new/photos/components/app-lock/AppLockPrompt";+import { t } from "i18next";+import type { CSSProperties } from "react";++export const LockScreenContents = () => {+ return (+ <Box+ sx={{+ position: "fixed",+ inset: 0,+ display: "flex",+ flexDirection: "column",+ alignItems: "center",+ justifyContent: "center",+ outline: "none",+ }}+ style={{ WebkitAppRegion: "no-drag" } as CSSProperties}+ >+ <AppLockPrompt+ lockScreenMode="lock"+ renderHeader={({ showLogoutConfirm, showLogout }) => (+ <Box+ sx={{+ position: "absolute",+ top: 0,+ left: 0,+ right: 0,+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ p: 3,+ }}+ >+ <EnteLogo />+ {!showLogoutConfirm && (+ <FocusVisibleButton+ variant="text"+ color="secondary"+ size="small"+ onClick={showLogout}+ sx={{+ textTransform: "none",+ position: "absolute",+ right: 24,+ color: "text.muted",+ }}+ >+ {t("logout")}+ </FocusVisibleButton>+ )}+ </Box>+ )}+ />+ </Box>+ );+};diff --git a/web/apps/photos/src/components/utils/use-app-lock-route.ts b/web/apps/photos/src/components/utils/use-app-lock-route.tsnew file mode 100644index 0000000000..6a7992954d--- /dev/null+++ b/web/apps/photos/src/components/utils/use-app-lock-route.ts@@ -0,0 +1,69 @@+import { isDesktop } from "ente-base/app";+import type { AppLockState } from "ente-new/photos/services/app-lock";+import { useRouter } from "next/router";+import { useEffect } from "react";++const APP_LOCK_ROUTE = "/lock";+const APP_LOCK_RETURN_TO_KEY = "appLock.returnToPath";++interface DesktopAppLockRouteState {+ showLockPage: boolean;+ shouldBlockAppLockRouteTransition: boolean;+}++const rememberAppLockReturnTo = (path: string) => {+ if (path === APP_LOCK_ROUTE) return;+ sessionStorage.setItem(APP_LOCK_RETURN_TO_KEY, path);+};++const consumeAppLockReturnTo = (): string | null => {+ const returnTo = sessionStorage.getItem(APP_LOCK_RETURN_TO_KEY);+ sessionStorage.removeItem(APP_LOCK_RETURN_TO_KEY);+ return returnTo;+};++export const useDesktopAppLockRoute = (+ isAppLockReady: boolean,+ isLocked: AppLockState["isLocked"],+ lockScreenMode: AppLockState["lockScreenMode"],+): DesktopAppLockRouteState => {+ const router = useRouter();+ const showLockPage = isDesktop && isLocked && lockScreenMode === "lock";++ useEffect(() => {+ if (!isDesktop || !isAppLockReady || !showLockPage) return;++ if (router.asPath !== APP_LOCK_ROUTE) {+ rememberAppLockReturnTo(router.asPath);+ }++ if (router.pathname !== APP_LOCK_ROUTE) {+ void router.replace(APP_LOCK_ROUTE);+ }+ }, [isAppLockReady, showLockPage, router, router.asPath, router.pathname]);++ useEffect(() => {+ if (+ !isDesktop ||+ !isAppLockReady ||+ showLockPage ||+ router.pathname !== APP_LOCK_ROUTE+ ) {+ return;+ }++ const returnTo = consumeAppLockReturnTo();+ void router.replace(+ returnTo && returnTo !== APP_LOCK_ROUTE ? returnTo : "/gallery",+ );+ }, [isAppLockReady, showLockPage, router, router.pathname]);++ return {+ showLockPage,+ shouldBlockAppLockRouteTransition:+ isDesktop &&+ isAppLockReady &&+ ((showLockPage && router.pathname !== APP_LOCK_ROUTE) ||+ (!showLockPage && router.pathname === APP_LOCK_ROUTE)),+ };+};diff --git a/web/apps/photos/src/pages/_app.tsx b/web/apps/photos/src/pages/_app.tsxindex 660fe411b1..4ed6598f89 100644--- a/web/apps/photos/src/pages/_app.tsx+++ b/web/apps/photos/src/pages/_app.tsx@@ -3,6 +3,7 @@ import ArrowForwardIcon from "@mui/icons-material/ArrowForward";import { CssBaseline, Typography } from "@mui/material";import { styled, ThemeProvider } from "@mui/material/styles";import { useNotification } from "components/utils/hooks-app";+import { useDesktopAppLockRoute } from "components/utils/use-app-lock-route";import {isLocalStorageAndIndexedDBMismatch,savedLocalUser,@@ -31,7 +32,7 @@ import {initVideoProcessing,isHLSGenerationSupported,} from "ente-gallery/services/video";-import { AppLockOverlay } from "ente-new/photos/components/AppLockOverlay";+import { AppLockReauthenticationDialog } from "ente-new/photos/components/app-lock/AppLockReauthenticationDialog";import { Notification } from "ente-new/photos/components/Notification";import { ThemedLoadingBar } from "ente-new/photos/components/ThemedLoadingBar";import {@@ -244,6 +245,11 @@ const DesktopMainContent: React.FC<MainContentProps> = ({}) => {const isAppLockReady = useSetupAppLock();const appLock = useAppLockSnapshot();+ const { shouldBlockAppLockRouteTransition } = useDesktopAppLockRoute(+ isAppLockReady,+ appLock.isLocked,+ appLock.lockScreenMode,+ );useAutoLockWhenBackgrounded(appLock.enabled,@@ -252,12 +258,13 @@ const DesktopMainContent: React.FC<MainContentProps> = ({);if (!isAppLockReady) return <LoadingIndicator />;+ if (shouldBlockAppLockRouteTransition) return <LoadingIndicator />;return (<>{isChangingRoute && <TranslucentLoadingOverlay />}<Component {...pageProps} />- <AppLockOverlay />+ <AppLockReauthenticationDialog /></>);};diff --git a/web/apps/photos/src/pages/lock.tsx b/web/apps/photos/src/pages/lock.tsxnew file mode 100644index 0000000000..1b30368088--- /dev/null+++ b/web/apps/photos/src/pages/lock.tsx@@ -0,0 +1,24 @@+import { Modal } from "@mui/material";+import { LockScreenContents } from "components/app-lock/LockScreenContents";+import { t } from "i18next";++export const LockPage = () => (+ <Modal+ open+ disableEscapeKeyDown+ aria-label={t("app_lock")}+ slotProps={{+ backdrop: {+ sx: (theme) => ({+ backgroundColor: "secondary.main",+ ...theme.applyStyles("dark", { backgroundColor: "#000" }),+ }),+ },+ }}+ sx={{ zIndex: "calc(var(--mui-zIndex-tooltip) + 1)" }}+ >+ <LockScreenContents />+ </Modal>+);++export default LockPage;diff --git a/web/packages/new/photos/components/AppLockOverlay.tsx b/web/packages/new/photos/components/AppLockOverlay.tsxdeleted file mode 100644index aadb8b08a5..0000000000--- a/web/packages/new/photos/components/AppLockOverlay.tsx+++ /dev/null@@ -1,1374 +0,0 @@-/**- * @file Full-viewport lock screen overlay for the app lock feature.- *- * Renders as a sibling of the page Component in _app.tsx, covering all content- * when the app is locked. Supports PIN (4-digit), password, and local native- * device lock unlock mode, with brute-force cooldown display and a- * logout escape hatch.- */--import CloseIcon from "@mui/icons-material/Close";-import {- Box,- CircularProgress,- IconButton,- Modal,- Paper,- Stack,- TextField,- Typography,-} from "@mui/material";-import type { Theme } from "@mui/material/styles";-import { EnteLogo } from "ente-base/components/EnteLogo";-import { FocusVisibleButton } from "ente-base/components/mui/FocusVisibleButton";-import { ShowHidePasswordInputAdornment } from "ente-base/components/mui/PasswordInputAdornment";-import { useBaseContext } from "ente-base/context";-import log from "ente-base/log";-import { t } from "i18next";-import React, {- useCallback,- useEffect,- useMemo,- useRef,- useState,-} from "react";-import {- attemptDeviceLockUnlock,- attemptUnlock,- cancelReauthentication,- type DeviceLockUnlockResult,- type UnlockResult,-} from "../services/app-lock";-import { useAppLockSnapshot } from "./utils/use-snapshot";--/**- * A full-viewport overlay that blocks interaction with the app until the user- * authenticates with their PIN, password, or local device lock challenge.- *- * Renders nothing when the app is not locked.- */-export const AppLockOverlay: React.FC = () => {- const appLock = useAppLockSnapshot();- const { logout } = useBaseContext();- const [showLogoutConfirm, setShowLogoutConfirm] = useState(false);- const isReauthentication = appLock.lockScreenMode === "reauthenticate";-- useEffect(() => {- if (!appLock.isLocked) setShowLogoutConfirm(false);- }, [appLock.isLocked]);-- if (!appLock.isLocked) return null;-- const closeAction =- isReauthentication && !showLogoutConfirm ? (- <IconButton- aria-label={t("close")}- onClick={cancelReauthentication}- sx={(theme) => ({- backgroundColor: "#FAFAFA",- color: "#000",- p: 1.25,- "&:hover": { backgroundColor: "#F0F0F0" },- ...theme.applyStyles("dark", {- backgroundColor: "rgba(255, 255, 255, 0.12)",- color: "#fff",- "&:hover": {- backgroundColor: "rgba(255, 255, 255, 0.16)",- },- }),- })}- >- <CloseIcon sx={{ fontSize: 20 }} />- </IconButton>- ) : undefined;-- const unlockForm =- appLock.lockType === "pin" ? (- <PinUnlockForm- appLock={appLock}- isReauthentication={isReauthentication}- onLogout={() => setShowLogoutConfirm(true)}- closeAction={closeAction}- />- ) : appLock.lockType === "password" ? (- <PasswordUnlockForm- appLock={appLock}- isReauthentication={isReauthentication}- onLogout={() => setShowLogoutConfirm(true)}- closeAction={closeAction}- />- ) : appLock.lockType === "device" ? (- <DeviceLockUnlockForm- isReauthentication={isReauthentication}- closeAction={closeAction}- />- ) : (- <PinUnlockForm- appLock={appLock}- isReauthentication={isReauthentication}- onLogout={() => setShowLogoutConfirm(true)}- closeAction={closeAction}- />- );-- if (isReauthentication) {- return (- <Modal- open- disableEscapeKeyDown- aria-label={t("authenticate")}- slotProps={{- backdrop: {- sx: {- backgroundColor:- "var(--mui-palette-backdrop-muted)",- },- },- }}- sx={{ zIndex: "calc(var(--mui-zIndex-modal) + 1)" }}- >- <Box- sx={{- position: "fixed",- inset: 0,- display: "flex",- alignItems: "center",- justifyContent: "center",- p: 2,- outline: "none",- }}- style={- { WebkitAppRegion: "no-drag" } as React.CSSProperties- }- >- {showLogoutConfirm ? (- <LogoutConfirmation- onConfirm={logout}- onCancel={() => setShowLogoutConfirm(false)}- />- ) : (- unlockForm- )}- </Box>- </Modal>- );- }-- return (- <Modal- open- disableEscapeKeyDown- aria-label={t("app_lock")}- slotProps={{- backdrop: {- sx: (theme) => ({- backgroundColor: "secondary.main",- ...theme.applyStyles("dark", {- backgroundColor: "#000",- }),- }),- },- }}- sx={{ zIndex: "calc(var(--mui-zIndex-tooltip) + 1)" }}- >- <Box- sx={{- position: "fixed",- inset: 0,- display: "flex",- flexDirection: "column",- alignItems: "center",- justifyContent: "center",- outline: "none",- }}- style={{ WebkitAppRegion: "no-drag" } as React.CSSProperties}- >- {/* Top bar: logo centered, logout button at top-right */}- <Box- sx={{- position: "absolute",- top: 0,- left: 0,- right: 0,- display: "flex",- alignItems: "center",- justifyContent: "center",- p: 3,- }}- >- <EnteLogo />- {!showLogoutConfirm && (- <FocusVisibleButton- variant="text"- color="secondary"- size="small"- onClick={() => setShowLogoutConfirm(true)}- sx={{- textTransform: "none",- position: "absolute",- right: 24,- color: "text.muted",- }}- >- {t("logout")}- </FocusVisibleButton>- )}- </Box>-- {/* Centered form content */}- {showLogoutConfirm ? (- <LogoutConfirmation- onConfirm={logout}- onCancel={() => setShowLogoutConfirm(false)}- />- ) : (- unlockForm- )}- </Box>- </Modal>- );-};--// -- Shared types and helpers ----interface UnlockFormProps {- appLock: ReturnType<typeof useAppLockSnapshot>;- isReauthentication: boolean;- onLogout: () => void;- closeAction?: React.ReactNode;-}--const ENTE_GREEN = "#08C225";-const ENTE_GREEN_HOVER = "#07A820";-const DANGER_RED = "#E53935";-const DANGER_RED_HOVER = "#D32F2F";-const SECONDARY_ACTION_BG_LIGHT = "#F2F2F2";-const SECONDARY_ACTION_BG_HOVER_LIGHT = "#E8E8E8";-const SECONDARY_ACTION_BG_DARK = "rgba(255, 255, 255, 0.08)";-const SECONDARY_ACTION_BG_HOVER_DARK = "rgba(255, 255, 255, 0.12)";-const ILLUSTRATION_ICON_LIGHT = "#111";-const ILLUSTRATION_ICON_DARK = "#fff";-const APP_LOCK_MODAL_WIDTH = 408;-const APP_LOCK_MODAL_CONTENT_WIDTH = APP_LOCK_MODAL_WIDTH - 32;-const appLockModalContentSx = {- width: APP_LOCK_MODAL_CONTENT_WIDTH,- maxWidth: "100%",-} as const;-const LOGOUT_MODAL_WIDTH = 368;-const LOGOUT_MODAL_CONTENT_WIDTH = LOGOUT_MODAL_WIDTH - 32;-const logoutModalContentSx = {- width: LOGOUT_MODAL_CONTENT_WIDTH,- maxWidth: "100%",-} as const;--const titleTextSx = (theme: Theme) => ({- fontWeight: 600,- fontSize: 24,- lineHeight: "28px",- letterSpacing: "-0.48px",- color: "#000",- textAlign: "center" as const,- ...theme.applyStyles("dark", { color: "#fff" }),-});--const subtitleTextSx = (theme: Theme) => ({- fontWeight: 500,- fontSize: 14,- lineHeight: "20px",- color: "#666",- textAlign: "center" as const,- maxWidth: 295,- ...theme.applyStyles("dark", { color: "rgba(255, 255, 255, 0.64)" }),-});--const primaryActionButtonSx = (theme: Theme) => ({- display: "flex",- minHeight: 56,- padding: "18px 16px",- justifyContent: "center",- alignItems: "center",- gap: 1,- borderRadius: "20px",- backgroundColor: ENTE_GREEN,- fontSize: 16,- fontWeight: 500,- lineHeight: "20px",- textTransform: "none" as const,- color: "#fff",- boxShadow: "none",- "&:hover": { backgroundColor: ENTE_GREEN_HOVER, boxShadow: "none" },- "&.Mui-disabled": {- backgroundColor: "rgba(0, 0, 0, 0.04)",- color: "#999",- opacity: 1,- },- ...theme.applyStyles("dark", {- "&.Mui-disabled": {- backgroundColor: "rgba(255, 255, 255, 0.08)",- color: "rgba(255, 255, 255, 0.5)",- opacity: 1,- },- }),-});--const dangerActionButtonSx = (theme: Theme) => ({- ...primaryActionButtonSx(theme),- backgroundColor: DANGER_RED,- "&:hover": { backgroundColor: DANGER_RED_HOVER, boxShadow: "none" },-});--const secondaryActionButtonSx = (theme: Theme) => ({- display: "flex",- minHeight: 60,- padding: "20px 16px",- justifyContent: "center",- alignItems: "center",- gap: 1,- borderRadius: "20px",- backgroundColor: SECONDARY_ACTION_BG_LIGHT,- fontSize: 16,- fontWeight: 600,- lineHeight: "20px",- textTransform: "none" as const,- color: "#333",- boxShadow: "none",- "&:hover": {- backgroundColor: SECONDARY_ACTION_BG_HOVER_LIGHT,- boxShadow: "none",- },- ...theme.applyStyles("dark", {- backgroundColor: SECONDARY_ACTION_BG_DARK,- color: "rgba(255, 255, 255, 0.9)",- "&:hover": { backgroundColor: SECONDARY_ACTION_BG_HOVER_DARK },- }),-});--const illustrationSvgSx = (theme: Theme) => ({- "--app-lock-illustration-fill": SECONDARY_ACTION_BG_LIGHT,- "--app-lock-illustration-icon": ILLUSTRATION_ICON_LIGHT,- ...theme.applyStyles("dark", {- "--app-lock-illustration-fill": SECONDARY_ACTION_BG_DARK,- "--app-lock-illustration-icon": ILLUSTRATION_ICON_DARK,- }),-});--const inputFieldSx = (theme: Theme, options?: { borderRadius?: number }) => ({- borderRadius: options?.borderRadius ?? 12,- "& .MuiInputBase-root": {- // Enforce shape/height at InputBase level so variant-specific styles- // don't collapse these fields into pill/circle forms.- height: 54,- borderRadius: `${String(options?.borderRadius ?? 12)}px !important`,- overflow: "hidden",- },- "& .MuiInput-root": {- height: 54,- backgroundColor: "#FAFAFA",- borderRadius: `${String(options?.borderRadius ?? 12)}px !important`,- "&::before": { borderBottom: "1px solid #E0E0E0" },- "&::after": { borderBottom: `2px solid ${ENTE_GREEN}` },- "&.Mui-error::after": { borderBottomColor: theme.palette.error.main },- "&:hover:not(.Mui-disabled)::before": {- borderBottom: "1px solid #BDBDBD",- },- },- "& .MuiInputBase-input": {- padding: "0 16px",- height: "100%",- boxSizing: "border-box" as const,- fontSize: 16,- color: "#000",- "&::placeholder": { color: "#999", opacity: 1 },- },- ...theme.applyStyles("dark", {- "& .MuiInput-root": {- backgroundColor: "rgba(255, 255, 255, 0.08)",- "&::before": { borderBottom: "1px solid rgba(255, 255, 255, 0.3)" },- "&:hover:not(.Mui-disabled)::before": {- borderBottom: "1px solid rgba(255, 255, 255, 0.5)",- },- },- "& .MuiInputBase-root": {- backgroundColor: "rgba(255, 255, 255, 0.08)",- },- "& .MuiInputBase-input": {- color: "#fff",- "&::placeholder": { color: "rgba(255, 255, 255, 0.5)" },- },- }),-});--const LOCK_ILLUSTRATION_SRC = new URL(- "./icons/lock.svg",- import.meta.url,-).toString();--const LockIllustration: React.FC = () => (- <Box- component="img"- src={LOCK_ILLUSTRATION_SRC}- alt=""- aria-hidden- draggable={false}- sx={{- width: 124,- maxWidth: "100%",- height: "auto",- display: "block",- lineHeight: 0,- userSelect: "none",- }}- />-);--const LogoutIllustration: React.FC = () => {- return (- <Box sx={illustrationSvgSx}>- <svg- width="126"- height="121"- viewBox="0 0 126 121"- fill="none"- xmlns="http://www.w3.org/2000/svg"- aria-hidden- >- <circle- cx="67"- cy="52"- r="34"- fill="var(--app-lock-illustration-fill)"- />- <g- transform="translate(67 52) scale(1.18) translate(-12 -12)"- stroke="var(--app-lock-illustration-icon)"- fill="none"- strokeWidth="1.6"- strokeLinecap="round"- strokeLinejoin="round"- >- <path d="M7.86907 4C4.97674 5.49689 3 8.51664 3 11.9981C3 16.9686 7.02944 20.9981 12 20.9981C16.9706 20.9981 21 16.9686 21 11.9981C21 8.51664 19.0233 5.49689 16.1309 4" />- <path d="M12 3V10" />- </g>- </svg>- </Box>- );-};--const CooldownIllustration: React.FC = () => {- return (- <Box sx={illustrationSvgSx}>- <svg- width="126"- height="121"- viewBox="0 0 126 121"- fill="none"- xmlns="http://www.w3.org/2000/svg"- aria-hidden- >- <circle- cx="67"- cy="52"- r="34"- fill="var(--app-lock-illustration-fill)"- />- <g- transform="translate(67 52) scale(1.18) translate(-12 -12)"- stroke="var(--app-lock-illustration-icon)"- fill="none"- strokeWidth="2"- strokeLinecap="round"- strokeLinejoin="round"- >- <path d="M12 22C6.47714 22 2.00003 17.5228 2.00003 12C2.00003 6.47715 6.47718 2 12 2C16.4777 2 20.2257 4.94289 21.5 9H19" />- <path d="M12 8V12L14 14" />- <path d="M21.9551 13C21.9848 12.6709 22 12.3373 22 12M15 22C15.3416 21.8876 15.6753 21.7564 16 21.6078M20.7906 17C20.9835 16.6284 21.1555 16.2433 21.305 15.8462M18.1925 20.2292C18.5369 19.9441 18.8631 19.6358 19.1688 19.3065" />- </g>- </svg>- </Box>- );-};--const AppLockCard: React.FC<- React.PropsWithChildren<{ closeAction?: React.ReactNode; width?: number }>-> = ({ children, closeAction, width = APP_LOCK_MODAL_WIDTH }) => (- <Paper- elevation={0}- sx={(theme) => ({- width: `${String(width)}px`,- maxWidth: "calc(100% - 32px)",- boxSizing: "border-box",- borderRadius: "28px",- backgroundColor: "#fff",- border: "1px solid #E0E0E0",- boxShadow: "none",- overflow: "visible",- ...theme.applyStyles("dark", {- backgroundColor: "#1B1B1B",- border: "1px solid rgba(255, 255, 255, 0.18)",- }),- })}- >- <Box- sx={{- position: "relative",- width: "100%",- pt: closeAction ? 2 : 6,- px: 2,- pb: 2.5,- }}- >- {closeAction && (- <Box- sx={{- width: "100%",- display: "flex",- justifyContent: "flex-end",- mb: 1,- }}- >- {closeAction}- </Box>- )}- <Box- sx={{- width: "100%",- display: "flex",- justifyContent: "center",- }}- >- {children}- </Box>- </Box>- </Paper>-);--/**- * Format remaining cooldown seconds into a human-readable string.- *- * Input is in milliseconds, so convert it to minutes and seconds for display.- *- * - "Xm Ys" if at least 1 minute- * - "Xs" if under a minute- */-const formatCooldown = (remainingMs: number): string => {- const totalSeconds = Math.ceil(remainingMs / 1000);- const minutes = Math.floor(totalSeconds / 60);- const seconds = totalSeconds % 60;- if (minutes > 0) {- return `${String(minutes)}m ${String(seconds)}s`;- }- return `${String(seconds)}s`;-};--/**- * Move the caret to the end of the current input value.- */-const moveCaretToInputEnd = (input: HTMLInputElement) => {- try {- const caretPosition = input.value.length;- input.setSelectionRange(caretPosition, caretPosition);- } catch {- // Ignore if selection range isn't supported.- }-};--/**- * Hook that returns remaining cooldown time state, updating every second.- */-const useCooldownState = (- cooldownExpiresAt: number,-): { remainingMs: number; text: string | undefined } => {- const [remaining, setRemaining] = useState<number>(- Math.max(0, cooldownExpiresAt - Date.now()),- );-- useEffect(() => {- if (cooldownExpiresAt <= 0) {- setRemaining(0);- return;- }-- const update = () => {- const r = Math.max(0, cooldownExpiresAt - Date.now());- setRemaining(r);- };- update();-- const interval = setInterval(update, 1000);- return () => clearInterval(interval);- }, [cooldownExpiresAt]);-- return {- remainingMs: remaining,- text: remaining > 0 ? formatCooldown(remaining) : undefined,- };-};--const deviceLockErrorText = (result: DeviceLockUnlockResult) => {- if (result.status === "success") return undefined;-- if (result.status === "not-supported") {- switch (result.reason) {- case "touchid-temporarily-unavailable":- case "touchid-api-error":- return t("device_lock_login_failed");- case "unsupported-platform":- case "touchid-not-enrolled":- return t("device_lock_not_supported");- }- }-- switch (result.reason) {- case "native-prompt-failed":- return t("device_lock_login_cancelled");- default:- return t("device_lock_login_failed");- }-};--// -- PIN unlock form ----const PinUnlockForm: React.FC<UnlockFormProps> = ({- appLock,- isReauthentication,- onLogout,- closeAction,-}) => {- const { logout } = useBaseContext();-- const [pin, setPin] = useState(["", "", "", ""]);- const [error, setError] = useState<string>();- const [loading, setLoading] = useState(false);- const inputRefs = useRef<(HTMLInputElement | null)[]>([]);- const isSubmittingRef = useRef(false);- const hasAutoSubmittedRef = useRef(false);- const cooldown = useCooldownState(appLock.cooldownExpiresAt);- const cooldownText = cooldown.text;-- const handlePinChange = useCallback(- (index: number, value: string) => {- // Extract the last digit, ignoring non-digit characters.- const digit = value.replace(/\D/g, "").slice(-1);-- const newPin = [...pin];- newPin[index] = digit;- setPin(newPin);- setError(undefined);-- // Auto-advance to next field.- if (digit && index < 3) {- inputRefs.current[index + 1]?.focus();- }- },- [pin],- );-- const handleKeyDown = useCallback(- (index: number, e: React.KeyboardEvent) => {- if (e.key === "Backspace" && !pin[index] && index > 0) {- inputRefs.current[index - 1]?.focus();- }- },- [pin],- );-- const fullPin = useMemo(() => pin.join(""), [pin]);-- /**- * Focus the PIN field at the given index, then place the caret at the end.- */- const focusPinInput = useCallback((pinIndex: number) => {- const input = inputRefs.current[pinIndex];- if (!input) {- return;- }-- input.focus({ preventScroll: true });- moveCaretToInputEnd(input);- }, []);- const focusFirstEmptyPinInput = useCallback(() => {- const firstEmptyIndex = pin.findIndex((digit) => !digit);- focusPinInput(firstEmptyIndex === -1 ? 0 : firstEmptyIndex);- }, [pin, focusPinInput]);-- const handleSubmit = useCallback(async () => {- if (fullPin.length !== 4 || loading || isSubmittingRef.current) return;-- isSubmittingRef.current = true;- setLoading(true);- try {- const result: UnlockResult = await attemptUnlock(fullPin);-- /**- * The result can be "success", "failed", "cooldown", or "logout".- * Apply the corresponding UI updates for each case.- */- handleUnlockResult(result, setError, setLoading, logout);- } catch (e) {- log.error("Unlock attempt failed", e);- setError(t("generic_error"));- setLoading(false);- } finally {- isSubmittingRef.current = false;- }-- // Clear PIN after each attempt and refocus the first field.- setPin(["", "", "", ""]);- focusPinInput(0);- }, [fullPin, loading, logout, focusPinInput]);-- useEffect(() => {- if (fullPin.length !== 4) {- hasAutoSubmittedRef.current = false;- return;- }-- if (loading || hasAutoSubmittedRef.current) return;-- hasAutoSubmittedRef.current = true;- void handleSubmit();- }, [fullPin, loading, handleSubmit]);-- useEffect(() => {- if (!error || loading || cooldownText) return;-- const rafID = requestAnimationFrame(() => {- focusPinInput(0);- });- return () => cancelAnimationFrame(rafID);- }, [error, loading, cooldownText, focusPinInput]);-- if (cooldownText) {- return (- <AppLockCard closeAction={closeAction} width={LOGOUT_MODAL_WIDTH}>- <CooldownScreen- remainingMs={cooldown.remainingMs}- cooldownText={cooldownText}- attemptCount={appLock.invalidAttemptCount}- onLogout={onLogout}- />- </AppLockCard>- );- }-- return (- <Stack spacing={0} useFlexGap alignItems="center">- <AppLockCard closeAction={closeAction}>- <Stack- spacing={0}- useFlexGap- alignItems="center"- sx={appLockModalContentSx}- >- <Box- sx={{- mt: -0.5,- mb: 1.5,- display: "flex",- justifyContent: "center",- width: "100%",- }}- >- <LockIllustration />- </Box>-- <Box- sx={{- display: "flex",- flexDirection: "column",- alignItems: "center",- gap: "9px",- textAlign: "center",- mb: 4,- }}- >- <Typography- sx={(theme) => ({- ...titleTextSx(theme),- ...(isReauthentication ? {} : { mb: 0.5 }),- })}- >- {isReauthentication- ? t("authenticate")- : t("app_locked")}- </Typography>- <Typography sx={subtitleTextSx}>- {t("app_lock_enter_pin_to_unlock")}- </Typography>- </Box>-- <Stack- direction="row"- spacing={1.25}- justifyContent="center"- onClick={focusFirstEmptyPinInput}- sx={{ mb: 0, width: "100%" }}- >- {pin.map((digit, i) => (- <TextField- key={i}- variant="standard"- hiddenLabel- autoFocus={i === 0}- error={!!error}- inputRef={(el: HTMLInputElement | null) => {- inputRefs.current[i] = el;- }}- value={digit}- onChange={(e) =>- handlePinChange(i, e.target.value)- }- onKeyDown={(e) => handleKeyDown(i, e)}- disabled={loading}- slotProps={{- htmlInput: {- maxLength: 1,- inputMode: "numeric",- pattern: "[0-9]",- autoComplete: "off",- style: {- textAlign: "center",- WebkitTextSecurity: "disc",- },- "aria-label": t(- "app_lock_pin_digit_label",- { index: i + 1 },- ),- },- }}- sx={(theme) => ({- ...inputFieldSx(theme, {- borderRadius: 12,- }),- flex: 1,- minWidth: 0,- "& .MuiInputBase-input": {- padding: 0,- textAlign: "center",- height: "100%",- fontSize: 20,- fontWeight: 600,- },- })}- />- ))}- </Stack>- </Stack>- </AppLockCard>-- <ErrorMessage- error={error}- attemptCount={appLock.invalidAttemptCount}- />- </Stack>- );-};--// -- Password unlock form ----const PasswordUnlockForm: React.FC<UnlockFormProps> = ({- appLock,- isReauthentication,- onLogout,- closeAction,-}) => {- const { logout } = useBaseContext();-- const [password, setPassword] = useState("");- const [showPassword, setShowPassword] = useState(false);- const [error, setError] = useState<string>();- const [loading, setLoading] = useState(false);- const inputRef = useRef<HTMLInputElement | null>(null);- const cooldown = useCooldownState(appLock.cooldownExpiresAt);- const cooldownText = cooldown.text;-- const handleSubmit = useCallback(- async (e?: React.FormEvent) => {- e?.preventDefault();- if (!password || loading) return;-- setLoading(true);- try {- const result: UnlockResult = await attemptUnlock(password);- handleUnlockResult(result, setError, setLoading, logout);- } catch (e) {- log.error("Unlock attempt failed", e);- setError(t("generic_error"));- setLoading(false);- }-- setPassword("");- inputRef.current?.focus();- },- [password, loading, logout],- );-- useEffect(() => {- if (!error || loading || cooldownText) return;-- const rafID = requestAnimationFrame(() => {- inputRef.current?.focus();- });- return () => cancelAnimationFrame(rafID);- }, [error, loading, cooldownText]);-- if (cooldownText) {- return (- <AppLockCard closeAction={closeAction} width={LOGOUT_MODAL_WIDTH}>- <CooldownScreen- remainingMs={cooldown.remainingMs}- cooldownText={cooldownText}- attemptCount={appLock.invalidAttemptCount}- onLogout={onLogout}- />- </AppLockCard>- );- }-- return (- <Stack spacing={0} useFlexGap alignItems="center">- <AppLockCard closeAction={closeAction}>- <Stack- component="form"- onSubmit={(e: React.FormEvent) => void handleSubmit(e)}- spacing={0}- useFlexGap- alignItems="center"- sx={appLockModalContentSx}- >- <Box- sx={{- mt: -0.5,- mb: 1.5,- display: "flex",- justifyContent: "center",- width: "100%",- }}- >- <LockIllustration />- </Box>-- <Box- sx={{- display: "flex",- flexDirection: "column",- alignItems: "center",- gap: "9px",- textAlign: "center",- mb: 2,- }}- >- <Typography- sx={(theme) => ({- ...titleTextSx(theme),- ...(isReauthentication ? {} : { mb: 0.5 }),- })}- >- {isReauthentication- ? t("password")- : t("app_locked")}- </Typography>- <Typography sx={subtitleTextSx}>- {t("app_lock_enter_password")}- </Typography>- </Box>-- <TextField- inputRef={inputRef}- fullWidth- hiddenLabel- variant="standard"- autoFocus- error={!!error}- type={showPassword ? "text" : "password"}- value={password}- onChange={(e) => {- setPassword(e.target.value);- setError(undefined);- }}- disabled={loading}- placeholder={- isReauthentication- ? t("password")- : t("app_lock_password")- }- autoComplete="off"- slotProps={{- input: {- endAdornment: (- <ShowHidePasswordInputAdornment- showPassword={showPassword}- onToggle={() =>- setShowPassword((s) => !s)- }- />- ),- },- }}- sx={(theme) => ({- ...inputFieldSx(theme),- mt: 1,- "& .MuiInputAdornment-positionEnd": { pr: 0.5 },- })}- />-- <FocusVisibleButton- type="submit"- fullWidth- color="accent"- disabled={!password || loading}- sx={(theme) => ({- ...primaryActionButtonSx(theme),- mt: 2,- })}- >- {isReauthentication ? t("authenticate") : t("unlock")}- </FocusVisibleButton>- </Stack>- </AppLockCard>-- <ErrorMessage- error={error}- attemptCount={appLock.invalidAttemptCount}- />- </Stack>- );-};--// -- Device lock unlock form ----const DeviceLockUnlockForm: React.FC<{- isReauthentication: boolean;- closeAction?: React.ReactNode;-}> = ({ isReauthentication, closeAction }) => {- const [error, setError] = useState<string>();- const [loading, setLoading] = useState(true);- const [showManualUnlockButton, setShowManualUnlockButton] = useState(false);- const isUnlockInProgress = useRef(false);- const hasAutoTriggeredUnlock = useRef(false);-- const handleDeviceLockUnlock = useCallback(- async (source: "auto" | "manual") => {- if (isUnlockInProgress.current) return;- isUnlockInProgress.current = true;- setLoading(true);- setError(undefined);-- try {- const result: DeviceLockUnlockResult =- await attemptDeviceLockUnlock();- const nextError = deviceLockErrorText(result);- setError(nextError);- if (source === "auto" && nextError) {- setShowManualUnlockButton(true);- }- } catch (e) {- log.error("Device lock unlock attempt failed", e);- setError(t("generic_error"));- if (source === "auto") {- setShowManualUnlockButton(true);- }- } finally {- setLoading(false);- isUnlockInProgress.current = false;- }- },- [],- );-- useEffect(() => {- const maybeAutoTriggerUnlock = () => {- if (hasAutoTriggeredUnlock.current) return;- if (- typeof document == "undefined" ||- document.visibilityState !== "visible" ||- !document.hasFocus()- ) {- return;- }-- hasAutoTriggeredUnlock.current = true;- void handleDeviceLockUnlock("auto");- };-- maybeAutoTriggerUnlock();- if (hasAutoTriggeredUnlock.current || typeof window == "undefined") {- return;- }-- window.addEventListener("focus", maybeAutoTriggerUnlock);- document.addEventListener("visibilitychange", maybeAutoTriggerUnlock);- return () => {- window.removeEventListener("focus", maybeAutoTriggerUnlock);- document.removeEventListener(- "visibilitychange",- maybeAutoTriggerUnlock,- );- };- }, [handleDeviceLockUnlock]);-- return (- <Stack spacing={0} useFlexGap alignItems="center">- <AppLockCard closeAction={closeAction}>- <Stack- spacing={0}- useFlexGap- alignItems="center"- sx={appLockModalContentSx}- >- <Box- sx={{- mt: -0.5,- mb: 1.5,- display: "flex",- justifyContent: "center",- width: "100%",- }}- >- <LockIllustration />- </Box>-- <Box- sx={{- display: "flex",- flexDirection: "column",- alignItems: "center",- gap: "9px",- textAlign: "center",- mb: 2,- }}- >- <Typography- sx={(theme) => ({- ...titleTextSx(theme),- ...(isReauthentication ? {} : { mb: 0.5 }),- })}- >- {isReauthentication- ? t("authenticate")- : t("app_locked")}- </Typography>- <Typography sx={subtitleTextSx}>- {t("device_lock_login_instructions")}- </Typography>- </Box>-- <FocusVisibleButton- fullWidth- color="accent"- disabled={loading || !showManualUnlockButton}- onClick={() => {- void handleDeviceLockUnlock("manual");- }}- sx={(theme) => ({- ...primaryActionButtonSx(theme),- backgroundColor: ENTE_GREEN,- "&:hover": { backgroundColor: ENTE_GREEN_HOVER },- fontWeight: 600,- mt: 2,- })}- >- {loading ? (- <CircularProgress size={18} color="inherit" />- ) : isReauthentication ? (- t("authenticate")- ) : (- t("device_lock_login")- )}- </FocusVisibleButton>- </Stack>- </AppLockCard>-- <ErrorMessage error={error} attemptCount={0} />- </Stack>- );-};--// -- Shared sub-components ----interface ErrorMessageProps {- error: string | undefined;- attemptCount: number;-}--const ErrorMessage: React.FC<ErrorMessageProps> = ({ error, attemptCount }) => {- if (error) {- return (- <Typography- sx={(theme) => ({- ...subtitleTextSx(theme),- color: "#E53935",- mt: 3,- ...theme.applyStyles("dark", { color: "#FF6B6B" }),- })}- >- {error}- {attemptCount > 0 && ` (${String(attemptCount)}/10)`}- </Typography>- );- }- return null;-};--interface LogoutConfirmationProps {- onConfirm: () => void;- onCancel: () => void;-}--const LogoutConfirmation: React.FC<LogoutConfirmationProps> = ({- onConfirm,- onCancel,-}) => (- <AppLockCard width={LOGOUT_MODAL_WIDTH}>- <Stack- spacing={0}- useFlexGap- alignItems="center"- sx={logoutModalContentSx}- >- <Box- sx={{- mt: 0.5,- mb: 1,- display: "flex",- justifyContent: "center",- width: "100%",- }}- >- <LogoutIllustration />- </Box>-- <Box- sx={{- display: "flex",- flexDirection: "column",- alignItems: "center",- gap: "9px",- textAlign: "center",- mb: 4,- }}- >- <Typography sx={titleTextSx}>{t("logout")}</Typography>- <Typography sx={subtitleTextSx}>- {t("logout_message")}- </Typography>- </Box>-- <Stack spacing={1.5} sx={{ width: "100%" }}>- <FocusVisibleButton- fullWidth- onClick={onCancel}- sx={secondaryActionButtonSx}- >- {t("cancel")}- </FocusVisibleButton>- <FocusVisibleButton- fullWidth- onClick={onConfirm}- sx={dangerActionButtonSx}- >- {t("logout")}- </FocusVisibleButton>- </Stack>- </Stack>- </AppLockCard>-);--interface CooldownScreenProps {- remainingMs: number;- cooldownText: string;- attemptCount: number;- onLogout: () => void;-}--const CooldownScreen: React.FC<CooldownScreenProps> = ({- remainingMs,- cooldownText,- attemptCount,- onLogout,-}) => {- void remainingMs;- void attemptCount;- const retryDescriptionText = `${t("app_lock_please_try_again_in")}\u00A0${cooldownText}`;-- return (- <Stack- spacing={0}- useFlexGap- alignItems="center"- justifyContent="center"- sx={logoutModalContentSx}- >- <Box- sx={{- mt: 0.5,- mb: 1,- display: "flex",- justifyContent: "center",- width: "100%",- }}- >- <CooldownIllustration />- </Box>-- <Box- sx={{- display: "flex",- flexDirection: "column",- alignItems: "center",- gap: 0,- textAlign: "center",- mb: 2.5,- }}- >- <Typography- sx={(theme) => ({ ...titleTextSx(theme), mb: 0.5 })}- >- {t("app_locked")}- </Typography>- <Typography- sx={(theme) => ({ ...subtitleTextSx(theme), mt: 0.75 })}- >- {retryDescriptionText}- </Typography>- </Box>-- <FocusVisibleButton- fullWidth- color="secondary"- onClick={onLogout}- sx={(theme) => ({ ...dangerActionButtonSx(theme), mt: 1.5 })}- >- {t("logout")}- </FocusVisibleButton>- </Stack>- );-};--// -- Helpers ----/**- * Handle the result of an unlock attempt, updating UI state accordingly.- */-const handleUnlockResult = (- result: UnlockResult,- setError: (error: string | undefined) => void,- setLoading: (loading: boolean) => void,- logout: () => void,-) => {- switch (result) {- case "success":- case "cooldown":- setError(undefined);- setLoading(false);- break;- case "logout":- logout();- setLoading(false);- break;- case "failed":- setError(t("app_lock_incorrect"));- setLoading(false);- break;- }-};diff --git a/web/packages/new/photos/components/app-lock/AppLockCard.tsx b/web/packages/new/photos/components/app-lock/AppLockCard.tsxnew file mode 100644index 0000000000..d4fcef96be--- /dev/null+++ b/web/packages/new/photos/components/app-lock/AppLockCard.tsx@@ -0,0 +1,65 @@+import { Box, Paper } from "@mui/material";+import type { PropsWithChildren, ReactNode } from "react";++const APP_LOCK_MODAL_WIDTH = 408;++interface AppLockCardProps {+ closeAction?: ReactNode;+ width?: number;+}++export const AppLockCard = ({+ children,+ closeAction,+ width = APP_LOCK_MODAL_WIDTH,+}: PropsWithChildren<AppLockCardProps>) => (+ <Paper+ elevation={0}+ sx={(theme) => ({+ width: `${String(width)}px`,+ maxWidth: "calc(100% - 32px)",+ boxSizing: "border-box",+ borderRadius: "28px",+ backgroundColor: "#fff",+ border: "1px solid #E0E0E0",+ boxShadow: "none",+ overflow: "visible",+ ...theme.applyStyles("dark", {+ backgroundColor: "#1B1B1B",+ border: "1px solid rgba(255, 255, 255, 0.18)",+ }),+ })}+ >+ <Box+ sx={{+ position: "relative",+ width: "100%",+ pt: closeAction ? 2 : 6,+ px: 2,+ pb: 2.5,+ }}+ >+ {closeAction && (+ <Box+ sx={{+ width: "100%",+ display: "flex",+ justifyContent: "flex-end",+ mb: 1,+ }}+ >+ {closeAction}+ </Box>+ )}+ <Box+ sx={{+ width: "100%",+ display: "flex",+ justifyContent: "center",+ }}+ >+ {children}+ </Box>+ </Box>+ </Paper>+);diff --git a/web/packages/new/photos/components/app-lock/AppLockFeedback.tsx b/web/packages/new/photos/components/app-lock/AppLockFeedback.tsxnew file mode 100644index 0000000000..77e15e506c--- /dev/null+++ b/web/packages/new/photos/components/app-lock/AppLockFeedback.tsx@@ -0,0 +1,235 @@+import { Box, Stack, Typography } from "@mui/material";+import { FocusVisibleButton } from "ente-base/components/mui/FocusVisibleButton";+import { t } from "i18next";+import { AppLockCard } from "./AppLockCard";+import {+ CooldownIllustration,+ LogoutIllustration,+} from "./AppLockIllustrations";+import {+ LOGOUT_MODAL_WIDTH,+ subtitleTextSx,+ titleTextSx,+} from "./styles";++const DANGER_RED = "#E53935";+const DANGER_RED_HOVER = "#D32F2F";+const SECONDARY_ACTION_BG_LIGHT = "#F2F2F2";+const SECONDARY_ACTION_BG_HOVER_LIGHT = "#E8E8E8";+const SECONDARY_ACTION_BG_DARK = "rgba(255, 255, 255, 0.08)";+const SECONDARY_ACTION_BG_HOVER_DARK = "rgba(255, 255, 255, 0.12)";++const logoutModalContentSx = {+ width: LOGOUT_MODAL_WIDTH - 32,+ maxWidth: "100%",+} as const;++const dangerActionButtonSx = (theme: Parameters<typeof titleTextSx>[0]) => ({+ display: "flex",+ minHeight: 56,+ padding: "18px 16px",+ justifyContent: "center",+ alignItems: "center",+ gap: 1,+ borderRadius: "20px",+ backgroundColor: DANGER_RED,+ fontSize: 16,+ fontWeight: 500,+ lineHeight: "20px",+ textTransform: "none" as const,+ color: "#fff",+ boxShadow: "none",+ "&:hover": { backgroundColor: DANGER_RED_HOVER, boxShadow: "none" },+ "&.Mui-disabled": {+ backgroundColor: "rgba(0, 0, 0, 0.04)",+ color: "#999",+ opacity: 1,+ },+ ...theme.applyStyles("dark", {+ "&.Mui-disabled": {+ backgroundColor: "rgba(255, 255, 255, 0.08)",+ color: "rgba(255, 255, 255, 0.5)",+ opacity: 1,+ },+ }),+});++const secondaryActionButtonSx = (theme: Parameters<typeof titleTextSx>[0]) => ({+ display: "flex",+ minHeight: 60,+ padding: "20px 16px",+ justifyContent: "center",+ alignItems: "center",+ gap: 1,+ borderRadius: "20px",+ backgroundColor: SECONDARY_ACTION_BG_LIGHT,+ fontSize: 16,+ fontWeight: 600,+ lineHeight: "20px",+ textTransform: "none" as const,+ color: "#333",+ boxShadow: "none",+ "&:hover": {+ backgroundColor: SECONDARY_ACTION_BG_HOVER_LIGHT,+ boxShadow: "none",+ },+ ...theme.applyStyles("dark", {+ backgroundColor: SECONDARY_ACTION_BG_DARK,+ color: "rgba(255, 255, 255, 0.9)",+ "&:hover": { backgroundColor: SECONDARY_ACTION_BG_HOVER_DARK },+ }),+});++interface ErrorMessageProps {+ error: string | undefined;+ attemptCount: number;+}++export const ErrorMessage = ({ error, attemptCount }: ErrorMessageProps) => {+ if (!error) return null;++ return (+ <Typography+ sx={(theme) => ({+ ...subtitleTextSx(theme),+ color: "#E53935",+ mt: 3,+ ...theme.applyStyles("dark", { color: "#FF6B6B" }),+ })}+ >+ {error}+ {attemptCount > 0 && ` (${String(attemptCount)}/10)`}+ </Typography>+ );+};++interface AppLockLogoutConfirmationProps {+ onConfirm: () => void;+ onCancel: () => void;+}++export const AppLockLogoutConfirmation = ({+ onConfirm,+ onCancel,+}: AppLockLogoutConfirmationProps) => (+ <AppLockCard width={LOGOUT_MODAL_WIDTH}>+ <Stack+ spacing={0}+ useFlexGap+ alignItems="center"+ sx={logoutModalContentSx}+ >+ <Box+ sx={{+ mt: 0.5,+ mb: 1,+ display: "flex",+ justifyContent: "center",+ width: "100%",+ }}+ >+ <LogoutIllustration />+ </Box>++ <Box+ sx={{+ display: "flex",+ flexDirection: "column",+ alignItems: "center",+ gap: "9px",+ textAlign: "center",+ mb: 4,+ }}+ >+ <Typography sx={titleTextSx}>{t("logout")}</Typography>+ <Typography sx={subtitleTextSx}>{t("logout_message")}</Typography>+ </Box>++ <Stack spacing={1.5} sx={{ width: "100%" }}>+ <FocusVisibleButton+ fullWidth+ onClick={onCancel}+ sx={secondaryActionButtonSx}+ >+ {t("cancel")}+ </FocusVisibleButton>+ <FocusVisibleButton+ fullWidth+ onClick={onConfirm}+ sx={dangerActionButtonSx}+ >+ {t("logout")}+ </FocusVisibleButton>+ </Stack>+ </Stack>+ </AppLockCard>+);++interface CooldownScreenProps {+ remainingMs: number;+ cooldownText: string;+ attemptCount: number;+ onLogout: () => void;+}++export const CooldownScreen = ({+ remainingMs,+ cooldownText,+ attemptCount,+ onLogout,+}: CooldownScreenProps) => {+ void remainingMs;+ void attemptCount;+ const retryDescriptionText = `${t("app_lock_please_try_again_in")}\u00A0${cooldownText}`;++ return (+ <Stack+ spacing={0}+ useFlexGap+ alignItems="center"+ justifyContent="center"+ sx={logoutModalContentSx}+ >+ <Box+ sx={{+ mt: 0.5,+ mb: 1,+ display: "flex",+ justifyContent: "center",+ width: "100%",+ }}+ >+ <CooldownIllustration />+ </Box>++ <Box+ sx={{+ display: "flex",+ flexDirection: "column",+ alignItems: "center",+ gap: 0,+ textAlign: "center",+ mb: 2.5,+ }}+ >+ <Typography sx={(theme) => ({ ...titleTextSx(theme), mb: 0.5 })}>+ {t("app_locked")}+ </Typography>+ <Typography+ sx={(theme) => ({ ...subtitleTextSx(theme), mt: 0.75 })}+ >+ {retryDescriptionText}+ </Typography>+ </Box>++ <FocusVisibleButton+ fullWidth+ color="secondary"+ onClick={onLogout}+ sx={(theme) => ({ ...dangerActionButtonSx(theme), mt: 1.5 })}+ >+ {t("logout")}+ </FocusVisibleButton>+ </Stack>+ );+};diff --git a/web/packages/new/photos/components/app-lock/AppLockIllustrations.tsx b/web/packages/new/photos/components/app-lock/AppLockIllustrations.tsxnew file mode 100644index 0000000000..ea0fb0c971--- /dev/null+++ b/web/packages/new/photos/components/app-lock/AppLockIllustrations.tsx@@ -0,0 +1,102 @@+import { Box } from "@mui/material";+import type { Theme } from "@mui/material/styles";++const SECONDARY_ACTION_BG_LIGHT = "#F2F2F2";+const SECONDARY_ACTION_BG_DARK = "rgba(255, 255, 255, 0.08)";+const ILLUSTRATION_ICON_LIGHT = "#111";+const ILLUSTRATION_ICON_DARK = "#fff";++const illustrationSvgSx = (theme: Theme) => ({+ "--app-lock-illustration-fill": SECONDARY_ACTION_BG_LIGHT,+ "--app-lock-illustration-icon": ILLUSTRATION_ICON_LIGHT,+ ...theme.applyStyles("dark", {+ "--app-lock-illustration-fill": SECONDARY_ACTION_BG_DARK,+ "--app-lock-illustration-icon": ILLUSTRATION_ICON_DARK,+ }),+});++const LOCK_ILLUSTRATION_SRC = new URL(+ "../icons/lock.svg",+ import.meta.url,+).toString();++export const LockIllustration = () => (+ <Box+ component="img"+ src={LOCK_ILLUSTRATION_SRC}+ alt=""+ aria-hidden+ draggable={false}+ sx={{+ width: 124,+ maxWidth: "100%",+ height: "auto",+ display: "block",+ lineHeight: 0,+ userSelect: "none",+ }}+ />+);++export const LogoutIllustration = () => (+ <Box sx={illustrationSvgSx}>+ <svg+ width="126"+ height="121"+ viewBox="0 0 126 121"+ fill="none"+ xmlns="http://www.w3.org/2000/svg"+ aria-hidden+ >+ <circle+ cx="67"+ cy="52"+ r="34"+ fill="var(--app-lock-illustration-fill)"+ />+ <g+ transform="translate(67 52) scale(1.18) translate(-12 -12)"+ stroke="var(--app-lock-illustration-icon)"+ fill="none"+ strokeWidth="1.6"+ strokeLinecap="round"+ strokeLinejoin="round"+ >+ <path d="M7.86907 4C4.97674 5.49689 3 8.51664 3 11.9981C3 16.9686 7.02944 20.9981 12 20.9981C16.9706 20.9981 21 16.9686 21 11.9981C21 8.51664 19.0233 5.49689 16.1309 4" />+ <path d="M12 3V10" />+ </g>+ </svg>+ </Box>+);++export const CooldownIllustration = () => (+ <Box sx={illustrationSvgSx}>+ <svg+ width="126"+ height="121"+ viewBox="0 0 126 121"+ fill="none"+ xmlns="http://www.w3.org/2000/svg"+ aria-hidden+ >+ <circle+ cx="67"+ cy="52"+ r="34"+ fill="var(--app-lock-illustration-fill)"+ />+ <g+ transform="translate(67 52) scale(1.18) translate(-12 -12)"+ stroke="var(--app-lock-illustration-icon)"+ fill="none"+ strokeWidth="2"+ strokeLinecap="round"+ strokeLinejoin="round"+ >+ <path d="M12 22C6.47714 22 2.00003 17.5228 2.00003 12C2.00003 6.47715 6.47718 2 12 2C16.4777 2 20.2257 4.94289 21.5 9H19" />+ <path d="M12 8V12L14 14" />+ <path d="M21.9551 13C21.9848 12.6709 22 12.3373 22 12M15 22C15.3416 21.8876 15.6753 21.7564 16 21.6078M20.7906 17C20.9835 16.6284 21.1555 16.2433 21.305 15.8462M18.1925 20.2292C18.5369 19.9441 18.8631 19.6358 19.1688 19.3065" />+ </g>+ </svg>+ </Box>+);diff --git a/web/packages/new/photos/components/app-lock/AppLockPrompt.tsx b/web/packages/new/photos/components/app-lock/AppLockPrompt.tsxnew file mode 100644index 0000000000..3caa92d4bb--- /dev/null+++ b/web/packages/new/photos/components/app-lock/AppLockPrompt.tsx@@ -0,0 +1,88 @@+import CloseIcon from "@mui/icons-material/Close";+import { IconButton } from "@mui/material";+import { useBaseContext } from "ente-base/context";+import { t } from "i18next";+import type { ReactNode } from "react";+import { useCallback, useEffect, useState } from "react";+import { cancelReauthentication } from "../../services/app-lock";+import { AppLockLogoutConfirmation } from "./AppLockFeedback";+import { AppLockUnlockForm } from "./AppLockUnlockForm";+import { useAppLockSnapshot } from "../utils/use-snapshot";++type AppLockSnapshot = ReturnType<typeof useAppLockSnapshot>;++interface AppLockPromptProps {+ lockScreenMode: AppLockSnapshot["lockScreenMode"];+ renderHeader?: (props: {+ showLogoutConfirm: boolean;+ showLogout: () => void;+ }) => ReactNode;+}++const AppLockCloseAction = () => (+ <IconButton+ aria-label={t("close")}+ onClick={cancelReauthentication}+ sx={(theme) => ({+ backgroundColor: "#FAFAFA",+ color: "#000",+ p: 1.25,+ "&:hover": { backgroundColor: "#F0F0F0" },+ ...theme.applyStyles("dark", {+ backgroundColor: "rgba(255, 255, 255, 0.12)",+ color: "#fff",+ "&:hover": {+ backgroundColor: "rgba(255, 255, 255, 0.16)",+ },+ }),+ })}+ >+ <CloseIcon sx={{ fontSize: 20 }} />+ </IconButton>+);++export const AppLockPrompt = ({+ lockScreenMode,+ renderHeader,+}: AppLockPromptProps) => {+ const appLock = useAppLockSnapshot();+ const { logout } = useBaseContext();+ const [showLogoutConfirm, setShowLogoutConfirm] = useState(false);++ const isVisible =+ appLock.isLocked && appLock.lockScreenMode === lockScreenMode;+ const isReauthentication = lockScreenMode === "reauthenticate";++ useEffect(() => {+ if (!isVisible) {+ setShowLogoutConfirm(false);+ }+ }, [isVisible]);++ const showLogout = useCallback(() => setShowLogoutConfirm(true), []);+ const hideLogout = useCallback(() => setShowLogoutConfirm(false), []);++ if (!isVisible) return null;++ const closeAction =+ isReauthentication && !showLogoutConfirm ? <AppLockCloseAction /> : undefined;++ return (+ <>+ {renderHeader?.({ showLogoutConfirm, showLogout })}+ {showLogoutConfirm ? (+ <AppLockLogoutConfirmation+ onConfirm={logout}+ onCancel={hideLogout}+ />+ ) : (+ <AppLockUnlockForm+ appLock={appLock}+ isReauthentication={isReauthentication}+ onLogout={showLogout}+ closeAction={closeAction}+ />+ )}+ </>+ );+};diff --git a/web/packages/new/photos/components/app-lock/AppLockReauthenticationDialog.tsx b/web/packages/new/photos/components/app-lock/AppLockReauthenticationDialog.tsxnew file mode 100644index 0000000000..4437d4a87d--- /dev/null+++ b/web/packages/new/photos/components/app-lock/AppLockReauthenticationDialog.tsx@@ -0,0 +1,48 @@+/**+ * @file Reauthentication dialog for app-lock protected actions.+ */++import { Box, Modal } from "@mui/material";+import { t } from "i18next";+import type { CSSProperties } from "react";+import { AppLockPrompt } from "./AppLockPrompt";+import { useAppLockSnapshot } from "../utils/use-snapshot";++export const AppLockReauthenticationDialog = () => {+ const appLock = useAppLockSnapshot();+ const isVisible =+ appLock.isLocked && appLock.lockScreenMode === "reauthenticate";++ if (!isVisible) return null;++ return (+ <Modal+ open+ disableEscapeKeyDown+ aria-label={t("authenticate")}+ slotProps={{+ backdrop: {+ sx: {+ backgroundColor: "var(--mui-palette-backdrop-muted)",+ },+ },+ }}+ sx={{ zIndex: "calc(var(--mui-zIndex-modal) + 1)" }}+ >+ <Box+ sx={{+ position: "fixed",+ inset: 0,+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ p: 2,+ outline: "none",+ }}+ style={{ WebkitAppRegion: "no-drag" } as CSSProperties}+ >+ <AppLockPrompt lockScreenMode="reauthenticate" />+ </Box>+ </Modal>+ );+};diff --git a/web/packages/new/photos/components/app-lock/AppLockUnlockForm.tsx b/web/packages/new/photos/components/app-lock/AppLockUnlockForm.tsxnew file mode 100644index 0000000000..bc00718ecc--- /dev/null+++ b/web/packages/new/photos/components/app-lock/AppLockUnlockForm.tsx@@ -0,0 +1,748 @@+import { Box, CircularProgress, Stack, TextField, Typography } from "@mui/material";+import { FocusVisibleButton } from "ente-base/components/mui/FocusVisibleButton";+import { ShowHidePasswordInputAdornment } from "ente-base/components/mui/PasswordInputAdornment";+import { useBaseContext } from "ente-base/context";+import log from "ente-base/log";+import { t } from "i18next";+import type { ReactNode } from "react";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import {+ attemptDeviceLockUnlock,+ attemptUnlock,+ type DeviceLockUnlockResult,+ type UnlockResult,+} from "../../services/app-lock";+import { AppLockCard } from "./AppLockCard";+import { CooldownScreen, ErrorMessage } from "./AppLockFeedback";+import {+ LOGOUT_MODAL_WIDTH,+ subtitleTextSx,+ titleTextSx,+} from "./styles";+import { LockIllustration } from "./AppLockIllustrations";+import { useAppLockSnapshot } from "../utils/use-snapshot";++type AppLockSnapshot = ReturnType<typeof useAppLockSnapshot>;++interface AppLockUnlockFormProps {+ appLock: AppLockSnapshot;+ isReauthentication: boolean;+ onLogout: () => void;+ closeAction?: ReactNode;+}++interface UnlockContentProps extends AppLockUnlockFormProps {+ logout: () => void;+}++interface AppLockFormHeaderProps {+ title: string;+ subtitle: string;+ isReauthentication: boolean;+ marginBottom: number;+}++const ENTE_GREEN = "#08C225";+const ENTE_GREEN_HOVER = "#07A820";+const appLockModalContentSx = {+ width: 408 - 32,+ maxWidth: "100%",+} as const;++const useCooldownState = (+ cooldownExpiresAt: number,+): { remainingMs: number; text: string | undefined } => {+ const [remaining, setRemaining] = useState<number>(+ Math.max(0, cooldownExpiresAt - Date.now()),+ );++ useEffect(() => {+ if (cooldownExpiresAt <= 0) {+ setRemaining(0);+ return;+ }++ const update = () => {+ const nextRemaining = Math.max(0, cooldownExpiresAt - Date.now());+ setRemaining(nextRemaining);+ };+ update();++ const interval = setInterval(update, 1000);+ return () => clearInterval(interval);+ }, [cooldownExpiresAt]);++ if (remaining <= 0) {+ return { remainingMs: remaining, text: undefined };+ }++ const totalSeconds = Math.ceil(remaining / 1000);+ const minutes = Math.floor(totalSeconds / 60);+ const seconds = totalSeconds % 60;++ return {+ remainingMs: remaining,+ text:+ minutes > 0+ ? `${String(minutes)}m ${String(seconds)}s`+ : `${String(seconds)}s`,+ };+};++const moveCaretToInputEnd = (input: HTMLInputElement) => {+ try {+ const caretPosition = input.value.length;+ input.setSelectionRange(caretPosition, caretPosition);+ } catch {+ // Ignore if selection range isn't supported.+ }+};++const primaryActionButtonSx = (theme: Parameters<typeof titleTextSx>[0]) => ({+ display: "flex",+ minHeight: 56,+ padding: "18px 16px",+ justifyContent: "center",+ alignItems: "center",+ gap: 1,+ borderRadius: "20px",+ backgroundColor: ENTE_GREEN,+ fontSize: 16,+ fontWeight: 500,+ lineHeight: "20px",+ textTransform: "none" as const,+ color: "#fff",+ boxShadow: "none",+ "&:hover": { backgroundColor: ENTE_GREEN_HOVER, boxShadow: "none" },+ "&.Mui-disabled": {+ backgroundColor: "rgba(0, 0, 0, 0.04)",+ color: "#999",+ opacity: 1,+ },+ ...theme.applyStyles("dark", {+ "&.Mui-disabled": {+ backgroundColor: "rgba(255, 255, 255, 0.08)",+ color: "rgba(255, 255, 255, 0.5)",+ opacity: 1,+ },+ }),+});++const inputFieldSx = (+ theme: Parameters<typeof titleTextSx>[0],+ options?: { borderRadius?: number },+) => ({+ borderRadius: options?.borderRadius ?? 12,+ "& .MuiInputBase-root": {+ height: 54,+ borderRadius: `${String(options?.borderRadius ?? 12)}px !important`,+ overflow: "hidden",+ },+ "& .MuiInput-root": {+ height: 54,+ backgroundColor: "#FAFAFA",+ borderRadius: `${String(options?.borderRadius ?? 12)}px !important`,+ "&::before": { borderBottom: "1px solid #E0E0E0" },+ "&::after": { borderBottom: `2px solid ${ENTE_GREEN}` },+ "&.Mui-error::after": { borderBottomColor: theme.palette.error.main },+ "&:hover:not(.Mui-disabled)::before": {+ borderBottom: "1px solid #BDBDBD",+ },+ },+ "& .MuiInputBase-input": {+ padding: "0 16px",+ height: "100%",+ boxSizing: "border-box" as const,+ fontSize: 16,+ color: "#000",+ "&::placeholder": { color: "#999", opacity: 1 },+ },+ ...theme.applyStyles("dark", {+ "& .MuiInput-root": {+ backgroundColor: "rgba(255, 255, 255, 0.08)",+ "&::before": { borderBottom: "1px solid rgba(255, 255, 255, 0.3)" },+ "&:hover:not(.Mui-disabled)::before": {+ borderBottom: "1px solid rgba(255, 255, 255, 0.5)",+ },+ },+ "& .MuiInputBase-root": {+ backgroundColor: "rgba(255, 255, 255, 0.08)",+ },+ "& .MuiInputBase-input": {+ color: "#fff",+ "&::placeholder": { color: "rgba(255, 255, 255, 0.5)" },+ },+ }),+});++const deviceLockErrorText = (result: DeviceLockUnlockResult) => {+ if (result.status === "success") return undefined;++ if (result.status === "not-supported") {+ switch (result.reason) {+ case "touchid-temporarily-unavailable":+ case "touchid-api-error":+ return t("device_lock_login_failed");+ case "unsupported-platform":+ case "touchid-not-enrolled":+ return t("device_lock_not_supported");+ }+ }++ switch (result.reason) {+ case "native-prompt-failed":+ return t("device_lock_login_cancelled");+ default:+ return t("device_lock_login_failed");+ }+};++const handleUnlockResult = (+ result: UnlockResult,+ setError: (error: string | undefined) => void,+ setLoading: (loading: boolean) => void,+ logout: () => void,+) => {+ switch (result) {+ case "success":+ case "cooldown":+ setError(undefined);+ setLoading(false);+ break;+ case "logout":+ logout();+ setLoading(false);+ break;+ case "failed":+ setError(t("app_lock_incorrect"));+ setLoading(false);+ break;+ }+};++const AppLockFormHeader = ({+ title,+ subtitle,+ isReauthentication,+ marginBottom,+}: AppLockFormHeaderProps) => (+ <>+ <Box+ sx={{+ mt: -0.5,+ mb: 1.5,+ display: "flex",+ justifyContent: "center",+ width: "100%",+ }}+ >+ <LockIllustration />+ </Box>++ <Box+ sx={{+ display: "flex",+ flexDirection: "column",+ alignItems: "center",+ gap: "9px",+ textAlign: "center",+ mb: marginBottom,+ }}+ >+ <Typography+ sx={(theme) => ({+ ...titleTextSx(theme),+ ...(isReauthentication ? {} : { mb: 0.5 }),+ })}+ >+ {title}+ </Typography>+ <Typography sx={subtitleTextSx}>{subtitle}</Typography>+ </Box>+ </>+);++const PinUnlockContent = ({+ appLock,+ isReauthentication,+ onLogout,+ closeAction,+ logout,+}: UnlockContentProps) => {+ const [pin, setPin] = useState(["", "", "", ""]);+ const [error, setError] = useState<string>();+ const [loading, setLoading] = useState(false);+ const inputRefs = useRef<(HTMLInputElement | null)[]>([]);+ const isSubmittingRef = useRef(false);+ const hasAutoSubmittedRef = useRef(false);+ const cooldown = useCooldownState(appLock.cooldownExpiresAt);++ const handlePinChange = useCallback(+ (index: number, value: string) => {+ const digit = value.replace(/\D/g, "").slice(-1);+ const nextPin = [...pin];+ nextPin[index] = digit;+ setPin(nextPin);+ setError(undefined);++ if (digit && index < 3) {+ inputRefs.current[index + 1]?.focus();+ }+ },+ [pin],+ );++ const handleKeyDown = useCallback(+ (index: number, e: React.KeyboardEvent) => {+ if (e.key === "Backspace" && !pin[index] && index > 0) {+ inputRefs.current[index - 1]?.focus();+ }+ },+ [pin],+ );++ const fullPin = useMemo(() => pin.join(""), [pin]);++ const focusPinInput = useCallback((pinIndex: number) => {+ const input = inputRefs.current[pinIndex];+ if (!input) return;++ input.focus({ preventScroll: true });+ moveCaretToInputEnd(input);+ }, []);++ const focusFirstEmptyPinInput = useCallback(() => {+ const firstEmptyIndex = pin.findIndex((digit) => !digit);+ focusPinInput(firstEmptyIndex === -1 ? 0 : firstEmptyIndex);+ }, [pin, focusPinInput]);++ const handleSubmit = useCallback(async () => {+ if (fullPin.length !== 4 || loading || isSubmittingRef.current) return;++ isSubmittingRef.current = true;+ setLoading(true);+ try {+ const result = await attemptUnlock(fullPin);+ handleUnlockResult(result, setError, setLoading, logout);+ } catch (e) {+ log.error("Unlock attempt failed", e);+ setError(t("generic_error"));+ setLoading(false);+ } finally {+ isSubmittingRef.current = false;+ }++ setPin(["", "", "", ""]);+ focusPinInput(0);+ }, [focusPinInput, fullPin, loading, logout]);++ useEffect(() => {+ if (fullPin.length !== 4) {+ hasAutoSubmittedRef.current = false;+ return;+ }++ if (loading || hasAutoSubmittedRef.current) return;++ hasAutoSubmittedRef.current = true;+ void handleSubmit();+ }, [fullPin, handleSubmit, loading]);++ useEffect(() => {+ if (!error || loading || cooldown.text) return;++ const rafID = requestAnimationFrame(() => {+ focusPinInput(0);+ });+ return () => cancelAnimationFrame(rafID);+ }, [cooldown.text, error, focusPinInput, loading]);++ if (cooldown.text) {+ return (+ <AppLockCard closeAction={closeAction} width={LOGOUT_MODAL_WIDTH}>+ <CooldownScreen+ remainingMs={cooldown.remainingMs}+ cooldownText={cooldown.text}+ attemptCount={appLock.invalidAttemptCount}+ onLogout={onLogout}+ />+ </AppLockCard>+ );+ }++ return (+ <Stack spacing={0} useFlexGap alignItems="center">+ <AppLockCard closeAction={closeAction}>+ <Stack+ spacing={0}+ useFlexGap+ alignItems="center"+ sx={appLockModalContentSx}+ >+ <AppLockFormHeader+ title={+ isReauthentication ? t("authenticate") : t("app_locked")+ }+ subtitle={t("app_lock_enter_pin_to_unlock")}+ isReauthentication={isReauthentication}+ marginBottom={4}+ />++ <Stack+ direction="row"+ spacing={1.25}+ justifyContent="center"+ onClick={focusFirstEmptyPinInput}+ sx={{ mb: 0, width: "100%" }}+ >+ {pin.map((digit, i) => (+ <TextField+ key={i}+ variant="standard"+ hiddenLabel+ autoFocus={i === 0}+ error={!!error}+ inputRef={(el: HTMLInputElement | null) => {+ inputRefs.current[i] = el;+ }}+ value={digit}+ onChange={(e) => handlePinChange(i, e.target.value)}+ onKeyDown={(e) => handleKeyDown(i, e)}+ disabled={loading}+ slotProps={{+ htmlInput: {+ maxLength: 1,+ inputMode: "numeric",+ pattern: "[0-9]",+ autoComplete: "off",+ style: {+ textAlign: "center",+ WebkitTextSecurity: "disc",+ },+ "aria-label": t(+ "app_lock_pin_digit_label",+ { index: i + 1 },+ ),+ },+ }}+ sx={(theme) => ({+ ...inputFieldSx(theme, { borderRadius: 12 }),+ flex: 1,+ minWidth: 0,+ "& .MuiInputBase-input": {+ padding: 0,+ textAlign: "center",+ height: "100%",+ fontSize: 20,+ fontWeight: 600,+ },+ })}+ />+ ))}+ </Stack>+ </Stack>+ </AppLockCard>++ <ErrorMessage+ error={error}+ attemptCount={appLock.invalidAttemptCount}+ />+ </Stack>+ );+};++const PasswordUnlockContent = ({+ appLock,+ isReauthentication,+ onLogout,+ closeAction,+ logout,+}: UnlockContentProps) => {+ const [password, setPassword] = useState("");+ const [showPassword, setShowPassword] = useState(false);+ const [error, setError] = useState<string>();+ const [loading, setLoading] = useState(false);+ const inputRef = useRef<HTMLInputElement | null>(null);+ const cooldown = useCooldownState(appLock.cooldownExpiresAt);++ const handleSubmit = useCallback(+ async (e?: React.FormEvent) => {+ e?.preventDefault();+ if (!password || loading) return;++ setLoading(true);+ try {+ const result = await attemptUnlock(password);+ handleUnlockResult(result, setError, setLoading, logout);+ } catch (e) {+ log.error("Unlock attempt failed", e);+ setError(t("generic_error"));+ setLoading(false);+ }++ setPassword("");+ inputRef.current?.focus();+ },+ [loading, logout, password],+ );++ useEffect(() => {+ if (!error || loading || cooldown.text) return;++ const rafID = requestAnimationFrame(() => {+ inputRef.current?.focus();+ });+ return () => cancelAnimationFrame(rafID);+ }, [cooldown.text, error, loading]);++ if (cooldown.text) {+ return (+ <AppLockCard closeAction={closeAction} width={LOGOUT_MODAL_WIDTH}>+ <CooldownScreen+ remainingMs={cooldown.remainingMs}+ cooldownText={cooldown.text}+ attemptCount={appLock.invalidAttemptCount}+ onLogout={onLogout}+ />+ </AppLockCard>+ );+ }++ return (+ <Stack spacing={0} useFlexGap alignItems="center">+ <AppLockCard closeAction={closeAction}>+ <Stack+ component="form"+ onSubmit={(e: React.FormEvent) => void handleSubmit(e)}+ spacing={0}+ useFlexGap+ alignItems="center"+ sx={appLockModalContentSx}+ >+ <AppLockFormHeader+ title={isReauthentication ? t("password") : t("app_locked")}+ subtitle={t("app_lock_enter_password")}+ isReauthentication={isReauthentication}+ marginBottom={2}+ />++ <TextField+ inputRef={inputRef}+ fullWidth+ hiddenLabel+ variant="standard"+ autoFocus+ error={!!error}+ type={showPassword ? "text" : "password"}+ value={password}+ onChange={(e) => {+ setPassword(e.target.value);+ setError(undefined);+ }}+ disabled={loading}+ placeholder={+ isReauthentication ? t("password") : t("app_lock_password")+ }+ autoComplete="off"+ slotProps={{+ input: {+ endAdornment: (+ <ShowHidePasswordInputAdornment+ showPassword={showPassword}+ onToggle={() => setShowPassword((s) => !s)}+ />+ ),+ },+ }}+ sx={(theme) => ({+ ...inputFieldSx(theme),+ mt: 1,+ "& .MuiInputAdornment-positionEnd": { pr: 0.5 },+ })}+ />++ <FocusVisibleButton+ type="submit"+ fullWidth+ color="accent"+ disabled={!password || loading}+ sx={(theme) => ({+ ...primaryActionButtonSx(theme),+ mt: 2,+ })}+ >+ {isReauthentication ? t("authenticate") : t("unlock")}+ </FocusVisibleButton>+ </Stack>+ </AppLockCard>++ <ErrorMessage+ error={error}+ attemptCount={appLock.invalidAttemptCount}+ />+ </Stack>+ );+};++interface DeviceUnlockContentProps {+ isReauthentication: boolean;+ closeAction?: ReactNode;+}++const DeviceLockUnlockContent = ({+ isReauthentication,+ closeAction,+}: DeviceUnlockContentProps) => {+ const [error, setError] = useState<string>();+ const [loading, setLoading] = useState(true);+ const [showManualUnlockButton, setShowManualUnlockButton] = useState(false);+ const isUnlockInProgress = useRef(false);+ const hasAutoTriggeredUnlock = useRef(false);++ const handleDeviceLockUnlock = useCallback(+ async (source: "auto" | "manual") => {+ if (isUnlockInProgress.current) return;+ isUnlockInProgress.current = true;+ setLoading(true);+ setError(undefined);++ try {+ const result = await attemptDeviceLockUnlock();+ const nextError = deviceLockErrorText(result);+ setError(nextError);+ if (source === "auto" && nextError) {+ setShowManualUnlockButton(true);+ }+ } catch (e) {+ log.error("Device lock unlock attempt failed", e);+ setError(t("generic_error"));+ if (source === "auto") {+ setShowManualUnlockButton(true);+ }+ } finally {+ setLoading(false);+ isUnlockInProgress.current = false;+ }+ },+ [],+ );++ useEffect(() => {+ const maybeAutoTriggerUnlock = () => {+ if (hasAutoTriggeredUnlock.current) return;+ if (+ typeof document == "undefined" ||+ document.visibilityState !== "visible" ||+ !document.hasFocus()+ ) {+ return;+ }++ hasAutoTriggeredUnlock.current = true;+ void handleDeviceLockUnlock("auto");+ };++ maybeAutoTriggerUnlock();+ if (hasAutoTriggeredUnlock.current || typeof window == "undefined") {+ return;+ }++ window.addEventListener("focus", maybeAutoTriggerUnlock);+ document.addEventListener("visibilitychange", maybeAutoTriggerUnlock);+ return () => {+ window.removeEventListener("focus", maybeAutoTriggerUnlock);+ document.removeEventListener(+ "visibilitychange",+ maybeAutoTriggerUnlock,+ );+ };+ }, [handleDeviceLockUnlock]);++ return (+ <Stack spacing={0} useFlexGap alignItems="center">+ <AppLockCard closeAction={closeAction}>+ <Stack+ spacing={0}+ useFlexGap+ alignItems="center"+ sx={appLockModalContentSx}+ >+ <AppLockFormHeader+ title={+ isReauthentication ? t("authenticate") : t("app_locked")+ }+ subtitle={t("device_lock_login_instructions")}+ isReauthentication={isReauthentication}+ marginBottom={2}+ />++ <FocusVisibleButton+ fullWidth+ color="accent"+ disabled={loading || !showManualUnlockButton}+ onClick={() => {+ void handleDeviceLockUnlock("manual");+ }}+ sx={(theme) => ({+ ...primaryActionButtonSx(theme),+ backgroundColor: ENTE_GREEN,+ "&:hover": { backgroundColor: ENTE_GREEN_HOVER },+ fontWeight: 600,+ mt: 2,+ })}+ >+ {loading ? (+ <CircularProgress size={18} color="inherit" />+ ) : isReauthentication ? (+ t("authenticate")+ ) : (+ t("device_lock_login")+ )}+ </FocusVisibleButton>+ </Stack>+ </AppLockCard>++ <ErrorMessage error={error} attemptCount={0} />+ </Stack>+ );+};++export const AppLockUnlockForm = ({+ appLock,+ isReauthentication,+ onLogout,+ closeAction,+}: AppLockUnlockFormProps) => {+ const { logout } = useBaseContext();++ if (appLock.lockType === "password") {+ return (+ <PasswordUnlockContent+ appLock={appLock}+ isReauthentication={isReauthentication}+ onLogout={onLogout}+ closeAction={closeAction}+ logout={logout}+ />+ );+ }++ if (appLock.lockType === "device") {+ return (+ <DeviceLockUnlockContent+ isReauthentication={isReauthentication}+ closeAction={closeAction}+ />+ );+ }++ return (+ <PinUnlockContent+ appLock={appLock}+ isReauthentication={isReauthentication}+ onLogout={onLogout}+ closeAction={closeAction}+ logout={logout}+ />+ );+};diff --git a/web/packages/new/photos/components/app-lock/styles.ts b/web/packages/new/photos/components/app-lock/styles.tsnew file mode 100644index 0000000000..778796a5c3--- /dev/null+++ b/web/packages/new/photos/components/app-lock/styles.ts@@ -0,0 +1,23 @@+import type { Theme } from "@mui/material/styles";++export const LOGOUT_MODAL_WIDTH = 368;++export const titleTextSx = (theme: Theme) => ({+ fontWeight: 600,+ fontSize: 24,+ lineHeight: "28px",+ letterSpacing: "-0.48px",+ color: "#000",+ textAlign: "center" as const,+ ...theme.applyStyles("dark", { color: "#fff" }),+});++export const subtitleTextSx = (theme: Theme) => ({+ fontWeight: 500,+ fontSize: 14,+ lineHeight: "20px",+ color: "#666",+ textAlign: "center" as const,+ maxWidth: 295,+ ...theme.applyStyles("dark", { color: "rgba(255, 255, 255, 0.64)" }),+});diff --git a/web/packages/new/photos/services/app-lock.ts b/web/packages/new/photos/services/app-lock.tsindex 11eb3cdf52..33ac80ad0f 100644--- a/web/packages/new/photos/services/app-lock.ts+++ b/web/packages/new/photos/services/app-lock.ts@@ -238,8 +238,8 @@ const logDeviceLockEvent = (/*** Return the cooldown duration for a failed-attempt count.*- * This policy is shared by lockout enforcement and cooldown UI (used by- * AppLockOverlay to render countdown progress).+ * This policy is shared by lockout enforcement and cooldown UI (used by the+ * app lock screen to render countdown progress).*/export const appLockCooldownDurationMs = (attemptCount: number): number => {if (attemptCount < cooldownStartsAtAttempt) return 0;