Skip to content

@jsvision/ui / Calendar

Class: Calendar ​

Documented in: Calendar

Defined in: ui/src/date/calendar.ts:114

A focusable month-grid day picker. Navigates a day cursor by keyboard and commits a day on Enter/Space or a single click.

Example ​

ts
import { Group, Calendar, signal, dayOfWeek, toISO, at } from '@jsvision/ui';
import type { CalendarDate } from '@jsvision/ui';

const g = new Group();
const value = signal<CalendarDate | null>(null);

const cal = new Calendar({
  value,
  firstDayOfWeek: 1,                 // Monday-first
  showWeekNumbers: true,
  isDisabled: (d) => dayOfWeek(d) === 0, // Sundays not selectable
  onChange: (d) => console.log('picked', toISO(d)),
});
const size = cal.measure();          // size the widget to the chosen density
g.add(at(cal, 1, 0, size.width, size.height));

Extends ​

Constructors ​

Constructor ​

new Calendar(opts): Calendar

Defined in: ui/src/date/calendar.ts:147

Parameters ​

opts ​

CalendarOptions

The two-way value plus optional translation, date bounds, week layout, density, disabled-day predicate, and change callback.

Returns ​

Calendar

Overrides ​

View.constructor

Properties ​

bounds ​

bounds: Rect

Defined in: ui/src/view/view.ts:66

Parent-relative integer rect; written by the layout pass — read it in draw/hit-testing.

Inherited from ​

View.bounds


castsShadow ​

castsShadow: boolean = false

Defined in: ui/src/view/view.ts:97

When true, the renderer paints a drop shadow on the cells just below and to the right of this view, in paint order (a later sibling's shadow falls over an earlier one). Default false. The Desktop sets it per window.

Inherited from ​

View.castsShadow


centered ​

centered: boolean = false

Defined in: ui/src/view/view.ts:105

When true, the layout pass recentres this view within its parent after layout — origin = (parent - self) / 2 on both axes. Intended for absolutely-placed views (a modal dialog, a message box) whose size is fixed and whose origin would otherwise be placed by the caller. Default false; Dialog sets it when centered.

Inherited from ​

View.centered


cursor ​

protected readonly cursor: Signal<CalendarDate>

Defined in: ui/src/date/calendar.ts:141

The focus cursor cell (starts at value ?? today, clamped into [min,max]).


firstDayOfWeek ​

protected readonly firstDayOfWeek: 0 | 1

Defined in: ui/src/date/calendar.ts:125


focusable ​

focusable: boolean = true

Defined in: ui/src/date/calendar.ts:116

The calendar takes focus so its day cursor and keymap are scoped to it.

Overrides ​

View.focusable


grabsFocus ​

grabsFocus: boolean = true

Defined in: ui/src/view/view.ts:122

Whether a mouse-down that hits this view moves keyboard focus to it. Default true — the usual click-to-focus. Set false for a control that should act on a click without stealing focus from whatever is focused (e.g. a dialog Cancel button, or a toolbar/stepper button): the click still dispatches, but the previously-focused view keeps focus, so it never fires a focus-leave side effect such as a field's blur-validation. Independent of focusable — a grabsFocus: false view can still be reached by Tab and activated by Space.

Inherited from ​

View.grabsFocus


i18n ​

protected readonly i18n: I18n

Defined in: ui/src/date/calendar.ts:131

Service used for framework-owned labels.


isDisabled? ​

protected readonly optional isDisabled?: (date) => boolean

Defined in: ui/src/date/calendar.ts:124

Parameters ​

date ​

CalendarDate

Returns ​

boolean


layout ​

readonly layout: Readonly<LayoutProps> = {}

Defined in: ui/src/view/view.ts:88

Layout props for this view (direction, size, padding, absolute placement, …) — read-only.

Change them with setLayout, which is the only writer. The field and every prop on it are closed, so neither view.layout = {…} nor view.layout.rect = {…} compiles, and neither does editing a solved rect a field at a time (view.layout.rect.x = 5). That is deliberate: a wholesale assignment silently drops every prop it omits and never reflows, and an in-place prop write reflows only if you remember to ask.

Read it freely — this is where a view's solved intent lives, and layout.rect is how an absolutely-placed view reports where it was put.

Inherited from ​

View.layout


max? ​

protected readonly optional max?: CalendarDate

Defined in: ui/src/date/calendar.ts:123


metrics ​

protected readonly metrics: CalendarMetrics

Defined in: ui/src/date/calendar.ts:129

Resolved layout geometry for the chosen density + week-number flag (computed once).


min? ​

protected readonly optional min?: CalendarDate

Defined in: ui/src/date/calendar.ts:122


monthNames ​

protected readonly monthNames: readonly string[]

Defined in: ui/src/date/calendar.ts:133

Localized month names indexed 1-12 (index 0 unused).


onChange? ​

protected readonly optional onChange?: (date) => void

Defined in: ui/src/date/calendar.ts:127

Parameters ​

date ​

CalendarDate

Returns ​

void


postProcess ​

postProcess: boolean = false

Defined in: ui/src/view/view.ts:126

Take part in the post-process sweep (after the focused view sees the event).

Inherited from ​

View.postProcess


preProcess ​

preProcess: boolean = false

Defined in: ui/src/view/view.ts:124

Take part in the pre-process sweep (root→down, before the focused view sees the event).

Inherited from ​

View.preProcess


showWeekNumbers ​

protected readonly showWeekNumbers: boolean

Defined in: ui/src/date/calendar.ts:126


state ​

readonly state: ViewState

Defined in: ui/src/view/view.ts:75

Draw-against flags. The object reference is fixed; individual fields mutate (e.g. focused).

Writing visible or disabled changes only what the next paint would draw — it does not ask for that paint. Follow such a write with invalidate (or invalidateLayout, which a visibility flip needs, since layout omits hidden views). A development build warns when a write goes unaccounted for.

Inherited from ​

View.state


todayDate ​

protected readonly todayDate: CalendarDate

Defined in: ui/src/date/calendar.ts:121


value ​

readonly value: Signal<CalendarDate | null>

Defined in: ui/src/date/calendar.ts:119

Two-way selected day (null = none).


visibleMonth ​

protected readonly visibleMonth: Signal<number>

Defined in: ui/src/date/calendar.ts:139


visibleYear ​

protected readonly visibleYear: Signal<number>

Defined in: ui/src/date/calendar.ts:138

The shown month (reactive — month nav repaints).


weekdayNames ​

protected readonly weekdayNames: object

Defined in: ui/src/date/calendar.ts:135

Localized weekday labels in Sunday-first order at both supported widths.

short2 ​

readonly short2: readonly string[]

short3 ​

readonly short3: readonly string[]

Methods ​

accelerators() ​

accelerators(): readonly string[]

Defined in: ui/src/view/view.ts:142

The Alt+hotkey accelerator characters (lowercase) this view claims in its focus scope, for duplicate-accelerator detection. The base returns none; accelerator-bearing widgets (Button/Label/CheckGroup/RadioGroup) override it to report their ~X~ hotkey(s).

Returns ​

readonly string[]

The claimed accelerator chars, or an empty list when the view claims none.

Inherited from ​

View.accelerators


bind() ​

bind<T>(reader, apply?, opts?): void

Defined in: ui/src/view/view.ts:326

Bind a reactive value to a redraw. Creates an effect (owned by this view's scope) that reads reader() — subscribing to whatever signals it touches — runs the optional apply(value), then requests a frame: a repaint by default, or a reflow when { relayout: true }. It re-runs automatically whenever those signals change, and is disposed when the view unmounts.

Call it from onMount, not the constructor — the view's scope only exists once mounted, so a pre-mount bind throws rather than silently dropping the binding.

Type Parameters ​

T ​

T

Parameters ​

reader ​

() => T

Reads the reactive source; the signals it reads become dependencies.

apply? ​

(v) => void

Optional: apply the read value to the widget (e.g. store it in a field).

opts? ​

Pass { relayout: true } when the change affects layout, so it reflows instead of just repainting.

relayout? ​

boolean

Returns ​

void

Example ​

ts
import { View, signal, type DrawContext } from '@jsvision/ui';

const count = signal(0);

class StatusLine extends View {
  draw(ctx: DrawContext): void {
    ctx.text(0, 0, `${count()} pending`, ctx.color('statusBar'));
  }
}

const status = new StatusLine();
// In onMount, not the constructor: bind() needs the view's scope, which only exists once mounted.
status.onMount(() => {
  status.bind(() => count()); // repaint the status line whenever `count` changes
});

Inherited from ​

View.bind


cellRole() ​

protected cellRole(date): keyof Theme

Defined in: ui/src/date/calendar.ts:299

Resolve a day cell's theme colour by precedence: cursor (only while focused) > selected > today > disabled > normal.

Parameters ​

date ​

CalendarDate

Returns ​

keyof Theme


clampBounds() ​

protected clampBounds(d): CalendarDate

Defined in: ui/src/date/calendar.ts:197

Clamp a date into [min,max] (only where the respective bound is set); the cursor never leaves it.

Parameters ​

d ​

CalendarDate

Returns ​

CalendarDate


clampVisibleMonth() ​

protected clampVisibleMonth(year, month): object

Defined in: ui/src/date/calendar.ts:233

Clamp a visible (year, month) into [min,max] at month granularity (a bound's day is ignored): the visible view can never page earlier than min's month nor later than max's month (only where the respective bound is set). Returns the clamped month via a linear month index.

Parameters ​

year ​

number

month ​

number

Returns ​

object

month ​

month: number

year ​

year: number


commit() ​

protected commit(d): void

Defined in: ui/src/date/calendar.ts:212

Commit a date to value (+ onChange); a disabled or out-of-range date is a no-op.

Parameters ​

d ​

CalendarDate

Returns ​

void


currentGrid() ​

protected currentGrid(): MonthGrid

Defined in: ui/src/date/calendar.ts:288

Build the current month's grid (pure; shared by draw + mouse hit-test).

Returns ​

MonthGrid


derived() ​

protected derived<T>(fn): () => T

Defined in: ui/src/view/view.ts:359

Create a stable derived accessor owned by this view's scope. The returned () => T keeps the same identity for the life of the view, so it is safe to build in the constructor and hand to child views before this view mounts. The backing computed is created lazily under the view's own scope, so it is always owned and disposed at unmount — unlike a bare computed() in the constructor, which would run before any scope exists, leak, and warn.

Reads behave sensibly across the lifecycle:

  • Before mount: evaluates fn() directly (correct current value, nothing persisted). Good for a pre-mount natural-size measure.
  • After mount: builds and memoizes a computed(fn) under the view's scope.
  • After an unmount→remount: the memo is keyed to the scope it was built under, so a remounted view (which gets a fresh scope) re-derives under the new scope instead of returning the previous mount's disposed, now-frozen computed — keeping a Show/For-remounted widget reactive.

Type Parameters ​

T ​

T

Parameters ​

fn ​

() => T

The derivation (pure; the signals it reads become the computed's dependencies).

Returns ​

A stable accessor; call it to read the derived value.

() => T

Inherited from ​

View.derived


desiredCaret() ​

desiredCaret(): Point | null

Defined in: ui/src/view/view.ts:239

Where this view wants the hardware text cursor, in view-local cells, or null for no cursor (the default — most views never show one). A focused text input overrides this to place the caret at the edit position; the event loop reads it after each frame, converts it to an absolute cell, and moves the terminal cursor there.

Returns ​

Point | null

The view-local caret point (0-based, relative to this view's origin), or null.

Inherited from ​

View.desiredCaret


draw() ​

draw(ctx): void

Defined in: ui/src/date/calendar.ts:310

Paint the header, weekday row, 6 grid rows, and (comfortable/spacious) the footer, per the metrics.

Parameters ​

ctx ​

DrawContext

Returns ​

void

Overrides ​

View.draw


focusSignal() ​

focusSignal(): Signal<void>

Defined in: ui/src/view/view.ts:183

Subscribe to this view's focus changes. Reading the returned signal inside a bind/effect re-runs that effect whenever this view gains or loses focus — including from another view (e.g. a Label repainting when the control it labels is focused). The signal notifies on every poke even without a value change. Lazy: the backing signal is created on first call.

Returns ​

Signal<void>

A signal that ticks whenever this view gains or loses focus.

Example ​

ts
import { View, Button, type DrawContext } from '@jsvision/ui';

// A caption that highlights while the control it labels holds focus.
class Caption extends View {
  constructor(
    private readonly text: string,
    private readonly target: View,
  ) {
    super();
    // Reading the target's focus signal inside bind() ties this view's repaint to the target's
    // focus flips — a view can observe focus it does not own.
    this.onMount(() => this.bind(() => this.target.focusSignal()()));
  }

  draw(ctx: DrawContext): void {
    ctx.text(0, 0, this.text, ctx.color(this.target.state.focused ? 'labelSelected' : 'label'));
  }
}

const ok = new Button('~O~K');
const caption = new Caption('Confirm:', ok);

Inherited from ​

View.focusSignal


goToMonth() ​

goToMonth(year, month): void

Defined in: ui/src/date/calendar.ts:282

Change the visible month only (value + cursor unchanged).

Parameters ​

year ​

number

month ​

number

Returns ​

void


handleMouse() ​

protected handleMouse(ev): void

Defined in: ui/src/date/calendar.ts:407

Header ↑↓ hit columns + the footer Today button + day-click commit — all keyed off the metrics.

Parameters ​

ev ​

DispatchEvent

Returns ​

void


invalidate() ​

invalidate(): void

Defined in: ui/src/view/view.ts:244

Request a repaint of this view. A no-op before the view is mounted (the first frame paints everything).

Returns ​

void

Inherited from ​

View.invalidate


invalidateLayout() ​

invalidateLayout(): void

Defined in: ui/src/view/view.ts:250

Request a reflow (re-run layout, then repaint). Use this when a change affects size/position, not just pixels.

Returns ​

void

Inherited from ​

View.invalidateLayout


isCommittable() ​

protected isCommittable(d): boolean

Defined in: ui/src/date/calendar.ts:204

True when a date may be committed — not disabled and within [min,max].

Parameters ​

d ​

CalendarDate

Returns ​

boolean


measure() ​

measure(): Size2D

Defined in: ui/src/date/calendar.ts:187

Advertise the density's intrinsic size (width × height) for auto sizing.

Returns ​

Size2D

Overrides ​

View.measure


moveCursor() ​

protected moveCursor(target): void

Defined in: ui/src/date/calendar.ts:219

Move the cursor (clamped), re-pointing the visible month when the target's month differs.

Parameters ​

target ​

CalendarDate

Returns ​

void


onCleanup() ​

onCleanup(fn): void

Defined in: ui/src/view/view.ts:396

Register a teardown callback that runs once when this view unmounts. Requires a mounted view — so call it from within onMount. Use it to release anything the view acquired (a timer, an external subscription).

Parameters ​

fn ​

() => void

The teardown callback.

Returns ​

void

Inherited from ​

View.onCleanup


onEvent() ​

onEvent(ev): void

Defined in: ui/src/date/calendar.ts:353

Handle keyboard (cursor/month/year navigation + commit) and mouse (header arrows, footer Today, day-click commit). Plain arrow keys are always consumed so navigation never leaves the calendar.

Parameters ​

ev ​

DispatchEvent

The dispatch envelope.

Returns ​

void

Overrides ​

View.onEvent


onMount() ​

onMount(fn): void

Defined in: ui/src/view/view.ts:381

Register a callback to run once when the view becomes live (after its first layout gives it bounds). This is where to call bind, since the view's reactive scope exists by then. Registering after the view is already live runs the callback immediately.

Parameters ​

fn ​

() => void

Post-mount setup.

Returns ​

void

Inherited from ​

View.onMount


select() ​

select(date): void

Defined in: ui/src/date/calendar.ts:269

Programmatically commit a day (respects disabled/bounds — a no-op if the day is not committable).

Parameters ​

date ​

CalendarDate

Returns ​

void


selectByClick()? ​

optional selectByClick(): void

Defined in: ui/src/view/view.ts:229

Optional "select + raise on click" hook. Left undefined on the base, so a plain view is not a select/raise target. A container that owns z-order (a Window) overrides it to select and raise itself. The hit-test invokes the first ancestor that defines this — before delivering the mouse-down — so a click always raises the window even if the interior also consumes the click.

Returns ​

void

Inherited from ​

View.selectByClick


setLayout() ​

setLayout(patch): void

Defined in: ui/src/view/view.ts:285

Change some of this view's layout props and request a reflow — the only way to write layout. Props the patch does not name are kept, and the reflow happens for you.

The merge is shallow, deliberately: size and rect are replaced whole rather than merged field-by-field. That is what makes a variant swap correct — going from {kind:'fixed',cells:1} to {kind:'fr',weight:1} must not leave a stale cells behind. The cost is that per-side padding cannot be patched one side at a time; pass the whole padding value.

Two behaviours worth knowing:

  • An explicit undefined resets that prop to its layout default. setLayout({ size: undefined }) makes the view auto-sized again, and setLayout({ position: 'flow' }) puts an absolutely-placed view back in the flow (its now-unused rect is simply ignored).
  • Do not call it in a constructor of a class that subclasses may extend. A base constructor body runs before a subclass's override readonly layout = {…} field initializer, and that initializer installs a fresh object, so the call would be erased. Call it after construction, or from onMount.

Reflowing an unmounted view is a no-op, so calling it before mount is safe.

Parameters ​

patch ​

Partial<LayoutProps>

The layout props to change; anything omitted is preserved.

Returns ​

void

Example ​

ts
import { Group } from '@jsvision/ui';

const panel = new Group();
panel.setLayout({ direction: 'col', padding: 1 });
// Later — `direction` and `padding` survive; once `panel` is mounted this also reflows:
panel.setLayout({ size: { kind: 'fr', weight: 1 } });

Inherited from ​

View.setLayout


shiftMonth() ​

protected shiftMonth(delta): void

Defined in: ui/src/date/calendar.ts:244

Shift the visible month by delta, clamped to [min,max] (the cursor and value are untouched — the +/- keys and the left header ↑↓ arrows). At a bound edge the shift is a no-op.

Parameters ​

delta ​

number

Returns ​

void


shiftYear() ​

protected shiftYear(delta): void

Defined in: ui/src/date/calendar.ts:255

Shift the visible year by delta (month kept), clamped to [min,max] (the right header ↑↓ arrows). Clamping can pull the month to the bound's month when the target year lands on a boundary year.

Parameters ​

delta ​

number

Returns ​

void


today() ​

today(): void

Defined in: ui/src/date/calendar.ts:274

Move the cursor + visible month to today.

Returns ​

void


visibleMetrics() ​

protected visibleMetrics(): CalendarMetrics

Defined in: ui/src/date/calendar.ts:192

Resolve geometry against the live assigned width while retaining the intrinsic day-cell stride.

Returns ​

CalendarMetrics


weekBoundary() ​

protected weekBoundary(cur, which): CalendarDate

Defined in: ui/src/date/calendar.ts:262

The first (or last) day of the cursor's displayed week (rotated by firstDayOfWeek).

Parameters ​

cur ​

CalendarDate

which ​

"first" | "last"

Returns ​

CalendarDate