167 lines
9.1 KiB
TypeScript
167 lines
9.1 KiB
TypeScript
import React, { useRef, useState } from 'react';
|
||
import type { SitesmithReference, SitesmithRefImage } from '../../hooks/useSitesmith';
|
||
import { btn, btnDanger, btnPrimary, errBox, inputStyle, note, thumb, warnBox } from './Section';
|
||
import type { Outcome } from './useSitesmithRefs';
|
||
|
||
interface Props {
|
||
references: SitesmithReference[];
|
||
images: SitesmithRefImage[];
|
||
selected: number[];
|
||
onSelectedChange: (ids: number[]) => void;
|
||
imageUrl: (id: string) => string;
|
||
loadError?: string | null;
|
||
addRef: (url: string, likes: string, shots: string[]) => Promise<Outcome>;
|
||
updateRef: (id: number, url: string, likes: string, shots: string[]) => Promise<Outcome>;
|
||
deleteRef: (id: number) => Promise<Outcome>;
|
||
uploadShot: (f: File) => Promise<Outcome & { image?: SitesmithRefImage }>;
|
||
removeImage: (id: string) => Promise<Outcome>;
|
||
maxRefs: number;
|
||
/** Image features unavailable (no vision): text-only entries still work. */
|
||
imagesUnavailableReason?: string | null;
|
||
disabled?: boolean;
|
||
}
|
||
|
||
const MAX_SHOTS = 3;
|
||
|
||
interface FormState { id: number | null; url: string; likes: string; shots: string[]; added: string[] }
|
||
const EMPTY: FormState = { id: null, url: '', likes: '', shots: [], added: [] };
|
||
|
||
/** "Sites I like": a per-site list of label + notes + optional screenshots. The address is a label and is never fetched. */
|
||
export const SitesILikePanel: React.FC<Props> = ({
|
||
references, images, selected, onSelectedChange, imageUrl, loadError, addRef, updateRef, deleteRef, uploadShot, removeImage,
|
||
maxRefs, imagesUnavailableReason, disabled,
|
||
}) => {
|
||
const [form, setForm] = useState<FormState | null>(null);
|
||
const [err, setErr] = useState<string | null>(null);
|
||
const [busy, setBusy] = useState(false);
|
||
const [confirmDel, setConfirmDel] = useState<number | null>(null);
|
||
const fileRef = useRef<HTMLInputElement>(null);
|
||
const imgById = new Map(images.map((i) => [i.id, i]));
|
||
|
||
const startAdd = () => { setErr(null); setForm({ ...EMPTY }); };
|
||
const startEdit = (r: SitesmithReference) => { setErr(null); setForm({ id: r.id, url: r.url_label, likes: r.what_i_like, shots: [...r.screenshot_ids], added: [] }); };
|
||
|
||
const cancel = async () => {
|
||
// Screenshots uploaded for a form that was never saved would be orphans: drop them.
|
||
if (form) for (const id of form.added) await removeImage(id);
|
||
setForm(null); setErr(null);
|
||
};
|
||
|
||
const save = async () => {
|
||
if (!form) return;
|
||
setBusy(true); setErr(null);
|
||
try {
|
||
const r = form.id === null
|
||
? await addRef(form.url, form.likes, form.shots)
|
||
: await updateRef(form.id, form.url, form.likes, form.shots);
|
||
if (!r.ok) { setErr(r.message); return; }
|
||
setForm(null);
|
||
} finally { setBusy(false); }
|
||
};
|
||
|
||
const addShot = async (files: FileList | null) => {
|
||
if (!files || !form) return;
|
||
setErr(null); setBusy(true);
|
||
let count = form.shots.length;
|
||
try {
|
||
for (const f of Array.from(files)) {
|
||
if (count >= MAX_SHOTS) { setErr(`Up to ${MAX_SHOTS} screenshots per site.`); break; }
|
||
const r = await uploadShot(f);
|
||
if (!r.ok) { setErr(r.message); break; }
|
||
const id = r.image!.id;
|
||
count++;
|
||
setForm((s) => (s ? { ...s, shots: [...s.shots, id], added: [...s.added, id] } : s));
|
||
}
|
||
} finally { setBusy(false); }
|
||
};
|
||
|
||
const dropShot = async (id: string) => {
|
||
if (!form) return;
|
||
// Removing from a saved entry detaches it; an image added in this form is deleted outright.
|
||
if (form.added.includes(id)) await removeImage(id);
|
||
setForm((s) => (s ? { ...s, shots: s.shots.filter((x) => x !== id), added: s.added.filter((x) => x !== id) } : s));
|
||
};
|
||
|
||
const del = async (id: number) => {
|
||
setErr(null);
|
||
const r = await deleteRef(id);
|
||
setConfirmDel(null);
|
||
if (!r.ok) { setErr(r.message); return; }
|
||
onSelectedChange(selected.filter((x) => x !== id));
|
||
};
|
||
|
||
const toggle = (id: number) => onSelectedChange(selected.includes(id) ? selected.filter((x) => x !== id) : [...selected, id]);
|
||
|
||
return (
|
||
<div data-testid="ss-sites-i-like">
|
||
<p style={note} data-testid="ss-sites-copy">
|
||
List websites whose look you admire and say what you like about each. The address is only a label for you:
|
||
<strong> Sitesmith does not open, visit or fetch it</strong>. It works from your description and any screenshots you attach yourself.
|
||
</p>
|
||
{loadError && <div style={errBox} role="alert">{loadError}</div>}
|
||
{err && !form && <div style={errBox} role="alert">{err}</div>}
|
||
|
||
{references.length === 0 && !form && <p style={note}>No sites yet.</p>}
|
||
<ul style={{ listStyle: 'none', margin: 0, padding: 0, display: 'flex', flexDirection: 'column', gap: 8 }}>
|
||
{references.map((r) => (
|
||
<li key={r.id} data-testid="ss-ref-item" style={{ border: '1px solid #27272a', borderRadius: 6, padding: 8 }}>
|
||
<div style={{ display: 'flex', alignItems: 'flex-start', gap: 8 }}>
|
||
<input type="checkbox" checked={selected.includes(r.id)} disabled={disabled} onChange={() => toggle(r.id)} aria-label={`Use ${r.url_label} for the next request`} style={{ marginTop: 3 }} />
|
||
<div style={{ flex: 1, minWidth: 0 }}>
|
||
<div style={{ fontWeight: 600, color: '#e4e4e7', overflowWrap: 'anywhere' }}>{r.url_label}</div>
|
||
<div style={{ color: '#a1a1aa', whiteSpace: 'pre-wrap', overflowWrap: 'anywhere' }}>{r.what_i_like}</div>
|
||
{r.screenshot_ids.length > 0 && (
|
||
<div style={{ display: 'flex', gap: 6, marginTop: 6 }}>
|
||
{r.screenshot_ids.map((sid) => (
|
||
<img key={sid} src={imageUrl(sid)} alt={`Screenshot ${imgById.get(sid)?.name ?? ''}`} style={{ ...thumb, width: 48, height: 48 }} />
|
||
))}
|
||
</div>
|
||
)}
|
||
</div>
|
||
<button type="button" style={btn} disabled={disabled} onClick={() => startEdit(r)} aria-label={`Edit ${r.url_label}`}>Edit</button>
|
||
{confirmDel === r.id
|
||
? <button type="button" style={btnDanger} onClick={() => void del(r.id)} autoFocus>Confirm delete</button>
|
||
: <button type="button" style={btnDanger} disabled={disabled} onClick={() => setConfirmDel(r.id)} aria-label={`Delete ${r.url_label}`}>Delete</button>}
|
||
</div>
|
||
</li>
|
||
))}
|
||
</ul>
|
||
|
||
{form ? (
|
||
<div style={{ marginTop: 10, border: '1px solid #3f3f46', borderRadius: 6, padding: 10 }} data-testid="ss-ref-form">
|
||
<label style={{ display: 'block', fontSize: 12, color: '#a1a1aa', marginBottom: 2 }} htmlFor="ss-ref-url">Site address (label only, not opened)</label>
|
||
<input id="ss-ref-url" style={inputStyle} value={form.url} maxLength={300} placeholder="example.com" onChange={(e) => setForm({ ...form, url: e.target.value })} />
|
||
<label style={{ display: 'block', fontSize: 12, color: '#a1a1aa', margin: '8px 0 2px' }} htmlFor="ss-ref-likes">What I like about it</label>
|
||
<textarea id="ss-ref-likes" style={{ ...inputStyle, minHeight: 60, resize: 'vertical' }} value={form.likes} maxLength={1000} placeholder="Big photo header, lots of white space, simple menu" onChange={(e) => setForm({ ...form, likes: e.target.value })} />
|
||
<div style={{ fontSize: 12, color: '#a1a1aa', margin: '8px 0 4px' }}>Screenshots (optional, up to {MAX_SHOTS})</div>
|
||
{imagesUnavailableReason
|
||
? <div style={warnBox} role="note">{imagesUnavailableReason}</div>
|
||
: (
|
||
<div style={{ display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>
|
||
{form.shots.map((sid) => (
|
||
<span key={sid} style={{ position: 'relative' }}>
|
||
<img src={imageUrl(sid)} alt="Screenshot" style={{ ...thumb, width: 56, height: 56 }} />
|
||
<button type="button" onClick={() => void dropShot(sid)} aria-label="Remove screenshot" style={{ ...btnDanger, position: 'absolute', top: -6, right: -6, padding: '0 5px', fontSize: 11 }}>×</button>
|
||
</span>
|
||
))}
|
||
{form.shots.length < MAX_SHOTS && (
|
||
<button type="button" style={btn} disabled={busy} onClick={() => fileRef.current?.click()}>Add screenshot</button>
|
||
)}
|
||
<input ref={fileRef} type="file" hidden multiple accept="image/jpeg,image/png,image/webp,image/gif" data-testid="ss-shot-input" onChange={(e) => { void addShot(e.target.files); e.target.value = ''; }} />
|
||
</div>
|
||
)}
|
||
{err && <div style={errBox} role="alert">{err}</div>}
|
||
<div style={{ display: 'flex', gap: 8, marginTop: 10 }}>
|
||
<button type="button" style={btnPrimary} disabled={busy} onClick={() => void save()}>{form.id === null ? 'Add site' : 'Save changes'}</button>
|
||
<button type="button" style={btn} disabled={busy} onClick={() => void cancel()}>Cancel</button>
|
||
</div>
|
||
</div>
|
||
) : (
|
||
<button type="button" style={{ ...btn, marginTop: 10 }} disabled={disabled || references.length >= maxRefs} onClick={startAdd}>
|
||
Add a site I like{references.length >= maxRefs ? ` (limit ${maxRefs} reached)` : ''}
|
||
</button>
|
||
)}
|
||
</div>
|
||
);
|
||
};
|