Refresh HiveGrid Cloud reference snapshot

This commit is contained in:
david committed 2026-08-03 15:31:14 +02:00
1 parent 5e99e14772
commit 7f88026f79
5955 files changed
+1177325 -188362

No files matched your search

@@ -0,0 +1,149 @@
import "@testing-library/jest-dom";
import { fireEvent, render, screen } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import AvatarCropDialog from "./AvatarCropDialog";
import { OUTPUT_SIZE } from "../avatarCrop";
vi.mock("react-i18next", () => ({
useTranslation: () => ({ i18n: { language: "en" }, t: (key: string) => key }),
}));
const SOURCE = "data:image/png;base64,source";
const CROPPED = "data:image/jpeg;base64,cropped";
let drawImage: ReturnType<typeof vi.fn>;
let toDataURL: ReturnType<typeof vi.fn>;
/** jsdom has no canvas backend, so the 2d context is stubbed with the calls we assert on. */
function stubCanvas({ context = true }: { context?: boolean } = {}) {
drawImage = vi.fn();
toDataURL = vi.fn(() => CROPPED);
vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockImplementation(
() => (context ? ({ fillStyle: "", fillRect: vi.fn(), drawImage } as unknown as CanvasRenderingContext2D) : null)
);
vi.spyOn(HTMLCanvasElement.prototype, "toDataURL").mockImplementation(toDataURL);
}
/** Report a landscape source picture: jsdom reports 0x0 for images it never fetches. */
function loadImage({ width = 800, height = 400 }: { width?: number; height?: number } = {}) {
const image = screen.getByAltText("settings.profile.avatar.crop.previewAlt") as HTMLImageElement;
Object.defineProperty(image, "naturalWidth", { value: width, configurable: true });
Object.defineProperty(image, "naturalHeight", { value: height, configurable: true });
fireEvent.load(image);
return image;
}
function renderDialog(overrides: Partial<React.ComponentProps<typeof AvatarCropDialog>> = {}) {
const onConfirm = vi.fn();
const onCancel = vi.fn();
render(<AvatarCropDialog source={SOURCE} onConfirm={onConfirm} onCancel={onCancel} {...overrides} />);
return { onConfirm, onCancel };
}
describe("AvatarCropDialog", () => {
beforeEach(() => {
vi.restoreAllMocks();
stubCanvas();
});
it("shows the picked file so the user decides the section before anything is stored", () => {
renderDialog();
expect(screen.getByAltText("settings.profile.avatar.crop.previewAlt")).toHaveAttribute("src", SOURCE);
expect(screen.getByRole("dialog")).toHaveAccessibleName("settings.profile.avatar.crop.title");
});
it("keeps confirm disabled until the image has reported its size", () => {
renderDialog();
const confirm = screen.getByRole("button", { name: "settings.profile.avatar.crop.confirm" });
expect(confirm).toBeDisabled();
loadImage();
expect(confirm).toBeEnabled();
});
it("hands back the centred square section of a wide picture", () => {
const { onConfirm } = renderDialog();
loadImage();
fireEvent.click(screen.getByRole("button", { name: "settings.profile.avatar.crop.confirm" }));
// 800x400 centred: the 400px square starts 200px in from the left edge.
expect(drawImage).toHaveBeenCalledWith(expect.anything(), 200, 0, 400, 400, 0, 0, OUTPUT_SIZE, OUTPUT_SIZE);
expect(onConfirm).toHaveBeenCalledWith(CROPPED);
});
it("crops a smaller section after zooming in", () => {
renderDialog();
loadImage();
fireEvent.change(screen.getByLabelText("settings.profile.avatar.crop.zoom"), { target: { value: "2" } });
fireEvent.click(screen.getByRole("button", { name: "settings.profile.avatar.crop.confirm" }));
const [, sx, sy, size] = drawImage.mock.calls[0];
expect(size).toBe(200);
expect(sx).toBe(300);
expect(sy).toBe(100);
});
it("follows an arrow-key pan instead of always cropping the centre", () => {
renderDialog();
loadImage();
fireEvent.keyDown(screen.getByRole("group", { name: "settings.profile.avatar.crop.viewportLabel" }), { key: "ArrowRight" });
fireEvent.click(screen.getByRole("button", { name: "settings.profile.avatar.crop.confirm" }));
// The 288px viewport covers 400 source pixels, so one 12px key press shifts the section by 12 / 0.72.
expect(drawImage.mock.calls[0][1]).toBeCloseTo(200 + 12 / (288 / 400), 5);
});
it("returns to the centred section on reset", () => {
renderDialog();
loadImage();
fireEvent.change(screen.getByLabelText("settings.profile.avatar.crop.zoom"), { target: { value: "3" } });
fireEvent.click(screen.getByRole("button", { name: "settings.profile.avatar.crop.reset" }));
fireEvent.click(screen.getByRole("button", { name: "settings.profile.avatar.crop.confirm" }));
expect(drawImage).toHaveBeenCalledWith(expect.anything(), 200, 0, 400, 400, 0, 0, OUTPUT_SIZE, OUTPUT_SIZE);
});
it("cancels without handing back a picture", () => {
const { onCancel, onConfirm } = renderDialog();
loadImage();
fireEvent.click(screen.getByRole("button", { name: "shared.cancel" }));
expect(onCancel).toHaveBeenCalledTimes(1);
expect(onConfirm).not.toHaveBeenCalled();
});
it("closes on Escape like any other modal", () => {
const { onCancel } = renderDialog();
fireEvent.keyDown(document, { key: "Escape" });
expect(onCancel).toHaveBeenCalledTimes(1);
});
it("explains an unreadable file instead of submitting nothing", () => {
const { onConfirm } = renderDialog();
fireEvent.error(screen.getByAltText("settings.profile.avatar.crop.previewAlt"));
expect(screen.getByRole("alert")).toHaveTextContent("settings.profile.avatar.crop.failed");
expect(onConfirm).not.toHaveBeenCalled();
});
it("reports a missing canvas context in Klartext rather than crashing", () => {
stubCanvas({ context: false });
const { onConfirm } = renderDialog();
loadImage();
fireEvent.click(screen.getByRole("button", { name: "settings.profile.avatar.crop.confirm" }));
expect(screen.getByRole("alert")).toHaveTextContent("settings.profile.avatar.crop.failed");
expect(onConfirm).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,283 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { FeatherRotateCcw, FeatherX, FeatherZoomIn, FeatherZoomOut } from "@subframe/core";
import { Button } from "~/ui/components/Button";
import { IconButton } from "~/ui/components/IconButton";
import {
MAX_ZOOM,
MIN_ZOOM,
OUTPUT_SIZE,
ZOOM_STEP,
type CropOffset,
centeredOffset,
clampOffset,
clampZoom,
cropRegion,
offsetAfterZoom,
} from "../avatarCrop";
// The picked file is never stored as-is: the user first decides which square
// section becomes their picture. Without this step a wide photo would be
// squeezed into the round avatar slot and cut wherever it happened to land.
/** Edge length of the crop viewport in CSS pixels; the round mask sits inside it. */
const VIEWPORT = 288;
/** How far one arrow-key press pans, in CSS pixels. */
const PAN_STEP = 12;
export type AvatarCropDialogProps = {
/** Data URI of the freshly picked file. */
source: string;
submitting?: boolean;
onCancel: () => void;
onConfirm: (dataUri: string) => void;
};
export default function AvatarCropDialog({ source, submitting = false, onCancel, onConfirm }: AvatarCropDialogProps) {
const { t } = useTranslation();
const imageRef = useRef<HTMLImageElement | null>(null);
const dragRef = useRef<{ pointerId: number; startX: number; startY: number; startOffset: CropOffset } | null>(null);
const [natural, setNatural] = useState<{ width: number; height: number } | null>(null);
const [zoom, setZoom] = useState(MIN_ZOOM);
const [offset, setOffset] = useState<CropOffset>({ x: 0, y: 0 });
const [failed, setFailed] = useState(false);
const geometry = { imageWidth: natural?.width ?? 0, imageHeight: natural?.height ?? 0, viewport: VIEWPORT, zoom };
const ready = Boolean(natural) && !failed;
const onImageLoad = useCallback((event: React.SyntheticEvent<HTMLImageElement>) => {
const { naturalWidth, naturalHeight } = event.currentTarget;
const loaded = { imageWidth: naturalWidth, imageHeight: naturalHeight, viewport: VIEWPORT, zoom: MIN_ZOOM };
setNatural({ width: naturalWidth, height: naturalHeight });
setZoom(MIN_ZOOM);
setOffset(centeredOffset(loaded));
}, []);
function changeZoom(next: number) {
const nextZoom = clampZoom(next);
setOffset((current) => offsetAfterZoom(geometry, current, nextZoom));
setZoom(nextZoom);
}
function pan(dx: number, dy: number) {
setOffset((current) => clampOffset(geometry, { x: current.x + dx, y: current.y + dy }));
}
function reset() {
setZoom(MIN_ZOOM);
setOffset(centeredOffset({ ...geometry, zoom: MIN_ZOOM }));
}
function onPointerDown(event: React.PointerEvent<HTMLDivElement>) {
if (!ready || event.button !== 0) return;
dragRef.current = { pointerId: event.pointerId, startX: event.clientX, startY: event.clientY, startOffset: offset };
event.currentTarget.setPointerCapture(event.pointerId);
}
function onPointerMove(event: React.PointerEvent<HTMLDivElement>) {
const drag = dragRef.current;
if (!drag || drag.pointerId !== event.pointerId) return;
event.preventDefault();
setOffset(
clampOffset(geometry, {
x: drag.startOffset.x + (event.clientX - drag.startX),
y: drag.startOffset.y + (event.clientY - drag.startY),
})
);
}
function endDrag(event: React.PointerEvent<HTMLDivElement>) {
if (dragRef.current?.pointerId !== event.pointerId) return;
dragRef.current = null;
if (event.currentTarget.hasPointerCapture(event.pointerId)) {
event.currentTarget.releasePointerCapture(event.pointerId);
}
}
function onKeyDown(event: React.KeyboardEvent<HTMLDivElement>) {
const moves: Record<string, [number, number]> = {
ArrowLeft: [PAN_STEP, 0],
ArrowRight: [-PAN_STEP, 0],
ArrowUp: [0, PAN_STEP],
ArrowDown: [0, -PAN_STEP],
};
const move = moves[event.key];
if (!move || !ready) return;
event.preventDefault();
pan(move[0], move[1]);
}
// Escape closes the dialog like the cancel button — expected from any modal.
useEffect(() => {
function onEscape(event: KeyboardEvent) {
if (event.key === "Escape") onCancel();
}
document.addEventListener("keydown", onEscape);
return () => document.removeEventListener("keydown", onEscape);
}, [onCancel]);
function confirm() {
const image = imageRef.current;
if (!image || !ready) return;
const region = cropRegion(geometry, offset);
const canvas = document.createElement("canvas");
canvas.width = OUTPUT_SIZE;
canvas.height = OUTPUT_SIZE;
const context = canvas.getContext("2d");
if (!context) {
setFailed(true);
return;
}
// JPEG has no alpha, so a transparent PNG would otherwise bake in black.
context.fillStyle = "#ffffff";
context.fillRect(0, 0, OUTPUT_SIZE, OUTPUT_SIZE);
context.drawImage(image, region.sx, region.sy, region.size, region.size, 0, 0, OUTPUT_SIZE, OUTPUT_SIZE);
onConfirm(canvas.toDataURL("image/jpeg", 0.92));
}
const scale = ready ? (VIEWPORT / Math.min(geometry.imageWidth, geometry.imageHeight)) * zoom : 1;
return (
<div
className="bg-surface-neutral-overlay fixed inset-0 z-50 flex flex-col items-center justify-center gap-2 px-4 py-4"
data-ui-id="ui.settings.profile.avatarCrop.dialog"
>
<div
role="dialog"
aria-modal="true"
aria-label={t("settings.profile.avatar.crop.title")}
className="border-border-default bg-surface-neutral-secondary mobile:px-4 mobile:py-5 relative flex max-h-[90vh] w-full max-w-[480px] flex-col items-start gap-5 overflow-auto rounded-lg border border-solid px-6 py-6 shadow-lg"
>
<IconButton
className="absolute top-3 right-3"
variant="ghost"
size="small"
icon={<FeatherX />}
aria-label={t("shared.close")}
onClick={onCancel}
data-ui-id="ui.settings.profile.avatarCrop.close"
/>
<div className="flex w-full flex-col items-start gap-1">
<span className="text-heading- font-heading- text-text-neutral-primary">{t("settings.profile.avatar.crop.title")}</span>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
{t("settings.profile.avatar.crop.subtitle")}
</span>
</div>
{failed ? (
<span className="text-body-small-regular-0 font-body-small-regular-0 text-text-feedback-negative" role="alert">
{t("settings.profile.avatar.crop.failed")}
</span>
) : null}
<div className="flex w-full flex-col items-center gap-3">
{/* The pan surface has no native equivalent: it is dragged with a pointer and panned with the
arrow keys, so it has to take focus. No interactive role fits — "group" plus a label keeps
it announced without claiming button or slider semantics it does not have. */}
{/* eslint-disable jsx-a11y/no-noninteractive-element-interactions, jsx-a11y/no-noninteractive-tabindex */}
<div
role="group"
tabIndex={0}
aria-label={t("settings.profile.avatar.crop.viewportLabel")}
style={{ width: VIEWPORT, height: VIEWPORT }}
className="bg-surface-neutral-tertiary focus-visible:shadow-focus relative flex-none touch-none overflow-hidden rounded-lg select-none"
onPointerDown={onPointerDown}
onPointerMove={onPointerMove}
onPointerUp={endDrag}
onPointerCancel={endDrag}
onKeyDown={onKeyDown}
data-ui-id="ui.settings.profile.avatarCrop.viewport"
>
<img
ref={imageRef}
src={source}
alt={t("settings.profile.avatar.crop.previewAlt")}
onLoad={onImageLoad}
onError={() => setFailed(true)}
draggable={false}
style={{
width: ready ? geometry.imageWidth * scale : VIEWPORT,
height: ready ? geometry.imageHeight * scale : VIEWPORT,
transform: `translate(${offset.x}px, ${offset.y}px)`,
}}
className="absolute top-0 left-0 max-w-none"
/>
{/* Round mask: the dimmed surround shows what gets cut away. */}
<div aria-hidden="true" className="rounded-round pointer-events-none absolute inset-0 shadow-[0_0_0_9999px_rgb(0_0_0/0.45)]" />
</div>
{/* eslint-enable jsx-a11y/no-noninteractive-element-interactions, jsx-a11y/no-noninteractive-tabindex */}
<div className="flex w-full items-center gap-3">
<IconButton
variant="ghost"
size="small"
icon={<FeatherZoomOut />}
aria-label={t("settings.profile.avatar.crop.zoomOut")}
disabled={!ready || zoom <= MIN_ZOOM}
onClick={() => changeZoom(zoom - 10 * ZOOM_STEP)}
data-ui-id="ui.settings.profile.avatarCrop.zoomOut"
/>
<input
type="range"
min={MIN_ZOOM}
max={MAX_ZOOM}
step={ZOOM_STEP}
value={zoom}
disabled={!ready}
aria-label={t("settings.profile.avatar.crop.zoom")}
onChange={(event) => changeZoom(Number(event.target.value))}
className="accent-brand-brand-surface-solid-default h-1 shrink-0 grow basis-0 cursor-pointer"
data-ui-id="ui.settings.profile.avatarCrop.zoom"
/>
<IconButton
variant="ghost"
size="small"
icon={<FeatherZoomIn />}
aria-label={t("settings.profile.avatar.crop.zoomIn")}
disabled={!ready || zoom >= MAX_ZOOM}
onClick={() => changeZoom(zoom + 10 * ZOOM_STEP)}
data-ui-id="ui.settings.profile.avatarCrop.zoomIn"
/>
<IconButton
variant="ghost"
size="small"
icon={<FeatherRotateCcw />}
aria-label={t("settings.profile.avatar.crop.reset")}
disabled={!ready}
onClick={reset}
data-ui-id="ui.settings.profile.avatarCrop.reset"
/>
</div>
<span className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary text-center">
{t("settings.profile.avatar.crop.hint")}
</span>
</div>
<div className="mobile:flex-col-reverse flex w-full items-center justify-end gap-2">
<Button
className="mobile:w-full"
type="button"
variant="secondary"
onClick={onCancel}
data-ui-id="ui.settings.profile.avatarCrop.cancel"
>
{t("shared.cancel")}
</Button>
<Button
className="mobile:w-full"
type="button"
loading={submitting}
disabled={!ready}
onClick={confirm}
data-ui-id="ui.settings.profile.avatarCrop.confirm"
>
{t("settings.profile.avatar.crop.confirm")}
</Button>
</div>
</div>
</div>
);
}
@@ -32,7 +32,7 @@ export default function ForgotPasswordScreen({
icon={<FeatherMail />}
tone="positive"
title={t("account.forgot.sentTitle")}
message={t("account.forgot.sentBody", { email })}
message={t("account.forgot.sentBody")}
hint={t("account.forgot.sentHint")}
dataUiId="ui.auth.forgot.sent"
>
@@ -20,11 +20,14 @@ export default function GroupsListView({
items,
canManage,
onManageMembers,
onCreate,
}: {
items: GroupWithDetails[];
canManage: boolean;
/** R-P2b bulk interim UI (AD-28): opens the group members dialog when provided. */
onManageMembers?: (groupId: string) => void;
/** Opens the create dialog from the empty state; omitted when the caller has none. */
onCreate?: () => void;
}) {
const { t } = useTranslation();
const { csrf = "" } = useRootData();
@@ -34,24 +37,7 @@ export default function GroupsListView({
return (
<div className="flex w-full flex-col items-start gap-4">
<div className="flex w-full items-start justify-between gap-4 mobile:flex-col">
<div className="flex flex-col items-start gap-1">
<span className="text-title-page font-title-page text-text-neutral-primary mobile:text-subtitle mobile:font-subtitle">
{t("models.group.plural")}
</span>
<span className="text-body-default-regular-150 font-body-default-regular-150 text-text-neutral-tertiary">
{t("settings.members.groups.subtitle")}
</span>
</div>
{canManage ? (
<Link to="new" className="no-underline mobile:w-full" data-ui-id="ui.settings.groups.new">
<Button variant="primary" icon={<FeatherPlus />} className="mobile:w-full">
{t("settings.members.groups.createCta")}
</Button>
</Link>
) : null}
</div>
{/* Page headline (title/subtitle + create CTA) lives in the route's shared PageHeader. */}
<Table
header={
<Table.HeaderRow>
@@ -88,10 +74,10 @@ export default function GroupsListView({
</span>
</div>
</div>
{canManage ? (
<Link to="new" className="no-underline">
<Button variant="primary" icon={<FeatherPlus />}>{t("settings.members.groups.createCta")}</Button>
</Link>
{canManage && onCreate ? (
<Button variant="primary" icon={<FeatherPlus />} onClick={onCreate}>
{t("settings.members.groups.createCta")}
</Button>
) : null}
</div>
</Table.Cell>
@@ -108,37 +94,41 @@ export default function GroupsListView({
<Table.Cell>
<span className="whitespace-nowrap text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-secondary">{group.users.length}</span>
</Table.Cell>
<Table.Cell>
<div className="flex grow shrink-0 basis-0 items-center justify-end">
{canManage ? (
<SubframeCore.DropdownMenu.Root>
<SubframeCore.DropdownMenu.Trigger asChild>
<IconButton icon={<FeatherMoreHorizontal />} data-ui-id="ui.settings.groups.rowActions" />
</SubframeCore.DropdownMenu.Trigger>
<SubframeCore.DropdownMenu.Portal>
<SubframeCore.DropdownMenu.Content side="bottom" align="end" sideOffset={4} asChild>
<DropdownMenu>
<Link to={group.id} className="no-underline">
<DropdownMenu.DropdownItem icon={<FeatherEdit2 />}>{t("shared.edit")}</DropdownMenu.DropdownItem>
</Link>
{onManageMembers ? (
<DropdownMenu.DropdownItem
icon={<FeatherUsers />}
onClick={() => onManageMembers(group.id)}
data-ui-id="ui.settings.groups.manageMembers"
>
{t("settings.members.groups.bulk.manageAction")}
</DropdownMenu.DropdownItem>
) : null}
<DropdownMenu.DropdownItem icon={<FeatherTrash />} onClick={() => setConfirmDelete({ id: group.id, name: group.name })}>
{t("shared.delete")}
<Table.Cell variant="align-right">
{canManage ? (
<SubframeCore.DropdownMenu.Root>
<SubframeCore.DropdownMenu.Trigger asChild>
<IconButton
variant="ghost"
size="small"
icon={<FeatherMoreHorizontal />}
aria-label={`${t("shared.actions")}: ${group.name}`}
data-ui-id="ui.settings.groups.rowActions"
/>
</SubframeCore.DropdownMenu.Trigger>
<SubframeCore.DropdownMenu.Portal>
<SubframeCore.DropdownMenu.Content side="bottom" align="end" sideOffset={4} asChild>
<DropdownMenu>
<Link to={group.id} className="no-underline">
<DropdownMenu.DropdownItem icon={<FeatherEdit2 />}>{t("shared.edit")}</DropdownMenu.DropdownItem>
</Link>
{onManageMembers ? (
<DropdownMenu.DropdownItem
icon={<FeatherUsers />}
onClick={() => onManageMembers(group.id)}
data-ui-id="ui.settings.groups.manageMembers"
>
{t("settings.members.groups.bulk.manageAction")}
</DropdownMenu.DropdownItem>
</DropdownMenu>
</SubframeCore.DropdownMenu.Content>
</SubframeCore.DropdownMenu.Portal>
</SubframeCore.DropdownMenu.Root>
) : null}
</div>
) : null}
<DropdownMenu.DropdownItem icon={<FeatherTrash />} onClick={() => setConfirmDelete({ id: group.id, name: group.name })}>
{t("shared.delete")}
</DropdownMenu.DropdownItem>
</DropdownMenu>
</SubframeCore.DropdownMenu.Content>
</SubframeCore.DropdownMenu.Portal>
</SubframeCore.DropdownMenu.Root>
) : null}
</Table.Cell>
</Table.Row>
))
@@ -0,0 +1,96 @@
import "@testing-library/jest-dom";
import { fireEvent, render, screen } from "@testing-library/react";
import React from "react";
import { describe, expect, it, vi } from "vitest";
import LoginForm from "./LoginForm";
const navigate = vi.hoisted(() => vi.fn());
vi.mock("react-router", async (importOriginal) => {
const actual = await importOriginal<typeof import("react-router")>();
return {
...actual,
Form: ({ children, ...props }: React.FormHTMLAttributes<HTMLFormElement>) => <form {...props}>{children}</form>,
Link: ({ children, to, ...props }: React.AnchorHTMLAttributes<HTMLAnchorElement> & { to: string }) => (
<a href={to} {...props}>
{children}
</a>
),
useNavigate: () => navigate,
useNavigation: () => ({ state: "idle" }),
useSearchParams: () => [new URLSearchParams()],
};
});
const translations: Record<string, string> = {
"account.login.button": "Log in",
"account.login.forgot": "Forgot your password?",
"account.login.headline": "Welcome back.",
"account.login.passwordPlaceholder": "Enter your password",
"account.shared.email": "Email",
"account.shared.emailPlaceholder": "name@company.com",
"account.shared.password": "Password",
"api.errors.invalidPassword": "Email or password is incorrect.",
"shared.invalid": "Invalid",
};
vi.mock("react-i18next", () => ({
useTranslation: () => ({
t: (key: string) => translations[key] ?? key,
i18n: { exists: (key: string) => key in translations },
}),
}));
vi.mock("~/utils/data/useRootData", () => ({
useRootData: () => ({
csrf: "csrf-token",
appConfiguration: {
auth: { authMethods: { emailPassword: { enabled: true } } },
subscription: { allowSignUpBeforeSubscribe: false },
},
}),
}));
vi.mock("~/components/ui/buttons/LoadingButton", () => ({
default: ({ children, actionName: _actionName, dataUiId, ...props }: React.ButtonHTMLAttributes<HTMLButtonElement> & { actionName?: string; dataUiId?: string }) => (
<button {...props} data-ui-id={dataUiId}>
{children}
</button>
),
}));
describe("LoginForm password handling", () => {
it("clears its controlled password state after every credential response", () => {
const { rerender } = render(<LoginForm actionData={undefined} />);
const passwordInput = screen.getByPlaceholderText("Enter your password");
fireEvent.change(passwordInput, { target: { value: "first-wrong-secret" } });
expect(passwordInput).toHaveValue("first-wrong-secret");
rerender(
<LoginForm
actionData={{
error: "Email or password is incorrect.",
fields: { email: "user@example.com" },
}}
/>
);
expect(passwordInput).toHaveValue("");
expect(passwordInput).toHaveFocus();
fireEvent.change(passwordInput, { target: { value: "second-wrong-secret" } });
rerender(
<LoginForm
actionData={{
error: "Email or password is incorrect.",
fields: { email: "user@example.com" },
}}
/>
);
expect(passwordInput).toHaveValue("");
expect(passwordInput).toHaveFocus();
});
});
@@ -1,5 +1,5 @@
import { Form, Link, useNavigate, useNavigation, useSearchParams } from "react-router";
import { useEffect, useRef } from "react";
import { useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import LoadingButton from "~/components/ui/buttons/LoadingButton";
import ExclamationTriangleIcon from "~/components/ui/icons/ExclamationTriangleIcon";
@@ -14,7 +14,6 @@ export type LoginActionData = {
};
fields?: {
email: string;
password: string;
};
/**
* D1: set when the password is valid but the user has 2FA enabled. The session cookie only
@@ -44,6 +43,14 @@ export default function LoginForm({ actionData, redirectTo }: { actionData: Logi
const mfaVerifyPath = actionData?.mfaVerifyPath ?? "/login-mfa";
const emailInput = useRef<RefInputText>(null);
const passwordInput = useRef<RefInputText>(null);
const [password, setPassword] = useState("");
const passwordFieldError = Boolean(
actionData?.fieldErrors?.password || actionData?.error === t("api.errors.invalidPassword")
);
const shouldClearPassword = Boolean(
actionData && (actionData.fieldErrors?.password || actionData.error || actionData.requiresCaptcha)
);
useEffect(() => {
if (appConfiguration.auth.authMethods.emailPassword.enabled) {
setTimeout(() => {
@@ -59,6 +66,15 @@ export default function LoginForm({ actionData, redirectTo }: { actionData: Logi
}
}, [actionData?.requiresMfa, mfaVerifyPath, navigate]);
useEffect(() => {
if (shouldClearPassword) {
setPassword("");
}
if (passwordFieldError) {
passwordInput.current?.input.current?.focus();
}
}, [actionData, passwordFieldError, shouldClearPassword]);
if (actionData?.requiresMfa) {
return (
<div className="space-y-4 text-center" data-ui-id="ui.auth.login.mfaRedirect">
@@ -120,6 +136,7 @@ export default function LoginForm({ actionData, redirectTo }: { actionData: Logi
{t("account.shared.password")}
</label> */}
<InputText
ref={passwordInput}
id="password"
title={t("account.shared.password")}
name="password"
@@ -129,9 +146,10 @@ export default function LoginForm({ actionData, redirectTo }: { actionData: Logi
ariaDescribedBy={passwordErrorId}
ariaInvalid={passwordErrorId ? true : undefined}
// className="focus:border-theme-500 focus:ring-ring relative mt-1 block w-full appearance-none rounded-md border border-border px-3 py-2 text-sm text-foreground placeholder-gray-500 focus:z-10 focus:outline-hidden sm:text-sm dark:border-gray-700 dark:bg-gray-900 dark:text-slate-200"
placeholder="************"
placeholder={t("account.login.passwordPlaceholder")}
value={password}
setValue={setPassword}
disabled={navigation.state !== "idle"}
defaultValue={actionData?.fields?.password}
/>
{actionData?.fieldErrors?.password ? (
<p className="text-destructive-foreground py-2 text-xs" role="alert" id="password-error">
@@ -0,0 +1,149 @@
import "@testing-library/jest-dom";
import { fireEvent, render, screen } from "@testing-library/react";
import React from "react";
import { describe, expect, it, vi } from "vitest";
import LoginScreen from "./LoginScreen";
import type { LoginActionData } from "./LoginForm";
const navigate = vi.hoisted(() => vi.fn());
vi.mock("react-router", async (importOriginal) => {
const actual = await importOriginal<typeof import("react-router")>();
return {
...actual,
Form: ({ children, ...props }: React.FormHTMLAttributes<HTMLFormElement>) => <form {...props}>{children}</form>,
Link: ({ children, to, ...props }: React.AnchorHTMLAttributes<HTMLAnchorElement> & { to: string }) => (
<a href={to} {...props}>
{children}
</a>
),
useNavigate: () => navigate,
useNavigation: () => ({ state: "idle" }),
useSearchParams: () => [new URLSearchParams()],
};
});
const translations: Record<string, string> = {
"account.login.button": "Log in",
"account.login.divider": "or",
"account.login.forgot": "Forgot your password?",
"account.login.headline": "Welcome back.",
"account.login.invalidCredentialsDescription": "Please check your details and try again.",
"account.login.invalidCredentialsTitle": "Email or password is incorrect.",
"account.login.magicLink": "Sign in with magic link",
"account.login.noAccount": "No account yet?",
"account.login.passwordPlaceholder": "Enter your password",
"account.login.register": "Sign up",
"account.login.title": "Log in",
"account.shared.email": "Email",
"account.shared.emailPlaceholder": "name@company.com",
"account.shared.password": "Password",
"api.errors.invalidPassword": "Email or password is incorrect.",
};
vi.mock("react-i18next", () => ({
useTranslation: () => ({ t: (key: string) => translations[key] ?? key }),
}));
vi.mock("~/utils/data/useRootData", () => ({
useRootData: () => ({
csrf: "csrf-token",
appConfiguration: {
auth: {
captcha: {
enabled: false,
provider: "mcaptcha",
instanceUrl: undefined,
loginSiteKey: undefined,
},
},
},
}),
}));
vi.mock("~/components/captcha/Captcha", () => ({ default: () => null }));
describe("LoginScreen", () => {
it("shows a clear password placeholder instead of mask characters", () => {
render(<LoginScreen actionData={undefined} />);
const passwordInput = screen.getByLabelText("Password");
expect(passwordInput).toHaveValue("");
expect(passwordInput).toHaveAttribute("placeholder", "Enter your password");
expect(passwordInput.getAttribute("placeholder")).not.toMatch(/^[*•]+$/u);
});
it("focuses and describes the password field after a server validation error without restoring the submitted secret", () => {
const { rerender } = render(<LoginScreen actionData={undefined} />);
const passwordInput = screen.getByLabelText("Password");
fireEvent.change(passwordInput, { target: { value: "user-submitted-secret" } });
expect(passwordInput).toHaveValue("user-submitted-secret");
const responseWithLegacySecret = {
fieldErrors: { email: undefined, password: "Invalid password" },
fields: { email: "user@example.com", password: "must-not-be-restored" },
} as unknown as LoginActionData;
rerender(<LoginScreen actionData={responseWithLegacySecret} />);
expect(passwordInput).toHaveFocus();
expect(passwordInput).toHaveValue("");
expect(passwordInput).toHaveAttribute("aria-invalid", "true");
expect(passwordInput).toHaveAttribute("aria-describedby", "login-password-error");
expect(passwordInput).toHaveAccessibleDescription("Invalid password");
expect(screen.getByRole("alert")).toHaveTextContent("Invalid password");
});
it("describes both fields after server validation errors", () => {
render(
<LoginScreen
actionData={{
fieldErrors: { email: "Invalid email", password: "Invalid password" },
fields: { email: "not-an-email" },
}}
/>
);
const emailInput = screen.getByLabelText("Email");
const passwordInput = screen.getByLabelText("Password");
expect(emailInput).toHaveAttribute("aria-invalid", "true");
expect(emailInput).toHaveAttribute("aria-describedby", "login-email-error");
expect(emailInput).toHaveAccessibleDescription("Invalid email");
expect(passwordInput).toHaveAttribute("aria-invalid", "true");
expect(passwordInput).toHaveAccessibleDescription("Invalid password");
expect(screen.getAllByRole("alert")).toHaveLength(2);
});
it("focuses and describes the password field after generic invalid credentials", () => {
const { rerender } = render(<LoginScreen actionData={undefined} />);
const passwordInput = screen.getByLabelText("Password");
fireEvent.change(passwordInput, { target: { value: "first-wrong-secret" } });
rerender(
<LoginScreen
actionData={{
error: "Email or password is incorrect.",
fields: { email: "user@example.com" },
}}
/>
);
expect(passwordInput).toHaveFocus();
expect(passwordInput).toHaveValue("");
expect(passwordInput).toHaveAttribute("aria-invalid", "true");
expect(passwordInput).toHaveAccessibleDescription("Email or password is incorrect.");
fireEvent.change(passwordInput, { target: { value: "second-wrong-secret" } });
rerender(
<LoginScreen
actionData={{
error: "Email or password is incorrect.",
fields: { email: "user@example.com" },
}}
/>
);
expect(passwordInput).toHaveFocus();
expect(passwordInput).toHaveValue("");
});
});
@@ -34,11 +34,19 @@ export default function LoginScreen({
const emailError = actionData?.fieldErrors?.email;
const passwordError = actionData?.fieldErrors?.password;
const loginEmailRef = useRef<HTMLInputElement | null>(null);
const loginPasswordRef = useRef<HTMLInputElement | null>(null);
const [loginPassword, setLoginPassword] = useState("");
const [magicRequestOpen, setMagicRequestOpen] = useState(Boolean(actionData?.magicLinkRequest));
const [magicEmail, setMagicEmail] = useState(actionData?.magicLinkEmail ?? actionData?.fields?.email ?? "");
const showMagicRequest = !actionData?.magicLinkSent && (magicRequestOpen || Boolean(actionData?.magicLinkRequest));
const invalidCredentials = actionData?.error === t("api.errors.invalidPassword");
const credentialFieldError = invalidCredentials ? t("account.login.invalidCredentialsTitle") : undefined;
const passwordFieldError = credentialFieldError ?? passwordError;
const emailErrorId = emailError ? "login-email-error" : undefined;
const passwordErrorId = passwordFieldError ? "login-password-error" : undefined;
const shouldClearPassword = Boolean(
actionData && !actionData.magicLinkRequest && !actionData.magicLinkSent && (passwordError || actionData.error || actionData.requiresCaptcha)
);
const formError = actionData?.error && !actionData.requiresCaptcha ? actionData.error : undefined;
const captchaSitekey = actionData?.sitekey ?? appConfiguration.auth.captcha.loginSiteKey;
const compactActionButtons = Boolean(invalidCredentials || actionData?.requiresCaptcha);
@@ -50,6 +58,15 @@ export default function LoginScreen({
}
}, [actionData?.requiresMfa, mfaVerifyPath, navigate]);
useEffect(() => {
if (shouldClearPassword) {
setLoginPassword("");
}
if (passwordFieldError) {
loginPasswordRef.current?.focus();
}
}, [actionData, passwordFieldError, shouldClearPassword]);
if (actionData?.requiresMfa) {
return (
<AuthShell title={t("account.loginMfa.title")} dataUiId="ui.auth.login.page">
@@ -193,14 +210,14 @@ export default function LoginScreen({
<span
className={
compactActionButtons
? "text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary"
: "text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary"
? "text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-secondary"
: "text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-secondary"
}
>
{t("account.login.noAccount")}
</span>
<Link to="/signup" className="no-underline" data-ui-id="ui.auth.login.register">
<LinkButton size="small" hideIcon>
<LinkButton size="small" variant="subtle" hideIcon>
{t("account.login.register")}
</LinkButton>
</Link>
@@ -262,28 +279,40 @@ export default function LoginScreen({
</Card>
</>
) : null}
<TextInput
className="h-auto w-full flex-none"
fillContainer
showLabel
label={t("account.shared.email")}
helpText={credentialFieldError ? "" : emailError ?? ""}
message={credentialFieldError ?? ""}
error={Boolean(emailError || credentialFieldError)}
type="email"
>
<TextInput.Input
ref={loginEmailRef}
name="email"
<div className="flex w-full flex-col items-start gap-2">
<TextInput
className="h-auto w-full flex-none"
fillContainer
showLabel
label={t("account.shared.email")}
message={credentialFieldError ?? ""}
error={Boolean(emailError || credentialFieldError)}
type="email"
required
autoComplete="email"
placeholder={t("account.shared.emailPlaceholder")}
defaultValue={actionData?.fields?.email}
disabled={isSubmitting}
data-ui-id="ui.auth.login.email"
/>
</TextInput>
>
<TextInput.Input
ref={loginEmailRef}
name="email"
type="email"
required
autoComplete="email"
placeholder={t("account.shared.emailPlaceholder")}
defaultValue={actionData?.fields?.email}
disabled={isSubmitting}
aria-invalid={emailError ? true : undefined}
aria-describedby={emailErrorId}
data-ui-id="ui.auth.login.email"
/>
</TextInput>
{emailError ? (
<span
id={emailErrorId}
className="text-body-small-regular-0 font-body-small-regular-0 text-text-feedback-negative"
role="alert"
>
{emailError}
</span>
) : null}
</div>
<div className="flex w-full flex-col items-start gap-2">
<TextInput
@@ -291,26 +320,37 @@ export default function LoginScreen({
fillContainer
showLabel
label={t("account.shared.password")}
helpText={credentialFieldError ? "" : passwordError ?? ""}
message={credentialFieldError ?? ""}
error={Boolean(passwordError || credentialFieldError)}
error={Boolean(passwordFieldError)}
type="password"
>
<TextInput.Input
ref={loginPasswordRef}
name="password"
type="password"
required
autoComplete="current-password"
placeholder={t("account.shared.passwordPlaceholder")}
defaultValue={actionData?.fields?.password}
placeholder={t("account.login.passwordPlaceholder")}
value={loginPassword}
onChange={(event) => setLoginPassword(event.target.value)}
disabled={isSubmitting}
aria-invalid={passwordFieldError ? true : undefined}
aria-describedby={passwordErrorId}
data-ui-id="ui.auth.login.password"
/>
</TextInput>
{passwordFieldError ? (
<span
id={passwordErrorId}
className="text-body-small-regular-0 font-body-small-regular-0 text-text-feedback-negative"
role="alert"
>
{passwordFieldError}
</span>
) : null}
<div className="flex w-full items-start justify-end">
<Link to="/forgot-password" className="no-underline" data-ui-id="ui.auth.login.forgot">
<LinkButton size="small" hideIcon>
<LinkButton size="small" variant="subtle" hideIcon>
{t("account.login.forgot")}
</LinkButton>
</Link>
@@ -94,7 +94,11 @@ export default function MembersListView({
{canEdit ? (
<SubframeCore.DropdownMenu.Root>
<SubframeCore.DropdownMenu.Trigger asChild>
<IconButton icon={<FeatherMoreHorizontal />} data-ui-id="ui.settings.members.rowActions" />
<IconButton
icon={<FeatherMoreHorizontal />}
aria-label={`${t("shared.actions")}: ${name}`}
data-ui-id="ui.settings.members.rowActions"
/>
</SubframeCore.DropdownMenu.Trigger>
<SubframeCore.DropdownMenu.Portal>
<SubframeCore.DropdownMenu.Content side="bottom" align="end" sideOffset={4} asChild>
@@ -1,6 +1,7 @@
import { useEffect, useRef, useState } from "react";
import { Form, useActionData, useNavigation, useSubmit } from "react-router";
import { useTranslation } from "react-i18next";
import { formatDate } from "~/locale/format";
import { QRCodeSVG } from "qrcode.react";
import {
FeatherArrowLeft,
@@ -22,6 +23,7 @@ import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
import { Button } from "~/ui/components/Button";
import { Card } from "~/ui/components/Card";
import { CopyToClipboardButton } from "~/ui/components/CopyToClipboardButton";
import { Dialog } from "~/ui/components/Dialog";
import { IconButton } from "~/ui/components/IconButton";
import { IconWithBackground } from "~/ui/components/IconWithBackground";
import { InputOtp } from "~/ui/components/InputOtp";
@@ -30,6 +32,7 @@ import { Select } from "~/ui/components/Select";
import { TextInput } from "~/ui/components/TextInput";
import { TenantUserType } from "~/application/enums/tenants/TenantUserType";
import { useRootData } from "~/utils/data/useRootData";
import AvatarCropDialog from "./AvatarCropDialog";
// D-P2 — Settings > Profil nach Davids Subframe-"My Profile"-Design: Profil-Card (Avatar + Name inline-edit +
// E-Mail read-only) + Sicherheits-Card (Passwort ändern -> Modal, 2FA -> Verwalten/Setup/Disable-Modal). Praesentational,
@@ -72,14 +75,14 @@ function userDisplayName(user: ProfileUser): string {
// hier 1:1 als Markup nachgebaut, OHNE die Settings-Shell/Navigation umzubauen.
function NeutralCard({ children }: { children: React.ReactNode }) {
return (
<div className="flex h-full w-full flex-col items-start gap-3 rounded-lg bg-surface-neutral-secondary px-4 py-4">
<div className="flex w-full grow shrink-0 basis-0 flex-col items-start gap-3">{children}</div>
<div className="bg-surface-neutral-secondary flex h-full w-full flex-col items-start gap-3 rounded-lg px-4 py-4">
<div className="flex w-full shrink-0 grow basis-0 flex-col items-start gap-3">{children}</div>
</div>
);
}
function CardDivider() {
return <div className="flex h-px w-full flex-col items-center gap-2 bg-surface-neutral-tertiary" />;
return <div className="bg-surface-neutral-tertiary flex h-px w-full flex-col items-center gap-2" />;
}
function SettingRow({ label, helpText, children }: { label: React.ReactNode; helpText?: React.ReactNode; children: React.ReactNode }) {
@@ -88,10 +91,10 @@ function SettingRow({ label, helpText, children }: { label: React.ReactNode; hel
<div className="flex flex-col items-start gap-1">
<span className="text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary">{label}</span>
{helpText ? (
<span className="w-full text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary">{helpText}</span>
<span className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary w-full">{helpText}</span>
) : null}
</div>
<div className="flex grow shrink-0 basis-0 items-center justify-end">{children}</div>
<div className="flex shrink-0 grow basis-0 items-center justify-end">{children}</div>
</div>
);
}
@@ -147,6 +150,8 @@ export default function MyProfileScreen({
const fileInput = useRef<HTMLInputElement | null>(null);
const avatarForm = useRef<HTMLFormElement | null>(null);
const [avatarData, setAvatarData] = useState<string>("");
// Data URI of the picked file while the crop dialog is open; null when closed.
const [cropSource, setCropSource] = useState<string | null>(null);
// Schritt-Übergänge des 2FA-Flows aus der Action-Antwort ableiten.
useEffect(() => {
@@ -164,17 +169,24 @@ export default function MyProfileScreen({
if (!mfaStatus?.enabled && (twoFa === "disable" || twoFa === "manage")) setTwoFa(null);
}, [mfaStatus?.enabled, twoFa]);
// A picked file goes into the crop dialog first; only the section the user
// confirmed there is submitted. Clearing the input lets the same file be
// picked again after a cancel, which otherwise fires no change event.
function onPickAvatar(event: React.ChangeEvent<HTMLInputElement>) {
const file = event.target.files?.[0];
event.target.value = "";
if (!file) return;
const reader = new FileReader();
reader.onload = () => {
setAvatarData(String(reader.result ?? ""));
requestAnimationFrame(() => avatarForm.current && submit(avatarForm.current));
};
reader.onload = () => setCropSource(String(reader.result ?? ""));
reader.readAsDataURL(file);
}
function onCropConfirmed(dataUri: string) {
setCropSource(null);
setAvatarData(dataUri);
requestAnimationFrame(() => avatarForm.current && submit(avatarForm.current));
}
const mfaEnabled = Boolean(mfaStatus?.enabled);
const roleName = role === null || role === undefined ? "" : TenantUserType[role];
const roleLabel = roleName ? t(`settings.profile.types.${roleName}`) : "";
@@ -182,30 +194,20 @@ export default function MyProfileScreen({
return (
<div className="flex w-full flex-col items-start gap-4" data-ui-id="ui.settings.profile.page">
<div className="flex w-full flex-col items-start gap-4">
{/* Header */}
<div className="flex w-full flex-col items-start gap-2">
<span className="text-title-page font-title-page text-text-neutral-primary mobile:text-subtitle mobile:font-subtitle">
{t("settings.profile.accountSettings.title")}
</span>
<span className="w-full text-body-default-regular-150 font-body-default-regular-150 text-text-neutral-tertiary">
{t("settings.profile.accountSettings.description")}
</span>
</div>
{/* Page headline (title/subtitle) lives in the route's shared PageHeader. */}
{/* Reihe 1 — Profil + Accountsicherheit */}
<div className="flex w-full items-start gap-4 mobile:flex-col">
<div className="mobile:flex-col flex w-full items-start gap-4">
<NeutralCard>
<div className="flex w-full items-center gap-6 mobile:flex-col mobile:items-start">
<div className="flex grow shrink-0 basis-0 items-center gap-4">
<Avatar size="large" image={user.avatar ?? undefined}>
<div className="mobile:flex-col mobile:items-start flex w-full items-center gap-6">
<div className="flex shrink-0 grow basis-0 items-center gap-4">
<Avatar size="extra-large" image={user.avatar ?? undefined}>
{initials(user)}
</Avatar>
<div className="flex grow shrink-0 basis-0 flex-col items-start gap-3">
<div className="flex shrink-0 grow basis-0 flex-col items-start gap-3">
<div className="flex flex-col items-start gap-0.5">
<span className="text-heading- font-heading- text-text-neutral-primary">{userDisplayName(user)}</span>
{roleLabel ? (
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">{roleLabel}</span>
) : null}
{roleLabel ? <span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">{roleLabel}</span> : null}
</div>
<div className="flex items-center gap-2">
{/* Bild ändern (Avatar-Upload, autosubmit per onPick) */}
@@ -215,7 +217,14 @@ export default function MyProfileScreen({
<input type="hidden" name="firstName" value={user.firstName ?? ""} readOnly />
<input type="hidden" name="lastName" value={user.lastName ?? ""} readOnly />
<input type="hidden" name="avatar" value={avatarData} readOnly />
<input ref={fileInput} type="file" accept="image/png,image/jpeg" className="hidden" onChange={onPickAvatar} data-ui-id="ui.settings.profile.avatarInput" />
<input
ref={fileInput}
type="file"
accept="image/png,image/jpeg"
className="hidden"
onChange={onPickAvatar}
data-ui-id="ui.settings.profile.avatarInput"
/>
<Button
type="button"
variant="secondary"
@@ -249,19 +258,18 @@ export default function MyProfileScreen({
</div>
</div>
</div>
<div className="flex w-px flex-none flex-col items-center self-stretch bg-surface-neutral-tertiary mobile:hidden" />
<div className="flex w-80 flex-none flex-col items-start gap-2 mobile:w-full">
<div className="bg-surface-neutral-tertiary mobile:hidden flex w-px flex-none flex-col items-center self-stretch" />
<div className="mobile:w-full flex w-80 flex-none flex-col items-start gap-2">
<span className="text-body-small-semibold-150 font-body-small-semibold-150 text-text-neutral-tertiary">
{t("settings.profile.security.accountSecurity")}
</span>
<div className="flex w-full items-center gap-3 rounded-md bg-surface-neutral-primary px-3 py-2">
<div className="bg-surface-neutral-primary flex w-full items-center gap-3 rounded-md px-3 py-2">
<FeatherShieldCheck
className={
"text-body-default-regular-0 font-body-default-regular-0 " +
(mfaEnabled ? "text-icon-feedback-positive" : "text-icon-neutral-tertiary")
"text-body-default-regular-0 font-body-default-regular-0 " + (mfaEnabled ? "text-icon-feedback-positive" : "text-icon-neutral-tertiary")
}
/>
<div className="flex grow shrink-0 basis-0 flex-col items-start">
<div className="flex shrink-0 grow basis-0 flex-col items-start">
<span className="text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-primary">
{t("settings.profile.security.twoFactorShort")}
</span>
@@ -279,11 +287,11 @@ export default function MyProfileScreen({
</div>
{/* Reihe 2 — Basis info + Login info */}
<div className="flex w-full items-start gap-4 mobile:flex-col">
<div className="mobile:flex-col flex w-full items-start gap-4">
<NeutralCard>
<span className="text-heading- font-heading- text-text-neutral-primary">{t("settings.profile.basicInfo.title")}</span>
<CardDivider />
<Form method="post" replace className="flex w-full flex-col items-start gap-3">
<Form method="post" replace className="flex w-full flex-col items-start gap-3" data-ui-id="ui.settings.profile.form">
<input type="hidden" name="csrf" value={csrf} readOnly />
<input type="hidden" name="action" value="profile" readOnly />
{/* Avatar mitsenden, damit Speichern des Namens das vorhandene Bild nicht löscht. */}
@@ -293,6 +301,7 @@ export default function MyProfileScreen({
<TextInput.Input
name="firstName"
required
aria-label={t("models.user.firstName")}
defaultValue={user.firstName ?? ""}
placeholder={t("account.shared.firstNamePlaceholder")}
data-ui-id="ui.settings.profile.firstName"
@@ -304,6 +313,7 @@ export default function MyProfileScreen({
<TextInput className="h-auto w-56 flex-none">
<TextInput.Input
name="lastName"
aria-label={t("models.user.lastName")}
defaultValue={user.lastName ?? ""}
placeholder={t("account.shared.lastNamePlaceholder")}
data-ui-id="ui.settings.profile.lastName"
@@ -313,7 +323,14 @@ export default function MyProfileScreen({
<CardDivider />
<SettingRow label={t("settings.profile.basicInfo.phone")}>
<TextInput disabled className="h-auto w-56 flex-none" type="tel">
<TextInput.Input type="tel" disabled readOnly value={user.phone ?? ""} data-ui-id="ui.settings.profile.phone" />
<TextInput.Input
type="tel"
disabled
readOnly
aria-label={t("settings.profile.basicInfo.phone")}
value={user.phone ?? ""}
data-ui-id="ui.settings.profile.phone"
/>
</TextInput>
</SettingRow>
<CardDivider />
@@ -322,13 +339,21 @@ export default function MyProfileScreen({
disabled
className="h-auto w-56 flex-none"
placeholder={t("settings.profile.basicInfo.department")}
triggerAriaLabel={t("settings.profile.basicInfo.department")}
data-ui-id="ui.settings.profile.department"
/>
</SettingRow>
<CardDivider />
<SettingRow label={t("models.user.role")} helpText={t("settings.profile.basicInfo.roleAssignedByAdmin")}>
<TextInput disabled className="h-auto w-56 flex-none">
<TextInput.Input disabled readOnly value={roleLabel} placeholder={t("models.user.role")} data-ui-id="ui.settings.profile.role" />
<TextInput.Input
disabled
readOnly
aria-label={t("models.user.role")}
value={roleLabel}
placeholder={t("models.user.role")}
data-ui-id="ui.settings.profile.role"
/>
</TextInput>
</SettingRow>
<div className="flex w-full items-center justify-end">
@@ -345,15 +370,20 @@ export default function MyProfileScreen({
<CardDivider />
<SettingRow label={t("settings.profile.loginInfo.email")}>
<TextInput disabled className="h-auto w-72 flex-none" type="email">
<TextInput.Input type="email" disabled readOnly value={user.email} data-ui-id="ui.settings.profile.email" />
<TextInput.Input
type="email"
disabled
readOnly
aria-label={t("settings.profile.loginInfo.email")}
value={user.email}
data-ui-id="ui.settings.profile.email"
/>
</TextInput>
</SettingRow>
<CardDivider />
<SettingRow label={t("settings.profile.password")}>
<div className="flex items-center gap-3">
<span className="text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-secondary tracking-widest">
••••••••••
</span>
<span className="text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-secondary tracking-widest">••••••••••</span>
<Button size="small" onClick={() => setPwOpen(true)} data-ui-id="ui.settings.profile.password.open">
{t("settings.profile.changePassword")}
</Button>
@@ -374,6 +404,9 @@ export default function MyProfileScreen({
</div>
</div>
{cropSource ? (
<AvatarCropDialog source={cropSource} submitting={submitting} onCancel={() => setCropSource(null)} onConfirm={onCropConfirmed} />
) : null}
{pwOpen ? (
actionData?.passwordLocked ? (
<ChangePasswordLockedDialog retryLabel={actionData.passwordLockedRetryLabel} onClose={() => setPwOpen(false)} />
@@ -398,17 +431,27 @@ export default function MyProfileScreen({
);
}
function ModalShell({ children, dataUiId, center = false }: { children: React.ReactNode; dataUiId: string; center?: boolean }) {
function ModalShell({
children,
dataUiId,
center = false,
onClose,
}: {
children: React.ReactNode;
dataUiId: string;
center?: boolean;
onClose: () => void;
}) {
return (
<div className="fixed inset-0 z-50 flex flex-col items-center justify-center gap-2 bg-surface-neutral-overlay px-4 py-4" data-ui-id={dataUiId}>
<DialogOverlay dataUiId={dataUiId} onClose={onClose}>
<div
className={`flex w-full max-w-[480px] flex-col gap-6 rounded-md border border-solid border-border-default bg-surface-neutral-modal px-6 py-6 shadow-lg mobile:max-w-full ${
className={`border-border-default bg-surface-neutral-modal mobile:max-w-full flex w-full max-w-[480px] flex-col gap-6 rounded-md border border-solid px-6 py-6 shadow-lg ${
center ? "items-center text-center" : "items-start"
}`}
>
{children}
</div>
</div>
</DialogOverlay>
);
}
@@ -443,32 +486,37 @@ function ChangePasswordDialog({
const strength = passwordStrength(pw);
const fullName = [user.firstName, user.lastName].filter(Boolean).join(" ");
return (
<DialogOverlay dataUiId="ui.settings.profile.password.modal">
<div className="flex w-full flex-col items-start gap-6 rounded-lg border border-solid border-border-default bg-surface-neutral-secondary px-6 py-6 shadow-lg max-w-[480px] relative mobile:px-4 mobile:py-5">
<DialogOverlay dataUiId="ui.settings.profile.password.modal" onClose={onClose}>
<div className="border-border-default bg-surface-neutral-secondary mobile:px-4 mobile:py-5 relative flex w-full max-w-[480px] flex-col items-start gap-6 rounded-lg border border-solid px-6 py-6 shadow-lg">
<IconButton
className="absolute right-3 top-3"
className="absolute top-3 right-3"
variant="ghost"
size="small"
icon={<FeatherX />}
aria-label={t("shared.close")}
onClick={onClose}
data-ui-id="ui.settings.profile.password.close"
/>
<div className="flex w-full flex-col items-center justify-center gap-1">
<div className="flex h-11 w-11 flex-none items-center justify-center rounded-round bg-surface-feedback-subtle-information">
<div className="rounded-round bg-surface-feedback-subtle-information flex h-11 w-11 flex-none items-center justify-center">
<FeatherShieldCheck className="text-heading- font-heading- text-icon-feedback-information" />
</div>
<span className="w-full text-heading- font-heading- text-text-neutral-primary text-center">{t("settings.profile.reauth.title")}</span>
<span className="w-full text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary text-center">
<span className="text-heading- font-heading- text-text-neutral-primary w-full text-center">{t("settings.profile.reauth.title")}</span>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary w-full text-center">
{t("settings.profile.reauth.subtitle")}
</span>
</div>
<div className="flex w-full items-center gap-3 rounded-md border border-solid border-border-default bg-surface-neutral-secondary px-4 py-3">
<Avatar size="medium" image={user.avatar ?? undefined}>{initials(user)}</Avatar>
<div className="flex grow shrink-0 basis-0 flex-col items-start">
<span className="w-full text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-primary">{fullName || user.email}</span>
<span className="w-full text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary">{user.email}</span>
<div className="border-border-default bg-surface-neutral-secondary flex w-full items-center gap-3 rounded-md border border-solid px-4 py-3">
<Avatar size="medium" image={user.avatar ?? undefined}>
{initials(user)}
</Avatar>
<div className="flex shrink-0 grow basis-0 flex-col items-start">
<span className="text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-primary w-full">{fullName || user.email}</span>
<span className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary w-full">{user.email}</span>
</div>
<BadgeFeedback farbe="subtle-neutral" size="small">{t("settings.profile.reauth.currentAccount")}</BadgeFeedback>
<BadgeFeedback farbe="subtle-neutral" size="small">
{t("settings.profile.reauth.currentAccount")}
</BadgeFeedback>
</div>
<Form method="post" replace className="flex w-full flex-col items-start gap-6">
<input type="hidden" name="csrf" value={csrf} readOnly />
@@ -495,18 +543,32 @@ function ChangePasswordDialog({
data-ui-id="ui.settings.profile.password.new"
/>
</TextInput>
<Progress className="h-auto w-full flex-none" hideLabel value={strength} state={strength >= 80 ? "success" : undefined} />
<span className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary">{t("settings.profile.passwordDialog.hint")}</span>
<Progress
className="h-auto w-full flex-none"
hideLabel
value={strength}
state={strength >= 80 ? "success" : undefined}
aria-label={t("settings.profile.passwordDialog.hint")}
/>
<span className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary">
{t("settings.profile.passwordDialog.hint")}
</span>
</div>
<TextInput className="h-auto w-full flex-none" showLabel label={t("settings.profile.passwordDialog.confirm")} type="password">
<TextInput.Input name="passwordNewConfirm" type="password" required autoComplete="new-password" data-ui-id="ui.settings.profile.password.confirm" />
</TextInput>
{error ? <span className="text-body-small-regular-0 font-body-small-regular-0 text-text-feedback-negative">{error}</span> : null}
<div className="flex w-full items-center justify-end gap-2 mobile:flex-col-reverse">
<Button className="h-9 grow shrink-0 basis-0" type="button" variant="secondary" onClick={onClose} data-ui-id="ui.settings.profile.password.cancel">
<div className="mobile:flex-col-reverse flex w-full items-center justify-end gap-2">
<Button className="h-9 shrink-0 grow basis-0" type="button" variant="secondary" onClick={onClose} data-ui-id="ui.settings.profile.password.cancel">
{t("shared.cancel")}
</Button>
<Button className="h-9 grow shrink-0 basis-0" type="submit" iconRight={<FeatherArrowRight />} loading={submitting} data-ui-id="ui.settings.profile.password.submit">
<Button
className="h-9 shrink-0 grow basis-0"
type="submit"
iconRight={<FeatherArrowRight />}
loading={submitting}
data-ui-id="ui.settings.profile.password.submit"
>
{t("settings.profile.mfa.setup.next")}
</Button>
</div>
@@ -519,13 +581,13 @@ function ChangePasswordDialog({
function ChangePasswordLockedDialog({ retryLabel, onClose }: { retryLabel?: string; onClose: () => void }) {
const { t } = useTranslation();
return (
<DialogOverlay dataUiId="ui.settings.profile.password.locked">
<Card className="max-w-[480px] mobile:gap-6 mobile:shadow-lg mobile:px-4 mobile:py-5">
<DialogOverlay dataUiId="ui.settings.profile.password.locked" onClose={onClose}>
<Card className="mobile:gap-6 mobile:shadow-lg mobile:px-4 mobile:py-5 max-w-[480px]">
<div className="flex w-full flex-col items-center gap-4">
<IconWithBackground variant="warning" size="extra-large" round={true} icon={<FeatherShieldAlert />} />
<div className="flex w-full flex-col items-center gap-1">
<span className="w-full text-heading- font-heading- text-text-neutral-primary text-center">{t("settings.profile.changePasswordLocked.title")}</span>
<span className="w-full text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary text-center">
<span className="text-heading- font-heading- text-text-neutral-primary w-full text-center">{t("settings.profile.changePasswordLocked.title")}</span>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary w-full text-center">
{t("settings.profile.changePasswordLocked.subtitle")}
</span>
</div>
@@ -555,15 +617,31 @@ function ChangePasswordLockedDialog({ retryLabel, onClose }: { retryLabel?: stri
);
}
function DialogOverlay({ children, dataUiId }: { children: React.ReactNode; dataUiId: string }) {
// Entspricht Davids DialogLayout/Dialog-Overlay (zentrierte Card auf abgedunkeltem Hintergrund).
function DialogOverlay({ children, dataUiId, onClose }: { children: React.ReactNode; dataUiId: string; onClose: () => void }) {
// Davids DialogLayout (zentrierte Card auf abgedunkeltem Hintergrund) — aber
// durch die geteilte Dialog-Komponente, wie jeder andere Pop-up im Produkt.
// Vorher war das ein handgebautes `fixed inset-0` mitten im Seiteninhalt: das
// dunkelte nur den Inhaltsbereich ab, weil Sidebar und Kopfleiste auf
// derselben z-Ebene darueber lagen, und brachte weder Fokus-Falle noch
// Escape-to-close mit. Die Dialog-Komponente portalisiert nach document.body
// und loest das strukturell.
//
// Dialog.Content bleibt hier bewusst transparent und randlos: die Karte
// darin ist Davids Screen und bringt Rahmen, Flaeche und Schatten selbst mit.
return (
<div
className="fixed inset-0 z-50 flex flex-col items-center justify-center gap-2 bg-surface-neutral-overlay px-4 py-4"
data-ui-id={dataUiId}
<Dialog
open
onOpenChange={(open: boolean) => {
if (!open) onClose();
}}
>
{children}
</div>
<Dialog.Content
className="max-h-[90vh] w-auto min-w-0 max-w-[92vw] overflow-auto border-none bg-transparent shadow-none"
data-ui-id={dataUiId}
>
{children}
</Dialog.Content>
</Dialog>
);
}
@@ -591,7 +669,7 @@ function TwoFaModal({
onClose: () => void;
}) {
const { t, i18n } = useTranslation();
const secret = otpauthUri ? new URLSearchParams(otpauthUri.split("?")[1] ?? "").get("secret") ?? "" : "";
const secret = otpauthUri ? (new URLSearchParams(otpauthUri.split("?")[1] ?? "").get("secret") ?? "") : "";
const groupedSecret = secret.replace(/(.{4})/g, "$1 ").trim();
const [digits, setDigits] = useState<string[]>(Array(6).fill(""));
const code = digits.join("");
@@ -607,15 +685,15 @@ function TwoFaModal({
if (step === "manage") {
const activatedLabel =
enabledAt != null
? t("settings.profile.mfa.manage.activatedAt", { date: new Date(enabledAt).toLocaleDateString(i18n.language) })
? t("settings.profile.mfa.manage.activatedAt", { date: formatDate(enabledAt, i18n.language) })
: t("settings.profile.mfa.status.enabled");
return (
<DialogOverlay dataUiId="ui.settings.profile.mfa.manage.dialog">
<div className="flex h-auto w-auto min-w-[384px] max-w-[576px] max-h-[90vh] flex-none flex-col items-start gap-2 overflow-auto rounded-md border border-solid border-border-default bg-surface-neutral-modal shadow-lg mobile:w-full mobile:min-w-0">
<div className="flex w-full items-start gap-4 px-4 pt-4 mobile:pb-4">
<div className="flex grow shrink-0 basis-0 flex-col items-start gap-1">
<span className="w-full text-heading- font-heading- text-text-neutral-primary">{t("settings.profile.mfa.title")}</span>
<span className="w-full text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
<DialogOverlay dataUiId="ui.settings.profile.mfa.manage.dialog" onClose={onClose}>
<div className="border-border-default bg-surface-neutral-modal mobile:w-full mobile:min-w-0 flex h-auto max-h-[90vh] w-auto max-w-[576px] min-w-[384px] flex-none flex-col items-start gap-2 overflow-auto rounded-md border border-solid shadow-lg">
<div className="mobile:pb-4 flex w-full items-start gap-4 px-4 pt-4">
<div className="flex shrink-0 grow basis-0 flex-col items-start gap-1">
<span className="text-heading- font-heading- text-text-neutral-primary w-full">{t("settings.profile.mfa.title")}</span>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary w-full">
{t("settings.profile.mfa.manage.subtitle")}
</span>
</div>
@@ -623,11 +701,13 @@ function TwoFaModal({
<IconButton variant="ghost" icon={<FeatherX />} onClick={onClose} data-ui-id="ui.settings.profile.mfa.manage.close" />
</div>
</div>
<div className="flex w-full flex-col items-start gap-3 px-4 pb-4 mobile:pt-4">
<div className="flex w-full items-end justify-end gap-4 rounded-md border border-solid border-border-negative-subtle bg-surface-feedback-subtle-negative px-4 py-3 mobile:flex-col mobile:items-start mobile:justify-start mobile:gap-3">
<div className="flex grow shrink-0 basis-0 flex-col items-start gap-1">
<span className="text-body-small-semibold-0 font-body-small-semibold-0 text-text-neutral-primary">{t("settings.profile.mfa.disable.title")}</span>
<span className="w-full text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary">
<div className="mobile:pt-4 flex w-full flex-col items-start gap-3 px-4 pb-4">
<div className="border-border-negative-subtle bg-surface-feedback-subtle-negative mobile:flex-col mobile:items-start mobile:justify-start mobile:gap-3 flex w-full items-end justify-end gap-4 rounded-md border border-solid px-4 py-3">
<div className="flex shrink-0 grow basis-0 flex-col items-start gap-1">
<span className="text-body-small-semibold-0 font-body-small-semibold-0 text-text-neutral-primary">
{t("settings.profile.mfa.disable.title")}
</span>
<span className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary w-full">
{t("settings.profile.mfa.manage.deactivateHint")}
</span>
</div>
@@ -643,15 +723,17 @@ function TwoFaModal({
</Button>
</div>
<div className="flex w-full flex-col items-start gap-1">
<span className="text-body-extra-small-semibold-150 font-body-extra-small-semibold-150 uppercase tracking-wider text-text-neutral-tertiary">
<span className="text-body-extra-small-semibold-150 font-body-extra-small-semibold-150 text-text-neutral-tertiary tracking-wider uppercase">
{t("settings.profile.mfa.manage.methodsLabel")}
</span>
<div className="flex w-full flex-col items-start rounded-md border border-solid border-border-default bg-surface-neutral-secondary">
<div className="flex w-full items-center gap-3 px-4 py-3 mobile:flex-col mobile:items-start">
<div className="border-border-default bg-surface-neutral-secondary flex w-full flex-col items-start rounded-md border border-solid">
<div className="mobile:flex-col mobile:items-start flex w-full items-center gap-3 px-4 py-3">
<IconWithBackground variant="neutral" size="large" icon={<FeatherSmartphone />} />
<div className="flex grow shrink-0 basis-0 flex-col items-start gap-1">
<div className="flex shrink-0 grow basis-0 flex-col items-start gap-1">
<div className="flex items-center gap-2">
<span className="text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary">{t("settings.profile.mfa.authenticatorApp")}</span>
<span className="text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary">
{t("settings.profile.mfa.authenticatorApp")}
</span>
</div>
<span className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary">{activatedLabel}</span>
</div>
@@ -688,23 +770,29 @@ function TwoFaModal({
if (step === "success") {
return (
<ModalShell dataUiId="ui.settings.profile.mfa.success" center>
<FeatherCheckCircle className="text-[48px] font-[400] text-icon-feedback-positive" />
<ModalShell dataUiId="ui.settings.profile.mfa.success" center onClose={onClose}>
<FeatherCheckCircle className="text-icon-feedback-positive text-[48px] font-[400]" />
<div className="flex w-full flex-col items-center gap-2">
<span className="text-heading- font-heading- text-text-neutral-primary">{t("settings.profile.mfa.success.title")}</span>
<span className="text-body-default-regular-150 font-body-default-regular-150 text-text-neutral-secondary">{t("settings.profile.mfa.success.subtitle")}</span>
<span className="text-body-default-regular-150 font-body-default-regular-150 text-text-neutral-secondary">
{t("settings.profile.mfa.success.subtitle")}
</span>
</div>
{recoveryCodes && recoveryCodes.length > 0 ? (
<div className="flex w-full flex-col items-start gap-2 rounded-md border border-solid border-border-default bg-surface-neutral-primary px-4 py-4">
<div className="border-border-default bg-surface-neutral-primary flex w-full flex-col items-start gap-2 rounded-md border border-solid px-4 py-4">
<span className="text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-secondary">{t("settings.profile.mfa.recoveryCodes")}</span>
<div className="grid w-full grid-cols-2 gap-1">
{recoveryCodes.map((code) => (
<span key={code} className="font-mono text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-primary">{code}</span>
<span key={code} className="text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-primary font-mono">
{code}
</span>
))}
</div>
</div>
) : null}
<Button className="h-10 w-full flex-none" variant="primary" onClick={onClose} data-ui-id="ui.settings.profile.mfa.done">{t("settings.profile.mfa.success.done")}</Button>
<Button className="h-10 w-full flex-none" variant="primary" onClick={onClose} data-ui-id="ui.settings.profile.mfa.done">
{t("settings.profile.mfa.success.done")}
</Button>
</ModalShell>
);
}
@@ -713,22 +801,22 @@ function TwoFaModal({
// (Der Passwort-Gate-Step "password" läuft davor, da startTotpEnrollment das aktuelle Passwort verlangt.)
if (step === "qr") {
return (
<DialogOverlay dataUiId="ui.settings.profile.mfa.setup">
<DialogOverlay dataUiId="ui.settings.profile.mfa.setup" onClose={onClose}>
<Card
className="h-auto w-auto min-w-[384px] max-w-[576px] max-h-[90vh] overflow-auto mobile:w-full mobile:min-w-0 mobile:px-4 mobile:py-4 mobile:shadow-lg"
className="mobile:w-full mobile:min-w-0 mobile:px-4 mobile:py-4 mobile:shadow-lg h-auto max-h-[90vh] w-auto max-w-[576px] min-w-[384px] overflow-auto"
size="large"
>
<div className="flex w-full items-start justify-between">
<div className="flex grow shrink-0 basis-0 flex-col items-center gap-1">
<div className="flex shrink-0 grow basis-0 flex-col items-center gap-1">
<span className="text-heading- font-heading- text-text-neutral-primary text-center">{t("settings.profile.mfa.manage.addDevice")}</span>
<span className="w-full text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary text-center">
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary w-full text-center">
{t("settings.profile.mfa.add.subtitle")}
</span>
</div>
<IconButton variant="ghost" size="small" icon={<FeatherX />} onClick={onClose} data-ui-id="ui.settings.profile.mfa.setup.close" />
</div>
<div className="flex w-full flex-col items-center gap-2">
<div className="flex h-44 w-44 flex-none items-center justify-center rounded-md border border-solid border-border-default bg-surface-neutral-secondary px-2 py-2">
<div className="border-border-default bg-surface-neutral-secondary flex h-44 w-44 flex-none items-center justify-center rounded-md border border-solid px-2 py-2">
{otpauthUri ? <QRCodeSVG className="h-40 w-40 flex-none" value={otpauthUri} size={160} /> : null}
</div>
<span className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary text-center">
@@ -738,13 +826,21 @@ function TwoFaModal({
{secret ? (
<>
<div className="flex w-full items-center gap-2.5">
<div className="flex h-px grow shrink-0 basis-0 flex-col items-center bg-border-default" />
<span className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary">{t("settings.profile.mfa.setup.manualKey")}</span>
<div className="flex h-px grow shrink-0 basis-0 flex-col items-center bg-border-default" />
<div className="bg-border-default flex h-px shrink-0 grow basis-0 flex-col items-center" />
<span className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary">
{t("settings.profile.mfa.setup.manualKey")}
</span>
<div className="bg-border-default flex h-px shrink-0 grow basis-0 flex-col items-center" />
</div>
<div className="flex w-full items-center justify-between rounded-md border border-solid border-border-default bg-surface-neutral-secondary px-1 py-1">
<span className="grow shrink-0 basis-0 text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-primary text-center">{groupedSecret}</span>
<CopyToClipboardButton clipboardText={secret} tooltipText={t("settings.profile.mfa.add.copyKey")} />
<div className="border-border-default bg-surface-neutral-secondary flex w-full items-center justify-between rounded-md border border-solid px-1 py-1">
<span className="text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-primary shrink-0 grow basis-0 text-center">
{groupedSecret}
</span>
<CopyToClipboardButton
clipboardText={secret}
tooltipText={t("settings.profile.mfa.add.copyKey")}
successKey="settings.profile.mfa.add.keyCopied"
/>
</div>
</>
) : null}
@@ -753,7 +849,9 @@ function TwoFaModal({
<input type="hidden" name="action" value="confirmTotpEnrollment" readOnly />
<input type="hidden" name="code" value={code} readOnly />
<div className="flex w-full flex-col items-center gap-2">
<span className="text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-secondary text-center">{t("settings.profile.mfa.add.codeLabel")}</span>
<span className="text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-secondary text-center">
{t("settings.profile.mfa.add.codeLabel")}
</span>
<div className="flex w-full flex-col items-center gap-2 px-1 py-1">
<InputOtp state={mfaError ? "error" : "default"} title="" helperText={mfaError ?? ""}>
{Array.from({ length: 6 }).map((_, i) => (
@@ -771,7 +869,7 @@ function TwoFaModal({
</InputOtp>
</div>
</div>
<div className="flex w-full items-center justify-end gap-2 mobile:flex-col-reverse">
<div className="mobile:flex-col-reverse flex w-full items-center justify-end gap-2">
<Button type="button" className="mobile:w-full" variant="secondary" onClick={onClose} data-ui-id="ui.settings.profile.mfa.setup.cancel">
{t("shared.cancel")}
</Button>
@@ -796,38 +894,51 @@ function TwoFaModal({
// das bestehende disableTotpEnrollment verifiziert das Passwort -> Bestätigung bleibt Passwort-basiert.
if (step === "disable") {
return (
<DialogOverlay dataUiId="ui.settings.profile.mfa.disable">
<Card className="w-full max-w-[480px] max-h-[90vh] overflow-auto mobile:gap-6 mobile:px-4 mobile:py-5 mobile:shadow-lg">
<DialogOverlay dataUiId="ui.settings.profile.mfa.disable" onClose={onClose}>
<Card className="mobile:gap-6 mobile:px-4 mobile:py-5 mobile:shadow-lg max-h-[90vh] w-full max-w-[480px] overflow-auto">
<div className="flex w-full flex-col items-center justify-center gap-1">
<IconWithBackground variant="destructive" size="large" round={true} icon={<FeatherShieldOff />} />
<span className="w-full text-heading- font-heading- text-text-neutral-primary text-center">{t("settings.profile.mfa.deactivate.title")}</span>
<span className="w-full text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary text-center">
<span className="text-heading- font-heading- text-text-neutral-primary w-full text-center">{t("settings.profile.mfa.deactivate.title")}</span>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary w-full text-center">
{t("settings.profile.mfa.deactivate.subtitle")}
</span>
</div>
<div className="flex w-full flex-col items-center justify-center gap-2 rounded-md border border-solid border-border-negative-subtle bg-surface-feedback-subtle-negative px-4 py-3">
<div className="border-border-negative-subtle bg-surface-feedback-subtle-negative flex w-full flex-col items-center justify-center gap-2 rounded-md border border-solid px-4 py-3">
<div className="flex w-full items-center justify-center gap-2">
<span className="grow shrink-0 basis-0 text-body-small-semibold-150 font-body-small-semibold-150 text-text-feedback-negative text-center">
<span className="text-body-small-semibold-150 font-body-small-semibold-150 text-text-feedback-negative shrink-0 grow basis-0 text-center">
{t("settings.profile.mfa.deactivate.consequencesTitle")}
</span>
</div>
<div className="flex w-full flex-col items-start gap-2">
<span className="w-full text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-secondary">{t("settings.profile.mfa.deactivate.consequence1")}</span>
<span className="w-full text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-secondary">{t("settings.profile.mfa.deactivate.consequence2")}</span>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-secondary w-full">
{t("settings.profile.mfa.deactivate.consequence1")}
</span>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-secondary w-full">
{t("settings.profile.mfa.deactivate.consequence2")}
</span>
</div>
</div>
<Form method="post" replace className="contents">
<input type="hidden" name="csrf" value={csrf} readOnly />
<input type="hidden" name="action" value="disableTotpEnrollment" readOnly />
<div className="flex w-full flex-col items-center justify-center gap-2">
<span className="text-body-small-medium-150 font-body-small-medium-150 text-text-neutral-secondary">{t("settings.profile.passwordDialog.current")}</span>
<span className="text-body-small-medium-150 font-body-small-medium-150 text-text-neutral-secondary">
{t("settings.profile.passwordDialog.current")}
</span>
<TextInput className="h-auto w-full flex-none" type="password">
<TextInput.Input name="passwordCurrent" type="password" required autoFocus autoComplete="current-password" data-ui-id="ui.settings.profile.mfa.disablePassword" />
<TextInput.Input
name="passwordCurrent"
type="password"
required
autoFocus
autoComplete="current-password"
data-ui-id="ui.settings.profile.mfa.disablePassword"
/>
</TextInput>
{mfaError ? <span className="text-body-small-regular-0 font-body-small-regular-0 text-text-feedback-negative">{mfaError}</span> : null}
</div>
<div className="flex h-px w-full flex-none flex-col items-center bg-border-default" />
<div className="flex w-full items-center justify-end gap-2 mobile:flex-col-reverse">
<div className="bg-border-default flex h-px w-full flex-none flex-col items-center" />
<div className="mobile:flex-col-reverse flex w-full items-center justify-end gap-2">
<Button type="button" className="mobile:w-full" variant="secondary" onClick={onClose} data-ui-id="ui.settings.profile.mfa.disableCancel">
{t("shared.cancel")}
</Button>
@@ -850,10 +961,12 @@ function TwoFaModal({
// step === "password" — Setup-Gate (Action verlangt aktuelles Passwort, bevor der QR erzeugt wird)
return (
<ModalShell dataUiId="ui.settings.profile.mfa.gate">
<ModalShell dataUiId="ui.settings.profile.mfa.gate" onClose={onClose}>
<div className="flex w-full flex-col items-start gap-2">
<span className="text-heading- font-heading- text-text-neutral-primary">{t("settings.profile.mfa.setup.title")}</span>
<span className="text-body-default-regular-150 font-body-default-regular-150 text-text-neutral-secondary">{t("settings.profile.mfa.gate.subtitle")}</span>
<span className="text-body-default-regular-150 font-body-default-regular-150 text-text-neutral-secondary">
{t("settings.profile.mfa.gate.subtitle")}
</span>
</div>
<Form method="post" replace className="flex w-full flex-col items-start gap-4">
<input type="hidden" name="csrf" value={csrf} readOnly />
@@ -862,9 +975,13 @@ function TwoFaModal({
<TextInput.Input name="passwordCurrent" type="password" required autoComplete="current-password" data-ui-id="ui.settings.profile.mfa.gatePassword" />
</TextInput>
{mfaError ? <span className="text-body-small-regular-0 font-body-small-regular-0 text-text-feedback-negative">{mfaError}</span> : null}
<div className="flex w-full items-center justify-end gap-2 mobile:flex-col-reverse mobile:items-stretch">
<Button type="button" variant="tertiary" onClick={onClose}>{t("shared.cancel")}</Button>
<Button type="submit" variant="primary" loading={submitting} data-ui-id="ui.settings.profile.mfa.gateSubmit">{t("settings.profile.mfa.setup.next")}</Button>
<div className="mobile:flex-col-reverse mobile:items-stretch flex w-full items-center justify-end gap-2">
<Button type="button" variant="tertiary" onClick={onClose}>
{t("shared.cancel")}
</Button>
<Button type="submit" variant="primary" loading={submitting} data-ui-id="ui.settings.profile.mfa.gateSubmit">
{t("settings.profile.mfa.setup.next")}
</Button>
</div>
</Form>
</ModalShell>
@@ -0,0 +1,303 @@
// @vitest-environment jsdom
import "@testing-library/jest-dom/vitest";
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import React from "react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import RegisterScreen, { type RegistrationPlanOptionData } from "./RegisterScreen";
const rootDataState = vi.hoisted(() => ({ requireEmailVerification: true }));
globalThis.ResizeObserver =
globalThis.ResizeObserver ??
class ResizeObserver {
observe() {}
unobserve() {}
disconnect() {}
};
vi.mock("react-router", async (importOriginal) => {
const actual = await importOriginal<typeof import("react-router")>();
return {
...actual,
Form: React.forwardRef<HTMLFormElement, React.FormHTMLAttributes<HTMLFormElement>>(function TestForm({ children, ...props }, ref) {
return (
<form ref={ref} {...props}>
{children}
</form>
);
}),
Link: ({ children, to, ...props }: React.AnchorHTMLAttributes<HTMLAnchorElement> & { to: string }) => (
<a href={to} {...props}>
{children}
</a>
),
useNavigate: () => vi.fn(),
useNavigation: () => ({ state: "idle" }),
useSearchParams: () => [new URLSearchParams()],
};
});
vi.mock("react-i18next", () => ({
useTranslation: () => ({ t: (key: string) => key }),
}));
vi.mock("~/utils/data/useRootData", () => ({
useRootData: () => ({
csrf: "csrf-token",
appConfiguration: {
auth: {
requireEmailVerification: rootDataState.requireEmailVerification,
requireOrganization: true,
requireName: true,
authMethods: { emailPassword: { enabled: true } },
captcha: { enabled: true, provider: "cap" },
},
},
}),
}));
vi.mock("~/components/captcha/Captcha", () => ({
default: ({ onStatusChange }: { onStatusChange?: (status: "pending" | "solved" | "error") => void }) => {
React.useEffect(() => onStatusChange?.("pending"), [onStatusChange]);
return (
<button type="button" data-ui-id="ui.captcha.mount" aria-label="captcha" onClick={() => onStatusChange?.("solved")}>
captcha
</button>
);
},
}));
const core: RegistrationPlanOptionData = {
planId: "product_starter",
planCode: "starter",
titleKey: "Core",
descriptionKey: "Core plan",
priceId: "price_starter",
amountCents: 19_900,
baseAmountCents: 19_900,
currency: "EUR",
billingPeriod: 3,
includedOfficeSeatQuantity: 2,
includedFieldSeatQuantity: 5,
includedStorageGb: 100,
storagePerAdditionalSeatGb: 10,
extraOfficeSeatQuantity: 0,
extraFieldSeatQuantity: 0,
recommended: true,
};
const swarm: RegistrationPlanOptionData = {
...core,
planId: "product_pro",
planCode: "pro",
titleKey: "Swarm",
descriptionKey: "Swarm plan",
priceId: "price_pro",
amountCents: 49_900,
baseAmountCents: 49_900,
includedOfficeSeatQuantity: 5,
includedFieldSeatQuantity: 15,
includedStorageGb: 500,
storagePerAdditionalSeatGb: 20,
recommended: true,
};
describe("RegisterScreen plan advisor", () => {
beforeEach(() => {
rootDataState.requireEmailVerification = true;
vi.stubGlobal(
"fetch",
vi.fn(async (input: RequestInfo | URL) => {
const url = new URL(String(input), "https://app.example.test");
const largeTeam = url.searchParams.get("office") === "5" && url.searchParams.get("field") === "15";
return Response.json(
largeTeam
? {
plans: [{ ...core, amountCents: 62_600, extraOfficeSeatQuantity: 3, extraFieldSeatQuantity: 10, recommended: false }, swarm],
selectedPriceId: "price_pro",
recommendedPriceId: "price_pro",
officeSeatQuantity: 5,
fieldSeatQuantity: 15,
}
: {
plans: [core, { ...swarm, recommended: false }],
selectedPriceId: "price_starter",
recommendedPriceId: "price_starter",
officeSeatQuantity: 1,
fieldSeatQuantity: 0,
}
);
})
);
});
it("blocks the plan step until every visible password requirement is met", () => {
rootDataState.requireEmailVerification = false;
const { container } = render(
<RegisterScreen
creationRequestKey="d7077797-054b-497a-b1ce-8e4f36257a96"
subscriptionPlans={[core, { ...swarm, recommended: false }]}
selectedSubscriptionPriceId="price_starter"
recommendedSubscriptionPriceId="price_starter"
initialOfficeSeatQuantity={1}
initialFieldSeatQuantity={0}
passwordPolicy={{ minLength: 12, requireUpper: true, requireLower: true, requireDigit: true, requireSpecial: true }}
/>
);
fireEvent.change(container.querySelector('input[name="email"]')!, { target: { value: "ada@example.test" } });
fireEvent.change(container.querySelector('input[name="password"]')!, { target: { value: "TooShort1!" } });
fireEvent.change(container.querySelector('input[name="first-name"]')!, { target: { value: "Ada" } });
fireEvent.change(container.querySelector('input[name="last-name"]')!, { target: { value: "Lovelace" } });
fireEvent.change(container.querySelector('input[name="company"]')!, { target: { value: "Analytical Engines" } });
fireEvent.click(screen.getByRole("button", { name: "account.register.continueToTeam" }));
expect(container.querySelector('[data-ui-id="ui.auth.register.accountStep"]')).not.toHaveClass("hidden");
expect(screen.getByRole("alert")).toHaveTextContent("account.register.passwordRequirements.fixBeforeContinue");
expect(container.querySelector('input[name="password"]')).toHaveFocus();
fireEvent.change(container.querySelector('input[name="password"]')!, { target: { value: "ValidPassword1!" } });
fireEvent.click(screen.getByRole("button", { name: "account.register.continueToTeam" }));
expect(container.querySelector('[data-ui-id="ui.auth.register.planStep"]')).not.toHaveClass("hidden");
expect(container.querySelector('[data-ui-id="ui.auth.register.teamStep"]')).toBeInTheDocument();
});
it("moves account data to a separate team step and applies the server recommendation", async () => {
const { container } = render(
<RegisterScreen
requireCaptcha
creationRequestKey="d7077797-054b-497a-b1ce-8e4f36257a96"
subscriptionPlans={[core, { ...swarm, recommended: false }]}
selectedSubscriptionPriceId="price_starter"
recommendedSubscriptionPriceId="price_starter"
initialOfficeSeatQuantity={1}
initialFieldSeatQuantity={0}
/>
);
fireEvent.change(container.querySelector('input[name="email"]')!, { target: { value: "ada@example.test" } });
fireEvent.change(container.querySelector('input[name="first-name"]')!, { target: { value: "Ada" } });
fireEvent.change(container.querySelector('input[name="last-name"]')!, { target: { value: "Lovelace" } });
fireEvent.change(container.querySelector('input[name="company"]')!, { target: { value: "Analytical Engines" } });
fireEvent.click(screen.getByRole("button", { name: "account.register.continueToTeam" }));
expect(container.querySelector('[data-ui-id="ui.auth.register.planStep"]')).not.toHaveClass("hidden");
expect(screen.queryByText("account.register.paymentStepLabel")).not.toBeInTheDocument();
fireEvent.change(container.querySelector('input[name="selectedOfficeSeatQuantity"]')!, { target: { value: "5" } });
fireEvent.change(container.querySelector('input[name="selectedFieldSeatQuantity"]')!, { target: { value: "15" } });
await waitFor(() => expect(container.querySelector('input[name="selectedSubscriptionPriceId"]')).toHaveValue("price_pro"));
fireEvent.click(screen.getByRole("button", { name: "account.register.continueToPlans" }));
expect(screen.getByText("Swarm")).toBeInTheDocument();
expect(screen.getByText("account.register.recommendedBadge")).toBeInTheDocument();
const finalPayload = new FormData(container.querySelector("form")!);
expect(finalPayload.get("selectedOfficeSeatQuantity")).toBe("5");
expect(finalPayload.get("selectedFieldSeatQuantity")).toBe("15");
fireEvent.click(screen.getByRole("radio", { name: /Core/u }));
expect(container.querySelector('input[name="selectedSubscriptionPriceId"]')).toHaveValue("price_starter");
fireEvent.click(screen.getByRole("button", { name: "account.register.backToTeam" }));
fireEvent.click(screen.getByRole("button", { name: "account.register.backToAccount" }));
expect(container.querySelector('[data-ui-id="ui.auth.register.accountStep"]')).not.toHaveClass("hidden");
expect(container.querySelector('input[name="company"]')).toHaveValue("Analytical Engines");
fireEvent.click(screen.getByRole("button", { name: "account.register.continueToTeam" }));
expect(container.querySelector('input[name="selectedOfficeSeatQuantity"]')).toHaveValue(5);
expect(container.querySelector('input[name="selectedFieldSeatQuantity"]')).toHaveValue(15);
expect(container.querySelector('input[name="selectedSubscriptionPriceId"]')).toHaveValue("price_starter");
});
it("keeps an explicit deep-linked plan through the initial recommendation refresh", async () => {
const { container } = render(
<RegisterScreen
creationRequestKey="d7077797-054b-497a-b1ce-8e4f36257a96"
subscriptionPlans={[core, { ...swarm, recommended: false }]}
selectedSubscriptionPriceId="price_pro"
recommendedSubscriptionPriceId="price_starter"
initialOfficeSeatQuantity={1}
initialFieldSeatQuantity={0}
/>
);
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 300));
});
expect(fetch).toHaveBeenCalled();
expect(container.querySelector('input[name="selectedSubscriptionPriceId"]')).toHaveValue("price_pro");
});
it("offers an explicit retry when plan advice fails without trapping the team step", async () => {
const fetchMock = vi
.fn<typeof fetch>()
.mockResolvedValueOnce(new Response(null, { status: 503 }))
.mockResolvedValueOnce(
Response.json({
plans: [core, { ...swarm, recommended: false }],
selectedPriceId: "price_starter",
recommendedPriceId: "price_starter",
officeSeatQuantity: 1,
fieldSeatQuantity: 0,
})
);
vi.stubGlobal("fetch", fetchMock);
const { container } = render(
<RegisterScreen
creationRequestKey="d7077797-054b-497a-b1ce-8e4f36257a96"
subscriptionPlans={[core, { ...swarm, recommended: false }]}
selectedSubscriptionPriceId="price_starter"
recommendedSubscriptionPriceId="price_starter"
initialOfficeSeatQuantity={1}
initialFieldSeatQuantity={0}
/>
);
fireEvent.change(container.querySelector('input[name="email"]')!, { target: { value: "ada@example.test" } });
fireEvent.change(container.querySelector('input[name="first-name"]')!, { target: { value: "Ada" } });
fireEvent.change(container.querySelector('input[name="last-name"]')!, { target: { value: "Lovelace" } });
fireEvent.change(container.querySelector('input[name="company"]')!, { target: { value: "Analytical Engines" } });
fireEvent.click(screen.getByRole("button", { name: "account.register.continueToTeam" }));
await waitFor(() => expect(screen.getByText("account.register.recommendationErrorTitle")).toBeVisible());
expect(screen.getByRole("button", { name: "account.register.continueToPlans" })).toBeDisabled();
fireEvent.click(screen.getByRole("button", { name: "account.register.recommendationRetry" }));
await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2));
await waitFor(() => expect(screen.queryByText("account.register.recommendationErrorTitle")).not.toBeInTheDocument());
expect(screen.getByRole("button", { name: "account.register.continueToPlans" })).toBeEnabled();
});
it("requires a solved CAP proof and remounts a fresh challenge after a failed submit", () => {
const props = {
requireCaptcha: true,
creationRequestKey: "d7077797-054b-497a-b1ce-8e4f36257a96",
subscriptionPlans: [core, { ...swarm, recommended: false }],
selectedSubscriptionPriceId: "price_starter",
recommendedSubscriptionPriceId: "price_starter",
initialOfficeSeatQuantity: 1,
initialFieldSeatQuantity: 0,
} as const;
const { container, rerender } = render(<RegisterScreen {...props} />);
fireEvent.change(container.querySelector('input[name="email"]')!, { target: { value: "ada@example.test" } });
fireEvent.change(container.querySelector('input[name="first-name"]')!, { target: { value: "Ada" } });
fireEvent.change(container.querySelector('input[name="last-name"]')!, { target: { value: "Lovelace" } });
fireEvent.change(container.querySelector('input[name="company"]')!, { target: { value: "Analytical Engines" } });
fireEvent.click(screen.getByRole("button", { name: "account.register.continueToTeam" }));
fireEvent.click(screen.getByRole("button", { name: "account.register.continueToPlans" }));
const submit = screen.getByRole("button", { name: "account.register.continueWithPlan" });
fireEvent.click(screen.getByLabelText("account.register.consentTerms"));
fireEvent.click(screen.getByLabelText("account.register.consentPrivacy"));
expect(submit).toBeDisabled();
const firstCaptcha = screen.getByRole("button", { name: "captcha" });
fireEvent.click(firstCaptcha);
expect(submit).toBeEnabled();
rerender(<RegisterScreen {...props} error="account.register.errors.captchaFailed" captchaResetKey="retry-1" />);
expect(screen.getByRole("button", { name: "account.register.continueWithPlan" })).toBeDisabled();
expect(screen.getByRole("button", { name: "captcha" })).not.toBe(firstCaptcha);
expect(screen.getByText("account.register.captchaReloadedTitle")).toBeInTheDocument();
});
});
@@ -0,0 +1,118 @@
// @vitest-environment jsdom
import "@testing-library/jest-dom/vitest";
import { render, screen } from "@testing-library/react";
import type React from "react";
import { describe, expect, it, vi } from "vitest";
import RegisterScreen from "./RegisterScreen";
globalThis.ResizeObserver =
globalThis.ResizeObserver ??
class ResizeObserver {
observe() {}
unobserve() {}
disconnect() {}
};
vi.mock("react-router", async (importOriginal) => {
const actual = await importOriginal<typeof import("react-router")>();
return {
...actual,
Form: ({ children, ...props }: React.FormHTMLAttributes<HTMLFormElement>) => <form {...props}>{children}</form>,
Link: ({ children, to, ...props }: React.AnchorHTMLAttributes<HTMLAnchorElement> & { to: string }) => (
<a href={to} {...props}>
{children}
</a>
),
useNavigate: () => vi.fn(),
useNavigation: () => ({ state: "idle" }),
useSearchParams: () => [new URLSearchParams()],
};
});
vi.mock("react-i18next", () => ({
useTranslation: () => ({ t: (key: string) => key }),
}));
vi.mock("~/utils/data/useRootData", () => ({
useRootData: () => ({
csrf: "csrf-token",
appConfiguration: {
auth: {
requireEmailVerification: true,
requireOrganization: true,
requireName: true,
authMethods: { emailPassword: { enabled: true } },
captcha: { enabled: false, provider: "mcaptcha" },
},
},
}),
}));
vi.mock("~/components/captcha/Captcha", () => ({ default: () => null }));
const subscriptionPlans = [
{
planId: "product_starter",
planCode: "starter",
titleKey: "Core",
descriptionKey: "Core plan",
priceId: "price_starter",
amountCents: 19_900,
baseAmountCents: 19_900,
currency: "EUR",
billingPeriod: 3,
includedOfficeSeatQuantity: 2,
includedFieldSeatQuantity: 5,
includedStorageGb: 100,
storagePerAdditionalSeatGb: 10,
extraOfficeSeatQuantity: 0,
extraFieldSeatQuantity: 0,
recommended: true,
},
] as const;
describe("RegisterScreen recovery state", () => {
it("marks every configured organization and name field as required", () => {
const { container } = render(
<RegisterScreen
creationRequestKey="d7077797-054b-497a-b1ce-8e4f36257a96"
subscriptionPlans={subscriptionPlans}
selectedSubscriptionPriceId="price_starter"
recommendedSubscriptionPriceId="price_starter"
initialOfficeSeatQuantity={1}
initialFieldSeatQuantity={0}
/>
);
expect(container.querySelector('input[name="company"]')).toBeRequired();
expect(container.querySelector('input[name="first-name"]')).toBeRequired();
expect(container.querySelector('input[name="last-name"]')).toBeRequired();
expect(container.querySelector('input[name="selectedSubscriptionPriceId"]')).toHaveValue("price_starter");
});
it("keeps the generic pending screen visible and renders resend errors in place", () => {
const creationRequestKey = "d7077797-054b-497a-b1ce-8e4f36257a96";
const { container } = render(
<RegisterScreen
verificationEmailSent
error="api.errors.tooManyRequests"
data={{ email: "ada@example.test" }}
creationRequestKey={creationRequestKey}
subscriptionPlans={subscriptionPlans}
selectedSubscriptionPriceId="price_starter"
recommendedSubscriptionPriceId="price_starter"
initialOfficeSeatQuantity={1}
initialFieldSeatQuantity={0}
/>
);
expect(container.querySelector('[data-ui-id="ui.auth.register.verificationSent"]')).toBeInTheDocument();
expect(container.querySelector('[data-ui-id="ui.auth.register.form"]')).not.toBeInTheDocument();
expect(screen.getByRole("alert")).toHaveTextContent("api.errors.tooManyRequests");
expect(container.querySelector('[data-ui-id="ui.auth.register.resendError"]')).toBeInTheDocument();
expect(container.querySelector(`input[name="creationRequestKey"][value="${creationRequestKey}"]`)).toBeInTheDocument();
expect(container.querySelector('input[name="selectedSubscriptionPriceId"]')).toHaveValue("price_starter");
});
});
@@ -1,20 +1,20 @@
import { useMemo, useState } from "react";
import { useEffect, useMemo, useRef, useState } from "react";
import { Form, Link, useNavigate, useNavigation, useSearchParams } from "react-router";
import { useTranslation } from "react-i18next";
import { FeatherArrowLeft, FeatherBuilding, FeatherMail, FeatherMailCheck, FeatherPencil, FeatherRotateCw } from "@subframe/core";
import { FeatherArrowLeft, FeatherBuilding, FeatherMailCheck, FeatherPencil, FeatherRotateCw } from "@subframe/core";
import { useRootData } from "~/utils/data/useRootData";
import { AuthShell } from "~/components/auth/AuthShell";
import { Alert } from "~/ui/components/Alert";
import { Button } from "~/ui/components/Button";
import { Card } from "~/ui/components/Card";
import { Checkbox } from "~/ui/components/Checkbox";
import { IconWithBackground } from "~/ui/components/IconWithBackground";
import { LinkButton } from "~/ui/components/LinkButton";
import { Logo } from "~/ui/components/Logo";
import { Progress } from "~/ui/components/Progress";
import { StepperHorizontal } from "~/ui/components/StepperHorizontal";
import { TextInput } from "~/ui/components/TextInput";
import Captcha from "~/components/captcha/Captcha";
import { getPasswordChecks, type PasswordPolicy } from "~/modules/users/components/RegisterForm";
import { RegistrationPlanStep } from "~/modules/users/components/RegistrationPlanStep";
// Signup-Screens nach Davids Subframe-"WF-P2"-Designs:
// S01 "Signup" -> Form (Logo + Card "Konto erstellen": E-Mail, Passwort+Staerke, Vor-/Nachname,
@@ -26,32 +26,74 @@ import { getPasswordChecks, type PasswordPolicy } from "~/modules/users/componen
// Token-genaue Uebernahme + bewusste Abweichungen (vom Backend erzwungen, nicht erfunden):
// - Davids S01 zeigt das Passwort IMMER. Bei aktiver E-Mail-Verifizierung sammelt das Backend das Passwort
// aber erst beim Verify (Registration-Modell hat KEINE Passwort-Spalte) -> showPasswordInput bleibt
// `!requireEmailVerification` (Default ist OFF -> Passwort sichtbar = Davids Optik). [Backend-Flag]
// `!requireEmailVerification` (launch-sicherer Default ist ON -> Passwort genau einmal im Verify-Schritt).
// Eine explizit deaktivierte Verifizierung zeigt das Passwort weiterhin direkt in S01. [Backend-Flag]
// - Davids S01 hat KEIN Telefon-/USt-IdNr-Feld -> entfernt (wurden ohnehin nie persistiert).
// - Davids S01 hat 2 Consents (AGB, Datenschutz); der separate AVV/DPA-Consent wurde gestrichen. [Flag]
// - Davids PasswordStrengthIndicator existiert nicht in ~/ui -> bestehender Progress-Balken beibehalten.
// - Davids statische Captcha-Box ("Ich bin kein Roboter") -> echtes mCaptcha-Widget in Davids Box-Optik,
// nur sichtbar wenn Captcha aktiv ist.
// - S03 "E-Mail erneut senden": echtes Resend braucht `recreateToken:true` (registerFromRequest nutzt
// `false` -> versendet bei bestehender Registration NICHTS). Button postet `intent=resendVerification`;
// das Backend muss diesen Intent noch auf createRegistrationForm({recreateToken:true}) mappen. [Backend-Flag]
// - S03 resend posts `intent=resendVerification`. The server verifies the persisted HMAC-bound pending
// capability, rotates its token and TTL atomically, and returns the new request key for the next click.
type RegisterData = { company?: string; firstName?: string; lastName?: string; email?: string; slug?: string };
export type RegistrationPlanOptionData = {
readonly planId: string;
readonly planCode: string;
readonly titleKey: string;
readonly descriptionKey: string;
readonly priceId: string;
readonly amountCents: number;
readonly baseAmountCents: number;
readonly currency: string;
readonly billingPeriod: number;
readonly includedOfficeSeatQuantity: number;
readonly includedFieldSeatQuantity: number;
readonly includedStorageGb: number;
readonly storagePerAdditionalSeatGb: number;
readonly extraOfficeSeatQuantity: number;
readonly extraFieldSeatQuantity: number;
readonly recommended: boolean;
};
type RegistrationPlanAdviceData = {
readonly plans: readonly RegistrationPlanOptionData[];
readonly selectedPriceId: string;
readonly recommendedPriceId: string;
readonly officeSeatQuantity: number;
readonly fieldSeatQuantity: number;
};
export default function RegisterScreen({
requireCaptcha = false,
error,
captchaResetKey,
verificationEmailSent,
data = {},
leadConversion,
passwordPolicy,
creationRequestKey,
subscriptionPlans,
selectedSubscriptionPriceId,
recommendedSubscriptionPriceId,
initialOfficeSeatQuantity,
initialFieldSeatQuantity,
}: {
requireCaptcha?: boolean;
error?: string;
/** Changes after every failed initial submit so single-use CAPTCHA proofs cannot poison retries. */
captchaResetKey?: string;
verificationEmailSent?: boolean;
data?: RegisterData;
leadConversion?: { leadId: string; token: string; planId?: string | null };
passwordPolicy?: PasswordPolicy;
creationRequestKey: string;
subscriptionPlans: readonly RegistrationPlanOptionData[];
selectedSubscriptionPriceId: string;
recommendedSubscriptionPriceId: string;
initialOfficeSeatQuantity: number;
initialFieldSeatQuantity: number;
}) {
const { t } = useTranslation();
const { appConfiguration, csrf } = useRootData();
@@ -60,6 +102,8 @@ export default function RegisterScreen({
const [searchParams] = useSearchParams();
const isSubmitting = navigation.state !== "idle";
const redirect = searchParams.get("redirect") ?? "";
const formRef = useRef<HTMLFormElement>(null);
const passwordInputRef = useRef<HTMLInputElement>(null);
// Controlled, damit Werte ueber den Wechsel Form <-> "E-Mail bestaetigt"-Status erhalten bleiben
// (E-Mail-Anzeige in S03, Resend ohne erneutes Tippen).
@@ -68,21 +112,96 @@ export default function RegisterScreen({
const [company, setCompany] = useState(data.company ?? "");
const [firstName, setFirstName] = useState(data.firstName ?? "");
const [lastName, setLastName] = useState(data.lastName ?? "");
const [selectedPriceId, setSelectedPriceId] = useState(selectedSubscriptionPriceId);
const [step, setStep] = useState<"account" | "team" | "plan">("account");
const [officeSeatQuantity, setOfficeSeatQuantity] = useState(initialOfficeSeatQuantity);
const [fieldSeatQuantity, setFieldSeatQuantity] = useState(initialFieldSeatQuantity);
const [planOptions, setPlanOptions] = useState(subscriptionPlans);
const [recommendedPriceId, setRecommendedPriceId] = useState(recommendedSubscriptionPriceId);
const [planManuallyOverridden, setPlanManuallyOverridden] = useState(selectedSubscriptionPriceId !== recommendedSubscriptionPriceId);
const [planAdviceLoading, setPlanAdviceLoading] = useState(false);
const [planAdviceFailed, setPlanAdviceFailed] = useState(false);
const [planAdviceRetryKey, setPlanAdviceRetryKey] = useState(0);
const [acceptTerms, setAcceptTerms] = useState(false);
const [acceptPrivacy, setAcceptPrivacy] = useState(false);
const allConsents = acceptTerms && acceptPrivacy;
const [captchaStatus, setCaptchaStatus] = useState<"pending" | "solved" | "error">("pending");
const [passwordValidationRequested, setPasswordValidationRequested] = useState(false);
const requireEmailVerification = appConfiguration.auth.requireEmailVerification;
const showPasswordInput = !requireEmailVerification;
const captchaEnabled = requireCaptcha && appConfiguration.auth.captcha.enabled;
const checks = useMemo(() => getPasswordChecks(password, passwordPolicy), [password, passwordPolicy]);
const strength = checks.length === 0 ? 0 : Math.round((checks.filter((c) => c.valid).length / checks.length) * 100);
const passwordMeetsClientPolicy = !showPasswordInput || checks.length === 0 || checks.every((check) => check.valid);
const showPasswordPolicyError = passwordValidationRequested && !passwordMeetsClientPolicy;
useEffect(() => {
if (captchaResetKey) setCaptchaStatus("pending");
}, [captchaResetKey]);
useEffect(() => {
if (verificationEmailSent) return;
if (
!Number.isSafeInteger(officeSeatQuantity) ||
!Number.isSafeInteger(fieldSeatQuantity) ||
officeSeatQuantity < 1 ||
officeSeatQuantity > 10_000 ||
fieldSeatQuantity < 0 ||
fieldSeatQuantity > 10_000
) {
setPlanAdviceFailed(true);
return;
}
const controller = new AbortController();
const timer = window.setTimeout(async () => {
setPlanAdviceLoading(true);
setPlanAdviceFailed(false);
try {
const params = new URLSearchParams({ office: String(officeSeatQuantity), field: String(fieldSeatQuantity) });
const response = await fetch(`/auth/registration-plan-advice?${params}`, {
headers: { Accept: "application/json" },
signal: controller.signal,
});
if (!response.ok) throw new Error("Registration plan advice failed");
const advice = (await response.json()) as RegistrationPlanAdviceData;
setPlanOptions(advice.plans);
setRecommendedPriceId(advice.recommendedPriceId);
if (!planManuallyOverridden) setSelectedPriceId(advice.recommendedPriceId);
} catch {
if (!controller.signal.aborted) setPlanAdviceFailed(true);
} finally {
if (!controller.signal.aborted) setPlanAdviceLoading(false);
}
}, 250);
return () => {
window.clearTimeout(timer);
controller.abort();
};
}, [fieldSeatQuantity, officeSeatQuantity, planAdviceRetryKey, planManuallyOverridden, verificationEmailSent]);
function showTeamStep() {
setPasswordValidationRequested(true);
const accountStep = formRef.current?.querySelector('[data-ui-id="ui.auth.register.accountStep"]');
if (!accountStep) return;
const controls = Array.from(accountStep.querySelectorAll<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>("input, select, textarea"));
const nativeFieldsValid = controls.every((control) => control.reportValidity());
if (!passwordMeetsClientPolicy) {
passwordInputRef.current?.focus();
return;
}
if (nativeFieldsValid) setStep("team");
}
function selectPlan(priceId: string) {
setPlanManuallyOverridden(true);
setSelectedPriceId(priceId);
}
// S03 "E-Mail bestaetigen" — Davids Status-Card.
if (verificationEmailSent) {
return (
<div
className="flex min-h-screen w-full flex-col items-center justify-center gap-8 bg-surface-neutral-primary px-4 py-12 mobile:gap-6 mobile:py-6"
className="bg-surface-neutral-primary mobile:gap-6 mobile:py-6 flex min-h-screen w-full flex-col items-center justify-center gap-8 px-4 py-12"
data-ui-id="ui.auth.register.verificationSent"
>
<Logo size="64" />
@@ -91,28 +210,46 @@ export default function RegisterScreen({
<IconWithBackground variant="information" size="large" round={true} icon={<FeatherMailCheck />} />
<div className="flex w-full flex-col items-center gap-2">
<span className="text-heading- font-heading- text-text-neutral-primary text-center">{t("account.verify.confirmEmailTitle")}</span>
<span className="w-full text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary text-center">
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary w-full text-center">
{t("account.verify.confirmEmailBody")}
</span>
</div>
</div>
<div className="flex w-full flex-col items-center gap-2 rounded-md border border-solid border-border-default bg-surface-neutral-primary px-4 py-3">
<span className="text-body-extra-small-medium-150 font-body-extra-small-medium-150 text-text-neutral-tertiary">{t("account.verify.linkSentTo")}</span>
<span className="w-full text-body-default-semibold-0 font-body-default-semibold-0 text-text-neutral-primary text-center" data-ui-id="ui.auth.register.sentEmail">
<div className="border-border-default bg-surface-neutral-primary flex w-full flex-col items-center gap-2 rounded-md border border-solid px-4 py-3">
<span className="text-body-extra-small-medium-150 font-body-extra-small-medium-150 text-text-neutral-tertiary">
{t("account.verify.linkSentTo")}
</span>
<span
className="text-body-default-semibold-0 font-body-default-semibold-0 text-text-neutral-primary w-full text-center"
data-ui-id="ui.auth.register.sentEmail"
>
{email}
</span>
</div>
<Alert variant="neutral" notDismissible={true} title="" description={t("account.verify.checkInboxHint")} />
{error && navigation.state === "idle" ? (
<p
className="text-body-small-regular-0 font-body-small-regular-0 text-text-feedback-negative text-center"
role="alert"
data-ui-id="ui.auth.register.resendError"
>
{error}
</p>
) : null}
<div className="flex w-full flex-col items-center gap-3">
{/* Resend: echtes Re-Send ist backend-seitig offen (recreateToken:true) -> Intent posten + Flag. */}
{/* The resend intent proves the persisted HMAC-bound pending capability; the server rotates token and TTL before queueing a new mail job. */}
<Form method="post" className="w-full">
<input type="hidden" name="csrf" value={csrf} readOnly />
<input type="hidden" name="redirectTo" value={redirect} readOnly />
<input type="hidden" name="intent" value="resendVerification" readOnly />
<input type="hidden" name="creationRequestKey" value={creationRequestKey} readOnly />
<input type="hidden" name="email" value={email} readOnly />
<input type="hidden" name="company" value={company} readOnly />
<input type="hidden" name="first-name" value={firstName} readOnly />
<input type="hidden" name="last-name" value={lastName} readOnly />
<input type="hidden" name="selectedSubscriptionPriceId" value={selectedPriceId} readOnly />
<input type="hidden" name="selectedOfficeSeatQuantity" value={officeSeatQuantity} readOnly />
<input type="hidden" name="selectedFieldSeatQuantity" value={fieldSeatQuantity} readOnly />
{leadConversion ? (
<>
<input type="hidden" name="leadId" value={leadConversion.leadId} readOnly />
@@ -135,7 +272,7 @@ export default function RegisterScreen({
className="h-10 w-full flex-none"
variant="secondary"
icon={<FeatherPencil />}
onClick={() => navigate("/signup")}
onClick={() => navigate("/signup?restart=1")}
data-ui-id="ui.auth.register.changeEmail"
>
{t("account.verify.changeEmail")}
@@ -149,7 +286,7 @@ export default function RegisterScreen({
</Link>
</div>
</Card>
<span className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary text-center max-w-[400px]">
<span className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary max-w-[400px] text-center">
{t("account.verify.linkValidityNote")}
</span>
</div>
@@ -159,8 +296,17 @@ export default function RegisterScreen({
// S01 "Signup".
return (
<AuthShell
title={t("account.register.title")}
subtitle={t("account.register.signupSubtitle")}
title={step === "account" ? t("account.register.title") : step === "team" ? t("account.register.teamStepTitle") : t("account.register.planStepTitle")}
subtitle={
step === "account"
? t("account.register.signupSubtitle")
: step === "team"
? t("account.register.teamStepSubtitle")
: t("account.register.planStepSubtitle")
}
cardSize={step === "account" ? "large" : "extra-large"}
cardClassName={step === "account" ? "max-w-[448px]" : "max-w-[960px]"}
logoSize="32"
dataUiId="ui.auth.register.page"
footer={
<>
@@ -174,9 +320,27 @@ export default function RegisterScreen({
}
>
{appConfiguration.auth.authMethods.emailPassword.enabled ? (
<Form method="post" noValidate className="flex w-full flex-col gap-4" data-ui-id="ui.auth.register.form">
<Form ref={formRef} method="post" className="flex w-full flex-col gap-4" data-ui-id="ui.auth.register.form">
<StepperHorizontal className="pb-1" data-ui-id="ui.auth.register.steps">
<StepperHorizontal.Step
firstStep
variant={step === "account" ? "active" : "completed"}
stepNumber="1"
label={t("account.register.accountStepLabel")}
/>
<StepperHorizontal.Step
variant={step === "team" ? "active" : step === "plan" ? "completed" : "default"}
stepNumber="2"
label={t("account.register.teamStepLabel")}
/>
<StepperHorizontal.Step lastStep variant={step === "plan" ? "active" : "default"} stepNumber="3" label={t("account.register.planStepLabel")} />
</StepperHorizontal>
<input type="hidden" name="redirectTo" value={redirect} readOnly />
<input type="hidden" name="csrf" value={csrf} readOnly />
<input type="hidden" name="creationRequestKey" value={creationRequestKey} readOnly />
<input type="hidden" name="selectedSubscriptionPriceId" value={selectedPriceId} readOnly />
<input type="hidden" name="acceptTerms" value={acceptTerms ? "true" : "false"} readOnly />
<input type="hidden" name="acceptPrivacy" value={acceptPrivacy ? "true" : "false"} readOnly />
{leadConversion ? (
<>
<input type="hidden" name="leadId" value={leadConversion.leadId} readOnly />
@@ -185,151 +349,180 @@ export default function RegisterScreen({
</>
) : null}
{/* Davids Felder-Gruppe (gap-4). */}
<div className="flex w-full flex-col items-start gap-4">
<TextInput className="h-auto w-full flex-none" fillContainer showLabel label={t("account.shared.email")} type="email">
<TextInput.Input
name="email"
type="email"
required
autoComplete="email"
placeholder={t("account.shared.emailPlaceholder")}
value={email}
onChange={(event) => setEmail(event.target.value)}
readOnly={Boolean(leadConversion)}
disabled={isSubmitting}
data-ui-id="ui.auth.register.email"
/>
</TextInput>
<div className={step === "account" ? "flex w-full flex-col gap-4" : "hidden"} data-ui-id="ui.auth.register.accountStep">
{/* Davids Felder-Gruppe (gap-4). */}
<div className="flex w-full flex-col items-start gap-4">
<TextInput className="h-auto w-full flex-none" fillContainer showLabel label={t("account.shared.email")} type="email">
<TextInput.Input
name="email"
type="email"
required
autoComplete="email"
placeholder={t("account.shared.emailPlaceholder")}
value={email}
onChange={(event) => setEmail(event.target.value)}
readOnly={Boolean(leadConversion)}
disabled={isSubmitting}
data-ui-id="ui.auth.register.email"
/>
</TextInput>
{showPasswordInput ? (
<div className="flex w-full flex-col items-start gap-2">
<TextInput className="h-auto w-full flex-none" fillContainer showLabel label={t("account.shared.password")} type="password">
<TextInput.Input
name="password"
{showPasswordInput ? (
<div className="flex w-full flex-col items-start gap-2">
<TextInput
className="h-auto w-full flex-none"
fillContainer
showLabel
label={t("account.shared.password")}
type="password"
required
autoComplete="new-password"
placeholder={t("account.register.passwordChoosePlaceholder")}
value={password}
onChange={(event) => setPassword(event.target.value)}
error={showPasswordPolicyError}
message={
showPasswordPolicyError ? (
<span id="registration-password-policy-error" role="alert" data-ui-id="ui.auth.register.passwordPolicyError">
{t("account.register.passwordRequirements.fixBeforeContinue")}
</span>
) : undefined
}
>
<TextInput.Input
ref={passwordInputRef}
name="password"
type="password"
required
autoComplete="new-password"
placeholder={t("account.register.passwordChoosePlaceholder")}
value={password}
onChange={(event) => {
setPassword(event.target.value);
if (passwordValidationRequested) setPasswordValidationRequested(false);
}}
onBlur={() => {
if (password.length > 0 && !passwordMeetsClientPolicy) setPasswordValidationRequested(true);
}}
aria-invalid={showPasswordPolicyError}
aria-describedby={showPasswordPolicyError ? "registration-password-policy-error" : undefined}
disabled={isSubmitting}
data-ui-id="ui.auth.register.password"
/>
</TextInput>
{passwordPolicy ? (
<>
<Progress className="h-auto w-full flex-none" hideLabel label={t("account.register.passwordStrength")} value={strength} />
<span className="text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-tertiary">
{t("account.register.passwordStrength")}
</span>
<ul
className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 flex w-full flex-col gap-1"
aria-live="polite"
aria-label={t("account.register.passwordRequirements.label")}
data-ui-id="ui.auth.register.passwordRequirements"
>
{checks.map((check) => {
const label = t(check.label, check.args);
const status = check.valid ? t("account.register.passwordRequirements.met") : t("account.register.passwordRequirements.notMet");
return (
<li
key={check.key}
className={
check.valid
? "text-text-feedback-positive"
: showPasswordPolicyError
? "text-text-feedback-negative"
: "text-text-neutral-tertiary"
}
aria-label={`${status}: ${label}`}
>
<span aria-hidden="true">{check.valid ? "[x]" : "[ ]"}</span> {label}
</li>
);
})}
</ul>
</>
) : null}
</div>
) : null}
<div className="mobile:flex-col flex w-full items-start gap-4">
<TextInput className="h-auto shrink-0 grow basis-0" showLabel label={t("models.user.firstName")}>
<TextInput.Input
name="first-name"
required={appConfiguration.auth.requireName}
placeholder={t("account.shared.firstNamePlaceholder")}
value={firstName}
onChange={(event) => setFirstName(event.target.value)}
disabled={isSubmitting}
data-ui-id="ui.auth.register.password"
data-ui-id="ui.auth.register.firstName"
/>
</TextInput>
<TextInput className="h-auto shrink-0 grow basis-0" showLabel label={t("models.user.lastName")}>
<TextInput.Input
name="last-name"
required={appConfiguration.auth.requireName}
placeholder={t("account.shared.lastNamePlaceholder")}
value={lastName}
onChange={(event) => setLastName(event.target.value)}
disabled={isSubmitting}
data-ui-id="ui.auth.register.lastName"
/>
</TextInput>
{passwordPolicy ? (
<>
<Progress className="h-auto w-full flex-none" hideLabel value={strength} />
<span className="text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-tertiary">{t("account.register.passwordStrength")}</span>
<span className="w-full text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary">{t("account.register.passwordHint")}</span>
</>
) : null}
</div>
) : null}
<div className="flex w-full items-start gap-4 mobile:flex-col">
<TextInput className="h-auto grow shrink-0 basis-0" showLabel label={t("models.user.firstName")}>
<TextInput className="h-auto w-full flex-none" fillContainer showLabel label={t("account.register.companyLabel")} icon={<FeatherBuilding />}>
<TextInput.Input
name="first-name"
placeholder={t("account.shared.firstNamePlaceholder")}
value={firstName}
onChange={(event) => setFirstName(event.target.value)}
name="company"
required={appConfiguration.auth.requireOrganization}
placeholder={t("account.register.companyPlaceholder")}
value={company}
onChange={(event) => setCompany(event.target.value)}
disabled={isSubmitting}
data-ui-id="ui.auth.register.firstName"
/>
</TextInput>
<TextInput className="h-auto grow shrink-0 basis-0" showLabel label={t("models.user.lastName")}>
<TextInput.Input
name="last-name"
placeholder={t("account.shared.lastNamePlaceholder")}
value={lastName}
onChange={(event) => setLastName(event.target.value)}
disabled={isSubmitting}
data-ui-id="ui.auth.register.lastName"
data-ui-id="ui.auth.register.company"
/>
</TextInput>
</div>
<TextInput
className="h-auto w-full flex-none"
fillContainer
showLabel
label={t("account.register.companyLabel")}
icon={<FeatherBuilding />}
>
<TextInput.Input
name="company"
required={appConfiguration.auth.requireOrganization}
placeholder={t("account.register.companyPlaceholder")}
value={company}
onChange={(event) => setCompany(event.target.value)}
disabled={isSubmitting}
data-ui-id="ui.auth.register.company"
/>
</TextInput>
</div>
{/* Sicherheitspruefung — Davids Box mit echtem mCaptcha-Widget statt statischer Mock-Checkbox. */}
{captchaEnabled ? (
<div className="flex w-full flex-col items-start gap-2">
<span className="text-body-extra-small-semibold-0 font-body-extra-small-semibold-0 uppercase text-text-neutral-tertiary">
{t("account.register.securityCheck")}
</span>
<div className="flex w-full items-center justify-center rounded-md border border-solid border-border-default bg-surface-neutral-secondary px-4 py-3">
<Captcha
enabled
provider={appConfiguration.auth.captcha.provider}
instanceUrl={appConfiguration.auth.captcha.instanceUrl}
sitekey={appConfiguration.auth.captcha.loginSiteKey}
/>
</div>
</div>
) : null}
{/* Consents — Davids 2 Checkboxen mit Prefix + Link. */}
<div className="flex w-full flex-col items-start gap-3">
<div className="flex w-full items-center gap-2">
<Checkbox label={t("account.register.consentTerms")} hideLabel checked={acceptTerms} onCheckedChange={setAcceptTerms} data-ui-id="ui.auth.register.consentTerms" />
<div className="flex min-h-5 flex-wrap items-center gap-1">
<span className="text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-secondary">{t("account.register.consentAcceptPrefix")}</span>
<a href="/terms-and-conditions" target="_blank" rel="noreferrer" className="no-underline">
<LinkButton size="small" hideIcon>
{t("account.register.consentTermsLink")}
</LinkButton>
</a>
</div>
</div>
<div className="flex w-full items-center gap-2">
<Checkbox label={t("account.register.consentPrivacy")} hideLabel checked={acceptPrivacy} onCheckedChange={setAcceptPrivacy} data-ui-id="ui.auth.register.consentPrivacy" />
<div className="flex min-h-5 flex-wrap items-center gap-1">
<span className="text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-secondary">{t("account.register.consentAcceptPrefix")}</span>
<a href="/privacy-policy" target="_blank" rel="noreferrer" className="no-underline">
<LinkButton size="small" hideIcon>
{t("account.register.privacyPolicy")}
</LinkButton>
</a>
</div>
</div>
</div>
{/* Button-Gruppe — Submit + Bestaetigungs-Mail-Hinweis (nur wenn verifiziert wird). */}
<div className="flex w-full flex-col items-start gap-2">
<Button type="submit" className="h-9 w-full flex-none" loading={isSubmitting} disabled={isSubmitting || !allConsents} data-ui-id="ui.auth.register.submit">
{t("account.register.title")}
<Button type="button" className="h-9 w-full flex-none" onClick={showTeamStep} data-ui-id="ui.auth.register.toTeamStep">
{t("account.register.continueToTeam")}
</Button>
{requireEmailVerification ? (
<div className="flex w-full items-center justify-center gap-1">
<FeatherMail className="text-body-small-regular-0 font-body-small-regular-0 text-icon-neutral-tertiary" />
<span className="text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary">{t("account.register.confirmationEmailNote")}</span>
</div>
) : null}
</div>
{error && navigation.state === "idle" ? (
<p className="text-center text-body-small-regular-0 font-body-small-regular-0 text-text-feedback-negative" role="alert">
{error}
</p>
) : null}
<RegistrationPlanStep
visible={step !== "account"}
screen={step === "team" ? "team" : "plan"}
plans={planOptions}
selectedPriceId={selectedPriceId}
recommendedPriceId={recommendedPriceId}
officeSeatQuantity={officeSeatQuantity}
fieldSeatQuantity={fieldSeatQuantity}
planAdviceLoading={planAdviceLoading}
planAdviceFailed={planAdviceFailed}
isSubmitting={isSubmitting}
acceptTerms={acceptTerms}
acceptPrivacy={acceptPrivacy}
captchaEnabled={captchaEnabled}
captchaConfig={appConfiguration.auth.captcha}
captchaResetKey={captchaResetKey}
captchaStatus={captchaStatus}
requireEmailVerification={requireEmailVerification}
error={navigation.state === "idle" ? error : undefined}
onSelectPlan={selectPlan}
onOfficeSeatQuantityChange={setOfficeSeatQuantity}
onFieldSeatQuantityChange={setFieldSeatQuantity}
onAcceptTermsChange={setAcceptTerms}
onAcceptPrivacyChange={setAcceptPrivacy}
onCaptchaStatusChange={setCaptchaStatus}
onRetryPlanAdvice={() => {
setPlanAdviceFailed(false);
setPlanAdviceRetryKey((current) => current + 1);
}}
onContinue={() => setStep("plan")}
onBack={() => setStep(step === "plan" ? "team" : "account")}
/>
{/* The interactive seat controls live only on the team step and are
unmounted on the final plan step. Keep the submitted contract
present for the whole wizard so server-side price validation
always receives the exact quantities the customer reviewed. */}
<input type="hidden" name="selectedOfficeSeatQuantity" value={officeSeatQuantity} readOnly />
<input type="hidden" name="selectedFieldSeatQuantity" value={fieldSeatQuantity} readOnly />
</Form>
) : null}
</AuthShell>
@@ -0,0 +1,117 @@
import { useMemo } from "react";
import { createMemoryRouter, RouterProvider } from "react-router";
import RegisterScreen, { type RegistrationPlanOptionData } from "./RegisterScreen";
const plans: readonly RegistrationPlanOptionData[] = [
{
planId: "product_starter",
planCode: "starter",
titleKey: "pricing.products.plan1.title",
descriptionKey: "pricing.products.plan1.description",
priceId: "price_starter",
amountCents: 19_900,
baseAmountCents: 19_900,
currency: "EUR",
billingPeriod: 3,
includedOfficeSeatQuantity: 2,
includedFieldSeatQuantity: 5,
includedStorageGb: 100,
storagePerAdditionalSeatGb: 10,
extraOfficeSeatQuantity: 0,
extraFieldSeatQuantity: 0,
recommended: true,
},
{
planId: "product_pro",
planCode: "pro",
titleKey: "pricing.products.plan2.title",
descriptionKey: "pricing.products.plan2.description",
priceId: "price_pro",
amountCents: 49_900,
baseAmountCents: 49_900,
currency: "EUR",
billingPeriod: 3,
includedOfficeSeatQuantity: 5,
includedFieldSeatQuantity: 15,
includedStorageGb: 500,
storagePerAdditionalSeatGb: 20,
extraOfficeSeatQuantity: 0,
extraFieldSeatQuantity: 0,
recommended: false,
},
{
planId: "product_business",
planCode: "business",
titleKey: "pricing.products.plan3.title",
descriptionKey: "pricing.products.plan3.description",
priceId: "price_business",
amountCents: 99_900,
baseAmountCents: 99_900,
currency: "EUR",
billingPeriod: 3,
includedOfficeSeatQuantity: 10,
includedFieldSeatQuantity: 30,
includedStorageGb: 2_000,
storagePerAdditionalSeatGb: 40,
extraOfficeSeatQuantity: 0,
extraFieldSeatQuantity: 0,
recommended: false,
},
];
const rootData = {
csrf: "visual-csrf",
appConfiguration: {
auth: {
requireEmailVerification: true,
requireOrganization: true,
requireName: true,
authMethods: { emailPassword: { enabled: true } },
captcha: {
enabled: true,
provider: "cap" as const,
instanceUrl: "https://captcha.visual.invalid",
loginSiteKey: "registration-visual",
},
},
},
};
/** Real registration component in a deterministic data-router shell for visual regression. */
export function RegisterScreenVisualFixture({ requireEmailVerification = true }: { requireEmailVerification?: boolean } = {}) {
const router = useMemo(
() =>
createMemoryRouter(
[
{
id: "root",
path: "/",
loader: () => ({
...rootData,
appConfiguration: {
...rootData.appConfiguration,
auth: { ...rootData.appConfiguration.auth, requireEmailVerification },
},
}),
element: (
<RegisterScreen
requireCaptcha
creationRequestKey="d7077797-054b-497a-b1ce-8e4f36257a96"
subscriptionPlans={plans}
selectedSubscriptionPriceId="price_starter"
recommendedSubscriptionPriceId="price_starter"
initialOfficeSeatQuantity={1}
initialFieldSeatQuantity={0}
passwordPolicy={{ minLength: 12, requireUpper: true, requireLower: true, requireDigit: true, requireSpecial: true }}
/>
),
},
],
{ initialEntries: ["/"] }
),
[requireEmailVerification]
);
return <RouterProvider router={router} />;
}
@@ -0,0 +1,486 @@
import {
FeatherArrowLeft,
FeatherBriefcase,
FeatherCheck,
FeatherCreditCard,
FeatherHardHat,
FeatherLock,
FeatherMail,
FeatherMinus,
FeatherPlus,
FeatherUsers,
} from "@subframe/core";
import { useTranslation } from "react-i18next";
import Captcha from "~/components/captcha/Captcha";
import { useLocaleFormatters } from "~/locale/format";
import { Alert } from "~/ui/components/Alert";
import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
import { Button } from "~/ui/components/Button";
import { Card } from "~/ui/components/Card";
import { Checkbox } from "~/ui/components/Checkbox";
import { IconButton } from "~/ui/components/IconButton";
import { IconWithBackground } from "~/ui/components/IconWithBackground";
import { LinkButton } from "~/ui/components/LinkButton";
import { RadioCardGroup } from "~/ui/components/RadioCardGroup";
import { Slider } from "~/ui/components/Slider";
import { TextInput } from "~/ui/components/TextInput";
import type { RegistrationPlanOptionData } from "./RegisterScreen";
type CaptchaStatus = "pending" | "solved" | "error";
export function RegistrationPlanStep({
visible,
screen,
plans,
selectedPriceId,
recommendedPriceId,
officeSeatQuantity,
fieldSeatQuantity,
planAdviceLoading,
planAdviceFailed,
isSubmitting,
acceptTerms,
acceptPrivacy,
captchaEnabled,
captchaConfig,
captchaResetKey,
captchaStatus,
requireEmailVerification,
error,
onSelectPlan,
onOfficeSeatQuantityChange,
onFieldSeatQuantityChange,
onAcceptTermsChange,
onAcceptPrivacyChange,
onCaptchaStatusChange,
onRetryPlanAdvice,
onContinue,
onBack,
}: {
visible: boolean;
screen: "team" | "plan";
plans: readonly RegistrationPlanOptionData[];
selectedPriceId: string;
recommendedPriceId: string;
officeSeatQuantity: number;
fieldSeatQuantity: number;
planAdviceLoading: boolean;
planAdviceFailed: boolean;
isSubmitting: boolean;
acceptTerms: boolean;
acceptPrivacy: boolean;
captchaEnabled: boolean;
captchaConfig: {
provider?: "mcaptcha" | "cap";
instanceUrl?: string;
loginSiteKey?: string;
};
captchaResetKey?: string;
captchaStatus: CaptchaStatus;
requireEmailVerification: boolean;
error?: string;
onSelectPlan: (priceId: string) => void;
onOfficeSeatQuantityChange: (quantity: number) => void;
onFieldSeatQuantityChange: (quantity: number) => void;
onAcceptTermsChange: (accepted: boolean) => void;
onAcceptPrivacyChange: (accepted: boolean) => void;
onCaptchaStatusChange: (status: CaptchaStatus) => void;
onRetryPlanAdvice: () => void;
onContinue: () => void;
onBack: () => void;
}) {
const { t } = useTranslation();
const formatters = useLocaleFormatters();
const selectedPlan = plans.find((plan) => plan.priceId === selectedPriceId) ?? plans[0];
const allConsents = acceptTerms && acceptPrivacy;
const capProofPending = captchaEnabled && captchaConfig.provider === "cap" && captchaStatus !== "solved";
return (
<div className={visible ? "flex w-full flex-col gap-6" : "hidden"} data-ui-id="ui.auth.register.planStep">
{screen === "team" ? (
<div className="flex w-full flex-col gap-6" data-ui-id="ui.auth.register.teamStep">
<div className="flex w-full items-start gap-3">
<IconWithBackground variant="information" size="medium" icon={<FeatherUsers />} />
<div className="flex min-w-0 flex-col gap-1">
<span className="text-body-default-semibold-0 font-body-default-semibold-0 text-text-neutral-primary">{t("account.register.teamSizeTitle")}</span>
<span className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary">
{t("account.register.teamSizeHint")}
</span>
</div>
</div>
<div className="mobile:grid-cols-1 grid w-full grid-cols-2 gap-4">
<div className="min-w-0 grow basis-0">
<SeatQuantityStepper
name="selectedOfficeSeatQuantity"
label={t("account.register.officeUsersLabel")}
description={t("account.register.officeUsersHint")}
value={officeSeatQuantity}
min={1}
sliderMax={50}
icon={<FeatherBriefcase />}
disabled={isSubmitting}
decreaseLabel={t("account.register.decreaseQuantity", { role: t("account.register.officeUsersLabel") })}
increaseLabel={t("account.register.increaseQuantity", { role: t("account.register.officeUsersLabel") })}
dataUiId="ui.auth.register.officeSeats"
onChange={onOfficeSeatQuantityChange}
/>
</div>
<div className="min-w-0 grow basis-0">
<SeatQuantityStepper
name="selectedFieldSeatQuantity"
label={t("account.register.fieldUsersLabel")}
description={t("account.register.fieldUsersHint")}
value={fieldSeatQuantity}
min={0}
sliderMax={100}
icon={<FeatherHardHat />}
disabled={isSubmitting}
decreaseLabel={t("account.register.decreaseQuantity", { role: t("account.register.fieldUsersLabel") })}
increaseLabel={t("account.register.increaseQuantity", { role: t("account.register.fieldUsersLabel") })}
dataUiId="ui.auth.register.fieldSeats"
onChange={onFieldSeatQuantityChange}
/>
</div>
</div>
<Card variant="neutral" size="small" className="gap-2 p-4">
<div className="flex w-full items-center gap-2">
<FeatherCheck className="text-body-default-regular-0 font-body-default-regular-0 text-icon-feedback-positive" />
<span className="text-body-small-semibold-0 font-body-small-semibold-0 text-text-neutral-primary">
{t("account.register.recommendationPromise")}
</span>
</div>
<span className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary px-6">
{t("account.register.recommendationPromiseHint")}
</span>
</Card>
<Button
type="button"
size="large"
className="w-full"
icon={<FeatherArrowLeft className="rotate-180" />}
disabled={isSubmitting || planAdviceLoading || planAdviceFailed}
onClick={onContinue}
data-ui-id="ui.auth.register.toPlanStep"
>
{t("account.register.continueToPlans")}
</Button>
</div>
) : (
<div className="flex w-full flex-col gap-4" data-ui-id="ui.auth.register.planSelection">
<div className="flex w-full flex-col gap-1">
<span className="text-body-small-semibold-0 font-body-small-semibold-0 text-text-neutral-primary">{t("account.register.planSelectionLabel")}</span>
<span className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary">
{t("account.register.planSelectionHint")}
</span>
</div>
{selectedPlan ? (
<RadioCardGroup
className="mobile:grid-cols-1 grid w-full grid-cols-3"
value={selectedPriceId}
onValueChange={onSelectPlan}
aria-label={t("account.register.planSelectionLabel")}
>
{plans.map((plan) => (
<RadioCardGroup.RadioCard key={plan.priceId} value={plan.priceId} disabled={isSubmitting || planAdviceLoading}>
<div className="flex h-full w-full flex-col gap-4">
<div className="flex w-full flex-col gap-2">
<div className="flex flex-wrap items-center gap-2">
<span className="text-heading- font-heading- text-text-neutral-primary">{t(plan.titleKey)}</span>
{plan.priceId === recommendedPriceId ? (
<BadgeFeedback farbe="subtle-brand-primary" size="small">
{t("account.register.recommendedBadge")}
</BadgeFeedback>
) : null}
</div>
<span className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary">
{t("account.register.teamConfigured", { office: officeSeatQuantity, field: fieldSeatQuantity })}
</span>
</div>
<span className="text-heading-0 font-heading-0 text-text-neutral-primary">
{t("account.register.planPriceMonthly", {
price: formatters.currencyFromCents(plan.amountCents, plan.currency),
})}
</span>
<div className="border-border-default flex w-full flex-col gap-2 border-0 border-t border-solid pt-3">
<span className="text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-secondary">
{t("account.register.planIncluded", {
office: plan.includedOfficeSeatQuantity,
field: plan.includedFieldSeatQuantity,
storage: plan.includedStorageGb,
})}
</span>
<span className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary">
{t("account.register.planStorageGrowth", {
storage: plan.storagePerAdditionalSeatGb,
})}
</span>
{plan.extraOfficeSeatQuantity > 0 || plan.extraFieldSeatQuantity > 0 ? (
<span className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary">
{t("account.register.planExtrasIncluded", {
office: plan.extraOfficeSeatQuantity,
field: plan.extraFieldSeatQuantity,
})}
</span>
) : null}
</div>
</div>
</RadioCardGroup.RadioCard>
))}
</RadioCardGroup>
) : null}
{planAdviceLoading ? (
<span className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary" role="status">
{t("account.register.recommendationLoading")}
</span>
) : null}
</div>
)}
{planAdviceFailed ? (
<div className="flex w-full flex-col items-start gap-3">
<Alert
variant="error"
notDismissible
title={t("account.register.recommendationErrorTitle")}
description={t("account.register.recommendationErrorBody")}
/>
<Button type="button" variant="secondary" disabled={isSubmitting || planAdviceLoading} onClick={onRetryPlanAdvice}>
{t("account.register.recommendationRetry")}
</Button>
</div>
) : null}
{screen === "plan" ? (
<Card variant="default" size="medium" className="mobile:flex-col w-full flex-row items-start gap-6" data-ui-id="ui.auth.register.confirmation">
{captchaEnabled ? (
<div className="mobile:w-full flex w-[360px] flex-none flex-col gap-3">
<div className="flex w-full items-start gap-3">
<IconWithBackground variant="neutral" size="medium" icon={<FeatherLock />} />
<div className="flex min-w-0 flex-col gap-1">
<span className="text-body-small-semibold-0 font-body-small-semibold-0 text-text-neutral-primary">{t("account.register.securityCheck")}</span>
<span className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary">
{t("account.register.securityCheckHint")}
</span>
</div>
</div>
{captchaResetKey ? (
<Alert
variant="neutral"
notDismissible
title={t("account.register.captchaReloadedTitle")}
description={t("account.register.captchaReloadedBody")}
/>
) : null}
<div className="border-border-default bg-surface-neutral-secondary flex w-full items-center justify-center rounded-md border border-solid px-3 py-3">
<Captcha
key={captchaResetKey ?? "initial-captcha"}
enabled
provider={captchaConfig.provider}
instanceUrl={captchaConfig.instanceUrl}
sitekey={captchaConfig.loginSiteKey}
onStatusChange={onCaptchaStatusChange}
/>
</div>
{captchaStatus === "error" ? (
<span className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-feedback-negative" role="alert">
{t("account.register.captchaClientError")}
</span>
) : null}
</div>
) : null}
<div className="flex min-w-0 grow basis-0 flex-col gap-4">
<div className="flex w-full flex-col items-start gap-3">
<ConsentRow
checked={acceptTerms}
label={t("account.register.consentTerms")}
href="/terms-and-conditions"
linkLabel={t("account.register.consentTermsLink")}
dataUiId="ui.auth.register.consentTerms"
onChange={onAcceptTermsChange}
/>
<ConsentRow
checked={acceptPrivacy}
label={t("account.register.consentPrivacy")}
href="/privacy-policy"
linkLabel={t("account.register.privacyPolicy")}
dataUiId="ui.auth.register.consentPrivacy"
onChange={onAcceptPrivacyChange}
/>
</div>
{error ? (
<p className="text-body-small-regular-0 font-body-small-regular-0 text-text-feedback-negative" role="alert">
{error}
</p>
) : null}
<div className="flex w-full flex-col items-start gap-2">
<Button
type="submit"
size="large"
className="w-full flex-none"
icon={<FeatherCreditCard />}
loading={isSubmitting}
disabled={isSubmitting || !allConsents || planAdviceLoading || planAdviceFailed || capProofPending || !selectedPlan}
data-ui-id="ui.auth.register.submit"
>
{t("account.register.continueWithPlan", { plan: selectedPlan ? t(selectedPlan.titleKey) : "" })}
</Button>
<div className="flex w-full items-start justify-center gap-1.5">
{requireEmailVerification ? (
<FeatherMail className="text-body-small-regular-0 font-body-small-regular-0 text-icon-neutral-tertiary mt-0.5" />
) : (
<FeatherLock className="text-body-small-regular-0 font-body-small-regular-0 text-icon-neutral-tertiary mt-0.5" />
)}
<span className="text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary text-center">
{t(requireEmailVerification ? "account.register.noPaymentYet" : "account.register.checkoutNext")}
</span>
</div>
</div>
</div>
</Card>
) : null}
<Button
type="button"
className="self-start"
variant="ghost"
icon={<FeatherArrowLeft />}
onClick={onBack}
disabled={isSubmitting}
data-ui-id={screen === "plan" ? "ui.auth.register.backToTeam" : "ui.auth.register.backToAccount"}
>
{t(screen === "plan" ? "account.register.backToTeam" : "account.register.backToAccount")}
</Button>
</div>
);
}
function ConsentRow({
checked,
label,
href,
linkLabel,
dataUiId,
onChange,
}: {
checked: boolean;
label: string;
href: string;
linkLabel: string;
dataUiId: string;
onChange: (checked: boolean) => void;
}) {
const { t } = useTranslation();
return (
<div className="flex w-full items-center gap-2">
<Checkbox label={label} hideLabel checked={checked} onCheckedChange={onChange} data-ui-id={dataUiId} />
<div className="flex min-h-5 flex-wrap items-center gap-1">
<span className="text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-secondary">{t("account.register.consentAcceptPrefix")}</span>
<a href={href} target="_blank" rel="noreferrer" className="no-underline">
<LinkButton size="small" hideIcon>
{linkLabel}
</LinkButton>
</a>
</div>
</div>
);
}
function SeatQuantityStepper({
name,
label,
description,
value,
min,
max = 10_000,
sliderMax,
icon,
disabled,
decreaseLabel,
increaseLabel,
dataUiId,
onChange,
}: {
name: string;
label: string;
description: string;
value: number;
min: number;
max?: number;
sliderMax: number;
icon: React.ReactNode;
disabled: boolean;
decreaseLabel: string;
increaseLabel: string;
dataUiId: string;
onChange: (value: number) => void;
}) {
return (
<Card size="small" variant="default" className="h-full justify-between gap-3 p-4" data-ui-id={dataUiId}>
<div className="flex w-full items-start gap-3 px-1">
<IconWithBackground variant="neutral" size="medium" icon={icon} />
<div className="flex min-w-0 flex-col gap-1">
<span className="text-body-small-semibold-0 font-body-small-semibold-0 text-text-neutral-primary">{label}</span>
<span className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary">{description}</span>
</div>
</div>
<Slider
min={min}
max={sliderMax}
step={1}
value={[Math.min(value, sliderMax)]}
valueText={value}
description={value > sliderMax ? `${sliderMax}+` : undefined}
disabled={disabled}
onValueChange={(values) => onChange(values[0] ?? min)}
aria-label={label}
/>
<div className="flex w-full items-center justify-between gap-3" role="group" aria-label={label}>
<IconButton
type="button"
variant="tertiary"
square
size="medium"
icon={<FeatherMinus />}
aria-label={decreaseLabel}
disabled={disabled || value <= min}
onClick={() => onChange(Math.max(min, value - 1))}
data-ui-id={`${dataUiId}.decrease`}
/>
<TextInput className="max-w-24" type="number">
<TextInput.Input
name={name}
type="number"
min={min}
max={max}
step={1}
value={value}
aria-label={label}
disabled={disabled}
onChange={(event) => {
const nextValue = event.currentTarget.valueAsNumber;
if (Number.isFinite(nextValue)) {
onChange(Math.min(max, Math.max(min, nextValue)));
}
}}
/>
</TextInput>
<IconButton
type="button"
variant="tertiary"
square
size="medium"
icon={<FeatherPlus />}
aria-label={increaseLabel}
disabled={disabled || value >= max}
onClick={() => onChange(Math.min(max, value + 1))}
data-ui-id={`${dataUiId}.increase`}
/>
</div>
</Card>
);
}
@@ -110,7 +110,13 @@ export default function ResetPasswordScreen({
/>
</TextInput>
</div>
<Progress className="h-auto w-full flex-none" hideLabel value={strength} state={strength >= 80 ? "success" : undefined} />
<Progress
className="h-auto w-full flex-none"
hideLabel
label={t("account.register.passwordStrength")}
value={strength}
state={strength >= 80 ? "success" : undefined}
/>
<div className="flex w-full items-center justify-between">
<span className="text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary">
{t("account.register.passwordStrength")}: {strengthLabel}
@@ -104,7 +104,11 @@ export default function RolesListView({
{editable ? (
<SubframeCore.DropdownMenu.Root>
<SubframeCore.DropdownMenu.Trigger asChild>
<IconButton icon={<FeatherMoreHorizontal />} data-ui-id="ui.settings.rolesAndPermissions.roles.rowActions" />
<IconButton
icon={<FeatherMoreHorizontal />}
aria-label={`${t("shared.actions")}: ${roleDisplayName(role, t)}`}
data-ui-id="ui.settings.rolesAndPermissions.roles.rowActions"
/>
</SubframeCore.DropdownMenu.Trigger>
<SubframeCore.DropdownMenu.Portal>
<SubframeCore.DropdownMenu.Content side="bottom" align="end" sideOffset={4} asChild>
@@ -5,6 +5,7 @@ import { FeatherAlertTriangle, FeatherLogOut, FeatherMonitor, FeatherShieldOff,
import type { SessionListVM } from "@hivegrid/view-models";
import { Button } from "~/ui/components/Button";
import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
import { Card } from "~/ui/components/Card";
// D-P2 — Settings > Sicherheit nach Davids Subframe-"Session Management"-Design: Header (Titel + "Überall
// abmelden") + Geräte-Card (Icon + Label/Standort + "Dieses Gerät"-Badge / "Abmelden") + Confirm-Overlay
@@ -44,19 +45,11 @@ export default function SecuritySessionsScreen({
const onlyThisDevice = ready && devices.length <= 1 && !vm.data.canRevokeOthers;
return (
<div className="relative flex w-full flex-col items-center" data-ui-id="ui.settings.security.page">
<div className="flex w-full max-w-[768px] flex-col items-start gap-8">
{/* Header */}
<div className="flex w-full items-start justify-between gap-4 mobile:flex-col">
<div className="flex flex-col items-start gap-2">
<span className="text-title-page font-title-page text-text-neutral-primary mobile:text-subtitle mobile:font-subtitle">
{t("settings.security.title")}
</span>
<span className="text-body-default-regular-150 font-body-default-regular-150 text-text-neutral-tertiary">
{t("settings.security.sessions.subtitle")}
</span>
</div>
{ready && vm.data.canRevokeOthers ? (
<div className="relative flex w-full flex-col" data-ui-id="ui.settings.security.page">
<div className="flex w-full flex-col items-start gap-8">
{/* Page headline (title/subtitle) lives in the route's shared PageHeader; only the page-level action stays here. */}
{ready && vm.data.canRevokeOthers ? (
<div className="flex w-full items-start justify-end mobile:flex-col">
<Button
variant="secondary"
icon={<FeatherLogOut />}
@@ -66,15 +59,11 @@ export default function SecuritySessionsScreen({
>
{t("settings.security.sessions.revokeAll")}
</Button>
) : null}
</div>
</div>
) : null}
{/* Aktive Sitzungen */}
<section
className="flex w-full flex-col items-start rounded-lg border border-solid border-border-default bg-surface-neutral-secondary px-6 py-6 shadow-sm"
data-ui-id="ui.settings.security.sessions"
aria-label={t("settings.security.sessions.heading")}
>
<Card className="w-full" data-ui-id="ui.settings.security.sessions" aria-label={t("settings.security.sessions.heading")}>
{!ready ? (
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
{t("settings.security.sessions.empty")}
@@ -120,7 +109,7 @@ export default function SecuritySessionsScreen({
);
})
)}
</section>
</Card>
{onlyThisDevice ? (
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
@@ -154,7 +143,7 @@ export default function SecuritySessionsScreen({
{t("settings.security.trustedDevices.forgetAll")}
</Button>
</div>
<div className="flex w-full flex-col items-start rounded-lg border border-solid border-border-default bg-surface-neutral-secondary px-6 py-6 shadow-sm">
<Card className="w-full">
{trustedDevices.map((device, index) => (
<Fragment key={device.id}>
{index > 0 ? <div className="flex h-px w-full flex-none flex-col items-start bg-border-default" /> : null}
@@ -181,7 +170,7 @@ export default function SecuritySessionsScreen({
</div>
</Fragment>
))}
</div>
</Card>
</section>
) : null}
</div>
@@ -7,6 +7,7 @@ import { Button } from "~/ui/components/Button";
import { LinkButton } from "~/ui/components/LinkButton";
import { Progress } from "~/ui/components/Progress";
import { TextInput } from "~/ui/components/TextInput";
import { useRootData } from "~/utils/data/useRootData";
// Set-Password-Screen (WF-P2 / S01 "Neues Passwort setzen") nach Davids Subframe-Design: Card mit
// "Neues Passwort festlegen" + Stärke-Anzeige + Bestätigung + "Passwort setzen", Sicherheits-Footer.
@@ -40,6 +41,7 @@ export default function SetPasswordScreen({
actionData: { error?: string; invitationAccepted?: boolean } | null | undefined;
}) {
const { t } = useTranslation();
const { csrf } = useRootData();
const navigation = useNavigation();
const navigate = useNavigate();
const isSubmitting = navigation.state !== "idle";
@@ -85,11 +87,20 @@ export default function SetPasswordScreen({
dataUiId="ui.auth.setPassword.existingUser"
>
<Form method="post" className="flex w-full flex-col gap-4" data-ui-id="ui.auth.setPassword.acceptForm">
<Button type="submit" name="intent" value="set-password" className="h-9 w-full flex-none" loading={isSubmitting} disabled={isSubmitting} data-ui-id="ui.auth.setPassword.acceptSubmit">
<input type="hidden" name="csrf" value={csrf ?? ""} readOnly />
<Button
type="submit"
name="intent"
value="set-password"
className="h-9 w-full flex-none"
loading={isSubmitting}
disabled={isSubmitting}
data-ui-id="ui.auth.setPassword.acceptSubmit"
>
{t("account.invitation.button")}
</Button>
{actionData?.error && navigation.state === "idle" ? (
<p className="text-center text-body-small-regular-0 font-body-small-regular-0 text-text-feedback-negative" role="alert">
<p className="text-body-small-regular-0 font-body-small-regular-0 text-text-feedback-negative text-center" role="alert">
{actionData.error}
</p>
) : null}
@@ -123,11 +134,15 @@ export default function SetPasswordScreen({
</div>
}
>
<span className="w-full text-center text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary" data-ui-id="ui.auth.setPassword.invitedContext">
<span
className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary w-full text-center"
data-ui-id="ui.auth.setPassword.invitedContext"
>
{`${t("shared.hi")} ${invitedName}, ${t("account.invitation.youWereInvited")} ${invitation.tenant.name}`}
</span>
<Form id="setPasswordForm" method="post" noValidate className="flex w-full flex-col gap-5" data-ui-id="ui.auth.setPassword.form">
<input type="hidden" name="csrf" value={csrf ?? ""} readOnly />
<div className="flex w-full flex-col items-start gap-2">
<TextInput className="h-auto w-full flex-none" fillContainer showLabel label={t("account.newPassword.passwordLabel")} type="password">
<TextInput.Input
@@ -147,7 +162,7 @@ export default function SetPasswordScreen({
<span className="text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary">
{t("account.register.passwordStrength")}: {strengthLabel}
</span>
<span className="w-full text-body-extra-small-medium-150 font-body-extra-small-medium-150 text-text-neutral-tertiary">
<span className="text-body-extra-small-medium-150 font-body-extra-small-medium-150 text-text-neutral-tertiary w-full">
{t("account.setPassword.passwordHint")}
</span>
</div>
@@ -164,12 +179,20 @@ export default function SetPasswordScreen({
/>
</TextInput>
<Button type="submit" name="intent" value="set-password" className="h-9 w-full flex-none" loading={isSubmitting} disabled={isSubmitting} data-ui-id="ui.auth.setPassword.submit">
<Button
type="submit"
name="intent"
value="set-password"
className="h-9 w-full flex-none"
loading={isSubmitting}
disabled={isSubmitting}
data-ui-id="ui.auth.setPassword.submit"
>
{t("account.setPassword.button")}
</Button>
{actionData?.error && navigation.state === "idle" ? (
<p className="text-center text-body-small-regular-0 font-body-small-regular-0 text-text-feedback-negative" role="alert">
<p className="text-body-small-regular-0 font-body-small-regular-0 text-text-feedback-negative text-center" role="alert">
{actionData.error}
</p>
) : null}
@@ -2,7 +2,6 @@ import { useSubmit } from "react-router";
import { useTranslation } from "react-i18next";
import { PlanFeatureUsageDto } from "~/application/dtos/subscriptions/PlanFeatureUsageDto";
import MyProducts from "~/components/core/settings/subscription/MyProducts";
import MySubscriptionFeatures from "~/components/core/settings/subscription/MySubscriptionFeatures";
import MyInvoices from "~/components/core/settings/subscription/MyInvoices";
import SettingSection from "~/components/ui/sections/SettingSection";
import { TenantSubscriptionProductWithDetails } from "~/utils/db/subscriptions/tenantSubscriptionProducts.db.server";
@@ -12,15 +11,25 @@ import type { CustomerBillingInvoiceDto } from "~/application/dtos/billing/Custo
import type { SubscriptionProductDto } from "~/application/dtos/subscriptions/SubscriptionProductDto";
import type { SubscriptionBillingPeriod } from "~/application/enums/subscriptions/SubscriptionBillingPeriod";
import PlansGrouped from "~/components/core/settings/subscription/plans/PlansGrouped";
import SeatUsageSection from "~/components/core/settings/subscription/SeatUsageSection";
import { Alert } from "~/ui/components/Alert";
import type { SeatUsageVM, SubscriptionBannerTone, SubscriptionBannerVM } from "@hivegrid/view-models";
function bannerVariant(tone: SubscriptionBannerTone): "success" | "warning" | "error" {
if (tone === "success") return "success";
if (tone === "warning") return "warning";
return "error";
}
export default function SubscriptionSettings({
mySubscription,
myFeatures,
myInvoices,
availablePlans,
currenciesAndPeriod,
invoiceErrorKey,
permissions,
billingBanner,
seatUsage,
}: {
mySubscription: TenantSubscriptionWithDetails | null;
myFeatures: PlanFeatureUsageDto[];
@@ -32,6 +41,9 @@ export default function SubscriptionSettings({
};
invoiceErrorKey?: string | null;
permissions: { viewInvoices: boolean; manageSubscription: boolean };
billingBanner?: SubscriptionBannerVM;
seatUsage?: SeatUsageVM;
storageLimitGb?: number | null;
}) {
const { t } = useTranslation();
const submit = useSubmit();
@@ -57,6 +69,15 @@ export default function SubscriptionSettings({
return (
<div className="space-y-4" data-ui-id="ui.subscription.page">
{billingBanner?.status === "ready" ? (
<Alert
variant={bannerVariant(billingBanner.data.tone)}
notDismissible
title={t(billingBanner.data.titleKey)}
description={t(billingBanner.data.descriptionKey)}
data-ui-id="ui.subscription.statusBanner"
/>
) : null}
<SettingSection
title={t("settings.subscription.title")}
description={
@@ -69,6 +90,20 @@ export default function SubscriptionSettings({
<MyProducts items={mySubscription?.products ?? []} onCancel={onCancel} />
</SettingSection>
{seatUsage && seatUsage.status !== "idle" && (
<>
<div className="hidden sm:block" aria-hidden="true">
<div className="py-4">
<div className="border-border border-t"></div>
</div>
</div>
<SettingSection title={t("settings.subscription.seats.title")} description={t("settings.subscription.seats.description")} className="">
<SeatUsageSection vm={seatUsage} />
</SettingSection>
</>
)}
{availablePlans.length > 0 && (
<>
<div className="hidden sm:block" aria-hidden="true">
@@ -89,20 +124,6 @@ export default function SubscriptionSettings({
</>
)}
{myFeatures.length > 0 && (
<>
<div className="hidden sm:block" aria-hidden="true">
<div className="py-4">
<div className="border-border border-t"></div>
</div>
</div>
<SettingSection title={t("app.subscription.features.title")} description={t("app.subscription.features.description")} className="">
<MySubscriptionFeatures features={myFeatures} withCurrentPlan={false} />
</SettingSection>
</>
)}
{permissions.viewInvoices && (
<>
<div className="hidden sm:block" aria-hidden="true">
@@ -13,10 +13,10 @@ import SuccessModal, { RefSuccessModal } from "~/components/ui/modals/SuccessMod
import SettingSection from "~/components/ui/sections/SettingSection";
import UploadDocuments from "~/components/ui/uploaders/UploadDocument";
import UploadImage from "~/components/ui/uploaders/UploadImage";
import { i18nConfig } from "~/locale/i18n";
import type { CurrentSessionSettings } from "~/routes/app.$tenant/settings/profile";
import type { CurrentSessionSettings } from "~/routes/app.$tenant/settings/profile/index";
import { useRootData } from "~/utils/data/useRootData";
import { UserIcon } from "~/components/ui/icons/vendor";
import { defaultEnabledLocales } from "~/locale/i18n";
type UserProfileMfaStatus = {
enabled: boolean;
@@ -83,7 +83,8 @@ export default function UserProfileSettings({
const { t, i18n } = useTranslation();
const navigation = useNavigation();
const submit = useSubmit();
const { csrf } = useRootData();
const { csrf, enabledLocales } = useRootData();
const selectableLocales = enabledLocales ?? defaultEnabledLocales;
const errorModal = useRef<RefErrorModal>(null);
const successModal = useRef<RefSuccessModal>(null);
@@ -431,7 +432,7 @@ export default function UserProfileSettings({
required
value={i18n.language}
setValue={(e) => changedLocale(e?.toString() || "")}
options={i18nConfig.supportedLngs.map((locale) => ({ value: locale, name: t("shared.locales." + locale) }))}
options={selectableLocales.map((locale) => ({ value: locale, name: t("shared.locales." + locale) }))}
/>
</div>
</div>