288 lines
9.0 KiB
TypeScript
288 lines
9.0 KiB
TypeScript
"use client";
|
|
|
|
import { useCallback, useMemo, useState } from "react";
|
|
import {
|
|
buildAppliedTemplateCreateFlowState,
|
|
sectionsFromTemplateBody,
|
|
} from "../../../../lib/create/applyTemplatePrefill";
|
|
import { fetchDraftFromServer } from "../../../../lib/create/api";
|
|
import { createFlowStateHasKeys } from "../../../../lib/create/draftHydrationUtils";
|
|
import { loadTemplateReviewBySlug } from "../../../../lib/create/loadTemplateReviewBySlug";
|
|
import { templateChipCounts } from "../../../../lib/create/templatePath";
|
|
import messages from "../../../../messages/en/index";
|
|
import type { AsyncConfirmOptions } from "../../../hooks/useAsyncConfirm";
|
|
import type {
|
|
CreateFlowContextValue,
|
|
CreateFlowState,
|
|
} from "../types";
|
|
import { hasBrowserCreateFlowDraft } from "../utils/createRuleEntry";
|
|
import { createFlowStepPath } from "../utils/createFlowPaths";
|
|
import {
|
|
latchTemplateApply,
|
|
prepareFreshCreateFlowEntrySync,
|
|
} from "../utils/prepareFreshCreateFlowEntry";
|
|
|
|
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;
|
|
/** Decoded slug parsed out of the template-review pathname, or null. */
|
|
templateReviewSlug: string | null;
|
|
/** True between the fetch start and resolution for either action. */
|
|
isApplyingTemplate: boolean;
|
|
/** Set when the template fetch failed or the body was malformed. Cleared at the start of each action. */
|
|
templateReviewApplyError: string | null;
|
|
setTemplateReviewApplyError: (_message: string | null) => void;
|
|
/**
|
|
* 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: seed the template's cards and go to the name screen,
|
|
* then description and photo, then final review. Direct entry clears leftover
|
|
* identity. In-flow keeps the community answers already given so those
|
|
* screens are pre-filled.
|
|
*/
|
|
handleUseWithoutChanges: () => Promise<void>;
|
|
customizeDialog: TemplateCustomizeDialogModel | null;
|
|
closeCustomizeDialog: () => void;
|
|
confirmCustomizeDialog: (_fields: TemplateCustomizeFields) => void;
|
|
};
|
|
|
|
const TEMPLATE_NAV_KEYS = new Set([
|
|
"templateReviewEntryFromCreateFlow",
|
|
"templateReviewBackSlug",
|
|
"pendingTemplateAction",
|
|
"currentStep",
|
|
"methodSectionsPinCommitted",
|
|
]);
|
|
|
|
function createFlowStateLooksLikeProgress(state: CreateFlowState): boolean {
|
|
return Object.keys(state).some((key) => !TEMPLATE_NAV_KEYS.has(key));
|
|
}
|
|
|
|
async function hasDraftToReplace(
|
|
state: CreateFlowState,
|
|
signedIn: boolean,
|
|
): Promise<boolean> {
|
|
if (createFlowStateLooksLikeProgress(state)) return true;
|
|
if (hasBrowserCreateFlowDraft()) return true;
|
|
if (!signedIn) return false;
|
|
const server = await fetchDraftFromServer();
|
|
return server != null && createFlowStateHasKeys(server);
|
|
}
|
|
|
|
/**
|
|
* Encapsulates the two template-review footer actions (Customize / Use
|
|
* without changes) plus the Customize dialog they share.
|
|
*
|
|
* @example
|
|
* const {
|
|
* handleCustomize,
|
|
* handleUseWithoutChanges,
|
|
* customizeDialog,
|
|
* closeCustomizeDialog,
|
|
* confirmCustomizeDialog,
|
|
* } = useTemplateReviewActions({ ... });
|
|
*/
|
|
export function useTemplateReviewActions({
|
|
pathname,
|
|
state,
|
|
replaceState,
|
|
router,
|
|
fromCreateWizard = false,
|
|
signedIn = false,
|
|
requestConfirm,
|
|
markCreateFlowInteraction,
|
|
}: {
|
|
pathname: string | null | undefined;
|
|
state: CreateFlowState;
|
|
updateState: UpdateState;
|
|
replaceState: ReplaceStateFn;
|
|
router: AppRouterLike;
|
|
/**
|
|
* True when this template-review URL was opened from the create wizard
|
|
* (`?fromFlow=1`). Direct catalog / marketing entry is false — a leftover
|
|
* draft title must not count as “community steps already done”.
|
|
*/
|
|
fromCreateWizard?: boolean;
|
|
signedIn?: boolean;
|
|
requestConfirm?: (_opts: AsyncConfirmOptions) => Promise<boolean>;
|
|
markCreateFlowInteraction: () => void;
|
|
}): UseTemplateReviewActionsResult {
|
|
const [isApplyingTemplate, setIsApplyingTemplate] = useState(false);
|
|
const [templateReviewApplyError, setTemplateReviewApplyError] = useState<
|
|
string | null
|
|
>(null);
|
|
const [customizeDialog, setCustomizeDialog] =
|
|
useState<TemplateCustomizeDialogModel | null>(null);
|
|
|
|
const templateReviewSlug = useMemo(() => {
|
|
const m = pathname?.match(/\/create\/review-template\/([^/?#]+)/);
|
|
return m?.[1] ? decodeURIComponent(m[1]) : null;
|
|
}, [pathname]);
|
|
|
|
const isTemplateReviewRoute = Boolean(
|
|
pathname?.includes("/create/review-template/"),
|
|
);
|
|
|
|
const keepInFlowIdentity = fromCreateWizard;
|
|
|
|
const confirmReplaceDraft = useCallback(async (): Promise<boolean> => {
|
|
if (!requestConfirm) return true;
|
|
if (!(await hasDraftToReplace(state, signedIn))) return true;
|
|
const copy = messages.create.templateReview.replaceDraft;
|
|
return requestConfirm({
|
|
title: copy.title,
|
|
description: copy.description,
|
|
proceedText: copy.proceed,
|
|
cancelText: copy.cancel,
|
|
});
|
|
}, [requestConfirm, signedIn, state]);
|
|
|
|
const handleCustomize = useCallback(async () => {
|
|
if (!templateReviewSlug) return;
|
|
markCreateFlowInteraction();
|
|
setTemplateReviewApplyError(null);
|
|
if (!(await confirmReplaceDraft())) return;
|
|
setIsApplyingTemplate(true);
|
|
const loaded = await loadTemplateReviewBySlug(templateReviewSlug);
|
|
setIsApplyingTemplate(false);
|
|
if (loaded.ok === false) {
|
|
setTemplateReviewApplyError(loaded.message);
|
|
return;
|
|
}
|
|
const counts = templateChipCounts(templateReviewSlug);
|
|
setCustomizeDialog({
|
|
slug: templateReviewSlug,
|
|
templateTitle: loaded.template.title,
|
|
body: loaded.template.body,
|
|
valuesCount: counts?.values ?? 0,
|
|
cardsCount: counts?.cards ?? 0,
|
|
});
|
|
}, [
|
|
confirmReplaceDraft,
|
|
markCreateFlowInteraction,
|
|
templateReviewSlug,
|
|
]);
|
|
|
|
const closeCustomizeDialog = useCallback(() => {
|
|
setCustomizeDialog(null);
|
|
}, []);
|
|
|
|
const confirmCustomizeDialog = useCallback(
|
|
(fields: TemplateCustomizeFields) => {
|
|
if (!customizeDialog) return;
|
|
markCreateFlowInteraction();
|
|
prepareFreshCreateFlowEntrySync({ signedIn });
|
|
latchTemplateApply();
|
|
replaceState(() =>
|
|
buildAppliedTemplateCreateFlowState({
|
|
slug: customizeDialog.slug,
|
|
body: customizeDialog.body,
|
|
mode: "customize",
|
|
identity: {
|
|
title: fields.title,
|
|
communityContext: fields.communityContext,
|
|
communityLocation: fields.communityLocation,
|
|
},
|
|
}),
|
|
);
|
|
setCustomizeDialog(null);
|
|
router.push(createFlowStepPath("core-values"));
|
|
},
|
|
[
|
|
customizeDialog,
|
|
markCreateFlowInteraction,
|
|
replaceState,
|
|
router,
|
|
signedIn,
|
|
],
|
|
);
|
|
|
|
const handleUseWithoutChanges = useCallback(async () => {
|
|
if (!templateReviewSlug) return;
|
|
markCreateFlowInteraction();
|
|
setTemplateReviewApplyError(null);
|
|
if (!(await confirmReplaceDraft())) return;
|
|
setIsApplyingTemplate(true);
|
|
const loaded = await loadTemplateReviewBySlug(templateReviewSlug);
|
|
setIsApplyingTemplate(false);
|
|
if (loaded.ok === false) {
|
|
setTemplateReviewApplyError(loaded.message);
|
|
return;
|
|
}
|
|
const { template } = loaded;
|
|
const sections = sectionsFromTemplateBody(template.body);
|
|
if (!sections) {
|
|
setTemplateReviewApplyError(
|
|
messages.create.templateReview.errors.applyFailed,
|
|
);
|
|
return;
|
|
}
|
|
|
|
prepareFreshCreateFlowEntrySync({ signedIn });
|
|
latchTemplateApply();
|
|
replaceState(() =>
|
|
buildAppliedTemplateCreateFlowState({
|
|
slug: templateReviewSlug,
|
|
body: template.body,
|
|
mode: "useWithoutChanges",
|
|
identity: keepInFlowIdentity
|
|
? {
|
|
title: state.title,
|
|
communityContext: state.communityContext,
|
|
communityLocation: state.communityLocation,
|
|
communityAvatarUrl: state.communityAvatarUrl,
|
|
}
|
|
: undefined,
|
|
}),
|
|
);
|
|
router.push(createFlowStepPath("community-name"));
|
|
}, [
|
|
confirmReplaceDraft,
|
|
keepInFlowIdentity,
|
|
markCreateFlowInteraction,
|
|
replaceState,
|
|
router,
|
|
state.communityAvatarUrl,
|
|
state.communityContext,
|
|
state.communityLocation,
|
|
signedIn,
|
|
state.title,
|
|
templateReviewSlug,
|
|
]);
|
|
|
|
return {
|
|
isTemplateReviewRoute,
|
|
templateReviewSlug,
|
|
isApplyingTemplate,
|
|
templateReviewApplyError,
|
|
setTemplateReviewApplyError,
|
|
handleCustomize,
|
|
handleUseWithoutChanges,
|
|
customizeDialog,
|
|
closeCustomizeDialog,
|
|
confirmCustomizeDialog,
|
|
};
|
|
}
|