@tasknotes/calendar
v0.1.12
Published
Task-native calendar engine for TaskNotes: incremental layout, time grid, month, list, year and timeline views.
Maintainers
Readme
@tasknotes/calendar
A task-native calendar engine for TaskNotes: week/day/N-day time grid, month, list, year and timeline views, with incremental rendering, DST-safe drag arithmetic and popout-window support. No runtime dependencies.
Install
npm install @tasknotes/calendar
# Only for the optional React wrapper:
npm install reactES modules and CommonJS (require("@tasknotes/calendar")) are supported.
Import the stylesheet once in your bundler. React 18+ is an optional peer; the
DOM and core entry points have no runtime dependencies. Use a modern browser
with CSS Grid, color-mix(), Pointer Events and ResizeObserver. Node 22+
is supported for tooling and DOM-free core use.
Usage
import { Calendar } from "@tasknotes/calendar";
import "@tasknotes/calendar/calendar.css";
const calendar = new Calendar(el, {
view: "week",
timeZone: "local",
editable: true,
onItemDrop: ({ item, startStr, endStr, revert }) => save(item.id, startStr, endStr).catch(revert),
});
calendar.setItems([{ id: "t1", title: "Plan sprint", start: "2026-10-21T10:00", end: "2026-10-21T11:30" }]);
// On host/component teardown:
// calendar.destroy();Give el a height (for example height: 600px) for the default
height: "fill", or choose height: "auto" to grow with content.
The host persists changes; the calendar supplies optimistic updates and a
revert() function. Destroy the instance to release listeners and observers.
- Items take
start/endasYYYY-MM-DD(all-day) orYYYY-MM-DDTHH:mm(floating, read in the calendar's zone), ISO strings with an offset, or epoch ms.endis exclusive. Optional fields:allDay,color,kind,lane("plan"/"actual"),display: "background",completed,dependsOn,rev(cheap change signature),data. - Updates are incremental:
setItemsdiffs against the previous set, andupsertItems/removeItemsre-render only the days touched. Render hooks (itemDidMount, …) fire only for elements that actually change, but every callback'sitemis the object most recently passed in for that id, soitem.datais never stale. - Render hooks (
itemContent,itemClassNames,itemDidMount,itemWillUnmount,listItemContent) getvariant("timed","bar","dot","indicator","list","timeline") andtimeText, the time label in the calendar's locale and hour format ("9am – 10:30am"for timed, list and timeline items, the start for bars and dots, empty for all-day items). - Preview items: set
preview: trueon a temporary item passed throughupsertItemsto show a host-managed group-drag placement. Previews have mirror styling, are hidden from assistive navigation, cannot be activated or edited, and remain visible beyond month/all-day event limits and timed stack limits. Multiple overflow previews stack without covering each other.itemDidMountreportsisMirror: true. Restore the original item (or remove the preview ID) on drop, cancellation, source refresh and teardown; this flag does not persist or automatically commit a group. - Drags move the item itself with the pointer in every view (time grid, all-day row, month, timeline), for mouse and touch; the dragged item is never folded into "+N more".
- Changes (
onItemDrop,onItemResize,onSelect,onExternalDrop) report TaskNotes storage strings (startStr/endStr),revert(), andsource: "pointer" | "keyboard". Returning a rejected promise reverts. - Clicks:
onDateClickreportsminute(the slot's wall-clock minute, snapped toslotDuration; null for day cells and the all-day row),allDayandstartStr("YYYY-MM-DD"or"YYYY-MM-DDTHH:mm"), so a tap on a slot can prefill a time. - Input: mouse drag after 4px, touch long press (
longPressDelay), keyboard (Enter/Space, Shift+F10, Alt+Arrow to move, Alt+Shift+Arrow to resize), external drags viabeginExternalDragor native HTML5 drops. - Pinch: two fingers on a time grid rescale
slotHeightbetween 16 and 96px, keeping the time under the fingers in place.onSlotHeightChangereports the settled height for the host to store;pinchZoom: falseleaves the gesture to the browser. - Popouts: all listeners, timers and observers use the host element's
ownerDocument; barewindow/documentare lint errors insrc.
Views and options
| view | Layout |
| --- | --- |
| "week" / "day" / "days" | Time grid; dayCount controls the N-day view |
| "month" | Month cells, full items or compact dots |
| "list" | Agenda for listDayCount days (default 7) |
| "year" | Twelve mini-months with activity indicators |
| "timeline" | Resource/task rows with dependency bars |
Pass partial options to the constructor or setOptions().
changeView(), gotoDate(), prev(), next() and goToday() control navigation.
Common options include date, timeZone ("local" or an IANA zone),
locale, firstDay (0–6), hour12, weekends, hiddenDays,
weekNumbers, toolbar, editable, selectable, navLinks,
dayMaxEvents, slotMinTime, slotMaxTime, slotDuration,
snapDuration, scrollTime and nowIndicator. The time grid defaults
to 00:00–24:00 in 30-minute slots, initially scrolled to 08:00.
text supplies translated labels; itemContent and related hooks supply
custom DOM. The exported CalendarOptions<D> type documents the full API.
toolbar.viewDisplay defaults to "auto": full view-name buttons become a
native select when the toolbar cannot fit them. Use "buttons" or "select"
to choose a fixed presentation. The select uses the same translated view names
and changes views through the same navigation lifecycle as the buttons.
Month and list
monthDisplay: "chips"uses compact filled title strips instead of dots, clipped without ellipses, with a counted overflow row. Set--tnc-chip-hto size the rows. Like dots, chips are passive summaries: the whole day cell is the keyboard and pointer target, and the host can open a full selected-day list throughonDateClick.gotoDate()within the displayed month updates the navigation anchor without rebuilding its cells, preserving keyboard focus when a host selects a day. A subsequent view switch uses that selected date.listEmptyContent()may return a host-owned DOM node for an empty list, such as an explanation and recovery action. The default translated empty message remains when omitted. The node is removed when the list gains items.monthDisplay: "dots"draws every item in a month cell as a small dot (--tnc-dot-size,--tnc-dot-gap) that wraps across the cell, with "+N" when they do not fit;dayMaxEventscaps the dots (falselets cells grow). The day cell is the tap target: dots ignore the pointer, arearia-hidden, get no content hook, and the cell is labelled ", N items" (text.itemCount). Items in dots havevariant: "indicator"; colour them withcolororitemDidMountsetting--tnc-c."+N more" height: day rows (and the time grid's all-day row) make room for the link at its rendered height, so a host may give it a 44px touch target (
--tnc-more-h, or any min-height) without overflowing the row.listStart: "date" | "week": the list view starts at the date (default; FullCalendarduration: { days: n }lists, as the TaskNotes plugin and app used) or at the start of its week (FullCalendar's stocklistWeek); week-aligned lists step by whole weeks.listAgenda: boolean: turns the list view into a phone-style agenda. A date strip shows one week, or the whole month after a tap on its title, with a dot on busy days and the day at the top of the list marked. Below it, every day gets a section, empty days included, and more days load as the list nears its end. Picking a strip day scrolls the list to it and reports it throughonDateClick. Rows can be dragged onto another day's section or a strip day; timed items keep their time. Atheight: "auto"the strip sticks to the top of the page; set--tnc-sticky-topto keep it below a fixed host header. A Today chip appears in the strip's header when the list is away from today. Hosts can mount controls after the strip's arrows withstripSlotDidMount.dateStrip: boolean: puts the same strip above theday,daysandweekviews. Picking a day moves the grid to it, the rest of the grid's range is tinted, and items dragged onto a strip day move there at the same time.listLeadTitle: string | nullandlistLeadIncludes(item): in an agenda, a section above the first day holds the itemslistLeadIncludespicks out (overdue work, say) instead of their days.listLeadDidMountgives hosts a slot in its header for actions.listAddText: string | nullandonListAdd(arg): in an agenda, an add row under every day, reported with that day.ViewInfo.dataRange: the visible range, run on to the end of the days a strip shows. Load items fordataRangeso every strip day gets its dot;onRangeChangealso fires when only it changes.
Timeline
view: "timeline" draws one row per timeline.rows entry (rowOf(item) picks the row) with bars, milestones (kind: "milestone") and dependency arrows (timeline.dependencies).
- Scale:
timeline.scale = { unit, dayWidth | unitWidth, snapMinutes }.dayWidthsets pixels per day directly;unitthen only chooses the header ticks.TIMELINE_UNIT_DAYSis the days-per-unit table used to turnunitWidthinto a day width. - Dependencies:
dependsOntakes ids (finish-to-start) or{ id, type: "FS" | "SS" | "FF" | "SF" }. Arrows leave and enter the edges the type names, anddependencyConflicts(alsodependencySatisfied,itemDependencies,dependencyTypein core) checks those edges. - Linking: with
timeline.onLink, bars get start and finish link handles (a milestone has one). Dragging from a handle to another bar's handle, or to its body (nearer edge; a milestone's body is its start), callsonLink({ from, to, fromEdge, toEdge, type }).canLinkreturnsfalseor a reason to refuse a target live, andonLinkDragreportsstart/over/endphases for feedback. On touch, handles show on the bar inselected(44px hit areas) and on every bar while linking. - Selection: the
selectedoption (id or ids) marks barsis-selectedwithout a rebuild. - Hit testing:
calendar.hitTest(x, y)returns{ kind: "timeline", day, minute, rowId, area, overTrack }whereareais"track","header","label"or"outside"(inside the chart but past the rows or range), and null outside the chart. External drags (beginExternalDrag) drop on rows, group headings and the date header;onExternalDropcarries thehit, andonExternalDragEnd({ source, dropped, hit })fires for every external drag, dropped or not. - Scrolling and zoom:
calendar.scrollToDate(date, { align: "start" | "center" | "end", smooth }). In the timeline,setOptionskeeps what is on screen whendate, range or scale change (a scale change keeps the middle of the visible track);setOptions(next, { anchor: { clientX } })keeps the instant under the pointer instead, e.g. for Ctrl+wheel zoom. - Row labels:
rowLabelDidMount({ row, el })/rowLabelWillUnmounthand you each label cell to fill (React portals work); rows compare by value, so unchanged rows keep their cells, and a rows-only change re-renders in place. The click that ends a drag is swallowed in the capture phase, before it reaches content in the calendar. - Small bars: bars under 28px hide their title; under 20px they drop their resize grips and get a wider hit area so they still move and tap.
- Keyboard:
resizeHandleLabel({ item, edge })makes the grips focusable buttons; Left/Right on a focused grip moves that edge by the snap.todayLabellabels the today line.
@tasknotes/calendar/core exposes the DOM-free parts (zones, store, layout, ordering, planning helpers) and @tasknotes/calendar/react a thin TaskCalendar wrapper.
TaskNotes Bases settings
basesLayoutOptions(settings) maps the settings stored by the TaskNotes plugin's Bases calendar view (viewFromBases/viewToBases translate the FullCalendar view names held in .base files) to calendar options, applying the plugin's normalisation so existing settings keep their meaning. Saved listWeek views keep starting at the date (listStart: "date"): the plugin configured FullCalendar's list as duration: { days: listDayCount }, which aligns to the day, not the week. See docs/integration/plugin-bases-calendar-spec.md.
Theming
Set --tnc-theme-* variables on the host (they inherit into the calendar)
or on .tnc. The stylesheet is scoped to .tnc and does not inject CSS.
Time grids collapse crowded collision groups into labelled, expandable stacks
instead of widening every day. --tnc-event-min-width sets the readable event
width in pixels (default 128). Keep the day minimum independent of collisions:
.my-calendar .tnc-tg {
--tnc-col-min: 128px;
--tnc-event-min-width: 128px;
}When the day minimums exceed a narrow viewport, persistent day buttons reveal
offscreen dates, and Today reveals the current day. Headers, all-day rows and
timed columns stay aligned. --tnc-collision-columns remains available as
diagnostic metadata (respecting eventMaxStack), not a week-wide width multiplier.
Overflow dialogs clamp to the visible calendar and viewport, scroll vertically,
and support Tab, arrow keys, Home, End and Escape. Timed items dragged from
overflow start at their actual time rather than the slot underneath the dialog.
Timed events also expose --tnc-event-readable-width, the percentage of their
width not covered by the next collision column. Hosts can use it as the
max-width of .tnc-item-main to keep text readable while preserving the user's
overlapping event backgrounds. It is 100% for non-overlapping placements.
.my-calendar {
--tnc-theme-bg: #181818;
--tnc-theme-bg-2: #222;
--tnc-theme-bg-3: #303030;
--tnc-theme-text: #f5f5f5;
--tnc-theme-muted: #bbb;
--tnc-theme-faint: #aaa;
--tnc-theme-line: #444;
--tnc-theme-line-strong: #666;
--tnc-theme-accent: #b6a3ff;
--tnc-theme-accent-text: #181818;
}Additional semantic colours: --tnc-theme-now, --tnc-theme-warn,
--tnc-theme-ok, --tnc-theme-amber. Item colours come from color,
backgroundColor, borderColor and textColor.
Set an item's timeDisplay: "start" for deadlines or other point-in-time markers:
visible and accessible labels show only its exact start time. This presentation
option does not alter the item's stored dates, layout duration or hit area.
Override sizing tokens such as --tnc-font-size, --tnc-small,
--tnc-radius, --tnc-bar-h, --tnc-more-h, --tnc-dot-size and
--tnc-dot-gap directly on .tnc (not just its ancestor).
Accessibility
Items are labelled, focusable buttons: Enter/Space activates, Shift+F10 opens
the host's context menu, Alt+Arrow moves, and Alt+Shift+Arrow resizes when
editing is allowed (the list and year views are read-only). Month dots and year days expose date/item-count labels;
Enter/Space invokes onDateClick. Dots are summaries, not individual item
controls. Time grid and timeline expose labelled tables; month exposes a grid.
Full arrow-key grid navigation, keyboard dependency linking and keyboard range
selection are not implemented. Hosts must provide alternatives for those actions.
Structural ARIA checks are not a full WCAG audit; verify contrast and custom hook
content in your own theme.
Development
npm ci
npm run playground # http://localhost:4187 — demo data, options form, event log
npm test # unit tests (vitest)
npm run test:browser # Playwright: Chromium + touch (Pixel 7)
npm run lint && npm run typecheck
npm run build # dist/esm, dist/cjs, dist/types, dist/calendar.css
npm run test:package # pack/install; ESM, CJS, CSS, React and strict consumer typesVisual baselines and interaction tests use Chromium in the official
mcr.microsoft.com/playwright:v1.64.1-noble image, also used by CI. To run
the same environment locally (Docker required):
docker run --rm --ipc=host -v "$PWD:/work" -w /work \\
-v /work/node_modules -e CI=true \\
mcr.microsoft.com/playwright:v1.64.1-noble \\
bash -lc 'npm ci && npm run test:browser'Append -- --update-snapshots to the test command to regenerate baselines
inside that image, then review the PNGs before accepting them. Tests fix
the date, timezone, locale, viewport, colour scheme and motion preference.
Keep the image version and the exact @playwright/test pin in sync.
The playground reads URL parameters (view, tz, locale, date, theme, stress, height, capacity, display=dots, listStart=week, agenda=1 (agenda list and day strips with add rows), lead=1 (a Due lead section)) and exposes window.tnc for scripted checks.
