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

91 lines
3.0 KiB
Plaintext

@namespace Oqtane.UI
@using System.ComponentModel
@using Oqtane.Shared
@inject SiteState SiteState
@implements IDisposable
@if (!string.IsNullOrEmpty(_title))
{
@((MarkupString)_title)
}
@if (!string.IsNullOrEmpty(_content))
{
@((MarkupString)_content)
}
@code {
private string _title = "";
private string _content = "";
[Parameter]
public string RenderMode { get; set; }
[Parameter]
public string Runtime { get; set; }
protected override void OnInitialized()
{
((INotifyPropertyChanged)SiteState.Properties).PropertyChanged += PropertyChanged;
}
private void PropertyChanged(object sender, PropertyChangedEventArgs e)
{
switch (e.PropertyName)
{
case "PageTitle":
var title = "\n<title>" + SiteState.Properties.PageTitle + "</title>";
if (title != _title)
{
_title = title;
StateHasChanged();
}
break;
case "HeadContent":
var content = FormatScripts(SiteState.Properties.HeadContent) + "\n";
if (content != _content)
{
_content = content;
StateHasChanged();
}
break;
}
}
private string FormatScripts(string headcontent)
{
if (!string.IsNullOrEmpty(headcontent))
{
var index = headcontent.IndexOf("<script");
while (index >= 0)
{
var script = headcontent.Substring(index, headcontent.IndexOf("</script>") + 9 - index);
if (RenderMode == RenderModes.Interactive)
{
// remove scripts when interactive rendering
headcontent = headcontent.Remove(index, script.Length);
}
else
{
// transform scripts into page-scripts when static rendering
var pagescript = script.Replace("script", "page-script");
if (!pagescript.Contains("><"))
{
// convert inline script body to content attribute
var content = pagescript.Substring(pagescript.IndexOf(">") + 1, pagescript.LastIndexOf("<") - pagescript.IndexOf(">") - 1);
pagescript = pagescript.Replace(">" + content, " content=\"" + content.Replace("\"","'") + "\">");
}
// move page-script to end of headcontent as Blazor will move anything after a page-script element to the top of the body
headcontent = headcontent.Replace(script, "");
headcontent = headcontent + pagescript;
}
index = headcontent.IndexOf("<script");
}
}
return headcontent;
}
public void Dispose()
{
((INotifyPropertyChanged)SiteState.Properties).PropertyChanged -= PropertyChanged;
}
}