// datepicker.mjs — / → Date and Insert → Date… (build note 83): a month // at the caret (a selection's end: its words stay) with today, in the // viewer's zone, chosen. ← → move a day (once the field holds text they // move its caret), ↑ ↓ a week, Page Up and Page Down a month; ↵ inserts // the day's chip, [[2026-11-20]], the one [[ makes for a date; Esc // inserts nothing. A date typed in its field ("next friday", "12 nov") // moves to that day, read as ⌘K reads it (typeddate.mjs). A click or a // tap on a day inserts it. Where the chip would not read back as one // date link, commands.mjs's dateInsertion puts a space first, or the // picker says why no date can go there and does not open. // // The field is a combobox whose popup is the grid (ARIA 1.2): focus // stays in it and aria-activedescendant names the chosen day, as the // Page link field names its row. On a coarse pointer the picker takes // focus instead of the field, so a phone's keyboard goes down and the // month can be seen; a tap on the field brings the keyboard back. It // looks like the month calendar (links.css). import { dateInsertion, today as todayNow } from './commands.mjs' import { goTrimSpace } from './markup.mjs' import { dayLabel } from './resolutions.mjs' import { typedDate, iso } from './typeddate.mjs' import { firstDay, monthTitle as titleOf, order, weekHeads } from './dates.mjs' export const words = { dialog: 'Insert a date', field: 'Date', placeholder: 'Type a date, like next friday', help: 'Arrow keys move a day or a week, Page Up and Page Down a month. Enter inserts the day, Escape closes.', previous: 'Previous month', next: 'Next month', today: 'today', unknown: text => `“${text}” isn’t a date here. Try “next friday” or “12 nov”.` } // ── The arithmetic: pure, so Node tests it (datepicker.test.mjs). ── function utc (iso) { const [year, month, day] = iso.split('-').map(Number) const date = new Date(0) date.setUTCFullYear(year, month - 1, day) return date } // addDays is the day n days from date; null past the years ISO writes. export function addDays (date, n) { const day = utc(date) day.setUTCDate(day.getUTCDate() + n) return iso(day) || null } // addMonths keeps the day of the month, or the month's last day when // it has fewer: a month after 31 January is 28 or 29 February. export function addMonths (date, n) { const [year, month, day] = date.split('-').map(Number) const first = new Date(0) first.setUTCFullYear(year, month - 1 + n, 1) const last = new Date(0) last.setUTCFullYear(first.getUTCFullYear(), first.getUTCMonth() + 1, 0) first.setUTCDate(Math.min(day, last.getUTCDate())) return iso(first) || null } // monthGrid is six weeks from the locale's first day of the week on or // before date's month's first day, as the month calendar draws them // (calendar.go): Monday in en-IE, Sunday in en-US (build note 85). export function monthGrid (date, weekStart = firstDay()) { const first = `${date.slice(0, 8)}01` const back = (utc(first).getUTCDay() - weekStart + 7) % 7 return Array.from({ length: 42 }, (_, n) => addDays(first, n - back)) } // monthTitle is the month as the reader's locale names it: "November // 2026", "novembre 2026". export function monthTitle (date) { return titleOf(date) } // moveFor is where a key moves the chosen day, or null for a key the // grid does not take. export function moveFor (key, date, shift = false) { switch (key) { case 'ArrowLeft': return addDays(date, -1) case 'ArrowRight': return addDays(date, 1) case 'ArrowUp': return addDays(date, -7) case 'ArrowDown': return addDays(date, 7) case 'PageUp': return addMonths(date, shift ? -12 : -1) case 'PageDown': return addMonths(date, shift ? 12 : 1) } return null } // ── The picker. ── let serial = 0 function element (tag, attrs = {}, text = '') { const node = document.createElement(tag) for (const [name, value] of Object.entries(attrs)) node.setAttribute(name, value) if (text) node.textContent = text return node } function chevron (points) { const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg') svg.setAttribute('viewBox', '0 0 24 24') svg.setAttribute('aria-hidden', 'true') const line = document.createElementNS('http://www.w3.org/2000/svg', 'polyline') line.setAttribute('points', points) svg.append(line) return svg } class Picker { constructor (view, today) { this.view = view this.today = today this.chosen = today this.id = `mapa-datepick-${++serial}` this.build() } build () { const id = this.id this.root = element('div', { 'mapa-datepick': '', role: 'dialog', 'aria-label': words.dialog, tabindex: '-1' }) this.field = element('input', { 'mapa-datepick-field': '', type: 'text', role: 'combobox', 'aria-label': words.field, 'aria-expanded': 'true', 'aria-haspopup': 'grid', 'aria-controls': `${id}-grid`, 'aria-describedby': `${id}-help`, placeholder: words.placeholder, autocomplete: 'off', autocapitalize: 'off', spellcheck: 'false', enterkeyhint: 'done' }) this.title = element('strong', { id: `${id}-title` }) const head = element('div', { 'mapa-datepick-head': '' }) this.back = element('button', { type: 'button', 'aria-label': words.previous }) this.back.append(chevron('15 18 9 12 15 6')) this.ahead = element('button', { type: 'button', 'aria-label': words.next }) this.ahead.append(chevron('9 18 15 12 9 6')) head.append(this.title, this.back, this.ahead) this.grid = element('table', { role: 'grid', id: `${id}-grid`, 'aria-labelledby': `${id}-title` }) const row = element('tr') for (const { name, letter } of weekHeads()) row.append(element('th', { scope: 'col', abbr: name }, letter)) this.days = element('tbody') this.grid.append(element('thead'), this.days) this.grid.tHead.append(row) this.said = element('p', { 'mapa-datepick-said': '', 'aria-hidden': 'true' }) this.live = element('p', { 'mapa-sr': '', role: 'status' }) const help = element('p', { 'mapa-sr': '', id: `${id}-help` }, words.help) this.root.append(this.field, head, this.grid, this.said, help, this.live) this.wire() } wire () { // A click keeps focus where it is, so the field keeps the keys. this.root.addEventListener('mousedown', event => { if (event.target !== this.field) event.preventDefault() }) this.back.addEventListener('click', () => this.show(addMonths(this.chosen, -1))) this.ahead.addEventListener('click', () => this.show(addMonths(this.chosen, 1))) this.days.addEventListener('click', event => { const day = event.target.closest('td[data-date]') if (day) this.insert(day.dataset.date) }) this.root.addEventListener('keydown', event => this.keys(event)) this.field.addEventListener('input', () => this.typed()) this.root.addEventListener('focusout', event => { if (!this.root.contains(event.relatedTarget)) this.close() }) this.place = this.place.bind(this) window.visualViewport?.addEventListener('resize', this.place) window.visualViewport?.addEventListener('scroll', this.place) } keys (event) { if (event.isComposing) return if (event.key === 'Escape') { event.preventDefault() this.cancel() return } if (event.key === 'Enter' && event.target.closest('button') === null) { event.preventDefault() if (!this.understood) return this.insert(this.chosen) return } if (event.altKey || event.metaKey || event.ctrlKey) return // With text in the field, ← and → move its caret (review L3). const sideways = event.key === 'ArrowLeft' || event.key === 'ArrowRight' if (sideways && event.target === this.field && this.field.value !== '') return const next = moveFor(event.key, this.chosen, event.shiftKey) if (next === undefined || next === null) return event.preventDefault() this.show(next) } // typed moves to the day the field names, or says it names none. // The value goes to the port untrimmed: it trims as Go does, and // String.prototype.trim would take U+FEFF too (review L1). typed () { this.today = todayNow() const text = goTrimSpace(this.field.value) const found = text === '' ? this.chosen : typedDate(this.field.value, this.today, order()) this.understood = Boolean(found) if (found) { this.show(found) this.live.textContent = text === '' ? '' : this.label(found) } else { this.said.textContent = words.unknown(text) this.live.textContent = words.unknown(text) } } label (date) { const thisYear = Number(this.today.slice(0, 4)) return dayLabel(date, thisYear) + (date === this.today ? `, ${words.today}` : '') } // show draws the month holding date, with date chosen. show (date) { if (!date) return // Today is read again each time, so a picker left open past midnight // rings the new day (review L2). this.today = todayNow() this.chosen = date this.understood = true this.title.textContent = monthTitle(date) const month = date.slice(0, 7) const cells = monthGrid(date).map(day => { if (!day) return element('td', { role: 'gridcell' }) const cell = element('td', { role: 'gridcell', id: `${this.id}-${day}`, 'data-date': day, 'aria-label': this.label(day), 'aria-selected': day === date ? 'true' : 'false' }, String(Number(day.slice(8)))) if (day === this.today) cell.setAttribute('aria-current', 'date') if (day.slice(0, 7) !== month) cell.setAttribute('mapa-outside', '') return cell }) const rows = [] for (let week = 0; week < 6; week++) { const row = element('tr') row.append(...cells.slice(week * 7, week * 7 + 7)) rows.push(row) } this.days.replaceChildren(...rows) this.field.setAttribute('aria-activedescendant', `${this.id}-${date}`) this.said.textContent = this.label(date) } // place puts the picker under the caret, kept on screen and above a // phone's keyboard; above the caret when there is no room below. place () { if (!this.root.isConnected) return const caret = this.view.coordsAtPos(this.view.state.selection.to) const viewport = window.visualViewport const top0 = viewport ? viewport.offsetTop : 0 const bottom = viewport ? top0 + viewport.height : window.innerHeight const right = viewport ? viewport.offsetLeft + viewport.width : window.innerWidth const { offsetHeight: height, offsetWidth: width } = this.root const below = caret.bottom + 6 const top = below + height <= bottom ? below : Math.max(top0 + 4, caret.top - height - 6) const left = Math.max(4, Math.min(caret.left - 12, right - width - 4)) this.root.style.setProperty('top', `${top}px`) this.root.style.setProperty('left', `${left}px`) } open () { this.show(this.chosen) document.body.append(this.root) this.place() const coarse = window.matchMedia?.('(pointer: coarse)').matches ;(coarse ? this.root : this.field).focus({ preventScroll: true }) } close () { // Removing the focused field fires focusout, which closes again. if (this.closed || !this.root.isConnected) return this.closed = true window.visualViewport?.removeEventListener('resize', this.place) window.visualViewport?.removeEventListener('scroll', this.place) this.root.remove() if (current === this) current = null } cancel () { this.close() this.view.focus() } insert (date) { this.close() this.view.focus() put(this.view, date) } } let current = null // put inserts date's chip at the selection's end, or says why it can't. function put (view, date) { const made = dateInsertion(view.state, date) if (made?.tr) view.dispatch(made.tr) else if (made?.refuse) say(view, made.refuse) } // say shows a refusal under the caret, as a polite status, until the // next key or pointer press, or for eight seconds. function say (view, text) { document.querySelector('[mapa-datepick-note]')?.remove() const note = element('p', { 'mapa-datepick-note': '', role: 'status' }, text) document.body.append(note) const caret = view.coordsAtPos(view.state.selection.to) const left = Math.max(4, Math.min(caret.left - 12, window.innerWidth - note.offsetWidth - 4)) note.style.setProperty('top', `${caret.bottom + 6}px`) note.style.setProperty('left', `${left}px`) const gone = () => { note.remove() document.removeEventListener('keydown', gone, true) document.removeEventListener('pointerdown', gone, true) } setTimeout(() => { document.addEventListener('keydown', gone, true) document.addEventListener('pointerdown', gone, true) }, 0) setTimeout(gone, 8000) } // pickDate is the command / → Date and Insert → Date… run: it opens the // picker at the selection's end, whose words it keeps (review M3). // Where no chip can go (code, no text block) it does nothing; where the // block would not read back with one (review M1), it says so first. export function pickDate (state, dispatch, view) { const now = todayNow() const made = dateInsertion(state, now) if (!made) return false if (dispatch && view) { current?.close() if (made.refuse) { say(view, made.refuse) return true } current = new Picker(view, now) current.open() } return true } // insertToday is Insert → Today's date and / → Today's date: today's // chip at once, or the reason it can't go here. export function insertToday (state, dispatch, view) { if (!dateInsertion(state, todayNow())) return false if (dispatch && view) put(view, todayNow()) return true }