Event editing dialog and many other event-related improvements.

This commit is contained in:
2025-08-21 07:35:42 +00:00
parent bbdbefef1c
commit 12008e40c8
9 changed files with 579 additions and 187 deletions
+338 -94
View File
@@ -1,30 +1,19 @@
// calendar.js — Infinite scrolling week-by-week with overlay event rendering
const monthAbbr = ['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec']
const DAY_MS = 86400000
const WEEK_MS = 7 * DAY_MS
const isoWeekInfo = date => {
const d = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()))
const day = d.getUTCDay() || 7
d.setUTCDate(d.getUTCDate() + 4 - day)
const year = d.getUTCFullYear()
const yearStart = new Date(Date.UTC(year, 0, 1))
const diffDays = Math.floor((d - yearStart) / DAY_MS) + 1
return { week: Math.ceil(diffDays / 7), year }
}
function toLocalString(date = new Date()) {
const pad = n => String(Math.floor(Math.abs(n))).padStart(2, '0')
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`
}
function fromLocalString(dateString) {
const [year, month, day] = dateString.split('-').map(Number)
return new Date(year, month - 1, day)
}
const mondayIndex = d => (d.getDay() + 6) % 7
const pad = n => String(n).padStart(2, '0')
import {
monthAbbr,
DAY_MS,
WEEK_MS,
isoWeekInfo,
toLocalString,
fromLocalString,
mondayIndex,
pad,
daysInclusive,
addDaysStr,
getLocalizedWeekdayNames,
getLocalizedMonthName,
formatDateRange
} from './date-utils.js'
class InfiniteCalendar {
constructor(config = {}) {
@@ -68,6 +57,7 @@ class InfiniteCalendar {
this.setupYearScroll()
this.setupSelectionInput()
this.setupCurrentDate()
this.setupEventDialog()
this.setupInitialView()
}
@@ -189,29 +179,13 @@ class InfiniteCalendar {
return Math.round(h)
}
getLocalizedWeekdayNames() {
const res = []
const base = new Date(2025, 0, 6)
for (let i = 0; i < 7; i++) {
const d = new Date(base)
d.setDate(base.getDate() + i)
res.push(d.toLocaleDateString(undefined, { weekday: 'short' }))
}
return res
}
getLocalizedMonthName(idx, short = false) {
const d = new Date(2025, idx, 1)
return d.toLocaleDateString(undefined, { month: short ? 'short' : 'long' })
}
createHeader() {
this.yearLabel = document.createElement('div')
this.yearLabel.className = 'year-label'
this.yearLabel.textContent = isoWeekInfo(new Date()).year
this.header.appendChild(this.yearLabel)
const names = this.getLocalizedWeekdayNames()
const names = getLocalizedWeekdayNames()
names.forEach((name, i) => {
const c = document.createElement('div')
c.classList.add('dow')
@@ -434,7 +408,7 @@ class InfiniteCalendar {
const label = document.createElement('span')
const year = String((labelYear ?? monday.getFullYear())).slice(-2)
label.textContent = `${this.getLocalizedMonthName(monthToLabel)} '${year}`
label.textContent = `${getLocalizedMonthName(monthToLabel)} '${year}`
overlayCell.appendChild(label)
weekDiv.appendChild(overlayCell)
weekDiv.style.zIndex = '18'
@@ -481,31 +455,17 @@ class InfiniteCalendar {
// -------- Selection --------
daysInclusive(aStr, bStr) {
const a = fromLocalString(aStr)
const b = fromLocalString(bStr)
const A = new Date(a.getFullYear(), a.getMonth(), a.getDate()).getTime()
const B = new Date(b.getFullYear(), b.getMonth(), b.getDate()).getTime()
return Math.floor(Math.abs(B - A) / DAY_MS) + 1
}
addDaysStr(str, n) {
const d = fromLocalString(str)
d.setDate(d.getDate() + n)
return toLocalString(d)
}
clampRange(anchorStr, otherStr) {
if (this.config.select_days <= 1) return [otherStr, otherStr]
const limit = this.config.select_days
const forward = fromLocalString(otherStr) >= fromLocalString(anchorStr)
const span = this.daysInclusive(anchorStr, otherStr)
const span = daysInclusive(anchorStr, otherStr)
if (span <= limit) {
const a = [anchorStr, otherStr].sort()
return [a[0], a[1]]
}
if (forward) return [anchorStr, this.addDaysStr(anchorStr, limit - 1)]
return [this.addDaysStr(anchorStr, -(limit - 1)), anchorStr]
if (forward) return [anchorStr, addDaysStr(anchorStr, limit - 1)]
return [addDaysStr(anchorStr, -(limit - 1)), anchorStr]
}
setSelection(aStr, bStr) {
@@ -513,7 +473,7 @@ class InfiniteCalendar {
this.selStart = start
this.selEnd = end
this.applySelectionToVisible()
this.selectedDateInput.value = this.formatDateRange(fromLocalString(start), fromLocalString(end))
this.selectedDateInput.value = formatDateRange(fromLocalString(start), fromLocalString(end))
}
clearSelection() {
@@ -540,17 +500,6 @@ class InfiniteCalendar {
}
}
formatDateRange(startDate, endDate) {
if (toLocalString(startDate) === toLocalString(endDate)) return toLocalString(startDate)
const startISO = toLocalString(startDate)
const endISO = toLocalString(endDate)
const [sy, sm] = startISO.split('-')
const [ey, em, ed] = endISO.split('-')
if (sy === ey && sm === em) return `${startISO}/${ed}`
if (sy === ey) return `${startISO}/${em}-${ed}`
return `${startISO}/${endISO}`
}
setupGlobalDragHandlers() {
document.addEventListener('mouseup', () => {
if (!this.isDragging) return
@@ -600,33 +549,232 @@ class InfiniteCalendar {
this.setSelection(this.dragAnchor, dateStr)
document.body.style.cursor = 'default'
if (this.selStart && this.selEnd) {
setTimeout(() => this.promptForEvent(), 100)
setTimeout(() => this.showEventDialog('create'), 50)
}
}
// -------- Event Management (overlay-based) --------
promptForEvent() {
const title = prompt('Enter event title:')
if (!title || title.trim() === '') {
this.clearSelection()
return
}
this.createEvent({
title: title.trim(),
startDate: this.selStart,
endDate: this.selEnd
// Build dialog DOM once
setupEventDialog() {
const tpl = document.createElement('template')
tpl.innerHTML = `
<div class="ec-modal-backdrop" part="backdrop" hidden>
<div class="ec-modal" role="dialog" aria-modal="true" aria-labelledby="ec-modal-title">
<form class="ec-form" novalidate>
<header class="ec-header">
<h2 id="ec-modal-title">Event</h2>
</header>
<div class="ec-body">
<label class="ec-field">
<span>Title</span>
<input type="text" name="title" autocomplete="off" required />
</label>
<div class="ec-row">
<label class="ec-field">
<span>Start day</span>
<input type="date" name="startDate" />
</label>
<label class="ec-field">
<span>Duration</span>
<select name="duration">
<option value="15">15 minutes</option>
<option value="30">30 minutes</option>
<option value="45">45 minutes</option>
<option value="60" selected>1 hour</option>
<option value="90">1.5 hours</option>
<option value="120">2 hours</option>
<option value="180">3 hours</option>
<option value="240">4 hours</option>
<option value="480">8 hours</option>
<option value="720">12 hours</option>
<option value="1440">Full day</option>
<option value="2880">2 days</option>
<option value="4320">3 days</option>
<option value="10080">7 days</option>
</select>
</label>
</div>
<div class="ec-row ec-time-row">
<label class="ec-field">
<span>Start time</span>
<input type="time" name="startTime" step="300" />
</label>
<div></div>
</div>
<div class="ec-color-swatches">
${Array.from({ length: 8 }, (_, i) => `
<input class="swatch event-color-${i}" type="radio" name="colorId" value="${i}">
`).join('')}
</div>
</div>
<footer class="ec-footer">
<button type="button" class="ec-btn" data-action="cancel">Cancel</button>
<button type="submit" class="ec-btn primary">Save</button>
</footer>
</form>
</div>
</div>`
document.body.appendChild(tpl.content)
this.eventModal = document.querySelector('.ec-modal-backdrop')
this.eventForm = this.eventModal.querySelector('form.ec-form')
this.eventTitleInput = this.eventForm.elements['title']
this.eventStartDateInput = this.eventForm.elements['startDate']
this.eventStartTimeInput = this.eventForm.elements['startTime']
this.eventDurationInput = this.eventForm.elements['duration']
this.eventTimeRow = this.eventForm.querySelector('.ec-time-row')
this.eventColorInputs = Array.from(this.eventForm.querySelectorAll('input[name="colorId"]'))
// duration change toggles time visibility
this.eventDurationInput.addEventListener('change', () => this.updateTimeVisibilityByDuration())
// color selection visual state
this.eventColorInputs.forEach(radio => {
radio.addEventListener('change', () => {
const swatches = this.eventForm.querySelectorAll('.ec-color-swatches .swatch')
swatches.forEach(s => s.classList.toggle('selected', s.checked))
})
})
this.clearSelection()
this.eventForm.addEventListener('submit', e => {
e.preventDefault()
const data = this.readEventForm()
if (!data.title.trim()) return
if (this._dialogMode === 'create') {
const computed = this.computeDatesFromForm(data)
this.createEvent({
title: data.title.trim(),
startDate: computed.startDate,
endDate: computed.endDate,
colorId: data.colorId,
startTime: data.startTime,
durationMinutes: data.duration
})
this.clearSelection()
} else if (this._dialogMode === 'edit' && this._editingEventId != null) {
const computed = this.computeDatesFromForm(data)
this.applyEventEdit(this._editingEventId, { ...data, ...computed })
}
this.hideEventDialog()
})
this.eventForm.querySelector('[data-action="cancel"]').addEventListener('click', () => {
this.hideEventDialog()
if (this._dialogMode === 'create') this.clearSelection()
})
this.eventModal.addEventListener('click', e => {
if (e.target === this.eventModal) this.hideEventDialog()
})
document.addEventListener('keydown', e => {
if (this.eventModal.hidden) return
if (e.key === 'Escape') {
this.hideEventDialog()
if (this._dialogMode === 'create') this.clearSelection()
}
})
}
showEventDialog(mode, opts = {}) {
this._dialogMode = mode
this._editingEventId = null
if (mode === 'create') {
// Defaults for new event
this.eventTitleInput.value = ''
this.eventStartTimeInput.value = '09:00'
// start date defaults
this.eventStartDateInput.value = this.selStart || toLocalString(new Date())
// duration defaults from selection (full days) or 60 min
if (this.selStart && this.selEnd) {
const days = daysInclusive(this.selStart, this.selEnd)
this.setDurationValue(days * 1440)
} else {
this.setDurationValue(60)
}
// suggest least-used color across range
const suggested = this.selectEventColorId(this.selStart, this.selEnd)
this.eventColorInputs.forEach(r => r.checked = Number(r.value) === suggested)
this.updateTimeVisibilityByDuration()
} else if (mode === 'edit') {
const ev = this.getEventById(opts.id)
if (!ev) return
this._editingEventId = ev.id
this.eventTitleInput.value = ev.title || ''
this.eventStartDateInput.value = ev.startDate
if (ev.startDate !== ev.endDate) {
const days = daysInclusive(ev.startDate, ev.endDate)
this.setDurationValue(days * 1440)
} else {
this.setDurationValue(ev.durationMinutes || 60)
}
this.eventStartTimeInput.value = ev.startTime || '09:00'
this.eventColorInputs.forEach(r => r.checked = Number(r.value) === (ev.colorId ?? 0))
this.updateTimeVisibilityByDuration()
}
this.eventModal.hidden = false
// simple focus
setTimeout(() => this.eventTitleInput.focus(), 0)
}
toggleTimeRow(show) {
if (!this.eventTimeRow) return
this.eventTimeRow.style.display = show ? '' : 'none'
}
updateTimeVisibilityByDuration() {
const minutes = Number(this.eventDurationInput.value || 0)
const isFullDayOrMore = minutes >= 1440
this.toggleTimeRow(!isFullDayOrMore)
}
hideEventDialog() {
this.eventModal.hidden = true
}
readEventForm() {
const colorId = Number(this.eventForm.querySelector('input[name="colorId"]:checked')?.value ?? 0)
const timeRowVisible = this.eventTimeRow && this.eventTimeRow.style.display !== 'none'
return {
title: this.eventTitleInput.value,
startDate: this.eventStartDateInput.value,
startTime: timeRowVisible ? (this.eventStartTimeInput.value || '09:00') : null,
duration: timeRowVisible ? Math.max(15, Number(this.eventDurationInput.value) || 60) : null,
colorId
}
}
setDurationValue(minutes) {
const v = String(minutes)
const exists = Array.from(this.eventDurationInput.options).some(o => o.value === v)
if (!exists) {
const opt = document.createElement('option')
opt.value = v
const days = Math.floor(minutes / 1440)
opt.textContent = days >= 1 ? `${days} day${days > 1 ? 's' : ''}` : `${minutes} minutes`
this.eventDurationInput.appendChild(opt)
}
this.eventDurationInput.value = v
}
computeDatesFromForm(data) {
const minutes = Number(this.eventDurationInput.value || 0)
if (minutes >= 1440) {
const days = Math.max(1, Math.floor(minutes / 1440))
return { startDate: data.startDate, endDate: addDaysStr(data.startDate, days - 1) }
}
return { startDate: data.startDate, endDate: data.startDate }
}
createEvent(eventData) {
const singleDay = eventData.startDate === eventData.endDate
const event = {
id: this.eventIdCounter++,
title: eventData.title,
startDate: eventData.startDate,
endDate: eventData.endDate,
colorId: this.generateEventColorId()
colorId: eventData.colorId ?? this.selectEventColorId(eventData.startDate, eventData.endDate),
startTime: singleDay ? (eventData.startTime || '09:00') : null,
durationMinutes: singleDay ? (eventData.durationMinutes || 60) : null
}
const startDate = new Date(fromLocalString(event.startDate))
@@ -641,9 +789,62 @@ class InfiniteCalendar {
this.refreshEvents()
}
generateEventColorId() {
// Return a color ID from 0-11 for 12 evenly spaced hues
return Math.floor(Math.random() * 12)
applyEventEdit(eventId, data) {
// Update all instances of this event across dates
for (const [, list] of this.events) {
for (let i = 0; i < list.length; i++) {
if (list[i].id === eventId) {
const isMulti = list[i].startDate !== list[i].endDate
list[i] = {
...list[i],
title: data.title.trim(),
colorId: data.colorId,
startTime: isMulti ? null : data.startTime,
durationMinutes: isMulti ? null : data.duration
}
}
}
}
this.refreshEvents()
}
getEventById(id) {
for (const [, list] of this.events) {
const found = list.find(e => e.id === id)
if (found) return found
}
return null
}
selectEventColorId(startDateStr, endDateStr) {
// Count frequency of each color used on the date range
const colorCounts = [0, 0, 0, 0, 0, 0, 0, 0]
const startDate = new Date(fromLocalString(startDateStr))
const endDate = new Date(fromLocalString(endDateStr))
for (let d = new Date(startDate); d <= endDate; d.setDate(d.getDate() + 1)) {
const dateStr = toLocalString(d)
const dayEvents = this.events.get(dateStr) || []
for (const event of dayEvents) {
if (event.colorId >= 0 && event.colorId < 8) {
colorCounts[event.colorId]++
}
}
}
// Find the color with the lowest count
// For equal counts, prefer the lowest color number
let minCount = colorCounts[0]
let selectedColor = 0
for (let colorId = 1; colorId < 8; colorId++) {
if (colorCounts[colorId] < minCount) {
minCount = colorCounts[colorId]
selectedColor = colorId
}
}
return selectedColor
}
refreshEvents() {
@@ -682,8 +883,26 @@ class InfiniteCalendar {
}
}
const spans = Array.from(weekEvents.values())
.sort((a, b) => a.startIdx - b.startIdx || (b.endIdx - b.startIdx) - (a.endIdx - a.startIdx))
const timeToMin = t => {
if (typeof t !== 'string') return 1e9
const m = t.match(/^(\d{2}):(\d{2})/)
if (!m) return 1e9
return Number(m[1]) * 60 + Number(m[2])
}
const spans = Array.from(weekEvents.values()).sort((a, b) => {
if (a.startIdx !== b.startIdx) return a.startIdx - b.startIdx
// Prefer longer spans to be placed first for packing
const aLen = a.endIdx - a.startIdx
const bLen = b.endIdx - b.startIdx
if (aLen !== bLen) return bLen - aLen
// Within the same day and same span length, order by start time
const at = timeToMin(a.startTime)
const bt = timeToMin(b.startTime)
if (at !== bt) return at - bt
// Stable fallback by id
return (a.id || 0) - (b.id || 0)
})
const rowsLastEnd = []
for (const w of spans) {
@@ -694,9 +913,30 @@ class InfiniteCalendar {
w._row = placedRow + 1
}
overlay.style.gridTemplateRows = `repeat(${Math.max(1, rowsLastEnd.length)}, 1fr)`
overlay.style.rowGap = '.2em'
const numRows = Math.max(1, rowsLastEnd.length)
// Decide between "comfortable" layout (with gaps, not stretched)
// and "compressed" layout (fractional rows, no gaps) based on fit.
const cs = getComputedStyle(overlay)
const overlayHeight = overlay.getBoundingClientRect().height
const marginTopPx = parseFloat(cs.marginTop) || 0
const available = Math.max(0, overlayHeight - marginTopPx)
const baseEm = parseFloat(cs.fontSize) || 16
const rowPx = 1.2 * baseEm // preferred row height ~ 1.2em
const gapPx = 0.2 * baseEm // preferred gap ~ .2em
const needed = numRows * rowPx + (numRows - 1) * gapPx
if (needed <= available) {
// Comfortable: keep gaps and do not stretch rows to fill
overlay.style.gridTemplateRows = `repeat(${numRows}, ${rowPx}px)`
overlay.style.rowGap = `${gapPx}px`
} else {
// Compressed: use fractional rows so everything fits; remove gaps
overlay.style.gridTemplateRows = `repeat(${numRows}, 1fr)`
overlay.style.rowGap = '0'
}
// Create the spans
for (const w of spans) this.createOverlaySpan(overlay, w)
}
@@ -707,12 +947,16 @@ class InfiniteCalendar {
span.style.gridRow = `${w._row}`
span.textContent = w.title
span.title = `${w.title} (${w.startDate === w.endDate ? w.startDate : w.startDate + ' - ' + w.endDate})`
span.addEventListener('click', e => {
e.stopPropagation()
this.showEventDialog('edit', { id: w.id })
})
overlay.appendChild(span)
}
}
document.addEventListener('DOMContentLoaded', () => {
new InfiniteCalendar({
select_days: 14
select_days: 1000
})
})