Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
aos
GitHub Repository: aos/grafana-agent
Path: blob/main/web/ui/src/utils/partition.ts
5307 views
1
import { PartitionedBody } from '../features/component/types';
2
import { AttrStmt, Body, StmtType } from '../features/river-js/types';
3
4
/**
5
* partitionBody groups a body by attributes and inner blocks, assigning unique
6
* keys for each.
7
*/
8
export function partitionBody(body: Body, rootKey: string): PartitionedBody {
9
function impl(body: Body, displayName: string[], keyPath: string[]): PartitionedBody {
10
const attrs: AttrStmt[] = [];
11
const inner: PartitionedBody[] = [];
12
13
const blocksWithName: Record<string, number> = {};
14
15
body.forEach((stmt) => {
16
switch (stmt.type) {
17
case StmtType.ATTR:
18
attrs.push(stmt);
19
break;
20
case StmtType.BLOCK:
21
const blockName = stmt.label ? `${stmt.name}.${stmt.label}` : stmt.name;
22
23
// Keep track of how many blocks have this name so they can be given unique IDs.
24
if (blocksWithName[blockName] === undefined) {
25
blocksWithName[blockName] = 0;
26
}
27
const number = blocksWithName[blockName];
28
blocksWithName[blockName]++;
29
30
const key = blockName + `_${number}`;
31
32
inner.push(impl(stmt.body, displayName.concat([blockName]), keyPath.concat([key])));
33
break;
34
}
35
});
36
37
return {
38
displayName: displayName,
39
key: keyPath,
40
attrs: attrs,
41
inner: inner,
42
};
43
}
44
45
return impl(body, [rootKey], [rootKey]);
46
}
47
48