Merge remote-tracking branch 'origin/main'
This commit is contained in:
commit
c8eb9bc862
17 files changed
+750
-105
No files matched your search
+174
-41
@@ -1,3 +1,5 @@
|
||||
import { usePhotoRefresh } from './usePhotoRefresh';
|
||||
import { FlockSwitcher } from './FlockSwitcher';
|
||||
import { combineLocationOwnerMarkers } from './birdTimeline';
|
||||
import { BehaviorJournal } from './BehaviorJournal';
|
||||
import { useEffect, useMemo, useState, type CSSProperties, type Dispatch, type SetStateAction } from 'react';
|
||||
@@ -1799,6 +1801,20 @@ const formatRescueVerificationStatus = (status: RescueVerificationStatus) => {
|
||||
return 'Pending verification';
|
||||
};
|
||||
|
||||
const workspaceRoleDescriptions: Record<WorkspaceRole, string> = {
|
||||
viewer: 'Can view every bird and their care history, and download flock or individual bird exports. Cannot edit birds or care records.',
|
||||
caregiver: 'Can view and export, add and edit birds, record daily care, and delete supported care records. Cannot remove birds from the flock or manage sharing, billing, or bird transfers.',
|
||||
assistant: 'Can do everything a Caregiver can, plus remove birds from the flock, manage collaborators, flock settings and billing, transfer birds, and view the audit log. Cannot memorialize birds or delete the flock.',
|
||||
owner: 'Can do everything an Assistant can, plus memorialize birds, manage memorial reminders, and delete an empty flock. Owner access does not change the billing owner.',
|
||||
};
|
||||
|
||||
const workspaceRoleLabels: Record<WorkspaceRole, string> = {
|
||||
viewer: 'Viewer — view and export',
|
||||
caregiver: 'Caregiver — birds and daily care',
|
||||
assistant: 'Assistant — flock management',
|
||||
owner: 'Owner — full flock control',
|
||||
};
|
||||
|
||||
const formatWorkspaceRole = (role: WorkspaceRole) => {
|
||||
if (role === 'owner') {
|
||||
return 'Owner';
|
||||
@@ -2172,6 +2188,9 @@ function App() {
|
||||
|
||||
const [birdImportPreview, setBirdImportPreview] = useState<BirdImportPreview | null>(null);
|
||||
const [birdImportFileName, setBirdImportFileName] = useState('');
|
||||
const [exportBirdId, setExportBirdId] = useState('');
|
||||
const [exportingFlock, setExportingFlock] = useState(false);
|
||||
const [flockExportError, setFlockExportError] = useState('');
|
||||
const [birdImportNotice, setBirdImportNotice] = useState('');
|
||||
const [importingBirds, setImportingBirds] = useState(false);
|
||||
const [memorializeBirdForm, setMemorializeBirdForm] = useState<MemorializeBirdFormState>(emptyMemorializeBirdForm);
|
||||
@@ -2183,6 +2202,8 @@ function App() {
|
||||
const [savingWorkspace, setSavingWorkspace] = useState(false);
|
||||
const [cancelingRescueRequest, setCancelingRescueRequest] = useState(false);
|
||||
const [billingRedirecting, setBillingRedirecting] = useState(false);
|
||||
const [invitationNotice, setInvitationNotice] = useState<{ sent: boolean; message: string } | null>(null);
|
||||
const [resendingInvitationId, setResendingInvitationId] = useState<string | null>(null);
|
||||
const [savingWorkspaceMember, setSavingWorkspaceMember] = useState(false);
|
||||
const [creatingWorkspace, setCreatingWorkspace] = useState(false);
|
||||
const [deletingWorkspace, setDeletingWorkspace] = useState(false);
|
||||
@@ -2264,6 +2285,27 @@ function App() {
|
||||
const [expandedSettingsSection, setExpandedSettingsSection] = useState<SettingsSection | null>(null);
|
||||
|
||||
const flockBirds = useMemo(() => sortBirdsByName([...birds, ...memorializedBirds]), [birds, memorializedBirds]);
|
||||
const handlePhotoError = usePhotoRefresh({
|
||||
apiBaseUrl, token: authToken, workspaceId: workspace?.id, publicProfileCode,
|
||||
fallback: defaultBirdPhoto,
|
||||
onPhotos: (photos) => {
|
||||
const urls = new Map(photos.map((photo) => [photo.id, photo.photoDataUrl]));
|
||||
const update = (current: Bird[]) => current.map((bird) => urls.has(bird.id)
|
||||
? { ...bird, photoDataUrl: urls.get(bird.id) ?? null } : bird);
|
||||
setBirds(update);
|
||||
setMemorializedBirds(update);
|
||||
setPublicProfile((current) => current && urls.has(current.id)
|
||||
? { ...current, photoDataUrl: urls.get(current.id) ?? null } : current);
|
||||
// Renew the editor preview only if it still matches the saved photo.
|
||||
// Never replace an uploaded/cropped photo or a deliberate removal.
|
||||
const editingBird = [...birds, ...memorializedBirds].find((bird) => bird.id === editingBirdId);
|
||||
if (editingBird && urls.has(editingBirdId)) {
|
||||
setBirdForm((current) => current.photoDataUrl === editingBird.photoDataUrl
|
||||
? { ...current, photoDataUrl: urls.get(editingBirdId) ?? '' } : current);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const selectedBird = useMemo(
|
||||
() => flockBirds.find((bird) => bird.id === selectedBirdId) ?? null,
|
||||
[flockBirds, selectedBirdId],
|
||||
@@ -3389,7 +3431,7 @@ function App() {
|
||||
};
|
||||
|
||||
const handleWorkspaceSwitch = async (workspaceId: number, nextActivePage: AppPage = 'overview') => {
|
||||
if (!authToken || workspaceId === workspace?.id) {
|
||||
if (!authToken || switchingWorkspaceId !== null || workspaceId === workspace?.id) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -3841,6 +3883,34 @@ function App() {
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
setExportBirdId('');
|
||||
setFlockExportError('');
|
||||
setInvitationNotice(null);
|
||||
}, [workspace?.id]);
|
||||
|
||||
const handleFlockExport = async () => {
|
||||
if (exportingFlock) return;
|
||||
setExportingFlock(true);
|
||||
setFlockExportError('');
|
||||
try {
|
||||
const response = await apiFetch(`/workspace/export${exportBirdId ? `?birdId=${encodeURIComponent(exportBirdId)}` : ''}`, authToken);
|
||||
if (!response.ok) throw new Error(await readErrorMessage(response, 'Unable to export flock data.'));
|
||||
const url = URL.createObjectURL(await response.blob());
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.download = `flockpal-${exportBirdId ? `bird-${exportBirdId}` : `flock-${workspace?.id ?? 'export'}`}-${new Date().toISOString().slice(0, 10)}.json`;
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
link.remove();
|
||||
window.setTimeout(() => URL.revokeObjectURL(url), 60_000);
|
||||
} catch (exportError) {
|
||||
setFlockExportError(exportError instanceof Error ? exportError.message : 'Unable to export flock data.');
|
||||
} finally {
|
||||
setExportingFlock(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleBirdImportSubmit = async () => {
|
||||
if (!birdImportPreview || birdImportPreview.errors.length || importingBirds) {
|
||||
return;
|
||||
@@ -4594,7 +4664,7 @@ function App() {
|
||||
};
|
||||
|
||||
const handleRemoveBird = async () => {
|
||||
if (!selectedBird || deletingBird) {
|
||||
if (!selectedBird || deletingBird || !['owner', 'assistant'].includes(activeMembership?.role ?? '')) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -5506,6 +5576,7 @@ function App() {
|
||||
const handleWorkspaceMemberSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
setError('');
|
||||
setInvitationNotice(null);
|
||||
setSavingWorkspaceMember(true);
|
||||
|
||||
try {
|
||||
@@ -5519,7 +5590,7 @@ function App() {
|
||||
throw new Error(await readErrorMessage(response, 'Unable to add rescue team member.'));
|
||||
}
|
||||
|
||||
const data = (await readJsonSafely<{ member?: WorkspaceMember }>(response)) ?? {};
|
||||
const data = (await readJsonSafely<{ member?: WorkspaceMember; invitation?: { sent: boolean; message: string } }>(response)) ?? {};
|
||||
|
||||
if (!data.member) {
|
||||
throw new Error('Unable to add rescue team member.');
|
||||
@@ -5540,6 +5611,7 @@ function App() {
|
||||
return current.map((member) => (member.id === nextMember.id ? nextMember : member));
|
||||
});
|
||||
setWorkspaceMemberForm(emptyWorkspaceMemberForm);
|
||||
setInvitationNotice(data.invitation ?? null);
|
||||
} catch (memberError) {
|
||||
setError(memberError instanceof Error ? memberError.message : 'Unable to add rescue team member.');
|
||||
} finally {
|
||||
@@ -5547,6 +5619,21 @@ function App() {
|
||||
}
|
||||
};
|
||||
|
||||
const handleResendInvitation = async (memberId: string) => {
|
||||
setResendingInvitationId(memberId);
|
||||
setInvitationNotice(null);
|
||||
try {
|
||||
const response = await apiFetch(`/workspace/members/${memberId}/invitation`, authToken, { method: 'POST' });
|
||||
if (!response.ok) throw new Error(await readErrorMessage(response, 'Unable to resend invitation.'));
|
||||
const data = await response.json() as { invitation: { sent: boolean; message: string } };
|
||||
setInvitationNotice(data.invitation);
|
||||
} catch (error) {
|
||||
setInvitationNotice({ sent: false, message: error instanceof Error ? error.message : 'Unable to resend invitation.' });
|
||||
} finally {
|
||||
setResendingInvitationId(null);
|
||||
}
|
||||
};
|
||||
|
||||
const handleUpdateWorkspaceMemberRole = async (memberId: string, role: WorkspaceRole) => {
|
||||
setError('');
|
||||
setUpdatingWorkspaceMemberId(memberId);
|
||||
@@ -5633,7 +5720,7 @@ function App() {
|
||||
|
||||
if (shouldShowPublicProfilePage) {
|
||||
return (
|
||||
<main className="auth-shell public-profile-shell">
|
||||
<main className="auth-shell public-profile-shell" onErrorCapture={handlePhotoError}>
|
||||
<section className="panel public-profile-card">
|
||||
<a className="public-profile-logo-link" href="/" aria-label="Go to FlockPal sign in">
|
||||
<img className="public-profile-logo" src={flockPalLandingArt} alt="FlockPal" />
|
||||
@@ -5830,7 +5917,7 @@ function App() {
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<main className="app-shell">
|
||||
<main className="app-shell" onErrorCapture={handlePhotoError}>
|
||||
<section className="hero-card">
|
||||
<p>Loading flock data...</p>
|
||||
</section>
|
||||
@@ -5941,12 +6028,21 @@ function App() {
|
||||
);
|
||||
|
||||
return (
|
||||
<main className="app-shell">
|
||||
<main className="app-shell" onErrorCapture={handlePhotoError}>
|
||||
<div className="side-rail">
|
||||
<div className="brand-lockup">
|
||||
<img className="side-nav-logo" src={flockPalLandingArt} alt="FlockPal" />
|
||||
</div>
|
||||
<aside className="side-nav panel">
|
||||
{showWorkspaceSwitcher ? (
|
||||
<FlockSwitcher
|
||||
entries={authSession.workspaces}
|
||||
currentId={workspace?.id}
|
||||
switching={switchingWorkspaceId !== null}
|
||||
disabled={switchingWorkspaceId !== null || savingWorkspace || deletingWorkspace}
|
||||
onSwitch={(id) => { void handleWorkspaceSwitch(id); }}
|
||||
/>
|
||||
) : null}
|
||||
<div className="page-tabs" role="tablist" aria-label="Main navigation">
|
||||
<button data-tab="overview" className={`page-tab ${activePage === 'overview' ? 'active' : ''}`} onClick={() => setActivePage('overview')} type="button">
|
||||
Overview
|
||||
@@ -5964,26 +6060,6 @@ function App() {
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{showWorkspaceSwitcher ? (
|
||||
<section className="workspace-switcher">
|
||||
<div className="workspace-switcher-list">
|
||||
{authSession.workspaces.map((entry) => (
|
||||
<button
|
||||
key={`${entry.workspace.id}-${entry.membership.id}`}
|
||||
className={`workspace-switcher-item ${entry.workspace.id === workspace?.id ? 'active' : ''}`}
|
||||
onClick={() => handleWorkspaceSwitch(entry.workspace.id)}
|
||||
type="button"
|
||||
disabled={switchingWorkspaceId === entry.workspace.id}
|
||||
>
|
||||
<span>{entry.workspace.name}</span>
|
||||
<small>
|
||||
{formatBillingPlanName(entry.workspace.billingPlan)} • {formatWorkspaceRole(entry.membership.role)}
|
||||
</small>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
) : null}
|
||||
<button className="secondary-button" onClick={handleLogout} type="button">
|
||||
Log out
|
||||
</button>
|
||||
@@ -7015,9 +7091,9 @@ function App() {
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
<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>
|
||||
<p className="muted">Only Owners and Assistants can remove birds. 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}>
|
||||
<button className="danger-button" onClick={handleRemoveBird} type="button" disabled={deletingBird || !['owner', 'assistant'].includes(activeMembership?.role ?? '')}>
|
||||
{deletingBird ? 'Removing...' : 'Remove from flock'}
|
||||
</button>
|
||||
</div>
|
||||
@@ -8512,9 +8588,26 @@ function App() {
|
||||
{expandedSettingsSection === 'collaborators' ? (
|
||||
<>
|
||||
<p className="muted">
|
||||
Invite other people to help manage this flock. Rescue flocks support teams, and household flocks can also support
|
||||
co-caregivers without changing who owns the billing.
|
||||
Give someone access to this flock using their email address. Their role applies to every bird in this flock,
|
||||
including memorialized birds. Every role can download flock data. Sharing access does not change the billing owner.
|
||||
</p>
|
||||
<details className="summary-card">
|
||||
<summary>Compare shared flock roles</summary>
|
||||
<div className="recent-list">
|
||||
{(['viewer', 'caregiver', 'assistant', 'owner'] as const).map((role) => (
|
||||
<div key={role}>
|
||||
<strong>{workspaceRoleLabels[role]}</strong>
|
||||
<p>{workspaceRoleDescriptions[role]}</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<p className="muted">
|
||||
Memorialized bird records remain read-only. Editing also depends on the flock’s subscription or rescue verification status.
|
||||
</p>
|
||||
</details>
|
||||
{invitationNotice ? (
|
||||
<p className={invitationNotice.sent ? 'success-banner' : 'error-banner'} role="status">{invitationNotice.message}</p>
|
||||
) : null}
|
||||
<form className="form-panel" onSubmit={handleWorkspaceMemberSubmit}>
|
||||
<label>
|
||||
Team member name
|
||||
@@ -8537,6 +8630,7 @@ function App() {
|
||||
Role
|
||||
<select
|
||||
value={workspaceMemberForm.role}
|
||||
aria-describedby="invite-role-description"
|
||||
onChange={(event) =>
|
||||
setWorkspaceMemberForm({
|
||||
...workspaceMemberForm,
|
||||
@@ -8544,14 +8638,17 @@ function App() {
|
||||
})
|
||||
}
|
||||
>
|
||||
{isBillingOwner ? <option value="owner">Owner</option> : null}
|
||||
<option value="assistant">Assistant</option>
|
||||
<option value="caregiver">Caregiver</option>
|
||||
<option value="viewer">Viewer</option>
|
||||
{isBillingOwner ? <option value="owner">{workspaceRoleLabels.owner}</option> : null}
|
||||
<option value="assistant">{workspaceRoleLabels.assistant}</option>
|
||||
<option value="caregiver">{workspaceRoleLabels.caregiver}</option>
|
||||
<option value="viewer">{workspaceRoleLabels.viewer}</option>
|
||||
</select>
|
||||
</label>
|
||||
<p id="invite-role-description" className="muted" aria-live="polite">
|
||||
{workspaceRoleDescriptions[workspaceMemberForm.role]}
|
||||
</p>
|
||||
<button className="primary-button" type="submit" disabled={savingWorkspaceMember}>
|
||||
{savingWorkspaceMember ? 'Adding member...' : 'Add collaborator'}
|
||||
{savingWorkspaceMember ? 'Sending invitation...' : 'Add collaborator and send invitation'}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
@@ -8583,6 +8680,7 @@ function App() {
|
||||
Role
|
||||
<select
|
||||
value={member.role}
|
||||
aria-describedby={`member-role-description-${member.id}`}
|
||||
onChange={(event) => handleUpdateWorkspaceMemberRole(member.id, event.target.value as WorkspaceRole)}
|
||||
disabled={
|
||||
(member.role === 'owner' && !canChangeOwnerRole) ||
|
||||
@@ -8590,12 +8688,21 @@ function App() {
|
||||
removingWorkspaceMemberId === member.id
|
||||
}
|
||||
>
|
||||
{member.role === 'owner' || canPromoteToOwner ? <option value="owner">Owner</option> : null}
|
||||
<option value="assistant">Assistant</option>
|
||||
<option value="caregiver">Caregiver</option>
|
||||
<option value="viewer">Viewer</option>
|
||||
{member.role === 'owner' || canPromoteToOwner ? <option value="owner">{workspaceRoleLabels.owner}</option> : null}
|
||||
<option value="assistant">{workspaceRoleLabels.assistant}</option>
|
||||
<option value="caregiver">{workspaceRoleLabels.caregiver}</option>
|
||||
<option value="viewer">{workspaceRoleLabels.viewer}</option>
|
||||
</select>
|
||||
</label>
|
||||
<p id={`member-role-description-${member.id}`} className="muted" aria-live="polite">
|
||||
{workspaceRoleDescriptions[member.role]}
|
||||
</p>
|
||||
{['owner', 'assistant'].includes(activeMembership?.role ?? '') ? (
|
||||
<button className="secondary-button" type="button" onClick={() => handleResendInvitation(member.id)}
|
||||
disabled={resendingInvitationId !== null || removingWorkspaceMemberId === member.id}>
|
||||
{resendingInvitationId === member.id ? 'Sending...' : 'Resend invitation'}
|
||||
</button>
|
||||
) : null}
|
||||
<button
|
||||
className="danger-button"
|
||||
onClick={() => handleRemoveWorkspaceMember(member.id)}
|
||||
@@ -8735,8 +8842,8 @@ function App() {
|
||||
<article className="panel form-panel settings-card-bird-import">
|
||||
<div className="panel-header">
|
||||
<div>
|
||||
<p className="eyebrow">Import</p>
|
||||
<h2>Bulk Import</h2>
|
||||
<p className="eyebrow">Flock data</p>
|
||||
<h2>Bulk actions</h2>
|
||||
</div>
|
||||
<button
|
||||
className="secondary-button"
|
||||
@@ -8751,6 +8858,32 @@ function App() {
|
||||
</div>
|
||||
{expandedSettingsSection === 'bird-import' ? (
|
||||
<>
|
||||
<h3>Bulk export</h3>
|
||||
<p className="muted">
|
||||
Download all information for {workspace?.name ?? 'this flock'}, including active and memorialized bird profiles,
|
||||
photos, all weights, vet visits, medications and doses, behaviors, timeline history, and flock notes.
|
||||
Choose a single flock member to export only their profile and records, including their bird-specific notes.
|
||||
The JSON file preserves your complete records. Export each flock separately if you have multiple flocks.
|
||||
JSON exports cannot be uploaded through the Excel import below.
|
||||
</p>
|
||||
<label>
|
||||
Export scope
|
||||
<select value={exportBirdId} onChange={(event) => setExportBirdId(event.target.value)} disabled={exportingFlock}>
|
||||
<option value="">All flock members</option>
|
||||
{flockBirds.map((bird) => (
|
||||
<option key={bird.id} value={bird.id}>
|
||||
{bird.name}{bird.tagId ? ` — ${bird.tagId}` : ''}{bird.memorializedAt ? ' (In memory)' : ''}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<div className="button-row">
|
||||
<button className="primary-button" type="button" onClick={handleFlockExport} disabled={exportingFlock}>
|
||||
{exportingFlock ? 'Exporting...' : exportBirdId ? 'Export selected flock member' : 'Export all flock data'}
|
||||
</button>
|
||||
</div>
|
||||
{flockExportError ? <p className="error-banner" role="alert">{flockExportError}</p> : null}
|
||||
<h3>Bulk import</h3>
|
||||
<p className="muted">
|
||||
Import the first worksheet from an Excel file. Use one row per weight entry and repeat the Bird Name for rows that belong to the
|
||||
same profile.
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
|
||||
type FlockEntry = { workspace: { id: number; name: string }; membership: { role: string } };
|
||||
const roleName = (role: string) => role.charAt(0).toUpperCase() + role.slice(1);
|
||||
|
||||
export function FlockSwitcher({ entries, currentId, switching, disabled, onSwitch }: {
|
||||
entries: FlockEntry[]; currentId?: number; switching: boolean; disabled: boolean; onSwitch: (id: number) => void;
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const container = useRef<HTMLElement>(null);
|
||||
const trigger = useRef<HTMLButtonElement>(null);
|
||||
const current = entries.find((entry) => entry.workspace.id === currentId);
|
||||
|
||||
useEffect(() => { setOpen(false); }, [currentId, disabled]);
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const closeOutside = (event: PointerEvent) => {
|
||||
if (!container.current?.contains(event.target as Node)) setOpen(false);
|
||||
};
|
||||
document.addEventListener('pointerdown', closeOutside);
|
||||
return () => document.removeEventListener('pointerdown', closeOutside);
|
||||
}, [open]);
|
||||
|
||||
return (
|
||||
<section className="workspace-switcher" aria-label="Flock selection" ref={container}
|
||||
onBlur={(event) => { if (!event.currentTarget.contains(event.relatedTarget)) setOpen(false); }}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'Escape' && open) {
|
||||
event.preventDefault();
|
||||
setOpen(false);
|
||||
trigger.current?.focus();
|
||||
}
|
||||
}}>
|
||||
<span className="workspace-switcher-label">Current flock</span>
|
||||
<button className="flock-switcher-trigger" ref={trigger} type="button" disabled={disabled}
|
||||
aria-expanded={open} aria-controls="flock-switcher-options" onClick={() => setOpen(!open)}>
|
||||
<span className="flock-switcher-avatar" aria-hidden="true">{current?.workspace.name.trim().charAt(0).toUpperCase() || 'F'}</span>
|
||||
<span className="flock-switcher-copy">
|
||||
<strong>{current?.workspace.name ?? 'Choose a flock'}</strong>
|
||||
<small>{current ? roleName(current.membership.role) : 'Switch flocks'}</small>
|
||||
</span>
|
||||
<svg className={`flock-switcher-chevron ${open ? 'is-open' : ''}`} width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden="true"><path d="m6 9 6 6 6-6" /></svg>
|
||||
</button>
|
||||
<span className="flock-switcher-status" role="status">{switching ? 'Switching flocks…' : ''}</span>
|
||||
{open ? (
|
||||
<div id="flock-switcher-options" className="flock-switcher-options">
|
||||
<p className="flock-switcher-heading">Switch flock</p>
|
||||
{[
|
||||
{ label: 'My flocks', items: entries.filter((entry) => entry.membership.role === 'owner') },
|
||||
{ label: 'Shared with me', items: entries.filter((entry) => entry.membership.role !== 'owner') },
|
||||
].filter((group) => group.items.length).map((group) => (
|
||||
<div className="flock-switcher-group" key={group.label} role="group" aria-label={group.label}>
|
||||
<p>{group.label}</p>
|
||||
{group.items.map((entry) => (
|
||||
<button className="flock-switcher-option" key={entry.workspace.id} type="button"
|
||||
aria-current={entry.workspace.id === currentId ? 'true' : undefined}
|
||||
onClick={() => { setOpen(false); trigger.current?.focus(); onSwitch(entry.workspace.id); }}>
|
||||
<span className="flock-switcher-copy"><strong>{entry.workspace.name}</strong><small>{roleName(entry.membership.role)}</small></span>
|
||||
{entry.workspace.id === currentId ? <span className="flock-switcher-check" aria-label="Current flock">✓</span> : null}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
+63
-41
@@ -216,6 +216,7 @@ textarea {
|
||||
}
|
||||
|
||||
.side-rail {
|
||||
z-index: 30;
|
||||
position: sticky;
|
||||
top: 2rem;
|
||||
display: grid;
|
||||
@@ -856,33 +857,77 @@ textarea {
|
||||
|
||||
.workspace-switcher {
|
||||
display: grid;
|
||||
gap: 0.9rem;
|
||||
gap: 0.45rem;
|
||||
min-width: 0;
|
||||
padding-bottom: 1rem;
|
||||
border-bottom: 1px solid rgba(39, 105, 179, 0.16);
|
||||
}
|
||||
|
||||
.workspace-switcher-item small {
|
||||
.workspace-switcher-label {
|
||||
color: var(--muted);
|
||||
font-size: 0.78rem;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.06em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.workspace-switcher-list {
|
||||
display: grid;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
.workspace-switcher { position: relative; }
|
||||
|
||||
.workspace-switcher-item {
|
||||
.flock-switcher-trigger {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.7rem;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
padding: 0.8rem;
|
||||
color: var(--ink);
|
||||
text-align: left;
|
||||
border: 1px solid rgba(39, 105, 179, 0.12);
|
||||
border-radius: 18px;
|
||||
padding: 0.85rem 0.95rem;
|
||||
background: rgba(255, 255, 255, 0.58);
|
||||
display: grid;
|
||||
gap: 0.2rem;
|
||||
background: rgba(255, 255, 255, 0.65);
|
||||
border: 1px solid var(--panel-border);
|
||||
border-radius: 16px;
|
||||
box-shadow: 0 3px 10px rgba(53, 90, 66, 0.05);
|
||||
}
|
||||
|
||||
.workspace-switcher-item.active {
|
||||
background: linear-gradient(135deg, rgba(203, 58, 53, 0.16), rgba(39, 105, 179, 0.18));
|
||||
border-color: rgba(39, 105, 179, 0.24);
|
||||
.flock-switcher-trigger:hover:not(:disabled) { background: #fffaf0; border-color: var(--accent-green); }
|
||||
.flock-switcher-trigger:focus-visible, .flock-switcher-option:focus-visible { outline: 2px solid var(--accent-green); outline-offset: 3px; }
|
||||
.flock-switcher-avatar {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
flex: 0 0 36px;
|
||||
height: 36px;
|
||||
border-radius: 11px;
|
||||
background: #e1eee2;
|
||||
color: #276b48;
|
||||
font-weight: 800;
|
||||
}
|
||||
.flock-switcher-copy { display: grid; gap: 0.15rem; min-width: 0; flex: 1; }
|
||||
.flock-switcher-copy strong { font-size: 0.95rem; line-height: 1.35; overflow-wrap: anywhere; }
|
||||
.flock-switcher-copy small { color: var(--muted); font-size: 0.76rem; font-weight: 400; }
|
||||
.flock-switcher-chevron { flex-shrink: 0; color: var(--muted); }
|
||||
.flock-switcher-chevron.is-open { transform: rotate(180deg); }
|
||||
.flock-switcher-status:empty { display: none; }
|
||||
.flock-switcher-status { color: var(--muted); font-size: 0.78rem; }
|
||||
.flock-switcher-options {
|
||||
position: absolute;
|
||||
top: calc(100% - 0.5rem);
|
||||
left: 0;
|
||||
z-index: 50;
|
||||
width: max(100%, 280px);
|
||||
max-width: calc(100vw - 3rem);
|
||||
max-height: min(420px, 60dvh);
|
||||
overflow-y: auto;
|
||||
padding: 0.65rem;
|
||||
border: 1px solid var(--panel-border);
|
||||
border-radius: 18px;
|
||||
background: #fffaf1;
|
||||
box-shadow: 0 18px 45px rgba(35, 65, 45, 0.2);
|
||||
}
|
||||
.flock-switcher-heading { margin: 0; padding: 0.35rem 0.5rem 0.6rem; font-size: 0.9rem; font-weight: 700; }
|
||||
.flock-switcher-group + .flock-switcher-group { border-top: 1px solid var(--panel-border); margin-top: 0.5rem; padding-top: 0.35rem; }
|
||||
.flock-switcher-group > p { margin: 0; padding: 0.4rem 0.5rem; color: var(--muted); font-size: 0.72rem; font-weight: 700; letter-spacing: 0.05em; text-transform: uppercase; }
|
||||
.flock-switcher-option { display: flex; align-items: center; gap: 0.7rem; width: 100%; min-height: 54px; padding: 0.65rem; border: 0; border-radius: 11px; background: transparent; color: var(--ink); text-align: left; }
|
||||
.flock-switcher-option:hover, .flock-switcher-option[aria-current="true"] { background: #e8f1e7; }
|
||||
.flock-switcher-check { color: #276b48; font-weight: 800; }
|
||||
|
||||
.integration-token-secret {
|
||||
gap: 0.75rem;
|
||||
@@ -2623,25 +2668,12 @@ label {
|
||||
|
||||
.workspace-switcher {
|
||||
grid-column: 1 / -1;
|
||||
gap: 0.5rem;
|
||||
gap: 0.4rem;
|
||||
padding-bottom: 0.65rem;
|
||||
}
|
||||
|
||||
.workspace-switcher-list {
|
||||
display: flex;
|
||||
gap: 0.45rem;
|
||||
overflow-x: auto;
|
||||
padding-bottom: 0.1rem;
|
||||
}
|
||||
|
||||
.workspace-switcher-item {
|
||||
min-width: 160px;
|
||||
padding: 0.55rem 0.7rem;
|
||||
border-radius: 14px;
|
||||
}
|
||||
|
||||
.workspace-switcher-item small {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 720px) {
|
||||
@@ -2787,17 +2819,7 @@ label {
|
||||
gap: 0.4rem;
|
||||
}
|
||||
|
||||
.workspace-switcher-list {
|
||||
margin: 0 -0.2rem;
|
||||
padding: 0 0.2rem 0.2rem;
|
||||
}
|
||||
|
||||
.workspace-switcher-item {
|
||||
min-width: min(180px, 78vw);
|
||||
padding: 0.5rem 0.65rem;
|
||||
border-radius: 999px;
|
||||
font-size: 0.86rem;
|
||||
}
|
||||
|
||||
.top-alert-notification {
|
||||
gap: 0.65rem;
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
export type PhotoRecord = { id: string; photoDataUrl: string | null };
|
||||
export const PHOTO_REFRESH_INTERVAL_MS = 5 * 60_000;
|
||||
|
||||
// One request for all mounted photos; throttle failures without blocking later recovery.
|
||||
export function createPhotoRefresher({ load, apply, now = Date.now }: {
|
||||
load: (signal: AbortSignal) => Promise<PhotoRecord[]>;
|
||||
apply: (photos: PhotoRecord[]) => void;
|
||||
now?: () => number;
|
||||
}) {
|
||||
const controller = new AbortController();
|
||||
let inFlight = false;
|
||||
let lastAttempt = -Infinity;
|
||||
return {
|
||||
async refresh() {
|
||||
if (controller.signal.aborted || inFlight || now() - lastAttempt < 30_000) return;
|
||||
inFlight = true;
|
||||
lastAttempt = now();
|
||||
try {
|
||||
const photos = await load(controller.signal);
|
||||
if (!controller.signal.aborted) apply(photos);
|
||||
} catch {
|
||||
// Keep existing photos on transient failures; retry on the next focus/timer/error.
|
||||
} finally {
|
||||
inFlight = false;
|
||||
}
|
||||
},
|
||||
dispose() { controller.abort(); },
|
||||
};
|
||||
}
|
||||
|
||||
export function isExpiringPhotoUrl(src: string) {
|
||||
try {
|
||||
const url = new URL(src, window.location.href);
|
||||
return /\/birds\/[^/]+\/photo$/.test(url.pathname) && url.searchParams.has('token');
|
||||
} catch { return false; }
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { useEffect, useRef, type SyntheticEvent } from 'react';
|
||||
import { createPhotoRefresher, isExpiringPhotoUrl, PHOTO_REFRESH_INTERVAL_MS, type PhotoRecord } from './photoRefresh';
|
||||
|
||||
export function usePhotoRefresh({ apiBaseUrl, token, workspaceId, publicProfileCode, onPhotos, fallback }: {
|
||||
apiBaseUrl: string; token: string; workspaceId?: number; publicProfileCode: string;
|
||||
onPhotos: (photos: PhotoRecord[]) => void; fallback: string;
|
||||
}) {
|
||||
const apply = useRef(onPhotos);
|
||||
apply.current = onPhotos;
|
||||
const refresh = useRef<(() => Promise<void>) | null>(null);
|
||||
useEffect(() => {
|
||||
if (!publicProfileCode && (!token || !workspaceId)) return;
|
||||
const refresher = createPhotoRefresher({
|
||||
load: async (signal) => {
|
||||
const path = publicProfileCode ? `/public/birds/${encodeURIComponent(publicProfileCode)}` : '/birds';
|
||||
const response = await fetch(`${apiBaseUrl}${path}`, {
|
||||
signal, cache: 'no-store',
|
||||
headers: publicProfileCode ? {} : { Authorization: `Bearer ${token}` },
|
||||
});
|
||||
if (!response.ok) throw new Error('Unable to refresh photos.');
|
||||
const data = await response.json();
|
||||
return publicProfileCode ? (data.bird ? [data.bird] : []) : [...(data.birds ?? []), ...(data.memorializedBirds ?? [])];
|
||||
},
|
||||
apply: (photos) => apply.current(photos),
|
||||
});
|
||||
refresh.current = refresher.refresh;
|
||||
const onResume = () => { if (document.visibilityState === 'visible') void refresher.refresh(); };
|
||||
const timer = window.setInterval(onResume, PHOTO_REFRESH_INTERVAL_MS);
|
||||
window.addEventListener('focus', onResume);
|
||||
window.addEventListener('online', onResume);
|
||||
document.addEventListener('visibilitychange', onResume);
|
||||
return () => {
|
||||
refresher.dispose();
|
||||
refresh.current = null;
|
||||
window.clearInterval(timer);
|
||||
window.removeEventListener('focus', onResume);
|
||||
window.removeEventListener('online', onResume);
|
||||
document.removeEventListener('visibilitychange', onResume);
|
||||
};
|
||||
}, [apiBaseUrl, token, workspaceId, publicProfileCode]);
|
||||
|
||||
return (event: SyntheticEvent) => {
|
||||
const image = event.target;
|
||||
if (!(image instanceof Element)) return;
|
||||
const attribute = image.localName === 'img' ? 'src' : image.localName === 'image' ? 'href' : null;
|
||||
if (!attribute || !isExpiringPhotoUrl(image.getAttribute(attribute) ?? '')) return;
|
||||
image.setAttribute(attribute, fallback);
|
||||
void refresh.current?.();
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { createPhotoRefresher } from '../src/photoRefresh.ts';
|
||||
|
||||
test('simultaneous image errors share a refresh, then can renew again after cooldown', async () => {
|
||||
let now = 0;
|
||||
let calls = 0;
|
||||
let finish!: (photos: { id: string; photoDataUrl: string }[]) => void;
|
||||
const applied: unknown[] = [];
|
||||
const refresher = createPhotoRefresher({
|
||||
now: () => now,
|
||||
load: async () => { calls++; return new Promise((resolve) => { finish = resolve; }); },
|
||||
apply: (photos) => applied.push(photos),
|
||||
});
|
||||
const first = refresher.refresh();
|
||||
await refresher.refresh();
|
||||
assert.equal(calls, 1);
|
||||
finish([{ id: 'bird', photoDataUrl: 'renewed' }]);
|
||||
await first;
|
||||
assert.equal(applied.length, 1);
|
||||
await refresher.refresh();
|
||||
assert.equal(calls, 1);
|
||||
now = 30_000;
|
||||
const next = refresher.refresh();
|
||||
finish([]);
|
||||
await next;
|
||||
assert.equal(calls, 2);
|
||||
});
|
||||
|
||||
test('logout or flock switching aborts requests and discards stale photo responses', async () => {
|
||||
let finish!: (photos: { id: string; photoDataUrl: string }[]) => void;
|
||||
let signal!: AbortSignal;
|
||||
let applied = false;
|
||||
const refresher = createPhotoRefresher({
|
||||
load: async (requestSignal) => { signal = requestSignal; return new Promise((resolve) => { finish = resolve; }); },
|
||||
apply: () => { applied = true; },
|
||||
});
|
||||
const pending = refresher.refresh();
|
||||
refresher.dispose();
|
||||
finish([{ id: 'old-flock-bird', photoDataUrl: 'stale' }]);
|
||||
await pending;
|
||||
assert.equal(signal.aborted, true);
|
||||
assert.equal(applied, false);
|
||||
});
|
||||
|
||||
test('a failed refresh can recover on a later timer, focus, or reconnect', async () => {
|
||||
let now = 0;
|
||||
let attempts = 0;
|
||||
let applied = false;
|
||||
const refresher = createPhotoRefresher({
|
||||
now: () => now,
|
||||
load: async () => { if (++attempts === 1) throw new Error('offline'); return []; },
|
||||
apply: () => { applied = true; },
|
||||
});
|
||||
await refresher.refresh();
|
||||
assert.equal(applied, false);
|
||||
now = 30_000;
|
||||
await refresher.refresh();
|
||||
assert.equal(applied, true);
|
||||
});
|
||||
Reference in new issue
Block a user