@grafana/data#standardFieldConfigEditorRegistry TypeScript Examples

The following examples show how to use @grafana/data#standardFieldConfigEditorRegistry. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: utils.test.ts    From grafana-chinese with Apache License 2.0 7 votes vote down vote up
describe('standardFieldConfigEditorRegistry', () => {
  const dummyConfig: FieldConfig = {
    title: 'Hello',
    min: 10,
    max: 10,
    decimals: 10,
    thresholds: {} as any,
    noValue: 'no value',
    unit: 'km/s',
    links: {} as any,
  };

  it('make sure all fields have a valid name', () => {
    standardFieldConfigEditorRegistry.list().forEach(v => {
      if (!dummyConfig.hasOwnProperty(v.id)) {
        fail(`Registry uses unknown property: ${v.id}`);
      }
    });
  });
});
Example #2
Source File: FieldConfigEditor.tsx    From grafana-chinese with Apache License 2.0 5 votes vote down vote up
renderStandardConfigs() {
    const { include } = this.props;
    if (include) {
      return include.map(f => this.renderEditor(standardFieldConfigEditorRegistry.get(f), false));
    }
    return standardFieldConfigEditorRegistry.list().map(f => this.renderEditor(f, false));
  }
Example #3
Source File: FieldConfigEditor.tsx    From grafana-chinese with Apache License 2.0 5 votes vote down vote up
renderOverrides() {
    const { config, data, plugin } = this.props;
    const { customFieldConfigs } = plugin;

    if (config.overrides.length === 0) {
      return null;
    }

    let configPropertiesOptions = standardFieldConfigEditorRegistry.list().map(i => ({
      label: i.name,
      value: i.id,
      description: i.description,
      custom: false,
    }));

    if (customFieldConfigs) {
      configPropertiesOptions = configPropertiesOptions.concat(
        customFieldConfigs.list().map(i => ({
          label: i.name,
          value: i.id,
          description: i.description,
          custom: true,
        }))
      );
    }

    return (
      <div>
        {config.overrides.map((o, i) => {
          // TODO:  apply matcher to retrieve fields
          return (
            <OverrideEditor
              key={`${o.matcher.id}/${i}`}
              data={data}
              override={o}
              onChange={value => this.onOverrideChange(i, value)}
              onRemove={() => this.onOverrideRemove(i)}
              configPropertiesOptions={configPropertiesOptions}
              customPropertiesRegistry={customFieldConfigs}
            />
          );
        })}
      </div>
    );
  }
Example #4
Source File: fieldOverrides.test.ts    From grafana-chinese with Apache License 2.0 4 votes vote down vote up
describe('FieldOverrides', () => {
  beforeAll(() => {
    standardFieldConfigEditorRegistry.setInit(getStandardFieldConfigs);
  });

  const f0 = new MutableDataFrame();
  f0.add({ title: 'AAA', value: 100, value2: 1234 }, true);
  f0.add({ title: 'BBB', value: -20 }, true);
  f0.add({ title: 'CCC', value: 200, value2: 1000 }, true);
  expect(f0.length).toEqual(3);

  // Hardcode the max value
  f0.fields[1].config.max = 0;
  f0.fields[1].config.decimals = 6;

  const src: FieldConfigSource = {
    defaults: {
      unit: 'xyz',
      decimals: 2,
    },
    overrides: [
      {
        matcher: { id: FieldMatcherID.numeric },
        properties: [
          { prop: 'decimals', value: 1 }, // Numeric
          { prop: 'title', value: 'Kittens' }, // Text
        ],
      },
    ],
  };

  it('will merge FieldConfig with default values', () => {
    const field: FieldConfig = {
      min: 0,
      max: 100,
    };
    const f1 = {
      unit: 'ms',
      dateFormat: '', // should be ignored
      max: parseFloat('NOPE'), // should be ignored
      min: null, // should alo be ignored!
    };

    const f: DataFrame = toDataFrame({
      fields: [{ type: FieldType.number, name: 'x', config: field, values: [] }],
    });
    const processed = applyFieldOverrides({
      data: [f],
      standard: standardFieldConfigEditorRegistry,
      fieldOptions: {
        defaults: f1 as FieldConfig,
        overrides: [],
      },
      replaceVariables: v => v,
      theme: getTheme(),
    })[0];
    const out = processed.fields[0].config;

    expect(out.min).toEqual(0);
    expect(out.max).toEqual(100);
    expect(out.unit).toEqual('ms');
  });

  it('will apply field overrides', () => {
    const data = applyFieldOverrides({
      data: [f0], // the frame
      fieldOptions: src as FieldDisplayOptions, // defaults + overrides
      replaceVariables: (undefined as any) as InterpolateFunction,
      theme: (undefined as any) as GrafanaTheme,
    })[0];
    const valueColumn = data.fields[1];
    const config = valueColumn.config;

    // Keep max from the original setting
    expect(config.max).toEqual(0);

    // Don't Automatically pick the min value
    expect(config.min).toEqual(undefined);

    // The default value applied
    expect(config.unit).toEqual('xyz');

    // The default value applied
    expect(config.title).toEqual('Kittens');

    // The override applied
    expect(config.decimals).toEqual(1);
  });

  it('will apply set min/max when asked', () => {
    const data = applyFieldOverrides({
      data: [f0], // the frame
      fieldOptions: src as FieldDisplayOptions, // defaults + overrides
      replaceVariables: (undefined as any) as InterpolateFunction,
      theme: (undefined as any) as GrafanaTheme,
      autoMinMax: true,
    })[0];
    const valueColumn = data.fields[1];
    const config = valueColumn.config;

    // Keep max from the original setting
    expect(config.max).toEqual(0);

    // Don't Automatically pick the min value
    expect(config.min).toEqual(-20);
  });
});
Example #5
Source File: app.ts    From grafana-chinese with Apache License 2.0 4 votes vote down vote up
init() {
    const app = angular.module('grafana', []);

    setLocale(config.bootData.user.locale);

    setMarkdownOptions({ sanitize: !config.disableSanitizeHtml });
    standardFieldConfigEditorRegistry.setInit(getStandardFieldConfigs);

    app.config(
      (
        $locationProvider: angular.ILocationProvider,
        $controllerProvider: angular.IControllerProvider,
        $compileProvider: angular.ICompileProvider,
        $filterProvider: angular.IFilterProvider,
        $httpProvider: angular.IHttpProvider,
        $provide: angular.auto.IProvideService
      ) => {
        // pre assing bindings before constructor calls
        $compileProvider.preAssignBindingsEnabled(true);

        if (config.buildInfo.env !== 'development') {
          $compileProvider.debugInfoEnabled(false);
        }

        $httpProvider.useApplyAsync(true);

        this.registerFunctions.controller = $controllerProvider.register;
        this.registerFunctions.directive = $compileProvider.directive;
        this.registerFunctions.factory = $provide.factory;
        this.registerFunctions.service = $provide.service;
        this.registerFunctions.filter = $filterProvider.register;

        $provide.decorator('$http', [
          '$delegate',
          '$templateCache',
          ($delegate: any, $templateCache: any) => {
            const get = $delegate.get;
            $delegate.get = (url: string, config: any) => {
              if (url.match(/\.html$/)) {
                // some template's already exist in the cache
                if (!$templateCache.get(url)) {
                  url += '?v=' + new Date().getTime();
                }
              }
              return get(url, config);
            };
            return $delegate;
          },
        ]);
      }
    );

    this.ngModuleDependencies = [
      'grafana.core',
      'ngRoute',
      'ngSanitize',
      '$strap.directives',
      'ang-drag-drop',
      'grafana',
      'pasvaz.bindonce',
      'react',
    ];

    // makes it possible to add dynamic stuff
    _.each(angularModules, (m: angular.IModule) => {
      this.useModule(m);
    });

    // register react angular wrappers
    coreModule.config(setupAngularRoutes);
    registerAngularDirectives();

    // disable tool tip animation
    $.fn.tooltip.defaults.animation = false;

    // bootstrap the app
    angular.bootstrap(document, this.ngModuleDependencies).invoke(() => {
      _.each(this.preBootModules, (module: angular.IModule) => {
        _.extend(module, this.registerFunctions);
      });

      this.preBootModules = null;

      if (!checkBrowserCompatibility()) {
        setTimeout(() => {
          appEvents.emit(AppEvents.alertWarning, [
            'Your browser is not fully supported',
            'A newer browser version is recommended',
          ]);
        }, 1000);
      }
    });

    // Preload selected app plugins
    for (const modulePath of config.pluginsToPreload) {
      importPluginModule(modulePath);
    }
  }
Example #6
Source File: OverrideEditor.tsx    From grafana-chinese with Apache License 2.0 4 votes vote down vote up
OverrideEditor: React.FC<OverrideEditorProps> = ({
  data,
  override,
  onChange,
  onRemove,
  customPropertiesRegistry,
  configPropertiesOptions,
}) => {
  const theme = useTheme();
  const onMatcherConfigChange = useCallback(
    (matcherConfig: any) => {
      override.matcher.options = matcherConfig;
      onChange(override);
    },
    [override, onChange]
  );

  const onDynamicConfigValueChange = useCallback(
    (index: number, value: DynamicConfigValue) => {
      override.properties[index].value = value;
      onChange(override);
    },
    [override, onChange]
  );

  const onDynamicConfigValueRemove = useCallback(
    (index: number) => {
      override.properties.splice(index, 1);
      onChange(override);
    },
    [override, onChange]
  );

  const onDynamicConfigValueAdd = useCallback(
    (prop: string, custom?: boolean) => {
      const propertyConfig: DynamicConfigValue = {
        prop,
        custom,
      };
      if (override.properties) {
        override.properties.push(propertyConfig);
      } else {
        override.properties = [propertyConfig];
      }
      onChange(override);
    },
    [override, onChange]
  );

  const matcherUi = fieldMatchersUI.get(override.matcher.id);
  const styles = getStyles(theme);
  return (
    <div className={styles.wrapper}>
      <div className={styles.headerWrapper}>
        <OverrideHeader onRemove={onRemove} title={matcherUi.name} description={matcherUi.description} />
        <div className={styles.matcherUi}>
          <matcherUi.component
            matcher={matcherUi.matcher}
            data={data}
            options={override.matcher.options}
            onChange={option => onMatcherConfigChange(option)}
          />
        </div>
      </div>
      <div>
        {override.properties.map((p, j) => {
          const reg = p.custom ? customPropertiesRegistry : standardFieldConfigEditorRegistry;
          const item = reg?.getIfExists(p.prop);

          if (!item) {
            return <div>Unknown property: {p.prop}</div>;
          }

          return (
            <div key={`${p.prop}/${j}`}>
              <DynamicConfigValueEditor
                onChange={value => onDynamicConfigValueChange(j, value)}
                onRemove={() => onDynamicConfigValueRemove(j)}
                property={p}
                editorsRegistry={reg}
                context={{
                  data,
                  getSuggestions: (scope?: VariableSuggestionsScope) => getDataLinksVariableSuggestions(data, scope),
                }}
              />
            </div>
          );
        })}
        <div className={styles.propertyPickerWrapper}>
          <ValuePicker
            label="Set config property"
            icon="plus"
            options={configPropertiesOptions}
            variant={'link'}
            onChange={o => {
              onDynamicConfigValueAdd(o.value, o.custom);
            }}
          />
        </div>
      </div>
    </div>
  );
}