oqtane.framework/Oqtane.Client/UI/ThemeBuilder.razor

90 lines
3.5 KiB
Plaintext

@namespace Oqtane.UI
@inject IJSRuntime JsRuntime
@inject NavigationManager NavigationManager
@DynamicComponent
@code {
[CascadingParameter] PageState PageState { get; set; }
RenderFragment DynamicComponent { get; set; }
protected override async Task OnParametersSetAsync()
{
var interop = new Interop(JsRuntime);
if (!string.IsNullOrEmpty(PageState.Page.Title))
{
await interop.UpdateTitle(PageState.Page.Title);
}
else
{
await interop.UpdateTitle(PageState.Site.Name + " - " + PageState.Page.Name);
}
if (PageState.Site.FaviconFileId != null)
{
await interop.IncludeLink("fav-icon", "shortcut icon", Utilities.ContentUrl(PageState.Alias.Path, PageState.Site.FaviconFileId.Value), "image/x-icon");
}
if (PageState.Site.PwaIsEnabled)
{
await InitializePwa(interop);
}
DynamicComponent = builder =>
{
Type themeType = Type.GetType(PageState.Page.ThemeType);
if (themeType != null)
{
builder.OpenComponent(0, themeType);
builder.CloseComponent();
}
else
{
// theme does not exist with type specified
builder.OpenComponent(0, Type.GetType(Constants.ModuleMessageComponent));
builder.AddAttribute(1, "Message", "Error Loading Page Theme " + PageState.Page.ThemeType);
builder.CloseComponent();
}
};
}
private async Task InitializePwa(Interop interop)
{
// dynamically create manifest.json and add to page
string manifest = "setTimeout(() => { " +
"var manifest = { " +
"\"name\": \"" + PageState.Site.Name + "\", " +
"\"short_name\": \"" + PageState.Site.Name + "\", " +
"\"start_url\": \"/\", " +
"\"display\": \"standalone\", " +
"\"background_color\": \"#fff\", " +
"\"description\": \"" + PageState.Site.Name + "\", " +
"\"icons\": [{ " +
"\"src\": \"" + Utilities.ContentUrl(PageState.Alias.Path, PageState.Site.PwaAppIconFileId.Value) + "\", " +
"\"sizes\": \"192x192\", " +
"\"type\": \"image/png\" " +
"}, { " +
"\"src\": \"" + Utilities.ContentUrl(PageState.Alias.Path, PageState.Site.PwaSplashIconFileId.Value) + "\", " +
"\"sizes\": \"512x512\", " +
"\"type\": \"image/png\" " +
"}] " +
"} " +
"const serialized = JSON.stringify(manifest); " +
"const blob = new Blob([serialized], {type: 'application/javascript'}); " +
"const url = URL.createObjectURL(blob); " +
"document.getElementById('pwa-manifest').setAttribute('href', url); " +
"} " +
", 1000);";
await interop.IncludeScript("pwa-manifestscript", "", manifest, "body");
// service worker must be in root of site
string serviceworker = "if ('serviceWorker' in navigator) { " +
"navigator.serviceWorker.register('/service-worker.js').then(function(registration) { " +
"console.log('ServiceWorker Registration Successful'); " +
"}).catch (function(err) { " +
"console.log('ServiceWorker Registration Failed ', err); " +
"}); " +
"}";
await interop.IncludeScript("pwa-serviceworker", "", serviceworker, "body");
}
}