Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/api_reference.rst
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ Color Level 5

.. module:: tinycss2.nth
.. autofunction:: parse_nth
.. autofunction:: serialize_nth


AST nodes
Expand Down
18 changes: 17 additions & 1 deletion tests/test_tinycss2.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
from tinycss2.color4 import Color # isort:skip
from tinycss2.color4 import parse_color as parse_color4 # isort:skip
from tinycss2.color5 import parse_color as parse_color5 # isort:skip
from tinycss2.nth import parse_nth # isort:skip
from tinycss2.nth import parse_nth, serialize_nth # isort:skip


def generic(func):
Expand Down Expand Up @@ -153,6 +153,22 @@ def test_nth(input):
return parse_nth(input)


@pytest.mark.parametrize(('a', 'b', 'expected'), [
(0, 0, '0'), (0, 1, '1'), (0, -2, '-2'), (1, 0, 'n'), (1, 3, 'n+3'), (1, -3, 'n-3'),
(-1, 0, '-n'), (-1, 3, '-n+3'), (-1, -3, '-n-3'), (2, 0, '2n'), (2, 1, '2n+1'),
(2, -4, '2n-4'), (-2, 0, '-2n'), (-2, 1, '-2n+1'), (-2, -4, '-2n-4'),
])
def test_serialize_nth(a, b, expected):
assert serialize_nth(a, b) == expected
assert parse_nth(expected) == (a, b)


@json_test(filename='An+B.json')
def test_round_trip_nth(input):
if numbers := parse_nth(input):
return parse_nth(serialize_nth(*numbers))


@pytest.mark.parametrize('invalid', ['+', '+/**/', 'n+', 'n +', '-n-', '2n +'])
def test_nth_invalid_does_not_crash(invalid):
# Truncated/invalid An+B fragments must return None per parse_nth's
Expand Down
14 changes: 14 additions & 0 deletions tinycss2/nth.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,20 @@ def parse_nth(input):
return parse_end(tokens, 1, int(match.group(1)))



def serialize_nth(a, b):
"""Serialize `<An+B> <https://drafts.csswg.org/css-syntax/#serializing-anb>`_.

:param int a: The step coefficient.
:param int b: The offset.
:returns: An ``an+b`` string.

"""
an = 'n' if a == 1 else '-n' if a == -1 else f'{a}n' if a else ''
b = f'{b}' if not a else f'{b:+}' if b else ''
return an + b


def parse_b(tokens, a):
token = _next_significant(tokens)
if token is None:
Expand Down