Merge pull request 'Repo cleanup pass: assets, FeatureGrid, templates, create-flow UX, and API tests' (#53) from adilallo/Cleanup into main

Reviewed-on: #53
This commit was merged in pull request #53.
This commit is contained in:
2026-05-22 20:14:14 +00:00
291 changed files with 4802 additions and 2658 deletions
+1
View File
@@ -18,6 +18,7 @@ the file tree without affecting URLs.
| `app/(app)/` | `/create/*`, `/login`, `/profile`, future signed-in surfaces | Authenticated product | `Top` (via root) — no footer except **`/profile`** (see `profile/layout.tsx`) |
| `app/(admin)/` | `/monitor`, future ops dashboards | Operators | `Top` (via root) — no footer |
| `app/(dev)/` | `/components-preview`, future dev previews | Local dev (NODE_ENV gated) | `Top` (via root) — no footer |
| `app/(marketing-case-study)/` | `/use-cases/[slug]/rule` | Public case-study demos | Chromeless (no global `Top`; see `navigationChromelessPath.ts`) |
| `app/api/` | API routes | n/a | n/a |
Route folders **must not** sit loose at the top level of `app/`. If a new
+1
View File
@@ -15,6 +15,7 @@ SMTP_FROM="Community Rule <noreply@localhost>"
ORGANIZER_INQUIRY_TO=
# Set to `true` to sync the create-flow draft with `/api/drafts/me` when the user is signed in.
# Server draft sync (default on). Set to `false` to disable PUT/GET /api/drafts/me.
NEXT_PUBLIC_ENABLE_BACKEND_SYNC=
# Web vitals API (CR-80): `external` = structured logs only, no writes under `.next` (default in production).
+2 -1
View File
@@ -68,7 +68,8 @@ Run these (in order) before declaring a change done:
```bash
rm -rf .next # only if you moved/renamed routes or layouts
npx tsc --noEmit # type check
npx vitest run # unit + component (101 files / ~700 tests)
npm run knip # unused files / exports (local; no remote CI)
npx vitest run # unit + component (~185 test files)
npx next build # production build + route manifest
```
+16 -4
View File
@@ -46,6 +46,18 @@ deployment-pipeline work.
| GET | `/api/templates` | List curated templates. Optional repeatable `facet.<group>=<value>` query params re-rank results (and may include `scores` in the JSON). See [docs/guides/template-recommendation-matrix.md](docs/guides/template-recommendation-matrix.md) §9.1. |
| GET | `/api/create-flow/methods` | Facet-aware scores for custom-rule card steps: required `section` (`communication` \| `membership` \| `decisionApproaches` \| `conflictManagement`) and optional `facet.*` params (same facet groups as `/api/templates`). Returns `methods` with match metadata for re-ordering in the wizard. |
| POST / GET | `/api/web-vitals` | Ingest or read web vitals. **Production default:** `external` — structured logs only (no writes under `.next`; safe for read-only FS). **Development default:** `local` — aggregates under `.next/web-vitals`. Override with `WEB_VITALS_STORAGE`. See [docs/guides/backend-roadmap.md](docs/guides/backend-roadmap.md) §7. |
| GET | `/api/rules/me` | Authenticated list of own published rules. |
| GET / PATCH / DELETE | `/api/rules/[id]` | Public read; owner update/delete. |
| POST | `/api/rules/[id]/duplicate` | Owner clone of a published rule. |
| GET / POST | `/api/rules/[id]/stakeholders` | List or invite rule stakeholders. |
| DELETE | `/api/rules/[id]/stakeholders/[stakeholderId]` | Remove a stakeholder. |
| POST | `/api/rules/[id]/stakeholders/[stakeholderId]/resend` | Resend stakeholder invite email. |
| GET | `/api/invites/rule-stakeholder/verify` | Verify stakeholder invite token; redirect. |
| DELETE | `/api/user/me` | Delete authenticated user account. |
| POST | `/api/user/email-change/request` | Request email change (magic link to new address). |
| GET | `/api/user/email-change/verify` | Verify email-change token; update `User.email`. |
| POST | `/api/organizer-inquiry` | Submit ask-organizer inquiry form. |
| POST | `/api/use-cases/[slug]/duplicate` | Duplicate a use-case demo rule. |
### Magic-link sign-in
@@ -58,10 +70,10 @@ deployment-pipeline work.
### Optional draft sync
`NEXT_PUBLIC_ENABLE_BACKEND_SYNC=true` enables Postgres draft persistence
via `PUT /api/drafts/me` for signed-in users and post-sign-in upload of
anonymous drafts. Without it, anonymous progress stays in `localStorage`
and signed-in progress stays in memory until **Save & Exit**.
Postgres draft persistence via `PUT /api/drafts/me` is **on by default** for
signed-in users and post-sign-in transfer of anonymous drafts. Set
`NEXT_PUBLIC_ENABLE_BACKEND_SYNC=false` to disable server sync (anonymous
progress stays in `localStorage` only).
### Create flow
@@ -1,5 +1,9 @@
"use client";
/**
* Figma: "WebVitalsDashboard" (see registry)
*/
import { memo, useEffect, useState } from "react";
import { useMessages } from "../../../../contexts/MessagesContext";
import { logger } from "../../../../../lib/logger";
@@ -4,6 +4,7 @@ import {
Suspense,
useCallback,
useEffect,
useRef,
useState,
type ReactNode,
} from "react";
@@ -80,6 +81,7 @@ import { PostLoginDraftTransfer } from "./PostLoginDraftTransfer";
import { SignedInDraftHydration } from "./SignedInDraftHydration";
import { CreateFlowPendingAvatarFlush } from "./components/CreateFlowPendingAvatarFlush";
import Alert from "../../components/modals/Alert";
import Create from "../../components/modals/Create";
import Share from "../../components/modals/Share";
import {
CreateFlowDraftSaveBannerProvider,
@@ -190,6 +192,26 @@ function CreateFlowLayoutContent({
description?: string;
} | null>(null);
const [shareModalOpen, setShareModalOpen] = useState(false);
const [leaveConfirmOpen, setLeaveConfirmOpen] = useState(false);
const leaveConfirmResolverRef = useRef<((proceed: boolean) => void) | null>(
null,
);
const confirmLeave = useCallback(
() =>
new Promise<boolean>((resolve) => {
leaveConfirmResolverRef.current = resolve;
setLeaveConfirmOpen(true);
}),
[],
);
const closeLeaveConfirm = useCallback((proceed: boolean) => {
setLeaveConfirmOpen(false);
const resolve = leaveConfirmResolverRef.current;
leaveConfirmResolverRef.current = null;
resolve?.(proceed);
}, []);
const {
copyPublishedRuleLink,
@@ -256,6 +278,7 @@ function CreateFlowLayoutContent({
router,
user: sessionUser ?? null,
setDraftSaveBannerMessage,
confirmLeave,
});
const handleExit = async (opts?: { saveDraft?: boolean }) => {
@@ -601,6 +624,28 @@ function CreateFlowLayoutContent({
onSlackShare={() => void sharePublishedRuleViaSlack()}
onDiscordShare={() => void sharePublishedRuleViaDiscord()}
/>
<Create
isOpen={leaveConfirmOpen}
onClose={() => closeLeaveConfirm(false)}
title={messages.create.topNav.leaveConfirmTitle}
description={messages.create.topNav.leaveConfirmDescription}
showBackButton={false}
showNextButton
nextButtonText={messages.create.topNav.leaveConfirmProceed}
onNext={() => closeLeaveConfirm(true)}
footerContent={
<Button
buttonType="ghost"
palette="default"
size="xsmall"
onClick={() => closeLeaveConfirm(false)}
>
{messages.create.topNav.leaveConfirmCancel}
</Button>
}
backdropVariant="blurredYellow"
ariaLabel={messages.create.topNav.leaveConfirmTitle}
/>
<CreateFlowTopNav
hasShare={isCompletedStep}
hasExport={isCompletedStep}
+13 -7
View File
@@ -2,18 +2,24 @@
import dynamic from "next/dynamic";
import type { ReactNode } from "react";
import { useTranslation } from "../../contexts/MessagesContext";
function CreateFlowLayoutLoading() {
const t = useTranslation("controlsChrome");
return (
<div
className="flex h-screen min-h-0 flex-col overflow-hidden bg-black"
aria-busy="true"
aria-label={t("loadingCreateFlow")}
/>
);
}
const CreateFlowLayoutClient = dynamic(
() => import("./CreateFlowLayoutClient"),
{
ssr: false,
loading: () => (
<div
className="flex h-screen min-h-0 flex-col overflow-hidden bg-black"
aria-busy="true"
aria-label="Loading create flow"
/>
),
loading: () => <CreateFlowLayoutLoading />,
},
);
+2 -2
View File
@@ -15,7 +15,7 @@ import type { CreateFlowState } from "./types";
import messages from "../../../messages/en/index";
import Alert from "../../components/modals/Alert";
const SYNC_ENABLED = process.env.NEXT_PUBLIC_ENABLE_BACKEND_SYNC === "true";
import { isBackendSyncEnabled } from "../../../lib/create/backendSyncEnabled";
function buildPayloadWithStep(
base: CreateFlowState,
@@ -111,7 +111,7 @@ export function PostLoginDraftTransfer({
return;
}
if (SYNC_ENABLED && createFlowStateHasKeys(local)) {
if (isBackendSyncEnabled() && createFlowStateHasKeys(local)) {
const saveResult = await saveDraftToServer(payload);
if (cancelled) return;
+2 -2
View File
@@ -17,7 +17,7 @@ import {
parseCreateFlowScreenFromPathname,
} from "./utils/flowSteps";
const SYNC_ENABLED = process.env.NEXT_PUBLIC_ENABLE_BACKEND_SYNC === "true";
import { isBackendSyncEnabled } from "../../../lib/create/backendSyncEnabled";
/**
* When sync is on and the user is signed in, restore the server-side draft only
@@ -54,7 +54,7 @@ export function SignedInDraftHydration({
const finishedUserIdRef = useRef<string | null>(null);
useEffect(() => {
if (!SYNC_ENABLED) return;
if (!isBackendSyncEnabled()) return;
if (!sessionResolved) return;
if (sessionUser == null || sessionUser === undefined) {
finishedUserIdRef.current = null;
@@ -1,364 +0,0 @@
"use client";
/**
* Controlled field blocks for wizard-authored method cards in Create modals
* (facet screens + final-review chip edit). When `onBlocksChange` is omitted,
* blocks render read-only (disabled controls).
*
* Layout matches preset method editors ({@link CommunicationMethodEditFields},
* {@link DecisionApproachEditFields}): {@link ModalTextAreaField},
* {@link ApplicableScopeField} chip rows, {@link IncrementerBlock}.
*/
import { memo, useCallback, useRef, useState } from "react";
import { useMessages, useTranslation } from "../../../contexts/MessagesContext";
import Chip from "../../../components/controls/Chip";
import IncrementerBlock from "../../../components/controls/IncrementerBlock";
import Upload from "../../../components/controls/Upload";
import { getAssetPath } from "../../../../lib/assetUtils";
import ApplicableScopeField from "./ApplicableScopeField";
import InputLabel from "../../../components/type/InputLabel";
import type { CustomMethodCardFieldBlock } from "../../../../lib/create/customMethodCardFieldBlocks";
import ModalTextAreaField from "./ModalTextAreaField";
import { uploadCreateFlowFile } from "../../../../lib/create/uploadToServer";
const TEXT_VALUE_MAX = 8000;
export interface CustomMethodCardFieldBlocksSummaryProps {
blocks: CustomMethodCardFieldBlock[];
/** When set, fields update the draft via immutable block-array replacements. */
onBlocksChange?: (_next: CustomMethodCardFieldBlock[]) => void;
}
function mapBlockById(
blocks: CustomMethodCardFieldBlock[],
blockId: string,
mapFn: (_b: CustomMethodCardFieldBlock) => CustomMethodCardFieldBlock,
): CustomMethodCardFieldBlock[] {
return blocks.map((b) => (b.id === blockId ? mapFn(b) : b));
}
function CustomMethodCardUploadBlockRow({
block,
blocks,
patch,
uploadFileInputAriaLabel,
uploadHint,
clearPendingUploadAriaLabel,
clearPendingUploadTooltip,
uploadPreviewImageAlt,
noFileChosen,
}: {
block: Extract<CustomMethodCardFieldBlock, { kind: "upload" }>;
blocks: CustomMethodCardFieldBlock[];
patch: (_next: CustomMethodCardFieldBlock[]) => void;
uploadFileInputAriaLabel: string;
uploadHint: string;
clearPendingUploadAriaLabel: string;
clearPendingUploadTooltip: string;
uploadPreviewImageAlt: string;
noFileChosen: string;
}) {
const uploadInputRef = useRef<HTMLInputElement | null>(null);
const tUpload = useTranslation("create.upload");
const [busy, setBusy] = useState(false);
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const displayName = block.fileName?.trim() ? block.fileName : noFileChosen;
const assetUrlTrimmed = block.assetUrl?.trim() ?? "";
const hasAsset = assetUrlTrimmed.length > 0;
const clearUpload = () =>
patch(
mapBlockById(blocks, block.id, (b) =>
b.kind === "upload"
? { ...b, fileName: undefined, assetUrl: undefined }
: b,
),
);
return (
<div className="flex flex-col gap-2">
<InputLabel
label={block.blockTitle}
helpIcon
size="s"
palette="default"
/>
{!hasAsset ? (
<p className="font-[family-name:var(--font-body)] text-[length:var(--font-size-body-m)] text-[var(--color-content-default-secondary)]">
{displayName}
</p>
) : null}
<input
ref={uploadInputRef}
type="file"
className="sr-only"
tabIndex={-1}
accept="image/jpeg,image/png,image/webp,image/gif,application/pdf"
aria-label={uploadFileInputAriaLabel}
onChange={(e) => {
const file = e.target.files?.[0];
e.target.value = "";
if (!file) return;
setErrorMessage(null);
setBusy(true);
void (async () => {
try {
const { url } = await uploadCreateFlowFile(
file,
"customMethodAttachment",
);
const name = file.name?.trim();
patch(
mapBlockById(blocks, block.id, (b) =>
b.kind === "upload"
? {
...b,
...(name ? { fileName: name } : {}),
assetUrl: url,
}
: b,
),
);
} catch {
setErrorMessage(tUpload("errors.generic"));
} finally {
setBusy(false);
}
})();
}}
/>
{hasAsset ? (
<div className="relative inline-block max-w-full">
<button
type="button"
onClick={clearUpload}
className="absolute right-[8px] top-[8px] z-[1] flex h-[32px] w-[32px] cursor-pointer items-center justify-center rounded-full bg-[var(--color-surface-default-secondary)] focus:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-border-invert-primary)] focus-visible:ring-offset-2 focus-visible:ring-offset-[var(--color-surface-default-primary)]"
aria-label={clearPendingUploadAriaLabel}
title={clearPendingUploadTooltip}
>
{/* eslint-disable-next-line @next/next/no-img-element -- matches ModalHeader close control */}
<img
src={getAssetPath("assets/Icon_Close.svg")}
alt=""
className="h-[16px] w-[16px]"
style={{
filter: "brightness(0) invert(1)",
}}
/>
</button>
{/* eslint-disable-next-line @next/next/no-img-element -- same-origin upload URL */}
<img
src={assetUrlTrimmed}
alt={uploadPreviewImageAlt}
className="max-h-[160px] max-w-full rounded-[var(--measures-radius-200,8px)] object-contain"
/>
</div>
) : (
<Upload
active={!busy}
hintText={busy ? tUpload("uploading") : uploadHint}
onClick={() => {
if (!busy) uploadInputRef.current?.click();
}}
/>
)}
{errorMessage ? (
<p
className="font-[family-name:var(--font-body)] text-[length:var(--font-size-body-s)] text-[var(--color-content-default-secondary)]"
role="alert"
>
{errorMessage}
</p>
) : null}
</div>
);
}
function CustomMethodCardFieldBlocksSummaryComponent({
blocks,
onBlocksChange,
}: CustomMethodCardFieldBlocksSummaryProps) {
const m = useMessages();
const wiz = m.create.customRule.customMethodCardWizard;
const fm = wiz.fieldModals;
const em = wiz.editModal;
const emptyValue = em.readout.emptyValue;
const noFileChosen = em.readout.noFileChosen;
const readOnly = !onBlocksChange;
const patch = useCallback(
(next: CustomMethodCardFieldBlock[]) => {
onBlocksChange?.(next);
},
[onBlocksChange],
);
return (
<div className="flex flex-col gap-6">
{blocks.map((block) => {
if (block.kind === "text") {
return (
<ModalTextAreaField
key={block.id}
label={block.blockTitle}
rows={6}
value={block.placeholderText}
onChange={(v) =>
patch(
mapBlockById(blocks, block.id, (b) =>
b.kind === "text"
? { ...b, placeholderText: v.slice(0, TEXT_VALUE_MAX) }
: b,
),
)
}
disabled={readOnly}
/>
);
}
if (block.kind === "badges") {
if (readOnly) {
return (
<div key={block.id} className="flex flex-col gap-2">
<InputLabel
label={block.blockTitle}
helpIcon
size="s"
palette="default"
/>
{block.options.length > 0 ? (
<div className="flex flex-wrap items-center gap-2">
{block.options.map((opt, idx) => (
<Chip
key={`${block.id}-${idx}`}
label={opt}
state="selected"
palette="default"
size="s"
disabled
ariaLabel={opt}
/>
))}
</div>
) : (
<p className="font-[family-name:var(--font-body)] text-[length:var(--font-size-body-m)] text-[var(--color-content-default-secondary)]">
{emptyValue}
</p>
)}
</div>
);
}
return (
<ApplicableScopeField
key={block.id}
label={block.blockTitle}
addLabel={fm.badges.addOptionLabel}
scopes={block.options}
selectedScopes={block.options}
onToggleScope={(scope) =>
patch(
mapBlockById(blocks, block.id, (b) =>
b.kind === "badges"
? { ...b, options: b.options.filter((o) => o !== scope) }
: b,
),
)
}
onAddScope={(scope) =>
patch(
mapBlockById(blocks, block.id, (b) => {
if (b.kind !== "badges") return b;
if (b.options.includes(scope) || b.options.length >= 50)
return b;
return { ...b, options: [...b.options, scope] };
}),
)
}
/>
);
}
if (block.kind === "upload") {
return (
<div key={block.id}>
{readOnly ? (
<div className="flex flex-col gap-2">
<InputLabel
label={block.blockTitle}
helpIcon
size="s"
palette="default"
/>
{block.assetUrl?.trim() ? (
// eslint-disable-next-line @next/next/no-img-element
<img
src={block.assetUrl.trim()}
alt={
block.fileName?.trim() ||
block.blockTitle ||
noFileChosen
}
className="max-h-[160px] max-w-full rounded-[var(--measures-radius-200,8px)] object-contain"
/>
) : (
<p className="font-[family-name:var(--font-body)] text-[length:var(--font-size-body-m)] text-[var(--color-content-default-secondary)]">
{noFileChosen}
</p>
)}
</div>
) : (
<CustomMethodCardUploadBlockRow
block={block}
blocks={blocks}
patch={patch}
uploadFileInputAriaLabel={fm.upload.uploadFileInputAriaLabel}
uploadHint={fm.upload.uploadHint}
clearPendingUploadAriaLabel={
fm.upload.clearPendingUploadAriaLabel
}
clearPendingUploadTooltip={
fm.upload.clearPendingUploadTooltip
}
uploadPreviewImageAlt={fm.upload.uploadPreviewImageAlt}
noFileChosen={noFileChosen}
/>
)}
</div>
);
}
return (
<IncrementerBlock
key={block.id}
label={block.blockTitle}
value={block.defaultPercent}
min={1}
max={100}
step={1}
disabled={readOnly}
onChange={(v) =>
patch(
mapBlockById(blocks, block.id, (b) =>
b.kind === "proportion" ? { ...b, defaultPercent: v } : b,
),
)
}
formatValue={(v) => `${v}%`}
decrementAriaLabel={fm.proportion.decrementAriaLabel}
incrementAriaLabel={fm.proportion.incrementAriaLabel}
/>
);
})}
</div>
);
}
const CustomMethodCardFieldBlocksSummary = memo(
CustomMethodCardFieldBlocksSummaryComponent,
);
CustomMethodCardFieldBlocksSummary.displayName =
"CustomMethodCardFieldBlocksSummary";
export default CustomMethodCardFieldBlocksSummary;
@@ -0,0 +1,66 @@
"use client";
/**
* Controlled field blocks for wizard-authored method cards in Create modals
* (facet screens + final-review chip edit). When `onBlocksChange` is omitted,
* blocks render read-only (disabled controls).
*
* Layout matches preset method editors ({@link CommunicationMethodEditFields},
* {@link DecisionApproachEditFields}): {@link ModalTextAreaField},
* {@link ApplicableScopeField} chip rows, {@link IncrementerBlock}.
*/
import { memo, useCallback } from "react";
import { useMessages } from "../../../../contexts/MessagesContext";
import { CustomMethodCardFieldBlocksSummaryView } from "./CustomMethodCardFieldBlocksSummary.view";
import type { CustomMethodCardFieldBlocksSummaryProps } from "./CustomMethodCardFieldBlocksSummary.types";
function CustomMethodCardFieldBlocksSummaryContainerComponent({
blocks,
onBlocksChange,
}: CustomMethodCardFieldBlocksSummaryProps) {
const m = useMessages();
const wiz = m.create.customRule.customMethodCardWizard;
const fm = wiz.fieldModals;
const em = wiz.editModal;
const readOnly = !onBlocksChange;
const onPatch = useCallback(
(next: Parameters<NonNullable<typeof onBlocksChange>>[0]) => {
onBlocksChange?.(next);
},
[onBlocksChange],
);
return (
<CustomMethodCardFieldBlocksSummaryView
blocks={blocks}
readOnly={readOnly}
emptyValue={em.readout.emptyValue}
noFileChosen={em.readout.noFileChosen}
fieldModalsCopy={{
badges: { addOptionLabel: fm.badges.addOptionLabel },
upload: {
uploadFileInputAriaLabel: fm.upload.uploadFileInputAriaLabel,
uploadHint: fm.upload.uploadHint,
clearPendingUploadAriaLabel: fm.upload.clearPendingUploadAriaLabel,
clearPendingUploadTooltip: fm.upload.clearPendingUploadTooltip,
uploadPreviewImageAlt: fm.upload.uploadPreviewImageAlt,
},
proportion: {
decrementAriaLabel: fm.proportion.decrementAriaLabel,
incrementAriaLabel: fm.proportion.incrementAriaLabel,
},
}}
onPatch={onPatch}
/>
);
}
const CustomMethodCardFieldBlocksSummary = memo(
CustomMethodCardFieldBlocksSummaryContainerComponent,
);
CustomMethodCardFieldBlocksSummary.displayName =
"CustomMethodCardFieldBlocksSummary";
export default CustomMethodCardFieldBlocksSummary;
@@ -0,0 +1,55 @@
import type { ChangeEventHandler, RefObject } from "react";
import type { CustomMethodCardFieldBlock } from "../../../../../lib/create/customMethodCardFieldBlocks";
export interface CustomMethodCardFieldBlocksSummaryProps {
blocks: CustomMethodCardFieldBlock[];
/** When set, fields update the draft via immutable block-array replacements. */
onBlocksChange?: (_next: CustomMethodCardFieldBlock[]) => void;
}
export type CustomMethodCardFieldBlocksSummaryFieldModalsCopy = {
badges: { addOptionLabel: string };
upload: {
uploadFileInputAriaLabel: string;
uploadHint: string;
clearPendingUploadAriaLabel: string;
clearPendingUploadTooltip: string;
uploadPreviewImageAlt: string;
};
proportion: {
decrementAriaLabel: string;
incrementAriaLabel: string;
};
};
export interface CustomMethodCardFieldBlocksSummaryViewProps {
blocks: CustomMethodCardFieldBlock[];
readOnly: boolean;
emptyValue: string;
noFileChosen: string;
fieldModalsCopy: CustomMethodCardFieldBlocksSummaryFieldModalsCopy;
onPatch: (_next: CustomMethodCardFieldBlock[]) => void;
}
export type CustomMethodCardUploadBlockRowProps = {
block: Extract<CustomMethodCardFieldBlock, { kind: "upload" }>;
blocks: CustomMethodCardFieldBlock[];
onPatch: (_next: CustomMethodCardFieldBlock[]) => void;
uploadFileInputAriaLabel: string;
uploadHint: string;
clearPendingUploadAriaLabel: string;
clearPendingUploadTooltip: string;
uploadPreviewImageAlt: string;
noFileChosen: string;
};
export type CustomMethodCardUploadBlockRowViewProps =
CustomMethodCardUploadBlockRowProps & {
uploadInputRef: RefObject<HTMLInputElement | null>;
busy: boolean;
uploadingHint: string;
errorMessage: string | null;
onClearUpload: () => void;
onFileInputChange: ChangeEventHandler<HTMLInputElement>;
onUploadClick: () => void;
};
@@ -0,0 +1,198 @@
"use client";
import { memo } from "react";
import Chip from "../../../../components/controls/Chip";
import IncrementerBlock from "../../../../components/controls/IncrementerBlock";
import InputLabel from "../../../../components/type/InputLabel";
import type { CustomMethodCardFieldBlock } from "../../../../../lib/create/customMethodCardFieldBlocks";
import ApplicableScopeField from "../ApplicableScopeField";
import ModalTextAreaField from "../ModalTextAreaField";
import { CustomMethodCardUploadBlockRow } from "./CustomMethodCardUploadBlockRow.container";
import type { CustomMethodCardFieldBlocksSummaryViewProps } from "./CustomMethodCardFieldBlocksSummary.types";
const TEXT_VALUE_MAX = 8000;
function mapBlockById(
blocks: CustomMethodCardFieldBlock[],
blockId: string,
mapFn: (_b: CustomMethodCardFieldBlock) => CustomMethodCardFieldBlock,
): CustomMethodCardFieldBlock[] {
return blocks.map((b) => (b.id === blockId ? mapFn(b) : b));
}
function CustomMethodCardFieldBlocksSummaryViewComponent({
blocks,
readOnly,
emptyValue,
noFileChosen,
fieldModalsCopy,
onPatch,
}: CustomMethodCardFieldBlocksSummaryViewProps) {
const fm = fieldModalsCopy;
return (
<div className="flex flex-col gap-6">
{blocks.map((block) => {
if (block.kind === "text") {
return (
<ModalTextAreaField
key={block.id}
label={block.blockTitle}
rows={6}
value={block.placeholderText}
onChange={(v) =>
onPatch(
mapBlockById(blocks, block.id, (b) =>
b.kind === "text"
? { ...b, placeholderText: v.slice(0, TEXT_VALUE_MAX) }
: b,
),
)
}
disabled={readOnly}
/>
);
}
if (block.kind === "badges") {
if (readOnly) {
return (
<div key={block.id} className="flex flex-col gap-2">
<InputLabel
label={block.blockTitle}
helpIcon
size="s"
palette="default"
/>
{block.options.length > 0 ? (
<div className="flex flex-wrap items-center gap-2">
{block.options.map((opt, idx) => (
<Chip
key={`${block.id}-${idx}`}
label={opt}
state="selected"
palette="default"
size="s"
disabled
ariaLabel={opt}
/>
))}
</div>
) : (
<p className="font-[family-name:var(--font-body)] text-[length:var(--font-size-body-m)] text-[var(--color-content-default-secondary)]">
{emptyValue}
</p>
)}
</div>
);
}
return (
<ApplicableScopeField
key={block.id}
label={block.blockTitle}
addLabel={fm.badges.addOptionLabel}
scopes={block.options}
selectedScopes={block.options}
onToggleScope={(scope) =>
onPatch(
mapBlockById(blocks, block.id, (b) =>
b.kind === "badges"
? { ...b, options: b.options.filter((o) => o !== scope) }
: b,
),
)
}
onAddScope={(scope) =>
onPatch(
mapBlockById(blocks, block.id, (b) => {
if (b.kind !== "badges") return b;
if (b.options.includes(scope) || b.options.length >= 50)
return b;
return { ...b, options: [...b.options, scope] };
}),
)
}
/>
);
}
if (block.kind === "upload") {
return (
<div key={block.id}>
{readOnly ? (
<div className="flex flex-col gap-2">
<InputLabel
label={block.blockTitle}
helpIcon
size="s"
palette="default"
/>
{block.assetUrl?.trim() ? (
// eslint-disable-next-line @next/next/no-img-element
<img
src={block.assetUrl.trim()}
alt={
block.fileName?.trim() ||
block.blockTitle ||
noFileChosen
}
className="max-h-[160px] max-w-full rounded-[var(--measures-radius-200,8px)] object-contain"
/>
) : (
<p className="font-[family-name:var(--font-body)] text-[length:var(--font-size-body-m)] text-[var(--color-content-default-secondary)]">
{noFileChosen}
</p>
)}
</div>
) : (
<CustomMethodCardUploadBlockRow
block={block}
blocks={blocks}
onPatch={onPatch}
uploadFileInputAriaLabel={fm.upload.uploadFileInputAriaLabel}
uploadHint={fm.upload.uploadHint}
clearPendingUploadAriaLabel={
fm.upload.clearPendingUploadAriaLabel
}
clearPendingUploadTooltip={
fm.upload.clearPendingUploadTooltip
}
uploadPreviewImageAlt={fm.upload.uploadPreviewImageAlt}
noFileChosen={noFileChosen}
/>
)}
</div>
);
}
return (
<IncrementerBlock
key={block.id}
label={block.blockTitle}
value={block.defaultPercent}
min={1}
max={100}
step={1}
disabled={readOnly}
onChange={(v) =>
onPatch(
mapBlockById(blocks, block.id, (b) =>
b.kind === "proportion" ? { ...b, defaultPercent: v } : b,
),
)
}
formatValue={(v) => `${v}%`}
decrementAriaLabel={fm.proportion.decrementAriaLabel}
incrementAriaLabel={fm.proportion.incrementAriaLabel}
/>
);
})}
</div>
);
}
export const CustomMethodCardFieldBlocksSummaryView = memo(
CustomMethodCardFieldBlocksSummaryViewComponent,
);
CustomMethodCardFieldBlocksSummaryView.displayName =
"CustomMethodCardFieldBlocksSummaryView";
@@ -0,0 +1,110 @@
"use client";
import { memo, useCallback, useRef, useState } from "react";
import { useTranslation } from "../../../../contexts/MessagesContext";
import type { CustomMethodCardFieldBlock } from "../../../../../lib/create/customMethodCardFieldBlocks";
import { uploadCreateFlowFile } from "../../../../../lib/create/uploadToServer";
import { CustomMethodCardUploadBlockRowView } from "./CustomMethodCardUploadBlockRow.view";
import type { CustomMethodCardUploadBlockRowProps } from "./CustomMethodCardFieldBlocksSummary.types";
function mapBlockById(
blocks: CustomMethodCardFieldBlock[],
blockId: string,
mapFn: (_b: CustomMethodCardFieldBlock) => CustomMethodCardFieldBlock,
): CustomMethodCardFieldBlock[] {
return blocks.map((b) => (b.id === blockId ? mapFn(b) : b));
}
function CustomMethodCardUploadBlockRowContainerComponent({
block,
blocks,
onPatch,
uploadFileInputAriaLabel,
uploadHint,
clearPendingUploadAriaLabel,
clearPendingUploadTooltip,
uploadPreviewImageAlt,
noFileChosen,
}: CustomMethodCardUploadBlockRowProps) {
const uploadInputRef = useRef<HTMLInputElement | null>(null);
const tUpload = useTranslation("create.upload");
const [busy, setBusy] = useState(false);
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const clearUpload = useCallback(() => {
onPatch(
mapBlockById(blocks, block.id, (b) =>
b.kind === "upload"
? { ...b, fileName: undefined, assetUrl: undefined }
: b,
),
);
}, [block.id, blocks, onPatch]);
const handleFileInputChange = useCallback<
React.ChangeEventHandler<HTMLInputElement>
>(
(e) => {
const file = e.target.files?.[0];
e.target.value = "";
if (!file) return;
setErrorMessage(null);
setBusy(true);
void (async () => {
try {
const { url } = await uploadCreateFlowFile(
file,
"customMethodAttachment",
);
const name = file.name?.trim();
onPatch(
mapBlockById(blocks, block.id, (b) =>
b.kind === "upload"
? {
...b,
...(name ? { fileName: name } : {}),
assetUrl: url,
}
: b,
),
);
} catch {
setErrorMessage(tUpload("errors.generic"));
} finally {
setBusy(false);
}
})();
},
[block.id, blocks, onPatch, tUpload],
);
const handleUploadClick = useCallback(() => {
if (!busy) uploadInputRef.current?.click();
}, [busy]);
return (
<CustomMethodCardUploadBlockRowView
block={block}
blocks={blocks}
onPatch={onPatch}
uploadFileInputAriaLabel={uploadFileInputAriaLabel}
uploadHint={uploadHint}
clearPendingUploadAriaLabel={clearPendingUploadAriaLabel}
clearPendingUploadTooltip={clearPendingUploadTooltip}
uploadPreviewImageAlt={uploadPreviewImageAlt}
noFileChosen={noFileChosen}
uploadInputRef={uploadInputRef}
busy={busy}
uploadingHint={tUpload("uploading")}
errorMessage={errorMessage}
onClearUpload={clearUpload}
onFileInputChange={handleFileInputChange}
onUploadClick={handleUploadClick}
/>
);
}
export const CustomMethodCardUploadBlockRow = memo(
CustomMethodCardUploadBlockRowContainerComponent,
);
CustomMethodCardUploadBlockRow.displayName = "CustomMethodCardUploadBlockRow";
@@ -0,0 +1,100 @@
"use client";
import { memo } from "react";
import Upload from "../../../../components/controls/Upload";
import InputLabel from "../../../../components/type/InputLabel";
import { ASSETS, getAssetPath } from "../../../../../lib/assetUtils";
import type { CustomMethodCardUploadBlockRowViewProps } from "./CustomMethodCardFieldBlocksSummary.types";
function CustomMethodCardUploadBlockRowViewComponent({
block,
uploadFileInputAriaLabel,
uploadHint,
clearPendingUploadAriaLabel,
clearPendingUploadTooltip,
uploadPreviewImageAlt,
noFileChosen,
uploadInputRef,
busy,
uploadingHint,
errorMessage,
onClearUpload,
onFileInputChange,
onUploadClick,
}: CustomMethodCardUploadBlockRowViewProps) {
const displayName = block.fileName?.trim() ? block.fileName : noFileChosen;
const assetUrlTrimmed = block.assetUrl?.trim() ?? "";
const hasAsset = assetUrlTrimmed.length > 0;
return (
<div className="flex flex-col gap-2">
<InputLabel
label={block.blockTitle}
helpIcon
size="s"
palette="default"
/>
{!hasAsset ? (
<p className="font-[family-name:var(--font-body)] text-[length:var(--font-size-body-m)] text-[var(--color-content-default-secondary)]">
{displayName}
</p>
) : null}
<input
ref={uploadInputRef}
type="file"
className="sr-only"
tabIndex={-1}
accept="image/jpeg,image/png,image/webp,image/gif,application/pdf"
aria-label={uploadFileInputAriaLabel}
onChange={onFileInputChange}
/>
{hasAsset ? (
<div className="relative inline-block max-w-full">
<button
type="button"
onClick={onClearUpload}
className="absolute right-[8px] top-[8px] z-[1] flex h-[32px] w-[32px] cursor-pointer items-center justify-center rounded-full bg-[var(--color-surface-default-secondary)] focus:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-border-invert-primary)] focus-visible:ring-offset-2 focus-visible:ring-offset-[var(--color-surface-default-primary)]"
aria-label={clearPendingUploadAriaLabel}
title={clearPendingUploadTooltip}
>
{/* eslint-disable-next-line @next/next/no-img-element -- matches ModalHeader close control */}
<img
src={getAssetPath(ASSETS.ICON_CLOSE)}
alt=""
className="h-[16px] w-[16px]"
style={{
filter: "brightness(0) invert(1)",
}}
/>
</button>
{/* eslint-disable-next-line @next/next/no-img-element -- same-origin upload URL */}
<img
src={assetUrlTrimmed}
alt={uploadPreviewImageAlt}
className="max-h-[160px] max-w-full rounded-[var(--measures-radius-200,8px)] object-contain"
/>
</div>
) : (
<Upload
active={!busy}
hintText={busy ? uploadingHint : uploadHint}
onClick={onUploadClick}
/>
)}
{errorMessage ? (
<p
className="font-[family-name:var(--font-body)] text-[length:var(--font-size-body-s)] text-[var(--color-content-default-secondary)]"
role="alert"
>
{errorMessage}
</p>
) : null}
</div>
);
}
export const CustomMethodCardUploadBlockRowView = memo(
CustomMethodCardUploadBlockRowViewComponent,
);
CustomMethodCardUploadBlockRowView.displayName =
"CustomMethodCardUploadBlockRowView";
@@ -0,0 +1,2 @@
export { default } from "./CustomMethodCardFieldBlocksSummary.container";
export type { CustomMethodCardFieldBlocksSummaryProps } from "./CustomMethodCardFieldBlocksSummary.types";
@@ -6,7 +6,7 @@ import InputWithCounter from "../../../../components/controls/InputWithCounter";
import TextArea from "../../../../components/controls/TextArea";
import AddCustomField from "../../../../components/controls/AddCustomField";
import { CustomMethodCardWizardFieldBodiesView } from "./CustomMethodCardWizardFieldBodies.view";
import { CustomMethodCardWizardBlocksListView } from "./CustomMethodCardWizardBlocksList.view";
import { CustomMethodCardWizardBlocksList } from "./CustomMethodCardWizardBlocksList.container";
import type { CustomMethodCardWizardViewProps } from "./CustomMethodCardWizard.types";
function CustomMethodCardWizardViewComponent({
@@ -90,7 +90,7 @@ function CustomMethodCardWizardViewComponent({
{!fieldTypeModal && wizardStep === 3 ? (
<div className="flex w-full flex-col gap-4">
{draftFieldBlocks.length > 0 ? (
<CustomMethodCardWizardBlocksListView
<CustomMethodCardWizardBlocksList
blocks={draftFieldBlocks}
fieldTypeLabels={copy.fieldTypeLabels}
dragHandleAriaLabel={copy.step3BlocksList.dragHandleAriaLabel}
@@ -0,0 +1,77 @@
"use client";
import { memo, useCallback, useState, type DragEvent } from "react";
import { reorderCustomMethodCardFieldBlocks } from "../../../../../lib/create/reorderCustomMethodCardFieldBlocks";
import { CustomMethodCardWizardBlocksListView } from "./CustomMethodCardWizardBlocksList.view";
import type { CustomMethodCardWizardBlocksListProps } from "./CustomMethodCardWizardBlocksList.types";
function CustomMethodCardWizardBlocksListContainerComponent({
blocks,
fieldTypeLabels,
dragHandleAriaLabel,
listLabel,
onBlocksReorder,
}: CustomMethodCardWizardBlocksListProps) {
const [draggingIndex, setDraggingIndex] = useState<number | null>(null);
const [overIndex, setOverIndex] = useState<number | null>(null);
const clearDragUi = useCallback(() => {
setDraggingIndex(null);
setOverIndex(null);
}, []);
const handleDragStart = useCallback(
(index: number) => (e: DragEvent) => {
e.dataTransfer.effectAllowed = "move";
e.dataTransfer.setData("text/plain", String(index));
setDraggingIndex(index);
},
[],
);
const handleDragOver = useCallback((index: number) => {
return (e: DragEvent) => {
e.preventDefault();
e.dataTransfer.dropEffect = "move";
setOverIndex(index);
};
}, []);
const handleDrop = useCallback(
(index: number) => (e: DragEvent) => {
e.preventDefault();
const from = Number.parseInt(e.dataTransfer.getData("text/plain"), 10);
if (Number.isNaN(from)) {
clearDragUi();
return;
}
onBlocksReorder(
reorderCustomMethodCardFieldBlocks(blocks, from, index),
);
clearDragUi();
},
[blocks, clearDragUi, onBlocksReorder],
);
return (
<CustomMethodCardWizardBlocksListView
blocks={blocks}
fieldTypeLabels={fieldTypeLabels}
dragHandleAriaLabel={dragHandleAriaLabel}
listLabel={listLabel}
onBlocksReorder={onBlocksReorder}
draggingIndex={draggingIndex}
overIndex={overIndex}
onDragStart={handleDragStart}
onDragOver={handleDragOver}
onDrop={handleDrop}
onDragEnd={clearDragUi}
/>
);
}
export const CustomMethodCardWizardBlocksList = memo(
CustomMethodCardWizardBlocksListContainerComponent,
);
CustomMethodCardWizardBlocksList.displayName =
"CustomMethodCardWizardBlocksList";
@@ -0,0 +1,21 @@
import type { AddCustomFieldType } from "../../../../components/controls/AddCustomField/AddCustomField.types";
import type { CustomMethodCardFieldBlock } from "../../../../../lib/create/customMethodCardFieldBlocks";
import type { DragEvent } from "react";
export interface CustomMethodCardWizardBlocksListProps {
blocks: CustomMethodCardFieldBlock[];
fieldTypeLabels: Record<AddCustomFieldType, string>;
dragHandleAriaLabel: string;
listLabel: string;
onBlocksReorder: (_next: CustomMethodCardFieldBlock[]) => void;
}
export interface CustomMethodCardWizardBlocksListViewProps
extends CustomMethodCardWizardBlocksListProps {
draggingIndex: number | null;
overIndex: number | null;
onDragStart: (_index: number) => (_e: DragEvent) => void;
onDragOver: (_index: number) => (_e: DragEvent) => void;
onDrop: (_index: number) => (_e: DragEvent) => void;
onDragEnd: () => void;
}
@@ -1,11 +1,10 @@
"use client";
import { memo, useCallback, useState, type DragEvent } from "react";
import { memo } from "react";
import Icon from "../../../../components/asset/icon";
import { ADD_CUSTOM_FIELD_TYPE_ICONS } from "../../../../components/controls/AddCustomField/AddCustomField.types";
import type { AddCustomFieldType } from "../../../../components/controls/AddCustomField/AddCustomField.types";
import type { CustomMethodCardFieldBlock } from "../../../../../lib/create/customMethodCardFieldBlocks";
import { reorderCustomMethodCardFieldBlocks } from "../../../../../lib/create/reorderCustomMethodCardFieldBlocks";
import type { CustomMethodCardWizardBlocksListViewProps } from "./CustomMethodCardWizardBlocksList.types";
function DragHandleGlyph({ className }: { className?: string }) {
return (
@@ -28,62 +27,18 @@ function DragHandleGlyph({ className }: { className?: string }) {
);
}
export interface CustomMethodCardWizardBlocksListViewProps {
blocks: CustomMethodCardFieldBlock[];
fieldTypeLabels: Record<AddCustomFieldType, string>;
dragHandleAriaLabel: string;
listLabel: string;
onBlocksReorder: (_next: CustomMethodCardFieldBlock[]) => void;
}
function CustomMethodCardWizardBlocksListViewComponent({
blocks,
fieldTypeLabels,
dragHandleAriaLabel,
listLabel,
onBlocksReorder,
draggingIndex,
overIndex,
onDragStart,
onDragOver,
onDrop,
onDragEnd,
}: CustomMethodCardWizardBlocksListViewProps) {
const [draggingIndex, setDraggingIndex] = useState<number | null>(null);
const [overIndex, setOverIndex] = useState<number | null>(null);
const clearDragUi = useCallback(() => {
setDraggingIndex(null);
setOverIndex(null);
}, []);
const handleDragStart = useCallback(
(index: number) => (e: DragEvent) => {
e.dataTransfer.effectAllowed = "move";
e.dataTransfer.setData("text/plain", String(index));
setDraggingIndex(index);
},
[],
);
const handleDragOver = useCallback((index: number) => {
return (e: DragEvent) => {
e.preventDefault();
e.dataTransfer.dropEffect = "move";
setOverIndex(index);
};
}, []);
const handleDrop = useCallback(
(index: number) => (e: DragEvent) => {
e.preventDefault();
const from = Number.parseInt(e.dataTransfer.getData("text/plain"), 10);
if (Number.isNaN(from)) {
clearDragUi();
return;
}
onBlocksReorder(
reorderCustomMethodCardFieldBlocks(blocks, from, index),
);
clearDragUi();
},
[blocks, clearDragUi, onBlocksReorder],
);
return (
<ul className="flex list-none flex-col gap-2 p-0" aria-label={listLabel}>
{blocks.map((block, index) => {
@@ -98,14 +53,14 @@ function CustomMethodCardWizardBlocksListViewComponent({
? "ring-2 ring-[var(--color-border-invert-primary)] ring-offset-2 ring-offset-[var(--color-surface-default-primary)]"
: ""
} ${draggingIndex === index ? "opacity-60" : ""}`}
onDragOver={handleDragOver(index)}
onDrop={handleDrop(index)}
onDragOver={onDragOver(index)}
onDrop={onDrop(index)}
>
<button
type="button"
draggable
onDragStart={handleDragStart(index)}
onDragEnd={clearDragUi}
onDragStart={onDragStart(index)}
onDragEnd={onDragEnd}
className="flex shrink-0 cursor-grab touch-manipulation items-center justify-center rounded-[var(--measures-radius-200,8px)] border-0 bg-transparent px-1 text-[var(--color-content-default-secondary)] active:cursor-grabbing focus:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-border-invert-primary)]"
aria-label={dragHandleAriaLabel}
>
@@ -1,7 +1,7 @@
"use client";
import { memo } from "react";
import { getAssetPath } from "../../../../../lib/assetUtils";
import { ASSETS, getAssetPath } from "../../../../../lib/assetUtils";
import InputWithCounter from "../../../../components/controls/InputWithCounter";
import TextArea from "../../../../components/controls/TextArea";
import TextInput from "../../../../components/controls/TextInput";
@@ -140,7 +140,7 @@ function CustomMethodCardWizardFieldBodiesViewComponent({
>
{/* eslint-disable-next-line @next/next/no-img-element -- matches ModalHeader close control */}
<img
src={getAssetPath("assets/Icon_Close.svg")}
src={getAssetPath(ASSETS.ICON_CLOSE)}
alt=""
className="h-[16px] w-[16px]"
style={{
@@ -28,6 +28,7 @@ import {
import CustomMethodCardModalBody from "./CustomMethodCardModalBody";
import MethodCardCustomizeModalHeader from "./MethodCardCustomizeModalHeader";
import { buildCustomRuleModalKebabMenu } from "./customRuleModalKebabMenu";
import { useDiscardCustomizeConfirm } from "../hooks/useDiscardCustomizeConfirm";
import {
communicationPresetFor,
conflictManagementPresetFor,
@@ -52,7 +53,6 @@ import {
} from "../../../../lib/create/coreValueChipFacet";
import {
captureMethodCardCustomizeSnapshot,
confirmDiscardMethodCardCustomizeSession,
isMethodCardCustomizeSessionDirty,
type MethodCardCustomizeSnapshot,
type MethodCardHeaderDraft,
@@ -171,6 +171,8 @@ export function FinalReviewChipEditModal({
const tModal = useTranslation(
"create.reviewAndComplete.finalReview.chipEditModal",
);
const { confirmDiscard, confirmDirtyCustomizeCancel, confirmDialog } =
useDiscardCustomizeConfirm();
const [draft, setDraft] = useState<Draft | null>(null);
const [modalEditUnlocked, setModalEditUnlocked] = useState(false);
@@ -342,32 +344,30 @@ export function FinalReviewChipEditModal({
onClose();
}, [onClose]);
const handleModalClose = useCallback(() => {
const handleModalClose = useCallback(async () => {
if (
target &&
target.groupKey === "coreValues" &&
!confirmDiscardMethodCardCustomizeSession(
!(await confirmDiscard(
modalEditUnlocked,
coreCustomizeSnapshotRef.current,
draft?.groupKey === "coreValues" ? draft.value : null,
null,
customizeHeaderDraft,
modalKebabMenu.discardUnsavedCustomizeChanges,
)
))
) {
return;
}
if (
target &&
isMethodFacetGroup(target.groupKey) &&
!confirmDiscardMethodCardCustomizeSession(
!(await confirmDiscard(
modalEditUnlocked,
customizeSnapshotRef.current,
methodDetailDraftForCustomizeSession(draft),
draftFieldBlocks,
customizeHeaderDraft,
modalKebabMenu.discardUnsavedCustomizeChanges,
)
))
) {
return;
}
@@ -380,17 +380,17 @@ export function FinalReviewChipEditModal({
}
finalizeModalClose();
}, [
confirmDiscard,
customizeHeaderDraft,
draft,
draftFieldBlocks,
finalizeModalClose,
modalEditUnlocked,
modalKebabMenu.discardUnsavedCustomizeChanges,
replaceState,
target,
]);
const handleCancelCustomize = useCallback(() => {
const handleCancelCustomize = useCallback(async () => {
if (!modalEditUnlocked || !target) {
return;
}
@@ -404,13 +404,12 @@ export function FinalReviewChipEditModal({
}
if (
draft?.groupKey === "coreValues" &&
isMethodCardCustomizeSessionDirty(
!(await confirmDirtyCustomizeCancel(
snap,
draft.value,
null,
customizeHeaderDraft,
) &&
!window.confirm(modalKebabMenu.discardUnsavedCustomizeChanges)
))
) {
return;
}
@@ -435,13 +434,12 @@ export function FinalReviewChipEditModal({
return;
}
if (
isMethodCardCustomizeSessionDirty(
!(await confirmDirtyCustomizeCancel(
snap,
methodDetailDraftForCustomizeSession(draft),
draftFieldBlocks,
customizeHeaderDraft,
) &&
!window.confirm(modalKebabMenu.discardUnsavedCustomizeChanges)
))
) {
return;
}
@@ -451,11 +449,11 @@ export function FinalReviewChipEditModal({
customizeSnapshotRef.current = null;
setCustomizeHeaderDraft(null);
}, [
confirmDirtyCustomizeCancel,
customizeHeaderDraft,
draft,
draftFieldBlocks,
modalEditUnlocked,
modalKebabMenu.discardUnsavedCustomizeChanges,
target,
]);
@@ -565,7 +563,7 @@ export function FinalReviewChipEditModal({
tCm,
]);
const handleRemoveSelectedFromModal = useCallback(() => {
const handleRemoveSelectedFromModal = useCallback(async () => {
if (!target || !isMethodFacetGroup(target.groupKey)) {
return;
}
@@ -575,14 +573,13 @@ export function FinalReviewChipEditModal({
}
onInteract?.();
if (
!confirmDiscardMethodCardCustomizeSession(
!(await confirmDiscard(
modalEditUnlocked,
customizeSnapshotRef.current,
methodDetailDraftForCustomizeSession(draft),
draftFieldBlocks,
customizeHeaderDraft,
modalKebabMenu.discardUnsavedCustomizeChanges,
)
))
) {
return;
}
@@ -597,32 +594,31 @@ export function FinalReviewChipEditModal({
}));
finalizeModalClose();
}, [
confirmDiscard,
customizeHeaderDraft,
draft,
draftFieldBlocks,
finalizeModalClose,
modalEditUnlocked,
modalKebabMenu.discardUnsavedCustomizeChanges,
onInteract,
replaceState,
selectionIdsForTarget,
target,
]);
const handleRemoveCoreValueFromModal = useCallback(() => {
const handleRemoveCoreValueFromModal = useCallback(async () => {
if (!target || target.groupKey !== "coreValues") {
return;
}
onInteract?.();
if (
!confirmDiscardMethodCardCustomizeSession(
!(await confirmDiscard(
modalEditUnlocked,
coreCustomizeSnapshotRef.current,
draft?.groupKey === "coreValues" ? draft.value : null,
null,
customizeHeaderDraft,
modalKebabMenu.discardUnsavedCustomizeChanges,
)
))
) {
return;
}
@@ -634,17 +630,17 @@ export function FinalReviewChipEditModal({
}));
finalizeModalClose();
}, [
confirmDiscard,
customizeHeaderDraft,
draft,
finalizeModalClose,
modalEditUnlocked,
modalKebabMenu.discardUnsavedCustomizeChanges,
onInteract,
replaceState,
target,
]);
const handleDuplicateCoreValue = useCallback(() => {
const handleDuplicateCoreValue = useCallback(async () => {
if (
!target ||
target.groupKey !== "coreValues" ||
@@ -659,14 +655,13 @@ export function FinalReviewChipEditModal({
return;
}
if (
!confirmDiscardMethodCardCustomizeSession(
!(await confirmDiscard(
modalEditUnlocked,
coreCustomizeSnapshotRef.current,
draft.value,
null,
customizeHeaderDraft,
modalKebabMenu.discardUnsavedCustomizeChanges,
)
))
) {
return;
}
@@ -711,10 +706,10 @@ export function FinalReviewChipEditModal({
chipLabel: outcome.newLabel,
});
}, [
confirmDiscard,
customizeHeaderDraft,
draft,
modalEditUnlocked,
modalKebabMenu.discardUnsavedCustomizeChanges,
modalKebabMenu.duplicateTitleSuffix,
onEditTargetChange,
onInteract,
@@ -1015,6 +1010,7 @@ export function FinalReviewChipEditModal({
: showMethodModalPrimary;
return (
<>
<Create
isOpen={isOpen}
onClose={handleModalClose}
@@ -1184,6 +1180,8 @@ export function FinalReviewChipEditModal({
))}
</div>
</Create>
{confirmDialog}
</>
);
}
+17 -8
View File
@@ -5,10 +5,9 @@ import type { CreateFlowState, CreateFlowStep } from "../types";
import { buildPublishPayload } from "../../../../lib/create/buildPublishPayload";
import { saveDraftToServer, updatePublishedRule } from "../../../../lib/create/api";
import { writeLastPublishedRule } from "../../../../lib/create/lastPublishedRule";
import { isBackendSyncEnabled } from "../../../../lib/create/backendSyncEnabled";
import messages from "../../../../messages/en/index";
const SYNC_ENABLED = process.env.NEXT_PUBLIC_ENABLE_BACKEND_SYNC === "true";
export type CreateFlowExitClearState = () => void;
type AppRouterLike = { push: (_href: string) => void };
@@ -23,6 +22,7 @@ export function useCreateFlowExit({
router,
user,
setDraftSaveBannerMessage,
confirmLeave,
}: {
state: CreateFlowState;
currentStep: CreateFlowStep | null;
@@ -31,6 +31,8 @@ export function useCreateFlowExit({
user: { id: string; email: string } | null;
/** When save fails, surface the server message in the create shell banner (no leave confirm). */
setDraftSaveBannerMessage?: (_message: string | null) => void;
/** When exit would discard unsaved work, return true to proceed. Defaults to denying leave. */
confirmLeave?: () => Promise<boolean>;
}): (_options?: { saveDraft?: boolean }) => Promise<void> {
return useCallback(
async (options?: { saveDraft?: boolean }) => {
@@ -38,14 +40,13 @@ export function useCreateFlowExit({
const saveDraft = options?.saveDraft ?? false;
if (!saveDraft && typeof window !== "undefined") {
const confirmed = window.confirm(
messages.create.topNav.leaveConfirmLoss,
);
if (!saveDraft) {
const confirmFn = confirmLeave ?? (async () => false);
const confirmed = await confirmFn();
if (!confirmed) return;
}
if (saveDraft && SYNC_ENABLED) {
if (saveDraft && isBackendSyncEnabled()) {
const editingId =
typeof state.editingPublishedRuleId === "string"
? state.editingPublishedRuleId.trim()
@@ -97,6 +98,14 @@ export function useCreateFlowExit({
clearState();
router.push("/");
},
[state, currentStep, clearState, router, user, setDraftSaveBannerMessage],
[
state,
currentStep,
clearState,
router,
user,
setDraftSaveBannerMessage,
confirmLeave,
],
);
}
@@ -0,0 +1,78 @@
"use client";
import { useCallback } from "react";
import messages from "../../../../messages/en/index";
import { useAsyncConfirm } from "../../../hooks/useAsyncConfirm";
import type { CustomMethodCardFieldBlock } from "../../../../lib/create/customMethodCardFieldBlocks";
import {
confirmDiscardMethodCardCustomizeSession,
isMethodCardCustomizeSessionDirty,
type MethodCardCustomizeSnapshot,
type MethodCardHeaderDraft,
} from "../../../../lib/create/methodCardCustomizeSession";
const copy = messages.create.customRule.modalKebabMenu;
const confirmOptions = {
title: copy.discardUnsavedCustomizeChangesTitle,
description: copy.discardUnsavedCustomizeChangesDescription,
proceedText: copy.discardUnsavedCustomizeChangesProceed,
cancelText: copy.discardUnsavedCustomizeChangesCancel,
};
/**
* Create-flow confirm for exiting customize mode with unsaved edits.
*
* @returns Async helpers plus `confirmDialog` to render once in the screen JSX.
*/
export function useDiscardCustomizeConfirm() {
const { requestConfirm, confirmDialog } = useAsyncConfirm();
const runConfirm = useCallback(
() => requestConfirm(confirmOptions),
[requestConfirm],
);
const confirmDiscard = useCallback(
async <TDraft,>(
modalEditUnlocked: boolean,
snapshot: MethodCardCustomizeSnapshot<TDraft> | null,
pendingDraft: TDraft | null,
draftFieldBlocks: CustomMethodCardFieldBlock[] | null,
headerDraft: MethodCardHeaderDraft | null,
) =>
confirmDiscardMethodCardCustomizeSession(
modalEditUnlocked,
snapshot,
pendingDraft,
draftFieldBlocks,
headerDraft,
runConfirm,
),
[runConfirm],
);
const confirmDirtyCustomizeCancel = useCallback(
async <TDraft,>(
snapshot: MethodCardCustomizeSnapshot<TDraft>,
pendingDraft: TDraft | null,
draftFieldBlocks: CustomMethodCardFieldBlock[] | null,
headerDraft: MethodCardHeaderDraft | null,
) => {
if (
!isMethodCardCustomizeSessionDirty(
snapshot,
pendingDraft,
draftFieldBlocks,
headerDraft,
)
) {
return true;
}
return runConfirm();
},
[runConfirm],
);
return { confirmDiscard, confirmDirtyCustomizeCancel, confirmDialog };
}
@@ -19,6 +19,7 @@ import { useState, useCallback, useMemo, useRef } from "react";
import { useMessages } from "../../../../contexts/MessagesContext";
import { useCreateFlow } from "../../context/CreateFlowContext";
import { useCreateFlowMdUp } from "../../hooks/useCreateFlowMdUp";
import { useDiscardCustomizeConfirm } from "../../hooks/useDiscardCustomizeConfirm";
import { useMethodCardDeckOrdering } from "../../hooks/useMethodCardDeckOrdering";
import { CreateFlowHeaderLockup } from "../../components/CreateFlowHeaderLockup";
import CardStack from "../../../../components/cards/CardStack";
@@ -53,8 +54,6 @@ import { buildCustomRuleModalKebabMenu } from "../../components/customRuleModalK
import { methodCardMetaWithCustomizeHeader } from "../../../../../lib/create/methodCardCustomizeMetaPatch";
import {
captureMethodCardCustomizeSnapshot,
confirmDiscardMethodCardCustomizeSession,
isMethodCardCustomizeSessionDirty,
type MethodCardCustomizeSnapshot,
type MethodCardHeaderDraft,
} from "../../../../../lib/create/methodCardCustomizeSession";
@@ -65,6 +64,8 @@ export function CommunicationMethodsScreen() {
const comm = m.create.customRule.communication;
const modalKebabMenu = m.create.customRule.modalKebabMenu;
const mdUp = useCreateFlowMdUp();
const { confirmDiscard, confirmDirtyCustomizeCancel, confirmDialog } =
useDiscardCustomizeConfirm();
const { state, updateState, replaceState, markCreateFlowInteraction } =
useCreateFlow();
const pendingEphemeralDuplicateIdRef = useRef<string | null>(null);
@@ -201,16 +202,15 @@ export function CommunicationMethodsScreen() {
],
);
const handleCreateModalClose = useCallback(() => {
const handleCreateModalClose = useCallback(async () => {
if (
!confirmDiscardMethodCardCustomizeSession(
!(await confirmDiscard(
modalEditUnlocked,
customizeSnapshotRef.current,
pendingDraft,
draftFieldBlocks,
customizeHeaderDraft,
modalKebabMenu.discardUnsavedCustomizeChanges,
)
))
) {
return;
}
@@ -241,15 +241,15 @@ export function CommunicationMethodsScreen() {
setDraftFieldBlocks(null);
setCustomizeHeaderDraft(null);
}, [
confirmDiscard,
customizeHeaderDraft,
draftFieldBlocks,
modalEditUnlocked,
modalKebabMenu.discardUnsavedCustomizeChanges,
pendingDraft,
replaceState,
]);
const handleCancelCustomize = useCallback(() => {
const handleCancelCustomize = useCallback(async () => {
if (!modalEditUnlocked) {
return;
}
@@ -262,13 +262,12 @@ export function CommunicationMethodsScreen() {
return;
}
if (
isMethodCardCustomizeSessionDirty(
!(await confirmDirtyCustomizeCancel(
snap,
pendingDraft,
draftFieldBlocks,
customizeHeaderDraft,
) &&
!window.confirm(modalKebabMenu.discardUnsavedCustomizeChanges)
))
) {
return;
}
@@ -278,27 +277,26 @@ export function CommunicationMethodsScreen() {
customizeSnapshotRef.current = null;
setCustomizeHeaderDraft(null);
}, [
confirmDirtyCustomizeCancel,
customizeHeaderDraft,
draftFieldBlocks,
modalEditUnlocked,
modalKebabMenu.discardUnsavedCustomizeChanges,
pendingDraft,
]);
const handleRemoveSelectedFromModal = useCallback(() => {
const handleRemoveSelectedFromModal = useCallback(async () => {
if (!pendingCardId || !selectedIds.includes(pendingCardId)) {
return;
}
markCreateFlowInteraction();
if (
!confirmDiscardMethodCardCustomizeSession(
!(await confirmDiscard(
modalEditUnlocked,
customizeSnapshotRef.current,
pendingDraft,
draftFieldBlocks,
customizeHeaderDraft,
modalKebabMenu.discardUnsavedCustomizeChanges,
)
))
) {
return;
}
@@ -310,14 +308,14 @@ export function CommunicationMethodsScreen() {
pendingCardId,
),
);
handleCreateModalClose();
await handleCreateModalClose();
}, [
confirmDiscard,
customizeHeaderDraft,
draftFieldBlocks,
handleCreateModalClose,
markCreateFlowInteraction,
modalEditUnlocked,
modalKebabMenu.discardUnsavedCustomizeChanges,
pendingDraft,
pendingCardId,
selectedIds,
@@ -829,6 +827,7 @@ export function CommunicationMethodsScreen() {
uploadCreateFlowFile(file, "customMethodAttachment")
}
/>
{confirmDialog}
</>
);
}
@@ -16,6 +16,7 @@ import { useState, useCallback, useMemo, useRef } from "react";
import { useMessages } from "../../../../contexts/MessagesContext";
import { useCreateFlow } from "../../context/CreateFlowContext";
import { useCreateFlowMdUp } from "../../hooks/useCreateFlowMdUp";
import { useDiscardCustomizeConfirm } from "../../hooks/useDiscardCustomizeConfirm";
import { useMethodCardDeckOrdering } from "../../hooks/useMethodCardDeckOrdering";
import { CreateFlowHeaderLockup } from "../../components/CreateFlowHeaderLockup";
import CardStack from "../../../../components/cards/CardStack";
@@ -50,8 +51,6 @@ import { buildCustomRuleModalKebabMenu } from "../../components/customRuleModalK
import { methodCardMetaWithCustomizeHeader } from "../../../../../lib/create/methodCardCustomizeMetaPatch";
import {
captureMethodCardCustomizeSnapshot,
confirmDiscardMethodCardCustomizeSession,
isMethodCardCustomizeSessionDirty,
type MethodCardCustomizeSnapshot,
type MethodCardHeaderDraft,
} from "../../../../../lib/create/methodCardCustomizeSession";
@@ -62,6 +61,8 @@ export function ConflictManagementScreen() {
const cm = m.create.customRule.conflictManagement;
const modalKebabMenu = m.create.customRule.modalKebabMenu;
const mdUp = useCreateFlowMdUp();
const { confirmDiscard, confirmDirtyCustomizeCancel, confirmDialog } =
useDiscardCustomizeConfirm();
const { state, updateState, replaceState, markCreateFlowInteraction } =
useCreateFlow();
const pendingEphemeralDuplicateIdRef = useRef<string | null>(null);
@@ -202,16 +203,15 @@ export function ConflictManagementScreen() {
],
);
const handleCreateModalClose = useCallback(() => {
const handleCreateModalClose = useCallback(async () => {
if (
!confirmDiscardMethodCardCustomizeSession(
!(await confirmDiscard(
modalEditUnlocked,
customizeSnapshotRef.current,
pendingDraft,
draftFieldBlocks,
customizeHeaderDraft,
modalKebabMenu.discardUnsavedCustomizeChanges,
)
))
) {
return;
}
@@ -242,15 +242,15 @@ export function ConflictManagementScreen() {
setDraftFieldBlocks(null);
setCustomizeHeaderDraft(null);
}, [
confirmDiscard,
customizeHeaderDraft,
draftFieldBlocks,
modalEditUnlocked,
modalKebabMenu.discardUnsavedCustomizeChanges,
pendingDraft,
replaceState,
]);
const handleCancelCustomize = useCallback(() => {
const handleCancelCustomize = useCallback(async () => {
if (!modalEditUnlocked) {
return;
}
@@ -263,13 +263,12 @@ export function ConflictManagementScreen() {
return;
}
if (
isMethodCardCustomizeSessionDirty(
!(await confirmDirtyCustomizeCancel(
snap,
pendingDraft,
draftFieldBlocks,
customizeHeaderDraft,
) &&
!window.confirm(modalKebabMenu.discardUnsavedCustomizeChanges)
))
) {
return;
}
@@ -279,27 +278,26 @@ export function ConflictManagementScreen() {
customizeSnapshotRef.current = null;
setCustomizeHeaderDraft(null);
}, [
confirmDirtyCustomizeCancel,
customizeHeaderDraft,
draftFieldBlocks,
modalEditUnlocked,
modalKebabMenu.discardUnsavedCustomizeChanges,
pendingDraft,
]);
const handleRemoveSelectedFromModal = useCallback(() => {
const handleRemoveSelectedFromModal = useCallback(async () => {
if (!pendingCardId || !selectedIds.includes(pendingCardId)) {
return;
}
markCreateFlowInteraction();
if (
!confirmDiscardMethodCardCustomizeSession(
!(await confirmDiscard(
modalEditUnlocked,
customizeSnapshotRef.current,
pendingDraft,
draftFieldBlocks,
customizeHeaderDraft,
modalKebabMenu.discardUnsavedCustomizeChanges,
)
))
) {
return;
}
@@ -311,14 +309,14 @@ export function ConflictManagementScreen() {
pendingCardId,
),
);
handleCreateModalClose();
await handleCreateModalClose();
}, [
confirmDiscard,
customizeHeaderDraft,
draftFieldBlocks,
handleCreateModalClose,
markCreateFlowInteraction,
modalEditUnlocked,
modalKebabMenu.discardUnsavedCustomizeChanges,
pendingDraft,
pendingCardId,
selectedIds,
@@ -828,6 +826,7 @@ export function ConflictManagementScreen() {
uploadCreateFlowFile(file, "customMethodAttachment")
}
/>
{confirmDialog}
</>
);
}
@@ -17,6 +17,7 @@ import { useState, useCallback, useMemo, useRef } from "react";
import { useMessages } from "../../../../contexts/MessagesContext";
import { useCreateFlow } from "../../context/CreateFlowContext";
import { useCreateFlowMdUp } from "../../hooks/useCreateFlowMdUp";
import { useDiscardCustomizeConfirm } from "../../hooks/useDiscardCustomizeConfirm";
import { useMethodCardDeckOrdering } from "../../hooks/useMethodCardDeckOrdering";
import { CreateFlowHeaderLockup } from "../../components/CreateFlowHeaderLockup";
import CardStack from "../../../../components/cards/CardStack";
@@ -51,8 +52,6 @@ import { buildCustomRuleModalKebabMenu } from "../../components/customRuleModalK
import { methodCardMetaWithCustomizeHeader } from "../../../../../lib/create/methodCardCustomizeMetaPatch";
import {
captureMethodCardCustomizeSnapshot,
confirmDiscardMethodCardCustomizeSession,
isMethodCardCustomizeSessionDirty,
type MethodCardCustomizeSnapshot,
type MethodCardHeaderDraft,
} from "../../../../../lib/create/methodCardCustomizeSession";
@@ -63,6 +62,8 @@ export function MembershipMethodsScreen() {
const mem = m.create.customRule.membership;
const modalKebabMenu = m.create.customRule.modalKebabMenu;
const mdUp = useCreateFlowMdUp();
const { confirmDiscard, confirmDirtyCustomizeCancel, confirmDialog } =
useDiscardCustomizeConfirm();
const { state, updateState, replaceState, markCreateFlowInteraction } =
useCreateFlow();
const pendingEphemeralDuplicateIdRef = useRef<string | null>(null);
@@ -199,16 +200,15 @@ export function MembershipMethodsScreen() {
],
);
const handleCreateModalClose = useCallback(() => {
const handleCreateModalClose = useCallback(async () => {
if (
!confirmDiscardMethodCardCustomizeSession(
!(await confirmDiscard(
modalEditUnlocked,
customizeSnapshotRef.current,
pendingDraft,
draftFieldBlocks,
customizeHeaderDraft,
modalKebabMenu.discardUnsavedCustomizeChanges,
)
))
) {
return;
}
@@ -239,15 +239,15 @@ export function MembershipMethodsScreen() {
setDraftFieldBlocks(null);
setCustomizeHeaderDraft(null);
}, [
confirmDiscard,
customizeHeaderDraft,
draftFieldBlocks,
modalEditUnlocked,
modalKebabMenu.discardUnsavedCustomizeChanges,
pendingDraft,
replaceState,
]);
const handleCancelCustomize = useCallback(() => {
const handleCancelCustomize = useCallback(async () => {
if (!modalEditUnlocked) {
return;
}
@@ -260,13 +260,12 @@ export function MembershipMethodsScreen() {
return;
}
if (
isMethodCardCustomizeSessionDirty(
!(await confirmDirtyCustomizeCancel(
snap,
pendingDraft,
draftFieldBlocks,
customizeHeaderDraft,
) &&
!window.confirm(modalKebabMenu.discardUnsavedCustomizeChanges)
))
) {
return;
}
@@ -276,27 +275,26 @@ export function MembershipMethodsScreen() {
customizeSnapshotRef.current = null;
setCustomizeHeaderDraft(null);
}, [
confirmDirtyCustomizeCancel,
customizeHeaderDraft,
draftFieldBlocks,
modalEditUnlocked,
modalKebabMenu.discardUnsavedCustomizeChanges,
pendingDraft,
]);
const handleRemoveSelectedFromModal = useCallback(() => {
const handleRemoveSelectedFromModal = useCallback(async () => {
if (!pendingCardId || !selectedIds.includes(pendingCardId)) {
return;
}
markCreateFlowInteraction();
if (
!confirmDiscardMethodCardCustomizeSession(
!(await confirmDiscard(
modalEditUnlocked,
customizeSnapshotRef.current,
pendingDraft,
draftFieldBlocks,
customizeHeaderDraft,
modalKebabMenu.discardUnsavedCustomizeChanges,
)
))
) {
return;
}
@@ -304,14 +302,14 @@ export function MembershipMethodsScreen() {
updateState(
removeMethodCardFromFacetSelection(state, "membership", pendingCardId),
);
handleCreateModalClose();
await handleCreateModalClose();
}, [
confirmDiscard,
customizeHeaderDraft,
draftFieldBlocks,
handleCreateModalClose,
markCreateFlowInteraction,
modalEditUnlocked,
modalKebabMenu.discardUnsavedCustomizeChanges,
pendingDraft,
pendingCardId,
selectedIds,
@@ -821,6 +819,7 @@ export function MembershipMethodsScreen() {
uploadCreateFlowFile(file, "customMethodAttachment")
}
/>
{confirmDialog}
</>
);
}
@@ -26,6 +26,7 @@ import type { InfoMessageBoxItem } from "../../../../components/controls/InfoMes
import { useMessages } from "../../../../contexts/MessagesContext";
import { useCreateFlow } from "../../context/CreateFlowContext";
import { useCreateFlowMdUp } from "../../hooks/useCreateFlowMdUp";
import { useDiscardCustomizeConfirm } from "../../hooks/useDiscardCustomizeConfirm";
import { useMethodCardDeckOrdering } from "../../hooks/useMethodCardDeckOrdering";
import { CreateFlowTwoColumnSelectShell } from "../../components/CreateFlowTwoColumnSelectShell";
import { DecisionApproachEditFields } from "../../components/methodEditFields";
@@ -52,8 +53,6 @@ import { buildCustomRuleModalKebabMenu } from "../../components/customRuleModalK
import { methodCardMetaWithCustomizeHeader } from "../../../../../lib/create/methodCardCustomizeMetaPatch";
import {
captureMethodCardCustomizeSnapshot,
confirmDiscardMethodCardCustomizeSession,
isMethodCardCustomizeSessionDirty,
type MethodCardCustomizeSnapshot,
type MethodCardHeaderDraft,
} from "../../../../../lib/create/methodCardCustomizeSession";
@@ -64,6 +63,8 @@ export function DecisionApproachesScreen() {
const da = m.create.customRule.decisionApproaches;
const modalKebabMenu = m.create.customRule.modalKebabMenu;
const mdUp = useCreateFlowMdUp();
const { confirmDiscard, confirmDirtyCustomizeCancel, confirmDialog } =
useDiscardCustomizeConfirm();
const { state, updateState, replaceState, markCreateFlowInteraction } =
useCreateFlow();
const pendingEphemeralDuplicateIdRef = useRef<string | null>(null);
@@ -216,16 +217,15 @@ export function DecisionApproachesScreen() {
],
);
const handleCreateModalClose = useCallback(() => {
const handleCreateModalClose = useCallback(async () => {
if (
!confirmDiscardMethodCardCustomizeSession(
!(await confirmDiscard(
modalEditUnlocked,
customizeSnapshotRef.current,
pendingDraft,
draftFieldBlocks,
customizeHeaderDraft,
modalKebabMenu.discardUnsavedCustomizeChanges,
)
))
) {
return;
}
@@ -256,15 +256,15 @@ export function DecisionApproachesScreen() {
setDraftFieldBlocks(null);
setCustomizeHeaderDraft(null);
}, [
confirmDiscard,
customizeHeaderDraft,
draftFieldBlocks,
modalEditUnlocked,
modalKebabMenu.discardUnsavedCustomizeChanges,
pendingDraft,
replaceState,
]);
const handleCancelCustomize = useCallback(() => {
const handleCancelCustomize = useCallback(async () => {
if (!modalEditUnlocked) {
return;
}
@@ -277,13 +277,12 @@ export function DecisionApproachesScreen() {
return;
}
if (
isMethodCardCustomizeSessionDirty(
!(await confirmDirtyCustomizeCancel(
snap,
pendingDraft,
draftFieldBlocks,
customizeHeaderDraft,
) &&
!window.confirm(modalKebabMenu.discardUnsavedCustomizeChanges)
))
) {
return;
}
@@ -293,27 +292,26 @@ export function DecisionApproachesScreen() {
customizeSnapshotRef.current = null;
setCustomizeHeaderDraft(null);
}, [
confirmDirtyCustomizeCancel,
customizeHeaderDraft,
draftFieldBlocks,
modalEditUnlocked,
modalKebabMenu.discardUnsavedCustomizeChanges,
pendingDraft,
]);
const handleRemoveSelectedFromModal = useCallback(() => {
const handleRemoveSelectedFromModal = useCallback(async () => {
if (!pendingCardId || !selectedIds.includes(pendingCardId)) {
return;
}
markCreateFlowInteraction();
if (
!confirmDiscardMethodCardCustomizeSession(
!(await confirmDiscard(
modalEditUnlocked,
customizeSnapshotRef.current,
pendingDraft,
draftFieldBlocks,
customizeHeaderDraft,
modalKebabMenu.discardUnsavedCustomizeChanges,
)
))
) {
return;
}
@@ -325,14 +323,14 @@ export function DecisionApproachesScreen() {
pendingCardId,
),
);
handleCreateModalClose();
await handleCreateModalClose();
}, [
confirmDiscard,
customizeHeaderDraft,
draftFieldBlocks,
handleCreateModalClose,
markCreateFlowInteraction,
modalEditUnlocked,
modalKebabMenu.discardUnsavedCustomizeChanges,
pendingDraft,
pendingCardId,
selectedIds,
@@ -867,6 +865,7 @@ export function DecisionApproachesScreen() {
uploadCreateFlowFile(file, "customMethodAttachment")
}
/>
{confirmDialog}
</>
);
}
@@ -8,6 +8,7 @@ import ContentLockup from "../../../../components/type/ContentLockup";
import { useMessages } from "../../../../contexts/MessagesContext";
import { buildCoreValueChipOptionsFromDraft } from "../../../../../lib/create/coreValueChipOptionsFromDraft";
import { useCreateFlow } from "../../context/CreateFlowContext";
import { useDiscardCustomizeConfirm } from "../../hooks/useDiscardCustomizeConfirm";
import type {
CommunityStructureChipSnapshotRow,
CoreValueDetailEntry,
@@ -19,7 +20,6 @@ import MethodCardCustomizeModalHeader from "../../components/MethodCardCustomize
import { buildCustomRuleModalKebabMenu } from "../../components/customRuleModalKebabMenu";
import {
captureMethodCardCustomizeSnapshot,
confirmDiscardMethodCardCustomizeSession,
isMethodCardCustomizeSessionDirty,
type MethodCardCustomizeSnapshot,
type MethodCardHeaderDraft,
@@ -101,6 +101,8 @@ export function CoreValuesSelectScreen() {
[cv.values],
);
const { confirmDiscard, confirmDirtyCustomizeCancel, confirmDialog } =
useDiscardCustomizeConfirm();
const { markCreateFlowInteraction, updateState, replaceState, state } =
useCreateFlow();
@@ -239,7 +241,7 @@ export function CoreValuesSelectScreen() {
setModalEditUnlocked(true);
}, [activeModalChipId, coreValueOptions, draft, markCreateFlowInteraction]);
const handleCancelCustomize = useCallback(() => {
const handleCancelCustomize = useCallback(async () => {
if (!modalEditUnlocked) return;
const snap = coreCustomizeSnapshotRef.current;
if (!snap) {
@@ -247,18 +249,22 @@ export function CoreValuesSelectScreen() {
return;
}
if (
isMethodCardCustomizeSessionDirty(snap, draft, null, customizeHeaderDraft) &&
!window.confirm(modalKebabMenu.discardUnsavedCustomizeChanges)
!(await confirmDirtyCustomizeCancel(
snap,
draft,
null,
customizeHeaderDraft,
))
) {
return;
}
setDraft(structuredClone(snap.pendingDraft));
resetCustomizeSession();
}, [
confirmDirtyCustomizeCancel,
customizeHeaderDraft,
draft,
modalEditUnlocked,
modalKebabMenu.discardUnsavedCustomizeChanges,
resetCustomizeSession,
]);
@@ -271,17 +277,16 @@ export function CoreValuesSelectScreen() {
);
}, [activeModalChipId, customizeHeaderDraft, coreValueOptions]);
const handleDuplicateCoreChip = useCallback(() => {
const handleDuplicateCoreChip = useCallback(async () => {
if (!activeModalChipId || !modalSession) return;
if (
!confirmDiscardMethodCardCustomizeSession(
!(await confirmDiscard(
modalEditUnlocked,
coreCustomizeSnapshotRef.current,
draft,
null,
customizeHeaderDraft,
modalKebabMenu.discardUnsavedCustomizeChanges,
)
))
) {
return;
}
@@ -317,11 +322,11 @@ export function CoreValuesSelectScreen() {
);
}, [
activeModalChipId,
confirmDiscard,
customizeHeaderDraft,
draft,
markCreateFlowInteraction,
modalEditUnlocked,
modalKebabMenu.discardUnsavedCustomizeChanges,
modalKebabMenu.duplicateTitleSuffix,
modalSession,
openModal,
@@ -329,16 +334,15 @@ export function CoreValuesSelectScreen() {
resetCustomizeSession,
]);
const handleRemoveFromKebab = useCallback(() => {
const handleRemoveFromKebab = useCallback(async () => {
if (
!confirmDiscardMethodCardCustomizeSession(
!(await confirmDiscard(
modalEditUnlocked,
coreCustomizeSnapshotRef.current,
draft,
null,
customizeHeaderDraft,
modalKebabMenu.discardUnsavedCustomizeChanges,
)
))
) {
return;
}
@@ -382,30 +386,27 @@ export function CoreValuesSelectScreen() {
finalizeModalDismiss();
}, [
activeModalChipId,
confirmDiscard,
coreValueOptions,
customizeHeaderDraft,
draft,
finalizeModalDismiss,
markCreateFlowInteraction,
modalEditUnlocked,
modalKebabMenu.discardUnsavedCustomizeChanges,
modalSession,
persistCoreValues,
replaceState,
modalSession,
persistCoreValues,
]);
const handleModalDismiss = useCallback(() => {
const handleModalDismiss = useCallback(async () => {
if (
!confirmDiscardMethodCardCustomizeSession(
!(await confirmDiscard(
modalEditUnlocked,
coreCustomizeSnapshotRef.current,
draft,
null,
customizeHeaderDraft,
modalKebabMenu.discardUnsavedCustomizeChanges,
)
))
) {
return;
}
@@ -435,12 +436,12 @@ export function CoreValuesSelectScreen() {
finalizeModalDismiss();
}, [
activeModalChipId,
confirmDiscard,
coreValueOptions,
customizeHeaderDraft,
draft,
finalizeModalDismiss,
modalEditUnlocked,
modalKebabMenu.discardUnsavedCustomizeChanges,
modalSession,
persistCoreValues,
replaceState,
@@ -645,6 +646,7 @@ export function CoreValuesSelectScreen() {
const detailModal = cv.detailModal;
return (
<>
<CreateFlowTwoColumnSelectShell
lgVerticalAlign="start"
header={
@@ -724,5 +726,7 @@ export function CoreValuesSelectScreen() {
</Create>
)}
</CreateFlowTwoColumnSelectShell>
{confirmDialog}
</>
);
}
@@ -14,7 +14,7 @@ import { CreateFlowHeaderLockup } from "../../components/CreateFlowHeaderLockup"
import { CreateFlowStepShell } from "../../components/CreateFlowStepShell";
import { CREATE_FLOW_MD_UP_COLUMN_MAX_CLASS } from "../../components/createFlowLayoutTokens";
import { fetchAuthSession } from "../../../../../lib/create/api";
import { getAssetPath } from "../../../../../lib/assetUtils";
import { ASSETS, getAssetPath } from "../../../../../lib/assetUtils";
import {
UploadToServerError,
uploadCreateFlowFile,
@@ -177,7 +177,7 @@ export function CommunityUploadScreen() {
>
{/* eslint-disable-next-line @next/next/no-img-element -- matches ModalHeader close control */}
<img
src={getAssetPath("assets/Icon_Close.svg")}
src={getAssetPath(ASSETS.ICON_CLOSE)}
alt=""
className="h-[16px] w-[16px]"
style={{
@@ -13,10 +13,11 @@ export const CREATE_FLOW_TRANSFER_PENDING_KEY =
"create-flow-transfer-pending" as const;
/**
* When signed-in + sync, {@link SignedInDraftHydration} resolves server vs this key via `window.confirm`
* if both are non-empty; see `messages/en/create/draftHydration.json`.
* When signed-in + sync, local draft wins if non-empty; server draft applies when local is empty.
* See `messages/en/create/draftHydration.json`.
*/
// TODO(legacy): Remove after production soak — one-time migration from pre-anonymous keys.
const LEGACY_LIVE_KEY = "create-flow-state";
const LEGACY_DRAFT_KEY = "create-flow-draft";
@@ -2,8 +2,7 @@ import { deleteServerDraft } from "../../../../lib/create/api";
import { clearAnonymousCreateFlowStorage } from "./anonymousDraftStorage";
import { clearCoreValueDetailsLocalStorage } from "./coreValueDetailsLocalStorage";
const SYNC_ENABLED =
process.env.NEXT_PUBLIC_ENABLE_BACKEND_SYNC === "true";
import { isBackendSyncEnabled } from "../../../../lib/create/backendSyncEnabled";
/**
* Call **before** navigating into `/create` from marketing or profile “new rule”
@@ -17,7 +16,7 @@ const SYNC_ENABLED =
export async function prepareFreshCreateFlowEntry(): Promise<void> {
clearAnonymousCreateFlowStorage();
clearCoreValueDetailsLocalStorage();
if (SYNC_ENABLED) {
if (isBackendSyncEnabled()) {
await deleteServerDraft();
}
}
+4 -1
View File
@@ -1,7 +1,10 @@
import type { ReactNode } from "react";
import { notFound } from "next/navigation";
// Development-only previews (e.g. `/components-preview`) — no public chrome.
// Routes here are gated by NODE_ENV checks at the page level.
export default function DevLayout({ children }: { children: ReactNode }) {
if (process.env.NODE_ENV === "production") {
notFound();
}
return <main className="flex-1">{children}</main>;
}
+2 -1
View File
@@ -1,4 +1,5 @@
import messages from "../../../messages/en/index";
import { getAssetPath, governanceBookletPath } from "../../../lib/assetUtils";
import { getTranslation } from "../../../lib/i18n/getTranslation";
import AboutHeader from "../../components/type/AboutHeader";
import type { AboutHeaderSegment } from "../../components/type/AboutHeader";
@@ -55,7 +56,7 @@ export default function AboutPage() {
title={page.book.title}
description={page.book.description}
buttonText={page.book.buttonText}
buttonHref={page.book.buttonHref}
buttonHref={getAssetPath(governanceBookletPath())}
imageAlt={page.book.imageAlt}
/>
<FaqAccordion title={page.faq.title} items={faqItems} />
+1 -1
View File
@@ -135,7 +135,7 @@ export default async function BlogPostPage({ params }: PageProps) {
url: "https://communityrule.com",
logo: {
"@type": "ImageObject",
url: "https://communityrule.com/assets/logo/Logo.svg",
url: "https://communityrule.com/assets/logos/community-rule.svg",
},
},
datePublished: post.frontmatter.date,
+2 -1
View File
@@ -1,5 +1,6 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import messages from "../../../../messages/en/index";
import { getPublicPublishedRuleById } from "../../../../lib/server/publishedRules";
import { parsePublishedDocumentForCommunityRuleDisplay } from "../../../../lib/create/publishedDocumentToDisplaySections";
import CommunityRule from "../../../components/type/CommunityRule";
@@ -16,7 +17,7 @@ export async function generateMetadata({
const rule = await getPublicPublishedRuleById(id);
if (!rule) {
return {
title: "Rule Not Found",
title: messages.pages.ruleDetail.notFoundTitle,
description: "The requested CommunityRule could not be found.",
};
}
@@ -0,0 +1,57 @@
"use client";
import { memo, useState } from "react";
import { useRouter } from "next/navigation";
import { useCreateFlowMdUp } from "../../../../../(app)/create/hooks/useCreateFlowMdUp";
import { useTranslation } from "../../../../../contexts/MessagesContext";
import { UseCaseCompletedRuleView } from "./UseCaseCompletedRule.view";
import {
useUseCaseCompletedRuleActions,
type UseCaseCompletedRuleActionBanner,
} from "./useUseCaseCompletedRuleActions";
import type { UseCaseCompletedRuleProps } from "./UseCaseCompletedRule.types";
/** Figma: Completed CR — use case demos (21995:39476, 21995:40092, 22015:42413). */
function UseCaseCompletedRuleContainerComponent({
slug,
fixture,
sections,
}: UseCaseCompletedRuleProps) {
const router = useRouter();
const mdUp = useCreateFlowMdUp();
const tTopNav = useTranslation("pages.useCasesCompletedRule.topNav");
const [shareModalOpen, setShareModalOpen] = useState(false);
const [actionBanner, setActionBanner] =
useState<UseCaseCompletedRuleActionBanner | null>(null);
const { copyPageLink, mailtoPageLink, handleDuplicate } =
useUseCaseCompletedRuleActions({
slug,
fixture,
setActionBanner,
});
return (
<UseCaseCompletedRuleView
slug={slug}
fixture={fixture}
sections={sections}
mdUp={mdUp}
duplicateLabel={tTopNav("duplicate")}
duplicateAriaLabel={tTopNav("duplicateAriaLabel")}
exitLabel={tTopNav("return")}
shareModalOpen={shareModalOpen}
onShareOpen={() => setShareModalOpen(true)}
onShareClose={() => setShareModalOpen(false)}
onCopyLink={() => void copyPageLink()}
onEmailShare={mailtoPageLink}
onDuplicate={() => void handleDuplicate()}
onExit={() => router.push(`/use-cases/${slug}`)}
actionBanner={actionBanner}
onActionBannerClose={() => setActionBanner(null)}
/>
);
}
export const UseCaseCompletedRule = memo(UseCaseCompletedRuleContainerComponent);
UseCaseCompletedRule.displayName = "UseCaseCompletedRule";
@@ -0,0 +1,26 @@
import type { CommunityRuleSection } from "../../../../../components/type/CommunityRule/CommunityRule.types";
import type { UseCaseDetailSlug } from "../../../../../../lib/useCaseSyntheticPost";
import type { UseCaseCompletedRuleFixture } from "../../../../../../lib/useCaseCompletedRule";
import type { UseCaseCompletedRuleActionBanner } from "./useUseCaseCompletedRuleActions";
export type UseCaseCompletedRuleProps = {
slug: UseCaseDetailSlug;
fixture: UseCaseCompletedRuleFixture;
sections: CommunityRuleSection[];
};
export type UseCaseCompletedRuleViewProps = UseCaseCompletedRuleProps & {
mdUp: boolean;
duplicateLabel: string;
duplicateAriaLabel: string;
exitLabel: string;
shareModalOpen: boolean;
onShareOpen: () => void;
onShareClose: () => void;
onCopyLink: () => void;
onEmailShare: () => void;
onDuplicate: () => void;
onExit: () => void;
actionBanner: UseCaseCompletedRuleActionBanner | null;
onActionBannerClose: () => void;
};
@@ -1,9 +1,6 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import CommunityRule from "../../../../../components/type/CommunityRule";
import type { CommunityRuleSection } from "../../../../../components/type/CommunityRule/CommunityRule.types";
import CreateFlowTopNav from "../../../../../components/navigation/CreateFlowTopNav";
import Share from "../../../../../components/modals/Share";
import Alert from "../../../../../components/modals/Alert";
@@ -12,41 +9,25 @@ import {
CREATE_FLOW_MD_UP_GRID_CELL_CLASS,
CREATE_FLOW_TWO_COLUMN_MAX_WIDTH_CLASS,
} from "../../../../../(app)/create/components/createFlowLayoutTokens";
import { useCreateFlowMdUp } from "../../../../../(app)/create/hooks/useCreateFlowMdUp";
import { useTranslation } from "../../../../../contexts/MessagesContext";
import type { UseCaseDetailSlug } from "../../../../../../lib/useCaseSyntheticPost";
import type { UseCaseCompletedRuleFixture } from "../../../../../../lib/useCaseCompletedRule";
import {
useUseCaseCompletedRuleActions,
type UseCaseCompletedRuleActionBanner,
} from "./useUseCaseCompletedRuleActions";
import type { UseCaseCompletedRuleViewProps } from "./UseCaseCompletedRule.types";
export type UseCaseCompletedRuleViewProps = {
slug: UseCaseDetailSlug;
fixture: UseCaseCompletedRuleFixture;
sections: CommunityRuleSection[];
};
/** Figma: Completed CR — use case demos (21995:39476, 21995:40092, 22015:42413). */
export function UseCaseCompletedRuleView({
slug,
fixture,
sections,
mdUp,
duplicateLabel,
duplicateAriaLabel,
exitLabel,
shareModalOpen,
onShareOpen,
onShareClose,
onCopyLink,
onEmailShare,
onDuplicate,
onExit,
actionBanner,
onActionBannerClose,
}: UseCaseCompletedRuleViewProps) {
const router = useRouter();
const mdUp = useCreateFlowMdUp();
const tTopNav = useTranslation("pages.useCasesCompletedRule.topNav");
const [shareModalOpen, setShareModalOpen] = useState(false);
const [actionBanner, setActionBanner] =
useState<UseCaseCompletedRuleActionBanner | null>(null);
const { copyPageLink, mailtoPageLink, handleDuplicate } =
useUseCaseCompletedRuleActions({
slug,
fixture,
setActionBanner,
});
const pageBg = fixture.pageBackground;
return (
@@ -69,7 +50,7 @@ export function UseCaseCompletedRuleView({
description={actionBanner.description}
hasLeadingIcon
hasBodyText={Boolean(actionBanner.description)}
onClose={() => setActionBanner(null)}
onClose={onActionBannerClose}
className="w-full"
/>
</div>
@@ -77,24 +58,24 @@ export function UseCaseCompletedRuleView({
) : null}
<Share
isOpen={shareModalOpen}
onClose={() => setShareModalOpen(false)}
onCopyLink={() => void copyPageLink()}
onEmailShare={mailtoPageLink}
onSignalShare={() => void copyPageLink()}
onSlackShare={() => void copyPageLink()}
onDiscordShare={() => void copyPageLink()}
onClose={onShareClose}
onCopyLink={onCopyLink}
onEmailShare={onEmailShare}
onSignalShare={onCopyLink}
onSlackShare={onCopyLink}
onDiscordShare={onCopyLink}
/>
<CreateFlowTopNav
hasShare
hasDuplicate
duplicateLabel={tTopNav("duplicate")}
duplicateAriaLabel={tTopNav("duplicateAriaLabel")}
exitLabel={tTopNav("return")}
duplicateLabel={duplicateLabel}
duplicateAriaLabel={duplicateAriaLabel}
exitLabel={exitLabel}
buttonPalette="inverse"
className="shrink-0 !bg-transparent"
onShare={() => setShareModalOpen(true)}
onDuplicate={() => void handleDuplicate()}
onExit={() => router.push(`/use-cases/${slug}`)}
onShare={onShareOpen}
onDuplicate={onDuplicate}
onExit={onExit}
/>
<div
className={`mx-auto grid w-full min-h-0 flex-1 grid-cols-1 gap-4 px-5 max-md:max-w-[639px] max-md:gap-6 max-md:overflow-y-auto max-md:overscroll-y-contain max-md:pt-[var(--space-800)] max-md:pb-8 md:h-full md:flex-1 md:grid-cols-2 md:grid-rows-1 md:items-start md:justify-items-center md:gap-[var(--measures-spacing-1200,48px)] md:overflow-hidden md:px-12 md:py-0 ${CREATE_FLOW_TWO_COLUMN_MAX_WIDTH_CLASS}`}
@@ -10,7 +10,7 @@ import {
USE_CASE_DETAIL_SLUGS,
useCaseContentKeyForSlug,
} from "../../../../../lib/useCaseSyntheticPost";
import { UseCaseCompletedRuleView } from "./_components/UseCaseCompletedRule.view";
import { UseCaseCompletedRule } from "./_components/UseCaseCompletedRule.container";
type PageProps = {
params: Promise<{ slug: string }>;
@@ -57,7 +57,7 @@ export default async function UseCaseCompletedRulePage({ params }: PageProps) {
}
return (
<UseCaseCompletedRuleView
<UseCaseCompletedRule
slug={resolved.slug}
fixture={resolved.fixture}
sections={resolved.sections}
+33 -33
View File
@@ -1,7 +1,8 @@
import { NextResponse, type NextRequest } from "next/server";
import { isDatabaseConfigured } from "../../../../lib/server/env";
import { listMethodRecommendations } from "../../../../lib/server/methodRecommendations";
import { dbUnavailable } from "../../../../lib/server/responses";
import { apiRoute } from "../../../../lib/server/apiRoute";
import { dbUnavailable, errorJson } from "../../../../lib/server/responses";
import {
SECTION_IDS,
type SectionId,
@@ -19,38 +20,37 @@ const SECTION_SET = new Set<string>(SECTION_IDS);
*
* See `docs/guides/template-recommendation-matrix.md` §9.2 / §10.
*/
export async function GET(request: NextRequest) {
if (!isDatabaseConfigured()) {
return dbUnavailable();
}
export const GET = apiRoute(
"createFlow.methods.get",
async (request: NextRequest) => {
if (!isDatabaseConfigured()) {
return dbUnavailable();
}
const sectionParam = request.nextUrl.searchParams.get("section");
if (!sectionParam || !SECTION_SET.has(sectionParam)) {
return NextResponse.json(
{
error: {
code: "validation_error",
message: `Unknown section. Expected one of: ${SECTION_IDS.join(", ")}`,
},
},
{ status: 400 },
const sectionParam = request.nextUrl.searchParams.get("section");
if (!sectionParam || !SECTION_SET.has(sectionParam)) {
return errorJson(
"validation_error",
`Unknown section. Expected one of: ${SECTION_IDS.join(", ")}`,
400,
);
}
const section = sectionParam as SectionId;
const facets = parseRequestedFacetsFromSearchParams(
request.nextUrl.searchParams,
);
}
const section = sectionParam as SectionId;
const result = await listMethodRecommendations({ section, facets });
if (!result) {
// DB query failed; return empty so the wizard falls back to its messages
// deck in authoring order (§10).
return NextResponse.json({ section, methods: [] });
}
const facets = parseRequestedFacetsFromSearchParams(
request.nextUrl.searchParams,
);
const result = await listMethodRecommendations({ section, facets });
if (!result) {
// DB query failed; return empty so the wizard falls back to its messages
// deck in authoring order (§10).
return NextResponse.json({ section, methods: [] });
}
const methods = result.rankedSlugs.map((slug) => ({
slug,
matches: result.matchesBySlug[slug] ?? { score: 0, matchedFacets: [] },
}));
return NextResponse.json({ section, methods });
}
const methods = result.rankedSlugs.map((slug) => ({
slug,
matches: result.matchesBySlug[slug] ?? { score: 0, matchedFacets: [] },
}));
return NextResponse.json({ section, methods });
},
);
+3 -2
View File
@@ -1,8 +1,9 @@
import { NextResponse } from "next/server";
import { prisma } from "../../../lib/server/db";
import { isDatabaseConfigured } from "../../../lib/server/env";
import { apiRoute } from "../../../lib/server/apiRoute";
export async function GET() {
export const GET = apiRoute("health.get", async () => {
if (!isDatabaseConfigured()) {
return NextResponse.json({
ok: true,
@@ -16,4 +17,4 @@ export async function GET() {
} catch {
return NextResponse.json({ ok: false, database: "error" }, { status: 503 });
}
}
});
+3 -2
View File
@@ -3,6 +3,7 @@ import { isDatabaseConfigured } from "../../../lib/server/env";
import { listRankedRuleTemplatesFromDb } from "../../../lib/server/ruleTemplates";
import { dbUnavailable } from "../../../lib/server/responses";
import { parseRequestedFacetsFromSearchParams } from "../../../lib/server/validation/methodFacetsSchemas";
import { apiRoute } from "../../../lib/server/apiRoute";
/**
* GET /api/templates
@@ -15,7 +16,7 @@ import { parseRequestedFacetsFromSearchParams } from "../../../lib/server/valida
*
* See `docs/guides/template-recommendation-matrix.md` §9.1.
*/
export async function GET(request: NextRequest) {
export const GET = apiRoute("templates.get", async (request: NextRequest) => {
if (!isDatabaseConfigured()) {
return dbUnavailable();
}
@@ -29,4 +30,4 @@ export async function GET(request: NextRequest) {
return NextResponse.json(
hasScores ? { templates, scores } : { templates },
);
}
});
+47 -62
View File
@@ -1,5 +1,6 @@
import { NextRequest, NextResponse } from "next/server";
import { logger } from "../../../lib/logger";
import { apiRoute } from "../../../lib/server/apiRoute";
import { getWebVitalsStorageMode } from "../../../lib/server/webVitals/mode";
import {
appendLocalWebVital,
@@ -29,70 +30,54 @@ function logExternalIngest(body: WebVitalData): void {
logger.info(line);
}
export async function POST(request: NextRequest) {
try {
const limited = await readLimitedJson(request);
if (limited.ok === false) {
return limited.response;
}
const parsed = webVitalIngestSchema.safeParse(limited.value);
if (!parsed.success) return jsonFromZodError(parsed.error);
const body = parsed.data;
const vitalsData: WebVitalData = {
metric: body.metric,
data: {
value: body.data.value,
rating: body.data.rating,
},
url: body.url,
userAgent: body.userAgent,
timestamp: normalizeTimestamp(body.timestamp),
receivedAt: new Date().toISOString(),
};
const mode = getWebVitalsStorageMode();
if (mode === "external") {
logExternalIngest(vitalsData);
return NextResponse.json({ success: true, storage: "external" });
}
appendLocalWebVital(vitalsData);
logger.info(
`Web Vital received: ${body.metric} = ${body.data.value}ms (${body.data.rating})`,
);
return NextResponse.json({ success: true, storage: "local" });
} catch (error) {
logger.error("Error processing web vital:", error);
return NextResponse.json(
{ error: "Internal server error" },
{ status: 500 },
);
export const POST = apiRoute("webVitals.post", async (request: NextRequest) => {
const limited = await readLimitedJson(request);
if (limited.ok === false) {
return limited.response;
}
}
export async function GET() {
try {
const mode = getWebVitalsStorageMode();
const parsed = webVitalIngestSchema.safeParse(limited.value);
if (!parsed.success) return jsonFromZodError(parsed.error);
if (mode === "external") {
return NextResponse.json({
metrics: {},
storage: "external" as const,
});
}
const body = parsed.data;
const metrics = readLocalAggregatedMetrics();
return NextResponse.json({ metrics, storage: "local" as const });
} catch (error) {
logger.error("Error fetching web vitals:", error);
return NextResponse.json(
{ error: "Internal server error" },
{ status: 500 },
);
const vitalsData: WebVitalData = {
metric: body.metric,
data: {
value: body.data.value,
rating: body.data.rating,
},
url: body.url,
userAgent: body.userAgent,
timestamp: normalizeTimestamp(body.timestamp),
receivedAt: new Date().toISOString(),
};
const mode = getWebVitalsStorageMode();
if (mode === "external") {
logExternalIngest(vitalsData);
return NextResponse.json({ success: true, storage: "external" });
}
}
appendLocalWebVital(vitalsData);
logger.info(
`Web Vital received: ${body.metric} = ${body.data.value}ms (${body.data.rating})`,
);
return NextResponse.json({ success: true, storage: "local" });
});
export const GET = apiRoute("webVitals.get", async () => {
const mode = getWebVitalsStorageMode();
if (mode === "external") {
return NextResponse.json({
metrics: {},
storage: "external" as const,
});
}
const metrics = readLocalAggregatedMetrics();
return NextResponse.json({ metrics, storage: "local" as const });
});
+9 -4
View File
@@ -1,5 +1,8 @@
"use client";
import { memo } from "react";
import Link from "next/link";
import { useTranslation } from "../../../contexts/MessagesContext";
import { getAssetPath, ASSETS } from "../../../../lib/assetUtils";
interface LogoProps {
@@ -31,6 +34,8 @@ interface SizeConfig {
const Logo = memo<LogoProps>(
({ size = "default", palette = "default", wordmark = true }) => {
const t = useTranslation("controlsChrome");
// Size configurations
const sizes: Record<string, SizeConfig> = {
default: {
@@ -97,7 +102,7 @@ const Logo = memo<LogoProps>(
: "hidden";
return (
<Link href="/" className="block" aria-label="CommunityRule Logo">
<Link href="/" className="block" aria-label={t("logoAlt")}>
<div
className={`flex items-center ${config.containerHeight} ${
wordmark ? config.gap : ""
@@ -106,16 +111,16 @@ const Logo = memo<LogoProps>(
{/* Logo Text - responsive visibility for topNav sizes */}
<div
className={`font-bricolage-grotesque ${textColorClass} ${config.textSize} ${config.lineHeight} font-normal tracking-[0px] transition-colors duration-200 ${wordmarkVisibilityClass}`}
aria-label="CommunityRule"
aria-label={t("logoText")}
>
CommunityRule
{t("logoText")}
</div>
{/* Vector Icon */}
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src={getAssetPath(ASSETS.LOGO)}
alt="CommunityRule Logo Icon"
alt={t("logoAlt")}
width={27.05}
height={27.05}
className={`flex-shrink-0 ${config.iconSize} transition-all duration-200 ${
@@ -1,11 +1,11 @@
"use client";
import { memo, useCallback, useState } from "react";
import { useTranslation } from "../../../contexts/MessagesContext";
import { CardStackView } from "./CardStack.view";
import type { CardStackProps } from "./CardStack.types";
const DEFAULT_TOGGLE_LABEL = "See all communication approaches";
const DEFAULT_SHOW_LESS_LABEL = "Show less";
/**
* Figma: "Utility / CardStack"; canonical code under `cards/`.
@@ -22,7 +22,7 @@ const CardStackContainer = memo<CardStackProps>(
onToggleExpand: controlledOnToggleExpand,
hasMore = true,
toggleLabel = DEFAULT_TOGGLE_LABEL,
showLessLabel = DEFAULT_SHOW_LESS_LABEL,
showLessLabel,
title = "",
description = "",
layout = "default",
@@ -37,6 +37,7 @@ const CardStackContainer = memo<CardStackProps>(
addCardAriaLabel = "",
onAddCard,
}) => {
const t = useTranslation("controlsChrome");
const [internalExpanded, setInternalExpanded] = useState(false);
const [internalSelectedIds, setInternalSelectedIds] = useState<string[]>(
[],
@@ -84,7 +85,7 @@ const CardStackContainer = memo<CardStackProps>(
onToggleExpand={handleToggleExpand}
hasMore={hasMore}
toggleLabel={toggleLabel}
showLessLabel={showLessLabel}
showLessLabel={showLessLabel ?? t("cardStackShowLess")}
title={title}
description={description}
layout={layout}
@@ -7,10 +7,10 @@ export type CaseStudySurfaceValue = (typeof CASE_STUDY_SURFACE_OPTIONS)[number];
export interface CaseStudyProps {
surface: CaseStudySurfaceValue;
/**
* Alt text for built-in raster art (`public/assets/use-cases/`) when **`visual`** is omitted.
* Alt text for built-in SVG art (`public/assets/case-study/`) when **`visual`** is omitted.
*/
imageAlt?: string;
/** Overrides built-in raster with custom slot content when provided. */
/** Overrides built-in artwork with custom slot content when provided. */
visual?: ReactNode;
className?: string;
}
@@ -2,6 +2,7 @@
import Image from "next/image";
import { memo } from "react";
import { caseStudyVisualPath, getAssetPath } from "../../../../lib/assetUtils";
import type { CaseStudyProps } from "./CaseStudy.types";
const SURFACE_CLASS: Record<CaseStudyProps["surface"], string> = {
@@ -12,9 +13,9 @@ const SURFACE_CLASS: Record<CaseStudyProps["surface"], string> = {
/** Default art per tile: Figma-exported SVG composites (305×305 incl. rounded bg). */
const SURFACE_ART: Record<CaseStudyProps["surface"], string> = {
lavender: "/assets/case-study/case-study-mutual-aid.svg",
neutral: "/assets/case-study/case-study-food-not-bombs.svg",
rose: "/assets/case-study/case-study-boulder-county-street-medics.svg",
lavender: getAssetPath(caseStudyVisualPath("lavender")),
neutral: getAssetPath(caseStudyVisualPath("neutral")),
rose: getAssetPath(caseStudyVisualPath("rose")),
};
/** Figma: ~23px corner (“Card / CaseStudy” shells). */
@@ -1,5 +1,9 @@
"use client";
/**
* Figma: "Card / Icon" (see registry)
*/
import { memo, useId } from "react";
import { IconView } from "./Icon.view";
import type { IconProps } from "./Icon.types";
+17 -2
View File
@@ -1,6 +1,11 @@
"use client";
/**
* Figma: "Card / Mini" (see registry)
*/
import { memo, useMemo } from "react";
import { useTranslation } from "../../../contexts/MessagesContext";
import MiniView from "./Mini.view";
import type { MiniProps } from "./Mini.types";
@@ -16,15 +21,21 @@ const MiniContainer = memo<MiniProps>(
onClick,
href,
ariaLabel,
featureGridShell = false,
panelWidth,
panelHeight,
panelImageClassName,
}) => {
const t = useTranslation("controlsChrome");
// Compute aria-label
const computedAriaLabel = useMemo(
() =>
ariaLabel ||
(labelLine1 && labelLine2
? `${labelLine1} ${labelLine2}`
: label || "Feature card"),
[ariaLabel, labelLine1, labelLine2, label],
: label || t("miniFeatureFallback")),
[ariaLabel, labelLine1, labelLine2, label, t],
);
// Determine wrapper element and props
@@ -85,6 +96,10 @@ const MiniContainer = memo<MiniProps>(
computedAriaLabel={computedAriaLabel}
wrapperElement={wrapperElement}
wrapperProps={wrapperProps}
featureGridShell={featureGridShell}
panelWidth={panelWidth}
panelHeight={panelHeight}
panelImageClassName={panelImageClassName}
>
{children}
</MiniView>
+9
View File
@@ -9,6 +9,11 @@ export interface MiniProps {
onClick?: () => void;
href?: string;
ariaLabel?: string;
/** Figma Feature-Grid mini tile shell (18847:22410). */
featureGridShell?: boolean;
panelWidth?: number;
panelHeight?: number;
panelImageClassName?: string;
}
export interface MiniViewProps {
@@ -25,4 +30,8 @@ export interface MiniViewProps {
| React.AnchorHTMLAttributes<HTMLAnchorElement>
| React.ButtonHTMLAttributes<HTMLButtonElement>
| React.HTMLAttributes<HTMLDivElement>;
featureGridShell?: boolean;
panelWidth?: number;
panelHeight?: number;
panelImageClassName?: string;
}
+36 -15
View File
@@ -2,6 +2,7 @@
import { memo } from "react";
import Image from "next/image";
import { SVG_GRAIN_MULTIPLY_FILTER } from "../../../../lib/svgGrainFilter";
import type { MiniViewProps } from "./Mini.types";
function MiniView({
@@ -15,39 +16,59 @@ function MiniView({
computedAriaLabel,
wrapperElement,
wrapperProps,
featureGridShell = false,
panelWidth,
panelHeight,
panelImageClassName,
}: MiniViewProps) {
const defaultPanelSize = featureGridShell ? 48 : 58;
const imageWidth = panelWidth ?? defaultPanelSize;
const imageHeight = panelHeight ?? defaultPanelSize;
const outerClass = featureGridShell
? `flex min-h-[159px] flex-col gap-[7px] ${className}`
: `h-[186px] flex flex-col gap-[7px] ${className}`;
const panelClass = featureGridShell
? `h-[138px] shrink-0 rounded-[var(--measures-radius-400,16px)] px-[24px] py-[32px] ${backgroundColor} flex items-center justify-center`
: `flex-1 rounded-[var(--radius-measures-radius-xlarge)] border border-[1px] py-[var(--spacing-scale-032)] px-[var(--spacing-scale-024)] ${backgroundColor} flex items-center justify-center transition-all duration-200 hover:scale-[1.02] hover:shadow-lg`;
const imageClass = featureGridShell
? `max-h-[48px] max-w-[56px] w-auto h-auto object-contain${panelImageClassName ? ` ${panelImageClassName}` : ""}`
: "max-w-[58px] max-h-[58px] w-auto h-auto object-contain";
const cardContentElement = (
<div className={`h-[186px] flex flex-col gap-[7px] ${className}`}>
{/* Top part - Inner panel */}
<div
className={`flex-1 rounded-[var(--radius-measures-radius-xlarge)] border border-[1px] py-[var(--spacing-scale-032)] px-[var(--spacing-scale-024)] ${backgroundColor} flex items-center justify-center transition-all duration-200 hover:scale-[1.02] hover:shadow-lg`}
>
{/* Content for the inner panel */}
<div className={outerClass}>
<div className={panelClass}>
{panelContent && (
<div className="flex items-center justify-center w-full h-full">
<div className="flex h-full w-full items-center justify-center">
<Image
src={panelContent}
alt={computedAriaLabel}
className="max-w-[58px] max-h-[58px] w-auto h-auto object-contain"
width={58}
height={58}
className={imageClass}
width={imageWidth}
height={imageHeight}
sizes="(max-width: 768px) 50vw, 25vw"
loading="lazy"
placeholder="blur"
blurDataURL="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCAABAAEDASIAAhEBAxEB/8QAFQABAQAAAAAAAAAAAAAAAAAAAAv/xAAUEAEAAAAAAAAAAAAAAAAAAAAA/8QAFQEBAQAAAAAAAAAAAAAAAAAAAAX/xAAUEQEAAAAAAAAAAAAAAAAAAAAA/9oADAMBAAIRAxEAPwCdABmX/9k="
style={
featureGridShell
? {
filter: SVG_GRAIN_MULTIPLY_FILTER,
WebkitFilter: SVG_GRAIN_MULTIPLY_FILTER,
}
: undefined
}
/>
</div>
)}
{children}
</div>
{/* Bottom part - Text container */}
<div className="font-inter font-medium text-[12px] leading-[14px] text-center text-[var(--color-content-default-primary)]">
<div className="text-center font-inter text-[12px] font-medium leading-[14px] text-[var(--color-content-default-primary)]">
{labelLine1 && labelLine2 ? (
<>
<div>{labelLine1}</div>
<div>{labelLine2}</div>
<div>&nbsp;</div>
</>
) : (
label
@@ -1,6 +1,7 @@
"use client";
import { memo } from "react";
import { useTranslation } from "../../../contexts/MessagesContext";
import { RuleView } from "./Rule.view";
import type { RuleProps } from "./Rule.types";
@@ -49,6 +50,9 @@ const RuleContainer = memo<RuleProps>(
fluidWidth = false,
}) => {
const size = sizeProp ?? "L";
const t = useTranslation("ruleCard");
const cardAriaLabel = t("ariaLabel")?.replace("{title}", title) || title;
const recommendedLabel = t("recommendedLabel");
const handleClick = () => {
if (hasBottomLinks) return;
@@ -106,6 +110,8 @@ const RuleContainer = memo<RuleProps>(
recommended={recommended}
templateGridFigmaShell={templateGridFigmaShell}
fluidWidth={fluidWidth}
cardAriaLabel={cardAriaLabel}
recommendedLabel={recommendedLabel}
/>
);
},
+3
View File
@@ -107,4 +107,7 @@ export interface RuleViewProps {
recommended?: boolean;
templateGridFigmaShell?: boolean;
fluidWidth?: boolean;
/** Interactive card aria-label; supplied by the container from `ruleCard` messages. */
cardAriaLabel: string;
recommendedLabel: string;
}
+4 -4
View File
@@ -1,7 +1,6 @@
"use client";
import Image from "next/image";
import { useTranslation } from "../../../contexts/MessagesContext";
import MultiSelect from "../../controls/MultiSelect";
import InlineTextButton from "../../buttons/InlineTextButton";
import NavigationLink from "../../navigation/Link";
@@ -34,9 +33,10 @@ export function RuleView({
recommended = false,
templateGridFigmaShell = false,
fluidWidth = false,
cardAriaLabel,
recommendedLabel,
}: RuleViewProps) {
const t = useTranslation("ruleCard");
const ariaLabel = t("ariaLabel")?.replace("{title}", title) || title;
const ariaLabel = cardAriaLabel;
const interactiveCard = !hasBottomLinks;
// Size-based styling
@@ -306,7 +306,7 @@ export function RuleView({
>
{showRecommendedTag ? (
<Tag variant="templateRecommended">
{t("recommendedLabel")}
{recommendedLabel}
</Tag>
) : null}
{onTitleClick ? (
@@ -1,5 +1,9 @@
"use client";
/**
* Figma: "Card / Stat" (21598-18215)
*/
import { memo } from "react";
import StatView from "./Stat.view";
import type { StatProps } from "./Stat.types";
@@ -20,7 +20,7 @@ function ContentContainerView({
return (
<div
className={containerClasses}
style={size === "responsive" || size === "xs" ? {} : { width }}
style={size === "xs" ? {} : { width }}
>
{/* Content Container - gap between icon and text */}
<div className={contentGapClasses}>
@@ -1,6 +1,7 @@
"use client";
import { memo, useState, useEffect, useRef } from "react";
import { useTranslation } from "../../../contexts/MessagesContext";
import ChipView from "./Chip.view";
import type { ChipProps } from "./Chip.types";
@@ -22,6 +23,7 @@ const ChipContainer = memo<ChipProps>(
onClose,
ariaLabel,
}) => {
const t = useTranslation("controlsChrome");
const state = stateProp;
const palette = paletteProp;
const size = sizeProp;
@@ -92,6 +94,9 @@ const ChipContainer = memo<ChipProps>(
onInputKeyDown={isCustom ? handleKeyDown : undefined}
inputRef={isCustom ? inputRef : undefined}
ariaLabel={ariaLabel}
confirmAriaLabel={t("chipConfirm")}
typeToAddPlaceholder={t("chipTypeToAdd")}
closeAriaLabel={t("chipClose")}
/>
);
},
@@ -68,4 +68,7 @@ export interface ChipViewProps {
onInputKeyDown?: (event: React.KeyboardEvent<HTMLInputElement>) => void;
inputRef?: React.RefObject<HTMLInputElement>;
ariaLabel?: string;
confirmAriaLabel: string;
typeToAddPlaceholder: string;
closeAriaLabel: string;
}
+6 -3
View File
@@ -19,6 +19,9 @@ function ChipView({
onInputKeyDown,
inputRef,
ariaLabel,
confirmAriaLabel,
typeToAddPlaceholder,
closeAriaLabel,
}: ChipViewProps) {
// The container is the source of truth for `disabled`. This allows
// `state="disabled"` to be used purely as a visual (for toggle-group chips
@@ -167,7 +170,7 @@ function ChipView({
<button
type="button"
className="flex items-center justify-center p-[var(--measures-spacing-150,6px)] rounded-full hover:bg-[var(--color-surface-default-semi-opaque,rgba(0,0,0,0.1))] transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
aria-label="Confirm"
aria-label={confirmAriaLabel}
disabled={!inputValue || !inputValue.trim()}
onClick={(event) => {
event.stopPropagation();
@@ -204,7 +207,7 @@ function ChipView({
value={inputValue ?? ""}
onChange={(e) => onInputChange?.(e.target.value)}
onKeyDown={onInputKeyDown}
placeholder="Type to add"
placeholder={typeToAddPlaceholder}
className="bg-transparent border-none outline-none flex-1 min-w-0 font-inter font-normal text-[color:var(--color-content-default-tertiary,#b4b4b4)] placeholder:text-[color:var(--color-content-default-tertiary,#b4b4b4)]"
style={{
fontSize: isSmall
@@ -222,7 +225,7 @@ function ChipView({
<button
type="button"
className="flex items-center justify-center p-[var(--measures-spacing-150,6px)] rounded-full hover:bg-[var(--color-surface-default-semi-opaque,rgba(0,0,0,0.1))] transition-colors"
aria-label="Close"
aria-label={closeAriaLabel}
onClick={(event) => {
event.stopPropagation();
onClose(event);
@@ -1,6 +1,7 @@
"use client";
import { memo } from "react";
import { useTranslation } from "../../../contexts/MessagesContext";
import MultiSelectView from "./MultiSelect.view";
import type { MultiSelectProps } from "./MultiSelect.types";
@@ -18,12 +19,13 @@ const MultiSelectContainer = memo<MultiSelectProps>(
onChipClick,
onAddClick,
addButton: addButtonProp = true,
addButtonText = "Add organization type",
addButtonText,
formHeader = true,
onCustomChipConfirm,
onCustomChipClose,
className = "",
}) => {
const t = useTranslation("controlsChrome");
const size = sizeProp;
const palette = paletteProp;
@@ -38,6 +40,9 @@ const MultiSelectContainer = memo<MultiSelectProps>(
onAddClick={onAddClick}
addButton={addButtonProp}
addButtonText={addButtonText}
addButtonAriaLabel={
addButtonText || t("multiSelectAddFallback")
}
formHeader={formHeader}
onCustomChipConfirm={onCustomChipConfirm}
onCustomChipClose={onCustomChipClose}
@@ -74,7 +74,8 @@ export interface MultiSelectViewProps {
onChipClick?: (chipId: string) => void;
onAddClick?: () => void;
addButton: boolean;
addButtonText: string;
addButtonText?: string;
addButtonAriaLabel: string;
formHeader: boolean;
onCustomChipConfirm?: (chipId: string, value: string) => void;
onCustomChipClose?: (chipId: string) => void;
@@ -15,6 +15,7 @@ function MultiSelectView({
onAddClick,
addButton,
addButtonText,
addButtonAriaLabel,
formHeader = true,
onCustomChipConfirm,
onCustomChipClose,
@@ -81,7 +82,7 @@ function MultiSelectView({
{addButton && (
<button
type="button"
aria-label={addButtonText || "Add option"}
aria-label={addButtonAriaLabel}
onClick={(e) => {
e.stopPropagation();
onAddClick?.();
@@ -5,10 +5,11 @@ import { forwardRef, memo } from "react";
interface SelectDropdownProps extends React.HTMLAttributes<HTMLDivElement> {
className?: string;
children?: React.ReactNode;
ariaLabel: string;
}
const SelectDropdown = forwardRef<HTMLDivElement, SelectDropdownProps>(
({ className = "", children, ...props }, ref) => {
({ className = "", children, ariaLabel, ...props }, ref) => {
const menuClasses = `
bg-black
border border-[var(--color-border-default-tertiary)]
@@ -27,7 +28,7 @@ const SelectDropdown = forwardRef<HTMLDivElement, SelectDropdownProps>(
ref={ref}
className={menuClasses}
role="listbox"
aria-label="Select an option"
aria-label={ariaLabel}
style={{ backgroundColor: "#000000" }}
{...props}
>
@@ -14,6 +14,7 @@ import React, {
useEffect,
} from "react";
import { useClickOutside } from "../../../hooks";
import { useTranslation } from "../../../contexts/MessagesContext";
import { SelectInputView } from "./SelectInput.view";
import type { SelectInputProps } from "./SelectInput.types";
@@ -38,7 +39,7 @@ const SelectInputContainer = forwardRef<HTMLButtonElement, SelectInputProps>(
textHint = false,
disabled = false,
error = false,
placeholder = "Choose an option",
placeholder,
className = "",
children,
value,
@@ -48,6 +49,9 @@ const SelectInputContainer = forwardRef<HTMLButtonElement, SelectInputProps>(
},
ref,
) => {
const t = useTranslation("controlsChrome");
const resolvedPlaceholder = placeholder ?? t("selectPlaceholder");
// Determine if label should be shown
const shouldShowLabel =
showLabel !== undefined ? showLabel : labelText !== undefined;
@@ -181,13 +185,13 @@ const SelectInputContainer = forwardRef<HTMLButtonElement, SelectInputProps>(
// Get display text for selected value
const getDisplayText = (): string => {
if (!selectedValue) return placeholder;
if (!selectedValue) return resolvedPlaceholder;
if (options && Array.isArray(options)) {
const selectedOption = options.find(
(option) => option.value === selectedValue,
);
return selectedOption ? selectedOption.label : placeholder;
return selectedOption ? selectedOption.label : resolvedPlaceholder;
}
const selectedOption = Children.toArray(children).find(
@@ -207,13 +211,13 @@ const SelectInputContainer = forwardRef<HTMLButtonElement, SelectInputProps>(
);
return selectedOption
? String(selectedOption.props.children)
: placeholder;
: resolvedPlaceholder;
};
return (
<SelectInputView
label={shouldShowLabel ? labelText : undefined}
placeholder={placeholder}
placeholder={resolvedPlaceholder}
state={actualState}
disabled={disabled}
error={error}
@@ -241,6 +245,8 @@ const SelectInputContainer = forwardRef<HTMLButtonElement, SelectInputProps>(
textData={textData}
iconRight={iconRight}
textHint={textHint}
selectAriaLabel={t("selectAriaLabel")}
hintDefault={t("hintDefault")}
{...props}
/>
);
@@ -40,6 +40,8 @@ export interface SelectInputViewProps {
textData?: boolean;
iconRight?: boolean;
textHint?: boolean;
selectAriaLabel: string;
hintDefault: string;
}
export function SelectInputView({
@@ -72,6 +74,8 @@ export function SelectInputView({
textData = true,
iconRight = true,
textHint = false,
selectAriaLabel,
hintDefault,
}: SelectInputViewProps) {
// Styles based on Figma design
const containerClasses = "flex flex-col gap-[8px]";
@@ -222,7 +226,7 @@ export function SelectInputView({
ref={menuRef}
className="absolute top-full left-0 right-0 z-50 mt-1"
>
<SelectDropdown>
<SelectDropdown ariaLabel={selectAriaLabel}>
{options && Array.isArray(options)
? options.map((option) => (
<SelectOption
@@ -268,7 +272,7 @@ export function SelectInputView({
{textHint && (
<div className="flex items-start relative shrink-0 w-full">
<p className="flex-[1_0_0] font-inter font-normal leading-[16px] min-h-px min-w-px relative text-[color:var(--color-content-default-tertiary,#b4b4b4)] text-[length:var(--sizing-300,12px)]">
Hint text here
{hintDefault}
</p>
</div>
)}
@@ -1,6 +1,7 @@
"use client";
import { memo, useCallback, useId, forwardRef } from "react";
import { useTranslation } from "../../../contexts/MessagesContext";
import { SwitchView } from "./Switch.view";
import type { SwitchProps } from "./Switch.types";
@@ -10,6 +11,7 @@ import type { SwitchProps } from "./Switch.types";
*/
const SwitchContainer = memo(
forwardRef<HTMLButtonElement, SwitchProps>((props, ref) => {
const t = useTranslation("controlsChrome");
const {
propSwitch = false,
onChange,
@@ -154,6 +156,7 @@ const SwitchContainer = memo(
trackClasses={trackClasses}
thumbClasses={thumbClasses}
labelClasses={labelClasses}
switchAriaLabel={text ?? t("toggleSwitch")}
onClick={handleClick}
onKeyDown={handleKeyDown}
onFocus={handleFocus}
@@ -37,6 +37,7 @@ export interface SwitchViewProps {
trackClasses: string;
thumbClasses: string;
labelClasses: string;
switchAriaLabel: string;
onClick: (_e: React.MouseEvent<HTMLButtonElement>) => void;
onKeyDown: (_e: React.KeyboardEvent<HTMLButtonElement>) => void;
onFocus: (_e: React.FocusEvent<HTMLButtonElement>) => void;
@@ -11,6 +11,7 @@ export const SwitchView = forwardRef<HTMLButtonElement, SwitchViewProps>(
trackClasses,
thumbClasses,
labelClasses,
switchAriaLabel,
onClick,
onKeyDown,
onFocus,
@@ -27,7 +28,7 @@ export const SwitchView = forwardRef<HTMLButtonElement, SwitchViewProps>(
type="button"
role="switch"
aria-checked={propSwitch}
aria-label={text || "Toggle switch"}
aria-label={switchAriaLabel}
onClick={onClick}
onKeyDown={onKeyDown}
onFocus={onFocus}
@@ -2,6 +2,7 @@
import { memo, forwardRef } from "react";
import { useComponentId, useFormField } from "../../../hooks";
import { useTranslation } from "../../../contexts/MessagesContext";
import { TextAreaView } from "./TextArea.view";
import type { TextAreaProps } from "./TextArea.types";
@@ -35,6 +36,7 @@ const TextAreaContainer = forwardRef<HTMLTextAreaElement, TextAreaProps>(
},
ref,
) => {
const t = useTranslation("controlsChrome");
const size = sizeProp;
const labelVariant = labelVariantProp;
const state = stateProp;
@@ -200,6 +202,8 @@ const TextAreaContainer = forwardRef<HTMLTextAreaElement, TextAreaProps>(
formHeader={formHeader}
showHelpIcon={showHelpIcon}
appearance={appearance}
helpIconAlt={t("helpIconAlt")}
hintDefault={t("hintDefault")}
{...props}
/>
);
@@ -79,4 +79,6 @@ export interface TextAreaViewProps {
formHeader?: boolean;
showHelpIcon?: boolean;
appearance?: "default" | "embedded";
helpIconAlt: string;
hintDefault: string;
}
@@ -25,6 +25,8 @@ export const TextAreaView = forwardRef<HTMLTextAreaElement, TextAreaViewProps>(
formHeader = true,
showHelpIcon = false,
appearance: _appearance,
helpIconAlt,
hintDefault,
// Component-only props: do not pass to DOM
size: _size,
labelVariant: _labelVariant,
@@ -51,7 +53,7 @@ export const TextAreaView = forwardRef<HTMLTextAreaElement, TextAreaViewProps>(
{/* eslint-disable-next-line @next/next/no-img-element -- icon asset */}
<img
src={getAssetPath(ASSETS.ICON_HELP)}
alt="Help"
alt={helpIconAlt}
className="block max-w-none size-full"
/>
</div>
@@ -81,7 +83,7 @@ export const TextAreaView = forwardRef<HTMLTextAreaElement, TextAreaViewProps>(
{textHint ? (
<div className="flex items-start relative shrink-0 w-full">
<p className="flex-[1_0_0] font-inter font-normal leading-[16px] min-h-px min-w-px relative text-[color:var(--color-content-default-tertiary,#b4b4b4)] text-[length:var(--sizing-300,12px)]">
{typeof textHint === "string" ? textHint : "Hint text here"}
{typeof textHint === "string" ? textHint : hintDefault}
</p>
</div>
) : null}
@@ -2,6 +2,7 @@
import { memo, forwardRef, useState, useRef } from "react";
import { useComponentId, useFormField } from "../../../hooks";
import { useTranslation } from "../../../contexts/MessagesContext";
import { TextInputView } from "./TextInput.view";
import type { TextInputProps } from "./TextInput.types";
@@ -34,6 +35,7 @@ const TextInputContainer = forwardRef<HTMLInputElement, TextInputProps>(
},
ref,
) => {
const t = useTranslation("controlsChrome");
const externalState = externalStateProp;
const inputSize = inputSizeProp;
@@ -244,6 +246,8 @@ const TextInputContainer = forwardRef<HTMLInputElement, TextInputProps>(
textHint={textHint}
formHeader={formHeader}
maxLength={maxLength}
helpIconAlt={t("helpIconAlt")}
hintDefault={t("hintDefault")}
{...props}
/>
);
@@ -65,4 +65,6 @@ export interface TextInputViewProps {
textHint?: boolean | string;
formHeader?: boolean;
maxLength?: number;
helpIconAlt: string;
hintDefault: string;
}
@@ -29,6 +29,8 @@ export const TextInputView = forwardRef<HTMLInputElement, TextInputViewProps>(
textHint = false,
formHeader = true,
maxLength,
helpIconAlt,
hintDefault,
},
ref,
) => {
@@ -49,7 +51,7 @@ export const TextInputView = forwardRef<HTMLInputElement, TextInputViewProps>(
{/* eslint-disable-next-line @next/next/no-img-element -- icon asset */}
<img
src={getAssetPath(ASSETS.ICON_HELP)}
alt="Help"
alt={helpIconAlt}
className="block max-w-none size-full"
/>
</div>
@@ -83,7 +85,7 @@ export const TextInputView = forwardRef<HTMLInputElement, TextInputViewProps>(
{textHint && (
<div className="flex items-start relative shrink-0 w-full">
<p className="flex-[1_0_0] font-inter font-normal leading-[16px] min-h-px min-w-px relative text-[color:var(--color-content-default-tertiary,#b4b4b4)] text-[length:var(--sizing-300,12px)]">
{typeof textHint === "string" ? textHint : "Hint text here"}
{typeof textHint === "string" ? textHint : hintDefault}
</p>
</div>
)}
@@ -1,6 +1,7 @@
"use client";
import { memo, useCallback, useId, forwardRef } from "react";
import { useTranslation } from "../../../contexts/MessagesContext";
import { ToggleGroupView } from "./ToggleGroup.view";
import type { ToggleGroupProps } from "./ToggleGroup.types";
@@ -10,6 +11,7 @@ import type { ToggleGroupProps } from "./ToggleGroup.types";
*/
const ToggleGroupContainer = memo(
forwardRef<HTMLButtonElement, ToggleGroupProps>((props, _ref) => {
const t = useTranslation("controlsChrome");
const {
children,
className = "",
@@ -131,6 +133,7 @@ const ToggleGroupContainer = memo(
state={state}
showText={showText}
ariaLabel={ariaLabel}
defaultToggleOptionAriaLabel={t("toggleOption")}
toggleClasses={toggleClasses}
onClick={handleClick}
onKeyDown={handleKeyDown}
@@ -35,6 +35,7 @@ export interface ToggleGroupViewProps {
state: "default" | "hover" | "focus" | "selected";
showText: boolean;
ariaLabel?: string;
defaultToggleOptionAriaLabel: string;
toggleClasses: string;
onClick: (_e: React.MouseEvent<HTMLButtonElement>) => void;
onKeyDown: (_e: React.KeyboardEvent<HTMLButtonElement>) => void;
@@ -8,6 +8,7 @@ export function ToggleGroupView({
state: _state,
showText,
ariaLabel,
defaultToggleOptionAriaLabel,
toggleClasses,
onClick,
onKeyDown,
@@ -20,7 +21,7 @@ export function ToggleGroupView({
id={groupId}
type="button"
role="button"
aria-label={ariaLabel || (showText ? undefined : "Toggle option")}
aria-label={ariaLabel || (showText ? undefined : defaultToggleOptionAriaLabel)}
onClick={onClick}
onKeyDown={onKeyDown}
onFocus={onFocus}
@@ -1,6 +1,7 @@
"use client";
import { memo } from "react";
import { useTranslation } from "../../../contexts/MessagesContext";
import UploadView from "./Upload.view";
import type { UploadProps } from "./Upload.types";
@@ -13,16 +14,20 @@ const UploadContainer = memo<UploadProps>(
active = true,
label,
showHelpIcon = true,
hintText = "Add image from your device",
hintText,
onClick,
className = "",
}) => {
const t = useTranslation("controlsChrome");
return (
<UploadView
active={active}
label={label}
showHelpIcon={showHelpIcon}
hintText={hintText}
hintText={hintText ?? t("uploadHintDefault")}
uploadButtonLabel={t("uploadButton")}
uploadAriaLabel={t("uploadAriaLabel")}
onClick={onClick}
className={className}
/>
@@ -35,6 +35,8 @@ export interface UploadViewProps {
label?: string;
showHelpIcon: boolean;
hintText: string;
uploadButtonLabel: string;
uploadAriaLabel: string;
onClick?: () => void;
className: string;
}
@@ -9,6 +9,8 @@ function UploadView({
label,
showHelpIcon = true,
hintText,
uploadButtonLabel,
uploadAriaLabel,
onClick,
className = "",
}: UploadViewProps) {
@@ -56,7 +58,7 @@ function UploadView({
type="button"
onClick={onClick}
className={`${buttonBgClass} flex gap-[var(--measures-spacing-150,6px)] items-center justify-center overflow-clip px-[var(--space-400,16px)] py-[var(--measures-spacing-300,12px)] rounded-[var(--measures-radius-full,9999px)] shrink-0 hover:opacity-80 transition-opacity`}
aria-label="Upload"
aria-label={uploadAriaLabel}
>
{/* Upload icon */}
<div className={`relative shrink-0 size-[20px] ${iconColor}`}>
@@ -98,7 +100,7 @@ function UploadView({
<div
className={`flex flex-col font-inter font-medium justify-center leading-[0] relative shrink-0 text-[length:var(--sizing-400,16px)] whitespace-nowrap ${buttonTextColor}`}
>
<p className="leading-[20px]">Upload</p>
<p className="leading-[20px]">{uploadButtonLabel}</p>
</div>
</button>
@@ -1,18 +0,0 @@
"use client";
import { memo } from "react";
import LanguageSwitcherView from "./LanguageSwitcher.view";
import type { LanguageSwitcherProps } from "./LanguageSwitcher.types";
const LanguageSwitcherContainer = memo<LanguageSwitcherProps>(
({ className }) => {
// Future: Add language switching logic here
// For now, this is just a UI component
return <LanguageSwitcherView className={className} />;
},
);
LanguageSwitcherContainer.displayName = "LanguageSwitcher";
export default LanguageSwitcherContainer;
@@ -1,9 +0,0 @@
export interface LanguageSwitcherProps {
className?: string;
}
export interface Language {
code: string;
name: string;
nativeName: string;
}
@@ -1,42 +0,0 @@
"use client";
import { memo } from "react";
import { useTranslation } from "../../../contexts/MessagesContext";
import type { LanguageSwitcherProps, Language } from "./LanguageSwitcher.types";
function LanguageSwitcherView({ className = "" }: LanguageSwitcherProps) {
const t = useTranslation("languageSwitcher");
const AVAILABLE_LANGUAGES: Language[] = [
{
code: "en",
name: t("languages.english.name"),
nativeName: t("languages.english.nativeName"),
},
];
return (
<div className={className}>
<label htmlFor="language-select" className="sr-only">
{t("label")}
</label>
<select
id="language-select"
className="bg-[var(--color-surface-default-primary)] text-[var(--color-content-default-primary)] font-inter text-sm leading-5 font-normal border border-[var(--color-surface-default-secondary)] rounded-[var(--radius-measures-radius-small)] px-[var(--spacing-scale-012)] py-[var(--spacing-scale-008)] focus:outline-none focus:ring-2 focus:ring-[var(--color-surface-default-brand-royal)] focus:ring-offset-2 cursor-pointer"
aria-label={t("ariaLabel")}
disabled
>
{AVAILABLE_LANGUAGES.map((language) => (
<option key={language.code} value={language.code}>
{language.nativeName}
</option>
))}
</select>
<p className="text-[var(--color-content-default-secondary)] font-inter text-xs leading-4 font-normal mt-[var(--spacing-scale-008)]">
{t("comingSoonMessage")}
</p>
</div>
);
}
export default memo(LanguageSwitcherView);
@@ -1,2 +0,0 @@
export { default } from "./LanguageSwitcher.container";
export type { LanguageSwitcherProps, Language } from "./LanguageSwitcher.types";
@@ -6,6 +6,7 @@
*/
import { memo } from "react";
import { useTranslation } from "../../../contexts/MessagesContext";
import { AlertView } from "./Alert.view";
import type { AlertProps } from "./Alert.types";
@@ -74,6 +75,7 @@ const AlertContainer = memo<AlertProps>(
onClose,
className = "",
}) => {
const t = useTranslation("controlsChrome");
const status = statusProp;
const type = typeProp;
const size = sizeProp;
@@ -175,6 +177,7 @@ const AlertContainer = memo<AlertProps>(
iconColor={statusStyles.iconColor}
closeButtonIconColor={statusStyles.closeButtonIconColor}
onClose={onClose}
closeAlertAriaLabel={t("closeAlert")}
/>
);
},
@@ -57,4 +57,5 @@ export interface AlertViewProps {
iconColor: string;
closeButtonIconColor: string;
onClose?: () => void;
closeAlertAriaLabel: string;
}
+2 -1
View File
@@ -17,6 +17,7 @@ export function AlertView({
iconColor,
closeButtonIconColor,
onClose,
closeAlertAriaLabel,
}: AlertViewProps) {
const getIcon = () => {
// Use the Icon_Alert.svg with dynamic fill color
@@ -61,7 +62,7 @@ export function AlertView({
palette="default"
size="large"
onClick={onClose}
ariaLabel="Close alert"
ariaLabel={closeAlertAriaLabel}
className="shrink-0 [&_svg_path]:transition-colors [&_svg_path]:duration-200 hover:[&_svg_path]:fill-[var(--color-content-default-primary)]"
>
<svg
@@ -5,7 +5,7 @@
* File: agv0VBLiBlcnSAaiAORgPR, node 22078-587823
*/
import { memo, useCallback, useEffect, useState, type FormEvent } from "react";
import { memo, useCallback, useEffect, useMemo, useState, type FormEvent } from "react";
import { AskOrganizerInquiryModalView } from "./AskOrganizerInquiryModal.view";
import type { AskOrganizerInquiryModalProps } from "./AskOrganizerInquiryModal.types";
import { ORGANIZER_INQUIRY_HONEYPOT_FIELD } from "../../../../lib/organizerInquiryConstants";
@@ -14,6 +14,23 @@ import { useTranslation } from "../../../contexts/MessagesContext";
const AskOrganizerInquiryModalContainer = memo<AskOrganizerInquiryModalProps>(
({ isOpen, onClose }) => {
const t = useTranslation("modals.askOrganizerInquiry");
const copy = useMemo(
() => ({
title: t("title"),
description: t("description"),
emailLabel: t("emailLabel"),
emailPlaceholder: t("emailPlaceholder"),
questionLabel: t("questionLabel"),
questionPlaceholder: t("questionPlaceholder"),
submitButton: t("submitButton"),
closeAfterSuccess: t("closeAfterSuccess"),
successTitle: t("successTitle"),
successDescription: t("successDescription"),
ariaDialog: t("ariaDialog"),
honeypotLabel: t("honeypotLabel"),
}),
[t],
);
const [email, setEmail] = useState("");
const [message, setMessage] = useState("");
const [honeypot, setHoneypot] = useState("");
@@ -102,6 +119,7 @@ const AskOrganizerInquiryModalContainer = memo<AskOrganizerInquiryModalProps>(
<AskOrganizerInquiryModalView
isOpen={isOpen}
onClose={onClose}
copy={copy}
email={email}
message={message}
honeypot={honeypot}
@@ -2,3 +2,35 @@ export interface AskOrganizerInquiryModalProps {
isOpen: boolean;
onClose: () => void;
}
export interface AskOrganizerInquiryModalCopy {
title: string;
description: string;
emailLabel: string;
emailPlaceholder: string;
questionLabel: string;
questionPlaceholder: string;
submitButton: string;
closeAfterSuccess: string;
successTitle: string;
successDescription: string;
ariaDialog: string;
honeypotLabel: string;
}
export interface AskOrganizerInquiryModalViewProps
extends AskOrganizerInquiryModalProps {
copy: AskOrganizerInquiryModalCopy;
email: string;
message: string;
honeypot: string;
submitting: boolean;
success: boolean;
formError: string | null;
emailError: boolean;
questionError: boolean;
onEmailChange: (_v: string) => void;
onMessageChange: (_v: string) => void;
onHoneypotChange: (_v: string) => void;
onSubmit: (_e: import("react").FormEvent<HTMLFormElement>) => void;
}
@@ -1,31 +1,14 @@
"use client";
import type { FormEvent } from "react";
import Create from "../Create";
import TextInput from "../../controls/TextInput";
import TextArea from "../../controls/TextArea";
import Button from "../../buttons/Button";
import { useTranslation } from "../../../contexts/MessagesContext";
import {
ASK_ORGANIZER_INQUIRY_FORM_ID,
ORGANIZER_INQUIRY_HONEYPOT_FIELD,
} from "../../../../lib/organizerInquiryConstants";
import type { AskOrganizerInquiryModalProps } from "./AskOrganizerInquiryModal.types";
export type AskOrganizerInquiryModalViewProps = AskOrganizerInquiryModalProps & {
email: string;
message: string;
honeypot: string;
submitting: boolean;
success: boolean;
formError: string | null;
emailError: boolean;
questionError: boolean;
onEmailChange: (_v: string) => void;
onMessageChange: (_v: string) => void;
onHoneypotChange: (_v: string) => void;
onSubmit: (_e: FormEvent<HTMLFormElement>) => void;
};
import type { AskOrganizerInquiryModalViewProps } from "./AskOrganizerInquiryModal.types";
/**
* Figma: Community Rule System Modal / Ask an Organizer (22078-587823)
@@ -33,6 +16,7 @@ export type AskOrganizerInquiryModalViewProps = AskOrganizerInquiryModalProps &
export function AskOrganizerInquiryModalView({
isOpen,
onClose,
copy,
email,
message,
honeypot,
@@ -46,8 +30,6 @@ export function AskOrganizerInquiryModalView({
onHoneypotChange,
onSubmit,
}: AskOrganizerInquiryModalViewProps) {
const t = useTranslation("modals.askOrganizerInquiry");
const footer = success ? (
<div className="w-full px-1">
<Button
@@ -58,7 +40,7 @@ export function AskOrganizerInquiryModalView({
className="w-full !justify-center"
onClick={onClose}
>
{t("closeAfterSuccess")}
{copy.closeAfterSuccess}
</Button>
</div>
) : (
@@ -72,7 +54,7 @@ export function AskOrganizerInquiryModalView({
className="w-full !justify-center"
disabled={submitting}
>
{t("submitButton")}
{copy.submitButton}
</Button>
</div>
);
@@ -82,22 +64,22 @@ export function AskOrganizerInquiryModalView({
isOpen={isOpen}
onClose={onClose}
backdropVariant="blurredYellow"
title={t("title")}
description={t("description")}
title={copy.title}
description={copy.description}
showBackButton={false}
showNextButton={false}
stepper={false}
ariaLabel={t("ariaDialog")}
ariaLabel={copy.ariaDialog}
footerContent={footer}
footerClassName="!h-auto min-h-[112px] shrink-0 flex flex-col justify-end pb-8 pt-3 px-4"
>
{success ? (
<div className="flex flex-col gap-3 py-2">
<p className="font-inter text-[18px] font-semibold leading-[24px] text-[var(--color-content-default-primary)]">
{t("successTitle")}
{copy.successTitle}
</p>
<p className="font-inter text-[14px] leading-[20px] text-[var(--color-content-default-secondary)]">
{t("successDescription")}
{copy.successDescription}
</p>
</div>
) : (
@@ -120,8 +102,8 @@ export function AskOrganizerInquiryModalView({
type="email"
name="email"
autoComplete="email"
label={t("emailLabel")}
placeholder={t("emailPlaceholder")}
label={copy.emailLabel}
placeholder={copy.emailPlaceholder}
value={email}
onChange={(e) => onEmailChange(e.target.value)}
error={emailError}
@@ -131,8 +113,8 @@ export function AskOrganizerInquiryModalView({
<TextArea
name="message"
label={t("questionLabel")}
placeholder={t("questionPlaceholder")}
label={copy.questionLabel}
placeholder={copy.questionPlaceholder}
value={message}
onChange={(e) => onMessageChange(e.target.value)}
error={questionError}
@@ -146,7 +128,7 @@ export function AskOrganizerInquiryModalView({
className="pointer-events-none absolute left-0 top-0 h-px w-px overflow-hidden opacity-0"
>
<label htmlFor={`${ASK_ORGANIZER_INQUIRY_FORM_ID}-${ORGANIZER_INQUIRY_HONEYPOT_FIELD}`}>
{t("honeypotLabel")}
{copy.honeypotLabel}
</label>
<input
id={`${ASK_ORGANIZER_INQUIRY_FORM_ID}-${ORGANIZER_INQUIRY_HONEYPOT_FIELD}`}
@@ -1,5 +1,9 @@
"use client";
/**
* Figma: "Modal / Create" (20874-172292)
*/
import { memo, useRef } from "react";
import { CreateView } from "./Create.view";
import type { CreateProps } from "./Create.types";
@@ -1,5 +1,9 @@
"use client";
/**
* Figma: "Dialog" (see registry)
*/
import { memo, useId, useRef } from "react";
import { useCreateModalA11y } from "../Create/useCreateModalA11y";
import { DialogView } from "./Dialog.view";
@@ -1,5 +1,9 @@
"use client";
/**
* Figma: "Modal / Login" (see registry)
*/
import { memo, useEffect, useLayoutEffect, useRef, useState } from "react";
import { LoginView } from "./Login.view";
import type { LoginProps } from "./Login.types";
+2 -2
View File
@@ -262,14 +262,14 @@ export default function LoginForm({
<p className="text-center font-inter text-[14px] leading-[20px] text-[var(--color-content-default-tertiary)]">
{t("legalPrefix")}
<Link
href="#"
href={tFooter("legal.termsOfServiceHref")}
className="text-[var(--color-content-default-tertiary)] underline decoration-solid underline-offset-2"
>
{tFooter("legal.termsOfService")}
</Link>
{t("legalAnd")}
<Link
href="#"
href={tFooter("legal.privacyPolicyHref")}
className="text-[var(--color-content-default-tertiary)] underline decoration-solid underline-offset-2"
>
{tFooter("legal.privacyPolicy")}
@@ -1,6 +1,7 @@
"use client";
import { memo } from "react";
import { useTranslation } from "../../../contexts/MessagesContext";
import { ModalFooterView } from "./ModalFooter.view";
import type { ModalFooterProps } from "./ModalFooter.types";
@@ -10,7 +11,17 @@ import type { ModalFooterProps } from "./ModalFooter.types";
* primary/secondary actions.
*/
const ModalFooterContainer = memo<ModalFooterProps>((props) => {
return <ModalFooterView {...props} />;
const t = useTranslation("common");
const resolvedBackText = props.backButtonText ?? t("buttons.back");
const resolvedNextText = props.nextButtonText ?? t("buttons.next");
return (
<ModalFooterView
{...props}
backButtonText={resolvedBackText}
nextButtonText={resolvedNextText}
/>
);
});
ModalFooterContainer.displayName = "ModalFooter";
@@ -1,6 +1,5 @@
"use client";
import { useTranslation } from "../../../contexts/MessagesContext";
import Button from "../../buttons/Button";
import Stepper from "../../progress/Stepper";
import type { ModalFooterProps } from "./ModalFooter.types";
@@ -19,14 +18,6 @@ export function ModalFooterView({
footerContent,
className = "",
}: ModalFooterProps) {
const t = useTranslation("common");
// Use localized defaults if text not provided
const defaultBackText = backButtonText || t("buttons.back");
const defaultNextText = nextButtonText || t("buttons.next");
// Determine if stepper should be shown
// Defaults to true if currentStep and totalSteps are provided, unless explicitly set to false
const shouldShowStepper =
stepperProp !== undefined
? stepperProp
@@ -36,7 +27,6 @@ export function ModalFooterView({
<div
className={`h-[64px] bg-[var(--color-surface-default-primary)] rounded-bl-[var(--radius-300,12px)] rounded-br-[var(--radius-300,12px)] shrink-0 relative ${className}`}
>
{/* Back Button - Absolutely positioned bottom left */}
{showBackButton && (
<div className="absolute left-[16px] top-[12px]">
<Button
@@ -45,19 +35,17 @@ export function ModalFooterView({
size="medium"
onClick={onBack}
>
{defaultBackText}
{backButtonText}
</Button>
</div>
)}
{/* Stepper (Centered) */}
{shouldShowStepper && currentStep && totalSteps && (
<div className="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2">
<Stepper active={currentStep} totalSteps={totalSteps} />
</div>
)}
{/* Next Button - Absolutely positioned bottom right */}
{showNextButton && (
<div className="absolute right-[16px] top-[12px]">
<Button
@@ -67,12 +55,11 @@ export function ModalFooterView({
onClick={onNext}
disabled={nextButtonDisabled}
>
{defaultNextText}
{nextButtonText}
</Button>
</div>
)}
{/* Custom Footer Content */}
{footerContent}
</div>
);
@@ -1,6 +1,7 @@
"use client";
import { memo, useEffect, useId, useRef, useState } from "react";
import { useTranslation } from "../../../contexts/MessagesContext";
import { ModalHeaderView } from "./ModalHeader.view";
import type { ModalHeaderProps } from "./ModalHeader.types";
@@ -10,7 +11,14 @@ import type { ModalHeaderProps } from "./ModalHeader.types";
* (right) icon buttons.
*/
const ModalHeaderContainer = memo<ModalHeaderProps>((props) => {
const { menuItems = [] } = props;
const t = useTranslation("controlsChrome");
const {
closeButtonAriaLabel = t("closeDialog"),
moreOptionsAriaLabel = t("moreOptions"),
menuAriaLabel = t("moreOptionsMenu"),
menuItems = [],
...rest
} = props;
const hasMenu = menuItems.length > 0;
const [menuOpen, setMenuOpen] = useState(false);
const menuId = useId();
@@ -44,7 +52,11 @@ const ModalHeaderContainer = memo<ModalHeaderProps>((props) => {
return (
<div ref={menuWrapRef}>
<ModalHeaderView
{...props}
{...rest}
menuItems={menuItems}
closeButtonAriaLabel={closeButtonAriaLabel}
moreOptionsAriaLabel={moreOptionsAriaLabel}
menuAriaLabel={menuAriaLabel}
menuId={menuId}
menuOpen={menuOpen}
onToggleMenu={hasMenu ? () => setMenuOpen((open) => !open) : undefined}
@@ -1,6 +1,6 @@
import ListItem from "../../layout/ListItem";
import Popover from "../Popover";
import { getAssetPath } from "../../../../lib/assetUtils";
import { ASSETS, getAssetPath } from "../../../../lib/assetUtils";
import type { ModalHeaderProps } from "./ModalHeader.types";
const iconButtonClass =
@@ -11,9 +11,9 @@ export function ModalHeaderView({
onMoreOptions,
showCloseButton = true,
showMoreOptionsButton = true,
closeButtonAriaLabel = "Close dialog",
moreOptionsAriaLabel = "More options",
menuAriaLabel = "More options menu",
closeButtonAriaLabel,
moreOptionsAriaLabel,
menuAriaLabel,
menuItems = [],
menuId,
menuOpen = false,
@@ -37,7 +37,7 @@ export function ModalHeaderView({
>
{/* eslint-disable-next-line @next/next/no-img-element -- icon asset */}
<img
src={getAssetPath("assets/Icon_Close.svg")}
src={getAssetPath(ASSETS.ICON_CLOSE)}
alt=""
className="w-[16px] h-[16px]"
style={{
+14 -14
View File
@@ -2,6 +2,11 @@
import Image from "next/image";
import { memo } from "react";
import {
getAssetPath,
shareIconPath,
type ShareIconName,
} from "../../../../lib/assetUtils";
import ContentLockup from "../../type/ContentLockup";
import Button from "../../buttons/Button";
import ModalHeader from "../ModalHeader";
@@ -9,21 +14,16 @@ import ModalFooter from "../ModalFooter";
import { CreateModalFrameView } from "../Create/CreateModalFrame.view";
import type { ShareChannelTileProps, ShareViewProps } from "./Share.types";
/** Decorative glyphs in `public/assets/Share/` — sizes match prior inline SVGs within the 60×60 circles. */
/** Decorative glyphs in `public/assets/share/` — sizes match prior inline SVGs within the 60×60 circles. */
function ShareAssetIcon(props: {
src:
| "/assets/Share/Discord.svg"
| "/assets/Share/Link.svg"
| "/assets/Share/Mail.svg"
| "/assets/Share/Signal.svg"
| "/assets/Share/Slack.svg";
name: ShareIconName;
width: number;
height: number;
}) {
const { src, width, height } = props;
const { name, width, height } = props;
return (
<Image
src={src}
src={getAssetPath(shareIconPath(name))}
alt=""
width={width}
height={height}
@@ -111,31 +111,31 @@ export const ShareView = memo(function ShareView({
label={copyLinkLabel}
onClick={onCopyLink}
circleClassName="border-[#444444] bg-[#333333]"
icon={<ShareAssetIcon src="/assets/Share/Link.svg" width={24} height={24} />}
icon={<ShareAssetIcon name="link" width={24} height={24} />}
/>
<ShareChannelTile
label={signalLabel}
onClick={onSignalShare}
circleClassName="border-[#3a76f0] bg-[#3a76f0]"
icon={<ShareAssetIcon src="/assets/Share/Signal.svg" width={26} height={26} />}
icon={<ShareAssetIcon name="signal" width={26} height={26} />}
/>
<ShareChannelTile
label={slackLabel}
onClick={onSlackShare}
circleClassName="border-[#4a154b] bg-[#4a154b]"
icon={<ShareAssetIcon src="/assets/Share/Slack.svg" width={26} height={26} />}
icon={<ShareAssetIcon name="slack" width={26} height={26} />}
/>
<ShareChannelTile
label={discordLabel}
onClick={onDiscordShare}
circleClassName="border-[#5865f2] bg-[#5865f2]"
icon={<ShareAssetIcon src="/assets/Share/Discord.svg" width={30} height={30} />}
icon={<ShareAssetIcon name="discord" width={30} height={30} />}
/>
<ShareChannelTile
label={emailLabel}
onClick={onEmailShare}
circleClassName="border-[var(--color-surface-default-brand-kiwi)] bg-[var(--color-surface-default-brand-kiwi)]"
icon={<ShareAssetIcon src="/assets/Share/Mail.svg" width={24} height={24} />}
icon={<ShareAssetIcon name="mail" width={24} height={24} />}
/>
</div>
</div>

Some files were not shown because too many files have changed in this diff Show More