Forked from janv8000/CssRewriteUrlTransformIgnoringDataUri.cs
Last active
August 29, 2015 14:10
-
-
Save wildcard/86b915ab2cdc7d82cd89 to your computer and use it in GitHub Desktop.
forked to ignore data-uri and put surrounded by url(data:image..)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <remarks>Part of Microsoft.AspNet.Web.Optimization.1.1.3, forked to ignore data-uri</remarks> | |
/// <remarks>forked to ignore data-uri and put surrounded by url(data:image..)</remarks> | |
/// <summary> | |
/// Rewrites urls to be absolute so assets will still be found after bundling | |
/// </summary> | |
public class CssRewriteUrlTransformIgnoringDataUri : IItemTransform | |
{ | |
internal static string RebaseUrlToAbsolute(string baseUrl, string url) | |
{ | |
// Don't do anything to invalid urls or absolute urls or data:image urls | |
if (String.IsNullOrWhiteSpace(url) || | |
String.IsNullOrWhiteSpace(baseUrl) || | |
url.StartsWith("data:image", StringComparison.CurrentCultureIgnoreCase) || | |
url.StartsWith("/", StringComparison.OrdinalIgnoreCase)) | |
{ | |
return url; | |
} | |
// NOTE: now we support for ~ app relative urls here | |
if (!baseUrl.EndsWith("/", StringComparison.OrdinalIgnoreCase)) | |
{ | |
baseUrl += "/"; | |
} | |
return VirtualPathUtility.ToAbsolute(baseUrl + url); | |
} | |
internal static string ConvertUrlsToAbsolute(string baseUrl, string content) | |
{ | |
if (String.IsNullOrWhiteSpace(content)) | |
{ | |
return content; | |
} | |
// Replace all urls with absolute urls | |
var url = new Regex(@"url\(['""]?(?<url>[^)]+?)['""]?\)"); | |
return url.Replace(content, (match => | |
"url(" + RebaseUrlToAbsolute(baseUrl, match.Groups["url"].Value) + ")") | |
); | |
} | |
/// <summary> | |
/// Converts any urls in the input to absolute using the base directory of the include virtual path. | |
/// </summary> | |
/// <param name="includedVirtualPath">The virtual path that was included in the bundle for this item that is being transformed</param> | |
/// <param name="input"></param> | |
/// <example> | |
/// bundle.Include("~/content/some.css") will transform url(images/1.jpg) => url(/content/images/1.jpg) | |
/// </example> | |
public string Process(string includedVirtualPath, string input) | |
{ | |
if (includedVirtualPath == null) | |
{ | |
throw new ArgumentNullException("includedVirtualPath"); | |
} | |
// Strip off the ~ that always occurs in app relative virtual paths | |
string baseUrl = VirtualPathUtility.GetDirectory(includedVirtualPath.Substring(1)); | |
return ConvertUrlsToAbsolute(baseUrl, input); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment