Keep shared Rule files reachable, and say when a privacy change does not save.

This commit is contained in:
adilallo committed 2026-11-09 20:05:06 -07:00
1 parent b6795c1f18
commit 63ba21c614
9 files changed
+140 -8

No files matched your search

+1
View File
@@ -69,6 +69,7 @@ export const GET = apiRoute<RouteContext>(
idOrSlug: row.ruleId, idOrSlug: row.ruleId,
user, user,
viaShareSlug: visibility === RULE_VISIBILITY.shared_by_link, viaShareSlug: visibility === RULE_VISIBILITY.shared_by_link,
lookup: "id",
requestPath: request.nextUrl.pathname, requestPath: request.nextUrl.pathname,
}); });
allowed = resolved != null; allowed = resolved != null;
@@ -65,6 +65,7 @@ const ShareContainer = memo<ShareProps>((props) => {
const [inviteError, setInviteError] = useState<string | null>(null); const [inviteError, setInviteError] = useState<string | null>(null);
const [turnOnBusy, setTurnOnBusy] = useState(false); const [turnOnBusy, setTurnOnBusy] = useState(false);
const [linkCopied, setLinkCopied] = useState(false); const [linkCopied, setLinkCopied] = useState(false);
const [saveFailed, setSaveFailed] = useState(false);
useCreateModalA11y(isOpen, onClose, dialogRef); useCreateModalA11y(isOpen, onClose, dialogRef);
@@ -76,6 +77,7 @@ const ShareContainer = memo<ShareProps>((props) => {
setInviteError(null); setInviteError(null);
setLinkCopied(false); setLinkCopied(false);
setTurnOnBusy(false); setTurnOnBusy(false);
setSaveFailed(false);
if (!previewSettings) setSettings(null); if (!previewSettings) setSettings(null);
return; return;
} }
@@ -106,6 +108,7 @@ const ShareContainer = memo<ShareProps>((props) => {
setSettings(next); setSettings(next);
setPhase("idle"); setPhase("idle");
setCommunityAgreed(false); setCommunityAgreed(false);
setSaveFailed(false);
}, []); }, []);
const handleSelectValue = useCallback( const handleSelectValue = useCallback(
@@ -132,7 +135,11 @@ const ShareContainer = memo<ShareProps>((props) => {
} }
void (async () => { void (async () => {
const res = await patchRuleShare(ruleId, "private"); const res = await patchRuleShare(ruleId, "private");
if (res.ok) applySettings(res.share); if (res.ok) {
applySettings(res.share);
return;
}
setSaveFailed(true);
})(); })();
return; return;
} }
@@ -146,6 +153,7 @@ const ShareContainer = memo<ShareProps>((props) => {
} }
setPhase("confirm"); setPhase("confirm");
setCommunityAgreed(false); setCommunityAgreed(false);
setSaveFailed(false);
} }
}, },
[applySettings, phase, ruleId, settings], [applySettings, phase, ruleId, settings],
@@ -185,7 +193,11 @@ const ShareContainer = memo<ShareProps>((props) => {
return; return;
} }
const res = await patchRuleShare(ruleId, "private"); const res = await patchRuleShare(ruleId, "private");
if (res.ok) applySettings(res.share); if (res.ok) {
applySettings(res.share);
return;
}
setSaveFailed(true);
}, [applySettings, ruleId, settings]); }, [applySettings, ruleId, settings]);
const handleInvite = useCallback(async () => { const handleInvite = useCallback(async () => {
@@ -274,6 +286,7 @@ const ShareContainer = memo<ShareProps>((props) => {
turnOnDisabled turnOnDisabled
turnOnBusy={false} turnOnBusy={false}
showError={false} showError={false}
showSaveError={false}
copyEnabled={false} copyEnabled={false}
linkCopied={false} linkCopied={false}
onCopyLink={() => undefined} onCopyLink={() => undefined}
@@ -327,6 +340,7 @@ const ShareContainer = memo<ShareProps>((props) => {
turnOnDisabled={!communityAgreed} turnOnDisabled={!communityAgreed}
turnOnBusy={turnOnBusy} turnOnBusy={turnOnBusy}
showError={phase === "error"} showError={phase === "error"}
showSaveError={saveFailed}
copyEnabled={copyEnabled} copyEnabled={copyEnabled}
linkCopied={linkCopied} linkCopied={linkCopied}
onCopyLink={() => void handleCopyLink()} onCopyLink={() => void handleCopyLink()}
@@ -44,6 +44,8 @@ export type ShareCopy = {
done: string; done: string;
errorTitle: string; errorTitle: string;
errorDescription: string; errorDescription: string;
saveErrorTitle: string;
saveErrorDescription: string;
closeDialogAriaLabel: string; closeDialogAriaLabel: string;
accessSelectAriaLabel: string; accessSelectAriaLabel: string;
}; };
@@ -79,6 +81,7 @@ export type ShareViewProps = {
turnOnDisabled: boolean; turnOnDisabled: boolean;
turnOnBusy: boolean; turnOnBusy: boolean;
showError: boolean; showError: boolean;
showSaveError: boolean;
copyEnabled: boolean; copyEnabled: boolean;
linkCopied: boolean; linkCopied: boolean;
onCopyLink: () => void; onCopyLink: () => void;
@@ -107,6 +107,7 @@ export const ShareView = memo(function ShareView({
turnOnDisabled, turnOnDisabled,
turnOnBusy, turnOnBusy,
showError, showError,
showSaveError,
copyEnabled, copyEnabled,
linkCopied, linkCopied,
onCopyLink, onCopyLink,
@@ -229,6 +230,19 @@ export const ShareView = memo(function ShareView({
{linkOn ? copy.anyoneWithLinkHint : copy.inviteOnlyHint} {linkOn ? copy.anyoneWithLinkHint : copy.inviteOnlyHint}
</p> </p>
) : null} ) : null}
{showSaveError ? (
<Alert
type="banner"
status="danger"
size="s"
title={copy.saveErrorTitle}
description={copy.saveErrorDescription}
hasLeadingIcon
hasBodyText
hasTrailingIcon={false}
className="w-full"
/>
) : null}
</div> </div>
{showLinkField ? ( {showLinkField ? (
+10 -5
View File
@@ -133,22 +133,27 @@ async function resolveAccessForRow(opts: {
/** /**
* Fetch a published rule the viewer is allowed to read. * Fetch a published rule the viewer is allowed to read.
* *
* Lookup is by internal id unless `viaShareSlug` is set. Shared-by-link * Lookup is by internal id unless `viaShareSlug` is set. Pass `lookup: "id"`
* strangers must use the rotating slug so turning the link off invalidates it. * when the caller already has the Rule id but link visitors should still
* Returns `null` for missing rows, denied readers, and DB failures — callers * count as readers (file URLs on a shared Rule). Shared-by-link strangers
* render the same 404 as a missing Rule. * opening the Rule itself must use the rotating slug so turning the link off
* invalidates it. Returns `null` for missing rows, denied readers, and DB
* failures — callers render the same 404 as a missing Rule.
*/ */
export async function getReadablePublishedRule(opts: { export async function getReadablePublishedRule(opts: {
idOrSlug: string; idOrSlug: string;
user: User | null; user: User | null;
viaShareSlug: boolean; viaShareSlug: boolean;
requestPath: string; requestPath: string;
lookup?: "id" | "shareSlug";
}): Promise<ReadablePublishedRule | null> { }): Promise<ReadablePublishedRule | null> {
if (!isDatabaseConfigured()) return null; if (!isDatabaseConfigured()) return null;
const idOrSlug = opts.idOrSlug.trim(); const idOrSlug = opts.idOrSlug.trim();
if (idOrSlug.length === 0) return null; if (idOrSlug.length === 0) return null;
const lookup = opts.lookup ?? (opts.viaShareSlug ? "shareSlug" : "id");
try { try {
const row = opts.viaShareSlug const row =
lookup === "shareSlug"
? await prisma.publishedRule.findUnique({ ? await prisma.publishedRule.findUnique({
where: { shareSlug: idOrSlug }, where: { shareSlug: idOrSlug },
select: RULE_ACCESS_SELECT, select: RULE_ACCESS_SELECT,
+2
View File
@@ -25,6 +25,8 @@
"done": "Done", "done": "Done",
"errorTitle": "The link didn’t turn on", "errorTitle": "The link didn’t turn on",
"errorDescription": "Check your connection and try again.", "errorDescription": "Check your connection and try again.",
"saveErrorTitle": "That change didn’t save",
"saveErrorDescription": "Check your connection and try again.",
"closeDialogAriaLabel": "Close", "closeDialogAriaLabel": "Close",
"accessSelectAriaLabel": "Who can read this Rule" "accessSelectAriaLabel": "Who can read this Rule"
} }
+68
View File
@@ -8,8 +8,15 @@ import {
} from "../../utils/test-utils"; } from "../../utils/test-utils";
import "@testing-library/jest-dom/vitest"; import "@testing-library/jest-dom/vitest";
import Share from "../../../app/components/modals/Share"; import Share from "../../../app/components/modals/Share";
import { patchRuleShare } from "../../../lib/create/api";
import type { RuleShareSettings } from "../../../lib/ruleShareTypes"; import type { RuleShareSettings } from "../../../lib/ruleShareTypes";
vi.mock("../../../lib/create/api", () => ({
patchRuleShare: vi.fn(),
fetchRuleShare: vi.fn(),
addRuleStakeholder: vi.fn(),
}));
const previewSettings: RuleShareSettings = { const previewSettings: RuleShareSettings = {
visibility: "private", visibility: "private",
shareSlug: null, shareSlug: null,
@@ -41,9 +48,18 @@ function openShare(overrides: Partial<RuleShareSettings> = {}) {
const writeText = vi.fn().mockResolvedValue(undefined); const writeText = vi.fn().mockResolvedValue(undefined);
const sharedSettings: RuleShareSettings = {
...previewSettings,
visibility: "shared_by_link",
shareSlug: "k7f2-9qxm",
shareUrl: "https://communityrule.info/r/k7f2-9qxm",
shareUrlDisplay: "communityrule.info/r/k7f2-9qxm",
};
beforeEach(() => { beforeEach(() => {
writeText.mockReset(); writeText.mockReset();
writeText.mockResolvedValue(undefined); writeText.mockResolvedValue(undefined);
vi.mocked(patchRuleShare).mockReset();
Object.defineProperty(window.navigator, "clipboard", { Object.defineProperty(window.navigator, "clipboard", {
configurable: true, configurable: true,
value: { writeText }, value: { writeText },
@@ -133,6 +149,58 @@ describe("Share modal", () => {
).toBeInTheDocument(); ).toBeInTheDocument();
}); });
it("keeps the link on and says so when turning the Rule private does not save", async () => {
vi.mocked(patchRuleShare).mockResolvedValueOnce({
ok: false,
status: 500,
error: "nope",
});
const user = userEvent.setup();
render(
<Share
isOpen
onClose={vi.fn()}
ruleId="rule-1"
previewSettings={sharedSettings}
/>,
);
await user.click(
screen.getByRole("button", { name: /Anyone with the link/i }),
);
await user.click(
await screen.findByRole("option", { name: "Only people you invite" }),
);
expect(await screen.findByText("That change didn’t save")).toBeInTheDocument();
expect(
screen.getByRole("button", { name: "Turn off link" }),
).toBeInTheDocument();
expect(
screen.queryByText("Only people you invite can open it."),
).not.toBeInTheDocument();
});
it("keeps the link on and says so when turning the link off does not save", async () => {
vi.mocked(patchRuleShare).mockResolvedValueOnce({
ok: false,
status: 500,
error: "nope",
});
const user = userEvent.setup();
render(
<Share
isOpen
onClose={vi.fn()}
ruleId="rule-1"
previewSettings={sharedSettings}
/>,
);
await user.click(screen.getByRole("button", { name: "Turn off link" }));
expect(await screen.findByText("That change didn’t save")).toBeInTheDocument();
expect(
screen.getByDisplayValue("communityrule.info/r/k7f2-9qxm"),
).toBeInTheDocument();
});
it("calls onClose when Done is clicked", async () => { it("calls onClose when Done is clicked", async () => {
const user = userEvent.setup(); const user = userEvent.setup();
const onClose = vi.fn(); const onClose = vi.fn();
+21
View File
@@ -153,6 +153,27 @@ describe("getReadablePublishedRule", () => {
).toBeNull(); ).toBeNull();
}); });
it("lets anonymous readers of a shared Rule through when the caller already has the id", async () => {
isDatabaseConfiguredMock.mockReturnValue(true);
findUniqueMock.mockResolvedValueOnce(
row({
visibility: RULE_VISIBILITY.shared_by_link,
shareSlug: "k7f2-9qxm",
}),
);
const resolved = await getReadablePublishedRule({
idOrSlug: "owned-1",
user: null,
viaShareSlug: true,
lookup: "id",
requestPath: "/api/uploads/file-1",
});
expect(resolved?.rule.id).toBe("owned-1");
expect(findUniqueMock).toHaveBeenCalledWith(
expect.objectContaining({ where: { id: "owned-1" } }),
);
});
it("lets anonymous readers use the rotating slug", async () => { it("lets anonymous readers use the rotating slug", async () => {
isDatabaseConfiguredMock.mockReturnValue(true); isDatabaseConfiguredMock.mockReturnValue(true);
findUniqueMock.mockResolvedValueOnce( findUniqueMock.mockResolvedValueOnce(
+5 -1
View File
@@ -153,7 +153,11 @@ describe("GET /api/uploads/[id]", () => {
); );
expect(res.status).toBe(200); expect(res.status).toBe(200);
expect(getReadablePublishedRuleMock).toHaveBeenCalledWith( expect(getReadablePublishedRuleMock).toHaveBeenCalledWith(
expect.objectContaining({ viaShareSlug: true }), expect.objectContaining({
idOrSlug: "rule-shared",
viaShareSlug: true,
lookup: "id",
}),
); );
expect(res.headers.get("Cache-Control")).toBe("private, no-store"); expect(res.headers.get("Cache-Control")).toBe("private, no-store");
}); });