Skip to content

Commit f81bf98

Browse files
author
ArthurHub
committed
clean default style from copy-paste html
1 parent 18f0902 commit f81bf98

1 file changed

Lines changed: 104 additions & 81 deletions

File tree

‎Source/HtmlRenderer/Utils/DomUtils.cs‎

Lines changed: 104 additions & 81 deletions
Original file line numberDiff line numberDiff line change
@@ -192,7 +192,7 @@ public static CssBox GetNextSibling(CssBox b)
192192
public static string GetAttribute(CssBox box, string attribute)
193193
{
194194
string value = null;
195-
while( box != null && value == null )
195+
while (box != null && value == null)
196196
{
197197
value = box.GetAttribute(attribute, null);
198198
box = box.ParentBox;
@@ -210,13 +210,13 @@ public static string GetAttribute(CssBox box, string attribute)
210210
/// <returns>css link box if exists or null</returns>
211211
public static CssBox GetCssBox(CssBox box, Point location, bool visible = true)
212212
{
213-
if( box != null )
213+
if (box != null)
214214
{
215-
if( ( !visible || box.Visibility == CssConstants.Visible ) && ( box.Bounds.IsEmpty || box.Bounds.Contains(location) ) )
215+
if ((!visible || box.Visibility == CssConstants.Visible) && (box.Bounds.IsEmpty || box.Bounds.Contains(location)))
216216
{
217-
foreach(var childBox in box.Boxes)
217+
foreach (var childBox in box.Boxes)
218218
{
219-
if( CommonUtils.GetFirstValueOrDefault(box.Rectangles, box.Bounds).Contains(location) )
219+
if (CommonUtils.GetFirstValueOrDefault(box.Rectangles, box.Bounds).Contains(location))
220220
{
221221
return GetCssBox(childBox, location) ?? childBox;
222222
}
@@ -236,11 +236,11 @@ public static CssBox GetCssBox(CssBox box, Point location, bool visible = true)
236236
/// <returns>css link box if exists or null</returns>
237237
public static CssBox GetLinkBox(CssBox box, Point location)
238238
{
239-
if(box != null)
239+
if (box != null)
240240
{
241-
if(box.IsClickable && box.Visibility == CssConstants.Visible)
241+
if (box.IsClickable && box.Visibility == CssConstants.Visible)
242242
{
243-
if( IsInBox(box, location) )
243+
if (IsInBox(box, location))
244244
return box;
245245
}
246246

@@ -266,17 +266,17 @@ public static CssBox GetLinkBox(CssBox box, Point location)
266266
/// <returns>css box if exists or null</returns>
267267
public static CssBox GetBoxById(CssBox box, string id)
268268
{
269-
if( box != null && !string.IsNullOrEmpty(id) )
269+
if (box != null && !string.IsNullOrEmpty(id))
270270
{
271-
if( box.HtmlTag != null && id.Equals(box.HtmlTag.TryGetAttribute("id"), StringComparison.OrdinalIgnoreCase) )
271+
if (box.HtmlTag != null && id.Equals(box.HtmlTag.TryGetAttribute("id"), StringComparison.OrdinalIgnoreCase))
272272
{
273273
return box;
274274
}
275275

276-
foreach(var childBox in box.Boxes)
276+
foreach (var childBox in box.Boxes)
277277
{
278278
var foundBox = GetBoxById(childBox, id);
279-
if( foundBox != null )
279+
if (foundBox != null)
280280
return foundBox;
281281
}
282282
}
@@ -298,7 +298,7 @@ public static CssLineBox GetCssLineBox(CssBox box, Point location)
298298
{
299299
if (box.LineBoxes.Count > 0)
300300
{
301-
if(box.HtmlTag == null || box.HtmlTag.Name != "td" || box.Bounds.Contains(location))
301+
if (box.HtmlTag == null || box.HtmlTag.Name != "td" || box.Bounds.Contains(location))
302302
{
303303
foreach (var lineBox in box.LineBoxes)
304304
{
@@ -405,7 +405,7 @@ public static CssLineBox GetCssLineBoxByWord(CssRect word)
405405
{
406406
foreach (var lineWord in lineBox.Words)
407407
{
408-
if(lineWord == word)
408+
if (lineWord == word)
409409
{
410410
return lineBox;
411411
}
@@ -423,12 +423,12 @@ public static string GetSelectedPlainText(CssBox root)
423423
{
424424
var sb = new StringBuilder();
425425
var lastWordIndex = GetSelectedPlainText(sb, root);
426-
return sb.ToString(0,lastWordIndex).Trim();
426+
return sb.ToString(0, lastWordIndex).Trim();
427427
}
428428

429429
/// <summary>
430-
/// Generate html from the given dom tree.<br/>
431-
/// Generate all the tyle inside the html.
430+
/// Generate html from the given DOM tree.<br/>
431+
/// Generate all the style inside the html, in header or for every tag depending on <paramref name="styleGen"/> value.
432432
/// </summary>
433433
/// <param name="root">the box of the html generate html from</param>
434434
/// <param name="styleGen">Optional: controls the way styles are generated when html is generated</param>
@@ -501,7 +501,7 @@ private static int GetSelectedPlainText(StringBuilder sb, CssBox box)
501501
// convert hr to line of dashes
502502
if (box.HtmlTag != null && box.HtmlTag.Name == "hr")
503503
{
504-
if(sb.Length > 1 && sb[sb.Length-1] != '\n')
504+
if (sb.Length > 1 && sb[sb.Length - 1] != '\n')
505505
sb.AppendLine();
506506
sb.AppendLine(new string('-', 80));
507507
}
@@ -525,7 +525,7 @@ private static int GetSelectedPlainText(StringBuilder sb, CssBox box)
525525
int newlines = 0;
526526
for (int i = sb.Length - 1; i >= 0 && char.IsWhiteSpace(sb[i]); i--)
527527
newlines += sb[i] == '\n' ? 1 : 0;
528-
if(newlines < 2)
528+
if (newlines < 2)
529529
sb.AppendLine();
530530
}
531531
}
@@ -534,11 +534,11 @@ private static int GetSelectedPlainText(StringBuilder sb, CssBox box)
534534
}
535535

536536
/// <summary>
537-
/// Collect the html tags that have at least one word down the heirarchy that is selected recursevly.<br/>
537+
/// Collect the html tags that have at least one word down the hierarchy that is selected recursively.<br/>
538538
/// </summary>
539539
/// <param name="root">the box to check its sub-tree</param>
540540
/// <returns>the collection to add the selected tags to</returns>
541-
private static Dictionary<HtmlTag,bool> CollectSelectedHtmlTags(CssBox root)
541+
private static Dictionary<HtmlTag, bool> CollectSelectedHtmlTags(CssBox root)
542542
{
543543
var selectedTags = new Dictionary<HtmlTag, bool>();
544544
var maybeTags = new Dictionary<HtmlTag, bool>();
@@ -547,7 +547,7 @@ private static Dictionary<HtmlTag,bool> CollectSelectedHtmlTags(CssBox root)
547547
}
548548

549549
/// <summary>
550-
/// Collect the html tags that have at least one word down the heirarchy that is selected recursevly.<br/>
550+
/// Collect the html tags that have at least one word down the hierarchy that is selected recursively.<br/>
551551
/// </summary>
552552
/// <param name="box">the box to check its sub-tree</param>
553553
/// <param name="selectedTags">the collection to add the selected tags to</param>
@@ -593,61 +593,62 @@ private static bool CollectSelectedHtmlTags(CssBox box, Dictionary<HtmlTag, bool
593593
}
594594

595595
/// <summary>
596-
/// Write the given html dom subtree into the given string builder.
596+
/// Write the given html DOM sub-tree into the given string builder.<br/>
597+
/// If <paramref name="selectedTags"/> are given write html only from those tags.
597598
/// </summary>
598599
/// <param name="sb">the string builder to write html into</param>
599600
/// <param name="box">the html sub-tree to write</param>
600-
/// <param name="indent">the indent to use for nice formating</param>
601+
/// <param name="indent">the indent to use for nice formatting</param>
601602
/// <param name="styleGen">Controls the way styles are generated when html is generated</param>
602603
/// <param name="selectedTags">Control if to generate only selected tags, if given only tags found in collection will be generated</param>
603604
private static void WriteHtml(StringBuilder sb, CssBox box, int indent, HtmlGenerationStyle styleGen, Dictionary<HtmlTag, bool> selectedTags)
604605
{
605-
if (box.HtmlTag != null && selectedTags != null && !selectedTags.ContainsKey(box.HtmlTag))
606-
return;
607-
608-
if (box.HtmlTag != null)
606+
if (box.HtmlTag == null || selectedTags == null || selectedTags.ContainsKey(box.HtmlTag))
609607
{
610-
if (box.HtmlTag.Name != "link" || !box.HtmlTag.Attributes.ContainsKey("href") ||
611-
(!box.HtmlTag.Attributes["href"].StartsWith("property") && !box.HtmlTag.Attributes["href"].StartsWith("method")))
608+
if (box.HtmlTag != null)
612609
{
613-
WriteHtmlTag(sb, box, indent, styleGen);
614-
indent = indent + (box.HtmlTag.IsSingle ? 0 : 1);
615-
}
610+
if (box.HtmlTag.Name != "link" || !box.HtmlTag.Attributes.ContainsKey("href") ||
611+
(!box.HtmlTag.Attributes["href"].StartsWith("property") && !box.HtmlTag.Attributes["href"].StartsWith("method")))
612+
{
613+
WriteHtmlTag(sb, box, indent, styleGen);
614+
indent = indent + (box.HtmlTag.IsSingle ? 0 : 1);
615+
}
616616

617-
if (styleGen == HtmlGenerationStyle.InHeader && box.HtmlTag.Name == "html" && box.HtmlContainer.CssData != null)
618-
{
619-
sb.Append(new string(' ', indent * 4));
620-
sb.AppendLine("<head>");
621-
WriteStylesheet(sb, box.HtmlContainer.CssData, indent + 1);
622-
sb.Append(new string(' ', indent * 4));
623-
sb.AppendLine("</head>");
617+
if (styleGen == HtmlGenerationStyle.InHeader && box.HtmlTag.Name == "html" && box.HtmlContainer.CssData != null)
618+
{
619+
sb.Append(new string(' ', indent * 4));
620+
sb.AppendLine("<head>");
621+
WriteStylesheet(sb, box.HtmlContainer.CssData, indent + 1);
622+
sb.Append(new string(' ', indent * 4));
623+
sb.AppendLine("</head>");
624+
}
624625
}
625-
}
626626

627-
if (box.Words.Count > 0)
628-
{
629-
sb.Append(new string(' ', indent * 4));
630-
foreach (var word in box.Words)
627+
if (box.Words.Count > 0)
631628
{
632-
if (selectedTags == null || word.Selected)
629+
sb.Append(new string(' ', indent * 4));
630+
foreach (var word in box.Words)
633631
{
634-
var wordText = GetSelectedWord(word, selectedTags != null);
635-
sb.Append(HtmlUtils.EncodeHtml(wordText));
632+
if (selectedTags == null || word.Selected)
633+
{
634+
var wordText = GetSelectedWord(word, selectedTags != null);
635+
sb.Append(HtmlUtils.EncodeHtml(wordText));
636+
}
636637
}
638+
sb.AppendLine();
637639
}
638-
sb.AppendLine();
639-
}
640640

641-
foreach (var childBox in box.Boxes)
642-
{
643-
WriteHtml(sb, childBox, indent, styleGen, selectedTags);
644-
}
641+
foreach (var childBox in box.Boxes)
642+
{
643+
WriteHtml(sb, childBox, indent, styleGen, selectedTags);
644+
}
645645

646-
if (box.HtmlTag != null && !box.HtmlTag.IsSingle)
647-
{
648-
sb.Append(new string(' ', Math.Max((indent - 1) * 4, 0)));
649-
sb.AppendFormat("</{0}>", box.HtmlTag.Name);
650-
sb.AppendLine();
646+
if (box.HtmlTag != null && !box.HtmlTag.IsSingle)
647+
{
648+
sb.Append(new string(' ', Math.Max((indent - 1) * 4, 0)));
649+
sb.AppendFormat("</{0}>", box.HtmlTag.Name);
650+
sb.AppendLine();
651+
}
651652
}
652653
}
653654

@@ -656,14 +657,14 @@ private static void WriteHtml(StringBuilder sb, CssBox box, int indent, HtmlGene
656657
/// </summary>
657658
/// <param name="sb">the string builder to write html into</param>
658659
/// <param name="box">the css box with the html tag to write</param>
659-
/// <param name="indent">the indent to use for nice formating</param>
660+
/// <param name="indent">the indent to use for nice formatting</param>
660661
/// <param name="styleGen">Controls the way styles are generated when html is generated</param>
661662
private static void WriteHtmlTag(StringBuilder sb, CssBox box, int indent, HtmlGenerationStyle styleGen)
662663
{
663664
sb.Append(new string(' ', indent * 4));
664665
sb.AppendFormat("<{0}", box.HtmlTag.Name);
665666

666-
// collect all element style properties incliding from stylesheet
667+
// collect all element style properties including from stylesheet
667668
var tagStyles = new Dictionary<string, string>();
668669
var tagCssBlock = box.HtmlContainer.CssData.GetCssBlock(box.HtmlTag.Name);
669670
if (tagCssBlock != null)
@@ -672,6 +673,7 @@ private static void WriteHtmlTag(StringBuilder sb, CssBox box, int indent, HtmlG
672673
foreach (var cssBlock in tagCssBlock)
673674
foreach (var prop in cssBlock.Properties)
674675
tagStyles[prop.Key] = prop.Value;
676+
675677
}
676678

677679
if (box.HtmlTag.HasAttributes())
@@ -680,20 +682,7 @@ private static void WriteHtmlTag(StringBuilder sb, CssBox box, int indent, HtmlG
680682
foreach (var att in box.HtmlTag.Attributes)
681683
{
682684
// handle image tags by inserting the image using base64 data
683-
if (box.HtmlTag.Name == "img" && att.Key == "src" && (att.Value.StartsWith("property") || att.Value.StartsWith("method")))
684-
{
685-
var img = ((CssBoxImage)box).Image;
686-
if (img != null)
687-
{
688-
using (var buffer = new MemoryStream())
689-
{
690-
img.Save(buffer, ImageFormat.Png);
691-
var base64 = Convert.ToBase64String(buffer.ToArray());
692-
sb.AppendFormat("{0}=\"data:image/png;base64, {1}\" ", att.Key, base64);
693-
}
694-
}
695-
}
696-
else if (styleGen == HtmlGenerationStyle.Inline && att.Key == HtmlConstants.Style)
685+
if (styleGen == HtmlGenerationStyle.Inline && att.Key == HtmlConstants.Style)
697686
{
698687
// if inline style add the styles to the collection
699688
var block = CssParser.ParseCssBlock(box.HtmlTag.Name, box.HtmlTag.TryGetAttribute("style"));
@@ -724,25 +713,59 @@ private static void WriteHtmlTag(StringBuilder sb, CssBox box, int indent, HtmlG
724713
// if inline style insert the style tag with all collected style properties
725714
if (styleGen == HtmlGenerationStyle.Inline && tagStyles.Count > 0)
726715
{
727-
sb.Append(" style=\"");
728-
foreach (var style in tagStyles)
716+
var cleanTagStyles = StripDefaultStyles(box, tagStyles);
717+
if (cleanTagStyles.Count > 0)
729718
{
730-
sb.AppendFormat("{0}: {1}; ", style.Key, style.Value);
719+
sb.Append(" style=\"");
720+
foreach (var style in cleanTagStyles)
721+
sb.AppendFormat("{0}: {1}; ", style.Key, style.Value);
722+
sb.Remove(sb.Length - 1, 1);
723+
sb.Append("\"");
731724
}
732-
sb.Remove(sb.Length - 1, 1);
733-
sb.Append("\"");
734725
}
735726

736727
sb.AppendFormat("{0}>", box.HtmlTag.IsSingle ? "/" : "");
737728
sb.AppendLine();
738729
}
739730

731+
/// <summary>
732+
/// Clean the given style collection by removing default styles so only custom styles remain.<br/>
733+
/// Return new collection where the old remains unchanged.
734+
/// </summary>
735+
/// <param name="box">the box the styles apply to, used to know the default style</param>
736+
/// <param name="tagStyles">the collection of styles to clean</param>
737+
/// <returns>new cleaned styles collection</returns>
738+
private static Dictionary<string, string> StripDefaultStyles(CssBox box, Dictionary<string, string> tagStyles)
739+
{
740+
// ReSharper disable PossibleMultipleEnumeration
741+
var cleanTagStyles = new Dictionary<string, string>();
742+
var defaultBlocks = CssUtils.DefaultCssData.GetCssBlock(box.HtmlTag.Name);
743+
foreach (var style in tagStyles)
744+
{
745+
bool isDefault = false;
746+
foreach (var defaultBlock in defaultBlocks)
747+
{
748+
string value;
749+
if (defaultBlock.Properties.TryGetValue(style.Key, out value) && value.Equals(style.Value, StringComparison.OrdinalIgnoreCase))
750+
{
751+
isDefault = true;
752+
break;
753+
}
754+
}
755+
756+
if (!isDefault)
757+
cleanTagStyles[style.Key] = style.Value;
758+
}
759+
return cleanTagStyles;
760+
// ReSharper restore PossibleMultipleEnumeration
761+
}
762+
740763
/// <summary>
741764
/// Write stylesheet data inline into the html.
742765
/// </summary>
743766
/// <param name="sb">the string builder to write stylesheet into</param>
744767
/// <param name="cssData">the css data to write to the head</param>
745-
/// <param name="indent">the indent to use for nice formating</param>
768+
/// <param name="indent">the indent to use for nice formatting</param>
746769
private static void WriteStylesheet(StringBuilder sb, CssData cssData, int indent)
747770
{
748771
sb.Append(new string(' ', indent * 4));

0 commit comments

Comments
 (0)