Exemple #1
0
        private string PreprocessorSorting(StyleSheet stylesheet)
        {
            StringBuilder sb = new StringBuilder(stylesheet.Text);

            var visitor = new CssItemCollector <CssRuleBlock>(true);

            stylesheet.Accept(visitor);

            foreach (var rule in visitor.Items.Where(r => r.IsValid).Reverse())
            {
                if (rule.Children.Count < 2)
                {
                    continue;
                }

                int start  = rule.OpenCurlyBrace.AfterEnd;
                int length = rule.Length - 1;

                length = AdjustLength(rule, start, length);

                if (length < 1)
                {
                    continue;
                }

                string text = GetNormalizedText(rule, start, length);

                string[] declarations = text.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                //.Where(t => !string.IsNullOrWhiteSpace(t)).ToArray();

                var sorted = SortDeclarations2(declarations);

                sb.Remove(start, length - 1);
                sb.Insert(start, string.Join("", sorted));
            }

            return(sb.ToString());
        }
Exemple #2
0
        public string SortStyleSheet(string css)
        {
            ICssParser parser     = new CssParser();
            StyleSheet stylesheet = parser.Parse(css.Trim(), true);

            CssFormatter formatter = new CssFormatter();

            formatter.Options.RemoveLastSemicolon = false;

            StringBuilder sb = new StringBuilder(stylesheet.Text);

            var visitor = new CssItemCollector <RuleBlock>(true);

            stylesheet.Accept(visitor);

            foreach (RuleBlock rule in visitor.Items.Where(r => r.IsValid).Reverse())
            {
                if (rule.Declarations.Count <= 1)
                {
                    continue;
                }

                int start  = rule.OpenCurlyBrace.AfterEnd;
                int length = rule.Length - 2;

                string   text         = formatter.Format(rule.Text).Trim().Trim('}', '{');
                string[] declarations = text.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

                var sorted = SortDeclarations(declarations);

                sb.Remove(start, length);
                sb.Insert(start, string.Join("", sorted));
            }

            return(sb.ToString());
        }