@grafana/data#rangeUtil TypeScript Examples

The following examples show how to use @grafana/data#rangeUtil. 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: ng_model_on_blur.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
function validTimeSpan() {
  return {
    require: 'ngModel',
    link: (scope: any, elm: any, attrs: any, ctrl: any) => {
      ctrl.$validators.integer = (modelValue: any, viewValue: any) => {
        if (ctrl.$isEmpty(modelValue)) {
          return true;
        }
        if (viewValue.indexOf('$') === 0 || viewValue.indexOf('+$') === 0) {
          return true; // allow template variable
        }
        const info = rangeUtil.describeTextRange(viewValue);
        return info.invalid !== true;
      };
    },
  };
}
Example #2
Source File: QueryOptions.tsx    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
timeRangeValidationEvents: ValidationEvents = {
  [EventsWithValidation.onBlur]: [
    {
      rule: value => {
        if (!value) {
          return true;
        }
        return rangeUtil.isValidTimeSpan(value);
      },
      errorMessage: 'Not a valid timespan',
    },
  ],
}
Example #3
Source File: TimePicker.tsx    From grafana-chinese with Apache License 2.0 5 votes vote down vote up
formattedRange = (value: TimeRange, isUTC: boolean) => {
  const adjustedTimeRange = {
    to: dateMath.isMathString(value.raw.to) ? value.raw.to : adjustedTime(value.to, isUTC),
    from: dateMath.isMathString(value.raw.from) ? value.raw.from : adjustedTime(value.from, isUTC),
  };
  return rangeUtil.describeTimeRange(adjustedTimeRange);
}
Example #4
Source File: time.ts    From grafana-chinese with Apache License 2.0 5 votes vote down vote up
mapTimeRangeToRangeString = (timeRange: RawTimeRange): string => {
  return rangeUtil.describeTimeRange(timeRange);
}
Example #5
Source File: rangeutil.test.ts    From grafana-chinese with Apache License 2.0 5 votes vote down vote up
describe('rangeUtil', () => {
  describe('Can get range grouped list of ranges', () => {
    it('when custom settings should return default range list', () => {
      const groups: any = rangeUtil.getRelativeTimesList({ time_options: [] }, 'Last 5 minutes');
      expect(_.keys(groups).length).toBe(4);
      expect(groups[3][0].active).toBe(true);
    });
  });

  describe('Can get range text described', () => {
    it('should handle simple old expression with only amount and unit', () => {
      const info = rangeUtil.describeTextRange('5m');
      expect(info.display).toBe('Last 5 minutes');
    });

    it('should have singular when amount is 1', () => {
      const info = rangeUtil.describeTextRange('1h');
      expect(info.display).toBe('Last 1 hour');
    });

    it('should handle non default amount', () => {
      const info = rangeUtil.describeTextRange('13h');
      expect(info.display).toBe('Last 13 hours');
      expect(info.from).toBe('now-13h');
    });

    it('should handle non default future amount', () => {
      const info = rangeUtil.describeTextRange('+3h');
      expect(info.display).toBe('Next 3 hours');
      expect(info.from).toBe('now');
      expect(info.to).toBe('now+3h');
    });

    it('should handle now/d', () => {
      const info = rangeUtil.describeTextRange('now/d');
      expect(info.display).toBe('Today so far');
    });

    it('should handle now/w', () => {
      const info = rangeUtil.describeTextRange('now/w');
      expect(info.display).toBe('This week so far');
    });

    it('should handle now/M', () => {
      const info = rangeUtil.describeTextRange('now/M');
      expect(info.display).toBe('This month so far');
    });

    it('should handle now/y', () => {
      const info = rangeUtil.describeTextRange('now/y');
      expect(info.display).toBe('This year so far');
    });
  });

  describe('Can get date range described', () => {
    it('Date range with simple ranges', () => {
      const text = rangeUtil.describeTimeRange({ from: 'now-1h', to: 'now' });
      expect(text).toBe('Last 1 hour');
    });

    it('Date range with rounding ranges', () => {
      const text = rangeUtil.describeTimeRange({ from: 'now/d+6h', to: 'now' });
      expect(text).toBe('now/d+6h to now');
    });

    it('Date range with absolute to now', () => {
      const text = rangeUtil.describeTimeRange({
        from: dateTime([2014, 10, 10, 2, 3, 4]),
        to: 'now',
      });
      expect(text).toBe('2014-11-10 02:03:04 to a few seconds ago');
    });

    it('Date range with absolute to relative', () => {
      const text = rangeUtil.describeTimeRange({
        from: dateTime([2014, 10, 10, 2, 3, 4]),
        to: 'now-1d',
      });
      expect(text).toBe('2014-11-10 02:03:04 to a day ago');
    });

    it('Date range with relative to absolute', () => {
      const text = rangeUtil.describeTimeRange({
        from: 'now-7d',
        to: dateTime([2014, 10, 10, 2, 3, 4]),
      });
      expect(text).toBe('7 days ago to 2014-11-10 02:03:04');
    });

    it('Date range with non matching default ranges', () => {
      const text = rangeUtil.describeTimeRange({ from: 'now-13h', to: 'now' });
      expect(text).toBe('Last 13 hours');
    });

    it('Date range with from and to both are in now-* format', () => {
      const text = rangeUtil.describeTimeRange({ from: 'now-6h', to: 'now-3h' });
      expect(text).toBe('now-6h to now-3h');
    });

    it('Date range with from and to both are either in now-* or now/* format', () => {
      const text = rangeUtil.describeTimeRange({
        from: 'now/d+6h',
        to: 'now-3h',
      });
      expect(text).toBe('now/d+6h to now-3h');
    });

    it('Date range with from and to both are either in now-* or now+* format', () => {
      const text = rangeUtil.describeTimeRange({ from: 'now-6h', to: 'now+1h' });
      expect(text).toBe('now-6h to now+1h');
    });
  });
});
Example #6
Source File: panel.ts    From grafana-chinese with Apache License 2.0 5 votes vote down vote up
export function applyPanelTimeOverrides(panel: PanelModel, timeRange: TimeRange): TimeOverrideResult {
  const newTimeData = {
    timeInfo: '',
    timeRange: timeRange,
  };

  if (panel.timeFrom) {
    const timeFromInterpolated = templateSrv.replace(panel.timeFrom, panel.scopedVars);
    const timeFromInfo = rangeUtil.describeTextRange(timeFromInterpolated);
    if (timeFromInfo.invalid) {
      newTimeData.timeInfo = 'invalid time override';
      return newTimeData;
    }

    if (_isString(timeRange.raw.from)) {
      const timeFromDate = dateMath.parse(timeFromInfo.from);
      newTimeData.timeInfo = timeFromInfo.display;
      newTimeData.timeRange = {
        from: timeFromDate,
        to: dateMath.parse(timeFromInfo.to),
        raw: {
          from: timeFromInfo.from,
          to: timeFromInfo.to,
        },
      };
    }
  }

  if (panel.timeShift) {
    const timeShiftInterpolated = templateSrv.replace(panel.timeShift, panel.scopedVars);
    const timeShiftInfo = rangeUtil.describeTextRange(timeShiftInterpolated);
    if (timeShiftInfo.invalid) {
      newTimeData.timeInfo = 'invalid timeshift';
      return newTimeData;
    }

    const timeShift = '-' + timeShiftInterpolated;
    newTimeData.timeInfo += ' timeshift ' + timeShift;
    const from = dateMath.parseDateMath(timeShift, newTimeData.timeRange.from, false);
    const to = dateMath.parseDateMath(timeShift, newTimeData.timeRange.to, true);

    newTimeData.timeRange = {
      from,
      to,
      raw: {
        from,
        to,
      },
    };
  }

  if (panel.hideTimeOverride) {
    newTimeData.timeInfo = '';
  }

  return newTimeData;
}
Example #7
Source File: Logs.tsx    From grafana-chinese with Apache License 2.0 4 votes vote down vote up
render() {
    const {
      logRows,
      logsMeta,
      logsSeries,
      highlighterExpressions,
      loading = false,
      onClickFilterLabel,
      onClickFilterOutLabel,
      timeZone,
      scanning,
      scanRange,
      width,
      dedupedRows,
      absoluteRange,
      onChangeTime,
      getFieldLinks,
    } = this.props;

    if (!logRows) {
      return null;
    }

    const { showLabels, showTime, wrapLogMessage } = this.state;
    const { dedupStrategy } = this.props;
    const hasData = logRows && logRows.length > 0;
    const dedupCount = dedupedRows
      ? dedupedRows.reduce((sum, row) => (row.duplicates ? sum + row.duplicates : sum), 0)
      : 0;
    const meta = logsMeta ? [...logsMeta] : [];

    if (dedupStrategy !== LogsDedupStrategy.none) {
      meta.push({
        label: 'Dedup count',
        value: dedupCount,
        kind: LogsMetaKind.Number,
      });
    }

    const scanText = scanRange ? `Scanning ${rangeUtil.describeTimeRange(scanRange)}` : 'Scanning...';
    const series = logsSeries ? logsSeries : [];

    return (
      <div className="logs-panel">
        <div className="logs-panel-graph">
          <ExploreGraphPanel
            series={series}
            width={width}
            onHiddenSeriesChanged={this.onToggleLogLevel}
            loading={loading}
            absoluteRange={absoluteRange}
            isStacked={true}
            showPanel={false}
            showingGraph={true}
            showingTable={true}
            timeZone={timeZone}
            showBars={true}
            showLines={false}
            onUpdateTimeRange={onChangeTime}
          />
        </div>
        <div className="logs-panel-options">
          <div className="logs-panel-controls">
            <Switch label="Time" checked={showTime} onChange={this.onChangeTime} transparent />
            <Switch label="Unique labels" checked={showLabels} onChange={this.onChangeLabels} transparent />
            <Switch label="Wrap lines" checked={wrapLogMessage} onChange={this.onChangewrapLogMessage} transparent />
            <ToggleButtonGroup label="Dedup" transparent={true}>
              {Object.keys(LogsDedupStrategy).map((dedupType: string, i) => (
                <ToggleButton
                  key={i}
                  value={dedupType}
                  onChange={this.onChangeDedup}
                  selected={dedupStrategy === dedupType}
                  // @ts-ignore
                  tooltip={LogsDedupDescription[dedupType]}
                >
                  {dedupType}
                </ToggleButton>
              ))}
            </ToggleButtonGroup>
          </div>
        </div>

        {hasData && meta && (
          <MetaInfoText
            metaItems={meta.map(item => {
              return {
                label: item.label,
                value: renderMetaItem(item.value, item.kind),
              };
            })}
          />
        )}

        <LogRows
          logRows={logRows}
          deduplicatedRows={dedupedRows}
          dedupStrategy={dedupStrategy}
          getRowContext={this.props.getRowContext}
          highlighterExpressions={highlighterExpressions}
          rowLimit={logRows ? logRows.length : undefined}
          onClickFilterLabel={onClickFilterLabel}
          onClickFilterOutLabel={onClickFilterOutLabel}
          showLabels={showLabels}
          showTime={showTime}
          wrapLogMessage={wrapLogMessage}
          timeZone={timeZone}
          getFieldLinks={getFieldLinks}
        />

        {!loading && !hasData && !scanning && (
          <div className="logs-panel-nodata">
            No logs found.
            <a className="link" onClick={this.onClickScan}>
              Scan for older logs
            </a>
          </div>
        )}

        {scanning && (
          <div className="logs-panel-nodata">
            <span>{scanText}</span>
            <a className="link" onClick={this.onClickStopScan}>
              Stop scan
            </a>
          </div>
        )}
      </div>
    );
  }