Skip to content

Commit

Permalink
More updates. Code fixes and modernizations. Convert to IIncrementalG…
Browse files Browse the repository at this point in the history
…enerator.
  • Loading branch information
IEvangelist committed Nov 22, 2024
1 parent 19cccd6 commit 148d855
Show file tree
Hide file tree
Showing 33 changed files with 236 additions and 222 deletions.
18 changes: 9 additions & 9 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,16 @@
<!-- Use these versions regardless of TFM -->
<ItemGroup>
<PackageVersion Include="Microsoft.SourceLink.GitHub" Version="8.0.0" />
<PackageVersion Include="MinVer" Version="5.0.0-beta.1" />
<PackageVersion Include="Microsoft.CodeAnalysis.CSharp" Version="4.7.0" />
<PackageVersion Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.4" />
<PackageVersion Include="MinVer" Version="6.0.0" />
<PackageVersion Include="Microsoft.CodeAnalysis.CSharp" Version="4.11.0" />
<PackageVersion Include="Microsoft.CodeAnalysis.Analyzers" Version="3.11.0" />
<PackageVersion Include="System.Reactive.Linq" Version="6.0.0" />
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
<PackageVersion Include="Microsoft.Playwright" Version="1.39.0" />
<PackageVersion Include="xunit" Version="2.6.1" />
<PackageVersion Include="xunit.runner.visualstudio" Version="2.5.3" />
<PackageVersion Include="coverlet.collector" Version="6.0.0" />
<PackageVersion Include="Basic.Reference.Assemblies" Version="1.4.5" />
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.12.0" />
<PackageVersion Include="Microsoft.Playwright" Version="1.49.0" />
<PackageVersion Include="xunit" Version="2.9.2" />
<PackageVersion Include="xunit.runner.visualstudio" Version="2.8.2" />
<PackageVersion Include="coverlet.collector" Version="6.0.2" />
<PackageVersion Include="Basic.Reference.Assemblies" Version="1.7.9" />
<PackageVersion Include="Humanizer.Core" Version="2.14.1" />
</ItemGroup>
<!-- .NET 8.0 bits -->
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
@page "/geolocation"

@inject IGeolocationService Geolocation

<PageTitle>Geolocation</PageTitle>
<h1>
Geolocation
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

namespace Blazor.ExampleConsumer.Components.Pages;

public sealed partial class ClientPosition
public sealed partial class ClientPosition(IGeolocationService geolocation)
{
readonly JsonSerializerOptions _opts = new()
{
Expand All @@ -23,7 +23,7 @@ public sealed partial class ClientPosition
bool _isLoading = true;

protected override void OnInitialized() =>
Geolocation.GetCurrentPosition(
geolocation.GetCurrentPosition(
component: this,
onSuccessCallbackMethodName: nameof(OnPositionReceived),
onErrorCallbackMethodName: nameof(OnPositionError),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@

namespace Blazor.ExampleConsumer.Components.Pages;

public sealed partial class ListenToMe : IDisposable
public sealed partial class ListenToMe(
ISpeechRecognitionService speechRecognition,
ISessionStorageService sessionStorage) : IDisposable
{
const string TranscriptKey = "listen-to-me-page-transcript";

Expand All @@ -12,35 +14,29 @@ public sealed partial class ListenToMe : IDisposable
SpeechRecognitionErrorEvent? _errorEvent;
string? _transcript;

[Inject]
public ISpeechRecognitionService SpeechRecognition { get; set; } = null!;

[Inject]
public ISessionStorageService SessionStorage { get; set; } = null!;

protected override void OnInitialized() =>
_transcript = SessionStorage.GetItem<string>(TranscriptKey);
_transcript = sessionStorage.GetItem<string>(TranscriptKey);

protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
await SpeechRecognition.InitializeModuleAsync();
await speechRecognition.InitializeModuleAsync();
}
}

void OnRecognizeSpeechClick()
{
if (_isRecognizingSpeech)
{
SpeechRecognition.CancelSpeechRecognition(false);
speechRecognition.CancelSpeechRecognition(false);
}
else
{
var bcp47Tag = CurrentUICulture.Name;

_recognitionSubscription?.Dispose();
_recognitionSubscription = SpeechRecognition.RecognizeSpeech(
_recognitionSubscription = speechRecognition.RecognizeSpeech(
bcp47Tag,
OnRecognized,
OnError,
Expand Down Expand Up @@ -75,7 +71,7 @@ void OnRecognized(string transcript)
_ => $"{_transcript.Trim()} {transcript}".Trim()
};

SessionStorage.SetItem(TranscriptKey, _transcript);
sessionStorage.SetItem(TranscriptKey, _transcript);
StateHasChanged();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,13 +46,13 @@
<span class="oi oi-audio"></span>
<span class="ps-2">Speak</span>
</button>
<button type="button" class="btn btn-lg btn-warning" title="Pause" @onclick=@SpeechSynthesis.Pause>
<button type="button" class="btn btn-lg btn-warning" title="Pause" @onclick=@speechSynthesis.Pause>
<span class="oi oi-media-pause"></span>
</button>
<button type="button" class="btn btn-lg btn-info"title="Play" @onclick=@SpeechSynthesis.Resume>
<button type="button" class="btn btn-lg btn-info"title="Play" @onclick=@speechSynthesis.Resume>
<span class="oi oi-media-play"></span>
</button>
<button type="button" class="btn btn-lg btn-danger" title="Stop" @onclick=@SpeechSynthesis.Cancel>
<button type="button" class="btn btn-lg btn-danger" title="Stop" @onclick=@speechSynthesis.Cancel>
<span class="oi oi-media-stop"></span>
</button>
</div>
41 changes: 16 additions & 25 deletions samples/Blazor.ExampleConsumer/Components/Pages/ReadToMe.razor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,19 @@

namespace Blazor.ExampleConsumer.Components.Pages;

public sealed partial class ReadToMe : IDisposable
public sealed partial class ReadToMe(
ISpeechSynthesisService speechSynthesis,
ILocalStorageService localStorage,
ISessionStorageService sessionStorage) : IDisposable
{
const string PreferredVoiceKey = "preferred-voice";
const string PreferredSpeedKey = "preferred-speed";
const string TextKey = "read-to-me-text";

string? _text = "Blazorators is an open-source project that strives to simplify JavaScript interop in Blazor. JavaScript interoperability is possible by parsing TypeScript type declarations and using this metadata to output corresponding C# types.";
SpeechSynthesisVoice[] _voices = Array.Empty<SpeechSynthesisVoice>();
SpeechSynthesisVoice[] _voices = [];
readonly IList<double> _voiceSpeeds =
Enumerable.Range(0, 12).Select(i => (i + 1) * .25).ToList();
[..Enumerable.Range(0, 12).Select(i => (i + 1) * .25)];
double _voiceSpeed = 1.5;
string? _selectedVoice;
string? _elapsedTimeMessage = null;
Expand All @@ -29,34 +32,22 @@ public sealed partial class ReadToMe : IDisposable
: null
};

[Inject]
public ISpeechSynthesisService SpeechSynthesis { get; set; } = null!;

[Inject]
public ILocalStorageService LocalStorage { get; set; } = null!;

[Inject]
public ISessionStorageService SessionStorage { get; set; } = null!;

[Inject]
public ILogger<ReadToMe> Logger { get; set; } = null!;

protected override async Task OnInitializedAsync()
{
await GetVoicesAsync();
SpeechSynthesis.OnVoicesChanged(() => GetVoicesAsync(true));
speechSynthesis.OnVoicesChanged(() => GetVoicesAsync(true));

if (LocalStorage.GetItem<string>(PreferredVoiceKey)
if (localStorage.GetItem<string>(PreferredVoiceKey)
is { Length: > 0 } voice)
{
_selectedVoice = voice;
}
if (LocalStorage.GetItem<double>(PreferredSpeedKey)
if (localStorage.GetItem<double>(PreferredSpeedKey)
is double speed && speed > 0)
{
_voiceSpeed = speed;
}
if (SessionStorage.GetItem<string>(TextKey)
if (sessionStorage.GetItem<string>(TextKey)
is { Length: > 0 } text)
{
_text = text;
Expand All @@ -65,7 +56,7 @@ protected override async Task OnInitializedAsync()

async Task GetVoicesAsync(bool isFromCallback = false)
{
_voices = await SpeechSynthesis.GetVoicesAsync();
_voices = await speechSynthesis.GetVoicesAsync();
if (_voices is { } && isFromCallback)
{
StateHasChanged();
Expand All @@ -78,7 +69,7 @@ void OnVoiceSpeedChange(ChangeEventArgs args) =>
_voiceSpeed = double.TryParse(args.Value?.ToString() ?? "1.5", out var speed)
? speed : 1.5;

void Speak() => SpeechSynthesis.Speak(
void Speak() => speechSynthesis.Speak(
Utterance,
elapsedTime =>
{
Expand All @@ -90,10 +81,10 @@ void Speak() => SpeechSynthesis.Speak(

void IDisposable.Dispose()
{
LocalStorage.SetItem(PreferredVoiceKey, _selectedVoice);
LocalStorage.SetItem(PreferredSpeedKey, _voiceSpeed);
SessionStorage.SetItem(TextKey, _text);
localStorage.SetItem(PreferredVoiceKey, _selectedVoice);
localStorage.SetItem(PreferredSpeedKey, _voiceSpeed);
sessionStorage.SetItem(TextKey, _text);

SpeechSynthesis.UnsubscribeFromVoicesChanged();
speechSynthesis.UnsubscribeFromVoicesChanged();
}
}
23 changes: 8 additions & 15 deletions samples/Blazor.ExampleConsumer/Components/Pages/TodoList.razor.cs
Original file line number Diff line number Diff line change
@@ -1,28 +1,21 @@
// Copyright (c) David Pine. All rights reserved.
// Licensed under the MIT License.

using System.Diagnostics.CodeAnalysis;
using Blazor.ExampleConsumer.Models;
using Microsoft.AspNetCore.Components.Web;

namespace Blazor.ExampleConsumer.Components.Pages;

public sealed partial class TodoList
public sealed partial class TodoList(ILocalStorageService localStorage)
{
readonly Dictionary<string, string> _localStorageItems = [];
HashSet<TodoItem> _todos = [];
string? _todoValue;

[Inject]
public ILocalStorageService LocalStorage { get; set; } = null!;

protected override void OnInitialized() => UpdateTodoItems();

void UpdateTodoItems()
{
var todos = GetLocalStorageKeys()
.Where(key => key.StartsWith(TodoItem.IdPrefix))
.Select(key => LocalStorage.GetItem<TodoItem>(key))
.Select(key => localStorage.GetItem<TodoItem>(key))
.Where(todo => todo is not null)
.ToHashSet() ?? [];

Expand Down Expand Up @@ -56,7 +49,7 @@ bool TryGet<T>(string key, [NotNullWhen(true)] out T? value)
{
try
{
value = LocalStorage.GetItem<T>(key);
value = localStorage.GetItem<T>(key);
return value is not null;
}
catch
Expand All @@ -69,10 +62,10 @@ bool TryGet<T>(string key, [NotNullWhen(true)] out T? value)

IEnumerable<string> GetLocalStorageKeys()
{
var length = LocalStorage.Length;
var length = localStorage.Length;
for (var i = 0; i < length; ++i)
{
if (LocalStorage.Key(i) is { Length: > 0 } key)
if (localStorage.Key(i) is { Length: > 0 } key)
{
yield return key;
}
Expand All @@ -84,7 +77,7 @@ void AddNewTodo()
if (_todoValue is not null)
{
var todo = new TodoItem(_todoValue, false);
LocalStorage.SetItem(todo.Id, todo);
localStorage.SetItem(todo.Id, todo);
UpdateTodoItems();
_todoValue = null;
}
Expand All @@ -100,14 +93,14 @@ void OnKeyUp(KeyboardEventArgs args)

void Delete(TodoItem todo)
{
LocalStorage.RemoveItem(todo.Id);
localStorage.RemoveItem(todo.Id);
_todos.RemoveWhere(t => t.Id == todo.Id);
_localStorageItems.Remove(todo.Id);
}

void ClearAll()
{
LocalStorage.Clear();
localStorage.Clear();
_todos.Clear();
_localStorageItems.Clear();
}
Expand Down
2 changes: 0 additions & 2 deletions samples/Blazor.ExampleConsumer/Components/Pages/Track.razor
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
@page "/track"

@inject IGeolocationService Geolocation

<PageTitle>Track</PageTitle>
<h1>
Geolocation
Expand Down
10 changes: 5 additions & 5 deletions samples/Blazor.ExampleConsumer/Components/Pages/Track.razor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

namespace Blazor.ExampleConsumer.Components.Pages;

public partial class Track : IDisposable
public sealed partial class Track(IGeolocationService geolocation) : IDisposable
{
readonly JsonSerializerOptions _opts = new()
{
Expand All @@ -24,14 +24,14 @@ public partial class Track : IDisposable
bool _isLoading = true;

protected override void OnInitialized() =>
_watchId = Geolocation.WatchPosition(
_watchId = geolocation.WatchPosition(
component: this,
onSuccessCallbackMethodName: nameof(OnPositionRecieved),
onSuccessCallbackMethodName: nameof(OnPositionReceived),
onErrorCallbackMethodName: nameof(OnPositionError),
options: _options);

[JSInvokable]
public void OnPositionRecieved(GeolocationPosition position)
public void OnPositionReceived(GeolocationPosition position)
{
_isLoading = false;
_position = position;
Expand All @@ -46,5 +46,5 @@ public void OnPositionError(GeolocationPositionError positionError)
StateHasChanged();
}

public void Dispose() => Geolocation.ClearWatch(_watchId);
public void Dispose() => geolocation.ClearWatch(_watchId);
}
5 changes: 5 additions & 0 deletions samples/Blazor.ExampleConsumer/GlobalUsings.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
// Copyright (c) David Pine. All rights reserved.
// Licensed under the MIT License.

global using System.Diagnostics.CodeAnalysis;
global using System.Text.Json;
global using System.Text.Json.Serialization;
global using Blazor.ExampleConsumer.Components;
global using Blazor.ExampleConsumer.Models;
global using Microsoft.AspNetCore.Components;
global using Microsoft.AspNetCore.Components.Web;
global using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
global using Microsoft.JSInterop;
global using static System.Globalization.CultureInfo;
4 changes: 0 additions & 4 deletions samples/Blazor.ExampleConsumer/Program.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
// Copyright (c) David Pine. All rights reserved.
// Licensed under the MIT License.

using Blazor.ExampleConsumer.Components;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;

var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ public sealed partial class ReadToMe : IAsyncDisposable
const string TextKey = "read-to-me-text";

string? _text = "Blazorators is an open-source project that strives to simplify JavaScript interop in Blazor. JavaScript interoperability is possible by parsing TypeScript type declarations and using this metadata to output corresponding C# types.";
SpeechSynthesisVoice[] _voices = Array.Empty<SpeechSynthesisVoice>();
SpeechSynthesisVoice[] _voices = [];
readonly IList<double> _voiceSpeeds =
Enumerable.Range(0, 12).Select(i => (i + 1) * .25).ToList();
double _voiceSpeed = 1.5;
Expand Down
2 changes: 0 additions & 2 deletions samples/BlazorServer.ExampleConsumer/Pages/Track.razor
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
@page "/track"

@inject IGeolocationService Geolocation

<PageTitle>Track</PageTitle>
<h1>
Geolocation
Expand Down
Loading

0 comments on commit 148d855

Please sign in to comment.