Skip to content

Commit

Permalink
Introduced source-gen for dependency of callbacks.
Browse files Browse the repository at this point in the history
  • Loading branch information
IEvangelist committed Mar 16, 2022
1 parent d3b3bc0 commit 0fbb558
Show file tree
Hide file tree
Showing 30 changed files with 775 additions and 143 deletions.
11 changes: 10 additions & 1 deletion .github/workflows/publish-nuget.yml
Original file line number Diff line number Diff line change
Expand Up @@ -34,13 +34,15 @@ jobs:
dotnet restore ./src/Blazor.LocalStorage.WebAssembly/Blazor.LocalStorage.WebAssembly.csproj
dotnet restore ./src/Blazor.LocalStorage.Server/Blazor.LocalStorage.Server.csproj
dotnet restore ./src/Blazor.Serialization/Blazor.Serialization.csproj
dotnet restore ./src/Blazor.Geolocation.WebAssembly/Blazor.Geolocation.WebAssembly.csproj
- name: Build
run: |
dotnet build ./src/Blazor.SourceGenerators/Blazor.SourceGenerators.csproj --configuration Release --no-restore
dotnet build ./src/Blazor.LocalStorage.WebAssembly/Blazor.LocalStorage.WebAssembly.csproj --configuration Release --no-restore
dotnet build ./src/Blazor.LocalStorage.Server/Blazor.LocalStorage.Server.csproj --configuration Release --no-restore
dotnet build ./src/Blazor.Serialization/Blazor.Serialization.csproj --configuration Release --no-restore
dotnet build ./src/Blazor.Geolocation.WebAssembly/Blazor.Geolocation.WebAssembly.csproj --configuration Release --no-restore
- name: Test
run: dotnet test
Expand All @@ -51,7 +53,8 @@ jobs:
dotnet pack ./src/Blazor.LocalStorage.WebAssembly/Blazor.LocalStorage.WebAssembly.csproj --output packages
dotnet pack ./src/Blazor.LocalStorage.Server/Blazor.LocalStorage.Server.csproj --output packages
dotnet pack ./src/Blazor.Serialization/Blazor.Serialization.csproj --output packages
dotnet pack ./src/Blazor.Geolocation.WebAssembly/Blazor.Geolocation.WebAssembly.csproj --output packages
- name: Publish package
run: |
nuget push **\*.nupkg -Source 'https://api.nuget.org/v3/index.json' -NoSymbols -NonInteractive -ApiKey ${{secrets.NUGET_API_KEY}}
Expand All @@ -78,4 +81,10 @@ jobs:
uses: actions/upload-artifact@v2
with:
name: Blazor.Serialization.${{ steps.regex-match.outputs.match }}.nupkg
path: packages/

- name: Upload geolocation WebAssembly package
uses: actions/upload-artifact@v2
with:
name: Blazor.Geolocation.WebAssembly.${{ steps.regex-match.outputs.match }}.nupkg
path: packages/
7 changes: 7 additions & 0 deletions blazorators.sln
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Blazor.LocalStorage.Server"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Blazor.Serialization", "src\Blazor.Serialization\Blazor.Serialization.csproj", "{5E4658A7-4751-4F85-A558-12B8EBCA2BCA}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Blazor.Geolocation.WebAssembly", "src\Blazor.Geolocation.WebAssembly\Blazor.Geolocation.WebAssembly.csproj", "{0BAC9703-45EE-4E9E-A0F0-556F02FCB901}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -62,6 +64,10 @@ Global
{5E4658A7-4751-4F85-A558-12B8EBCA2BCA}.Debug|Any CPU.Build.0 = Debug|Any CPU
{5E4658A7-4751-4F85-A558-12B8EBCA2BCA}.Release|Any CPU.ActiveCfg = Release|Any CPU
{5E4658A7-4751-4F85-A558-12B8EBCA2BCA}.Release|Any CPU.Build.0 = Release|Any CPU
{0BAC9703-45EE-4E9E-A0F0-556F02FCB901}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{0BAC9703-45EE-4E9E-A0F0-556F02FCB901}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0BAC9703-45EE-4E9E-A0F0-556F02FCB901}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0BAC9703-45EE-4E9E-A0F0-556F02FCB901}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand All @@ -73,6 +79,7 @@ Global
{2F4EE253-7D56-4853-ADA7-4F2F6280C2D2} = {537EB83C-6982-40B0-801A-479DF3B17DBE}
{9AA2BB50-9F1A-43D0-BB6B-C3C4E9765BE1} = {537EB83C-6982-40B0-801A-479DF3B17DBE}
{5E4658A7-4751-4F85-A558-12B8EBCA2BCA} = {537EB83C-6982-40B0-801A-479DF3B17DBE}
{0BAC9703-45EE-4E9E-A0F0-556F02FCB901} = {537EB83C-6982-40B0-801A-479DF3B17DBE}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {3F86284A-32D2-4F79-B23C-7A0CB8775971}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\src\Blazor.Geolocation.WebAssembly\Blazor.Geolocation.WebAssembly.csproj" />
<ProjectReference Include="..\..\src\Blazor.LocalStorage.WebAssembly\Blazor.LocalStorage.WebAssembly.csproj" />
<ProjectReference Include="..\..\src\Blazor.Serialization\Blazor.Serialization.csproj" />
</ItemGroup>
Expand Down
65 changes: 55 additions & 10 deletions samples/Blazor.ExampleConsumer/Pages/FetchData.razor
Original file line number Diff line number Diff line change
@@ -1,17 +1,33 @@
@page "/fetchdata"

@using Microsoft.JSInterop
@using System.Text.Json

@inject IJSInProcessRuntime JavaScript
@inject IGeolocation Geolocation
@inject HttpClient Http

<PageTitle>Weather forecast</PageTitle>

<h1>Weather forecast</h1>

@if (_position is { Coords: { } })
{
<pre class="bg-dark text-light p-4 pb-0">
<code>
@_position.ToJson(_opts);
</code>
</pre>
}
else if (_positionError is not null)
{
<pre class="bg-danger text-light p-4 pb-0">
<code>
@_positionError.ToJson(_opts);
</code>
</pre>
}
<p>This component demonstrates fetching data from the server.</p>

@if (forecasts == null)
@if (_forecasts is null)
{
<p><em>Loading...</em></p>
}
Expand All @@ -27,7 +43,7 @@ else
</tr>
</thead>
<tbody>
@foreach (var forecast in forecasts)
@foreach (var forecast in _forecasts)
{
<tr>
<td>@forecast.Date.ToShortDateString()</td>
Expand All @@ -41,20 +57,49 @@ else
}

@code {
private WeatherForecast[]? forecasts;
private WeatherForecast[]? _forecasts;
private JsonSerializerOptions _opts = new()
{
WriteIndented = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};

private readonly PositionOptions _options =
new PositionOptions()
{
EnableHighAccuracy = true,
MaximumAge = 0 ,
Timeout = 5_000
};

private GeolocationPosition? _position;
private GeolocationPositionError? _positionError;

protected override async Task OnInitializedAsync()
{
forecasts = await Http.GetFromJsonAsync<WeatherForecast[]>("sample-data/weather.json");
//await JavaScript.GetCurrentPositionAsync(
// this,
// nameof(OnPositionRecievedAsync));
_forecasts = await Http.GetFromJsonAsync<WeatherForecast[]>("sample-data/weather.json");

Geolocation.GetCurrentPosition(
this,
nameof(OnPositionRecievedAsync),
nameof(OnPositionErrorAsync));
}

[JSInvokable]
public Task OnPositionRecievedAsync() =>
public Task OnPositionRecievedAsync(GeolocationPosition position) =>
InvokeAsync(() =>
{
_position = position;

StateHasChanged();
});

[JSInvokable]
public Task OnPositionErrorAsync(GeolocationPositionError positionError) =>
InvokeAsync(() =>
{
_positionError = positionError;

StateHasChanged();
});

Expand Down
1 change: 1 addition & 0 deletions samples/Blazor.ExampleConsumer/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,6 @@
});

builder.Services.AddLocalStorageServices();
builder.Services.AddGeolocationServices();

await builder.Build().RunAsync();
1 change: 1 addition & 0 deletions samples/Blazor.ExampleConsumer/wwwroot/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
<a href="" class="reload">Reload</a>
<a class="dismiss">🗙</a>
</div>
<script src="_content/Blazor.Geolocation.WebAssembly/blazorators.geolocation.g.js"></script>
<script src="_framework/blazor.webassembly.js"></script>
</body>

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
<Project Sdk="Microsoft.NET.Sdk.Razor">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<Description>Source generated JavaScript interop for the browser's geolocation API compatible with Blazor WebAssembly.</Description>
<Copyright>Copyright © David Pine. All rights reserved. Licensed under the MIT License.</Copyright>
<NeutralLanguage>en-US</NeutralLanguage>
<CurrentDate>$([System.DateTime]::Now.ToString(yyyyMMdd))</CurrentDate>
<ClientVersion Condition=" '$(IsPreview)' != 'true' ">$(ClientOfficialVersion)</ClientVersion>
<ClientVersion Condition=" '$(IsPreview)' == 'true' ">$(ClientPreviewVersion)</ClientVersion>
<VersionSuffix Condition=" '$(IsNightly)' == 'true' ">nightly-$(CurrentDate)</VersionSuffix>
<VersionSuffix Condition=" '$(IsPreview)' == 'true' ">preview</VersionSuffix>
<Version Condition=" '$(VersionSuffix)' == '' ">$(ClientVersion)</Version>
<Version Condition=" '$(VersionSuffix)' != '' ">$(ClientVersion)-$(VersionSuffix)</Version>
<FileVersion>$(ClientVersion)</FileVersion>
<Authors>David Pine</Authors>
<!--<TreatWarningsAsErrors>true</TreatWarningsAsErrors>-->
<AssemblyName>Blazor.Geolocation.WebAssembly</AssemblyName>
<Title>A C# source-generated Razor class library implementation of the native browser's geolocation API available as a DI-ready service.</Title>
<PackageId>Blazor.LocalStorage.WebAssembly</PackageId>
<PackageTags>dotnet;dotnetcore;csharp;blazor;webassembly;wasm;generators;sourcegen;roslyn;</PackageTags>
<PackageReleaseNotes></PackageReleaseNotes>
<PackageProjectUrl>https://github.com/IEvangelist/blazorators</PackageProjectUrl>
<PublishRepositoryUrl Condition=" '$(ProjectRef)' != 'True' ">true</PublishRepositoryUrl>
<GenerateAssemblyInfo>true</GenerateAssemblyInfo>
<GeneratePackageOnBuild>false</GeneratePackageOnBuild>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<PlatformTarget>AnyCPU</PlatformTarget>
<ShippingScope>External</ShippingScope>
<SigningType>Product</SigningType>
<DebugType>embedded</DebugType>
<IncludeSymbols>false</IncludeSymbols>
<IncludeSource>false</IncludeSource>
<RootNamespace>Blazor.Geolocation.WebAssembly</RootNamespace>
<NoWarn>NU5125;NU5039;</NoWarn>
<Optimize Condition="'$(Configuration)'=='Release'">true</Optimize>
<RepositoryUrl>https://github.com/IEvangelist/blazorators</RepositoryUrl>
<PackageLicenseFile>LICENSE</PackageLicenseFile>
<RepositoryType>git</RepositoryType>
<EmbedUntrackedSources>true</EmbedUntrackedSources>
<AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder>
<ContinuousIntegrationBuild>true</ContinuousIntegrationBuild>
<PackageReadmeFile>README.md</PackageReadmeFile>
<IsPackable>true</IsPackable>
<PackageIcon>logo.png</PackageIcon>
</PropertyGroup>

<ItemGroup>
<SupportedPlatform Include="browser" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="MinVer" Version="2.5.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.AspNetCore.Components.Web" Version="6.0.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\Blazor.SourceGenerators\Blazor.SourceGenerators.csproj" OutputItemType="Analyzer" SetTargetFramework="TargetFramework=netstandard2.0" ReferenceOutputAssembly="false" />
</ItemGroup>

<ItemGroup Label="Files">
<None Include="..\..\LICENSE" Pack="true" PackagePath="\" />
<None Include="..\..\README.md" Pack="true" PackagePath="\" />
<None Include="..\..\logo.png" Pack="true" PackagePath="\" />
</ItemGroup>

</Project>
12 changes: 12 additions & 0 deletions src/Blazor.Geolocation.WebAssembly/GeolocationExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
// Copyright (c) David Pine. All rights reserved.
// Licensed under the MIT License.

namespace Microsoft.JSInterop;

[JSAutoInterop(
TypeName = "Geolocation",
Implementation = "window.navigator.geolocation",
Url = "https://developer.mozilla.org/docs/Web/API/Geolocation")]
internal static partial class GeolocationExtensions
{
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
// TODO: source-generate this.

const getCurrentPosition = (
dotnetObj,
successMethodName,
errorMethodName,
options) => {
navigator.geolocation.getCurrentPosition(
position => {
const result = {
Timestamp: new Date(position.timestamp).toISOString(),
Coords: {
Accuracy: position.coords.accuracy,
Altitude: position.coords.altitude,
AltitudeAccuracy: position.coords.altitudeAccuracy,
Heading: position.coords.heading,
Latitude: position.coords.latitude,
Longitude: position.coords.longitude,
Speed: position.coords.speed
}
};
var json = JSON.stringify(result);
dotnetObj.invokeMethodAsync(successMethodName, result);
},
error => dotnetObj.invokeMethodAsync(errorMethodName, error),
options);
}

const watchPosition = (
dotnetObj,
successMethodName,
errorMethodName,
options) => {
return navigator.geolocation.watchPosition(
position => dotnetObj.invokeMethodAsync(successMethodName, position),
error => dotnetObj.invokeMethodAsync(errorMethodName, error),
options);
}

window.blazorators = {
getCurrentPosition,
watchPosition
};
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@
</PackageReference>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Primitives" Version="6.0.0" />
<PackageReference Include="Microsoft.JSInterop" Version="6.0.2" />
<PackageReference Include="Microsoft.JSInterop" Version="6.0.0" />
</ItemGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@
</PackageReference>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Primitives" Version="6.0.0" />
<PackageReference Include="Microsoft.JSInterop" Version="6.0.2" />
<PackageReference Include="Microsoft.JSInterop" Version="6.0.0" />
</ItemGroup>

<ItemGroup>
Expand Down
20 changes: 14 additions & 6 deletions src/Blazor.SourceGenerators/Builders/MethodBuilderDetails.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ internal readonly record struct MethodBuilderDetails(
string BareType,
string Suffix,
string ExtendingType,
string GenericTypeArgs)
string? GenericTypeArgs)
{
/// <summary>
/// A value representing the generic return type, <c>"TResult"</c>.
Expand All @@ -27,6 +27,11 @@ internal readonly record struct MethodBuilderDetails(
/// </summary>
internal const string GenericArgumentType = "TArg";

/// <summary>
/// A value representing the generic component type, <c>"TComponent"</c>.
/// </summary>
internal const string GenericComponentType = "TComponent";

internal static readonly Func<string, string> ToGenericTypeArgument =
string (string value) => $"<{value}>";

Expand All @@ -39,8 +44,13 @@ internal static MethodBuilderDetails Create(CSharpMethod method, GeneratorOption
var containsGenericParameters =
method.ParameterDefinitions.Any(p => p.IsGenericParameter(method.RawName, options));
var genericTypeArgs = isGenericReturnType
? ToGenericTypeArgument(GenericReturnType)
: containsGenericParameters ? ToGenericTypeArgument(GenericArgumentType) : "";
? ToGenericTypeArgument(GenericReturnType)
: containsGenericParameters ? ToGenericTypeArgument(GenericArgumentType) : null;
var fullyQualifiedJavaScriptIdentifier = method.JavaScriptMethodDependency?.InvokableMethodName;
fullyQualifiedJavaScriptIdentifier ??=
options.Implementation is not null
? $"{options.Implementation}.{method.RawName}"
: method.RawName;
var (suffix, extendingType) = options.IsWebAssembly
? ("", "IJSInProcessRuntime")
: ("Async", "IJSRuntime");
Expand All @@ -54,9 +64,7 @@ internal static MethodBuilderDetails Create(CSharpMethod method, GeneratorOption
IsGenericReturnType: isGenericReturnType,
ContainsGenericParameters: containsGenericParameters,
CSharpMethodName: method.RawName.CapitalizeFirstLetter(),
FullyQualifiedJavaScriptIdentifier: options.Implementation is not null
? $"{options.Implementation}.{method.RawName}"
: method.RawName,
FullyQualifiedJavaScriptIdentifier: fullyQualifiedJavaScriptIdentifier,
ReturnType: returnType,
BareType: bareType,
Suffix: suffix,
Expand Down
Loading

0 comments on commit 0fbb558

Please sign in to comment.