# Blazor Scheduler (Event Calendar)

URL: https://flexcoreui.com/demo/scheduler  
Section: Components  
Controls: SchedulerControl, SchedulerEvent  
Keywords: scheduler, event calendar, appointment calendar, calendar component, recurring events, timeline view

A Blazor scheduler for bookings and shift schedules: day, week, month, timeline and agenda views, with resources, repeat rules, time zones and a change veto.

## Documentation

### Params

| Name | Type | Default | Description |
|---|---|---|---|
| Events | IReadOnlyList<SchedulerEvent> | Array.Empty<SchedulerEvent>() | The appointments, each with a unique Id. Two-way with @bind-Events: the control never edits this list, and every accepted change arrives as a new list of copies. Not read once OnRead has returned rows. |
| OnRead | Func<SchedulerRange,CancellationToken,Task<IReadOnlyList<SchedulerEvent>>>? | null | Loads appointments for a range instead of Events. Called with the visible SchedulerRange on the first render and whenever the range or time zone changes, and after Previous, Today, Next and a view change; a newer call cancels the older call's token. "Loading appointments" shows meanwhile, and an exception's message shows as an alert. After an accepted change the control keeps the edited list without calling it again. |
| Resources | IReadOnlyList<SchedulerResource> | Array.Empty<SchedulerResource>() | People or rooms. Day, Week, WorkWeek and MultiDay give each day one column per resource, headed with its Text, with its Color on the left edge of the timed appointments; Timeline gives each a row; Agenda prints the name; the editor offers them in a drop-down. When set, time views and Timeline show only appointments whose ResourceId matches one; Month and Agenda show all. Empty means one column or row headed "Appointments". |
| Date | DateTime | DateTime.Today | A date inside the period to show. Week and WorkWeek start at the beginning of its week, Month at the beginning of the week holding the 1st of its month; the other views start on it. Two-way with @bind-Date: Previous, Today and Next change it. |
| View | SchedulerView | SchedulerView.Week | The layout; see SchedulerView. Two-way with @bind-View: the toolbar's drop-down changes it. |
| TimeZoneId | string | "UTC" | The zone times are shown in; each appointment is converted from its own TimeZoneId. The editor fills this zone into new and edited appointments (the field can be changed), except that choosing Entire series keeps the series' zone. Any id TimeZoneInfo.FindSystemTimeZoneById accepts. |
| FirstDayOfWeek | DayOfWeek | DayOfWeek.Monday | First column of Week and WorkWeek, and of each row in Month. |
| MultiDayCount | int | 3 | Days shown by MultiDay, from Date, and the step of Previous and Next in that view. 1 to 31. |
| StartHour | int | 8 | First hour of the time grid in Day, Week, WorkWeek and MultiDay. Also the time New appointment and the Month and Timeline date buttons start a new appointment at. 0 or more and below EndHour. |
| EndHour | int | 18 | End of the time grid, at most 24. Appointments are cut to the hours shown, and one wholly outside them is not drawn in the time views (Month and Agenda still list it). |
| SlotMinutes | int | 30 | Height of a grid row in minutes, at one pixel per minute. A double-click on a row starts a new appointment at its start; a resize strip dropped on it sets the end there. 5 to 120. |
| ReadOnly | bool | false | Disables New appointment and the Month date buttons, ignores clicks on appointments and double-clicks on slots, and removes the resize strips. Previous, Today, Next and the view drop-down still work. |
| Height | string | "600px" | CSS height of the scrolling area under the toolbar. |
| Enabled (base) | bool | true | false has the same effect as ReadOnly. |
| CssClass / Style (base) | string? | null | On the fx-scheduler root element. |
| Visible (base) | bool | true | false hides the root element with display:none. |

### Events

| Name | Type | Description |
|---|---|---|
| EventsChanged | IReadOnlyList<SchedulerEvent> | After an accepted create, update or delete, with the whole new list of copies. Not raised when validation fails or Changing cancels. |
| Changing | SchedulerChangingArgs | Before a change is applied, once the whole proposed list has passed validation. Set Cancel to refuse it: the control shows no message, and the editor or the delete confirmation stays open. |
| DateChanged | DateTime | After Previous, Today or Next. |
| ViewChanged | SchedulerView | After a pick in the toolbar's view drop-down. |

### Methods

| Name | Type | Description |
|---|---|---|
| RefreshAsync() | Task | Calls OnRead again for the current range, or re-expands Events when there is no OnRead. |
| NavigateAsync(int direction) | Task | Moves Date by direction steps, back when negative: a month in Month, MultiDayCount days in MultiDay, a day in Day, seven days in the other views. Raises DateChanged, then refreshes. |
| NewAsync(DateTime start, string? resource) | Task | Opens the editor on a new one-hour appointment at start for that resource id. Ignored when read-only or disabled. |
| EditAsync(SchedulerOccurrence occurrence) | Task | Opens the editor on an occurrence, with its start and end in the scheduler's zone. Ignored when read-only or disabled. |
| Dispose() | void | Cancels a pending OnRead call; a result that arrives later is dropped. |
| Range | SchedulerRange | Read-only. The period on screen, end exclusive, in TimeZoneId: one day (Day), MultiDayCount days (MultiDay), seven days from the week start (Week, WorkWeek), 42 days from the start of the week holding the 1st (Month), seven days from Date (Timeline), 30 days from Date (Agenda). |
| SchedulerEngine.Expand(IEnumerable<SchedulerEvent> events, SchedulerRange range, int maxOccurrences = 20000) | IReadOnlyList<SchedulerOccurrence> | Static. Validates every appointment and returns the occurrences that overlap the range, repeat rules and excluded starts applied, converted into the range's zone and ordered by start, then end. Throws for an unordered range, duplicate ids, an invalid appointment, or more than maxOccurrences results. The control calls it each time it receives parameters and before offering a change. |

### Event

| Name | Type | Default | Description |
|---|---|---|---|
| Id | string | Guid.NewGuid().ToString("N") | Unique within the list; Expand throws on duplicates. |
| Title | string | "New appointment" | Required, at least one character. |
| Start | DateTime | DateTime.Today.AddHours(9) | Wall-clock time in TimeZoneId; for a repeating appointment, the first occurrence. |
| End | DateTime | DateTime.Today.AddHours(10) | Must be after Start. |
| AllDay | bool | false | A button in the column heading of the time views and "All day" in Agenda, on the same dates in every time zone. Start and End are read as dates with End exclusive, so a one-day entry ends on the next date; an all-day entry whose End is on its Start date has no length and appears only in Agenda. In the current version the button makes its day's heading taller than the hour labels' heading, so that day's time grid is drawn lower than the hour labels by the extra height. |
| TimeZoneId | string | "UTC" | The zone Start and End are written in. Must be known to FindSystemTimeZoneById, and neither time may fall in a daylight-saving gap. Expand reads this zone through Ical.Net, which uses the time-zone data built into NodaTime, but converts to the display zone with the operating system's data; where the two disagree about a zone's rules, times shift by the difference. |
| ResourceId | string? | null | Id of a SchedulerResource; picks the column or row in resource layouts. |
| Color | string? | null | A CSS color for this appointment, such as #0f766e: its edge and a light tint of the same color in the day, week, month and timeline views (all-day entries included), and a dot in the agenda. Use it to tell kinds of appointment apart. Only a real CSS color is applied (hex of 3, 4, 6 or 8 digits, rgb()/hsl() with numbers, or a named color); anything else is ignored. Null keeps the default look, in which only timed appointments take their resource's color, on the edge. |
| Description | string? | null | Plain text, edited as a text area in the editor. No view displays it. |
| RecurrenceRule | string? | null | iCalendar RRULE text such as FREQ=WEEKLY;BYDAY=TU,TH, expanded by Ical.Net. The editor's repeat drop-down offers daily, weekly, monthly and yearly; anything else is typed into the rule field. A rule Ical.Net cannot parse is refused with its message. |
| ExcludedStarts | List<DateTime> | [] | Original starts of occurrences removed from the series, in the appointment's zone. The editor adds one when a single occurrence is saved or deleted. |
| SeriesId | string? | null | Set on an entry split off from a repeating appointment, naming the series. Deleting the entire series deletes these entries too. |

### Views

| Name | Description |
|---|---|
| Day | One day from Date as a time grid: an hour column, then one column per resource. |
| Week | Seven days from the start of the week holding Date, one time-grid column per day and resource. |
| WorkWeek | The same week without the Saturday and Sunday columns. The toolbar still shows the seven-day range. |
| MultiDay | MultiDayCount days from Date, not aligned to the week, as a time grid. |
| Month | Six rows of seven day cells from the start of the week holding the 1st. Each cell lists its appointments as start time and title, and its date button starts a new one. Previous and Next move a month. |
| Timeline | A row per resource (or one "Appointments" row) with a cell for each of seven days from Date. Each cell has a date button that starts a new appointment and lists titles without times. |
| Agenda | A table of every occurrence in the 30 days from Date: date, time or "All day", the title as a button that opens the editor, and the resource. Previous and Next move seven days. |

### Actions

| Name | Description |
|---|---|
| Create | Saving the editor opened by New appointment, a double-click on a slot, a Month or Timeline date button, or NewAsync. |
| Update | Saving an edited appointment, dropping a resize strip, or saving one occurrence of a repeating appointment, which adds a new entry and excludes that date from the series. |
| Delete | Delete in the editor, after the confirmation. For one occurrence of a repeating appointment it excludes that date; for the entire series it removes the series and the entries split from it. |

### Args

| Name | Type | Default | Description |
|---|---|---|---|
| Action | SchedulerChangeAction |  | Create, Update or Delete. |
| Item | SchedulerEvent |  | A copy of the appointment being saved or deleted; changing it has no effect. For one occurrence of a repeating appointment that is saved, it is the new split-off entry with SeriesId set. |
| Cancel | bool | false | Set to true to refuse the change; the list stays as it was. |

### Records

| Name | Type | Default | Description |
|---|---|---|---|
| SchedulerResource.Id / Text | string |  | Key that ResourceId matches; the heading text. |
| SchedulerResource.Color | string | "#3274B9" | Left edge of the resource's timed appointments in Day, Week, WorkWeek and MultiDay, unless an appointment sets its own Color. All-day, Month, Timeline and Agenda entries never take the resource color. A value that is not a real CSS color draws the default blue. |
| SchedulerRange.Start / End | DateTime |  | First day and the day after the last, as OnRead receives them and Range returns them. |
| SchedulerRange.TimeZoneId | string |  | The zone of the range and of the expanded times. |
| SchedulerOccurrence.Event | SchedulerEvent |  | The appointment the occurrence comes from. |
| SchedulerOccurrence.Start / End | DateTime |  | Times in the range's zone; dates only for an all-day entry. |
| SchedulerOccurrence.OriginalStart | DateTime |  | Start in the appointment's own zone, the value ExcludedStarts receives when this occurrence is removed. |

### Css

| Name | Description |
|---|---|
| fx-scheduler | The root: a 1px border on a white background. |
| fx-scheduler-scroll | The scrolling area under the toolbar; Height sets its height. |
| fx-scheduler-time-columns · fx-time-labels · fx-time-column | The time grid (at least 700px wide, day columns at least 140px); the hour labels; one day-and-resource column. |
| fx-time-heading · fx-time-body · fx-time-slot | The sticky column heading with date, resource and all-day buttons; the body, one pixel per minute; one slot row, tinted on hover. |
| fx-timed-event · fx-schedule-resize | A positioned appointment, its left edge in its Color, or else the resource color; the 6px resize strip along its bottom. |
| fx-scheduler-month · fx-month-day · fx-appointment | The Month grid; one day cell; an appointment button in it. |
| fx-timeline-resource · fx-timeline-days | A Timeline row; its grid of day cells. |
| fx-agenda | The Agenda table. |
| fx-event-colored · fx-event-dot · fx-agenda-item | An appointment with its own Color, positioned or as a Month, Timeline or all-day button: its edge and a light tint in that color; the round Agenda dot in that color; the Agenda wrapper that lines up the dot and the title button. |

## Examples

### Week

```razor
@using Fx.ControlKit
@using Fx.ControlKit.Scheduling

<div class="controls">
    <ButtonGroupControl Items="_slotItems" Values="@(new[] { _slot.ToString() })" ValuesChanged="PickSlot" AriaLabel="Slot length" />
    <SwitchControl @bind-Checked="_readOnly" Label="Read-only" />
</div>
<div class="legend" aria-label="Kinds of tour">
    @foreach (var (kind, color) in Kinds.Where(k => _tours.Any(t => t.Color == k.Color)))
    {
        <span><i style="background:@color"></i>@kind</span>
    }
</div>
<SchedulerControl @bind-Events="_tours" @bind-Date="_date" @bind-View="_view" TimeZoneId="Europe/Lisbon" EndHour="22"
                  SlotMinutes="_slot" ReadOnly="_readOnly" Height="520px" />
<p class="result">@_view view, date @_date.ToString("dddd, MMMM d") · @_tours.Count entries in the list, @(_tours.Count(t => t.RecurrenceRule is not null)) of them repeating.</p>
```

```csharp
// A week of guided tours
private IReadOnlyList<SchedulerEvent> _tours = Tours();
private DateTime _date = DateTime.Today;
private SchedulerView _view = SchedulerView.Week;
private int _slot = 30;
private bool _readOnly;
private readonly SelectionItem[] _slotItems = { new("15", "15 min"), new("30", "30 min"), new("60", "60 min") };

private void PickSlot(IReadOnlyList<string> values)
{
    if (values.Count > 0) _slot = int.Parse(values[0]);
}

// Each kind of tour has a color: SchedulerEvent.Color tints the appointment, and the legend lists the kinds on show
private static readonly (string Kind, string Color)[] Kinds =
{
    ("Walking tour", "#0f766e"), ("Food and drink", "#b45309"), ("Day trip", "#4f46e5"), ("Evening", "#be123c"),
    ("Transfer", "#475569"), ("Call", "#7c3aed"),
};
private static string ColorOf(string kind) => Kinds.First(k => k.Kind == kind).Color;

private static SchedulerEvent[] Tours()
{
    var monday = DateTime.Today.AddDays(-(((int)DateTime.Today.DayOfWeek + 6) % 7));
    var series = monday.AddDays(-28);                 // the repeating tours started four weeks ago
    const string group = "Lisbon Explorer";          // seven nights, Saturday to Saturday
    SchedulerEvent Tour(string title, string kind, DateTime day, double from, double to, string? rule = null) => new()
    {
        Title = title, Color = ColorOf(kind), Start = day.AddHours(from), End = day.AddHours(to), TimeZoneId = "Europe/Lisbon", RecurrenceRule = rule,
    };
    return
    [
        Tour("Old town walk", "Walking tour", series, 10, 12.5, "FREQ=DAILY"),
        Tour("Food tour", "Food and drink", series.AddDays(1), 13, 16, "FREQ=WEEKLY;BYDAY=TU,TH,SA"),
        Tour("Day trip to Sintra", "Day trip", series.AddDays(2), 9, 18, "FREQ=WEEKLY;BYDAY=WE"),
        Tour("Belém walking tour", "Walking tour", series, 14, 16.5, "FREQ=WEEKLY;BYDAY=MO,FR"),
        Tour("Fado evening", "Evening", series.AddDays(4), 19.5, 21.5, "FREQ=WEEKLY;BYDAY=FR,SA"),
        Tour($"{group}: airport meet-and-greet", "Transfer", monday.AddDays(-2), 8.5, 9.5),
        Tour($"{group}: departure transfer", "Transfer", monday.AddDays(5), 8, 9),
    ];
}
```

### Rules

```razor
@using Fx.ControlKit.Scheduling

<div class="legend" aria-label="Kinds of tour">
    @foreach (var (kind, color) in Kinds.Where(k => _guided.Any(t => t.Color == k.Color)))
    {
        <span><i style="background:@color"></i>@kind</span>
    }
</div>
<SchedulerControl @bind-Events="_guided" @bind-Date="_guideDay" @bind-View="_guideView" Resources="_guides" Changing="Guard"
                  TimeZoneId="Europe/Lisbon" EndHour="20" Height="480px" />
<p class="result">@_decision</p>
```

```csharp
// Each kind of tour has a color: SchedulerEvent.Color tints the appointment, and the legend lists the kinds on show
private static readonly (string Kind, string Color)[] Kinds =
{
    ("Walking tour", "#0f766e"), ("Food and drink", "#b45309"), ("Day trip", "#4f46e5"), ("Evening", "#be123c"),
    ("Transfer", "#475569"), ("Call", "#7c3aed"),
};
private static string ColorOf(string kind) => Kinds.First(k => k.Kind == kind).Color;

// Changes the page refuses
private IReadOnlyList<SchedulerEvent> _guided = Guided();
private DateTime _guideDay = DateTime.Today;
private SchedulerView _guideView = SchedulerView.Day;
private string _decision = "No changes yet.";
// A guide's color edges the tours added here, which have no Color of their own
private readonly SchedulerResource[] _guides = { new("lavender", "Lavender", "#a21caf"), new("rufus", "Rufus", "#4d7c0f") };
private readonly Dictionary<string, int> _seatsSold = new() { ["walk"] = 6, ["belem"] = 4 };

private static SchedulerEvent[] Guided()
{
    var today = DateTime.Today;
    SchedulerEvent Tour(string id, string title, string kind, string guide, double from, double to) => new()
    {
        Id = id, Title = title, Color = ColorOf(kind), ResourceId = guide, Start = today.AddHours(from), End = today.AddHours(to), TimeZoneId = "Europe/Lisbon",
    };
    return
    [
        Tour("pickup", "Airport meet-and-greet", "Transfer", "rufus", 8.5, 9.5),
        Tour("walk", "Old town walk", "Walking tour", "lavender", 10, 12.5),
        Tour("food", "Food tour", "Food and drink", "lavender", 13, 16),
        Tour("belem", "Belém walking tour", "Walking tour", "rufus", 14, 16.5),
        Tour("sunset", "Evening at the viewpoints", "Evening", "rufus", 17.5, 19),
    ];
}

private void Guard(SchedulerChangingArgs e)
{
    var tour = e.Item;
    var clash = _guided.FirstOrDefault(t => t.Id != tour.Id && t.ResourceId == tour.ResourceId && t.Start < tour.End && tour.Start < t.End);
    var reason = e.Action switch
    {
        SchedulerChangeAction.Delete => _seatsSold.TryGetValue(tour.Id, out var sold) ? $"{sold} seats are sold" : null,
        _ when tour.Start.TimeOfDay < TimeSpan.FromHours(8) => "tours start at 8:00 AM or later",
        _ when string.IsNullOrEmpty(tour.ResourceId) => "pick a guide",
        _ when clash is not null => $"{_guides.First(g => g.Id == tour.ResourceId).Text} already leads {clash.Title} then",
        _ => null,
    };
    e.Cancel = reason is not null;
    _decision = reason is null
        ? $"Accepted: {e.Action} of '{tour.Title}', {tour.Start:h:mm tt} to {tour.End:h:mm tt}."
        : $"Refused: {e.Action} of '{tour.Title}': {reason}.";
}
```

### Zones

```razor
@using Fx.ControlKit.Scheduling

<div class="legend" aria-label="Kinds of tour">
    @foreach (var (kind, color) in Kinds.Where(k => _trip.Any(t => t.Color == k.Color)))
    {
        <span><i style="background:@color"></i>@kind</span>
    }
</div>
<div class="pair">
    <div>
        <p class="pane-title">Guide in Lisbon · <code>TimeZoneId="Europe/Lisbon"</code></p>
        <SchedulerControl @bind-Events="_trip" @bind-Date="_tripDate" @bind-View="_tripView" TimeZoneId="Europe/Lisbon"
                          StartHour="0" EndHour="24" Height="320px" />
    </div>
    <div>
        <p class="pane-title">Client in Denver · <code>TimeZoneId="America/Denver"</code></p>
        <SchedulerControl @bind-Events="_trip" @bind-Date="_tripDate" @bind-View="_tripView" TimeZoneId="America/Denver"
                          StartHour="0" EndHour="24" Height="320px" />
    </div>
</div>
<p class="result">How the list stores them:</p>
<ul class="stored">
    @foreach (var t in _trip)
    {
        <li>@t.Title, @t.Start.ToString("ddd h:mm tt") <code>@t.TimeZoneId</code></li>
    }
</ul>
```

```csharp
// Each kind of tour has a color: SchedulerEvent.Color tints the appointment, and the legend lists the kinds on show
private static readonly (string Kind, string Color)[] Kinds =
{
    ("Walking tour", "#0f766e"), ("Food and drink", "#b45309"), ("Day trip", "#4f46e5"), ("Evening", "#be123c"),
    ("Transfer", "#475569"), ("Call", "#7c3aed"),
};
private static string ColorOf(string kind) => Kinds.First(k => k.Kind == kind).Color;

// Two time zones
private IReadOnlyList<SchedulerEvent> _trip = Trip();
private DateTime _tripDate = DateTime.Today;
private SchedulerView _tripView = SchedulerView.Agenda;

private static SchedulerEvent[] Trip()
{
    var today = DateTime.Today;
    SchedulerEvent At(string title, string kind, int day, double from, double to, string zone = "Europe/Lisbon") => new()
    {
        Title = title, Color = ColorOf(kind), Start = today.AddDays(day).AddHours(from), End = today.AddDays(day).AddHours(to), TimeZoneId = zone,
    };
    return
    [
        At("Planning call", "Call", 0, 9, 9.5, "America/Denver"),
        At("Airport meet-and-greet", "Transfer", 3, 6.5, 7.5),
        At("Old town walk", "Walking tour", 3, 10, 12.5),
        At("Day trip to Sintra", "Day trip", 4, 9, 18),
        At("Fado evening", "Evening", 5, 19.5, 21.5),
        At("Departure transfer", "Transfer", 7, 8, 9),
    ];
}
```

