Queries are not preformed as soon as they are created, but they are partially prepared. While the query runs, additional parts to the query will be included in as needed.
To prepare a query for a JSX node, import and use prepare
import {prepare} from "@virtualstate/kdl";
const node = (
<main>
<h1>@virtualstate/focus</h1>
<blockquote>Version: <span>1.0.0</span></blockquote>
</main>
);
The first parameter, is the JSX node you want to query The second parameter, is a string containing KDL Query Language
const result = prepare(
node,
`main blockquote > span`
);
The result is an async object that can be resolved in many ways
First, if used as a promise, will result in an array of matching JSX nodes
const [span] = await result
console.log(span); // Is the node for <span>1.0.0</span>
If used as an async iterable, then snapshots of results can be accessed, allowing for earlier processing of earlier found JSX nodes
for await (const [span] of result) {
if (!span) continue;
// We have at least one span!
console.log(span) // Is the node for <span>1.0.0</span>
}
If used as an iterable, and destructuring is used, the individual destructured values will be async objects too, which can be used as a promise or async iterable
const [firstSpan] = result;
const span = await firstSpan;
console.log(span) // Is the node for <span>1.0.0</span>
const [firstSpan] = result;
for await (const span of firstSpan) {
console.log(span) // Is the node for <span>1.0.0</span>
}
The async object returned from prepare supports many array like operations,
like .at
, .filter
, .map
, .group
, .flatMap
, and more
These operations are performed on the individual snapshots yielded across the lifecycle of the query
The map operator is also available, which can be used to directly return information about the node found
const [value] = await prepare(
node,
`main blockquote > span => val()`
);
console.log(value); // Logs the content of the span "1.0.0"