A calendar looks like a grid of boxes, and the grid hides a great many rules about time. This chapter designs a calendar's web client, following the seven steps of the method chapter.
Step one lists what a person can do. The functional requirements for this design are these.
See a day, a week or a month, and move between them.
Create, edit and delete an event with a title, a start, an end and a place.
Repeat an event, for example every Monday and Wednesday, and change or delete one instance without touching the rest.
Keep an event in its own time zone, and show times in the viewer's zone, so that a 9:00 meeting is still at 9:00 after the clocks change.
See invitations and answer them.
Do all of it from the keyboard.
Out of scope, said aloud: finding free time across people, room booking, the delivery of reminders, import and export of calendar files, and sharing permissions. RFC 5545, the iCalendar standard, defines the recurrence rules this design uses, and the server stores events; the client's job is to show them and to change them safely.
Question
Because the answer changes
Do events repeat, and how freely?
the data model, and whether the client or the server expands a series
Which zones, and do people travel?
whether an event keeps its own zone or follows the viewer
Can two people edit one event?
whether edits need version checks
Is it used offline?
whether edits queue and replay later
Which locales?
the first day of the week, the weekend, month and day names
Targets
Each target below has a way to check it. They are ours, chosen for a work calendar used on a phone and a desktop.
Area
Target
How it is checked
Time
an event keeps its wall-clock time in its zone across daylight saving changes; a series never lands on a date that does not exist
tests around clock changes and month ends
Layout
every overlapping event is visible; events that only touch do not share a column
a property test over thousands of random days
Editing
a drag lands on a 15-minute step, Escape puts the event back, and every drag has a keyboard route
pointer and keyboard runs in Chrome
Conflicts
an edit never silently overwrites someone else's change
a stale write answered with 412
Keyboard
the month grid is one tab stop and moves with the arrow keys
key presses in Chrome
Languages
the first day of the week and the weekend follow the locale
an Intl.Locale run
The first row is the one that makes calendars hard. Most of this chapter is about keeping it true.
The week does not start on the same day everywhere
A month grid has seven columns, and which day comes first depends on where you are. Intl.Locale can say. Its getWeekInfo() method returns the first day of the week and the weekend days, numbered 1 for Monday to 7 for Sunday. MDN marks it as newly available in 2026, with the older weekInfo property in some browsers, so the helper tries both. MDN also notes that the minimalDays field is being removed, so the design does not use it.
js
// weekinfo.mjs: the first day of the week and the weekend, per locale.const info = (loc) => {
const l = new Intl.Locale(loc)
return l.getWeekInfo ? l.getWeekInfo() : l.weekInfo // older engines
}
// a Monday in the week of 2 March 2026, as a UTC dateconst MONDAY = Date.UTC(2026, 2, 2)
exportfunction weekdayHeads(loc) {
const { firstDay } = info(loc)
const name = new Intl.DateTimeFormat(loc, {
weekday: 'short',
timeZone: 'UTC',
})
return Array.from({ length: 7 }, (_, i) => {
const day = MONDAY + ((firstDay - 1 + i) % 7) * 864e5
return name.format(day)
})
}
for (const loc of ['en-IN', 'hi-IN', 'en-GB', 'en-US']) {
const w = info(loc)
console.log(
loc.padEnd(6),
`first ${w.firstDay}, weekend ${w.weekend}`.padEnd(24),
weekdayHeads(loc).join(' '),
)
}
console.log('1 = Monday ... 7 = Sunday')
weekinfo.mjs: first day, weekend and the column heads.
text
en-IN first 7, weekend 7 Sun Mon Tue Wed Thu Fri Sat
hi-IN first 7, weekend 7 रवि सोम मंगल बुध गुरु शुक्र शनि
en-GB first 1, weekend 6,7 Mon Tue Wed Thu Fri Sat Sun
en-US first 7, weekend 6,7 Sun Mon Tue Wed Thu Fri Sat
1 = Monday ... 7 = Sunday
Output (Node 24)
For en-IN and hi-IN the data says the week starts on Sunday and the weekend is Sunday only, which differs from en-GB, where it starts on Monday and the weekend is Saturday and Sunday. These are the rules in this machine's Intl data, and a workplace may differ from its locale, so the design lets the user override the first day. The column heads came out in Devanagari for hi-IN without any translation table: month and day names are part of Intl.DateTimeFormat.
Why does the month grid ask Intl.Locale for the first day of the week instead of assuming Monday?
The run showed en-IN and en-US starting on Sunday and en-GB on Monday, so a fixed choice is wrong for some users.
What did the run show about the weekend for en-IN?
The data lists only Sunday (weekend 7), where en-GB lists Saturday and Sunday.
A work calendar should let the user override it.
The helper tries getWeekInfo() first and then weekInfo. Why?
MDN says some older browser versions expose the data as a weekInfo property, and newer ones as the method.
Part 2 · Data model: three kinds of time
Instants, wall times and dates
A calendar mixes three different kinds of time, and mixing them up is the source of most calendar bugs. An instant is one moment in the world, the same for everyone, such as 2026-03-02T03:30:00Z. A wall-clock time is what a clock on a wall reads in some zone, such as 9:00 in Kolkata, and it names an instant only when you say which zone. A date is a calendar day with no time at all, such as the fourth of March.
Which one an event uses decides what happens when the world changes. A meeting at 9:00 in New York should stay at 9:00 when the clocks change, so it is stored as a wall-clock time and a zone, and the instant is worked out each time it is needed. An all-day event is a date, and it is the same day for every viewer, not 24 hours. A flight is the exception: it has a fixed duration in elapsed minutes. The types say all of this.
ts
// model.ts: the three kinds of time a calendar stores.type Wall = string // 'YYYY-MM-DDTHH:mm', read in the event's own zonetype DateOnly = string // 'YYYY-MM-DD', a calendar day with no timeexporttype Timed = {
kind: 'timed'
id: string
title: string
start: Wall
tz: string // an IANA zone such as 'Asia/Kolkata'
minutes: number // exact length, in elapsed minutes
}
exporttype AllDay = {
kind: 'allDay'
id: string
title: string
start: DateOnly
days: number // whole calendar days, however long they are
}
model.ts: timed and all-day events.
ts
exporttype Repeating = Timed & {
rrule: string // 'FREQ=WEEKLY;BYDAY=MO,WE'
exdates: Wall[] // instances deleted from the series
overrides: Record<Wall, Partial<Timed>> // instances edited alone
}
exporttype CalEvent = Timed | AllDay | Repeating
exportfunction describe(e: CalEvent): string {
switch (e.kind) {
case'allDay':
return`${e.title}: ${e.days} day(s) from ${e.start}`case'timed':
return'rrule'in e
? `${e.title}: repeats (${e.rrule}) at ${e.start.slice(11)}`
model.ts: repeating events, and a function over all three.
Three small choices to say aloud. A repeating event is an ordinary timed event with a rule, a list of deleted instances and a map of instances edited alone. Each instance is named by its original wall-clock start, which stays the same even if the instance is moved. And the length is in elapsed minutes, not in days, so it stays exact across a clock change.
text
Standup: 15 min from 2026-03-02T09:30 Asia/Kolkata
Office holiday: 1 day(s) from 2026-03-04
Planning: repeats (FREQ=WEEKLY;BYDAY=MO) at 11:00
Output (Node 24, run with node model-run.ts; tsc --strict passes)
Repeating events
A repeating event stores a rule, not a list of dates. The rule format comes from RFC 5545. FREQ is required and says how often: daily, weekly, monthly or yearly. INTERVAL says how many periods to skip and defaults to 1. COUNT and UNTIL end the series, and the RFC says they must not appear together. BYDAY and BYMONTHDAY pick days. This design supports DAILY, WEEKLY and MONTHLY, and rejects anything else loudly so that nothing is silently wrong.
js
// rrule.mjs: a subset of RFC 5545, expanded in the event's zone.import { toInstant, instantsFor, validDate } from'./zones.mjs'import { parseWall } from'./wall.mjs'const DAYS = ['SU', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA']
// a rule that can never match must still stopconst LIMIT = 5000const isDay = (n) => Number.isInteger(n) && n >= 1 && n <= 31exportfunction parseRule(text) {
const r = {
freq: null,
interval: 1,
count: null,
until: null,
byday: [],
bymonthday: [],
}
const seen = new Set()
for (const part of text.split(';')) {
const [k, v = ''] = part.split('=')
if (seen.has(k)) thrownew Error(`${k} appears twice`)
seen.add(k)
if (k === 'FREQ') {
if (!['DAILY', 'WEEKLY', 'MONTHLY'].includes(v))
thrownew Error(`FREQ=${v} is not supported`)
r.freq = v
} elseif (k === 'INTERVAL' || k === 'COUNT') {
if (!/^[1-9]\d*$/.test(v))
thrownew Error(`${k} must be a positive whole number`)
rrule.mjs: read a rule, and refuse bad ones.
js
r[k.toLowerCase()] = Number(v)
} elseif (k === 'UNTIL') {
const m = /^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z$/.exec(v)
if (!m) thrownew Error('UNTIL must look like 20261231T180000Z')
const [y, mo, d, h, mi, sec] = m.slice(1).map(Number)
r.until = Date.UTC(y, mo - 1, d, h, mi, sec)
} elseif (k === 'BYDAY') {
r.byday = v.split(',').map((d) => {
if (!DAYS.includes(d))
thrownew Error(`BYDAY ${d} is not a day`)
return DAYS.indexOf(d)
})
} elseif (k === 'BYMONTHDAY') {
r.bymonthday = v.split(',').map(Number)
if (!r.bymonthday.every(isDay))
thrownew Error('BYMONTHDAY is 1 to 31')
} elsethrownew Error(`${k} is not supported`)
}
if (!r.freq) thrownew Error('FREQ is required')
if (r.count !== null && r.until !== null)
thrownew Error('COUNT and UNTIL cannot both appear')
return r
}
rrule.mjs: the rest of the parser.
Expanding a rule into dates
Expansion walks the rule in the event's own wall-clock time, then turns each date into an instant with the zone. The order matters. If you add 24 hours to an instant for each step, the series drifts by an hour at every clock change. The generator below makes local dates only, and a monthly rule on the 31st simply skips months without a 31st. RFC 5545 says an instance on an invalid date, or at a local time that does not exist, must be skipped and not counted, and the generator follows that unless a series asks to shift.
js
const day = (ms) => {
const d = new Date(ms)
return {
y: d.getUTCFullYear(),
m: d.getUTCMonth() + 1,
d: d.getUTCDate(),
}
}
const addDays = (c, n) => day(Date.UTC(c.y, c.m - 1, c.d + n))
/** local dates the rule names, in order, from the start date */function* dates(rule, start) {
const s0 = Date.UTC(start.y, start.m - 1, start.d)
if (rule.freq === 'DAILY') {
for (let k = 0; k < LIMIT; k++)
yield addDays(start, k * rule.interval)
} elseif (rule.freq === 'WEEKLY') {
const days = rule.byday.length
? [...rule.byday]
: [new Date(s0).getUTCDay()]
const monday = addDays(start, -((new Date(s0).getUTCDay() + 6) % 7))
for (let k = 0; k < LIMIT; k++) {
for (const wd of days
.map((x) => (x + 6) % 7)
.sort((a, b) => a - b)) {
const c = addDays(monday, k * 7 * rule.interval + wd)
if (Date.UTC(c.y, c.m - 1, c.d) >= s0) yield c
}
}
rrule.mjs: local dates for daily and weekly rules.
js
} else {
const nums = rule.bymonthday.length
? [...rule.bymonthday].sort((a, b) => a - b)
: [start.d]
for (let k = 0; k < LIMIT; k++) {
const idx = start.m - 1 + k * rule.interval
const y = start.y + Math.floor(idx / 12),
m = (idx % 12) + 1for (const d of nums) {
if (!validDate(y, m, d)) continue// 31 Feb: no instanceif (Date.UTC(y, m - 1, d) >= s0) yield { y, m, d }
}
}
}
}
rrule.mjs: the monthly branch.
js
exportfunction expand(ev, from, to, cap = 5000) {
const rule = parseRule(ev.rrule)
const { y, m, d, h, mi } = parseWall(ev.start)
const time = ev.start.slice(11)
if (!(ev.minutes >= 0)) thrownew RangeError('bad length')
const skip = new Set(ev.exdates ?? [])
const out = []
let n = 0,
steps = 0for (const c of dates(rule, { y, m, d })) {
if (++steps > cap) breakconst wall = { ...c, h, mi }
const p2 = (n) => String(n).padStart(2, '0')
const key = `${c.y}-${p2(c.m)}-${p2(c.d)}T${time}`// RFC 5545: an instance at a time that does not exist is ignored// and not counted; 'shift' moves it later insteadif (ev.gap !== 'shift' && instantsFor(wall, ev.tz).length === 0)
continueconst start = toInstant(wall, ev.tz)
if (rule.until !== null && start > rule.until) breakif (rule.count !== null && n >= rule.count) breakif (start >= to) break
n++
if (skip.has(key) || start < from) continue
out.push({ key, start, end: start + ev.minutes * 60000 })
}
return out
}
rrule.mjs: from dates to instants, inside a window.
expand takes a window, because a calendar view never needs more than its own range. It stops at COUNT, at UNTIL and at the end of the window, counts an instance before the list of deleted ones is applied, as the RFC says deleted dates are removed from the set, and uses toInstant from the next lesson.
Running the rules
The script expands six rules, and then tries seven rules and two events that must be refused.
text
weekly Mon+Wed 09:00 New York, across the March change
2026-03-04T09:00 -> 2026-03-04T14:00Z
2026-03-09T09:00 -> 2026-03-09T13:00Z
2026-03-11T09:00 -> 2026-03-11T13:00Z
2026-03-16T09:00 -> 2026-03-16T13:00Z
2026-03-18T09:00 -> 2026-03-18T13:00Z
the same in Kolkata
2026-03-04T09:00 -> 2026-03-04T03:30Z
2026-03-09T09:00 -> 2026-03-09T03:30Z
2026-03-11T09:00 -> 2026-03-11T03:30Z
monthly on the 31st
2026-01-31T10:00 -> 2026-01-31T04:30Z
2026-03-31T10:00 -> 2026-03-31T04:30Z
2026-05-31T10:00 -> 2026-05-31T04:30Z
2026-07-31T10:00 -> 2026-07-31T04:30Z
2026-08-31T10:00 -> 2026-08-31T04:30Z
Output (Node 24)
text
daily 02:30 New York; 8 Mar has no 02:30; EXDATE on the 9th
2026-03-07T02:30 -> 2026-03-07T07:30Z
2026-03-10T02:30 -> 2026-03-10T06:30Z
2026-03-11T02:30 -> 2026-03-11T06:30Z
the same, with the missing time moved later
2026-03-07T02:30 -> 2026-03-07T07:30Z
2026-03-08T02:30 -> 2026-03-08T07:30Z
2026-03-10T02:30 -> 2026-03-10T06:30Z
every 2 weeks until a date
2026-05-04T18:00 -> 2026-05-04T12:30Z
2026-05-18T18:00 -> 2026-05-18T12:30Z
2026-06-01T18:00 -> 2026-06-01T12:30Z
2026-06-15T18:00 -> 2026-06-15T12:30Z
a rule with no end, asked for one window
2027-06-01T08:00 -> 2027-06-01T02:30Z
2027-06-02T08:00 -> 2027-06-02T02:30Z
2027-06-03T08:00 -> 2027-06-03T02:30Z
Output (Node 24), continued
text
bad rules
FREQ=WEEKLY;COUNT=3;UNTIL=20261231T000000Z
-> COUNT and UNTIL cannot both appear
INTERVAL=2
-> FREQ is required
FREQ=DAILY;INTERVAL=0
-> INTERVAL must be a positive whole number
FREQ=DAILY;FREQ=WEEKLY
-> FREQ appears twice
FREQ=YEARLY
-> FREQ=YEARLY is not supported
FREQ=WEEKLY;BYDAY=XX
-> BYDAY XX is not a day
FREQ=DAILY;UNTIL=2026-12-31
-> UNTIL must look like 20261231T180000Z
bad events
2026-02-30T09:00
-> no such date
2026-03-0409:00
-> use YYYY-MM-DDTHH:mm
Output (Node 24), rules and events that must be refused
The weekly Monday and Wednesday meeting in New York ran at 14:00 UTC on the first date and at 13:00 UTC after 8 March, when the clocks moved. The same rule in Kolkata stayed at 03:30 UTC. The monthly event on the 31st skipped February, April and June, without counting them. The daily rule at 02:30 in New York has no instance on 8 March, because 02:30 did not exist that day. RFC 5545 says such an instance must be ignored and not counted, so the series went from the 7th to the 10th, with the deleted 9th left out. People often expect the meeting to appear anyway, so this code lets a series ask for gap: "shift", which is not in the RFC, and the 8th then appears at 07:30 UTC, which is 03:30 on the clock. The RFC also asks that the start match the rule and counts it as the first instance. This expander begins at the first date the rule names on or after the start, so a weekly Monday rule that starts on a Wednesday gives its first instance on the next Monday.
The tests pin each of these down with node:test.
text
✔ COUNT stops the series
✔ INTERVAL skips periods
✔ the 31st skips short months and does not count them
✔ EXDATE removes one instance
✔ a window cuts an endless rule
✔ a wall time in New York keeps its hour across the change
✔ a time that does not exist is skipped, or moved on request
✔ a duration is kept in absolute time
✔ a rule that can never match ends
✔ bad rules throw
✔ an event that starts on a date that does not exist throws
ℹ tests 11
ℹ pass 11
ℹ fail 0
Output (Node 24)
Two tests were added after bugs. The first: a rule such as FREQ=MONTHLY;INTERVAL=12;BYMONTHDAY=31 from a February start never finds a valid date, and the first version looped for ever inside the generator, since only valid dates were counted. Running the script with a 5-second limit confirmed it. The fix is a cap on how many periods a generator may walk. After it, the same call returned no instances in a few milliseconds.
text
node never.mjs: still running after 5 seconds (stopped by timeout, exit
code 124)
Before the fix
text
instances: 0 in 3 ms
After the fix (Node 24)
The second came from a probe. An event that started on 2026-02-30T09:00 was accepted, and its series began on 2 March, because the date arithmetic rolled the day over. expand now reads the start with the strict reader from the next lesson, which refuses it, as the last two lines of the run show.
Where each piece of state lives
State
Home
Why
Events and their rules
server, cached on the client by range
the server is the source of truth
Expanded instances for the view
derived on the client, never stored
they are cheap to recompute and change with the view
Visible range and view kind
the URL, for example /week/2026-03-02
links and Back work
Viewer's zone and first day of week
user setting, with the browser as default
a person may differ from the browser
An event being dragged
local UI state
it is not saved until it is dropped
Why is a 9:00 meeting in New York stored as a wall-clock time and a zone, not as an instant?
It should stay at 9:00 when the clocks change: in the run the same rule gave 14:00 UTC before 8 March and 13:00 UTC after.
A stored instant would drift by an hour.
A monthly rule on the 31st starts in January. What does it do in February, and does that use up a COUNT?
It skips February: there is no 31 February. A skipped date is not counted, so COUNT=5 still gave five real instances in the run.
Why does the generator have a cap on how many periods it walks?
A rule such as every 12 months on the 31st from a February start never finds a date, and without the cap the first version looped for ever.
Part 3 · Time zones and daylight saving
A zone is a set of rules; an offset is one answer
A time zone, in the sense of the IANA database that browsers use, is a name such as Asia/Kolkata plus the history of the rules for it. An offset is a single answer from those rules for one instant, for example +5:30. In Kolkata the offset is the same all year, while in New York it is -5:00 in January and -4:00 in July. The rule that moves between the two is daylight saving time, and it makes some days 23 hours long, some 25, and some local times impossible or doubled.
Per MDN, Intl.DateTimeFormat takes a timeZone option with an IANA name, so the page does not need to ship a zone table of its own. That gives us a way to ask what the clock reads in a zone at an instant. The helper parts caches one formatter per zone and returns the numbers, and offsetAt compares what the zone's clock reads with the instant in UTC. validDate is the guard we need whenever a date is typed.
js
// zones.mjs: wall-clock times in a named zone, without Temporal.const fmt = new Map()
const parts = (ms, tz) => {
let f = fmt.get(tz)
if (!f) {
f = new Intl.DateTimeFormat('en-CA', {
timeZone: tz,
hourCycle: 'h23',
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
})
fmt.set(tz, f)
}
const o = {}
for (const p of f.formatToParts(ms)) o[p.type] = +p.value
return o
}
zones.mjs: what a zone's clock reads at an instant.
js
/** minutes east of UTC that the zone uses at this instant */exportfunction offsetAt(ms, tz) {
const p = parts(ms, tz)
const asUtc = Date.UTC(
p.year,
p.month - 1,
p.day,
p.hour,
p.minute,
p.second,
)
return Math.round((asUtc - Math.floor(ms / 1000) * 1000) / 60000)
}
/** a date that really exists (Date.parse rolls 30 Feb over) */exportfunction validDate(y, m, d) {
const t = new Date(Date.UTC(y, m - 1, d))
return (
t.getUTCFullYear() === y &&
t.getUTCMonth() === m - 1 &&
t.getUTCDate() === d
)
}
zones.mjs: the offset at an instant, and real dates.
From a wall-clock time to an instant
The other direction is the hard one: given 2:30 in the morning on a date in New York, which instant is it? There may be one, none or two. instantsFor tries the offsets in use a day before and a day after, and keeps every candidate whose clock really reads the wanted time. toInstant then chooses, with the same four rules as Temporal: for a time that does not exist, compatible and later move forward by the length of the gap, earlier moves back by it, and reject throws. Any other word throws too. For a doubled time, compatible and earlier take the first, later takes the second.
js
/** every instant whose wall clock reads w in tz: none, one or two */exportfunction instantsFor(w, tz) {
if (
!validDate(w.y, w.m, w.d) ||
w.h < 0 ||
w.h > 23 ||
w.mi < 0 ||
w.mi > 59
) {
thrownew RangeError('not a real date and time')
}
const guess = Date.UTC(w.y, w.m - 1, w.d, w.h, w.mi)
const found = new Set()
for (const probe of [guess - 864e5, guess + 864e5]) {
const t = guess - offsetAt(probe, tz) * 60000const p = parts(t, tz)
if (
p.year === w.y &&
p.month === w.m &&
p.day === w.d &&
p.hour === w.h &&
p.minute === w.mi
)
found.add(t)
}
return [...found].sort((a, b) => a - b)
}
zones.mjs: every instant that reads this wall time.
js
/** one instant: gaps move later, overlaps take the earlier */exportfunction toInstant(w, tz, how = 'compatible') {
if (!['compatible', 'earlier', 'later', 'reject'].includes(how)) {
thrownew RangeError(`unknown disambiguation: ${how}`)
}
const c = instantsFor(w, tz)
if (c.length === 1) return c[0]
if (c.length === 2) {
if (how === 'reject')
thrownew RangeError('ambiguous wall-clock time')
return how === 'later' ? c[1] : c[0]
}
if (how === 'reject')
thrownew RangeError('wall-clock time does not exist')
const guess = Date.UTC(w.y, w.m - 1, w.d, w.h, w.mi)
// the offset in use before the gapconst before = offsetAt(guess - 864e5, tz)
const after = offsetAt(guess + 864e5, tz)
const t = guess - before * 60000// the gap is as long as the jump in offset, not always an hourreturn how === 'earlier' ? t - (after - before) * 60000 : t
}
exportconst wallOf = (ms, tz) => {
const p = parts(ms, tz)
return { y: p.year, m: p.month, d: p.day, h: p.hour, mi: p.minute }
}
zones.mjs: choose one, and read an instant back.
The script tries Kolkata and New York around both clock changes of 2026, and then the inputs that should fail.
text
offset, minutes east of UTC
Kolkata, any day : 330330
New York, 1 Jan, 1 Jul : -300 -2409:00 on a weekday, as UTC
New York, 6 Mar 2026-03-06T14:00Z
New York, 9 Mar 2026-03-09T13:00Z
Kolkata, 6 Mar 2026-03-06T03:30Z
2:30 on 8 Mar 2026 in New York (clocks jump 2:00 to 3:00)
compatible 2026-03-08T07:30Z reads 3:30
earlier 2026-03-08T06:30Z reads 1:30
later 2026-03-08T07:30Z reads 3:30
reject RangeError: wall-clock time does not exist
1:30 on 1 Nov 2026 in New York (clocks go back 2:00 to 1:00)
compatible 2026-11-01T05:30Z
earlier 2026-11-01T05:30Z
later 2026-11-01T06:30Z
reject RangeError: ambiguous wall-clock time
bad input
Date.parse('2026-02-30') : 2026-03-02
validDate(2026, 2, 30) : false
validDate(2028, 2, 29) : true
validDate(2026, 13, 1) : false
hour 24 -> RangeError: not a real date and time
30 Feb -> RangeError: not a real date and time
unknown zone -> RangeError: Invalid time zone specified: Mars/Base
typo in choice -> RangeError: unknown disambiguation: laeter
Output (Node 24)
Nine in the morning in New York is 14:00 UTC before the change and 13:00 after, and Kolkata is 03:30 UTC in both. At 2:30 on 8 March, which does not exist, compatible gave 07:30 UTC, which reads 3:30 on the clock. At 1:30 on 1 November, which happens twice, compatible gave 05:30 UTC, the first one. For a single date and time with a zone, RFC 5545 agrees: a doubled time means the first occurrence, and a missing one uses the offset from before the gap.
The bad-input lines matter as much. Date.parse('2026-02-30') did not fail. It returned 2 March, because V8 rolls the day over, and our validDate rebuilds the date and compares, so 30 February is refused. An hour of 24 is refused, a misspelt choice such as laeter is refused, and an unknown zone throws a RangeError from Intl. The first version took a misspelt choice as compatible without a word.
Checking against Temporal
Hand-written zone code deserves a second opinion. Temporal is the new date and time API in JavaScript, and its ZonedDateTime is built for exactly this. MDN lists it as having limited availability, not Baseline, because it does not work in some widely used browsers. It was present in Chrome 157 here and absent in Node 24, so the check runs in the browser. The page cross-checks toInstant against Temporal.ZonedDateTime.from with all three choices, for every quarter hour on the day before, of and after each clock change from 2025 to 2028 in six zones, and shows a day arithmetic example. One zone is Lord Howe Island, whose clocks move by 30 minutes, not an hour.
// every quarter hour of every day around each clock change, 2025-2028
const tally = { checked: 0, gaps: 0, overlaps: 0, mismatches: 0 }
for (const tz of zones) {
let prev = offsetAt(Date.UTC(2025, 0, 1), tz)
for (let day = 0; day < 4 * 366; day++) {
const t = new Date(Date.UTC(2025, 0, 1 + day))
const now = offsetAt(t.getTime() + 864e5, tz)
if (now === prev) continue
prev = now
for (const dd of [-1, 0, 1]) {
const c = new Date(Date.UTC(2025, 0, 1 + day + dd))
for (let q = 0; q < 96; q++) {
const x = w(
c.getUTCFullYear(),
c.getUTCMonth() + 1,
c.getUTCDate(),
Math.floor(q / 4),
(q % 4) * 15,
)
for (const how of ['compatible', 'earlier', 'later']) {
tally.checked++
if (
toInstant(x, tz, how) !==
viaTemporal(x, tz, how).epochMilliseconds
)
tally.mismatches++
}
temporal.html: the check, first part.
html
const n = instantsFor(x, tz).length
if (n === 0) tally.gaps++
if (n === 2) tally.overlaps++
let threw = false
try {
viaTemporal(x, tz, 'reject')
} catch {
threw = true
}
if (threw !== (n !== 1)) tally.mismatches++
}
}
}
}
out.push(JSON.stringify(tally))
temporal.html: the check, second part.
text
Chrome 157
Temporal in this browser: object
New York: gap is 2:30 on 8 Mar, overlap is 1:30 on 1 Nov
gap compatible 2026-03-08T03:30:00-04:00
gap earlier 2026-03-08T01:30:00-05:00
gap later 2026-03-08T03:30:00-04:00
gap reject Temporal error: Rejecting ambiguous time zones.
overlap compatible 2026-11-01T01:30:00-04:00
overlap earlier 2026-11-01T01:30:00-04:00
overlap later 2026-11-01T01:30:00-05:00
overlap reject Temporal error: Rejecting ambiguous time zones.
{"checked":34560,"gaps":72,"overlaps":72,"mismatches":0}
9:00 Sat 7 Mar + 1 day : 2026-03-08T09:00:00-04:00[America/New_York]
9:00 Sat 7 Mar + 24 hours: 2026-03-08T10:00:00-04:00[America/New_York]
hours in 8 Mar in New York: 23
America/New_York 8 Mar, 3:30 am GMT-4
Asia/Kolkata 8 Mar, 1:00 pm GMT+5:30
Australia/Sydney 8 Mar, 6:30 pm GMT+11
Node says: undefined
Output (Chrome 157)
The eight rows of answers are Temporal's own for the two awkward times, and they match the values computed by our helper in the previous run: 3:30 for a gap, 1:30 earlier and later in the overlap. The summary line says 34,560 checks with 72 times that did not exist and 72 that happened twice, and no mismatch with Temporal, including that reject throws for exactly those 144 cases. The first version of toInstant had 8 mismatches, all in Lord Howe with earlier: it moved back by a fixed hour, where the gap is 30 minutes. It now takes the gap from the change in offset.
The next lines show why the day is not 24 hours. Adding one day to 9:00 on Saturday 7 March gives 9:00 on Sunday, while adding 24 hours gives 10:00, and 8 March has 23 hours in New York. A week view that draws 24 equal rows on that day is wrong, and a "same time tomorrow" button must add days, not hours. The last three lines format one instant in three zones, with the offset shown, using Intl.DateTimeFormat.
Dates typed by people
Time zones are one source of bad data and typed input is another. A person, or a pasted link, can supply a date that does not exist. The reader below accepts one shape only, YYYY-MM-DDTHH:mm, and rejects the rest by name, so that the form can say which part was wrong.
js
// wall.mjs: read a date and time typed by a person, strictly.import { validDate } from'./zones.mjs'exportfunction parseWall(text) {
const m = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})$/.exec(text)
if (!m) thrownew RangeError('use YYYY-MM-DDTHH:mm')
const [y, mo, d, h, mi] = m.slice(1).map(Number)
if (!validDate(y, mo, d)) thrownew RangeError('no such date')
if (h > 23 || mi > 59) thrownew RangeError('no such time')
return { y, m: mo, d, h, mi }
}
wall.mjs: read a typed date and time strictly.
text
"2026-03-02T09:00" ok, 2026-03-02T14:00Z
"2026-02-30T09:00" RangeError: no such date
"2026-04-31T09:00" RangeError: no such date
"2028-02-29T09:00" ok, 2028-02-29T14:00Z
"2026-13-01T09:00" RangeError: no such date
"2026-03-02T24:00" RangeError: no such time
"2026-3-2T9:00" RangeError: use YYYY-MM-DDTHH:mm
"2026-03-02 09:00" RangeError: use YYYY-MM-DDTHH:mm
"2026-03-02T09:00:00Z" RangeError: use YYYY-MM-DDTHH:mm
"" RangeError: use YYYY-MM-DDTHH:mm
Date.parse('2026-04-31') : 2026-05-01
Date.parse('2026-13-01') : NaN
Output (Node 24)
The 29th of February 2028 was accepted, because 2028 is a leap year, and 31 April and 30 February were refused. Hour 24 was refused, and so were shapes with a single-digit month or a space in place of the T. At the bottom, Date.parse for 31 April quietly returned 1 May and, for month 13, NaN. The run shows why every date the calendar reads goes through its own check first.
The nonexistent local time is handled one step later and not here. A string such as 2026-03-08T02:30 is a valid date and time in New York terms and only the zone makes it a gap, so toInstant decides, and the form should show the time that was used.
A recurring event is saved as 9:00 in New York. After the clocks change, what has changed in its UTC time, and what has not?
The UTC time moved from 14:00 to 13:00, because the zone's offset changed.
The wall-clock time, 9:00, did not change, and that is what the owner meant.
Date.parse('2026-04-31') returned 1 May in the run. What should the form do instead?
Rebuild the date from its parts and compare, as validDate does, and refuse 31 April by name.
In the Temporal check, 72 wall-clock times did not exist and 72 happened twice. How should a calendar treat each when a person types one?
Use a stated rule such as compatible and show the time that was actually used.
For a time that happens twice, ask or take the first, and say so.
Part 4 · Deep dive: the week view
Putting overlapping events side by side
A week view draws each day as a column of 24 hours, and an event is a box whose top and height come from its start and length. With one event at a time this is easy. When two events overlap, the boxes must share the width, and the rule for sharing has to be one that people read correctly: no event hidden, and events that only touch (one ends at 10:00 and the next starts at 10:00) kept at full width.
The method has two steps. First, group the events into clusters: runs of events where each overlaps the next, so that a cluster can be laid out alone. Second, within a cluster, give each event the first column that is free when it starts, and make a new column only when none is. Every event in a cluster then gets the same width, one over the number of columns that cluster used.
js
// layout.mjs: put one day's overlapping events side by side.exportconst MIN_MINUTES = 15exportfunction layoutDay(events) {
const evs = events
.map((e) => {
if (!(e.end >= e.start))
thrownew RangeError(`event ${e.id} ends before it starts`)
return { ...e, end: Math.max(e.end, e.start + MIN_MINUTES) }
})
.sort(
(a, b) =>
a.start - b.start || b.end - a.end || (a.id < b.id ? -1 : 1),
)
const out = []
let cluster = [],
clusterEnd = -Infinity
const flush = () => {
const cols = Math.max(0, ...cluster.map((e) => e.col + 1))
for (const e of cluster) out.push({ id: e.id, col: e.col, cols })
cluster = []
}
let colEnds = [] // when each column becomes free
layout.mjs: sort the events, start the clusters.
js
for (const e of evs) {
if (e.start >= clusterEnd) {
flush()
colEnds = []
clusterEnd = -Infinity
}
let col = colEnds.findIndex((end) => end <= e.start)
if (col < 0) col = colEnds.length
colEnds[col] = e.end
cluster.push({ ...e, col })
clusterEnd = Math.max(clusterEnd, e.end)
}
flush()
return out
}
layout.mjs: give each event a column.
The columns, step by step
Take a three-hour workshop with three short calls inside it. Sorted by start time the order is the workshop, the first call, the third call and the second call. The scene shows the free-time of each column as it goes.
Animated sceneAssigning columns to a cluster0:17
Watch for a column being freed when its event ends
Read it as steps
Each event takes the first column that is free when it starts.
The last step shows the touching rule at work: call 2 started at 11:00 and column 2 became free at 11:00, so an event that starts exactly when another ends does not need a new column. The script then runs the function on four sets, and on a property check of 2,000 random days.
text
two overlap, one is later
standup column 1 of 2
review column 2 of 2
lunch column 1 of 1
touching is not overlapping
a column 1 of 1
b column 1 of 1
a long event and two short ones
workshop column 1 of 3
call1 column 2 of 3
call3 column 3 of 3
call2 column 2 of 3
identical times, and zero length
x column 1 of 3
y column 2 of 3
ping column 3 of 3
bad: event bad ends before it starts
2000 random days: no clashes in 9370 overlapping pairs
Output (Node 24)
The three calls and the workshop each got one of three columns. Two events with identical times took two columns. A zero-length event, a reminder, was given a minimum of 15 minutes so that it can be seen and clicked, and it sat in a third column beside the two. An event that ends before it starts was refused. The property check compared every overlapping pair on 2,000 random days, 9,370 pairs, and found no two in the same column.
Events that cross midnight, and days that are not 24 hours
Each day is its own column, so an event that crosses midnight has to be cut into one piece for each day it touches. The cut must be made at local midnight in the viewer's zone, not at a fixed 1,440 minutes, because on the days the clocks change the day has 1,380 or 1,500 minutes. The pieces are measured in elapsed minutes since local midnight, and the day's own length is returned with each piece so that the grid can scale.
js
// split.mjs: cut an event into the local days it touches.import { toInstant, wallOf } from'./zones.mjs'const midnight = (w, tz) =>
toInstant({ y: w.y, m: w.m, d: w.d, h: 0, mi: 0 }, tz)
const nextDay = (w) => {
const t = new Date(Date.UTC(w.y, w.m - 1, w.d + 1))
return {
y: t.getUTCFullYear(),
m: t.getUTCMonth() + 1,
d: t.getUTCDate(),
}
}
split.mjs: local midnight, and the next day.
js
/** pieces of [start, end): minutes since local midnight, per day */exportfunction splitByDay(start, end, tz) {
if (!(end >= start)) thrownew RangeError('ends before it starts')
if (!(end - start <= 366 * 864e5)) {
thrownew RangeError('longer than a year')
}
const out = []
let at = start
do {
const w = wallOf(at, tz)
const open = midnight(w, tz)
const close = midnight(nextDay(w), tz)
const to = Math.min(end, close)
const p2 = (n) => String(n).padStart(2, '0')
out.push({
date: `${w.y}-${p2(w.m)}-${p2(w.d)}`,
from: (at - open) / 60000,
to: (to - open) / 60000,
dayMinutes: (close - open) / 60000,
})
at = to
} while (at < end)
return out
}
split.mjs: cut an event into local days.
text
Kolkata, Monday 22:00 to Tuesday 02:002026-03-02 from 1320 to 1440 of 1440 minutes
2026-03-03 from 0 to 120 of 1440 minutes
New York, Sat 22:00 to Sun 06:00 over the March change
2026-03-07 from 1320 to 1440 of 1440 minutes
2026-03-08 from 0 to 300 of 1380 minutes
New York, Sun 1 Nov 00:30 to 03:00 (a 25 hour day)
2026-11-01 from 30 to 240 of 1500 minutes
ends exactly at midnight
2026-03-02 from 1380 to 1440 of 1440 minutes
zero length
2026-03-02 from 540 to 540 of 1440 minutes
three days
2026-03-02 from 1080 to 1440 of 1440 minutes
2026-03-03 from 0 to 1440 of 1440 minutes
2026-03-04 from 0 to 540 of 1440 minutes
end before start: RangeError: ends before it starts
an end of Infinity: RangeError: longer than a year
ten years: RangeError: longer than a year
Output (Node 24)
The Kolkata event produced 120 minutes on each day. The New York event from Saturday 22:00 to Sunday 06:00 was only 7 hours long, since the clocks jumped forward in between: 120 minutes on the Saturday and 300 on a Sunday that has 1,380 minutes. The event on 1 November began 30 minutes after midnight and ended at 240 minutes, because the day has 1,500 minutes and 3:00 on the clock is 210 minutes after 00:30. An event that ends exactly at midnight did not spill onto the next day, a zero-length event gave one empty piece, and an end before the start was refused. An end of Infinity made the first version loop for ever, building pieces until the process was killed. A span longer than 366 days is now refused.
All-day events are a different thing. They are dates, so they are drawn in a banner above the grid and are never cut or converted, and an all-day event on 8 March is one day, not 23 hours.
Why do the events that only touch, one ending at 10:00 and one starting at 10:00, get a full-width column each?
A column is free again at the moment its event ends, so an event that starts then can reuse it. The run showed a and b each in column 1 of 1.
What does the property check prove, and what does it not?
It shows that on 2,000 random days no two overlapping events shared a column, over 9,370 overlapping pairs.
It does not prove the layout looks good, only that nothing is hidden.
Why is the day cut at local midnight rather than every 1,440 minutes?
On 8 March in New York the day has 1,380 minutes, and on 1 November it has 1,500, as the run showed.
A fixed cut would put the piece on the wrong day.
Part 5 · Deep dive: moving and resizing events
Pointer events, and the states of a drag
Dragging an event is the interaction people expect from a calendar, and it has more states than it seems. HTML has a drag and drop API: per MDN, an element becomes draggable with the draggable attribute, data can be stored only in the dragstart handler, and a drop target must cancel dragover. It was built for moving data between places, not for snapping to a 15-minute step. This design uses pointer events instead: pointerdown, pointermove, pointerup and pointercancel cover mouse, touch and pen in one model.
Two details keep a pointer drag working. setPointerCapture makes the element receive the pointer's events until capture is released, which MDN says happens automatically at pointerup, so the drag continues when the pointer leaves the element or the window. And touch-action: none on the event boxes disables the browser's own panning and zooming there; without it the browser can take over a touch gesture and send pointercancel. MDN warns that this can stop people zooming, so it goes on the boxes only, not on the page. The states of a drag are shown below.
Animated sceneThe states of a drag0:16
Watch for Escape ending a drag that was already moving
Read it as steps
A drag is cancelled by Escape, and cancelling is final.
A drag as a small session
The drag logic is kept out of the page, so it can be tested without a browser. moved gives the landing place after some minutes of movement: it snaps to 15 minutes, keeps the event inside the day, and keeps a minimum length when resizing. session is the state machine of the scene, holding the event as it was picked up.
js
// drag.mjs: moving and resizing an event (pointer and keyboard).exportconst SNAP = 15,
DAY = 1440,
MIN = 15const clamp = (v, lo, hi) => Math.min(Math.max(v, lo), hi)
const snap = (m) => Math.round(m / SNAP) * SNAP
/** where an event would land after `deltaMin` minutes of movement */exportfunction moved(ev, kind, deltaMin) {
if (!Number.isFinite(deltaMin))
return { start: ev.start, end: ev.end }
const len = ev.end - ev.start
if (kind === 'move') {
const start = clamp(snap(ev.start + deltaMin), 0, DAY - len)
return { start, end: start + len }
}
const end = clamp(snap(ev.end + deltaMin), ev.start + MIN, DAY)
return { start: ev.start, end }
}
drag.mjs: where an event lands.
js
exportfunction session(ev, kind, pxPerHour = 40, slop = 4) {
// the event as it was when picked upconst base = { start: ev.start, end: ev.end }
let state = 'pressed',
draft = nullconst live = () => state === 'pressed' || state === 'dragging'return {
get state() {
return state
},
get draft() {
return draft
},
drag(deltaPx) {
if (!live()) returnfalseif (state === 'pressed' && Math.abs(deltaPx) < slop) returnfalse
state = 'dragging'
draft = moved(base, kind, (deltaPx * 60) / pxPerHour)
returntrue
},
drag.mjs: the session, and its drag.
js
drop() {
if (!live()) returnnull// no drag at all means it was a clickconst result = state === 'dragging' ? draft : null
state = state === 'dragging' ? 'dropped' : 'idle'return result
},
cancel() {
if (live()) {
state = 'cancelled'
draft = null
}
},
}
}
drag.mjs: drop and cancel.
The script feeds moved some extreme values and then walks a session through a cancel and a click.
text
move 49.5 min (33 px) 09:45 - 10:45
move 7 min 09:00 - 10:00
move up 20 hours 00:00 - 01:00
move down 20 hours 23:00 - 24:00
resize, drag up 3 hours 09:00 - 09:15
resize, drag down 45 min 09:00 - 10:45
move by NaN 09:00 - 10:00
press: pressed
2 px: pressed
40 px: dragging, draft 10:00
Escape: cancelled, draft null
drop after cancel: null
click without a drag: drop gives null, state idle
Output (Node 24)
A 49.5-minute move landed on 09:45, the nearest quarter hour, and 7 minutes snapped back to 09:00. Twenty hours up or down stopped at the edges of the day, and dragging the bottom edge up past the top left the minimum 15 minutes. A move by NaN changed nothing. After Escape the session was cancelled with no draft and a later drop returned nothing, and a press and release with no drag was a click.
In the page, and a bug the run found
The page has a column for each day, a box for each event, and a status region. Each box has touch-action: none and a thin grip along its bottom edge for resizing.
<div id="week" role="group" aria-label="Week of 2 March 2026"></div>
<div id="status" role="status" aria-live="polite"></div>
<script type="module" src="/week.mjs"></script>
week.html: the markup.
The code that draws an event takes its top and height from its minutes, and its left and width from the column layout of the previous lesson. It runs again after every change.
js
exportfunction render() {
days.forEach((_, d) => {
const here = events.filter((e) => e.day === d)
for (const l of layoutDay(here)) {
const e = events.find((x) => x.id === l.id)
let b = nodes.get(e.id)
if (!b) {
b = document.createElement('button')
b.className = 'ev'
b.innerHTML = '<span></span><i class="grip"></i>'
b.dataset.id = e.id
nodes.set(e.id, b)
}
if (b.parentNode !== cols[d]) cols[d].append(b)
b.firstChild.textContent = `${e.id} ${hm(e.start)}-${hm(e.end)}`
b.setAttribute(
'aria-label',
`${e.id}, ${days[d]}, ${hm(e.start)} to ${hm(e.end)}`,
)
Object.assign(b.style, {
top: `${(e.start * PX) / 60}px`,
height: `${((e.end - e.start) * PX) / 60}px`,
left: `${(l.col / l.cols) * 100}%`,
width: `${100 / l.cols}%`,
})
b.dataset.state = b.dataset.state || 'idle'
}
})
}
week.mjs: draw each day with the layout.
Pointer handlers start a session on pointerdown with capture, feed it the distance moved, apply the draft, and finish on pointerup, pointercancel, a lost capture or Escape.
js
// pointer: move from the body, resize from the grip at the bottomlet active = null
host.addEventListener('pointerdown', (e) => {
const b = e.target.closest('.ev')
if (!b || e.button !== 0) returnconst ev = events.find((x) => x.id === b.dataset.id)
active = {
b,
ev,
y0: e.clientY,
s: session(ev, e.target.matches('.grip') ? 'resize' : 'move'),
}
b.setPointerCapture(e.pointerId)
})
host.addEventListener('pointermove', (e) => {
if (!active || !active.s.drag(e.clientY - active.y0)) return
active.b.dataset.state = 'dragging'
Object.assign(active.ev, active.s.draft)
render()
})
week.mjs: press and move.
js
const finish = (cancelled) => {
if (!active) returnconst { b, ev, s, from } = active
if (cancelled) {
s.cancel()
Object.assign(ev, from)
} else s.drop()
b.dataset.state = 'idle'
active = null
render()
const when = `${hm(ev.start)} to ${hm(ev.end)}`
status.textContent = `${ev.id} ${s.state}: ${when}`
}
host.addEventListener('pointerdown', () => {
if (active)
active.from = { start: active.ev.start, end: active.ev.end }
})
host.addEventListener('pointerup', () => finish(false))
host.addEventListener('pointercancel', () => finish(true))
host.addEventListener('lostpointercapture', () => {
if (active && active.s.state === 'dragging') finish(true)
})
window.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && active) finish(true)
})
week.mjs: finish, or cancel.
What the Chrome run showed
The script uses real mouse input in Chrome 157: it presses on the first event, moves, releases, and reads the result. The first version had a bug that only a run could show. A drag of 33 pixels, about 50 minutes, put the stand-up at 12:00 instead of 09:45.
text
drag 33 px down: standup 12:00-12:30 left 0% width 100% | standup
dropped: 12:00 to 12:30
drag 80 px, then Escape: during standup 19:00-19:30 | after standup
12:00-12:30
First run: a drag that went too far
The cause was that session calculated from the live event, which the page was already moving on each pointermove, so every move added to the last one. The fix is the base copy at the top of session, which the code above already has. After it the same drag gave 09:45.
text
Chrome 157
start
standup 09:00-09:30 column 1 of 2
review 09:15-10:15 column 2 of 21 drag standup 33 px down, release
standup 09:45-10:15 column 2 of 2
status: standup dropped: 09:45 to 10:152 drag 80 px, Escape, then release
during: standup 11:45-12:15 column 1 of 1
after: standup 09:45-10:15 column 2 of 23 drag design up and out of the window
design 00:00-02:00 column 1 of 14 pointercancel in the middle of a drag
lunch 12:00-13:00 column 1 of 1
status: lunch cancelled: 12:00 to 13:005 resize lunch from its grip, 20 px
lunch 12:00-13:30 column 1 of 16 keyboard on review
Enter: Moving review. Arrow keys change the time, Enter drops, Escape
cancels.
ArrowDown twice: 09:45 to 10:45
Shift+ArrowDown: 09:45 to 11:00
Enter: review dropped: 09:45 to 11:00
Enter, ArrowUp, Escape: review put back: 09:45 to 11:00
name of review for a screen reader: review, Mon 2 Mar, 09:45 to 11:00
Output (Chrome 157)
In case 1 the stand-up moved to 09:45 and took the second column next to the review. In case 2 the event followed the pointer to 11:45, Escape put it back to 09:45, and the release did nothing. In case 3 the pointer went above the window and the event stopped at 00:00, because capture kept the events coming. A synthetic pointercancel in case 4 put the lunch back, and the grip in case 5 added 30 minutes.
The keyboard, and a month grid
A drag with no keyboard route fails anyone who cannot use a pointer. The design adds a move mode. The event is a button. Enter picks it up, the arrow keys move it by 15 minutes, Shift with an arrow resizes it, Enter drops it and Escape puts it back, with the status region saying what is happening. The same moved function does the arithmetic. The last lines of the run above show it, and the event's accessible name carries its day and time.
A month view is a grid of days, and the WAI-ARIA authoring practices describe a pattern for grids: roles grid, row and gridcell, one cell in the tab order, arrow keys between cells, Home and End to the ends of the row, and Ctrl with them to the first and last cell, which this design reads as the first and last day of the month. Page Up and Page Down move by an amount the author chooses, here one month. The date arithmetic is the part that goes wrong, so it is a pure function with its own run.
js
/** the same day number in another month, held to the month's length */exportfunction addMonths(s, n) {
const { y, m, d } = parse(s)
const i = y * 12 + (m - 1) + n
const ny = Math.floor(i / 12),
nm = (i % 12) + 1return`${ny}-${pad(nm)}-${pad(Math.min(d, daysInMonth(ny, nm)))}`
}
monthgrid.mjs: a month later, held to its length.
js
/** firstDay as in Intl: 1 is Monday, 7 is Sunday */exportfunction move(s, key, { ctrl = false, firstDay = 7 } = {}) {
const { y, m } = parse(s)
const weekday = new Date(`${s}T00:00:00Z`).getUTCDay() // 0 is Sundayconst col = ((((weekday || 7) - firstDay) % 7) + 7) % 7// 0 to 6switch (key) {
case'ArrowLeft':
return days(s, -1)
case'ArrowRight':
return days(s, 1)
case'ArrowUp':
return days(s, -7)
case'ArrowDown':
return days(s, 7)
case'Home':
return ctrl ? `${y}-${pad(m)}-01` : days(s, -col)
case'End':
return ctrl
? `${y}-${pad(m)}-${pad(daysInMonth(y, m))}`
: days(s, 6 - col)
case'PageUp':
return addMonths(s, -1)
case'PageDown':
return addMonths(s, 1)
default:
return s
}
}
The arrow keys cross month and year ends. Home and End follow the first day of the week, Sunday for the first call and Monday for the second. Page Down from 31 January gave 28 February, and 29 February in the leap year 2028.
html
function render() {
const [y, m] = focus.split('-').map(Number)
document.getElementById('title').textContent =
new Intl.DateTimeFormat('en-IN', {
month: 'long',
year: 'numeric',
timeZone: 'UTC',
}).format(Date.UTC(y, m - 1, 1))
const first = new Date(Date.UTC(y, m - 1, 1))
const col = ((((first.getUTCDay() || 7) - FIRST) % 7) + 7) % 7
const rows = []
for (let r = 0; r < 6; r++) {
const cells = []
for (let c = 0; c < 7; c++) {
const t = new Date(Date.UTC(y, m - 1, 1 - col + r * 7 + c))
const iso = t.toISOString().slice(0, 10)
cells.push(`<td role="gridcell" data-date="${iso}"
tabindex="${iso === focus ? 0 : -1}"
aria-label="${label.format(t)}">${t.getUTCDate()}</td>`)
}
rows.push(`<tr role="row">${cells.join('')}</tr>`)
}
grid.innerHTML = rows.join('')
}
month.html: the grid, with one tab stop.
text
Chrome 157
cells in the tab order: 1 of 42
Tab 2026-03-04 | month shown: March 2026
ArrowRight 2026-03-05 | month shown: March 2026
ArrowRight 2026-03-06 | month shown: March 2026
ArrowDown 2026-03-13 | month shown: March 2026
End 2026-03-14 | month shown: March 2026
Control+End 2026-03-31 | month shown: March 2026
ArrowRight 2026-04-01 | month shown: April 2026
PageDown 2026-05-01 | month shown: May 2026
PageUp 2026-04-01 | month shown: April 2026
Control+Home 2026-04-01 | month shown: April 2026
ArrowLeft 2026-03-31 | month shown: March 2026
label of the focused cell: Tuesday, 31 March 2026
Output (Chrome 157)
One of the 42 cells was in the tab order. Tab landed on it, and the arrow keys moved the focus and re-drew the grid when it crossed into April, and back. The focused cell's accessible name was the full date.
The first version of the drag put the stand-up at 12:00 after a 33 pixel drag. What was wrong?
The session calculated from the event the page was already moving, so every pointermove added to the previous one.
It must calculate from a copy of the event as it was picked up.
Why does the drag use setPointerCapture, and what did the run show?
The element keeps receiving pointer events after the pointer leaves it. In the run the pointer went above the window and the event stopped at 00:00 instead of freezing.
Page Down from 31 January gave 28 February. Why not 3 March?
The day number is held to the length of the target month, so the result stays in the next month, and 29 February in a leap year.
Part 6 · Deep dive: sync, conflicts and trade-offs
Two people, one event
The last deep dive is what happens when two people, or one person on two devices, change the same event. The server must not let the second save silently overwrite the first. HTTP has a tool for this. A response carries an ETag, a name for the current version of the resource; the performance chapter used one with If-None-Match to check a cache. A write carries If-Match with the ETag the client last saw. Per RFC 9110, an origin server that evaluates a false If-Match must not perform the method, and it may answer 412 Precondition Failed, the code for a condition in the request headers that tested false. The comparison is strong, so a weak tag never matches, and * matches any current version.
Animated sceneA stale write is refused0:17
Watch for the second write being refused instead of overwriting the first
Read it as steps
Two clients edit one event, and the second write answers 412.
Nothing was lost. The server's only job was to compare tags, and the 412 carried the current version of the event in its body, so the client did not need another request to find out what changed.
Merging, or asking
A 412 is not an error to show a person. In most cases the two edits touch different fields and can be combined. The rule is a three-way merge per field: take the version the client started from as the base. If the client did not change a field, take the server's value. If the server did not change it, take the client's. If both changed it to the same value, there is no problem. Only when both changed it differently is there a conflict that a person must settle. Answering an invitation is a small write to the attendee's own response, so it rarely meets one.
js
// edit.mjs: save with If-Match, and merge when someone else won.exportfunction merge(base, mine, theirs) {
const merged = { ...theirs }
const conflicts = []
for (const k ofnew Set([
...Object.keys(mine),
...Object.keys(theirs),
])) {
if (mine[k] === base[k]) continue// I did not touch it: take theirsif (theirs[k] === base[k] || theirs[k] === mine[k])
merged[k] = mine[k]
else conflicts.push(k) // both changed it, differently
}
return { merged, conflicts }
}
The server side is a small store with a version counter that becomes the ETag. A write without If-Match is refused with 428 Precondition Required, from RFC 6585, so a client cannot forget. A write whose end is not after its start is refused with a 422 even when the tag matches.
js
const match = req.headers['if-match']
if (!match) {
return send(res, 428, { error: { code: 'missing_if_match' } })
}
let raw = ''forawait (const c of req) raw += c
// If-Match: a list of tags or *; weak tags never matchconst tags = match.split(',').map((t) => t.trim())
if (!tags.some((t) => t === '*' || t === etag())) {
return send(res, 412, {
error: { code: 'changed' },
current: store.event,
})
}
The script plays the scene and then more cases against a real local server, including bad tags and bad bodies.
text
both clients hold "v1": Design review, 09:00-10:00
A renames it : saved, now "v2"
B, plain PUT with "v1": HTTP 412 changed
B moves it, merged: saved, "v3", Design review (moved), 11:00-12:00
both move it : conflict on start, end
the other copy : Design review (moved), 13:00-14:00
end before start : rejected end_before_start
no If-Match : HTTP 428
weak tag W/"v4" : HTTP 412 changed
tag list, one match: HTTP 200 saved
body is not JSON : HTTP 400 bad_json
unknown field id : HTTP 422 bad_fields
field is a number: HTTP 422 bad_fields
server is at version 5: Review, 13:00-14:00
Output (Node 24)
A renamed the event, and B, still holding version 1, got a 412 when it moved it. save merged the two edits, retried with the new tag and saved version 3 with both the new title and the new time. When two clients both moved the event to different times, the merge reported a conflict on start and end and showed the other copy, and nobody was overwritten. An end before the start was rejected on its own merits, and a write with no If-Match got a 428. A weak tag did not match and got a 412, a list of tags matched when one of them was current, and a body that is not JSON, an unknown field and a number in a text field were refused. The first version of the server crashed the whole process on the broken JSON and let a client change the event id, because the body was parsed without a guard and spread over the event as it came.
For offline edits the same rule applies at replay. A queued edit is sent with the ETag it was based on, and the answer decides whether it saves, merges or becomes a conflict to show. The outbox itself, with its storage and its replay, is the one from the chat chapter.
Checks and trade-offs
The checks, in the fixed order, one or two points each.
Check
What this design does
Performance
expand only the visible range; re-render a few boxes, not the page; cut the layout work to one pass per day
Accessibility
a button for each event with a name that includes its day and time; move mode and a status region; the month grid as one tab stop
Internationalisation
first day of week and weekend from Intl.Locale; month and day names from Intl.DateTimeFormat; Indian number and time formats
Security
event text is data and is shown with textContent; invite links are checked on the server; no secrets in the URL
Observability
log 412 and 422 rates, rule parse failures and zone errors, which show where the model is being misused
Choice
Alternative rejected
What it costs
Wall-clock time plus zone
store UTC instants only
every instance needs a zone lookup
Expand rules on the client, by range
the server returns every instance
rule code on the client, but small payloads
Pointer events with move mode
HTML drag and drop only
snapping and cancel are ours to build
If-Match with a merge
last write wins
a version on every write, and merge code
Cut events at local midnight
fixed 24-hour days
a day may be 23 or 25 hours long
A client sends a write with an old If-Match tag. What does the server answer, and what should the client do with it?
412 Precondition Failed. The client merges its change with the current event from the body and tries again, or shows a conflict.
Both clients moved the event to different times. Why can the merge not choose for them?
Both changed start and end away from the base, differently. A person must decide which time is right.
Why is the length of an event stored in elapsed minutes and the start as a wall-clock time and zone?
The start must stay at the same wall-clock time across clock changes. The length is a count of real minutes, so it is exact.