Skip to content

Commit

Permalink
♻️ Use content collection for docs
Browse files Browse the repository at this point in the history
  • Loading branch information
koeeenig committed Feb 9, 2024
1 parent 1716ca0 commit 3da3dcb
Show file tree
Hide file tree
Showing 69 changed files with 1,235 additions and 453 deletions.
4 changes: 4 additions & 0 deletions frontmatter.json
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,10 @@
"frontMatter.framework.id": "other",
"frontMatter.content.publicFolder": "",
"frontMatter.content.pageFolders": [
{
"title": "Docs",
"path": "[[workspace]]/src/BlazeKit.Website/Content/Docs"
},
{
"title": "Blog",
"path": "[[workspace]]/src/BlazeKit.Website/Content/Blog"
Expand Down
15 changes: 13 additions & 2 deletions src/BlazeKit.Abstraction/Config/BkConfig.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace BlazeKit.Abstraction.Config;

Expand All @@ -13,7 +14,7 @@ public BkConfig()
public string Routes { get; set; }
public TailwindcssConfig Tailwindcss { get; set; }

public bool PreRender { get; set; } = false;
public BuildAdapter Adapter { get; set; } = BuildAdapter.SSG;

public static bool TryLoad(out BkConfig config)
{
Expand All @@ -34,7 +35,11 @@ public static bool TryLoad(DirectoryInfo directory, out BkConfig config)
if (File.Exists(path))
{
exists = true;
config = JsonSerializer.Deserialize<BkConfig>(File.ReadAllText("blazekit.config.json"))!;
config = JsonSerializer.Deserialize<BkConfig>(File.ReadAllText("blazekit.config.json"), new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter() }
})!;
}

return exists;
Expand All @@ -55,3 +60,9 @@ public static bool HasTailwindcss(this BkConfig config)
}
}

internal enum BuildAdapter
{
SSG,
SSR
}

9 changes: 2 additions & 7 deletions src/BlazeKit.CLI/Commands/Build/BuildCommand.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
using BlazeKit.Abstraction.Config;
using BlazeKit.CLI.Tasks.Utils;
using Microsoft.AspNetCore.Components;
using Spectre.Console;
using Spectre.Console.Cli;
using System.Diagnostics;
using System.Runtime.Loader;

namespace BlazeKit.CLI.Commands.Build;
Expand Down Expand Up @@ -61,7 +59,7 @@ public override int Execute(CommandContext context, BuildSettings settings)
Task.WhenAll(publishTask).Wait();

// var tempOutput = bkConfig.PreRender ? ".blazekit/tmp/" : settings.Output;
var tempOutput = bkConfig.PreRender ? Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()) : settings.Output;
var tempOutput = bkConfig.Adapter == BuildAdapter.SSG ? Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()) : settings.Output;
// clean the temp output directory
if (Directory.Exists(tempOutput))
{
Expand All @@ -76,7 +74,6 @@ public override int Execute(CommandContext context, BuildSettings settings)
"dotnet",
output =>
{
//AnsiConsole.MarkupLine($"[purple]{$"[DOTNET PUBLISH]".EscapeMarkup()}[/] {output.EscapeMarkup()}");
AnsiConsole.MarkupLine($"{output.EscapeMarkup()}");
},
info => info.EnvironmentVariables.Add("DOTNET_SYSTEM_CONSOLE_ALLOW_ANSI_COLOR_REDIRECTION", "True"),
Expand All @@ -99,7 +96,7 @@ public override int Execute(CommandContext context, BuildSettings settings)

Task.WhenAll(publishTask).Wait();
// check if preprender is enabled
if(bkConfig.PreRender)
if(bkConfig.Adapter == BuildAdapter.SSG)
{
// pre-render the app (SSG output)
AnsiConsole.MarkupLine("[yellow] Pre-rendering app...[/]");
Expand All @@ -110,8 +107,6 @@ public override int Execute(CommandContext context, BuildSettings settings)
// get the path to the assembly
var assemblyPath = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), tempOutput, assemblyName + ".dll"));
// use BlazeKit.Static to pre-render the app
// var loadCtx = AssemblyLoadContext.Default;

System.Runtime.Loader.AssemblyLoadContext loadCtx = new AssemblyLoadContext("ssg",isCollectible:true);
loadCtx.Resolving += (ctx, name) =>
{
Expand Down
2 changes: 1 addition & 1 deletion src/BlazeKit.CLI/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
using System.Diagnostics;

Console.OutputEncoding = System.Text.Encoding.UTF8;
//Debugger.Launch();
Debugger.Launch();

var app = new Spectre.Console.Cli.CommandApp();
app.Configure(config =>
Expand Down
2 changes: 1 addition & 1 deletion src/BlazeKit.Static/ContentCollections/ISchema.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
namespace BlazeKit.Static.ContentCollections;
namespace BlazeKit.Static.ContentCollections;

public interface ISchema {
string Content { get; set; }
Expand Down
36 changes: 36 additions & 0 deletions src/BlazeKit.Static/FkHttpContext.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace BlazeKit.Static
{
internal class FkHttpContext : HttpContext
{
public override IFeatureCollection Features => throw new NotImplementedException();

public override HttpRequest Request => throw new NotImplementedException();

public override HttpResponse Response => new FkHttpResponse(this);

public override ConnectionInfo Connection => throw new NotImplementedException();

public override WebSocketManager WebSockets => throw new NotImplementedException();

public override ClaimsPrincipal User { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
public override IDictionary<object, object?> Items { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
public override IServiceProvider RequestServices { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
public override CancellationToken RequestAborted { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
public override string TraceIdentifier { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
public override ISession Session { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }

public override void Abort()
{
throw new NotImplementedException();
}
}
}
55 changes: 55 additions & 0 deletions src/BlazeKit.Static/FkHttpResponse.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BlazeKit.Static;

/// <summary>
/// A <see cref="HttpResponse"/> implementation for static site generation purposes"/>
/// </summary>
internal class FkHttpResponse : HttpResponse
{
private readonly HttpContext ctx;

/// <summary>
/// A <see cref="HttpResponse"/> implementation for static site generation purposes"/>
/// </summary>
public FkHttpResponse(HttpContext ctx)
{
this.ctx = ctx;
}
public override HttpContext HttpContext => this.ctx;

public override int StatusCode { get; set; }

public override IHeaderDictionary Headers => new HeaderDictionary();

public override Stream Body { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
public override long? ContentLength { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
public override string? ContentType { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }

public override IResponseCookies Cookies => new FkResponseCookies();

public override bool HasStarted => throw new NotImplementedException();

public override void OnCompleted(Func<object, Task> callback, object state)
{
throw new NotSupportedException();
}

public override void OnStarting(Func<object, Task> callback, object state)
{
throw new NotSupportedException();
}

public override void Redirect([StringSyntax("Uri")] string location, bool permanent)
{
throw new NotSupportedException("'Redirect' is not supported in Static Site Generation");
}
}
28 changes: 28 additions & 0 deletions src/BlazeKit.Static/FkResponseCookies.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
using Microsoft.AspNetCore.Http;

namespace BlazeKit.Static;
/// <summary>
/// A <see cref="IResponseCookies"/> implementation for static site generation purposes"/>
/// </summary>
internal class FkResponseCookies : IResponseCookies
{
public void Append(string key, string value)
{
// do nothing
}

public void Append(string key, string value, CookieOptions options)
{
// do nothing
}

public void Delete(string key)
{
// do nothing
}

public void Delete(string key, CookieOptions options)
{
// do nothing
}
}
61 changes: 61 additions & 0 deletions src/BlazeKit.Static/PageRenderer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Routing;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.JSInterop;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BlazeKit.Static
{
public class PageRenderer
{
private readonly Type rootComponent;
private readonly IServiceCollection serviceCollection;

public PageRenderer(Type rootComponent,IServiceCollection serviceCollection)
{
this.rootComponent = rootComponent;
this.serviceCollection = serviceCollection;
}
public async Task<string> Render(string route)
{
var routeManager = new StaticNavigationManager();

serviceCollection.AddLogging();
serviceCollection.AddSingleton<IHostEnvironment>(new BKitHostEnvironment("Production"));
serviceCollection.AddSingleton<NavigationManager>(routeManager);
serviceCollection.AddSingleton<IJSRuntime>(new FkJsRuntime());
serviceCollection.AddSingleton<INavigationInterception>(new FkNavigationInterception());
serviceCollection.AddSingleton<IScrollToLocationHash>(new FkScrollToLocationHash());
serviceCollection.AddSingleton<IErrorBoundaryLogger>(new StaticErrorBoundaryLogger());

var spv = serviceCollection.BuildServiceProvider();
var scoped = spv.CreateScope();
var serviceProvider = scoped.ServiceProvider;

routeManager.NavigateTo(route, forceLoad: true);
var renderer =
new BlazorRenderer(
new HtmlRenderer(
serviceProvider,
serviceProvider
.GetRequiredService<ILoggerFactory>()
),
serviceProvider
);
var html =
await renderer.RenderComponent(this.rootComponent);

return html;

}
}
}
13 changes: 2 additions & 11 deletions src/BlazeKit.Static/StaticSiteGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Routing;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
Expand Down Expand Up @@ -102,6 +103,7 @@ public Task Build(Type rootComponent, IServiceCollection serviceCollection)
serviceCollection.AddSingleton<INavigationInterception>(new FkNavigationInterception());
serviceCollection.AddSingleton<IScrollToLocationHash>(new FkScrollToLocationHash());
serviceCollection.AddSingleton<IErrorBoundaryLogger>(new StaticErrorBoundaryLogger());
serviceCollection.AddSingleton<HttpContext>(sp => new FkHttpContext());


//serviceCollection.AddScoped<DataHydrationContext>();
Expand Down Expand Up @@ -151,17 +153,6 @@ public Task Build(Type rootComponent, IServiceCollection serviceCollection)

//var route2 = "/loadtest";
routeManager.NavigateTo(route, forceLoad: true);
//var html =
// await
// new BlazorRenderer(
// new HtmlRenderer(
// serviceCollection.BuildServiceProvider(),
// serviceCollection.BuildServiceProvider()
// .GetRequiredService<ILoggerFactory>()
// ),
// serviceCollection.BuildServiceProvider()
// )
// .RenderComponent(rootComponent);
var renderer =
new BlazorRenderer(
new HtmlRenderer(
Expand Down
3 changes: 2 additions & 1 deletion src/BlazeKit.Static/Utils/MarkdownExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using Markdig;
using Markdig;
using Markdig.Extensions.Yaml;
using Markdig.Syntax;
using YamlDotNet.Serialization;
Expand All @@ -14,6 +14,7 @@ public static class MarkdownExtensions

private static readonly MarkdownPipeline Pipeline
= new MarkdownPipelineBuilder()
.UseAdvancedExtensions()
.UseYamlFrontMatter()
.Build();

Expand Down
17 changes: 14 additions & 3 deletions src/BlazeKit.Web/Components/PageComponentBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Rendering;
using Microsoft.AspNetCore.Http;
using System.Net;

namespace BlazeKit.Web.Components;
public abstract class PageComponentBase<TResult> : IComponent, IPageLoad<TResult> where TResult : PageDataBase
{
[Inject] required public DataHydrationContext HydrationContext { get; init; }
[Inject] required public NavigationManager NavigationManager { get; init; }
[CascadingParameter] private HttpContext? Context { get; set; }
[Inject][CascadingParameter] private HttpContext? Context { get; set; }

private RenderFragment renderFragment;
private readonly string dataKey;
Expand Down Expand Up @@ -58,7 +59,17 @@ public async Task SetParametersAsync(ParameterView parameters)
if(IsServer())
{
var route = new Uri(NavigationManager.Uri);
var data = await this.ServerLoadAsync(route, Context);

var data = await this.ServerLoadAsync(route, new Response(Context));

// check if a redirect has been requested ... if so we stop rendering
if(Context.Response.StatusCode == (int)HttpStatusCode.Redirect)
{
// stop redering
return;
}


if(data != null)
{
this.data = data;
Expand All @@ -83,7 +94,7 @@ protected virtual void BuildRenderTree(RenderTreeBuilder builder)
// but instead should invoke the _renderFragment field.
}

protected virtual Task<TResult> ServerLoadAsync(Uri route, HttpContext? context)
protected virtual Task<TResult> ServerLoadAsync(Uri route, Response? context)
{
return Task.FromResult<TResult>(default(TResult));
}
Expand Down
2 changes: 1 addition & 1 deletion src/BlazeKit.Web/IPageLoad.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,5 @@ namespace BlazeKit.Web;

internal interface IPageLoad<TPageData>
{
virtual Task<TPageData> ServerLoadAsync(Uri route, HttpContext? context) => Task.FromResult(default(TPageData));
virtual Task<TPageData> ServerLoadAsync(Uri route, Response? response) => Task.FromResult(default(TPageData));
}
Loading

0 comments on commit 3da3dcb

Please sign in to comment.