mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-01 08:53:13 +00:00
* 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:
@@ -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',
|
||||
|
||||
@@ -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>
|
||||
)}
|
||||
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -38,6 +38,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',
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Building2, ChevronLeft, ChevronRight, Eye, Minus, PenLine, Pencil, Plus, Settings2, ShieldCheck, Trash2, Unlink, UserPlus } from 'lucide-react'
|
||||
import { Building2, ChevronLeft, ChevronRight, Eye, Minus, PenLine, Pencil, Plus, Settings2, Share2, ShieldCheck, Trash2, Unlink, UserPlus } from 'lucide-react'
|
||||
import type { LucideIcon } from 'lucide-react'
|
||||
import MSheet from '../../components/MSheet'
|
||||
import MIconBtn from '../../components/MIconBtn'
|
||||
@@ -8,6 +8,7 @@ import { useMVacay } from './useMVacay'
|
||||
import MVacayMonth from './MVacayMonth'
|
||||
import MVacayInviteSheet from './MVacayInviteSheet'
|
||||
import MVacaySettingsSheet from './MVacaySettingsSheet'
|
||||
import MVacayShareSheet from './MVacayShareSheet'
|
||||
import { FALLBACK_PERSON_COLOR } from './vacayDayModel'
|
||||
|
||||
const WEEKDAY_KEYS_MONDAY = ['vacay.mon', 'vacay.tue', 'vacay.wed', 'vacay.thu', 'vacay.fri', 'vacay.sat', 'vacay.sun'] as const
|
||||
@@ -46,6 +47,9 @@ export default function MVacay() {
|
||||
<MIconBtn onClick={() => v.setSheet('invite')} ariaLabel={t('vacay.inviteUser')}>
|
||||
<UserPlus size={16} strokeWidth={2} className="text-m-muted" />
|
||||
</MIconBtn>
|
||||
<MIconBtn onClick={() => v.setSheet('share')} ariaLabel={t('vacay.sharedCalendars')}>
|
||||
<Share2 size={16} strokeWidth={2} className="text-m-muted" />
|
||||
</MIconBtn>
|
||||
<span className="flex flex-1 items-center justify-between rounded-full border border-[color:var(--m-gbr)] bg-[color:var(--m-sheet)] p-1 shadow-[0_5px_12px_-8px_rgba(0,0,0,.18)]">
|
||||
<button type="button" onClick={v.prevYear} aria-label={t('mobileVacay.prevYear')} className="flex h-[34px] w-[34px] flex-none items-center justify-center rounded-full">
|
||||
<ChevronLeft size={17} strokeWidth={2.2} />
|
||||
@@ -135,6 +139,22 @@ export default function MVacay() {
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
{/* Shared read-only calendars: tap toggles that person's ring overlay. */}
|
||||
{v.incomingShares.map(s => (
|
||||
<button
|
||||
key={`share-${s.id}`}
|
||||
type="button"
|
||||
onClick={() => v.toggleShareHidden(s.id, !s.hidden)}
|
||||
aria-pressed={!s.hidden}
|
||||
className="box-border inline-flex min-w-0 flex-[1_1_calc(25%-6px)] items-center justify-center gap-1 rounded-full px-1 py-1 font-geist text-[0.625rem] font-bold"
|
||||
style={s.hidden
|
||||
? { background: 'var(--m-sheetop)', border: '1px solid var(--m-rowbr)', color: 'var(--m-faint)', opacity: 0.7 }
|
||||
: { background: `${s.color}1f`, border: `1px solid ${s.color}`, color: 'var(--m-ink)' }}
|
||||
>
|
||||
<span className="h-[9px] w-[9px] flex-none rounded-[3px]" style={{ border: `2px solid ${s.color}` }} />
|
||||
<span className="truncate">{s.username}</span>
|
||||
</button>
|
||||
))}
|
||||
{v.companyHolidaysEnabled && (
|
||||
<LegendChip color="#F5D9A6" label={t('mobileVacay.companyLegend')} />
|
||||
)}
|
||||
@@ -280,6 +300,7 @@ export default function MVacay() {
|
||||
{/* Sheets */}
|
||||
<MVacayInviteSheet open={v.sheet === 'invite'} onClose={() => v.setSheet(null)} />
|
||||
<MVacaySettingsSheet open={v.sheet === 'settings'} onClose={() => v.setSheet(null)} />
|
||||
<MVacayShareSheet open={v.sheet === 'share'} onClose={() => v.setSheet(null)} />
|
||||
<MVacayIncomingInvite
|
||||
invites={v.incomingInvites}
|
||||
onAccept={v.acceptInvite}
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { ChevronDown, Eye, EyeOff, Loader2, Share2, X } from 'lucide-react'
|
||||
import MSheet from '../../components/MSheet'
|
||||
import MIconBtn from '../../components/MIconBtn'
|
||||
import { useVacayStore } from '../../../store/vacayStore'
|
||||
import { useTranslation } from '../../../i18n'
|
||||
import { useToast } from '../../../components/shared/Toast'
|
||||
import { getApiErrorMessage } from '../../../types'
|
||||
import apiClient from '../../../api/client'
|
||||
|
||||
interface MVacayShareSheetProps {
|
||||
open: boolean
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Read-only calendar sharing sheet (#444/#667): share your own calendar with
|
||||
* another TREK user (view only, no fusion), see who shares with you (with a
|
||||
* per-person overlay eye toggle) and stop shares in both directions.
|
||||
*/
|
||||
export default function MVacayShareSheet({ open, onClose }: MVacayShareSheetProps) {
|
||||
const { t } = useTranslation()
|
||||
const toast = useToast()
|
||||
const { incomingShares, outgoingShares, shareWith, removeShare, setShareHidden } = useVacayStore()
|
||||
const [available, setAvailable] = useState<{ id: number; username: string }[]>([])
|
||||
const [selected, setSelected] = useState<number | null>(null)
|
||||
const [pickerOpen, setPickerOpen] = useState(false)
|
||||
const [sending, setSending] = useState(false)
|
||||
|
||||
const showError = (err: unknown) => toast.error(getApiErrorMessage(err, t('vacay.shareFailed')))
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
setSelected(null)
|
||||
setPickerOpen(false)
|
||||
apiClient.get('/addons/vacay/shares/available-users')
|
||||
.then(r => setAvailable(r.data.users))
|
||||
.catch(() => setAvailable([]))
|
||||
}, [open])
|
||||
|
||||
const selectedUser = available.find(u => u.id === selected)
|
||||
|
||||
const handleShare = async () => {
|
||||
if (!selected) return
|
||||
setSending(true)
|
||||
try {
|
||||
await shareWith(selected)
|
||||
toast.success(t('vacay.shareSent'))
|
||||
setSelected(null)
|
||||
} catch (err: unknown) {
|
||||
toast.error(getApiErrorMessage(err, t('vacay.shareFailed')))
|
||||
} finally {
|
||||
setSending(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<MSheet open={open} onClose={onClose} variant="card" material="glass" ariaLabel={t('vacay.sharedCalendars')}>
|
||||
<div className="px-[18px] pb-[18px] pt-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex-1 text-[1.0625rem] font-bold">{t('vacay.sharedCalendars')}</div>
|
||||
<MIconBtn variant="neutral" size={34} onClick={onClose} ariaLabel={t('common.close')}>
|
||||
<X size={15} strokeWidth={2.2} />
|
||||
</MIconBtn>
|
||||
</div>
|
||||
<div className="mb-3 mt-2 font-geist text-[0.75rem] leading-normal text-m-muted">
|
||||
{t('vacay.shareCalendarHint')}
|
||||
</div>
|
||||
|
||||
{available.length === 0 ? (
|
||||
<div className="rounded-[14px] border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] px-[14px] py-3 text-center font-geist text-[0.75rem] text-m-faint">
|
||||
{t('vacay.noUsersAvailable')}
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setPickerOpen(o => !o)}
|
||||
className="flex min-w-0 flex-1 items-center gap-[9px] rounded-[14px] border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] px-[14px] py-3 text-[0.8125rem] font-semibold"
|
||||
>
|
||||
<span className={`min-w-0 flex-1 truncate text-left ${selectedUser ? '' : 'text-m-muted'}`}>
|
||||
{selectedUser ? selectedUser.username : t('vacay.selectUser')}
|
||||
</span>
|
||||
<ChevronDown size={14} strokeWidth={2} className="flex-none text-m-faint" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleShare}
|
||||
disabled={!selected || sending}
|
||||
className="flex flex-none items-center gap-[6px] rounded-full bg-m-act px-4 py-[10px] text-[0.78125rem] font-semibold text-m-actfg disabled:opacity-40"
|
||||
>
|
||||
{sending ? <Loader2 size={13} className="animate-spin" /> : <Share2 size={13} strokeWidth={2.2} />}
|
||||
{t('vacay.share')}
|
||||
</button>
|
||||
</div>
|
||||
{pickerOpen && (
|
||||
<div className="mt-[6px] max-h-[180px] overflow-y-auto rounded-[14px] border border-[color:var(--m-rowbr)] bg-[color:var(--m-sheetop)] p-[6px]">
|
||||
{available.map(u => (
|
||||
<button
|
||||
key={u.id}
|
||||
type="button"
|
||||
onClick={() => { setSelected(u.id); setPickerOpen(false) }}
|
||||
className={`flex w-full items-center gap-[9px] rounded-[10px] px-[10px] py-[9px] text-left text-[0.8125rem] font-semibold ${
|
||||
u.id === selected ? 'bg-[color:var(--m-ic)]' : ''
|
||||
}`}
|
||||
>
|
||||
<span className="min-w-0 flex-1 truncate">{u.username}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{incomingShares.length > 0 && (
|
||||
<div className="mt-3 flex flex-col gap-[6px]">
|
||||
<div className="px-1 font-geist text-[0.625rem] font-bold uppercase tracking-[.06em] text-m-faint">
|
||||
{t('vacay.sharedWithYou')}
|
||||
</div>
|
||||
{incomingShares.map(s => (
|
||||
<div key={s.id} className="flex items-center gap-[9px] rounded-[14px] border border-[color:var(--m-rowbr)] bg-[color:var(--m-sheetop)] px-[14px] py-[10px]">
|
||||
<span className="h-[11px] w-[11px] flex-none rounded-full" style={{ border: `2.5px solid ${s.color}` }} />
|
||||
<span className={`min-w-0 flex-1 truncate text-[0.8125rem] font-semibold ${s.hidden ? 'text-m-faint' : ''}`}>
|
||||
{s.username}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShareHidden(s.id, !s.hidden).catch(showError)}
|
||||
aria-label={s.hidden ? t('vacay.showInCalendar') : t('vacay.hideFromCalendar')}
|
||||
className="flex h-[28px] w-[28px] flex-none items-center justify-center rounded-full bg-[color:var(--m-ic)]"
|
||||
>
|
||||
{s.hidden
|
||||
? <EyeOff size={13} strokeWidth={2.2} className="text-m-faint" />
|
||||
: <Eye size={13} strokeWidth={2.2} className="text-m-muted" />}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => removeShare(s.id).catch(showError)}
|
||||
className="flex-none rounded-full px-[8px] py-1 font-geist text-[0.6875rem] font-semibold text-m-muted"
|
||||
>
|
||||
{t('vacay.remove')}
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{outgoingShares.length > 0 && (
|
||||
<div className="mt-3 flex flex-col gap-[6px]">
|
||||
<div className="px-1 font-geist text-[0.625rem] font-bold uppercase tracking-[.06em] text-m-faint">
|
||||
{t('vacay.youShareWith')}
|
||||
</div>
|
||||
{outgoingShares.map(s => (
|
||||
<div key={s.id} className="flex items-center gap-[9px] rounded-[14px] border border-[color:var(--m-rowbr)] bg-[color:var(--m-sheetop)] px-[14px] py-[10px]">
|
||||
<Share2 size={13} strokeWidth={2} className="flex-none text-m-faint" />
|
||||
<span className="min-w-0 flex-1 truncate text-[0.8125rem] font-semibold">{s.username}</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => removeShare(s.id).catch(showError)}
|
||||
className="flex-none rounded-full px-[10px] py-1 font-geist text-[0.6875rem] font-semibold text-m-muted"
|
||||
>
|
||||
{t('vacay.stopSharing')}
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</MSheet>
|
||||
)
|
||||
}
|
||||
@@ -4,14 +4,15 @@ import { useVacay } from '../../../pages/vacay/useVacay'
|
||||
import { useVacayStore } from '../../../store/vacayStore'
|
||||
import { useAuthStore } from '../../../store/authStore'
|
||||
import { useTranslation } from '../../../i18n'
|
||||
import { useToast } from '../../../components/shared/Toast'
|
||||
import { tripsApi } from '../../../api/client'
|
||||
import { isWeekend } from '../../../components/Vacay/holidays'
|
||||
import { FALLBACK_PERSON_COLOR, localDateStr, type DayVisualContext } from './vacayDayModel'
|
||||
import type { Trip } from '../../../types'
|
||||
import { getApiErrorMessage, type Trip } from '../../../types'
|
||||
|
||||
export type MVacayView = 'grid' | 'edit'
|
||||
export type MVacayMode = 'vacation' | 'company'
|
||||
export type MVacaySheet = 'invite' | 'settings' | null
|
||||
export type MVacaySheet = 'invite' | 'settings' | 'share' | null
|
||||
|
||||
/**
|
||||
* Screen state of the mobile Vacay experience. Data loading, WebSocket sync
|
||||
@@ -20,7 +21,8 @@ export type MVacaySheet = 'invite' | 'settings' | null
|
||||
* mode, sheets) plus the derived per-day render context.
|
||||
*/
|
||||
export function useMVacay() {
|
||||
const { locale } = useTranslation()
|
||||
const { t, locale } = useTranslation()
|
||||
const toast = useToast()
|
||||
const navigate = useNavigate()
|
||||
const {
|
||||
years, selectedYear, setSelectedYear, loading,
|
||||
@@ -31,6 +33,7 @@ export function useMVacay() {
|
||||
entries, companyHolidays, stats, users, holidays,
|
||||
selectedUserId, setSelectedUserId, isFused,
|
||||
toggleEntry, toggleCompanyHoliday, updateVacationDays,
|
||||
incomingShares, sharedCalendars, setShareHidden,
|
||||
} = useVacayStore()
|
||||
const currentUser = useAuthStore(s => s.user)
|
||||
|
||||
@@ -95,9 +98,23 @@ export function useMVacay() {
|
||||
return localDateStr(d.getFullYear(), d.getMonth(), d.getDate())
|
||||
}, [])
|
||||
|
||||
// Shared read-only calendars (#444/#667) overlay as rings; hidden ones stay out.
|
||||
const sharedMap = useMemo(() => {
|
||||
const map: Record<string, { color: string }[]> = {}
|
||||
sharedCalendars.filter(c => !c.hidden).forEach(cal => {
|
||||
const push = (date: string) => {
|
||||
if (!map[date]) map[date] = []
|
||||
map[date].push({ color: cal.color })
|
||||
}
|
||||
cal.entries.forEach(e => push(e.date))
|
||||
cal.companyHolidays.forEach(h => push(h.date))
|
||||
})
|
||||
return map
|
||||
}, [sharedCalendars])
|
||||
|
||||
const dayCtx = useMemo<DayVisualContext>(() => ({
|
||||
todayStr, entryMap, companyHolidaySet, companyHolidaysEnabled, holidays, weekendDays,
|
||||
}), [todayStr, entryMap, companyHolidaySet, companyHolidaysEnabled, holidays, weekendDays])
|
||||
todayStr, entryMap, companyHolidaySet, companyHolidaysEnabled, holidays, weekendDays, sharedMap,
|
||||
}), [todayStr, entryMap, companyHolidaySet, companyHolidaysEnabled, holidays, weekendDays, sharedMap])
|
||||
|
||||
const monthNamesShort = useMemo(() => {
|
||||
const fmt = new Intl.DateTimeFormat(locale, { month: 'short' })
|
||||
@@ -113,6 +130,12 @@ export function useMVacay() {
|
||||
const selectedColor = selectedUser?.color || FALLBACK_PERSON_COLOR
|
||||
const selectedStat = stats.find(s => s.user_id === selectedUserId)
|
||||
|
||||
// Shared-chip tap: the optimistic hide toggle rolls back on server errors —
|
||||
// tell the user instead of letting the chip snap back silently.
|
||||
const toggleShareHidden = useCallback((shareId: number, hidden: boolean) => {
|
||||
setShareHidden(shareId, hidden).catch((err: unknown) => toast.error(getApiErrorMessage(err, t('vacay.shareFailed'))))
|
||||
}, [setShareHidden, toast, t])
|
||||
|
||||
// Fusion: logging for each other — any fused member is selectable.
|
||||
const selectPerson = useCallback((id: number) => {
|
||||
if (isFused || id === currentUser?.id) {
|
||||
@@ -174,6 +197,7 @@ export function useMVacay() {
|
||||
loading, plan, selectedYear,
|
||||
users, isFused, currentUser,
|
||||
incomingInvites, acceptInvite, declineInvite,
|
||||
incomingShares, toggleShareHidden,
|
||||
view, month, mode, halfDay, setHalfDay, sheet, setSheet, setMode, setMonth,
|
||||
tripDates, tripDotColor,
|
||||
blockWeekends, companyHolidaysEnabled, holidaysEnabled, weekStart, weekendDays,
|
||||
|
||||
@@ -19,6 +19,9 @@ export interface DayVisualContext {
|
||||
companyHolidaysEnabled: boolean
|
||||
holidays: HolidaysMap
|
||||
weekendDays: number[]
|
||||
// Shared read-only calendars per date (#444/#667) — drawn as inset rings on
|
||||
// top of whatever the cell shows, never as fills.
|
||||
sharedMap?: Record<string, { color: string }[]>
|
||||
}
|
||||
|
||||
function hexToHsl(hex: string): { h: number; s: number; l: number } | null {
|
||||
@@ -80,7 +83,7 @@ export function splitBackground(colors: string[]): string {
|
||||
* plain. Logged and company cells keep hard dark inks — the pastels are
|
||||
* theme-independent surfaces.
|
||||
*/
|
||||
export function dayVisual(dateStr: string, dayOfWeek: number, ctx: DayVisualContext): DayVisual {
|
||||
function baseDayVisual(dateStr: string, dayOfWeek: number, ctx: DayVisualContext): DayVisual {
|
||||
if (dateStr === ctx.todayStr) {
|
||||
return { background: 'transparent', numColor: 'var(--m-ink)', boxShadow: 'inset 0 0 0 1.5px var(--m-ink)' }
|
||||
}
|
||||
@@ -107,6 +110,20 @@ export function dayVisual(dateStr: string, dayOfWeek: number, ctx: DayVisualCont
|
||||
return { background: 'transparent', numColor: 'var(--m-muted)' }
|
||||
}
|
||||
|
||||
export function dayVisual(dateStr: string, dayOfWeek: number, ctx: DayVisualContext): DayVisual {
|
||||
const visual = baseDayVisual(dateStr, dayOfWeek, ctx)
|
||||
// Shared calendars (#444/#667) draw inset rings over the base cell — capped at
|
||||
// two so tiny mini-grid cells stay readable. Nested inside the today ring.
|
||||
const rings = [...new Set((ctx.sharedMap?.[dateStr] || []).map(m => m.color))].slice(0, 2)
|
||||
if (rings.length > 0) {
|
||||
const shadows = visual.boxShadow ? [visual.boxShadow] : []
|
||||
const base = visual.boxShadow ? 1.5 : 0
|
||||
rings.forEach((c, i) => shadows.push(`inset 0 0 0 ${base + (i + 1) * 1.5}px ${c}`))
|
||||
visual.boxShadow = shadows.join(', ')
|
||||
}
|
||||
return visual
|
||||
}
|
||||
|
||||
/** Empty leading cells before the 1st, honoring the configured week start. */
|
||||
export function monthLead(year: number, month: number, weekStart: number): number {
|
||||
return (new Date(year, month, 1).getDay() - weekStart + 7) % 7
|
||||
|
||||
@@ -30,6 +30,10 @@ vi.mock('../components/Vacay/VacaySettings', () => ({
|
||||
),
|
||||
}));
|
||||
|
||||
vi.mock('../components/Vacay/VacaySharedCalendars', () => ({
|
||||
default: () => <div data-testid="vacay-shared-calendars" />,
|
||||
}));
|
||||
|
||||
vi.mock('../components/Layout/Navbar', () => ({
|
||||
default: () => <nav data-testid="navbar" />,
|
||||
}));
|
||||
@@ -45,11 +49,14 @@ const makeVacayState = (overrides = {}) => ({
|
||||
loading: false,
|
||||
incomingInvites: [] as any[],
|
||||
plan: null,
|
||||
sharedCalendars: [] as any[],
|
||||
loadAll: vi.fn().mockResolvedValue(undefined),
|
||||
loadPlan: vi.fn().mockResolvedValue(undefined),
|
||||
loadEntries: vi.fn().mockResolvedValue(undefined),
|
||||
loadStats: vi.fn().mockResolvedValue(undefined),
|
||||
loadHolidays: vi.fn().mockResolvedValue(undefined),
|
||||
loadShares: vi.fn().mockResolvedValue(undefined),
|
||||
loadSharedCalendars: vi.fn().mockResolvedValue(undefined),
|
||||
setSelectedYear: vi.fn(),
|
||||
addYear: vi.fn(),
|
||||
removeYear: vi.fn().mockResolvedValue(undefined),
|
||||
@@ -363,4 +370,29 @@ describe('VacayPage', () => {
|
||||
expect(mockRemoveYear).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
// FE-PAGE-VACAY-024: Shared calendars card renders in the sidebar
|
||||
it('renders VacaySharedCalendars', async () => {
|
||||
render(<VacayPage />);
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('vacay-shared-calendars')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
// FE-PAGE-VACAY-025: WebSocket vacay:share reloads shares and shared calendars
|
||||
it('handles vacay:share WebSocket message', () => {
|
||||
const mockLoadShares = vi.fn().mockResolvedValue(undefined);
|
||||
const mockLoadSharedCalendars = vi.fn().mockResolvedValue(undefined);
|
||||
const addListenerMock = websocket.addListener as ReturnType<typeof vi.fn>;
|
||||
seedStore(useVacayStore, makeVacayState({
|
||||
loadShares: mockLoadShares,
|
||||
loadSharedCalendars: mockLoadSharedCalendars,
|
||||
}) as any);
|
||||
render(<VacayPage />);
|
||||
const handler = addListenerMock.mock.calls[0][0];
|
||||
mockLoadSharedCalendars.mockClear();
|
||||
handler({ type: 'vacay:share' });
|
||||
expect(mockLoadShares).toHaveBeenCalled();
|
||||
expect(mockLoadSharedCalendars).toHaveBeenCalledWith(2025);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4,6 +4,7 @@ import { useTranslation } from '../i18n'
|
||||
import PageShell from '../components/Layout/PageShell'
|
||||
import VacayCalendar from '../components/Vacay/VacayCalendar'
|
||||
import VacayPersons from '../components/Vacay/VacayPersons'
|
||||
import VacaySharedCalendars from '../components/Vacay/VacaySharedCalendars'
|
||||
import VacayStats from '../components/Vacay/VacayStats'
|
||||
import VacaySettings from '../components/Vacay/VacaySettings'
|
||||
import { Plus, Minus, ChevronLeft, ChevronRight, Settings, CalendarDays, AlertTriangle, Eye, Pencil, Trash2, Unlink, ShieldCheck, SlidersHorizontal } from 'lucide-react'
|
||||
@@ -22,12 +23,14 @@ function VacayPageDesktop(): React.ReactElement {
|
||||
// Page = wiring container: vacay store, live sync + UI state live in the hook.
|
||||
const {
|
||||
years, selectedYear, setSelectedYear, removeYear, loading,
|
||||
incomingInvites, acceptInvite, declineInvite, plan,
|
||||
incomingInvites, acceptInvite, declineInvite, plan, sharedCalendars,
|
||||
showSettings, setShowSettings, deleteYear, setDeleteYear,
|
||||
showMobileSidebar, setShowMobileSidebar,
|
||||
handleAddNextYear, handleAddPrevYear,
|
||||
} = useVacay()
|
||||
|
||||
const hasVisibleShared = sharedCalendars.some(c => !c.hidden)
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<PageShell background="var(--vg-bg)" contentClassName="flex items-center justify-center" contentStyle={{ minHeight: 'calc(100vh - var(--nav-h))' }}>
|
||||
@@ -88,8 +91,10 @@ function VacayPageDesktop(): React.ReactElement {
|
||||
|
||||
<VacayPersons />
|
||||
|
||||
<VacaySharedCalendars />
|
||||
|
||||
{/* Legend */}
|
||||
{(plan?.holidays_enabled || plan?.company_holidays_enabled || plan?.block_weekends) && (
|
||||
{(plan?.holidays_enabled || plan?.company_holidays_enabled || plan?.block_weekends || hasVisibleShared) && (
|
||||
<div className="vg-card rounded-[22px]" style={{ padding: '14px 18px' }}>
|
||||
<span style={{ fontSize: 11, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.14em', color: 'var(--vg-ink3)' }}>{t('vacay.legend')}</span>
|
||||
<div className="mt-3 flex flex-wrap gap-x-3.5 gap-y-2.5">
|
||||
@@ -101,6 +106,7 @@ function VacayPageDesktop(): React.ReactElement {
|
||||
))}
|
||||
{plan?.company_holidays_enabled && <LegendItem color="#fde68a" label={t('vacay.companyHoliday')} />}
|
||||
{plan?.block_weekends && <LegendItem color="#e5e7eb" label={t('vacay.weekend')} />}
|
||||
{hasVisibleShared && <LegendItem ring label={t('vacay.sharedLegend')} />}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
@@ -258,10 +264,13 @@ function InfoItem({ icon: Icon, text }: { icon: React.ComponentType<{ size?: num
|
||||
)
|
||||
}
|
||||
|
||||
function LegendItem({ color, label }: { color: string; label: string }): React.ReactElement {
|
||||
function LegendItem({ color, label, ring }: { color?: string; label: string; ring?: boolean }): React.ReactElement {
|
||||
return (
|
||||
<span className="inline-flex items-center gap-[7px]">
|
||||
<span style={{ width: 18, height: 12, borderRadius: 4, flex: 'none', background: color }} />
|
||||
{/* Shared calendars render as rings in the grid, so the legend swatch does too. */}
|
||||
{ring
|
||||
? <span style={{ width: 18, height: 12, borderRadius: 4, flex: 'none', border: '2px solid var(--vg-ink2)' }} />
|
||||
: <span style={{ width: 18, height: 12, borderRadius: 4, flex: 'none', background: color }} />}
|
||||
<span style={{ fontSize: 12, color: 'var(--vg-ink2)' }}>{label}</span>
|
||||
</span>
|
||||
)
|
||||
|
||||
@@ -10,7 +10,7 @@ import { addListener, removeListener } from '../../api/websocket'
|
||||
* Behaviour is identical to the previous in-component logic.
|
||||
*/
|
||||
export function useVacay() {
|
||||
const { years, selectedYear, setSelectedYear, addYear, removeYear, loadAll, loadPlan, loadEntries, loadStats, loadHolidays, loading, incomingInvites, acceptInvite, declineInvite, plan } = useVacayStore()
|
||||
const { years, selectedYear, setSelectedYear, addYear, removeYear, loadAll, loadPlan, loadEntries, loadStats, loadHolidays, loadShares, loadSharedCalendars, loading, incomingInvites, acceptInvite, declineInvite, plan, sharedCalendars } = useVacayStore()
|
||||
const [showSettings, setShowSettings] = useState<boolean>(false)
|
||||
const [deleteYear, setDeleteYear] = useState<number | null>(null)
|
||||
const [showMobileSidebar, setShowMobileSidebar] = useState<boolean>(false)
|
||||
@@ -28,6 +28,10 @@ export function useVacay() {
|
||||
if (msg.type === 'vacay:invite' || msg.type === 'vacay:accepted' || msg.type === 'vacay:declined' || msg.type === 'vacay:cancelled' || msg.type === 'vacay:dissolved') {
|
||||
loadAll()
|
||||
}
|
||||
if (msg.type === 'vacay:share' || msg.type === 'vacay:share-removed' || msg.type === 'vacay:shared-update') {
|
||||
loadShares()
|
||||
loadSharedCalendars(selectedYear)
|
||||
}
|
||||
}, [selectedYear])
|
||||
|
||||
useEffect(() => {
|
||||
@@ -35,7 +39,7 @@ export function useVacay() {
|
||||
return () => removeListener(handleWsMessage)
|
||||
}, [handleWsMessage])
|
||||
useEffect(() => {
|
||||
if (selectedYear) { loadEntries(selectedYear); loadStats(selectedYear); loadHolidays(selectedYear) }
|
||||
if (selectedYear) { loadEntries(selectedYear); loadStats(selectedYear); loadHolidays(selectedYear); loadSharedCalendars(selectedYear) }
|
||||
}, [selectedYear])
|
||||
|
||||
const handleAddNextYear = () => {
|
||||
@@ -50,7 +54,7 @@ export function useVacay() {
|
||||
|
||||
return {
|
||||
years, selectedYear, setSelectedYear, removeYear, loading,
|
||||
incomingInvites, acceptInvite, declineInvite, plan,
|
||||
incomingInvites, acceptInvite, declineInvite, plan, sharedCalendars,
|
||||
showSettings, setShowSettings, deleteYear, setDeleteYear,
|
||||
showMobileSidebar, setShowMobileSidebar,
|
||||
handleAddNextYear, handleAddPrevYear,
|
||||
|
||||
@@ -2,11 +2,14 @@ import { create } from 'zustand'
|
||||
import apiClient from '../api/client'
|
||||
import { useAuthStore } from './authStore'
|
||||
import type { AxiosResponse } from 'axios'
|
||||
import type { VacayPlan, VacayUser, VacayEntry, VacayStat, HolidaysMap, HolidayInfo, VacayHolidayCalendar } from '../types'
|
||||
import type {
|
||||
VacayPlan, VacayUser, VacayEntry, VacayStat, HolidaysMap, HolidayInfo, VacayHolidayCalendar,
|
||||
VacayShareOutgoing, VacayShareIncoming, SharedVacayCalendar,
|
||||
} from '../types'
|
||||
import type {
|
||||
VacaySetColorRequest, VacayInviteRequest, VacayInviteActionRequest,
|
||||
VacayAddYearRequest, VacayToggleEntryRequest, VacayCompanyHolidayRequest,
|
||||
VacayUpdateStatsRequest,
|
||||
VacayUpdateStatsRequest, VacayShareRequest, VacayShareUpdateRequest,
|
||||
} from '@trek/shared'
|
||||
|
||||
const ax = apiClient
|
||||
@@ -74,6 +77,12 @@ interface VacayApi {
|
||||
addHolidayCalendar: (data: { region: string; color?: string; label?: string | null }) => Promise<{ calendar: VacayHolidayCalendar }>
|
||||
updateHolidayCalendar: (id: number, data: { region?: string; color?: string; label?: string | null }) => Promise<{ calendar: VacayHolidayCalendar }>
|
||||
deleteHolidayCalendar: (id: number) => Promise<unknown>
|
||||
getShares: () => Promise<{ outgoing: VacayShareOutgoing[]; incoming: VacayShareIncoming[] }>
|
||||
share: (userId: number) => Promise<unknown>
|
||||
removeShare: (shareId: number) => Promise<unknown>
|
||||
updateShare: (shareId: number, hidden: boolean) => Promise<unknown>
|
||||
shareAvailableUsers: () => Promise<{ users: VacayUser[] }>
|
||||
getSharedCalendars: (year: number) => Promise<{ calendars: SharedVacayCalendar[] }>
|
||||
}
|
||||
|
||||
const api: VacayApi = {
|
||||
@@ -99,6 +108,12 @@ const api: VacayApi = {
|
||||
addHolidayCalendar: (data) => ax.post('/addons/vacay/plan/holiday-calendars', data).then((r: AxiosResponse) => r.data),
|
||||
updateHolidayCalendar: (id, data) => ax.put(`/addons/vacay/plan/holiday-calendars/${id}`, data).then((r: AxiosResponse) => r.data),
|
||||
deleteHolidayCalendar: (id) => ax.delete(`/addons/vacay/plan/holiday-calendars/${id}`).then((r: AxiosResponse) => r.data),
|
||||
getShares: () => ax.get('/addons/vacay/shares').then((r: AxiosResponse) => r.data),
|
||||
share: (userId) => ax.post('/addons/vacay/shares', { user_id: userId } satisfies VacayShareRequest).then((r: AxiosResponse) => r.data),
|
||||
removeShare: (shareId) => ax.delete(`/addons/vacay/shares/${shareId}`).then((r: AxiosResponse) => r.data),
|
||||
updateShare: (shareId, hidden) => ax.put(`/addons/vacay/shares/${shareId}`, { hidden } satisfies VacayShareUpdateRequest).then((r: AxiosResponse) => r.data),
|
||||
shareAvailableUsers: () => ax.get('/addons/vacay/shares/available-users').then((r: AxiosResponse) => r.data),
|
||||
getSharedCalendars: (year) => ax.get(`/addons/vacay/shares/calendars/${year}`).then((r: AxiosResponse) => r.data),
|
||||
}
|
||||
|
||||
interface VacayState {
|
||||
@@ -116,6 +131,9 @@ interface VacayState {
|
||||
selectedUserId: number | null
|
||||
holidays: HolidaysMap
|
||||
loading: boolean
|
||||
outgoingShares: VacayShareOutgoing[]
|
||||
incomingShares: VacayShareIncoming[]
|
||||
sharedCalendars: SharedVacayCalendar[]
|
||||
|
||||
setSelectedYear: (year: number) => void
|
||||
setSelectedUserId: (id: number | null) => void
|
||||
@@ -139,6 +157,11 @@ interface VacayState {
|
||||
addHolidayCalendar: (data: { region: string; color?: string; label?: string | null }) => Promise<void>
|
||||
updateHolidayCalendar: (id: number, data: { region?: string; color?: string; label?: string | null }) => Promise<void>
|
||||
deleteHolidayCalendar: (id: number) => Promise<void>
|
||||
loadShares: () => Promise<void>
|
||||
loadSharedCalendars: (year?: number) => Promise<void>
|
||||
shareWith: (userId: number) => Promise<void>
|
||||
removeShare: (shareId: number) => Promise<void>
|
||||
setShareHidden: (shareId: number, hidden: boolean) => Promise<void>
|
||||
loadAll: () => Promise<void>
|
||||
}
|
||||
|
||||
@@ -157,6 +180,9 @@ export const useVacayStore = create<VacayState>((set, get) => ({
|
||||
selectedUserId: null,
|
||||
holidays: {},
|
||||
loading: false,
|
||||
outgoingShares: [],
|
||||
incomingShares: [],
|
||||
sharedCalendars: [],
|
||||
|
||||
setSelectedYear: (year: number) => set({ selectedYear: year }),
|
||||
setSelectedUserId: (id: number | null) => set({ selectedUserId: id }),
|
||||
@@ -347,6 +373,44 @@ export const useVacayStore = create<VacayState>((set, get) => ({
|
||||
await get().loadHolidays()
|
||||
},
|
||||
|
||||
loadShares: async () => {
|
||||
const data = await api.getShares()
|
||||
set({ outgoingShares: data.outgoing, incomingShares: data.incoming })
|
||||
},
|
||||
|
||||
loadSharedCalendars: async (year?: number) => {
|
||||
const y = year || get().selectedYear
|
||||
const data = await api.getSharedCalendars(y)
|
||||
set({ sharedCalendars: data.calendars })
|
||||
},
|
||||
|
||||
shareWith: async (userId: number) => {
|
||||
await api.share(userId)
|
||||
await get().loadShares()
|
||||
},
|
||||
|
||||
removeShare: async (shareId: number) => {
|
||||
await api.removeShare(shareId)
|
||||
await get().loadShares()
|
||||
await get().loadSharedCalendars()
|
||||
},
|
||||
|
||||
setShareHidden: async (shareId: number, hidden: boolean) => {
|
||||
// Optimistic: the eye toggle should feel instant; reconcile via refetch.
|
||||
const prevIncoming = get().incomingShares
|
||||
const prevCalendars = get().sharedCalendars
|
||||
set({
|
||||
incomingShares: prevIncoming.map(s => (s.id === shareId ? { ...s, hidden } : s)),
|
||||
sharedCalendars: prevCalendars.map(c => (c.share_id === shareId ? { ...c, hidden } : c)),
|
||||
})
|
||||
try {
|
||||
await api.updateShare(shareId, hidden)
|
||||
} catch (e) {
|
||||
set({ incomingShares: prevIncoming, sharedCalendars: prevCalendars })
|
||||
throw e
|
||||
}
|
||||
},
|
||||
|
||||
loadAll: async () => {
|
||||
set({ loading: true })
|
||||
try {
|
||||
@@ -356,6 +420,8 @@ export const useVacayStore = create<VacayState>((set, get) => ({
|
||||
await get().loadEntries(year)
|
||||
await get().loadStats(year)
|
||||
await get().loadHolidays(year)
|
||||
await get().loadShares()
|
||||
await get().loadSharedCalendars(year)
|
||||
} finally {
|
||||
set({ loading: false })
|
||||
}
|
||||
|
||||
@@ -330,6 +330,31 @@ export interface HolidaysMap {
|
||||
[date: string]: HolidayInfo
|
||||
}
|
||||
|
||||
// Read-only calendar shares (#444/#667)
|
||||
export interface VacayShareOutgoing {
|
||||
id: number
|
||||
user_id: number
|
||||
username: string
|
||||
}
|
||||
|
||||
export interface VacayShareIncoming {
|
||||
id: number
|
||||
owner_id: number
|
||||
username: string
|
||||
color: string
|
||||
hidden: boolean
|
||||
}
|
||||
|
||||
export interface SharedVacayCalendar {
|
||||
share_id: number
|
||||
owner_id: number
|
||||
owner_name: string
|
||||
color: string
|
||||
hidden: boolean
|
||||
entries: { date: string; fraction?: number }[]
|
||||
companyHolidays: { date: string; note?: string }[]
|
||||
}
|
||||
|
||||
// API error shape from axios
|
||||
export interface ApiError {
|
||||
response?: {
|
||||
|
||||
Reference in New Issue
Block a user