diff --git a/app/(app)/create/CreateFlowLayoutClient.tsx b/app/(app)/create/CreateFlowLayoutClient.tsx index 89e0d01..7bee008 100644 --- a/app/(app)/create/CreateFlowLayoutClient.tsx +++ b/app/(app)/create/CreateFlowLayoutClient.tsx @@ -253,16 +253,10 @@ function CreateFlowLayoutContent({ resolve?.(choice); }, []); - const { - copyPublishedRuleLink, - mailtoPublishedRule, - sharePublishedRuleViaSignal, - sharePublishedRuleViaSlack, - sharePublishedRuleViaDiscord, - onSelectExportFormat: onCompletedExportFormat, - } = useCompletedRuleShareExport({ - setActionBanner: setCompletedFlowBanner, - }); + const { onSelectExportFormat: onCompletedExportFormat } = + useCompletedRuleShareExport({ + setActionBanner: setCompletedFlowBanner, + }); const handleOpenCompletedShareModal = () => { if (!readLastPublishedRule()) { @@ -862,11 +856,13 @@ function CreateFlowLayoutContent({ setShareModalOpen(false)} - onCopyLink={() => void copyPublishedRuleLink()} - onEmailShare={mailtoPublishedRule} - onSignalShare={() => void sharePublishedRuleViaSignal()} - onSlackShare={() => void sharePublishedRuleViaSlack()} - onDiscordShare={() => void sharePublishedRuleViaDiscord()} + ruleId={readLastPublishedRule()?.id ?? null} + onRequestLogin={() => + openLogin({ + nextPath: pathname, + backdropVariant: "blurredYellow", + }) + } /> { + if ( + rule.document === null || + typeof rule.document !== "object" || + Array.isArray(rule.document) + ) { + return null; + } + return { + id: rule.id, + title: rule.title, + summary: rule.summary, + document: rule.document as Record, + }; + }, + [], + ); + + const handleExportRulePdf = useCallback( + async (id: string) => { + setActionError(null); + const detail = await fetchPublishedRuleDetail(id); + const stored = detail ? toStoredRule(detail.rule) : null; + if (!stored) { + setActionError(t("actionError")); + return; + } + try { + downloadStoredRuleAsPdf(stored); + } catch { + setActionError(t("actionError")); + } + }, + [t, toStoredRule], + ); + + const handleExportRuleMarkdown = useCallback( + async (id: string) => { + setActionError(null); + const detail = await fetchPublishedRuleDetail(id); + const stored = detail ? toStoredRule(detail.rule) : null; + if (!stored) { + setActionError(t("actionError")); + return; + } + try { + const markdown = exportStoredRuleAsMarkdown(stored); + downloadTextFile( + `${exportFilenameBase(stored)}-community-rule.md`, + markdown, + "text/markdown;charset=utf-8", + ); + } catch { + setActionError(t("actionError")); + } + }, + [t, toStoredRule], + ); + const handleConfirmDeleteAccount = useCallback(async () => { setActionError(null); setAccountDeleteBusy(true); @@ -409,6 +479,8 @@ export default function ProfilePageClient() { }} onCloseDeleteAccount={() => setAccountDeleteOpen(false)} onConfirmDeleteAccount={handleConfirmDeleteAccount} + onExportRulePdf={(id) => void handleExportRulePdf(id)} + onExportRuleMarkdown={(id) => void handleExportRuleMarkdown(id)} onStartNewCustomRule={handleStartNewCustomRule} /> ); diff --git a/app/(app)/profile/_components/ProfilePage.view.tsx b/app/(app)/profile/_components/ProfilePage.view.tsx index 239cd11..5bc399c 100644 --- a/app/(app)/profile/_components/ProfilePage.view.tsx +++ b/app/(app)/profile/_components/ProfilePage.view.tsx @@ -9,6 +9,7 @@ import type { ListItem, ListSize } from "../../../components/layout/List"; import ListEntry from "../../../components/layout/ListEntry"; import Icon from "../../../components/asset/icon"; import Dialog from "../../../components/modals/Dialog"; +import DeleteAccount from "../../../components/modals/DeleteAccount"; import Alert from "../../../components/modals/Alert"; import HeaderLockup from "../../../components/type/HeaderLockup"; import { useTranslation } from "../../../contexts/MessagesContext"; @@ -71,6 +72,8 @@ export type ProfilePageViewProps = { onOpenDeleteAccount: () => void; onCloseDeleteAccount: () => void; onConfirmDeleteAccount: () => void; + onExportRulePdf: (id: string) => void; + onExportRuleMarkdown: (id: string) => void; onDismissProfileSuccess: () => void; onDismissActionError: () => void; onDismissRulesError: () => void; @@ -194,6 +197,8 @@ export function ProfilePageView({ onOpenDeleteAccount, onCloseDeleteAccount, onConfirmDeleteAccount, + onExportRulePdf, + onExportRuleMarkdown, onDismissProfileSuccess, onDismissActionError, onDismissRulesError, @@ -489,39 +494,18 @@ export function ProfilePageView({ } /> - { if (!accountDeleteBusy) onCloseDeleteAccount(); }} - backdropVariant="blurredYellow" - title={t("deleteAccountModalTitle")} - description={t("deleteAccountModalBody")} - footer={ - <> - - - - } + onConfirm={onConfirmDeleteAccount} + busy={accountDeleteBusy} + rules={rules + .filter((rule) => rule.role === "owner") + .map((rule) => ({ id: rule.id, title: rule.title }))} + onExportPdf={onExportRulePdf} + onExportMarkdown={onExportRuleMarkdown} /> (null); - const { copyPageLink, mailtoPageLink, handleDuplicate } = - useUseCaseCompletedRuleActions({ - slug, - fixture, - setActionBanner, - }); + const { copyPageLink, handleDuplicate } = useUseCaseCompletedRuleActions({ + slug, + fixture, + setActionBanner, + }); return ( setShareModalOpen(true)} - onShareClose={() => setShareModalOpen(false)} - onCopyLink={() => void copyPageLink()} - onEmailShare={mailtoPageLink} + onShare={() => void copyPageLink()} onDuplicate={() => void handleDuplicate()} onExit={() => router.push(`/use-cases/${slug}`)} actionBanner={actionBanner} diff --git a/app/(marketing-case-study)/use-cases/[slug]/rule/_components/UseCaseCompletedRule.types.ts b/app/(marketing-case-study)/use-cases/[slug]/rule/_components/UseCaseCompletedRule.types.ts index d0796fd..03339a8 100644 --- a/app/(marketing-case-study)/use-cases/[slug]/rule/_components/UseCaseCompletedRule.types.ts +++ b/app/(marketing-case-study)/use-cases/[slug]/rule/_components/UseCaseCompletedRule.types.ts @@ -14,11 +14,7 @@ export type UseCaseCompletedRuleViewProps = UseCaseCompletedRuleProps & { duplicateLabel: string; duplicateAriaLabel: string; exitLabel: string; - shareModalOpen: boolean; - onShareOpen: () => void; - onShareClose: () => void; - onCopyLink: () => void; - onEmailShare: () => void; + onShare: () => void; onDuplicate: () => void; onExit: () => void; actionBanner: UseCaseCompletedRuleActionBanner | null; diff --git a/app/(marketing-case-study)/use-cases/[slug]/rule/_components/UseCaseCompletedRule.view.tsx b/app/(marketing-case-study)/use-cases/[slug]/rule/_components/UseCaseCompletedRule.view.tsx index b306095..9268c92 100644 --- a/app/(marketing-case-study)/use-cases/[slug]/rule/_components/UseCaseCompletedRule.view.tsx +++ b/app/(marketing-case-study)/use-cases/[slug]/rule/_components/UseCaseCompletedRule.view.tsx @@ -2,7 +2,6 @@ import CommunityRule from "../../../../../components/type/CommunityRule"; import CreateFlowTopNav from "../../../../../components/navigation/CreateFlowTopNav"; -import Share from "../../../../../components/modals/Share"; import Alert from "../../../../../components/modals/Alert"; import { CreateFlowHeaderLockup } from "../../../../../(app)/create/components/CreateFlowHeaderLockup"; import { @@ -19,11 +18,7 @@ export function UseCaseCompletedRuleView({ duplicateLabel, duplicateAriaLabel, exitLabel, - shareModalOpen, - onShareOpen, - onShareClose, - onCopyLink, - onEmailShare, + onShare, onDuplicate, onExit, actionBanner, @@ -59,15 +54,6 @@ export function UseCaseCompletedRuleView({ ) : null} - diff --git a/app/components/modals/Create/CreateModalFrame.view.tsx b/app/components/modals/Create/CreateModalFrame.view.tsx index c18e0b2..55b35b3 100644 --- a/app/components/modals/Create/CreateModalFrame.view.tsx +++ b/app/components/modals/Create/CreateModalFrame.view.tsx @@ -12,6 +12,8 @@ const backdropOverlayClasses: Record = { "fixed inset-0 z-[9998] bg-[var(--color-surface-invert-brand-primary)]/85 backdrop-blur-md supports-[backdrop-filter]:bg-[var(--color-surface-invert-brand-primary)]/75", }; +export type CreateModalPresentationValue = "dialog" | "sheet"; + export type CreateModalFrameViewProps = { isOpen: boolean; onOverlayClick: () => void; @@ -24,6 +26,11 @@ export type CreateModalFrameViewProps = { children: ReactNode; /** Rendered below the dialog card on the backdrop (e.g. “Back to home”). */ belowCard?: ReactNode; + /** + * `sheet` is full-viewport below `md` (Figma 320–639) and a 546px dialog + * from `md`. `dialog` is the centered card used by Create and Dialog. + */ + presentation?: CreateModalPresentationValue; }; /** @@ -40,13 +47,22 @@ export function CreateModalFrameView({ dialogRef, children, belowCard, + presentation = "dialog", }: CreateModalFrameViewProps) { if (!isOpen) return null; + const isSheet = presentation === "sheet"; + const overlayLayout = isSheet + ? "flex flex-col items-stretch justify-end overflow-hidden p-0 md:items-center md:justify-center md:gap-6 md:overflow-y-auto md:px-4 md:py-8" + : "flex flex-col items-center justify-center gap-6 overflow-y-auto px-4 py-8"; + const dialogShell = isSheet + ? "flex h-dvh max-h-dvh min-h-0 w-full shrink-0 flex-col overflow-hidden rounded-none bg-[var(--color-surface-default-primary)] shadow-[0px_0px_48px_0px_rgba(0,0,0,0.1)] z-[9999] md:h-auto md:max-h-[90vh] md:w-[546px] md:max-w-[546px] md:rounded-[var(--radius-500)]" + : "flex min-h-0 max-h-[90vh] w-full max-w-[560px] shrink-0 flex-col overflow-hidden rounded-[var(--radius-500)] bg-[var(--color-surface-default-primary)] shadow-[0px_0px_48px_0px_rgba(0,0,0,0.1)] z-[9999]"; + const content = (
@@ -56,7 +72,7 @@ export function CreateModalFrameView({ aria-modal="true" aria-label={ariaLabel} aria-labelledby={ariaLabelledBy} - className={`flex min-h-0 max-h-[90vh] w-full max-w-[560px] shrink-0 flex-col overflow-hidden rounded-[var(--radius-500)] bg-[var(--color-surface-default-primary)] shadow-[0px_0px_48px_0px_rgba(0,0,0,0.1)] z-[9999] ${className}`} + className={`${dialogShell} ${className}`} onClick={(e) => e.stopPropagation()} > {children} diff --git a/app/components/modals/DeleteAccount/DeleteAccount.container.tsx b/app/components/modals/DeleteAccount/DeleteAccount.container.tsx new file mode 100644 index 0000000..b44fd85 --- /dev/null +++ b/app/components/modals/DeleteAccount/DeleteAccount.container.tsx @@ -0,0 +1,60 @@ +"use client"; + +/** + * Figma: Overlay / Modal / Delete Account (24985:1959) + * https://www.figma.com/design/agv0VBLiBlcnSAaiAORgPR/Community-Rule-System?node-id=24985-1959 + */ +import { memo, useEffect, useId, useRef, useState } from "react"; +import { useMessages } from "../../../contexts/MessagesContext"; +import { useCreateModalA11y } from "../Create/useCreateModalA11y"; +import { DeleteAccountView } from "./DeleteAccount.view"; +import type { DeleteAccountProps } from "./DeleteAccount.types"; + +const DeleteAccountContainer = memo((props) => { + const { + isOpen, + onClose, + onConfirm, + busy = false, + rules, + onExportPdf, + onExportMarkdown, + className = "", + backdropVariant = "blurredYellow", + } = props; + const dialogRef = useRef(null); + const overlayRef = useRef(null); + const titleId = useId(); + const copy = useMessages().modals.deleteAccount; + const [understood, setUnderstood] = useState(false); + + useCreateModalA11y(isOpen, busy ? () => undefined : onClose, dialogRef); + + useEffect(() => { + if (!isOpen) setUnderstood(false); + }, [isOpen]); + + return ( + + ); +}); + +DeleteAccountContainer.displayName = "DeleteAccount"; + +export default DeleteAccountContainer; diff --git a/app/components/modals/DeleteAccount/DeleteAccount.types.ts b/app/components/modals/DeleteAccount/DeleteAccount.types.ts new file mode 100644 index 0000000..28f35f9 --- /dev/null +++ b/app/components/modals/DeleteAccount/DeleteAccount.types.ts @@ -0,0 +1,50 @@ +import type { RefObject } from "react"; +import type { CreateModalBackdropVariant } from "../Create/CreateModalFrame.view"; + +export type DeleteAccountRule = { + id: string; + title: string; +}; + +export type DeleteAccountProps = { + isOpen: boolean; + onClose: () => void; + onConfirm: () => void; + busy?: boolean; + rules: DeleteAccountRule[]; + onExportPdf: (_id: string) => void; + onExportMarkdown: (_id: string) => void; + className?: string; + backdropVariant?: CreateModalBackdropVariant; +}; + +export type DeleteAccountCopy = { + title: string; + description: string; + yourRules: string; + exportPdf: string; + exportMarkdown: string; + confirmLabel: string; + confirmHint: string; + cancel: string; + confirm: string; + closeDialogAriaLabel: string; +}; + +export type DeleteAccountViewProps = { + isOpen: boolean; + onClose: () => void; + onConfirm: () => void; + busy: boolean; + rules: DeleteAccountRule[]; + onExportPdf: (_id: string) => void; + onExportMarkdown: (_id: string) => void; + className: string; + backdropVariant: CreateModalBackdropVariant; + dialogRef: RefObject; + overlayRef: RefObject; + titleId: string; + copy: DeleteAccountCopy; + understood: boolean; + onUnderstoodChange: (_checked: boolean) => void; +}; diff --git a/app/components/modals/DeleteAccount/DeleteAccount.view.tsx b/app/components/modals/DeleteAccount/DeleteAccount.view.tsx new file mode 100644 index 0000000..000ef82 --- /dev/null +++ b/app/components/modals/DeleteAccount/DeleteAccount.view.tsx @@ -0,0 +1,139 @@ +"use client"; + +import { memo } from "react"; +import Avatar from "../../asset/Avatar"; +import Icon from "../../asset/icon"; +import Button from "../../buttons/Button"; +import Checkbox from "../../controls/Checkbox"; +import { CreateModalFrameView } from "../Create/CreateModalFrame.view"; +import ModalHeader from "../ModalHeader"; +import ContentLockup from "../../type/ContentLockup"; +import { communityInviteInitials } from "../../../../lib/create/ruleInviteCardMeta"; +import type { DeleteAccountViewProps } from "./DeleteAccount.types"; + +export const DeleteAccountView = memo(function DeleteAccountView({ + isOpen, + onClose, + onConfirm, + busy, + rules, + onExportPdf, + onExportMarkdown, + className, + backdropVariant, + dialogRef, + overlayRef, + titleId, + copy, + understood, + onUnderstoodChange, +}: DeleteAccountViewProps) { + return ( + undefined : onClose} + backdropVariant={backdropVariant} + presentation="sheet" + className={className} + ariaLabel={copy.title} + ariaLabelledBy={titleId} + overlayRef={overlayRef} + dialogRef={dialogRef} + > + + +
+ +
+ +
+

+ {copy.yourRules} +

+ {rules.map((rule) => ( +
+ +

+ {rule.title} +

+
+ + +
+
+ ))} + onUnderstoodChange(data.checked)} + /> +
+ +
+ + +
+
+ ); +}); + +DeleteAccountView.displayName = "DeleteAccountView"; diff --git a/app/components/modals/DeleteAccount/index.tsx b/app/components/modals/DeleteAccount/index.tsx new file mode 100644 index 0000000..5692653 --- /dev/null +++ b/app/components/modals/DeleteAccount/index.tsx @@ -0,0 +1,5 @@ +export { default } from "./DeleteAccount.container"; +export type { + DeleteAccountProps, + DeleteAccountRule, +} from "./DeleteAccount.types"; diff --git a/app/components/modals/Share/Share.container.tsx b/app/components/modals/Share/Share.container.tsx index fcf2f55..2a309f0 100644 --- a/app/components/modals/Share/Share.container.tsx +++ b/app/components/modals/Share/Share.container.tsx @@ -1,62 +1,335 @@ "use client"; /** - * Figma: Community Rule System — "Modal / Share" - * https://www.figma.com/design/agv0VBLiBlcnSAaiAORgPR/Community-Rule-System?node-id=22073-30884 - * Copy-link hover / Copied! : 23769:27494 / 23769:27443 + * Figma: Overlay / Modal / Share (24972:2094) + * https://www.figma.com/design/agv0VBLiBlcnSAaiAORgPR/Community-Rule-System?node-id=24972-2094 */ import { memo, useCallback, useEffect, useId, useRef, useState } from "react"; -import { useTranslation } from "../../../contexts/MessagesContext"; +import { useMessages } from "../../../contexts/MessagesContext"; +import { + addRuleStakeholder, + fetchRuleShare, + patchRuleShare, +} from "../../../../lib/create/api"; +import { MAX_STAKEHOLDER_EMAILS } from "../../../../lib/create/stakeholderLimits"; +import { + formatInviteCountWord, + parseInvitePaste, +} from "../../../../lib/create/parseInviteEmails"; +import { + emailInitials, + visibleShareReaders, + type RuleShareSettings, +} from "../../../../lib/ruleShareTypes"; +import { RULE_VISIBILITY } from "../../../../lib/ruleVisibility"; import { useCreateModalA11y } from "../Create/useCreateModalA11y"; import { ShareView } from "./Share.view"; -import type { ShareProps } from "./Share.types"; +import type { SharePhase, ShareProps } from "./Share.types"; + +function selectValueFor( + visibility: RuleShareSettings["visibility"], + phase: SharePhase, +): "private" | "shared_by_link" { + if (phase === "confirm" || phase === "error") return "shared_by_link"; + if (visibility === RULE_VISIBILITY.private) return "private"; + return "shared_by_link"; +} + +function titleCountWord(n: number): string { + const word = formatInviteCountWord(n); + return word.charAt(0).toUpperCase() + word.slice(1); +} const ShareContainer = memo((props) => { + const { + isOpen, + onClose, + ruleId = null, + previewSettings, + onRequestLogin, + className = "", + backdropVariant = "blurredYellow", + } = props; const dialogRef = useRef(null); const overlayRef = useRef(null); const titleId = useId(); - const t = useTranslation("modals.share"); + const copy = useMessages().modals.share; + + const [settings, setSettings] = useState( + previewSettings ?? null, + ); + const [phase, setPhase] = useState("idle"); + const [communityAgreed, setCommunityAgreed] = useState(false); + const [inviteValue, setInviteValue] = useState(""); + const [inviteBusy, setInviteBusy] = useState(false); + const [inviteError, setInviteError] = useState(null); + const [turnOnBusy, setTurnOnBusy] = useState(false); const [linkCopied, setLinkCopied] = useState(false); - useCreateModalA11y(props.isOpen, props.onClose, dialogRef); + useCreateModalA11y(isOpen, onClose, dialogRef); useEffect(() => { - if (!props.isOpen) { + if (!isOpen) { + setPhase("idle"); + setCommunityAgreed(false); + setInviteValue(""); + setInviteError(null); setLinkCopied(false); + setTurnOnBusy(false); + if (!previewSettings) setSettings(null); + return; } - }, [props.isOpen]); - - const onCopyLinkClick = useCallback(async () => { - try { - const result = await props.onCopyLink(); - if (result !== false) { - setLinkCopied(true); + if (previewSettings) { + setSettings(previewSettings); + return; + } + if (!ruleId) return; + let cancelled = false; + void (async () => { + const res = await fetchRuleShare(ruleId); + if (cancelled) return; + if (res.ok === false) { + if (res.status === 401) { + onRequestLogin?.(); + onClose(); + } + return; } + setSettings(res.share); + })(); + return () => { + cancelled = true; + }; + }, [isOpen, onClose, onRequestLogin, previewSettings, ruleId]); + + const applySettings = useCallback((next: RuleShareSettings) => { + setSettings(next); + setPhase("idle"); + setCommunityAgreed(false); + }, []); + + const handleSelectValue = useCallback( + (value: string) => { + if (!settings) return; + if (value === "private") { + if ( + settings.visibility === RULE_VISIBILITY.private && + (phase === "confirm" || phase === "error") + ) { + setPhase("idle"); + setCommunityAgreed(false); + return; + } + if (settings.visibility === RULE_VISIBILITY.private) return; + if (!ruleId) { + applySettings({ + ...settings, + visibility: RULE_VISIBILITY.private, + shareSlug: null, + shareUrlDisplay: null, + }); + return; + } + void (async () => { + const res = await patchRuleShare(ruleId, "private"); + if (res.ok) applySettings(res.share); + })(); + return; + } + if (value === "shared_by_link") { + if ( + settings.visibility === RULE_VISIBILITY.shared_by_link || + settings.visibility === RULE_VISIBILITY.public_and_featured + ) { + setPhase("idle"); + return; + } + setPhase("confirm"); + setCommunityAgreed(false); + } + }, + [applySettings, phase, ruleId, settings], + ); + + const handleTurnOnLink = useCallback(async () => { + if (!settings || !communityAgreed || turnOnBusy) return; + if (!ruleId) { + applySettings({ + ...settings, + visibility: RULE_VISIBILITY.shared_by_link, + shareSlug: settings.shareSlug ?? "k7f2-9qxm", + shareUrlDisplay: + settings.shareUrlDisplay ?? "communityrule.info/r/k7f2-9qxm", + }); + return; + } + setTurnOnBusy(true); + const res = await patchRuleShare(ruleId, "shared_by_link", true); + setTurnOnBusy(false); + if (res.ok === false) { + setPhase("error"); + return; + } + applySettings(res.share); + }, [applySettings, communityAgreed, ruleId, settings, turnOnBusy]); + + const handleTurnOffLink = useCallback(async () => { + if (!settings) return; + if (!ruleId) { + applySettings({ + ...settings, + visibility: RULE_VISIBILITY.private, + shareSlug: null, + shareUrlDisplay: null, + }); + return; + } + const res = await patchRuleShare(ruleId, "private"); + if (res.ok) applySettings(res.share); + }, [applySettings, ruleId, settings]); + + const handleInvite = useCallback(async () => { + if (!settings || inviteBusy) return; + const existing = [ + settings.ownerEmail, + ...settings.readers.map((r) => r.email), + ]; + const parsed = parseInvitePaste( + inviteValue, + existing, + MAX_STAKEHOLDER_EMAILS, + ); + const email = parsed.added[0]; + if (!email) { + setInviteError(copy.inviteInvalid); + return; + } + setInviteError(null); + if (!ruleId) { + setSettings({ + ...settings, + readers: [ + ...settings.readers, + { email, initials: emailInitials(email), role: "reader" }, + ], + }); + setInviteValue(""); + return; + } + setInviteBusy(true); + const res = await addRuleStakeholder(ruleId, email); + if (res.ok === false) { + setInviteBusy(false); + setInviteError(res.error); + return; + } + const next = await fetchRuleShare(ruleId); + setInviteBusy(false); + if (next.ok) { + setSettings(next.share); + setInviteValue(""); + } + }, [copy.inviteInvalid, inviteBusy, inviteValue, ruleId, settings]); + + const handleCopyLink = useCallback(async () => { + if (!settings) return; + try { + await navigator.clipboard.writeText(settings.shareUrl); + setLinkCopied(true); } catch { setLinkCopied(false); } - }, [props.onCopyLink]); + }, [settings]); + + if (!settings) { + return ( + undefined} + inviteBusy={false} + inviteError={null} + ownerEmail="" + ownerInitials="?" + shownReaders={[]} + overflowLabel={null} + selectValue="private" + onSelectValue={() => undefined} + showLinkField={false} + shareUrlDisplay="" + onTurnOffLink={() => undefined} + showConfirm={false} + communityAgreed={false} + onCommunityAgreedChange={setCommunityAgreed} + onTurnOnLink={() => undefined} + turnOnDisabled + turnOnBusy={false} + showError={false} + copyEnabled={false} + linkCopied={false} + onCopyLink={() => undefined} + /> + ); + } + + const selectValue = selectValueFor(settings.visibility, phase); + const { shown, overflowCount } = visibleShareReaders(settings.readers); + const overflowLabel = + overflowCount > 0 + ? copy.overflowReaders.replace("{{count}}", titleCountWord(overflowCount)) + : null; + const showLinkField = + settings.visibility === RULE_VISIBILITY.shared_by_link && phase === "idle"; + const showConfirm = phase === "confirm" || phase === "error"; + const copyEnabled = phase !== "confirm" && phase !== "error"; return ( { + setInviteValue(value); + if (inviteError) setInviteError(null); + }} + onInvite={() => void handleInvite()} + inviteBusy={inviteBusy} + inviteError={inviteError} + ownerEmail={settings.ownerEmail} + ownerInitials={settings.ownerInitials} + shownReaders={shown} + overflowLabel={overflowLabel} + selectValue={selectValue} + onSelectValue={handleSelectValue} + showLinkField={showLinkField} + shareUrlDisplay={settings.shareUrlDisplay ?? ""} + onTurnOffLink={() => void handleTurnOffLink()} + showConfirm={showConfirm} + communityAgreed={communityAgreed} + onCommunityAgreedChange={setCommunityAgreed} + onTurnOnLink={() => void handleTurnOnLink()} + turnOnDisabled={!communityAgreed} + turnOnBusy={turnOnBusy} + showError={phase === "error"} + copyEnabled={copyEnabled} linkCopied={linkCopied} - onCopyLinkClick={onCopyLinkClick} - signalLabel={t("signal")} - slackLabel={t("slack")} - discordLabel={t("discord")} - emailLabel={t("email")} - doneLabel={t("done")} - closeDialogAriaLabel={t("closeDialogAriaLabel")} - moreOptionsAriaLabel={t("moreOptionsAriaLabel")} + onCopyLink={() => void handleCopyLink()} /> ); }); diff --git a/app/components/modals/Share/Share.types.ts b/app/components/modals/Share/Share.types.ts index e8d35c5..3407aa3 100644 --- a/app/components/modals/Share/Share.types.ts +++ b/app/components/modals/Share/Share.types.ts @@ -1,43 +1,85 @@ -import type { ReactNode, RefObject } from "react"; +import type { RefObject } from "react"; import type { CreateModalBackdropVariant } from "../Create/CreateModalFrame.view"; +import type { + RuleShareSettings, + SharePerson, +} from "../../../../lib/ruleShareTypes"; + +export type SharePhase = "idle" | "confirm" | "error"; export type ShareProps = { isOpen: boolean; onClose: () => void; - /** Return `false` when the clipboard write did not succeed. */ - onCopyLink: () => void | boolean | Promise; - onEmailShare: () => void; - onSignalShare: () => void | Promise; - onSlackShare: () => void | Promise; - onDiscordShare: () => void | Promise; + ruleId?: string | null; + /** Story / test seed. Skips the share API when set. */ + previewSettings?: RuleShareSettings; + onRequestLogin?: () => void; className?: string; backdropVariant?: CreateModalBackdropVariant; }; -export type ShareViewProps = ShareProps & { +export type ShareCopy = { + title: string; + addPeoplePlaceholder: string; + invite: string; + inviteInvalid: string; + peopleWithAccess: string; + you: string; + holdsThePen: string; + canRead: string; + overflowReaders: string; + whoCanRead: string; + inviteOnly: string; + inviteOnlyHint: string; + anyoneWithLink: string; + anyoneWithLinkHint: string; + confirmBody: string; + communityAgreed: string; + turnOnLink: string; + turnOffLink: string; + linkHint: string; + copyLink: string; + copied: string; + copiedLive: string; + done: string; + errorTitle: string; + errorDescription: string; + closeDialogAriaLabel: string; + accessSelectAriaLabel: string; +}; + +export type ShareViewProps = { + isOpen: boolean; + onClose: () => void; + className: string; + backdropVariant: CreateModalBackdropVariant; dialogRef: RefObject; overlayRef: RefObject; titleId: string; - title: string; - description: string; - copyLinkLabel: string; - copiedLabel: string; - copiedLive: string; + copy: ShareCopy; + communityName: string; + inviteValue: string; + onInviteValueChange: (_value: string) => void; + onInvite: () => void; + inviteBusy: boolean; + inviteError: string | null; + ownerEmail: string; + ownerInitials: string; + shownReaders: SharePerson[]; + overflowLabel: string | null; + selectValue: "private" | "shared_by_link"; + onSelectValue: (_value: string) => void; + showLinkField: boolean; + shareUrlDisplay: string; + onTurnOffLink: () => void; + showConfirm: boolean; + communityAgreed: boolean; + onCommunityAgreedChange: (_checked: boolean) => void; + onTurnOnLink: () => void; + turnOnDisabled: boolean; + turnOnBusy: boolean; + showError: boolean; + copyEnabled: boolean; linkCopied: boolean; - onCopyLinkClick: () => void | Promise; - signalLabel: string; - slackLabel: string; - discordLabel: string; - emailLabel: string; - doneLabel: string; - closeDialogAriaLabel: string; - moreOptionsAriaLabel: string; -}; - -export type ShareChannelTileProps = { - label: string; - onClick: () => void | Promise; - circleClassName: string; - icon: ReactNode; - copied?: boolean; + onCopyLink: () => void; }; diff --git a/app/components/modals/Share/Share.view.tsx b/app/components/modals/Share/Share.view.tsx index 4e40d40..7a4a25b 100644 --- a/app/components/modals/Share/Share.view.tsx +++ b/app/components/modals/Share/Share.view.tsx @@ -7,26 +7,26 @@ import { shareIconPath, type ShareIconName, } from "../../../../lib/assetUtils"; -import ContentLockup from "../../type/ContentLockup"; +import Avatar from "../../asset/Avatar"; import Button from "../../buttons/Button"; -import ModalHeader from "../ModalHeader"; -import ModalFooter from "../ModalFooter"; +import Checkbox from "../../controls/Checkbox"; +import SelectInput from "../../controls/SelectInput"; +import TextInput from "../../controls/TextInput"; +import Alert from "../Alert"; import { CreateModalFrameView } from "../Create/CreateModalFrame.view"; -import type { ShareChannelTileProps, ShareViewProps } from "./Share.types"; +import ModalHeader from "../ModalHeader"; +import ContentLockup from "../../type/ContentLockup"; +import type { SharePerson } from "../../../../lib/ruleShareTypes"; +import type { ShareViewProps } from "./Share.types"; -/** Decorative glyphs in `public/assets/share/` — sizes match prior inline SVGs within the 60×60 circles. */ -function ShareAssetIcon(props: { - name: ShareIconName; - width: number; - height: number; -}) { - const { name, width, height } = props; +function ShareGlyph(props: { name: ShareIconName; size?: number }) { + const size = props.size ?? 24; return ( void onClick()} - aria-pressed={copied || undefined} - className="group flex w-16 shrink-0 flex-col items-center gap-2 rounded-md 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)]" - > -
- {icon} +
+ +
+

+ {props.title} +

+ {props.subtitle ? ( +

+ {props.subtitle} +

+ ) : null}
- - {label} - - +

+ {props.roleLabel} +

+
+ ); +} + +function ReaderRow({ reader, roleLabel }: { reader: SharePerson; roleLabel: string }) { + return ( + ); } export const ShareView = memo(function ShareView({ isOpen, onClose, - onEmailShare, - onSignalShare, - onSlackShare, - onDiscordShare, - className = "", - backdropVariant = "blurredYellow", + className, + backdropVariant, dialogRef, overlayRef, titleId, - title, - description, - copyLinkLabel, - copiedLabel, - copiedLive, + copy, + communityName, + inviteValue, + onInviteValueChange, + onInvite, + inviteBusy, + inviteError, + ownerEmail, + ownerInitials, + shownReaders, + overflowLabel, + selectValue, + onSelectValue, + showLinkField, + shareUrlDisplay, + onTurnOffLink, + showConfirm, + communityAgreed, + onCommunityAgreedChange, + onTurnOnLink, + turnOnDisabled, + turnOnBusy, + showError, + copyEnabled, linkCopied, - onCopyLinkClick, - signalLabel, - slackLabel, - discordLabel, - emailLabel, - doneLabel, - closeDialogAriaLabel, - moreOptionsAriaLabel, + onCopyLink, }: ShareViewProps) { + const linkOn = selectValue === "shared_by_link"; + return ( -
+
-
- {/* Channel circle hexes are third-party brand colors (copy/link, Signal, Slack, Discord), not DS tokens. */} -
- - } - /> - } - /> - } - /> - } - /> - } - /> +
+
+
+ onInviteValueChange(e.target.value)} + onKeyDown={(e) => { + if (e.key === "Enter") { + e.preventDefault(); + onInvite(); + } + }} + /> +
+
-

- {linkCopied ? copiedLive : ""} -

-
+ {inviteError ? ( +

+ {inviteError} +

+ ) : null} - +
+

+ {copy.peopleWithAccess} +

+ + {shownReaders.map((reader) => ( + + ))} + {overflowLabel ? ( +

+ {overflowLabel} +

+ ) : null} +
+ +
+

+ {copy.whoCanRead} +

+
+ +
+ onSelectValue(data.target.value)} + options={[ + { value: "private", label: copy.inviteOnly }, + { value: "shared_by_link", label: copy.anyoneWithLink }, + ]} + /> +
+
+ {!showConfirm && !showError ? ( +

+ {linkOn ? copy.anyoneWithLinkHint : copy.inviteOnlyHint} +

+ ) : null} +
+ + {showLinkField ? ( +
+
- } - /> + ) : null} + + {showConfirm || showError ? ( +
+ {showError ? ( + + ) : null} +

+ {copy.confirmBody} +

+ onCommunityAgreedChange(data.checked)} + /> + +
+ ) : null} + + {linkCopied ? ( + + ) : null} +
+ +
+ + +
); }); diff --git a/lib/assetUtils.ts b/lib/assetUtils.ts index d4df3c3..731c95a 100644 --- a/lib/assetUtils.ts +++ b/lib/assetUtils.ts @@ -89,7 +89,9 @@ export function partnerLogoPath(slug: string): string { export type ShareIconName = | "check" | "discord" + | "language" | "link" + | "lock" | "mail" | "signal" | "slack"; diff --git a/lib/create/api.ts b/lib/create/api.ts index 760e6ec..928f337 100644 --- a/lib/create/api.ts +++ b/lib/create/api.ts @@ -1,4 +1,6 @@ import type { CreateFlowState } from "../../app/(app)/create/types"; +import type { RuleShareSettings } from "../ruleShareTypes"; +import { isRuleVisibility } from "../ruleVisibility"; import { migrateLegacyCreateFlowState } from "./migrateLegacyCreateFlowState"; const jsonHeaders = { "Content-Type": "application/json" }; @@ -750,6 +752,108 @@ export async function duplicateUseCaseTemplate( } } +export type FetchRuleShareResult = + | { ok: true; share: RuleShareSettings } + | { ok: false; status: number; error: string }; + +function isRuleShareSettings(value: unknown): value is RuleShareSettings { + if (!value || typeof value !== "object") return false; + const o = value as Record; + return ( + isRuleVisibility(o.visibility) && + typeof o.shareUrl === "string" && + typeof o.title === "string" && + typeof o.ownerEmail === "string" && + Array.isArray(o.readers) + ); +} + +export async function fetchRuleShare( + ruleId: string, +): Promise { + try { + const res = await fetch( + `/api/rules/${encodeURIComponent(ruleId)}/share`, + { credentials: "include" }, + ); + if (!res.ok) { + const data = await safeParseJsonResponse(res); + return { + ok: false as const, + status: res.status, + error: readApiErrorMessage(data), + }; + } + const data = await safeParseJsonResponse(res); + const share = + data && typeof data === "object" && "share" in data + ? (data as { share: unknown }).share + : null; + if (!isRuleShareSettings(share)) { + return { + ok: false as const, + status: res.status, + error: DRAFT_SAVE_NETWORK_ERROR, + }; + } + return { ok: true as const, share }; + } catch { + return { + ok: false as const, + status: 0, + error: DRAFT_SAVE_NETWORK_ERROR, + }; + } +} + +export async function patchRuleShare( + ruleId: string, + visibility: "private" | "shared_by_link", + communityAgreed?: boolean, +): Promise { + try { + const res = await fetch( + `/api/rules/${encodeURIComponent(ruleId)}/share`, + { + method: "PATCH", + credentials: "include", + headers: jsonHeaders, + body: JSON.stringify({ + visibility, + ...(communityAgreed !== undefined ? { communityAgreed } : {}), + }), + }, + ); + if (!res.ok) { + const data = await safeParseJsonResponse(res); + return { + ok: false as const, + status: res.status, + error: readApiErrorMessage(data), + }; + } + const data = await safeParseJsonResponse(res); + const share = + data && typeof data === "object" && "share" in data + ? (data as { share: unknown }).share + : null; + if (!isRuleShareSettings(share)) { + return { + ok: false as const, + status: res.status, + error: DRAFT_SAVE_NETWORK_ERROR, + }; + } + return { ok: true as const, share }; + } catch { + return { + ok: false as const, + status: 0, + error: DRAFT_SAVE_NETWORK_ERROR, + }; + } +} + export type DeleteAccountResult = { ok: true } | { ok: false; error: string }; /** diff --git a/messages/en/index.ts b/messages/en/index.ts index faa971c..e079c12 100644 --- a/messages/en/index.ts +++ b/messages/en/index.ts @@ -38,6 +38,7 @@ import invite from "./pages/invite.json"; import navigation from "./navigation.json"; import metadata from "./metadata.json"; import modalsShare from "./modals/share.json"; +import modalsDeleteAccount from "./modals/deleteAccount.json"; import modalsPopoverExport from "./modals/popoverExport.json"; import modalsAskOrganizerInquiry from "./modals/askOrganizerInquiry.json"; @@ -159,6 +160,7 @@ export default { metadata, modals: { share: modalsShare, + deleteAccount: modalsDeleteAccount, popoverExport: modalsPopoverExport, askOrganizerInquiry: modalsAskOrganizerInquiry, }, diff --git a/messages/en/modals/deleteAccount.json b/messages/en/modals/deleteAccount.json new file mode 100644 index 0000000..5984d49 --- /dev/null +++ b/messages/en/modals/deleteAccount.json @@ -0,0 +1,13 @@ +{ + "_comment": "Overlay / Modal / Delete Account 24985:1959", + "title": "Delete your account", + "description": "This deletes your account and every Rule you made. The people you invited lose access to them. Export any Rule you want to keep first.", + "yourRules": "Your Rules", + "exportPdf": "PDF", + "exportMarkdown": "RULE.md", + "confirmLabel": "I understand this can’t be undone", + "confirmHint": "Tick this to continue.", + "cancel": "Cancel", + "confirm": "Delete account", + "closeDialogAriaLabel": "Close" +} diff --git a/messages/en/modals/share.json b/messages/en/modals/share.json index ea7af0b..93c767c 100644 --- a/messages/en/modals/share.json +++ b/messages/en/modals/share.json @@ -1,14 +1,30 @@ { - "title": "Share this CommunityRule", - "description": "Anyone with the link can view this rule.", + "_comment": "Overlay / Modal / Share 24972:2094", + "title": "Share this Rule", + "addPeoplePlaceholder": "Add people by email", + "invite": "Invite", + "inviteInvalid": "Enter an email address.", + "peopleWithAccess": "People with access", + "you": "You", + "holdsThePen": "Holds the pen", + "canRead": "Can read", + "overflowReaders": "{{count}} more people can read it", + "whoCanRead": "Who can read this Rule", + "inviteOnly": "Only people you invite", + "inviteOnlyHint": "Only people you invite can open it.", + "anyoneWithLink": "Anyone with the link", + "anyoneWithLinkHint": "Anyone with the link can read it without logging in. They can pass it on.", + "confirmBody": "Anyone with the link can read it without logging in and pass it on. Check with your community first.", + "communityAgreed": "Our community agreed to share this Rule", + "turnOnLink": "Turn on link", + "turnOffLink": "Turn off link", + "linkHint": "Turning the link off stops it working. Turning it on again makes a new one.", "copyLink": "Copy link", - "copied": "Copied!", - "copiedLive": "Link copied to clipboard", - "signal": "Signal", - "slack": "Slack", - "discord": "Discord", - "email": "Email", + "copied": "Copied", + "copiedLive": "Link copied", "done": "Done", + "errorTitle": "The link didn’t turn on", + "errorDescription": "Check your connection and try again.", "closeDialogAriaLabel": "Close", - "moreOptionsAriaLabel": "More share options" + "accessSelectAriaLabel": "Who can read this Rule" } diff --git a/public/assets/share/language.svg b/public/assets/share/language.svg new file mode 100644 index 0000000..2a32bfa --- /dev/null +++ b/public/assets/share/language.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/public/assets/share/lock.svg b/public/assets/share/lock.svg new file mode 100644 index 0000000..3ff65a3 --- /dev/null +++ b/public/assets/share/lock.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/stories/modals/DeleteAccount.stories.js b/stories/modals/DeleteAccount.stories.js new file mode 100644 index 0000000..be90d8d --- /dev/null +++ b/stories/modals/DeleteAccount.stories.js @@ -0,0 +1,47 @@ +import React, { useState } from "react"; +import DeleteAccount from "../../app/components/modals/DeleteAccount"; + +/** Figma: Overlay / Modal / Delete Account — node 24985-1959. */ +export default { + title: "Components/Modals/DeleteAccount", + component: DeleteAccount, + parameters: { + layout: "fullscreen", + docs: { + description: { + component: + "Account deletion lists each owned Rule with PDF and RULE.md export, then requires a confirmation checkbox.", + }, + }, + }, +}; + +function DeleteAccountStoryHost() { + const [open, setOpen] = useState(true); + return ( +
+ + setOpen(false)} + onConfirm={() => setOpen(false)} + rules={[ + { id: "rule-1", title: "Juniper Street Food Share" }, + { id: "rule-2", title: "Mutual Aid Colorado" }, + ]} + onExportPdf={() => undefined} + onExportMarkdown={() => undefined} + /> +
+ ); +} + +export const Default = { + render: () => , +}; diff --git a/stories/modals/Share.stories.js b/stories/modals/Share.stories.js index 231d459..e1cf1bd 100644 --- a/stories/modals/Share.stories.js +++ b/stories/modals/Share.stories.js @@ -1,7 +1,7 @@ import React, { useState } from "react"; import Share from "../../app/components/modals/Share"; -/** Figma: Modal / Share — node 22073-30884 (Community Rule System). */ +/** Figma: Overlay / Modal / Share — node 24972-2094. */ export default { title: "Components/Modals/Share", component: Share, @@ -10,12 +10,31 @@ export default { docs: { description: { component: - "Share modal for published rules (copy link and channel actions).", + "Share settings for a finished Rule: invite people, confirm a link, or copy it.", }, }, }, }; +const previewSettings = { + visibility: "private", + shareSlug: null, + shareUrl: "https://communityrule.info/rules/rule-1", + shareUrlDisplay: null, + title: "Juniper Street Food Share", + ownerEmail: "name@example.org", + ownerInitials: "N", + readers: [ + { email: "rosa@example.org", initials: "R", role: "reader" }, + { email: "a@example.org", initials: "A", role: "reader" }, + { email: "b@example.org", initials: "B", role: "reader" }, + { email: "c@example.org", initials: "C", role: "reader" }, + { email: "d@example.org", initials: "D", role: "reader" }, + { email: "e@example.org", initials: "E", role: "reader" }, + ], + copyEnabled: true, +}; + function ShareStoryHost() { const [open, setOpen] = useState(true); return ( @@ -30,11 +49,7 @@ function ShareStoryHost() { setOpen(false)} - onCopyLink={() => {}} - onEmailShare={() => {}} - onSignalShare={() => {}} - onSlackShare={() => {}} - onDiscordShare={() => {}} + previewSettings={previewSettings} />
); @@ -43,3 +58,19 @@ function ShareStoryHost() { export const Default = { render: () => , }; + +export const AnyoneWithTheLink = { + render: () => ( + undefined} + previewSettings={{ + ...previewSettings, + visibility: "shared_by_link", + shareSlug: "k7f2-9qxm", + shareUrl: "https://communityrule.info/r/k7f2-9qxm", + shareUrlDisplay: "communityrule.info/r/k7f2-9qxm", + }} + /> + ), +}; diff --git a/tests/components/modals/DeleteAccount.test.tsx b/tests/components/modals/DeleteAccount.test.tsx new file mode 100644 index 0000000..47d26e9 --- /dev/null +++ b/tests/components/modals/DeleteAccount.test.tsx @@ -0,0 +1,53 @@ +import { describe, it, expect, vi } from "vitest"; +import userEvent from "@testing-library/user-event"; +import { renderWithProviders as render, screen } from "../../utils/test-utils"; +import "@testing-library/jest-dom/vitest"; +import DeleteAccount from "../../../app/components/modals/DeleteAccount"; + +describe("DeleteAccount modal", () => { + it("does not render dialog when closed", () => { + render( + , + ); + expect(screen.queryByRole("dialog")).not.toBeInTheDocument(); + }); + + it("keeps Delete account disabled until the box is ticked", async () => { + const user = userEvent.setup(); + const onConfirm = vi.fn(); + const onExportPdf = vi.fn(); + render( + , + ); + expect( + screen.getByRole("heading", { level: 1, name: "Delete your account" }), + ).toBeInTheDocument(); + expect(screen.getByText("Juniper Street Food Share")).toBeInTheDocument(); + const confirm = screen.getByRole("button", { name: "Delete account" }); + expect(confirm).toBeDisabled(); + await user.click(screen.getByRole("button", { name: "PDF" })); + expect(onExportPdf).toHaveBeenCalledWith("rule-1"); + await user.click( + screen.getByRole("checkbox", { + name: "I understand this can’t be undone", + }), + ); + expect(confirm).toBeEnabled(); + await user.click(confirm); + expect(onConfirm).toHaveBeenCalledTimes(1); + }); +}); diff --git a/tests/components/modals/Share.test.tsx b/tests/components/modals/Share.test.tsx index 1da950d..8410458 100644 --- a/tests/components/modals/Share.test.tsx +++ b/tests/components/modals/Share.test.tsx @@ -1,117 +1,149 @@ -import { describe, it, expect, vi } from "vitest"; +import { describe, it, expect, vi, beforeEach } from "vitest"; import userEvent from "@testing-library/user-event"; -import { renderWithProviders as render, screen } from "../../utils/test-utils"; +import { fireEvent } from "@testing-library/react"; +import { + renderWithProviders as render, + screen, + waitFor, +} from "../../utils/test-utils"; import "@testing-library/jest-dom/vitest"; import Share from "../../../app/components/modals/Share"; +import type { RuleShareSettings } from "../../../lib/ruleShareTypes"; -const noopHandlers = { - onCopyLink: vi.fn(), - onEmailShare: vi.fn(), - onSignalShare: vi.fn(), - onSlackShare: vi.fn(), - onDiscordShare: vi.fn(), +const previewSettings: RuleShareSettings = { + visibility: "private", + shareSlug: null, + shareUrl: "https://communityrule.info/rules/rule-1", + shareUrlDisplay: null, + title: "Juniper Street Food Share", + ownerEmail: "name@example.org", + ownerInitials: "N", + readers: [ + { email: "rosa@example.org", initials: "R", role: "reader" }, + { email: "a@example.org", initials: "A", role: "reader" }, + { email: "b@example.org", initials: "B", role: "reader" }, + { email: "c@example.org", initials: "C", role: "reader" }, + { email: "d@example.org", initials: "D", role: "reader" }, + { email: "e@example.org", initials: "E", role: "reader" }, + ], + copyEnabled: true, }; +function openShare(overrides: Partial = {}) { + return render( + , + ); +} + +const writeText = vi.fn().mockResolvedValue(undefined); + +beforeEach(() => { + writeText.mockReset(); + writeText.mockResolvedValue(undefined); + Object.defineProperty(window.navigator, "clipboard", { + configurable: true, + value: { writeText }, + }); +}); + describe("Share modal", () => { it("does not render dialog when closed", () => { render( - , + , ); expect(screen.queryByRole("dialog")).not.toBeInTheDocument(); }); - it("renders localized heading and copy link action when open", async () => { - const user = userEvent.setup(); - const onCopyLink = vi.fn(); - render( - , - ); + it("renders invite-only copy and people with access", () => { + openShare(); expect(screen.getByRole("dialog")).toBeInTheDocument(); expect( - screen.getByRole("heading", { level: 1, name: /Share this CommunityRule/ }), + screen.getByRole("heading", { level: 1, name: "Share this Rule" }), ).toBeInTheDocument(); - await user.click(screen.getByRole("button", { name: "Copy link" })); - expect(onCopyLink).toHaveBeenCalledTimes(1); + expect(screen.getByText("Juniper Street Food Share")).toBeInTheDocument(); + expect(screen.getByText("You")).toBeInTheDocument(); + expect(screen.getByText("rosa@example.org")).toBeInTheDocument(); + expect(screen.getByText("Five more people can read it")).toBeInTheDocument(); + expect(screen.getByText("Only people you invite can open it.")).toBeInTheDocument(); }); - it("invokes channel handlers for Signal, Slack, and Discord", async () => { - const user = userEvent.setup(); - const onSignalShare = vi.fn(); - const onSlackShare = vi.fn(); - const onDiscordShare = vi.fn(); - render( - , + it("copies the private Rule URL", async () => { + openShare(); + fireEvent.click(screen.getByRole("button", { name: /Copy link/i })); + await waitFor(() => { + expect(screen.getByText("Link copied")).toBeInTheDocument(); + }); + expect(writeText).toHaveBeenCalledWith( + "https://communityrule.info/rules/rule-1", ); - await user.click(screen.getByRole("button", { name: "Signal" })); - await user.click(screen.getByRole("button", { name: "Slack" })); - await user.click(screen.getByRole("button", { name: "Discord" })); - expect(onSignalShare).toHaveBeenCalledTimes(1); - expect(onSlackShare).toHaveBeenCalledTimes(1); - expect(onDiscordShare).toHaveBeenCalledTimes(1); + expect(screen.getByRole("button", { name: /Copied/i })).toHaveAttribute( + "aria-pressed", + "true", + ); + }); + + it("asks for community agreement before turning a link on", async () => { + const user = userEvent.setup(); + openShare(); + await user.click(screen.getByRole("button", { name: /Only people you invite/i })); + await user.click( + await screen.findByRole("option", { name: "Anyone with the link" }), + ); + expect( + screen.getByText( + "Anyone with the link can read it without logging in and pass it on. Check with your community first.", + ), + ).toBeInTheDocument(); + expect(screen.getByRole("button", { name: "Turn on link" })).toBeDisabled(); + expect(screen.getByRole("button", { name: /Copy link/i })).toBeDisabled(); + await user.click( + screen.getByRole("checkbox", { + name: "Our community agreed to share this Rule", + }), + ); + expect(screen.getByRole("button", { name: "Turn on link" })).toBeEnabled(); + }); + + it("turns the preview link on after community agreement", async () => { + const user = userEvent.setup(); + openShare(); + await user.click(screen.getByRole("button", { name: /Only people you invite/i })); + await user.click( + await screen.findByRole("option", { name: "Anyone with the link" }), + ); + await user.click( + screen.getByRole("checkbox", { + name: "Our community agreed to share this Rule", + }), + ); + await user.click(screen.getByRole("button", { name: "Turn on link" })); + expect( + screen.getByDisplayValue("communityrule.info/r/k7f2-9qxm"), + ).toBeInTheDocument(); + expect( + screen.getByRole("button", { name: "Turn off link" }), + ).toBeInTheDocument(); }); it("calls onClose when Done is clicked", async () => { const user = userEvent.setup(); const onClose = vi.fn(); - render(); + render( + , + ); await user.click(screen.getByRole("button", { name: "Done" })); expect(onClose).toHaveBeenCalledTimes(1); }); - - it("confirms Copy link with Copied! when the handler succeeds", async () => { - const user = userEvent.setup(); - const onCopyLink = vi.fn().mockResolvedValue(true); - render( - , - ); - await user.click(screen.getByRole("button", { name: "Copy link" })); - expect(onCopyLink).toHaveBeenCalledTimes(1); - expect(screen.getByRole("button", { name: "Copied!" })).toHaveAttribute( - "aria-pressed", - "true", - ); - expect(screen.getByText("Link copied to clipboard")).toBeInTheDocument(); - }); - - it("keeps Copy link when the handler reports failure", async () => { - const user = userEvent.setup(); - render( - , - ); - await user.click(screen.getByRole("button", { name: "Copy link" })); - expect(screen.getByRole("button", { name: "Copy link" })).toBeInTheDocument(); - expect( - screen.queryByRole("button", { name: "Copied!" }), - ).not.toBeInTheDocument(); - }); - - it("calls onClose when header overflow (more) is activated, matching modal chrome parity", async () => { - const user = userEvent.setup(); - const onClose = vi.fn(); - render(); - await user.click(screen.getByRole("button", { name: "More share options" })); - expect(onClose).toHaveBeenCalledTimes(1); - }); }); diff --git a/tests/pages/profile.test.tsx b/tests/pages/profile.test.tsx index 88ffb34..f4cd53e 100644 --- a/tests/pages/profile.test.tsx +++ b/tests/pages/profile.test.tsx @@ -61,6 +61,8 @@ function viewProps( onOpenDeleteAccount: vi.fn(), onCloseDeleteAccount: vi.fn(), onConfirmDeleteAccount: vi.fn(), + onExportRulePdf: vi.fn(), + onExportRuleMarkdown: vi.fn(), onDismissProfileSuccess: vi.fn(), onDismissActionError: vi.fn(), onDismissRulesError: vi.fn(), @@ -127,12 +129,13 @@ describe("ProfilePageView", () => { ); const dialog = screen.getByRole("dialog", { - name: copy.deleteAccountModalTitle, + name: messages.modals.deleteAccount.title, }); - expect(dialog).toHaveTextContent(copy.deleteAccountModalBody); + expect(dialog).toHaveTextContent(messages.modals.deleteAccount.description); const confirm = within(dialog).getByRole("button", { - name: copy.deleteAccountConfirm, + name: messages.modals.deleteAccount.confirm, }); + expect(confirm).toBeDisabled(); expect(confirm.className).toContain( "border-[var(--color-border-default-negative-primary)]", ); @@ -140,6 +143,12 @@ describe("ProfilePageView", () => { "bg-[var(--color-surface-invert-primary)]", ); + await user.click( + within(dialog).getByRole("checkbox", { + name: messages.modals.deleteAccount.confirmLabel, + }), + ); + expect(confirm).toBeEnabled(); await user.click(confirm); expect(onConfirmDeleteAccount).toHaveBeenCalledTimes(1); }); diff --git a/tests/pages/use-cases-completed-rule.test.jsx b/tests/pages/use-cases-completed-rule.test.jsx index fc1cf1b..e6e28a4 100644 --- a/tests/pages/use-cases-completed-rule.test.jsx +++ b/tests/pages/use-cases-completed-rule.test.jsx @@ -118,6 +118,27 @@ describe("UseCaseCompletedRulePage", () => { ); }); + test("Share copies the page link through a banner instead of a privacy modal", async () => { + const user = userEvent.setup(); + const writeText = vi.fn().mockResolvedValue(undefined); + Object.defineProperty(window.navigator, "clipboard", { + configurable: true, + value: { writeText }, + }); + + render( + await UseCaseCompletedRulePage({ + params: Promise.resolve({ slug: "food-not-bombs" }), + }), + ); + + await user.click(screen.getByRole("button", { name: "Share" })); + expect(writeText).toHaveBeenCalled(); + expect(screen.getByText("Link copied")).toBeInTheDocument(); + expect(screen.queryByRole("dialog")).not.toBeInTheDocument(); + }); + + test("Share button reads Share under the marketing case-study bundle", async () => { rtlRender( diff --git a/tests/unit/createFlowLayoutTokens.test.ts b/tests/unit/createFlowLayoutTokens.test.ts index 8f13473..e624d21 100644 --- a/tests/unit/createFlowLayoutTokens.test.ts +++ b/tests/unit/createFlowLayoutTokens.test.ts @@ -31,7 +31,7 @@ describe("createFlowLayoutTokens", () => { expect(CREATE_FLOW_PAGE_GUTTER_CLASS).toBe("px-5 md:px-12 lg:px-16"); }); - it("offsets fixed top banners below the create-flow header", () => { + it("offsets fixed top banners below the create-flow header so Share stays clickable", () => { expect(CREATE_FLOW_FIXED_TOP_BANNER_OFFSET_CLASS).toBe("top-14 md:top-16"); });