Integration with CSS Parsers
Relevant source files
The following files were used as context for generating this wiki page:
The nth-check module provides a specialized utility for parsing and compiling CSS nth-formulas, such as those used in :nth-child() and :nth-last-of-type() selectors. Its primary role in a CSS parsing pipeline is to transform raw string formulas into optimized JavaScript functions that determine if an element's index matches the specified rule.
The integration focuses on high performance and strict adherence to the W3C CSS Selectors Level 3 specification. It abstracts the complexity of the an+b syntax, handling various edge cases like negative step sizes, offsets, and keywords like even or odd.
Sources: README.md:1-10, package.json:5-7, src/parse.ts:1-1, src/index.ts:10-15
Architectural Overview
The integration follows a functional pipeline where a CSS formula string is converted into a numeric representation and then into an executable matcher or generator.
The data flow starts with a string input and results in optimized execution paths for checking indices or generating valid sequences.
Sources: src/index.ts:5-50, src/compile.ts:21-125
Parsing Component
The parser is responsible for interpreting the an+b syntax. It handles the specific tokens allowed in CSS selectors, including signs (+, -), integers, the n identifier, and whitespace.
Parsing Logic and Data Structures
The parser returns a tuple [a, b], where a is the step size and b is the offset.
| Input Type | Formula Example | Resulting [a, b] Tuple |
|---|---|---|
| Keyword | even | [2, 0] |
| Keyword | odd | [2, 1] |
| Simple Offset | 5 | [0, 5] |
| Full Formula | 2n+3 | [2, 3] |
| Negative Step | -n+2 | [-1, 2] |
Sources: src/parse.ts:21-45, src/fixtures/rules.ts:1-35
Implementation Details
The parse function uses internal helpers like readSign, readNumber, and skipWhitespace to navigate the string. It normalizes input by trimming and converting to lowercase before processing.
// src/parse.ts:18-20
export function parse(formula: string): [a: number, b: number] {
formula = formula.trim().toLowerCase();
// ... logic for keywords and an+b parsing
}
Sources: src/parse.ts:18-80
Compilation and Optimization
The compiler takes the [a, b] tuple and produces a highly optimized function. This is critical for CSS engines that may need to evaluate nth-rules against hundreds of DOM nodes.
Optimization Strategies
The compiler evaluates the properties of a and b to return the simplest possible logic:
- Constant Functions: Uses
boolbase'sfalseFuncortrueFuncwhen the rule matches no or all elements. - Simple Comparisons: If
ais 0, -1, or 1, it performs direct index comparisons (e.g.,index === borindex >= b). - Modulo Arithmetic: For complex rules where
abs(a) > 1, it uses a pre-calculated modulo (bModulo) to check matches.
Sources: src/compile.ts:21-50, package.json:62-64
Sequence Generation
In addition to checking indices, the library provides a generator to produce a monotonously increasing sequence of matching indices.
The generator ensures that even negative step sizes result in increasing sequences by calculating appropriate starting points.
Sources: src/compile.ts:100-125, README.md:90-105
Public API for Integrators
The index.ts file exports a simplified interface for external parsers to consume.
nthCheck(formula): The default export. It combinesparseandcompile. Returns a function(index: number) => boolean.sequence(formula): Combinesparseandgenerate. Returns a function() => number | null.
Indexing Note
While CSS nth-rules are 1-indexed (e.g., :nth-child(1) is the first element), the functions returned by nth-check expect 0-indexed values to align with standard JavaScript array and DOM node list indexing.
Sources: src/index.ts:25-28, src/compile.ts:23-25, README.md:25-30
Summary of Integration Flow
- Input: A CSS selector string (e.g.,
"3n+1"). - Parsing: The string is validated and converted to
[3, 1]viasrc/parse.ts. - Indexing Adjustment: The compiler subtracts 1 from the offset
bto handle 0-based indexing (e.g.,[3, 0]). - Execution: The optimized function is used by the CSS engine to filter elements or identify matching positions in the DOM tree.
Sources: src/index.ts:1-50, src/compile.ts:1-50, README.md:1-60