Keep finished Rules private until a rotating share link is on, and delete files with the Rule #102

Merged
an.di merged 3 commits from adilallo/feature/CR-248-rule-visibility into main 2026-11-10 04:12:12 +00:00
28 changed files with 1467 additions and 377 deletions
Showing only changes of commit b6795c1f18 - Show all commits

No files matched your search

+11 -15
View File
@@ -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({
<Share
isOpen={shareModalOpen}
onClose={() => 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",
})
}
/>
<Create
isOpen={leaveConfirmOpen}
+73 -1
View File
@@ -16,7 +16,18 @@ import {
logout,
requestEmailChange,
type MyPublishedRule,
type PublishedRuleDetailForClient,
} from "../../../lib/create/api";
import {
downloadStoredRuleAsPdf,
downloadTextFile,
exportFilenameBase,
exportStoredRuleAsMarkdown,
} from "../../../lib/create/ruleExport";
import {
writeLastPublishedRule,
type StoredLastPublishedRule,
} from "../../../lib/create/lastPublishedRule";
import {
CREATE_FLOW_MANAGE_STAKEHOLDERS_QUERY,
CREATE_FLOW_MANAGE_STAKEHOLDERS_VALUE,
@@ -29,7 +40,6 @@ import { clearAnonymousCreateFlowStorage } from "../create/utils/anonymousDraftS
import { clearCoreValueDetailsLocalStorage } from "../create/utils/coreValueDetailsLocalStorage";
import { prepareFreshCreateFlowEntrySync } from "../create/utils/prepareFreshCreateFlowEntry";
import { createFlowStepPath } from "../create/utils/createFlowPaths";
import { writeLastPublishedRule } from "../../../lib/create/lastPublishedRule";
import { useMediaQuery } from "../../hooks/useMediaQuery";
import {
ProfilePageSignedOutView,
@@ -315,6 +325,66 @@ export default function ProfilePageClient() {
void load();
}, [draftDeleteBusy, load]);
const toStoredRule = useCallback(
(rule: PublishedRuleDetailForClient): StoredLastPublishedRule | null => {
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<string, unknown>,
};
},
[],
);
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}
/>
);
@@ -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({
}
/>
<Dialog
<DeleteAccount
isOpen={accountDeleteOpen}
onClose={() => {
if (!accountDeleteBusy) onCloseDeleteAccount();
}}
backdropVariant="blurredYellow"
title={t("deleteAccountModalTitle")}
description={t("deleteAccountModalBody")}
footer={
<>
<Button
type="button"
size="medium"
buttonType="outline"
palette="default"
onClick={onCloseDeleteAccount}
disabled={accountDeleteBusy}
>
{t("deleteAccountCancel")}
</Button>
<Button
type="button"
size="medium"
buttonType="outline"
danger
palette="default"
onClick={onConfirmDeleteAccount}
disabled={accountDeleteBusy}
>
{t("deleteAccountConfirm")}
</Button>
</>
}
onConfirm={onConfirmDeleteAccount}
busy={accountDeleteBusy}
rules={rules
.filter((rule) => rule.role === "owner")
.map((rule) => ({ id: rule.id, title: rule.title }))}
onExportPdf={onExportRulePdf}
onExportMarkdown={onExportRuleMarkdown}
/>
<Dialog
@@ -20,16 +20,14 @@ function UseCaseCompletedRuleContainerComponent({
const router = useRouter();
const mdUp = useCreateFlowMdUp();
const tTopNav = useTranslation("pages.useCasesCompletedRule.topNav");
const [shareModalOpen, setShareModalOpen] = useState(false);
const [actionBanner, setActionBanner] =
useState<UseCaseCompletedRuleActionBanner | null>(null);
const { copyPageLink, mailtoPageLink, handleDuplicate } =
useUseCaseCompletedRuleActions({
slug,
fixture,
setActionBanner,
});
const { copyPageLink, handleDuplicate } = useUseCaseCompletedRuleActions({
slug,
fixture,
setActionBanner,
});
return (
<UseCaseCompletedRuleView
@@ -40,11 +38,7 @@ function UseCaseCompletedRuleContainerComponent({
duplicateLabel={tTopNav("duplicate")}
duplicateAriaLabel={tTopNav("duplicateAriaLabel")}
exitLabel={tTopNav("return")}
shareModalOpen={shareModalOpen}
onShareOpen={() => setShareModalOpen(true)}
onShareClose={() => setShareModalOpen(false)}
onCopyLink={() => void copyPageLink()}
onEmailShare={mailtoPageLink}
onShare={() => void copyPageLink()}
onDuplicate={() => void handleDuplicate()}
onExit={() => router.push(`/use-cases/${slug}`)}
actionBanner={actionBanner}
@@ -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;
@@ -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({
</div>
</div>
) : null}
<Share
isOpen={shareModalOpen}
onClose={onShareClose}
onCopyLink={onCopyLink}
onEmailShare={onEmailShare}
onSignalShare={onCopyLink}
onSlackShare={onCopyLink}
onDiscordShare={onCopyLink}
/>
<CreateFlowTopNav
hasShare
hasDuplicate
@@ -76,7 +62,7 @@ export function UseCaseCompletedRuleView({
exitLabel={exitLabel}
buttonPalette="inverse"
className="relative z-[21] shrink-0 !bg-transparent"
onShare={onShareOpen}
onShare={onShare}
onDuplicate={onDuplicate}
onExit={onExit}
/>
@@ -12,6 +12,8 @@ const backdropOverlayClasses: Record<CreateModalBackdropVariant, string> = {
"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 = (
<div
ref={overlayRef}
className={`${backdropOverlayClasses[backdropVariant]} flex flex-col items-center justify-center gap-6 overflow-y-auto px-4 py-8`}
className={`${backdropOverlayClasses[backdropVariant]} ${overlayLayout}`}
onClick={onOverlayClick}
role="presentation"
>
@@ -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}
@@ -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<DeleteAccountProps>((props) => {
const {
isOpen,
onClose,
onConfirm,
busy = false,
rules,
onExportPdf,
onExportMarkdown,
className = "",
backdropVariant = "blurredYellow",
} = props;
const dialogRef = useRef<HTMLDivElement>(null);
const overlayRef = useRef<HTMLDivElement>(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 (
<DeleteAccountView
isOpen={isOpen}
onClose={onClose}
onConfirm={onConfirm}
busy={busy}
rules={rules}
onExportPdf={onExportPdf}
onExportMarkdown={onExportMarkdown}
className={className}
backdropVariant={backdropVariant}
dialogRef={dialogRef}
overlayRef={overlayRef}
titleId={titleId}
copy={copy}
understood={understood}
onUnderstoodChange={setUnderstood}
/>
);
});
DeleteAccountContainer.displayName = "DeleteAccount";
export default DeleteAccountContainer;
@@ -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<HTMLDivElement | null>;
overlayRef: RefObject<HTMLDivElement | null>;
titleId: string;
copy: DeleteAccountCopy;
understood: boolean;
onUnderstoodChange: (_checked: boolean) => void;
};
@@ -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 (
<CreateModalFrameView
isOpen={isOpen}
onOverlayClick={busy ? () => undefined : onClose}
backdropVariant={backdropVariant}
presentation="sheet"
className={className}
ariaLabel={copy.title}
ariaLabelledBy={titleId}
overlayRef={overlayRef}
dialogRef={dialogRef}
>
<ModalHeader
onClose={busy ? undefined : onClose}
showMoreOptionsButton={false}
closeButtonAriaLabel={copy.closeDialogAriaLabel}
/>
<div className="shrink-0 bg-[var(--color-surface-default-primary)] px-6">
<ContentLockup
title={copy.title}
description={copy.description}
variant="modal"
alignment="left"
titleId={titleId}
/>
</div>
<div className="flex min-h-0 flex-1 flex-col gap-3 overflow-x-clip overflow-y-auto px-6 pb-6 pt-6">
<p className="w-full text-small-label text-[var(--color-content-default-secondary)]">
{copy.yourRules}
</p>
{rules.map((rule) => (
<div
key={rule.id}
className="flex w-full items-center gap-3 overflow-hidden rounded-[12px] bg-[var(--color-surface-default-secondary)] p-3"
>
<Avatar
alt=""
initials={communityInviteInitials(rule.title)}
size="large"
shape="circle"
variant="filled"
/>
<p className="min-w-0 flex-1 truncate text-small-label text-[var(--color-content-default-primary)]">
{rule.title}
</p>
<div className="flex shrink-0 items-start gap-2">
<Button
type="button"
buttonType="outline"
palette="default"
size="small"
disabled={busy}
onClick={() => onExportPdf(rule.id)}
>
<Icon name="picture_as_pdf" size={14} />
{copy.exportPdf}
</Button>
<Button
type="button"
buttonType="outline"
palette="default"
size="small"
disabled={busy}
onClick={() => onExportMarkdown(rule.id)}
>
<Icon name="markdown_copy" size={14} />
{copy.exportMarkdown}
</Button>
</div>
</div>
))}
<Checkbox
checked={understood}
disabled={busy}
label={copy.confirmLabel}
onChange={(data) => onUnderstoodChange(data.checked)}
/>
</div>
<div className="flex shrink-0 items-center justify-end gap-2 border-t border-solid border-[var(--color-border-default-secondary)] bg-[var(--color-surface-default-primary)] px-6 py-4">
<Button
type="button"
buttonType="outline"
palette="default"
size="small"
disabled={busy}
onClick={onClose}
>
{copy.cancel}
</Button>
<Button
type="button"
buttonType="outline"
palette="default"
size="small"
danger
disabled={busy || !understood}
onClick={onConfirm}
>
{copy.confirm}
</Button>
</div>
</CreateModalFrameView>
);
});
DeleteAccountView.displayName = "DeleteAccountView";
@@ -0,0 +1,5 @@
export { default } from "./DeleteAccount.container";
export type {
DeleteAccountProps,
DeleteAccountRule,
} from "./DeleteAccount.types";
+303 -30
View File
@@ -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<ShareProps>((props) => {
const {
isOpen,
onClose,
ruleId = null,
previewSettings,
onRequestLogin,
className = "",
backdropVariant = "blurredYellow",
} = props;
const dialogRef = useRef<HTMLDivElement>(null);
const overlayRef = useRef<HTMLDivElement>(null);
const titleId = useId();
const t = useTranslation("modals.share");
const copy = useMessages().modals.share;
const [settings, setSettings] = useState<RuleShareSettings | null>(
previewSettings ?? null,
);
const [phase, setPhase] = useState<SharePhase>("idle");
const [communityAgreed, setCommunityAgreed] = useState(false);
const [inviteValue, setInviteValue] = useState("");
const [inviteBusy, setInviteBusy] = useState(false);
const [inviteError, setInviteError] = useState<string | null>(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 (
<ShareView
isOpen={isOpen}
onClose={onClose}
className={className}
backdropVariant={backdropVariant}
dialogRef={dialogRef}
overlayRef={overlayRef}
titleId={titleId}
copy={copy}
communityName=""
inviteValue=""
onInviteValueChange={setInviteValue}
onInvite={() => 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 (
<ShareView
{...props}
isOpen={isOpen}
onClose={onClose}
className={className}
backdropVariant={backdropVariant}
dialogRef={dialogRef}
overlayRef={overlayRef}
titleId={titleId}
title={t("title")}
description={t("description")}
copyLinkLabel={t("copyLink")}
copiedLabel={t("copied")}
copiedLive={t("copiedLive")}
copy={copy}
communityName={settings.title}
inviteValue={inviteValue}
onInviteValueChange={(value) => {
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()}
/>
);
});
+71 -29
View File
@@ -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<void | boolean>;
onEmailShare: () => void;
onSignalShare: () => void | Promise<void>;
onSlackShare: () => void | Promise<void>;
onDiscordShare: () => void | Promise<void>;
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<HTMLDivElement | null>;
overlayRef: RefObject<HTMLDivElement | null>;
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<void>;
signalLabel: string;
slackLabel: string;
discordLabel: string;
emailLabel: string;
doneLabel: string;
closeDialogAriaLabel: string;
moreOptionsAriaLabel: string;
};
export type ShareChannelTileProps = {
label: string;
onClick: () => void | Promise<void>;
circleClassName: string;
icon: ReactNode;
copied?: boolean;
onCopyLink: () => void;
};
+266 -129
View File
@@ -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 (
<Image
src={getAssetPath(shareIconPath(name))}
src={getAssetPath(shareIconPath(props.name))}
alt=""
width={width}
height={height}
width={size}
height={size}
className="shrink-0"
unoptimized
aria-hidden
@@ -34,161 +34,298 @@ function ShareAssetIcon(props: {
);
}
function ShareChannelTile({
label,
onClick,
circleClassName,
icon,
copied = false,
}: ShareChannelTileProps) {
function PersonRow(props: {
initials: string;
title: string;
subtitle?: string;
roleLabel: string;
}) {
return (
<button
type="button"
onClick={() => 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)]"
>
<div
className={`flex h-[60px] w-[60px] items-center justify-center rounded-full border border-solid transition-[transform,background-color,border-color,filter] duration-150 ease-out group-active:scale-90 ${circleClassName}`}
>
{icon}
<div className="flex w-full items-center gap-3 overflow-hidden">
<Avatar
alt=""
initials={props.initials}
size="xlarge"
shape="circle"
variant="filled"
/>
<div className="flex min-w-0 flex-1 flex-col gap-0.5 overflow-hidden">
<p className="truncate text-small-label text-[var(--color-content-default-primary)]">
{props.title}
</p>
{props.subtitle ? (
<p className="truncate text-x-small-paragraph text-[var(--color-content-default-tertiary)]">
{props.subtitle}
</p>
) : null}
</div>
<span
className={`max-w-[4.5rem] text-center text-x-small-label ${
copied
? "text-[var(--color-border-default-positive-primary)]"
: "text-[var(--color-content-default-tertiary)]"
}`}
>
{label}
</span>
</button>
<p className="shrink-0 text-x-small-paragraph text-[var(--color-content-default-tertiary)]">
{props.roleLabel}
</p>
</div>
);
}
function ReaderRow({ reader, roleLabel }: { reader: SharePerson; roleLabel: string }) {
return (
<PersonRow
initials={reader.initials}
title={reader.email}
roleLabel={roleLabel}
/>
);
}
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 (
<CreateModalFrameView
isOpen={isOpen}
onOverlayClick={onClose}
backdropVariant={backdropVariant}
className={`max-h-[90vh] w-[min(546px,calc(100vw-32px))] max-w-[546px] min-h-0 ${className}`}
ariaLabel={title}
presentation="sheet"
className={className}
ariaLabel={copy.title}
ariaLabelledBy={titleId}
overlayRef={overlayRef}
dialogRef={dialogRef}
>
<ModalHeader
onClose={onClose}
onMoreOptions={onClose}
closeButtonAriaLabel={closeDialogAriaLabel}
moreOptionsAriaLabel={moreOptionsAriaLabel}
showMoreOptionsButton={false}
closeButtonAriaLabel={copy.closeDialogAriaLabel}
/>
<div className="shrink-0 bg-[var(--color-surface-default-primary)] px-[24px] py-[12px]">
<div className="shrink-0 bg-[var(--color-surface-default-primary)] px-6">
<ContentLockup
title={title}
description={description}
title={copy.title}
description={communityName}
variant="modal"
alignment="left"
titleId={titleId}
/>
</div>
<div className="scrollbar-design flex min-h-0 flex-1 flex-col overflow-x-clip overflow-y-auto px-[24px] pb-6 pt-0">
{/* Channel circle hexes are third-party brand colors (copy/link, Signal, Slack, Discord), not DS tokens. */}
<div className="flex flex-wrap gap-4">
<ShareChannelTile
label={linkCopied ? copiedLabel : copyLinkLabel}
onClick={onCopyLinkClick}
copied={linkCopied}
circleClassName={
linkCopied
? "border-2 border-[var(--color-gray-600)] bg-[var(--color-gray-700)]"
: "border-[var(--color-gray-600)] bg-[var(--color-gray-700)] group-hover:border-2 group-hover:border-[var(--color-border-default-positive-primary)] group-hover:bg-[var(--color-gray-600)]"
}
icon={
<ShareAssetIcon
name={linkCopied ? "check" : "link"}
width={24}
height={24}
/>
}
/>
<ShareChannelTile
label={signalLabel}
onClick={onSignalShare}
circleClassName="border-[#3a76f0] bg-[#3a76f0] group-hover:brightness-110"
icon={<ShareAssetIcon name="signal" width={26} height={26} />}
/>
<ShareChannelTile
label={slackLabel}
onClick={onSlackShare}
circleClassName="border-[#4a154b] bg-[#4a154b] group-hover:brightness-110"
icon={<ShareAssetIcon name="slack" width={26} height={26} />}
/>
<ShareChannelTile
label={discordLabel}
onClick={onDiscordShare}
circleClassName="border-[#5865f2] bg-[#5865f2] group-hover:brightness-110"
icon={<ShareAssetIcon name="discord" width={30} height={30} />}
/>
<ShareChannelTile
label={emailLabel}
onClick={onEmailShare}
circleClassName="border-[var(--color-surface-invert-brand-kiwi)] bg-[var(--color-surface-invert-brand-kiwi)] group-hover:brightness-110"
icon={<ShareAssetIcon name="mail" width={24} height={24} />}
/>
<div className="flex min-h-0 flex-1 flex-col gap-5 overflow-x-clip overflow-y-auto px-6 pb-6 pt-6">
<div className="flex w-full items-center gap-2">
<div className="min-w-0 flex-1">
<TextInput
type="email"
inputSize="medium"
formHeader={false}
showHelpIcon={false}
label={copy.addPeoplePlaceholder}
placeholder={copy.addPeoplePlaceholder}
value={inviteValue}
error={Boolean(inviteError)}
disabled={inviteBusy}
autoComplete="email"
onChange={(e) => onInviteValueChange(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") {
e.preventDefault();
onInvite();
}
}}
/>
</div>
<Button
type="button"
buttonType="outline"
palette="default"
size="small"
disabled={inviteBusy || inviteValue.trim().length === 0}
onClick={onInvite}
>
{copy.invite}
</Button>
</div>
<p className="sr-only" aria-live="polite">
{linkCopied ? copiedLive : ""}
</p>
</div>
{inviteError ? (
<p className="-mt-3 text-x-small-paragraph text-[var(--color-content-default-negative-primary)]">
{inviteError}
</p>
) : null}
<ModalFooter
showBackButton={false}
showNextButton={false}
stepper={false}
footerContent={
<div className="absolute right-[16px] top-[12px] flex max-w-[calc(100%-32px)] flex-wrap items-center justify-end gap-3">
<div className="flex w-full flex-col items-start gap-3 overflow-hidden">
<p className="w-full text-small-label text-[var(--color-content-default-secondary)]">
{copy.peopleWithAccess}
</p>
<PersonRow
initials={ownerInitials}
title={copy.you}
subtitle={ownerEmail}
roleLabel={copy.holdsThePen}
/>
{shownReaders.map((reader) => (
<ReaderRow
key={reader.email}
reader={reader}
roleLabel={copy.canRead}
/>
))}
{overflowLabel ? (
<p className="w-full text-x-small-paragraph text-[var(--color-content-default-tertiary)]">
{overflowLabel}
</p>
) : null}
</div>
<div className="flex w-full flex-col items-start gap-2 overflow-hidden">
<p className="w-full text-small-label text-[var(--color-content-default-secondary)]">
{copy.whoCanRead}
</p>
<div className="flex w-full items-center gap-3">
<ShareGlyph name={linkOn ? "language" : "lock"} />
<div className="min-w-0 flex-1">
<SelectInput
showLabel={false}
iconHelp={false}
value={selectValue}
onChange={(data) => onSelectValue(data.target.value)}
options={[
{ value: "private", label: copy.inviteOnly },
{ value: "shared_by_link", label: copy.anyoneWithLink },
]}
/>
</div>
</div>
{!showConfirm && !showError ? (
<p className="w-full text-small-paragraph text-[var(--color-content-default-tertiary)]">
{linkOn ? copy.anyoneWithLinkHint : copy.inviteOnlyHint}
</p>
) : null}
</div>
{showLinkField ? (
<div className="flex w-full flex-col items-start gap-3">
<TextInput
formHeader={false}
showHelpIcon={false}
label={copy.anyoneWithLink}
value={shareUrlDisplay}
disabled
textHint={copy.linkHint}
/>
<Button
buttonType="filled"
palette="default"
size="medium"
type="button"
onClick={onClose}
buttonType="ghost"
palette="default"
size="small"
onClick={onTurnOffLink}
>
{doneLabel}
{copy.turnOffLink}
</Button>
</div>
}
/>
) : null}
{showConfirm || showError ? (
<div className="flex w-full flex-col items-start gap-4 overflow-hidden rounded-[8px] bg-[var(--color-surface-default-secondary)] p-4">
{showError ? (
<Alert
type="banner"
status="danger"
size="s"
title={copy.errorTitle}
description={copy.errorDescription}
hasLeadingIcon
hasBodyText
hasTrailingIcon={false}
className="w-full"
/>
) : null}
<p className="w-full text-small-paragraph text-[var(--color-content-default-primary)]">
{copy.confirmBody}
</p>
<Checkbox
checked={communityAgreed}
label={copy.communityAgreed}
onChange={(data) => onCommunityAgreedChange(data.checked)}
/>
<Button
type="button"
buttonType="filled"
palette="default"
size="small"
disabled={turnOnDisabled || turnOnBusy}
onClick={onTurnOnLink}
>
{copy.turnOnLink}
</Button>
</div>
) : null}
{linkCopied ? (
<Alert
type="toast"
status="positive"
size="s"
title={copy.copiedLive}
hasLeadingIcon
hasBodyText={false}
hasTrailingIcon={false}
className="w-full"
/>
) : null}
</div>
<div className="flex shrink-0 items-center justify-between border-t border-solid border-[var(--color-border-default-secondary)] bg-[var(--color-surface-default-primary)] px-6 py-4">
<Button
type="button"
buttonType="outline"
palette="default"
size="small"
disabled={!copyEnabled}
aria-pressed={linkCopied || undefined}
onClick={onCopyLink}
>
<ShareGlyph name={linkCopied ? "check" : "link"} size={14} />
{linkCopied ? copy.copied : copy.copyLink}
</Button>
<Button
type="button"
buttonType="filled"
palette="default"
size="small"
onClick={onClose}
>
{copy.done}
</Button>
</div>
</CreateModalFrameView>
);
});
+2
View File
@@ -89,7 +89,9 @@ export function partnerLogoPath(slug: string): string {
export type ShareIconName =
| "check"
| "discord"
| "language"
| "link"
| "lock"
| "mail"
| "signal"
| "slack";
+104
View File
@@ -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<string, unknown>;
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<FetchRuleShareResult> {
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<FetchRuleShareResult> {
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 };
/**
+2
View File
@@ -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,
},
+13
View File
@@ -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"
}
+25 -9
View File
@@ -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"
}
+5
View File
@@ -0,0 +1,5 @@
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<circle cx="12" cy="12" r="9" stroke="white" stroke-width="2"/>
<path d="M3 12h18" stroke="white" stroke-width="2" stroke-linecap="round"/>
<path d="M12 3c2.5 3 3.5 6 3.5 9s-1 6-3.5 9c-2.5-3-3.5-6-3.5-9s1-6 3.5-9Z" stroke="white" stroke-width="2" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 382 B

+5
View File
@@ -0,0 +1,5 @@
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M7 11V8a5 5 0 0 1 10 0v3" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<rect x="5" y="11" width="14" height="10" rx="2" stroke="white" stroke-width="2"/>
<path d="M12 15v2" stroke="white" stroke-width="2" stroke-linecap="round"/>
</svg>

After

Width:  |  Height:  |  Size: 384 B

+47
View File
@@ -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 (
<div className="min-h-[100dvh] bg-[var(--color-surface-invert-brand-primary)] p-6">
<button
type="button"
className="rounded-md bg-[var(--color-surface-default-primary)] px-4 py-2 text-small-paragraph text-[var(--color-content-default-primary)]"
onClick={() => setOpen(true)}
>
Open Delete Account
</button>
<DeleteAccount
isOpen={open}
onClose={() => 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}
/>
</div>
);
}
export const Default = {
render: () => <DeleteAccountStoryHost />,
};
+38 -7
View File
@@ -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() {
<Share
isOpen={open}
onClose={() => setOpen(false)}
onCopyLink={() => {}}
onEmailShare={() => {}}
onSignalShare={() => {}}
onSlackShare={() => {}}
onDiscordShare={() => {}}
previewSettings={previewSettings}
/>
</div>
);
@@ -43,3 +58,19 @@ function ShareStoryHost() {
export const Default = {
render: () => <ShareStoryHost />,
};
export const AnyoneWithTheLink = {
render: () => (
<Share
isOpen
onClose={() => undefined}
previewSettings={{
...previewSettings,
visibility: "shared_by_link",
shareSlug: "k7f2-9qxm",
shareUrl: "https://communityrule.info/r/k7f2-9qxm",
shareUrlDisplay: "communityrule.info/r/k7f2-9qxm",
}}
/>
),
};
@@ -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(
<DeleteAccount
isOpen={false}
onClose={vi.fn()}
onConfirm={vi.fn()}
rules={[]}
onExportPdf={vi.fn()}
onExportMarkdown={vi.fn()}
/>,
);
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(
<DeleteAccount
isOpen
onClose={vi.fn()}
onConfirm={onConfirm}
rules={[{ id: "rule-1", title: "Juniper Street Food Share" }]}
onExportPdf={onExportPdf}
onExportMarkdown={vi.fn()}
/>,
);
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);
});
});
+121 -89
View File
@@ -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<RuleShareSettings> = {}) {
return render(
<Share
isOpen
onClose={vi.fn()}
previewSettings={{ ...previewSettings, ...overrides }}
/>,
);
}
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(
<Share isOpen={false} onClose={vi.fn()} {...noopHandlers} />,
<Share
isOpen={false}
onClose={vi.fn()}
previewSettings={previewSettings}
/>,
);
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(
<Share
isOpen={true}
onClose={vi.fn()}
{...noopHandlers}
onCopyLink={onCopyLink}
/>,
);
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(
<Share
isOpen={true}
onClose={vi.fn()}
{...noopHandlers}
onSignalShare={onSignalShare}
onSlackShare={onSlackShare}
onDiscordShare={onDiscordShare}
/>,
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(<Share isOpen={true} onClose={onClose} {...noopHandlers} />);
render(
<Share
isOpen
onClose={onClose}
previewSettings={previewSettings}
/>,
);
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(
<Share
isOpen={true}
onClose={vi.fn()}
{...noopHandlers}
onCopyLink={onCopyLink}
/>,
);
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(
<Share
isOpen={true}
onClose={vi.fn()}
{...noopHandlers}
onCopyLink={vi.fn().mockResolvedValue(false)}
/>,
);
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(<Share isOpen={true} onClose={onClose} {...noopHandlers} />);
await user.click(screen.getByRole("button", { name: "More share options" }));
expect(onClose).toHaveBeenCalledTimes(1);
});
});
+12 -3
View File
@@ -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);
});
@@ -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(
<MessagesProvider messages={marketingMessages}>
+1 -1
View File
@@ -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");
});