cm_bot_v2/web/components/users-table.tsx
yiekheng 9eed051916 feat(web,api): row-level search, more sort columns, copy buttons
Three operator-quality-of-life features behind the same caching and
pagination contract that the existing tables already use:

- Search bar on /acc and /users (Find/Enter to apply, Clear to reset).
  Backed by a new `q` API param that filters via WHERE
  username/f_username LIKE 'q%' on both rows + count queries so the
  table header total stays consistent under a filter.
- Two more sortable columns: acc.status and user.t_username. Sort
  columns are whitelisted because sort_col is f-string'd into ORDER
  BY (parameterised binding doesn't apply to column names) — anything
  outside the allowed set falls back to the table's default.
- Copy button on every row that writes a multi-line credentials
  message to the clipboard. New lib/clipboard.ts helper tries
  navigator.clipboard.writeText() first and falls back to
  textarea+execCommand("copy") so it works over the internal-network
  HTTP deploy where the modern API is gated by secure-context rules.
  Acc message: Username/Password (+Link if set). User message:
  From/To username and password.

Also: inactive sort indicators now render ↓ (the direction they'll
sort on first click) instead of the more ambiguous ↕.

Test suite grows from 53 to 70: tests/test_user_search_filter.py
(9 tests) pins the q-filter contract on both /user/ and /acc/;
tests/test_sort_whitelist.py (8 tests) pins the allowed sort columns
and proves out-of-set values cannot reach the SQL parser.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-04 09:26:11 +08:00

694 lines
23 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"use client";
import { useEffect, useOptimistic, useRef, useState, useTransition } from "react";
import type { User } from "@/lib/types";
import {
deleteUser,
loadMoreUsers,
refreshUsers,
updateUser,
} from "@/app/actions";
import EditableCell from "./editable-cell";
import ConfirmDialog from "./confirm-dialog";
import CreateUserDialog from "./create-user-dialog";
import Toast, { type ToastMessage } from "./toast";
import { copyToClipboard } from "@/lib/clipboard";
type Props = {
initial: User[];
initialHasMore: boolean;
initialTotal: number;
prefixPattern: string;
};
type SortDir = "asc" | "desc";
type SortKey = "f_username" | "t_username" | "last_update_time";
type OptimisticPatch = {
f_username: string;
field: keyof Pick<User, "f_password" | "t_username" | "t_password">;
value: string;
};
function formatTime(t: string | null) {
if (!t) return <em className="not-italic text-zinc-400"></em>;
const d = new Date(t);
if (Number.isNaN(d.getTime())) return t;
return d.toLocaleString(undefined, {
month: "short",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
});
}
function DeleteButton({
label,
onClick,
}: {
label: string;
onClick: () => void;
}) {
return (
<button
type="button"
onClick={onClick}
aria-label={`Delete ${label}`}
className="inline-flex h-7 w-7 items-center justify-center rounded-md text-zinc-400 transition-colors hover:bg-red-50 hover:text-red-600 focus:outline-none focus-visible:ring-2 focus-visible:ring-red-400"
>
<span aria-hidden="true" className="text-base leading-none">
×
</span>
</button>
);
}
function CopyButton({
label,
onClick,
}: {
label: string;
onClick: () => void;
}) {
return (
<button
type="button"
onClick={onClick}
aria-label={`Copy credentials for ${label}`}
title="Copy from/to credentials"
className="inline-flex h-7 w-7 items-center justify-center rounded-md text-zinc-400 transition-colors hover:bg-zinc-100 hover:text-zinc-700 focus:outline-none focus-visible:ring-2 focus-visible:ring-zinc-400"
>
<svg
aria-hidden="true"
viewBox="0 0 16 16"
fill="none"
stroke="currentColor"
strokeWidth="1.5"
strokeLinecap="round"
strokeLinejoin="round"
className="h-4 w-4"
>
<rect x="5.5" y="5.5" width="8" height="8" rx="1.25" />
<path d="M3 10.5V3.5A1 1 0 0 1 4 2.5h7" />
</svg>
</button>
);
}
export default function UsersTable({
initial,
initialHasMore,
initialTotal,
prefixPattern,
}: Props) {
const [sortKey, setSortKey] = useState<SortKey>("last_update_time");
const [sortDir, setSortDir] = useState<SortDir>("desc");
const [editingKey, setEditingKey] = useState<string | null>(null);
const [, startTransition] = useTransition();
const [loadingMore, setLoadingMore] = useState(false);
const [deleteTarget, setDeleteTarget] = useState<string | null>(null);
const [deleting, setDeleting] = useState(false);
const [deleteError, setDeleteError] = useState<string | null>(null);
const [createOpen, setCreateOpen] = useState(false);
const [toast, setToast] = useState<ToastMessage | null>(null);
// Force scroll-to-top on mount — iOS Safari preserves document scroll
// across SPA route changes, so tab-switching leaves the new page
// halfway down. Route transitions remount the table, so [] deps fire.
useEffect(() => {
window.scrollTo({ top: 0, left: 0, behavior: "instant" });
}, []);
const [rows, setRows] = useState<User[]>(initial);
const [hasMore, setHasMore] = useState<boolean>(initialHasMore);
const [total, setTotal] = useState<number>(initialTotal);
const sentinelRef = useRef<HTMLDivElement | null>(null);
// `searchInput` is what the user is typing; `appliedQuery` is what
// the server actually filtered on. Decoupling them means the input
// doesn't fire a request on every keystroke — only on Enter / Find /
// Clear. `appliedQuery` flows into refresh / changeSort / loadMore so
// sort + infinite-scroll respect the active search.
const [searchInput, setSearchInput] = useState("");
const [appliedQuery, setAppliedQuery] = useState("");
const [searching, setSearching] = useState(false);
const [optimistic, applyOptimistic] = useOptimistic<User[], OptimisticPatch>(
rows,
(state, patch) =>
state.map((row) =>
row.f_username === patch.f_username ? { ...row, [patch.field]: patch.value } : row,
),
);
function saveCell(
f_username: string,
field: OptimisticPatch["field"],
value: string,
) {
return new Promise<{ ok: boolean; error?: string }>((resolve) => {
startTransition(async () => {
applyOptimistic({ f_username, field, value });
const row = rows.find((r) => r.f_username === f_username);
if (!row) return resolve({ ok: false, error: "row not found" });
const next = {
f_username: row.f_username,
f_password: row.f_password,
t_username: row.t_username,
t_password: row.t_password,
[field]: value,
};
const result = await updateUser(next);
if (result.ok) {
setRows((prev) =>
prev.map((r) =>
r.f_username === f_username ? { ...r, [field]: value } : r,
),
);
resolve({ ok: true });
} else {
resolve({ ok: false, error: result.error });
}
});
});
}
// Force-evict the cache and re-fetch page 1. Used by the create-success
// path so a freshly added row appears in its sorted position.
async function refresh() {
const page = await refreshUsers({
prefix: prefixPattern,
sort: sortKey,
dir: sortDir,
q: appliedQuery,
});
setRows(page.rows);
setHasMore(page.hasMore);
setTotal(page.total);
}
async function applySearch(nextQuery: string) {
setSearching(true);
setAppliedQuery(nextQuery);
try {
const page = await refreshUsers({
prefix: prefixPattern,
sort: sortKey,
dir: sortDir,
q: nextQuery,
});
setRows(page.rows);
setHasMore(page.hasMore);
setTotal(page.total);
} finally {
setSearching(false);
}
}
async function changeSort(nextKey: SortKey) {
let nextDir: SortDir;
if (nextKey === sortKey) {
nextDir = sortDir === "asc" ? "desc" : "asc";
} else {
nextDir = "desc";
}
setSortKey(nextKey);
setSortDir(nextDir);
setLoadingMore(true);
try {
const page = await loadMoreUsers({
offset: 0,
prefix: prefixPattern,
sort: nextKey,
dir: nextDir,
q: appliedQuery,
});
setRows(page.rows);
setHasMore(page.hasMore);
setTotal(page.total);
} finally {
setLoadingMore(false);
}
}
useEffect(() => {
if (!hasMore || loadingMore) return;
const sentinel = sentinelRef.current;
if (!sentinel) return;
const observer = new IntersectionObserver(
(entries) => {
if (!entries.some((e) => e.isIntersecting)) return;
setLoadingMore(true);
loadMoreUsers({
offset: rows.length,
prefix: prefixPattern,
sort: sortKey,
dir: sortDir,
q: appliedQuery,
})
.then((page) => {
setRows((prev) => [...prev, ...page.rows]);
setHasMore(page.hasMore);
setTotal(page.total);
})
.catch((err) => console.error("loadMoreUsers failed:", err))
.finally(() => setLoadingMore(false));
},
{ rootMargin: "300px 0px" },
);
observer.observe(sentinel);
return () => observer.disconnect();
}, [hasMore, loadingMore, rows.length, prefixPattern, sortKey, sortDir, appliedQuery]);
async function handleCopy(row: User) {
const text =
`From Username: ${row.f_username}\n` +
`From Password: ${row.f_password}\n` +
`To Username: ${row.t_username}\n` +
`To Password: ${row.t_password}`;
const ok = await copyToClipboard(text);
setToast(
ok
? { type: "success", message: `Copied credentials for ${row.f_username}` }
: {
type: "error",
message: `Could not copy — clipboard access blocked. Select text manually.`,
},
);
}
async function confirmDelete() {
if (!deleteTarget) return;
setDeleting(true);
setDeleteError(null);
const result = await deleteUser(deleteTarget);
setDeleting(false);
if (result.ok) {
const deleted = deleteTarget;
setRows((prev) => prev.filter((r) => r.f_username !== deleted));
setTotal((t) => Math.max(0, t - 1));
setDeleteTarget(null);
setToast({ type: "success", message: `User ${deleted} deleted` });
} else {
setDeleteError(result.error);
}
}
function HeaderTh({ k, label }: { k: SortKey; label: string }) {
const active = sortKey === k;
return (
<button
type="button"
onClick={() => changeSort(k)}
className={`inline-flex items-center gap-1 text-[11px] font-medium uppercase tracking-wider transition-colors ${
active ? "text-zinc-900" : "text-zinc-500 hover:text-zinc-900"
}`}
>
{label}
<span aria-hidden="true">{active && sortDir === "asc" ? "↑" : "↓"}</span>
</button>
);
}
const onSearchSubmit = (e: React.FormEvent) => {
e.preventDefault();
void applySearch(searchInput.trim());
};
const onSearchClear = () => {
setSearchInput("");
void applySearch("");
};
if (rows.length === 0 && !appliedQuery) {
return (
<div>
<PageHead
total={total}
loaded={0}
onAdd={() => setCreateOpen(true)}
/>
<SearchBar
value={searchInput}
onChange={setSearchInput}
onSubmit={onSearchSubmit}
onClear={onSearchClear}
appliedQuery={appliedQuery}
searching={searching}
/>
<div className="mt-6 rounded-2xl bg-white px-8 py-16 text-center ring-1 ring-zinc-200/60">
<p className="text-sm text-zinc-500">
No users yet. Click <span className="font-medium text-zinc-700">Add</span> to create one manually.
</p>
</div>
<CreateUserDialog
open={createOpen}
onClose={() => setCreateOpen(false)}
onSuccess={async (name) => {
setToast({ type: "success", message: `User ${name} created` });
await refresh();
}}
/>
<Toast toast={toast} onDismiss={() => setToast(null)} />
</div>
);
}
return (
<div>
<PageHead
total={total}
loaded={optimistic.length}
onAdd={() => setCreateOpen(true)}
/>
<SearchBar
value={searchInput}
onChange={setSearchInput}
onSubmit={onSearchSubmit}
onClear={onSearchClear}
appliedQuery={appliedQuery}
searching={searching}
/>
{rows.length === 0 && appliedQuery && (
<div className="mt-6 rounded-2xl bg-white px-8 py-16 text-center ring-1 ring-zinc-200/60">
<p className="text-sm text-zinc-500">
No users match <span className="font-medium text-zinc-700">{appliedQuery}</span>.
{" "}
<button
type="button"
onClick={onSearchClear}
className="font-medium text-zinc-700 underline-offset-2 hover:underline"
>
Clear search
</button>
.
</p>
</div>
)}
{rows.length > 0 && (
<>
<div className="mt-6 hidden overflow-hidden rounded-2xl bg-white ring-1 ring-zinc-200/60 sm:block">
<table className="w-full table-fixed border-collapse">
<thead>
<tr className="bg-zinc-50/60">
<th className="w-[18%] px-5 py-3 text-left">
<HeaderTh k="f_username" label="From username" />
</th>
<th className="w-[18%] px-5 py-3 text-left text-[11px] font-medium uppercase tracking-wider text-zinc-500">
From password
</th>
<th className="w-[18%] px-5 py-3 text-left">
<HeaderTh k="t_username" label="To username" />
</th>
<th className="w-[18%] px-5 py-3 text-left text-[11px] font-medium uppercase tracking-wider text-zinc-500">
To password
</th>
<th className="px-5 py-3 text-left">
<HeaderTh k="last_update_time" label="Last update" />
</th>
<th className="w-20 px-3 py-3" aria-hidden="true" />
</tr>
</thead>
<tbody className="divide-y divide-zinc-100">
{optimistic.map((row) => {
const k = (f: string) => `${row.f_username}::${f}`;
return (
<tr key={row.f_username} className="transition-colors hover:bg-zinc-50/60">
<td className="px-5 py-3 align-middle font-mono text-[13px] font-semibold text-zinc-900">
{row.f_username}
</td>
<td className="px-5 py-3 align-middle">
<EditableCell
value={row.f_password}
label={`from password for ${row.f_username}`}
isCurrentlyEditing={editingKey === k("f_password")}
onEditStart={() => setEditingKey(k("f_password"))}
onEditEnd={() => setEditingKey(null)}
onSave={(v) => saveCell(row.f_username, "f_password", v)}
/>
</td>
<td className="px-5 py-3 align-middle">
<EditableCell
value={row.t_username}
label={`to username for ${row.f_username}`}
isCurrentlyEditing={editingKey === k("t_username")}
onEditStart={() => setEditingKey(k("t_username"))}
onEditEnd={() => setEditingKey(null)}
onSave={(v) => saveCell(row.f_username, "t_username", v)}
/>
</td>
<td className="px-5 py-3 align-middle">
<EditableCell
value={row.t_password}
label={`to password for ${row.f_username}`}
isCurrentlyEditing={editingKey === k("t_password")}
onEditStart={() => setEditingKey(k("t_password"))}
onEditEnd={() => setEditingKey(null)}
onSave={(v) => saveCell(row.f_username, "t_password", v)}
/>
</td>
<td className="px-5 py-3 align-middle text-xs text-zinc-500">
{formatTime(row.last_update_time)}
</td>
<td className="px-3 py-3 text-right align-middle">
<div className="inline-flex items-center gap-1">
<CopyButton
label={row.f_username}
onClick={() => handleCopy(row)}
/>
<DeleteButton
label={row.f_username}
onClick={() => {
setDeleteError(null);
setDeleteTarget(row.f_username);
}}
/>
</div>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
<div className="mt-6 space-y-3 sm:hidden">
{optimistic.map((row) => {
const k = (f: string) => `${row.f_username}::${f}`;
return (
<div key={row.f_username} className="rounded-2xl bg-white p-5 ring-1 ring-zinc-200/60">
<div className="flex items-center justify-between gap-2">
<span className="font-mono text-base font-semibold text-zinc-900">
{row.f_username}
</span>
<div className="flex items-center gap-2">
<span className="text-[11px] text-zinc-500">
{formatTime(row.last_update_time)}
</span>
<CopyButton
label={row.f_username}
onClick={() => handleCopy(row)}
/>
<DeleteButton
label={row.f_username}
onClick={() => {
setDeleteError(null);
setDeleteTarget(row.f_username);
}}
/>
</div>
</div>
<dl className="mt-4 space-y-3 border-t border-zinc-100 pt-4">
<MobileRow label="From PW">
<EditableCell
value={row.f_password}
label={`from password for ${row.f_username}`}
isCurrentlyEditing={editingKey === k("f_password")}
onEditStart={() => setEditingKey(k("f_password"))}
onEditEnd={() => setEditingKey(null)}
onSave={(v) => saveCell(row.f_username, "f_password", v)}
/>
</MobileRow>
<MobileRow label="To User">
<EditableCell
value={row.t_username}
label={`to username for ${row.f_username}`}
isCurrentlyEditing={editingKey === k("t_username")}
onEditStart={() => setEditingKey(k("t_username"))}
onEditEnd={() => setEditingKey(null)}
onSave={(v) => saveCell(row.f_username, "t_username", v)}
/>
</MobileRow>
<MobileRow label="To PW">
<EditableCell
value={row.t_password}
label={`to password for ${row.f_username}`}
isCurrentlyEditing={editingKey === k("t_password")}
onEditStart={() => setEditingKey(k("t_password"))}
onEditEnd={() => setEditingKey(null)}
onSave={(v) => saveCell(row.f_username, "t_password", v)}
/>
</MobileRow>
</dl>
</div>
);
})}
</div>
<div ref={sentinelRef} className="h-10" aria-hidden="true" />
{loadingMore && (
<p className="mt-4 text-center text-[11px] font-medium uppercase tracking-wider text-zinc-400">
Loading more
</p>
)}
{!hasMore && rows.length > 0 && (
<p className="mt-6 text-center text-[11px] text-zinc-400">
End of list {rows.length} users loaded
</p>
)}
</>
)}
<CreateUserDialog
open={createOpen}
onClose={() => setCreateOpen(false)}
onSuccess={async (name) => {
setToast({ type: "success", message: `User ${name} created` });
await refresh();
}}
/>
<Toast toast={toast} onDismiss={() => setToast(null)} />
<ConfirmDialog
open={!!deleteTarget}
onCancel={() => {
if (!deleting) setDeleteTarget(null);
}}
onConfirm={confirmDelete}
title={`Delete ${deleteTarget ?? ""}?`}
message={
<>
<p>
Permanently remove the user pairing for{" "}
<code className="rounded bg-zinc-100 px-1.5 py-0.5 font-mono text-xs text-zinc-700">
{deleteTarget}
</code>{" "}
from the users table. This action cannot be undone and only
removes the pairing the underlying account row stays.
</p>
{deleteError && (
<p className="mt-3 font-mono text-[11px] text-red-600" role="alert">
{deleteError}
</p>
)}
</>
}
confirmLabel="Delete"
destructive
pending={deleting}
/>
</div>
);
}
function SearchBar({
value,
onChange,
onSubmit,
onClear,
appliedQuery,
searching,
}: {
value: string;
onChange: (v: string) => void;
onSubmit: (e: React.FormEvent) => void;
onClear: () => void;
appliedQuery: string;
searching: boolean;
}) {
return (
<form onSubmit={onSubmit} role="search" className="mt-4 flex flex-wrap items-center gap-2">
<label className="sr-only" htmlFor="users-search">Search by username</label>
<input
id="users-search"
type="search"
autoComplete="off"
spellCheck={false}
placeholder="Search username (e.g. 13c4511)"
value={value}
onChange={(e) => onChange(e.target.value)}
className="min-w-0 flex-1 rounded-full bg-white px-4 py-1.5 text-sm text-zinc-900 ring-1 ring-zinc-200/60 placeholder:text-zinc-400 focus:outline-none focus:ring-2 focus:ring-zinc-900"
/>
<button
type="submit"
disabled={searching}
className="inline-flex items-center rounded-full bg-zinc-900 px-3 py-1.5 text-xs font-medium text-white shadow-sm transition-colors hover:bg-zinc-700 disabled:cursor-not-allowed disabled:opacity-50"
>
{searching ? "Finding…" : "Find"}
</button>
{appliedQuery && (
<button
type="button"
onClick={onClear}
disabled={searching}
className="inline-flex items-center rounded-full bg-white px-3 py-1.5 text-xs font-medium text-zinc-700 ring-1 ring-zinc-200/60 transition-colors hover:bg-zinc-50 disabled:cursor-not-allowed disabled:opacity-50"
>
Clear
</button>
)}
{appliedQuery && (
<span className="text-[11px] text-zinc-500">
Filtered by <span className="font-mono text-zinc-700">{appliedQuery}</span>
</span>
)}
</form>
);
}
function MobileRow({ label, children }: { label: string; children: React.ReactNode }) {
return (
<div className="grid grid-cols-[max-content_1fr] items-baseline gap-x-4">
<dt className="text-[11px] font-medium uppercase tracking-wider text-zinc-500">{label}</dt>
<dd className="min-w-0">{children}</dd>
</div>
);
}
function PageHead({
total,
loaded,
onAdd,
}: {
total: number;
loaded: number;
onAdd: () => void;
}) {
const showLoaded = loaded > 0 && loaded < total;
return (
<div>
<p className="text-[11px] font-medium uppercase tracking-wider text-zinc-500">Table</p>
<div className="mt-1 flex flex-wrap items-center justify-between gap-x-3 gap-y-2">
<h1 className="text-2xl font-semibold tracking-tight text-zinc-900 sm:text-3xl">
Users
<span className="ml-2 align-middle text-base font-medium text-zinc-400">
{total}
</span>
</h1>
<button
type="button"
onClick={onAdd}
aria-label="Add user"
className="inline-flex items-center gap-1.5 rounded-full bg-zinc-900 px-3 py-1.5 text-xs font-medium text-white shadow-sm transition-colors hover:bg-zinc-700"
>
<span aria-hidden="true">+</span>
Add
</button>
</div>
{showLoaded && (
<p className="mt-1 text-[11px] text-zinc-400">
Showing {loaded} of {total}
</p>
)}
</div>
);
}