| 1 | // datepicker.mjs — / → Date and Insert → Date… (build note 83): a month |
| 2 | // at the caret (a selection's end: its words stay) with today, in the |
| 3 | // viewer's zone, chosen. ← → move a day (once the field holds text they |
| 4 | // move its caret), ↑ ↓ a week, Page Up and Page Down a month; ↵ inserts |
| 5 | // the day's chip, [[2026-11-20]], the one [[ makes for a date; Esc |
| 6 | // inserts nothing. A date typed in its field ("next friday", "12 nov") |
| 7 | // moves to that day, read as ⌘K reads it (typeddate.mjs). A click or a |
| 8 | // tap on a day inserts it. Where the chip would not read back as one |
| 9 | // date link, commands.mjs's dateInsertion puts a space first, or the |
| 10 | // picker says why no date can go there and does not open. |
| 11 | // |
| 12 | // The field is a combobox whose popup is the grid (ARIA 1.2): focus |
| 13 | // stays in it and aria-activedescendant names the chosen day, as the |
| 14 | // Page link field names its row. On a coarse pointer the picker takes |
| 15 | // focus instead of the field, so a phone's keyboard goes down and the |
| 16 | // month can be seen; a tap on the field brings the keyboard back. It |
| 17 | // looks like the month calendar (links.css). |
| 18 | |
| 19 | import { dateInsertion, today as todayNow } from './commands.mjs' |
| 20 | import { goTrimSpace } from './markup.mjs' |
| 21 | import { dayLabel } from './resolutions.mjs' |
| 22 | import { typedDate, iso } from './typeddate.mjs' |
| 23 | import { firstDay, monthTitle as titleOf, order, weekHeads } from './dates.mjs' |
| 24 | |
| 25 | export const words = { |
| 26 | dialog: 'Insert a date', |
| 27 | field: 'Date', |
| 28 | placeholder: 'Type a date, like next friday', |
| 29 | help: 'Arrow keys move a day or a week, Page Up and Page Down a month. Enter inserts the day, Escape closes.', |
| 30 | previous: 'Previous month', |
| 31 | next: 'Next month', |
| 32 | today: 'today', |
| 33 | unknown: text => `“${text}” isn’t a date here. Try “next friday” or “12 nov”.` |
| 34 | } |
| 35 | |
| 36 | // ── The arithmetic: pure, so Node tests it (datepicker.test.mjs). ── |
| 37 | |
| 38 | function utc (iso) { |
| 39 | const [year, month, day] = iso.split('-').map(Number) |
| 40 | const date = new Date(0) |
| 41 | date.setUTCFullYear(year, month - 1, day) |
| 42 | return date |
| 43 | } |
| 44 | |
| 45 | // addDays is the day n days from date; null past the years ISO writes. |
| 46 | export function addDays (date, n) { |
| 47 | const day = utc(date) |
| 48 | day.setUTCDate(day.getUTCDate() + n) |
| 49 | return iso(day) || null |
| 50 | } |
| 51 | |
| 52 | // addMonths keeps the day of the month, or the month's last day when |
| 53 | // it has fewer: a month after 31 January is 28 or 29 February. |
| 54 | export function addMonths (date, n) { |
| 55 | const [year, month, day] = date.split('-').map(Number) |
| 56 | const first = new Date(0) |
| 57 | first.setUTCFullYear(year, month - 1 + n, 1) |
| 58 | const last = new Date(0) |
| 59 | last.setUTCFullYear(first.getUTCFullYear(), first.getUTCMonth() + 1, 0) |
| 60 | first.setUTCDate(Math.min(day, last.getUTCDate())) |
| 61 | return iso(first) || null |
| 62 | } |
| 63 | |
| 64 | // monthGrid is six weeks from the locale's first day of the week on or |
| 65 | // before date's month's first day, as the month calendar draws them |
| 66 | // (calendar.go): Monday in en-IE, Sunday in en-US (build note 85). |
| 67 | export function monthGrid (date, weekStart = firstDay()) { |
| 68 | const first = `${date.slice(0, 8)}01` |
| 69 | const back = (utc(first).getUTCDay() - weekStart + 7) % 7 |
| 70 | return Array.from({ length: 42 }, (_, n) => addDays(first, n - back)) |
| 71 | } |
| 72 | |
| 73 | // monthTitle is the month as the reader's locale names it: "November |
| 74 | // 2026", "novembre 2026". |
| 75 | export function monthTitle (date) { |
| 76 | return titleOf(date) |
| 77 | } |
| 78 | |
| 79 | // moveFor is where a key moves the chosen day, or null for a key the |
| 80 | // grid does not take. |
| 81 | export function moveFor (key, date, shift = false) { |
| 82 | switch (key) { |
| 83 | case 'ArrowLeft': return addDays(date, -1) |
| 84 | case 'ArrowRight': return addDays(date, 1) |
| 85 | case 'ArrowUp': return addDays(date, -7) |
| 86 | case 'ArrowDown': return addDays(date, 7) |
| 87 | case 'PageUp': return addMonths(date, shift ? -12 : -1) |
| 88 | case 'PageDown': return addMonths(date, shift ? 12 : 1) |
| 89 | } |
| 90 | return null |
| 91 | } |
| 92 | |
| 93 | // ── The picker. ── |
| 94 | |
| 95 | let serial = 0 |
| 96 | |
| 97 | function element (tag, attrs = {}, text = '') { |
| 98 | const node = document.createElement(tag) |
| 99 | for (const [name, value] of Object.entries(attrs)) node.setAttribute(name, value) |
| 100 | if (text) node.textContent = text |
| 101 | return node |
| 102 | } |
| 103 | |
| 104 | function chevron (points) { |
| 105 | const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg') |
| 106 | svg.setAttribute('viewBox', '0 0 24 24') |
| 107 | svg.setAttribute('aria-hidden', 'true') |
| 108 | const line = document.createElementNS('http://www.w3.org/2000/svg', 'polyline') |
| 109 | line.setAttribute('points', points) |
| 110 | svg.append(line) |
| 111 | return svg |
| 112 | } |
| 113 | |
| 114 | class Picker { |
| 115 | constructor (view, today) { |
| 116 | this.view = view |
| 117 | this.today = today |
| 118 | this.chosen = today |
| 119 | this.id = `mapa-datepick-${++serial}` |
| 120 | this.build() |
| 121 | } |
| 122 | |
| 123 | build () { |
| 124 | const id = this.id |
| 125 | this.root = element('div', { 'mapa-datepick': '', role: 'dialog', 'aria-label': words.dialog, tabindex: '-1' }) |
| 126 | this.field = element('input', { |
| 127 | 'mapa-datepick-field': '', type: 'text', role: 'combobox', 'aria-label': words.field, |
| 128 | 'aria-expanded': 'true', 'aria-haspopup': 'grid', 'aria-controls': `${id}-grid`, |
| 129 | 'aria-describedby': `${id}-help`, placeholder: words.placeholder, autocomplete: 'off', |
| 130 | autocapitalize: 'off', spellcheck: 'false', enterkeyhint: 'done' |
| 131 | }) |
| 132 | this.title = element('strong', { id: `${id}-title` }) |
| 133 | const head = element('div', { 'mapa-datepick-head': '' }) |
| 134 | this.back = element('button', { type: 'button', 'aria-label': words.previous }) |
| 135 | this.back.append(chevron('15 18 9 12 15 6')) |
| 136 | this.ahead = element('button', { type: 'button', 'aria-label': words.next }) |
| 137 | this.ahead.append(chevron('9 18 15 12 9 6')) |
| 138 | head.append(this.title, this.back, this.ahead) |
| 139 | this.grid = element('table', { role: 'grid', id: `${id}-grid`, 'aria-labelledby': `${id}-title` }) |
| 140 | const row = element('tr') |
| 141 | for (const { name, letter } of weekHeads()) row.append(element('th', { scope: 'col', abbr: name }, letter)) |
| 142 | this.days = element('tbody') |
| 143 | this.grid.append(element('thead'), this.days) |
| 144 | this.grid.tHead.append(row) |
| 145 | this.said = element('p', { 'mapa-datepick-said': '', 'aria-hidden': 'true' }) |
| 146 | this.live = element('p', { 'mapa-sr': '', role: 'status' }) |
| 147 | const help = element('p', { 'mapa-sr': '', id: `${id}-help` }, words.help) |
| 148 | this.root.append(this.field, head, this.grid, this.said, help, this.live) |
| 149 | this.wire() |
| 150 | } |
| 151 | |
| 152 | wire () { |
| 153 | // A click keeps focus where it is, so the field keeps the keys. |
| 154 | this.root.addEventListener('mousedown', event => { |
| 155 | if (event.target !== this.field) event.preventDefault() |
| 156 | }) |
| 157 | this.back.addEventListener('click', () => this.show(addMonths(this.chosen, -1))) |
| 158 | this.ahead.addEventListener('click', () => this.show(addMonths(this.chosen, 1))) |
| 159 | this.days.addEventListener('click', event => { |
| 160 | const day = event.target.closest('td[data-date]') |
| 161 | if (day) this.insert(day.dataset.date) |
| 162 | }) |
| 163 | this.root.addEventListener('keydown', event => this.keys(event)) |
| 164 | this.field.addEventListener('input', () => this.typed()) |
| 165 | this.root.addEventListener('focusout', event => { |
| 166 | if (!this.root.contains(event.relatedTarget)) this.close() |
| 167 | }) |
| 168 | this.place = this.place.bind(this) |
| 169 | window.visualViewport?.addEventListener('resize', this.place) |
| 170 | window.visualViewport?.addEventListener('scroll', this.place) |
| 171 | } |
| 172 | |
| 173 | keys (event) { |
| 174 | if (event.isComposing) return |
| 175 | if (event.key === 'Escape') { |
| 176 | event.preventDefault() |
| 177 | this.cancel() |
| 178 | return |
| 179 | } |
| 180 | if (event.key === 'Enter' && event.target.closest('button') === null) { |
| 181 | event.preventDefault() |
| 182 | if (!this.understood) return |
| 183 | this.insert(this.chosen) |
| 184 | return |
| 185 | } |
| 186 | if (event.altKey || event.metaKey || event.ctrlKey) return |
| 187 | // With text in the field, ← and → move its caret (review L3). |
| 188 | const sideways = event.key === 'ArrowLeft' || event.key === 'ArrowRight' |
| 189 | if (sideways && event.target === this.field && this.field.value !== '') return |
| 190 | const next = moveFor(event.key, this.chosen, event.shiftKey) |
| 191 | if (next === undefined || next === null) return |
| 192 | event.preventDefault() |
| 193 | this.show(next) |
| 194 | } |
| 195 | |
| 196 | // typed moves to the day the field names, or says it names none. |
| 197 | // The value goes to the port untrimmed: it trims as Go does, and |
| 198 | // String.prototype.trim would take U+FEFF too (review L1). |
| 199 | typed () { |
| 200 | this.today = todayNow() |
| 201 | const text = goTrimSpace(this.field.value) |
| 202 | const found = text === '' ? this.chosen : typedDate(this.field.value, this.today, order()) |
| 203 | this.understood = Boolean(found) |
| 204 | if (found) { |
| 205 | this.show(found) |
| 206 | this.live.textContent = text === '' ? '' : this.label(found) |
| 207 | } else { |
| 208 | this.said.textContent = words.unknown(text) |
| 209 | this.live.textContent = words.unknown(text) |
| 210 | } |
| 211 | } |
| 212 | |
| 213 | label (date) { |
| 214 | const thisYear = Number(this.today.slice(0, 4)) |
| 215 | return dayLabel(date, thisYear) + (date === this.today ? `, ${words.today}` : '') |
| 216 | } |
| 217 | |
| 218 | // show draws the month holding date, with date chosen. |
| 219 | show (date) { |
| 220 | if (!date) return |
| 221 | // Today is read again each time, so a picker left open past midnight |
| 222 | // rings the new day (review L2). |
| 223 | this.today = todayNow() |
| 224 | this.chosen = date |
| 225 | this.understood = true |
| 226 | this.title.textContent = monthTitle(date) |
| 227 | const month = date.slice(0, 7) |
| 228 | const cells = monthGrid(date).map(day => { |
| 229 | if (!day) return element('td', { role: 'gridcell' }) |
| 230 | const cell = element('td', { |
| 231 | role: 'gridcell', id: `${this.id}-${day}`, 'data-date': day, |
| 232 | 'aria-label': this.label(day), 'aria-selected': day === date ? 'true' : 'false' |
| 233 | }, String(Number(day.slice(8)))) |
| 234 | if (day === this.today) cell.setAttribute('aria-current', 'date') |
| 235 | if (day.slice(0, 7) !== month) cell.setAttribute('mapa-outside', '') |
| 236 | return cell |
| 237 | }) |
| 238 | const rows = [] |
| 239 | for (let week = 0; week < 6; week++) { |
| 240 | const row = element('tr') |
| 241 | row.append(...cells.slice(week * 7, week * 7 + 7)) |
| 242 | rows.push(row) |
| 243 | } |
| 244 | this.days.replaceChildren(...rows) |
| 245 | this.field.setAttribute('aria-activedescendant', `${this.id}-${date}`) |
| 246 | this.said.textContent = this.label(date) |
| 247 | } |
| 248 | |
| 249 | // place puts the picker under the caret, kept on screen and above a |
| 250 | // phone's keyboard; above the caret when there is no room below. |
| 251 | place () { |
| 252 | if (!this.root.isConnected) return |
| 253 | const caret = this.view.coordsAtPos(this.view.state.selection.to) |
| 254 | const viewport = window.visualViewport |
| 255 | const top0 = viewport ? viewport.offsetTop : 0 |
| 256 | const bottom = viewport ? top0 + viewport.height : window.innerHeight |
| 257 | const right = viewport ? viewport.offsetLeft + viewport.width : window.innerWidth |
| 258 | const { offsetHeight: height, offsetWidth: width } = this.root |
| 259 | const below = caret.bottom + 6 |
| 260 | const top = below + height <= bottom ? below : Math.max(top0 + 4, caret.top - height - 6) |
| 261 | const left = Math.max(4, Math.min(caret.left - 12, right - width - 4)) |
| 262 | this.root.style.setProperty('top', `${top}px`) |
| 263 | this.root.style.setProperty('left', `${left}px`) |
| 264 | } |
| 265 | |
| 266 | open () { |
| 267 | this.show(this.chosen) |
| 268 | document.body.append(this.root) |
| 269 | this.place() |
| 270 | const coarse = window.matchMedia?.('(pointer: coarse)').matches |
| 271 | ;(coarse ? this.root : this.field).focus({ preventScroll: true }) |
| 272 | } |
| 273 | |
| 274 | close () { |
| 275 | // Removing the focused field fires focusout, which closes again. |
| 276 | if (this.closed || !this.root.isConnected) return |
| 277 | this.closed = true |
| 278 | window.visualViewport?.removeEventListener('resize', this.place) |
| 279 | window.visualViewport?.removeEventListener('scroll', this.place) |
| 280 | this.root.remove() |
| 281 | if (current === this) current = null |
| 282 | } |
| 283 | |
| 284 | cancel () { |
| 285 | this.close() |
| 286 | this.view.focus() |
| 287 | } |
| 288 | |
| 289 | insert (date) { |
| 290 | this.close() |
| 291 | this.view.focus() |
| 292 | put(this.view, date) |
| 293 | } |
| 294 | } |
| 295 | |
| 296 | let current = null |
| 297 | |
| 298 | // put inserts date's chip at the selection's end, or says why it can't. |
| 299 | function put (view, date) { |
| 300 | const made = dateInsertion(view.state, date) |
| 301 | if (made?.tr) view.dispatch(made.tr) |
| 302 | else if (made?.refuse) say(view, made.refuse) |
| 303 | } |
| 304 | |
| 305 | // say shows a refusal under the caret, as a polite status, until the |
| 306 | // next key or pointer press, or for eight seconds. |
| 307 | function say (view, text) { |
| 308 | document.querySelector('[mapa-datepick-note]')?.remove() |
| 309 | const note = element('p', { 'mapa-datepick-note': '', role: 'status' }, text) |
| 310 | document.body.append(note) |
| 311 | const caret = view.coordsAtPos(view.state.selection.to) |
| 312 | const left = Math.max(4, Math.min(caret.left - 12, window.innerWidth - note.offsetWidth - 4)) |
| 313 | note.style.setProperty('top', `${caret.bottom + 6}px`) |
| 314 | note.style.setProperty('left', `${left}px`) |
| 315 | const gone = () => { |
| 316 | note.remove() |
| 317 | document.removeEventListener('keydown', gone, true) |
| 318 | document.removeEventListener('pointerdown', gone, true) |
| 319 | } |
| 320 | setTimeout(() => { |
| 321 | document.addEventListener('keydown', gone, true) |
| 322 | document.addEventListener('pointerdown', gone, true) |
| 323 | }, 0) |
| 324 | setTimeout(gone, 8000) |
| 325 | } |
| 326 | |
| 327 | // pickDate is the command / → Date and Insert → Date… run: it opens the |
| 328 | // picker at the selection's end, whose words it keeps (review M3). |
| 329 | // Where no chip can go (code, no text block) it does nothing; where the |
| 330 | // block would not read back with one (review M1), it says so first. |
| 331 | export function pickDate (state, dispatch, view) { |
| 332 | const now = todayNow() |
| 333 | const made = dateInsertion(state, now) |
| 334 | if (!made) return false |
| 335 | if (dispatch && view) { |
| 336 | current?.close() |
| 337 | if (made.refuse) { |
| 338 | say(view, made.refuse) |
| 339 | return true |
| 340 | } |
| 341 | current = new Picker(view, now) |
| 342 | current.open() |
| 343 | } |
| 344 | return true |
| 345 | } |
| 346 | |
| 347 | // insertToday is Insert → Today's date and / → Today's date: today's |
| 348 | // chip at once, or the reason it can't go here. |
| 349 | export function insertToday (state, dispatch, view) { |
| 350 | if (!dateInsertion(state, todayNow())) return false |
| 351 | if (dispatch && view) put(view, todayNow()) |
| 352 | return true |
| 353 | } |
| 354 | |