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 README.md
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ parse_selector_list('h1, h2').children.map((s) => s.text) // ["h1", "h2"]
const decl = parse_declaration('color: red !important')
decl.property // "color"
decl.is_important // true
decl.important // "!important"

for (const node of parse_value('10px 20px')) {
node.type_name // "Dimension"
Expand Down
1 change: 1 addition & 0 deletions src/api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1124,6 +1124,7 @@ describe('CSSNode', () => {
const clone = decl.clone()

expect(clone.is_important).toBe(true)
expect(clone.important).toBe('!important')
})

test('is_important is false', () => {
Expand Down
13 changes: 13 additions & 0 deletions src/arena.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ export class CSSDataArena {
private count: number // Number of nodes currently allocated
private growth_count: number // Number of times the arena has grown
private overflow_lengths: Map<number, number> // Stores actual lengths for nodes > 65535 chars
private important_ranges: Map<number, [number, number]> // Source range of "!important" per declaration; only !important declarations have an entry, so nodes stay 32 bytes
private parents: Uint32Array | null = null // Built on first get_parent() call; nothing is stored per node while parsing

// Growth multiplier when capacity is exceeded
Expand Down Expand Up @@ -145,6 +146,7 @@ export class CSSDataArena {
this.buffer = new ArrayBuffer(initial_capacity * BYTES_PER_NODE)
this.view = new DataView(this.buffer)
this.overflow_lengths = new Map()
this.important_ranges = new Map()
}

// Calculate recommended initial capacity based on CSS source size
Expand Down Expand Up @@ -297,6 +299,17 @@ export class CSSDataArena {
this.overflow_lengths.set(node_index, length)
}

// Mark a declaration as important and record where its "!important" text sits in the source
set_important(node_index: number, start: number, end: number): void {
this.set_flag(node_index, FLAG_IMPORTANT)
this.important_ranges.set(node_index, [start, end])
}

// Source range [start, end) of the "!important" text, undefined if the declaration isn't important
get_important(node_index: number): [number, number] | undefined {
return this.important_ranges.get(node_index)
}

// Write content start delta (offset from startOffset)
set_content_start_delta(node_index: number, delta: number): void {
this.view.setUint16(this.node_offset(node_index) + 16, delta, true)
Expand Down
11 changes: 11 additions & 0 deletions src/css-node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,7 @@ export type PlainCSSNode = {

// Flags (only when true)
is_important?: boolean
important?: string | null
is_vendor_prefixed?: boolean
is_browserhack?: boolean
has_error?: boolean
Expand Down Expand Up @@ -286,6 +287,7 @@ const enumerable_properties = [
'is_vendor_prefixed',
'has_error',
'is_important',
'important',
'left',
'right',
] as const
Expand Down Expand Up @@ -709,6 +711,15 @@ export class CSSNode {
return this.arena.has_flag(this.index, FLAG_IMPORTANT)
}

// Exact source text of the important annotation ("!important", "! IE"), null if absent
get important(): string | null | undefined {
if (this.type !== DECLARATION) {
return undefined
}
const range = this.arena.get_important(this.index)
return range ? this.source.substring(range[0], range[1]) : null
}

// Check if this declaration has a browser hack prefix
get is_browserhack(): boolean | undefined {
if (this.type !== DECLARATION) {
Expand Down
12 changes: 12 additions & 0 deletions src/node-types.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -177,11 +177,23 @@ describe('type narrowing — compile-time', () => {
expectTypeOf(decl).toExtend<Declaration>()
expectTypeOf(decl.property).toEqualTypeOf<string>()
expectTypeOf(decl.is_important).toEqualTypeOf<boolean>()
expectTypeOf(decl.important).toEqualTypeOf<string | null>()
expectTypeOf(decl.is_browserhack).toEqualTypeOf<boolean>()
// `name`, `prelude`, `block` are absent on Declaration — verified by tsc
}
})

test('Declaration narrows important to string / null via is_important', () => {
const decl = parse_declaration('color: red !important')
if (decl.is_important) {
expectTypeOf(decl.important).toEqualTypeOf<string>()
expect(decl.important).toBe('!important')
} else {
expectTypeOf(decl.important).toEqualTypeOf<null>()
}
expect(parse_declaration('color: red').important).toBeNull()
})

test('is_block narrows is_empty to boolean', () => {
const root = parse('a { color: red }')
const rule = root.first_child! as Rule
Expand Down
7 changes: 5 additions & 2 deletions src/node-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,10 @@ export type Atrule = WithClone<
}
>

/**
* When `is_important` is true, `important` is the exact text as written
* (e.g. "!important", "! IE"); otherwise it is null.
*/
export type Declaration = Leaf<
typeof DECLARATION,
'Declaration',
Expand All @@ -210,9 +214,8 @@ export type Declaration = Leaf<
readonly property: string
/** VALUE node (parse_values=true), RAW node (parse_values=false), or null */
readonly value: Value | Raw | null
readonly is_important: boolean
readonly is_browserhack: boolean
}
} & Toggle<'is_important', 'important', string>
>

export type SelectorNode =
Expand Down
29 changes: 29 additions & 0 deletions src/parse-declaration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,35 @@ describe('parse_declaration', () => {
})
})

describe('important text', () => {
test.each([
['color: red !important', '!important'],
['color: red !important;', '!important'],
['color: red!important', '!important'],
['color: red ! important', '! important'],
['color: red !IMPORTANT', '!IMPORTANT'],
['color: red !ie', '!ie'],
['color: red !important /* c */;', '!important'],
['color: red !important/* c */;', '!important'],
['color: red /* ! */ !important', '!important'],
['color: red /* c */ ! /* c */ important;', '! /* c */ important'],
['color: !important', '!important'],
])('%s', (source, expected) => {
expect(parse_declaration(source).important).toBe(expected)
})

test('null when not important', () => {
expect(parse_declaration('color: red').important).toBeNull()
expect(parse_declaration('color: red;').important).toBeNull()
expect(parse_declaration('color: red !').important).toBeNull()
})

test('undefined on non-declaration nodes', () => {
const value = parse_declaration('color: red !important').first_child!
expect((value as { important?: unknown }).important).toBeUndefined()
})
})

describe('Vendor Prefixes', () => {
test('-webkit- vendor prefix', () => {
const node = parse_declaration('-webkit-transform: rotate(45deg)')
Expand Down
15 changes: 8 additions & 7 deletions src/parse-declaration.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// Declaration Parser - Parses CSS declarations into structured AST nodes
import { Lexer, type LexerPosition } from './tokenize.ts'
import { CSSDataArena, DECLARATION, RAW, FLAG_IMPORTANT, FLAG_BROWSERHACK } from './arena.ts'
import { CSSDataArena, DECLARATION, RAW, FLAG_BROWSERHACK } from './arena.ts'
import { ValueParser } from './parse-value.ts'
import {
is_vendor_prefixed,
Expand Down Expand Up @@ -160,7 +160,8 @@ export class DeclarationParser {
let value_end = value_start

// Parse value (everything until ';' or EOF)
let has_important = false
let important_start = 0
let important_end = 0 // stays 0 unless !important is found
let last_end = value_start
// Track parenthesis depth to handle semicolons inside functions (e.g., url(data:image/png;base64,...))
let paren_depth = 0
Expand Down Expand Up @@ -216,12 +217,12 @@ export class DeclarationParser {
if (stop_ch === CHAR_EXCLAMATION) {
// Mark end of value before !important
value_end = lexer.pos
important_start = value_end
lexer.pos++ // consume '!'
// Check if next token is an identifier (doesn't verify it's literally "important")
const next_type = lexer.next_token(true) // skip whitespace
if (next_type === TOKEN_IDENT) {
has_important = true
last_end = lexer.token_end
last_end = important_end = lexer.token_end
lexer.next_token(true) // Advance to next token after "important", skip whitespace
break
}
Expand Down Expand Up @@ -291,9 +292,9 @@ export class DeclarationParser {
}
}

// Set !important flag if found
if (has_important) {
this.arena.set_flag(declaration, FLAG_IMPORTANT)
// Set !important flag and record its text range if found
if (important_end > 0) {
this.arena.set_important(declaration, important_start, important_end)
}

// Set browser hack flag if found
Expand Down
Loading