Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dashboard: Migration - Dashboard Settings Variables (List, Duplicate, Delete) #78917

Merged
merged 28 commits into from
Dec 14, 2023
Merged
Show file tree
Hide file tree
Changes from 15 commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
bdc6235
First attempt: List variables using SceneVariablesSet and also variab…
axelavargas Nov 30, 2023
bbf200b
Merge remote-tracking branch 'origin' into axelav/settings-variables
axelavargas Dec 6, 2023
16016d6
Merge remote-tracking branch 'origin' into axelav/settings-variables
axelavargas Dec 6, 2023
129527d
List variables and create Scaffold for Change order, duplicate and de…
axelavargas Dec 6, 2023
3fe0edf
Refactor: use right methods to get variables and implement onDelete
axelavargas Dec 7, 2023
cb1ce5a
Implement duplicate variables and clean up code
axelavargas Dec 8, 2023
8d92f02
Modify duplicated function to keep the same format as core grafana
axelavargas Dec 8, 2023
474e46b
Fix betterer and linter issues
axelavargas Dec 8, 2023
640e818
Add confirmation delete modal
axelavargas Dec 8, 2023
87c2297
Fix linter
axelavargas Dec 8, 2023
9e19e38
More linter...
axelavargas Dec 8, 2023
33d3040
Fix React removal
axelavargas Dec 8, 2023
55d1822
Merge remote-tracking branch 'origin' into axelav/settings-variables
axelavargas Dec 8, 2023
8b42494
Attempt to fix scenes types
axelavargas Dec 8, 2023
0be281c
Fix typescript error, pass variableScene to the component
axelavargas Dec 8, 2023
5db6c48
Disable create button and empty variable set
axelavargas Dec 12, 2023
aca9c65
Move methods to VariableEditView model
axelavargas Dec 12, 2023
f99ea12
Add unit test
axelavargas Dec 13, 2023
3052d19
Merge remote-tracking branch 'origin' into axelav/settings-variables
axelavargas Dec 13, 2023
db3e7a9
Fix linter
axelavargas Dec 13, 2023
db8ed9d
Use getDashboardSceneFor method in all DashboardSettings
axelavargas Dec 13, 2023
dfea723
Remove dashboardRef param from Dashboard Scene Url Sync
axelavargas Dec 13, 2023
bcd2a52
Add missing changes
axelavargas Dec 13, 2023
dccd570
Apply suggestions from code review
axelavargas Dec 13, 2023
3d835c2
Fix references of PR suggestion
axelavargas Dec 13, 2023
811347a
Add unit test for default variable set
axelavargas Dec 13, 2023
0c4f50d
Remove unnecesary function
axelavargas Dec 13, 2023
7edc34a
Remove unnecesary get _dashboard function
axelavargas Dec 14, 2023
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
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import React from 'react';

import { PageLayoutType } from '@grafana/data';
import { SceneComponentProps, SceneObjectBase } from '@grafana/scenes';
import { SceneComponentProps, SceneObjectBase, sceneGraph } from '@grafana/scenes';
import { Page } from 'app/core/components/Page/Page';

import { NavToolbarActions } from '../scene/NavToolbarActions';
import { getDashboardSceneFor } from '../utils/utils';

import { DashboardEditView, DashboardEditViewState, useDashboardEditPageNav } from './utils';

import { VariableEditorList } from './variables/VariableEditorList';
export interface VariablesEditViewState extends DashboardEditViewState {}

export class VariablesEditView extends SceneObjectBase<VariablesEditViewState> implements DashboardEditView {
Expand All @@ -19,11 +19,93 @@ export class VariablesEditView extends SceneObjectBase<VariablesEditViewState> i
static Component = ({ model }: SceneComponentProps<VariablesEditView>) => {
const dashboard = getDashboardSceneFor(model);
const { navModel, pageNav } = useDashboardEditPageNav(dashboard, model.getUrlKey());
// get variables from dashboard state
const variablesObject = sceneGraph.getVariables(dashboard);
const variables = variablesObject.useState().variables;

const getVariableIndex = (identifier: string) => {
return variables.findIndex((variable) => variable.state.name === identifier);
};

const onDelete = (identifier: string) => {
// Find the index of the variable to be deleted
const variableIndex = getVariableIndex(identifier);
if (variableIndex === -1) {
// Handle the case where the variable is not found
console.error('Variable not found');
return;
}

// Create a new array excluding the variable to be deleted
const updatedVariables = [...variables.slice(0, variableIndex), ...variables.slice(variableIndex + 1)];

// Update the state or the variables array
variablesObject.setState({ variables: updatedVariables });
};

const onDuplicated = (identifier: string) => {
const variableIndex = getVariableIndex(identifier);
axelavargas marked this conversation as resolved.
Show resolved Hide resolved
if (variableIndex === -1) {
console.error('Variable not found');
return;
}

const originalVariable = variables[variableIndex];
let copyNumber = 0;
let newName = `copy_of_${originalVariable.state.name}`;

// Check if the name is unique, if not, increment the copy number
while (variables.some((v) => v.state.name === newName)) {
copyNumber++;
newName = `copy_of_${originalVariable.state.name}_${copyNumber}`;
}

//clone the original variable

const newVariable = originalVariable.clone(originalVariable.state);
// update state name of the new variable
newVariable.setState({ name: newName });

const updatedVariables = [
...variables.slice(0, variableIndex + 1),
newVariable,
...variables.slice(variableIndex + 1),
];

variablesObject.setState({ variables: updatedVariables });
};

const onOrderChanged = (fromIndex: number, toIndex: number) => {
if (!variables) {
return;
}
// check the index are within the variables array
if (fromIndex < 0 || fromIndex >= variables.length || toIndex < 0 || toIndex >= variables.length) {
console.error('Invalid index');
return;
}
const updatedVariables = [...variables];
// Remove the variable from the array
const movedItem = updatedVariables.splice(fromIndex, 1);
updatedVariables.splice(toIndex, 0, movedItem[0]);
variablesObject.setState({ variables: updatedVariables });
};

const onEdit = (identifier: string) => {
return 'not implemented';
};

return (
<Page navModel={navModel} pageNav={pageNav} layout={PageLayoutType.Standard}>
<NavToolbarActions dashboard={dashboard} />
<div>variables todo</div>
<VariableEditorList
variables={variables}
onDelete={onDelete}
onDuplicate={onDuplicated}
onChangeOrder={onOrderChanged}
onAdd={() => {}}
onEdit={onEdit}
/>
</Page>
);
};
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
import { css } from '@emotion/css';
import React, { ReactElement } from 'react';
import { DragDropContext, Droppable, DropResult } from 'react-beautiful-dnd';

import { selectors } from '@grafana/e2e-selectors';
import { reportInteraction } from '@grafana/runtime';
import { SceneVariable, SceneVariableState } from '@grafana/scenes';
import { useStyles2, Stack } from '@grafana/ui';
import EmptyListCTA from 'app/core/components/EmptyListCTA/EmptyListCTA';

import { VariableEditorListRow } from './VariableEditorListRow';

export interface Props {
variables: Array<SceneVariable<SceneVariableState>>;
onAdd: () => void;
onChangeOrder: (fromIndex: number, toIndex: number) => void;
onDuplicate: (identifier: string) => void;
onDelete: (identifier: string) => void;
onEdit: (identifier: string) => void;
}

export function VariableEditorList({
variables,
onChangeOrder,
onDelete,
onDuplicate,
onAdd,
onEdit,
}: Props): ReactElement {
const styles = useStyles2(getStyles);
const onDragEnd = (result: DropResult) => {
if (!result.destination || !result.source) {
return;
}
reportInteraction('Variable drag and drop');
onChangeOrder(result.source.index, result.destination.index);
};

return (
<div>
<div>
{variables.length === 0 && <EmptyVariablesList onAdd={onAdd} />}

{variables && (
<Stack direction="column" gap={4}>
<div className={styles.tableContainer}>
<table
className="filter-table filter-table--hover"
data-testid={selectors.pages.Dashboard.Settings.Variables.List.table}
role="grid"
>
<thead>
<tr>
<th>Variable</th>
<th>Definition</th>
<th colSpan={5} />
</tr>
</thead>
<DragDropContext onDragEnd={onDragEnd}>
<Droppable droppableId="variables-list" direction="vertical">
{(provided) => (
<tbody ref={provided.innerRef} {...provided.droppableProps}>
{variables.map((variableScene, index) => {
const variableState = variableScene.state;
return (
<VariableEditorListRow
index={index}
key={`${variableState.name}-${index}`}
variable={variableScene}
onDelete={onDelete}
onDuplicate={onDuplicate}
onEdit={onEdit}
/>
);
})}
{provided.placeholder}
</tbody>
)}
</Droppable>
</DragDropContext>
</table>
</div>
</Stack>
)}
</div>
</div>
);
}

function EmptyVariablesList({ onAdd }: { onAdd: () => void }): ReactElement {
return (
<div>
<EmptyListCTA
title="There are no variables yet"
buttonIcon="calculator-alt"
buttonTitle="Add variable"
infoBox={{
__html: ` <p>
Variables enable more interactive and dynamic dashboards. Instead of hard-coding things like server
or sensor names in your metric queries you can use variables in their place. Variables are shown as
list boxes at the top of the dashboard. These drop-down lists make it easy to change the data
being displayed in your dashboard. Check out the
<a class="external-link" href="https://grafana.com/docs/grafana/latest/variables/" target="_blank">
Templates and variables documentation
</a>
for more information.
</p>`,
}}
Comment on lines +98 to +109
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Probably, we should add internationalization here. WDYT?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think is a good idea, but I would refrain from doing it in the scope of the migration 😄.

infoBoxTitle="What do variables do?"
onClick={(event) => {
event.preventDefault();
onAdd();
}}
/>
</div>
);
}

const getStyles = () => ({
tableContainer: css({
overflow: 'scroll',
width: '100%',
}),
});
Loading
Loading