|
1 | 1 | @using LinkDotNet.Blog.Web.Features.Components.Typeahead
|
2 | 2 |
|
| 3 | +@* We are using Bootstrap 5 example here. I want my input and the suggestion directly under each other*@ |
3 | 4 | <div class="row">
|
| 5 | + @* |
| 6 | + Every time the user inputs a text we update our suggestion |
| 7 | + You could also add debouncing and stuff here |
| 8 | + *@ |
4 | 9 | <input @oninput="UpdateAutoCompletion" value="@content"/>
|
| 10 | + @* Only show suggestions if we have at least one *@ |
5 | 11 | @if (similarWords.Any())
|
6 | 12 | {
|
| 13 | + @* |
| 14 | + Not super sexy but it does what we want. We are using a select element |
| 15 | + which shows all the words and we can change/click on it so that the |
| 16 | + input element will change |
| 17 | + *@ |
7 | 18 | <select size="@AutoCompleteCount" @onchange="UseSelectedWord">
|
8 |
| - @foreach (var similarWord in similarWords) |
9 |
| - { |
10 |
| - <option value="@similarWord">@similarWord</option> |
11 |
| - } |
| 19 | + @foreach (var similarWord in similarWords) |
| 20 | + { |
| 21 | + <option value="@similarWord">@similarWord</option> |
| 22 | + } |
12 | 23 | </select>
|
13 | 24 | }
|
14 | 25 | </div>
|
15 | 26 | @code {
|
| 27 | + // Let the parent tell which words we have to "index" |
16 | 28 | [Parameter] public IEnumerable<string> AllWords { get; set; }
|
| 29 | + // The maximum amount of suggestion we will give |
17 | 30 | [Parameter] public int AutoCompleteCount { get; set; } = 10;
|
18 | 31 |
|
19 | 32 | private readonly Trie trie = new();
|
20 | 33 | private string content = string.Empty;
|
21 | 34 | private List<string> similarWords = new();
|
22 | 35 |
|
23 |
| - protected override void OnParametersSet() |
| 36 | + // Create the Trie once |
| 37 | + // You could also use OnParameterSet and re-create the trie when the parameters change |
| 38 | + protected override void OnInitialized() |
24 | 39 | {
|
25 |
| - foreach (var word in AllWords) |
| 40 | + // Lets order the words alphabetically - so it is easier for the user to select her/his word |
| 41 | + foreach (var word in AllWords.OrderBy(w => w)) |
26 | 42 | {
|
27 | 43 | trie.Add(word);
|
28 | 44 | }
|
29 | 45 | }
|
30 | 46 |
|
31 |
| - private void UpdateAutoCompletion(ChangeEventArgs obj) |
| 47 | + private void UpdateAutoCompletion(ChangeEventArgs inputEventArgs) |
32 | 48 | {
|
33 |
| - content = obj.Value.ToString(); |
| 49 | + content = inputEventArgs.Value.ToString(); |
| 50 | + // Get all words from our Trie which share the prefix (at most AutoCompleteCount) |
34 | 51 | similarWords = trie.GetWordsWithPrefix(content).Take(AutoCompleteCount).ToList();
|
35 | 52 | }
|
36 | 53 |
|
|
0 commit comments