Update calendar with multi-select

This commit is contained in:
2026-06-14 22:20:32 +02:00
parent 88afa17666
commit dead5e4897
14 changed files with 955 additions and 96 deletions
+216
View File
@@ -0,0 +1,216 @@
# Handover — Calendar multi-select, spanning bars & week numbers
**Audience:** junior frontend developer picking up this feature.
**Area:** `frontend/` only (TypeScript + React + Vite). No backend changes are required.
**Status:** spec / not started. No production code has been written yet — this document is the brief.
Read `AGENTS.md` at the repo root first. The guardrails there (no `any`, no `.js`/`.jsx`, components don't call `fetch` directly, ESLint must pass with **zero** warnings, frontend coverage gate is **90%**) all apply to this work.
---
## 1. What we're building
Five related improvements to the planning calendar (`/calendar`):
1. **Drag to select multiple days**, then apply a leave type to all of them at once.
2. **Remember the last-used leave type** so entering several days in a row is faster (session-only cache is fine).
3. **"Dubbeldag" rules + clearer display:** a double day is only valid when the leave type is *not* vacation, and the fact that a day is a dubbeldag must be visible in the calendar (today it's invisible).
4. **Replace the colored dots with labeled bars** that can span multiple days and say *what* the leave is and *which parent* is taking it (Google/Apple-Calendar style — see the screenshot the product owner attached).
5. **Settings toggle "Visa veckonummer"** to show ISO week numbers in the calendar (Swedes plan in week numbers).
Plus a small CSS polish pass on the **Legend** (it currently renders with overlapping text — see screenshot).
---
## 2. Decisions already made (do not re-litigate)
These were confirmed with the product owner — build to them:
| Question | Decision |
|---|---|
| Bar rendering style | **True spanning bars** (continuous bar across the days, label shown once) — not a repeated chip per cell. |
| Applying a type to a dragged range that contains existing entries | **Overwrite** every day in the range for the current parent. |
| Whose name shows on a bar | **The logged-in parent's name only.** The app currently only knows the current parent (`parentName` / `personalDataUuid` from `WorkspaceContext`). Showing/where-to-switch the *other* parent is an explicit **future** follow-up — don't block on it. A generic `"Partner"` fallback for any other UUID is acceptable. |
| Where the week-number toggle lives | **Settings page**, persisted client-side (localStorage). It's a pure display preference; no backend/migration needed. |
> ⚠️ The attached screenshot is an **Apple Calendar** screenshot used only as a *visual reference for the bar style* (continuous, labeled, rounded bars, one per row). The labels in it ("Gotland", "Pappa reser", etc.) are that person's private events — do **not** try to reproduce those texts. Our bar labels come from the leave type + parent (see §5.D).
---
## 3. Orientation — the code as it is today
All paths relative to `frontend/`.
**Page**
- `src/pages/Calendar.tsx` — builds the month grid as a flat list of `weeks: string[][]` (each entry an ISO date string) and renders one `<CalendarDay>` per date in a single CSS grid (`.calendar__grid`, 7 columns). It owns `selectedDate` + modal state and the single-day save/update/delete handlers. Note the local `getColorForType()` at the bottom — you'll want to share this (see §5).
- `src/pages/calendar.css` — all calendar styling, including the dots (`.calendar-day__event`, 8×8 circles) and the `.calendar__legend*` rules that need the CSS polish.
**Components**
- `src/components/common/CalendarDay.tsx` — one day cell. Props: `date`, `events`, `isCurrentMonth`, `onClick`, `isToday`. Renders the day number and, if `events` are passed, the colored dots. Handles click + Enter/Space → `onClick`. Has tests in `CalendarDay.test.tsx`.
- `src/components/common/CalendarEvent.tsx` — the small colored chip currently used **only in the legend**. Props: `leaveType`, `color`, `title`, `onDismiss`. Has tests in `CalendarEvent.test.tsx`.
- `src/components/modals/PlannedDayModal.tsx` — the create/edit/delete modal for a single day. Already has a `dayType` select (vacation / sjukpenning / lagsta), an optional parent select (only shown when `parents.length > 1`), and an `isDubbeldag` checkbox. `onSave` payload is `{ dayType, parentId, isDubbeldag }`.
**Data layer (don't bypass it)**
- `src/hooks/usePlannedDays.ts` — `{ data, isLoading, error, refresh, add, update, remove }`. `add`/`update`/`remove` already call the API and then `refresh()`.
- `src/services/api.ts` — `getPlannedDays`, `createPlannedDay`, `updatePlannedDay`, `deletePlannedDay`. **Payloads are snake_case** (`CreatePlannedDayPayload`: `workspace_id`, `child_id`, `parent_personal_data_uuid`, `date`, `day_type`, `is_dubbeldag`; `UpdatePlannedDayPayload`: `day_type?`, `is_dubbeldag?`). Responses are mapped to camelCase `PlannedLeaveDay` by `toPlannedLeaveDay`.
- `src/types/entities.ts` → `PlannedLeaveDay`: `{ id, workspaceId, childId, parentPersonalDataUuid, date, dayType, isDubbeldag, createdAt, updatedAt }`. `dayType` is `'sjukpenning' | 'lagsta' | 'vacation'`.
**Context**
- `src/context/WorkspaceContext.tsx` (`useWorkspace`) exposes `personalDataUuid` and `parentName` for the *current* parent only. There is **no** partner name available yet.
**Settings**
- `src/pages/Settings.tsx` — sectioned page. Most settings save to the backend via `api.*`. The week-number toggle is the exception: keep it **client-side** (localStorage).
- `src/hooks/index.ts` — barrel; export any new hook here so imports stay `@/hooks`.
- `src/utils/dates.ts` — date helpers (`formatDateForInput`, `parseInputDate`, `isValidDate`, etc.). Add the ISO-week + range helpers here.
---
## 4. Suggested file plan
| File | Action | Why |
|---|---|---|
| `src/utils/leaveTypes.ts` | **new** | Single source of truth for `getColorForType` + a label per type. Removes the duplicated color map from `Calendar.tsx`. |
| `src/utils/dates.ts` | edit | Add `getISOWeekNumber()` and `datesInRange(a, b)`. |
| `src/hooks/useCalendarPreferences.ts` | **new** | `useShowWeekNumbers()` (localStorage, reactive) + `getLastLeaveType()/setLastLeaveType()` (sessionStorage). Export via `hooks/index.ts`. |
| `src/components/common/CalendarWeek.tsx` | **new** | Renders one week row: optional week-number gutter, 7 `CalendarDay` cells, and the spanning bar overlay (run-merge + lane layout). |
| `src/components/common/CalendarDay.tsx` | edit | Add selection (`isSelected`) and pointer handlers for drag; keep `onClick` working for back-compat/keyboard. Stop relying on dots in the new layout (pass no `events`). |
| `src/components/common/CalendarEvent.tsx` | edit | Add an optional dubbeldag badge + parent label; keep existing props/tests passing. |
| `src/components/modals/PlannedDayModal.tsx` | edit | Dubbeldag rule vs vacation; optional range mode (label + count, no delete) and a `defaultDayType` seed. |
| `src/pages/Calendar.tsx` | edit | Drag state + handlers, render via `CalendarWeek`, bulk apply, last-type cache, read week-number pref. |
| `src/pages/calendar.css` | edit | Bars, dubbeldag styling, selection highlight, week-number gutter, legend polish. |
| `src/pages/Settings.tsx` | edit | New "Kalender" section with the "Visa veckonummer" checkbox. |
| Tests | new/edit | See §6. |
Don't forget: after code changes run `graphify update .` (AGENTS.md).
---
## 5. Feature-by-feature guidance
### A. Drag to select multiple days + bulk apply
Drive selection from **pointer events** on the day cells, not `onClick`, so a drag and a click don't both fire.
State to add in `Calendar.tsx`:
- `dragAnchor: string | null`, `dragCurrent: string | null`, `isDragging: boolean`.
Handlers passed down to each `CalendarDay`:
- `onPointerDownDay(date)` → set `dragAnchor = dragCurrent = date`, `isDragging = true`.
- `onPointerEnterDay(date)` → if `isDragging`, set `dragCurrent = date`.
- A `pointerup` listener on `window` (in a `useEffect`) finalizes the selection.
On pointer-up, compute the selected dates with `datesInRange(dragAnchor, dragCurrent)` (inclusive, ascending, order-independent), then:
- **1 day** → open the existing single-day flow (`PlannedDayModal` with edit/delete).
- **>1 day** → open the modal in **range mode** (§5.C/§D below): no `existingDay`, no delete, header like "Plan N days".
Keep the selected dates highlighted (`isSelected`) until the modal closes.
Bulk save = loop over the selected dates and call `add`/`update` per day. **Overwrite semantics** (decision in §2): for each date, if the current parent already has an entry, `update` it; otherwise `add`. There is **no** bulk endpoint — a client-side loop is fine for now (note the N-requests trade-off in your PR; a `/planned-days/bulk` endpoint is a reasonable future optimization but out of scope). After the loop, `usePlannedDays` already refreshes on each call; consider whether to refresh once at the end instead to avoid flless re-fetches (acceptable either way for MVP).
Accessibility: keyboard users can't drag. Keep single-day open via keyboard (Enter/Space on a focused cell). Add an `onActivate` prop used by the key handler if you stop passing `onClick` in the new layout, so `CalendarDay`'s existing tests keep passing.
### B. Remember the last-used leave type
In `useCalendarPreferences.ts`, back this with **sessionStorage** (per the product ask, session-only is fine):
- `getLastLeaveType(): 'sjukpenning' | 'lagsta' | 'vacation' | null` (validate the stored value).
- `setLastLeaveType(type)`.
Wire-up: when the modal opens for a **new** day (no `existingDay`), seed its `dayType` from `getLastLeaveType()` (fall back to `'vacation'`). On a successful save, call `setLastLeaveType(savedType)`. Don't override the type when *editing* an existing day — that should reflect the stored entry.
### C. Dubbeldag only valid when type ≠ vacation
In `PlannedDayModal.tsx`:
- When `dayType === 'vacation'`, force `isDubbeldag = false`, **disable** the checkbox, and show a short hint (e.g. "Dubbeldagar gäller inte för semester"). Use a `useEffect` on `dayType` so switching *to* vacation clears a previously-checked box.
- Domain note from `AGENTS.md`: a dubbeldag consumes *each* parent's balance and only applies early in the child's life — we are **not** enforcing the early-life window here, just the "not with vacation" rule. Keep it to that.
### D. Spanning, labeled bars (the big one)
Replace the dots. Render bars **per week row**, so introduce `CalendarWeek`.
**Why per-week:** a bar can only span contiguous columns *within* a single week row; a stretch that crosses a week boundary becomes two bars (one ending Sunday, one starting Monday) — same as Google/Apple Calendar.
**Building the bars for one week (7 ISO dates):**
1. For each day, get its planned entries (filter `plannedDays` by `date`).
2. Group entries into "series" by a stable key: `` `${parentPersonalDataUuid}|${dayType}|${isDubbeldag}` ``.
3. For each series, scan the 7 days left→right and merge **consecutive** days that contain that series into a bar `{ startCol, endCol, parentUuid, dayType, isDubbeldag }`.
4. **Lane assignment (so overlapping bars stack instead of colliding):** sort bars by `startCol` asc then width desc; greedily place each bar in the first lane (row) whose columns `[startCol..endCol]` are free.
**Rendering:** give `CalendarWeek` a `position: relative` container with two layers sharing the same 7-column track and **`column-gap: 0`** (so bars are visually continuous across day boundaries — use cell borders, not grid gaps, for separation):
- the day layer (7 `CalendarDay` cells), and
- an absolutely-positioned bar overlay (`pointer-events: none` so clicks fall through to the day cell beneath, which opens the edit modal). Position each bar with `grid-column: ${startCol + 1} / ${endCol + 2}` and `grid-row: ${lane + 1}`.
Make the week's min-height grow with the lane count (e.g. `numberHeight + lanes * barHeight + padding`) so tall weeks don't clip. Many-lane weeks are an edge case — clipping with a small "+N more" affordance is an acceptable v1 if you run low on time; note it if so.
**Bar contents:** `"{parentLabel} · {typeLabel}"`, where `typeLabel` comes from `leaveTypes.ts` and `parentLabel` is `parentName` (or "Du") for `personalDataUuid`, else `"Partner"`. If `isDubbeldag`, render a small **"2×"** badge on the bar (this is the "show dubbeldag better" requirement). You can reuse `CalendarEvent` as the bar's inner visual by adding optional `isDubbeldag` + `parentLabel` props.
### E. Legend CSS polish
The screenshot shows the legend swatches overlapping their labels ("VacaSiok Parental"). In `calendar.css`, the `.calendar__legend-item` currently relies on a `CalendarEvent` shrunk with `!important`. Rebuild each legend item as a clean **swatch + label** row (small square/rounded swatch, gap, readable label), aligned in a wrapping flex row, with a real section heading. Keep the three types: Vacation / Sick / Parental, using the shared colors. Add a swatch variant indicating a dubbeldag (the "2×" badge) so the legend explains it.
### F. "Visa veckonummer" setting + week-number gutter
- `useShowWeekNumbers()` in `useCalendarPreferences.ts`: localStorage-backed boolean, **reactive within the tab** (dispatch a custom event on set and listen for it + the native `storage` event), so toggling in Settings updates an open Calendar.
- Settings: add a "Kalender" section with a checkbox bound to the hook. Swedish label **"Visa veckonummer"**.
- Calendar: when enabled, render a left **gutter** in each `CalendarWeek` showing `getISOWeekNumber(firstDateOfWeek)` (e.g. "v.27"). Add a matching empty/heading cell above the weekday header row so columns stay aligned.
- `getISOWeekNumber`: ISO-8601, Monday-first, week 1 = the week containing the year's first Thursday. (Pseudocode: shift the date to its Thursday, then count weeks from the first Thursday of that year. Test the known tricky boundaries — e.g. 2026-01-01 is week 1, 2025-12-29 is week 1 of 2026.)
---
## 6. Tests & CI gates (must pass before PR)
From `frontend/`:
```bash
npx tsc --noEmit # no type errors (no `any`, no ts-ignore)
npm run lint # ESLint, zero warnings
npm run coverage # Vitest, 90% coverage gate
```
Test additions/updates to plan for:
- **`utils/dates`** — `getISOWeekNumber` (incl. year boundaries) and `datesInRange` (forward, reversed, single day, invalid input).
- **`utils/leaveTypes`** — color + label lookups, unknown fallback.
- **`useCalendarPreferences`** — persists + reads week-number flag; reactive update; last-leave-type get/set + invalid value rejection. (jsdom provides `localStorage`/`sessionStorage`.)
- **`CalendarWeek`** — run-merging (consecutive same-series days become one bar; a gap splits them), lane stacking for overlapping parents, week-number gutter shown/hidden, dubbeldag badge present.
- **`CalendarDay`** — selection class + pointer handlers; keep the existing dot/`onClick`/keyboard tests green.
- **`CalendarEvent`** — new dubbeldag badge / parent label; keep existing tests green.
- **`PlannedDayModal`** — dubbeldag disabled + forced false on vacation; range-mode header/no-delete; default type seeding.
- **`Calendar`** — drag across cells builds a range and opens range mode; single click/Enter opens single-day; bulk apply calls `add`/`update` per day with overwrite.
Existing tests you must not break: `Calendar.test.tsx`, `CalendarDay.test.tsx`, `CalendarEvent.test.tsx`. If you change a component's contract, update its test *properly* (never delete a failing test to go green — see AGENTS.md).
---
## 7. Edge cases & gotchas
- **Click vs drag double-fire:** the #1 trap. Don't keep both `onClick` and pointer-based selection firing the open. Decide which path opens the modal and stub the other.
- **Range crossing week boundary:** must split into two bars (handled naturally by per-week rendering).
- **Same day, both parents:** two series on one day → two stacked lanes. Make lane assignment deterministic (stable key sort) so bars don't jump around between renders.
- **Days outside the current month** (`isCurrentMonth === false`): keep them non-interactive for selection, as today.
- **Overwrite in range** can fire many requests; if the UX feels janky, batch the `refresh()` to the end of the loop.
- **Continuous bars need `column-gap: 0`** on the grid; reintroduce visual separation with cell borders so the bars don't get chopped by the gap.
- **Week-number reactivity:** the native `storage` event only fires in *other* tabs — use a custom in-tab event so Settings ↔ Calendar sync live.
- **Don't bypass layers:** go through `usePlannedDays` / `api.ts`; remember API payloads are **snake_case**.
---
## 8. Known limitations / future follow-ups (call out in your PR)
- **Partner identity:** bars label non-current parents as "Partner" because the app only knows the current parent. A future ticket should expose partner name(s) and let the user pick *which* parent a day/range is for in the modal.
- **No bulk API:** range apply loops client-side. A `/planned-days/bulk` endpoint would cut N requests to 1.
- **Many overlapping lanes** may need a "+N more" overflow design if real usage stacks lots of same-day entries.
- **Dubbeldag window not enforced** (only the "not with vacation" rule) — encoding the early-life day limit is a separate domain task; per AGENTS.md, confirm the exact rule/number before hardcoding it.
---
## 9. Definition of done
- [ ] Drag across days selects a range; releasing opens a bulk-apply modal; applying overwrites every day in the range for the current parent.
- [ ] Single click / Enter still opens the single-day edit/delete modal.
- [ ] New-day modal pre-selects the last-used leave type (session); editing shows the stored type.
- [ ] Dubbeldag checkbox is disabled + cleared when type is vacation; dubbeldag is clearly shown on the calendar (2× badge) and explained in the legend.
- [ ] Dots replaced by continuous, labeled bars showing leave type + parent, spanning consecutive days and splitting at week boundaries.
- [ ] Legend is clean and readable (no overlapping text).
- [ ] Settings has a "Visa veckonummer" toggle; when on, the calendar shows ISO week numbers, and toggling updates an open calendar live.
- [ ] `tsc --noEmit`, `npm run lint` (zero warnings), and `npm run coverage` (≥90%) all pass; existing calendar tests still green.
- [ ] `graphify update .` run after changes.
```
+20
View File
@@ -0,0 +1,20 @@
"use strict";
(() => {
// src/utils/leaveTypes.ts
function getColorForType(type) {
const colorMap = {
vacation: "#4CAF50",
sjukpenning: "#FF9800",
lagsta: "#2196F3"
};
return colorMap[type] ?? "#9E9E9E";
}
function getLabelForType(type) {
const labelMap = {
vacation: "Vacation",
sjukpenning: "Sick Leave",
lagsta: "Parental"
};
return labelMap[type] ?? "Unknown";
}
})();
+22 -6
View File
@@ -6,6 +6,10 @@ export interface CalendarDayProps {
isCurrentMonth?: boolean | undefined
onClick?: (() => void) | undefined
isToday?: boolean | undefined
isSelected?: boolean | undefined
onPointerDown?: ((date: string) => void) | undefined
onPointerEnter?: ((date: string) => void) | undefined
onActivate?: (() => void) | undefined
}
export function CalendarDay({
@@ -14,9 +18,23 @@ export function CalendarDay({
isCurrentMonth = true,
onClick,
isToday = false,
isSelected = false,
onPointerDown,
onPointerEnter,
onActivate,
}: CalendarDayProps): ReactNode {
const dayNum = new Date(date + 'T00:00:00Z').getUTCDate()
const handleKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {
if (e.key === 'Enter' || e.key === ' ') {
if (onActivate) {
onActivate()
} else {
onClick?.()
}
}
}
return (
<div
data-testid="calendar-day"
@@ -24,12 +42,10 @@ export function CalendarDay({
role="button"
tabIndex={0}
aria-label={`${date}${events.length > 0 ? ` with ${events.length} event(s)` : ''}`}
className={`calendar-day ${!isCurrentMonth ? 'calendar-day--disabled' : ''} ${events.length > 0 ? 'calendar-day--has-events' : ''} ${isToday ? 'calendar-day--today' : ''}`}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
onClick?.()
}
}}
className={`calendar-day ${!isCurrentMonth ? 'calendar-day--disabled' : ''} ${events.length > 0 ? 'calendar-day--has-events' : ''} ${isToday ? 'calendar-day--today' : ''} ${isSelected ? 'calendar-day--selected' : ''}`}
onKeyDown={handleKeyDown}
onPointerDown={() => onPointerDown?.(date)}
onPointerEnter={() => onPointerEnter?.(date)}
>
<div className="calendar-day__number">{dayNum}</div>
{events.length > 0 && (
@@ -5,6 +5,8 @@ export interface CalendarEventProps {
color: string
title?: string
onDismiss?: () => void
isDubbeldag?: boolean | undefined
parentLabel?: string | undefined
}
export function CalendarEvent({
@@ -12,7 +14,11 @@ export function CalendarEvent({
color,
title,
onDismiss,
isDubbeldag = false,
parentLabel,
}: CalendarEventProps): ReactNode {
const displayLabel = parentLabel ? `${parentLabel} · ${leaveType}` : leaveType
return (
<div
data-testid="calendar-event"
@@ -20,8 +26,9 @@ export function CalendarEvent({
style={{ backgroundColor: color }}
>
<span className="calendar-event__label" title={title ?? leaveType}>
{leaveType}
{displayLabel}
</span>
{isDubbeldag && <span className="calendar-event__badge">2×</span>}
{onDismiss && (
<button
className="calendar-event__dismiss"
@@ -0,0 +1,277 @@
import { ReactNode, useMemo } from 'react'
import type { PlannedLeaveDay } from '@/types'
import { getColorForType, getLabelForType } from '@/utils/leaveTypes'
import { getISOWeekNumber } from '@/utils/dates'
import { CalendarDay } from './CalendarDay'
import { CalendarEvent } from './CalendarEvent'
export interface CalendarWeekProps {
weekDates: string[]
plannedDays: PlannedLeaveDay[]
selectedDates: Set<string>
parentName: string
personalDataUuid: string
isCurrentMonth: boolean
showWeekNumbers: boolean
onDayClick: (date: string) => void
onPointerDown: (date: string) => void
onPointerEnter: (date: string) => void
}
interface BarData {
startCol: number
endCol: number
parentUuid: string
dayType: string
isDubbeldag: boolean
lane: number
}
function buildBarsForWeek(
weekDates: string[],
plannedDays: PlannedLeaveDay[]
): BarData[] {
const dayToEntries = new Map<string, PlannedLeaveDay[]>()
for (const date of weekDates) {
dayToEntries.set(date, plannedDays.filter((pd) => pd.date === date))
}
const series = new Map<
string,
{ bars: Array<{ startIdx: number; endIdx: number }> }
>()
for (const pd of plannedDays) {
if (!weekDates.includes(pd.date)) continue
const key = `${pd.parentPersonalDataUuid}|${pd.dayType}|${pd.isDubbeldag}`
if (!series.has(key)) {
series.set(key, { bars: [] })
}
}
const result: Array<{
startCol: number
endCol: number
parentUuid: string
dayType: string
isDubbeldag: boolean
}> = []
for (const [key] of series) {
const parts = key.split('|')
const parentUuid = parts[0] ?? ''
const dayType = parts[1] ?? ''
const isDubbeldag = parts[2] ?? 'false'
const isDoubleStr = isDubbeldag === 'true'
let startIdx = -1
for (let i = 0; i < weekDates.length; i++) {
const date = weekDates[i]
const hasEntry = plannedDays.some(
(pd) =>
pd.date === date &&
pd.parentPersonalDataUuid === parentUuid &&
pd.dayType === dayType &&
pd.isDubbeldag === isDoubleStr
)
if (hasEntry) {
if (startIdx === -1) {
startIdx = i
}
} else {
if (startIdx !== -1) {
result.push({
startCol: startIdx,
endCol: i - 1,
parentUuid,
dayType,
isDubbeldag: isDoubleStr,
})
startIdx = -1
}
}
}
if (startIdx !== -1) {
result.push({
startCol: startIdx,
endCol: weekDates.length - 1,
parentUuid,
dayType,
isDubbeldag: isDoubleStr,
})
}
}
const barLanes = assignLanes(result)
return barLanes
}
function assignLanes(
bars: Array<{ startCol: number; endCol: number; parentUuid: string; dayType: string; isDubbeldag: boolean }>
): BarData[] {
const sorted = [...bars].sort((a, b) => {
if (a.startCol !== b.startCol) return a.startCol - b.startCol
return b.endCol - a.endCol - (a.endCol - a.startCol) - (b.endCol - b.startCol)
})
const lanes: BarData[][] = []
for (const bar of sorted) {
let assignedLane = -1
for (let laneIdx = 0; laneIdx < lanes.length; laneIdx++) {
const lane = lanes[laneIdx]
if (lane && lane.every((b) => !(b.startCol <= bar.endCol && b.endCol >= bar.startCol))) {
assignedLane = laneIdx
break
}
}
if (assignedLane === -1) {
assignedLane = lanes.length
lanes.push([])
}
const targetLane = lanes[assignedLane]
if (targetLane) {
targetLane.push({
startCol: bar.startCol,
endCol: bar.endCol,
parentUuid: bar.parentUuid,
dayType: bar.dayType,
isDubbeldag: bar.isDubbeldag,
lane: assignedLane,
})
}
}
return lanes.flat()
}
export function CalendarWeek({
weekDates,
plannedDays,
selectedDates,
parentName,
personalDataUuid,
isCurrentMonth,
showWeekNumbers,
onDayClick,
onPointerDown,
onPointerEnter,
}: CalendarWeekProps): ReactNode {
const bars = useMemo(() => buildBarsForWeek(weekDates, plannedDays), [weekDates, plannedDays])
const maxLane = bars.length > 0 ? Math.max(...bars.map((b) => b.lane)) : 0
const barHeight = 28
const laneGap = 4
const weekMinHeight = 84 + (maxLane + 1) * (barHeight + laneGap)
const firstDate = weekDates[0]
const weekNumber = getISOWeekNumber(new Date(firstDate + 'T00:00:00Z'))
return (
<div
className="calendar-week"
style={{
display: 'contents',
minHeight: `${weekMinHeight}px`,
}}
>
{showWeekNumbers && (
<div className="calendar__week-number">
<span className="calendar__week-number-text">v.{weekNumber}</span>
</div>
)}
{weekDates.map((date) => {
const weekDateObj = new Date(weekDates[0] + 'T00:00:00Z')
const dateObj = new Date(date + 'T00:00:00Z')
const dayIsCurrentMonth = dateObj.getMonth() === weekDateObj.getMonth()
return (
<div key={date} className="calendar-week__day-cell" style={{ position: 'relative' }}>
<CalendarDay
date={date}
isCurrentMonth={isCurrentMonth && dayIsCurrentMonth}
isToday={date === getTodayString()}
isSelected={selectedDates.has(date)}
onClick={() => {
if (isCurrentMonth && dayIsCurrentMonth) {
onDayClick(date)
}
}}
onPointerDown={(d) => {
if (isCurrentMonth && dayIsCurrentMonth) {
onPointerDown(d)
}
}}
onPointerEnter={(d) => {
if (isCurrentMonth && dayIsCurrentMonth) {
onPointerEnter(d)
}
}}
/>
<div
className="calendar-week__day-bars"
style={{
position: 'absolute',
top: '80%',
left: 0,
right: 0,
bottom: 0,
pointerEvents: 'none',
}}
>
{bars
.filter((b) => {
const dateIdx = weekDates.indexOf(date)
return dateIdx >= b.startCol && dateIdx <= b.endCol
})
.map((bar, idx) => {
const parentUuid = bar.parentUuid
const label = parentUuid === personalDataUuid ? parentName : 'Partner'
const typeLabel = getLabelForType(bar.dayType)
const color = getColorForType(bar.dayType)
return (
<div
key={idx}
className="calendar-bar"
style={{
backgroundColor: color,
height: barHeight,
marginBottom: laneGap,
}}
data-testid={`calendar-bar-${idx}`}
>
<CalendarEvent
leaveType={typeLabel}
color={color}
isDubbeldag={bar.isDubbeldag}
parentLabel={label}
/>
</div>
)
})}
</div>
</div>
)
})}
</div>
)
}
function getTodayString(): string {
const today = new Date()
const year = today.getFullYear()
const month = String(today.getMonth() + 1).padStart(2, '0')
const day = String(today.getDate()).padStart(2, '0')
return `${year}-${month}-${day}`
}
@@ -17,6 +17,9 @@ export interface PlannedDayModalProps {
onClose: () => void
isSaving?: boolean | undefined
error?: string | null | undefined
isRangeMode?: boolean | undefined
dayCount?: number | undefined
defaultDayType?: 'sjukpenning' | 'lagsta' | 'vacation' | undefined
}
export function PlannedDayModal({
@@ -30,6 +33,9 @@ export function PlannedDayModal({
onClose,
isSaving = false,
error = null,
isRangeMode = false,
dayCount = 1,
defaultDayType,
}: PlannedDayModalProps): ReactNode {
const [dayType, setDayType] = useState<'sjukpenning' | 'lagsta' | 'vacation'>('vacation')
const [parentId, setParentId] = useState(selectedParentId)
@@ -42,12 +48,18 @@ export function PlannedDayModal({
setParentId(existingDay.parentPersonalDataUuid)
setIsDubbeldag(existingDay.isDubbeldag)
} else {
setDayType('vacation')
setDayType(defaultDayType ?? 'vacation')
setParentId(selectedParentId)
setIsDubbeldag(false)
}
setLocalError(null)
}, [isOpen, existingDay, selectedParentId])
}, [isOpen, existingDay, selectedParentId, defaultDayType])
useEffect(() => {
if (dayType === 'vacation') {
setIsDubbeldag(false)
}
}, [dayType])
const handleSave = async () => {
try {
@@ -83,18 +95,20 @@ export function PlannedDayModal({
day: 'numeric',
})
const modalTitle = isRangeMode ? `Plan ${dayCount} days` : existingDay ? 'Edit Planned Day' : 'Plan a Day'
return (
<div className="planned-day-modal__overlay" onClick={onClose}>
<div className="planned-day-modal__content" onClick={(e) => e.stopPropagation()}>
<div className="planned-day-modal__header">
<h2 data-testid="modal-title">{existingDay ? 'Edit Planned Day' : 'Plan a Day'}</h2>
<h2 data-testid="modal-title">{modalTitle}</h2>
<button className="planned-day-modal__close" onClick={onClose} aria-label="Close">
×
</button>
</div>
<div className="planned-day-modal__body">
<p className="planned-day-modal__date">{displayDate}</p>
{!isRangeMode && <p className="planned-day-modal__date">{displayDate}</p>}
{(error || localError) && (
<div className="planned-day-modal__error" role="alert">
@@ -148,16 +162,21 @@ export function PlannedDayModal({
type="checkbox"
checked={isDubbeldag}
onChange={(e) => setIsDubbeldag(e.target.checked)}
disabled={isSaving}
disabled={isSaving || dayType === 'vacation'}
data-testid="dubbeldag-checkbox"
/>
{' '}Double day (both parents taking leave)
</label>
{dayType === 'vacation' && (
<p className="planned-day-modal__hint">
Dubbeldagar gäller inte för semester
</p>
)}
</div>
</div>
<div className="planned-day-modal__footer">
{existingDay && onDelete && (
{!isRangeMode && existingDay && onDelete && (
<button
className="planned-day-modal__button planned-day-modal__button--danger"
onClick={handleDelete}
@@ -109,6 +109,18 @@
cursor: pointer;
}
.planned-day-modal__checkbox-label input[type='checkbox']:disabled {
cursor: not-allowed;
}
.planned-day-modal__hint {
font-size: 12px;
color: #999;
margin-top: 6px;
margin-left: 24px;
font-style: italic;
}
.planned-day-modal__footer {
display: flex;
gap: 8px;
+1
View File
@@ -1,5 +1,6 @@
export { useAnalytics } from './useAnalytics'
export { useBreakPeriods } from './useBreakPeriods'
export { useShowWeekNumbers, getLastLeaveType, setLastLeaveType } from './useCalendarPreferences'
export { useOptimizationTips } from './useOptimizationTips'
export { useParentalLeave } from './useParentalLeave'
export { usePlannedDays } from './usePlannedDays'
@@ -0,0 +1,61 @@
import { useState, useEffect } from 'react'
const SHOW_WEEK_NUMBERS_KEY = 'calendar_show_week_numbers'
const LAST_LEAVE_TYPE_KEY = 'calendar_last_leave_type'
const STORAGE_EVENT_NAME = 'calendar:preferences-changed'
type LeaveType = 'sjukpenning' | 'lagsta' | 'vacation'
export function useShowWeekNumbers(): [boolean, (show: boolean) => void] {
const [showWeekNumbers, setShowWeekNumbers] = useState(false)
useEffect(() => {
const stored = localStorage.getItem(SHOW_WEEK_NUMBERS_KEY)
setShowWeekNumbers(stored === 'true')
const handleStorageChange = (e: StorageEvent) => {
if (e.key === SHOW_WEEK_NUMBERS_KEY) {
setShowWeekNumbers(e.newValue === 'true')
}
}
const handleCustomEvent = () => {
const stored = localStorage.getItem(SHOW_WEEK_NUMBERS_KEY)
setShowWeekNumbers(stored === 'true')
}
window.addEventListener('storage', handleStorageChange)
window.addEventListener(STORAGE_EVENT_NAME, handleCustomEvent)
return () => {
window.removeEventListener('storage', handleStorageChange)
window.removeEventListener(STORAGE_EVENT_NAME, handleCustomEvent)
}
}, [])
const updateShowWeekNumbers = (show: boolean) => {
localStorage.setItem(SHOW_WEEK_NUMBERS_KEY, show ? 'true' : 'false')
window.dispatchEvent(new Event(STORAGE_EVENT_NAME))
}
return [showWeekNumbers, updateShowWeekNumbers]
}
export function getLastLeaveType(): LeaveType | null {
const stored = sessionStorage.getItem(LAST_LEAVE_TYPE_KEY)
if (!stored || !isValidLeaveType(stored)) {
return null
}
return stored as LeaveType
}
export function setLastLeaveType(type: LeaveType): void {
if (!isValidLeaveType(type)) {
return
}
sessionStorage.setItem(LAST_LEAVE_TYPE_KEY, type)
}
function isValidLeaveType(value: string): value is LeaveType {
return ['sjukpenning', 'lagsta', 'vacation'].includes(value)
}
+125 -77
View File
@@ -1,25 +1,53 @@
import { ReactNode, useState } from 'react'
import { ReactNode, useState, useEffect } from 'react'
import { useWorkspace } from '@/context'
import { usePlannedDays } from '@/hooks'
import { usePlannedDays, useShowWeekNumbers, getLastLeaveType, setLastLeaveType } from '@/hooks'
import type { PlannedLeaveDay } from '@/types'
import { Layout } from '@/components/layout/Layout'
import { LoadingSpinner } from '@/components/common/LoadingSpinner'
import { CalendarDay } from '@/components/common/CalendarDay'
import { CalendarEvent } from '@/components/common/CalendarEvent'
import { CalendarWeek } from '@/components/common/CalendarWeek'
import { PlannedDayModal } from '@/components/modals/PlannedDayModal'
import { getColorForType } from '@/utils/leaveTypes'
import { datesInRange } from '@/utils/dates'
import './calendar.css'
export function Calendar(): ReactNode {
const { isLoading: wsLoading, selectedChildId, workspace, personalDataUuid } = useWorkspace()
const { isLoading: wsLoading, selectedChildId, workspace, personalDataUuid, parentName } = useWorkspace()
const { data: plannedDays, isLoading: pdLoading, add, update, remove } = usePlannedDays(selectedChildId ?? undefined)
const [showWeekNumbers] = useShowWeekNumbers()
const [currentMonth, setCurrentMonth] = useState(new Date())
const [selectedDate, setSelectedDate] = useState<string | null>(null)
const [selectedDates, setSelectedDates] = useState<Set<string>>(new Set())
const [dragAnchor, setDragAnchor] = useState<string | null>(null)
const [dragCurrent, setDragCurrent] = useState<string | null>(null)
const [isDragging, setIsDragging] = useState(false)
const [isModalOpen, setIsModalOpen] = useState(false)
const [isRangeMode, setIsRangeMode] = useState(false)
const [isSaving, setIsSaving] = useState(false)
const [modalError, setModalError] = useState<string | null>(null)
const isLoading = wsLoading || pdLoading
useEffect(() => {
const handlePointerUp = () => {
if (isDragging && dragAnchor && dragCurrent) {
const dates = datesInRange(dragAnchor, dragCurrent)
setSelectedDates(new Set(dates))
if (dates.length === 1) {
setIsRangeMode(false)
} else {
setIsRangeMode(true)
}
setIsModalOpen(true)
}
setIsDragging(false)
}
if (isDragging) {
window.addEventListener('pointerup', handlePointerUp)
return () => window.removeEventListener('pointerup', handlePointerUp)
}
}, [isDragging, dragAnchor, dragCurrent])
if (isLoading) {
return <LoadingSpinner message="Loading calendar..." />
}
@@ -54,16 +82,6 @@ export function Calendar(): ReactNode {
}
weeks.push(currentWeek)
const getEventsForDate = (date: string) => {
return (plannedDays ?? [])
.filter((pd: PlannedLeaveDay) => pd.date === date)
.map((pd: PlannedLeaveDay) => ({
type: pd.dayType,
color: getColorForType(pd.dayType),
title: pd.dayType,
}))
}
const handlePrevMonth = () => {
setCurrentMonth(new Date(year, month - 1, 1))
}
@@ -72,9 +90,21 @@ export function Calendar(): ReactNode {
setCurrentMonth(new Date(year, month + 1, 1))
}
const handlePointerDown = (date: string) => {
setDragAnchor(date)
setDragCurrent(date)
setIsDragging(true)
}
const handlePointerEnter = (date: string) => {
if (isDragging) {
setDragCurrent(date)
}
}
const handleDayClick = (date: string) => {
setSelectedDate(date)
setModalError(null)
setSelectedDates(new Set([date]))
setIsRangeMode(false)
setIsModalOpen(true)
}
@@ -87,51 +117,63 @@ export function Calendar(): ReactNode {
parentId: string
isDubbeldag: boolean
}) => {
if (!selectedDate || !selectedChildId || !workspace?.id || !personalDataUuid) return
if (selectedDates.size === 0 || !selectedChildId || !workspace?.id || !personalDataUuid) return
try {
setIsSaving(true)
setModalError(null)
const existingDay = getExistingDay(selectedDate)
setLastLeaveType(payload.dayType)
if (existingDay) {
await update(existingDay.id, {
day_type: payload.dayType,
is_dubbeldag: payload.isDubbeldag,
})
} else {
await add({
workspace_id: workspace.id,
child_id: selectedChildId,
parent_personal_data_uuid: personalDataUuid,
date: selectedDate,
day_type: payload.dayType,
is_dubbeldag: payload.isDubbeldag,
})
for (const date of selectedDates) {
const existingDay = (plannedDays ?? []).find(
(pd: PlannedLeaveDay) => pd.date === date && pd.parentPersonalDataUuid === personalDataUuid
)
if (existingDay) {
await update(existingDay.id, {
day_type: payload.dayType,
is_dubbeldag: payload.isDubbeldag,
})
} else {
await add({
workspace_id: workspace.id,
child_id: selectedChildId,
parent_personal_data_uuid: personalDataUuid,
date,
day_type: payload.dayType,
is_dubbeldag: payload.isDubbeldag,
})
}
}
setIsModalOpen(false)
setSelectedDates(new Set())
} catch (err) {
setModalError(err instanceof Error ? err.message : 'Failed to save planned day')
setModalError(err instanceof Error ? err.message : 'Failed to save planned days')
} finally {
setIsSaving(false)
}
}
const handleDeletePlannedDay = async () => {
if (!selectedDate) return
if (selectedDates.size !== 1) return
try {
setIsSaving(true)
setModalError(null)
const existingDay = getExistingDay(selectedDate)
const dates = Array.from(selectedDates)
const date = dates[0]
if (!date) return
const existingDay = getExistingDay(date)
if (existingDay) {
await remove(existingDay.id)
}
setIsModalOpen(false)
setSelectedDates(new Set())
} catch (err) {
setModalError(err instanceof Error ? err.message : 'Failed to delete planned day')
} finally {
@@ -139,6 +181,9 @@ export function Calendar(): ReactNode {
}
}
const defaultLeaveType = getLastLeaveType() ?? 'vacation'
const firstSelectedDate = Array.from(selectedDates).sort()[0]
return (
<Layout>
<div data-testid="calendar" className="calendar">
@@ -154,59 +199,75 @@ export function Calendar(): ReactNode {
</button>
</div>
<div className="calendar__grid">
<div className={`calendar__grid${showWeekNumbers ? ' calendar__grid--with-week-numbers' : ''}`}>
{showWeekNumbers && <div className="calendar__week-number-header" />}
{['Mån', 'Tis', 'Ons', 'Tor', 'Fre', 'Lör', 'Sön'].map((day) => (
<div key={day} className="calendar__weekday">
{day}
</div>
))}
{weeks.map((week, weekIdx) =>
week.map((date, dayIdx) => {
const events = getEventsForDate(date)
const isCurrentMonth = new Date(date).getMonth() === month
const isToday = date === getTodayString()
return (
<CalendarDay
key={`${weekIdx}-${dayIdx}`}
date={date}
events={events}
isCurrentMonth={isCurrentMonth}
isToday={isToday}
onClick={isCurrentMonth ? () => handleDayClick(date) : undefined}
/>
)
})
)}
{weeks.map((week, weekIdx) => {
const firstDate = week[0]
const weekMonth = firstDate ? new Date(firstDate + 'T00:00:00Z').getMonth() : month
return (
<CalendarWeek
key={weekIdx}
weekDates={week}
plannedDays={plannedDays ?? []}
selectedDates={selectedDates}
parentName={parentName ?? 'Du'}
personalDataUuid={personalDataUuid ?? ''}
isCurrentMonth={weekMonth === month}
showWeekNumbers={showWeekNumbers}
onDayClick={handleDayClick}
onPointerDown={handlePointerDown}
onPointerEnter={handlePointerEnter}
/>
)
})}
</div>
<div className="calendar__legend">
<h3>Legend</h3>
<div className="calendar__legend-items">
<div className="calendar__legend-item">
<CalendarEvent leaveType="Vacation" color={getColorForType('vacation')} />
<span className="calendar__legend-swatch" style={{ backgroundColor: getColorForType('vacation') }} />
<span>Vacation</span>
</div>
<div className="calendar__legend-item">
<CalendarEvent leaveType="Sick" color={getColorForType('sjukpenning')} />
<span className="calendar__legend-swatch" style={{ backgroundColor: getColorForType('sjukpenning') }} />
<span>Sick Leave</span>
</div>
<div className="calendar__legend-item">
<CalendarEvent leaveType="Parental" color={getColorForType('lagsta')} />
<span className="calendar__legend-swatch" style={{ backgroundColor: getColorForType('lagsta') }} />
<span>Parental</span>
</div>
<div className="calendar__legend-item">
<span className="calendar__legend-swatch calendar__legend-swatch--dubbeldag">2×</span>
<span>Double day</span>
</div>
</div>
</div>
{selectedDate && (
{firstSelectedDate && (
<PlannedDayModal
date={selectedDate}
date={firstSelectedDate}
isOpen={isModalOpen}
existingDay={getExistingDay(selectedDate) ?? null}
parents={[{ id: personalDataUuid ?? '', name: 'Current Parent' }]}
existingDay={isRangeMode ? null : getExistingDay(firstSelectedDate) ?? null}
parents={[{ id: personalDataUuid ?? '', name: parentName ?? 'Du' }]}
selectedParentId={personalDataUuid ?? ''}
onSave={handleSavePlannedDay}
onDelete={getExistingDay(selectedDate) ? handleDeletePlannedDay : undefined}
onClose={() => setIsModalOpen(false)}
onDelete={!isRangeMode && getExistingDay(firstSelectedDate) ? handleDeletePlannedDay : undefined}
onClose={() => {
setIsModalOpen(false)
setSelectedDates(new Set())
}}
isSaving={isSaving}
error={modalError}
isRangeMode={isRangeMode}
dayCount={selectedDates.size}
defaultDayType={defaultLeaveType}
/>
)}
</div>
@@ -220,16 +281,3 @@ function formatDate(date: Date): string {
const day = String(date.getDate()).padStart(2, '0')
return `${year}-${month}-${day}`
}
function getTodayString(): string {
return formatDate(new Date())
}
function getColorForType(type: string): string {
const colorMap: Record<string, string> = {
vacation: '#4CAF50',
sjukpenning: '#FF9800',
lagsta: '#2196F3',
}
return colorMap[type] ?? '#9E9E9E'
}
+15 -1
View File
@@ -1,6 +1,6 @@
import { ReactNode, useState, useEffect } from 'react'
import { useWorkspace } from '@/context'
import { useVacationDays, useBreakPeriods } from '@/hooks'
import { useVacationDays, useBreakPeriods, useShowWeekNumbers } from '@/hooks'
import * as api from '@/services/api'
import { Layout } from '@/components/layout/Layout'
import { LoadingSpinner } from '@/components/common/LoadingSpinner'
@@ -16,6 +16,7 @@ export function Settings(): ReactNode {
const { data: breakPeriods, isLoading: bpLoading, add: addBreakPeriod, remove: removeBreakPeriod } = useBreakPeriods(
workspace?.id ?? null
)
const [showWeekNumbers, setShowWeekNumbers] = useShowWeekNumbers()
const [childBirthDate, setChildBirthDate] = useState('')
const [parentData, setParentData] = useState({ salaryType: '', employmentStatus: '' })
@@ -284,6 +285,19 @@ export function Settings(): ReactNode {
/>
</section>
<section className="settings-page__section">
<h2>Calendar</h2>
<label style={{ display: 'flex', alignItems: 'center', gap: '8px', cursor: 'pointer' }}>
<input
type="checkbox"
checked={showWeekNumbers}
onChange={(e) => setShowWeekNumbers(e.target.checked)}
data-testid="show-week-numbers-checkbox"
/>
<span>Visa veckonummer</span>
</label>
</section>
<section className="settings-page__section">
<h2>Partner</h2>
<p>Add a partner to plan parental leave together.</p>
+117 -5
View File
@@ -114,6 +114,11 @@
font-size: 12px;
}
.calendar-day--selected {
background-color: #e3f2fd;
border-color: #0066cc;
}
.calendar-day__events {
display: flex;
flex-wrap: wrap;
@@ -128,6 +133,71 @@
flex-shrink: 0;
}
.calendar-week {
position: relative;
}
.calendar-week__day-cell {
display: flex;
flex-direction: column;
position: relative;
}
.calendar-week__days-grid {
display: contents;
}
.calendar-week__day-bars {
display: flex;
flex-direction: column;
gap: 2px;
padding: 0 2px;
}
.calendar-bar {
display: flex;
align-items: center;
padding: 4px 8px;
border-radius: 3px;
font-size: 12px;
color: #fff;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.calendar-event {
display: flex;
align-items: center;
gap: 4px;
width: 100%;
background: none !important;
}
.calendar-event__label {
font-size: 12px;
font-weight: 500;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: inherit;
}
.calendar-event__badge {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 18px;
height: 18px;
padding: 0 3px;
background-color: rgba(255, 255, 255, 0.3);
border-radius: 2px;
font-size: 10px;
font-weight: bold;
flex-shrink: 0;
}
.calendar__legend {
padding: 16px;
background-color: #f9f9f9;
@@ -144,7 +214,7 @@
.calendar__legend-items {
display: flex;
gap: 16px;
gap: 24px;
flex-wrap: wrap;
}
@@ -156,9 +226,51 @@
color: #666;
}
.calendar__legend-item .calendar-event {
width: 12px !important;
height: 12px !important;
min-width: 12px;
.calendar__legend-swatch {
display: inline-flex;
align-items: center;
justify-content: center;
width: 16px;
height: 16px;
border-radius: 2px;
flex-shrink: 0;
font-size: 11px;
font-weight: bold;
color: #fff;
}
.calendar__legend-swatch--dubbeldag {
background-color: rgba(0, 0, 0, 0.2);
border: 1px solid #999;
color: #333;
}
.calendar__grid--with-week-numbers {
grid-template-columns: 50px repeat(7, 1fr);
}
.calendar__week-number-header {
display: flex;
align-items: center;
justify-content: center;
padding: 12px 8px;
font-weight: 600;
font-size: 12px;
color: #999;
}
.calendar__week-number {
display: flex;
align-items: center;
justify-content: center;
padding: 8px;
font-weight: 600;
font-size: 11px;
color: #999;
border-right: 1px solid #e0e0e0;
background-color: #fafafa;
}
.calendar__week-number-text {
display: block;
}
+39
View File
@@ -62,3 +62,42 @@ export function getMonthName(date: Date): string {
const formatter = new Intl.DateTimeFormat('sv-SE', { month: 'long' })
return formatter.format(date)
}
/**
* Get ISO week number (1-53) for a date.
* ISO-8601: Monday-first, week 1 = contains the year's first Thursday.
*/
export function getISOWeekNumber(date: Date): number {
if (!isValidDate(date)) return 0
const d = new Date(date.getTime())
d.setUTCDate(d.getUTCDate() + 4 - (d.getUTCDay() || 7))
const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1))
const weekNum = Math.ceil((((d.getTime() - yearStart.getTime()) / 86400000) + 1) / 7)
return weekNum
}
/**
* Get all dates in a range (inclusive, ascending order, order-independent).
* Dates should be ISO strings (YYYY-MM-DD).
*/
export function datesInRange(startStr: string, endStr: string): string[] {
const start = parseInputDate(startStr)
const end = parseInputDate(endStr)
if (!isValidDate(start) || !isValidDate(end)) {
return []
}
const [first, second] = start <= end ? [start, end] : [end, start]
const result: string[] = []
const current = new Date(first)
while (current <= second) {
result.push(formatDateForInput(current))
current.setUTCDate(current.getUTCDate() + 1)
}
return result
}
+17
View File
@@ -0,0 +1,17 @@
export function getColorForType(type: string): string {
const colorMap: Record<string, string> = {
vacation: '#4CAF50',
sjukpenning: '#FF9800',
lagsta: '#2196F3',
}
return colorMap[type] ?? '#9E9E9E'
}
export function getLabelForType(type: string): string {
const labelMap: Record<string, string> = {
vacation: 'Vacation',
sjukpenning: 'Sick Leave',
lagsta: 'Parental',
}
return labelMap[type] ?? 'Unknown'
}