Esempio n. 1
0
        public void Bug184()
        {
            input = @"<div>
	<a>(Show)</a>
	<a>(Hide)</a>
</div>
<div>
	Inline text
	<a>(Show)</a>
	Between As
	<a>(Hide)</a>
</div>";
            var htmlSettings = HtmlSettings.Pretty();

            htmlSettings.RemoveOptionalTags       = false;
            htmlSettings.Indent                   = "\t";
            htmlSettings.IsFragmentOnly           = true;
            htmlSettings.OutputTextNodesOnNewLine = false;

            var htmlToText = Uglify.Html(input, htmlSettings);

            equal(htmlToText.Code, @"<div>
	<a>(Show)</a> <a>(Hide)</a>
</div>
<div>
	Inline text <a>(Show)</a> Between As <a>(Hide)</a>
</div>");
        }
Esempio n. 2
0
        public void RemoveAttributes3()
        {
            var settings = new HtmlSettings { RemoveJavaScript = true };

            input = "<a style='text-align: center;'>test</a>";
            equal(minify(input, settings), "<a style=text-align:center>test</a>");
        }
Esempio n. 3
0
        public void Bug174()
        {
            input = @"
<html>
	<head>
		<script>let x = 1; 
let y = function() { foo() }</script>
		<script></script>
		<style>h1 { color: red; }</style>
	</head>
</html>";
            var htmlSettings = HtmlSettings.Pretty();

            htmlSettings.Indent = "\t";
            var htmlToText = Uglify.Html(input, htmlSettings);

            equal(htmlToText.Code, @"<html>
	<head>
		<script>
			let x = 1; 
			let y = function() { foo() }
		</script>
		<script>
		</script>
		<style>
			h1 { color: red; }
		</style>
	</head>
</html>");
        }
Esempio n. 4
0
        public void RemoveAttributes2()
        {
            var settings = new HtmlSettings() { RemoveJavaScript = true };

            input = "<a src='javascript:wtf()'>test</a>";
            equal(minify(input, settings), "<a>test</a>");
        }
Esempio n. 5
0
        public void RemoveScript()
        {
            var settings = new HtmlSettings() {RemoveJavaScript = true};

            input = "<script><!--\nalert(1);\n--></script>";
            equal(minify(input, settings), string.Empty);
        }
Esempio n. 6
0
        /// <summary>
        /// Crunched HTML string passed to it, returning crunched string.
        /// </summary>
        /// <param name="source">source HTML</param>
        /// <param name="settings">HTML minification settings</param>
        /// <param name="sourceFileName">The source file name used when reporting errors. Default is <c>null</c></param>
        /// <returns>minified HTML</returns>
        public static UglifyResult Html(string source, HtmlSettings settings = null, string sourceFileName = null)
        {
            settings = settings ?? DefaultSettings;

            var    parser   = new HtmlParser(source, sourceFileName, settings);
            var    document = parser.Parse();
            string text     = null;

            var errors = new List <UglifyError>(parser.Errors);

            if (document != null)
            {
                var minifier = new HtmlMinifier(document, settings);
                minifier.Minify();

                errors.AddRange(minifier.Errors);

                var writer     = new StringWriter();
                var htmlWriter = new HtmlWriterToHtml(writer, settings);
                htmlWriter.Write(document);
                text = writer.ToString();
            }

            return(new UglifyResult(text, errors));
        }
Esempio n. 7
0
        /// <summary>
        /// Generates HTML for the markdown element.
        /// </summary>
        /// <param name="Output">HTML will be output here.</param>
        public override void GenerateHTML(StringBuilder Output)
        {
            Output.Append("<mark");

            HtmlSettings Settings = this.Document.Settings?.HtmlSettings;
            string       s        = Settings?.HashtagClass;

            if (!string.IsNullOrEmpty(s))
            {
                Output.Append(" class=\"");
                Output.Append(XML.HtmlAttributeEncode(s));
                Output.Append('"');
            }

            s = Settings?.HashtagClickScript;

            if (!string.IsNullOrEmpty(s))
            {
                Output.Append(" onclick=\"");
                Output.Append(XML.HtmlAttributeEncode(s));
                Output.Append('"');
            }

            Output.Append('>');
            Output.Append(this.tag);
            Output.Append("</mark>");
        }
Esempio n. 8
0
        /// <summary>
        /// Runs the HTML minifier on the content.
        /// </summary>
        public static IAsset MinifyHtml(this IAsset bundle, HtmlSettings settings)
        {
            var minifier = new WebOptimizer.HtmlMinifier(settings);

            bundle.Processors.Add(minifier);

            return(bundle);
        }
Esempio n. 9
0
        protected string minify(string html, HtmlSettings settings = null)
        {
            currentHtml = html;
            var result = Uglify.Html(html, settings);

            var text = result.Code;

            messages = result.Errors;
            return(text);
        }
Esempio n. 10
0
        public static string Prettify(string html)
        {
            var settings = HtmlSettings.Pretty();

            settings.IsFragmentOnly      = true;
            settings.MinifyCss           = false;
            settings.MinifyCssAttributes = false;
            settings.MinifyJs            = false;
            return(Uglify.Html(html, settings).ToString());
        }
Esempio n. 11
0
        public void AlphaOrderAttributes()
        {
            var settings = new HtmlSettings
            {
                AlphabeticallyOrderAttributes = true
            };

            input = "<div x=\"1\" y=\"1\" r=\"1\" q=\"1\" p=\"1\"></div>";
            equal(minify(input, settings), "<div p=1 q=1 r=1 x=1 y=1></div>");
        }
        public void PreTagRetainsWhitespace()
        {
            var settings = new HtmlSettings();

            //settings.CollapseWhitespaces = false;
            equal(minify("<pre>Line1\nLine2</pre>", settings), "<pre>Line1\nLine2</pre>");
            equal(minify("<pre>    Line1\n    Line2</pre>", settings), "<pre>    Line1\n    Line2</pre>");
            equal(minify("<pre><code>Line1\nLine2</code></pre>", settings), "<pre><code>Line1\nLine2</code></pre>");
            equal(minify("<pre><code>    Line1\n    Line2</code></pre>", settings), "<pre><code>    Line1\n    Line2</code></pre>");
        }
Esempio n. 13
0
        public void Bug172()
        {
            input = @"
<div>
	<p onclick=""doSomething(1 + 2); "">click me</p>
</div>";
            var htmlSettings = new HtmlSettings();
            var htmlToText   = Uglify.Html(input, htmlSettings);

            equal(htmlToText.Code, @"<div><p onclick=doSomething(3)>click me</div>");
        }
Esempio n. 14
0
        public void Bug73()
        {
            var settings = new HtmlSettings();

            input = @"
<p>para1</p>
<!-- <div class=""block__element--modifier"">something</div> -->
<h2>heading2</h2>
";
            equal(minify(input, settings), "<p>para1<h2>heading2</h2>");
        }
 public OptimizationMiddleware(IOptions <WebOptimizationOptions> optionsAccessor, ILogger <OptimizationMiddleware> logger)
 {
     this.Logger       = logger;
     this.Options      = optionsAccessor.Value;
     this.HtmlSettings = new HtmlSettings()
     {
         IsFragmentOnly      = true,
         MinifyCssAttributes = true,
         MinifyJs            = false
     };
 }
Esempio n. 16
0
        public void AddHtmlBundle_CustomSettings_Success()
        {
            var settings = new HtmlSettings();
            var pipeline = new AssetPipeline();
            var asset    = pipeline.AddHtmlBundle("/foo.html", settings, "file1.css", "file2.css");

            Assert.Equal("/foo.html", asset.Route);
            Assert.Equal("text/html; charset=UTF-8", asset.ContentType);
            Assert.Equal(2, asset.SourceFiles.Count());
            Assert.Equal(3, asset.Processors.Count);
        }
Esempio n. 17
0
 static Minifier()
 {
     htmlsetting = new HtmlSettings
     {
         // 标签上的属性值为空时不要删除,例如<input value="">
         RemoveEmptyAttributes = false
     };
     // body,html,head.如果没有属性会被优化掉的,如果有属性,结束标记会优化掉.
     // 这个优化是合法的,浏览器会自动补全.
     // 参考文档:https://github.com/trullock/NUglify/issues/27
 }
Esempio n. 18
0
        public void TestInvalidHtmlTags()
        {
            var input    = "<p>this should be <parsed>\nthis should> appear\nthis text &lt;should appear</p>";
            var settings = HtmlSettings.Pretty();

            settings.IsFragmentOnly      = true;
            settings.MinifyCss           = false;
            settings.MinifyCssAttributes = false;
            settings.MinifyJs            = false;
            settings.RemoveJavaScript    = true;
            equal(minify(input, settings), "\n<p>\n  this should be\n  <parsed>\n     this should> appear this text &lt;should appear\n  </parsed>\n</p>\n", "(1,19): warning : Unbalanced tag [parsed] within tag [p] requiring a closing tag. Force closing it");
        }
Esempio n. 19
0
 HtmlSettings ConfigureSettings(HtmlSettings htmlSettings)
 {
     if (_HtmlSettings != null)
     {
         return(_HtmlSettings);
     }
     htmlSettings.RemoveEmptyAttributes      = false;
     htmlSettings.KeepOneSpaceWhenCollapsing = true;
     htmlSettings.RemoveComments             = true;
     htmlSettings.AttributeQuoteChar         = '\'';
     return(htmlSettings);
 }
Esempio n. 20
0
        public void TestSelfClosingTagWithOptionalTags()
        {
            var settings = new HtmlSettings()
            {
                IsFragmentOnly        = true,
                RemoveOptionalTags    = false,
                RemoveAttributeQuotes = false
            };

            input  = "<link rel=\"stylesheet\" href=\"style.css\" />";
            output = "<link rel=\"stylesheet\" href=\"style.css\" />";

            equal(minify(input, settings), output);
        }
Esempio n. 21
0
        private IEnumerable <Post> PreparePosts(IEnumerable <Post> posts)
        {
            // Wrap the HTML content with headers, styles, scripts etc.
            int fontsize = _settings.GetSetting("fontsize", () => Config.DefaultFontSize, SettingLocality.Roamed);
            var settings = new HtmlSettings
            {
                FontSize = fontsize
            };

            foreach (var post in posts)
            {
                post.Content.Rendered = HtmlTools.WrapContent(post, settings);
            }
            return(posts);
        }
Esempio n. 22
0
        public void RemoveAttributes()
        {
            var settings = new HtmlSettings
            {
                RemoveAttributes =
                {
                    "data-test",
                    "class"
                }
            };

            input  = "<div CLASS=\"a\" data-foo=\"bar\"><div id=\"id\"></div><p data-test=\"test\"></div>";
            output = "<div data-foo=bar><div id=id></div><p></div>";
            equal(minify(input, settings), output);
        }
Esempio n. 23
0
        public void TestListItemAndParagraph()
        {
            var input = @"<ul> <li><p>test <li><p>test2 <li><p>test3 </ul>";

            equal(minify(input),
                  "<ul><li><p>test<li><p>test2<li><p>test3</ul>");

            var settings = new HtmlSettings()
            {
                RemoveOptionalTags = false, IsFragmentOnly = true
            };

            equal(minify(input, settings),
                  "<ul><li><p>test</p></li><li><p>test2</p></li><li><p>test3</p></li></ul>");
        }
Esempio n. 24
0
        public void Bug170()
        {
            input = "<html><head><title>Please indent me properly</title></head></html>";
            var htmlSettings = HtmlSettings.Pretty();

            htmlSettings.Indent = "\t";
            htmlSettings.OutputTextNodesOnNewLine = false;
            var htmlToText = Uglify.Html(input, htmlSettings);

            equal(htmlToText.Code, @"<html>
	<head>
		<title>Please indent me properly</title>
	</head>
</html>");
        }
Esempio n. 25
0
        public static string WrapContent(Post post, HtmlSettings settings)
        {
            var sb      = new StringBuilder();
            var isDark  = ThemeSelectorService.IsDarkMode();
            var content = post.Content.Rendered;


            // remove first img from post if there's one
            if (post.Embedded.WpFeaturedmedia != null)
            {
                content = Regex.Replace(content, "^<img.*?", "");
                content = Regex.Replace(content, "^<p><img.*?</p>", "");
            }
            // add missing protocols to img links
            content = Regex.Replace(content, "src=\"//", "src=\"https://");

            sb.Append("<html><head>");
            sb.Append("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\">");
            // add stylesheets
            sb.Append("<link rel=\"stylesheet\" href=\"ms-appx-web:///Assets/Web/Style.css\" type=\"text/css\" media=\"screen\" />");
            if (isDark)
            {
                sb.Append("<link rel=\"stylesheet\" href=\"ms-appx-web:///Assets/Web/Dark.css\" type=\"text/css\" media=\"screen\" />");
            }
            else
            {
                sb.Append("<link rel=\"stylesheet\" href=\"ms-appx-web:///Assets/Web/Light.css\" type=\"text/css\" media=\"screen\" />");
            }

            // sb.Append("<script>window.external.notify('test');</script>");
            sb.Append("<style>p {font-size: " + settings.FontSize + "px;}</style>");
            sb.Append("</head><body>");

            sb.Append(FeaturedImage(post));
            sb.Append($"<h1>{post.Title.Rendered}</h1>");

            var authors = new List <User>(post.Embedded.Author);

            sb.Append($"<p id=\"postmeta\">{authors[0].Name} | {post.Date}</p>");
            sb.Append(content);
            sb.Append("</body></html>");

            // add javascript
            sb.Append("<script type=\"text/javascript\" src=\"ms-appx-web:///Assets/Web/hammer.min.js\"></script>");
            sb.Append("<script type=\"text/javascript\" src=\"ms-appx-web:///Assets/Web/script.js\"></script>");

            return(sb.ToString());
        }
Esempio n. 26
0
        public void Bug182()
        {
            input = @"
<div class=defaultHeader style=""text-align: center; background-color: #00bfff"">
test
</div>";
            var htmlSettings = HtmlSettings.Pretty();

            htmlSettings.Indent         = "\t";
            htmlSettings.IsFragmentOnly = true;
            var htmlToText = Uglify.Html(input, htmlSettings);

            equal(htmlToText.Code, @"<div class=""defaultHeader"" style=""text-align: center; background-color: #00bfff;"">
	test
</div>");
        }
Esempio n. 27
0
        public static HtmlSettings GetSettings(Bundle bundle)
        {
            var settings = new HtmlSettings
            {
                RemoveOptionalTags    = GetValue(bundle, "removeOptionalEndTags") == "True",
                ShortBooleanAttribute = GetValue(bundle, "collapseBooleanAttributes", true) == "True",
                MinifyCss             = GetValue(bundle, "minifyEmbeddedCssCode", true) == "True",
                MinifyJs                = GetValue(bundle, "minifyEmbeddedJsCode", true) == "True",
                MinifyCssAttributes     = GetValue(bundle, "minifyInlineCssCode", false) == "True",
                AttributesCaseSensitive = GetValue(bundle, "preserveCase") == "True",
                RemoveComments          = GetValue(bundle, "removeHtmlComments", true) == "True",
                RemoveQuotedAttributes  = GetValue(bundle, "removeQuotedAttributes", true) == "True",
                CollapseWhitespaces     = GetValue(bundle, "collapseWhitespace", true) == "True",
                IsFragmentOnly          = GetValue(bundle, "isFragmentOnly", true) == "True"
            };

            return(settings);
        }
Esempio n. 28
0
        public async Task MinifyHtml_CustomSettings_Success()
        {
            var settings = new HtmlSettings {
                RemoveComments = false
            };
            var minifier = new HtmlMinifier(settings);
            var context  = new Mock <IAssetContext>().SetupAllProperties();

            context.Object.Content = new Dictionary <string, byte[]> {
                { "", "\r\n<!-- foo -->\r\n".AsByteArray() }
            };
            var options = new Mock <WebOptimizerOptions>();

            await minifier.ExecuteAsync(context.Object);

            Assert.Equal("<!-- foo -->", context.Object.Content.First().Value.AsString());
            Assert.Equal("", minifier.CacheKey(new DefaultHttpContext()));
        }
Esempio n. 29
0
        public void Bug206_MOTW()
        {
            var settings = HtmlSettings.Pretty();

            settings.Indent = "\t";
            settings.OutputTextNodesOnNewLine = false;
            settings.RemoveComments           = true;
            settings.KeepCommentsRegex.Add(new Regex(@"saved from url="));

            input = @"<!-- saved from url=(0014)about:internet -->
<!DOCTYPE html>
<html>
<body>
<p>test</p>
</body>
</html>";
            equal(minify(input, settings), "<!-- saved from url=(0014)about:internet -->\n<!DOCTYPE html>\n<html>\n	<body>\n		<p>test</p>\n	</body>\n</html>");
        }
Esempio n. 30
0
        public void TestDocHtmlHeadBody()
        {
            var input    = @"<!DOCTYPE html>
<html lang='en-us'>
<head>
</head>
<body>
<p>This is a paragraph</p>
</body>
</html>";
            var output   = @"<!DOCTYPE html><html lang=en-us><head></head><body><p>This is a paragraph</body></html>";
            var settings = new HtmlSettings();

            // settings.RemoveOptionalTags = true
            settings.KeepTags.Add("html");
            settings.KeepTags.Add("body");
            settings.KeepTags.Add("head");
            equal(minify(input, settings), output);
        }