-
Notifications
You must be signed in to change notification settings - Fork 27
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
JsonVariable: New type of object variable where each value user selects has many properties (POC) #995
Draft
torkelo
wants to merge
2
commits into
main
Choose a base branch
from
json-variable
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
JsonVariable: New type of object variable where each value user selects has many properties (POC) #995
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,74 @@ | ||
import { | ||
EmbeddedScene, | ||
JsonVariable, | ||
JsonVariableOptionProviders, | ||
PanelBuilders, | ||
SceneAppPage, | ||
SceneAppPageState, | ||
SceneCSSGridLayout, | ||
SceneVariableSet, | ||
} from '@grafana/scenes'; | ||
import { getEmbeddedSceneDefaults } from './utils'; | ||
|
||
export function getJsonVariableDemo(defaults: SceneAppPageState) { | ||
return new SceneAppPage({ | ||
...defaults, | ||
subTitle: 'Example of a JSON variable', | ||
getScene: () => { | ||
return new EmbeddedScene({ | ||
...getEmbeddedSceneDefaults(), | ||
$variables: new SceneVariableSet({ | ||
variables: [ | ||
new JsonVariable({ | ||
name: 'env', | ||
value: 'test', | ||
provider: JsonVariableOptionProviders.fromString({ | ||
json: `[ | ||
{ "id": 1, "name": "dev", "cluster": "us-dev-1", "status": "updating" }, | ||
{ "id": 2, "name": "prod", "cluster": "us-prod-2", "status": "ok" }, | ||
{ "id": 3, "name": "staging", "cluster": "us-staging-2", "status": "down" } | ||
]`, | ||
}), | ||
}), | ||
new JsonVariable({ | ||
name: 'testRun', | ||
label: 'Test run', | ||
value: 'test', | ||
provider: JsonVariableOptionProviders.fromObjectArray({ | ||
options: [ | ||
{ runId: 'CAM-01', timeTaken: '10s', startTime: 1733492238318, endTime: 1733492338318 }, | ||
{ runId: 'SSL-02', timeTaken: '2s', startTime: 1733472238318, endTime: 1733482338318 }, | ||
{ runId: 'MRA-02', timeTaken: '13s', startTime: 1733462238318, endTime: 1733472338318 }, | ||
], | ||
valueProp: 'runId', | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. so this will be the property used for default interpolation, when no path provided in the variable syntax? i.e. if i just used |
||
}), | ||
}), | ||
], | ||
}), | ||
body: new SceneCSSGridLayout({ | ||
children: [ | ||
PanelBuilders.text() | ||
.setTitle('Interpolation demos') | ||
.setOption( | ||
'content', | ||
` | ||
|
||
* env.id = \${env.id} | ||
* env.name = \${env.name} | ||
* env.status = \${env.status} | ||
|
||
|
||
* testRun.runId = \${testRun.runId} | ||
* testRun.timeTaken = \${testRun.timeTaken} | ||
* testRun.startTime = \${testRun.startTime} | ||
* testRun.endTime = \${testRun.endTime} | ||
* testRun.endTime:date = \${testRun.endTime:date} | ||
` | ||
) | ||
.build(), | ||
], | ||
}), | ||
}); | ||
}, | ||
}); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
49 changes: 49 additions & 0 deletions
49
packages/scenes/src/variables/variants/json/JsonStringOptionPrivider copy.tsx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
import { Observable } from 'rxjs'; | ||
import { JsonVariableOptionProvider, JsonVariableOption } from './JsonVariable'; | ||
|
||
export interface JsonStringOptionPrividerOptions { | ||
/** | ||
* String contauining JSON with an array of objects or a map of objects | ||
*/ | ||
json: string; | ||
/** | ||
* Defaults to name if not specified | ||
*/ | ||
valueProp?: string; | ||
} | ||
|
||
export class JsonStringOptionPrivider implements JsonVariableOptionProvider { | ||
public constructor(private options: JsonStringOptionPrividerOptions) {} | ||
|
||
public getOptions(): Observable<JsonVariableOption[]> { | ||
return new Observable((subscriber) => { | ||
try { | ||
const { json, valueProp = 'name' } = this.options; | ||
const jsonValue = JSON.parse(json); | ||
|
||
if (!Array.isArray(jsonValue)) { | ||
throw new Error('JSON must be an array'); | ||
} | ||
|
||
const resultOptions: JsonVariableOption[] = []; | ||
|
||
jsonValue.forEach((option) => { | ||
if (option[valueProp] == null) { | ||
return; | ||
} | ||
|
||
resultOptions.push({ | ||
value: option[valueProp], | ||
label: option[valueProp], | ||
obj: option, | ||
}); | ||
}); | ||
|
||
subscriber.next(resultOptions); | ||
subscriber.complete(); | ||
} catch (error) { | ||
subscriber.error(error); | ||
} | ||
}); | ||
} | ||
} |
49 changes: 49 additions & 0 deletions
49
packages/scenes/src/variables/variants/json/JsonStringOptionPrivider.tsx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
import { Observable } from 'rxjs'; | ||
import { JsonVariableOptionProvider, JsonVariableOption } from './JsonVariable'; | ||
|
||
export interface JsonStringOptionPrividerOptions { | ||
/** | ||
* String contauining JSON with an array of objects or a map of objects | ||
*/ | ||
json: string; | ||
/** | ||
* Defaults to name if not specified | ||
*/ | ||
valueProp?: string; | ||
} | ||
|
||
export class JsonStringOptionProvider implements JsonVariableOptionProvider { | ||
public constructor(private options: JsonStringOptionPrividerOptions) {} | ||
|
||
public getOptions(): Observable<JsonVariableOption[]> { | ||
return new Observable((subscriber) => { | ||
try { | ||
const { json, valueProp = 'name' } = this.options; | ||
const jsonValue = JSON.parse(json); | ||
|
||
if (!Array.isArray(jsonValue)) { | ||
throw new Error('JSON must be an array'); | ||
} | ||
|
||
const resultOptions: JsonVariableOption[] = []; | ||
|
||
jsonValue.forEach((option) => { | ||
if (option[valueProp] == null) { | ||
return; | ||
} | ||
|
||
resultOptions.push({ | ||
value: option[valueProp], | ||
label: option[valueProp], | ||
obj: option, | ||
}); | ||
}); | ||
|
||
subscriber.next(resultOptions); | ||
subscriber.complete(); | ||
} catch (error) { | ||
subscriber.error(error); | ||
} | ||
}); | ||
} | ||
} |
43 changes: 43 additions & 0 deletions
43
packages/scenes/src/variables/variants/json/JsonVariable.test.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
import { lastValueFrom } from 'rxjs'; | ||
import { JsonVariable } from './JsonVariable'; | ||
import { JsonVariableOptionProviders } from './JsonVariableOptionProviders'; | ||
|
||
describe('JsonVariable', () => { | ||
describe('fromString', () => { | ||
it('Should parse out an array of objects', async () => { | ||
const variable = new JsonVariable({ | ||
name: 'env', | ||
value: 'prod', | ||
provider: JsonVariableOptionProviders.fromString({ | ||
json: `[ | ||
{ "id": 1, "name": "dev", "cluster": "us-dev-1" } , | ||
{ "id": 2, "name": "prod", "cluster": "us-prod-2" } | ||
]`, | ||
}), | ||
}); | ||
|
||
await lastValueFrom(variable.validateAndUpdate()); | ||
|
||
expect(variable.getValue('cluster')).toBe('us-prod-2'); | ||
}); | ||
}); | ||
|
||
describe('fromObjectArray', () => { | ||
it('Should get options', async () => { | ||
const variable = new JsonVariable({ | ||
name: 'env', | ||
value: 'prod', | ||
provider: JsonVariableOptionProviders.fromObjectArray({ | ||
options: [ | ||
{ id: 1, name: 'dev', cluster: 'us-dev-1' }, | ||
{ id: 2, name: 'prod', cluster: 'us-prod-2' }, | ||
], | ||
}), | ||
}); | ||
|
||
await lastValueFrom(variable.validateAndUpdate()); | ||
|
||
expect(variable.getValue('cluster')).toBe('us-prod-2'); | ||
}); | ||
}); | ||
}); |
131 changes: 131 additions & 0 deletions
131
packages/scenes/src/variables/variants/json/JsonVariable.tsx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,131 @@ | ||
import React from 'react'; | ||
import { property } from 'lodash'; | ||
import { Observable, map, of } from 'rxjs'; | ||
import { Select } from '@grafana/ui'; | ||
import { SelectableValue } from '@grafana/data'; | ||
import { SceneObjectBase } from '../../../core/SceneObjectBase'; | ||
import { SceneComponentProps } from '../../../core/types'; | ||
import { | ||
SceneVariableState, | ||
SceneVariable, | ||
ValidateAndUpdateResult, | ||
VariableValue, | ||
SceneVariableValueChangedEvent, | ||
} from '../../types'; | ||
|
||
export interface JsonVariableState extends SceneVariableState { | ||
/** | ||
* The current value | ||
*/ | ||
value?: string; | ||
/** | ||
* O | ||
*/ | ||
options: JsonVariableOption[]; | ||
/** | ||
* The thing that generates/returns possible values / options | ||
*/ | ||
provider?: JsonVariableOptionProvider; | ||
} | ||
|
||
export interface JsonVariableOption { | ||
value: string; | ||
label: string; | ||
obj: unknown; | ||
} | ||
|
||
export interface JsonVariableOptionProvider { | ||
getOptions(): Observable<JsonVariableOption[]>; | ||
} | ||
|
||
export class JsonVariable extends SceneObjectBase<JsonVariableState> implements SceneVariable { | ||
public constructor(state: Partial<JsonVariableState>) { | ||
super({ | ||
// @ts-ignore | ||
type: 'json', | ||
options: [], | ||
...state, | ||
}); | ||
} | ||
|
||
private static fieldAccessorCache: FieldAccessorCache = {}; | ||
|
||
public validateAndUpdate(): Observable<ValidateAndUpdateResult> { | ||
if (!this.state.provider) { | ||
return of({}); | ||
} | ||
|
||
return this.state.provider.getOptions().pipe( | ||
map((options) => { | ||
this.updateValueGivenNewOptions(options); | ||
return {}; | ||
}) | ||
); | ||
} | ||
|
||
private updateValueGivenNewOptions(options: JsonVariableOption[]) { | ||
if (!this.state.value) { | ||
return; | ||
} | ||
|
||
const stateUpdate: Partial<JsonVariableState> = { options }; | ||
|
||
const found = options.find((option) => option.value === this.state.value); | ||
|
||
if (!found) { | ||
if (options.length > 0) { | ||
stateUpdate.value = options[0].value; | ||
} else { | ||
stateUpdate.value = undefined; | ||
} | ||
} | ||
|
||
this.setState(stateUpdate); | ||
} | ||
|
||
public getValueText?(fieldPath?: string): string { | ||
const current = this.state.options.find((option) => option.value === this.state.value); | ||
return current ? current.label : ''; | ||
} | ||
|
||
public getValue(fieldPath: string): VariableValue { | ||
const current = this.state.options.find((option) => option.value === this.state.value); | ||
return current ? this.getFieldAccessor(fieldPath)(current.obj) : ''; | ||
} | ||
|
||
private getFieldAccessor(fieldPath: string) { | ||
const accessor = JsonVariable.fieldAccessorCache[fieldPath]; | ||
if (accessor) { | ||
return accessor; | ||
} | ||
|
||
return (JsonVariable.fieldAccessorCache[fieldPath] = property(fieldPath)); | ||
} | ||
|
||
public _onChange = (selected: SelectableValue<string>) => { | ||
this.setState({ value: selected.value }); | ||
this.publishEvent(new SceneVariableValueChangedEvent(this), true); | ||
}; | ||
|
||
public static Component = ({ model }: SceneComponentProps<JsonVariable>) => { | ||
const { key, value, options } = model.useState(); | ||
|
||
const current = options.find((option) => option.value === value)?.value; | ||
|
||
return ( | ||
<Select | ||
id={key} | ||
placeholder="Select value" | ||
width="auto" | ||
value={current} | ||
tabSelectsValue={false} | ||
options={options} | ||
onChange={model._onChange} | ||
/> | ||
); | ||
}; | ||
} | ||
|
||
interface FieldAccessorCache { | ||
[key: string]: (obj: any) => any; | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Good idea with Observables provider, technically those can be easily retrieved from an async source, sounds very powerful.