@grafana/data#fieldReducers TypeScript Examples

The following examples show how to use @grafana/data#fieldReducers. 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: SingleStatBaseOptions.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
/*
 * Moves valueMappings and thresholds from root to new fieldOptions object
 * Renames valueOptions to to defaults and moves it under fieldOptions
 */
export function migrateFromValueOptions(old: any) {
  const { valueOptions } = old;
  if (!valueOptions) {
    return old;
  }

  const fieldOptions: any = {};
  const fieldDefaults: any = {};

  fieldOptions.mappings = old.valueMappings;
  fieldOptions.thresholds = old.thresholds;
  fieldOptions.defaults = fieldDefaults;

  fieldDefaults.unit = valueOptions.unit;
  fieldDefaults.decimals = valueOptions.decimals;

  // Make sure the stats have a valid name
  if (valueOptions.stat) {
    const reducer = fieldReducers.get(valueOptions.stat);
    if (reducer) {
      fieldOptions.calcs = [reducer.id];
    }
  }

  fieldDefaults.min = old.minValue;
  fieldDefaults.max = old.maxValue;

  const newOptions = {
    ...old,
    fieldOptions,
  };

  return omit(newOptions, 'valueMappings', 'thresholds', 'valueOptions', 'minValue', 'maxValue');
}
Example #2
Source File: StatsPicker.tsx    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
render() {
    const { width, stats, allowMultiple, defaultStat, placeholder } = this.props;

    const select = fieldReducers.selectOptions(stats);
    return (
      <Select
        width={width}
        value={select.current}
        isClearable={!defaultStat}
        isMulti={allowMultiple}
        isSearchable={true}
        options={select.options}
        placeholder={placeholder}
        onChange={this.onSelectionChange}
      />
    );
  }
Example #3
Source File: StatsPicker.tsx    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
checkInput = () => {
    const { stats, allowMultiple, defaultStat, onChange } = this.props;

    const current = fieldReducers.list(stats);
    if (current.length !== stats.length) {
      const found = current.map(v => v.id);
      const notFound = difference(stats, found);
      console.warn('Unknown stats', notFound, stats);
      onChange(current.map(stat => stat.id));
    }

    // Make sure there is only one
    if (!allowMultiple && stats.length > 1) {
      console.warn('Removing extra stat', stats);
      onChange([stats[0]]);
    }

    // Set the reducer from callback
    if (defaultStat && stats.length < 1) {
      onChange([defaultStat]);
    }
  };
Example #4
Source File: SingleStatBaseOptions.ts    From grafana-chinese with Apache License 2.0 5 votes vote down vote up
export function sharedSingleStatPanelChangedHandler(
  options: Partial<SingleStatBaseOptions> | any,
  prevPluginId: string,
  prevOptions: any
) {
  // Migrating from angular singlestat
  if (prevPluginId === 'singlestat' && prevOptions.angular) {
    const panel = prevOptions.angular;
    const reducer = fieldReducers.getIfExists(panel.valueName);
    const options = {
      fieldOptions: {
        defaults: {} as FieldConfig,
        overrides: [] as ConfigOverrideRule[],
        calcs: [reducer ? reducer.id : ReducerID.mean],
      },
      orientation: VizOrientation.Horizontal,
    };

    const defaults = options.fieldOptions.defaults;
    if (panel.format) {
      defaults.unit = panel.format;
    }
    if (panel.nullPointMode) {
      defaults.nullValueMode = panel.nullPointMode;
    }
    if (panel.nullText) {
      defaults.noValue = panel.nullText;
    }
    if (panel.decimals || panel.decimals === 0) {
      defaults.decimals = panel.decimals;
    }

    // Convert thresholds and color values
    if (panel.thresholds && panel.colors) {
      const levels = panel.thresholds.split(',').map((strVale: string) => {
        return Number(strVale.trim());
      });

      // One more color than threshold
      const thresholds: Threshold[] = [];
      for (const color of panel.colors) {
        const idx = thresholds.length - 1;
        if (idx >= 0) {
          thresholds.push({ value: levels[idx], color });
        } else {
          thresholds.push({ value: -Infinity, color });
        }
      }
      defaults.thresholds = {
        mode: ThresholdsMode.Absolute,
        steps: thresholds,
      };
    }

    // Convert value mappings
    const mappings = convertOldAngularValueMapping(panel);
    if (mappings && mappings.length) {
      defaults.mappings = mappings;
    }

    if (panel.gauge && panel.gauge.show) {
      defaults.min = panel.gauge.minValue;
      defaults.max = panel.gauge.maxValue;
    }
    return options;
  }

  for (const k of optionsToKeep) {
    if (prevOptions.hasOwnProperty(k)) {
      options[k] = cloneDeep(prevOptions[k]);
    }
  }
  return options;
}
Example #5
Source File: module.ts    From grafana-chinese with Apache License 2.0 5 votes vote down vote up
processField(fieldInfo: FieldInfo) {
    const { panel, dashboard } = this;

    const name = fieldInfo.field.config.title || fieldInfo.field.name;
    let calc = panel.valueName;
    let calcField = fieldInfo.field;
    let val: any = undefined;

    if ('name' === calc) {
      val = name;
    } else {
      if ('last_time' === calc) {
        if (fieldInfo.frame.firstTimeField) {
          calcField = fieldInfo.frame.firstTimeField;
          calc = ReducerID.last;
        }
      }

      // Normalize functions (avg -> mean, etc)
      const r = fieldReducers.getIfExists(calc);
      if (r) {
        calc = r.id;
        // With strings, don't accidentally use a math function
        if (calcField.type === FieldType.string) {
          const avoid = [ReducerID.mean, ReducerID.sum];
          if (avoid.includes(calc)) {
            calc = panel.valueName = ReducerID.first;
          }
        }
      } else {
        calc = ReducerID.lastNotNull;
      }

      // Calculate the value
      val = reduceField({
        field: calcField,
        reducers: [calc],
      })[calc];
    }

    const processor = getDisplayProcessor({
      field: {
        ...fieldInfo.field,
        config: {
          ...fieldInfo.field.config,
          unit: panel.format,
          decimals: panel.decimals,
          mappings: convertOldAngularValueMapping(panel),
        },
      },
      theme: config.theme,
      timeZone: dashboard.getTimezone(),
    });

    const sparkline: any[] = [];
    const data = {
      field: fieldInfo.field,
      value: val,
      display: processor(val),
      scopedVars: _.extend({}, panel.scopedVars),
      sparkline,
    };

    data.scopedVars['__name'] = { value: name };
    panel.tableColumn = this.fieldNames.length > 1 ? name : '';

    // Get the fields for a sparkline
    if (panel.sparkline && panel.sparkline.show && fieldInfo.frame.firstTimeField) {
      data.sparkline = getFlotPairs({
        xField: fieldInfo.frame.firstTimeField,
        yField: fieldInfo.field,
        nullValueMode: panel.nullPointMode,
      });
    }

    return data;
  }