@open-webapp/calendar 0.16.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,6 +2,8 @@
2
2
 
3
3
  Multi-account Google Calendar read-only sync (controller) plus React UI (`CalendarPane`, `CalendarSelector`). Storage and encryption are host-supplied adapters.
4
4
 
5
+ > **0.17.0 is additive and non-breaking.** The controller can load individual days, and CalendarPane adds a week strip and rendered close control. See [0.17.0](#0170-minor-additive-non-breaking).
6
+ >
5
7
  > **0.16.0 is additive and non-breaking.** New optional `resolveContact` prop supplies contact names and avatars in the event details overlay. See [0.16.0](#0160-minor-additive-non-breaking).
6
8
 
7
9
  > **0.15.0 is additive and non-breaking.** RSVP changes in the overlay now take an optional note and are sent with a Send button; `onRsvpChange` gets an optional third `note` argument. See [0.15.0](#0150-minor-additive-non-breaking).
@@ -65,6 +67,7 @@ void controller.refresh(); // then syncs from Google
65
67
  - `hydrate(): Promise<void>` loads the stored rows and publishes cached events before any network call. Never throws. Offline, the cache stays visible.
66
68
  - `refresh(): Promise<void>` syncs every source in parallel; never throws.
67
69
  - `retryDeferred(): Promise<void>` re-runs a refresh after a deferred pass (see [Deferred refresh](#deferred-refresh)).
70
+ - `loadDay(dateKey): Promise<void>` synchronizes the requested day into the current snapshot. It is additive to the rolling sync window: loaded extra days are kept in memory for the current controller lifetime and are not persisted.
68
71
  - `getEvents(): CalendarEvent[]` stable snapshot (updated on `hydrate`/`refresh`/`setSelectedIds`/`clearSelectedIds`), sources concatenated in `sources` order. Only events that pass the read-time filter are returned (see [Window](#window)).
69
72
  - `getState(): { loading, error, deferred, lastSyncAt }`:
70
73
  - `loading`: a refresh pass is in flight.
@@ -167,7 +170,7 @@ Call at top level of a vitest file; it registers a `describe('StorageAdapter con
167
170
  | `onReconnect?` | `() => void` | wired to the built-in "Reconnect to restore sync" button |
168
171
  | `emptyState?` | `ReactNode` | replaces the built-in not-connected block |
169
172
  | `sourceNotice?` | `(source) => ReactNode` | per-source slot, rendered for `needs-scope` sources (e.g. re-consent button); without it the built-in reauth block is shown |
170
- | `onClose?` | `() => void` | |
173
+ | `onClose?` | `() => void` | When provided, renders the pane close control and calls the host callback. |
171
174
  | `popupName?` | `string` | `window.open` name for the event popup window (default `notesdiary-cal-event`). The popup now opens only from the overlay's "Open in Google Calendar" link |
172
175
  | `resolveContact?` | `(email: string) => { name?: string; photoUrl?: string } \| undefined` | 0.16.0. Contact lookup for overlay invitee and organizer rows and list-row organizer labels: `name` beats `displayName`; avatar only when `photoUrl`, overlay only. Absent = unchanged. No dependency on contacts. |
173
176
  | `onRsvpChange?` | `(event: CalendarEvent, status: RsvpStatus, note?: string) => Promise<void>` | 0.14.0 (`note` added in 0.15.0). Host-owned RSVP writer. When absent, the overlay has no "Change RSVP" row. The package never writes to Google itself. See [Change RSVP](#change-rsvp-onrsvpchange) |
@@ -327,6 +330,8 @@ Day ribbon styling: each day's ribbon alternates between two tones by day parity
327
330
  - `--chip-row-height` (fallback `44px`; host may set it to match its chip row for sticky headers)
328
331
  - `--rsvp-bar` (set internally per RSVP status; do not override)
329
332
 
333
+ Week-strip hooks: `.calendar-week-strip` wraps the strip, `.calendar-week-strip-day` is each day button, and `.calendar-week-strip-day--active` marks the active day. The active day reuses the component's existing active/focus palette tokens, so hosts can style the strip through those scoped tokens without adding separate theme state.
334
+
330
335
  The Unaccepted count badge uses `.calendar-rsvp-chip-badge`, with light and dark styling included in `styles.css`.
331
336
 
332
337
  Event details overlay (0.13.0, footer-safe and redesigned in 0.14.0): `.calendar-event-details` is the backdrop (absolutely positioned inside the pane root, dimmed, bottom-aligned). In a pane with a footer, `.calendar-pane--has-footer > .calendar-event-details` sets `bottom: var(--calendar-footer-height)` so the footer is not covered. `.calendar-event-details-sheet` is the bottom sheet (max 80% of the area above the footer, scrolls internally). Both use the pane's palette tokens, so they follow the pane's `theme`. The overlay is positioned against the nearest positioned ancestor, so the pane root must stay positioned.
@@ -339,6 +344,12 @@ The shared `.calendar-selector-trigger` uses border-box inline-flex, centered al
339
344
 
340
345
  Done, Select all and Clear use the approved action-only flat styling via `.calendar-selector-actions > button` in standalone and grouped footer dropdowns: transparent resting background, zero border, no shadow, inherited font, `--calendar-selector-text` color and pointer cursor. Hover uses `--calendar-hover`; pointer focus has no decorative outline, while keyboard `:focus-visible` uses a 2px solid `--calendar-focus` outline with 2px offset. Action padding, row flex layout and 8px gap/top/bottom margins, footer/dropdown geometry, trigger/search/option styling, other native controls and all selection, callback and focus-return contracts are preserved.
341
346
 
347
+ ## 0.17.0 (minor, additive, non-breaking)
348
+
349
+ - `CalendarController.loadDay(dateKey)` synchronizes a requested day in addition to the normal rolling sync window. Extra-day results are in-memory only: they are not written to storage or retained after a new controller is created.
350
+ - `CalendarPane` now renders a week strip. Its active day uses the existing active-token highlight, and `.calendar-week-strip`, `.calendar-week-strip-day`, and `.calendar-week-strip-day--active` are available as host CSS hooks.
351
+ - `CalendarPane` now renders its close control when `onClose` is supplied; activating it calls `onClose`.
352
+
342
353
  ## 0.16.0 (minor, additive, non-breaking)
343
354
 
344
355
  - Optional `resolveContact?: (email: string) => { name?: string; photoUrl?: string } | undefined` on `CalendarPane`: in the event details overlay, a returned `name` wins over the event `displayName` (and email) on invitee rows and the organizer row, and the organizer label in list rows resolves the same way (via `getOrganizerLabel(event, resolveContact?)`, "You" kept when `organizer.self` and nothing resolves, multi-source rows keep the `· <account email>` suffix); a 20px round avatar `img` renders only when `photoUrl` is returned, in the overlay only (list rows never render avatars). The host normalizes emails; the package passes the email as given by the event. Absent prop or `undefined` result leaves output unchanged. Calendar has no dependency on `@open-webapp/contacts`; hosts wire any lookup.
@@ -18,6 +18,7 @@ export interface CalendarControllerState {
18
18
  export interface CalendarController {
19
19
  hydrate(): Promise<void>;
20
20
  refresh(): Promise<void>;
21
+ loadDay(dateKey: string): Promise<void>;
21
22
  /** Re-runs a refresh after a deferred pass. */
22
23
  retryDeferred(): Promise<void>;
23
24
  getState(): CalendarControllerState;
@@ -1,4 +1,5 @@
1
- import { CalendarFetchError, fetchCalendarList, isRefreshDeferredError } from './fetch.js';
1
+ import { CalendarFetchError, fetchCalendarList, fetchDayEvents, isRefreshDeferredError } from './fetch.js';
2
+ import { parseEvent } from './events.js';
2
3
  import { reconcileSelection } from './reconcile.js';
3
4
  import { syncCalendar } from './sync.js';
4
5
  export function createCalendarController(opts) {
@@ -7,6 +8,9 @@ export function createCalendarController(opts) {
7
8
  const state = new Map();
8
9
  const listeners = new Set();
9
10
  let snapshot = [];
11
+ const extraDays = new Map();
12
+ let dayLoading = false;
13
+ let dayGeneration = 0;
10
14
  let loadingCount = 0;
11
15
  let deferred = false;
12
16
  let statusSnapshot = {};
@@ -36,6 +40,19 @@ export function createCalendarController(opts) {
36
40
  ms(e.end.dateTime ?? e.end.date, Infinity) > ws &&
37
41
  ms(e.start.dateTime ?? e.start.date, -Infinity) < we);
38
42
  });
43
+ const key = (e) => JSON.stringify([e.sourceId, e.calendarId, e.id]);
44
+ const seen = new Set(snapshot.map(key));
45
+ for (const events of extraDays.values()) {
46
+ for (const event of events) {
47
+ if (event.calendarId && !state.get(event.sourceId)?.selectedIds.includes(event.calendarId))
48
+ continue;
49
+ const id = key(event);
50
+ if (seen.has(id))
51
+ continue;
52
+ seen.add(id);
53
+ snapshot.push(event);
54
+ }
55
+ }
39
56
  statusSnapshot = Object.fromEntries(sources.map((s) => [s.id, state.get(s.id).status]));
40
57
  listeners.forEach((l) => l());
41
58
  }
@@ -222,7 +239,52 @@ export function createCalendarController(opts) {
222
239
  }
223
240
  publish();
224
241
  },
225
- refresh: () => runPass(),
242
+ refresh() {
243
+ extraDays.clear();
244
+ dayGeneration++;
245
+ return runPass();
246
+ },
247
+ async loadDay(dateKey) {
248
+ if (dayLoading)
249
+ return;
250
+ dayLoading = true;
251
+ const generation = dayGeneration;
252
+ try {
253
+ const events = [];
254
+ await Promise.all(sources.map(async ({ id: sourceId }) => {
255
+ try {
256
+ await load(sourceId);
257
+ const token = await getToken(sourceId);
258
+ for (const calendarId of state.get(sourceId).selectedIds) {
259
+ try {
260
+ const page = await fetchDayEvents(token, calendarId, dateKey);
261
+ for (const item of page.items) {
262
+ const event = parseEvent(item, { sourceId, calendarId });
263
+ if (event)
264
+ events.push(event);
265
+ }
266
+ }
267
+ catch {
268
+ /* Keep successful calendars when another fails. */
269
+ }
270
+ }
271
+ }
272
+ catch {
273
+ /* A source's token/cache failure must not affect other sources. */
274
+ }
275
+ }));
276
+ if (generation === dayGeneration) {
277
+ extraDays.set(dateKey, events);
278
+ publish();
279
+ }
280
+ }
281
+ catch {
282
+ /* Day loads are best-effort and always resolve. */
283
+ }
284
+ finally {
285
+ dayLoading = false;
286
+ }
287
+ },
226
288
  retryDeferred: () => runPass(),
227
289
  getState() {
228
290
  const sel = sources.flatMap((s) => {
@@ -21,3 +21,5 @@ export declare function fetchEvents(token: string, calendarId: string, opts: {
21
21
  timeMin?: string;
22
22
  timeMax?: string;
23
23
  }): Promise<EventsPage>;
24
+ /** A local calendar day, including DST transitions; never participates in sync. */
25
+ export declare function fetchDayEvents(token: string, calendarId: string, dateKey: string): Promise<EventsPage>;
@@ -106,3 +106,10 @@ export async function fetchEvents(token, calendarId, opts) {
106
106
  } while (pageToken);
107
107
  return { items, nextSyncToken };
108
108
  }
109
+ /** A local calendar day, including DST transitions; never participates in sync. */
110
+ export async function fetchDayEvents(token, calendarId, dateKey) {
111
+ const [year, month, day] = dateKey.split('-').map(Number);
112
+ const start = new Date(year, month - 1, day);
113
+ const end = new Date(year, month - 1, day + 1);
114
+ return fetchEvents(token, calendarId, { timeMin: start.toISOString(), timeMax: end.toISOString() });
115
+ }
@@ -3,6 +3,7 @@ import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
3
3
  import { filterByRsvp, groupByDay, getOrganizerLabel, formatDayHeader, formatRibbonLabel, isEventCurrent, findNextUpcomingEvent, getCalendarEventKey, DEFAULT_RSVP_STATUSES, } from '../core/events.js';
4
4
  import { GroupedCalendarSelector } from './CalendarSelector.js';
5
5
  import { EventDetails } from './EventDetails.js';
6
+ import { WeekStrip } from './WeekStrip.js';
6
7
  function nextRsvpSelection(selection, status, saved) {
7
8
  const isUnacceptedOnly = selection.size === 1 && selection.has('needsAction');
8
9
  if (status === 'needsAction') {
@@ -178,6 +179,7 @@ export function CalendarPane(props) {
178
179
  const sourceColor = (id) => SOURCE_COLORS[Math.max(0, sources.findIndex((s) => s.id === id)) % SOURCE_COLORS.length];
179
180
  const sourceEmail = (id) => sources.find((s) => s.id === id)?.email ?? '';
180
181
  const todayIso = toIsoDate(new Date());
182
+ const [selectedDay, setSelectedDay] = useState(todayIso);
181
183
  const dayHeaderRefs = useRef(new Map());
182
184
  const timedEventRefs = useRef(new Map());
183
185
  const hasScrolledForEventsRef = useRef(false);
@@ -259,6 +261,14 @@ export function CalendarPane(props) {
259
261
  .map((s) => `${s.id}:${[...controller.getSelectedIds(s.id)].sort().join(',')}`)
260
262
  .join('|');
261
263
  const rsvpSignature = [...selectedRsvpStatuses].sort().join(',');
264
+ const [loadingDay, setLoadingDay] = useState(null);
265
+ const dayLoadRef = useRef(null);
266
+ const [loadedDay, setLoadedDay] = useState(null);
267
+ useEffect(() => {
268
+ setLoadingDay(null);
269
+ setLoadedDay(null);
270
+ return () => { dayLoadRef.current = null; };
271
+ }, [controller, selectionSignature, rsvpSignature]);
262
272
  const didMountFilterRef = useRef(false);
263
273
  useEffect(() => {
264
274
  if (!didMountFilterRef.current) {
@@ -365,6 +375,56 @@ export function CalendarPane(props) {
365
375
  props.onRsvpStatusesChange(selection.next);
366
376
  }
367
377
  const dayGroups = groupByDay(filteredEvents, todayIso);
378
+ const eventDays = new Set(dayGroups.filter((group) => group.events.length > 0).map((group) => group.dateKey));
379
+ useLayoutEffect(() => {
380
+ if (!loadedDay)
381
+ return;
382
+ setLoadedDay(null);
383
+ if (!eventDays.has(loadedDay))
384
+ return;
385
+ setSelectedDay(loadedDay);
386
+ dayHeaderRefs.current.get(loadedDay)?.scrollIntoView?.({ behavior: 'smooth', block: 'start' });
387
+ }, [loadedDay, eventDays]);
388
+ function selectDay(dateKey) {
389
+ const today = new Date();
390
+ const min = toIsoDate(new Date(today.getFullYear(), today.getMonth(), today.getDate() - 30));
391
+ const max = toIsoDate(new Date(today.getFullYear(), today.getMonth(), today.getDate() + 30));
392
+ if (!eventDays.has(dateKey) && (dateKey < min || dateKey > max) && typeof controller.loadDay === 'function') {
393
+ if (dayLoadRef.current)
394
+ return;
395
+ const request = {};
396
+ dayLoadRef.current = request;
397
+ setLoadingDay(dateKey);
398
+ const finish = (ok) => {
399
+ if (!mountedRef.current || dayLoadRef.current !== request)
400
+ return;
401
+ dayLoadRef.current = null;
402
+ setLoadingDay(null);
403
+ if (ok) {
404
+ // Re-read controller truth even when legacy subscriptions do not emit.
405
+ setVersion((v) => v + 1);
406
+ setLoadedDay(dateKey);
407
+ }
408
+ };
409
+ try {
410
+ Promise.resolve(controller.loadDay(dateKey)).then(() => finish(true), () => finish(false));
411
+ }
412
+ catch {
413
+ finish(false);
414
+ }
415
+ return;
416
+ }
417
+ const days = [...eventDays].sort();
418
+ const target = eventDays.has(dateKey) ? dateKey :
419
+ days.find((day) => day > dateKey) ?? days.reverse().find((day) => day < dateKey);
420
+ if (!target)
421
+ return;
422
+ setSelectedDay(target);
423
+ const header = dayHeaderRefs.current.get(target);
424
+ if (header && typeof header.scrollIntoView === 'function') {
425
+ header.scrollIntoView({ behavior: 'smooth', block: 'start' });
426
+ }
427
+ }
368
428
  function scrollToToday(behavior = 'auto') {
369
429
  const todayEl = dayHeaderRefs.current.get(todayIso);
370
430
  if (todayEl && typeof todayEl.scrollIntoView === 'function') {
@@ -517,7 +577,7 @@ export function CalendarPane(props) {
517
577
  const loading = ctrlState.loading && filteredEvents.length === 0;
518
578
  const emptyStateText = 'No matching events in the next 30 days';
519
579
  const showCalendarSelector = calendarSources.length > 0;
520
- return (_jsxs("div", { className: `calendar-pane${showCalendarSelector ? ' calendar-pane--has-footer' : ''}`, "data-calendar-theme": theme, ref: paneRef, children: [_jsxs("div", { className: "calendar-pane-scroll", ref: scrollRef, children: [_jsxs("div", { className: "calendar-rsvp-chips", ref: chipsRef, children: [_jsx("div", { className: "calendar-rsvp-chip-group", role: "group", "aria-label": "RSVP Status Filters", children: RSVP_CHIPS.map((chip) => (_jsxs("button", { type: "button", className: `calendar-rsvp-chip${selectedRsvpStatuses.has(chip.status) ? ' selected' : ''}`, "aria-pressed": selectedRsvpStatuses.has(chip.status), "aria-label": chip.status === 'needsAction' ? `${chip.label} (${unacceptedCount})` : chip.label, title: chip.status === 'needsAction' ? `${chip.label} (${unacceptedCount})` : chip.label, onClick: () => handleToggle(chip.status), children: [_jsx(RsvpGlyph, { path: chip.path }), chip.status === 'needsAction' && unacceptedCount > 0 && (_jsx("span", { className: "calendar-rsvp-chip-badge", "aria-hidden": "true", children: unacceptedCount > 99 ? '99+' : unacceptedCount }))] }, chip.status))) }), _jsx("button", { type: "button", className: "calendar-today-btn", "aria-label": "Scroll to today", title: "Scroll to today", onClick: () => recenter('smooth'), children: "Today" })] }), needsScopeSources.map((s) => (_jsx("div", { children: props.sourceNotice?.(s) }, s.id))), error && (_jsx("div", { className: "empty-state calendar-empty-state", role: "alert", children: _jsx("p", { children: "Couldn't load calendar events. Try again shortly." }) })), !(error && filteredEvents.length === 0) && (_jsxs("div", { className: "calendar-day-groups", children: [dayGroups.map((group) => (_jsxs("div", { className: "calendar-day-group", children: [_jsx("div", { className: "calendar-day-header", ref: (el) => {
580
+ return (_jsxs("div", { className: `calendar-pane${showCalendarSelector ? ' calendar-pane--has-footer' : ''}`, "data-calendar-theme": theme, ref: paneRef, children: [_jsxs("div", { className: "calendar-pane-scroll", ref: scrollRef, children: [_jsxs("div", { className: "calendar-rsvp-chips", ref: chipsRef, children: [_jsx("div", { className: "calendar-rsvp-chip-group", role: "group", "aria-label": "RSVP Status Filters", children: RSVP_CHIPS.map((chip) => (_jsxs("button", { type: "button", className: `calendar-rsvp-chip${selectedRsvpStatuses.has(chip.status) ? ' selected' : ''}`, "aria-pressed": selectedRsvpStatuses.has(chip.status), "aria-label": chip.status === 'needsAction' ? `${chip.label} (${unacceptedCount})` : chip.label, title: chip.status === 'needsAction' ? `${chip.label} (${unacceptedCount})` : chip.label, onClick: () => handleToggle(chip.status), children: [_jsx(RsvpGlyph, { path: chip.path }), chip.status === 'needsAction' && unacceptedCount > 0 && (_jsx("span", { className: "calendar-rsvp-chip-badge", "aria-hidden": "true", children: unacceptedCount > 99 ? '99+' : unacceptedCount }))] }, chip.status))) }), _jsx("button", { type: "button", className: "calendar-today-btn", "aria-label": "Scroll to today", title: "Scroll to today", onClick: () => { setSelectedDay(todayIso); recenter('smooth'); }, children: "Today" }), props.onClose && (_jsx("button", { type: "button", className: "calendar-close-btn", "aria-label": "Close", onClick: props.onClose, children: "\u00D7" }))] }), _jsx(WeekStrip, { today: new Date(), selected: selectedDay, eventDays: eventDays, loading: ctrlState.loading, loadingDay: loadingDay, onSelect: selectDay }), needsScopeSources.map((s) => (_jsx("div", { children: props.sourceNotice?.(s) }, s.id))), error && (_jsx("div", { className: "empty-state calendar-empty-state", role: "alert", children: _jsx("p", { children: "Couldn't load calendar events. Try again shortly." }) })), !(error && filteredEvents.length === 0) && (_jsxs("div", { className: "calendar-day-groups", children: [dayGroups.map((group) => (_jsxs("div", { className: "calendar-day-group", children: [_jsx("div", { className: "calendar-day-header", ref: (el) => {
521
581
  if (el) {
522
582
  dayHeaderRefs.current.set(group.dateKey, el);
523
583
  }
@@ -0,0 +1,10 @@
1
+ interface WeekStripProps {
2
+ today: Date;
3
+ selected: string;
4
+ eventDays: ReadonlySet<string>;
5
+ loading: boolean;
6
+ loadingDay?: string | null;
7
+ onSelect: (dateKey: string) => void;
8
+ }
9
+ export declare function WeekStrip({ today, selected, eventDays, loading, loadingDay, onSelect }: WeekStripProps): import("react").JSX.Element;
10
+ export {};
@@ -0,0 +1,124 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { useEffect, useLayoutEffect, useRef, useState } from 'react';
3
+ function dateKey(date) {
4
+ return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
5
+ }
6
+ export function WeekStrip({ today, selected, eventDays, loading, loadingDay, onSelect }) {
7
+ const [expanded, setExpanded] = useState(false);
8
+ const [window, setWindow] = useState({ first: 0, count: 12 });
9
+ const [topWeek, setTopWeek] = useState(0);
10
+ const monthFrame = useRef(null);
11
+ const pendingWeek = useRef(0);
12
+ const weeksRef = useRef(null);
13
+ const adjustment = useRef(null);
14
+ const pointer = useRef(null);
15
+ const suppressClick = useRef(false);
16
+ const start = new Date(today.getFullYear(), today.getMonth(), today.getDate());
17
+ start.setDate(start.getDate() - start.getDay());
18
+ const min = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 30);
19
+ const max = new Date(today.getFullYear(), today.getMonth(), today.getDate() + 30);
20
+ const todayKey = dateKey(today);
21
+ const wednesday = new Date(start.getFullYear(), start.getMonth(), start.getDate() + topWeek * 7 + 3);
22
+ const monthLabel = wednesday.toLocaleDateString('en-US', {
23
+ month: 'long',
24
+ ...(wednesday.getFullYear() !== new Date().getFullYear() ? { year: 'numeric' } : {}),
25
+ });
26
+ function resetGrid() {
27
+ if (monthFrame.current !== null)
28
+ cancelAnimationFrame(monthFrame.current);
29
+ monthFrame.current = null;
30
+ setTopWeek(0);
31
+ setWindow({ first: 0, count: 12 });
32
+ adjustment.current = 0;
33
+ }
34
+ function toggle(next) {
35
+ setExpanded(next);
36
+ resetGrid();
37
+ }
38
+ useEffect(() => {
39
+ // Today lives in the pane toolbar; observe its existing control without
40
+ // adding another button or depending on a selected-date change.
41
+ const pane = weeksRef.current?.closest('.calendar-pane');
42
+ function onToday(event) {
43
+ if (event.target instanceof Element && event.target.closest('.calendar-today-btn'))
44
+ resetGrid();
45
+ }
46
+ pane?.addEventListener('click', onToday);
47
+ return () => {
48
+ pane?.removeEventListener('click', onToday);
49
+ if (monthFrame.current !== null)
50
+ cancelAnimationFrame(monthFrame.current);
51
+ };
52
+ }, []);
53
+ useLayoutEffect(() => {
54
+ if (weeksRef.current && adjustment.current !== null) {
55
+ weeksRef.current.scrollTop = adjustment.current;
56
+ adjustment.current = null;
57
+ }
58
+ }, [expanded, window]);
59
+ return (_jsxs("div", { className: "calendar-weekstrip", role: "group", "aria-label": "Week", "aria-busy": loading || !!loadingDay, children: [_jsx("div", { className: "calendar-weekstrip-month", children: monthLabel }), _jsxs("div", { role: "table", "aria-label": "Week dates", children: [_jsx("div", { className: "calendar-weekstrip-row", role: "row", children: ['S', 'M', 'T', 'W', 'T', 'F', 'S'].map((label, index) => (_jsx("span", { role: "columnheader", children: label }, index))) }), _jsx("div", { ref: weeksRef, className: `calendar-weekstrip-weeks${expanded ? ' calendar-weekstrip-weeks--expanded' : ''}`, role: "rowgroup", onScroll: (event) => {
60
+ if (!expanded || adjustment.current !== null)
61
+ return;
62
+ const element = event.currentTarget;
63
+ const height = element.firstElementChild?.getBoundingClientRect().height ?? 0;
64
+ if (!height)
65
+ return;
66
+ pendingWeek.current = window.first + Math.floor(Math.max(0, element.scrollTop) / height);
67
+ if (monthFrame.current === null) {
68
+ monthFrame.current = requestAnimationFrame(() => {
69
+ monthFrame.current = null;
70
+ setTopWeek(pendingWeek.current);
71
+ });
72
+ }
73
+ if (element.scrollTop <= height) {
74
+ adjustment.current = element.scrollTop + 12 * height;
75
+ setWindow({ first: window.first - 12, count: Math.min(36, window.count + 12) });
76
+ }
77
+ else if (element.scrollHeight - element.clientHeight - element.scrollTop <= height) {
78
+ const removed = Math.max(0, window.count + 12 - 36);
79
+ adjustment.current = element.scrollTop - removed * height;
80
+ setWindow({ first: window.first + removed, count: Math.min(36, window.count + 12) });
81
+ }
82
+ }, children: Array.from({ length: expanded ? window.count : 1 }, (_, week) => {
83
+ const weekStart = new Date(start.getFullYear(), start.getMonth(), start.getDate() + (expanded ? window.first + week : 0) * 7);
84
+ return _jsx("div", { className: "calendar-weekstrip-row calendar-weekstrip-week", role: "row", "aria-label": `Week of ${dateKey(weekStart)}`, children: Array.from({ length: 7 }, (_, index) => {
85
+ const date = new Date(weekStart.getFullYear(), weekStart.getMonth(), weekStart.getDate() + index);
86
+ const key = dateKey(date);
87
+ const outsideWindow = (date < min || date > max) && !eventDays.has(key);
88
+ const isLoading = key === loadingDay;
89
+ const isToday = key === todayKey;
90
+ const isSelected = key === selected;
91
+ const hasEvents = eventDays.has(key);
92
+ const modifiers = [isToday && 'today', isSelected && 'selected', hasEvents && 'has-events', outsideWindow && 'outside-window', isLoading && 'loading'].filter(Boolean);
93
+ return (_jsx("div", { role: "cell", children: _jsxs("button", { type: "button", className: `calendar-weekstrip-day${modifiers.map((modifier) => ` calendar-weekstrip-day--${modifier}`).join('')}`, "aria-label": key, "aria-current": isToday ? 'date' : undefined, "aria-pressed": isSelected, "aria-busy": isLoading, "data-outside-window": outsideWindow, onClick: () => onSelect(key), children: [date.getDate(), (hasEvents || isLoading) && _jsx("span", { className: "calendar-weekstrip-dot", role: "img", "aria-label": isLoading ? 'Loading events' : 'Has events', children: "\u2022" })] }) }, key));
94
+ }) }, dateKey(weekStart));
95
+ }) })] }), _jsx("button", { type: "button", className: "calendar-weekstrip-handle", "aria-label": "Toggle calendar weeks", "aria-expanded": expanded, onClick: () => {
96
+ if (suppressClick.current) {
97
+ suppressClick.current = false;
98
+ return;
99
+ }
100
+ toggle(!expanded);
101
+ }, onKeyDown: (event) => {
102
+ if (event.key === 'Enter' || event.key === ' ') {
103
+ event.preventDefault();
104
+ suppressClick.current = false;
105
+ toggle(!expanded);
106
+ }
107
+ }, onPointerDown: (event) => {
108
+ if (event.button !== 0)
109
+ return;
110
+ suppressClick.current = false;
111
+ pointer.current = { id: event.pointerId, y: event.clientY };
112
+ event.currentTarget.setPointerCapture?.(event.pointerId);
113
+ }, onPointerUp: (event) => {
114
+ const gesture = pointer.current;
115
+ pointer.current = null;
116
+ if (!gesture || gesture.id !== event.pointerId)
117
+ return;
118
+ const distance = event.clientY - gesture.y;
119
+ if (Math.abs(distance) >= 24) {
120
+ suppressClick.current = true;
121
+ toggle(distance > 0);
122
+ }
123
+ }, onPointerCancel: () => { pointer.current = null; suppressClick.current = false; }, onLostPointerCapture: () => { pointer.current = null; }, children: _jsx("span", { "aria-hidden": "true", children: expanded ? '▴' : '▾' }) })] }));
124
+ }
@@ -0,0 +1,10 @@
1
+ export declare function localDateKey(date: Date): string;
2
+ export declare function startOfWeek(key: string): string;
3
+ export declare function addDays(key: string, days: number): string;
4
+ export declare function weekRows(startKey: string, count: number): string[][];
5
+ /** A row belongs to the month containing its Wednesday. */
6
+ export declare function monthOfRow(weekStartKey: string): string;
7
+ /** Prefer the first later event date, falling back to the last earlier date. */
8
+ export declare function nearestDayWithEvents(key: string, dates: ReadonlySet<string>): string | null;
9
+ /** Inclusive calendar-day distance from the local date of now. */
10
+ export declare function inWindow(key: string, now: Date, days?: number): boolean;
@@ -0,0 +1,71 @@
1
+ const DAY_MS = 86_400_000;
2
+ function dateKey(year, month, day) {
3
+ if (!Number.isInteger(year) || year < 0 || year > 9999) {
4
+ throw new RangeError('Invalid date');
5
+ }
6
+ return `${String(year).padStart(4, '0')}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
7
+ }
8
+ function parseKey(key) {
9
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(key)) {
10
+ throw new RangeError('Invalid date key');
11
+ }
12
+ const year = Number(key.slice(0, 4));
13
+ const month = Number(key.slice(5, 7));
14
+ const day = Number(key.slice(8, 10));
15
+ const date = new Date(0);
16
+ date.setUTCFullYear(year, month - 1, day);
17
+ if (date.getUTCFullYear() !== year || date.getUTCMonth() !== month - 1 || date.getUTCDate() !== day) {
18
+ throw new RangeError('Invalid date key');
19
+ }
20
+ return date;
21
+ }
22
+ function utcDateKey(date) {
23
+ return dateKey(date.getUTCFullYear(), date.getUTCMonth() + 1, date.getUTCDate());
24
+ }
25
+ export function localDateKey(date) {
26
+ return dateKey(date.getFullYear(), date.getMonth() + 1, date.getDate());
27
+ }
28
+ export function startOfWeek(key) {
29
+ const date = parseKey(key);
30
+ date.setUTCDate(date.getUTCDate() - date.getUTCDay());
31
+ return utcDateKey(date);
32
+ }
33
+ export function addDays(key, days) {
34
+ const date = parseKey(key);
35
+ if (!Number.isInteger(days))
36
+ throw new RangeError('Invalid day offset');
37
+ date.setUTCDate(date.getUTCDate() + days);
38
+ return utcDateKey(date);
39
+ }
40
+ export function weekRows(startKey, count) {
41
+ parseKey(startKey);
42
+ if (!Number.isInteger(count) || count < 0)
43
+ throw new RangeError('Invalid week count');
44
+ return Array.from({ length: count }, (_, week) => Array.from({ length: 7 }, (_, day) => addDays(startKey, week * 7 + day)));
45
+ }
46
+ /** A row belongs to the month containing its Wednesday. */
47
+ export function monthOfRow(weekStartKey) {
48
+ return addDays(weekStartKey, 3).slice(0, 7);
49
+ }
50
+ /** Prefer the first later event date, falling back to the last earlier date. */
51
+ export function nearestDayWithEvents(key, dates) {
52
+ parseKey(key);
53
+ let next = null;
54
+ let previous = null;
55
+ for (const date of dates) {
56
+ parseKey(date);
57
+ if (date > key && (next === null || date < next))
58
+ next = date;
59
+ if (date < key && (previous === null || date > previous))
60
+ previous = date;
61
+ }
62
+ return next ?? previous;
63
+ }
64
+ /** Inclusive calendar-day distance from the local date of now. */
65
+ export function inWindow(key, now, days = 30) {
66
+ const date = parseKey(key);
67
+ const today = parseKey(localDateKey(now));
68
+ if (!Number.isInteger(days) || days < 0)
69
+ throw new RangeError('Invalid window size');
70
+ return Math.abs(date.getTime() - today.getTime()) <= days * DAY_MS;
71
+ }
package/dist/styles.css CHANGED
@@ -238,6 +238,10 @@
238
238
 
239
239
  .calendar-today-btn {
240
240
  margin-left: auto;
241
+ }
242
+
243
+ .calendar-today-btn,
244
+ .calendar-close-btn {
241
245
  flex-shrink: 0;
242
246
  padding: 4px 8px;
243
247
  border: 0;
@@ -251,10 +255,109 @@
251
255
  cursor: pointer;
252
256
  }
253
257
 
254
- .calendar-today-btn:hover {
258
+ .calendar-today-btn:hover,
259
+ .calendar-close-btn:hover {
255
260
  background: var(--calendar-today-hover);
256
261
  }
257
262
 
263
+ .calendar-weekstrip {
264
+ padding: 0 16px 12px;
265
+ color: var(--calendar-card-time);
266
+ font-size: 11px;
267
+ text-align: center;
268
+ }
269
+
270
+ .calendar-weekstrip-month {
271
+ margin-bottom: 8px;
272
+ color: var(--calendar-card-title);
273
+ font-size: 13px;
274
+ font-weight: 600;
275
+ text-align: left;
276
+ }
277
+
278
+ .calendar-weekstrip-row {
279
+ display: grid;
280
+ grid-template-columns: repeat(7, minmax(0, 1fr));
281
+ gap: 4px;
282
+ }
283
+
284
+ .calendar-weekstrip-weeks {
285
+ overflow-anchor: none;
286
+ }
287
+
288
+ .calendar-weekstrip-weeks--expanded {
289
+ height: 264px;
290
+ overflow-y: auto;
291
+ scroll-snap-type: y mandatory;
292
+ }
293
+
294
+ .calendar-weekstrip-week {
295
+ height: 44px;
296
+ scroll-snap-align: start;
297
+ }
298
+
299
+ .calendar-weekstrip-handle {
300
+ display: block;
301
+ width: 100%;
302
+ min-height: 24px;
303
+ border: 0;
304
+ background: transparent;
305
+ color: inherit;
306
+ cursor: pointer;
307
+ touch-action: none;
308
+ }
309
+
310
+ .calendar-weekstrip-handle:focus-visible {
311
+ outline: 2px solid var(--calendar-focus);
312
+ }
313
+
314
+ .calendar-weekstrip-day {
315
+ display: flex;
316
+ flex-direction: column;
317
+ align-items: center;
318
+ justify-content: center;
319
+ width: 100%;
320
+ min-height: 40px;
321
+ margin-top: 4px;
322
+ border: 1px solid var(--calendar-card-border);
323
+ border-radius: 8px;
324
+ background: var(--calendar-card-background);
325
+ color: var(--calendar-card-title);
326
+ font: inherit;
327
+ cursor: pointer;
328
+ }
329
+
330
+ .calendar-weekstrip-day:hover {
331
+ background: var(--calendar-hover);
332
+ }
333
+
334
+ .calendar-weekstrip-day:focus-visible {
335
+ outline: 2px solid var(--calendar-focus);
336
+ outline-offset: 1px;
337
+ }
338
+
339
+ .calendar-weekstrip-day--outside-window {
340
+ opacity: 0.5;
341
+ }
342
+
343
+ .calendar-weekstrip-dot {
344
+ color: var(--calendar-accent);
345
+ line-height: 8px;
346
+ }
347
+
348
+ .calendar-weekstrip-day--loading .calendar-weekstrip-dot {
349
+ animation: calendar-weekstrip-pulse 1s ease-in-out infinite alternate;
350
+ }
351
+
352
+ @keyframes calendar-weekstrip-pulse {
353
+ from { opacity: 0.35; }
354
+ to { opacity: 1; }
355
+ }
356
+
357
+ @media (prefers-reduced-motion: reduce) {
358
+ .calendar-weekstrip-day--loading .calendar-weekstrip-dot { animation: none; }
359
+ }
360
+
258
361
  .calendar-empty-state {
259
362
  padding: 24px 16px;
260
363
  color: var(--calendar-empty);
@@ -503,7 +606,9 @@
503
606
  }
504
607
 
505
608
  .calendar-event-row--current,
506
- .calendar-event-row--selected {
609
+ .calendar-event-row--selected,
610
+ .calendar-weekstrip-day--today,
611
+ .calendar-weekstrip-day--selected {
507
612
  border-color: var(--calendar-card-active-border);
508
613
  box-shadow: 0 0 0 1px var(--calendar-card-active-ring);
509
614
  background: var(--calendar-card-active-background);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-webapp/calendar",
3
- "version": "0.16.0",
3
+ "version": "0.17.0",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",