Sitesmith self-review capture: sanitise page HTML before it reaches the frame (inert DOMParser allow-list, fixed-point guard), CSP + script-less sandbox, real-browser hostile-page proof; UI building blocks (attachments, sites I like, asset awareness, design payload)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
shadowdaoandClaude Sonnet 5.5 committed 2026-11-01 10:31:29 -08:00
1 parent 0fde4dc22f
commit 197b9c46ab
14 files changed
+965 -10

No files matched your search

@@ -0,0 +1,53 @@
import React from 'react';
import type { SitesmithAsset } from '../../hooks/useSitesmith';
import { note, thumb, errBox } from './Section';
interface Props {
assets: SitesmithAsset[];
loaded: boolean;
error?: string | null;
/** Filenames Sitesmith may see. */
included: Set<string>;
onToggle: (filename: string) => void;
onAll: (on: boolean) => void;
/** Public-safe display URL for a thumbnail. */
thumbUrl: (a: SitesmithAsset) => string;
visionAvailable: boolean;
disabled?: boolean;
}
/** Which uploaded images Sitesmith will see, with the captions it has, and a per-image toggle. */
export const AssetAwareness: React.FC<Props> = ({ assets, loaded, error, included, onToggle, onAll, thumbUrl, visionAvailable, disabled }) => (
<div data-testid="ss-assets">
<p style={note}>
Sitesmith can use the images you uploaded to this site and place them on the page. Untick any you do not want it to use.
{visionAvailable
? ' It looks at each picture (a small copy) and writes a short description the first time.'
: ' Image viewing is not available on this server, so Sitesmith works from file names and sizes only.'}
</p>
{error && <div style={errBox} role="alert">{error}</div>}
{!loaded && !error && <p style={note}>Loading your images…</p>}
{loaded && !error && assets.length === 0 && <p style={note}>You have not uploaded any images yet. Add some in the Assets tab and Sitesmith will be able to use them.</p>}
{assets.length > 0 && (
<>
<div style={{ marginBottom: 6, fontSize: 12 }}>
<button type="button" disabled={disabled} onClick={() => onAll(true)} style={{ background: 'none', border: 'none', color: '#a78bfa', cursor: 'pointer', padding: 0, marginRight: 12 }}>Include all</button>
<button type="button" disabled={disabled} onClick={() => onAll(false)} style={{ background: 'none', border: 'none', color: '#a78bfa', cursor: 'pointer', padding: 0 }}>Include none</button>
<span style={{ color: '#71717a', marginLeft: 12 }}>{included.size} of {assets.length} included</span>
</div>
<ul style={{ listStyle: 'none', margin: 0, padding: 0, display: 'flex', flexDirection: 'column', gap: 6, maxHeight: 220, overflowY: 'auto' }}>
{assets.map((a) => (
<li key={a.filename} data-testid="ss-asset-item" style={{ display: 'flex', gap: 8, alignItems: 'center', opacity: included.has(a.filename) ? 1 : 0.5 }}>
<input type="checkbox" checked={included.has(a.filename)} disabled={disabled} onChange={() => onToggle(a.filename)} aria-label={`Let Sitesmith use ${a.filename}`} />
<img src={thumbUrl(a)} alt="" loading="lazy" style={{ ...thumb, width: 40, height: 40 }} />
<div style={{ minWidth: 0 }}>
<div style={{ color: '#e4e4e7', overflowWrap: 'anywhere' }}>{a.filename}{a.width && a.height ? <span style={{ color: '#71717a' }}> · {a.width}×{a.height}</span> : null}</div>
<div style={{ color: '#a1a1aa', fontSize: 12 }}>{a.caption || a.alt || 'No description yet'}</div>
</div>
</li>
))}
</ul>
</>
)}
</div>
);
@@ -0,0 +1,113 @@
import React, { useRef, useState } from 'react';
import type { SitesmithRefImage } from '../../hooks/useSitesmith';
import { formatBytes } from '../../utils/sitesmith-attachments';
import { btn, btnDanger, errBox, note, thumb, warnBox } from './Section';
interface Props {
/** Mockup images already stored for this site (from refs_list). */
images: SitesmithRefImage[];
selected: string[];
onSelectedChange: (ids: string[]) => void;
/** Total image budget for one send (mockups + reference screenshots). */
maxAttach: number;
/** Images already counted by selected "Sites I like" entries. */
referenceImageCount: number;
imageUrl: (id: string) => string;
onUpload: (file: File) => Promise<{ ok: true; image?: SitesmithRefImage } | { ok: false; message: string }>;
onRemove: (id: string) => Promise<{ ok: true } | { ok: false; message: string }>;
/** Image features off: why (vision unavailable). Text-only generation is unaffected. */
unavailableReason?: string | null;
disabled?: boolean;
/** Called with the message when a file is rejected or an upload fails. */
}
/** Mockup picker: drag and drop or file picker, thumbnails, remove. Image names are rendered as text nodes only. */
export const AttachmentTray: React.FC<Props> = ({
images, selected, onSelectedChange, maxAttach, referenceImageCount, imageUrl, onUpload, onRemove, unavailableReason, disabled,
}) => {
const input = useRef<HTMLInputElement>(null);
const [drag, setDrag] = useState(false);
const [busy, setBusy] = useState(false);
const [err, setErr] = useState<string | null>(null);
const mockups = images.filter((i) => i.kind === 'mockup');
const off = !!unavailableReason || !!disabled;
const used = selected.length + referenceImageCount;
const addFiles = async (files: FileList | File[] | null) => {
if (!files || off) return;
setErr(null);
setBusy(true);
try {
for (const f of Array.from(files)) {
if (used + 1 > maxAttach) { setErr(`You can attach up to ${maxAttach} images to one request.`); break; }
const r = await onUpload(f);
if (!r.ok) { setErr(r.message); break; }
if (r.image) onSelectedChange([...selected, r.image.id]);
}
} finally { setBusy(false); }
};
const toggle = (id: string) => {
if (selected.includes(id)) onSelectedChange(selected.filter((x) => x !== id));
else if (used < maxAttach) onSelectedChange([...selected, id]);
else setErr(`You can attach up to ${maxAttach} images to one request.`);
};
const remove = async (id: string) => {
setErr(null);
const r = await onRemove(id);
if (!r.ok) { setErr(r.message); return; }
onSelectedChange(selected.filter((x) => x !== id));
};
return (
<div data-testid="ss-mockups">
<p style={note}>
Attach a picture of the page you want (a sketch, a screenshot, a design export). Sitesmith builds toward it.
The image is kept privately for Sitesmith; it is never published or added to your assets.
</p>
{unavailableReason && <div style={warnBox} role="note" data-testid="ss-vision-note">{unavailableReason}</div>}
<div
data-testid="ss-dropzone"
onDragOver={(e) => { if (off) return; e.preventDefault(); setDrag(true); }}
onDragLeave={() => setDrag(false)}
onDrop={(e) => { e.preventDefault(); setDrag(false); void addFiles(e.dataTransfer?.files ?? null); }}
style={{
border: `1px dashed ${drag ? '#a78bfa' : '#3f3f46'}`, borderRadius: 8, padding: 12, textAlign: 'center',
background: drag ? 'rgba(124,58,237,0.12)' : 'transparent', opacity: off ? 0.5 : 1,
}}
>
<button type="button" style={btn} disabled={off || busy} onClick={() => input.current?.click()}>
{busy ? 'Uploading…' : 'Choose an image'}
</button>
<span style={{ color: '#a1a1aa', fontSize: 12, marginLeft: 8 }}>or drop it here (JPEG, PNG, WebP or GIF, up to 8 MB)</span>
<input
ref={input} type="file" accept="image/jpeg,image/png,image/webp,image/gif" hidden multiple
data-testid="ss-mockup-input" disabled={off}
onChange={(e) => { void addFiles(e.target.files); e.target.value = ''; }}
/>
</div>
{err && <div role="alert" style={errBox}>{err}</div>}
{mockups.length > 0 && (
<ul style={{ listStyle: 'none', margin: '10px 0 0', padding: 0, display: 'flex', flexWrap: 'wrap', gap: 10 }}>
{mockups.map((im) => {
const on = selected.includes(im.id);
return (
<li key={im.id} style={{ width: 96 }} data-testid="ss-mockup-item">
<label style={{ display: 'block', cursor: 'pointer' }}>
<img src={imageUrl(im.id)} alt={`Mockup ${im.name}`} style={{ ...thumb, width: 96, height: 72, outline: on ? '2px solid #a78bfa' : 'none' }} />
<span style={{ display: 'flex', alignItems: 'center', gap: 4, fontSize: 11, color: '#d4d4d8', marginTop: 3 }}>
<input type="checkbox" checked={on} disabled={off} onChange={() => toggle(im.id)} aria-label={`Use ${im.name} for the next request`} />
<span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{im.name}</span>
</span>
</label>
<div style={{ fontSize: 10, color: '#71717a' }}>{im.width && im.height ? `${im.width}×${im.height} · ` : ''}{formatBytes(im.size)}</div>
<button type="button" style={{ ...btnDanger, marginTop: 3, padding: '2px 6px', fontSize: 11 }} disabled={off} onClick={() => void remove(im.id)} aria-label={`Remove ${im.name}`}>Remove</button>
</li>
);
})}
</ul>
)}
</div>
);
};
+30
View File
@@ -0,0 +1,30 @@
import React from 'react';
const sectionStyle: React.CSSProperties = { border: '1px solid #27272a', borderRadius: 8, marginBottom: 8, background: '#13131c' };
const headStyle: React.CSSProperties = { display: 'flex', alignItems: 'center', gap: 8, width: '100%', background: 'transparent', border: 'none', color: '#e4e4e7', padding: '8px 12px', cursor: 'pointer', fontSize: 13, fontWeight: 600, textAlign: 'left' };
const bodyStyle: React.CSSProperties = { padding: '4px 12px 12px', fontSize: 13, color: '#d4d4d8' };
/** Collapsible block used by the Sitesmith context area. */
export const Section: React.FC<{
id: string; title: string; icon?: string; badge?: string; open: boolean; onToggle: () => void; children: React.ReactNode;
}> = ({ id, title, icon, badge, open, onToggle, children }) => (
<div style={sectionStyle} data-testid={`ss-section-${id}`}>
<button type="button" style={headStyle} aria-expanded={open} aria-controls={`ss-sec-${id}`} onClick={onToggle}>
{icon && <i className={`fa ${icon}`} aria-hidden style={{ color: '#a78bfa', width: 16 }} />}
<span>{title}</span>
{badge && <span style={{ fontSize: 11, color: '#a1a1aa', fontWeight: 400 }}>{badge}</span>}
<span style={{ flex: 1 }} />
<i className={`fa fa-chevron-${open ? 'up' : 'down'}`} aria-hidden style={{ color: '#71717a', fontSize: 11 }} />
</button>
{open && <div id={`ss-sec-${id}`} style={bodyStyle}>{children}</div>}
</div>
);
export const note: React.CSSProperties = { fontSize: 12, color: '#a1a1aa', lineHeight: 1.5, margin: '4px 0 8px' };
export const warnBox: React.CSSProperties = { background: 'rgba(245,158,11,0.12)', border: '1px solid rgba(245,158,11,0.4)', color: '#fde68a', padding: '6px 10px', borderRadius: 6, fontSize: 12, margin: '6px 0' };
export const errBox: React.CSSProperties = { background: '#3b1d1d', border: '1px solid #7f1d1d', color: '#fecaca', padding: '6px 10px', borderRadius: 6, fontSize: 12, margin: '6px 0' };
export const btn: React.CSSProperties = { background: 'transparent', color: '#e4e4e7', border: '1px solid #3f3f46', borderRadius: 4, padding: '4px 10px', fontSize: 12, cursor: 'pointer' };
export const btnPrimary: React.CSSProperties = { background: '#7c3aed', color: '#fff', border: '1px solid #7c3aed', borderRadius: 4, padding: '4px 12px', fontSize: 12, cursor: 'pointer' };
export const btnDanger: React.CSSProperties = { background: 'transparent', color: '#fca5a5', border: '1px solid #7f1d1d', borderRadius: 4, padding: '4px 10px', fontSize: 12, cursor: 'pointer' };
export const inputStyle: React.CSSProperties = { width: '100%', boxSizing: 'border-box', background: '#0f0f17', color: '#e5e7eb', border: '1px solid #3f3f46', borderRadius: 6, padding: '6px 8px', fontSize: 13 };
export const thumb: React.CSSProperties = { width: 64, height: 64, objectFit: 'cover', borderRadius: 6, border: '1px solid #3f3f46', background: '#0f0f17', display: 'block' };
@@ -0,0 +1,165 @@
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);
try {
for (const f of Array.from(files)) {
if (form.shots.length >= 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;
setForm((s) => (s ? { ...s, shots: [...s.shots, id], added: [...s.added, id] } : s));
form.shots = [...form.shots, id];
}
} 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>
);
};
@@ -0,0 +1,85 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import type { SitesmithReference, SitesmithRefImage, SitesmithApiResult } from '../../hooks/useSitesmith';
import { validateAttachment, normalizeUrlLabel, DEFAULT_MAX_UPLOAD_BYTES } from '../../utils/sitesmith-attachments';
/** The slice of useSitesmith() this state needs (keeps it easy to fake in tests). */
export interface RefsApi {
listRefs: () => Promise<SitesmithApiResult<{ references: SitesmithReference[]; images: SitesmithRefImage[] }>>;
addReference: (r: { url_label: string; what_i_like: string; screenshot_ids?: string[] }) => Promise<SitesmithApiResult<{ reference: SitesmithReference }>>;
updateReference: (id: number, p: { url_label?: string; what_i_like?: string; screenshot_ids?: string[] }) => Promise<SitesmithApiResult<{ reference: SitesmithReference }>>;
deleteReference: (id: number) => Promise<SitesmithApiResult<object>>;
uploadRefImage: (f: File | Blob, kind: 'mockup' | 'screenshot') => Promise<SitesmithApiResult<{ image: SitesmithRefImage }>>;
deleteRefImage: (id: string) => Promise<SitesmithApiResult<object>>;
}
export type Outcome = { ok: true } | { ok: false; message: string };
/** Mockups, reference screenshots and "Sites I like" for one site. Never throws. */
export function useSitesmithRefs(api: RefsApi, enabled: boolean, maxUploadBytes = DEFAULT_MAX_UPLOAD_BYTES) {
const [references, setReferences] = useState<SitesmithReference[]>([]);
const [images, setImages] = useState<SitesmithRefImage[]>([]);
const [loaded, setLoaded] = useState(false);
const [loadError, setLoadError] = useState<string | null>(null);
const apiRef = useRef(api);
apiRef.current = api;
const alive = useRef(true);
useEffect(() => { alive.current = true; return () => { alive.current = false; }; }, []);
const load = useCallback(async () => {
const r = await apiRef.current.listRefs();
if (!alive.current) return;
if (r.ok) { setReferences(r.references ?? []); setImages(r.images ?? []); setLoadError(null); }
else setLoadError(r.message);
setLoaded(true);
}, []);
useEffect(() => { if (enabled && !loaded) void load(); }, [enabled, loaded, load]);
const uploadImage = useCallback(async (file: File, kind: 'mockup' | 'screenshot'): Promise<Outcome & { image?: SitesmithRefImage }> => {
const bad = await validateAttachment(file, maxUploadBytes);
if (bad) return { ok: false, message: bad };
const r = await apiRef.current.uploadRefImage(file, kind);
if (!r.ok) return { ok: false, message: r.message };
if (alive.current) setImages((xs) => [...xs, r.image]);
return { ok: true, image: r.image };
}, [maxUploadBytes]);
const removeImage = useCallback(async (id: string): Promise<Outcome> => {
const r = await apiRef.current.deleteRefImage(id);
if (!r.ok) return { ok: false, message: r.message };
if (alive.current) {
setImages((xs) => xs.filter((i) => i.id !== id));
setReferences((rs) => rs.map((x) => ({ ...x, screenshot_ids: x.screenshot_ids.filter((s) => s !== id) })));
}
return { ok: true };
}, []);
const addRef = useCallback(async (urlLabel: string, whatILike: string, screenshotIds: string[] = []): Promise<Outcome & { reference?: SitesmithReference }> => {
const u = normalizeUrlLabel(urlLabel);
if (!u.ok) return u;
if (!whatILike.trim()) return { ok: false, message: 'Say what you like about this site so Sitesmith knows what to take from it.' };
const r = await apiRef.current.addReference({ url_label: u.value, what_i_like: whatILike.trim(), screenshot_ids: screenshotIds });
if (!r.ok) return { ok: false, message: r.message };
if (alive.current) setReferences((rs) => [...rs, r.reference]);
return { ok: true, reference: r.reference };
}, []);
const updateRef = useCallback(async (id: number, urlLabel: string, whatILike: string, screenshotIds?: string[]): Promise<Outcome> => {
const u = normalizeUrlLabel(urlLabel);
if (!u.ok) return u;
if (!whatILike.trim()) return { ok: false, message: 'Say what you like about this site so Sitesmith knows what to take from it.' };
const r = await apiRef.current.updateReference(id, { url_label: u.value, what_i_like: whatILike.trim(), ...(screenshotIds ? { screenshot_ids: screenshotIds } : {}) });
if (!r.ok) return { ok: false, message: r.message };
if (alive.current) setReferences((rs) => rs.map((x) => (x.id === id ? r.reference : x)));
return { ok: true };
}, []);
const deleteRef = useCallback(async (id: number): Promise<Outcome> => {
const r = await apiRef.current.deleteReference(id);
if (!r.ok) return { ok: false, message: r.message };
if (alive.current) setReferences((rs) => rs.filter((x) => x.id !== id));
return { ok: true };
}, []);
return { references, images, loaded, loadError, reload: load, uploadImage, removeImage, addRef, updateRef, deleteRef };
}