Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

15.3 KB
Raw Blame
import React, { useId } from 'react'
import { createPortal } from 'react-dom'
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, Eye, Pencil, Trash2, Unlink, ShieldCheck, SlidersHorizontal, Handshake } from 'lucide-react'
import ConfirmDialog from '../components/shared/ConfirmDialog'
import { DialogButton, DialogFooter, DialogHeader, DialogShell, DialogTile, FooterSpacer, NEUTRAL_TINT, fs } from '../components/shared/DialogShell'
import HelpAnchor from '../components/Help/HelpAnchor'
import { useVacay } from './vacay/useVacay'

export default function VacayPage(): React.ReactElement {
  // ViewportRoute in App.tsx picks the branch now, so the phone screen is a
  // chunk of its own instead of a dead limb in this one.
  return (
    <>
      <HelpAnchor id="vacay" />
      <VacayPageDesktop />
    </>
  )
}

function VacayPageDesktop(): React.ReactElement {
  const { t } = useTranslation()
  // Page = wiring container: vacay store, live sync + UI state live in the hook.
  const {
    years, selectedYear, setSelectedYear, removeYear, loading,
    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))' }}>
        <div className="w-8 h-8 border-2 rounded-full animate-spin border-edge border-t-content" />
      </PageShell>
    )
  }

  // Sidebar content (shared between desktop sidebar and mobile drawer)
  const sidebarContent = (
    <>
      {/* Year Selector */}
      <div className="vg-card rounded-[22px]" style={{ padding: '14px 18px' }}>
        <div className="mb-3">
          <span style={{ fontSize: 11, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.14em', color: 'var(--vg-ink3)' }}>{t('vacay.year')}</span>
        </div>
        <div className="flex items-center justify-between mb-3">
          <div className="flex items-center gap-0.5">
            <button type="button" onClick={handleAddPrevYear} className="w-7 h-7 rounded-lg flex items-center justify-center transition-colors" style={{ color: 'var(--vg-ink3)' }} title={t('vacay.addPrevYear')}>
              <Plus size={14} />
            </button>
            <button type="button" onClick={() => { const idx = years.indexOf(selectedYear); if (idx > 0) setSelectedYear(years[idx - 1]) }} disabled={years.indexOf(selectedYear) <= 0} className="w-7 h-7 rounded-lg flex items-center justify-center disabled:opacity-20 transition-colors" style={{ color: 'var(--vg-ink3)' }}>
              <ChevronLeft size={16} />
            </button>
          </div>
          <span className="tabular-nums" style={{ fontSize: 22, fontWeight: 700, color: 'var(--vg-ink)' }}>{selectedYear}</span>
          <div className="flex items-center gap-0.5">
            <button type="button" onClick={() => { const idx = years.indexOf(selectedYear); if (idx < years.length - 1) setSelectedYear(years[idx + 1]) }} disabled={years.indexOf(selectedYear) >= years.length - 1} className="w-7 h-7 rounded-lg flex items-center justify-center disabled:opacity-20 transition-colors" style={{ color: 'var(--vg-ink3)' }}>
              <ChevronRight size={16} />
            </button>
            <button type="button" onClick={handleAddNextYear} className="w-7 h-7 rounded-lg flex items-center justify-center transition-colors" style={{ color: 'var(--vg-ink3)' }} title={t('vacay.addYear')}>
              <Plus size={14} />
            </button>
          </div>
        </div>
        <div className="grid grid-cols-4 gap-1.5">
          {years.map(y => (
            <div key={y} role="button" tabIndex={0} onClick={() => setSelectedYear(y)}
              onKeyDown={e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); setSelectedYear(y) } }}
              className="group relative rounded-[9px] text-center cursor-pointer transition-[background-color,color] duration-150 ease-[cubic-bezier(0.23,1,0.32,1)]"
              style={{
                padding: '7px 0',
                fontSize: 12,
                fontWeight: 600,
                background: y === selectedYear ? 'var(--vg-ink)' : 'var(--vg-surf2)',
                color: y === selectedYear ? 'var(--vg-bg)' : 'var(--vg-ink2)',
              }}>
              {y}
              {years.length > 1 && (
                <button type="button" aria-label={t('vacay.removeYear')}
                  onClick={e => { e.stopPropagation(); setDeleteYear(y); setShowMobileSidebar(false) }}
                  className="absolute -top-1 -end-1 w-3.5 h-3.5 rounded-full bg-red-500 text-white text-[7px] flex items-center justify-center opacity-0 group-hover:opacity-100 focus-visible:opacity-100 group-focus-within:opacity-100 transition-opacity cursor-pointer">
                  <Minus size={7} />
                </button>
              )}
            </div>
          ))}
        </div>
      </div>

      <VacayPersons />

      <VacaySharedCalendars />

      {/* Legend */}
      {(plan?.holidays_enabled || plan?.school_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">
            {plan?.holidays_enabled && (plan?.holiday_calendars ?? []).filter(cal => (cal.type ?? 'public_holiday') === 'public_holiday').length === 0 && (
              <LegendItem color="#fecaca" label={t('vacay.publicHoliday')} />
            )}
            {plan?.holidays_enabled && (plan?.holiday_calendars ?? []).filter(cal => (cal.type ?? 'public_holiday') === 'public_holiday').map(cal => (
              <LegendItem key={cal.id} color={cal.color} label={cal.label || cal.region} />
            ))}
            {plan?.school_holidays_enabled && (plan?.holiday_calendars ?? []).filter(cal => cal.type === 'school_holiday').map(cal => (
              <LegendItem key={cal.id} color={cal.color} label={cal.label || cal.region} />
            ))}
            {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>
      )}

      <VacayStats />
    </>
  )

  return (
    <PageShell background="var(--vg-bg)">
        <div className="max-w-[1800px] mx-auto px-3 sm:px-4 lg:px-8 py-4 lg:py-9">
          {/* Mobile + tablet header (filter toggle lives here) */}
          <div className="lg:hidden flex items-center justify-between mb-4">
            <div className="flex items-center gap-3">
              <div className="w-9 h-9 rounded-xl flex items-center justify-center bg-surface-secondary">
                <CalendarDays size={18} className="text-content" />
              </div>
              <h1 className="text-lg font-bold text-content">{t('admin.addons.catalog.vacay.name')}</h1>
            </div>
            <div className="flex items-center gap-2">
              <button type="button"
                onClick={() => setShowMobileSidebar(true)}
                className="lg:hidden flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-sm transition-colors bg-surface-secondary text-content-muted"
              >
                <SlidersHorizontal size={14} />
              </button>
              <button type="button"
                onClick={() => setShowSettings(true)}
                className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-sm transition-colors bg-surface-secondary text-content-muted"
              >
                <Settings size={14} />
              </button>
            </div>
          </div>

          {/* Main layout */}
          <div className="flex gap-4 lg:gap-7 items-start">
            {/* Desktop Sidebar */}
            <div className="hidden lg:flex w-[300px] shrink-0 flex-col gap-[12px] sticky top-[84px]">
              {sidebarContent}
              <button type="button"
                onClick={() => setShowSettings(true)}
                className="vg-card flex items-center justify-center gap-2.5 rounded-[18px] transition-transform hover:-translate-y-px"
                style={{ padding: '13px 16px', fontSize: 14, fontWeight: 600, color: 'var(--vg-ink)', cursor: 'pointer' }}
              >
                <Settings size={16} strokeWidth={2.2} /> {t('vacay.settings')}
              </button>
            </div>

            {/* Calendar */}
            <div className="flex-1 min-w-0">
              <VacayCalendar />
            </div>
          </div>
        </div>

      {/* Mobile Sidebar Drawer. It sits just under the dialog layer, because the
          invite, share and colour dialogs of the cards inside it open over it. */}
      {showMobileSidebar && createPortal(
        <div className="fixed inset-0 lg:hidden" style={{ zIndex: 'calc(var(--z-modal) - 1)' }}>
          <div className="absolute inset-0 bg-[rgba(0,0,0,0.4)]" role="presentation" onClick={() => setShowMobileSidebar(false)} />
          <div className="absolute left-0 top-0 bottom-0 w-[280px] overflow-y-auto p-3 flex flex-col gap-3 bg-surface"
            style={{ boxShadow: '4px 0 24px rgba(0,0,0,0.15)', animation: 'slideInLeft 0.2s ease-out' }}>
            {sidebarContent}
          </div>
        </div>,
        document.body
      )}

      <SettingsDialog open={showSettings} onClose={() => setShowSettings(false)} />

      <ConfirmDialog
        isOpen={deleteYear !== null}
        onClose={() => setDeleteYear(null)}
        onConfirm={() => removeYear(deleteYear)}
        title={t('vacay.removeYear')}
        message={t('vacay.removeYearConfirm', { year: deleteYear })}
        confirmLabel={t('vacay.remove')}
      >
        <p className="m-0 text-content-muted" style={fs(12.5, 'body')}>{t('vacay.removeYearHint')}</p>
      </ConfirmDialog>

      {incomingInvites[0] && (
        <FusionRequestDialog
          key={incomingInvites[0].plan_id}
          invite={incomingInvites[0]}
          onAccept={acceptInvite}
          onDecline={declineInvite}
        />
      )}

      <style>{`
        @keyframes slideInLeft {
          from { transform: translateX(-100%); }
          to { transform: translateX(0); }
        }
      `}</style>
    </PageShell>
  )
}

/** The plan's settings. They save as they change, so the frame has no footer. */
function SettingsDialog({ open, onClose }: { open: boolean; onClose: () => void }): React.ReactElement {
  const { t } = useTranslation()
  const labelId = useId()
  return (
    <DialogShell
      open={open}
      onClose={onClose}
      labelledBy={labelId}
      width="wide"
      // Calendars and their add form open inside, so the upper edge stays put.
      align="top"
      header={(
        <DialogHeader
          tile={<DialogTile><Settings size={20} strokeWidth={1.9} className="text-content-muted" /></DialogTile>}
          tint={NEUTRAL_TINT}
          labelId={labelId}
          onClose={onClose}
          title={t('vacay.settings')}
        />
      )}
    >
      <VacaySettings onClose={onClose} />
    </DialogShell>
  )
}

/**
 * Someone asks to fuse their calendar with yours. The request has to be
 * answered, so there is no close button and Escape and the backdrop leave it
 * alone. Several requests are shown one after the other, the next once the
 * first is answered.
 */
function FusionRequestDialog({ invite, onAccept, onDecline }: {
  invite: { plan_id: number; owner_username: string }
  onAccept: (planId: number) => void
  onDecline: (planId: number) => void
}): React.ReactElement {
  const { t } = useTranslation()
  const labelId = useId()
  return (
    <DialogShell
      onClose={() => { /* never called: blocked keeps Escape and the backdrop from closing it */ }}
      blocked
      labelledBy={labelId}
      width="narrow"
      header={(
        // DialogHeader always draws a close button, so the band is drawn here without one.
        <header className="flex-none px-6 pb-4 pt-5" style={{ background: NEUTRAL_TINT }}>
          <div className="flex items-start gap-3.5">
            <DialogTile><Handshake size={20} strokeWidth={1.9} className="text-content-muted" /></DialogTile>
            <div className="min-w-0 flex-1 pt-0.5">
              <h2 id={labelId} className="m-0 truncate font-bold tracking-[-0.01em] text-content" style={fs(20, 'subtitle')}>
                {t('vacay.inviteTitle')}
              </h2>
              <p className="m-0 mt-0.5 break-words font-geist text-content-muted" style={fs(12.5)}>
                <span className="font-semibold text-content">{invite.owner_username}</span> {t('vacay.inviteWantsToFuse')}
              </p>
            </div>
          </div>
        </header>
      )}
      footer={(
        <DialogFooter>
          <FooterSpacer />
          <DialogButton onClick={() => onDecline(invite.plan_id)}>{t('vacay.decline')}</DialogButton>
          <DialogButton variant="primary" onClick={() => onAccept(invite.plan_id)}>{t('vacay.acceptFusion')}</DialogButton>
        </DialogFooter>
      )}
    >
      <ul className="m-0 flex list-none flex-col gap-0.5 rounded-[14px] border border-edge-faint bg-surface-secondary p-1.5">
        <InfoItem icon={Eye} text={t('vacay.fuseInfo1')} />
        <InfoItem icon={Pencil} text={t('vacay.fuseInfo2')} />
        <InfoItem icon={Trash2} text={t('vacay.fuseInfo3')} />
        <InfoItem icon={ShieldCheck} text={t('vacay.fuseInfo4')} />
        <InfoItem icon={Unlink} text={t('vacay.fuseInfo5')} />
      </ul>
    </DialogShell>
  )
}

function InfoItem({ icon: Icon, text }: { icon: React.ComponentType<{ size?: number; strokeWidth?: number; className?: string }>; text: string }): React.ReactElement {
  return (
    <li className="flex items-start gap-3 rounded-[10px] px-2.5 py-2">
      <span className="grid h-7 w-7 flex-none place-items-center rounded-[9px] bg-surface-card text-content-muted shadow-sm">
        <Icon size={14} strokeWidth={2} />
      </span>
      <span className="min-w-0 pt-1 leading-normal text-content" style={fs(12.5, 'body')}>{text}</span>
    </li>
  )
}

function LegendItem({ color, label, ring }: { color?: string; label: string; ring?: boolean }): React.ReactElement {
  return (
    <span className="inline-flex items-center gap-[7px]">
      {/* 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>
  )
}