refactor: focus admin dashboard layout

This commit is contained in:
2026-04-29 12:10:55 -04:00
parent baf7a497eb
commit 3d8ca8b54d
2 changed files with 753 additions and 245 deletions

View File

@@ -1,9 +1,15 @@
import {
Activity,
ChevronRight,
Clock3,
Database,
FileText,
Folder,
FolderGit2,
FolderOpen,
LogIn,
LogOut,
PanelLeftClose,
PanelLeftOpen,
RefreshCw,
Shield,
UserPlus,
@@ -12,6 +18,7 @@ import {
import { useEffect, useState } from "preact/hooks";
type Role = "admin" | "editor" | "viewer";
type View = "workspace" | "users";
type User = {
id: string;
@@ -47,32 +54,66 @@ type Session = {
user: User;
};
type BrowserItem = {
type: "folder" | "document";
name: string;
path: string;
document?: DocumentRecord;
indexDocument?: DocumentRecord;
};
type BrowserColumn = {
title: string;
prefix: string;
items: BrowserItem[];
};
const sessionKey = "mdhub.admin.session";
export function App() {
const [session, setSession] = useState<Session | null>(() => readSession());
const [activeView, setActiveView] = useState<View>("workspace");
const [sidebarOpen, setSidebarOpen] = useState(true);
const [users, setUsers] = useState<User[]>([]);
const [workspace, setWorkspace] = useState<WorkspaceResponse | null>(null);
const [status, setStatus] = useState("Idle");
const [syncing, setSyncing] = useState(false);
const [lastSyncedAt, setLastSyncedAt] = useState("");
const [activePath, setActivePath] = useState("");
const [selectedUserId, setSelectedUserId] = useState("");
async function refresh() {
if (!session) {
return;
}
setStatus("Refreshing");
const [usersResponse, workspaceResponse] = await Promise.all([
api<{ users: User[] }>("/api/admin/users"),
api<WorkspaceResponse>("/api/admin/workspace"),
]);
setUsers(usersResponse.users);
setWorkspace(workspaceResponse);
setStatus("Current");
setLastSyncedAt(new Date().toISOString());
}
useEffect(() => {
void refresh();
}, [session?.user.email]);
useEffect(() => {
const documents = workspace?.documents ?? [];
if (
documents.length > 0 &&
!isKnownDocumentLocation(documents, activePath)
) {
setActivePath(documents[0].path);
}
}, [workspace?.documents, activePath]);
useEffect(() => {
if (users.length > 0 && !users.some((user) => user.id === selectedUserId)) {
setSelectedUserId(users[0].id);
}
}, [users, selectedUserId]);
async function handleLogin(email: string, displayName: string) {
const response = await api<{ user: User }>("/api/admin/login", {
method: "POST",
@@ -88,17 +129,22 @@ export function App() {
displayName: string;
role: Role;
}) {
await api<{ user: User }>("/api/admin/users", {
const response = await api<{ user: User }>("/api/admin/users", {
method: "POST",
body: JSON.stringify(input),
});
await refresh();
setSelectedUserId(response.user.id);
}
async function handleSync() {
setStatus("Syncing");
await api("/api/admin/workspace/sync", { method: "POST" });
await refresh();
setSyncing(true);
try {
await api("/api/admin/workspace/sync", { method: "POST" });
await refresh();
} finally {
setSyncing(false);
}
}
function logout() {
@@ -106,56 +152,122 @@ export function App() {
setSession(null);
setUsers([]);
setWorkspace(null);
setStatus("Idle");
setActivePath("");
setSelectedUserId("");
}
if (!session) {
return <LoginScreen onLogin={handleLogin} />;
}
const selectedDocument = selectDocument(
workspace?.documents ?? [],
activePath,
);
const selectedUser =
users.find((user) => user.id === selectedUserId) ?? users[0];
return (
<main class="admin-shell">
<main class={`admin-shell ${sidebarOpen ? "" : "is-collapsed"}`}>
<aside class="admin-sidebar">
<a class="brand" href="/docs">
<Shield size={20} />
<span>MD Hub Secure</span>
</a>
<nav>
<a class="is-active" href="#workspace">
<div class="sidebar-header">
<a class="brand" href="/docs" title="Open public docs">
<Shield size={18} />
<span>MD Hub</span>
</a>
<button
class="icon-button"
type="button"
onClick={() => setSidebarOpen((open) => !open)}
aria-label={sidebarOpen ? "Collapse sidebar" : "Expand sidebar"}
>
{sidebarOpen ? (
<PanelLeftClose size={17} />
) : (
<PanelLeftOpen size={17} />
)}
</button>
</div>
<nav class="nav-list" aria-label="Admin sections">
<button
class={activeView === "workspace" ? "is-active" : ""}
type="button"
onClick={() => setActiveView("workspace")}
title="Workspace"
>
<FolderGit2 size={17} />
<span>Workspace</span>
</a>
<a href="#users">
</button>
<button
class={activeView === "users" ? "is-active" : ""}
type="button"
onClick={() => setActiveView("users")}
title="Users"
>
<Users size={17} />
<span>Users</span>
</a>
</button>
</nav>
<button class="ghost-button" type="button" onClick={logout}>
<button
class="nav-button"
type="button"
onClick={logout}
title="Sign out"
>
<LogOut size={16} />
<span>Sign out</span>
</button>
</aside>
<section class="admin-main">
<header class="admin-topbar">
<header class="compact-topbar">
<div>
<p class="eyebrow">Admin</p>
<h1>Workspace control</h1>
<span class="section-label">{activeView}</span>
<strong>
{activeView === "workspace" ? "Documents" : "Accounts"}
</strong>
</div>
<div class="topbar-actions">
<span class="status-pill">
<Activity size={14} />
{status}
{activeView === "workspace" && (
<button
type="button"
class="primary-button sync-button"
onClick={handleSync}
disabled={syncing}
aria-label="Sync workspace"
>
<RefreshCw size={15} />
<span>Sync</span>
</button>
)}
<span class="sync-label">
<Clock3 size={14} />
{syncing
? "Syncing"
: lastSyncedAt
? `Synced ${formatTime(lastSyncedAt)}`
: "Not synced"}
</span>
<button type="button" class="primary-button" onClick={handleSync}>
<RefreshCw size={16} />
Sync
</button>
</div>
</header>
<WorkspacePanel data={workspace} />
<UsersPanel users={users} onCreateUser={handleCreateUser} />
{activeView === "workspace" ? (
<WorkspaceView
data={workspace}
activePath={activePath}
selectedDocument={selectedDocument}
onSelectPath={setActivePath}
/>
) : (
<UsersView
users={users}
selectedUser={selectedUser}
onSelectUser={setSelectedUserId}
onCreateUser={handleCreateUser}
/>
)}
</section>
</main>
);
@@ -182,7 +294,7 @@ function LoginScreen(props: {
<main class="login-shell">
<form class="login-panel" onSubmit={submit}>
<div class="login-mark">
<Shield size={22} />
<Shield size={20} />
</div>
<h1>Admin login</h1>
<label>
@@ -205,7 +317,7 @@ function LoginScreen(props: {
</label>
{error && <p class="form-error">{error}</p>}
<button type="submit" class="primary-button">
<LogIn size={16} />
<LogIn size={15} />
Sign in
</button>
</form>
@@ -213,47 +325,170 @@ function LoginScreen(props: {
);
}
function WorkspacePanel(props: { data: WorkspaceResponse | null }) {
const workspace = props.data?.workspace;
function WorkspaceView(props: {
data: WorkspaceResponse | null;
activePath: string;
selectedDocument?: DocumentRecord;
onSelectPath: (path: string) => void;
}) {
const documents = props.data?.documents ?? [];
const columns = buildDocumentColumns(documents, props.activePath);
return (
<section id="workspace" class="panel">
<div class="panel-header">
<div>
<p class="eyebrow">Workspace</p>
<h2>Storage and documents</h2>
</div>
<Database size={19} />
</div>
<div class="metric-grid">
<Metric label="Documents" value={workspace?.documentCount ?? 0} />
<Metric label="Users" value={workspace?.userCount ?? 0} />
<Metric label="Database" value={workspace?.databasePath ?? "Loading"} />
<Metric label="Content" value={workspace?.sourceDir ?? "Loading"} />
</div>
<div class="document-table">
<div class="table-row table-row--head">
<span>Document</span>
<span>Hash</span>
<span>Updated</span>
</div>
{(props.data?.documents ?? []).map((document) => (
<div class="table-row" key={document.path}>
<a href={`/docs/${document.path.replace(/\.md$/, "")}`}>
{document.title}
</a>
<code>{document.currentHash.slice(0, 12)}</code>
<span>{formatDate(document.updatedAt)}</span>
<div class="workspace-grid">
<section class="column-browser" aria-label="Workspace files">
{columns.map((column) => (
<div class="browser-column" key={column.prefix || "root"}>
<header>{column.title}</header>
<div class="item-list">
{column.items.map((item) => (
<button
class={
isActiveItem(item, props.activePath)
? "list-item is-active"
: "list-item"
}
type="button"
key={`${item.type}:${item.path}`}
onClick={() =>
props.onSelectPath(item.indexDocument?.path ?? item.path)
}
>
{item.type === "folder" ? (
isActiveItem(item, props.activePath) ? (
<FolderOpen size={15} />
) : (
<Folder size={15} />
)
) : (
<FileText size={15} />
)}
<span>{item.name}</span>
{item.type === "folder" && <ChevronRight size={14} />}
</button>
))}
{column.items.length === 0 && (
<p class="empty-state">No documents</p>
)}
</div>
</div>
))}
</div>
</section>
</section>
<WorkspaceDetails
workspace={props.data?.workspace}
document={props.selectedDocument}
/>
</div>
);
}
function UsersPanel(props: {
function WorkspaceDetails(props: {
workspace?: Workspace;
document?: DocumentRecord;
}) {
return (
<aside class="detail-panel">
<header class="detail-header">
<Database size={17} />
<span>Details</span>
</header>
{props.document ? (
<>
<h2>{props.document.title}</h2>
<a class="open-link" href={documentHref(props.document.path)}>
Open document
</a>
<dl class="detail-list">
<div>
<dt>File</dt>
<dd>{props.document.path}</dd>
</div>
<div>
<dt>Hash</dt>
<dd>
<code>{props.document.currentHash.slice(0, 12)}</code>
</dd>
</div>
<div>
<dt>Updated</dt>
<dd>{formatDate(props.document.updatedAt)}</dd>
</div>
</dl>
</>
) : (
<p class="empty-state">Select a document.</p>
)}
{props.workspace && (
<dl class="detail-list compact">
<div>
<dt>Documents</dt>
<dd>{props.workspace.documentCount}</dd>
</div>
<div>
<dt>Content</dt>
<dd>{props.workspace.sourceDir}</dd>
</div>
<div>
<dt>Storage</dt>
<dd>{props.workspace.storeDir}</dd>
</div>
<div>
<dt>Database</dt>
<dd>{props.workspace.databasePath}</dd>
</div>
</dl>
)}
</aside>
);
}
function UsersView(props: {
users: User[];
selectedUser?: User;
onSelectUser: (id: string) => void;
onCreateUser: (input: {
email: string;
displayName: string;
role: Role;
}) => Promise<void>;
}) {
return (
<div class="workspace-grid">
<section class="browser-column user-column" aria-label="Users">
<header>Users</header>
<div class="item-list">
{props.users.map((user) => (
<button
class={
user.id === props.selectedUser?.id
? "list-item is-active"
: "list-item"
}
type="button"
key={user.id}
onClick={() => props.onSelectUser(user.id)}
>
<Users size={15} />
<span>{user.displayName}</span>
<small>{user.role}</small>
</button>
))}
</div>
</section>
<UserDetails
selectedUser={props.selectedUser}
onCreateUser={props.onCreateUser}
/>
</div>
);
}
function UserDetails(props: {
selectedUser?: User;
onCreateUser: (input: {
email: string;
displayName: string;
@@ -273,16 +508,13 @@ function UsersPanel(props: {
}
return (
<section id="users" class="panel">
<div class="panel-header">
<div>
<p class="eyebrow">Users</p>
<h2>Accounts and roles</h2>
</div>
<Users size={19} />
</div>
<aside class="detail-panel">
<header class="detail-header">
<UserPlus size={17} />
<span>Add user</span>
</header>
<form class="user-form" onSubmit={submit}>
<form class="stack-form" onSubmit={submit}>
<input
type="email"
placeholder="email@example.com"
@@ -306,35 +538,148 @@ function UsersPanel(props: {
<option value="admin">Admin</option>
</select>
<button type="submit" class="primary-button">
<UserPlus size={16} />
<UserPlus size={15} />
Add
</button>
</form>
<div class="user-list">
{props.users.map((user) => (
<article class="user-row" key={user.id}>
{props.selectedUser && (
<>
<h2>{props.selectedUser.displayName}</h2>
<dl class="detail-list">
<div>
<strong>{user.displayName}</strong>
<span>{user.email}</span>
<dt>Email</dt>
<dd>{props.selectedUser.email}</dd>
</div>
<span class="role-pill">{user.role}</span>
</article>
))}
</div>
</section>
<div>
<dt>Role</dt>
<dd>{props.selectedUser.role}</dd>
</div>
<div>
<dt>Created</dt>
<dd>{formatDate(props.selectedUser.createdAt)}</dd>
</div>
</dl>
</>
)}
</aside>
);
}
function Metric(props: { label: string; value: string | number }) {
function buildDocumentColumns(
documents: DocumentRecord[],
activePath: string,
): BrowserColumn[] {
const activeSegments = activePath.split("/").filter(Boolean);
const prefixes = [""];
const maxFolderDepth = activePath.endsWith(".md")
? activeSegments.length - 1
: activeSegments.length;
for (let index = 0; index < maxFolderDepth; index += 1) {
prefixes.push(activeSegments.slice(0, index + 1).join("/"));
}
return prefixes.map((prefix) => ({
title: prefix ? folderLabel(prefix) : "Documents",
prefix,
items: collectItems(documents, prefix),
}));
}
function collectItems(
documents: DocumentRecord[],
prefix: string,
): BrowserItem[] {
const items = new Map<string, BrowserItem>();
const prefixWithSlash = prefix ? `${prefix}/` : "";
for (const document of documents) {
if (!document.path.startsWith(prefixWithSlash)) {
continue;
}
const remainder = document.path.slice(prefixWithSlash.length);
if (!remainder || remainder === "index.md") {
continue;
}
const [nextSegment, ...rest] = remainder.split("/");
if (rest.length > 0) {
const folderPath = `${prefixWithSlash}${nextSegment}`;
const indexDocument = documents.find(
(candidate) => candidate.path === `${folderPath}/index.md`,
);
items.set(folderPath, {
type: "folder",
name: folderLabel(nextSegment),
path: folderPath,
indexDocument,
});
continue;
}
items.set(document.path, {
type: "document",
name: document.title || fileLabel(document.path),
path: document.path,
document,
});
}
return [...items.values()].sort((left, right) => {
if (left.type !== right.type) {
return left.type === "folder" ? -1 : 1;
}
return left.name.localeCompare(right.name);
});
}
function selectDocument(documents: DocumentRecord[], activePath: string) {
if (!activePath) {
return documents[0];
}
return (
<article class="metric">
<span>{props.label}</span>
<strong>{props.value}</strong>
</article>
documents.find((document) => document.path === activePath) ??
documents.find((document) => document.path === `${activePath}/index.md`)
);
}
function isKnownDocumentLocation(documents: DocumentRecord[], path: string) {
if (!path) {
return false;
}
return documents.some(
(document) =>
document.path === path ||
document.path === `${path}/index.md` ||
document.path.startsWith(`${path}/`),
);
}
function isActiveItem(item: BrowserItem, activePath: string) {
return (
activePath === item.path ||
activePath === item.indexDocument?.path ||
activePath.startsWith(`${item.path}/`)
);
}
function documentHref(path: string) {
return `/docs/${path.replace(/(^|\/)index\.md$/, "").replace(/\.md$/, "")}`;
}
function folderLabel(path: string) {
return fileLabel(path.split("/").filter(Boolean).at(-1) ?? path);
}
function fileLabel(path: string) {
return path
.replace(/\.md$/, "")
.replace(/[-_]/g, " ")
.replace(/\b\w/g, (match) => match.toUpperCase());
}
async function api<T = unknown>(path: string, init?: RequestInit): Promise<T> {
const response = await fetch(path, {
...init,
@@ -368,3 +713,10 @@ function formatDate(value: string) {
timeStyle: "short",
}).format(new Date(value));
}
function formatTime(value: string) {
return new Intl.DateTimeFormat(undefined, {
hour: "numeric",
minute: "2-digit",
}).format(new Date(value));
}