Files
siftlode/frontend/src/components/ShareDialog.tsx
T
peter 2768ab5bdd fix(gate): the plan-code guard catches decision codes, and the purge takes them
A plan's decision ids (`D1`, `D4`, `D6-A`) cited in 11 comments and test titles named a document
no reader of this repo has, and the guard had no pattern for them. It has now (mirrored in
audit_metrics), with cases for each form the citations took and for the look-alikes it must leave
alone (a JPEG marker, "3D"); the 11 lines say their why without the id. Case test seen red without
the pattern, the scan red on a planted `D9:`.
2026-10-05 03:16:13 +02:00

364 lines
14 KiB
TypeScript

import { useEffect, useRef, useState } from "react";
import { qk } from "../lib/queryKeys";
import { useTranslation } from "react-i18next";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { Check, Copy, Link2, Lock, Trash2, UserPlus, Eye } from "lucide-react";
import Modal from "./ui/Modal";
import { useConfirm } from "./confirmContext";
import { notify } from "../lib/notifications";
import { notifyActionError } from "../lib/actionErrors";
import { copyText } from "../lib/clipboard";
import { formatDate } from "../lib/format";
import { api, type DownloadJob, type ShareLink, type ShareRecipient } from "../lib/api";
import { Button } from "./ui/Button";
import { IconButton } from "./ui/IconButton";
import { Input, InnerInput } from "./ui/Input";
import { CheckRow } from "./ui/NativeControls";
import { SURFACE } from "./ui/surfaces";
import UserPicker from "./UserPicker";
const EXPIRY_DAYS = [null, 1, 7, 30] as const;
// --- share with a registered user (ACL) -----------------------------------------------------
// One shared empty list while the recipients load: a fresh `[]` per render made `filtered` below
// recompute on every render.
const NO_RECIPIENTS: ShareRecipient[] = [];
function UserShare({ job }: { job: DownloadJob }) {
const { t } = useTranslation();
const recipients = useQuery({ queryKey: qk.shareRecipients(), queryFn: api.shareRecipients });
const list = recipients.data ?? NO_RECIPIENTS;
const share = useMutation({
mutationFn: (email: string) => api.shareDownload(job.id, email),
onSuccess: (r) => {
notify({ level: "success", message: t("downloads.share.done", { email: r.shared_with }) });
},
onError: (e) => notifyActionError(e, t("downloads.share.failed")),
});
return (
<div>
<div className="flex items-center gap-2 text-sm font-medium mb-1">
<UserPlus className="w-4 h-4 text-muted" /> {t("downloads.share.userSection")}
</div>
<p className="text-xs text-muted mb-2">{t("downloads.share.userHint")}</p>
<UserPicker
users={list}
loading={recipients.isLoading}
error={recipients.isError}
onRetry={() => void recipients.refetch()}
disabled={share.isPending}
onPick={(u) => {
if (!share.isPending) share.mutate(u.email);
}}
label={t("downloads.share.userSection")}
placeholder={t("downloads.share.pickPlaceholder")}
/>
{recipients.data && list.length === 0 && (
<p className="text-xs text-muted mt-1">{t("downloads.share.noUsers")}</p>
)}
</div>
);
}
// --- share by public link -------------------------------------------------------------------
function LinkRow({ link, onChanged }: { link: ShareLink; onChanged: () => void }) {
const { t, i18n } = useTranslation();
const confirm = useConfirm();
const [copied, setCopied] = useState(false);
const [editPass, setEditPass] = useState(false);
const [newPass, setNewPass] = useState("");
const fullUrl = window.location.origin + link.url;
const copy = async () => {
if (await copyText(fullUrl)) {
setCopied(true);
setTimeout(() => setCopied(false), 1500);
} else {
notify({ level: "error", message: t("downloads.share.copyFailed") });
}
};
const toggle = useMutation({
mutationFn: () => api.updateDownloadLink(link.id, { allow_download: !link.allow_download }),
onSuccess: onChanged,
meta: { failTitle: "errors.writeFailed.shareLinkDownload" },
});
const revoke = useMutation({
mutationFn: () => api.revokeDownloadLink(link.id),
onSuccess: onChanged,
meta: { failTitle: "errors.writeFailed.shareLinkRevoke" },
});
// Set / change / clear the link password. Rotating (or clearing) it bumps the link's
// password_version server-side, which invalidates any watch grant issued under the old password.
const savePass = useMutation({
mutationFn: (pw: string) => api.updateDownloadLink(link.id, { password: pw }),
meta: { failTitle: "errors.writeFailed.shareLinkPassword" },
onSuccess: () => {
setEditPass(false);
setNewPass("");
onChanged();
},
});
const badges: string[] = [];
if (link.has_password) badges.push(t("downloads.share.hasPassword"));
if (link.allow_download) badges.push(t("downloads.share.downloadable"));
if (link.expires_at)
badges.push(
t("downloads.share.expiresOn", { date: formatDate(link.expires_at, i18n.language) }),
);
return (
<div className={`${SURFACE.card} p-2.5 space-y-2`}>
<div className="flex items-center gap-2 rounded-md focus-within:outline-2 focus-within:outline-accent/60 focus-within:outline-offset-2">
<Link2 className="w-4 h-4 text-muted shrink-0" />
<InnerInput className="text-xs text-muted truncate" readOnly value={fullUrl} />
<IconButton label={t("downloads.share.copy")} size="sm" variant="ghost" onClick={copy}>
{copied ? <Check className="w-4 h-4 text-success" /> : <Copy className="w-4 h-4" />}
</IconButton>
{/* All three on the same rung. Only Copy was migrated at first, which left one 2rem button
between two 1.75rem ones with a different radius and hover fill — and, on a coarse
pointer, `.touch-target` grew ONLY the migrated one to 2.75rem while the destructive
Revoke stayed small. */}
<IconButton
label={
link.has_password
? t("downloads.share.changePassword")
: t("downloads.share.setPassword")
}
size="sm"
variant="ghost"
onClick={() => {
setNewPass("");
setEditPass((v) => !v);
}}
// On the ICON, not the button: `clsx` does not merge Tailwind, so a colour className loses
// to the variant's own `text-muted`/`hover:text-fg` by stylesheet order and the state was
// simply invisible. The Copy button above already does it this way.
>
<Lock className={`w-4 h-4 ${link.has_password ? "text-accent" : ""}`} />
</IconButton>
<IconButton
label={t("downloads.share.revoke")}
size="sm"
variant="ghost"
onClick={async () => {
if (
await confirm({
title: t("downloads.share.revoke"),
message: t("downloads.share.revokeConfirm"),
confirmLabel: t("downloads.share.revoke"),
danger: true,
})
)
revoke.mutate();
}}
>
<Trash2 className="w-4 h-4 text-danger" />
</IconButton>
</div>
<div className="flex items-center gap-2 text-xs text-muted flex-wrap">
<span className="inline-flex items-center gap-1">
<Eye className="w-3 h-3" /> {t("downloads.share.views", { count: link.view_count })}
</span>
{badges.map((b) => (
<span
key={b}
className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded-sm bg-surface"
>
{b === t("downloads.share.hasPassword") && <Lock className="w-3 h-3" />}
{b}
</span>
))}
<div className="flex-1" />
<CheckRow checked={link.allow_download} onChange={() => toggle.mutate()}>
{t("downloads.share.allowDownload")}
</CheckRow>
</div>
{editPass && (
<div className="flex items-center gap-2">
<Input
className="flex-1"
size="sm"
type="password"
autoComplete="new-password"
value={newPass}
onChange={(e) => setNewPass(e.target.value)}
onKeyDown={(e) =>
e.key === "Enter" && newPass.trim() && savePass.mutate(newPass.trim())
}
placeholder={t(
link.has_password ? "downloads.share.newPassword" : "downloads.share.setPassword",
)}
/>
<Button
size="xs"
onClick={() => savePass.mutate(newPass.trim())}
loading={savePass.isPending}
disabled={!newPass.trim()}
>
{t("downloads.share.savePassword")}
</Button>
{link.has_password && (
<Button
variant="outline-danger"
size="xs"
onClick={async () => {
if (
await confirm({
title: t("downloads.share.removePassword"),
message: t("downloads.share.removePasswordConfirm"),
confirmLabel: t("downloads.share.removePassword"),
danger: true,
})
)
savePass.mutate("");
}}
disabled={savePass.isPending}
>
{t("downloads.share.removePassword")}
</Button>
)}
</div>
)}
</div>
);
}
function LinkShare({ job }: { job: DownloadJob }) {
const { t } = useTranslation();
const qc = useQueryClient();
const links = useQuery({
queryKey: qk.downloadLinks(job.id),
queryFn: () => api.downloadLinks(job.id),
});
const [creating, setCreating] = useState(false);
// Downloadable by default — matches the one-click Share (which relies on the backend
// default) and the common "let them have the file" intent. The owner can uncheck it here.
const [allowDownload, setAllowDownload] = useState(true);
const [expiryDays, setExpiryDays] = useState<number | null>(null);
const [password, setPassword] = useState("");
const invalidate = () => void qc.invalidateQueries({ queryKey: qk.downloadLinks(job.id) });
const create = useMutation({
mutationFn: () =>
api.createDownloadLink(job.id, {
allow_download: allowDownload,
expires_days: expiryDays,
password: password.trim() || undefined,
}),
onSuccess: () => {
invalidate();
setCreating(false);
setAllowDownload(false);
setExpiryDays(null);
setPassword("");
},
meta: { failTitle: "downloads.share.linkFailed" },
});
// Open with a link already generated: sharing is almost always the goal, so mint a default
// (no password, no expiry, downloadable) link the moment the dialog finds none — as if the
// user had pressed "New link" → "Create". All further controls (password, download toggle, expiry,
// extra links, revoke) stay available on the created link and via the "New link" button.
const autoTried = useRef(false);
// The mutation OBJECT is rebuilt every render; `mutate` is not (react-query memoises it), so the
// two halves the effect actually uses can be named while `links.data` stays the only real trigger.
// The autoTried ref is what makes it fire exactly once.
const { mutate: createLink, isPending: createPending } = create;
useEffect(() => {
if (links.data && links.data.length === 0 && !autoTried.current && !createPending) {
autoTried.current = true;
createLink();
}
}, [links.data, createLink, createPending]);
return (
<div>
<div className="flex items-center gap-2 text-sm font-medium mb-1">
<Link2 className="w-4 h-4 text-muted" /> {t("downloads.share.linkSection")}
</div>
<p className="text-xs text-muted mb-2">{t("downloads.share.linkHint")}</p>
<div className="space-y-2">
{(links.data ?? []).map((l) => (
<LinkRow key={l.id} link={l} onChanged={invalidate} />
))}
{links.data && links.data.length === 0 && !creating && !create.isPending && (
<p className="text-xs text-muted">{t("downloads.share.noLinks")}</p>
)}
</div>
{creating ? (
<div className="mt-2 rounded-lg border border-border p-3 space-y-3">
<CheckRow checked={allowDownload} onChange={setAllowDownload} className="text-sm">
{t("downloads.share.allowDownload")}
</CheckRow>
<div className="flex items-center gap-2 text-sm">
<span className="text-muted">{t("downloads.share.expiry")}:</span>
{EXPIRY_DAYS.map((d) => (
<Button
key={String(d)}
variant="outline"
size="xs"
pressed={expiryDays === d}
onClick={() => setExpiryDays(d)}
>
{d === null
? t("downloads.share.expiryNever")
: t("downloads.share.days", { count: d })}
</Button>
))}
</div>
<Input
className="w-full"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder={t("downloads.share.password")}
autoComplete="new-password"
/>
<div className="flex justify-end gap-2">
<Button variant="ghost" size="sm" onClick={() => setCreating(false)}>
{t("common.cancel")}
</Button>
<Button
variant="primary"
size="sm"
onClick={() => create.mutate()}
disabled={create.isPending}
>
{t("downloads.share.createLink")}
</Button>
</div>
</div>
) : (
<Button
variant="outline"
size="sm"
onClick={() => setCreating(true)}
icon={<Link2 className="w-4 h-4" />}
className="mt-2"
>
{t("downloads.share.newLink")}
</Button>
)}
</div>
);
}
export default function ShareDialog({ job, onClose }: { job: DownloadJob; onClose: () => void }) {
const { t } = useTranslation();
return (
<Modal initialFocus="close" title={t("downloads.share.title")} onClose={onClose}>
<div className="space-y-5">
<UserShare job={job} />
<div className="border-t border-border" />
<LinkShare job={job} />
</div>
</Modal>
);
}