UNPKG

@grafana/ui

Version:
82 lines (80 loc) 2.23 kB
const regex = /^now$|^now(\-|\+)(\d{1,10})([wdhms])$/; const mapOptionToRelativeTimeRange = (option) => { return { from: relativeToSeconds(option.from), to: relativeToSeconds(option.to) }; }; const mapRelativeTimeRangeToOption = (range) => { const from = secondsToRelativeFormat(range.from); const to = secondsToRelativeFormat(range.to); return { from, to, display: `${from} to ${to}` }; }; const isRangeValid = (relative, now = Date.now()) => { if (!isRelativeFormat(relative)) { return { isValid: false, errorMessage: "Value not in relative time format." }; } const seconds = relativeToSeconds(relative); if (seconds > Math.ceil(now / 1e3)) { return { isValid: false, errorMessage: "Can not enter value prior to January 1, 1970." }; } return { isValid: true }; }; const isRelativeFormat = (format) => { return regex.test(format); }; const relativeToSeconds = (relative) => { const match = regex.exec(relative); if (!match || match.length !== 4) { return 0; } const [, sign, value, unit] = match; const parsed = parseInt(value, 10); if (isNaN(parsed)) { return 0; } const seconds = parsed * units[unit]; return sign === "+" ? seconds * -1 : seconds; }; const units = { w: 604800, d: 86400, h: 3600, m: 60, s: 1 }; const secondsToRelativeFormat = (seconds) => { if (seconds === 0) { return "now"; } const absoluteSeconds = Math.abs(seconds); if (seconds < 0) { return `now+${formatDuration(absoluteSeconds)}`; } return `now-${formatDuration(absoluteSeconds)}`; }; function formatDuration(seconds) { const units2 = [ { unit: "w", value: 7 * 24 * 60 * 60 }, { unit: "d", value: 24 * 60 * 60 }, { unit: "h", value: 60 * 60 }, { unit: "m", value: 60 }, { unit: "s", value: 1 } ]; for (const { unit, value } of units2) { if (seconds % value === 0) { const quotient = seconds / value; return `${quotient}${unit}`; } } const leastSignificant = units2[units2.length - 1]; return `${seconds}${leastSignificant.unit}`; } export { isRangeValid, isRelativeFormat, mapOptionToRelativeTimeRange, mapRelativeTimeRangeToOption }; //# sourceMappingURL=utils.mjs.map