Repository Public
1// Pure calendar maths for the maintenance screens. Everything works on UTC instants (ms) and civil day keys2// ("YYYY-MM-DD") interpreted in an explicit IANA time zone; nothing depends on the zone of the machine running it.3// Recurrences are NEVER expanded here: the server returns one item per occurrence.4import type { Schemas } from "@/api/client";56export type Occurrence = Schemas["MaintenanceOccurrence"];7export type DayKey = string;89export interface CivilTime {10 y: number;11 m: number; // 1–1212 d: number;13 h: number;14 mi: number;15}1617const partsFmt = new Map<string, Intl.DateTimeFormat>();18function fmtFor(zone: string): Intl.DateTimeFormat {19 let f = partsFmt.get(zone);20 if (!f) {21 f = new Intl.DateTimeFormat("en-US", { timeZone: zone, hourCycle: "h23", year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit" });22 partsFmt.set(zone, f);23 }24 return f;25}2627export function isValidZone(zone: string): boolean {28 try {29 new Intl.DateTimeFormat("en-US", { timeZone: zone });30 return true;31 } catch {32 return false;33 }34}3536/** Wall-clock time of an instant in a zone. */37export function zonedParts(utcMs: number, zone: string): CivilTime & { s: number } {38 const out: Record<string, number> = {};39 for (const p of fmtFor(zone).formatToParts(new Date(utcMs))) if (p.type !== "literal") out[p.type] = Number(p.value);40 return { y: out.year ?? 1970, m: out.month ?? 1, d: out.day ?? 1, h: (out.hour ?? 0) % 24, mi: out.minute ?? 0, s: out.second ?? 0 };41}4243/** Offset of the zone at an instant, in ms (east of UTC is positive). */44export function zoneOffsetMs(utcMs: number, zone: string): number {45 const p = zonedParts(utcMs, zone);46 return Date.UTC(p.y, p.m - 1, p.d, p.h, p.mi, p.s) - Math.floor(utcMs / 1000) * 1000;47}4849/**50 * Instant of a wall-clock time in a zone. A time skipped by a DST jump resolves to the instant after the jump51 * (02:30 on a spring-forward night → 03:30); a repeated time resolves to its first occurrence.52 */53export function zonedToUtc(t: CivilTime, zone: string): number {54 const wall = Date.UTC(t.y, t.m - 1, t.d, t.h, t.mi);55 const o1 = zoneOffsetMs(wall, zone);56 const o2 = zoneOffsetMs(wall - o1, zone);57 if (o1 === o2) return wall - o1;58 // around a transition: both candidates, keep the one that round-trips; none round-trips inside a gap59 const a = wall - o1, b = wall - o2;60 const ok = (ms: number) => { const p = zonedParts(ms, zone); return p.h === t.h && p.mi === t.mi && p.d === t.d; };61 if (ok(a) && ok(b)) return Math.min(a, b);62 if (ok(a)) return a;63 if (ok(b)) return b;64 return Math.max(a, b);65}6667const pad = (n: number) => String(n).padStart(2, "0");68export const toDayKey = (y: number, m: number, d: number): DayKey => `${y}-${pad(m)}-${pad(d)}`;69export function parseDayKey(key: DayKey): { y: number; m: number; d: number } {70 const [y, m, d] = key.split("-").map(Number);71 return { y: y ?? 1970, m: m ?? 1, d: d ?? 1 };72}73export function dayKeyOf(utcMs: number, zone: string): DayKey {74 const p = zonedParts(utcMs, zone);75 return toDayKey(p.y, p.m, p.d);76}77/** Civil-calendar arithmetic (no zone involved). */78export function addDays(key: DayKey, n: number): DayKey {79 const { y, m, d } = parseDayKey(key);80 const t = new Date(Date.UTC(y, m - 1, d + n));81 return toDayKey(t.getUTCFullYear(), t.getUTCMonth() + 1, t.getUTCDate());82}83/** Same day of month `n` months away, clamped to the length of the target month. */84export function addMonths(key: DayKey, n: number): DayKey {85 const { y, m, d } = parseDayKey(key);86 const first = new Date(Date.UTC(y, m - 1 + n, 1));87 const last = new Date(Date.UTC(first.getUTCFullYear(), first.getUTCMonth() + 1, 0)).getUTCDate();88 return toDayKey(first.getUTCFullYear(), first.getUTCMonth() + 1, Math.min(d, last));89}90/** 0 = Sunday … 6 = Saturday. */91export function weekdayOf(key: DayKey): number {92 const { y, m, d } = parseDayKey(key);93 return new Date(Date.UTC(y, m - 1, d)).getUTCDay();94}95export function diffDays(a: DayKey, b: DayKey): number {96 const x = parseDayKey(a), y = parseDayKey(b);97 return Math.round((Date.UTC(y.y, y.m - 1, y.d) - Date.UTC(x.y, x.m - 1, x.d)) / 86400_000);98}99100/** [start, end) of a civil day in a zone, as instants. Days are 23 or 25 hours long on DST changes. */101export function dayBounds(key: DayKey, zone: string): [number, number] {102 const a = parseDayKey(key), b = parseDayKey(addDays(key, 1));103 return [zonedToUtc({ ...a, h: 0, mi: 0 }, zone), zonedToUtc({ ...b, h: 0, mi: 0 }, zone)];104}105106/** First day of the week for a BCP 47 tag: 0 = Sunday … 6 = Saturday. */107export function weekStartFor(localeTag: string): number {108 try {109 const loc = new Intl.Locale(localeTag) as Intl.Locale & { weekInfo?: { firstDay?: number }; getWeekInfo?: () => { firstDay?: number } };110 const first = (typeof loc.getWeekInfo === "function" ? loc.getWeekInfo() : loc.weekInfo)?.firstDay;111 if (typeof first === "number" && first >= 1 && first <= 7) return first % 7;112 const region = loc.maximize().region ?? "";113 return SUNDAY_REGIONS.has(region) ? 0 : 1;114 } catch {115 return 1;116 }117}118const SUNDAY_REGIONS = new Set(["CA", "US", "MX", "BR", "JP", "IL", "AU", "IN", "PH", "ZA", "KR", "TW", "HK"]);119120export function startOfWeek(key: DayKey, weekStart: number): DayKey {121 return addDays(key, -((weekdayOf(key) - weekStart + 7) % 7));122}123export function weekDays(key: DayKey, weekStart: number): DayKey[] {124 const s = startOfWeek(key, weekStart);125 return Array.from({ length: 7 }, (_, i) => addDays(s, i));126}127/** Weeks (rows of 7 day keys) covering the month of `key`; leading/trailing days belong to adjacent months. */128export function monthGrid(key: DayKey, weekStart: number): DayKey[][] {129 const { y, m } = parseDayKey(key);130 const first = toDayKey(y, m, 1);131 const lastDay = new Date(Date.UTC(y, m, 0)).getUTCDate();132 const start = startOfWeek(first, weekStart);133 const end = addDays(startOfWeek(toDayKey(y, m, lastDay), weekStart), 6);134 const weeks: DayKey[][] = [];135 for (let d = start; d <= end; d = addDays(d, 7)) weeks.push(Array.from({ length: 7 }, (_, i) => addDays(d, i)));136 return weeks;137}138139export type CalendarView = "month" | "week" | "agenda";140export const AGENDA_DAYS = 30;141/** Days shown by a view around its anchor day. */142export function visibleDays(view: CalendarView, anchor: DayKey, weekStart: number): DayKey[] {143 if (view === "month") return monthGrid(anchor, weekStart).flat();144 if (view === "week") return weekDays(anchor, weekStart);145 return Array.from({ length: AGENDA_DAYS }, (_, i) => addDays(anchor, i));146}147export function visibleRange(view: CalendarView, anchor: DayKey, weekStart: number, zone: string): { from: string; to: string } {148 const days = visibleDays(view, anchor, weekStart);149 const first = days[0] ?? anchor, last = days[days.length - 1] ?? anchor;150 return { from: new Date(dayBounds(first, zone)[0]).toISOString(), to: new Date(dayBounds(last, zone)[1]).toISOString() };151}152export function shiftAnchor(view: CalendarView, anchor: DayKey, dir: 1 | -1): DayKey {153 return view === "month" ? addMonths(anchor, dir) : view === "week" ? addDays(anchor, 7 * dir) : addDays(anchor, AGENDA_DAYS * dir);154}155156export interface DaySegment {157 occ: Occurrence;158 key: string;159 /** clipped to the day, as fractions (0–1) of the day's real length */160 start: number;161 end: number;162 startMs: number;163 endMs: number;164 continuesBefore: boolean;165 continuesAfter: boolean;166}167export const occKey = (o: Occurrence): string => `${o.window.id}@${o.occurrence_start}`;168169/** Occurrences intersecting each day (a multi-day occurrence yields one segment per day it covers). */170export function segmentsByDay(occs: readonly Occurrence[], days: readonly DayKey[], zone: string): Map<DayKey, DaySegment[]> {171 const out = new Map<DayKey, DaySegment[]>();172 const parsed = occs.map((occ) => ({ occ, s: Date.parse(occ.occurrence_start), e: Math.max(Date.parse(occ.occurrence_end), Date.parse(occ.occurrence_start) + 1) })).filter((x) => Number.isFinite(x.s) && Number.isFinite(x.e));173 for (const day of days) {174 const [ds, de] = dayBounds(day, zone);175 const len = de - ds;176 const list: DaySegment[] = [];177 for (const { occ, s, e } of parsed) {178 if (s >= de || e <= ds) continue;179 const a = Math.max(s, ds), b = Math.min(e, de);180 list.push({ occ, key: occKey(occ), start: (a - ds) / len, end: (b - ds) / len, startMs: a, endMs: b, continuesBefore: s < ds, continuesAfter: e > de });181 }182 list.sort((x, y) => x.startMs - y.startMs || y.endMs - x.endMs || x.key.localeCompare(y.key));183 out.set(day, list);184 }185 return out;186}187188export interface LaidOut<T> {189 item: T;190 lane: number;191 /** number of lanes of the overlap cluster the item belongs to */192 lanes: number;193}194/** Side-by-side lanes for overlapping intervals (week view). Items that merely touch do not overlap. */195export function layoutLanes<T extends { start: number; end: number }>(items: readonly T[]): LaidOut<T>[] {196 const sorted = [...items].sort((a, b) => a.start - b.start || b.end - a.end);197 const out: LaidOut<T>[] = [];198 let cluster: LaidOut<T>[] = [];199 let laneEnds: number[] = [];200 let clusterEnd = -Infinity;201 const flush = () => {202 for (const c of cluster) c.lanes = laneEnds.length;203 out.push(...cluster);204 cluster = [];205 laneEnds = [];206 };207 for (const item of sorted) {208 if (cluster.length > 0 && item.start >= clusterEnd) flush();209 let lane = laneEnds.findIndex((end) => end <= item.start);210 if (lane === -1) {211 lane = laneEnds.length;212 laneEnds.push(item.end);213 } else laneEnds[lane] = item.end;214 cluster.push({ item, lane, lanes: 1 });215 clusterEnd = cluster.length === 1 ? item.end : Math.max(clusterEnd, item.end);216 }217 flush();218 return out;219}220221/** "UTC−5", "UTC+5:30", "UTC" for a zone at an instant. */222export function utcOffsetLabel(zone: string, atMs: number): string {223 const min = Math.round(zoneOffsetMs(atMs, zone) / 60_000);224 if (min === 0) return "UTC";225 const abs = Math.abs(min);226 return `UTC${min < 0 ? "−" : "+"}${Math.floor(abs / 60)}${abs % 60 ? `:${pad(abs % 60)}` : ""}`;227}228export function zoneLabel(zone: string, atMs: number): string {229 return zone === "UTC" ? "UTC" : `${zone} (${utcOffsetLabel(zone, atMs)})`;230}231232// ── <input type="datetime-local"> / <input type="date"> values in an arbitrary zone ──233export function parseLocalInput(value: string): CivilTime | null {234 const m = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})/.exec(value);235 if (!m) return null;236 const t = { y: Number(m[1]), m: Number(m[2]), d: Number(m[3]), h: Number(m[4]), mi: Number(m[5]) };237 if (t.m < 1 || t.m > 12 || t.d < 1 || t.d > 31 || t.h > 23 || t.mi > 59) return null;238 return t;239}240export function localInputToUtc(value: string, zone: string): string | null {241 const t = parseLocalInput(value);242 return t ? new Date(zonedToUtc(t, zone)).toISOString() : null;243}244export function utcToLocalInput(iso: string | number, zone: string): string {245 const p = zonedParts(typeof iso === "number" ? iso : Date.parse(iso), zone);246 return `${toDayKey(p.y, p.m, p.d)}T${pad(p.h)}:${pad(p.mi)}`;247}248249/** Text split around case-insensitive matches of a query (rendered as text nodes and <mark>). */250export function splitHighlight(text: string, query: string): { text: string; match: boolean }[] {251 const q = query.trim().toLowerCase();252 if (!q) return text ? [{ text, match: false }] : [];253 const out: { text: string; match: boolean }[] = [];254 const lower = text.toLowerCase();255 let i = 0;256 for (;;) {257 const j = lower.indexOf(q, i);258 if (j === -1) break;259 if (j > i) out.push({ text: text.slice(i, j), match: false });260 out.push({ text: text.slice(j, j + q.length), match: true });261 i = j + q.length;262 }263 if (i < text.length) out.push({ text: text.slice(i), match: false });264 return out;265}266