Added behavior journal, adjusted layout, and added some colors
This commit is contained in:
1 parent
b1b89ad334
commit
3237cd7601
31 files changed
+2135
-275
No files matched your search
@@ -0,0 +1,132 @@
|
||||
import { useEffect, useMemo, useState, type FormEvent } from 'react';
|
||||
import './behaviorJournal.css';
|
||||
|
||||
type BehaviorType = { id: string; name: string; description: string | null };
|
||||
type Occurrence = {
|
||||
id: string; birdId: string; behaviorTypeId: string; behaviorName: string; occurredAt: string;
|
||||
durationSeconds: number | null; severity: number | null; notes: string | null; createdAt: string; updatedAt: string;
|
||||
};
|
||||
type Props = {
|
||||
bird: { id: string; name: string }; birds: { id: string; name: string }[]; onSelectBird: (id: string) => void; token: string; writable: boolean;
|
||||
apiFetch: (path: string, token?: string, init?: RequestInit) => Promise<Response>;
|
||||
};
|
||||
const localDate = (date: Date) => `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
|
||||
const localTime = (date: Date) => `${localDate(date)}T${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
|
||||
const emptyForm = () => ({ behaviorTypeId: '', occurredAt: localTime(new Date()), duration: '', severity: '', notes: '' });
|
||||
|
||||
export function BehaviorJournal({ bird, birds, onSelectBird, token, writable, apiFetch }: Props) {
|
||||
const [month, setMonth] = useState(() => new Date(new Date().getFullYear(), new Date().getMonth(), 1));
|
||||
const [day, setDay] = useState(() => localDate(new Date()));
|
||||
const [filter, setFilter] = useState('');
|
||||
const [types, setTypes] = useState<BehaviorType[]>([]);
|
||||
const [entries, setEntries] = useState<Occurrence[]>([]);
|
||||
const [form, setForm] = useState(emptyForm);
|
||||
const [editing, setEditing] = useState<Occurrence | null>(null);
|
||||
const [showForm, setShowForm] = useState(false);
|
||||
const [customName, setCustomName] = useState('');
|
||||
const [customDescription, setCustomDescription] = useState('');
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [notice, setNotice] = useState('');
|
||||
const [revision, setRevision] = useState(0);
|
||||
const base = `/birds/${bird.id}`;
|
||||
|
||||
async function request(path: string, init?: RequestInit) {
|
||||
const response = await apiFetch(path, token, { ...init, headers: { 'Content-Type': 'application/json', ...init?.headers } });
|
||||
if (response.status === 204) return null;
|
||||
const data = await response.json();
|
||||
if (!response.ok) throw new Error(data.error || 'Unable to update the journal.');
|
||||
return data;
|
||||
}
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
setLoading(true); setError(''); setEntries([]);
|
||||
const query = new URLSearchParams({ from: month.toISOString(), to: new Date(month.getFullYear(), month.getMonth() + 1, 1).toISOString() });
|
||||
if (filter) query.set('behaviorTypeId', filter);
|
||||
Promise.all([request(`${base}/behavior-types`), request(`${base}/behaviors?${query}`)])
|
||||
.then(([typeData, occurrenceData]) => { if (active) { setTypes(typeData.behaviorTypes); setEntries(occurrenceData.occurrences); } })
|
||||
.catch((e) => { if (active) setError(e instanceof Error ? e.message : 'Unable to load journal.'); })
|
||||
.finally(() => { if (active) setLoading(false); });
|
||||
return () => { active = false; };
|
||||
}, [bird.id, token, month, filter, revision]);
|
||||
|
||||
const byDay = useMemo(() => {
|
||||
const result = new Map<string, Occurrence[]>();
|
||||
entries.forEach((entry) => { const key = localDate(new Date(entry.occurredAt)); result.set(key, [...(result.get(key) || []), entry]); });
|
||||
return result;
|
||||
}, [entries]);
|
||||
function navigate(offset: number) {
|
||||
const next = new Date(month.getFullYear(), month.getMonth() + offset, 1);
|
||||
setMonth(next); setDay(localDate(next));
|
||||
}
|
||||
function edit(entry: Occurrence) {
|
||||
setEditing(entry); setShowForm(true); setError(''); setNotice('');
|
||||
setForm({ behaviorTypeId: entry.behaviorTypeId, occurredAt: localTime(new Date(entry.occurredAt)), duration: entry.durationSeconds === null ? '' : String(entry.durationSeconds), severity: entry.severity === null ? '' : String(entry.severity), notes: entry.notes || '' });
|
||||
}
|
||||
async function save(event: FormEvent) {
|
||||
event.preventDefault(); setSaving(true); setError(''); setNotice('');
|
||||
try {
|
||||
let typeId = form.behaviorTypeId;
|
||||
if (typeId === 'custom') {
|
||||
const data = await request(`${base}/behavior-types`, { method: 'POST', body: JSON.stringify({ name: customName, description: customDescription }) });
|
||||
typeId = data.behaviorType.id;
|
||||
setTypes((previous) => [...previous.filter((type) => type.id !== typeId), data.behaviorType]);
|
||||
setForm((previous) => ({ ...previous, behaviorTypeId: typeId }));
|
||||
}
|
||||
// Preserve sub-second precision if the timestamp was not edited.
|
||||
const occurredAt = editing && form.occurredAt === localTime(new Date(editing.occurredAt)) ? editing.occurredAt : new Date(form.occurredAt).toISOString();
|
||||
await request(`${base}/behaviors${editing ? `/${editing.id}` : ''}`, { method: editing ? 'PUT' : 'POST', body: JSON.stringify({ behaviorTypeId: typeId, occurredAt, durationSeconds: form.duration === '' ? null : Number(form.duration), severity: form.severity === '' ? null : Number(form.severity), notes: form.notes || null }) });
|
||||
const savedDate = new Date(occurredAt);
|
||||
setMonth(new Date(savedDate.getFullYear(), savedDate.getMonth(), 1)); setDay(localDate(savedDate));
|
||||
setFilter(''); setShowForm(false); setEditing(null); setRevision((value) => value + 1); setNotice('Occurrence saved.');
|
||||
} catch (e) { setError(e instanceof Error ? e.message : 'Unable to save occurrence.'); }
|
||||
finally { setSaving(false); }
|
||||
}
|
||||
async function remove(entry: Occurrence) {
|
||||
if (!window.confirm(`Delete this ${entry.behaviorName} occurrence?`)) return;
|
||||
setSaving(true); setError(''); setNotice('');
|
||||
try {
|
||||
await request(`${base}/behaviors/${entry.id}`, { method: 'DELETE' });
|
||||
if (editing?.id === entry.id) { setShowForm(false); setEditing(null); }
|
||||
setRevision((value) => value + 1); setNotice('Occurrence deleted.');
|
||||
} catch (e) { setError(e instanceof Error ? e.message : 'Unable to delete occurrence.'); }
|
||||
finally { setSaving(false); }
|
||||
}
|
||||
const days = new Date(month.getFullYear(), month.getMonth() + 1, 0).getDate();
|
||||
return <section className="panel inset-panel behavior-journal" role="tabpanel" aria-label="Behavior Journal">
|
||||
<div className="panel-header"><div><p className="eyebrow">{bird.name}</p><h2>Behavior Journal</h2></div>
|
||||
{writable && <button type="button" className="primary-button" disabled={saving} onClick={() => { setForm(emptyForm()); setEditing(null); setCustomName(''); setCustomDescription(''); setShowForm(true); setError(''); setNotice(''); }}>Record behavior</button>}
|
||||
</div>
|
||||
<p className="muted">Record what you observed and review when it happened. Dates and times use your device’s local time zone.</p>
|
||||
{error && <p className="error-banner" role="alert">{error}</p>}
|
||||
{notice && <p className="success-banner" role="status">{notice}</p>}
|
||||
{showForm && writable && <form onSubmit={save} className="behavior-form">
|
||||
<h3>{editing ? 'Edit occurrence' : 'Record occurrence'}</h3>
|
||||
<fieldset disabled={saving}>
|
||||
<label>Behavior<select aria-label="Behavior" required value={form.behaviorTypeId} onChange={(e) => setForm({ ...form, behaviorTypeId: e.target.value })}><option value="">Select behavior</option>{types.map((type) => <option key={type.id} value={type.id}>{type.name}</option>)}<option value="custom">Create custom behavior…</option></select></label>
|
||||
{form.behaviorTypeId === 'custom' && <><label>Custom behavior name<input required maxLength={120} value={customName} onChange={(e) => setCustomName(e.target.value)} /></label><label>Description (optional)<input maxLength={2000} value={customDescription} onChange={(e) => setCustomDescription(e.target.value)} /></label></>}
|
||||
<label className="behavior-wide">Date and time<input type="datetime-local" step="1" required value={form.occurredAt} onChange={(e) => setForm({ ...form, occurredAt: e.target.value })} /></label>
|
||||
<label>Duration in seconds (optional)<input type="number" min="0.001" max="31536000" step="any" value={form.duration} onChange={(e) => setForm({ ...form, duration: e.target.value })} /></label>
|
||||
<label>Intensity (optional)<select aria-label="Intensity (optional)" value={form.severity} onChange={(e) => setForm({ ...form, severity: e.target.value })}><option value="">Not recorded</option>{[1, 2, 3, 4, 5].map((value) => <option key={value} value={value}>{value}{value === 1 ? ' — Low' : value === 5 ? ' — High' : ''}</option>)}</select></label>
|
||||
<label className="behavior-wide">Notes (optional)<textarea maxLength={10000} rows={3} value={form.notes} onChange={(e) => setForm({ ...form, notes: e.target.value })} /></label>
|
||||
<div className="behavior-actions"><button className="primary-button" type="submit">{saving ? 'Saving…' : 'Save occurrence'}</button><button className="secondary-button" type="button" onClick={() => { setShowForm(false); setEditing(null); }}>Cancel</button></div>
|
||||
</fieldset>
|
||||
</form>}
|
||||
<label>Bird<select aria-label="Bird" value={bird.id} disabled={saving} onChange={(e) => onSelectBird(e.target.value)}>{birds.map((item) => <option key={item.id} value={item.id}>{item.name}</option>)}</select></label>
|
||||
<label>Show behavior<select aria-label="Show behavior" value={filter} disabled={saving} onChange={(e) => setFilter(e.target.value)}><option value="">All behaviors</option>{types.map((type) => <option key={type.id} value={type.id}>{type.name}</option>)}</select></label>
|
||||
<div className="behavior-month"><button className="secondary-button" type="button" aria-label="Previous month" onClick={() => navigate(-1)}>‹</button><h3 aria-live="polite">{month.toLocaleDateString(undefined, { month: 'long', year: 'numeric' })}</h3><button className="secondary-button" type="button" aria-label="Next month" onClick={() => navigate(1)}>›</button></div>
|
||||
<p aria-live="polite">{loading ? 'Loading occurrences…' : `${entries.length} occurrence${entries.length === 1 ? '' : 's'} this month`}</p>
|
||||
<div className="behavior-calendar" aria-label="Monthly behavior occurrences" aria-busy={loading}>
|
||||
{['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'].map((label) => <span className="behavior-weekday" key={label}>{label}</span>)}
|
||||
{Array.from({ length: month.getDay() }, (_, index) => <span key={`blank-${index}`} />)}
|
||||
{Array.from({ length: days }, (_, index) => {
|
||||
const date = new Date(month.getFullYear(), month.getMonth(), index + 1); const key = localDate(date); const count = byDay.get(key)?.length || 0;
|
||||
return <button type="button" key={key} className={`behavior-day ${count ? 'has-occurrences' : ''}`} aria-pressed={key === day} aria-current={key === localDate(new Date()) ? 'date' : undefined} aria-label={`${date.toLocaleDateString()}: ${count} occurrences`} onClick={() => setDay(key)}><span>{index + 1}</span>{count > 0 && <><span className="behavior-dots" aria-hidden="true">{'●'.repeat(Math.min(count, 3))}{count > 3 ? '+' : ''}</span><small>{count}</small></>}</button>;
|
||||
})}
|
||||
</div>
|
||||
<h3>{new Date(`${day}T12:00:00`).toLocaleDateString(undefined, { dateStyle: 'long' })}</h3>
|
||||
{!loading && !(byDay.get(day)?.length) && <p className="muted">No occurrences recorded for this day{filter ? ' for the selected behavior' : ''}.</p>}
|
||||
{(byDay.get(day) || []).map((entry) => <details key={entry.id} className="behavior-entry"><summary><strong>{entry.behaviorName}</strong><span>{new Date(entry.occurredAt).toLocaleString()}</span>{entry.durationSeconds !== null && <span>Duration: {entry.durationSeconds} seconds</span>}{entry.severity !== null && <span>Intensity: {entry.severity}/5</span>}{entry.notes && <span className="behavior-note-preview">{entry.notes}</span>}</summary><div>{entry.notes && <p className="behavior-notes">{entry.notes}</p>}<p className="muted">Created: {new Date(entry.createdAt).toLocaleString()}<br />Updated: {new Date(entry.updatedAt).toLocaleString()}</p>{writable && <div className="behavior-actions"><button className="secondary-button" type="button" disabled={saving} onClick={() => edit(entry)}>Edit</button><button className="danger-button" type="button" disabled={saving} onClick={() => void remove(entry)}>Delete</button></div>}</div></details>)}
|
||||
</section>;
|
||||
}
|
||||
Reference in new issue
Block a user