Skip to content

Commit

Permalink
Added css inlining
Browse files Browse the repository at this point in the history
  • Loading branch information
TwentyFourMinutes committed Jul 22, 2020
1 parent 0eeb8aa commit 7222fb3
Show file tree
Hide file tree
Showing 8 changed files with 114 additions and 70 deletions.
29 changes: 22 additions & 7 deletions src/RazorMinifier/RazorMinifier.Core/Minifiers/CSHtmlMinifier.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
using System;
using PreMailer.Net;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace RazorMinifier.Core.Minifiers
{
Expand All @@ -20,16 +22,21 @@ static CSHtmlMinifier()
_razorFunctionsRegex = new Regex(@"@functions\s\w+\s?{");
}

public static void MinifyFile(string source, string output)
public static Task<MinifyResult> MinifyFileAsync(string source, string output, bool usePreMailer)
{
var content = File.ReadAllText(source);
return Task.Run(() =>
{
var content = File.ReadAllText(source);
var result = Minify(content, usePreMailer);
content = Minify(content);
File.WriteAllText(output, result.Item1);
File.WriteAllText(output, content);
return result.Item2;
});
}

public static string Minify(string input)
private static (string, MinifyResult) Minify(string input, bool usePreMailer)
{
var headers = new List<string>();

Expand Down Expand Up @@ -58,6 +65,14 @@ public static string Minify(string input)
}
}

InlineResult inlineResult = null;

if (usePreMailer)
{
inlineResult = PreMailer.Net.PreMailer.MoveCssInline(input, true, stripIdAndClassAttributes: true);
input = inlineResult.Html;
}

input = _multiLineCommentRegex.Replace(input, string.Empty);

input = _emptyLineRegex.Replace(input, string.Empty);
Expand All @@ -77,7 +92,7 @@ public static string Minify(string input)
input = string.Concat(header, Environment.NewLine, input);
}

return input;
return (input, new MinifyResult { Success = inlineResult is null || (inlineResult != null && inlineResult.Warnings.Count == 0), Message = inlineResult is null ? null : string.Join(", ", inlineResult.Warnings) });
}
}
}
4 changes: 2 additions & 2 deletions src/RazorMinifier/RazorMinifier.Core/Minifiers/JsMinifier.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
using System;
using StringyEnums;
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using StringyEnums;

namespace RazorMinifier.Core.Minifiers
{
Expand Down
9 changes: 9 additions & 0 deletions src/RazorMinifier/RazorMinifier.Core/MinifyResult.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
namespace RazorMinifier.Core
{
public class MinifyResult
{
public bool Success { get; set; }

public string Message { get; set; }
}
}
66 changes: 33 additions & 33 deletions src/RazorMinifier/RazorMinifier.Core/ProccessExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,43 +5,43 @@

namespace RazorMinifier.Core
{
public static class ProcessExtensions
{
public static async Task StartAndWaitForExitAsync(this Process process, bool dispose = true, CancellationToken cancellationToken = default)
{
var tcs = new TaskCompletionSource<bool>();
public static class ProcessExtensions
{
public static async Task StartAndWaitForExitAsync(this Process process, bool dispose = true, CancellationToken cancellationToken = default)
{
var tcs = new TaskCompletionSource<bool>();

void Process_Exited(object sender, EventArgs e)
{
tcs.TrySetResult(true);
}
void Process_Exited(object sender, EventArgs e)
{
tcs.TrySetResult(true);
}

process.EnableRaisingEvents = true;
process.Exited += Process_Exited;
process.EnableRaisingEvents = true;
process.Exited += Process_Exited;

process.Start();
process.Start();

try
{
if (process.HasExited)
{
return;
}
try
{
if (process.HasExited)
{
return;
}

using (cancellationToken.Register(() => tcs.TrySetCanceled()))
{
await tcs.Task;
}
}
finally
{
process.Exited -= Process_Exited;
using (cancellationToken.Register(() => tcs.TrySetCanceled()))
{
await tcs.Task;
}
}
finally
{
process.Exited -= Process_Exited;

if (dispose)
{
process.Dispose();
}
}
}
}
if (dispose)
{
process.Dispose();
}
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
<PackageReference Include="PreMailer.Net" Version="2.2.0" />
<PackageReference Include="StringyEnums" Version="1.2.0" />
</ItemGroup>

Expand Down
13 changes: 9 additions & 4 deletions src/RazorMinifier/RazorMinifier/Models/Config.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
using Newtonsoft.Json;
using RazorMinifier.Core.Minifiers;
using RazorMinifier.Models.Enums;
using System;
using System.Collections.Generic;
using System.IO;
using System;

namespace RazorMinifier.Models
{
Expand All @@ -18,7 +18,7 @@ public void RemoveFile(MinifiedFile file)
switch (file.MinifyType)
{
case MinifyType.CSHtml:
UserSettings.CSHtmlFiles.Remove(file);
UserSettings.CSHtmlFiles.Remove((CsHtmlMinifiedFile)file);
break;
case MinifyType.Js:
UserSettings.JsFiles.Remove((JsMinifiedFile)file);
Expand Down Expand Up @@ -73,11 +73,11 @@ public MinifiedFile FindFileByFullName(string root, string fullName, MinifyType

public class UserSettings
{
public List<MinifiedFile> CSHtmlFiles { get; set; }
public List<CsHtmlMinifiedFile> CSHtmlFiles { get; set; }
public List<JsMinifiedFile> JsFiles { get; set; }
}

public class MinifiedFile
public abstract class MinifiedFile
{
public string SourceFile { get; set; }
public string OutputFile { get; set; }
Expand Down Expand Up @@ -108,6 +108,11 @@ private string GetFullPath(string root, string path)
=> Path.IsPathRooted(path) ? path : Path.Combine(root, path);
}

public class CsHtmlMinifiedFile : MinifiedFile
{
public bool UsePreMailer { get; set; }
}

public class JsMinifiedFile : MinifiedFile
{
public bool ShortenSyntax { get; set; }
Expand Down
52 changes: 33 additions & 19 deletions src/RazorMinifier/RazorMinifier/RazorMinifier.cs
Original file line number Diff line number Diff line change
@@ -1,23 +1,23 @@
using System;
using System.Collections.Generic;
using System.Data.SqlTypes;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using DulcisX.Core;
using DulcisX.Core;
using DulcisX.Core.Enums;
using DulcisX.Core.Enums.VisualStudio;
using DulcisX.Nodes;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Newtonsoft.Json;
using RazorMinifier.Core;
using RazorMinifier.Core.Minifiers;
using RazorMinifier.Models;
using RazorMinifier.Models.Enums;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Task = System.Threading.Tasks.Task;

namespace RazorMinifier.VSIX
Expand Down Expand Up @@ -119,7 +119,7 @@ public void OnDocumentSaved(IPhysicalNode node)
_ = Task.Run(() => MinifyFileAsync(minifiedFile));
}

public async Task AddToConfigFile(DocumentNode document, string fullName, string relativePath, MinifyType minifyType)
public async Task AddToConfigFileAsync(DocumentNode document, string fullName, string relativePath, MinifyType minifyType)
{
if (Config is null)
return;
Expand All @@ -135,12 +135,12 @@ public async Task AddToConfigFile(DocumentNode document, string fullName, string
case MinifyType.CSHtml:
minifiedFile = await ThreadHelper.JoinableTaskFactory.RunAsync(() =>
{
var file = AddCSHtmlToConfigFile(document, fullName, relativePath);
var file = AddCSHtmlToConfigFileAsync(document, fullName, relativePath);
return Task.FromResult(file);
});

Config.UserSettings.CSHtmlFiles.Add(minifiedFile);
Config.UserSettings.CSHtmlFiles.Add((CsHtmlMinifiedFile)minifiedFile);
break;
default:
throw new InvalidOperationException("Please create an issue on GitHub, if this throws.");
Expand All @@ -164,7 +164,7 @@ private JsMinifiedFile AddJsToConfigFile(string relativePath)

}

private MinifiedFile AddCSHtmlToConfigFile(DocumentNode document, string fullName, string relativePath)
private MinifiedFile AddCSHtmlToConfigFileAsync(DocumentNode document, string fullName, string relativePath)
{
if (!File.Exists(Path.ChangeExtension(fullName, "edit.cshtml")))
{
Expand All @@ -188,9 +188,10 @@ private MinifiedFile AddCSHtmlToConfigFile(DocumentNode document, string fullNam

var newPath = Path.ChangeExtension(relativePath, "edit.cshtml");

return new MinifiedFile
return new CsHtmlMinifiedFile
{
OutputFile = relativePath,
UsePreMailer = false,
SourceFile = newPath
};
}
Expand Down Expand Up @@ -222,10 +223,12 @@ public async Task MinifyFileAsync(MinifiedFile minifiedFile)
return;
}

MinifyResult result = null;

switch (minifiedFile.MinifyType)
{
case MinifyType.CSHtml:
CSHtmlMinifier.MinifyFile(minifiedFile.GetFullSourcePath(root), destinationFile);
result = await CSHtmlMinifier.MinifyFileAsync(minifiedFile.GetFullSourcePath(root), destinationFile, ((CsHtmlMinifiedFile)minifiedFile).UsePreMailer);
break;
case MinifyType.Js:
if (!await JsMinifier.TryMinifyFileAsync("esbuild.exe", minifiedFile.GetFullSourcePath(root), destinationFile, ((JsMinifiedFile)minifiedFile).Options))
Expand All @@ -241,6 +244,17 @@ public async Task MinifyFileAsync(MinifiedFile minifiedFile)
default:
throw new InvalidOperationException("Please create an issue on GitHub, if this throws.");
}

if (result is object && !result.Success)
{
InfoBar.NewMessage()
.WithErrorImage()
.WithText("The file ")
.WithText(minifiedFile.SourceFile, underline: true)
.WithText(" produced warnings. ")
.WithText(result.Message)
.Publish();
}
}

public void CreateConfig()
Expand Down Expand Up @@ -286,7 +300,7 @@ public void SetConfigFile(string fullName)
if (!File.Exists(fullName))
return;

UserSettings config = Config?.UserSettings ?? new UserSettings { CSHtmlFiles = new List<MinifiedFile>(), JsFiles = new List<JsMinifiedFile>() };
UserSettings config = Config?.UserSettings ?? new UserSettings { CSHtmlFiles = new List<CsHtmlMinifiedFile>(), JsFiles = new List<JsMinifiedFile>() };

var content = JsonConvert.SerializeObject(config, Formatting.Indented);

Expand Down Expand Up @@ -358,10 +372,10 @@ public bool TryUpdateConfigFile(string fullName, bool showMessageOnError = true)

settings = JsonConvert.DeserializeObject<UserSettings>(content);

settings.CSHtmlFiles = settings.CSHtmlFiles ?? new List<MinifiedFile>();
settings.CSHtmlFiles = settings.CSHtmlFiles ?? new List<CsHtmlMinifiedFile>();
settings.JsFiles = settings.JsFiles ?? new List<JsMinifiedFile>();

foreach (var file in settings.CSHtmlFiles.Union(settings.JsFiles))
foreach (var file in settings.CSHtmlFiles.Cast<MinifiedFile>().Union(settings.JsFiles))
{
var isSourceValid = File.Exists(file.GetFullSourcePath(root));
var isOutputValid = File.Exists(file.GetFullOutputPath(root));
Expand Down
10 changes: 5 additions & 5 deletions src/RazorMinifier/RazorMinifier/ToggleRazorMinifier.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
using System;
using DulcisX.Nodes;
using Microsoft.VisualStudio.Shell;
using RazorMinifier.Models.Enums;
using System;
using System.ComponentModel.Design;
using System.IO;
using System.Linq;
using DulcisX.Nodes;
using Microsoft.VisualStudio.Shell;
using RazorMinifier.Models.Enums;
using Task = System.Threading.Tasks.Task;

namespace RazorMinifier.VSIX
Expand Down Expand Up @@ -96,7 +96,7 @@ private async void Execute(object sender, EventArgs e)
}
else
{
await _package.AddToConfigFile(node, path, relativePath, minifyType);
await _package.AddToConfigFileAsync(node, path, relativePath, minifyType);
}
}
}
Expand Down

0 comments on commit 7222fb3

Please sign in to comment.