optionsHelper.tsx 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import { set, get as lodashGet } from 'lodash';
  2. import { StandardEditorContext, TransformerUIProps, PanelOptionsEditorBuilder } from '@grafana/data';
  3. import { PanelOptionsSupplier } from '@grafana/data/src/panel/PanelPlugin';
  4. import { NestedValueAccess } from '@grafana/data/src/utils/OptionsUIBuilders';
  5. import { OptionsPaneCategoryDescriptor } from 'app/features/dashboard/components/PanelEditor/OptionsPaneCategoryDescriptor';
  6. import { fillOptionsPaneItems } from 'app/features/dashboard/components/PanelEditor/getVisualizationOptions';
  7. import { setOptionImmutably } from 'app/features/dashboard/components/PanelEditor/utils';
  8. export function getTransformerOptionPane<T = any>(
  9. props: TransformerUIProps<T>,
  10. supplier: PanelOptionsSupplier<T>
  11. ): OptionsPaneCategoryDescriptor {
  12. const context: StandardEditorContext<unknown, unknown> = {
  13. data: props.input,
  14. options: props.options,
  15. };
  16. const root = new OptionsPaneCategoryDescriptor({ id: 'root', title: 'root' });
  17. const getOptionsPaneCategory = (categoryNames?: string[]): OptionsPaneCategoryDescriptor => {
  18. if (categoryNames?.length) {
  19. const key = categoryNames[0];
  20. let sub = root.categories.find((v) => v.props.id === key);
  21. if (!sub) {
  22. sub = new OptionsPaneCategoryDescriptor({ id: key, title: key });
  23. root.categories.push(sub);
  24. }
  25. return sub;
  26. }
  27. return root;
  28. };
  29. const access: NestedValueAccess = {
  30. getValue: (path: string) => lodashGet(props.options, path),
  31. onChange: (path: string, value: any) => {
  32. props.onChange(setOptionImmutably(props.options as any, path, value));
  33. },
  34. };
  35. // Use the panel options loader
  36. fillOptionsPaneItems(supplier, access, getOptionsPaneCategory, context);
  37. return root;
  38. }
  39. export function getDefaultOptions<T = any>(supplier: PanelOptionsSupplier<T>): T {
  40. const context: StandardEditorContext<T, unknown> = {
  41. data: [],
  42. options: {} as T,
  43. };
  44. const results = {};
  45. const builder = new PanelOptionsEditorBuilder<T>();
  46. supplier(builder, context);
  47. for (const item of builder.getItems()) {
  48. if (item.defaultValue != null) {
  49. set(results, item.path, item.defaultValue);
  50. }
  51. }
  52. return results as T;
  53. }