AstArena
Hierarchy (View Summary)
- Arena
- AstArena
Index
Accessors
Constructors
Methods
Properties
Accessors
transferred
-
get transferred(): boolean
true when the column buffers have been transferred to another thread: the arena can no longer be used
Returns boolean
Methods
allocate
allocate(): number
Returns number
append Child
appendChild(id: number, child: number): void
append a single child node. faster than appendChildren()
Parameters
id: numberchild: number
Returns void
append Child List
appendChildList(id: number, children: number[]): void
append children. same as appendChildren with an array
Parameters
id: numberchildren: number[]
Returns void
append Children
appendChildren(id: number, ...children: number[]): void
Parameters
id: number…children: number[]
Returns void
append Field
appendField(id: number, field: TokenField, ...tokens: number[]): void
append tokens to a structured token field
Parameters
id: numberfield: TokenField…tokens: number[]
Returns void
append Token
appendToken(id: number, token: number): void
append a single token. faster than appendTokens()
Parameters
id: numbertoken: number
Returns void
append Token List
appendTokenList(id: number, children: number[]): void
append tokens. same as appendTokens with an array
Parameters
id: numberchildren: number[]
Returns void
append Tokens
appendTokens(id: number, ...children: number[]): void
Parameters
id: number…children: number[]
Returns void
child Count
childCount(id: number): number
number of children
Parameters
id: number
Returns number
children
children(id: number, filter?: (arena: this, id: number) => boolean): number[]
child node ids
Parameters
id: numberOptionalfilter: (arena: this, id: number) => booleancalled with the arena and the node id
Returns number[]
clone
clone(id: number, deep?: boolean, cloneMap?: Map<number, number> | null): number
clone a node or a token. tokens are always cloned deeply
Parameters
id: numberdeep: boolean = falsealso clone the children (rules) or the value tokens (declarations)
cloneMap: Map<number, number> | null = nullmap of the source ids to their clones
Returns number
compact
compact(errors?: ErrorDescription[] | null): Uint32Array
drop the nodes that are not reachable from the root and renumber the remaining nodes in document order. the node ids change: ids obtained before the call (from visitors for instance) are no longer valid. the unused strings are dropped too
Parameters
Optionalerrors: ErrorDescription[] | nullerror descriptions whose
nodeis remapped
Returns Uint32Array
mapping of the old ids to the new ids (0 when the node was dropped)
compact Strings
compactStrings(): void
drop the interned strings that are no longer referenced by any node
Returns void
copy Location
copyLocation(id: number, source: number): void
copy the source location of another node
Parameters
id: numbersource: numbernode id
Returns void
copy Span
copySpan(target: number, source: number): void
copy the packed location of a node
Parameters
target: numbersource: number
Returns void
copy Token
copyToken(target: number, source: number): void
copy the data columns of a token (type, values, unit, color type, location)
Parameters
target: numbersource: number
Returns void
create At Rule
createAtRule(
typ: EnumToken,
nam: string,
val: string,
block: boolean,
tokens: number[] | null | undefined,
state: EnumAstNodeStatus | null | undefined,
errors: ErrorDescription[] | null | undefined,
): number
allocate an at-rule node
Parameters
typ: EnumTokennam: stringval: stringblock: booleantrue if the at-rule has a block
tokens: number[] | null | undefinedprelude tokens
state: EnumAstNodeStatus | null | undefinederrors: ErrorDescription[] | null | undefined
Returns number
create Binary Expression
create Color
create Comment
create Declaration
createDeclaration(
typ: EnumToken,
nam: string,
val: number[] | null | undefined,
state: EnumAstNodeStatus | null | undefined,
errors: ErrorDescription[] | null | undefined,
): number
allocate a declaration node
Parameters
typ: EnumTokennam: stringval: number[] | null | undefinedvalue tokens
state: EnumAstNodeStatus | null | undefinederrors: ErrorDescription[] | null | undefined
Returns number
create Fraction
createFraction(l: number, r: number): number
allocate a fraction token
Parameters
l: numbernumerator
r: numberdenominator
Returns number
create Function
create List
create Rule
createRule(
typ: EnumToken,
sel: string,
tokens: number[] | null | undefined,
state: EnumAstNodeStatus | null | undefined,
errors: ErrorDescription[] | null | undefined,
): number
allocate a rule node
Parameters
typ: EnumTokensel: stringtokens: number[] | null | undefinedprelude tokens
state: EnumAstNodeStatus | null | undefinederrors: ErrorDescription[] | null | undefined
Returns number
create Style Sheet
createStyleSheet(): number
allocate a stylesheet node
Returns number
create Token
denominator
denominator(id: number): number
denominator of a fraction token
Parameters
id: number
Returns number
detach
detach(id: number): void
detach a node from its parent
Parameters
id: number
Returns void
equals Ignore Case
equalsIgnoreCase(node: number, key: "val" | "nam", string: string): boolean
Parameters
node: numberkey: "val" | "nam"string: string
Returns boolean
expand
expand(ast: number): number
Expand the css nesting rules of a stylesheet, a rule or an at-rule. The tree is expanded in place: the nested rules are moved into the parent of their rule and their selectors are resolved
const result = await parse(`.foo { color: red; .bar & { color: blue } }`);
result.arena.expand(result.ast);
console.log(render(result.arena, result.ast).code);
Parameters
ast: numbernode id
Returns number
the node id
Protectedexpand Rule
expandRule(node: number, parent: number, before: number): void
expand a rule: the nested rules and at-rules are moved out of the rule, into parent before before.
the rule is detached when it has no children left
Parameters
node: numberparent: numberbefore: numberthe expanded nodes are inserted before this child of parent. they are appended when 0
Returns void
Protectedexport Properties
exportProperties(): ArenaProperties
structured-cloneable properties of the arena
Returns ArenaProperties
Protectedexport Transferables
exportTransferables(): ArenaTransferables
column buffers, in the order of arenaColumns. the spans buffer is shared with the spans32 view
Returns ArenaTransferables
field
field(id: number, field: TokenField): number
first token of a structured token field (single token fields: l and r of binary expressions, op, ...)
Parameters
id: numberfield: TokenField
Returns number
field List
fieldList(id: number, field: TokenField): number
list node holding the tokens of a structured token field. created when missing
Parameters
id: numberfield: TokenField
Returns number
field Tokens
fieldTokens(id: number, field: TokenField): number[]
find
find(node: number, matcher: AstNodeMatcher): number | null
Search the ast subtree and return the first match, in document order
// find the first declaration which name is 'aspect-ratio'
import { EnumToken, transform } from "@tbela99/css-parser";
const result = await transform(css);
const arena = result.arena;
const node = arena.find(result.ast, (arena, node) =>
arena.getType(node) == EnumToken.DeclarationNodeType && arena.getName(node) == 'aspect-ratio');
console.log(node == null ? null : arena.toObject(node));
Parameters
node: numbernode id
matcher: AstNodeMatchercalled with the arena and the node id
Returns number | null
the node id or null
find All
findAll(node: number, matcher: AstNodeMatcher): number[]
Search the ast subtree and return all matches, in document order
Parameters
node: numbernode id
matcher: AstNodeMatchercalled with the arena and the node id
Returns number[]
find By Value
findByValue(
node: number,
matcher: AstValueMatcher,
): { node: number; value: number } | null
Search the value tokens of the ast subtree and return the first match: the node that owns the token and the token
// find the first node which contains the length token '30px'
import { EnumToken, transform } from "@tbela99/css-parser";
const result = await transform(css);
const {node, value} = result.arena.findByValue(result.ast, (arena, value) =>
arena.getType(value) == EnumToken.LengthTokenType && arena.getNumericValue(value) == 30 && arena.getUnit(value) == 'px') ?? {};
Parameters
node: numbernode id
matcher: AstValueMatchercalled with the arena and the token id
Returns { node: number; value: number } | null
find Child
findChild(id: number, predicate: (id: number) => boolean): number | null
Parameters
id: numberpredicate: (id: number) => boolean
Returns number | null
find Last
findLast(node: number, matcher: AstNodeMatcher): number | null
Search the ast subtree in reverse order and return the first match (the last node in document order)
Parameters
node: numbernode id
matcher: AstNodeMatchercalled with the arena and the node id
Returns number | null
find Token
findToken(
id: number,
predicate: (arena: this, id: number) => boolean,
): number | null
find a token in the token list
Parameters
id: numberpredicate: (arena: this, id: number) => booleancalled with the arena and the token id
Returns number | null
find Value
findValue(node: number, matcher: AstValueMatcher): number | null
Search a token and its descendants, or the value tokens of a node and their descendants, and return the first match
Parameters
node: numbernode or token id
matcher: AstValueMatchercalled with the arena and the token id
Returns number | null
the token id or null
from Object
fromObject(node: AstArenaNode | PlainAstNode | PlainToken): number
Import an object: an AstArenaNode or a plain object (PlainAstNode, PlainToken).
- importing a view of this arena is a noop: its node id is returned, the node is not copied,
- a view of another arena is copied with its descendants (see import),
- a plain object is allocated in the arena.
chi,val,l,r, ... are created recursively, they can be node ids, views or plain objects.
Parameters
node: AstArenaNode | PlainAstNode | PlainToken
Returns number
the node id
get Capacity
getCapacity(): number
number of nodes the columns can hold before the arena grows. see getLastId for the last allocated id
Returns number
get Child At
getChildAt(id: number, index: number): number | null
Parameters
id: numberindex: number
Returns number | null
get Color Type
getColorType(id: number): number
Parameters
id: number
Returns number
get Errors
getErrors(id: number): ErrorDescription[] | null
Parameters
id: number
Returns ErrorDescription[] | null
get First Child
getFirstChild(id: number): number
first child of a node. 0 when the node has no children
Parameters
id: number
Returns number
get First Token
getFirstToken(id: number): number
first token of the token list of a node or of a token (declaration value, selector / prelude tokens, function arguments). 0 when the list is empty
Parameters
id: number
Returns number
get Flags
getFlags(id: number): number
Parameters
id: number
Returns number
get Fraction
getFraction(id: number): number
fraction token of a numeric token
Parameters
id: number
Returns number
get Last Child
getLastChild(id: number): number
Parameters
id: number
Returns number
get Last Id
getLastId(): number
last allocated node id. the ids of the arena are in the range 1 ... getLastId(), the detached nodes included
Returns number
get Last Token
getLastToken(id: number): number
last token of the token list of a node or of a token. 0 when the list is empty
Parameters
id: number
Returns number
get Left
getLeft(id: number): number[] | null
Parameters
id: number
Returns number[] | null
get Location
getLocation(id: number): SourceLocation | null
get Name
getName(id: number): string
Parameters
id: number
Returns string
get Next Sibling
getNextSibling(id: number): number
next sibling of a node or of a token. 0 for the last node / token of the list
Parameters
id: number
Returns number
get Numeric Value
getNumericValue(id: number): number
Parameters
id: number
Returns number
get Op
getOp(id: number): number
Parameters
id: number
Returns number
get Op2
getOp2(id: number): number
Parameters
id: number
Returns number
get Parent
getParent(id: number): number
Parameters
id: number
Returns number
get Previous Sibling
getPreviousSibling(id: number): number
previous sibling of a node or of a token. 0 for the first node / token of the list
Parameters
id: number
Returns number
get Right
getRight(id: number): number[] | null
Parameters
id: number
Returns number[] | null
get Selector
getSelector(id: number): string
rule selector
Parameters
id: number
Returns string
get Source
getSource(id: number): number
source id of the node location
Parameters
id: number
Returns number
get Source Id
getSourceId(id: number): number
Parameters
id: number
Returns number
get Span End
getSpanEnd(id: number): number
Parameters
id: number
Returns number
get Span Start
getSpanStart(id: number): number
Parameters
id: number
Returns number
get State
getState(id: number): EnumAstNodeStatus
get String Count
getStringCount(): number
number of interned strings
Returns number
get Token At
getTokenAt(id: number, index: number): number | null
token at the given position of the token list
Parameters
id: numberindex: number
Returns number | null
get Type
get Unit
getUnit(id: number): string
Parameters
id: number
Returns string
get Value
getValue(id: number): string
Parameters
id: number
Returns string
get Value Owner
getValueOwner(id: number): number
node that owns a value token: the declaration, the rule or the at-rule. 0 when the token is detached
Parameters
id: number
Returns number
get Value Parent
getValueParent(id: number): number
parent of a value token: the node or the token that owns the token list, or the structured token that owns the field (the field list token is skipped). 0 when the token is detached
Parameters
id: number
Returns number
has Children
hasChildren(id: number): boolean
true if the node has a block (at-rules) or a children list
Parameters
id: number
Returns boolean
has Field
hasField(id: number, field: TokenField): boolean
has Flags
hasFlags(id: number, flag: number): boolean
Parameters
id: numberflag: number
Returns boolean
has Fraction
hasFraction(id: number): boolean
true if the numeric token value is a fraction
Parameters
id: number
Returns boolean
has Location
hasLocation(id: number): boolean
true if the node has a source location
Parameters
id: number
Returns boolean
import
Protectedimport Properties
importProperties(
properties: ArenaProperties,
transferables: ArenaTransferables,
): void
initialize the arena from exported properties and column buffers
Parameters
properties: ArenaPropertiestransferables: ArenaTransferables
Returns void
index Of
indexOf(id: number): number
index of a child in its parent's children (or tokens) list
Parameters
id: number
Returns number
insert After
insertAfter(reference: number, ...nodes: number[]): void
insert nodes after a child
Parameters
reference: number…nodes: number[]
Returns void
insert Before
insertBefore(reference: number, ...nodes: number[]): void
insert nodes before a child
Parameters
reference: number…nodes: number[]
Returns void
intern String
internString(str: string): number
Interns a string and returns its unique ID. If the string has already been interned, it returns the existing ID.
Parameters
str: string
Returns number
is Invalid
isInvalid(id: number): boolean
true if the node is invalid
Parameters
id: number
Returns boolean
is Marked
isMarked(id: number): boolean
is Numeric
isNumeric(id: number): boolean
true if the token is a numeric token (number, dimension, percentage, ...)
Parameters
id: number
Returns boolean
mark
move Children
moveChildren(from: number, to: number, before?: number): void
move the children of a node into another node, in order
Parameters
from: numberto: numberbefore: number = 0the children are inserted before this child of
to. they are appended when 0
Returns void
Protectednode From Object
nodeFromObject(node: PlainAstNode): number
numerator
numerator(id: number): number
numerator of a fraction token
Parameters
id: number
Returns number
prepend Children
prependChildren(id: number, ...nodes: number[]): void
prepend children
Parameters
id: number…nodes: number[]
Returns void
prepend Tokens
prependTokens(id: number, ...tokens: number[]): void
prepend tokens to the token list
Parameters
id: number…tokens: number[]
Returns void
recycle
recycle(id: number): void
recycle a detached leaf node (no parent, no children, no tokens) that is no longer referenced: its id is reused by the next allocation. the record is zeroed, so a stale reference reads an empty node
Parameters
id: number
Returns void
release
release(id?: number, deep?: boolean): void
release nodes: detach them and drop their data (interned strings, errors). node ids are never reused: the memory is reclaimed by trim
Parameters
Optionalid: numberthe node to release. every marked node (and its descendants) is released when omitted
deep: boolean = falserelease the children and the tokens too
Returns void
replace Child
replaceChild(id: number, ...nodes: number[]): void
replace a child with other nodes. the node itself may be part of the replacement
Parameters
id: number…nodes: number[]
Returns void
replace Compound
replaceCompound(input: string, replace: string): string
Internal
replace the nesting selector '&' of a selector
Parameters
input: stringreplace: string
Returns string
Protectedreplace Compound Literal
replaceCompoundLiteral(selector: string, replace: string): string
Parameters
selector: stringreplace: string
Returns string
replace Token
replaceToken(id: number, ...tokens: number[]): void
replace a token by other tokens in its parent token list
Parameters
id: number…tokens: number[]
Returns void
reset Token
resize
resize(newSize: number): void
Parameters
newSize: number
Returns void
resolve String
resolveString(id: number): string
Parameters
id: number
Returns string
set
set(id: number, type: EnumToken): void
set node data for a given id. The first argument is the id, the second is the type, the third is the string value, the fourth is the numeric value, and the fifth is the unit.
Parameters
id: numbertype: EnumToken
Returns void
set(id: number, type: EnumToken, stringValue: number): void
set node data for a given id. The first argument is the id, the second is the type, the third is the string value, the fourth is the numeric value, and the fifth is the unit.
Parameters
id: numbertype: EnumTokenstringValue: number
Returns void
set(
id: number,
type: EnumToken,
stringValue: number,
numericValue: number,
): void
set node data for a given id. The first argument is the id, the second is the type, the third is the string value, and the fourth is the numeric value.
Parameters
id: numbertype: EnumTokenstringValue: numbernumericValue: number
Returns void
set(
id: number,
type: EnumToken,
stringValue: number,
numericValue: number,
unit: number,
): void
set node data for a given id. The first argument is the id, the second is the type, the third is the string value, the fourth is the numeric value, and the fifth is the unit.
Parameters
id: numbertype: EnumTokenstringValue: numbernumericValue: numberunit: number
Returns void
set Child At
setChildAt(id: number, index: number, child: number): void
replace the child at the given index. the node is appended when the index is out of range
Parameters
id: numberindex: numberchild: number
Returns void
set Child List
setChildList(id: number, children: number[]): void
replace the children. same as setChildren with an array
Parameters
id: numberchildren: number[]
Returns void
set Children
setChildren(id: number, ...children: number[]): void
Parameters
id: number…children: number[]
Returns void
set Color Type
setColorType(id: number, colorType: number): void
Parameters
id: numbercolorType: number
Returns void
set Errors
setErrors(id: number, errors: ErrorDescription[] | null): void
Parameters
id: numbererrors: ErrorDescription[] | null
Returns void
set Field
setField(id: number, field: TokenField, ...tokens: number[]): void
set the tokens of a structured token field
Parameters
id: numberfield: TokenField…tokens: number[]
Returns void
set First Child
setFirstChild(id: number, firstChildId: number): void
replace the first child
Parameters
id: numberfirstChildId: number
Returns void
set First Token
setFirstToken(id: number, firstTokenId: number): void
replace the first token
Parameters
id: numberfirstTokenId: number
Returns void
set Flags
setFlags(id: number, flags: number): void
Parameters
id: numberflags: number
Returns void
set Fraction
setFraction(id: number, fraction: number | null): void
set the fraction value of a numeric token. the numeric value is set to the fraction value
Parameters
id: numberfraction: number | nullfraction token id or null
Returns void
set Last Child
setLastChild(id: number, lastChildId: number): void
replace the last child
Parameters
id: numberlastChildId: number
Returns void
set Left
setLeft(id: number, ...children: number[]): void
Parameters
id: number…children: number[]
Returns void
set Location
setLocation(
id: number,
srcId: number | null | undefined,
sta: number | null | undefined,
end: number | null | undefined,
): void
set the source location
Parameters
id: numbersrcId: number | null | undefinedsource id
sta: number | null | undefinedstart offset
end: number | null | undefinedend offset
Returns void
set Name
setName(id: number, nameId: number): void
Parameters
id: numbernameId: number
Returns void
set Name String
setNameString(id: number, nam: string): void
set the at-rule / declaration name
Parameters
id: numbernam: string
Returns void
set Next Sibling
setNextSibling(id: number, nextSiblingId: number): void
insert a node after another one
Parameters
id: numbernextSiblingId: number
Returns void
set Numeric Value
setNumericValue(id: number, numericValue: number): void
Parameters
id: numbernumericValue: number
Returns void
set Op
setOp(id: number, opId: number): void
Parameters
id: numberopId: number
Returns void
set Op2
setOp2(id: number, op2Id: number): void
Parameters
id: numberop2Id: number
Returns void
set Parent
setParent(id: number, parentId: number): void
Parameters
id: numberparentId: number
Returns void
set Previous Sibling
setPreviousSibling(id: number, previousSiblingId: number): void
insert a node before another one
Parameters
id: numberpreviousSiblingId: number
Returns void
set Right
setRight(id: number, rightId: null): void
Parameters
id: numberrightId: null
Returns void
setRight(id: number, ...rightId: number[]): void
Parameters
id: number…rightId: number[]
Returns void
set Selector
setSelector(id: number, sel: string): void
set the rule selector
Parameters
id: numbersel: string
Returns void
set Span
setSpan(id: number, sourceId: number, start: number, end: number): void
Parameters
id: numbersourceId: numberstart: numberend: number
Returns void
set Spand Start
setSpandStart(id: number, start: number): void
Parameters
id: numberstart: number
Returns void
set Span End
setSpanEnd(id: number, end: number): void
Parameters
id: numberend: number
Returns void
set State
setState(id: number, state: EnumAstNodeStatus | null | undefined): void
set the validation state bits
Parameters
id: numberstate: EnumAstNodeStatus | null | undefined
Returns void
set Str
setStr(id: number, value: string): void
set the string value of a token (val)
Parameters
id: numbervalue: string
Returns void
set Token List
setTokenList(id: number, tokens: number[]): void
replace the token list. same as setTokens with an array
Parameters
id: numbertokens: number[]
Returns void
set Token Location
setTokenLocation(
id: number,
sourceIndex: number,
sta: number,
end: number,
): void
set the location of a token from the tokenizer values. the source index is the index of the source id in the sources table
Parameters
id: numbersourceIndex: numbersta: numberend: number
Returns void
set Tokens
setTokens(id: number, ...children: number[]): void
Parameters
id: number…children: number[]
Returns void
set Type
set Unit
setUnit(id: number, unit: number): void
Parameters
id: numberunit: number
Returns void
set Unit String
setUnitString(id: number, unit: string | null): void
set the unit of a token
Parameters
id: numberunit: string | null
Returns void
set Value
setValue(id: number, valueId: number): void
Parameters
id: numbervalueId: number
Returns void
set Value String
setValueString(id: number, val: string): void
set the at-rule prelude / comment string value
Parameters
id: numberval: string
Returns void
siblings
siblings(id: number, filter?: (arena: this, id: number) => boolean): number[]
the children of the parent of a node, the node included
Parameters
id: numberOptionalfilter: (arena: this, id: number) => booleancalled with the arena and the node id
Returns number[]
source Index
sourceIndex(srcId: number): number
index of a source id in the sources table
Parameters
srcId: number
Returns number
span Location
spanLocation(id: number, start: number, end: number): void
set the location from the start of a node to the end of another one
Parameters
id: numberstart: numberend: number
Returns void
starts With
startsWith(node: number, key: "val" | "nam", string: string): boolean
Parameters
node: numberkey: "val" | "nam"string: string
Returns boolean
str
str(id: number): string
string value of a token (val)
Parameters
id: number
Returns string
sub Tokens
subTokens(id: number): number[]
direct value tokens of a node or a token: the token list, then the tokens of the structured fields and the child tokens (fractions, unary expressions)
Parameters
id: number
Returns number[]
take
take(token: number): number
get a token that can be attached to a new parent: the token itself when it is detached, a deep clone otherwise. a token can only belong to one token list
Parameters
token: number
Returns number
token Count
tokenCount(id: number): number
number of tokens in the token list
Parameters
id: number
Returns number
Protectedtoken From Object
tokenFromObject(token: PlainToken): number
tokens
tokens(id: number, filter?: (arena: this, id: number) => boolean): number[]
token ids of the token list: the declaration values, the selector / prelude tokens, the function arguments
Parameters
id: numberOptionalfilter: (arena: this, id: number) => booleancalled with the arena and the token id
Returns number[]
token To Object
tokenToObject(id: number): PlainToken
to Object
toObject(id: number): AstArenaNode
Object view of a node or a token: an AstArenaNode. The view does not copy the node: its properties read and write the arena. Importing the view in this arena (fromObject, visitor results, setters of the views) is a noop
function visitor(arena: AstArena, id: number) {
const node = arena.toObject(id);
console.log(node.typ, node.nam, node.val);
}
Parameters
id: numbernode or token id
Returns AstArenaNode
to Plain Object
toPlainObject(id: number): PlainAstNode | PlainToken
export a node or a token as a plain object (deep copy). JSON.stringify() of an AstArenaNode returns
the plain object
Parameters
id: number
Returns PlainAstNode | PlainToken
trim
trim(errors?: ErrorDescription[] | null): Uint32Array
reclaim the memory: release the marked nodes, then drop the nodes that are not reachable from the root and renumber the remaining ones, see compact. the ids obtained before the call are no longer valid
Parameters
Optionalerrors: ErrorDescription[] | nullerror descriptions whose
nodeis remapped
Returns Uint32Array
mapping of the old ids to the new ids (0 when the node was dropped)
type Of
visit Values
visitValues(
tokens: number[],
visitor: (arena: this, token: number) => void,
): void
Internal
call the visitor for the tokens and their children, in the order of walkValues (the children of a token are read after the visitor returns). no iterator or stack is created: use it when the visitor is not a closure
Parameters
tokens: number[]visitor: (arena: this, token: number) => void
Returns void
walk
walk(
node: number,
filter?: WalkerFilter | WalkerOptions | null,
reverse?: boolean,
): IterableIterator<number>
Walk the ast nodes: the node and its descendants, in document order. The iterator returns node ids (and value
tokens when attributes is set). The children of a node are read when the next node is requested: the current
node can be modified or detached by the caller.
import {EnumToken, transform, WalkerOptionEnum} from '@tbela99/css-parser';
const result = await transform(css);
const arena = result.arena;
for (const node of arena.walk(result.ast)) {
console.log(EnumToken[arena.getType(node)], arena.getParent(node));
}
// the filter controls the walk, see WalkerOptionEnum
function filter(arena: AstArena, node: number) {
if (arena.getType(node) == EnumToken.RuleNodeType && arena.getSelector(node).includes('html')) {
// skip the children of the current node
return WalkerOptionEnum.IgnoreChildren;
}
}
for (const node of arena.walk(result.ast, filter)) {
console.log(EnumToken[arena.getType(node)]);
}
Parameters
node: numberinitial node id (or value token)
Optionalfilter: WalkerFilter | WalkerOptions | nullfilter function or walker options
Optionalreverse: booleanwalk in reverse order
Returns IterableIterator<number>
walk Values
walkValues(
tokens: number | number[],
filter?: WalkerValueFilter | WalkerValueOptions | null,
reverse?: boolean,
): IterableIterator<number>
Walk value tokens and their descendants (function arguments, structured token fields, ...), in document order. The iterator returns token ids. The children of a token are read when the next token is requested: the current token can be modified or replaced by the caller.
import {EnumToken, transform} from '@tbela99/css-parser';
const css = `
body { color: color(from var(--base-color) display-p3 r calc(g + 0.24) calc(b + 0.15)); }
`;
const result = await transform(css);
const arena = result.arena;
const declaration = arena.getFirstChild(arena.getFirstChild(result.ast));
// walk the value tokens of the declaration in reverse order
for (const value of arena.walkValues(declaration, null, true)) {
console.error([EnumToken[arena.getType(value)], arena.getValue(value)]);
}
Parameters
tokens: number | number[]token ids, or a node / token id: its value tokens are walked
Optionalfilter: WalkerValueFilter | WalkerValueOptions | nullfilter function, called with the arena, the token id and the event, or filter options
Optionalreverse: booleanwalk in reverse order
Returns IterableIterator<number>
Staticfrom Transferable Arena Objects
fromTransferableArenaObjects<T extends Arena>(
this: new (size?: number) => T,
properties: ArenaProperties,
transferables: ArenaTransferables,
): T
Create an arena from the objects produced by Arena.toTransferableArenaObject. The column buffers are used as is (zero copy): the typed arrays are views on the given buffers.
Type Parameters
- T extends Arena
Parameters
this: new (size?: number) => Tproperties: ArenaPropertiesarena properties
transferables: ArenaTransferablescolumn buffers
Returns T
an Arena or an AstArena depending on the class the method is called on
Staticto Transferable Arena Object
toTransferableArenaObject(arena: Arena): [ArenaProperties, ArenaTransferables]
Export the arena as a structured-cloneable object and the list of its column buffers, to send an arena to a worker (or back to the main thread) without copying the node data.
The properties (strings, errors, ...) are cloned by postMessage(), the column buffers are moved when they are
passed as the transfer list: the source arena must not be used afterwards (its columns are detached).
The buffers are copied instead when the transfer list is omitted.
// main thread
const [properties, transferables] = AstArena.toTransferableArenaObject(result.arena);
worker.postMessage({ ast: result.ast, properties, transferables }, transferables);
// worker
const { ast, properties, transferables } = event.data;
const arena = AstArena.fromTransferableArenaObjects(properties, transferables);
Parameters
arena: Arena
Returns [ArenaProperties, ArenaTransferables]
the arena properties and the column buffers, see ArenaProperties and ArenaTransferables
Properties
color Type
color type. previously use as (node as ColorToken).kin
current
last allocated node id. the next node is allocated with the id current + 1 (unless a recycled id is available). 0 is never allocated: it means "no node"
data Types
node EnumToken type array
errors
error cache
first Child
first child node id array
first Token
first token node id array
flags
node flags
Protectedfree List
head of the list of recycled node ids. the list is linked through the nextSibling column, see recycle
last Child
last child node id array
last Token
last token node id array
name
node name string interner id array. used to store (node as AstRule | AstDeclaration | AstKeyframesAtRule).nam and (node as AstRule | AstKeyframesRule).sel
next Sibling
next sibling node id array
numeric Value
node numeric value array. previously used as (node as NumberToken | DimensionToken).val
optimized
optimized selector (minification cache). sparse: only rules have an entry
parents
parent node id array
previous Sibling
previous sibling node id array
raw
raw selector (minification cache). sparse: only rules have an entry
Readonlyroot
root node
sources
source ids. spans store the index in this table (8 bits)
spans
token spans. 8 bits for source type. 28 bits for start position, 28 bits for end position. This allows us to store the start and end positions of tokens in a single 64-bit integer, which is more efficient than storing them separately.
Protectedspans32
32 bits view of the spans: the low word holds the end position and the 4 low bits of the start position, the high word holds the 24 high bits of the start position and the source
string Ids
string interner identifiers
strings
string interner values
string Value
node string value index array.
unit
node unit string interner id array. previously used as (node as DimensionToken).unit
Css ast arena: ast nodes and value tokens.
The node data is read and written with the methods of the arena (getType, getName, getFirstChild, tokens, ...). See Arena and the Arena Memory guide for the memory usage.