Skip setup questions on the template path and collect name, photo, and description without recommendations.
Customize opens a dialog then walks the template decks; Use without changes lands on final review with Has Name Field. Template cards stay first, the engine is not called, and the catalog no longer shows a recommended tag.
This commit is contained in:
1 parent
53d236d0d5
commit
6498d52541
37 files changed
+1450
-733
No files matched your search
@@ -15,6 +15,7 @@ import { useCreateFlowExit } from "./hooks/useCreateFlowExit";
|
||||
import { usePrefetchMethodFacetRecommendations } from "./hooks/usePrefetchMethodFacetRecommendations";
|
||||
import { useCreateFlowFinalize } from "./hooks/useCreateFlowFinalize";
|
||||
import { useTemplateReviewActions } from "./hooks/useTemplateReviewActions";
|
||||
import { TemplateCustomizeDialog } from "./components/TemplateCustomizeDialog";
|
||||
import { useCompletedRuleShareExport } from "./hooks/useCompletedRuleShareExport";
|
||||
import CreateFlowFooter from "../../components/navigation/CreateFlowFooter";
|
||||
import CreateFlowTopNav from "../../components/navigation/CreateFlowTopNav";
|
||||
@@ -323,6 +324,9 @@ function CreateFlowLayoutContent({
|
||||
setTemplateReviewApplyError,
|
||||
handleCustomize: handleCustomizeTemplate,
|
||||
handleUseWithoutChanges: handleUseTemplateWithoutChanges,
|
||||
customizeDialog,
|
||||
closeCustomizeDialog,
|
||||
confirmCustomizeDialog,
|
||||
} = useTemplateReviewActions({
|
||||
pathname,
|
||||
state,
|
||||
@@ -876,6 +880,25 @@ function CreateFlowLayoutContent({
|
||||
backdropVariant="blurredYellow"
|
||||
ariaLabel={messages.create.topNav.leaveConfirmTitle}
|
||||
/>
|
||||
<TemplateCustomizeDialog
|
||||
isOpen={customizeDialog !== null}
|
||||
templateTitle={customizeDialog?.templateTitle ?? ""}
|
||||
valuesCount={customizeDialog?.valuesCount ?? 0}
|
||||
cardsCount={customizeDialog?.cardsCount ?? 0}
|
||||
initialTitle={typeof state.title === "string" ? state.title : ""}
|
||||
initialDescription={
|
||||
typeof state.communityContext === "string"
|
||||
? state.communityContext
|
||||
: ""
|
||||
}
|
||||
initialLocation={
|
||||
typeof state.communityLocation === "string"
|
||||
? state.communityLocation
|
||||
: ""
|
||||
}
|
||||
onClose={closeCustomizeDialog}
|
||||
onContinue={confirmCustomizeDialog}
|
||||
/>
|
||||
<CreateFlowTopNav
|
||||
hasShare={isCompletedStep}
|
||||
hasExport={isCompletedStep}
|
||||
|
||||
@@ -0,0 +1,256 @@
|
||||
"use client";
|
||||
|
||||
/**
|
||||
* Figma: "Modal / Customize (template)" (24991:40503).
|
||||
* Name, optional logo, description, and optional location before the
|
||||
* template decks.
|
||||
*/
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import Button from "../../../components/buttons/Button";
|
||||
import Icon from "../../../components/asset/icon";
|
||||
import TextInput from "../../../components/controls/TextInput";
|
||||
import TextArea from "../../../components/controls/TextArea";
|
||||
import Create from "../../../components/modals/Create";
|
||||
import HeaderLockup from "../../../components/type/HeaderLockup";
|
||||
import InputLabel from "../../../components/type/InputLabel";
|
||||
import { useMessages, useTranslation } from "../../../contexts/MessagesContext";
|
||||
import { COMMUNITY_TITLE_FIELD_MAX_LENGTH } from "./FinalReviewTitleEditModal";
|
||||
import { COMMUNITY_CONTEXT_FIELD_MAX_LENGTH } from "./FinalReviewCommunityContextEditModal";
|
||||
import { useCommunityAvatarUpload } from "../hooks/useCommunityAvatarUpload";
|
||||
import type { TemplateCustomizeFields } from "../hooks/useTemplateReviewActions";
|
||||
|
||||
const COMMUNITY_LOCATION_MAX_LENGTH = 200;
|
||||
|
||||
const COUNT_WORD_KEYS = [
|
||||
"1",
|
||||
"2",
|
||||
"3",
|
||||
"4",
|
||||
"5",
|
||||
"6",
|
||||
"7",
|
||||
"8",
|
||||
"9",
|
||||
"10",
|
||||
"11",
|
||||
"12",
|
||||
"13",
|
||||
"14",
|
||||
"15",
|
||||
"16",
|
||||
"17",
|
||||
"18",
|
||||
"19",
|
||||
"20",
|
||||
] as const;
|
||||
|
||||
function countWord(
|
||||
count: number,
|
||||
words: Record<string, string>,
|
||||
): string {
|
||||
const key = String(count);
|
||||
if ((COUNT_WORD_KEYS as readonly string[]).includes(key)) {
|
||||
const word = words[key];
|
||||
if (typeof word === "string" && word.length > 0) return word;
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
function countPhrase(
|
||||
count: number,
|
||||
one: string,
|
||||
many: string,
|
||||
words: Record<string, string>,
|
||||
): string {
|
||||
if (count === 1) return one;
|
||||
return many.replace("{word}", countWord(count, words));
|
||||
}
|
||||
|
||||
export function TemplateCustomizeDialog({
|
||||
isOpen,
|
||||
templateTitle,
|
||||
valuesCount,
|
||||
cardsCount,
|
||||
initialTitle,
|
||||
initialDescription,
|
||||
initialLocation,
|
||||
onClose,
|
||||
onContinue,
|
||||
}: {
|
||||
isOpen: boolean;
|
||||
templateTitle: string;
|
||||
valuesCount: number;
|
||||
cardsCount: number;
|
||||
initialTitle: string;
|
||||
initialDescription: string;
|
||||
initialLocation: string;
|
||||
onClose: () => void;
|
||||
onContinue: (_fields: TemplateCustomizeFields) => void;
|
||||
}) {
|
||||
const copy = useMessages().create.templateCustomize;
|
||||
const tName = useTranslation("create.community.communityName");
|
||||
const tContext = useTranslation("create.community.communityContext");
|
||||
const avatar = useCommunityAvatarUpload();
|
||||
|
||||
const [title, setTitle] = useState(initialTitle);
|
||||
const [description, setDescription] = useState(initialDescription);
|
||||
const [location, setLocation] = useState(initialLocation);
|
||||
const [attempted, setAttempted] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isOpen) {
|
||||
setAttempted(false);
|
||||
return;
|
||||
}
|
||||
setTitle(initialTitle);
|
||||
setDescription(initialDescription);
|
||||
setLocation(initialLocation);
|
||||
}, [isOpen, initialTitle, initialDescription, initialLocation]);
|
||||
|
||||
const words = copy.countWords;
|
||||
const valuesPhrase = countPhrase(
|
||||
valuesCount,
|
||||
copy.valuesOne,
|
||||
copy.valuesMany,
|
||||
words,
|
||||
);
|
||||
const cardsPhrase = countPhrase(
|
||||
cardsCount,
|
||||
copy.cardsOne,
|
||||
copy.cardsMany,
|
||||
words,
|
||||
);
|
||||
const heading = copy.title.replace("{template}", templateTitle);
|
||||
const lockupDescription = copy.description
|
||||
.replaceAll("{template}", templateTitle)
|
||||
.replace("{valuesPhrase}", valuesPhrase)
|
||||
.replace("{cardsPhrase}", cardsPhrase);
|
||||
|
||||
const trimmedTitle = title.trim();
|
||||
const nameError = attempted && trimmedTitle.length === 0;
|
||||
const canContinue = trimmedTitle.length > 0 && !avatar.busy;
|
||||
|
||||
const nameHint = nameError ? copy.nameRequired : copy.nameHint;
|
||||
|
||||
const handleContinue = () => {
|
||||
setAttempted(true);
|
||||
if (!canContinue) return;
|
||||
onContinue({
|
||||
title: trimmedTitle,
|
||||
communityContext: description.trim(),
|
||||
communityLocation: location.trim(),
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<Create
|
||||
isOpen={isOpen}
|
||||
onClose={onClose}
|
||||
backdropVariant="default"
|
||||
ariaLabel={heading}
|
||||
headerContent={
|
||||
<div className="px-[24px] pt-[8px]">
|
||||
<HeaderLockup
|
||||
title={heading}
|
||||
description={lockupDescription}
|
||||
justification="left"
|
||||
size="M"
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
showBackButton={false}
|
||||
showCancelButton
|
||||
showNextButton
|
||||
cancelButtonText={copy.cancel}
|
||||
nextButtonText={copy.continue}
|
||||
nextButtonDisabled={!canContinue}
|
||||
onCancel={onClose}
|
||||
onNext={handleContinue}
|
||||
>
|
||||
<div className="flex flex-col gap-[16px]">
|
||||
<TextInput
|
||||
className="!transition-none"
|
||||
type="text"
|
||||
label={tName("title")}
|
||||
placeholder={tName("placeholder")}
|
||||
value={title}
|
||||
onChange={(event) => setTitle(event.target.value)}
|
||||
inputSize="medium"
|
||||
formHeader
|
||||
showHelpIcon={false}
|
||||
textHint={nameHint}
|
||||
error={nameError}
|
||||
maxLength={COMMUNITY_TITLE_FIELD_MAX_LENGTH}
|
||||
required
|
||||
autoFocus
|
||||
/>
|
||||
<div className="flex flex-col gap-[8px]">
|
||||
<InputLabel
|
||||
label={copy.logoLabel}
|
||||
helpIcon={false}
|
||||
size="s"
|
||||
palette="default"
|
||||
/>
|
||||
<div className="flex items-center gap-[12px]">
|
||||
<input
|
||||
ref={avatar.fileInputRef}
|
||||
type="file"
|
||||
className="sr-only"
|
||||
tabIndex={-1}
|
||||
accept={avatar.accept}
|
||||
aria-label={copy.upload}
|
||||
onChange={(event) => void avatar.handleFileChange(event)}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
buttonType="outline"
|
||||
palette="default"
|
||||
size="xsmall"
|
||||
hasIconLeading
|
||||
disabled={avatar.busy}
|
||||
onClick={avatar.handlePickFile}
|
||||
>
|
||||
<Icon name="image" size={14} />
|
||||
{copy.upload}
|
||||
</Button>
|
||||
<p className="min-w-0 flex-1 text-x-small-label text-[color:var(--color-content-default-secondary)]">
|
||||
{avatar.errorMessage ??
|
||||
(avatar.fileName && avatar.displaySrc
|
||||
? avatar.fileName
|
||||
: copy.logoHint)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<TextArea
|
||||
className="!transition-none"
|
||||
label={tContext("title")}
|
||||
placeholder={copy.descriptionPlaceholder}
|
||||
value={description}
|
||||
onChange={(event) => setDescription(event.target.value)}
|
||||
size="medium"
|
||||
formHeader
|
||||
showHelpIcon={false}
|
||||
maxLength={COMMUNITY_CONTEXT_FIELD_MAX_LENGTH}
|
||||
rows={2}
|
||||
/>
|
||||
<TextInput
|
||||
className="!transition-none"
|
||||
type="text"
|
||||
label={tContext("locationLabel")}
|
||||
placeholder={tContext("locationPlaceholder")}
|
||||
value={location}
|
||||
onChange={(event) => setLocation(event.target.value)}
|
||||
inputSize="medium"
|
||||
formHeader
|
||||
showHelpIcon={false}
|
||||
textHint={tContext("locationHint")}
|
||||
maxLength={COMMUNITY_LOCATION_MAX_LENGTH}
|
||||
/>
|
||||
<p className="text-small-paragraph text-[color:var(--color-content-default-tertiary)]">
|
||||
{copy.privacyNote}
|
||||
</p>
|
||||
</div>
|
||||
</Create>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
useCallback,
|
||||
useEffect,
|
||||
useRef,
|
||||
useState,
|
||||
type ChangeEvent,
|
||||
type RefObject,
|
||||
} from "react";
|
||||
import { fetchAuthSession } from "../../../../lib/create/api";
|
||||
import {
|
||||
COMMUNITY_AVATAR_ACCEPT,
|
||||
messageKeyForCreateFlowUploadReason,
|
||||
validateCreateFlowUploadFile,
|
||||
} from "../../../../lib/create/createFlowUploadValidation";
|
||||
import {
|
||||
clearPendingCommunityAvatarFile,
|
||||
storePendingCommunityAvatarFile,
|
||||
} from "../../../../lib/create/pendingCommunityAvatarUpload";
|
||||
import {
|
||||
createFlowUploadFailureMessageKey,
|
||||
uploadCreateFlowFile,
|
||||
} from "../../../../lib/create/uploadToServer";
|
||||
import { useMessages, useTranslation } from "../../../contexts/MessagesContext";
|
||||
import { useCreateFlow } from "../context/CreateFlowContext";
|
||||
|
||||
function hasCommunityAvatarUrl(url: string | undefined): boolean {
|
||||
return typeof url === "string" && url.trim().length > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pick and store a community logo for the create flow. Signed-in users upload
|
||||
* immediately; guests keep the file in IndexedDB until they sign in.
|
||||
*
|
||||
* @example
|
||||
* const avatar = useCommunityAvatarUpload();
|
||||
* <input ref={avatar.fileInputRef} type="file" onChange={avatar.handleFileChange} />
|
||||
*/
|
||||
export function useCommunityAvatarUpload(): {
|
||||
fileInputRef: RefObject<HTMLInputElement | null>;
|
||||
accept: string;
|
||||
busy: boolean;
|
||||
errorMessage: string | null;
|
||||
displaySrc: string | null;
|
||||
fileName: string | undefined;
|
||||
handlePickFile: () => void;
|
||||
handleFileChange: (_event: ChangeEvent<HTMLInputElement>) => Promise<void>;
|
||||
} {
|
||||
const m = useMessages();
|
||||
const u = m.create.community.communityUpload;
|
||||
const tUpload = useTranslation("create.upload");
|
||||
const { markCreateFlowInteraction, state, updateState } = useCreateFlow();
|
||||
const fileInputRef = useRef<HTMLInputElement | null>(null);
|
||||
const [signedIn, setSignedIn] = useState<boolean | null>(null);
|
||||
const [localPreviewUrl, setLocalPreviewUrl] = useState<string | null>(null);
|
||||
const [localFileName, setLocalFileName] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
void fetchAuthSession().then(({ user }) => {
|
||||
if (!cancelled) setSignedIn(Boolean(user));
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (localPreviewUrl) URL.revokeObjectURL(localPreviewUrl);
|
||||
},
|
||||
[localPreviewUrl],
|
||||
);
|
||||
|
||||
const serverAvatarUrl = hasCommunityAvatarUrl(state.communityAvatarUrl)
|
||||
? state.communityAvatarUrl!.trim()
|
||||
: null;
|
||||
|
||||
useEffect(() => {
|
||||
if (serverAvatarUrl) {
|
||||
setLocalPreviewUrl((prev) => {
|
||||
if (prev) URL.revokeObjectURL(prev);
|
||||
return null;
|
||||
});
|
||||
}
|
||||
}, [serverAvatarUrl]);
|
||||
|
||||
const resolveUploadError = useCallback(
|
||||
(err: unknown) => {
|
||||
const key = createFlowUploadFailureMessageKey(err);
|
||||
if (key === "errors.tooLarge") return u.fileTooLarge;
|
||||
return tUpload(key);
|
||||
},
|
||||
[tUpload, u.fileTooLarge],
|
||||
);
|
||||
|
||||
const handleFileChange = useCallback(
|
||||
async (e: ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
e.target.value = "";
|
||||
if (!file) return;
|
||||
markCreateFlowInteraction();
|
||||
setErrorMessage(null);
|
||||
|
||||
if (signedIn === true) {
|
||||
setBusy(true);
|
||||
try {
|
||||
const { url } = await uploadCreateFlowFile(file, "communityAvatar");
|
||||
setLocalPreviewUrl((prev) => {
|
||||
if (prev) URL.revokeObjectURL(prev);
|
||||
return null;
|
||||
});
|
||||
setLocalFileName(file.name);
|
||||
updateState({
|
||||
communityAvatarUrl: url,
|
||||
communityAvatarFileName: file.name,
|
||||
});
|
||||
} catch (err) {
|
||||
setErrorMessage(resolveUploadError(err));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const validated = await validateCreateFlowUploadFile(
|
||||
file,
|
||||
"communityAvatar",
|
||||
);
|
||||
if (validated.ok === false) {
|
||||
setErrorMessage(
|
||||
validated.reason === "tooLarge"
|
||||
? u.fileTooLarge
|
||||
: tUpload(messageKeyForCreateFlowUploadReason(validated.reason)),
|
||||
);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await storePendingCommunityAvatarFile(file);
|
||||
setLocalPreviewUrl((prev) => {
|
||||
if (prev) URL.revokeObjectURL(prev);
|
||||
return URL.createObjectURL(file);
|
||||
});
|
||||
setLocalFileName(file.name);
|
||||
updateState({ communityAvatarFileName: file.name });
|
||||
} catch {
|
||||
await clearPendingCommunityAvatarFile().catch(() => undefined);
|
||||
setErrorMessage(tUpload("errors.generic"));
|
||||
}
|
||||
},
|
||||
[
|
||||
markCreateFlowInteraction,
|
||||
resolveUploadError,
|
||||
signedIn,
|
||||
tUpload,
|
||||
u.fileTooLarge,
|
||||
updateState,
|
||||
],
|
||||
);
|
||||
|
||||
const handlePickFile = useCallback(() => {
|
||||
if (!busy) fileInputRef.current?.click();
|
||||
}, [busy]);
|
||||
|
||||
const displaySrc = serverAvatarUrl ?? localPreviewUrl;
|
||||
const fileName =
|
||||
localFileName ??
|
||||
(typeof state.communityAvatarFileName === "string" &&
|
||||
state.communityAvatarFileName.trim().length > 0
|
||||
? state.communityAvatarFileName.trim()
|
||||
: undefined);
|
||||
|
||||
return {
|
||||
fileInputRef,
|
||||
accept: COMMUNITY_AVATAR_ACCEPT,
|
||||
busy,
|
||||
errorMessage,
|
||||
displaySrc,
|
||||
fileName,
|
||||
handlePickFile,
|
||||
handleFileChange,
|
||||
};
|
||||
}
|
||||
@@ -34,12 +34,10 @@ const blurActiveElement = (): void => {
|
||||
*
|
||||
* Resolves the active step from `/create/{screenId}` via
|
||||
* {@link parseCreateFlowScreenFromPathname} (flowSteps). Footer Back uses
|
||||
* {@link resolveCreateFlowBackTarget}: template **Use without changes** that
|
||||
* still needs identity (direct from a template) walks name / description /
|
||||
* photo, then Back from `community-name` returns to
|
||||
* `/create/review-template/{slug}`. In-flow picks (`?fromFlow=1`) skip
|
||||
* identity and land on `final-review`; Back from that step returns
|
||||
* to the template instead of `conflict-management`.
|
||||
* {@link resolveCreateFlowBackTarget}: template **Customize** walks values
|
||||
* then the four decks, and Back from `core-values` returns to
|
||||
* `/create/review-template/{slug}`. **Use without changes** lands on
|
||||
* `final-review`; Back from that step returns to the template.
|
||||
*
|
||||
* Template review footer Back uses {@link buildTemplateReviewHref}’s
|
||||
* `?fromFlow=1` marker (and persisted `templateReviewEntryFromCreateFlow`) so
|
||||
@@ -87,14 +85,13 @@ export function useCreateFlowNavigation(
|
||||
updateState,
|
||||
]);
|
||||
|
||||
const identityOnly =
|
||||
state.pendingTemplateAction?.mode === "useWithoutChanges";
|
||||
const templatePathMode = state.pendingTemplateAction?.mode;
|
||||
const navigationOptions = useMemo(
|
||||
(): CreateFlowNavigationOptions => ({
|
||||
skipCommunitySave: options?.skipCommunitySave,
|
||||
useWithoutChangesIdentityOnly: identityOnly,
|
||||
templatePathMode,
|
||||
}),
|
||||
[options?.skipCommunitySave, identityOnly],
|
||||
[options?.skipCommunitySave, templatePathMode],
|
||||
);
|
||||
|
||||
const nextStep = getNextStep(validStep, navigationOptions);
|
||||
|
||||
@@ -8,7 +8,11 @@ import {
|
||||
groupAnswersForRecommendations,
|
||||
type RecommendationSection,
|
||||
} from "./useFacetRecommendations";
|
||||
import { deckData } from "../../../../lib/create/deckRecommend";
|
||||
import { deckData, templateDeck } from "../../../../lib/create/deckRecommend";
|
||||
import {
|
||||
templateCardIdsForDeck,
|
||||
templatePathFromState,
|
||||
} from "../../../../lib/create/templatePath";
|
||||
import { useCreateFlow } from "../context/CreateFlowContext";
|
||||
import { useMessages } from "../../../contexts/MessagesContext";
|
||||
|
||||
@@ -30,6 +34,8 @@ function orderByIds<T extends { id: string }>(
|
||||
/**
|
||||
* Deck order and the compact stack come from the job rule. Compact shows
|
||||
* at most seven recommended cards. Selected cards still pin into the stack.
|
||||
* On the template path the engine is not called: template cards first, then
|
||||
* the rest of the deck, with no tag and no seven-card cut.
|
||||
*/
|
||||
export function useMethodCardDeckOrdering(
|
||||
section: RecommendationSection,
|
||||
@@ -38,15 +44,32 @@ export function useMethodCardDeckOrdering(
|
||||
) {
|
||||
const { state } = useCreateFlow();
|
||||
const copy = useMessages().create.customRule.recommendations;
|
||||
const compactLimit = deckData(section).config.displayLimit;
|
||||
const templateSlug = templatePathFromState(state)?.slug;
|
||||
const engineCompactLimit = deckData(section).config.displayLimit;
|
||||
const answers = useMemo(
|
||||
() => groupAnswersForRecommendations(state),
|
||||
[state],
|
||||
);
|
||||
const deck = useMemo(
|
||||
() => deriveCompactCards(section, answers, compactLimit),
|
||||
[section, answers, compactLimit],
|
||||
);
|
||||
const deck = useMemo(() => {
|
||||
if (templateSlug) {
|
||||
const templateIds = templateCardIdsForDeck(templateSlug, section);
|
||||
const firstIds =
|
||||
templateIds.length > 0 ? templateIds : [...selectedIds];
|
||||
const ordered = templateDeck(deckData(section), firstIds);
|
||||
const orderedIds = [...ordered.first, ...ordered.rest];
|
||||
return {
|
||||
compactCardIds: orderedIds,
|
||||
recommendedIds: new Set<string>(),
|
||||
orderedIds,
|
||||
fallback: true,
|
||||
recommendedById: new Map(),
|
||||
};
|
||||
}
|
||||
return deriveCompactCards(section, answers, engineCompactLimit);
|
||||
}, [answers, engineCompactLimit, section, selectedIds, templateSlug]);
|
||||
const compactLimit = templateSlug
|
||||
? deck.orderedIds.length
|
||||
: engineCompactLimit;
|
||||
|
||||
const rankedMethods = useMemo(
|
||||
() => orderByIds(methods, deck.orderedIds),
|
||||
|
||||
@@ -4,6 +4,7 @@ import { useEffect, useMemo } from "react";
|
||||
import { buildFacetQueryString } from "../../../../lib/create/buildFacetQueryString";
|
||||
import { METHOD_FACET_API_SECTION_IDS } from "../../../../lib/create/customRuleFacets";
|
||||
import { loadFacetScores } from "../../../../lib/create/facetRecommendationsLoad";
|
||||
import { isTemplateCreatePath } from "../../../../lib/create/templatePath";
|
||||
import { useCreateFlow } from "../context/CreateFlowContext";
|
||||
|
||||
/**
|
||||
@@ -18,10 +19,12 @@ export function usePrefetchMethodFacetRecommendations(): void {
|
||||
[state],
|
||||
);
|
||||
|
||||
const skipEngine = isTemplateCreatePath(state);
|
||||
|
||||
useEffect(() => {
|
||||
if (queryString.length === 0) return;
|
||||
if (skipEngine || queryString.length === 0) return;
|
||||
for (const section of METHOD_FACET_API_SECTION_IDS) {
|
||||
void loadFacetScores(section, queryString);
|
||||
}
|
||||
}, [queryString]);
|
||||
}, [queryString, skipEngine]);
|
||||
}
|
||||
@@ -1,10 +1,14 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import { buildTemplateCustomizePrefill } from "../../../../lib/create/applyTemplatePrefill";
|
||||
import {
|
||||
buildTemplateCustomizePrefill,
|
||||
templatePresetDetailsFromPrefill,
|
||||
} from "../../../../lib/create/applyTemplatePrefill";
|
||||
import { loadTemplateReviewBySlug } from "../../../../lib/create/loadTemplateReviewBySlug";
|
||||
import { methodSectionsPinsForHydratedSelections } from "../../../../lib/create/publishedDocumentToCreateFlowState";
|
||||
import { stripCustomRuleSelectionFields } from "../../../../lib/create/stripCustomRuleSelectionFields";
|
||||
import { templateChipCounts } from "../../../../lib/create/templatePath";
|
||||
import messages from "../../../../messages/en/index";
|
||||
import type {
|
||||
CreateFlowContextValue,
|
||||
@@ -16,6 +20,20 @@ type AppRouterLike = { push: (_href: string) => void };
|
||||
type UpdateState = CreateFlowContextValue["updateState"];
|
||||
type ReplaceStateFn = CreateFlowContextValue["replaceState"];
|
||||
|
||||
export type TemplateCustomizeDialogModel = {
|
||||
slug: string;
|
||||
templateTitle: string;
|
||||
body: unknown;
|
||||
valuesCount: number;
|
||||
cardsCount: number;
|
||||
};
|
||||
|
||||
export type TemplateCustomizeFields = {
|
||||
title: string;
|
||||
communityContext: string;
|
||||
communityLocation: string;
|
||||
};
|
||||
|
||||
export type UseTemplateReviewActionsResult = {
|
||||
/** True iff the current pathname is a template-review route (locale/basePath tolerant). */
|
||||
isTemplateReviewRoute: boolean;
|
||||
@@ -27,47 +45,43 @@ export type UseTemplateReviewActionsResult = {
|
||||
templateReviewApplyError: string | null;
|
||||
setTemplateReviewApplyError: (_message: string | null) => void;
|
||||
/**
|
||||
* Customize: apply the template's selections onto state and route to
|
||||
* `/create/core-values` (if community name is set) or `/create/informational`
|
||||
* with a `pendingTemplateAction` pin so `/create/review` can later replace
|
||||
* itself with `/create/core-values`. A named community skips setup
|
||||
* questions, so leftover setup answers are dropped and cannot change
|
||||
* suggested cards.
|
||||
* Customize: open the name / photo / description dialog. Continue applies
|
||||
* the template's cards and routes to `/create/core-values`. Setup questions
|
||||
* are skipped.
|
||||
*/
|
||||
handleCustomize: () => Promise<void>;
|
||||
/**
|
||||
* Use without changes: scrub any prior customize picks, seed core values +
|
||||
* method-card selections from the template body (same id mapping as
|
||||
* Customize) so drilling from final-review via + shows selected cards, drop
|
||||
* the Values row from `state.sections`. Direct template entry routes to
|
||||
* `/create/community-name` with a pin so Next/Back collect only name →
|
||||
* description → photo, and drops leftover setup answers along with the
|
||||
* other identity fields. In-flow (`?fromFlow=1`, community steps already
|
||||
* done) routes to `/create/final-review` and keeps those answers.
|
||||
* Use without changes: seed the template's cards and go to final review.
|
||||
* Direct entry clears leftover identity so the Rule card can collect name,
|
||||
* photo, and description. In-flow keeps the community answers already given.
|
||||
*/
|
||||
handleUseWithoutChanges: () => Promise<void>;
|
||||
customizeDialog: TemplateCustomizeDialogModel | null;
|
||||
closeCustomizeDialog: () => void;
|
||||
confirmCustomizeDialog: (_fields: TemplateCustomizeFields) => void;
|
||||
};
|
||||
|
||||
function sectionsFromTemplateBody(
|
||||
body: unknown,
|
||||
): Record<string, unknown>[] | null {
|
||||
if (!body || typeof body !== "object" || Array.isArray(body)) return null;
|
||||
const sectionsRaw = (body as { sections?: unknown }).sections;
|
||||
if (!Array.isArray(sectionsRaw) || sectionsRaw.length === 0) return null;
|
||||
return sectionsRaw as Record<string, unknown>[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Encapsulates the two template-review footer actions (Customize / Use
|
||||
* without changes) plus the small amount of state they share (in-flight
|
||||
* flag, error banner, parsed slug). Called from `CreateFlowLayoutClient`
|
||||
* once; extracting it here keeps the layout shell focused on rendering
|
||||
* rather than orchestrating template fetch + state seeding.
|
||||
* without changes) plus the Customize dialog they share.
|
||||
*
|
||||
* @example
|
||||
* const {
|
||||
* isTemplateReviewRoute,
|
||||
* templateReviewSlug,
|
||||
* isApplyingTemplate,
|
||||
* templateReviewApplyError,
|
||||
* setTemplateReviewApplyError,
|
||||
* handleCustomize,
|
||||
* handleUseWithoutChanges,
|
||||
* } = useTemplateReviewActions({
|
||||
* pathname, state, updateState, replaceState, router,
|
||||
* fromCreateWizard, markCreateFlowInteraction,
|
||||
* });
|
||||
* customizeDialog,
|
||||
* closeCustomizeDialog,
|
||||
* confirmCustomizeDialog,
|
||||
* } = useTemplateReviewActions({ ... });
|
||||
*/
|
||||
export function useTemplateReviewActions({
|
||||
pathname,
|
||||
@@ -95,6 +109,8 @@ export function useTemplateReviewActions({
|
||||
const [templateReviewApplyError, setTemplateReviewApplyError] = useState<
|
||||
string | null
|
||||
>(null);
|
||||
const [customizeDialog, setCustomizeDialog] =
|
||||
useState<TemplateCustomizeDialogModel | null>(null);
|
||||
|
||||
const templateReviewSlug = useMemo(() => {
|
||||
const m = pathname?.match(/\/create\/review-template\/([^/?#]+)/);
|
||||
@@ -116,42 +132,64 @@ export function useTemplateReviewActions({
|
||||
setTemplateReviewApplyError(loaded.message);
|
||||
return;
|
||||
}
|
||||
const prefill = buildTemplateCustomizePrefill(
|
||||
loaded.template.body,
|
||||
templateReviewSlug,
|
||||
);
|
||||
const pinPatch = methodSectionsPinsForHydratedSelections(prefill);
|
||||
const hasCommunityName =
|
||||
typeof state.title === "string" && state.title.trim().length > 0;
|
||||
updateState({
|
||||
...prefill,
|
||||
methodSectionsPinCommitted: {
|
||||
...state.methodSectionsPinCommitted,
|
||||
...pinPatch,
|
||||
},
|
||||
templateReviewBackSlug: undefined,
|
||||
...(hasCommunityName
|
||||
? { pendingTemplateAction: undefined, setupTraits: undefined }
|
||||
: {
|
||||
pendingTemplateAction: {
|
||||
slug: templateReviewSlug,
|
||||
mode: "customize",
|
||||
},
|
||||
}),
|
||||
const counts = templateChipCounts(templateReviewSlug);
|
||||
setCustomizeDialog({
|
||||
slug: templateReviewSlug,
|
||||
templateTitle: loaded.template.title,
|
||||
body: loaded.template.body,
|
||||
valuesCount: counts?.values ?? 0,
|
||||
cardsCount: counts?.cards ?? 0,
|
||||
});
|
||||
router.push(
|
||||
hasCommunityName
|
||||
? createFlowStepPath("core-values")
|
||||
: createFlowStepPath("informational"),
|
||||
);
|
||||
}, [
|
||||
router,
|
||||
state.methodSectionsPinCommitted,
|
||||
state.title,
|
||||
templateReviewSlug,
|
||||
updateState,
|
||||
markCreateFlowInteraction,
|
||||
]);
|
||||
}, [markCreateFlowInteraction, templateReviewSlug]);
|
||||
|
||||
const closeCustomizeDialog = useCallback(() => {
|
||||
setCustomizeDialog(null);
|
||||
}, []);
|
||||
|
||||
const confirmCustomizeDialog = useCallback(
|
||||
(fields: TemplateCustomizeFields) => {
|
||||
if (!customizeDialog) return;
|
||||
markCreateFlowInteraction();
|
||||
const prefill = buildTemplateCustomizePrefill(
|
||||
customizeDialog.body,
|
||||
customizeDialog.slug,
|
||||
);
|
||||
const details = templatePresetDetailsFromPrefill(prefill);
|
||||
const pinPatch = methodSectionsPinsForHydratedSelections(prefill);
|
||||
const title = fields.title.trim();
|
||||
const communityContext = fields.communityContext.trim();
|
||||
const communityLocation = fields.communityLocation.trim();
|
||||
updateState({
|
||||
...prefill,
|
||||
...details,
|
||||
title: title.length > 0 ? title : undefined,
|
||||
communityContext:
|
||||
communityContext.length > 0 ? communityContext : undefined,
|
||||
summary: communityContext.length > 0 ? communityContext : undefined,
|
||||
communityLocation:
|
||||
communityLocation.length > 0 ? communityLocation : undefined,
|
||||
methodSectionsPinCommitted: {
|
||||
...state.methodSectionsPinCommitted,
|
||||
...pinPatch,
|
||||
},
|
||||
templateReviewBackSlug: customizeDialog.slug,
|
||||
setupTraits: undefined,
|
||||
pendingTemplateAction: {
|
||||
slug: customizeDialog.slug,
|
||||
mode: "customize",
|
||||
},
|
||||
});
|
||||
setCustomizeDialog(null);
|
||||
router.push(createFlowStepPath("core-values"));
|
||||
},
|
||||
[
|
||||
customizeDialog,
|
||||
markCreateFlowInteraction,
|
||||
router,
|
||||
state.methodSectionsPinCommitted,
|
||||
updateState,
|
||||
],
|
||||
);
|
||||
|
||||
const handleUseWithoutChanges = useCallback(async () => {
|
||||
if (!templateReviewSlug) return;
|
||||
@@ -165,33 +203,21 @@ export function useTemplateReviewActions({
|
||||
return;
|
||||
}
|
||||
const { template } = loaded;
|
||||
const doc = template.body;
|
||||
if (!doc || typeof doc !== "object" || Array.isArray(doc)) {
|
||||
setTemplateReviewApplyError(
|
||||
messages.create.templateReview.errors.applyFailed,
|
||||
);
|
||||
return;
|
||||
}
|
||||
const sectionsRaw = (doc as { sections?: unknown }).sections;
|
||||
const sections = Array.isArray(sectionsRaw)
|
||||
? (sectionsRaw as Record<string, unknown>[])
|
||||
: [];
|
||||
if (sections.length === 0) {
|
||||
const sections = sectionsFromTemplateBody(template.body);
|
||||
if (!sections) {
|
||||
setTemplateReviewApplyError(
|
||||
messages.create.templateReview.errors.applyFailed,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Atomic read-modify-write: strip prior custom-rule picks and merge template
|
||||
// body in one replaceState so method ids are never lost across React batching
|
||||
// (reset + update separately could leave selections undefined in Strict Mode).
|
||||
replaceState((prev) => {
|
||||
const base = stripCustomRuleSelectionFields(prev);
|
||||
const customizePrefill = buildTemplateCustomizePrefill(
|
||||
doc,
|
||||
template.body,
|
||||
templateReviewSlug ?? undefined,
|
||||
);
|
||||
const details = templatePresetDetailsFromPrefill(customizePrefill);
|
||||
const hasValuesSeed =
|
||||
customizePrefill.selectedCoreValueIds !== undefined;
|
||||
|
||||
@@ -209,68 +235,34 @@ export function useTemplateReviewActions({
|
||||
|
||||
const seeded: CreateFlowState = {
|
||||
...base,
|
||||
...(hasValuesSeed
|
||||
? {
|
||||
selectedCoreValueIds: customizePrefill.selectedCoreValueIds,
|
||||
coreValuesChipsSnapshot:
|
||||
customizePrefill.coreValuesChipsSnapshot,
|
||||
}
|
||||
: {}),
|
||||
...(customizePrefill.selectedCommunicationMethodIds !== undefined
|
||||
? {
|
||||
selectedCommunicationMethodIds:
|
||||
customizePrefill.selectedCommunicationMethodIds,
|
||||
}
|
||||
: {}),
|
||||
...(customizePrefill.selectedMembershipMethodIds !== undefined
|
||||
? {
|
||||
selectedMembershipMethodIds:
|
||||
customizePrefill.selectedMembershipMethodIds,
|
||||
}
|
||||
: {}),
|
||||
...(customizePrefill.selectedDecisionApproachIds !== undefined
|
||||
? {
|
||||
selectedDecisionApproachIds:
|
||||
customizePrefill.selectedDecisionApproachIds,
|
||||
}
|
||||
: {}),
|
||||
...(customizePrefill.selectedConflictManagementIds !== undefined
|
||||
? {
|
||||
selectedConflictManagementIds:
|
||||
customizePrefill.selectedConflictManagementIds,
|
||||
}
|
||||
: {}),
|
||||
...customizePrefill,
|
||||
...details,
|
||||
sections: sectionsWithoutValues,
|
||||
methodSectionsPinCommitted: pinPatch,
|
||||
templateReviewBackSlug: templateReviewSlug,
|
||||
};
|
||||
|
||||
if (fromCreateWizard) {
|
||||
return {
|
||||
...seeded,
|
||||
pendingTemplateAction: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
...seeded,
|
||||
title: undefined,
|
||||
communityContext: undefined,
|
||||
communityAvatarUrl: undefined,
|
||||
currentStep: undefined,
|
||||
templateReviewEntryFromCreateFlow: undefined,
|
||||
setupTraits: undefined,
|
||||
pendingTemplateAction: {
|
||||
slug: templateReviewSlug,
|
||||
mode: "useWithoutChanges",
|
||||
},
|
||||
};
|
||||
|
||||
if (fromCreateWizard) {
|
||||
return seeded;
|
||||
}
|
||||
|
||||
return {
|
||||
...seeded,
|
||||
title: undefined,
|
||||
communityContext: undefined,
|
||||
communityLocation: undefined,
|
||||
communityAvatarUrl: undefined,
|
||||
communityAvatarFileName: undefined,
|
||||
currentStep: undefined,
|
||||
templateReviewEntryFromCreateFlow: undefined,
|
||||
};
|
||||
});
|
||||
router.push(
|
||||
fromCreateWizard
|
||||
? createFlowStepPath("final-review")
|
||||
: createFlowStepPath("community-name"),
|
||||
);
|
||||
router.push(createFlowStepPath("final-review"));
|
||||
}, [
|
||||
fromCreateWizard,
|
||||
markCreateFlowInteraction,
|
||||
@@ -287,5 +279,8 @@ export function useTemplateReviewActions({
|
||||
setTemplateReviewApplyError,
|
||||
handleCustomize,
|
||||
handleUseWithoutChanges,
|
||||
customizeDialog,
|
||||
closeCustomizeDialog,
|
||||
confirmCustomizeDialog,
|
||||
};
|
||||
}
|
||||
@@ -19,7 +19,6 @@ import {
|
||||
getAssetPath,
|
||||
vectorMarkPath,
|
||||
} from "../../../../../lib/assetUtils";
|
||||
import { methodSectionsPinsForHydratedSelections } from "../../../../../lib/create/publishedDocumentToCreateFlowState";
|
||||
import { CREATE_ROUTES, createFlowStepPath } from "../../utils/createFlowPaths";
|
||||
import { CREATE_FLOW_REVIEW_RETURN_QUERY_KEY } from "../../utils/flowSteps";
|
||||
import type { CreateFlowStep } from "../../types";
|
||||
@@ -83,7 +82,7 @@ export function CommunityReviewScreen() {
|
||||
const lgUp = useCreateFlowLgUp();
|
||||
const messages = useMessages();
|
||||
const t = useTranslation("create.community.review");
|
||||
const { state, updateState } = useCreateFlow();
|
||||
const { state } = useCreateFlow();
|
||||
/**
|
||||
* Server layout has an empty context; the client layout may already hold a
|
||||
* named draft. Defer empty-vs-congrats until after mount so the first paint
|
||||
@@ -95,11 +94,9 @@ export function CommunityReviewScreen() {
|
||||
}, []);
|
||||
|
||||
/**
|
||||
* If the user picked **Customize** from a template before finishing community
|
||||
* stage, we pinned `pendingTemplateAction` so this screen can skip itself
|
||||
* and `replace` to `core-values`. **Use without changes** does not skip
|
||||
* identity: if they land here with that pin, send them to `community-name`
|
||||
* and leave the pin so name → description → photo stay in the skip list.
|
||||
* Leftover pin from an older draft: bounce off community review onto the
|
||||
* template path. Customize walks the decks; Use without changes lands on
|
||||
* final review. The pin stays so decks skip the engine.
|
||||
*
|
||||
* Ref guard covers React 18 StrictMode's double-mount in dev so we don't
|
||||
* fire `router.replace` twice on the same transition.
|
||||
@@ -109,31 +106,13 @@ export function CommunityReviewScreen() {
|
||||
if (firedRedirectRef.current) return;
|
||||
const pending = state.pendingTemplateAction;
|
||||
if (!pending) return;
|
||||
if (pending.mode !== "customize") {
|
||||
firedRedirectRef.current = true;
|
||||
router.replace(createFlowStepPath("community-name"));
|
||||
return;
|
||||
}
|
||||
const target = createFlowStepPath("core-values");
|
||||
firedRedirectRef.current = true;
|
||||
const pinMerge = {
|
||||
methodSectionsPinCommitted: {
|
||||
...state.methodSectionsPinCommitted,
|
||||
...methodSectionsPinsForHydratedSelections(state),
|
||||
},
|
||||
};
|
||||
updateState({ pendingTemplateAction: undefined, ...pinMerge });
|
||||
router.replace(target);
|
||||
}, [
|
||||
router,
|
||||
state.pendingTemplateAction,
|
||||
state.methodSectionsPinCommitted,
|
||||
state.selectedCommunicationMethodIds,
|
||||
state.selectedMembershipMethodIds,
|
||||
state.selectedDecisionApproachIds,
|
||||
state.selectedConflictManagementIds,
|
||||
updateState,
|
||||
]);
|
||||
router.replace(
|
||||
createFlowStepPath(
|
||||
pending.mode === "customize" ? "core-values" : "final-review",
|
||||
),
|
||||
);
|
||||
}, [router, state.pendingTemplateAction]);
|
||||
|
||||
const cardTitle =
|
||||
typeof state.title === "string" && state.title.trim().length > 0
|
||||
|
||||
@@ -29,11 +29,19 @@ import {
|
||||
type FinalReviewChipEditPatch,
|
||||
type FinalReviewChipEditTarget,
|
||||
} from "../../components/FinalReviewChipEditModal";
|
||||
import { FinalReviewCommunityContextEditModal } from "../../components/FinalReviewCommunityContextEditModal";
|
||||
import { FinalReviewTitleEditModal } from "../../components/FinalReviewTitleEditModal";
|
||||
import {
|
||||
FinalReviewCommunityContextEditModal,
|
||||
COMMUNITY_CONTEXT_FIELD_MAX_LENGTH,
|
||||
} from "../../components/FinalReviewCommunityContextEditModal";
|
||||
import {
|
||||
FinalReviewTitleEditModal,
|
||||
COMMUNITY_TITLE_FIELD_MAX_LENGTH,
|
||||
} from "../../components/FinalReviewTitleEditModal";
|
||||
import { useCommunityAvatarDisplayUrl } from "../../hooks/useCommunityAvatarDisplayUrl";
|
||||
import { usePreviewSurfaceColor } from "../../hooks/usePreviewSurfaceColor";
|
||||
import { useCreateFlowNavigation } from "../../hooks/useCreateFlowNavigation";
|
||||
import { useCommunityAvatarUpload } from "../../hooks/useCommunityAvatarUpload";
|
||||
import { isTemplateCreatePath } from "../../../../../lib/create/templatePath";
|
||||
import { createFlowStepForFacetGroup } from "../../utils/facetGroupToCreateFlowStep";
|
||||
import { isPreviewSurfaceColor } from "../../../../../lib/create/previewSurfaceColor";
|
||||
import {
|
||||
@@ -225,7 +233,10 @@ export function FinalReviewScreen({
|
||||
|
||||
const descriptionEmptyHint = t("communityContextEditModal.emptyHint");
|
||||
|
||||
const avatarUrl = useCommunityAvatarDisplayUrl(state.communityAvatarUrl);
|
||||
const templatePath = isTemplateCreatePath(state);
|
||||
const avatarUpload = useCommunityAvatarUpload();
|
||||
const serverAvatarUrl = useCommunityAvatarDisplayUrl(state.communityAvatarUrl);
|
||||
const avatarUrl = avatarUpload.displaySrc ?? serverAvatarUrl;
|
||||
const storedFallback =
|
||||
typeof state.previewSurfaceColor === "string"
|
||||
? state.previewSurfaceColor
|
||||
@@ -275,23 +286,73 @@ export function FinalReviewScreen({
|
||||
hasTrailingIcon={false}
|
||||
/>
|
||||
) : null}
|
||||
{templatePath ? (
|
||||
<input
|
||||
ref={avatarUpload.fileInputRef}
|
||||
type="file"
|
||||
className="sr-only"
|
||||
tabIndex={-1}
|
||||
accept={avatarUpload.accept}
|
||||
aria-label={m.create.community.communityUpload.title}
|
||||
onChange={(event) => void avatarUpload.handleFileChange(event)}
|
||||
/>
|
||||
) : null}
|
||||
<Rule
|
||||
title={ruleCardTitle}
|
||||
description={ruleCardDescription}
|
||||
onTitleClick={() => setTitleModalOpen(true)}
|
||||
description={
|
||||
templatePath ? rawCommunityContextForModal : ruleCardDescription
|
||||
}
|
||||
interactive={!templatePath}
|
||||
hasNameField={templatePath}
|
||||
nameValue={rawTitleForModal}
|
||||
nameLabel={m.create.community.communityName.inputLabel}
|
||||
namePlaceholder={m.create.community.communityName.placeholder}
|
||||
onNameChange={
|
||||
templatePath
|
||||
? (value) => {
|
||||
markCreateFlowInteraction();
|
||||
updateState({
|
||||
title: value.slice(0, COMMUNITY_TITLE_FIELD_MAX_LENGTH),
|
||||
});
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
onTitleClick={
|
||||
templatePath ? undefined : () => setTitleModalOpen(true)
|
||||
}
|
||||
titleEditAriaLabel={t("titleEditModal.ariaEditTitle")}
|
||||
onDescriptionClick={() => setCommunityContextModalOpen(true)}
|
||||
onDescriptionClick={
|
||||
templatePath ? undefined : () => setCommunityContextModalOpen(true)
|
||||
}
|
||||
descriptionEmptyHint={descriptionEmptyHint}
|
||||
descriptionEditAriaLabel={t("communityContextEditModal.ariaEditDescription")}
|
||||
descriptionLabel={m.create.community.communityContext.title}
|
||||
descriptionPlaceholder={m.create.community.communityContext.placeholder}
|
||||
descriptionHelperText={m.create.community.communityContext.optional}
|
||||
onDescriptionChange={
|
||||
templatePath
|
||||
? (value) => {
|
||||
markCreateFlowInteraction();
|
||||
const next = value.slice(0, COMMUNITY_CONTEXT_FIELD_MAX_LENGTH);
|
||||
updateState({ communityContext: next, summary: next });
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
onLogoClick={
|
||||
templatePath ? avatarUpload.handlePickFile : undefined
|
||||
}
|
||||
logoUploadAriaLabel={m.create.community.communityUpload.title}
|
||||
size={mdUp ? "L" : "M"}
|
||||
expanded={true}
|
||||
descriptionAtBottom
|
||||
backgroundColor="bg-transparent"
|
||||
surfaceColor={surfaceColor}
|
||||
logoUrl={avatarUrl}
|
||||
logoUrl={avatarUrl ?? undefined}
|
||||
logoAlt={ruleCardTitle}
|
||||
communityInitials={
|
||||
avatarUrl ? undefined : communityInitialsFromTitle(ruleCardTitle)
|
||||
avatarUrl || templatePath
|
||||
? undefined
|
||||
: communityInitialsFromTitle(ruleCardTitle)
|
||||
}
|
||||
categories={finalReviewCategories}
|
||||
className={`${CREATE_FLOW_REVIEW_RULE_LAYOUT_CLASS}${surfaceColor ? "" : " invisible"}`}
|
||||
@@ -312,24 +373,28 @@ export function FinalReviewScreen({
|
||||
onClose={() => setActiveReadOnlyDetail(null)}
|
||||
detail={activeReadOnlyDetail}
|
||||
/>
|
||||
<FinalReviewTitleEditModal
|
||||
isOpen={titleModalOpen}
|
||||
onClose={() => setTitleModalOpen(false)}
|
||||
initialValue={rawTitleForModal}
|
||||
onSave={(value) => {
|
||||
markCreateFlowInteraction();
|
||||
updateState({ title: value });
|
||||
}}
|
||||
/>
|
||||
<FinalReviewCommunityContextEditModal
|
||||
isOpen={communityContextModalOpen}
|
||||
onClose={() => setCommunityContextModalOpen(false)}
|
||||
initialValue={rawCommunityContextForModal}
|
||||
onSave={(value) => {
|
||||
markCreateFlowInteraction();
|
||||
updateState({ communityContext: value, summary: value });
|
||||
}}
|
||||
/>
|
||||
{templatePath ? null : (
|
||||
<>
|
||||
<FinalReviewTitleEditModal
|
||||
isOpen={titleModalOpen}
|
||||
onClose={() => setTitleModalOpen(false)}
|
||||
initialValue={rawTitleForModal}
|
||||
onSave={(value) => {
|
||||
markCreateFlowInteraction();
|
||||
updateState({ title: value });
|
||||
}}
|
||||
/>
|
||||
<FinalReviewCommunityContextEditModal
|
||||
isOpen={communityContextModalOpen}
|
||||
onClose={() => setCommunityContextModalOpen(false)}
|
||||
initialValue={rawCommunityContextForModal}
|
||||
onSave={(value) => {
|
||||
markCreateFlowInteraction();
|
||||
updateState({ communityContext: value, summary: value });
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</CreateFlowLockupCardStepShell>
|
||||
);
|
||||
}
|
||||
@@ -35,6 +35,11 @@ import {
|
||||
} from "../../../../../lib/create/methodCardWizardPrefill";
|
||||
import type { CustomMethodCardFieldBlock } from "../../../../../lib/create/customMethodCardFieldBlocks";
|
||||
import { uploadCreateFlowFile } from "../../../../../lib/create/uploadToServer";
|
||||
import {
|
||||
orderIdsFirst,
|
||||
templatePathFromState,
|
||||
templateValueIdsForSlug,
|
||||
} from "../../../../../lib/create/templatePath";
|
||||
|
||||
const MAX_CORE_VALUES = MAX_SELECTED_CORE_VALUES;
|
||||
|
||||
@@ -114,13 +119,16 @@ export function CoreValuesSelectScreen() {
|
||||
const initialDraftRef = useRef<CoreValueDetailEntry | null>(null);
|
||||
const pendingEphemeralCoreDuplicateRef = useRef<string | null>(null);
|
||||
|
||||
const [coreValueOptions, setCoreValueOptions] = useState<ChipOption[]>(() =>
|
||||
buildCoreValueChipOptionsFromDraft(
|
||||
const [coreValueOptions, setCoreValueOptions] = useState<ChipOption[]>(() => {
|
||||
const base = buildCoreValueChipOptionsFromDraft(
|
||||
presets,
|
||||
state.coreValuesChipsSnapshot,
|
||||
state.selectedCoreValueIds,
|
||||
),
|
||||
);
|
||||
);
|
||||
const path = templatePathFromState(state);
|
||||
if (!path) return base;
|
||||
return orderIdsFirst(base, templateValueIdsForSlug(path.slug));
|
||||
});
|
||||
|
||||
const [activeModalChipId, setActiveModalChipId] = useState<string | null>(
|
||||
null,
|
||||
@@ -137,18 +145,23 @@ export function CoreValuesSelectScreen() {
|
||||
CustomMethodCardFieldBlock[] | null
|
||||
>(null);
|
||||
|
||||
const templatePathSlug = templatePathFromState(state)?.slug;
|
||||
useEffect(() => {
|
||||
const base = buildCoreValueChipOptionsFromDraft(
|
||||
presets,
|
||||
state.coreValuesChipsSnapshot,
|
||||
state.selectedCoreValueIds,
|
||||
);
|
||||
setCoreValueOptions(
|
||||
buildCoreValueChipOptionsFromDraft(
|
||||
presets,
|
||||
state.coreValuesChipsSnapshot,
|
||||
state.selectedCoreValueIds,
|
||||
),
|
||||
templatePathSlug
|
||||
? orderIdsFirst(base, templateValueIdsForSlug(templatePathSlug))
|
||||
: base,
|
||||
);
|
||||
}, [
|
||||
presets,
|
||||
state.coreValuesChipsSnapshot,
|
||||
state.selectedCoreValueIds,
|
||||
templatePathSlug,
|
||||
]);
|
||||
|
||||
/** Sync chips to create-flow draft. Never call `updateState` from inside a `setCoreValueOptions` updater — defer with `queueMicrotask`. */
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
import { GovernanceTemplateGrid } from "../../../components/sections/GovernanceTemplateGrid";
|
||||
import type { TemplateGridCardEntry } from "../../../../lib/templates/templateGridPresentation";
|
||||
import { useTranslation } from "../../../contexts/MessagesContext";
|
||||
import { useTemplatesFacetGridEntries } from "../../../(marketing)/templates/useTemplatesFacetGridEntries";
|
||||
import { CreateFlowHeaderLockup } from "../components/CreateFlowHeaderLockup";
|
||||
import { CreateFlowStepShell } from "../components/CreateFlowStepShell";
|
||||
import { CREATE_FLOW_TWO_COLUMN_MAX_WIDTH_CLASS } from "../components/createFlowLayoutTokens";
|
||||
@@ -15,10 +14,6 @@ export function CreateFlowTemplatesPageClient({
|
||||
initialGridEntries: TemplateGridCardEntry[];
|
||||
}) {
|
||||
const t = useTranslation("pages.templates");
|
||||
const entries = useTemplatesFacetGridEntries({
|
||||
initialGridEntries,
|
||||
enableFacetRecommendations: true,
|
||||
});
|
||||
|
||||
return (
|
||||
<CreateFlowStepShell
|
||||
@@ -34,7 +29,7 @@ export function CreateFlowTemplatesPageClient({
|
||||
justification="left"
|
||||
/>
|
||||
<GovernanceTemplateGrid
|
||||
entries={entries}
|
||||
entries={initialGridEntries}
|
||||
hrefForTemplate={(slug) =>
|
||||
buildTemplateReviewHref(slug, { fromCreateWizard: true })
|
||||
}
|
||||
|
||||
@@ -219,24 +219,19 @@ export interface CreateFlowState {
|
||||
*/
|
||||
customMethodCardFieldBlocksById?: Record<string, CustomMethodCardFieldBlock[]>;
|
||||
/**
|
||||
* Set when a user picks a template (Customize or Use without changes) before
|
||||
* completing the community stage. Customize: the community-review screen
|
||||
* `router.replace`s past `/create/review` to `core-values`. Use without
|
||||
* changes: navigation skips to name → description → optional photo, then
|
||||
* `confirm-stakeholders` (the pin keeps that skip list active). Set only for
|
||||
* **direct** template entry, not when community identity was already collected
|
||||
* in-flow. Cleared when community-review consumes a customize pin, or when
|
||||
* the flow is reset.
|
||||
* Set when a user starts from a template (Customize or Use without changes).
|
||||
* Kept for the rest of the wizard so community setup is skipped, decks skip
|
||||
* the engine, and final-review Back / identity fields know which path it is.
|
||||
* Customize walks values and the four decks; Use without changes lands on
|
||||
* final review. Cleared when the flow is reset.
|
||||
*/
|
||||
pendingTemplateAction?: {
|
||||
slug: string;
|
||||
mode: "customize" | "useWithoutChanges";
|
||||
};
|
||||
/**
|
||||
* Set when the user chooses **Use without changes** on a template-review
|
||||
* page. Used so Back from `community-name` (identity-only path) returns to
|
||||
* `/create/review-template/{slug}` instead of the intro. Cleared when the user
|
||||
* picks **Customize** from template review or when the flow state is cleared.
|
||||
* Template-review slug to return to from Customize values or from
|
||||
* Use-without-changes final review. Cleared when the flow state is cleared.
|
||||
*/
|
||||
templateReviewBackSlug?: string;
|
||||
/**
|
||||
|
||||
@@ -50,26 +50,32 @@ export const FIRST_STEP: CreateFlowStep = FLOW_STEP_ORDER[0];
|
||||
export type CreateFlowNavigationOptions = {
|
||||
skipCommunitySave?: boolean;
|
||||
/**
|
||||
* Template **Use without changes**: collect community name, description, and
|
||||
* optional photo only. Skips intro, structure, size, setup questions, save,
|
||||
* community review, and the custom-rule authoring segment.
|
||||
* Template path. Skips size, kind, scale, maturity, and setup questions.
|
||||
* Customize still walks values and the four decks; Use without changes
|
||||
* jumps to final review. Identity is collected in the Customize dialog or
|
||||
* on the final-review Rule card.
|
||||
*/
|
||||
useWithoutChangesIdentityOnly?: boolean;
|
||||
templatePathMode?: "customize" | "useWithoutChanges";
|
||||
};
|
||||
|
||||
/**
|
||||
* Community + custom-rule steps skipped when
|
||||
* {@link CreateFlowNavigationOptions.useWithoutChangesIdentityOnly} is set.
|
||||
* Remaining identity steps: `community-name` → `community-context` →
|
||||
* `community-upload`, then `final-review`.
|
||||
* Community questionnaire skipped on both template-path modes. Identity is
|
||||
* collected in the Customize dialog or on the final-review Rule card.
|
||||
*/
|
||||
const USE_WITHOUT_CHANGES_IDENTITY_SKIP = new Set<CreateFlowStep>([
|
||||
const TEMPLATE_PATH_COMMUNITY_SKIP = new Set<CreateFlowStep>([
|
||||
"informational",
|
||||
"community-name",
|
||||
"community-structure",
|
||||
"community-context",
|
||||
"community-size",
|
||||
"setup-questions",
|
||||
"community-upload",
|
||||
"community-save",
|
||||
"review",
|
||||
]);
|
||||
|
||||
/** Use without changes does not run values or the four decks unless + Add opens one. */
|
||||
const TEMPLATE_PATH_DECK_SKIP = new Set<CreateFlowStep>([
|
||||
"core-values",
|
||||
"communication-methods",
|
||||
"membership-methods",
|
||||
@@ -82,9 +88,11 @@ function shouldSkipStep(
|
||||
options?: CreateFlowNavigationOptions,
|
||||
): boolean {
|
||||
if (options?.skipCommunitySave && step === "community-save") return true;
|
||||
return Boolean(
|
||||
options?.useWithoutChangesIdentityOnly &&
|
||||
USE_WITHOUT_CHANGES_IDENTITY_SKIP.has(step),
|
||||
if (!options?.templatePathMode) return false;
|
||||
if (TEMPLATE_PATH_COMMUNITY_SKIP.has(step)) return true;
|
||||
return (
|
||||
options.templatePathMode === "useWithoutChanges" &&
|
||||
TEMPLATE_PATH_DECK_SKIP.has(step)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -128,13 +136,10 @@ export function getPreviousStep(
|
||||
* Where the create-flow footer Back action should go. Usually the previous
|
||||
* step in {@link FLOW_STEP_ORDER}.
|
||||
*
|
||||
* Template **Use without changes** exceptions:
|
||||
* - Direct from a template (`useWithoutChangesIdentityOnly`): Back from
|
||||
* `community-name` returns to template review; Back from
|
||||
* `final-review` is `community-upload`.
|
||||
* - In-flow (`?fromFlow=1`, community identity already collected): Back
|
||||
* from `final-review` returns to template review instead of
|
||||
* `conflict-management`.
|
||||
* Template path:
|
||||
* - Customize: Back from `core-values` returns to template review; Back from
|
||||
* `final-review` is the conflict deck.
|
||||
* - Use without changes: Back from `final-review` returns to template review.
|
||||
*/
|
||||
export type CreateFlowBackTarget =
|
||||
| { kind: "step"; step: CreateFlowStep }
|
||||
@@ -149,19 +154,14 @@ export function resolveCreateFlowBackTarget(
|
||||
typeof templateReviewBackSlug === "string"
|
||||
? templateReviewBackSlug.trim()
|
||||
: "";
|
||||
if (
|
||||
currentStep === "community-name" &&
|
||||
options?.useWithoutChangesIdentityOnly &&
|
||||
slug.length > 0
|
||||
) {
|
||||
return { kind: "templateReview", slug };
|
||||
}
|
||||
if (
|
||||
currentStep === "final-review" &&
|
||||
slug.length > 0 &&
|
||||
!options?.useWithoutChangesIdentityOnly
|
||||
) {
|
||||
return { kind: "templateReview", slug };
|
||||
const mode = options?.templatePathMode;
|
||||
if (slug.length > 0) {
|
||||
if (currentStep === "core-values" && mode === "customize") {
|
||||
return { kind: "templateReview", slug };
|
||||
}
|
||||
if (currentStep === "final-review" && mode !== "customize") {
|
||||
return { kind: "templateReview", slug };
|
||||
}
|
||||
}
|
||||
const prev = getPreviousStep(currentStep, options);
|
||||
return prev != null ? { kind: "step", step: prev } : null;
|
||||
@@ -289,14 +289,6 @@ export function isDirectTemplateReviewEntry(
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Only set from `/create/review` “Create from template” with `fromFlow=1`.
|
||||
* Enables facet-ranked `GET /api/templates` + “RECOMMENDED” on the grid; omit
|
||||
* on profile and marketing so stale localStorage facets never show badges.
|
||||
*/
|
||||
export const TEMPLATES_FACET_RECOMMEND_QUERY = "recommendTemplates" as const;
|
||||
export const TEMPLATES_FACET_RECOMMEND_VALUE = "1" as const;
|
||||
|
||||
/** `/create/completed?celebrate=1` — post-publish toast; set only after **initial** POST publish, not PATCH updates. */
|
||||
export const CREATE_FLOW_COMPLETED_CELEBRATE_QUERY = "celebrate" as const;
|
||||
export const CREATE_FLOW_COMPLETED_CELEBRATE_VALUE = "1" as const;
|
||||
|
||||
@@ -6,13 +6,8 @@ import HeaderLockup from "../../components/type/HeaderLockup";
|
||||
import { GovernanceTemplateGrid } from "../../components/sections/GovernanceTemplateGrid";
|
||||
import type { TemplateGridCardEntry } from "../../../lib/templates/templateGridPresentation";
|
||||
import { prepareFreshCreateFlowEntrySync } from "../../(app)/create/utils/prepareFreshCreateFlowEntry";
|
||||
import {
|
||||
buildTemplateReviewHref,
|
||||
TEMPLATES_FACET_RECOMMEND_QUERY,
|
||||
TEMPLATES_FACET_RECOMMEND_VALUE,
|
||||
} from "../../(app)/create/utils/flowSteps";
|
||||
import { buildTemplateReviewHref } from "../../(app)/create/utils/flowSteps";
|
||||
import { useTranslation } from "../../contexts/MessagesContext";
|
||||
import { useTemplatesFacetGridEntries } from "./useTemplatesFacetGridEntries";
|
||||
|
||||
export interface TemplatesPageClientProps {
|
||||
initialGridEntries: TemplateGridCardEntry[];
|
||||
@@ -69,8 +64,7 @@ export default function TemplatesPageClient({
|
||||
/**
|
||||
* - `fromFlow=1` — skip `prepareFreshCreateFlowEntry` on template click
|
||||
* (draft preserved). Used by profile “Create from template”.
|
||||
* - `recommendTemplates=1` — rank templates + “RECOMMENDED”
|
||||
* from `GET /api/templates?facet.*` using the persisted community draft.
|
||||
* Templates carry no recommendation; the grid stays in curated order.
|
||||
*/
|
||||
function TemplatesGridWithSearchParams({
|
||||
initialGridEntries,
|
||||
@@ -79,14 +73,9 @@ function TemplatesGridWithSearchParams({
|
||||
}) {
|
||||
const searchParams = useSearchParams();
|
||||
const fromFlow = searchParams.get("fromFlow") === "1";
|
||||
const enableFacetRecommendations =
|
||||
searchParams.get(TEMPLATES_FACET_RECOMMEND_QUERY) ===
|
||||
TEMPLATES_FACET_RECOMMEND_VALUE;
|
||||
const entries = useTemplatesFacetGridEntries({
|
||||
initialGridEntries,
|
||||
enableFacetRecommendations,
|
||||
});
|
||||
return <TemplatesGrid entries={entries} fromFlow={fromFlow} />;
|
||||
return (
|
||||
<TemplatesGrid entries={initialGridEntries} fromFlow={fromFlow} />
|
||||
);
|
||||
}
|
||||
|
||||
function TemplatesGrid({
|
||||
|
||||
@@ -1,71 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { readAnonymousCreateFlowState } from "../../(app)/create/utils/anonymousDraftStorage";
|
||||
import { buildFacetQueryString } from "../../../lib/create/buildFacetQueryString";
|
||||
import {
|
||||
fetchRankedTemplatesByFacets,
|
||||
isTemplatesFetchAborted,
|
||||
} from "../../../lib/create/fetchTemplates";
|
||||
import {
|
||||
gridEntriesWithFacetScores,
|
||||
type TemplateGridCardEntry,
|
||||
} from "../../../lib/templates/templateGridPresentation";
|
||||
|
||||
type UseTemplatesFacetGridEntriesArgs = {
|
||||
initialGridEntries: TemplateGridCardEntry[];
|
||||
enableFacetRecommendations: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* When `enableFacetRecommendations` (in-flow `/create/templates`, or marketing
|
||||
* `/templates?recommendTemplates=1`), re-fetch ranked templates from
|
||||
* `GET /api/templates?facet.*` using the persisted create-flow draft.
|
||||
* Otherwise returns `initialGridEntries` from SSR.
|
||||
*/
|
||||
export function useTemplatesFacetGridEntries({
|
||||
initialGridEntries,
|
||||
enableFacetRecommendations,
|
||||
}: UseTemplatesFacetGridEntriesArgs): TemplateGridCardEntry[] {
|
||||
const [entries, setEntries] = useState(initialGridEntries);
|
||||
|
||||
useEffect(() => {
|
||||
if (!enableFacetRecommendations) {
|
||||
setEntries(initialGridEntries);
|
||||
return;
|
||||
}
|
||||
const state = readAnonymousCreateFlowState();
|
||||
const facetQuery = buildFacetQueryString(state);
|
||||
if (facetQuery.length === 0) {
|
||||
setEntries(initialGridEntries);
|
||||
return;
|
||||
}
|
||||
|
||||
const ac = new AbortController();
|
||||
void (async () => {
|
||||
try {
|
||||
const result = await fetchRankedTemplatesByFacets({
|
||||
signal: ac.signal,
|
||||
facetQuery,
|
||||
});
|
||||
if (ac.signal.aborted) return;
|
||||
if ("error" in result) {
|
||||
setEntries(initialGridEntries);
|
||||
return;
|
||||
}
|
||||
setEntries(
|
||||
gridEntriesWithFacetScores(result.templates, result.scores),
|
||||
);
|
||||
} catch (e) {
|
||||
if (isTemplatesFetchAborted(e)) return;
|
||||
setEntries(initialGridEntries);
|
||||
}
|
||||
})();
|
||||
|
||||
return () => {
|
||||
ac.abort();
|
||||
};
|
||||
}, [enableFacetRecommendations, initialGridEntries]);
|
||||
|
||||
return entries;
|
||||
}
|
||||
@@ -52,6 +52,17 @@ const RuleContainer = memo<RuleProps>(
|
||||
fluidWidth = false,
|
||||
descriptionAtBottom = false,
|
||||
surfaceColor,
|
||||
hasNameField = false,
|
||||
nameValue,
|
||||
nameLabel,
|
||||
namePlaceholder,
|
||||
onNameChange,
|
||||
descriptionLabel,
|
||||
descriptionPlaceholder,
|
||||
descriptionHelperText,
|
||||
onDescriptionChange,
|
||||
onLogoClick,
|
||||
logoUploadAriaLabel,
|
||||
}) => {
|
||||
const size = sizeProp ?? "L";
|
||||
const isInteractive = interactive ?? !hasBottomLinks;
|
||||
@@ -123,6 +134,17 @@ const RuleContainer = memo<RuleProps>(
|
||||
surfaceColor={surfaceColor}
|
||||
cardAriaLabel={cardAriaLabel}
|
||||
recommendedLabel={recommendedLabel}
|
||||
hasNameField={hasNameField}
|
||||
nameValue={nameValue}
|
||||
nameLabel={nameLabel}
|
||||
namePlaceholder={namePlaceholder}
|
||||
onNameChange={onNameChange}
|
||||
descriptionLabel={descriptionLabel}
|
||||
descriptionPlaceholder={descriptionPlaceholder}
|
||||
descriptionHelperText={descriptionHelperText}
|
||||
onDescriptionChange={onDescriptionChange}
|
||||
onLogoClick={onLogoClick}
|
||||
logoUploadAriaLabel={logoUploadAriaLabel}
|
||||
/>
|
||||
);
|
||||
},
|
||||
|
||||
@@ -103,6 +103,21 @@ export interface RuleProps {
|
||||
* {@link backgroundColor}.
|
||||
*/
|
||||
surfaceColor?: string;
|
||||
/**
|
||||
* Figma Has Name Field: inline community name, optional logo upload, and
|
||||
* labeled description. Used on the template-path final review.
|
||||
*/
|
||||
hasNameField?: boolean;
|
||||
nameValue?: string;
|
||||
nameLabel?: string;
|
||||
namePlaceholder?: string;
|
||||
onNameChange?: (_value: string) => void;
|
||||
descriptionLabel?: string;
|
||||
descriptionPlaceholder?: string;
|
||||
descriptionHelperText?: string;
|
||||
onDescriptionChange?: (_value: string) => void;
|
||||
onLogoClick?: () => void;
|
||||
logoUploadAriaLabel?: string;
|
||||
}
|
||||
|
||||
export interface RuleViewProps {
|
||||
@@ -138,4 +153,15 @@ export interface RuleViewProps {
|
||||
/** Interactive card aria-label; supplied by the container from `ruleCard` messages. */
|
||||
cardAriaLabel: string;
|
||||
recommendedLabel: string;
|
||||
hasNameField?: boolean;
|
||||
nameValue?: string;
|
||||
nameLabel?: string;
|
||||
namePlaceholder?: string;
|
||||
onNameChange?: (_value: string) => void;
|
||||
descriptionLabel?: string;
|
||||
descriptionPlaceholder?: string;
|
||||
descriptionHelperText?: string;
|
||||
onDescriptionChange?: (_value: string) => void;
|
||||
onLogoClick?: () => void;
|
||||
logoUploadAriaLabel?: string;
|
||||
}
|
||||
@@ -4,8 +4,11 @@ import Image from "next/image";
|
||||
import NextLink from "next/link";
|
||||
import MultiSelect from "../../controls/MultiSelect";
|
||||
import InlineTextButton from "../../buttons/InlineTextButton";
|
||||
import TextInput from "../../controls/TextInput";
|
||||
import TextArea from "../../controls/TextArea";
|
||||
import NavigationLink from "../../navigation/Link";
|
||||
import Tag from "../../utility/Tag";
|
||||
import InputLabel from "../../type/InputLabel";
|
||||
import type { RuleBottomLink, RuleViewProps } from "./Rule.types";
|
||||
|
||||
export function RuleView({
|
||||
@@ -40,6 +43,17 @@ export function RuleView({
|
||||
surfaceColor,
|
||||
cardAriaLabel,
|
||||
recommendedLabel,
|
||||
hasNameField = false,
|
||||
nameValue = "",
|
||||
nameLabel,
|
||||
namePlaceholder,
|
||||
onNameChange,
|
||||
descriptionLabel,
|
||||
descriptionPlaceholder,
|
||||
descriptionHelperText,
|
||||
onDescriptionChange,
|
||||
onLogoClick,
|
||||
logoUploadAriaLabel,
|
||||
}: RuleViewProps) {
|
||||
const ariaLabel = cardAriaLabel;
|
||||
const interactiveCard = interactive ?? !hasBottomLinks;
|
||||
@@ -229,9 +243,39 @@ export function RuleView({
|
||||
);
|
||||
}
|
||||
|
||||
if (hasNameField) {
|
||||
return (
|
||||
<span
|
||||
className={`${logoContainerClass} flex items-center justify-center rounded-full border border-dashed border-[var(--color-content-invert-primary)] text-[24px] leading-none text-[var(--color-content-invert-primary)]`}
|
||||
aria-hidden={onLogoClick ? true : undefined}
|
||||
>
|
||||
+
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
const renderLogoControl = () => {
|
||||
const inner = renderLogo();
|
||||
if (!inner) return null;
|
||||
if (!onLogoClick) return inner;
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className="cursor-pointer rounded-full p-0"
|
||||
aria-label={logoUploadAriaLabel}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
onLogoClick();
|
||||
}}
|
||||
>
|
||||
{inner}
|
||||
</button>
|
||||
);
|
||||
};
|
||||
|
||||
// Border radius - use CSS classes if provided via className, otherwise use size-based logic
|
||||
const borderRadiusClass = className?.includes("rounded-")
|
||||
? "" // If className already has border radius, don't add size-based one
|
||||
@@ -291,12 +335,36 @@ export function RuleView({
|
||||
.join(" ");
|
||||
|
||||
const showExpandedDescription = Boolean(
|
||||
hasNameField ||
|
||||
description ||
|
||||
(onDescriptionClick && typeof descriptionEmptyHint === "string"),
|
||||
);
|
||||
const expandedDescription = showExpandedDescription ? (
|
||||
<div className={expandedDescriptionFrameClass}>
|
||||
{onDescriptionClick ? (
|
||||
{hasNameField && onDescriptionChange ? (
|
||||
<div
|
||||
className="flex w-full min-w-0 flex-col gap-[6px]"
|
||||
data-testid="rule-description-field"
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
>
|
||||
<InputLabel
|
||||
label={descriptionLabel ?? ""}
|
||||
helpIcon={false}
|
||||
helperText={descriptionHelperText}
|
||||
size="s"
|
||||
/>
|
||||
<TextArea
|
||||
label={descriptionLabel}
|
||||
placeholder={descriptionPlaceholder}
|
||||
value={description ?? ""}
|
||||
onChange={(event) => onDescriptionChange(event.target.value)}
|
||||
size="small"
|
||||
formHeader={false}
|
||||
showHelpIcon={false}
|
||||
rows={2}
|
||||
/>
|
||||
</div>
|
||||
) : onDescriptionClick ? (
|
||||
<InlineTextButton
|
||||
type="button"
|
||||
underline={false}
|
||||
@@ -333,12 +401,12 @@ export function RuleView({
|
||||
w-full shrink-0 items-center gap-px
|
||||
"
|
||||
>
|
||||
{renderLogo() && (
|
||||
{(renderLogoControl() || hasNameField) && (
|
||||
<div className={headerIconCellClass}>
|
||||
{renderLogo()}
|
||||
{renderLogoControl()}
|
||||
</div>
|
||||
)}
|
||||
{title && (
|
||||
{(title || hasNameField) && (
|
||||
<div
|
||||
className={`
|
||||
flex min-w-0 flex-1 flex-col justify-center
|
||||
@@ -365,7 +433,31 @@ export function RuleView({
|
||||
{recommendedLabel}
|
||||
</Tag>
|
||||
) : null}
|
||||
{onTitleClick ? (
|
||||
{hasNameField && onNameChange ? (
|
||||
<div
|
||||
className="flex w-full min-w-0 flex-col gap-[6px]"
|
||||
data-testid="rule-name-field"
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
>
|
||||
<InputLabel
|
||||
label={nameLabel ?? ""}
|
||||
helpIcon={false}
|
||||
asterisk
|
||||
size="s"
|
||||
/>
|
||||
<TextInput
|
||||
label={nameLabel}
|
||||
placeholder={namePlaceholder}
|
||||
value={nameValue}
|
||||
onChange={(event) => onNameChange(event.target.value)}
|
||||
inputSize="small"
|
||||
formHeader={false}
|
||||
showHelpIcon={false}
|
||||
required
|
||||
autoFocus={nameValue.trim().length === 0}
|
||||
/>
|
||||
</div>
|
||||
) : onTitleClick ? (
|
||||
<InlineTextButton
|
||||
type="button"
|
||||
underline={false}
|
||||
|
||||
Reference in new issue
Block a user