Processed some UI issues on journal
This commit is contained in:
@@ -0,0 +1,128 @@
|
||||
import { createContext, useCallback, useContext, useEffect, useRef, useState } from "react";
|
||||
import { Link } from "react-router-dom";
|
||||
import { getAdminSession, loginAdmin } from "../api";
|
||||
import Modal from "./Modal";
|
||||
import Icon from "./Icon";
|
||||
|
||||
const TOKEN_KEY = "alex-journal-admin";
|
||||
const AdminContext = createContext(null);
|
||||
export const useAdmin = () => useContext(AdminContext);
|
||||
|
||||
export default function AdminProvider({ children }) {
|
||||
const [token, setToken] = useState(() => sessionStorage.getItem(TOKEN_KEY) ?? "");
|
||||
const [checking, setChecking] = useState(Boolean(token));
|
||||
const [role, setRole] = useState(null);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [password, setPassword] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const [sessionRevision, setSessionRevision] = useState(0);
|
||||
const [checkAttempt, setCheckAttempt] = useState(0);
|
||||
const tokenRef = useRef(token);
|
||||
const verifiedToken = useRef("");
|
||||
|
||||
const signOut = useCallback(() => {
|
||||
tokenRef.current = "";
|
||||
verifiedToken.current = "";
|
||||
sessionStorage.removeItem(TOKEN_KEY);
|
||||
setToken("");
|
||||
setRole(null);
|
||||
setChecking(false);
|
||||
setPassword("");
|
||||
setOpen(false);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!token || verifiedToken.current === token) return;
|
||||
const controller = new AbortController();
|
||||
setChecking(true);
|
||||
getAdminSession(token, controller.signal)
|
||||
.then((session) => {
|
||||
if (!controller.signal.aborted && tokenRef.current === token) {
|
||||
verifiedToken.current = token;
|
||||
setRole(session.role);
|
||||
setError("");
|
||||
setSessionRevision((current) => current + 1);
|
||||
}
|
||||
})
|
||||
.catch((requestError) => {
|
||||
if (!controller.signal.aborted && tokenRef.current === token) {
|
||||
if (requestError.status === 401) signOut();
|
||||
setError(requestError.status === 401 ? requestError.message : "Could not check your session. Retry when your connection is back, or sign in again.");
|
||||
}
|
||||
})
|
||||
.finally(() => { if (!controller.signal.aborted) setChecking(false); });
|
||||
return () => controller.abort();
|
||||
}, [token, checkAttempt, signOut]);
|
||||
|
||||
useEffect(() => {
|
||||
const retry = () => { if (tokenRef.current && !verifiedToken.current) setCheckAttempt((current) => current + 1); };
|
||||
window.addEventListener("online", retry);
|
||||
window.addEventListener("focus", retry);
|
||||
return () => { window.removeEventListener("online", retry); window.removeEventListener("focus", retry); };
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const expire = (event) => {
|
||||
const expiredToken = event?.detail?.token ?? token;
|
||||
if (!expiredToken || expiredToken !== tokenRef.current) return;
|
||||
signOut();
|
||||
setError("Your session ended. Sign in again to manage articles.");
|
||||
};
|
||||
window.addEventListener("journal-session-expired", expire);
|
||||
const expiresAt = Number(token.split(".")[0]) * 1000;
|
||||
const timer = token ? setTimeout(expire, Math.max(0, expiresAt - Date.now())) : null;
|
||||
return () => {
|
||||
window.removeEventListener("journal-session-expired", expire);
|
||||
if (timer !== null) clearTimeout(timer);
|
||||
};
|
||||
}, [token, signOut]);
|
||||
|
||||
async function signIn(event) {
|
||||
event.preventDefault();
|
||||
if (busy) return;
|
||||
setBusy(true);
|
||||
setError("");
|
||||
try {
|
||||
const session = await loginAdmin(password);
|
||||
sessionStorage.setItem(TOKEN_KEY, session.access_token);
|
||||
tokenRef.current = session.access_token;
|
||||
verifiedToken.current = session.access_token;
|
||||
setToken(session.access_token);
|
||||
setRole(session.role);
|
||||
setChecking(false);
|
||||
setSessionRevision((current) => current + 1);
|
||||
setPassword("");
|
||||
setOpen(false);
|
||||
} catch (requestError) {
|
||||
setError(requestError.message);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
const isAdmin = role === "admin" && Boolean(token) && !checking;
|
||||
const close = () => { setOpen(false); setPassword(""); };
|
||||
return <AdminContext.Provider value={{ token, checking, isAdmin, sessionRevision, signOut, openSignIn: () => setOpen(true) }}>
|
||||
{children}
|
||||
{open && <Modal title={isAdmin ? "Admin account" : "Admin sign in"} onClose={close} busy={busy}>
|
||||
{isAdmin ? <div className="admin-account">
|
||||
<span className="publisher-badge"><span /> Admin</span>
|
||||
<p>You can create, edit, and delete journal articles.</p>
|
||||
<Link className="button button--primary" to="/blog/manage" onClick={close}><Icon name="plus" size={18} /> New article</Link>
|
||||
<Link className="button" to="/blog" onClick={close}>Manage articles</Link>
|
||||
<button className="text-button" type="button" onClick={signOut}><Icon name="logout" size={18} /> Sign out</button>
|
||||
</div> : <form className="admin-signin" onSubmit={signIn}>
|
||||
<p>Enter the admin password to manage journal articles.</p>
|
||||
<label className="publisher-field">
|
||||
<span>Admin password</span>
|
||||
<input autoFocus autoComplete="current-password" type="password" required maxLength={200}
|
||||
value={password} onChange={(event) => setPassword(event.target.value)} />
|
||||
</label>
|
||||
{error && <p className="form-status form-status--error" role="alert">{error}</p>}
|
||||
{token && !checking && <button className="text-button" type="button" onClick={() => setCheckAttempt((current) => current + 1)}>Retry session check</button>}
|
||||
<button className="button button--primary" type="submit" disabled={busy || checking}>{busy ? "Signing in…" : "Sign in"}</button>
|
||||
</form>}
|
||||
</Modal>}
|
||||
</AdminContext.Provider>;
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { useState } from "react";
|
||||
import { Link } from "react-router-dom";
|
||||
import { deleteArticle } from "../api";
|
||||
import { useAdmin } from "./AdminSession";
|
||||
import Icon from "./Icon";
|
||||
import Modal from "./Modal";
|
||||
|
||||
export default function ArticleAdminActions({ post, onDeleted }) {
|
||||
const { isAdmin, token } = useAdmin();
|
||||
const [confirming, setConfirming] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
if (!isAdmin) return null;
|
||||
|
||||
async function remove() {
|
||||
if (busy) return;
|
||||
setBusy(true);
|
||||
setError("");
|
||||
try {
|
||||
await deleteArticle(post.slug, token);
|
||||
setConfirming(false);
|
||||
onDeleted(post.slug);
|
||||
} catch (requestError) {
|
||||
setError(requestError.message);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return <div className="article-admin-actions">
|
||||
<Link className="text-button" to={`/blog/${post.slug}/edit`}><Icon name="edit" size={16} /> Edit</Link>
|
||||
<button className="text-button text-button--danger" type="button" onClick={() => { setError(""); setConfirming(true); }}>
|
||||
<Icon name="trash" size={16} /> Delete
|
||||
</button>
|
||||
{confirming && <Modal title="Delete article?" onClose={() => setConfirming(false)} busy={busy}>
|
||||
<p>“{post.title}” will be removed from the journal. This cannot be undone.</p>
|
||||
{error && <p className="form-status form-status--error" role="alert">{error}</p>}
|
||||
<div className="dialog-actions">
|
||||
<button autoFocus className="button" type="button" disabled={busy} onClick={() => setConfirming(false)}>Cancel</button>
|
||||
<button className="button button--danger" type="button" disabled={busy} onClick={remove}>{busy ? "Deleting…" : "Delete article"}</button>
|
||||
</div>
|
||||
</Modal>}
|
||||
</div>;
|
||||
}
|
||||
@@ -1,40 +1,184 @@
|
||||
import { useEffect, useId, useRef, useState } from "react";
|
||||
import { mediaUrl } from "../api";
|
||||
import Icon from "./Icon";
|
||||
|
||||
export default function ArticleUploads({ banner, attachments, busy, onUpload, onRemoveBanner, onRemoveAttachment }) {
|
||||
return (
|
||||
<fieldset className="article-uploads" disabled={busy}>
|
||||
<legend>Photos & files</legend>
|
||||
<label className="publisher-field">
|
||||
<span>Banner image</span>
|
||||
<small>Shown on the journal thumbnail and above the article title. JPEG, PNG, WebP or GIF, up to 8 MB.</small>
|
||||
<input type="file" accept="image/jpeg,image/png,image/webp,image/gif" onChange={(event) => {
|
||||
onUpload(Array.from(event.target.files), "banner");
|
||||
event.target.value = "";
|
||||
}} />
|
||||
</label>
|
||||
{banner && <div className="upload-preview">
|
||||
<img src={mediaUrl(banner)} alt="Banner preview" />
|
||||
<span>{banner.name}</span>
|
||||
<button type="button" className="text-button" onClick={onRemoveBanner}>Remove banner</button>
|
||||
const imageTypes = ["image/jpeg", "image/png", "image/webp", "image/gif"];
|
||||
const isImage = (file) => imageTypes.includes(file.type) || (!file.type && /\.(jpe?g|png|webp|gif)$/i.test(file.name));
|
||||
const fileSize = (size) => size < 1024 * 1024 ? `${Math.max(1, Math.round(size / 1024))} KB` : `${(size / 1024 / 1024).toFixed(1)} MB`;
|
||||
|
||||
function Dropzone({ purpose, disabled, onFiles, hasBanner }) {
|
||||
const input = useRef(null);
|
||||
const depth = useRef(0);
|
||||
const [dragging, setDragging] = useState(false);
|
||||
const hintId = useId();
|
||||
const banner = purpose === "banner";
|
||||
return <div className={`upload-dropzone ${dragging && !disabled ? "is-dragging" : ""} ${disabled ? "is-disabled" : ""}`}
|
||||
onDragEnter={(event) => { event.preventDefault(); depth.current += 1; setDragging(true); }}
|
||||
onDragOver={(event) => { event.preventDefault(); event.dataTransfer.dropEffect = disabled ? "none" : "copy"; }}
|
||||
onDragLeave={(event) => { event.preventDefault(); depth.current -= 1; if (depth.current <= 0) setDragging(false); }}
|
||||
onDrop={(event) => {
|
||||
event.preventDefault(); depth.current = 0; setDragging(false);
|
||||
if (!disabled) onFiles(Array.from(event.dataTransfer.files), purpose);
|
||||
}}>
|
||||
<span className="upload-dropzone__icon"><Icon name={banner ? "photo" : "upload"} size={25} /></span>
|
||||
<strong>{banner ? hasBanner ? "Drop a new banner to replace it" : "Give your article a cover" : "Add something worth sharing"}</strong>
|
||||
<p>{banner ? "Drag an image here, or choose one below." : "Drop photos, documents, or other files here."}</p>
|
||||
<button type="button" className="upload-browse" disabled={disabled} aria-describedby={hintId} onClick={() => input.current.click()}>
|
||||
<Icon name="plus" size={16} /> {banner ? hasBanner ? "Replace banner" : "Choose banner" : "Browse files"}
|
||||
</button>
|
||||
<small id={hintId}>{banner ? "JPG, PNG, WebP or GIF · Up to 8 MB" : "Up to 10 files · 20 MB each"}</small>
|
||||
<input ref={input} className="upload-input" type="file" tabIndex={-1}
|
||||
aria-label={banner ? "Banner image" : "Additional photos & files"}
|
||||
accept={banner ? "image/jpeg,image/png,image/webp,image/gif" : undefined}
|
||||
multiple={!banner} disabled={disabled} onChange={(event) => {
|
||||
onFiles(Array.from(event.target.files), purpose);
|
||||
event.target.value = "";
|
||||
}} />
|
||||
</div>;
|
||||
}
|
||||
|
||||
export default function ArticleUploads({ banner, attachments, busy, title, subtitle, onUpload, onPendingChange, onRemoveBanner, onRemoveAttachment, onMoveAttachment }) {
|
||||
const [tasks, setTasks] = useState([]);
|
||||
const [messages, setMessages] = useState([]);
|
||||
const queue = useRef([]);
|
||||
const running = useRef(false);
|
||||
const mounted = useRef(true);
|
||||
const previews = useRef(new Set());
|
||||
|
||||
useEffect(() => {
|
||||
mounted.current = true;
|
||||
return () => {
|
||||
mounted.current = false;
|
||||
queue.current.forEach((task) => task.controller?.abort());
|
||||
previews.current.forEach((url) => URL.revokeObjectURL(url));
|
||||
previews.current.clear();
|
||||
onPendingChange(false);
|
||||
};
|
||||
}, [onPendingChange]);
|
||||
|
||||
function updateQueue(next) {
|
||||
queue.current = next;
|
||||
if (mounted.current) { setTasks(next); onPendingChange(next.length > 0); }
|
||||
}
|
||||
|
||||
function forget(id) {
|
||||
const task = queue.current.find((item) => item.id === id);
|
||||
if (task?.preview) { URL.revokeObjectURL(task.preview); previews.current.delete(task.preview); }
|
||||
updateQueue(queue.current.filter((item) => item.id !== id));
|
||||
}
|
||||
|
||||
function change(id, values) {
|
||||
updateQueue(queue.current.map((task) => task.id === id ? { ...task, ...values } : task));
|
||||
}
|
||||
|
||||
async function processQueue() {
|
||||
if (running.current) return;
|
||||
running.current = true;
|
||||
try {
|
||||
let task;
|
||||
while (mounted.current && (task = queue.current.find((item) => item.status === "queued"))) {
|
||||
const controller = new AbortController();
|
||||
const id = task.id;
|
||||
change(id, { status: "uploading", controller, progress: 0 });
|
||||
try {
|
||||
await onUpload(task.file, task.purpose, {
|
||||
signal: controller.signal,
|
||||
onProgress: (progress) => { if (mounted.current) change(id, { progress }); },
|
||||
});
|
||||
if (mounted.current) forget(id);
|
||||
} catch (error) {
|
||||
if (mounted.current && error.name !== "AbortError") change(id, { status: "error", error: error.message });
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
running.current = false;
|
||||
}
|
||||
}
|
||||
|
||||
function addFiles(files, purpose) {
|
||||
if (busy || !files.length) return;
|
||||
const errors = [];
|
||||
if (purpose === "banner" && (files.length > 1 || queue.current.some((task) => task.purpose === "banner"))) {
|
||||
setMessages(["Choose one banner at a time. Finish or remove the current banner upload first."]);
|
||||
return;
|
||||
}
|
||||
const additions = [];
|
||||
const existing = [...attachments, ...queue.current.filter((task) => task.purpose === "attachment").map((task) => task.file)];
|
||||
for (const file of files) {
|
||||
const limit = (purpose === "banner" ? 8 : 20) * 1024 * 1024;
|
||||
if (!file.size) { errors.push(`${file.name}: this file is empty.`); continue; }
|
||||
if (file.size > limit) { errors.push(`${file.name}: exceeds the ${purpose === "banner" ? 8 : 20} MB limit.`); continue; }
|
||||
if (purpose === "banner" && !isImage(file)) { errors.push(`${file.name}: choose a JPG, PNG, WebP, or GIF image.`); continue; }
|
||||
if (purpose === "attachment" && existing.some((item) => item.name === file.name && item.size === file.size)) {
|
||||
errors.push(`${file.name}: already added.`); continue;
|
||||
}
|
||||
if (purpose === "attachment" && existing.length >= 10) { errors.push(`${file.name}: all 10 attachment slots are filled.`); continue; }
|
||||
const preview = isImage(file) ? URL.createObjectURL(file) : null;
|
||||
if (preview) previews.current.add(preview);
|
||||
additions.push({ id: crypto.randomUUID(), file, purpose, preview, status: "queued", progress: 0 });
|
||||
if (purpose === "attachment") existing.push(file);
|
||||
}
|
||||
setMessages(errors);
|
||||
if (additions.length) {
|
||||
updateQueue([...queue.current, ...additions]);
|
||||
processQueue();
|
||||
}
|
||||
}
|
||||
|
||||
function cancel(task) { task.controller?.abort(); forget(task.id); }
|
||||
const bannerTask = tasks.find((task) => task.purpose === "banner");
|
||||
const heroImage = bannerTask?.preview ?? (banner ? mediaUrl(banner) : null);
|
||||
const attachmentCount = attachments.length + tasks.filter((task) => task.purpose === "attachment").length;
|
||||
|
||||
return <fieldset className="article-uploads" disabled={busy}>
|
||||
<legend>Photos & files</legend>
|
||||
<div className="upload-section">
|
||||
<div className="upload-section__heading"><div><h3>Banner image</h3><p>Your journal thumbnail and article cover.</p></div><span className="upload-label">Optional</span></div>
|
||||
{heroImage && <div className="upload-hero-preview">
|
||||
<img src={heroImage} alt="Banner preview" />
|
||||
<div><span>{bannerTask ? "Preview · Upload pending" : "Hero preview"}</span><strong>{title || "Your article title"}</strong><p>{subtitle || "Your subtitle appears here, over the cover image."}</p></div>
|
||||
</div>}
|
||||
<label className="publisher-field">
|
||||
<span>Additional photos & files</span>
|
||||
<small>Displayed below the article text, in upload order. Up to 10 files, 20 MB each.</small>
|
||||
<input type="file" multiple onChange={(event) => {
|
||||
onUpload(Array.from(event.target.files), "attachment");
|
||||
event.target.value = "";
|
||||
}} />
|
||||
</label>
|
||||
{banner && <div className="upload-saved-banner"><span><Icon name="check" size={15} /> {banner.name} <small>{fileSize(banner.size)}</small></span>
|
||||
<button type="button" className="text-button" disabled={Boolean(bannerTask)} onClick={onRemoveBanner}>Remove banner</button></div>}
|
||||
<Dropzone purpose="banner" hasBanner={Boolean(banner)} disabled={busy || Boolean(bannerTask)} onFiles={addFiles} />
|
||||
<small className="upload-tip">Wide images work best. The cover is cropped to fill the hero and thumbnail.</small>
|
||||
</div>
|
||||
|
||||
<div className="upload-section">
|
||||
<div className="upload-section__heading"><div><h3>Additional photos & files</h3><p>Shown below your article, in this order.</p></div><span className="upload-label">{attachmentCount}/10</span></div>
|
||||
<Dropzone purpose="attachment" disabled={busy || attachmentCount >= 10} onFiles={addFiles} />
|
||||
{attachments.length > 0 && <ul className="upload-list">
|
||||
{attachments.map((file) => <li key={file.url}>
|
||||
{file.media_type.startsWith("image/") && <img src={mediaUrl(file)} alt="" />}
|
||||
<span>{file.name} <small>({Math.ceil(file.size / 1024)} KB)</small></span>
|
||||
<button type="button" className="text-button" aria-label={`Remove ${file.name}`} onClick={() => onRemoveAttachment(file.url)}>Remove</button>
|
||||
{attachments.map((file, index) => <li key={file.url}>
|
||||
<span className="upload-file-icon">{file.media_type.startsWith("image/") ? <img src={mediaUrl(file)} alt="" /> : <Icon name="file" size={24} />}</span>
|
||||
<div className="upload-file-info"><strong>{file.name}</strong><small>{fileSize(file.size)} · <span className="upload-ready">Ready</span></small></div>
|
||||
<div className="upload-file-actions">
|
||||
<button type="button" className="upload-icon-button" disabled={index === 0} aria-label={`Move ${file.name} up`} title="Move up" onClick={() => onMoveAttachment(file.url, -1)}><Icon name="up" size={17} /></button>
|
||||
<button type="button" className="upload-icon-button" disabled={index === attachments.length - 1} aria-label={`Move ${file.name} down`} title="Move down" onClick={() => onMoveAttachment(file.url, 1)}><Icon name="down" size={17} /></button>
|
||||
<button type="button" className="upload-icon-button" aria-label={`Remove ${file.name}`} title="Remove file" onClick={() => onRemoveAttachment(file.url)}><Icon name="close" size={17} /></button>
|
||||
</div>
|
||||
</li>)}
|
||||
</ul>}
|
||||
{busy && <p role="status">Uploading…</p>}
|
||||
</fieldset>
|
||||
);
|
||||
</div>
|
||||
|
||||
{messages.length > 0 && <div className="upload-feedback" role="alert"><strong>Some files could not be added</strong><ul>{messages.map((message, index) => <li key={index}>{message}</li>)}</ul><button type="button" className="text-button" onClick={() => setMessages([])}>Dismiss</button></div>}
|
||||
{tasks.length > 0 && <div className="upload-queue">
|
||||
<h3>Upload queue</h3>
|
||||
<ul className="upload-list">{tasks.map((task) => <li key={task.id} className={task.status === "error" ? "has-error" : ""}>
|
||||
<span className="upload-file-icon">{task.preview ? <img src={task.preview} alt="" /> : <Icon name="file" size={24} />}</span>
|
||||
<div className="upload-file-info"><strong>{task.file.name}</strong><small>{fileSize(task.file.size)} · {task.purpose === "banner" ? "Banner" : "Attachment"}</small>
|
||||
{task.status === "error" ? <p role="alert">{task.error}</p> : <>
|
||||
<small>{task.status === "queued" ? "Waiting to upload" : task.progress === 100 ? "Processing file…" : `Uploading ${task.progress}%`}</small>
|
||||
<progress max="100" value={task.progress} aria-label={`Uploading ${task.file.name}`} />
|
||||
</>}
|
||||
</div>
|
||||
<div className="upload-file-actions">
|
||||
{task.status === "error" && <button type="button" className="text-button" aria-label={`Retry ${task.file.name}`} onClick={() => { change(task.id, { status: "queued", error: "" }); processQueue(); }}>Retry</button>}
|
||||
<button type="button" className="upload-icon-button" aria-label={`${task.status === "error" ? "Remove" : "Cancel"} upload ${task.file.name}`} onClick={() => cancel(task)}><Icon name="close" size={18} /></button>
|
||||
</div>
|
||||
</li>)}</ul>
|
||||
<p className="upload-tip" role="status">{tasks.some((task) => task.status === "error") ? "Retry or remove failed uploads before publishing." : "You can keep writing while your files upload."}</p>
|
||||
</div>}
|
||||
</fieldset>;
|
||||
}
|
||||
|
||||
export function ArticleAttachments({ attachments = [] }) {
|
||||
|
||||
@@ -1,4 +1,12 @@
|
||||
const paths = {
|
||||
upload: <path d="M12 16V3m-5 5 5-5 5 5M4 16v5h16v-5" />,
|
||||
photo: <><rect x="3" y="3" width="18" height="18" rx="3" /><circle cx="8" cy="8" r="1.5" /><path d="m3 17 6-6 4 4 3-3 5 5" /></>,
|
||||
file: <><path d="M14 2H5v20h14V7l-5-5Zm0 0v6h5M8 13h8M8 17h5" /></>,
|
||||
up: <path d="m6 14 6-6 6 6" />,
|
||||
down: <path d="m6 10 6 6 6-6" />,
|
||||
user: <><circle cx="12" cy="8" r="4" /><path d="M4 21v-2a8 8 0 0 1 16 0v2" /></>,
|
||||
edit: <><path d="m15 4 5 5M4 20l5-1L21 7a2 2 0 0 0-5-5L4 14v6Z" /></>,
|
||||
trash: <><path d="M3 6h18M9 6V3h6v3M5 6l1 15h12l1-15M10 10v7M14 10v7" /></>,
|
||||
arrow: <path d="M5 12h14m-5-5 5 5-5 5" />,
|
||||
arrowLeft: <path d="m11 17-5-5 5-5m-5 5h13" />,
|
||||
arrowUpRight: <path d="M7 17 17 7M8 7h9v9" />,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { NavLink, useLocation } from "react-router-dom";
|
||||
import Icon from "./Icon";
|
||||
import { useAdmin } from "./AdminSession";
|
||||
|
||||
const navItems = [
|
||||
{ label: "About", to: "/" },
|
||||
@@ -11,6 +12,7 @@ const navItems = [
|
||||
];
|
||||
|
||||
function Header({ name }) {
|
||||
const { isAdmin, checking, openSignIn } = useAdmin();
|
||||
const [menuOpen, setMenuOpen] = useState(false);
|
||||
const location = useLocation();
|
||||
|
||||
@@ -20,10 +22,11 @@ function Header({ name }) {
|
||||
<header className="site-header">
|
||||
<div className="container header-inner">
|
||||
<NavLink className="brand" to="/" aria-label={`${name} home`}>
|
||||
<span className="brand-mark">AH</span>
|
||||
<img className="brand-mark brand-photo" src="/alex-avatar-96.webp" width="42" height="42" alt="" />
|
||||
<span className="brand-name">{name}</span>
|
||||
</NavLink>
|
||||
|
||||
<div className="header-actions">
|
||||
<nav className={`nav-shell ${menuOpen ? "is-open" : ""}`} aria-label="Main navigation">
|
||||
{navItems.map((item) => (
|
||||
<NavLink
|
||||
@@ -37,6 +40,13 @@ function Header({ name }) {
|
||||
))}
|
||||
</nav>
|
||||
|
||||
<button type="button" className={`icon-button header-signin ${isAdmin ? "is-admin" : ""}`}
|
||||
aria-label={isAdmin ? "Admin account" : "Admin sign in"} title={isAdmin ? "Admin account" : "Admin sign in"}
|
||||
aria-haspopup="dialog" disabled={checking} onClick={openSignIn}>
|
||||
<Icon name={isAdmin ? "user" : "lock"} />
|
||||
{isAdmin && <span className="admin-indicator" />}
|
||||
</button>
|
||||
|
||||
<button
|
||||
aria-expanded={menuOpen}
|
||||
aria-label={menuOpen ? "Close navigation" : "Open navigation"}
|
||||
@@ -46,6 +56,7 @@ function Header({ name }) {
|
||||
>
|
||||
<Icon name={menuOpen ? "close" : "menu"} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
@@ -75,6 +86,41 @@ export default function Layout({ children, profile }) {
|
||||
const name = profile?.display_name ?? "Alex Herlan";
|
||||
const isAbout = location.pathname === "/";
|
||||
|
||||
useEffect(() => {
|
||||
let pressed = null;
|
||||
let origin = null;
|
||||
const clear = () => {
|
||||
pressed?.removeAttribute("data-pressed");
|
||||
pressed = null;
|
||||
origin = null;
|
||||
};
|
||||
const press = (event) => {
|
||||
clear();
|
||||
if (!event.isPrimary || event.button !== 0) return;
|
||||
const control = event.target.closest?.(".button, .culture-link");
|
||||
if (!control || control.matches(":disabled")) return;
|
||||
pressed = control;
|
||||
origin = { x: event.clientX, y: event.clientY };
|
||||
pressed.setAttribute("data-pressed", "true");
|
||||
};
|
||||
const move = (event) => {
|
||||
if (origin && Math.hypot(event.clientX - origin.x, event.clientY - origin.y) > 10) clear();
|
||||
};
|
||||
window.addEventListener("pointerdown", press, { passive: true });
|
||||
window.addEventListener("pointermove", move, { passive: true });
|
||||
window.addEventListener("pointerup", clear);
|
||||
window.addEventListener("pointercancel", clear);
|
||||
window.addEventListener("blur", clear);
|
||||
return () => {
|
||||
clear();
|
||||
window.removeEventListener("pointerdown", press);
|
||||
window.removeEventListener("pointermove", move);
|
||||
window.removeEventListener("pointerup", clear);
|
||||
window.removeEventListener("pointercancel", clear);
|
||||
window.removeEventListener("blur", clear);
|
||||
};
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="app-shell">
|
||||
<a className="skip-link" href="#main-content">Skip to content</a>
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { useEffect, useId, useRef } from "react";
|
||||
import Icon from "./Icon";
|
||||
|
||||
export default function Modal({ title, children, onClose, busy = false }) {
|
||||
const dialog = useRef(null);
|
||||
const titleId = useId();
|
||||
useEffect(() => {
|
||||
const element = dialog.current;
|
||||
element.showModal();
|
||||
return () => element.close();
|
||||
}, []);
|
||||
|
||||
return <dialog ref={dialog} className="admin-dialog" aria-labelledby={titleId}
|
||||
onCancel={(event) => { event.preventDefault(); if (!busy) onClose(); }}>
|
||||
<div className="admin-dialog__heading">
|
||||
<h2 id={titleId}>{title}</h2>
|
||||
<button type="button" className="icon-button" aria-label="Close dialog" disabled={busy} onClick={onClose}><Icon name="close" /></button>
|
||||
</div>
|
||||
{children}
|
||||
</dialog>;
|
||||
}
|
||||
@@ -7,15 +7,15 @@ export function LoadingState({ label = "Loading" }) {
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorState({ message }) {
|
||||
export function ErrorState({ message, onRetry, retrying = false }) {
|
||||
return (
|
||||
<div className="state-card state-card--error" role="alert">
|
||||
<span className="state-icon">!</span>
|
||||
<div>
|
||||
<strong>That didn’t load.</strong>
|
||||
<p>{message}</p>
|
||||
{onRetry && <button className="button" type="button" disabled={retrying} onClick={onRetry}>{retrying ? "Retrying..." : "Try again"}</button>}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user