### Setup tinycss2 Development Environment Source: https://github.com/kozea/tinycss2/blob/main/docs/contribute.md Clones the tinycss2 repository, creates a virtual environment, and installs the project with development and testing dependencies. This is the initial setup required for contributing. ```shell git clone https://github.com/Kozea/tinycss2.git cd tinycss2 python -m venv venv virtualenv/bin/pip install -e .[doc,test] ``` -------------------------------- ### Launch Python Interpreter Source: https://github.com/kozea/tinycss2/blob/main/docs/contribute.md Starts a Python interpreter within the activated virtual environment. This allows for interactive testing of code changes. ```shell venv/bin/python ``` -------------------------------- ### Install tinycss2 via pip Source: https://github.com/kozea/tinycss2/blob/main/docs/first_steps.md The standard command to install the tinycss2 library and its dependencies into an active Python virtual environment. ```shell pip install tinycss2 ``` -------------------------------- ### Parse Component Value List with Tinycss2 Source: https://context7.com/kozea/tinycss2/llms.txt Shows how to parse a string into a list of component values (tokens and blocks) using tinycss2.parse_component_value_list. This function provides the lowest-level parsing, returning raw tokens. Examples include parsing dimensions, idents, hashes, and function calls like 'calc()'. ```python import tinycss2 # Parse component values tokens = tinycss2.parse_component_value_list('10px solid #333', skip_comments=True) for token in tokens: print(f"Type: {token.type}") if token.type == 'dimension': print(f" Value: {token.value}, Unit: {token.unit}") elif token.type == 'ident': print(f" Value: {token.value}") elif token.type == 'hash': print(f" Value: #{token.value}, Is ID: {token.is_identifier}") elif token.type == 'whitespace': pass # Skip whitespace in output # Parse function calls tokens = tinycss2.parse_component_value_list('calc(100% - 20px)') func = tokens[0] if func.type == 'function': print(f"Function: {func.name}()") print(f"Arguments: {func.arguments}") ``` -------------------------------- ### Get Declaration Name and Value - Python Source: https://github.com/kozea/tinycss2/blob/main/docs/common_use_cases.md Extracts the name and value from parsed CSS declarations. The value is returned as a list of tokens, which may include whitespace and other token types. ```Python import tinycss2 declarations = tinycss2.parse_blocks_contents('width: 50%;height: 50%') declarations[0].name, declarations[0].value # ('width', [, ]) ``` -------------------------------- ### Serialize CSS Identifier with tinycss2 Source: https://context7.com/kozea/tinycss2/llms.txt Converts a string into a valid CSS identifier. It automatically handles escaping for special characters or identifiers starting with digits. ```python import tinycss2 # Serialize simple identifier print(tinycss2.serialize_identifier('myClass')) # Serialize identifier starting with digit (must be escaped) print(tinycss2.serialize_identifier('123abc')) # Serialize identifier with special characters print(tinycss2.serialize_identifier('my-class')) print(tinycss2.serialize_identifier('has spaces')) # Serialize CSS custom property name print(tinycss2.serialize_identifier('--my-variable')) ``` -------------------------------- ### Build Documentation with Sphinx Source: https://github.com/kozea/tinycss2/blob/main/docs/contribute.md Builds the project's documentation using Sphinx. The output is generated in the docs/_build directory and can be viewed in a web browser. ```shell venv/bin/sphinx-build docs docs/_build ``` -------------------------------- ### Navigate CSS Abstract Syntax Tree Source: https://context7.com/kozea/tinycss2/llms.txt Shows how to parse a full stylesheet into an AST and traverse rules, declarations, and individual tokens. It also demonstrates how to access source location metadata. ```python import tinycss2 css = '@import "base.css"; #main .content { font-size: 16px; color: rgb(50, 50, 50); }' rules = tinycss2.parse_stylesheet(css, skip_whitespace=True, skip_comments=True) for rule in rules: if rule.type == 'at-rule': print(f"At-rule: @{rule.at_keyword}") elif rule.type == 'qualified-rule': declarations = tinycss2.parse_blocks_contents(rule.content, skip_whitespace=True) for decl in declarations: if decl.type == 'declaration': print(f"Property: {decl.name}") # Source location tracking tokens = tinycss2.parse_component_value_list(' abc ') for token in tokens: if token.type == 'ident': print(f"Token '{token.value}' at line {token.source_line}, column {token.source_column}") ``` -------------------------------- ### Compare At-Keyword Tokens Source: https://github.com/kozea/tinycss2/blob/main/docs/api_reference.md Illustrates how to identify an at-keyword token and verify its value using the normalized lower_value attribute. ```python if node.type == 'at-keyword' and node.lower_value == 'import': ``` -------------------------------- ### Compare Literal Tokens Source: https://github.com/kozea/tinycss2/blob/main/docs/api_reference.md Shows how to compare a literal token node against a string value, demonstrating that instances compare equal to their internal value. ```python if node == ';': if node.type == 'literal' and node.value == ';': ``` -------------------------------- ### Check Coding Style with ruff Source: https://github.com/kozea/tinycss2/blob/main/docs/contribute.md Uses the ruff tool to check the coding style of the project according to defined standards. This helps maintain code consistency. ```shell venv/bin/python -m ruff check ``` -------------------------------- ### Check AST Node Type Source: https://github.com/kozea/tinycss2/blob/main/docs/api_reference.md Demonstrates how to check the type of an AST node using the 'type' attribute instead of using isinstance checks. ```python if node.type == 'whitespace': pass ``` -------------------------------- ### Check Dimension Token Unit Source: https://github.com/kozea/tinycss2/blob/main/docs/api_reference.md Demonstrates how to verify if a node is a dimension token and compare its unit to a specific CSS unit like pixels. ```python if node.type == 'dimension' and node.lower_unit == 'px': # Handle pixel dimension ``` -------------------------------- ### Parse CSS Colors with light-dark support Source: https://context7.com/kozea/tinycss2/llms.txt Demonstrates how to resolve CSS light-dark color functions based on specified color schemes. It returns coordinate values for colors or None if the scheme cannot be resolved. ```python from tinycss2.color import parse_color # Dark mode color dark_color = parse_color('light-dark(white, black)', color_schemes=('dark',)) print(f"Dark mode: {dark_color.coordinates}") # Normal color scheme normal_result = parse_color('light-dark(red, blue)', color_schemes='normal') print(f"Normal scheme result: {normal_result}") # Parse with complex light-dark values light = parse_color('light-dark(#ffffff, #1a1a1a)', color_schemes=('light',)) dark = parse_color('light-dark(#ffffff, #1a1a1a)', color_schemes=('dark',)) print(f"Light theme: rgb({light[0]*255:.0f}, {light[1]*255:.0f}, {light[2]*255:.0f})") print(f"Dark theme: rgb({dark[0]*255:.0f}, {dark[1]*255:.0f}, {dark[2]*255:.0f})") ``` -------------------------------- ### AST Node: AtRule Source: https://github.com/kozea/tinycss2/blob/main/docs/api_reference.md Represents a CSS At-Rule, such as @media or @import. ```APIDOC ### *class* `tinycss2.ast.AtRule` **Description**: Represents an [at-rule](https://www.w3.org/TR/css-syntax-3/#at-rule-diagram). At-rules consist of an at-keyword, a prelude, and either a block ('{' ... '}') or a semicolon. **Inherits from**: `tinycss2.ast.Node` **Attributes**: - **`type`**: `'at-rule'` - **`at_keyword`** (`str`): The unescaped value of the at-keyword, without the '@' symbol. - **`lower_at_keyword`** (`str`): The `at_keyword` normalized to ASCII lower case, useful for comparisons (e.g., `node.lower_at_keyword == 'import'`). - **`prelude`** (`list` of component values): The part of the rule before the block or semicolon. - **`content`** (`list` of component values or `None`): The content of the block if the at-rule has one, otherwise `None`. ``` -------------------------------- ### Identify At-Rule Type Source: https://github.com/kozea/tinycss2/blob/main/docs/api_reference.md Shows how to identify an at-rule node and compare its keyword against a known value like 'import' using the lower_at_keyword attribute. ```python if node.type == 'at-rule' and node.lower_at_keyword == 'import': pass ``` -------------------------------- ### Run pytest Tests Source: https://github.com/kozea/tinycss2/blob/main/docs/contribute.md Executes the test suite for tinycss2 using the pytest framework. This command should be run after making code changes to ensure functionality. ```shell venv/bin/python -m pytest ``` -------------------------------- ### Parse One Rule with Tinycss2 Source: https://context7.com/kozea/tinycss2/llms.txt Illustrates parsing a single CSS rule (qualified or at-rule) using tinycss2.parse_one_rule. It shows how to differentiate between rule types, extract selectors and content for qualified rules, and parse at-keywords and preludes for at-rules. It also demonstrates parsing nested rules within an @media block. ```python import tinycss2 # Parse a qualified rule (style rule) rule = tinycss2.parse_one_rule('div.highlight { color: yellow; }') if rule.type == 'qualified-rule': selector = tinycss2.serialize(rule.prelude).strip() print(f"Selector: {selector}") print(f"Content: {tinycss2.serialize(rule.content)}") # Parse an at-rule rule = tinycss2.parse_one_rule('@import url("reset.css");') if rule.type == 'at-rule': print(f"At-keyword: @{rule.at_keyword}") print(f"Prelude: {tinycss2.serialize(rule.prelude).strip()}") print(f"Has block: {rule.content is not None}") # Parse @media rule with block rule = tinycss2.parse_one_rule('@media screen { body { margin: 0; } }') if rule.type == 'at-rule' and rule.lower_at_keyword == 'media': # Parse nested rules from content nested = tinycss2.parse_rule_list(rule.content, skip_whitespace=True) print(f"Nested rules: {len(nested)}") ``` -------------------------------- ### Serialize CSS Nodes with Tinycss2 Source: https://context7.com/kozea/tinycss2/llms.txt Explains how to use tinycss2.serialize to convert parsed CSS structures back into CSS syntax strings. It covers serializing entire stylesheets, lists of component values, declarations, and individual nodes. The function correctly handles edge cases to ensure valid CSS output. ```python import tinycss2 # Round-trip parsing and serialization css = 'body { margin: 0; padding: 10px 20px; }' rules = tinycss2.parse_stylesheet(css) serialized = tinycss2.serialize(rules) print(serialized) # Serialize component values tokens = tinycss2.parse_component_value_list('1px solid red') print(tinycss2.serialize(tokens)) # Serialize declarations declarations = tinycss2.parse_blocks_contents('width: 100%; height: auto;') print(tinycss2.serialize(declarations)) # Individual node serialization rule = tinycss2.parse_one_rule('.box { display: flex; }') print(rule.serialize()) ``` -------------------------------- ### Parse CSS Stylesheet with tinycss2 Source: https://context7.com/kozea/tinycss2/llms.txt Demonstrates parsing a CSS stylesheet string using tinycss2.parse_stylesheet. It shows how to iterate through rules, extract selectors, and parse declarations within qualified rules, while also identifying at-rules. Options to skip comments and whitespace are available. ```python import tinycss2 # Parse a simple stylesheet css = ''' #header { background: blue; color: white; } .container { width: 100%; margin: 0 auto; } @media print { body { font-size: 12pt; } } ''' rules = tinycss2.parse_stylesheet(css, skip_comments=True, skip_whitespace=True) for rule in rules: if rule.type == 'qualified-rule': # Style rule: prelude contains selector, content contains declarations selector = tinycss2.serialize(rule.prelude).strip() print(f"Selector: {selector}") # Parse declarations from rule content declarations = tinycss2.parse_blocks_contents(rule.content, skip_whitespace=True) for decl in declarations: if decl.type == 'declaration': print(f" {decl.name}: {tinycss2.serialize(decl.value).strip()}") elif rule.type == 'at-rule': print(f"At-rule: @{rule.at_keyword}") # Output: # Selector: #header # background: blue # color: white # Selector: .container # width: 100% # margin: 0 auto # At-rule: @media ``` -------------------------------- ### Color Spaces and White Points Source: https://github.com/kozea/tinycss2/blob/main/docs/api_reference.md Defines supported color spaces and XYZ values for D50 and D65 white points. ```APIDOC ## Color Constants ### `tinycss2.color5.COLOR_SPACES` **Description**: A set of supported color spaces. **Type**: `set` of strings **Values**: `{'a98-rgb', 'device-cmyk', 'display-p3', 'hsl', 'hwb', 'lab', 'lch', 'oklab', 'oklch', 'prophoto-rgb', 'rec2020', 'srgb', 'srgb-linear', 'xyz', 'xyz-d50', 'xyz-d65'}` ### `tinycss2.color5.D50` **Description**: XYZ values of the D50 white point, normalized to Y=1. **Type**: `tuple` of floats **Values**: `(0.9642956764295677, 1, 0.8251046025104602)` ### `tinycss2.color5.D65` **Description**: XYZ values of the D65 white point, normalized to Y=1. **Type**: `tuple` of floats **Values**: `(0.9504559270516716, 1, 1.0890577507598784)` ``` -------------------------------- ### AST Node: Declaration Source: https://github.com/kozea/tinycss2/blob/main/docs/api_reference.md Represents a CSS declaration (e.g., 'color: red'). ```APIDOC ### *class* `tinycss2.ast.Declaration` **Description**: Represents a [declaration](https://www.w3.org/TR/css-syntax-3/#declaration-diagram), which is a property-value pair, optionally followed by `!important`. **Inherits from**: `tinycss2.ast.Node` **Attributes**: - **`type`**: `'declaration'` - **`name`** (`str`): The unescaped name of the CSS property or descriptor. - **`value`** (`list` of component values): The value of the declaration. - **`important`** (`bool`): True if the declaration was marked with `!important`, False otherwise. ``` -------------------------------- ### Parse One Declaration with Tinycss2 Source: https://context7.com/kozea/tinycss2/llms.txt Demonstrates parsing a single CSS declaration using tinycss2.parse_one_declaration. It shows how to extract the declaration name and check for the !important flag, as well as how to handle potential parse errors. ```python import tinycss2 # Parse declaration with !important decl = tinycss2.parse_one_declaration('display: none !important') print(f"{decl.name}: important={decl.important}") # Handle parse errors result = tinycss2.parse_one_declaration('invalid declaration') if result.type == 'error': print(f"Parse error: {result.kind} - {result.message}") ``` -------------------------------- ### Parse CSS Stylesheet Source: https://github.com/kozea/tinycss2/blob/main/docs/first_steps.md Demonstrates the use of parse_stylesheet to convert a CSS string into a list of rule objects. It shows how to inspect the prelude and content tokens of a qualified rule. ```python import tinycss2 rules = tinycss2.parse_stylesheet('#cell div { width: 50% }') print(rules) rule = rules[0] print(rule.prelude) print(rule.content) ``` -------------------------------- ### Compare CSS Declaration Property Source: https://github.com/kozea/tinycss2/blob/main/docs/api_reference.md Demonstrates how to check if a declaration node represents a specific CSS property by using the normalized lower_name attribute. ```python if node.type == 'declaration' and node.lower_name == 'color': ``` -------------------------------- ### tinycss2.serialize Source: https://github.com/kozea/tinycss2/blob/main/docs/api_reference.md Serializes a collection of CSS nodes back into a CSS string. ```APIDOC ## FUNCTION tinycss2.serialize ### Description Serializes an iterable of nodes into a valid CSS string, handling necessary separators like semicolons. ### Parameters - **nodes** (iterable) - Required - An iterable of tinycss2.ast.Node objects. ### Returns A string representing the serialized CSS. ``` -------------------------------- ### Parse One Component Value with Tinycss2 Source: https://context7.com/kozea/tinycss2/llms.txt Demonstrates parsing a single CSS component value using tinycss2.parse_one_component_value. This is useful for parsing individual values like dimensions, function calls (e.g., rgb()), or URL tokens. It shows how to access properties like value, unit, and arguments. ```python import tinycss2 # Parse a single dimension value value = tinycss2.parse_one_component_value('24px') print(f"Type: {value.type}") print(f"Value: {value.value}, Unit: {value.unit}") print(f"Is integer: {value.is_integer}") # Parse a function value value = tinycss2.parse_one_component_value('rgb(255, 128, 0)') if value.type == 'function': print(f"Function: {value.lower_name}") # Arguments include commas and whitespace args = [t for t in value.arguments if t.type not in ('whitespace', 'literal')] print(f"RGB values: {[t.value for t in args]}") # Parse a URL token value = tinycss2.parse_one_component_value('url(image.png)') if value.type == 'url': print(f"URL: {value.value}") ``` -------------------------------- ### Process @media Rules with tinycss2 Source: https://context7.com/kozea/tinycss2/llms.txt Parses CSS stylesheets to extract and process @media rules, including their nested selectors and declarations. It iterates through rules, identifies media queries, and prints nested selectors and their properties. Dependencies: tinycss2. ```python import tinycss2 css = ''' body { margin: 0; } @media screen and (min-width: 768px) { .container { max-width: 750px; } .sidebar { display: block; } } @media print { .no-print { display: none; } } ''' rules = tinycss2.parse_stylesheet(css, skip_whitespace=True, skip_comments=True) for rule in rules: if rule.type == 'at-rule' and rule.lower_at_keyword == 'media': # Extract media query from prelude media_query = tinycss2.serialize(rule.prelude).strip() print(f"@media {media_query}") # Parse nested rules from content if rule.content: nested_rules = tinycss2.parse_rule_list(rule.content, skip_whitespace=True) for nested in nested_rules: if nested.type == 'qualified-rule': selector = tinycss2.serialize(nested.prelude).strip() print(f" {selector}") # Get declarations decls = tinycss2.parse_blocks_contents(nested.content, skip_whitespace=True) for decl in decls: if decl.type == 'declaration': print(f" {decl.name}: {tinycss2.serialize(decl.value).strip()}") print() # Output: # @media screen and (min-width: 768px) # .container # max-width: 750px # .sidebar # display: block # # @media print # .no-print # display: none ``` -------------------------------- ### tinycss2.parse_declaration_list Source: https://github.com/kozea/tinycss2/blob/main/docs/api_reference.md Parses a CSS declaration list, which may include at-rules, declarations, and comments. ```APIDOC ## FUNCTION tinycss2.parse_declaration_list ### Description Parses a CSS declaration list. Note: This is deprecated in CSS Syntax Level 3; use parse_blocks_contents() instead. ### Parameters - **input** (str/iterable) - Required - A string or iterable of component values. - **skip_comments** (bool) - Optional - Ignore CSS comments at the top-level. - **skip_whitespace** (bool) - Optional - Ignore whitespace at the top-level. ### Returns A list of Declaration, AtRule, Comment, WhitespaceToken, and ParseError objects. ``` -------------------------------- ### Parse CSS Stylesheet from Bytes with tinycss2 Source: https://context7.com/kozea/tinycss2/llms.txt Shows how to parse CSS from bytes using tinycss2.parse_stylesheet_bytes, which automatically detects character encoding. This is useful for reading CSS from files or network responses. It also demonstrates how to provide explicit encoding information. ```python import tinycss2 # Parse CSS from a file with open('styles.css', 'rb') as f: css_bytes = f.read() rules, encoding = tinycss2.parse_stylesheet_bytes( css_bytes, protocol_encoding=None, # e.g., charset from Content-Type header environment_encoding=None, # fallback encoding skip_comments=True, skip_whitespace=True ) print(f"Detected encoding: {encoding.name}") for rule in rules: if rule.type == 'qualified-rule': print(tinycss2.serialize(rule.prelude).strip()) # Parse CSS with explicit protocol encoding (e.g., from HTTP response) from urllib.request import urlopen # response = urlopen('https://example.com/style.css') # rules, encoding = tinycss2.parse_stylesheet_bytes( # css_bytes=response.read(), # protocol_encoding=response.info().get_param('charset'), # ) ``` -------------------------------- ### parse_stylesheet Source: https://github.com/kozea/tinycss2/blob/main/docs/first_steps.md Parses a full CSS stylesheet string into a list of qualified rules. ```APIDOC ## parse_stylesheet(css_string) ### Description Parses a string of CSS and returns a list of qualified rule objects representing the stylesheet. ### Method Python Function ### Parameters #### Path Parameters - **css_string** (string) - Required - The CSS stylesheet content to be parsed. ### Request Example import tinycss2 rules = tinycss2.parse_stylesheet('#cell div { width: 50% }') ### Response #### Success Response (List) - **rules** (list) - A list of QualifiedRule objects containing the parsed CSS structure. #### Response Example [] ``` -------------------------------- ### AST Node Base Class Source: https://github.com/kozea/tinycss2/blob/main/docs/api_reference.md Defines the base class for all Abstract Syntax Tree (AST) nodes in tinycss2. ```APIDOC ## Abstract Syntax Tree (AST) Nodes ### *class* `tinycss2.ast.Node` **Description**: Base class for all node types in the tinycss2 AST. This class is never instantiated directly. **Attributes & Methods**: - **`type`** (class attribute, `str`): A unique string identifier for the node type (e.g., 'whitespace', 'qualified-rule'). - **`source_line`** (`int`): The line number of the start of the node in the CSS source (starts at 1). - **`source_column`** (`int`): The column number within `source_line` of the start of the node (starts at 1). - **`serialize()`**: Method that serializes the node back into CSS syntax as a Unicode string. ``` -------------------------------- ### tinycss2.parse_component_value_list Source: https://github.com/kozea/tinycss2/blob/main/docs/api_reference.md Parses a list of CSS component values. ```APIDOC ## FUNCTION tinycss2.parse_component_value_list ### Description Parses a full string of CSS into a list of component values. ### Parameters - **css** (str) - Required - The CSS string to parse. - **skip_comments** (bool) - Optional - Ignore CSS comments. ### Returns A list of component values. ``` -------------------------------- ### nth.parse_nth() Function Source: https://github.com/kozea/tinycss2/blob/main/docs/api_reference.md Parses the syntax used in CSS pseudo-classes like :nth-child(). ```APIDOC ## Parse Syntax ### `tinycss2.nth.parse_nth(input)` **Description**: Parses the [](https://drafts.csswg.org/css-syntax-3/#anb) syntax, commonly found in CSS pseudo-classes such as [:nth-child()](https://drafts.csswg.org/selectors/#nth-child-pseudo). **Parameters**: - **input** (`str` or iterable) - A string or an iterable of component values. **Returns**: - A tuple `(a, b)` of integers if the input is valid. - `None` if the input is invalid. ``` -------------------------------- ### tinycss2.parse_one_declaration Source: https://github.com/kozea/tinycss2/blob/main/docs/api_reference.md Parses a single CSS declaration. ```APIDOC ## FUNCTION tinycss2.parse_one_declaration ### Description Parses a single CSS declaration, commonly used for @supports tests. ### Parameters - **input** (str/iterable) - Required - A string or iterable of component values. - **skip_comments** (bool) - Optional - If input is a string, ignore all CSS comments. ### Returns A Declaration or ParseError object. ``` -------------------------------- ### Serialize CSS AST to String - Python Source: https://github.com/kozea/tinycss2/blob/main/docs/common_use_cases.md Serializes a tinycss2 AST node (like a rule or declaration) back into a CSS string. This is useful for regenerating CSS after modifications or for creating CSS from Python objects. ```Python import tinycss2 rules = tinycss2.parse_stylesheet('body div { width: 50% }') rule = rules[0] print(rule.serialize()) # 'body div { width: 50% }' ``` -------------------------------- ### FUNCTION tinycss2.parse_one_rule Source: https://github.com/kozea/tinycss2/blob/main/docs/api_reference.md Parses a single qualified rule or at-rule. ```APIDOC ## FUNCTION tinycss2.parse_one_rule ### Description Parses a single qualified rule or at-rule. Whitespace or comments before or after the rule are dropped. ### Parameters - **input** (str/iterable) - Required - A string or iterable of component values. - **skip_comments** (bool) - Optional - If input is a string, ignore all CSS comments. ### Response - **Returns** (object) - A QualifiedRule, AtRule, or ParseError object. ``` -------------------------------- ### FUNCTION tinycss2.parse_rule_list Source: https://github.com/kozea/tinycss2/blob/main/docs/api_reference.md Parses a non-top-level CSS rule list, typically used for nested rules like @media. ```APIDOC ## FUNCTION tinycss2.parse_rule_list ### Description Parses a non-top-level rule list. Note: This is deprecated; use parse_blocks_contents instead. ### Parameters - **input** (str/iterable) - Required - A string or iterable of component values. - **skip_comments** (bool) - Optional - Ignore CSS comments at the top-level. - **skip_whitespace** (bool) - Optional - Ignore whitespace at the top-level. ### Response - **Returns** (list) - A list of QualifiedRule, AtRule, Comment, WhitespaceToken, and ParseError objects. ``` -------------------------------- ### Parse An+B Syntax Source: https://github.com/kozea/tinycss2/blob/main/docs/api_reference.md Parses CSS An+B syntax commonly used in pseudo-classes like :nth-child(). It returns a tuple of integers (a, b) or None if the input is invalid. ```python from tinycss2.nth import parse_nth result = parse_nth("2n+1") ``` -------------------------------- ### Parse CSS Stylesheet from Bytes - Python Source: https://github.com/kozea/tinycss2/blob/main/docs/common_use_cases.md Parses CSS from bytes, intelligently handling character encoding based on various hints like @charset rules, HTTP headers, and environment encoding. This is useful for files or network data. ```Python import tinycss2 with open('file.css', 'rb') as fd: css = fd.read() tinycss2.parse_stylesheet_bytes(css) # [] ``` -------------------------------- ### Parse a Single CSS Declaration with tinycss2 Source: https://context7.com/kozea/tinycss2/llms.txt Illustrates parsing a single CSS declaration using tinycss2.parse_one_declaration. This function is useful for parsing individual property-value pairs, such as those found in `@supports` conditions or for validating specific declarations. ```python import tinycss2 # Parse a single declaration decl = tinycss2.parse_one_declaration('background-color: #ff5500') if decl.type == 'declaration': print(f"Property: {decl.name}") print(f"Value tokens: {decl.value}") print(f"Important: {decl.important}") print(f"Serialized: {decl.serialize()}") # Output: # Property: background-color # Value tokens: [] # Important: False # Serialized: background-color: #ff5500 ``` -------------------------------- ### AST Node: QualifiedRule Source: https://github.com/kozea/tinycss2/blob/main/docs/api_reference.md Represents a CSS Qualified Rule, typically a style rule with a prelude and a content block. ```APIDOC ### *class* `tinycss2.ast.QualifiedRule` **Description**: Represents a [qualified rule](https://www.w3.org/TR/css-syntax-3/#qualified-rule-diagram), which has a prelude, followed by a '{' and content, ending with '}'. At the top-level or within conditional rules, this typically represents a style rule. **Inherits from**: `tinycss2.ast.Node` **Attributes**: - **`type`**: `'qualified-rule'` - **`prelude`** (`list` of component values): The part of the rule before the '{' block. - **`content`** (`list` of component values): The list of component values inside the '{' block. ``` -------------------------------- ### Parse CSS nth-child notation Source: https://context7.com/kozea/tinycss2/llms.txt Parses the notation used in CSS pseudo-classes. It converts strings like '2n+1' or 'odd' into a tuple of (a, b) integers. ```python from tinycss2.nth import parse_nth import tinycss2 # Parse simple numbers and keywords print(f"'5' -> {parse_nth('5')}") print(f"'odd' -> {parse_nth('odd')}") # Parse An+B notation print(f"'2n+1' -> {parse_nth('2n+1')}") print(f"'-n+3' -> {parse_nth('-n+3')}") # Use with parsed selector content tokens = tinycss2.parse_component_value_list('3n+2') result = parse_nth(tokens) print(f"Parsed from tokens: {result}") ``` -------------------------------- ### CSS Component Value Types Source: https://github.com/kozea/tinycss2/blob/main/docs/api_reference.md Defines the structure of component values in tinycss2, which are the fundamental building blocks of the CSS AST. ```APIDOC ## CSS Component Value Definitions ### Description Component values represent the atomic units or blocks within a CSS document as parsed by tinycss2. These include tokens like identifiers, numbers, and structural blocks. ### Supported Types - **ParseError**: Represents a syntax error encountered during parsing. - **WhitespaceToken**: Represents CSS whitespace. - **LiteralToken**: Represents punctuation or symbols. - **IdentToken**: Represents CSS identifiers. - **AtKeywordToken**: Represents @-keywords. - **HashToken**: Represents hash-based values (e.g., IDs). - **StringToken**: Represents quoted strings. - **URLToken**: Represents URL values. - **NumberToken**: Represents numeric values. - **PercentageToken**: Represents percentage values. - **DimensionToken**: Represents values with units. - **UnicodeRangeToken**: Represents unicode ranges. - **ParenthesesBlock**: Represents content inside (). - **SquareBracketsBlock**: Represents content inside []. - **CurlyBracketsBlock**: Represents content inside {}. - **FunctionBlock**: Represents CSS functions. - **Comment**: Represents CSS comments. ### Usage These objects are returned by the parser when traversing the CSS AST. ``` -------------------------------- ### tinycss2.parse_stylesheet_bytes Source: https://github.com/kozea/tinycss2/blob/main/docs/api_reference.md Parses a CSS stylesheet from bytes, automatically detecting character encoding similar to web browsers. It handles protocol and environment encodings, with UTF-8 as the fallback. Options are available to skip comments and whitespace at the top level. ```APIDOC ## tinycss2.parse_stylesheet_bytes ### Description Parses a CSS stylesheet from bytes, determining the character encoding as web browsers do. This is useful for reading files or fetching URLs. The encoding is determined from initial bytes or parameters, with UTF-8 as the ultimate fallback. ### Method `parse_stylesheet_bytes` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **css_bytes** (bytes) - Required - A CSS byte string. - **protocol_encoding** (str) - Optional - The encoding label defined by HTTP or equivalent protocol (e.g., via `Content-Type` header). - **environment_encoding** (webencodings.Encoding) - Optional - The environment encoding, if any. - **skip_comments** (bool) - Optional - Ignore CSS comments at the top-level of the stylesheet. If the input is a string, ignore all comments. - **skip_whitespace** (bool) - Optional - Ignore whitespace at the top-level of the stylesheet. Whitespace is preserved in the prelude and content of rules. ### Request Example ```python from urllib.request import urlopen from tinycss2 import parse_stylesheet_bytes response = urlopen('http://example.net/foo.css') rules, encoding = parse_stylesheet_bytes( css_bytes=response.read(), protocol_encoding=response.info().get_content_type().get_param('charset'), ) for rule in rules: ... ``` ### Response #### Success Response (200) - **rules** (list) - A list of QualifiedRule, AtRule, Comment, WhitespaceToken, and ParseError objects. - **encoding** (webencodings.Encoding) - The webencodings.Encoding object used. If `rules` contains an `@import` rule, this is the environment encoding for the imported stylesheet. #### Response Example ```json { "rules": [ { "type": "QualifiedRule", "prelude": [...], "content": [...] } ], "encoding": "utf-8" } ``` ``` -------------------------------- ### FUNCTION tinycss2.parse_blocks_contents Source: https://github.com/kozea/tinycss2/blob/main/docs/api_reference.md Parses the contents of a CSS block, such as style rules or HTML style attributes. ```APIDOC ## FUNCTION tinycss2.parse_blocks_contents ### Description Parses a block’s contents, used for style rules, @page rules, or HTML style attributes. ### Parameters - **input** (str/iterable) - Required - A string or iterable of component values. - **skip_comments** (bool) - Optional - Ignore CSS comments at the top-level. - **skip_whitespace** (bool) - Optional - Ignore whitespace at the top-level. ### Response - **Returns** (list) - A list of Declaration, AtRule, QualifiedRule, Comment, WhitespaceToken, and ParseError objects. ``` -------------------------------- ### Parse CSS Block Contents with tinycss2 Source: https://context7.com/kozea/tinycss2/llms.txt This snippet demonstrates parsing the content within CSS blocks, such as declarations inside style rules or HTML style attributes, using tinycss2.parse_blocks_contents. It shows how to extract declaration names, values, and the 'important' flag. ```python import tinycss2 # Parse declarations from a style attribute or rule content style = 'color: red; font-size: 16px; margin: 10px 20px !important;' declarations = tinycss2.parse_blocks_contents(style, skip_comments=True, skip_whitespace=True) for item in declarations: if item.type == 'declaration': name = item.name value = tinycss2.serialize(item.value).strip() important = item.important print(f"{name}: {value}{' !important' if important else ''}") # Output: # color: red # font-size: 16px # margin: 10px 20px !important # Parse content from a qualified rule rules = tinycss2.parse_stylesheet('.box { width: 50%; height: auto; }') rule = rules[0] declarations = tinycss2.parse_blocks_contents(rule.content, skip_whitespace=True) for decl in declarations: if decl.type == 'declaration': print(f"{decl.name} = {decl.value}") # Output: # width = [] # height = [] ``` -------------------------------- ### CSS Minification with tinycss2 Source: https://context7.com/kozea/tinycss2/llms.txt Minifies CSS by removing unnecessary whitespace and comments while preserving functionality. The function parses the stylesheet, serializes selectors and declarations, and joins them into a compact string. Dependencies: tinycss2. ```python import tinycss2 def minify_css(css): """Minify CSS by removing unnecessary whitespace and comments.""" rules = tinycss2.parse_stylesheet(css, skip_comments=True, skip_whitespace=True) result = [] for rule in rules: if rule.type == 'qualified-rule': # Minify selector (prelude) selector = tinycss2.serialize(rule.prelude).strip() # Minify declarations decls = tinycss2.parse_blocks_contents(rule.content, skip_whitespace=True) decl_strings = [] for decl in decls: if decl.type == 'declaration': value = tinycss2.serialize(decl.value).strip() important = '!important' if decl.important else '' decl_strings.append(f"{decl.name}:{value}{important}") result.append(f"{selector}{{{';'.join(decl_strings)}}}") elif rule.type == 'at-rule': result.append(rule.serialize()) return ''.join(result) # Example usage css = ''' /* Main styles */ body { margin: 0; padding: 0; font-family: Arial, sans-serif; } .container { max-width: 1200px; margin: 0 auto; } ''' minified = minify_css(css) print(minified) # Output: body{margin:0;padding:0;font-family:Arial, sans-serif}.container{max-width:1200px;margin:0 auto} ``` -------------------------------- ### Parse CSS Declarations - Python Source: https://github.com/kozea/tinycss2/blob/main/docs/common_use_cases.md Parses a list of CSS declarations, typically from the content of a rule or an HTML style attribute. It can accept a list of tokens or a string and optionally skip comments and whitespace. ```Python import tinycss2 rules = tinycss2.parse_stylesheet('body div {width: 50%;height: 50%}') tinycss2.parse_blocks_contents(rules[0].content) # [, ] tinycss2.parse_blocks_contents('width: 50%;height: 50%') # [, ] ``` -------------------------------- ### Parse CSS Color Level 5 Source: https://context7.com/kozea/tinycss2/llms.txt Parses CSS Color Level 5 values, extending Level 4 with features like the light-dark() function and device-cmyk color space. ```python from tinycss2.color5 import parse_color, COLOR_SPACES # Parse light-dark() function for color scheme support light_color = parse_color('light-dark(white, black)', color_schemes=('light',)) print(f"Light mode: {light_color.coordinates}") ``` -------------------------------- ### tinycss2.parse_stylesheet Source: https://github.com/kozea/tinycss2/blob/main/docs/api_reference.md Parses a CSS stylesheet from text (string or iterable). This function is suitable for parsing content from sources like HTML `