feat(vacay): read-only calendar sharing (#444, #667) (#1637)

* feat(vacay): read-only calendar shares on the server (#444, #667)

* feat(vacay): shared calendars card and ring overlay on desktop

* feat(vacay): share sheet and calendar rings on mobile

* test(vacay): cover the calendar share flows

* docs(vacay): document read-only calendar sharing
This commit is contained in:
Maurice
2026-07-21 13:46:38 +02:00
committed by GitHub
parent 7528706d00
commit 31f6ec1f47
129 changed files with 2593 additions and 97 deletions
@@ -39,6 +39,7 @@ const EVENT_LABEL_KEYS: Record<string, string> = {
trip_reminder: 'settings.notifyTripReminder',
todo_due: 'settings.notifyTodoDue',
vacay_invite: 'settings.notifyVacayInvite',
vacay_share: 'settings.notifyVacayShare',
photos_shared: 'settings.notifyPhotosShared',
collab_message: 'settings.notifyCollabMessage',
packing_tagged: 'settings.notifyPackingTagged',
+41 -8
View File
@@ -9,10 +9,11 @@ import { Building2, MousePointer2 } from 'lucide-react'
type VacayMode = 'vacation' | 'company'
type HoverTip = { date: string; top: number; left: number }
export type SharedDayMark = { color: string; name: string; fraction?: number; company?: boolean }
export default function VacayCalendar() {
const { t, locale } = useTranslation()
const { selectedYear, selectedUserId, entries, companyHolidays, toggleEntry, toggleCompanyHoliday, plan, users, holidays } = useVacayStore()
const { selectedYear, selectedUserId, entries, companyHolidays, toggleEntry, toggleCompanyHoliday, plan, users, holidays, sharedCalendars } = useVacayStore()
const [mode, setMode] = useState<VacayMode>('vacation')
// Half-day is a per-person modifier on the vacation action, not a mode: with it
// on, clicking a day logs (or converts) it as a 0.5 day for the selected person.
@@ -59,6 +60,24 @@ export default function VacayCalendar() {
return map
}, [entries])
// Shared read-only calendars (#444/#667) render as colored rings, not fills,
// so they never mix into the members' split logic — merged stays merged,
// shared stays a distinct overlay.
const sharedMap = useMemo(() => {
const map: Record<string, SharedDayMark[]> = {}
sharedCalendars.filter(c => !c.hidden).forEach(cal => {
cal.entries.forEach(e => {
if (!map[e.date]) map[e.date] = []
map[e.date].push({ color: cal.color, name: cal.owner_name, fraction: e.fraction })
})
cal.companyHolidays.forEach(h => {
if (!map[h.date]) map[h.date] = []
map[h.date].push({ color: cal.color, name: cal.owner_name, company: true })
})
})
return map
}, [sharedCalendars])
const blockWeekends = plan?.block_weekends !== false
const weekendDays = useMemo<number[]>(() => (plan?.weekend_days ? String(plan.weekend_days).split(',').map(Number) : [0, 6]), [plan?.weekend_days])
const companyHolidaysEnabled = plan?.company_holidays_enabled !== false
@@ -74,8 +93,9 @@ export default function VacayCalendar() {
await toggleEntry(dateStr, selectedUserId || undefined, halfDay ? 0.5 : 1)
}, [mode, halfDay, toggleEntry, toggleCompanyHoliday, companyHolidaySet, blockWeekends, weekendDays, companyHolidaysEnabled, selectedUserId])
// Only half-day cells report a hover, so the tooltip appears exactly when there's
// a half day to explain. Fixed-positioned at the root so no card clips it.
// Cells with a half day or a shared overlay report a hover, so the tooltip
// appears exactly when there's something to explain. Fixed-positioned at the
// root so no card clips it.
const handleCellHover = useCallback((dateStr: string | null, el: HTMLElement | null) => {
if (!dateStr || !el) { setTip(null); return }
const r = el.getBoundingClientRect()
@@ -84,6 +104,7 @@ export default function VacayCalendar() {
const selectedUser = users.find(u => u.id === selectedUserId)
const tipEntries = tip ? entryMap[tip.date] : undefined
const tipShared = tip ? sharedMap[tip.date] : undefined
const tipDate = tip ? new Intl.DateTimeFormat(locale, { weekday: 'short', day: 'numeric', month: 'long' }).format(new Date(tip.date + 'T00:00:00')) : ''
return (
@@ -98,6 +119,7 @@ export default function VacayCalendar() {
companyHolidaySet={companyHolidaySet}
companyHolidaysEnabled={companyHolidaysEnabled}
entryMap={entryMap}
sharedMap={sharedMap}
onCellClick={handleCellClick}
onCellHover={handleCellHover}
companyMode={companyMode}
@@ -109,17 +131,18 @@ export default function VacayCalendar() {
))}
</div>
{/* Custom half-day tooltip — who is off on this date and how much. Rendered
fixed at the root (not inside a month card) so backdrop-filter stacking
contexts can't clip or occlude it. */}
{tip && tipEntries && tipEntries.length > 0 && (
{/* Custom day tooltip — who is off on this date and how much (own members
with half days, plus shared read-only calendars). Rendered fixed at the
root (not inside a month card) so backdrop-filter stacking contexts
can't clip or occlude it. */}
{tip && ((tipEntries && tipEntries.length > 0) || (tipShared && tipShared.length > 0)) && (
<div
className="vg-card rounded-xl"
style={{ position: 'fixed', top: tip.top - 9, left: tip.left, transform: 'translate(-50%, -100%)', zIndex: 80, pointerEvents: 'none' }}
>
<div style={{ padding: '8px 11px', minWidth: 132 }}>
<div className="capitalize" style={{ fontSize: 10, fontWeight: 700, letterSpacing: '0.02em', color: 'var(--vg-ink3)', marginBottom: 5 }}>{tipDate}</div>
{tipEntries.map((e, i) => {
{(tipEntries ?? []).map((e, i) => {
const isHalf = (e.fraction ?? 1) === 0.5
return (
<div key={i} className="flex items-center gap-2" style={{ marginTop: i ? 4 : 0 }}>
@@ -131,6 +154,16 @@ export default function VacayCalendar() {
</div>
)
})}
{/* Shared calendars: ring dot instead of a filled one, like the grid. */}
{(tipShared ?? []).map((m, i) => (
<div key={`s${i}`} className="flex items-center gap-2" style={{ marginTop: (tipEntries?.length || i) ? 4 : 0 }}>
<span className="w-2 h-2 rounded-full shrink-0" style={{ border: `2px solid ${m.color}` }} />
<span style={{ fontSize: 12, fontWeight: 600, color: 'var(--vg-ink)' }}>{m.name}</span>
<span style={{ marginLeft: 'auto', paddingLeft: 12, fontSize: 11, fontWeight: 700, color: 'var(--vg-ink3)' }}>
{m.company ? t('vacay.companyHoliday') : (m.fraction ?? 1) === 0.5 ? t('vacay.modeHalf') : t('vacay.fullDay')}
</span>
</div>
))}
</div>
</div>
)}
+17 -7
View File
@@ -11,6 +11,8 @@ interface VacayMonthCardProps {
companyHolidaySet: Set<string>
companyHolidaysEnabled?: boolean
entryMap: Record<string, VacayEntry[]>
// Shared read-only calendars per date (#444/#667) — rendered as rings, not fills.
sharedMap?: Record<string, { color: string }[]>
onCellClick: (date: string) => void
onCellHover?: (date: string | null, el: HTMLElement | null) => void
companyMode: boolean
@@ -21,7 +23,7 @@ interface VacayMonthCardProps {
}
export default function VacayMonthCard({
year, month, holidays, companyHolidaySet, companyHolidaysEnabled = true, entryMap,
year, month, holidays, companyHolidaySet, companyHolidaysEnabled = true, entryMap, sharedMap,
onCellClick, onCellHover, companyMode, blockWeekends, weekendDays = [0, 6], tripDates, weekStart = 1
}: VacayMonthCardProps) {
const { t, locale } = useTranslation()
@@ -107,6 +109,11 @@ export default function VacayMonthCard({
// never collides with the two-person diagonal split (#552).
const anyHalf = dayEntries.some(e => (e.fraction ?? 1) === 0.5)
// Shared calendars mark the day with an inset ring per person (capped at
// two — the tooltip lists everyone), keeping them visually apart from the
// filled member days.
const sharedColors = [...new Set((sharedMap?.[dateStr] || []).map(m => m.color))].slice(0, 2)
// Cell fill — people win, then company, then holiday (keeps each calendar's own colour).
let background = 'transparent'
if (dayEntries.length === 1) background = fill(dayEntries[0].person_color)
@@ -116,10 +123,13 @@ export default function VacayMonthCard({
// Weekend / settings-blocked days read as inactive: subtle grey fill, like before the facelift.
else if (weekend && blockWeekends) background = 'color-mix(in srgb, var(--vg-ink3) 7%, transparent)'
// Ring — today's inset outline beats the entry drop-shadow.
const boxShadow = isToday
? 'inset 0 0 0 2px var(--vg-ink)'
: hasEntries ? `0 3px 8px -3px ${pc(dayEntries[0].person_color)}` : undefined
// Rings — today's inset outline first, then one ring per shared calendar
// nested inside it; the entry drop-shadow stays as an outer glow.
const shadows: string[] = []
if (isToday) shadows.push('inset 0 0 0 2px var(--vg-ink)')
sharedColors.forEach((c, i) => shadows.push(`inset 0 0 0 ${(isToday ? 2 : 0) + (i + 1) * 2}px ${c}`))
if (!isToday && hasEntries) shadows.push(`0 3px 8px -3px ${pc(dayEntries[0].person_color)}`)
const boxShadow = shadows.length > 0 ? shadows.join(', ') : undefined
let numColor = 'var(--vg-ink2)'
if (hasEntries) numColor = '#fff'
@@ -141,11 +151,11 @@ export default function VacayMonthCard({
onClick={() => onCellClick(dateStr)}
onMouseEnter={e => {
if (!isBlocked && plain) e.currentTarget.style.background = 'var(--vg-surf2)'
if (anyHalf) onCellHover?.(dateStr, e.currentTarget)
if (anyHalf || sharedColors.length > 0) onCellHover?.(dateStr, e.currentTarget)
}}
onMouseLeave={e => {
if (!isBlocked && plain) e.currentTarget.style.background = background
if (anyHalf) onCellHover?.(null, null)
if (anyHalf || sharedColors.length > 0) onCellHover?.(null, null)
}}
>
{/* 3+ people: quadrant overlay at full colour (1 & 2 use the cell background). */}
@@ -0,0 +1,144 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { render } from '../../../tests/helpers/render'
import { resetAllStores, seedStore } from '../../../tests/helpers/store'
import { useVacayStore } from '../../store/vacayStore'
import { server } from '../../../tests/helpers/msw/server'
import { http, HttpResponse } from 'msw'
import VacaySharedCalendars from './VacaySharedCalendars'
// ── MSW handler helpers ───────────────────────────────────────────────────────
function withShareUsers() {
server.use(
http.get('/api/addons/vacay/shares/available-users', () =>
HttpResponse.json({ users: [{ id: 2, username: 'Bob' }] })
)
)
}
// ── Store seed helpers ────────────────────────────────────────────────────────
function seedShares(overrides: Record<string, unknown> = {}) {
seedStore(useVacayStore, {
outgoingShares: [],
incomingShares: [],
...overrides,
})
}
const incoming = { id: 7, owner_id: 3, username: 'Carol', color: '#ec4899', hidden: false }
// ─────────────────────────────────────────────────────────────────────────────
beforeEach(() => {
resetAllStores()
})
describe('VacaySharedCalendars', () => {
it('FE-COMP-VACAYSHARED-001: Renders empty hint when nothing is shared', () => {
seedShares()
render(<VacaySharedCalendars />)
expect(document.body).toHaveTextContent('Show each other your calendars without merging them.')
})
it('FE-COMP-VACAYSHARED-002: Renders incoming share with view-only badge', () => {
seedShares({ incomingShares: [incoming] })
render(<VacaySharedCalendars />)
expect(document.body).toHaveTextContent('Carol')
expect(document.body).toHaveTextContent('view only')
})
it('FE-COMP-VACAYSHARED-003: Row click hides a visible share via setShareHidden', async () => {
const setShareHiddenMock = vi.fn().mockResolvedValue(undefined)
const user = userEvent.setup()
seedShares({ incomingShares: [incoming], setShareHidden: setShareHiddenMock })
render(<VacaySharedCalendars />)
// Clicking the username bubbles up to the row's onClick toggle
await user.click(screen.getByText('Carol'))
expect(setShareHiddenMock).toHaveBeenCalledWith(7, true)
})
it('FE-COMP-VACAYSHARED-004: Hidden share row toggles back to visible', async () => {
const setShareHiddenMock = vi.fn().mockResolvedValue(undefined)
const user = userEvent.setup()
seedShares({ incomingShares: [{ ...incoming, hidden: true }], setShareHidden: setShareHiddenMock })
render(<VacaySharedCalendars />)
await user.click(screen.getByTitle('Show in calendar'))
expect(setShareHiddenMock).toHaveBeenCalledWith(7, false)
})
it('FE-COMP-VACAYSHARED-005: Remove button on incoming row calls removeShare', async () => {
const removeShareMock = vi.fn().mockResolvedValue(undefined)
const user = userEvent.setup()
seedShares({ incomingShares: [incoming], removeShare: removeShareMock })
render(<VacaySharedCalendars />)
await user.click(screen.getByRole('button', { name: 'Remove' }))
expect(removeShareMock).toHaveBeenCalledWith(7)
})
it('FE-COMP-VACAYSHARED-006: Outgoing section lists recipients with stop sharing', async () => {
const removeShareMock = vi.fn().mockResolvedValue(undefined)
const user = userEvent.setup()
seedShares({
outgoingShares: [{ id: 9, user_id: 2, username: 'Bob' }],
removeShare: removeShareMock,
})
render(<VacaySharedCalendars />)
expect(document.body).toHaveTextContent('You share with')
expect(document.body).toHaveTextContent('Bob')
await user.click(screen.getByRole('button', { name: /stop sharing/i }))
expect(removeShareMock).toHaveBeenCalledWith(9)
})
it('FE-COMP-VACAYSHARED-007: Share modal fetches users and shares with the selected one', async () => {
withShareUsers()
const shareWithMock = vi.fn().mockResolvedValue(undefined)
const user = userEvent.setup()
seedShares({ shareWith: shareWithMock })
render(<VacaySharedCalendars />)
// Open the share modal via the header button
await user.click(screen.getByTitle('Share calendar'))
expect(screen.getByRole('heading', { name: 'Share calendar' })).toBeInTheDocument()
// Wait for MSW to respond and the CustomSelect trigger to appear
await waitFor(() =>
expect(screen.getByRole('button', { name: /select user/i })).toBeInTheDocument()
)
// Open dropdown and select Bob
await user.click(screen.getByRole('button', { name: /select user/i }))
await waitFor(() => expect(screen.getByText('Bob')).toBeInTheDocument())
await user.click(screen.getByText('Bob'))
await user.click(screen.getByRole('button', { name: /^share$/i }))
expect(shareWithMock).toHaveBeenCalledWith(2)
})
})
@@ -0,0 +1,170 @@
import ReactDOM from 'react-dom'
import { useState } from 'react'
import { Share2, Eye, EyeOff, Loader2, X } from 'lucide-react'
import { useVacayStore } from '../../store/vacayStore'
import { useTranslation } from '../../i18n'
import { getApiErrorMessage } from '../../types'
import { useToast } from '../shared/Toast'
import CustomSelect from '../shared/CustomSelect'
import apiClient from '../../api/client'
import VacayBadge from './VacayBadge'
/**
* Sidebar card for read-only calendar sharing (#444/#667). Deliberately separate
* from the Persons card: Persons is the fusion (merge) feature, this card only
* grants view access. Incoming rows toggle that person's calendar overlay.
*/
export default function VacaySharedCalendars() {
const { t } = useTranslation()
const toast = useToast()
const { outgoingShares, incomingShares, shareWith, removeShare, setShareHidden } = useVacayStore()
const [showShare, setShowShare] = useState(false)
const [availableUsers, setAvailableUsers] = useState<{ id: number; username: string }[]>([])
const [selectedUser, setSelectedUser] = useState<number | null>(null)
const [sharing, setSharing] = useState(false)
const loadAvailable = async () => {
try {
const data = await apiClient.get('/addons/vacay/shares/available-users').then(r => r.data)
setAvailableUsers(data.users)
} catch { /* */ }
}
const handleShare = async () => {
if (!selectedUser) return
setSharing(true)
try {
await shareWith(selectedUser)
toast.success(t('vacay.shareSent'))
setShowShare(false)
setSelectedUser(null)
} catch (err: unknown) {
toast.error(getApiErrorMessage(err, t('vacay.shareFailed')))
} finally {
setSharing(false)
}
}
// The optimistic hide and the removals reject on server errors — surface them
// instead of leaving an unhandled rejection behind a silently reverted toggle.
const handleToggleHidden = (id: number, hidden: boolean) => {
setShareHidden(id, hidden).catch((err: unknown) => toast.error(getApiErrorMessage(err, t('vacay.shareFailed'))))
}
const handleRemove = (id: number) => {
removeShare(id).catch((err: unknown) => toast.error(getApiErrorMessage(err, t('vacay.shareFailed'))))
}
const empty = incomingShares.length === 0 && outgoingShares.length === 0
return (
<div className="vg-card rounded-[22px]" style={{ padding: '14px 18px' }}>
<div className="flex items-center justify-between mb-2">
<span style={{ fontSize: 11, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.14em', color: 'var(--vg-ink3)' }}>{t('vacay.sharedCalendars')}</span>
<button onClick={() => { setShowShare(true); loadAvailable() }}
className="w-7 h-7 rounded-lg flex items-center justify-center transition-colors"
style={{ color: 'var(--vg-ink3)' }}
title={t('vacay.shareCalendar')}>
<Share2 size={14} />
</button>
</div>
{empty && (
<p style={{ fontSize: 12, color: 'var(--vg-ink3)', lineHeight: 1.5 }}>{t('vacay.sharedEmpty')}</p>
)}
{incomingShares.length > 0 && (
<div className="flex flex-col gap-1">
{incomingShares.map(s => (
<div key={s.id}
onClick={() => handleToggleHidden(s.id, !s.hidden)}
className="flex items-center gap-2.5 group transition-colors cursor-pointer"
style={{ padding: '7px 10px', borderRadius: 12, opacity: s.hidden ? 0.55 : 1 }}
title={s.hidden ? t('vacay.showInCalendar') : t('vacay.hideFromCalendar')}>
{/* Ring dot — mirrors how shared days render in the grid (outline, not fill). */}
<span className="w-3 h-3 rounded-full shrink-0" style={{ border: `2.5px solid ${s.color}` }} />
<span className="truncate min-w-0" style={{ fontSize: 13, fontWeight: 600, color: 'var(--vg-ink)' }}>
{s.username}
</span>
<VacayBadge label={t('vacay.viewOnly')} />
<span className="ml-auto flex items-center gap-1">
<button onClick={e => { e.stopPropagation(); handleRemove(s.id) }}
className="opacity-0 group-hover:opacity-100 w-5 h-5 rounded flex items-center justify-center transition-all"
style={{ color: 'var(--vg-ink3)' }}
title={t('vacay.remove')}>
<X size={12} />
</button>
{s.hidden
? <EyeOff size={14} style={{ color: 'var(--vg-ink3)' }} />
: <Eye size={14} style={{ color: 'var(--vg-ink2)' }} />}
</span>
</div>
))}
</div>
)}
{outgoingShares.length > 0 && (
<div className="flex flex-col gap-1" style={{ marginTop: incomingShares.length > 0 ? 10 : 0 }}>
<span style={{ fontSize: 10, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.1em', color: 'var(--vg-ink3)', padding: '0 10px' }}>
{t('vacay.youShareWith')}
</span>
{outgoingShares.map(s => (
<div key={s.id} className="flex items-center gap-2.5 group"
style={{ padding: '5px 10px', borderRadius: 12 }}>
<Share2 size={12} style={{ color: 'var(--vg-ink3)' }} />
<span className="truncate min-w-0" style={{ fontSize: 13, color: 'var(--vg-ink2)' }}>
{s.username}
</span>
<button onClick={() => handleRemove(s.id)}
className="ml-auto opacity-0 group-hover:opacity-100 text-[10px] px-1.5 py-0.5 rounded transition-all"
style={{ color: 'var(--vg-ink3)' }}>
{t('vacay.stopSharing')}
</button>
</div>
))}
</div>
)}
{/* Share Modal — Portal to body to avoid z-index issues */}
{showShare && ReactDOM.createPortal(
<div className="fixed inset-0 flex items-center justify-center px-4 trek-backdrop-enter bg-[rgba(15,23,42,0.5)]" style={{ zIndex: 99990, paddingTop: 70 }}
onClick={() => setShowShare(false)}>
<div className="trek-modal-enter rounded-2xl shadow-2xl w-full max-w-sm bg-surface-card"
onClick={e => e.stopPropagation()}>
<div className="flex items-center justify-between p-5 border-b border-edge-secondary">
<h2 className="text-base font-semibold text-content">{t('vacay.shareCalendar')}</h2>
<button onClick={() => setShowShare(false)} className="p-1.5 rounded-lg transition-colors text-content-faint">
<X size={16} />
</button>
</div>
<div className="p-5 space-y-4">
<p className="text-xs text-content-muted">{t('vacay.shareCalendarHint')}</p>
{availableUsers.length === 0 ? (
<p className="text-xs text-center py-4 text-content-faint">{t('vacay.noUsersAvailable')}</p>
) : (
<CustomSelect
value={selectedUser}
onChange={v => setSelectedUser(Number(v))}
options={availableUsers.map(u => ({ value: u.id, label: u.username }))}
placeholder={t('vacay.selectUser')}
searchable
/>
)}
<div className="flex gap-3 justify-end pt-2">
<button onClick={() => setShowShare(false)} className="px-4 py-2 text-sm rounded-lg text-content-muted border border-edge">
{t('common.cancel')}
</button>
<button onClick={handleShare} disabled={!selectedUser || sharing}
className="px-4 py-2 text-sm rounded-lg transition-colors flex items-center gap-1.5 disabled:opacity-40 bg-content text-surface-card">
{sharing && <Loader2 size={13} className="animate-spin" />}
{t('vacay.share')}
</button>
</div>
</div>
</div>
</div>,
document.body
)}
</div>
)
}