grafana/public/app/features/scenes/components/ScenePanelRepeater.tsx
Torkel Ödegaard 8d92417a16
Scenes: Improve typing of scene state to avoid type guards and casting (#52422)
* Trying to get rid of type guard but failing

* Improve typing of scene object state

* Fixed wrongly renamed event

* Tweaks
2022-07-19 17:46:49 +02:00

61 lines
1.5 KiB
TypeScript

import React from 'react';
import { LoadingState, PanelData } from '@grafana/data';
import { SceneDataNode } from '../core/SceneDataNode';
import { SceneObjectBase } from '../core/SceneObjectBase';
import {
SceneComponentProps,
SceneObject,
SceneObjectStatePlain,
SceneLayoutState,
SceneLayoutChild,
} from '../core/types';
interface RepeatOptions extends SceneObjectStatePlain {
layout: SceneObject<SceneLayoutState>;
}
export class ScenePanelRepeater extends SceneObjectBase<RepeatOptions> {
activate(): void {
super.activate();
this.subs.add(
this.getData().subscribe({
next: (data) => {
if (data.data?.state === LoadingState.Done) {
this.performRepeat(data.data);
}
},
})
);
}
performRepeat(data: PanelData) {
// assume parent is a layout
const firstChild = this.state.layout.state.children[0]!;
const newChildren: SceneLayoutChild[] = [];
for (const series of data.series) {
const clone = firstChild.clone({
key: `${newChildren.length}`,
$data: new SceneDataNode({
data: {
...data,
series: [series],
},
}),
});
newChildren.push(clone);
}
this.state.layout.setState({ children: newChildren });
}
static Component = ({ model, isEditing }: SceneComponentProps<ScenePanelRepeater>) => {
const { layout } = model.useState();
return <layout.Component model={layout} isEditing={isEditing} />;
};
}