Skip to content

SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.

7.7 KB
Raw Blame
import { useCallback, useMemo, useState } from 'react';
import { Tooltip } from 'antd';
import cx from 'classnames';
import { Button } from '@signozhq/ui/button';
import { InputNumber } from '@signozhq/ui/input-number';
import { ToggleGroup } from '@signozhq/ui/toggle-group';
import { ChevronUp, Info } from '@signozhq/icons';
import {
	Querybuildertypesv5BucketOptionsDTO,
	Querybuildertypesv5BucketsKindDTO,
} from 'api/generated/services/sigNoz.schemas';

import {
	BUCKET_KIND_HINTS,
	BUCKET_KIND_OPTIONS,
	DEFAULT_NUM_BUCKETS,
	LOG_SCALE_OPTIONS,
	MAX_NUM_BUCKETS,
} from './constants';
import {
	formatUpperBound,
	hasBoundsBeyondPreview,
	isLinearBuckets,
	kindOptionOf,
	linearBuckets,
	logBuckets,
	logScaleOf,
	previewUpperBounds,
} from './utils';

import styles from './BucketOptions.module.scss';

function BucketOptions({
	bucketOptions,
	unit,
	onChange,
	onClose,
}: {
	bucketOptions?: Querybuildertypesv5BucketOptionsDTO;
	/** The panel's y-axis unit, so the previewed bounds read the way the axis will. */
	unit?: string;
	onChange: (next: Querybuildertypesv5BucketOptionsDTO | undefined) => void;
	/** Omitted where the section isn't dismissable, as on a formula. */
	onClose?: () => void;
}): JSX.Element {
	// A linear axis has no bounds to describe until it has a max value, so the picked
	// kind is held here rather than read back off the emitted options: it has to survive
	// the gap between choosing Linear and filling the field in.
	const [kind, setKind] = useState<Querybuildertypesv5BucketsKindDTO>(() =>
		kindOptionOf(bucketOptions),
	);
	const linearSpec =
		bucketOptions && isLinearBuckets(bucketOptions)
			? bucketOptions.spec
			: undefined;
	const [logScale, setLogScale] = useState<number>(() =>
		logScaleOf(bucketOptions),
	);
	const [maxValue, setMaxValue] = useState<number | null>(
		linearSpec?.maxValue ?? null,
	);
	const [numBuckets, setNumBuckets] = useState<number | null>(
		linearSpec?.numBuckets ?? null,
	);

	const emitLinear = useCallback(
		(nextMaxValue: number | null, nextNumBuckets: number | null): void => {
			// An incomplete linear axis is sent as no axis at all rather than as a spec the
			// request would reject.
			if (nextMaxValue === null || nextMaxValue <= 0) {
				onChange(undefined);
				return;
			}

			onChange(linearBuckets(nextMaxValue, nextNumBuckets));
		},
		[onChange],
	);

	const handleKindChange = useCallback(
		(value: string): void => {
			// Radix clears the value when the active item is clicked again; a bucket axis is
			// always one of the two, so keep the current pick instead.
			if (!value) {
				return;
			}

			const nextKind = value as Querybuildertypesv5BucketsKindDTO;
			setKind(nextKind);

			if (nextKind === Querybuildertypesv5BucketsKindDTO.log) {
				onChange(logBuckets(logScale));
			} else {
				emitLinear(maxValue, numBuckets);
			}
		},
		[emitLinear, logScale, maxValue, numBuckets, onChange],
	);

	const handleScaleChange = useCallback(
		(value: string): void => {
			if (!value) {
				return;
			}

			const nextScale = Number(value);
			setLogScale(nextScale);
			onChange(logBuckets(nextScale));
		},
		[onChange],
	);

	const handleMaxValueChange = useCallback(
		(value: number | string | null): void => {
			const next = value === null || value === '' ? null : Number(value);
			setMaxValue(next);
			emitLinear(next, numBuckets);
		},
		[emitLinear, numBuckets],
	);

	const handleNumBucketsChange = useCallback(
		(value: number | string | null): void => {
			const next = value === null || value === '' ? null : Number(value);
			setNumBuckets(next);
			emitLinear(maxValue, next);
		},
		[emitLinear, maxValue],
	);

	// The toggle group takes a ReactNode label, which is how each item picks up the
	// query builder's value type — the component exposes no font-family token.
	const kindItems = useMemo(
		() =>
			BUCKET_KIND_OPTIONS.map(({ value, label }) => ({
				value,
				label: <span className={styles.toggleLabel}>{label}</span>,
				'aria-label': label,
			})),
		[],
	);

	const scaleItems = useMemo(
		() =>
			LOG_SCALE_OPTIONS.map(({ value, label }) => ({
				value,
				label: <span className={styles.toggleLabel}>{label}</span>,
				'aria-label': label,
			})),
		[],
	);

	// The kind toggle can be ahead of what has been emitted, so the preview describes
	// the picked kind rather than the emitted options.
	const previewedOptions = useMemo(():
		| Querybuildertypesv5BucketOptionsDTO
		| undefined => {
		if (kind === Querybuildertypesv5BucketsKindDTO.log) {
			return logBuckets(logScale);
		}
		if (kind === Querybuildertypesv5BucketsKindDTO.linear && maxValue !== null) {
			return linearBuckets(maxValue, numBuckets);
		}
		return undefined;
	}, [kind, logScale, maxValue, numBuckets]);

	const bounds = useMemo(
		() =>
			kind === Querybuildertypesv5BucketsKindDTO.linear && !previewedOptions
				? undefined
				: previewUpperBounds(previewedOptions),
		[kind, previewedOptions],
	);

	return (
		<div className={styles.bucketOptions} data-testid="bucket-options">
			<div className={styles.controls}>
				<div className={styles.field}>
					<span className={styles.label}>Bucket by</span>
					<ToggleGroup
						variant="outlined"
						color="secondary"
						size="sm"
						type="single"
						value={kind}
						items={kindItems}
						onChange={handleKindChange}
						testId="bucket-options-kind"
					/>
				</div>

				{kind === Querybuildertypesv5BucketsKindDTO.log && (
					<div className={styles.field}>
						<span className={styles.label}>Scale</span>
						<ToggleGroup
							variant="outlined"
							color="secondary"
							size="sm"
							type="single"
							value={String(logScale)}
							items={scaleItems}
							onChange={handleScaleChange}
							testId="bucket-options-scale"
						/>
					</div>
				)}

				{kind === Querybuildertypesv5BucketsKindDTO.linear && (
					<>
						<div className={styles.field}>
							<span className={styles.label}>Max value</span>
							<InputNumber
								className={styles.numberInput}
								min={0}
								value={maxValue}
								onChange={handleMaxValueChange}
								placeholder="Required"
								status={maxValue !== null && maxValue <= 0 ? 'error' : undefined}
								data-testid="bucket-options-max-value"
							/>
						</div>
						<div className={styles.field}>
							<span className={styles.label}>Buckets</span>
							<InputNumber
								className={styles.numberInput}
								min={1}
								max={MAX_NUM_BUCKETS}
								precision={0}
								value={numBuckets}
								onChange={handleNumBucketsChange}
								placeholder={`Default ${DEFAULT_NUM_BUCKETS}`}
								data-testid="bucket-options-num-buckets"
							/>
						</div>
					</>
				)}

				{onClose && (
					<Button
						color="secondary"
						variant="ghost"
						size="sm"
						icon
						aria-label="Close bucket options"
						onClick={onClose}
						testId="bucket-options-close"
					>
						<ChevronUp size={16} />
					</Button>
				)}
			</div>

			<div className={styles.bounds} data-testid="bucket-options-bounds">
				<span className={styles.label}>
					Bounds
					<Tooltip title={BUCKET_KIND_HINTS[kind]} placement="top">
						<Info size={12} className={styles.hintIcon} />
					</Tooltip>
				</span>
				{bounds ? (
					<>
						{bounds.map((bound) => (
							<span className={styles.bound} key={bound}>
								{formatUpperBound(bound, unit)}
							</span>
						))}
						{hasBoundsBeyondPreview(previewedOptions) && (
							<span className={styles.muted}>…</span>
						)}
						<span className={cx(styles.bound, styles.overflowBound)}>+Inf</span>
					</>
				) : (
					<span className={styles.muted}>Set a max value to see the bounds</span>
				)}
			</div>
		</div>
	);
}

BucketOptions.defaultProps = {
	bucketOptions: undefined,
	unit: undefined,
	onClose: undefined,
};

export default BucketOptions;