Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Move inline css and js to external files for SwaggerUI and ReDoc #2965

Merged
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 45 additions & 20 deletions src/Swashbuckle.AspNetCore.ReDoc/ReDocMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,24 +53,30 @@ public ReDocMiddleware(
public async Task Invoke(HttpContext httpContext)
{
var httpMethod = httpContext.Request.Method;
var path = httpContext.Request.Path.Value;

// If the RoutePrefix is requested (with or without trailing slash), redirect to index URL
if (httpMethod == "GET" && Regex.IsMatch(path, $"^/?{Regex.Escape(_options.RoutePrefix)}/?$", RegexOptions.IgnoreCase))
if (HttpMethods.IsGet(httpMethod))
{
// Use relative redirect to support proxy environments
var relativeIndexUrl = string.IsNullOrEmpty(path) || path.EndsWith("/")
? "index.html"
: $"{path.Split('/').Last()}/index.html";
var path = httpContext.Request.Path.Value;

RespondWithRedirect(httpContext.Response, relativeIndexUrl);
return;
}
// If the RoutePrefix is requested (with or without trailing slash), redirect to index URL
if (Regex.IsMatch(path, $"^/?{Regex.Escape(_options.RoutePrefix)}/?$", RegexOptions.IgnoreCase))
{
// Use relative redirect to support proxy environments
var relativeIndexUrl = string.IsNullOrEmpty(path) || path.EndsWith("/")
? "index.html"
: $"{path.Split('/').Last()}/index.html";

if (httpMethod == "GET" && Regex.IsMatch(path, $"/{_options.RoutePrefix}/?index.html", RegexOptions.IgnoreCase))
{
await RespondWithIndexHtml(httpContext.Response);
return;
RespondWithRedirect(httpContext.Response, relativeIndexUrl);
return;
}

var match = Regex.Match(path, $"^/{Regex.Escape(_options.RoutePrefix)}/?(index.(html|css|js))$", RegexOptions.IgnoreCase);

if (match.Success)
{
await RespondWithFile(httpContext.Response, match.Groups[1].Value);
return;
}
}

await _staticFileMiddleware.Invoke(httpContext);
Expand All @@ -97,21 +103,40 @@ private void RespondWithRedirect(HttpResponse response, string location)
response.Headers["Location"] = location;
}

private async Task RespondWithIndexHtml(HttpResponse response)
private async Task RespondWithFile(HttpResponse response, string fileName)
{
response.StatusCode = 200;
response.ContentType = "text/html";

using (var stream = _options.IndexStream())
Stream stream;

switch (fileName)
{
case "index.css":
response.ContentType = "text/css";
stream = typeof(ReDocMiddleware).GetTypeInfo().Assembly
.GetManifestResourceStream($"Swashbuckle.AspNetCore.ReDoc.{fileName}");
break;
case "index.js":
response.ContentType = "application/javascript;charset=utf-8";
stream = typeof(ReDocMiddleware).GetTypeInfo().Assembly
.GetManifestResourceStream($"Swashbuckle.AspNetCore.ReDoc.{fileName}");
break;
default:
response.ContentType = "text/html;charset=utf-8";
stream = _options.IndexStream();
break;
}
martincostello marked this conversation as resolved.
Show resolved Hide resolved

using (stream)
{
// Inject arguments before writing to response
var htmlBuilder = new StringBuilder(new StreamReader(stream).ReadToEnd());
var content = new StringBuilder(new StreamReader(stream).ReadToEnd());
foreach (var entry in GetIndexArguments())
{
htmlBuilder.Replace(entry.Key, entry.Value);
content.Replace(entry.Key, entry.Value);
}

await response.WriteAsync(htmlBuilder.ToString(), Encoding.UTF8);
await response.WriteAsync(content.ToString(), Encoding.UTF8);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,14 @@
</PropertyGroup>

<ItemGroup>
<None Remove="index.css" />
<None Remove="index.js" />
</ItemGroup>

<ItemGroup>
<EmbeddedResource Include="index.css" />
<EmbeddedResource Include="index.html" />
<EmbeddedResource Include="index.js" />
<EmbeddedResource Include="node_modules/redoc/bundles/redoc.standalone.js" />
</ItemGroup>

Expand Down
4 changes: 4 additions & 0 deletions src/Swashbuckle.AspNetCore.ReDoc/index.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
body {
margin: 0;
padding: 0;
}
13 changes: 3 additions & 10 deletions src/Swashbuckle.AspNetCore.ReDoc/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -10,19 +10,12 @@
<!--
Redoc doesn't change outer page styles
-->
<style>
body {
margin: 0;
padding: 0;
}
</style>
<link href="index.css" rel="stylesheet" type="text/css">
%(HeadContent)
</head>
<body>
<div id="redoc-container"></div>
<script src="redoc.standalone.js"></script>
<script type="text/javascript">
Redoc.init('%(SpecUrl)', JSON.parse('%(ConfigObject)'), document.getElementById('redoc-container'))
</script>
<script src="index.js"></script>
</body>
</html>
</html>
1 change: 1 addition & 0 deletions src/Swashbuckle.AspNetCore.ReDoc/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Redoc.init('%(SpecUrl)', JSON.parse('%(ConfigObject)'), document.getElementById('redoc-container'));
martincostello marked this conversation as resolved.
Show resolved Hide resolved
61 changes: 39 additions & 22 deletions src/Swashbuckle.AspNetCore.SwaggerUI/SwaggerUIMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -64,26 +64,30 @@ public SwaggerUIMiddleware(
public async Task Invoke(HttpContext httpContext)
{
var httpMethod = httpContext.Request.Method;
var path = httpContext.Request.Path.Value;

var isGet = HttpMethods.IsGet(httpMethod);

// If the RoutePrefix is requested (with or without trailing slash), redirect to index URL
if (isGet && Regex.IsMatch(path, $"^/?{Regex.Escape(_options.RoutePrefix)}/?$", RegexOptions.IgnoreCase))
if (HttpMethods.IsGet(httpMethod))
{
// Use relative redirect to support proxy environments
var relativeIndexUrl = string.IsNullOrEmpty(path) || path.EndsWith("/")
? "index.html"
: $"{path.Split('/').Last()}/index.html";
var path = httpContext.Request.Path.Value;

RespondWithRedirect(httpContext.Response, relativeIndexUrl);
return;
}
// If the RoutePrefix is requested (with or without trailing slash), redirect to index URL
if (Regex.IsMatch(path, $"^/?{Regex.Escape(_options.RoutePrefix)}/?$", RegexOptions.IgnoreCase))
{
// Use relative redirect to support proxy environments
var relativeIndexUrl = string.IsNullOrEmpty(path) || path.EndsWith("/")
? "index.html"
: $"{path.Split('/').Last()}/index.html";

if (isGet && Regex.IsMatch(path, $"^/{Regex.Escape(_options.RoutePrefix)}/?index.html$", RegexOptions.IgnoreCase))
{
await RespondWithIndexHtml(httpContext.Response);
return;
RespondWithRedirect(httpContext.Response, relativeIndexUrl);
return;
}

var match = Regex.Match(path, $"^/{Regex.Escape(_options.RoutePrefix)}/?(index.(html|js))$", RegexOptions.IgnoreCase);

if (match.Success)
{
await RespondWithFile(httpContext.Response, match.Groups[1].Value);
return;
}
}

await _staticFileMiddleware.Invoke(httpContext);
Expand All @@ -110,23 +114,36 @@ private static void RespondWithRedirect(HttpResponse response, string location)
response.Headers["Location"] = location;
}

private async Task RespondWithIndexHtml(HttpResponse response)
private async Task RespondWithFile(HttpResponse response, string fileName)
{
response.StatusCode = 200;
response.ContentType = "text/html;charset=utf-8";

using (var stream = _options.IndexStream())
Stream stream;

if (fileName == "index.js")
{
response.ContentType = "application/javascript;charset=utf-8";
stream = typeof(SwaggerUIMiddleware).GetTypeInfo().Assembly
.GetManifestResourceStream($"Swashbuckle.AspNetCore.SwaggerUI.{fileName}");
martincostello marked this conversation as resolved.
Show resolved Hide resolved
}
else
{
response.ContentType = "text/html;charset=utf-8";
stream = _options.IndexStream();
}

using (stream)
{
using var reader = new StreamReader(stream);

// Inject arguments before writing to response
var htmlBuilder = new StringBuilder(await reader.ReadToEndAsync());
var content = new StringBuilder(await reader.ReadToEndAsync());
foreach (var entry in GetIndexArguments())
{
htmlBuilder.Replace(entry.Key, entry.Value);
content.Replace(entry.Key, entry.Value);
}

await response.WriteAsync(htmlBuilder.ToString(), Encoding.UTF8);
await response.WriteAsync(content.ToString(), Encoding.UTF8);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@

<ItemGroup>
<EmbeddedResource Include="node_modules/swagger-ui-dist/**/*" Exclude="**/*/index.html;**/*/*.map;**/*/*.json;**/*/*.md;**/*/swagger-ui-es-*" />
<None Remove="index.js" />
<EmbeddedResource Include="index.html" />
<EmbeddedResource Include="index.js" />
junior-santana marked this conversation as resolved.
Show resolved Hide resolved
</ItemGroup>

<ItemGroup Condition=" '$(TargetFramework)' == 'netstandard2.0' ">
Expand Down
106 changes: 5 additions & 101 deletions src/Swashbuckle.AspNetCore.SwaggerUI/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -5,113 +5,17 @@
<meta charset="UTF-8">
<title>%(DocumentTitle)</title>
<link rel="stylesheet" type="text/css" href="%(StylesPath)">
<link rel="stylesheet" type="text/css" href="./index.css">
<link rel="icon" type="image/png" href="./favicon-32x32.png" sizes="32x32" />
<link rel="icon" type="image/png" href="./favicon-16x16.png" sizes="16x16" />
<style>

html {
box-sizing: border-box;
overflow: -moz-scrollbars-vertical;
overflow-y: scroll;
}

*,
*:before,
*:after {
box-sizing: inherit;
}

body {
margin: 0;
background: #fafafa;
}
</style>
%(HeadContent)
%(HeadContent)
</head>

<body>
<div id="swagger-ui"></div>

<!-- Workaround for https://github.com/swagger-api/swagger-editor/issues/1371 -->
<script>
martincostello marked this conversation as resolved.
Show resolved Hide resolved
if (window.navigator.userAgent.indexOf("Edge") > -1) {
console.log("Removing native Edge fetch in favor of swagger-ui's polyfill")
window.fetch = undefined;
}
</script>

<script src="%(ScriptBundlePath)"></script>
<script src="%(ScriptPresetsPath)"></script>
<script>
/* Source: https://gist.github.com/lamberta/3768814
* Parse a string function definition and return a function object. Does not use eval.
* @param {string} str
* @return {function}
*
* Example:
* var f = function (x, y) { return x * y; };
* var g = parseFunction(f.toString());
* g(33, 3); //=> 99
*/
function parseFunction(str) {
if (!str) return void (0);

var fn_body_idx = str.indexOf('{'),
fn_body = str.substring(fn_body_idx + 1, str.lastIndexOf('}')),
fn_declare = str.substring(0, fn_body_idx),
fn_params = fn_declare.substring(fn_declare.indexOf('(') + 1, fn_declare.lastIndexOf(')')),
args = fn_params.split(',');

args.push(fn_body);

function Fn() {
return Function.apply(this, args);
}
Fn.prototype = Function.prototype;

return new Fn();
}

window.onload = function () {
var configObject = JSON.parse('%(ConfigObject)');
var oauthConfigObject = JSON.parse('%(OAuthConfigObject)');

// Workaround for https://github.com/swagger-api/swagger-ui/issues/5945
configObject.urls.forEach(function (item) {
if (item.url.startsWith("http") || item.url.startsWith("/")) return;
item.url = window.location.href.replace("index.html", item.url).split('#')[0];
});

// If validatorUrl is not explicitly provided, disable the feature by setting to null
if (!configObject.hasOwnProperty("validatorUrl"))
configObject.validatorUrl = null

// If oauth2RedirectUrl isn't specified, use the built-in default
if (!configObject.hasOwnProperty("oauth2RedirectUrl"))
configObject.oauth2RedirectUrl = (new URL("oauth2-redirect.html", window.location.href)).href;

// Apply mandatory parameters
configObject.dom_id = "#swagger-ui";
configObject.presets = [SwaggerUIBundle.presets.apis, SwaggerUIStandalonePreset];
configObject.layout = "StandaloneLayout";

// Parse and add interceptor functions
var interceptors = JSON.parse('%(Interceptors)');
if (interceptors.RequestInterceptorFunction)
configObject.requestInterceptor = parseFunction(interceptors.RequestInterceptorFunction);
if (interceptors.ResponseInterceptorFunction)
configObject.responseInterceptor = parseFunction(interceptors.ResponseInterceptorFunction);

// Begin Swagger UI call region

const ui = SwaggerUIBundle(configObject);

ui.initOAuth(oauthConfigObject);

// End Swagger UI call region

window.ui = ui
}
</script>
<script src="%(ScriptBundlePath)" charset="utf-8"></script>
<script src="%(ScriptPresetsPath)" charset="utf-8"></script>
<script src="index.js" charset="utf-8"></script>
</body>
</html>
Loading
Loading