# Blazor AutoComplete, Stepper and Color Palette

URL: https://flexcoreui.com/demo/pickers  
Section: Components  
Controls: AutoCompleteControl, StepperControl, ColorPaletteControl  
Keywords: autocomplete, typeahead, stepper, wizard steps, color picker, color palette

Help users choose in Blazor: an autocomplete that suggests as they type, a stepper that guides them through steps, and a palette of your own swatches.

## Documentation

### Auto

| Name | Type | Default | Description |
|---|---|---|---|
| DataSource | IEnumerable<TItem> | Array.Empty<TItem>() | Items to filter when OnRead is not set. |
| TextSelector | Func<TItem, string>? | null | Text of an item. When null, TextField is read by reflection; when that is blank too, ToString(). |
| TextField | string | "" | Name of the property that holds an item's text. |
| Value | string? | null | The committed text: a chosen suggestion, or typed text accepted with Enter, Tab or by leaving the box. It does not change while the user types. A new value from the page clears the suggestions. |
| ValueExpression | Expression<Func<string?>>? | null | Set by @bind-Value; lets an enclosing form hear the change. |
| OnRead | Func<string, CancellationToken, Task<IEnumerable<TItem>>>? | null | Supplies the suggestions for the typed text; the token is canceled by the next keystroke. |
| ItemTemplate | RenderFragment<TItem>? | null | Renders a suggestion in the popup; the default is the item's text. |
| MinLength | int | 1 | Characters needed before a search runs. |
| DebounceDelay | int | 250 | Milliseconds of quiet after a keystroke before the search runs. |
| MaxSuggestions | int | 25 | Upper bound on the suggestions shown, at least 1. |
| Width | string? | null | Width of the box. When null, the box sizes to the longer of the placeholder and the longest current suggestion, between 8 and 28 characters, so it can change as suggestions arrive. With no placeholder and no suggestions, no width is set. |
| AriaLabel | string? | null | Accessible name of the box. |
| Placeholder | string? | null | Text shown while the box is empty. |
| Enabled (base) | bool | true | false disables the box, closes the popup and stops searches. |
| Visible (base) | bool | true | false hides the control with display:none. |
| CssClass / Style (base) | string? | null | On the fx-autocomplete root, which also receives unmatched attributes. |

### Auto events

| Name | Type | Description |
|---|---|---|
| ValueChanged | string? | When text is committed: a suggestion picked or the typed text accepted. |
| ItemSelected | TItem | Right after ValueChanged, when the committed text equals a current suggestion's text. Carries the first suggestion with that text, so give items distinct text. |

### Auto methods

| Name | Type | Description |
|---|---|---|
| SearchAsync(string text) | Task | Runs the search for that text from code, with the same length check, delay and popup handling. |

### Auto state

| Name | Type | Default | Description |
|---|---|---|---|
| IsLoading | bool | false | True from the keystroke until the suggestions are in. |
| ErrorMessage | string? | null | The message of an exception thrown by OnRead; null otherwise. |

### Stepper

| Name | Type | Default | Description |
|---|---|---|---|
| Steps | IReadOnlyList<WizardStepDescriptor> | Array.Empty<WizardStepDescriptor>() | The steps, in order; only Title and Description are used here. |
| Value | int | 0 | Index of the current step, from 0. |
| Linear | bool | true | True allows only earlier steps and the next step that is not disabled, and blocks forward moves while the current step is invalid. False lets any step that is not in DisabledSteps be entered. |
| Vertical | bool | false | Stacks the steps in a column instead of a row. |
| DisabledSteps | IReadOnlyCollection<int> | Array.Empty<int>() | Indexes that can never be entered. In linear mode the step after a disabled one counts as the next step. |
| InvalidSteps | IReadOnlyCollection<int> | Array.Empty<int>() | Indexes shown with a warning sign; in linear mode an invalid current step blocks forward moves. |
| CanNavigate | Func<int, int, Task<bool>>? | null | Called with the current and the requested index before a move; return false to refuse it. |
| AriaLabel | string | "Steps" | Accessible name of the nav element. |
| StepTemplate | RenderFragment<WizardStepContext>? | null | Renders the inside of a step button; the default is "n. Title". |
| Enabled (base) | bool | true | false disables every step button. |

### Stepper events

| Name | Type | Description |
|---|---|---|
| ValueChanged | int | After a move has been accepted, with the new index. |

### Stepper methods

| Name | Type | Description |
|---|---|---|
| SelectAsync(int index) | Task | Moves to that step from code, with the same rules as a click: the step must be enterable and CanNavigate must agree. Does nothing for the current step. |

### Step desc

| Name | Type | Default | Description |
|---|---|---|---|
| Key | string | "" | Identifier for the app's own use; no library control reads it. |
| Title | string | "" | Text of the step. |
| Description | string | "" | Tooltip of the step button. |
| IconCss / IconUrl | string | "" | Icon hints for the hosting wizard; not read by the stepper. |

### Step ctx

| Name | Type | Default | Description |
|---|---|---|---|
| StepIndex | int | 0 | Index of the step being rendered. |
| Step | WizardStepDescriptor | new() | Its descriptor. |
| IsFirst | bool | false | True for the first step. |
| IsLast | bool | false | True for the last step. |

### Palette

| Name | Type | Default | Description |
|---|---|---|---|
| Colors | IReadOnlyList<string> | ColorPalettes.Basic | The swatches, as CSS color strings. |
| Value | string? | null | The selected color; must be one of Colors, compared ignoring case. |
| Columns | int | 8 | Swatches per row; also the distance of an Up or Down key press. |
| TileSize | string | "28px" | Width and height of a swatch. |
| AriaLabel | string | "Color palette" | Accessible name of the listbox. |
| TileTemplate | RenderFragment<string>? | null | Content drawn inside each swatch instead of the check mark on the selected one; it receives the color string. Not used in this page's examples. |
| Enabled (base) | bool | true | false disables every swatch and makes SelectAsync do nothing. |
| Visible (base) | bool | true | false hides the palette with display:none. |
| CssClass / Style (base) | string? | null | On the listbox element, which also receives unmatched attributes. |
| Id (base) | string? | null | DOM id of the listbox element. |

### Palette events

| Name | Type | Description |
|---|---|---|
| ValueChanged | string? | After a swatch is chosen. |

### Palette methods

| Name | Type | Description |
|---|---|---|
| SelectAsync(string color) | Task | Selects that color from code and raises ValueChanged, even when it is already selected. Ignored when the control is disabled or the color is not in Colors; that check is case-sensitive. |

### Keys

| Name | Description |
|---|---|
| Autocomplete: Down / Up | With the list open, moves the highlight. With it closed, commits the next or previous suggestion at once. |
| Autocomplete: Home / End / PageUp / PageDown | With the list open, moves the highlight to the first or last suggestion, or a page up or down. |
| Autocomplete: Enter | Commits the suggestion highlighted with the keys, otherwise the typed text, and closes the list. |
| Autocomplete: Tab | Commits the same way when the text was edited or the list is open, then moves on. |
| Autocomplete: Escape | Closes the list without committing. |
| Autocomplete: F4 or Alt+Down | Opens the list. With the list open, commits and closes it, as does Alt+Up. |
| Stepper: Left, Up / Right, Down | Moves to the previous or next step that can be entered and focuses it. |
| Palette: Left / Right | Focuses the previous or next swatch. |
| Palette: Up / Down | Focuses the swatch one row up or down. |
| Palette: Home / End | Focuses the first or last swatch. |
| Palette: Enter or Space | Selects the focused swatch (it is a button). |

### Css

| Name | Description |
|---|---|
| fx-autocomplete | The autocomplete's root; the box and popup inside it are the dropdown list's own elements. |
| fx-stepper | The nav holding the step buttons. |
| fx-step · fx-step-current | On every step button; fx-step-current fills the current one with --fx-stepper-current-bg (falls back to --fx-accent when your app sets it, then #1c6ebf) and writes its text in --fx-stepper-current-color (#ffffff), weight 600. |
| fx-color-palette | The palette grid; --fx-palette-columns and --fx-swatch-size carry Columns and TileSize. |
| fx-palette-swatch | A swatch button; selected is added to the chosen one. |

## Examples

### Suggest

```razor
@using Fx.ControlKit

<div class="pk">
    <div class="pair">
        <div>
            <p class="pane-title">Going to</p>
            <AutoCompleteControl TItem="City" DataSource="@_cities" TextField="Name" Value="@_cityText" ValueChanged="CityTyped" ItemSelected="c => _pickedCity = c" Placeholder="Type a city" AriaLabel="Destination" Width="100%">
                <ItemTemplate Context="city"><span>@city.Name</span> <span class="muted">@city.Country</span></ItemTemplate>
            </AutoCompleteControl>
        </div>
        <div>
            <p class="pane-title">Flying from: 4,009 airports</p>
            <AutoCompleteControl TItem="Airport" OnRead="LookupAsync" TextField="Name" MinLength="2" DebounceDelay="400" MaxSuggestions="5" Value="@_airportText" ValueChanged="AirportTyped" ItemSelected="a => _pickedAirport = a" Placeholder="Airport, city or code" AriaLabel="Departure airport" Width="100%">
                <ItemTemplate Context="airport"><strong>@airport.Code</strong> @airport.Name <span class="muted">@airport.City, @airport.Country</span></ItemTemplate>
            </AutoCompleteControl>
        </div>
    </div>
    <p class="result" role="status">Quote for Albus Door: @Quote. @_lookups airport @(_lookups == 1 ? "lookup" : "lookups") so far.</p>
</div>
```

```csharp
// Suggestions
private sealed record City(string Name, string Country);
private readonly City[] _cities = TravelData.Destinations.Select(d => new City(d.City, d.Country)).ToArray();
private string? _cityText;
private City? _pickedCity;
private string? _airportText;
private Airport? _pickedAirport;
private int _lookups;
// Stands in for a server search over the airports (Data/AirportData.cs): an exact code first, then cities and names that start
// with the text, larger airports before smaller ones; the control keeps the first five.
private async Task<IEnumerable<Airport>> LookupAsync(string text, CancellationToken token)
{
    _lookups++;
    await InvokeAsync(StateHasChanged);   // the control re-renders itself, not this page, so refresh the counter here
    await Task.Delay(300, token);
    var ignoreCase = StringComparison.OrdinalIgnoreCase;
    return AirportData.Airports
        .Where(a => a.Code.Contains(text, ignoreCase) || a.City.Contains(text, ignoreCase) || a.Name.Contains(text, ignoreCase) || a.Country.Contains(text, ignoreCase))
        .OrderBy(a => a.Code.Equals(text, ignoreCase) ? 0 : a.City.StartsWith(text, ignoreCase) ? 1 : a.Name.StartsWith(text, ignoreCase) ? 2 : 3)
        .ThenBy(a => a.Type switch { "Large" => 0, "Medium" => 1, _ => 2 })
        .ThenBy(a => a.Name);
}
// Committed text that matches no suggestion drops the old pick; after a match, ItemSelected follows ValueChanged and sets it again.
private void CityTyped(string? text)
{
    _cityText = text;
    if (_pickedCity?.Name != text) _pickedCity = null;
}
private void AirportTyped(string? text)
{
    _airportText = text;
    if (_pickedAirport?.Name != text) _pickedAirport = null;
}
// The quote line: the picked item, or the committed text when it matches no suggestion
private string Quote
{
    get
    {
        var from = _pickedAirport is { } a ? $"{a.Code} ({a.City})" : _airportText;
        var to = _pickedCity is { } c ? $"{c.Name}, {c.Country}" : _cityText;
        return (string.IsNullOrWhiteSpace(from), string.IsNullOrWhiteSpace(to)) switch
        {
            (true, true) => "no airport or destination yet",
            (false, true) => $"from {from}, no destination yet",
            (true, false) => $"to {to}, no airport yet",
            _ => $"from {from} to {to}",
        };
    }
}
```

### Steps

```razor
@using Fx.ControlKit

<SwitchControl @bind-Checked="_vertical" Label="Vertical" />
<SwitchControl @bind-Checked="_noExtras" Label="No extras" />
<ButtonControl CssClass="btn-sm" OnClick="() => _stepper!.SelectAsync(Before)" Disabled="@(_step == 0 || _confirmed)">Back</ButtonControl>
<ButtonControl CssClass="btn-sm" OnClick="() => _stepper!.SelectAsync(After)" Disabled="@(_step == _steps.Count - 1 || !_done[_step])">Next</ButtonControl>
<div class="pk">
    <StepperControl @ref="_stepper" Steps="@_steps" @bind-Value="_step" Vertical="_vertical" DisabledSteps="@DisabledSteps" InvalidSteps="@InvalidSteps"
                    CanNavigate="Navigating" AriaLabel="Booking steps" />
    <div class="step-pane">
        @if (_step < 3)
        {
            <CheckBoxControl @bind-Checked="_done[_step]" Label="@Checks[_step]" />
        }
        else
        {
            <ButtonControl CssClass="btn-primary btn-sm" Disabled="_confirmed" OnClick="() => _confirmed = true">Confirm the booking</ButtonControl>
        }
    </div>
    <p class="result" role="status">Step @(_step + 1) of @_steps.Count: @_steps[_step].Title. @(_confirmed ? "Booking KYO-0005 is confirmed; the steps are locked." : _navLog)</p>
</div>
```

```csharp
// Booking steps
private StepperControl? _stepper;
private readonly IReadOnlyList<WizardStepDescriptor> _steps =
[
    new() { Title = "Traveler", Description = "Who is going" },
    new() { Title = "Trip", Description = "Where and when" },
    new() { Title = "Extras", Description = "Transfers and tours" },
    new() { Title = "Confirm", Description = "Check and confirm" },
];
private static readonly string[] Checks = { "Passport checked for Hermione Ranger", "Kyoto Classic, eight nights, dates agreed", "Airport transfer added" };
private readonly bool[] _done = new bool[4];
private int _step;
private bool _vertical, _noExtras, _confirmed;
private string _navLog = "Check the box to open the next step.";
// A step whose box is not checked is invalid, which blocks forward moves; No extras takes the Extras step out.
private IReadOnlyCollection<int> InvalidSteps => _step < 3 && !_done[_step] ? [_step] : Array.Empty<int>();
private IReadOnlyCollection<int> DisabledSteps => _noExtras ? [2] : Array.Empty<int>();
private int Before => _noExtras && _step == 3 ? 1 : _step - 1;
private int After => _noExtras && _step == 1 ? 3 : _step + 1;
// CanNavigate sees every move first: once the booking is confirmed it refuses them all.
private Task<bool> Navigating(int from, int to)
{
    if (_confirmed) return Task.FromResult(false);
    _navLog = $"Last move: {_steps[from].Title} to {_steps[to].Title}.";
    return Task.FromResult(true);
}
```

