import m from '@garage44/mithril' import {Button, Dialog, FieldSegmented, FieldSwitch, FieldText} from '@garage44/mithril/components' import type {ChatClient} from '@/lib/chat' import { type Entry, type FoundPlace, type MeetingEntry, type MeetupEntry, type NominatimResult, type Settings, type Source, addDays, clock, dayStart, entries, distinctPlaces, goingJson, loadSettings, longDate, meetupJson, monthStart, ruleWords, saveSettings, weekStart, } from '@/lib/calendar' import {type AnswerFor, type Plan, type Rsvp, RSVP_WORDS, isSkipped} from '@/lib/meeting' import {Icon} from '@/lib/icons' import {NOMINATIM} from '@/lib/stats' /** * The calendar page (`docs/mockups/calendar/v1.html` section 2, and * `v2-repeat.html` for series): every meeting and meet-up this person is in, * from every chat, as a list by day, a week of hours or a month, with the one * picked open on the right. * * Nothing in it is new on the wire: it reads the histories the chat worker * keeps in this browser, and what it sends — an answer, "I'm going", a skip — * is exactly what the chat's own cards send. So it shows only what this * browser has: a chat whose history is on another device has no plans here. */ export type View = 'list' | 'week' | 'month' /** What the page lends the calendar: the chat, faces and names, and its ways out. */ export interface CalendarCtx { client: ChatClient avatar: (address: string, size: number) => m.Children /** How a person is named: their bare name on this server. */ shown: (address: string) => string /** Where a plan came from: "oosterparkwijk · # general", "Sanne". */ where: (channel: string) => string /** Everybody in a chat, for "No answer". */ people: (channel: string) => string[] /** The chats, as calendar sources. */ sources: () => Source[] /** The communities, for "only the plans I answered". */ communities: () => {id: string; name: string}[] openChat: (channel: string) => void /** Back to the list of communities, on a phone. */ back: () => void join: (channel: string) => void /** Open a chat's plan dialog on a day (a local midnight), at a time if one * was clicked in the week. */ plan: (channel: string, day: number, at: number | null) => void } /** A meet-up being put together from the web: which chat, where, when. */ interface MeetupDraft { channel: string query: string found: FoundPlace[] place: FoundPlace | null /** "20:00", on [`st.day`]. */ time: string note: string searching: boolean error: string | null } /** Everything the calendar page holds. */ const st = { view: 'week' as View, /** The day the shown period is about, a local midnight. */ anchor: dayStart(Date.now()), /** The day picked: where Plan plans, and which day a month lists. */ day: dayStart(Date.now()), /** The entry open on the right, by key. */ selected: null as string | null, /** Whether an answer in the panel is for every date of the series. */ every: false, planning: false, /** What Plan makes: a meeting, or a meet-up (a place and a time). */ kind: 'meeting' as 'meeting' | 'meetup', /** The time clicked in the week, for Plan to start at. */ planAt: null as number | null, /** The meet-up form, once a chat is picked for one. */ meetup: null as MeetupDraft | null, settings: loadSettings() as Settings, } /** Open Plan on the picked day, at `at` if a time was clicked. */ function startPlanning(at: number | null): void { st.planAt = at st.kind = 'meeting' st.meetup = null st.planning = true } /** "20:00" for an instant, or for the next whole hour when there is none. */ function timeOf(at: number | null): string { const t = new Date(at ?? Date.now()) if (at === null) { t.setMinutes(0, 0, 0) t.setHours(t.getHours() + 1) } return `${String(t.getHours()).padStart(2, '0')}:${String(t.getMinutes()).padStart(2, '0')}` } let searchTimer: ReturnType | null = null /** Look the typed place up on our own address server, a moment after typing stops. */ function searchPlace(d: MeetupDraft): void { if (searchTimer) clearTimeout(searchTimer) const q = d.query.trim() if (q.length < 3) { d.found = [] return } searchTimer = setTimeout(async () => { d.searching = true d.error = null m.redraw() try { // Biased towards the Netherlands, where the map has its detail, // without ruling anywhere else out. const r = await fetch( `${NOMINATIM}/search?format=jsonv2&addressdetails=1&limit=10&viewbox=3.2,53.7,7.3,50.7&q=${encodeURIComponent(q)}`, ) const list = r.ok ? ((await r.json()) as NominatimResult[]) : [] if (d.query.trim() === q) d.found = distinctPlaces(list).slice(0, 6) if (!r.ok) d.error = 'The address search did not answer. Try again in a moment.' } catch { d.error = 'The address search could not be reached.' } d.searching = false m.redraw() }, 350) } /** Open on today: a week of hours, or the list on a phone, which has no room for hours. */ export function openCalendar(): void { if (matchMedia('(max-width: 760px)').matches) st.view = 'list' st.anchor = dayStart(Date.now()) st.day = st.anchor } const HOUR_PX = 44 const DAY_MS = 86_400_000 /** How far back the calendar looks: plans more than a month gone are left out. */ const PAST_MS = 30 * DAY_MS /** The first and last hours the week grid shows: 9 to 21, stretched to what is in it. */ function hourRange(list: Entry[]): [number, number] { let from = 9 let to = 21 for (const e of list) { const start = new Date(e.startMs) from = Math.min(from, start.getHours()) const end = new Date(Math.min(e.endMs, addDays(dayStart(e.startMs), 1))) const endH = end.getTime() === addDays(dayStart(e.startMs), 1) ? 24 : end.getHours() + (end.getMinutes() > 0 ? 1 : 0) to = Math.max(to, endH) } return [from, Math.min(24, to)] } /** The words for this person's answer on a row: their answer, "Skipped", or "Answer". */ function status(e: Entry, me: string): {cls: string; text: string} { if (e.kind === 'meeting' && e.skipped) return {cls: 'is-skipped', text: 'Skipped'} if (e.mine) return {cls: `is-${e.mine}`, text: e.kind === 'meetup' ? 'Going' : RSVP_WORDS[e.mine]} if (own(e, me)) return {cls: 'is-going', text: 'Yours'} return {cls: 'is-open', text: 'Answer'} } const own = (e: Entry, me: string) => (e.kind === 'meeting' ? e.planner === me : e.meetup.proposer === me) /** The classes an entry is drawn with: its kind, and how it was answered. */ function entryClass(e: Entry, me: string, base: string): string { return [ base, e.kind === 'meetup' ? 'is-meetup' : 'is-meeting', e.mine === null && !own(e, me) && !(e.kind === 'meeting' && e.skipped) ? 'is-unanswered' : '', e.mine === 'no' ? 'is-declined' : '', e.kind === 'meeting' && e.skipped ? 'is-skipped' : '', st.selected === e.key ? 'is-selected' : '', ].join(' ') } function dayWords(ms: number): string { const today = dayStart(Date.now()) if (ms === today) return 'Today' if (ms === addDays(today, 1)) return 'Tomorrow' return longDate(ms) } function span(fromMs: number, toMs: number): string { const a = new Date(fromMs) const b = new Date(toMs - 1) const year = b.getFullYear() if (a.getMonth() === b.getMonth()) return `${a.getDate()} – ${b.getDate()} ${b.toLocaleDateString([], {month: 'long'})} ${year}` const day = (d: Date) => d.toLocaleDateString([], {day: 'numeric', month: 'long'}) return `${day(a)} – ${day(b)} ${year}` } /** The period the view shows: [from, to), a title, and the step back and on. */ function period(): {from: number; step: (n: number) => number; title: string; to: number} { if (st.view === 'week') { const from = weekStart(st.anchor) const to = addDays(from, 7) return {from, step: (n) => addDays(st.anchor, 7 * n), title: span(from, to), to} } if (st.view === 'month') { const first = monthStart(st.anchor) const from = weekStart(first) const to = addDays(from, 42) const step = (n: number) => { const d = new Date(first) d.setMonth(d.getMonth() + n) return d.getTime() } return {from, step, title: new Date(first).toLocaleDateString([], {month: 'long', year: 'numeric'}), to} } const from = st.anchor const to = addDays(from, 28) const title = from === dayStart(Date.now()) ? 'From today' : `From ${longDate(from)}` return {from, step: (n) => addDays(st.anchor, 28 * n), title, to} } /** How many plans are today, for the calendar's row on the side. */ export function todayCount(ctx: Pick): number { const me = ctx.client.address if (!me) return 0 const today = dayStart(Date.now()) return entries(ctx.sources(), me, today, addDays(today, 1), st.settings) .filter((e) => !(e.kind === 'meeting' && e.skipped) && e.mine !== 'no').length } export function Calendar(ctx: CalendarCtx): m.Children { const me = ctx.client.address ?? '' const p = period() const from = Math.max(p.from, Date.now() - PAST_MS) const list = entries(ctx.sources(), me, from, p.to, st.settings) const picked = st.selected ? list.find((e) => e.key === st.selected) ?? null : null return (
{settingsMenu(ctx)}
{st.view === 'week' && weekView(ctx, list, p.from, me)} {st.view === 'month' && monthView(ctx, list, p.from, me)} {st.view === 'list' && listView(ctx, list, p.from, p.to, me)}

From the chats on this browser. A plan in a chat whose history is only on another device is not here.

{picked && } {planDialog(ctx)}
) } function pick(e: Entry): void { st.selected = st.selected === e.key ? null : e.key st.every = false } /** One plan in the week grid or a list. */ function block(ctx: CalendarCtx, e: Entry, me: string, style: string | null = null) { const s = status(e, me) return ( ) } function weekView(ctx: CalendarCtx, list: Entry[], from: number, me: string) { const days = Array.from({length: 7}, (_, i) => addDays(from, i)) const [h0, h1] = hourRange(list) const hours = h1 - h0 /** Where an hour of the day is, down the grid. */ const pct = (hour: number) => ((hour - h0) / hours) * 100 const today = dayStart(Date.now()) const now = Date.now() return (
{days.map((d) => ( ))}
{/* At least HOUR_PX an hour, and stretched to fill the pane when the hours fit. */}
{Array.from({length: hours}, (_, i) => ( {new Date(2000, 0, 1, h0 + i).toLocaleTimeString([], {hour: 'numeric'})} ))}
{days.map((d) => { const end = addDays(d, 1) const inDay = list.filter((e) => e.startMs >= d && e.startMs < end) // Side by side where they overlap: each takes the first free lane. const lanes: number[] = [] const lane = new Map() for (const e of inDay) { let i = lanes.findIndex((until) => until <= e.startMs) if (i < 0) i = lanes.push(0) - 1 lanes[i] = e.endMs lane.set(e.key, i) } const width = 100 / Math.max(1, lanes.length) // By the clock rather than by milliseconds since midnight, so a // day with a change to summer time still has 20:00 at 20:00. const hourOf = (ms: number) => { if (ms >= end) return 24 const t = new Date(ms) return t.getHours() + t.getMinutes() / 60 } // A click on an empty part of the day plans something at // that time, to the half hour; one on a plan opens it. const planHere = (ev: MouseEvent) => { if ((ev.target as HTMLElement).closest('.cal-block')) return const r = (ev.currentTarget as HTMLElement).getBoundingClientRect() const hour = Math.floor((h0 + ((ev.clientY - r.top) / r.height) * hours) * 2) / 2 const at = new Date(d) at.setHours(Math.floor(hour), (hour % 1) * 60, 0, 0) if (at.getTime() < Date.now()) return st.day = d startPlanning(at.getTime()) } return (
now ? 'Click to plan something at this time' : undefined} > {inDay.map((e) => { const y = pct(hourOf(e.startMs)) const h = pct(hourOf(e.endMs)) - y const x = lane.get(e.key)! * width return block(ctx, e, me, `top:${y}%;height:max(${h}%, 38px);left:calc(${x}% + 2px);width:calc(${width}% - 4px)`) })} {d === today && now < end && }
) })}
) } function monthView(ctx: CalendarCtx, list: Entry[], from: number, me: string) { const month = new Date(monthStart(st.anchor)).getMonth() const today = dayStart(Date.now()) const cells = Array.from({length: 42}, (_, i) => addDays(from, i)) const day = st.day const onDay = list.filter((e) => dayStart(e.startMs) === day) return (
{cells.slice(0, 7).map((d) => ( {new Date(d).toLocaleDateString([], {weekday: 'short'})} ))} {cells.map((d) => { const has = list.filter((e) => dayStart(e.startMs) === d && !(e.kind === 'meeting' && e.skipped)) return ( ) })}

{dayWords(day)} {day >= today && ( )}

{onDay.length === 0 ?

Nothing planned.

: onDay.map((e) => row(ctx, e, me))}
) } /** One plan in the list: its time, an edge in its kind's colour, what and where, and the answer. */ function row(ctx: CalendarCtx, e: Entry, me: string) { const s = status(e, me) const mins = Math.round((e.endMs - e.startMs) / 60000) return ( ) } function listView(ctx: CalendarCtx, list: Entry[], from: number, to: number, me: string) { const out: m.Children[] = [] for (let d = from; d < to; d = addDays(d, 1)) { const onDay = list.filter((e) => dayStart(e.startMs) === d) if (!onDay.length) continue out.push(

{dayWords(d)}

{onDay.map((e) => row(ctx, e, me))}
, ) } return (
{out.length ? out :

Nothing planned in these four weeks. Plan a meeting in a chat, or with Plan above.

}
) } /** The plan picked, as the phone's sheet draws it (v1, D and E; v2, K). */ function detail(ctx: CalendarCtx, e: Entry, me: string) { return (
{e.kind === 'meeting' ? meetingDetail(ctx, e, me) : meetupDetail(ctx, e, me)}
) } function whenWords(startMs: number, endMs: number | null): string { const day = dayStart(startMs) const today = dayStart(Date.now()) const date = day === today ? 'Today' : day === addDays(today, 1) ? 'Tomorrow' : longDate(startMs) return `${date}, ${clock(startMs)}${endMs === null ? '' : ` – ${clock(endMs)}`}` } const ORDINAL = (n: number) => `${n}${n % 100 >= 11 && n % 100 <= 13 ? 'th' : ['th', 'st', 'nd', 'rd'][n % 10] ?? 'th'}` function meetingDetail(ctx: CalendarCtx, e: MeetingEntry, me: string) { const c = ctx.client const plan = e.plan const now = Date.now() const answerFor: AnswerFor = !plan.repeat ? null : st.every ? 'every' : e.startMs const answer = (r: Rsvp) => c.sendMeeting(e.channel, {date: answerFor, kind: 'answer', plan: plan.id, rsvp: r}) // You first, then in the order they answered. const who = (r: Rsvp) => [...e.rsvps.entries()].filter(([, a]) => a === r).map(([w]) => w) .sort((a, b) => Number(b === me) - Number(a === me)) const answered = new Set(e.rsvps.keys()) const silent = ctx.people(e.channel).filter((p) => !answered.has(p)) // A big community's "no answer" is most of it: the first few, and how many more. const names = (list: string[]) => { const named = list.slice(0, 6).map((p) => (p === me ? 'you' : ctx.shown(p))).join(', ') return list.length > 6 ? `${named}, +${list.length - 6}` : named } const joinable = !e.skipped && now >= e.startMs - 10 * 60000 && now <= e.endMs const over = now > e.endMs const mine = e.planner === me const lines: [string, string[]][] = [ [`Going ${who('going').length}`, who('going')], [`Maybe ${who('maybe').length}`, who('maybe')], [`Can't come ${who('no').length}`, who('no')], [`No answer ${silent.length}`, silent], ] return ( <>
{Icon('videocam')} Meeting · a call

{plan.title}

{whenWords(e.startMs, e.endMs)}
{plan.repeat && (
{Icon('repeat')} {ruleWords(plan, false)} {e.count !== null ? ` · ${ORDINAL(e.index)} of ${e.count}` : ` · the ${ORDINAL(e.index)}`}
)}
{ctx.avatar(e.planner, 20)} {ctx.where(e.channel)} · planned by {mine ? 'you' : ctx.shown(e.planner)}
{e.skipped &&

{mine ? 'You' : ctx.shown(e.planner)} took this date out of the series.

} {!e.skipped && !over && ( <> {plan.repeat && ( )}
{(['going', 'maybe', 'no'] as Rsvp[]).map((r) => ( ))}
)}
{lines.map(([label, list]) => (
{label} {list.slice(0, 5).map((p) => ctx.avatar(p, 20))} {names(list)}
))}
{plan.agenda.length > 0 && (

Agenda

{plan.agenda.map((i) => (
{i.name} {i.minutes > 0 && {i.minutes} min}
))}
)} {plan.text &&

{plan.text}

}
{mine && plan.repeat && !over && (

You planned this

{!e.skipped && ( )} {e.skipped && ( )} {plan.repeat.untilMs !== e.startMs && ( )}
)} ) } /** The planner's changes: the plan again, as an update only theirs counts for. */ function update(c: ChatClient, channel: string, plan: Plan): void { c.sendMeeting(channel, {kind: 'update', plan}) } function skip(c: ChatClient, e: MeetingEntry): void { if (isSkipped(e.plan, e.startMs)) return update(c, e.channel, {...e.plan, skip: [...e.plan.skip, e.startMs].sort((a, b) => a - b)}) } function restore(c: ChatClient, e: MeetingEntry): void { update(c, e.channel, {...e.plan, skip: e.plan.skip.filter((d) => d !== e.startMs)}) } function stop(c: ChatClient, e: MeetingEntry): void { if (!e.plan.repeat) return if (!confirm(`Stop ${e.plan.title} after ${longDate(e.startMs)}? Everybody in the chat sees it end.`)) return update(c, e.channel, {...e.plan, repeat: {...e.plan.repeat, untilMs: e.startMs}}) } function meetupDetail(ctx: CalendarCtx, e: MeetupEntry, me: string) { const mu = e.meetup const going = e.mine === 'going' const over = Date.now() > e.endMs return ( <>
{Icon('location_on')} Meet-up · a place and a time

{e.title}

{whenWords(e.startMs, null)}
{ctx.avatar(mu.proposer, 20)} {ctx.where(e.channel)} · proposed by {mu.proposer === me ? 'you' : ctx.shown(mu.proposer)}
{mu.text && mu.text !== "I'm going" &&

{mu.text}

}
Going {mu.going.length} {mu.going.slice(0, 5).map((p) => ctx.avatar(p, 20))} {mu.going.map((p) => (p === me ? 'you' : ctx.shown(p))).join(', ')}

The way there, and sharing where you are as you go, are in the app. Here you can say you are coming.

{!over && ( )}
) } /** What shows, chosen on this browser: plans you can't come to, and big communities' noise. */ function settingsMenu(ctx: CalendarCtx) { const set = st.settings const save = () => saveSettings(set) const communities = ctx.communities() return (
{Icon('settings')}

Show

{communities.length > 0 &&

Only the plans I answered

} {communities.map((x) => ( id !== x.id) save() }, }} /> ))}

Kept on this browser only.

) } /** * Plan: what kind and in which chat (v1, G), then that chat's own plan dialog * on the day picked. A meet-up needs a place picked on a map, which is the * app's; so here it is a meeting. */ function planDialog(ctx: CalendarCtx) { const open = { get value() { return st.planning }, set value(v: boolean) { st.planning = v if (!v) st.meetup = null }, } const when = dayWords(st.day) === 'Today' || dayWords(st.day) === 'Tomorrow' ? dayWords(st.day).toLowerCase() : `on ${longDate(st.day)}` const at = st.planAt === null ? '' : ` at ${clock(st.planAt)}` return ( {st.meetup ? meetupForm(ctx, st.meetup) : planPicker(ctx)} ) } /** What to plan, and in which chat. */ function planPicker(ctx: CalendarCtx) { const chats = ctx.client.chats const kind = (k: 'meeting' | 'meetup', icon: string, title: string, sub: string) => ( ) return [
{kind('meeting', 'videocam', 'Meeting', 'A call, with an agenda')} {kind('meetup', 'location_on', 'Meet up', 'A place and a time')}
,

In which chat

,
{chats.length === 0 &&

No chats yet.

} {chats.map((x) => ( ))}
, ] } /** * A meet-up from the web: the place found by name on our own address server * (there is no map on this page to point at), a time on the picked day, and an * optional line. It goes out as the same message the app's `+ → Meet up` sends. */ function meetupForm(ctx: CalendarCtx, d: MeetupDraft) { const [h, mm] = d.time.split(':').map(Number) const start = new Date(st.day) start.setHours(h || 0, mm || 0, 0, 0) const past = start.getTime() < Date.now() const ready = d.place !== null && !past const model = (key: K, then?: () => void) => ({ get value() { return d[key] }, set value(v: string) { d[key] = v then?.() }, }) return [

In {ctx.where(d.channel)}

, d.place ? (
{Icon('location_on')} {d.place.name} {d.place.area}
) : ( ), , past &&

That time has passed.

, , , ] }