diff --git a/README.md b/README.md index aa7f0e3..fbb95da 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,12 @@ In a second terminal, run `npm run dev:web`, then open **http://localhost:5173** Samples use example addresses. Supply your own destination, media, contact information, Wi-Fi credentials, or wallet address before using a QR code. Scan-test the final export, especially after changing contrast, shapes, or logos. +## Edit a saved QR code + +Select a saved QR code, then choose **Edit QR** to load its current content and design into the editor. Update the fields and choose **Update saved QR**; the record and its audit history refresh after saving. Select a content type or cancel editing to return to creating a new record. + +A dynamic QR keeps the same encoded link when its destination or landing content changes, so existing prints continue to work. A static QR encodes its content directly: changing that content requires a new print. Design changes also require a new print to appear on the printed code. + ## Build and run ```sh diff --git a/src/client/App.tsx b/src/client/App.tsx index e84a47b..6a3d93c 100644 --- a/src/client/App.tsx +++ b/src/client/App.tsx @@ -1,9 +1,9 @@ import { Archive, Download, ImagePlus, Link2, Palette, QrCode, RefreshCw, Save, ShieldCheck } from 'lucide-react'; -import { useEffect, useMemo, useState } from 'react'; +import { useEffect, useMemo, useRef, useState } from 'react'; import { bodyShapes, defaultDesignConfig, eyeBalls, eyeFrames, logoGallery, templates } from '../qr/design'; import { getLogoIcon } from '../qr/logo-icons'; import { buildPayload } from '../qr/payloads'; -import type { ContentType, DesignConfig, QrMode, QrRecord } from '../shared/types'; +import type { AuditEvent, ContentType, DesignConfig, QrMode, QrRecord } from '../shared/types'; import { sampleContent } from './sample-content'; const contentTypes: ContentType[] = ['url', 'text', 'email', 'phone', 'sms', 'vcard', 'mecard', 'maps', 'facebook', 'twitter', 'youtube', 'wifi', 'event', 'crypto']; @@ -21,29 +21,47 @@ export function App() { const [keyword, setKeyword] = useState(''); const [preview, setPreview] = useState(''); const [downloadData, setDownloadData] = useState('https://example.com'); - const [error, setError] = useState(''); + const [errors, setErrors] = useState>({}); + const setError = (operation: string, message: string) => setErrors((current) => ({ ...current, [operation]: message })); + const clearDraftErrors = () => setErrors((current) => { + const { save, upload, json, ...remaining } = current; + return remaining; + }); + const detailRequest = useRef(0); + const detailTarget = useRef(null); + const previewRequest = useRef(0); + const recordsRequest = useRef(0); + const uploadRequest = useRef(0); + const saveRequest = useRef(0); + const editingId = useRef(null); + const editLoadingRef = useRef(false); + const [editLoading, setEditLoading] = useState(false); + const savePendingRef = useRef(false); + const [savePending, setSavePending] = useState(false); + const [uploadPending, setUploadPending] = useState(false); + const [detailPending, setDetailPending] = useState(false); + const [intendedId, setIntendedId] = useState(null); + const invalidateNavigation = () => { clearDraftErrors(); setError('detail', ''); detailRequest.current++; setDetailPending(false); saveRequest.current++; uploadRequest.current++; setUploadPending(false); editLoadingRef.current = false; setEditLoading(false); editingId.current = null; setKeyword(''); }; const [records, setRecords] = useState([]); const [selected, setSelected] = useState(null); + const [auditEvents, setAuditEvents] = useState([]); + const [editing, setEditing] = useState(null); const encodedPayload = useMemo(() => JSON.stringify(payload, null, 2), [payload]); - useEffect(() => { - setPayload(defaults[type]); - if (moreTypes.includes(type)) setMode('dynamic_payload'); - }, [type]); - useEffect(() => { void refreshPreview(); - }, [payload, design, size]); + }, [type, payload, design, size, editing]); useEffect(() => { void loadRecords(); }, []); async function refreshPreview() { + const request = ++previewRequest.current; try { - setError(''); - const data = await buildPreviewPayload(type, payload); + const data = editing && editing.mode !== 'static' ? editing.encodedPayload : await buildPreviewPayload(type, payload); + if (request !== previewRequest.current) return; setDownloadData(data); const response = await fetch('/api/qr/custom', { method: 'POST', @@ -51,43 +69,136 @@ export function App() { body: JSON.stringify({ data, size, file: 'svg', config: design }) }); if (!response.ok) throw new Error((await response.json()).error || 'Preview failed'); - setPreview(URL.createObjectURL(await response.blob())); + const blob = await response.blob(); + if (request !== previewRequest.current) return; + setPreview((old) => { if (old && typeof URL.revokeObjectURL === 'function') URL.revokeObjectURL(old); return URL.createObjectURL(blob); }); + setError('preview', ''); } catch (err) { - setError(err instanceof Error ? err.message : 'Preview failed'); + if (request === previewRequest.current) setError('preview', err instanceof Error ? err.message : 'Preview failed'); } } async function saveQr() { - const response = await fetch('/api/qr-codes', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ name, mode, contentType: type, contentPayload: payload, designConfig: design, sizePx: size, keyword: keyword || undefined }) - }); - if (!response.ok) { - setError((await response.json()).error || 'Save failed'); - return; + if (savePendingRef.current || uploadPending || editLoadingRef.current) return; + savePendingRef.current = true; + setSavePending(true); + const request = ++saveRequest.current; + const id = editingId.current; + try { + const response = await fetch(id ? `/api/qr-codes/${id}` : '/api/qr-codes', { + method: id ? 'PATCH' : 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ name, mode, contentType: type, contentPayload: payload, designConfig: design, sizePx: size, keyword: keyword || undefined }) + }); + if (!response.ok) throw new Error((await response.json()).error || 'Save failed'); + // A navigation may make the save's UI effects obsolete, but the server + // mutation still changes the list and invalidates older list requests. + const recordsRefresh = loadRecords(); + let qr: QrRecord; + try { + qr = (await response.json()) as QrRecord; + } catch (err) { + // PATCH already identifies the changed record even if its response is unreadable. + if (id && (request === saveRequest.current || detailTarget.current === id)) void loadDetail(id); + throw err; + } + if (request === saveRequest.current) setError('save', ''); + const shouldLoadDetail = request === saveRequest.current || detailTarget.current === qr.id; + const detail = shouldLoadDetail ? await loadDetail(qr.id) : null; + if (request === saveRequest.current) { + if (id && detail && detail.id === id) setEditing(detail); + } + await recordsRefresh; + } catch (err) { + if (request === saveRequest.current) setError('save', err instanceof Error ? err.message : 'Save failed'); + } finally { + savePendingRef.current = false; + setSavePending(false); } - const qr = (await response.json()) as QrRecord; - setSelected(qr); - await loadRecords(); } async function loadRecords() { - const response = await fetch('/api/qr-codes'); - if (response.ok) setRecords(await response.json()); + const request = ++recordsRequest.current; + try { + const response = await fetch('/api/qr-codes'); + if (!response.ok) throw new Error(response.status === 401 ? 'Admin token required. The bundled UI has no token login; configure access through your deployment.' : 'Could not load saved QR codes'); + const result = await response.json(); + if (request !== recordsRequest.current) return; + setRecords(result); + setError('records', ''); + } catch (err) { + if (request === recordsRequest.current) setError('records', err instanceof Error ? err.message : 'Could not load saved QR codes'); + } + } + + async function loadDetail(id: string) { + detailTarget.current = id; + setIntendedId(id); + setDetailPending(true); + setError('detail', ''); + const request = ++detailRequest.current; + try { + const response = await fetch(`/api/qr-codes/${id}`); + if (!response.ok) throw new Error((await response.json()).error || 'Could not load QR code'); + const detail: { qr: QrRecord; auditEvents: AuditEvent[] } = await response.json(); + if (request !== detailRequest.current) return null; + setError('detail', ''); + setSelected(detail.qr); + setAuditEvents(detail.auditEvents); + return detail.qr; + } catch (err) { + if (request === detailRequest.current) setError('detail', err instanceof Error ? err.message : 'Could not load QR code'); + return null; + } finally { + if (request === detailRequest.current) setDetailPending(false); + } + } + + async function editRecord(id: string) { + if (editLoadingRef.current || savePendingRef.current || detailPending || intendedId !== id) return; + editLoadingRef.current = true; + setEditLoading(true); + saveRequest.current++; + uploadRequest.current++; + setUploadPending(false); + const request = detailRequest.current + 1; + const record = await loadDetail(id); + if (request !== detailRequest.current) return; + editLoadingRef.current = false; + setEditLoading(false); + if (!record) return; + clearDraftErrors(); + uploadRequest.current++; + setUploadPending(false); + editingId.current = record.id; + setType(record.contentType); + setMode(record.mode); + setName(record.name); + setPayload(record.contentPayload); + setDesign(record.designConfig); + setSize(record.sizePx); + setKeyword(record.yourlsKeyword || ''); + setEditing(record); } async function uploadLogo(file?: File) { if (!file) return; + const request = ++uploadRequest.current; + setUploadPending(true); const form = new FormData(); form.set('file', file); - const response = await fetch('/api/qr/upload-image', { method: 'POST', body: form }); - if (!response.ok) { - setError((await response.json()).error || 'Upload failed'); - return; + try { + const response = await fetch('/api/qr/upload-image', { method: 'POST', body: form }); + if (!response.ok) throw new Error((await response.json()).error || 'Upload failed'); + const result = await response.json(); + if (request !== uploadRequest.current) return; + setDesign((current) => ({ ...current, logo: result.file })); + setError('upload', ''); + } catch (err) { + if (request === uploadRequest.current) setError('upload', err instanceof Error ? err.message : 'Upload failed'); + } finally { + if (request === uploadRequest.current) setUploadPending(false); } - const result = await response.json(); - setDesign({ ...design, logo: result.file }); } return ( @@ -111,7 +222,7 @@ export function App() {