Skip to content

Commit

Permalink
Move ComponentRenderer to ServiceStack
Browse files Browse the repository at this point in the history
  • Loading branch information
mythz committed Dec 6, 2022
1 parent fb2d5ef commit ef56501
Showing 1 changed file with 62 additions and 0 deletions.
62 changes: 62 additions & 0 deletions ServiceStack/src/ServiceStack/BlazorServerUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,11 @@
using System.Collections.Specialized;
using ServiceStack.Configuration;
using ServiceStack.Logging;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.TagHelpers;
using Microsoft.AspNetCore.Razor.TagHelpers;
using System.IO;
using System.Text.Encodings.Web;

namespace ServiceStack;

Expand Down Expand Up @@ -449,4 +454,61 @@ public class JsCookie
public string Expires { get; set; }
}

public interface IComponentRenderer
{
Task<string> RenderComponentAsync<T>(HttpContext httpContext, Dictionary<string, object>? args = null);
Task<string> RenderComponentAsync(Type type, HttpContext httpContext, Dictionary<string, object>? args = null);
}

public class ComponentRenderer : IComponentRenderer
{
public Task<string> RenderComponentAsync<T>(HttpContext httpContext, Dictionary<string, object>? args = null) =>
RenderComponentAsync(typeof(T), httpContext, args);

public async Task<string> RenderComponentAsync(Type componentType, HttpContext httpContext, Dictionary<string, object>? args = null)
{
var componentArgs = new Dictionary<string, object>();
if (args != null)
{
var accessors = TypeProperties.Get(componentType);
foreach (var entry in args)
{
var prop = accessors.GetPublicProperty(entry.Key);
if (prop == null)
continue;

var value = entry.Value.ConvertTo(prop.PropertyType);
componentArgs[prop.Name] = value;
}
}

var componentTagHelper = new ComponentTagHelper
{
ComponentType = componentType,
RenderMode = RenderMode.Static,
Parameters = componentArgs,
ViewContext = new ViewContext { HttpContext = httpContext },
};

var objArgs = new Dictionary<object, object>();
var tagHelperContext = new TagHelperContext(
new TagHelperAttributeList(),
objArgs,
"uniqueid");

var tagHelperOutput = new TagHelperOutput(
"tagName",
new TagHelperAttributeList(),
(useCachedResult, encoder) => Task.FromResult<TagHelperContent>(new DefaultTagHelperContent()));

await componentTagHelper.ProcessAsync(tagHelperContext, tagHelperOutput);

using var stringWriter = new StringWriter();

tagHelperOutput.Content.WriteTo(stringWriter, HtmlEncoder.Default);

return stringWriter.ToString();
}
}

#endif

0 comments on commit ef56501

Please sign in to comment.