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
20 changes: 20 additions & 0 deletions src/api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,26 @@ describe('CSSNode', () => {
})
})

describe('child_count', () => {
test('should return the number of children', () => {
const source = 'body { color: red; margin: 0; padding: 10px; }'
const root = parse(source, { parse_selectors: false, parse_values: false })
const block = root.first_child!.block!
expect(block.child_count).toBe(3)
})

test('should return 0 for a node with no children', () => {
const root = parse('', { parse_selectors: false, parse_values: false })
expect(root.child_count).toBe(0)
})

test('should match children.length', () => {
const source = 'body { color: red; } div { margin: 0; }'
const root = parse(source, { parse_selectors: false, parse_values: false })
expect(root.child_count).toBe(root.children.length)
})
})

describe('has_prelude', () => {
test('should return true for @media with prelude', () => {
const source = '@media (min-width: 768px) { body { color: red; } }'
Expand Down
11 changes: 11 additions & 0 deletions src/css-node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -584,6 +584,17 @@ export class CSSNode {
return this.arena.has_children(this.index)
}

/** Count children without allocating an intermediate array */
get child_count(): number {
let count = 0
let child_index = this.arena.get_first_child(this.index)
while (child_index !== 0) {
count++
child_index = this.arena.get_next_sibling(child_index)
}
return count
}

/** Get all children as an array */
get children(): CSSNode[] {
let result: CSSNode[] = []
Expand Down
Loading