feat(assistant): vacation calendar cards with the days left

This commit is contained in:
Maurice
2026-10-22 15:50:55 +02:00
parent c31b2162ad
commit a8ff98b660
59 changed files with 4783 additions and 70 deletions
@@ -0,0 +1,91 @@
import type { CSSProperties } from 'react';
import { useTranslation } from '../../../../i18n';
import { safeHexColor } from '../../../../utils/safeColor';
import type { CardEntry } from '../cardTypes';
import CardFrame from '../parts/CardFrame';
import { CardOpenButton } from '../parts/CardOpen';
import { useViewerId } from '../parts/useViewerId';
import VacayBalance from './VacayBalance';
import { balanceLines, mergeVacayCards, type VacayView } from './vacayCardModel';
import { personColor } from './vacayCellLook';
import { vacayPathOf } from './vacayLook';
import VacayMonthStrip from './VacayMonthStrip';
/**
* What the vacation planner's reads found, as one card: the months with the
* days off, a legend once more than one thing is drawn, the days off outside
* the months shown, the days left per person, and the way into Vacay on that
* year. Several reads in one answer read as one calendar.
*/
const LEGEND = 'mt-1.5 flex flex-wrap items-center gap-x-3 gap-y-1 text-caption text-content-muted';
const LEGEND_ITEM = 'inline-flex min-w-0 items-center gap-1.5';
const SWATCH = 'size-2 flex-none rounded-full';
const SQUARE = 'size-2 flex-none rounded-sm';
const COMPANY = 'size-2 flex-none rounded-sm bg-warning-soft ring-1 ring-inset ring-warning';
const TRIP = 'size-1.5 flex-none rounded-full bg-info';
const OTHER = 'mt-1.5 text-caption text-content-muted';
const FOOT = 'mt-1 flex justify-end';
interface LegendItem {
key: string;
label: string;
className: string;
style?: CSSProperties;
}
/** What the calendar draws, named once it draws more than one thing. */
function Legend({ view }: { view: VacayView }) {
const { t } = useTranslation();
const viewerId = useViewerId();
const people = view.people.filter((person) => view.days.some((day) => day.personId === person.id));
const holiday = view.holidays[0];
const items: LegendItem[] = people.map((person) => ({
key: `person-${person.id}`,
label: person.id === viewerId ? t('assistant.card.common.you') : person.name,
className: SWATCH,
style: { background: personColor(view, person.id) },
}));
if (holiday) {
const color = safeHexColor(holiday.color, 'var(--danger)');
items.push({
key: 'holiday',
label: t('vacay.publicHoliday'),
className: SQUARE,
style: { background: `color-mix(in srgb, ${color} 28%, transparent)` },
});
}
if (view.company.length > 0) items.push({ key: 'company', label: t('vacay.companyHoliday'), className: COMPANY });
if (view.tripDates.size > 0) items.push({ key: 'trip', label: t('assistant.card.vacay.trip'), className: TRIP });
if (items.length < 2) return null;
return (
<ul className={LEGEND}>
{items.map((item) => (
<li key={item.key} className={LEGEND_ITEM}>
<span aria-hidden="true" className={item.className} style={item.style} />
<bdi className="truncate">{item.label}</bdi>
</li>
))}
</ul>
);
}
export default function VacayAnswerBlock({ cards }: { cards: readonly CardEntry[] }) {
const { t } = useTranslation();
const own = cards.flatMap((entry) => (entry.card.kind === 'vacay' ? [entry.card] : []));
const view = mergeVacayCards(own);
const lines = balanceLines(view, []);
const first = own[0] ?? null;
return (
<CardFrame label={t('assistant.card.vacay.label')}>
{view.months.length > 0 && <VacayMonthStrip view={view} placed={[]} labelOf={() => ''} />}
<Legend view={view} />
{view.otherDays > 0 && <p className={OTHER}>{t('assistant.card.vacay.otherDays', { count: view.otherDays })}</p>}
<VacayBalance lines={lines} view={view} mode="read" />
<div className={FOOT}>
<CardOpenButton target={{ kind: 'page', path: vacayPathOf(first) }} labelKey="assistant.card.vacay.open" />
</div>
</CardFrame>
);
}
@@ -0,0 +1,184 @@
import { ArrowRight, CalendarDays, TriangleAlert } from 'lucide-react';
import type { CSSProperties, ReactNode } from 'react';
import { useTranslation } from '../../../../i18n';
import { SoftPill, WhiteBadge } from '../../../Planner/planParts';
import { Tooltip } from '../../../shared/Tooltip';
import { fmtDays } from '../../../Vacay/vacayFormat';
import { useViewerId } from '../parts/useViewerId';
import { type BalanceLine, lineFigures, namesYear, todayStr, type VacayView } from './vacayCardModel';
import { personColor } from './vacayCellLook';
/**
* The days left per person and leave year under the calendar: who, the days
* left before and after the changes that count, a meter of used, planned and
* left days in the person's colour, and what the changes come to (days used
* or given back, past the allowance, a new allowance). A read card shows the
* days left as they are.
*/
const ROW = 'mt-2 first:mt-1.5';
const HEAD = 'flex min-w-0 items-center gap-2';
const DOT = 'size-2 flex-none rounded-full';
const NAME = 'min-w-0 flex-1 text-body text-content';
const FIGURES = 'flex flex-none items-baseline gap-1 tabular-nums';
const FIGURE = 'text-body font-semibold text-content';
const CAPTION = 'text-caption text-content-muted';
const METER = 'mt-1 flex h-1.5 gap-0.5 overflow-hidden rounded-full';
const PILLS = 'mt-1 flex flex-wrap items-center gap-1';
const ARROW = 'flex-none self-center text-content-faint rtl:-scale-x-100';
type Mode = 'read' | 'change';
interface Piece {
key: string;
grow: number;
style: CSSProperties;
label: string;
className?: string;
}
/** The pieces of a person's meter: used, given back, planned, past the allowance, left. */
function meterPieces(line: BalanceLine, color: string, t: (key: string, params?: Record<string, number>) => string) {
const total = line.totalAfter ?? line.total;
const planned = Math.max(0, line.delta);
const given = Math.max(0, -line.delta);
const over = Math.max(0, line.used + line.delta - total);
const left = Math.max(0, total - line.used - line.delta);
const hatch = (tone: string) => `repeating-linear-gradient(45deg, ${tone} 0 2px, transparent 2px 4px)`;
const pieces: Piece[] = [
{
key: 'used',
grow: line.used - given,
style: { background: `color-mix(in srgb, ${color} 78%, transparent)` },
label: t('assistant.card.vacay.usedDays', { count: line.used - given }),
},
{
key: 'given',
grow: given,
style: {},
label: t('assistant.card.vacay.givesBack', { count: given }),
className: 'rounded-full outline-dashed outline-1 outline-offset-[-1px] outline-edge',
},
{
key: 'planned',
grow: planned - over,
style: { background: hatch(`color-mix(in srgb, ${color} 78%, transparent)`) },
label: t('assistant.card.vacay.uses', { count: planned - over }),
},
{
key: 'over',
grow: over,
style: { background: `${hatch('var(--danger)')}, var(--danger-soft)` },
label: t('assistant.card.vacay.over', { count: over }),
},
{
key: 'left',
grow: left,
style: { background: `color-mix(in srgb, ${color} 16%, transparent)` },
label: t('assistant.card.vacay.daysLeft', { count: left }),
},
];
return pieces.filter((piece) => piece.grow > 0);
}
function Line({ line, view, mode, withYear }: { line: BalanceLine; view: VacayView; mode: Mode; withYear: boolean }) {
const { t } = useTranslation();
const viewerId = useViewerId();
const person = view.people.find((candidate) => candidate.id === line.personId);
const color = personColor(view, line.personId);
const { left, leftAfter, over } = lineFigures(line);
const changes = line.delta !== 0 || line.totalAfter !== null;
const total = line.totalAfter ?? line.total;
const name = line.personId === viewerId ? t('assistant.card.common.you') : (person?.name ?? `#${line.personId}`);
const usedOf = t('assistant.card.vacay.usedOf', { used: fmtDays(line.used), total: fmtDays(total) });
const meter = t('assistant.card.vacay.meter', {
used: fmtDays(line.used),
planned: fmtDays(Math.max(0, line.delta)),
left: fmtDays(Math.max(0, leftAfter)),
total: fmtDays(total),
});
return (
<li className={ROW}>
<div className={HEAD}>
<span aria-hidden="true" className={DOT} style={{ background: color }} />
<bdi className={NAME}>{name}</bdi>
{withYear && <WhiteBadge>{line.year}</WhiteBadge>}
<span className={FIGURES}>
{changes && (
<>
<span className={FIGURE}>{fmtDays(left)}</span>
<ArrowRight size={12} aria-hidden="true" className={ARROW} />
</>
)}
{mode === 'read' && !changes && <span className={CAPTION}>{usedOf}</span>}
<span className={changes ? FIGURE : CAPTION}>
{t('assistant.card.vacay.daysLeft', { count: Math.max(0, changes ? leftAfter : left) })}
</span>
</span>
</div>
<div role="img" aria-label={meter} className={METER}>
{meterPieces(line, color, t).map((piece) => (
<Tooltip key={piece.key} label={piece.label} placement="top">
<span className={piece.className} style={{ ...piece.style, flexGrow: piece.grow }} />
</Tooltip>
))}
</div>
<BalanceFacts line={line} mode={mode} over={over} />
</li>
);
}
/** What the changes come to, in pills; a read card names the comp days only. */
function BalanceFacts({ line, mode, over }: { line: BalanceLine; mode: Mode; over: number }) {
const { t } = useTranslation();
const pills: ReactNode[] = [];
if (line.delta > 0) {
pills.push(<SoftPill key="uses">{t('assistant.card.vacay.uses', { count: line.delta })}</SoftPill>);
}
if (line.delta < 0) {
pills.push(<SoftPill key="given">{t('assistant.card.vacay.givesBack', { count: -line.delta })}</SoftPill>);
}
if (over > 0) {
pills.push(
<SoftPill key="over" tone="danger" icon={<TriangleAlert size={10} aria-hidden="true" />}>
{t('assistant.card.vacay.over', { count: over })}
</SoftPill>
);
}
if (line.totalAfter !== null) {
// The allowance alone, as the user set it: the totals also hold what was carried over.
pills.push(
<SoftPill key="allowance" icon={<CalendarDays size={10} aria-hidden="true" />}>
{t('assistant.card.vacay.allowance')}
<bdi className="text-content-faint line-through">{fmtDays(line.total - line.carried)}</bdi>
<ArrowRight size={9} aria-hidden="true" className={ARROW} />
<bdi>{fmtDays(line.totalAfter - line.carried)}</bdi>
</SoftPill>
);
}
if (mode === 'read' && line.comp > 0) {
pills.push(<SoftPill key="comp">{t('assistant.card.vacay.compDays', { count: line.comp })}</SoftPill>);
}
return pills.length > 0 ? <div className={PILLS}>{pills}</div> : null;
}
export default function VacayBalance({
lines,
view,
mode,
}: {
lines: readonly BalanceLine[];
view: VacayView;
mode: Mode;
}) {
if (lines.length === 0) return null;
const withYear = namesYear(lines, todayStr());
return (
<ul>
{lines.map((line) => (
<Line key={`${line.personId}:${line.year}`} line={line} view={view} mode={mode} withYear={withYear} />
))}
</ul>
);
}
@@ -0,0 +1,215 @@
/**
* FE-AI-VACAY-010 to FE-AI-VACAY-015
*
* The vacation card as the chat draws it: an answer as a month calendar with
* the days left and the way into Vacay, a change card's vacation rows under
* one calendar whose held days are taken in or left out with a tap, the days
* left following the choice, each row's facts, a decided card, and the phone,
* where one month fills the row.
*/
import type { AssistantApplied, AssistantChangeVerbKey, VacayCard, VacayCardProposal } from '@trek/shared';
import type { ReactElement } from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { buildUser } from '../../../../../tests/helpers/factories';
import { fireEvent, render, screen } from '../../../../../tests/helpers/render';
import { chatOf, useAssistantStore } from '../../../../store/assistantStore';
import { useAuthStore } from '../../../../store/authStore';
import AssistantChangeCard from '../../AssistantChangeCard';
import type { ChangeItem } from '../../assistantParts';
import { type AssistantView, AssistantViewContext } from '../../assistantViewContext';
import VacayAnswerBlock from './VacayAnswerBlock';
import VacayRowFacts from './VacayRowFacts';
const TRIP = 4;
const AUTH = useAuthStore.getState();
const INITIAL = useAssistantStore.getState();
const proposal = (over: Partial<VacayCardProposal> = {}): VacayCardProposal => ({
date: '2026-10-27',
personId: 7,
kind: 'vacation',
fraction: 1,
outcome: 'add',
before: null,
periodYear: 2026,
notes: [],
deltas: [{ personId: 7, year: 2026, days: 1 }],
...over,
});
const card = (over: Partial<VacayCard> = {}): VacayCard => ({
kind: 'vacay',
months: [{ year: 2026, month: 10 }],
weekStart: 1,
weekendDays: [0, 6],
people: [
{ id: 7, name: 'Ana', avatarKey: null, color: '#6366f1' },
{ id: 8, name: 'Ben', avatarKey: null, color: '#ec4899' },
],
days: [
{ date: '2026-10-26', personId: 7, fraction: 1, kind: 'vacation' },
{ date: '2026-10-29', personId: 8, fraction: 1, kind: 'vacation' },
],
company: [],
holidays: [{ date: '2026-10-03', name: 'Unity Day', color: null }],
tripDates: ['2026-10-28'],
proposal: null,
balances: [
{
personId: 7,
year: 2026,
total: 30,
used: 29,
comp: 0,
totalAfter: null,
windowStart: '2026-01-01',
windowEnd: '2027-01-01',
},
],
otherDays: 0,
...over,
});
function row(
id: string,
verbKey: AssistantChangeVerbKey,
held: VacayCardProposal,
state: ChangeItem['state'] = 'pending'
): ChangeItem {
const applied: AssistantApplied | null =
state === 'applied' ? { toolCallId: id, entity: 'vacay', ids: [], dayId: null, undoUntil: null } : null;
return {
toolCallId: id,
preview: { toolCallId: id, verbKey, subject: held.date, rows: [], dayId: null, placeIds: [], undoable: false },
applied,
state,
card: card({ proposal: held }),
};
}
function inView(ui: ReactElement, view: Partial<AssistantView> = {}) {
const value: AssistantView = { tripId: TRIP, variant: 'window', ...view };
return render(<AssistantViewContext.Provider value={value}>{ui}</AssistantViewContext.Provider>);
}
const decide = vi.fn(async () => {});
beforeEach(() => {
useAuthStore.setState({ user: buildUser({ id: 7 }) });
useAssistantStore.setState({
decide,
byTrip: { [TRIP]: { ...chatOf(useAssistantStore.getState(), TRIP), threadId: 1 } },
});
});
afterEach(() => {
useAuthStore.setState(AUTH, true);
useAssistantStore.setState(INITIAL, true);
vi.clearAllMocks();
});
describe('the vacation card', () => {
it('FE-AI-VACAY-010: an answer shows its month, a legend, the days left and the way into Vacay on its year', () => {
const onOpen = vi.fn();
inView(<VacayAnswerBlock cards={[{ toolCallId: 'r1', card: card({ otherDays: 2 }) }]} />, { onOpen });
expect(screen.getByRole('group', { name: 'October 2026' })).toBeInTheDocument();
expect(screen.getAllByText('You').length).toBeGreaterThan(1);
for (const label of ['Ben', 'Public Holiday', 'This trip', '2 more days off this year', '29 of 30 used']) {
expect(screen.getByText(label)).toBeInTheDocument();
}
expect(screen.getByText('1 day left')).toBeInTheDocument();
expect(screen.getByRole('img', { name: '29 used, 0 planned, 1 left of 30' })).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: /Open in Vacay/ }));
expect(onOpen).toHaveBeenCalledWith({ kind: 'page', path: '/vacay?year=2026' });
});
it('FE-AI-VACAY-011: held days sit on the calendar; a free one starts left out and a tap takes it in', () => {
inView(
<AssistantChangeCard
items={[
row('c1', 'addVacationDay', proposal()),
row('c2', 'removeVacationDay', proposal({ date: '2026-10-26', outcome: 'remove', deltas: [] })),
row('c3', 'addVacationDay', proposal({ date: '2026-10-03', notes: ['publicHoliday'] })),
]}
/>
);
const taken = screen.getByRole('button', { name: 'Tue, Oct 27: Take a day off' });
const free = screen.getByRole('button', { name: 'Sat, Oct 3: Take a day off' });
expect(taken).toHaveAttribute('aria-pressed', 'true');
expect(free).toHaveAttribute('aria-pressed', 'false');
expect(screen.getByRole('button', { name: 'Mon, Oct 26: Cancel a day off' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Apply 2' })).toBeEnabled();
expect(screen.getByText('Public holiday, no leave needed')).toBeInTheDocument();
fireEvent.click(free);
expect(screen.getByRole('button', { name: 'Sat, Oct 3: Take a day off' })).toHaveAttribute('aria-pressed', 'true');
fireEvent.click(screen.getByRole('button', { name: 'Apply 3' }));
expect(decide).toHaveBeenCalledWith(TRIP, [
{ toolCallId: 'c1', approved: true },
{ toolCallId: 'c2', approved: true },
{ toolCallId: 'c3', approved: true },
]);
});
it('FE-AI-VACAY-012: the days left follow the choice, up to a warning past the allowance', () => {
inView(
<AssistantChangeCard
items={[row('c1', 'addVacationDay', proposal()), row('c2', 'addVacationDay', proposal({ date: '2026-10-28' }))]}
/>
);
expect(screen.getByText('Uses 2 days')).toBeInTheDocument();
expect(screen.getByText('Over by 1 day')).toBeInTheDocument();
expect(screen.getByText('0 days left')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'Wed, Oct 28: Take a day off' }));
expect(screen.queryByText('Over by 1 day')).toBeNull();
expect(screen.getByText('Uses 1 day')).toBeInTheDocument();
});
it("FE-AI-VACAY-013: a row says how much of the day, whose day when it is not the user's, and a new allowance", () => {
const halfForBen = proposal({
personId: 8,
outcome: 'convert',
fraction: 0.5,
before: { fraction: 1, kind: 'vacation' },
notes: ['weekend'],
});
const item = row('c1', 'changeVacationDay', halfForBen);
const view = inView(<VacayRowFacts card={card({ proposal: halfForBen })} item={item} />);
expect(screen.getByText('Full day')).toHaveClass('line-through');
expect(screen.getByText('Half day')).toBeInTheDocument();
expect(screen.getByText('Ben')).toBeInTheDocument();
expect(screen.getByText('Weekend day, counts as leave')).toBeInTheDocument();
view.unmount();
// A company holiday while they are off in the plan: the tool writes it anyway, the row warns.
const off = proposal({ personId: null, kind: 'company', deltas: [], notes: ['companyOff'] });
const company = inView(<VacayRowFacts card={card({ proposal: off })} item={item} />);
expect(screen.getByText('Company holidays are turned off in this plan')).toBeInTheDocument();
company.unmount();
// The allowance alone: the totals 30 and 33 both hold the 2 days carried over.
const balance = { ...card().balances[0], carried: 2, totalAfter: 33 };
const allowance = card({ months: [], balances: [balance] });
inView(<VacayRowFacts card={allowance} item={item} />);
expect(screen.getByText('28')).toHaveClass('line-through');
expect(screen.getByText('31')).toBeInTheDocument();
});
it('FE-AI-VACAY-014: a decided card shows what was applied, without taps, and its receipt opens Vacay', () => {
const onOpen = vi.fn();
inView(<AssistantChangeCard items={[row('c1', 'addVacationDay', proposal(), 'applied')]} />, { onOpen });
expect(screen.queryByRole('button', { name: /Take a day off/ })).toBeNull();
expect(screen.getByText('0 days left')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'Open in Vacay' }));
expect(onOpen).toHaveBeenCalledWith({ kind: 'page', path: '/vacay?year=2026' });
});
it('FE-AI-VACAY-015: on the phone one month fills the row and a cell takes a finger', () => {
const { container } = inView(<AssistantChangeCard items={[row('c1', 'addVacationDay', proposal())]} />, {
variant: 'fullscreen',
});
expect(container.querySelector('li.w-full')).not.toBeNull();
expect(screen.getByRole('button', { name: 'Tue, Oct 27: Take a day off' })).toHaveClass('size-9');
});
});
@@ -0,0 +1,85 @@
import { TriangleAlert } from 'lucide-react';
import { useTranslation } from '../../../../i18n';
import { chatOf, useAssistantStore } from '../../../../store/assistantStore';
import { SoftPill } from '../../../Planner/planParts';
import type { ChangeItem } from '../../assistantParts';
import { useAssistantView } from '../../assistantViewContext';
import { verbLookOf } from '../cardLooks';
import VacayBalance from './VacayBalance';
import {
allowancesOf,
balanceLines,
mergeVacayCards,
type PlacedProposal,
placedProposals,
vacayCardsOf,
} from './vacayCardModel';
import VacayMonthStrip from './VacayMonthStrip';
/**
* The calendar over a change card's vacation rows: the months of the held
* days with what is logged there, each held day on its cell (tap one to take
* it in or leave it out), and the days left before and after what is chosen.
* Once the changes are decided it shows what was applied.
*/
const GROUP = 'mb-1 rounded-lg bg-surface-secondary px-2.5 pb-2 pt-2';
const PILLS = 'mt-1.5 flex flex-wrap items-center gap-1';
/** A held day's date as the change rows write it. */
function dateLabel(locale: string, date: string): string {
const value = new Date(`${date}T00:00:00`);
return new Intl.DateTimeFormat(locale, { weekday: 'short', day: 'numeric', month: 'short' }).format(value);
}
export default function VacayChangeGroup({
items,
excluded,
onToggle,
place,
}: {
items: readonly ChangeItem[];
excluded: ReadonlySet<string>;
onToggle(id: string): void;
place: 'head' | 'foot';
}) {
const { t, locale } = useTranslation();
const { tripId } = useAssistantView();
const isRunning = useAssistantStore((s) => chatOf(s, tripId).isRunning);
if (place !== 'head') return null;
const view = mergeVacayCards(vacayCardsOf(items).map((entry) => entry.card));
const placed = placedProposals(items, excluded);
const lines = balanceLines(view, placed, allowancesOf(items, excluded));
const waiting = items.some((item) => item.state === 'pending');
const verbOf = (toolCallId: string) => items.find((item) => item.toolCallId === toolCallId)?.preview?.verbKey;
const labelOf = (entry: PlacedProposal) => {
const verb = verbOf(entry.toolCallId);
const date = dateLabel(locale, entry.proposal.date);
return verb ? `${date}: ${t(verbLookOf(verb).labelKey)}` : date;
};
const twice = placed.some((entry) => entry.twice);
return (
<div className={GROUP}>
{view.months.length > 0 && (
<VacayMonthStrip
view={view}
placed={placed}
onToggle={waiting && !isRunning ? onToggle : undefined}
labelOf={labelOf}
/>
)}
{placed.length > 0 && (
<ul className="sr-only">{placed.map((entry) => <li key={entry.toolCallId}>{labelOf(entry)}</li>)}</ul>
)}
{twice && (
<div className={PILLS}>
<SoftPill tone="warning" icon={<TriangleAlert size={10} aria-hidden="true" />}>
{t('assistant.card.vacay.twice')}
</SoftPill>
</div>
)}
<VacayBalance lines={lines} view={view} mode="change" />
</div>
);
}
@@ -0,0 +1,124 @@
import { useMemo } from 'react';
import { useTranslation } from '../../../../i18n';
import { Tooltip } from '../../../shared/Tooltip';
import {
type CardMonth,
type CellSize,
type DayCell,
monthCells,
type PlacedProposal,
type VacayView,
} from './vacayCardModel';
import { cellLook } from './vacayCellLook';
/**
* One month of the vacation card, drawn the way the planner draws it: the
* weekdays in the user's language, a person's days in their colour, the
* company's and the public holidays, the trip's days dotted. A held day sits
* on its cell; while it waits, the cell is a button that takes it in or
* leaves it out, and its tooltip says which.
*/
const SIZE: Record<CellSize, string> = { compact: 'size-6', roomy: 'size-7', phone: 'size-9' };
const GRID: Record<CellSize, string> = {
compact: 'grid grid-cols-7 gap-0.5',
roomy: 'grid grid-cols-7 gap-1',
phone: 'grid grid-cols-7 gap-1.5',
};
const TITLE = 'mb-1.5 ps-0.5 text-caption font-semibold capitalize text-content';
const WEEKDAY = 'grid h-5 place-items-center text-caption text-content-faint';
const TRIP_DOT = 'absolute end-0.5 top-0.5 size-1 rounded-full bg-info';
const HALF_DOT = 'absolute bottom-0.5 end-0.5 size-1 rounded-full bg-warning';
interface MonthProps {
view: VacayView;
month: CardMonth;
placed: readonly PlacedProposal[];
today: string;
size: CellSize;
/** Takes a held day in or leaves it out; absent once the card is decided or while a turn runs. */
onToggle?: (toolCallId: string) => void;
/** A held day in words: its date and what it does. */
labelOf: (entry: PlacedProposal) => string;
}
/** The narrow weekday names from the week's first day on; 7 January 2024 was a Sunday. */
function weekdayNames(locale: string, weekStart: number): string[] {
const format = new Intl.DateTimeFormat(locale, { weekday: 'narrow' });
return Array.from({ length: 7 }, (_, column) => format.format(new Date(2024, 0, 7 + ((column + weekStart) % 7))));
}
/** "October 2026" in the user's language. */
function monthTitle(locale: string, year: number, month: number): string {
return new Intl.DateTimeFormat(locale, { month: 'long', year: 'numeric' }).format(new Date(year, month - 1));
}
function Cell({
view,
cell,
size,
onToggle,
labelOf,
}: Pick<MonthProps, 'view' | 'size' | 'onToggle' | 'labelOf'> & { cell: DayCell }) {
const { t } = useTranslation();
const look = cellLook(view, cell);
const className = [look.className, SIZE[size]].join(' ');
const marks = (
<>
{cell.trip && <span aria-hidden="true" className={TRIP_DOT} />}
{look.half && <span aria-hidden="true" className={HALF_DOT} />}
</>
);
const entry = look.proposal;
if (entry && onToggle && (entry.state === 'pending' || entry.state === 'excluded')) {
const label = labelOf(entry);
const hint = t(entry.state === 'pending' ? 'assistant.card.vacay.tapToSkip' : 'assistant.card.vacay.tapToTake');
return (
<Tooltip label={`${label}. ${hint}`} placement="top">
<button
type="button"
aria-pressed={entry.state === 'pending'}
aria-label={label}
onClick={() => onToggle(entry.toolCallId)}
className={className}
style={look.style}
>
{cell.day}
{marks}
</button>
</Tooltip>
);
}
const body = (
<span className={className} style={look.style}>
{cell.day}
{marks}
</span>
);
return cell.holiday ? <Tooltip label={cell.holiday.name} placement="top">{body}</Tooltip> : body;
}
export default function VacayMiniMonth({ view, month, placed, today, size, onToggle, labelOf }: MonthProps) {
const { locale } = useTranslation();
const title = useMemo(() => monthTitle(locale, month.year, month.month), [locale, month.year, month.month]);
const weekdays = useMemo(() => weekdayNames(locale, view.weekStart), [locale, view.weekStart]);
const cells = monthCells(view, month, placed, today);
return (
<div role="group" aria-label={title}>
<p className={TITLE}>{title}</p>
<div className={GRID[size]}>
{weekdays.map((name, column) => (
<span key={`weekday-${column}`} aria-hidden="true" className={WEEKDAY}>{name}</span>
))}
{cells.map((cell, index) =>
cell ? (
<Cell key={cell.date} view={view} cell={cell} size={size} onToggle={onToggle} labelOf={labelOf} />
) : (
<span key={`lead-${index}`} aria-hidden="true" />
)
)}
</div>
</div>
);
}
@@ -0,0 +1,91 @@
import { ChevronLeft, ChevronRight } from 'lucide-react';
import { useAssistantView } from '../../assistantViewContext';
import { useCardStrip } from '../parts/useCardStrip';
import { type CellSize, monthKey, type PlacedProposal, todayStr, type VacayView } from './vacayCardModel';
import VacayMiniMonth from './VacayMiniMonth';
/**
* The months of a vacation card side by side, to scroll through where they do
* not fit; on the phone one month fills the row and the next is a swipe away.
* The edges fade where there is more, as in the chat's other strips, and in
* the desktop window two arrows over the row page it by whole months.
*/
const STRIP =
'trek-assistant-strip flex snap-x snap-mandatory gap-4 overflow-x-auto overscroll-x-contain pb-1 motion-safe:scroll-smooth';
const WINDOW_MONTH = 'flex-none snap-start';
const PHONE_MONTH = 'w-full flex-none snap-center';
const PAGER = 'mb-1 flex justify-end gap-1.5';
// The look of the arrows over the chat's other strips (parts/CardStrip.tsx).
const PAGE_ARROW =
'grid h-7 w-7 place-items-center rounded-full bg-surface-card text-content-secondary shadow-sm ring-1 ring-edge-faint transition-colors hover:text-content disabled:cursor-default disabled:opacity-40 disabled:hover:text-content-secondary';
/** The two paging arrows, towards the start and towards the end; the months stay reachable by swipe and scroll. */
const PAGES = [
{ towards: -1, Icon: ChevronLeft, edge: 'start' },
{ towards: 1, Icon: ChevronRight, edge: 'end' },
] as const;
export default function VacayMonthStrip({
view,
placed,
onToggle,
labelOf,
}: {
view: VacayView;
placed: readonly PlacedProposal[];
onToggle?: (toolCallId: string) => void;
labelOf: (entry: PlacedProposal) => string;
}) {
const { variant, density } = useAssistantView();
// The months as text, so the strip measures again when they change and not on every render.
const { listRef, fade, measure, page } = useCardStrip(view.months.map(monthKey).join(','));
let size: CellSize = density === 'roomy' ? 'roomy' : 'compact';
if (variant === 'fullscreen') size = 'phone';
const today = todayStr();
const paged = variant === 'window' && (fade.start || fade.end);
return (
<>
{paged && (
<div className={PAGER}>
{PAGES.map(({ towards, Icon, edge }) => (
// For the pointer only, as over the other strips: the cells are reachable by Tab.
<button
key={edge}
type="button"
tabIndex={-1}
aria-hidden="true"
disabled={!fade[edge]}
onClick={() => page(towards)}
className={PAGE_ARROW}
>
<Icon size={15} className="rtl:-scale-x-100" />
</button>
))}
</div>
)}
<ul
ref={listRef}
onScroll={measure}
data-fade-start={fade.start || undefined}
data-fade-end={fade.end || undefined}
className={STRIP}
>
{view.months.map((month) => (
<li key={monthKey(month)} className={variant === 'fullscreen' ? PHONE_MONTH : WINDOW_MONTH}>
<VacayMiniMonth
view={view}
month={month}
placed={placed}
today={today}
size={size}
onToggle={onToggle}
labelOf={labelOf}
/>
</li>
))}
</ul>
</>
);
}
@@ -0,0 +1,77 @@
import type { VacayCard, VacayCardProposal, VacayProposalNote } from '@trek/shared';
import { CalendarDays, Coffee, Sun, SunDim } from 'lucide-react';
import { useTranslation } from '../../../../i18n';
import { safeHexColor } from '../../../../utils/safeColor';
import { type PillTone, SoftPill } from '../../../Planner/planParts';
import { fmtDays } from '../../../Vacay/vacayFormat';
import type { ChangeItem } from '../../assistantParts';
import { FactChange } from '../parts/CardFacts';
import { useViewerId } from '../parts/useViewerId';
/**
* The facts on a vacation row's faint line: how much of the day it is (old
* to new when it changes), whose day it is when it is not the user's, what
* the user should know about the day, and for a new allowance the allowance
* before and after.
*/
/** What the user should know about a day, in words and a tone. A table, so each key is named where it is read. */
const NOTE_LOOK: Record<VacayProposalNote, { labelKey: string; tone: PillTone }> = {
weekendBlocked: { labelKey: 'assistant.card.vacay.weekendBlocked', tone: 'warning' },
weekend: { labelKey: 'assistant.card.vacay.weekend', tone: 'warning' },
publicHoliday: { labelKey: 'assistant.card.vacay.publicHoliday', tone: 'info' },
companyHoliday: { labelKey: 'assistant.card.vacay.companyHoliday', tone: 'info' },
companyHalf: { labelKey: 'assistant.card.vacay.companyHalf', tone: 'info' },
notInPlan: { labelKey: 'assistant.card.vacay.notInPlan', tone: 'danger' },
companyOff: { labelKey: 'assistant.card.vacay.companyOff', tone: 'warning' },
};
/** How much of a day an entry is, by its kind and size. */
const SIZE_LOOK = {
comp: { labelKey: 'assistant.card.vacay.compDay', Icon: Coffee },
half: { labelKey: 'assistant.card.vacay.halfDay', Icon: SunDim },
full: { labelKey: 'assistant.card.vacay.fullDay', Icon: Sun },
} as const;
function sizeOf(day: Pick<VacayCardProposal, 'kind' | 'fraction'>): (typeof SIZE_LOOK)[keyof typeof SIZE_LOOK] {
if (day.kind === 'comp') return SIZE_LOOK.comp;
return day.fraction === 0.5 ? SIZE_LOOK.half : SIZE_LOOK.full;
}
const DOT = 'size-1.5 flex-none rounded-full';
export default function VacayRowFacts({ card }: { card: VacayCard; item: ChangeItem }) {
const { t } = useTranslation();
const viewerId = useViewerId();
const proposal = card.proposal;
if (!proposal) {
const balance = card.balances.find((row) => row.totalAfter !== null);
if (!balance || balance.totalAfter === null) return null;
// The allowance alone, the days carried over taken out of both totals.
const carried = balance.carried ?? 0;
const before = fmtDays(balance.total - carried);
return <FactChange icon={CalendarDays} before={before} after={fmtDays(balance.totalAfter - carried)} />;
}
const shown = proposal.outcome === 'remove' && proposal.before ? proposal.before : proposal;
const size = sizeOf(shown);
const before = proposal.outcome === 'convert' && proposal.before ? t(sizeOf(proposal.before).labelKey) : null;
const person =
proposal.personId !== null && proposal.personId !== viewerId
? card.people.find((candidate) => candidate.id === proposal.personId)
: undefined;
const dotColor = safeHexColor(person?.color, 'var(--accent)');
return (
<>
<FactChange icon={size.Icon} before={before} after={t(size.labelKey)} />
{person && (
<SoftPill icon={<span aria-hidden="true" className={DOT} style={{ background: dotColor }} />}>
<bdi className="truncate">{person.name}</bdi>
</SoftPill>
)}
{proposal.notes.map((note) => (
<SoftPill key={note} tone={NOTE_LOOK[note].tone}>{t(NOTE_LOOK[note].labelKey)}</SoftPill>
))}
</>
);
}
@@ -0,0 +1,227 @@
/**
* FE-AI-VACAY-001 to FE-AI-VACAY-007
*
* The pure side of the vacation cards: several cards read as one calendar,
* where each held day stands, the days left before and after the chosen
* changes, which days start left out, the cells of a month and their look,
* and where the card opens Vacay.
*/
import type { VacayCard, VacayCardProposal } from '@trek/shared';
import { describe, expect, it } from 'vitest';
import type { ChangeItem } from '../../assistantParts';
import {
allowancesOf,
balanceLines,
lineFigures,
mergeVacayCards,
monthCells,
namesYear,
placedProposals,
startsExcluded,
} from './vacayCardModel';
import { cellLook, entriesFill } from './vacayCellLook';
import { VACAY_LOOK, vacayPathOf, vacayYearOf } from './vacayLook';
const proposal = (over: Partial<VacayCardProposal> = {}): VacayCardProposal => ({
date: '2026-10-27',
personId: 7,
kind: 'vacation',
fraction: 1,
outcome: 'add',
before: null,
periodYear: 2026,
notes: [],
deltas: [{ personId: 7, year: 2026, days: 1 }],
...over,
});
const BALANCE = {
personId: 7,
year: 2026,
total: 30,
used: 28,
comp: 0,
totalAfter: null,
windowStart: '2026-01-01',
windowEnd: '2027-01-01',
};
const card = (over: Partial<VacayCard> = {}): VacayCard => ({
kind: 'vacay',
months: [{ year: 2026, month: 10 }],
weekStart: 1,
weekendDays: [0, 6],
people: [
{ id: 7, name: 'Ana', avatarKey: null, color: '#6366f1' },
{ id: 8, name: 'Ben', avatarKey: null, color: null },
],
days: [{ date: '2026-10-26', personId: 7, fraction: 1, kind: 'vacation' }],
company: [],
holidays: [],
tripDates: ['2026-10-28'],
proposal: proposal(),
balances: [BALANCE],
otherDays: 0,
...over,
});
/** The held days of a cell: each row's state with its day. */
type HeldStates = Array<[ChangeItem['state'], VacayCardProposal]>;
const item = (id: string, state: ChangeItem['state'], vacay: VacayCard): ChangeItem => ({
toolCallId: id,
preview: null,
applied: null,
state,
card: vacay,
});
describe('vacayCardModel', () => {
it('FE-AI-VACAY-001: cards of one block read as one calendar, months in order and each day once', () => {
const view = mergeVacayCards([
card({ months: [{ year: 2026, month: 11 }], otherDays: 2 }),
card({ days: [{ date: '2026-10-26', personId: 7, fraction: 0.5, kind: 'vacation' }], otherDays: 1 }),
]);
expect(view.months).toEqual([
{ year: 2026, month: 10 },
{ year: 2026, month: 11 },
]);
expect(view.days).toEqual([{ date: '2026-10-26', personId: 7, fraction: 0.5, kind: 'vacation' }]);
expect(view.balances).toHaveLength(1);
expect(view.otherDays).toBe(2);
expect(view.tripDates.has('2026-10-28')).toBe(true);
expect(mergeVacayCards([])).toMatchObject({ months: [], weekStart: 1, weekendDays: [0, 6], otherDays: 0 });
});
it('FE-AI-VACAY-002: a held day stands where its row stands, and the same day held twice is flagged', () => {
const excluded = new Set(['c2']);
const placed = placedProposals(
[
item('c1', 'pending', card()),
item('c2', 'pending', card()),
item('c3', 'discarded', card({ proposal: proposal({ date: '2026-10-29' }) })),
item('c4', 'applied', card({ proposal: null })),
],
excluded
);
expect(placed.map((entry) => [entry.toolCallId, entry.state, entry.twice])).toEqual([
['c1', 'pending', true],
['c2', 'excluded', true],
['c3', 'off', false],
]);
});
it('FE-AI-VACAY-003: the days left count the chosen, applying and applied changes, and a new allowance', () => {
const halfBack = [{ personId: 7, year: 2026, days: -0.5 }];
const giveBack = proposal({ date: '2026-10-30', outcome: 'remove', deltas: halfBack });
const items = [
item('c1', 'pending', card()),
item('c2', 'pending', card({ proposal: proposal({ date: '2026-10-28' }) })),
item('c3', 'failed', card({ proposal: proposal({ date: '2026-10-29' }) })),
item('c4', 'applied', card({ proposal: giveBack })),
];
const view = mergeVacayCards(items.map((entry) => entry.card as VacayCard));
const [line] = balanceLines(view, placedProposals(items, new Set()));
expect(line).toMatchObject({ personId: 7, year: 2026, used: 28, delta: 1.5, totalAfter: null });
expect(line && lineFigures(line)).toEqual({ left: 2, leftAfter: 0.5, over: 0 });
const [without] = balanceLines(view, placedProposals(items, new Set(['c1', 'c2'])));
expect(without?.delta).toBe(-0.5);
const allowance = card({
proposal: null,
months: [],
balances: [{ ...BALANCE, totalAfter: 26 }],
});
const raised = allowancesOf([...items, item('c5', 'pending', allowance)], new Set());
expect(raised.get('7:2026')).toBe(26);
const [tight] = balanceLines(view, placedProposals(items, new Set()), raised);
expect(tight && lineFigures(tight)).toEqual({ left: 2, leftAfter: -3.5, over: 3.5 });
expect(allowancesOf([item('c5', 'pending', allowance)], new Set(['c5'])).size).toBe(0);
// The same day held twice the same way is taken and cleared again: it counts for nothing.
const one = mergeVacayCards([card()]);
const twins = [item('t1', 'pending', card()), item('t2', 'pending', card())];
expect(balanceLines(one, placedProposals(twins, new Set()))[0]?.delta).toBe(0);
// Held twice in two sizes, the first says what happens to the day, and it counts once.
const halfDay = proposal({ fraction: 0.5, deltas: [{ personId: 7, year: 2026, days: 0.5 }] });
const sizes = [item('t1', 'pending', card()), item('t3', 'pending', card({ proposal: halfDay }))];
expect(balanceLines(one, placedProposals(sizes, new Set()))[0]?.delta).toBe(1);
// One of the pair left out: the other counts in full.
expect(balanceLines(one, placedProposals(twins, new Set(['t2'])))[0]?.delta).toBe(1);
});
it('FE-AI-VACAY-004: a refused day, or one with no leave needed, starts left out', () => {
expect(startsExcluded(card({ proposal: proposal({ outcome: 'blocked', notes: ['weekendBlocked'] }) }))).toBe(true);
expect(startsExcluded(card({ proposal: proposal({ notes: ['publicHoliday'] }) }))).toBe(true);
expect(startsExcluded(card({ proposal: proposal({ notes: ['companyHoliday'] }) }))).toBe(true);
expect(startsExcluded(card({ proposal: proposal({ notes: ['weekend'] }) }))).toBe(false);
expect(startsExcluded(card({ proposal: proposal({ outcome: 'remove', notes: ['publicHoliday'] }) }))).toBe(false);
const company = proposal({ personId: null, kind: 'company', notes: ['publicHoliday'] });
expect(startsExcluded(card({ proposal: company }))).toBe(false);
expect(startsExcluded(card({ proposal: null }))).toBe(false);
});
it('FE-AI-VACAY-005: a month starts on its weekday, marks the weekend, the trip, holidays and the held day', () => {
const holidays = [{ date: '2026-10-03', name: 'Unity Day', color: null }];
const view = mergeVacayCards([card({ holidays, company: [{ date: '2026-10-30', fraction: 0.5 }] })]);
const placed = placedProposals([item('c1', 'pending', card())], new Set());
const cells = monthCells(view, { year: 2026, month: 10 }, placed, '2026-10-26');
// 1 October 2026 is a Thursday: three empty cells in a week that starts on Monday.
expect(cells.slice(0, 3)).toEqual([null, null, null]);
expect(cells.filter(Boolean)).toHaveLength(31);
const day = (date: string) => cells.find((cell) => cell?.date === date);
expect(day('2026-10-03')).toMatchObject({ weekend: true, holiday: { name: 'Unity Day' } });
expect(day('2026-10-26')).toMatchObject({ today: true, entries: [{ personId: 7 }] });
expect(day('2026-10-27')?.proposals.map((entry) => entry.toolCallId)).toEqual(['c1']);
expect(day('2026-10-28')?.trip).toBe(true);
expect(day('2026-10-30')?.company).toBe(0.5);
const sunday = monthCells({ ...view, weekStart: 0 }, { year: 2026, month: 10 }, [], '2026-10-01');
expect(sunday.slice(0, 4)).toEqual([null, null, null, null]);
});
it('FE-AI-VACAY-006: a cell wears the planner colours and the state of its held day', () => {
const view = mergeVacayCards([card({ company: [{ date: '2026-10-22', fraction: 1 }] })]);
const cellOf = (date: string, held: HeldStates, excluded = new Set<string>()) => {
const rows = held.map(([state, day], index) => item(`c${index}`, state, card({ proposal: day })));
const cells = monthCells(view, { year: 2026, month: 10 }, placedProposals(rows, excluded), '2026-10-26');
const cell = cells.find((entry) => entry?.date === date);
if (!cell) throw new Error(`no cell for ${date}`);
return cellLook(view, cell);
};
const take = cellOf('2026-10-27', [['pending', proposal()]]);
expect(take.className).toContain('outline-accent');
expect(take.style.background).toContain('#6366f1');
expect(cellOf('2026-10-27', [['pending', proposal()]], new Set(['c0'])).className).toContain('outline-edge');
const giveBack = cellOf('2026-10-26', [['pending', proposal({ date: '2026-10-26', outcome: 'remove' })]]);
expect(giveBack.className).toContain('line-through');
expect(giveBack.className).toContain('ring-content');
expect(cellOf('2026-10-27', [['applying', proposal()]]).className).toContain('animate-pulse');
expect(cellOf('2026-10-27', [['failed', proposal()]]).className).toContain('outline-danger');
expect(cellOf('2026-10-22', []).className).toContain('bg-warning-soft');
expect(cellOf('2026-10-27', [['pending', proposal({ fraction: 0.5 })]]).half).toBe(true);
expect(entriesFill(view, [])).toBeNull();
expect(
entriesFill(view, [
{ date: '2026-10-26', personId: 7, fraction: 1, kind: 'vacation' },
{ date: '2026-10-26', personId: 8, fraction: 1, kind: 'comp' },
])
).toContain('linear-gradient(90deg');
});
it('FE-AI-VACAY-007: the card opens Vacay on its leave year, and names the year only where it helps', () => {
expect(vacayYearOf(card())).toBe(2026);
expect(vacayPathOf(card({ proposal: proposal({ periodYear: 2025 }) }))).toBe('/vacay?year=2025');
expect(vacayPathOf(card({ proposal: null, balances: [], months: [] }))).toBe('/vacay');
expect(vacayPathOf(null)).toBe('/vacay');
// A read of the days off opens the leave year it asked for, not the year of its first month.
const asked = card({ proposal: null, balances: [], months: [{ year: 2027, month: 2 }], year: 2026 });
expect(vacayPathOf(asked)).toBe('/vacay?year=2026');
const applied = { toolCallId: 'c1', entity: 'vacay' as const, ids: [], dayId: null, undoUntil: null };
expect(VACAY_LOOK.entities.vacay.open(applied, card())).toEqual({ kind: 'page', path: '/vacay?year=2026' });
const line = { personId: 7, year: 2026, total: 30, carried: 0, totalAfter: null, used: 2, comp: 0, delta: 0 };
expect(namesYear([line], '2026-10-01')).toBe(false);
expect(namesYear([line, { ...line, year: 2027 }], '2026-10-01')).toBe(true);
expect(namesYear([line], '2027-01-05')).toBe(true);
});
});
@@ -0,0 +1,284 @@
import type {
VacayCard,
VacayCardBalance,
VacayCardDay,
VacayCardHoliday,
VacayCardPerson,
VacayCardProposal,
} from '@trek/shared';
import { localDateStr, monthLead } from '../../../../vacay/monthGrid';
import type { ChangeItem } from '../../assistantParts';
/**
* The pure side of the vacation cards: several cards of one answer or one
* change card read as one calendar, where each held day stands and in which
* state, the days left before and after the chosen changes, and the cells of
* a month. The views only draw what this works out.
*/
export type CardMonth = VacayCard['months'][number];
/** How large the cells are: the narrow window, the wide one, and the phone, where a cell takes a finger. */
export type CellSize = 'compact' | 'roomy' | 'phone';
/** Where a held day stands: waiting (taken in or left out), being applied, applied, failed, or off the table. */
type ProposalState = 'pending' | 'excluded' | 'applying' | 'applied' | 'failed' | 'off';
export interface PlacedProposal {
toolCallId: string;
proposal: VacayCardProposal;
state: ProposalState;
/** The same day of the same person is held twice in this card, so the two cancel out. */
twice: boolean;
}
/** Everything the cards of one block show, merged. */
export interface VacayView {
months: CardMonth[];
weekStart: 0 | 1;
weekendDays: number[];
people: VacayCardPerson[];
days: VacayCardDay[];
company: VacayCard['company'];
holidays: VacayCardHoliday[];
tripDates: ReadonlySet<string>;
balances: VacayCardBalance[];
otherDays: number;
}
/** One person's days left in one leave year, before and after the changes that count. */
export interface BalanceLine {
personId: number;
year: number;
total: number;
/** What was carried over into the year: the allowance alone is `total - carried`. */
carried: number;
/** The total a new allowance gives, while that change counts. */
totalAfter: number | null;
used: number;
comp: number;
/** What the changes that count add to the used days; negative when they give days back. */
delta: number;
}
/** The most months one strip shows. */
const MAX_MONTHS = 12;
export function monthKey(month: CardMonth): string {
return `${month.year}-${String(month.month).padStart(2, '0')}`;
}
function byKey<T>(rows: readonly T[], key: (row: T) => string): T[] {
return [...new Map(rows.map((row) => [key(row), row])).values()];
}
/** The cards of one block as one calendar: months in order, a day or a holiday once, the last card's word winning. */
export function mergeVacayCards(cards: readonly VacayCard[]): VacayView {
const first = cards[0];
const months = byKey(
cards.flatMap((card) => card.months),
monthKey
)
.sort((a, b) => monthKey(a).localeCompare(monthKey(b)))
.slice(0, MAX_MONTHS);
return {
months,
weekStart: first?.weekStart ?? 1,
weekendDays: first?.weekendDays ?? [0, 6],
people: byKey(
cards.flatMap((card) => card.people),
(person) => String(person.id)
),
days: byKey(
cards.flatMap((card) => card.days),
(day) => `${day.date}:${day.personId}`
),
company: byKey(
cards.flatMap((card) => card.company),
(row) => row.date
),
holidays: byKey(
cards.flatMap((card) => card.holidays),
(holiday) => `${holiday.date}:${holiday.name}`
),
tripDates: new Set(cards.flatMap((card) => card.tripDates)),
balances: byKey(
cards.flatMap((card) => card.balances),
(balance) => `${balance.personId}:${balance.year}`
),
otherDays: Math.max(0, ...cards.map((card) => card.otherDays)),
};
}
/** Where a change stands, with the user's choice of the waiting ones. */
function proposalState(item: ChangeItem, excluded: ReadonlySet<string>): ProposalState {
if (item.state === 'pending') return excluded.has(item.toolCallId) ? 'excluded' : 'pending';
if (item.state === 'applying' || item.state === 'applied' || item.state === 'failed') return item.state;
return 'off';
}
/** Whether a change in this state counts for the days left: chosen, on its way, or done. */
function counts(state: ProposalState): boolean {
return state === 'pending' || state === 'applying' || state === 'applied';
}
/** The vacation cards among the change rows. */
export function vacayCardsOf(items: readonly ChangeItem[]): Array<{ item: ChangeItem; card: VacayCard }> {
return items.flatMap((item) => (item.card?.kind === 'vacay' ? [{ item, card: item.card }] : []));
}
/** The day a held change is about: one person's day, or the plan's company holiday that day. */
function dayKeyOf(entry: PlacedProposal): string {
return `${entry.proposal.date}:${entry.proposal.personId ?? 'company'}`;
}
/** What a held change makes of its day: its kind and size. */
function sizeKeyOf(entry: PlacedProposal): string {
return `${entry.proposal.kind}:${entry.proposal.fraction}`;
}
/** The held days of the rows, each with its state, and which of them name the same day twice. */
export function placedProposals(items: readonly ChangeItem[], excluded: ReadonlySet<string>): PlacedProposal[] {
const placed = vacayCardsOf(items).flatMap(({ item, card }) =>
card.proposal
? [{ toolCallId: item.toolCallId, proposal: card.proposal, state: proposalState(item, excluded), twice: false }]
: []
);
const seen = new Map<string, number>();
for (const entry of placed) {
if (entry.state !== 'off') seen.set(dayKeyOf(entry), (seen.get(dayKeyOf(entry)) ?? 0) + 1);
}
return placed.map((entry) => ({ ...entry, twice: entry.state !== 'off' && (seen.get(dayKeyOf(entry)) ?? 0) > 1 }));
}
/**
* The changes to the used days of the held days that count. Each day counts
* once: the toggles were all foreseen from the same calendar, so the same day
* held twice the same way takes it and clears it again (the pair cancels),
* and otherwise the first of them says what happens to the day.
*/
function countedDeltas(placed: readonly PlacedProposal[]): VacayCardProposal['deltas'] {
const days = new Map<string, PlacedProposal[]>();
for (const entry of placed.filter((candidate) => counts(candidate.state))) {
days.set(dayKeyOf(entry), [...(days.get(dayKeyOf(entry)) ?? []), entry]);
}
return [...days.values()].flatMap((held) => {
const [first] = held;
if (!first) return [];
const same = held.every((entry) => sizeKeyOf(entry) === sizeKeyOf(first));
return same && held.length % 2 === 0 ? [] : first.proposal.deltas;
});
}
/**
* The days left per person and year: the balances the cards carry, the held
* days that count added to the used days, and a new allowance that counts as
* the total it gives.
*/
export function balanceLines(
view: VacayView,
placed: readonly PlacedProposal[],
allowances: ReadonlyMap<string, number> = new Map()
): BalanceLine[] {
const deltas = countedDeltas(placed);
return view.balances.map((balance) => {
const key = `${balance.personId}:${balance.year}`;
const delta = deltas
.filter((change) => `${change.personId}:${change.year}` === key)
.reduce((sum, change) => sum + change.days, 0);
return {
personId: balance.personId,
year: balance.year,
total: balance.total,
carried: balance.carried ?? 0,
totalAfter: allowances.get(key) ?? null,
used: balance.used,
comp: balance.comp,
delta,
};
});
}
/** The totals the new allowances of the rows give, by person and year, while each counts. */
export function allowancesOf(items: readonly ChangeItem[], excluded: ReadonlySet<string>): Map<string, number> {
const found = new Map<string, number>();
for (const { item, card } of vacayCardsOf(items)) {
if (card.proposal || !counts(proposalState(item, excluded))) continue;
for (const balance of card.balances) {
if (balance.totalAfter !== null) found.set(`${balance.personId}:${balance.year}`, balance.totalAfter);
}
}
return found;
}
/** What a line comes to: the days left before and after, and how far past the allowance it would go. */
export function lineFigures(line: BalanceLine): { left: number; leftAfter: number; over: number } {
const total = line.totalAfter ?? line.total;
const leftAfter = total - (line.used + line.delta);
return { left: line.total - line.used, leftAfter, over: Math.max(0, -leftAfter) };
}
/** Whether the lines need their year named: two years in one card, or a year that is not this one. */
export function namesYear(lines: readonly BalanceLine[], today: string): boolean {
const years = new Set(lines.map((line) => line.year));
return years.size > 1 || [...years].some((year) => String(year) !== today.slice(0, 4));
}
/**
* A held day that starts left out: one the planner would refuse, or leave
* where no leave is needed (a whole company holiday, a public holiday). The
* user takes it in with one tap.
*/
export function startsExcluded(card: VacayCard): boolean {
const proposal = card.proposal;
if (!proposal) return false;
if (proposal.outcome === 'blocked') return true;
const free = proposal.notes.includes('companyHoliday') || proposal.notes.includes('publicHoliday');
return proposal.outcome === 'add' && proposal.personId !== null && free;
}
export interface DayCell {
date: string;
day: number;
weekend: boolean;
today: boolean;
entries: VacayCardDay[];
/** A company holiday that day: 1 whole, 0.5 half. */
company: number | null;
holiday: VacayCardHoliday | null;
trip: boolean;
proposals: PlacedProposal[];
}
/** The cells of a month, empty ones first for the days before the 1st. */
export function monthCells(
view: VacayView,
month: CardMonth,
placed: readonly PlacedProposal[],
today: string
): Array<DayCell | null> {
const lead = monthLead(month.year, month.month - 1, view.weekStart);
const length = new Date(month.year, month.month, 0).getDate();
const cells: Array<DayCell | null> = Array.from({ length: lead }, () => null);
for (let day = 1; day <= length; day++) {
const date = localDateStr(month.year, month.month - 1, day);
cells.push({
date,
day,
weekend: view.weekendDays.includes(new Date(month.year, month.month - 1, day).getDay()),
today: date === today,
entries: view.days.filter((entry) => entry.date === date),
company: view.company.find((row) => row.date === date)?.fraction ?? null,
holiday: view.holidays.find((holiday) => holiday.date === date) ?? null,
trip: view.tripDates.has(date),
proposals: placed.filter((entry) => entry.proposal.date === date),
});
}
return cells;
}
/** Today in the user's time zone, as the planner writes a date. */
export function todayStr(now = new Date()): string {
return localDateStr(now.getFullYear(), now.getMonth(), now.getDate());
}
@@ -0,0 +1,115 @@
import type { VacayCardDay } from '@trek/shared';
import type { CSSProperties } from 'react';
import { safeHexColor } from '../../../../utils/safeColor';
import type { DayCell, PlacedProposal, VacayView } from './vacayCardModel';
/**
* How a day of the vacation card looks, worked out apart from the markup:
* the planner's own colours (a person's days in their colour, a comp day
* hatched, a company holiday amber, a public holiday in its calendar's
* colour, the trip's days dotted), and a held day on top of it, dashed while
* it waits, solid once applied, struck through when it gives a day back.
*/
/** The colour a person's days wear, or the company's for a company holiday; the accent when they have none. */
export function personColor(view: VacayView, personId: number | null): string {
if (personId === null) return 'var(--warning)';
return safeHexColor(view.people.find((person) => person.id === personId)?.color, 'var(--accent)');
}
function tint(color: string, percent: number): string {
return `color-mix(in srgb, ${color} ${percent}%, transparent)`;
}
function hatch(color: string): string {
return `repeating-linear-gradient(45deg, ${tint(color, 45)} 0 2.5px, transparent 2.5px 5px)`;
}
/** The logged days of a cell: one person fills it, several share it side by side. */
export function entriesFill(view: VacayView, entries: readonly VacayCardDay[]): string | null {
const shown = entries.slice(0, 3);
const [only] = shown;
if (!only) return null;
if (shown.length === 1) {
const color = personColor(view, only.personId);
return only.kind === 'comp' ? hatch(color) : tint(color, 26);
}
const step = 100 / shown.length;
const stops = shown.map((entry, index) => {
const color = tint(personColor(view, entry.personId), entry.kind === 'comp' ? 18 : 30);
return `${color} ${Math.round(index * step)}% ${Math.round((index + 1) * step)}%`;
});
return `linear-gradient(90deg, ${stops.join(', ')})`;
}
const BASE = 'relative grid place-items-center rounded-md text-caption tabular-nums leading-none transition-colors';
const DASHED = 'outline-dashed outline-1 outline-offset-[-1px]';
/** What a held day adds to its cell, by its state and what it does: one text colour, its weight and its outline. */
type ProposalLook = 'take' | 'giveBack' | 'givenBack' | 'excluded' | 'blocked' | 'applied' | 'failed';
const PROPOSAL_CLASS: Record<ProposalLook, string> = {
take: `font-semibold text-content ${DASHED} outline-accent`,
giveBack: `text-content-faint line-through ${DASHED} outline-danger`,
givenBack: 'text-content-faint line-through',
excluded: `text-content-faint ${DASHED} outline-edge`,
blocked: `text-content-faint ${DASHED} outline-warning`,
applied: 'font-semibold text-content',
failed: 'text-content outline outline-1 outline-offset-[-1px] outline-danger',
};
interface CellLook {
className: string;
style: CSSProperties;
/** The held day the cell shows, when one is on the table. */
proposal: PlacedProposal | null;
/** Someone is off for half of the day. */
half: boolean;
}
function proposalClass(entry: PlacedProposal): string {
if (entry.state === 'excluded') return PROPOSAL_CLASS.excluded;
if (entry.state === 'failed') return PROPOSAL_CLASS.failed;
if (entry.proposal.outcome === 'blocked') return PROPOSAL_CLASS.blocked;
const applied = entry.state === 'applied';
if (entry.proposal.outcome === 'remove') return applied ? PROPOSAL_CLASS.givenBack : PROPOSAL_CLASS.giveBack;
return applied ? PROPOSAL_CLASS.applied : PROPOSAL_CLASS.take;
}
/** The text of a cell without a held day: a logged day reads strong, a whole company holiday amber, a weekend faint. */
function plainClass(cell: DayCell): string {
if (cell.entries.length > 0) return 'text-content';
if (cell.company === 1) return 'bg-warning-soft text-warning';
return cell.weekend ? 'text-content-faint' : 'text-content-secondary';
}
/** The background of a cell: the held day's colour where it takes a day, else what is logged or given. */
function backgroundOf(view: VacayView, cell: DayCell, entry: PlacedProposal | null): string | undefined {
const takes = entry?.proposal.outcome === 'add' || entry?.proposal.outcome === 'convert';
if (entry && takes && entry.state !== 'excluded' && entry.state !== 'failed') {
return `color-mix(in srgb, ${personColor(view, entry.proposal.personId)} 55%, var(--bg-card))`;
}
const logged = entriesFill(view, cell.entries);
if (logged) return logged;
if (cell.company === 0.5) return 'linear-gradient(135deg, var(--warning-soft) 50%, transparent 50%)';
if (cell.holiday && cell.company === null) return tint(safeHexColor(cell.holiday.color, 'var(--danger)'), 28);
return undefined;
}
/** The whole look of one cell. */
export function cellLook(view: VacayView, cell: DayCell): CellLook {
const entry = cell.proposals.find((placed) => placed.state !== 'off') ?? null;
const classes = [BASE, entry ? proposalClass(entry) : plainClass(cell)];
if (entry && cell.company === 1 && cell.entries.length === 0) classes.push('bg-warning-soft');
if (cell.today) classes.push('ring-1 ring-inset ring-content');
if (cell.today && !entry) classes.push('font-semibold');
if (entry?.state === 'applying') classes.push('motion-safe:animate-pulse');
const background = backgroundOf(view, cell, entry);
return {
className: classes.join(' '),
style: background ? { background } : {},
proposal: entry,
half: cell.entries.some((day) => day.fraction === 0.5) || entry?.proposal.fraction === 0.5,
};
}
@@ -1,18 +1,69 @@
import type { TrekCard } from '@trek/shared';
import { Building2, CalendarCog, CalendarDays, CalendarMinus, CalendarPlus } from 'lucide-react';
import type { PackLook } from '../cardTypes';
/**
* What the vacation planner brings to the chat's pure look: the verbs, tool
* names and steps it adds, what an applied change of its own opens, and the
* look of each of its kinds. Empty until the vacation cards fill it. A look
* stays pure, icons and literals only: the chat's main chunk reads every look,
* so whatever a look imports ships with it.
* look of each of its kinds. A look stays pure, icons and literals only: the
* chat's main chunk reads every look, so whatever a look imports ships with
* it.
*/
/**
* The leave year a vacation card is about: the held day's, else the year a
* read asked for (a leave year from April shows a February trip of the next
* calendar year), else the first of the days left, else its first month's.
*/
export function vacayYearOf(card: TrekCard | null): number | null {
if (card?.kind !== 'vacay') return null;
return card.proposal?.periodYear ?? card.year ?? card.balances[0]?.year ?? card.months[0]?.year ?? null;
}
/** Vacay on the year of the card, or on the period it would open anyway. */
export function vacayPathOf(card: TrekCard | null): string {
const year = vacayYearOf(card);
return year === null ? '/vacay' : `/vacay?year=${year}`;
}
export const VACAY_LOOK = {
verbs: {},
tools: {},
steps: {},
entities: {},
verbs: {
addVacationDay: { Icon: CalendarPlus, tone: 'success', labelKey: 'assistant.change.verb.addVacationDay' },
removeVacationDay: { Icon: CalendarMinus, tone: 'danger', labelKey: 'assistant.change.verb.removeVacationDay' },
changeVacationDay: { Icon: CalendarCog, tone: 'info', labelKey: 'assistant.change.verb.changeVacationDay' },
setCompanyHoliday: { Icon: Building2, tone: 'warning', labelKey: 'assistant.change.verb.setCompanyHoliday' },
setVacationAllowance: {
Icon: CalendarDays,
tone: 'info',
labelKey: 'assistant.change.verb.setVacationAllowance',
},
},
tools: {
add_vacay_year: { labelKey: 'assistant.tool.add_vacay_year' },
delete_vacay_year: { labelKey: 'assistant.tool.delete_vacay_year' },
update_vacay_plan: { labelKey: 'assistant.tool.update_vacay_plan' },
set_vacay_color: { labelKey: 'assistant.tool.set_vacay_color' },
add_holiday_calendar: { labelKey: 'assistant.tool.add_holiday_calendar' },
delete_holiday_calendar: { labelKey: 'assistant.tool.delete_holiday_calendar' },
},
steps: {
get_vacay_entries: { stepKey: 'assistant.step.vacayEntries' },
get_vacay_stats: { stepKey: 'assistant.step.vacayStats' },
list_holidays: { stepKey: 'assistant.step.vacayHolidays' },
},
entities: {
vacay: {
Icon: CalendarDays,
openLabelKey: 'assistant.card.vacay.open',
open: (_applied, card) => ({ kind: 'page', path: vacayPathOf(card) }),
},
},
cards: {
vacay: {},
vacay: {
entity: () => 'vacay',
// The change card's calendar shows the logged days already, so a read of them next to it gives way.
yieldsToChange: (_answer, change) => change.kind === 'vacay',
},
},
} satisfies PackLook<'vacay'>;
@@ -1,12 +1,19 @@
import { type CardView, PENDING_VIEW } from '../cardTypes';
import type { CardView } from '../cardTypes';
import VacayAnswerBlock from './VacayAnswerBlock';
import { startsExcluded } from './vacayCardModel';
import VacayChangeGroup from './VacayChangeGroup';
import VacayRowFacts from './VacayRowFacts';
/**
* How the kinds of the vacation planner draw in the chat; each one draws
* nothing until its cards are built. This file only maps each kind to its view:
* the components live in sibling files, since a file that exports anything
* besides components breaks fast refresh, and lint:warnings holds
* react-refresh/only-export-components at zero for a new file.
* How the vacation planner's card draws in the chat: an answer as a month
* calendar with the days left, a change card's vacation rows under one such
* calendar, each row's facts on its faint line, and the held days the planner
* would refuse or that need no leave left out at first. This file only maps
* the kind to its view: the components live in sibling files, since a file
* that exports anything besides components breaks fast refresh, and
* lint:warnings holds react-refresh/only-export-components at zero for a new
* file.
*/
export const VACAY_VIEWS = {
vacay: PENDING_VIEW,
vacay: { Block: VacayAnswerBlock, Group: VacayChangeGroup, Facts: VacayRowFacts, startsExcluded },
} satisfies { [K in 'vacay']: CardView<K> };