Skip to content

Commit 9911bd2

Browse files
committed
Implement CSS 2.1 §12.4 counter-reset/counter-increment for content: counter()
counter-reset/counter-increment parsed at the CSS-OM level but had zero effect anywhere - content: counter()/counters() were explicitly out of scope in CssContentEngine's own doc comment, and there was no counter-value tracking anywhere in Core. Adds CssCounterEngine: a forward-order tree walk (hooked into DomParser right after CascadeApplyStyles, before pseudo-element content gets resolved) that threads named counter values through document order - a box inherits its parent's counters for its first child, and each child's resulting counters feed the next sibling - covering ordinary sequential/nested counter usage (including the common case content:counter() needs). Deliberately not the full CSS 2.1 §12.4 algorithm: reversed() and counter-set aren't implemented, and a nested counter-reset for a name already in scope always starts a fresh value rather than the spec's more precise scoping rule - see the class's own remarks for the exact boundary. FormatCounterValue is the single counter-style resolver (decimal, decimal-leading-zero, roman, alpha, with CSS Counter Styles Level 3 §2's fallback-to-decimal for unknown/out-of-range styles), ported from PeachPDF's CssCounterEngine and reusing this fork's existing CommonUtils.ConvertToAlphaNumber for the alphabetic styles. Ports PeachPDF's CssCounterEngineTests.cs (pure formatting, 17 tests) and the counter-related subset of CssContentEngineTests.cs, adapted to run through the real box tree (LayoutHarness + a ::before/::after rule) rather than a hand-built box, since pseudo-element boxes here are only constructible via real selector matching. Adds two new integration tests proving the document-order threading itself works (sequential sibling increments, nested-ancestor visibility) beyond what PeachPDF's own box-local unit tests exercise.
1 parent 543e402 commit 9911bd2

7 files changed

Lines changed: 472 additions & 1 deletion

File tree

‎Source/HtmlRenderer/Core/Dom/CssBoxProperties.cs‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,8 @@ internal abstract class CssBoxProperties
7979
private string _marginRight = "0";
8080
private string _marginTop = "0";
8181
private string _left = "auto";
82+
private string _counterReset = CssConstants.None;
83+
private string _counterIncrement = CssConstants.None;
8284
private string _lineHeight = "normal";
8385
private string _listStyleType = "disc";
8486
private string _listStyleImage = string.Empty;
@@ -726,6 +728,27 @@ public string Right
726728
set { _right = value; }
727729
}
728730

731+
public string CounterReset
732+
{
733+
get { return _counterReset; }
734+
set { _counterReset = value; }
735+
}
736+
737+
public string CounterIncrement
738+
{
739+
get { return _counterIncrement; }
740+
set { _counterIncrement = value; }
741+
}
742+
743+
/// <summary>
744+
/// This box's resolved named-counter values (CSS 2.1 §12.4), as of just after its own
745+
/// <c>counter-reset</c>/<c>counter-increment</c> have been applied - populated once, by
746+
/// <see cref="CssCounterEngine.ResolveCounters"/>, before layout runs. Consulted by
747+
/// <c>content: counter()</c> (<see cref="CssContentEngine"/>).
748+
/// </summary>
749+
internal System.Collections.Generic.Dictionary<string, int> Counters { get; set; }
750+
= new System.Collections.Generic.Dictionary<string, int>();
751+
729752
public string Bottom
730753
{
731754
get { return _bottom; }

‎Source/HtmlRenderer/Core/Dom/CssContentEngine.cs‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,33 @@ private static string Resolve(CssBox box, string content)
7676
sb.Append(attrValue);
7777
}
7878
}
79+
else if (token is FunctionToken counterFunctionToken &&
80+
counterFunctionToken.Data.Equals(FunctionNames.Counter, StringComparison.OrdinalIgnoreCase))
81+
{
82+
// counter(<name> [, <style>]?) - a bare counter() with no name argument (malformed,
83+
// or the counters()-with-separator form this subset doesn't support) contributes no
84+
// text, matching this engine's graceful-ignore-the-unsupported-part behavior.
85+
// ArgumentTokens.ToList() (ValueExtensions' comma-splitting overload, not System.Linq's)
86+
// groups the raw token stream into one List<Token> per comma-separated argument.
87+
var counterArgs = counterFunctionToken.ArgumentTokens.ToList();
88+
if (counterArgs.Count > 0 && counterArgs[0].FirstOrDefault() is KeywordToken counterNameToken)
89+
{
90+
var style = counterArgs.Count > 1 && counterArgs[1].FirstOrDefault() is KeywordToken styleToken
91+
? styleToken.Data
92+
: CssConstants.Decimal;
93+
94+
// Unlike attr() above, no parent fallback is needed here: CssCounterEngine.
95+
// ResolveCounters walks this pseudo-element box as an ordinary child of its
96+
// generating element, so it already carries its own correct post-increment
97+
// counter snapshot (inherited from the generating element's, per §12.4).
98+
int counterValue;
99+
if (!box.Counters.TryGetValue(counterNameToken.Data, out counterValue))
100+
{
101+
counterValue = 1;
102+
}
103+
sb.Append(CssCounterEngine.FormatCounterValue(counterValue, style));
104+
}
105+
}
79106
else if (token is KeywordToken keywordToken)
80107
{
81108
if (keywordToken.Data.Equals(Keywords.OpenQuote, StringComparison.OrdinalIgnoreCase))
Lines changed: 177 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,177 @@
1+
// "Therefore those skilled at the unorthodox
2+
// are infinite as heaven and earth,
3+
// inexhaustible as the great rivers.
4+
// When they come to an end,
5+
// they begin again,
6+
// like the days and months;
7+
// they die and are reborn,
8+
// like the four seasons."
9+
//
10+
// - Sun Tsu,
11+
// "The Art of War"
12+
13+
using System;
14+
using System.Collections.Generic;
15+
using System.Globalization;
16+
using TheArtOfDev.HtmlRenderer.Core.Utils;
17+
18+
namespace TheArtOfDev.HtmlRenderer.Core.Dom
19+
{
20+
/// <summary>
21+
/// Resolves CSS 2.1 §12.4 named counters (<c>counter-reset</c>/<c>counter-increment</c>) into a
22+
/// per-box snapshot of counter values, consulted by <c>content: counter()</c>
23+
/// (<see cref="CssContentEngine"/>).<br/>
24+
/// Deliberately a subset of the full spec algorithm: counters thread forward through document order
25+
/// (a box inherits its parent's counters for its first child, and each child's resulting counters
26+
/// feed the next sibling) which covers ordinary sequential/nested counter usage, but
27+
/// <c>reversed(&lt;name&gt;)</c> and <c>counter-set</c> are not implemented, and a nested
28+
/// <c>counter-reset</c> for a name already in scope always starts a fresh inner value rather than
29+
/// the spec's more precise "new scope only among this element's own following siblings" rule -
30+
/// in practice indistinguishable from the full rule for the common case of one counter-reset per
31+
/// counter name in a document, which is what this port's test coverage exercises.
32+
/// </summary>
33+
internal static class CssCounterEngine
34+
{
35+
/// <summary>
36+
/// Walks <paramref name="box"/> and its descendants in document order, applying each box's own
37+
/// <c>counter-reset</c>/<c>counter-increment</c> (plus the implicit <c>list-item</c> counter a
38+
/// <c>display:list-item</c> box always increments) on top of <paramref name="inherited"/>, and
39+
/// storing the result on <see cref="CssBoxProperties.Counters"/>. Must run once, before layout,
40+
/// after every box's CSS properties are resolved (<c>counter-reset</c>/<c>counter-increment</c>
41+
/// need their final cascaded values).
42+
/// </summary>
43+
/// <returns>
44+
/// The counters visible immediately after <paramref name="box"/> and its whole subtree - what a
45+
/// following sibling should inherit.
46+
/// </returns>
47+
public static Dictionary<string, int> ResolveCounters(CssBox box, Dictionary<string, int> inherited)
48+
{
49+
var counters = new Dictionary<string, int>(inherited);
50+
51+
ApplyCounterReset(box, counters);
52+
ApplyCounterIncrement(box, counters);
53+
54+
box.Counters = new Dictionary<string, int>(counters);
55+
56+
foreach (var child in box.Boxes)
57+
{
58+
counters = ResolveCounters(child, counters);
59+
}
60+
61+
return counters;
62+
}
63+
64+
private static void ApplyCounterReset(CssBox box, Dictionary<string, int> counters)
65+
{
66+
if (string.IsNullOrEmpty(box.CounterReset) || box.CounterReset == CssConstants.None) return;
67+
68+
ForEachNameValuePair(box.CounterReset, defaultValue: 0, (name, value) => counters[name] = value);
69+
}
70+
71+
private static void ApplyCounterIncrement(CssBox box, Dictionary<string, int> counters)
72+
{
73+
if (box.Display == CssConstants.ListItem && !CounterNameAppears(box.CounterIncrement, CssConstants.ListItem))
74+
{
75+
counters[CssConstants.ListItem] = GetOrDefault(counters, CssConstants.ListItem) + 1;
76+
}
77+
78+
if (string.IsNullOrEmpty(box.CounterIncrement) || box.CounterIncrement == CssConstants.None) return;
79+
80+
ForEachNameValuePair(box.CounterIncrement, defaultValue: 1,
81+
(name, value) => counters[name] = GetOrDefault(counters, name) + value);
82+
}
83+
84+
/// <summary>
85+
/// <see cref="Dictionary{TKey,TValue}.GetValueOrDefault(TKey)"/> stand-in: this project also
86+
/// targets netstandard2.0/net462, where that method doesn't exist.
87+
/// </summary>
88+
private static int GetOrDefault(Dictionary<string, int> counters, string name)
89+
{
90+
int value;
91+
return counters.TryGetValue(name, out value) ? value : 0;
92+
}
93+
94+
private static bool CounterNameAppears(string counterPropertyValue, string counterName)
95+
{
96+
if (string.IsNullOrEmpty(counterPropertyValue) || counterPropertyValue == CssConstants.None) return false;
97+
98+
var found = false;
99+
ForEachNameValuePair(counterPropertyValue, 0, (name, _) => found |= name == counterName);
100+
return found;
101+
}
102+
103+
/// <summary>
104+
/// Parses a <c>counter-reset</c>/<c>counter-increment</c> value - a space-separated sequence of
105+
/// <c>&lt;name&gt; [&lt;integer&gt;]?</c> pairs - invoking <paramref name="apply"/> once per name,
106+
/// with <paramref name="defaultValue"/> when no integer follows a given name.
107+
/// </summary>
108+
private static void ForEachNameValuePair(string value, int defaultValue, Action<string, int> apply)
109+
{
110+
var parts = value.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
111+
112+
for (var i = 0; i < parts.Length; i++)
113+
{
114+
var name = parts[i];
115+
var next = i + 1 < parts.Length ? parts[i + 1] : null;
116+
117+
if (next != null && int.TryParse(next, NumberStyles.Integer, CultureInfo.InvariantCulture, out var explicitValue))
118+
{
119+
apply(name, explicitValue);
120+
i++;
121+
}
122+
else
123+
{
124+
apply(name, defaultValue);
125+
}
126+
}
127+
}
128+
129+
/// <summary>
130+
/// Formats a resolved counter value as a string using the given CSS counter style (<c>decimal</c>,
131+
/// <c>decimal-leading-zero</c>, <c>lower-roman</c>, <c>upper-alpha</c>, etc.) - the single
132+
/// counter-style resolver <c>content: counter()</c> uses. Per
133+
/// <see href="https://www.w3.org/TR/css-counter-styles-3/">CSS Counter Styles Level 3 §2</see>, an
134+
/// unknown/invalid style, or a value an alphabetic/symbolic style cannot represent (0 or negative),
135+
/// falls back to <c>decimal</c> rather than rendering nothing.
136+
/// </summary>
137+
public static string FormatCounterValue(int number, string style)
138+
{
139+
if (string.IsNullOrEmpty(style) || style.Equals(CssConstants.Decimal, StringComparison.OrdinalIgnoreCase))
140+
{
141+
return number.ToString(CultureInfo.InvariantCulture);
142+
}
143+
144+
if (style.Equals(CssConstants.DecimalLeadingZero, StringComparison.OrdinalIgnoreCase))
145+
{
146+
return number.ToString("00", CultureInfo.InvariantCulture);
147+
}
148+
149+
if (IsAlphabeticCounterStyle(style))
150+
{
151+
var formatted = CommonUtils.ConvertToAlphaNumber(number, style);
152+
153+
// Alphabetic/symbolic styles have no representation for values outside their range (e.g.
154+
// 0 or negatives, for which ConvertToAlphaNumber yields the empty string) - such values
155+
// fall back to decimal too, per CSS Counter Styles Level 3 §2.
156+
return formatted.Length > 0 ? formatted : number.ToString(CultureInfo.InvariantCulture);
157+
}
158+
159+
// Any other unknown/invalid style falls back to decimal.
160+
return number.ToString(CultureInfo.InvariantCulture);
161+
}
162+
163+
private static bool IsAlphabeticCounterStyle(string style)
164+
{
165+
return style.Equals(CssConstants.LowerRoman, StringComparison.OrdinalIgnoreCase)
166+
|| style.Equals(CssConstants.UpperRoman, StringComparison.OrdinalIgnoreCase)
167+
|| style.Equals(CssConstants.LowerAlpha, StringComparison.OrdinalIgnoreCase)
168+
|| style.Equals(CssConstants.UpperAlpha, StringComparison.OrdinalIgnoreCase)
169+
|| style.Equals(CssConstants.LowerLatin, StringComparison.OrdinalIgnoreCase)
170+
|| style.Equals(CssConstants.UpperLatin, StringComparison.OrdinalIgnoreCase)
171+
|| style.Equals(CssConstants.LowerGreek, StringComparison.OrdinalIgnoreCase)
172+
|| style.Equals(CssConstants.Armenian, StringComparison.OrdinalIgnoreCase)
173+
|| style.Equals(CssConstants.Georgian, StringComparison.OrdinalIgnoreCase)
174+
|| style.Equals(CssConstants.Hebrew, StringComparison.OrdinalIgnoreCase);
175+
}
176+
}
177+
}

‎Source/HtmlRenderer/Core/Parse/DomParser.cs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,8 @@ public DomParser(CssParser cssParser)
8080

8181
SetTextSelectionStyle(htmlContainer, cssData);
8282

83+
CssCounterEngine.ResolveCounters(root, new Dictionary<string, int>());
84+
8385
CorrectTextBoxes(root);
8486

8587
CorrectImgBoxes(root);

‎Source/HtmlRenderer/Core/Utils/CssUtils.cs‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,8 @@ internal static class CssUtils
4949
"padding-bottom", "padding-left", "padding-right", "padding-top",
5050
"page-break-inside", "break-inside", "break-before", "break-after", "page-break-before", "page-break-after",
5151
"widows", "orphans", "page",
52-
"left", "top", "right", "bottom", "width", "max-width", "height", "min-height", "max-height",
52+
"left", "top", "right", "bottom", "counter-reset", "counter-increment",
53+
"width", "max-width", "height", "min-height", "max-height",
5354
"background-color", "background-image", "background-position", "background-repeat",
5455
"content", "color", "display", "direction", "empty-cells", "float", "clear", "box-sizing", "position",
5556
"line-height", "vertical-align", "text-indent", "text-align", "text-decoration-line",
@@ -175,6 +176,10 @@ public static string GetPropertyValue(CssBox cssBox, string propName)
175176
return cssBox.Right;
176177
case "bottom":
177178
return cssBox.Bottom;
179+
case "counter-reset":
180+
return cssBox.CounterReset;
181+
case "counter-increment":
182+
return cssBox.CounterIncrement;
178183
case "width":
179184
return cssBox.Width;
180185
case "max-width":
@@ -386,6 +391,12 @@ public static void SetPropertyValue(CssBox cssBox, string propName, string value
386391
case "bottom":
387392
cssBox.Bottom = value;
388393
break;
394+
case "counter-reset":
395+
cssBox.CounterReset = value;
396+
break;
397+
case "counter-increment":
398+
cssBox.CounterIncrement = value;
399+
break;
389400
case "width":
390401
cssBox.Width = value;
391402
break;

0 commit comments

Comments
 (0)