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
+122
-32
@@ -1,3 +1,4 @@
|
||||
import { BehaviorJournal } from './BehaviorJournal';
|
||||
import { useEffect, useMemo, useState, type CSSProperties, type Dispatch, type SetStateAction } from 'react';
|
||||
import birdSilhouette from './assets/bird-silhouette.jpg';
|
||||
import flockPalLandingArt from './assets/flockpal-landing-art.png';
|
||||
@@ -252,7 +253,7 @@ type AuditLogEntry = {
|
||||
type BirdTimelineEvent = {
|
||||
id: string;
|
||||
birdId: string;
|
||||
eventType: 'profile_created' | 'transferred' | 'location_updated' | 'owner_changed' | 'manual_note';
|
||||
eventType: 'profile_created' | 'transferred' | 'location_updated' | 'owner_changed' | 'manual_note' | 'removed_from_flock' | 'joined_flock';
|
||||
fromWorkspaceId: number | null;
|
||||
toWorkspaceId: number | null;
|
||||
fromWorkspaceName: string | null;
|
||||
@@ -458,7 +459,7 @@ type WeightDropAlert = {
|
||||
};
|
||||
|
||||
type DismissibleAlertType = 'weight-range' | 'weight-drop' | 'vet-visit';
|
||||
type BirdDetailTab = 'info' | 'weight' | 'vet' | 'notes' | 'reports' | 'timeline' | 'audit';
|
||||
type BirdDetailTab = 'behavior' | 'info' | 'weight' | 'vet' | 'notes' | 'reports' | 'timeline' | 'audit';
|
||||
type DismissedAlertMap = Record<string, boolean>;
|
||||
|
||||
type PhotoCropState = {
|
||||
@@ -1174,6 +1175,9 @@ const formatAuditAction = (value: string) =>
|
||||
.join(' ');
|
||||
|
||||
const formatBirdTimelineTitle = (event: BirdTimelineEvent) => {
|
||||
if (event.eventType === 'removed_from_flock') return 'Removed from flock';
|
||||
if (event.eventType === 'joined_flock') return 'Joined flock with history';
|
||||
|
||||
if (event.eventType === 'profile_created') {
|
||||
return 'Added to flock';
|
||||
}
|
||||
@@ -1194,6 +1198,9 @@ const formatBirdTimelineTitle = (event: BirdTimelineEvent) => {
|
||||
};
|
||||
|
||||
const formatBirdTimelineDescription = (event: BirdTimelineEvent) => {
|
||||
if (event.eventType === 'removed_from_flock') return `Left ${event.fromWorkspaceName || 'previous flock'}; history retained.`;
|
||||
if (event.eventType === 'joined_flock') return `Joined ${event.toWorkspaceName || 'current flock'} with existing history.`;
|
||||
|
||||
if (event.eventType === 'profile_created') {
|
||||
return event.locationLabel ? `Location: ${event.locationLabel}` : `Flock: ${event.toWorkspaceName || 'Unknown flock'}`;
|
||||
}
|
||||
@@ -1272,6 +1279,9 @@ const getBirdHatchDay = (bird: Pick<Bird, 'hatchDay' | 'dateOfBirth'>) => {
|
||||
};
|
||||
|
||||
const getBirdTimelineGraphLabel = (event: BirdTimelineEvent) => {
|
||||
if (event.eventType === 'removed_from_flock') return 'Removed from flock';
|
||||
if (event.eventType === 'joined_flock') return 'Joined flock with history';
|
||||
|
||||
if (event.eventType === 'location_updated') {
|
||||
return event.locationLabel || 'Location updated';
|
||||
}
|
||||
@@ -2208,6 +2218,12 @@ function App() {
|
||||
const [integrationTokenForm, setIntegrationTokenForm] = useState<IntegrationTokenFormState>(emptyIntegrationTokenForm);
|
||||
const [flockNoteForm, setFlockNoteForm] = useState<FlockNoteFormState>(emptyFlockNoteForm);
|
||||
const [birdForm, setBirdForm] = useState<BirdFormState>(emptyBirdForm);
|
||||
const [unassignedBirdMatch, setUnassignedBirdMatch] = useState<{
|
||||
tagId: string; status: 'idle' | 'loading' | 'available' | 'none' | 'error';
|
||||
}>({ tagId: '', status: 'idle' });
|
||||
const matchingUnassignedBird = !editingBirdId && unassignedBirdMatch.status === 'available'
|
||||
&& unassignedBirdMatch.tagId === birdForm.tagId.trim().toLowerCase();
|
||||
|
||||
const [birdImportPreview, setBirdImportPreview] = useState<BirdImportPreview | null>(null);
|
||||
const [birdImportFileName, setBirdImportFileName] = useState('');
|
||||
const [birdImportNotice, setBirdImportNotice] = useState('');
|
||||
@@ -2332,12 +2348,33 @@ function App() {
|
||||
[auditLogEntries, selectedBird],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const tagId = birdForm.tagId.trim().toLowerCase();
|
||||
if (!authToken || !birdEditorOpen || editingBirdId || !tagId || ['unknown', 'not recorded', 'n/a', 'na', 'none'].includes(tagId)) {
|
||||
setUnassignedBirdMatch({ tagId, status: 'idle' });
|
||||
return;
|
||||
}
|
||||
const controller = new AbortController();
|
||||
setUnassignedBirdMatch({ tagId, status: 'loading' });
|
||||
const timer = window.setTimeout(async () => {
|
||||
try {
|
||||
const response = await apiFetch(`/birds/unassigned-match?${new URLSearchParams({ tagId })}`, authToken, { signal: controller.signal });
|
||||
if (!response.ok) throw new Error('Unable to check band ID.');
|
||||
const data = await response.json() as { available: boolean };
|
||||
if (!controller.signal.aborted) setUnassignedBirdMatch({ tagId, status: data.available ? 'available' : 'none' });
|
||||
} catch {
|
||||
if (!controller.signal.aborted) setUnassignedBirdMatch({ tagId, status: 'error' });
|
||||
}
|
||||
}, 350);
|
||||
return () => { window.clearTimeout(timer); controller.abort(); };
|
||||
}, [authToken, workspace?.id, birdEditorOpen, editingBirdId, birdForm.tagId]);
|
||||
|
||||
useEffect(() => {
|
||||
setDismissedAlerts(readDismissedAlerts());
|
||||
}, [workspace?.id]);
|
||||
|
||||
useEffect(() => {
|
||||
setSelectedBirdTab('info');
|
||||
setSelectedBirdTab((current) => current === 'behavior' ? 'behavior' : 'info');
|
||||
setBirdTimelineEvents([]);
|
||||
setBirdTimelineEventForm(emptyBirdTimelineEventForm);
|
||||
setBirdTimelineNotice(null);
|
||||
@@ -4224,6 +4261,37 @@ function App() {
|
||||
}
|
||||
};
|
||||
|
||||
const handleClaimUnassignedBird = async () => {
|
||||
if (!matchingUnassignedBird || savingBird) return;
|
||||
const tagId = birdForm.tagId.trim();
|
||||
if (!window.confirm(`Add the bird with band ID ${tagId} to this flock?\n\nIts saved profile, photo, notes, and care history will be brought in. The existing profile details will be used instead of any new details entered here.`)) return;
|
||||
setSavingBird(true);
|
||||
setError('');
|
||||
try {
|
||||
const response = await apiFetch('/birds/claim', authToken, {
|
||||
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ tagId, confirmHistory: true }),
|
||||
});
|
||||
if (!response.ok) throw new Error(await readErrorMessage(response, 'Unable to add the existing bird.'));
|
||||
const data = await response.json() as { bird: Bird };
|
||||
setBirds((current) => sortBirdsByName([...current.filter((bird) => bird.id !== data.bird.id), data.bird]));
|
||||
setSelectedBirdId(data.bird.id);
|
||||
setEditingBirdId(data.bird.id);
|
||||
setBirdForm(toBirdForm(data.bird));
|
||||
setBirdPhotoName('');
|
||||
setBirdEditorOpen(false);
|
||||
setActivePage('flock');
|
||||
setUnassignedBirdMatch({ tagId: '', status: 'idle' });
|
||||
// Refresh notes without treating a successful claim as failed if this secondary request fails.
|
||||
void apiFetch('/notes', authToken).then(async (notesResponse) => {
|
||||
if (notesResponse.ok) setFlockNotes(((await notesResponse.json()) as { notes: FlockNote[] }).notes);
|
||||
}).catch(() => setError('Bird added with its history. Refresh the flock to load its notes.'));
|
||||
window.alert(`${data.bird.name} was added with its existing profile and care history.`);
|
||||
} catch (claimError) {
|
||||
setError(claimError instanceof Error ? claimError.message : 'Unable to add the existing bird.');
|
||||
} finally { setSavingBird(false); }
|
||||
};
|
||||
|
||||
const handleBirdSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
setError('');
|
||||
@@ -4842,7 +4910,7 @@ function App() {
|
||||
}
|
||||
|
||||
const confirmed = window.confirm(
|
||||
`Remove ${selectedBird.name} from the flock?\n\nThis will also remove weight records and vet visits for this flock member.`,
|
||||
`Remove ${selectedBird.name} from the flock?\n\nThe bird will leave this flock, but its profile, photo, notes, and care history will be retained. Public sharing and pending transfers will be disabled. Someone adding its exact band ID can bring the bird and its history into their flock.${selectedBird.tagId ? '' : '\n\nThis bird has no band ID, so its history cannot be automatically matched later.'}`,
|
||||
);
|
||||
|
||||
if (!confirmed) {
|
||||
@@ -4862,6 +4930,7 @@ function App() {
|
||||
}
|
||||
|
||||
const nextBirds = birds.filter((bird) => bird.id !== selectedBird.id);
|
||||
setFlockNotes((current) => current.filter((note) => note.birdId !== selectedBird.id));
|
||||
setBirds(nextBirds);
|
||||
setAllBirdWeights((current) => {
|
||||
const next = { ...current };
|
||||
@@ -6193,17 +6262,17 @@ function App() {
|
||||
</div>
|
||||
<aside className="side-nav panel">
|
||||
<div className="page-tabs" role="tablist" aria-label="Main navigation">
|
||||
<button className={`page-tab ${activePage === 'overview' ? 'active' : ''}`} onClick={() => setActivePage('overview')} type="button">
|
||||
<button data-tab="overview" className={`page-tab ${activePage === 'overview' ? 'active' : ''}`} onClick={() => setActivePage('overview')} type="button">
|
||||
Overview
|
||||
</button>
|
||||
<button className={`page-tab ${activePage === 'flock' ? 'active' : ''}`} onClick={() => setActivePage('flock')} type="button">
|
||||
<button data-tab="flock" className={`page-tab ${activePage === 'flock' ? 'active' : ''}`} onClick={() => setActivePage('flock')} type="button">
|
||||
Flock
|
||||
</button>
|
||||
<button className={`page-tab ${activePage === 'settings' ? 'active' : ''}`} onClick={() => setActivePage('settings')} type="button">
|
||||
<button data-tab="settings" className={`page-tab ${activePage === 'settings' ? 'active' : ''}`} onClick={() => setActivePage('settings')} type="button">
|
||||
Settings
|
||||
</button>
|
||||
{authSession.isAdmin ? (
|
||||
<button className={`page-tab ${activePage === 'admin' ? 'active' : ''}`} onClick={() => setActivePage('admin')} type="button">
|
||||
<button data-tab="admin" className={`page-tab ${activePage === 'admin' ? 'active' : ''}`} onClick={() => setActivePage('admin')} type="button">
|
||||
Admin
|
||||
</button>
|
||||
) : null}
|
||||
@@ -7012,6 +7081,17 @@ function App() {
|
||||
placeholder="Optional if unknown"
|
||||
/>
|
||||
</label>
|
||||
{!editingBirdId && unassignedBirdMatch.status === 'loading' ? <p className="muted wide-field" role="status">Checking band ID for existing history…</p> : null}
|
||||
{matchingUnassignedBird ? (
|
||||
<div className="success-banner wide-field" role="status">
|
||||
<strong>This band ID matches a bird that is not currently in a flock.</strong>
|
||||
<p>Adding it will bring in its saved profile, photo, notes, and care history. Existing profile details will be used.</p>
|
||||
<button className="primary-button" type="button" disabled={savingBird} onClick={() => void handleClaimUnassignedBird()}>
|
||||
{savingBird ? 'Adding…' : 'Add bird with existing history'}
|
||||
</button>
|
||||
</div>
|
||||
) : null}
|
||||
{!editingBirdId && unassignedBirdMatch.status === 'error' ? <p className="muted wide-field" role="status">Could not check for existing history. The band ID will still be checked when you save.</p> : null}
|
||||
<label className="species-picker-field wide-field">
|
||||
Species
|
||||
<div className="species-picker">
|
||||
@@ -7090,7 +7170,7 @@ function App() {
|
||||
<span className="gender-symbol-mark">{getBirdGenderSymbol({ gender })}</span>
|
||||
</span>
|
||||
<BirdGenderSourceIcon bird={{ gender }} />
|
||||
{getBirdGenderLabel({ gender })}
|
||||
<span className="gender-option-label">{getBirdGenderLabel({ gender })}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
@@ -7308,7 +7388,7 @@ function App() {
|
||||
</div>
|
||||
</section>
|
||||
<div className="settings-save-row">
|
||||
<button className="primary-button" type="submit" disabled={savingBird}>
|
||||
<button className="primary-button" type="submit" disabled={savingBird || matchingUnassignedBird || (!editingBirdId && unassignedBirdMatch.status === 'loading')}>
|
||||
{savingBird ? 'Saving...' : editingBird ? 'Save profile changes' : 'Save bird profile'}
|
||||
</button>
|
||||
</div>
|
||||
@@ -7448,7 +7528,7 @@ function App() {
|
||||
<section className="settings-nested-card settings-danger-card">
|
||||
<div className="settings-nested-header">
|
||||
<p className="eyebrow">Danger zone</p>
|
||||
<h3>Destructive profile actions</h3>
|
||||
<h3>Remove or memorialize</h3>
|
||||
</div>
|
||||
<form className="form-panel inline-form care-entry-form" onSubmit={handleMemorializeBird}>
|
||||
<label>
|
||||
@@ -7474,7 +7554,7 @@ function App() {
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
<p className="muted">Removing permanently deletes weight records, vet visits, and medication history for this bird.</p>
|
||||
<p className="muted">Removing only takes this bird out of your flock. Its profile, photo, notes, and care history are retained and can be brought into a flock later using its exact band ID.</p>
|
||||
<div className="button-row">
|
||||
<button className="danger-button" onClick={handleRemoveBird} type="button" disabled={deletingBird}>
|
||||
{deletingBird ? 'Removing...' : 'Remove from flock'}
|
||||
@@ -7489,7 +7569,7 @@ function App() {
|
||||
<section className="panel flock-member-panel bird-detail-panel">
|
||||
<div className="bird-detail-tabs" role="tablist" aria-label={`${selectedBird.name} detail sections`}>
|
||||
<button
|
||||
className={`bird-detail-tab ${selectedBirdTab === 'info' ? 'active' : ''}`}
|
||||
data-tab="info" className={`bird-detail-tab ${selectedBirdTab === 'info' ? 'active' : ''}`}
|
||||
onClick={() => setSelectedBirdTab('info')}
|
||||
type="button"
|
||||
role="tab"
|
||||
@@ -7502,7 +7582,7 @@ function App() {
|
||||
</svg>
|
||||
</button>
|
||||
<button
|
||||
className={`bird-detail-tab ${selectedBirdTab === 'weight' ? 'active' : ''}`}
|
||||
data-tab="weight" className={`bird-detail-tab ${selectedBirdTab === 'weight' ? 'active' : ''}`}
|
||||
onClick={() => setSelectedBirdTab('weight')}
|
||||
type="button"
|
||||
role="tab"
|
||||
@@ -7514,21 +7594,11 @@ function App() {
|
||||
<path d="M240-200h480l-57-400H297l-57 400Zm240-480q17 0 28.5-11.5T520-720q0-17-11.5-28.5T480-760q-17 0-28.5 11.5T440-720q0 17 11.5 28.5T480-680Zm113 0h70q30 0 52 20t27 49l57 400q5 36-18.5 63.5T720-120H240q-37 0-60.5-27.5T161-211l57-400q5-29 27-49t52-20h70q-3-10-5-19.5t-2-20.5q0-50 35-85t85-35q50 0 85 35t35 85q0 11-2 20.5t-5 19.5ZM240-200h480-480Z" />
|
||||
</svg>
|
||||
</button>
|
||||
<button data-tab="behavior" className={`bird-detail-tab ${selectedBirdTab === 'behavior' ? 'active' : ''}`} type="button" role="tab" aria-selected={selectedBirdTab === 'behavior'} aria-label="Behavior Journal" title="Behavior Journal" onClick={() => setSelectedBirdTab('behavior')}>
|
||||
<span className="material-symbols-outlined behavior-tab-icon" aria-hidden="true">event</span>
|
||||
</button>
|
||||
<button
|
||||
className={`bird-detail-tab ${selectedBirdTab === 'vet' ? 'active' : ''}`}
|
||||
onClick={() => setSelectedBirdTab('vet')}
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={selectedBirdTab === 'vet'}
|
||||
aria-label="Vet"
|
||||
title="Vet"
|
||||
>
|
||||
<svg className="vet-tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
||||
<path d="M20 6h-4V4c0-1.11-.89-2-2-2h-4c-1.11 0-2 .89-2 2v2H4c-1.11 0-2 .89-2 2v12c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V8c0-1.11-.89-2-2-2ZM10 4h4v2h-4V4Zm6 11h-3v3h-2v-3H8v-2h3v-3h2v3h3v2Z" />
|
||||
</svg>
|
||||
</button>
|
||||
<button
|
||||
className={`bird-detail-tab ${selectedBirdTab === 'notes' ? 'active' : ''}`}
|
||||
data-tab="notes" className={`bird-detail-tab ${selectedBirdTab === 'notes' ? 'active' : ''}`}
|
||||
onClick={() => setSelectedBirdTab('notes')}
|
||||
type="button"
|
||||
role="tab"
|
||||
@@ -7541,7 +7611,20 @@ function App() {
|
||||
</svg>
|
||||
</button>
|
||||
<button
|
||||
className={`bird-detail-tab ${selectedBirdTab === 'reports' ? 'active' : ''}`}
|
||||
data-tab="vet" className={`bird-detail-tab ${selectedBirdTab === 'vet' ? 'active' : ''}`}
|
||||
onClick={() => setSelectedBirdTab('vet')}
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={selectedBirdTab === 'vet'}
|
||||
aria-label="Vet"
|
||||
title="Vet"
|
||||
>
|
||||
<svg className="vet-tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
||||
<path d="M20 6h-4V4c0-1.11-.89-2-2-2h-4c-1.11 0-2 .89-2 2v2H4c-1.11 0-2 .89-2 2v12c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V8c0-1.11-.89-2-2-2ZM10 4h4v2h-4V4Zm6 11h-3v3h-2v-3H8v-2h3v-3h2v3h3v2Z" />
|
||||
</svg>
|
||||
</button>
|
||||
<button
|
||||
data-tab="reports" className={`bird-detail-tab ${selectedBirdTab === 'reports' ? 'active' : ''}`}
|
||||
onClick={() => setSelectedBirdTab('reports')}
|
||||
type="button"
|
||||
role="tab"
|
||||
@@ -7554,7 +7637,7 @@ function App() {
|
||||
</svg>
|
||||
</button>
|
||||
<button
|
||||
className={`bird-detail-tab ${selectedBirdTab === 'timeline' ? 'active' : ''}`}
|
||||
data-tab="timeline" className={`bird-detail-tab ${selectedBirdTab === 'timeline' ? 'active' : ''}`}
|
||||
onClick={() => setSelectedBirdTab('timeline')}
|
||||
type="button"
|
||||
role="tab"
|
||||
@@ -7565,7 +7648,7 @@ function App() {
|
||||
<svg className="timeline-tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M21 6a2 2 0 0 0-1.93 2.51l-3.55 3.56A2.15 2.15 0 0 0 15 12c-.18 0-.36.02-.52.07l-2.55-2.55c.05-.16.07-.34.07-.52a2 2 0 1 0-4 0c0 .18.02.36.07.52l-4.56 4.55A2.03 2.03 0 0 0 3 14a2 2 0 1 0 1.93 1.49l4.55-4.56c.16.05.34.07.52.07s.36-.02.52-.07l2.55 2.55c-.05.16-.07.34-.07.52a2 2 0 1 0 4 0c0-.18-.02-.36-.07-.52l3.56-3.55A2 2 0 1 0 21 6Z" /></svg>
|
||||
</button>
|
||||
<button
|
||||
className={`bird-detail-tab ${selectedBirdTab === 'audit' ? 'active' : ''}`}
|
||||
data-tab="audit" className={`bird-detail-tab ${selectedBirdTab === 'audit' ? 'active' : ''}`}
|
||||
onClick={() => setSelectedBirdTab('audit')}
|
||||
type="button"
|
||||
role="tab"
|
||||
@@ -7729,6 +7812,10 @@ function App() {
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{selectedBirdTab === 'behavior' && authToken ? <BehaviorJournal
|
||||
key={`${workspace?.id}-${selectedBird.id}`} bird={selectedBird} birds={birds} onSelectBird={setSelectedBirdId} token={authToken} apiFetch={apiFetch}
|
||||
writable={!selectedBird.memorializedAt && ['owner', 'assistant', 'caregiver'].includes(activeMembership?.role ?? '') && Boolean(authSession?.isAdmin || (workspace?.workspaceType === 'rescue' ? workspace.rescueVerificationStatus === 'approved' : workspace && subscriptionAllowsFlockWrites(workspace.subscriptionStatus)))}
|
||||
/> : null}
|
||||
{selectedBirdTab === 'weight' ? (
|
||||
<div className="flock-member-sections" role="tabpanel">
|
||||
<section className="panel inset-panel">
|
||||
@@ -9116,7 +9203,10 @@ function App() {
|
||||
{expandedSettingsSection === 'integration-tokens' ? (
|
||||
<>
|
||||
<p className="muted">
|
||||
Create a flock-scoped token for automations like n8n. The secret is shown only once, so store it in your automation tool when it appears.
|
||||
Create a flock-scoped token for automations like n8n. The secret is shown only once, so store it in your automation tool when it appears.{' '}
|
||||
<a href={`${apiBaseUrl.replace(/\/$/, '')}/docs/`} target="_blank" rel="noopener noreferrer">
|
||||
Browse the API reference
|
||||
</a>.
|
||||
</p>
|
||||
<form className="form-panel" onSubmit={handleCreateIntegrationToken}>
|
||||
<label>
|
||||
|
||||
@@ -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>;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
.behavior-journal { min-width: 0; }
|
||||
.behavior-journal > label + label { margin-top: .75rem; }
|
||||
.behavior-journal label { display: grid; gap: .4rem; }
|
||||
.behavior-month { display: flex; justify-content: space-between; align-items: center; gap: .5rem; margin-top: 1rem; }
|
||||
.behavior-calendar { display: grid; grid-template-columns: repeat(7, minmax(0, 1fr)); gap: .3rem; }
|
||||
.behavior-weekday { text-align: center; font-size: .8rem; }
|
||||
.behavior-day { min-height: 76px; min-width: 0; border: 1px solid #c5d4ce; border-radius: .6rem; background: #fff; color: #244338; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: .15rem; cursor: pointer; }
|
||||
.behavior-day.has-occurrences { background: #e4f2e9; }
|
||||
.behavior-day[aria-pressed="true"] { outline: 3px solid #326b56; outline-offset: -3px; }
|
||||
.behavior-day[aria-current="date"] > span:first-child { text-decoration: underline; font-weight: bold; }
|
||||
.behavior-dots { font-size: .65rem; letter-spacing: .04em; }
|
||||
.behavior-day:focus-visible { outline: 3px solid #1c5ba3; }
|
||||
.behavior-form { margin: 1rem 0; }
|
||||
.behavior-form fieldset { border: 0; padding: 0; display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 1rem; }
|
||||
.behavior-wide { grid-column: 1 / -1; }
|
||||
.behavior-form input, .behavior-form select, .behavior-form textarea { min-width: 0; width: 100%; box-sizing: border-box; }
|
||||
.behavior-form .behavior-actions { grid-column: 1 / -1; }
|
||||
.behavior-actions { display: flex; flex-wrap: wrap; gap: .5rem; }
|
||||
.behavior-entry { padding: 1rem; margin: .75rem 0; border: 1px solid #c5d4ce; border-radius: .6rem; }
|
||||
.behavior-entry summary { cursor: pointer; }
|
||||
.behavior-entry summary > span { display: block; margin-top: .3rem; }
|
||||
.behavior-note-preview { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.behavior-notes { white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
@media (max-width: 540px) { .behavior-form fieldset { grid-template-columns: 1fr; } .behavior-day { min-height: 64px; padding: .2rem; } .behavior-calendar { gap: .15rem; } .behavior-weekday { font-size: .7rem; } }
|
||||
+81
-10
@@ -44,6 +44,30 @@ body,
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
/* Keep the page width steady when switching between short and long tabs. */
|
||||
html {
|
||||
overflow-y: scroll;
|
||||
background-color: #e9ddba;
|
||||
scrollbar-color: #898b93 transparent;
|
||||
}
|
||||
|
||||
/* Keep native scrollbar tracks from painting a white strip over the page. */
|
||||
html::-webkit-scrollbar {
|
||||
width: 14px;
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
html::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
html::-webkit-scrollbar-thumb {
|
||||
background-color: #898b93;
|
||||
border: 3px solid transparent;
|
||||
background-clip: padding-box;
|
||||
border-radius: 999px;
|
||||
}
|
||||
|
||||
body {
|
||||
min-height: 100vh;
|
||||
color: var(--ink);
|
||||
@@ -510,11 +534,26 @@ textarea {
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
/* Background X colors and their lighter tones give every tab a distinct active fill. */
|
||||
.page-tab[data-tab="overview"] { --tab-active-color: #5bb3b7; }
|
||||
.page-tab[data-tab="flock"] { --tab-active-color: #7eb773; }
|
||||
.page-tab[data-tab="settings"] { --tab-active-color: #f3a24a; }
|
||||
.page-tab[data-tab="admin"] { --tab-active-color: #9698a0; }
|
||||
.bird-detail-tab[data-tab="info"] { --tab-active-color: #9ed2d4; }
|
||||
.bird-detail-tab[data-tab="weight"] { --tab-active-color: #b9c945; }
|
||||
.bird-detail-tab[data-tab="behavior"] { --tab-active-color: #f7c27d; }
|
||||
.bird-detail-tab[data-tab="notes"] { --tab-active-color: #b4d5ad; }
|
||||
.bird-detail-tab[data-tab="vet"] { --tab-active-color: #71ad80; }
|
||||
.bird-detail-tab[data-tab="reports"] { --tab-active-color: #b9bac0; }
|
||||
.bird-detail-tab[data-tab="timeline"] { --tab-active-color: #d4ba64; }
|
||||
.bird-detail-tab[data-tab="audit"] { --tab-active-color: #78a8ad; }
|
||||
|
||||
.page-tab.active {
|
||||
background: linear-gradient(135deg, #d89a2f, #3c8f65 58%, #2f8f98);
|
||||
color: #fffdf9;
|
||||
border-color: transparent;
|
||||
background: var(--tab-active-color);
|
||||
color: var(--ink);
|
||||
border-color: rgba(31, 42, 42, 0.32);
|
||||
box-shadow: 0 14px 26px rgba(88, 110, 62, 0.2);
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.page-tab:hover {
|
||||
@@ -1679,6 +1718,20 @@ textarea {
|
||||
transition: border-color 0.2s ease, box-shadow 0.2s ease, color 0.2s ease, transform 0.2s ease;
|
||||
}
|
||||
|
||||
.bird-detail-tab .behavior-tab-icon {
|
||||
font-family: 'Material Symbols Outlined';
|
||||
font-size: 24px;
|
||||
font-weight: normal;
|
||||
font-style: normal;
|
||||
line-height: 1;
|
||||
letter-spacing: normal;
|
||||
text-transform: none;
|
||||
white-space: nowrap;
|
||||
font-feature-settings: 'liga';
|
||||
font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 24;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
|
||||
.bird-detail-tab svg {
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
@@ -1715,9 +1768,9 @@ textarea {
|
||||
}
|
||||
|
||||
.bird-detail-tab.active {
|
||||
border-color: rgba(35, 138, 90, 0.42);
|
||||
background: rgba(240, 248, 244, 0.95);
|
||||
color: var(--accent-green);
|
||||
border-color: rgba(31, 42, 42, 0.32);
|
||||
background: var(--tab-active-color);
|
||||
color: var(--ink);
|
||||
box-shadow: 10px 10px 20px rgba(39, 105, 179, 0.1);
|
||||
}
|
||||
|
||||
@@ -1793,11 +1846,12 @@ textarea {
|
||||
|
||||
.segmented-control {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(8.5rem, 1fr));
|
||||
grid-template-columns: repeat(auto-fit, minmax(min(13rem, 100%), 1fr));
|
||||
gap: 0.55rem;
|
||||
}
|
||||
|
||||
.segmented-option {
|
||||
min-width: 0;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
@@ -1810,6 +1864,17 @@ textarea {
|
||||
transition: border-color 0.2s ease, box-shadow 0.2s ease, transform 0.2s ease;
|
||||
}
|
||||
|
||||
.segmented-option .gender-symbol,
|
||||
.segmented-option .gender-source-icon {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.gender-option-label {
|
||||
min-width: 0;
|
||||
white-space: normal;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.segmented-option.active {
|
||||
border-color: rgba(35, 138, 90, 0.4);
|
||||
box-shadow: 0 10px 20px rgba(39, 105, 179, 0.1);
|
||||
@@ -2883,8 +2948,14 @@ label {
|
||||
min-width: 520px;
|
||||
}
|
||||
|
||||
.overview-chart-card {
|
||||
min-height: 230px;
|
||||
.chart-card.overview-chart-card {
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.overview-chart-card .weight-chart {
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.chart-footer {
|
||||
@@ -3004,7 +3075,7 @@ label {
|
||||
}
|
||||
|
||||
.segmented-control {
|
||||
grid-template-columns: repeat(auto-fit, minmax(min(8rem, 100%), 1fr));
|
||||
grid-template-columns: repeat(auto-fit, minmax(min(13rem, 100%), 1fr));
|
||||
}
|
||||
|
||||
.segmented-option {
|
||||
|
||||
Reference in new issue
Block a user