forked from dotnet/interactive
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPlotlyChartExtensions.cs
50 lines (45 loc) · 1.89 KB
/
PlotlyChartExtensions.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Text;
using Microsoft.AspNetCore.Html;
using XPlot.Plotly;
using static Microsoft.DotNet.Interactive.Formatting.PocketViewTags;
namespace XPlot.DotNet.Interactive.KernelExtensions
{
public static class PlotlyChartExtensions
{
public static string GetHtml(this PlotlyChart chart)
{
var divElement = div[style: $"width: {chart.Width}px; height: {chart.Height}px;", id: chart.Id]();
var jsElement = chart.GetInlineJS().Replace("<script>", string.Empty).Replace("</script>",string.Empty);
return $@"{divElement}
{GetScriptElementWithRequire(jsElement)}"
;
}
private static IHtmlContent GetScriptElementWithRequire(string script)
{
var newScript = new StringBuilder();
newScript.AppendLine("<script type=\"text/javascript\">");
newScript.AppendLine(@"
var renderPlotly = function() {
var xplotRequire = requirejs.config({context:'xplot-3.0.1',paths:{plotly:'https://cdn.plot.ly/plotly-1.49.2.min'}});
xplotRequire(['plotly'], function(Plotly) {");
newScript.AppendLine(script);
newScript.AppendLine(@"});
};
if ((typeof(requirejs) !== typeof(Function)) || (typeof(requirejs.config) !== typeof(Function))) {
var script = document.createElement(""script"");
script.setAttribute(""src"", ""https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.6/require.min.js"");
script.onload = function(){
renderPlotly();
};
document.getElementsByTagName(""head"")[0].appendChild(script);
}
else {
renderPlotly();
}");
newScript.AppendLine("</script>");
return new HtmlString(newScript.ToString());
}
}
}