mirror of
https://github.com/SigNoz/signoz.git
synced 2026-03-06 22:02:03 +00:00
Compare commits
17 Commits
main
...
feat/trace
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ca311717c2 | ||
|
|
a614da2c65 | ||
|
|
ce18709002 | ||
|
|
2b6977e891 | ||
|
|
3e6eedbcab | ||
|
|
fd9e3f0411 | ||
|
|
e99465e030 | ||
|
|
9ad2db4b99 | ||
|
|
07fd5f70ef | ||
|
|
ba79121795 | ||
|
|
6e4e419b5e | ||
|
|
2f06afaf27 | ||
|
|
f77c3cb23c | ||
|
|
9e3a8efcfc | ||
|
|
8e325ba8b3 | ||
|
|
884f516766 | ||
|
|
4bcbb4ffc3 |
4
.github/workflows/commitci.yaml
vendored
4
.github/workflows/commitci.yaml
vendored
@@ -7,14 +7,10 @@ on:
|
||||
pull_request_target:
|
||||
types:
|
||||
- labeled
|
||||
merge_group:
|
||||
types:
|
||||
- checks_requested
|
||||
|
||||
jobs:
|
||||
refcheck:
|
||||
if: |
|
||||
github.event_name == 'merge_group' ||
|
||||
(github.event_name == 'pull_request' && ! github.event.pull_request.head.repo.fork && github.event.pull_request.user.login != 'dependabot[bot]' && ! contains(github.event.pull_request.labels.*.name, 'safe-to-test')) ||
|
||||
(github.event_name == 'pull_request_target' && contains(github.event.pull_request.labels.*.name, 'safe-to-test'))
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
9
.github/workflows/goci.yaml
vendored
9
.github/workflows/goci.yaml
vendored
@@ -7,14 +7,10 @@ on:
|
||||
pull_request_target:
|
||||
types:
|
||||
- labeled
|
||||
merge_group:
|
||||
types:
|
||||
- checks_requested
|
||||
|
||||
jobs:
|
||||
test:
|
||||
if: |
|
||||
github.event_name == 'merge_group' ||
|
||||
(github.event_name == 'pull_request' && ! github.event.pull_request.head.repo.fork && github.event.pull_request.user.login != 'dependabot[bot]' && ! contains(github.event.pull_request.labels.*.name, 'safe-to-test')) ||
|
||||
(github.event_name == 'pull_request_target' && contains(github.event.pull_request.labels.*.name, 'safe-to-test'))
|
||||
uses: signoz/primus.workflows/.github/workflows/go-test.yaml@main
|
||||
@@ -25,7 +21,6 @@ jobs:
|
||||
GO_VERSION: 1.24
|
||||
fmt:
|
||||
if: |
|
||||
github.event_name == 'merge_group' ||
|
||||
(github.event_name == 'pull_request' && ! github.event.pull_request.head.repo.fork && github.event.pull_request.user.login != 'dependabot[bot]' && ! contains(github.event.pull_request.labels.*.name, 'safe-to-test')) ||
|
||||
(github.event_name == 'pull_request_target' && contains(github.event.pull_request.labels.*.name, 'safe-to-test'))
|
||||
uses: signoz/primus.workflows/.github/workflows/go-fmt.yaml@main
|
||||
@@ -35,7 +30,6 @@ jobs:
|
||||
GO_VERSION: 1.24
|
||||
lint:
|
||||
if: |
|
||||
github.event_name == 'merge_group' ||
|
||||
(github.event_name == 'pull_request' && ! github.event.pull_request.head.repo.fork && github.event.pull_request.user.login != 'dependabot[bot]' && ! contains(github.event.pull_request.labels.*.name, 'safe-to-test')) ||
|
||||
(github.event_name == 'pull_request_target' && contains(github.event.pull_request.labels.*.name, 'safe-to-test'))
|
||||
uses: signoz/primus.workflows/.github/workflows/go-lint.yaml@main
|
||||
@@ -45,7 +39,6 @@ jobs:
|
||||
GO_VERSION: 1.24
|
||||
deps:
|
||||
if: |
|
||||
github.event_name == 'merge_group' ||
|
||||
(github.event_name == 'pull_request' && ! github.event.pull_request.head.repo.fork && github.event.pull_request.user.login != 'dependabot[bot]' && ! contains(github.event.pull_request.labels.*.name, 'safe-to-test')) ||
|
||||
(github.event_name == 'pull_request_target' && contains(github.event.pull_request.labels.*.name, 'safe-to-test'))
|
||||
uses: signoz/primus.workflows/.github/workflows/go-deps.yaml@main
|
||||
@@ -55,7 +48,6 @@ jobs:
|
||||
GO_VERSION: 1.24
|
||||
build:
|
||||
if: |
|
||||
github.event_name == 'merge_group' ||
|
||||
(github.event_name == 'pull_request' && ! github.event.pull_request.head.repo.fork && github.event.pull_request.user.login != 'dependabot[bot]' && ! contains(github.event.pull_request.labels.*.name, 'safe-to-test')) ||
|
||||
(github.event_name == 'pull_request_target' && contains(github.event.pull_request.labels.*.name, 'safe-to-test'))
|
||||
runs-on: ubuntu-latest
|
||||
@@ -87,7 +79,6 @@ jobs:
|
||||
make docker-build-enterprise
|
||||
openapi:
|
||||
if: |
|
||||
github.event_name == 'merge_group' ||
|
||||
(github.event_name == 'pull_request' && ! github.event.pull_request.head.repo.fork && github.event.pull_request.user.login != 'dependabot[bot]' && ! contains(github.event.pull_request.labels.*.name, 'safe-to-test')) ||
|
||||
(github.event_name == 'pull_request_target' && contains(github.event.pull_request.labels.*.name, 'safe-to-test'))
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
10
.github/workflows/jsci.yaml
vendored
10
.github/workflows/jsci.yaml
vendored
@@ -7,14 +7,10 @@ on:
|
||||
pull_request_target:
|
||||
types:
|
||||
- labeled
|
||||
merge_group:
|
||||
types:
|
||||
- checks_requested
|
||||
|
||||
jobs:
|
||||
tsc:
|
||||
if: |
|
||||
github.event_name == 'merge_group' ||
|
||||
(github.event_name == 'pull_request' && ! github.event.pull_request.head.repo.fork && github.event.pull_request.user.login != 'dependabot[bot]' && ! contains(github.event.pull_request.labels.*.name, 'safe-to-test')) ||
|
||||
(github.event_name == 'pull_request_target' && contains(github.event.pull_request.labels.*.name, 'safe-to-test'))
|
||||
runs-on: ubuntu-latest
|
||||
@@ -31,7 +27,6 @@ jobs:
|
||||
run: cd frontend && yarn tsc
|
||||
tsc2:
|
||||
if: |
|
||||
github.event_name == 'merge_group' ||
|
||||
(github.event_name == 'pull_request' && ! github.event.pull_request.head.repo.fork && github.event.pull_request.user.login != 'dependabot[bot]' && ! contains(github.event.pull_request.labels.*.name, 'safe-to-test')) ||
|
||||
(github.event_name == 'pull_request_target' && contains(github.event.pull_request.labels.*.name, 'safe-to-test'))
|
||||
uses: signoz/primus.workflows/.github/workflows/js-tsc.yaml@main
|
||||
@@ -41,7 +36,6 @@ jobs:
|
||||
JS_SRC: frontend
|
||||
test:
|
||||
if: |
|
||||
github.event_name == 'merge_group' ||
|
||||
(github.event_name == 'pull_request' && ! github.event.pull_request.head.repo.fork && github.event.pull_request.user.login != 'dependabot[bot]' && ! contains(github.event.pull_request.labels.*.name, 'safe-to-test')) ||
|
||||
(github.event_name == 'pull_request_target' && contains(github.event.pull_request.labels.*.name, 'safe-to-test'))
|
||||
uses: signoz/primus.workflows/.github/workflows/js-test.yaml@main
|
||||
@@ -51,7 +45,6 @@ jobs:
|
||||
JS_SRC: frontend
|
||||
fmt:
|
||||
if: |
|
||||
github.event_name == 'merge_group' ||
|
||||
(github.event_name == 'pull_request' && ! github.event.pull_request.head.repo.fork && github.event.pull_request.user.login != 'dependabot[bot]' && ! contains(github.event.pull_request.labels.*.name, 'safe-to-test')) ||
|
||||
(github.event_name == 'pull_request_target' && contains(github.event.pull_request.labels.*.name, 'safe-to-test'))
|
||||
uses: signoz/primus.workflows/.github/workflows/js-fmt.yaml@main
|
||||
@@ -61,7 +54,6 @@ jobs:
|
||||
JS_SRC: frontend
|
||||
lint:
|
||||
if: |
|
||||
github.event_name == 'merge_group' ||
|
||||
(github.event_name == 'pull_request' && ! github.event.pull_request.head.repo.fork && github.event.pull_request.user.login != 'dependabot[bot]' && ! contains(github.event.pull_request.labels.*.name, 'safe-to-test')) ||
|
||||
(github.event_name == 'pull_request_target' && contains(github.event.pull_request.labels.*.name, 'safe-to-test'))
|
||||
uses: signoz/primus.workflows/.github/workflows/js-lint.yaml@main
|
||||
@@ -71,7 +63,6 @@ jobs:
|
||||
JS_SRC: frontend
|
||||
md-languages:
|
||||
if: |
|
||||
github.event_name == 'merge_group' ||
|
||||
(github.event_name == 'pull_request' && ! github.event.pull_request.head.repo.fork && github.event.pull_request.user.login != 'dependabot[bot]' && ! contains(github.event.pull_request.labels.*.name, 'safe-to-test')) ||
|
||||
(github.event_name == 'pull_request_target' && contains(github.event.pull_request.labels.*.name, 'safe-to-test'))
|
||||
runs-on: ubuntu-latest
|
||||
@@ -82,7 +73,6 @@ jobs:
|
||||
run: bash frontend/scripts/validate-md-languages.sh
|
||||
authz:
|
||||
if: |
|
||||
github.event_name == 'merge_group' ||
|
||||
(github.event_name == 'pull_request' && ! github.event.pull_request.head.repo.fork && github.event.pull_request.user.login != 'dependabot[bot]' && ! contains(github.event.pull_request.labels.*.name, 'safe-to-test')) ||
|
||||
(github.event_name == 'pull_request_target' && contains(github.event.pull_request.labels.*.name, 'safe-to-test'))
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
@@ -14,6 +14,8 @@ import cx from 'classnames';
|
||||
import { dragColumnParams } from 'hooks/useDragColumns/configs';
|
||||
import { getColumnWidth, RowData } from 'lib/query/createTableColumnsFromQuery';
|
||||
import { debounce, set } from 'lodash-es';
|
||||
import { useDashboard } from 'providers/Dashboard/Dashboard';
|
||||
import { Widgets } from 'types/api/dashboard/getAll';
|
||||
|
||||
import ResizableHeader from './ResizableHeader';
|
||||
import { DragSpanStyle } from './styles';
|
||||
@@ -24,26 +26,31 @@ function ResizeTable({
|
||||
columns,
|
||||
onDragColumn,
|
||||
pagination,
|
||||
columnWidths,
|
||||
onColumnWidthsChange,
|
||||
widgetId,
|
||||
shouldPersistColumnWidths = false,
|
||||
...restProps
|
||||
}: ResizeTableProps): JSX.Element {
|
||||
const [columnsData, setColumns] = useState<ColumnsType>([]);
|
||||
const onColumnWidthsChangeRef = useRef(onColumnWidthsChange);
|
||||
const { setColumnWidths, selectedDashboard } = useDashboard();
|
||||
|
||||
const columnWidths = shouldPersistColumnWidths
|
||||
? (selectedDashboard?.data?.widgets?.find(
|
||||
(widget) => widget.id === widgetId,
|
||||
) as Widgets)?.columnWidths
|
||||
: undefined;
|
||||
|
||||
const updateAllColumnWidths = useRef(
|
||||
debounce((widthsConfig: Record<string, number>) => {
|
||||
if (!onColumnWidthsChangeRef.current) {
|
||||
if (!widgetId || !shouldPersistColumnWidths) {
|
||||
return;
|
||||
}
|
||||
onColumnWidthsChangeRef.current(widthsConfig);
|
||||
setColumnWidths?.((prev) => ({
|
||||
...prev,
|
||||
[widgetId]: widthsConfig,
|
||||
}));
|
||||
}, 1000),
|
||||
).current;
|
||||
|
||||
useEffect(() => {
|
||||
onColumnWidthsChangeRef.current = onColumnWidthsChange;
|
||||
}, [onColumnWidthsChange]);
|
||||
|
||||
const handleResize = useCallback(
|
||||
(index: number) => (
|
||||
e: SyntheticEvent<Element>,
|
||||
@@ -68,7 +75,7 @@ function ResizeTable({
|
||||
...col,
|
||||
...(onDragColumn && {
|
||||
title: (
|
||||
<DragSpanStyle className="dragHandler" data-testid="drag-column-title">
|
||||
<DragSpanStyle className="dragHandler">
|
||||
{col?.title?.toString() || ''}
|
||||
</DragSpanStyle>
|
||||
),
|
||||
@@ -99,31 +106,31 @@ function ResizeTable({
|
||||
}, [mergedColumns, pagination, restProps]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!columns) {
|
||||
return;
|
||||
}
|
||||
|
||||
const columnsWithStoredWidths = columns.map((col) => {
|
||||
const dataIndex = (col as RowData).dataIndex as string;
|
||||
if (dataIndex && columnWidths) {
|
||||
const width = getColumnWidth(dataIndex, columnWidths);
|
||||
if (width) {
|
||||
return { ...col, width };
|
||||
if (columns) {
|
||||
// Apply stored column widths from widget configuration
|
||||
const columnsWithStoredWidths = columns.map((col) => {
|
||||
const dataIndex = (col as RowData).dataIndex as string;
|
||||
if (dataIndex && columnWidths) {
|
||||
const width = getColumnWidth(dataIndex, columnWidths);
|
||||
if (width) {
|
||||
return {
|
||||
...col,
|
||||
width, // Apply stored width
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
return col;
|
||||
});
|
||||
return col;
|
||||
});
|
||||
|
||||
setColumns(columnsWithStoredWidths);
|
||||
setColumns(columnsWithStoredWidths);
|
||||
}
|
||||
}, [columns, columnWidths]);
|
||||
|
||||
const lastReportedWidthsRef = useRef<Record<string, number>>({});
|
||||
|
||||
useEffect(() => {
|
||||
if (!onColumnWidthsChange) {
|
||||
if (!shouldPersistColumnWidths) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Collect all column widths in a single object
|
||||
const newColumnWidths: Record<string, number> = {};
|
||||
|
||||
mergedColumns.forEach((col) => {
|
||||
@@ -133,20 +140,11 @@ function ResizeTable({
|
||||
}
|
||||
});
|
||||
|
||||
if (Object.keys(newColumnWidths).length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const last = lastReportedWidthsRef.current;
|
||||
const hasChange =
|
||||
Object.keys(newColumnWidths).length !== Object.keys(last).length ||
|
||||
Object.keys(newColumnWidths).some((k) => newColumnWidths[k] !== last[k]);
|
||||
|
||||
if (hasChange) {
|
||||
lastReportedWidthsRef.current = newColumnWidths;
|
||||
// Only update if there are actual widths to set
|
||||
if (Object.keys(newColumnWidths).length > 0) {
|
||||
updateAllColumnWidths(newColumnWidths);
|
||||
}
|
||||
}, [mergedColumns, updateAllColumnWidths, onColumnWidthsChange]);
|
||||
}, [mergedColumns, updateAllColumnWidths, shouldPersistColumnWidths]);
|
||||
|
||||
return onDragColumn ? (
|
||||
<ReactDragListView.DragColumn {...dragColumnParams} onDragEnd={onDragColumn}>
|
||||
|
||||
@@ -1,244 +0,0 @@
|
||||
import { act } from '@testing-library/react';
|
||||
import { render, screen, userEvent } from 'tests/test-utils';
|
||||
|
||||
import ResizeTable from '../ResizeTable';
|
||||
|
||||
jest.mock('react-resizable', () => ({
|
||||
Resizable: ({
|
||||
children,
|
||||
onResize,
|
||||
width,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
onResize: (
|
||||
e: React.SyntheticEvent,
|
||||
data: { size: { width: number } },
|
||||
) => void;
|
||||
width: number;
|
||||
}): JSX.Element => (
|
||||
<div>
|
||||
{children}
|
||||
<button
|
||||
data-testid="resize-trigger"
|
||||
type="button"
|
||||
onClick={(e): void => onResize(e, { size: { width: width + 50 } })}
|
||||
/>
|
||||
</div>
|
||||
),
|
||||
}));
|
||||
|
||||
// Make debounce synchronous so onColumnWidthsChange fires immediately
|
||||
jest.mock('lodash-es', () => ({
|
||||
...jest.requireActual('lodash-es'),
|
||||
debounce: (fn: (...args: any[]) => any): ((...args: any[]) => any) => fn,
|
||||
}));
|
||||
|
||||
const baseColumns = [
|
||||
{ dataIndex: 'name', title: 'Name', width: 100 },
|
||||
{ dataIndex: 'value', title: 'Value', width: 100 },
|
||||
];
|
||||
|
||||
const baseDataSource = [
|
||||
{ key: '1', name: 'Alice', value: 42 },
|
||||
{ key: '2', name: 'Bob', value: 99 },
|
||||
];
|
||||
|
||||
describe('ResizeTable', () => {
|
||||
it('renders column headers and data rows', () => {
|
||||
render(
|
||||
<ResizeTable
|
||||
columns={baseColumns}
|
||||
dataSource={baseDataSource}
|
||||
rowKey="key"
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(screen.getByText('Name')).toBeInTheDocument();
|
||||
expect(screen.getByText('Value')).toBeInTheDocument();
|
||||
expect(screen.getByText('Alice')).toBeInTheDocument();
|
||||
expect(screen.getByText('Bob')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('overrides column widths from columnWidths prop and reports them via onColumnWidthsChange', () => {
|
||||
const onColumnWidthsChange = jest.fn();
|
||||
|
||||
act(() => {
|
||||
render(
|
||||
<ResizeTable
|
||||
columns={baseColumns}
|
||||
dataSource={baseDataSource}
|
||||
rowKey="key"
|
||||
columnWidths={{ name: 250, value: 180 }}
|
||||
onColumnWidthsChange={onColumnWidthsChange}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
|
||||
expect(onColumnWidthsChange).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ name: 250, value: 180 }),
|
||||
);
|
||||
});
|
||||
|
||||
it('reports original column widths via onColumnWidthsChange when columnWidths prop is not provided', () => {
|
||||
const onColumnWidthsChange = jest.fn();
|
||||
|
||||
act(() => {
|
||||
render(
|
||||
<ResizeTable
|
||||
columns={baseColumns}
|
||||
dataSource={baseDataSource}
|
||||
rowKey="key"
|
||||
onColumnWidthsChange={onColumnWidthsChange}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
|
||||
expect(onColumnWidthsChange).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ name: 100, value: 100 }),
|
||||
);
|
||||
});
|
||||
|
||||
it('does not call onColumnWidthsChange when it is not provided', () => {
|
||||
// Should render without errors and without attempting to call an undefined callback
|
||||
expect(() => {
|
||||
render(
|
||||
<ResizeTable
|
||||
columns={baseColumns}
|
||||
dataSource={baseDataSource}
|
||||
rowKey="key"
|
||||
/>,
|
||||
);
|
||||
}).not.toThrow();
|
||||
});
|
||||
|
||||
it('only overrides the column that has a stored width, leaving others at their original width', () => {
|
||||
const onColumnWidthsChange = jest.fn();
|
||||
|
||||
act(() => {
|
||||
render(
|
||||
<ResizeTable
|
||||
columns={baseColumns}
|
||||
dataSource={baseDataSource}
|
||||
rowKey="key"
|
||||
columnWidths={{ name: 250 }}
|
||||
onColumnWidthsChange={onColumnWidthsChange}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
|
||||
expect(onColumnWidthsChange).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ name: 250, value: 100 }),
|
||||
);
|
||||
});
|
||||
|
||||
it('does not call onColumnWidthsChange on re-render when widths have not changed', () => {
|
||||
const onColumnWidthsChange = jest.fn();
|
||||
|
||||
const { rerender } = render(
|
||||
<ResizeTable
|
||||
columns={baseColumns}
|
||||
dataSource={baseDataSource}
|
||||
rowKey="key"
|
||||
onColumnWidthsChange={onColumnWidthsChange}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(onColumnWidthsChange).toHaveBeenCalledTimes(1);
|
||||
onColumnWidthsChange.mockClear();
|
||||
|
||||
rerender(
|
||||
<ResizeTable
|
||||
columns={baseColumns}
|
||||
dataSource={baseDataSource}
|
||||
rowKey="key"
|
||||
onColumnWidthsChange={onColumnWidthsChange}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(onColumnWidthsChange).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not call onColumnWidthsChange when no column has a defined width', () => {
|
||||
const onColumnWidthsChange = jest.fn();
|
||||
|
||||
render(
|
||||
<ResizeTable
|
||||
columns={[
|
||||
{ dataIndex: 'name', title: 'Name' },
|
||||
{ dataIndex: 'value', title: 'Value' },
|
||||
]}
|
||||
dataSource={baseDataSource}
|
||||
rowKey="key"
|
||||
onColumnWidthsChange={onColumnWidthsChange}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(onColumnWidthsChange).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('calls onColumnWidthsChange with the new width after a column is resized', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onColumnWidthsChange = jest.fn();
|
||||
|
||||
render(
|
||||
<ResizeTable
|
||||
columns={baseColumns}
|
||||
dataSource={baseDataSource}
|
||||
rowKey="key"
|
||||
onColumnWidthsChange={onColumnWidthsChange}
|
||||
/>,
|
||||
);
|
||||
|
||||
onColumnWidthsChange.mockClear();
|
||||
|
||||
// Click the first column's resize trigger — mock adds 50px to the current width (100 → 150)
|
||||
const [firstResizeTrigger] = screen.getAllByTestId('resize-trigger');
|
||||
await user.click(firstResizeTrigger);
|
||||
|
||||
expect(onColumnWidthsChange).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ name: 150, value: 100 }),
|
||||
);
|
||||
});
|
||||
|
||||
it('does not affect other columns when only one column is resized', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onColumnWidthsChange = jest.fn();
|
||||
|
||||
render(
|
||||
<ResizeTable
|
||||
columns={baseColumns}
|
||||
dataSource={baseDataSource}
|
||||
rowKey="key"
|
||||
onColumnWidthsChange={onColumnWidthsChange}
|
||||
/>,
|
||||
);
|
||||
|
||||
onColumnWidthsChange.mockClear();
|
||||
|
||||
// Resize only the second column (value: 100 → 150), name should stay at 100
|
||||
const resizeTriggers = screen.getAllByTestId('resize-trigger');
|
||||
await user.click(resizeTriggers[1]);
|
||||
|
||||
expect(onColumnWidthsChange).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ name: 100, value: 150 }),
|
||||
);
|
||||
});
|
||||
|
||||
it('wraps column titles in drag handler spans when onDragColumn is provided', () => {
|
||||
const onDragColumn = jest.fn();
|
||||
|
||||
render(
|
||||
<ResizeTable
|
||||
columns={baseColumns}
|
||||
dataSource={baseDataSource}
|
||||
rowKey="key"
|
||||
onDragColumn={onDragColumn}
|
||||
/>,
|
||||
);
|
||||
|
||||
const dragTitles = screen.getAllByTestId('drag-column-title');
|
||||
expect(dragTitles).toHaveLength(baseColumns.length);
|
||||
expect(dragTitles[0]).toHaveTextContent('Name');
|
||||
expect(dragTitles[1]).toHaveTextContent('Value');
|
||||
});
|
||||
});
|
||||
@@ -6,25 +6,10 @@ import { LaunchChatSupportProps } from 'components/LaunchChatSupport/LaunchChatS
|
||||
|
||||
import { TableDataSource } from './contants';
|
||||
|
||||
type ColumnWidths = Record<string, number>;
|
||||
|
||||
export interface ResizeTableProps extends TableProps<any> {
|
||||
onDragColumn?: (fromIndex: number, toIndex: number) => void;
|
||||
/**
|
||||
* Pre-resolved column widths for this table, keyed by column dataIndex.
|
||||
* Use this to apply persisted widths on mount (e.g. from widget.columnWidths).
|
||||
* Do NOT pass a value that updates reactively on every resize — that creates a
|
||||
* feedback loop. Pass only stable / persisted values.
|
||||
*/
|
||||
columnWidths?: ColumnWidths;
|
||||
/**
|
||||
* Called (debounced) whenever the user finishes resizing a column.
|
||||
* The widths object contains all current column widths keyed by dataIndex.
|
||||
* Intended for persisting widths to an external store (e.g. dashboard context
|
||||
* staging buffer). The caller owns the storage; ResizeTable does not read back
|
||||
* whatever is written here.
|
||||
*/
|
||||
onColumnWidthsChange?: (widths: ColumnWidths) => void;
|
||||
widgetId?: string;
|
||||
shouldPersistColumnWidths?: boolean;
|
||||
}
|
||||
export interface DynamicColumnTableProps extends TableProps<any> {
|
||||
tablesource: typeof TableDataSource[keyof typeof TableDataSource];
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
.timeline-v3-container {
|
||||
// flex: 1;
|
||||
overflow: visible;
|
||||
}
|
||||
87
frontend/src/components/TimelineV3/TimelineV3.tsx
Normal file
87
frontend/src/components/TimelineV3/TimelineV3.tsx
Normal file
@@ -0,0 +1,87 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useMeasure } from 'react-use';
|
||||
import { useIsDarkMode } from 'hooks/useDarkMode';
|
||||
|
||||
import {
|
||||
getIntervals,
|
||||
getMinimumIntervalsBasedOnWidth,
|
||||
Interval,
|
||||
} from './utils';
|
||||
|
||||
import './TimelineV3.styles.scss';
|
||||
|
||||
interface ITimelineV3Props {
|
||||
startTimestamp: number;
|
||||
endTimestamp: number;
|
||||
timelineHeight: number;
|
||||
offsetTimestamp: number;
|
||||
}
|
||||
|
||||
function TimelineV3(props: ITimelineV3Props): JSX.Element {
|
||||
const {
|
||||
startTimestamp,
|
||||
endTimestamp,
|
||||
timelineHeight,
|
||||
offsetTimestamp,
|
||||
} = props;
|
||||
const [intervals, setIntervals] = useState<Interval[]>([]);
|
||||
const [ref, { width }] = useMeasure<HTMLDivElement>();
|
||||
const isDarkMode = useIsDarkMode();
|
||||
|
||||
useEffect(() => {
|
||||
const spread = endTimestamp - startTimestamp;
|
||||
if (spread < 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const minIntervals = getMinimumIntervalsBasedOnWidth(width);
|
||||
const intervalisedSpread = (spread / minIntervals) * 1.0;
|
||||
const intervals = getIntervals(intervalisedSpread, spread, offsetTimestamp);
|
||||
|
||||
setIntervals(intervals);
|
||||
}, [startTimestamp, endTimestamp, width, offsetTimestamp]);
|
||||
|
||||
if (endTimestamp < startTimestamp) {
|
||||
console.error(
|
||||
'endTimestamp cannot be less than startTimestamp',
|
||||
startTimestamp,
|
||||
endTimestamp,
|
||||
);
|
||||
return <div />;
|
||||
}
|
||||
|
||||
const strokeColor = isDarkMode ? ' rgb(192,193,195,0.8)' : 'black';
|
||||
|
||||
return (
|
||||
<div ref={ref as never} className="timeline-v3-container">
|
||||
<svg
|
||||
width={width}
|
||||
height={timelineHeight * 2.5}
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
overflow="visible"
|
||||
>
|
||||
{intervals &&
|
||||
intervals.length > 0 &&
|
||||
intervals.map((interval, index) => (
|
||||
<g
|
||||
transform={`translate(${(interval.percentage * width) / 100},0)`}
|
||||
key={`${interval.percentage + interval.label + index}`}
|
||||
textAnchor="middle"
|
||||
fontSize="0.6rem"
|
||||
>
|
||||
<text
|
||||
x={index === intervals.length - 1 ? -10 : 0}
|
||||
y={timelineHeight * 2}
|
||||
fill={strokeColor}
|
||||
>
|
||||
{interval.label}
|
||||
</text>
|
||||
<line y1={0} y2={timelineHeight} stroke={strokeColor} strokeWidth="1" />
|
||||
</g>
|
||||
))}
|
||||
</svg>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default TimelineV3;
|
||||
93
frontend/src/components/TimelineV3/utils.ts
Normal file
93
frontend/src/components/TimelineV3/utils.ts
Normal file
@@ -0,0 +1,93 @@
|
||||
import {
|
||||
IIntervalUnit,
|
||||
Interval,
|
||||
INTERVAL_UNITS,
|
||||
resolveTimeFromInterval,
|
||||
} from 'components/TimelineV2/utils';
|
||||
import { toFixed } from 'utils/toFixed';
|
||||
|
||||
export type { Interval };
|
||||
|
||||
/** Fewer intervals than TimelineV2 for a cleaner flamegraph ruler. */
|
||||
export function getMinimumIntervalsBasedOnWidth(width: number): number {
|
||||
if (width < 640) {
|
||||
return 3;
|
||||
}
|
||||
if (width < 768) {
|
||||
return 4;
|
||||
}
|
||||
if (width < 1024) {
|
||||
return 5;
|
||||
}
|
||||
return 6;
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes timeline intervals with offset-aware labels.
|
||||
* Labels reflect absolute time from trace start (offsetTimestamp + elapsed),
|
||||
* so when zoomed into a window, the first tick shows e.g. "50ms" not "0ms".
|
||||
*/
|
||||
export function getIntervals(
|
||||
intervalSpread: number,
|
||||
baseSpread: number,
|
||||
offsetTimestamp: number,
|
||||
): Interval[] {
|
||||
const integerPartString = intervalSpread.toString().split('.')[0];
|
||||
const integerPartLength = integerPartString.length;
|
||||
|
||||
const intervalSpreadNormalized =
|
||||
intervalSpread < 1.0
|
||||
? intervalSpread
|
||||
: Math.floor(Number(integerPartString) / 10 ** (integerPartLength - 1)) *
|
||||
10 ** (integerPartLength - 1);
|
||||
|
||||
// Unit must suit both: (1) tick granularity (intervalSpread) and (2) label magnitude
|
||||
// (offsetTimestamp). When zoomed deep into a trace, labels show offsetTimestamp + elapsed,
|
||||
// so we must pick a unit where that value is readable (e.g. "500.00s" not "500000.00ms").
|
||||
const valueForUnitSelection = Math.max(offsetTimestamp, intervalSpread);
|
||||
let intervalUnit: IIntervalUnit = INTERVAL_UNITS[0];
|
||||
for (let idx = INTERVAL_UNITS.length - 1; idx >= 0; idx -= 1) {
|
||||
const standardInterval = INTERVAL_UNITS[idx];
|
||||
if (valueForUnitSelection * standardInterval.multiplier >= 1) {
|
||||
intervalUnit = INTERVAL_UNITS[idx];
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const intervals: Interval[] = [
|
||||
{
|
||||
label: `${toFixed(
|
||||
resolveTimeFromInterval(offsetTimestamp, intervalUnit),
|
||||
2,
|
||||
)}${intervalUnit.name}`,
|
||||
percentage: 0,
|
||||
},
|
||||
];
|
||||
|
||||
let tempBaseSpread = baseSpread;
|
||||
let elapsedIntervals = 0;
|
||||
|
||||
while (tempBaseSpread && intervals.length < 20) {
|
||||
let intervalTime: number;
|
||||
|
||||
if (tempBaseSpread <= 1.5 * intervalSpreadNormalized) {
|
||||
intervalTime = elapsedIntervals + tempBaseSpread;
|
||||
tempBaseSpread = 0;
|
||||
} else {
|
||||
intervalTime = elapsedIntervals + intervalSpreadNormalized;
|
||||
tempBaseSpread -= intervalSpreadNormalized;
|
||||
}
|
||||
|
||||
elapsedIntervals = intervalTime;
|
||||
const labelTime = offsetTimestamp + intervalTime;
|
||||
|
||||
intervals.push({
|
||||
label: `${toFixed(resolveTimeFromInterval(labelTime, intervalUnit), 2)}${
|
||||
intervalUnit.name
|
||||
}`,
|
||||
percentage: (intervalTime / baseSpread) * 100,
|
||||
});
|
||||
}
|
||||
|
||||
return intervals;
|
||||
}
|
||||
@@ -81,18 +81,7 @@ function FullView({
|
||||
setCurrentGraphRef(fullViewRef);
|
||||
}, [setCurrentGraphRef]);
|
||||
|
||||
const {
|
||||
selectedDashboard,
|
||||
isDashboardLocked,
|
||||
setColumnWidths,
|
||||
} = useDashboard();
|
||||
|
||||
const onColumnWidthsChange = useCallback(
|
||||
(widths: Record<string, number>) => {
|
||||
setColumnWidths((prev) => ({ ...prev, [widget.id]: widths }));
|
||||
},
|
||||
[setColumnWidths, widget.id],
|
||||
);
|
||||
const { selectedDashboard, isDashboardLocked } = useDashboard();
|
||||
const { dashboardVariables } = useDashboardVariables();
|
||||
const { user } = useAppContext();
|
||||
|
||||
@@ -392,7 +381,6 @@ function FullView({
|
||||
onClickHandler={onClickHandler}
|
||||
enableDrillDown={enableDrillDown}
|
||||
selectedGraph={selectedPanelType}
|
||||
onColumnWidthsChange={onColumnWidthsChange}
|
||||
/>
|
||||
</GraphContainer>
|
||||
</div>
|
||||
|
||||
@@ -168,9 +168,6 @@ jest.mock('providers/Dashboard/Dashboard', () => ({
|
||||
variables: [],
|
||||
},
|
||||
},
|
||||
setLayouts: jest.fn(),
|
||||
setSelectedDashboard: jest.fn(),
|
||||
setColumnWidths: jest.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
|
||||
@@ -101,19 +101,7 @@ function WidgetGraphComponent({
|
||||
|
||||
const navigateToExplorerPages = useNavigateToExplorerPages();
|
||||
|
||||
const {
|
||||
setLayouts,
|
||||
selectedDashboard,
|
||||
setSelectedDashboard,
|
||||
setColumnWidths,
|
||||
} = useDashboard();
|
||||
|
||||
const onColumnWidthsChange = useCallback(
|
||||
(widths: Record<string, number>) => {
|
||||
setColumnWidths((prev) => ({ ...prev, [widget.id]: widths }));
|
||||
},
|
||||
[setColumnWidths, widget.id],
|
||||
);
|
||||
const { setLayouts, selectedDashboard, setSelectedDashboard } = useDashboard();
|
||||
|
||||
const onToggleModal = useCallback(
|
||||
(func: Dispatch<SetStateAction<boolean>>) => {
|
||||
@@ -436,7 +424,6 @@ function WidgetGraphComponent({
|
||||
customSeries={customSeries}
|
||||
customOnRowClick={customOnRowClick}
|
||||
enableDrillDown={enableDrillDown}
|
||||
onColumnWidthsChange={onColumnWidthsChange}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -45,8 +45,6 @@ function GridTableComponent({
|
||||
onOpenTraceBtnClick,
|
||||
customOnRowClick,
|
||||
widgetId,
|
||||
columnWidths,
|
||||
onColumnWidthsChange,
|
||||
panelType,
|
||||
queryRangeRequest,
|
||||
decimalPrecision,
|
||||
@@ -286,8 +284,6 @@ function GridTableComponent({
|
||||
dataSource={dataSource}
|
||||
sticky={sticky}
|
||||
widgetId={widgetId}
|
||||
columnWidths={columnWidths}
|
||||
onColumnWidthsChange={onColumnWidthsChange}
|
||||
panelType={panelType}
|
||||
queryRangeRequest={queryRangeRequest}
|
||||
onRow={
|
||||
|
||||
@@ -24,8 +24,6 @@ export type GridTableComponentProps = {
|
||||
onOpenTraceBtnClick?: (record: RowData) => void;
|
||||
customOnRowClick?: (record: RowData) => void;
|
||||
widgetId?: string;
|
||||
columnWidths?: Record<string, number>;
|
||||
onColumnWidthsChange?: (widths: Record<string, number>) => void;
|
||||
renderColumnCell?: QueryTableProps['renderColumnCell'];
|
||||
customColTitles?: Record<string, string>;
|
||||
enableDrillDown?: boolean;
|
||||
|
||||
@@ -33,7 +33,6 @@ function LogsPanelComponent({
|
||||
widget,
|
||||
setRequestData,
|
||||
queryResponse,
|
||||
onColumnWidthsChange,
|
||||
}: LogsPanelComponentProps): JSX.Element {
|
||||
const [pageSize, setPageSize] = useState<number>(10);
|
||||
const [offset, setOffset] = useState<number>(0);
|
||||
@@ -146,8 +145,8 @@ function LogsPanelComponent({
|
||||
columns={columns}
|
||||
onRow={handleRow}
|
||||
rowKey={(record): string => record.id}
|
||||
columnWidths={widget.columnWidths}
|
||||
onColumnWidthsChange={onColumnWidthsChange}
|
||||
widgetId={widget.id}
|
||||
shouldPersistColumnWidths
|
||||
/>
|
||||
</OverlayScrollbar>
|
||||
</div>
|
||||
@@ -190,7 +189,6 @@ export type LogsPanelComponentProps = {
|
||||
Error
|
||||
>;
|
||||
widget: Widgets;
|
||||
onColumnWidthsChange?: (widths: Record<string, number>) => void;
|
||||
};
|
||||
|
||||
export default LogsPanelComponent;
|
||||
|
||||
@@ -8,7 +8,6 @@ function ListPanelWrapper({
|
||||
widget,
|
||||
queryResponse,
|
||||
setRequestData,
|
||||
onColumnWidthsChange,
|
||||
}: PanelWrapperProps): JSX.Element {
|
||||
const dataSource = widget.query.builder?.queryData[0]?.dataSource;
|
||||
|
||||
@@ -22,7 +21,6 @@ function ListPanelWrapper({
|
||||
widget={widget}
|
||||
queryResponse={queryResponse}
|
||||
setRequestData={setRequestData}
|
||||
onColumnWidthsChange={onColumnWidthsChange}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -31,7 +29,6 @@ function ListPanelWrapper({
|
||||
widget={widget}
|
||||
queryResponse={queryResponse}
|
||||
setRequestData={setRequestData}
|
||||
onColumnWidthsChange={onColumnWidthsChange}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -24,7 +24,6 @@ function PanelWrapper({
|
||||
customOnRowClick,
|
||||
panelMode,
|
||||
enableDrillDown = false,
|
||||
onColumnWidthsChange,
|
||||
}: PanelWrapperProps): JSX.Element {
|
||||
const Component = PanelTypeVsPanelWrapper[
|
||||
selectedGraph || widget.panelTypes
|
||||
@@ -59,7 +58,6 @@ function PanelWrapper({
|
||||
customOnRowClick={customOnRowClick}
|
||||
customSeries={customSeries}
|
||||
enableDrillDown={enableDrillDown}
|
||||
onColumnWidthsChange={onColumnWidthsChange}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -14,7 +14,6 @@ function TablePanelWrapper({
|
||||
onOpenTraceBtnClick,
|
||||
customOnRowClick,
|
||||
enableDrillDown = false,
|
||||
onColumnWidthsChange,
|
||||
}: PanelWrapperProps): JSX.Element {
|
||||
const panelData =
|
||||
(queryResponse.data?.payload?.data?.result?.[0] as any)?.table || [];
|
||||
@@ -35,8 +34,6 @@ function TablePanelWrapper({
|
||||
onOpenTraceBtnClick={onOpenTraceBtnClick}
|
||||
customOnRowClick={customOnRowClick}
|
||||
widgetId={widget.id}
|
||||
columnWidths={widget.columnWidths}
|
||||
onColumnWidthsChange={onColumnWidthsChange}
|
||||
renderColumnCell={widget.renderColumnCell}
|
||||
customColTitles={widget.customColTitles}
|
||||
contextLinks={widget.contextLinks}
|
||||
|
||||
@@ -29,7 +29,6 @@ export type PanelWrapperProps = {
|
||||
customSeries?: (data: QueryData[]) => uPlot.Series[];
|
||||
enableDrillDown?: boolean;
|
||||
panelMode: PanelMode;
|
||||
onColumnWidthsChange?: (widths: Record<string, number>) => void;
|
||||
};
|
||||
|
||||
export type TooltipData = {
|
||||
|
||||
@@ -24,8 +24,6 @@ export type QueryTableProps = Omit<
|
||||
sticky?: TableProps<RowData>['sticky'];
|
||||
searchTerm?: string;
|
||||
widgetId?: string;
|
||||
columnWidths?: Record<string, number>;
|
||||
onColumnWidthsChange?: (widths: Record<string, number>) => void;
|
||||
enableDrillDown?: boolean;
|
||||
contextLinks?: ContextLinksData;
|
||||
panelType?: PANEL_TYPES;
|
||||
|
||||
@@ -28,8 +28,6 @@ export function QueryTable({
|
||||
sticky,
|
||||
searchTerm,
|
||||
widgetId,
|
||||
columnWidths,
|
||||
onColumnWidthsChange,
|
||||
panelType,
|
||||
...props
|
||||
}: QueryTableProps): JSX.Element {
|
||||
@@ -177,8 +175,8 @@ export function QueryTable({
|
||||
dataSource={filterTable === null ? newDataSource : filterTable}
|
||||
scroll={{ x: 'max-content' }}
|
||||
pagination={paginationConfig}
|
||||
columnWidths={columnWidths}
|
||||
onColumnWidthsChange={onColumnWidthsChange}
|
||||
widgetId={widgetId}
|
||||
shouldPersistColumnWidths
|
||||
sticky={sticky}
|
||||
{...props}
|
||||
/>
|
||||
|
||||
@@ -35,7 +35,6 @@ function TracesTableComponent({
|
||||
widget,
|
||||
queryResponse,
|
||||
setRequestData,
|
||||
onColumnWidthsChange,
|
||||
}: TracesTableComponentProps): JSX.Element {
|
||||
const [pagination, setPagination] = useState<Pagination>({
|
||||
offset: 0,
|
||||
@@ -132,8 +131,8 @@ function TracesTableComponent({
|
||||
columns={columns}
|
||||
onRow={handleRow}
|
||||
sticky
|
||||
columnWidths={widget.columnWidths}
|
||||
onColumnWidthsChange={onColumnWidthsChange}
|
||||
widgetId={widget.id}
|
||||
shouldPersistColumnWidths
|
||||
/>
|
||||
</OverlayScrollbar>
|
||||
</div>
|
||||
@@ -176,7 +175,6 @@ export type TracesTableComponentProps = {
|
||||
>;
|
||||
widget: Widgets;
|
||||
setRequestData: Dispatch<SetStateAction<GetQueryResultsProps>>;
|
||||
onColumnWidthsChange?: (widths: Record<string, number>) => void;
|
||||
};
|
||||
|
||||
export default TracesTableComponent;
|
||||
|
||||
@@ -4,19 +4,11 @@ import ROUTES from 'constants/routes';
|
||||
import history from 'lib/history';
|
||||
import { Compass, Cone, TowerControl } from 'lucide-react';
|
||||
|
||||
import TraceDetailsV2 from './TraceDetailV2';
|
||||
import TraceDetailsV3 from '../TraceDetailsV3';
|
||||
|
||||
import './TraceDetailV2.styles.scss';
|
||||
|
||||
interface INewTraceDetailProps {
|
||||
items: {
|
||||
label: JSX.Element;
|
||||
key: string;
|
||||
children: JSX.Element;
|
||||
}[];
|
||||
}
|
||||
|
||||
function NewTraceDetail(props: INewTraceDetailProps): JSX.Element {
|
||||
function NewTraceDetail(props: any): JSX.Element {
|
||||
const { items } = props;
|
||||
return (
|
||||
<div className="traces-module-container">
|
||||
@@ -50,7 +42,7 @@ export default function TraceDetailsPage(): JSX.Element {
|
||||
</div>
|
||||
),
|
||||
key: 'trace-details',
|
||||
children: <TraceDetailsV2 />,
|
||||
children: <TraceDetailsV3 />,
|
||||
},
|
||||
{
|
||||
label: (
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
.trace-details-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding: 0px 16px;
|
||||
|
||||
.previous-btn {
|
||||
display: flex;
|
||||
height: 30px;
|
||||
padding: 6px 8px;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
border: 1px solid var(--bg-slate-300);
|
||||
background: var(--bg-slate-500);
|
||||
border-radius: 4px;
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
.trace-name {
|
||||
display: flex;
|
||||
padding: 6px 8px;
|
||||
margin-left: 6px;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
border: 1px solid var(--bg-slate-300);
|
||||
border-radius: 4px 0px 0px 4px;
|
||||
background: var(--bg-slate-500);
|
||||
|
||||
.drafting {
|
||||
color: white;
|
||||
}
|
||||
|
||||
.trace-id {
|
||||
color: #fff;
|
||||
font-family: Inter;
|
||||
font-size: 13px;
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
line-height: 18px;
|
||||
letter-spacing: -0.07px;
|
||||
}
|
||||
}
|
||||
|
||||
.trace-id-value {
|
||||
display: flex;
|
||||
padding: 6px 8px;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
background: var(--bg-slate-400);
|
||||
color: var(--Vanilla-400, #c0c1c3);
|
||||
font-family: Inter;
|
||||
font-size: 13px;
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
line-height: 18px;
|
||||
letter-spacing: -0.07px;
|
||||
border: 1px solid var(--bg-slate-300);
|
||||
border-left: unset;
|
||||
border-radius: 0px 4px 4px 0px;
|
||||
}
|
||||
}
|
||||
|
||||
.lightMode {
|
||||
.trace-details-header {
|
||||
.previous-btn {
|
||||
border: 1px solid var(--bg-vanilla-300);
|
||||
background: var(--bg-vanilla-200);
|
||||
}
|
||||
|
||||
.trace-name {
|
||||
border: 1px solid var(--bg-vanilla-300);
|
||||
background: var(--bg-vanilla-200);
|
||||
border-right: none;
|
||||
|
||||
.drafting {
|
||||
color: var(--bg-ink-100);
|
||||
}
|
||||
|
||||
.trace-id {
|
||||
color: var(--bg-ink-100);
|
||||
}
|
||||
}
|
||||
|
||||
.trace-id-value {
|
||||
background: var(--bg-vanilla-300);
|
||||
color: var(--bg-ink-400);
|
||||
border: 1px solid var(--bg-vanilla-300);
|
||||
}
|
||||
}
|
||||
}
|
||||
// TODO: move to new css module name system
|
||||
@@ -0,0 +1,38 @@
|
||||
import { useCallback } from 'react';
|
||||
import { useParams } from 'react-router-dom';
|
||||
import { Button, Typography } from 'antd';
|
||||
import ROUTES from 'constants/routes';
|
||||
import history from 'lib/history';
|
||||
import { ArrowLeft } from 'lucide-react';
|
||||
import { TraceDetailV2URLProps } from 'types/api/trace/getTraceV2';
|
||||
|
||||
import './TraceDetailsHeader.styles.scss';
|
||||
|
||||
function TraceDetailsHeader(): JSX.Element {
|
||||
const { id: traceID } = useParams<TraceDetailV2URLProps>();
|
||||
|
||||
const handlePreviousBtnClick = useCallback((): void => {
|
||||
const isSpaNavigate =
|
||||
document.referrer &&
|
||||
new URL(document.referrer).origin === window.location.origin;
|
||||
if (isSpaNavigate) {
|
||||
history.goBack();
|
||||
} else {
|
||||
history.push(ROUTES.TRACES_EXPLORER);
|
||||
}
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="trace-details-header">
|
||||
<Button className="previous-btn" onClick={handlePreviousBtnClick}>
|
||||
<ArrowLeft size={14} />
|
||||
</Button>
|
||||
<div className="trace-name">
|
||||
<Typography.Text className="trace-id">Trace ID</Typography.Text>
|
||||
</div>
|
||||
<Typography.Text className="trace-id-value">{traceID}</Typography.Text>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default TraceDetailsHeader;
|
||||
@@ -0,0 +1,237 @@
|
||||
import React, { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import TimelineV3 from 'components/TimelineV3/TimelineV3';
|
||||
import { useIsDarkMode } from 'hooks/useDarkMode';
|
||||
|
||||
import { DEFAULT_ROW_HEIGHT } from './constants';
|
||||
import { useCanvasSetup } from './hooks/useCanvasSetup';
|
||||
import { useFlamegraphDrag } from './hooks/useFlamegraphDrag';
|
||||
import { useFlamegraphDraw } from './hooks/useFlamegraphDraw';
|
||||
import { useFlamegraphHover } from './hooks/useFlamegraphHover';
|
||||
import { useFlamegraphZoom } from './hooks/useFlamegraphZoom';
|
||||
import { useScrollToSpan } from './hooks/useScrollToSpan';
|
||||
import { FlamegraphCanvasProps, SpanRect } from './types';
|
||||
import { formatDuration } from './utils';
|
||||
|
||||
function FlamegraphCanvas(props: FlamegraphCanvasProps): JSX.Element {
|
||||
const { spans, traceMetadata, firstSpanAtFetchLevel, onSpanClick } = props;
|
||||
|
||||
const isDarkMode = useIsDarkMode(); //TODO: see if can be removed or use a new hook
|
||||
const canvasRef = useRef<HTMLCanvasElement>(null);
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const spanRectsRef = useRef<SpanRect[]>([]);
|
||||
|
||||
const [viewStartTs, setViewStartTs] = useState<number>(
|
||||
traceMetadata.startTime,
|
||||
);
|
||||
const [viewEndTs, setViewEndTs] = useState<number>(traceMetadata.endTime);
|
||||
const [scrollTop, setScrollTop] = useState<number>(0);
|
||||
const [rowHeight, setRowHeight] = useState<number>(DEFAULT_ROW_HEIGHT);
|
||||
|
||||
// Mutable refs for zoom and drag hooks to read during rAF / mouse callbacks
|
||||
const viewStartRef = useRef(viewStartTs);
|
||||
const viewEndRef = useRef(viewEndTs);
|
||||
const rowHeightRef = useRef(rowHeight);
|
||||
const scrollTopRef = useRef(scrollTop);
|
||||
|
||||
useEffect(() => {
|
||||
viewStartRef.current = viewStartTs;
|
||||
}, [viewStartTs]);
|
||||
|
||||
useEffect(() => {
|
||||
viewEndRef.current = viewEndTs;
|
||||
}, [viewEndTs]);
|
||||
|
||||
useEffect(() => {
|
||||
rowHeightRef.current = rowHeight;
|
||||
}, [rowHeight]);
|
||||
|
||||
useEffect(() => {
|
||||
scrollTopRef.current = scrollTop;
|
||||
}, [scrollTop]);
|
||||
|
||||
useEffect(() => {
|
||||
//TODO: see if this can be removed as once loaded the view start and end ts will not change
|
||||
setViewStartTs(traceMetadata.startTime);
|
||||
setViewEndTs(traceMetadata.endTime);
|
||||
viewStartRef.current = traceMetadata.startTime;
|
||||
viewEndRef.current = traceMetadata.endTime;
|
||||
}, [traceMetadata.startTime, traceMetadata.endTime]);
|
||||
|
||||
const totalHeight = spans.length * rowHeight;
|
||||
|
||||
const { isOverFlamegraphRef } = useFlamegraphZoom({
|
||||
canvasRef,
|
||||
traceMetadata,
|
||||
viewStartRef,
|
||||
viewEndRef,
|
||||
rowHeightRef,
|
||||
setViewStartTs,
|
||||
setViewEndTs,
|
||||
setRowHeight,
|
||||
});
|
||||
|
||||
const {
|
||||
handleMouseDown,
|
||||
handleMouseMove: handleDragMouseMove,
|
||||
handleMouseUp,
|
||||
handleDragMouseLeave,
|
||||
suppressClickRef,
|
||||
isDraggingRef,
|
||||
} = useFlamegraphDrag({
|
||||
canvasRef,
|
||||
containerRef,
|
||||
traceMetadata,
|
||||
viewStartRef,
|
||||
viewEndRef,
|
||||
setViewStartTs,
|
||||
setViewEndTs,
|
||||
scrollTopRef,
|
||||
setScrollTop,
|
||||
totalHeight,
|
||||
});
|
||||
|
||||
const {
|
||||
hoveredSpanId,
|
||||
handleHoverMouseMove,
|
||||
handleHoverMouseLeave,
|
||||
handleClick,
|
||||
tooltipContent,
|
||||
} = useFlamegraphHover({
|
||||
canvasRef,
|
||||
spanRectsRef,
|
||||
traceMetadata,
|
||||
viewStartTs,
|
||||
viewEndTs,
|
||||
isDraggingRef,
|
||||
suppressClickRef,
|
||||
onSpanClick,
|
||||
isDarkMode,
|
||||
});
|
||||
|
||||
const { drawFlamegraph } = useFlamegraphDraw({
|
||||
canvasRef,
|
||||
containerRef,
|
||||
spans,
|
||||
viewStartTs,
|
||||
viewEndTs,
|
||||
scrollTop,
|
||||
rowHeight,
|
||||
selectedSpanId: firstSpanAtFetchLevel || undefined,
|
||||
hoveredSpanId: hoveredSpanId ?? '',
|
||||
isDarkMode,
|
||||
spanRectsRef,
|
||||
});
|
||||
|
||||
useScrollToSpan({
|
||||
firstSpanAtFetchLevel,
|
||||
spans,
|
||||
traceMetadata,
|
||||
containerRef,
|
||||
viewStartRef,
|
||||
viewEndRef,
|
||||
scrollTopRef,
|
||||
rowHeight,
|
||||
setViewStartTs,
|
||||
setViewEndTs,
|
||||
setScrollTop,
|
||||
});
|
||||
|
||||
useCanvasSetup(canvasRef, containerRef, drawFlamegraph);
|
||||
|
||||
const handleMouseMove = useCallback(
|
||||
(e: React.MouseEvent): void => {
|
||||
handleDragMouseMove(e);
|
||||
handleHoverMouseMove(e);
|
||||
},
|
||||
[handleDragMouseMove, handleHoverMouseMove],
|
||||
);
|
||||
|
||||
const handleMouseLeave = useCallback((): void => {
|
||||
isOverFlamegraphRef.current = false;
|
||||
handleDragMouseLeave();
|
||||
handleHoverMouseLeave();
|
||||
}, [isOverFlamegraphRef, handleDragMouseLeave, handleHoverMouseLeave]);
|
||||
|
||||
// todo: move to a separate component/utils file
|
||||
const tooltipElement = tooltipContent
|
||||
? createPortal(
|
||||
<div
|
||||
style={{
|
||||
position: 'fixed',
|
||||
left: Math.min(tooltipContent.clientX + 15, window.innerWidth - 220),
|
||||
top: Math.min(tooltipContent.clientY + 15, window.innerHeight - 100),
|
||||
zIndex: 1000,
|
||||
backgroundColor: 'rgba(30, 30, 30, 0.95)',
|
||||
color: '#fff',
|
||||
padding: '8px 12px',
|
||||
borderRadius: 4,
|
||||
fontSize: 12,
|
||||
fontFamily: 'Inter, sans-serif',
|
||||
boxShadow: '0 2px 8px rgba(0,0,0,0.3)',
|
||||
pointerEvents: 'none',
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
fontWeight: 600,
|
||||
marginBottom: 4,
|
||||
color: tooltipContent.spanColor,
|
||||
}}
|
||||
>
|
||||
{tooltipContent.spanName}
|
||||
</div>
|
||||
<div>Status: {tooltipContent.status}</div>
|
||||
<div>Start: {tooltipContent.startMs.toFixed(2)} ms</div>
|
||||
<div>Duration: {formatDuration(tooltipContent.durationMs * 1e6)}</div>
|
||||
</div>,
|
||||
document.body,
|
||||
)
|
||||
: null;
|
||||
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
height: '100%',
|
||||
padding: '0 15px',
|
||||
}}
|
||||
>
|
||||
{tooltipElement}
|
||||
<TimelineV3
|
||||
startTimestamp={viewStartTs}
|
||||
endTimestamp={viewEndTs}
|
||||
offsetTimestamp={viewStartTs - traceMetadata.startTime}
|
||||
timelineHeight={10}
|
||||
/>
|
||||
<div
|
||||
ref={containerRef}
|
||||
style={{
|
||||
flex: 1,
|
||||
overflow: 'hidden',
|
||||
position: 'relative',
|
||||
}}
|
||||
onMouseEnter={(): void => {
|
||||
isOverFlamegraphRef.current = true;
|
||||
}}
|
||||
onMouseLeave={handleMouseLeave}
|
||||
>
|
||||
<canvas
|
||||
ref={canvasRef}
|
||||
style={{
|
||||
display: 'block',
|
||||
width: '100%',
|
||||
cursor: 'grab',
|
||||
}}
|
||||
onMouseDown={handleMouseDown}
|
||||
onMouseMove={handleMouseMove}
|
||||
onMouseUp={handleMouseUp}
|
||||
onClick={handleClick}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default FlamegraphCanvas;
|
||||
@@ -0,0 +1,118 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { useHistory, useLocation, useParams } from 'react-router-dom';
|
||||
import useGetTraceFlamegraph from 'hooks/trace/useGetTraceFlamegraph';
|
||||
import useUrlQuery from 'hooks/useUrlQuery';
|
||||
import { TraceDetailFlamegraphURLProps } from 'types/api/trace/getTraceFlamegraph';
|
||||
import { Span } from 'types/api/trace/getTraceV2';
|
||||
|
||||
import FlamegraphCanvas from './FlamegraphCanvas';
|
||||
|
||||
//TODO: analyse if this is needed or not and move to separate file if needed else delete this enum.
|
||||
enum TraceFlamegraphState {
|
||||
LOADING = 'LOADING',
|
||||
SUCCESS = 'SUCCESS',
|
||||
NO_DATA = 'NO_DATA',
|
||||
ERROR = 'ERROR',
|
||||
FETCHING_WITH_OLD_DATA = 'FETCHING_WITH_OLD_DATA',
|
||||
}
|
||||
|
||||
interface TraceFlamegraphProps {
|
||||
serviceExecTime: Record<string, number>;
|
||||
startTime: number;
|
||||
endTime: number;
|
||||
selectedSpan: Span | undefined;
|
||||
}
|
||||
|
||||
function TraceFlamegraph(props: TraceFlamegraphProps): JSX.Element {
|
||||
const { selectedSpan } = props;
|
||||
const { id: traceId } = useParams<TraceDetailFlamegraphURLProps>();
|
||||
const urlQuery = useUrlQuery();
|
||||
const history = useHistory();
|
||||
const { search } = useLocation();
|
||||
const [firstSpanAtFetchLevel, setFirstSpanAtFetchLevel] = useState<string>(
|
||||
urlQuery.get('spanId') || '',
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
setFirstSpanAtFetchLevel(urlQuery.get('spanId') || '');
|
||||
}, [urlQuery]);
|
||||
|
||||
const handleSpanClick = useCallback(
|
||||
(spanId: string): void => {
|
||||
setFirstSpanAtFetchLevel(spanId);
|
||||
const searchParams = new URLSearchParams(search);
|
||||
//tood: use from query params constants
|
||||
if (searchParams.get('spanId') !== spanId) {
|
||||
searchParams.set('spanId', spanId);
|
||||
history.replace({ search: searchParams.toString() });
|
||||
}
|
||||
},
|
||||
[history, search],
|
||||
);
|
||||
|
||||
const { data, isFetching, error } = useGetTraceFlamegraph({
|
||||
traceId,
|
||||
selectedSpanId: firstSpanAtFetchLevel,
|
||||
});
|
||||
|
||||
const flamegraphState = useMemo(() => {
|
||||
if (isFetching) {
|
||||
if (data?.payload?.spans && data.payload.spans.length > 0) {
|
||||
return TraceFlamegraphState.FETCHING_WITH_OLD_DATA;
|
||||
}
|
||||
return TraceFlamegraphState.LOADING;
|
||||
}
|
||||
if (error) {
|
||||
return TraceFlamegraphState.ERROR;
|
||||
}
|
||||
if (data?.payload?.spans && data.payload.spans.length === 0) {
|
||||
return TraceFlamegraphState.NO_DATA;
|
||||
}
|
||||
return TraceFlamegraphState.SUCCESS;
|
||||
}, [error, isFetching, data]);
|
||||
|
||||
const spans = useMemo(() => data?.payload?.spans || [], [
|
||||
data?.payload?.spans,
|
||||
]);
|
||||
|
||||
const content = useMemo(() => {
|
||||
switch (flamegraphState) {
|
||||
case TraceFlamegraphState.LOADING:
|
||||
return <div>Loading...</div>;
|
||||
case TraceFlamegraphState.ERROR:
|
||||
return <div>Error loading flamegraph</div>;
|
||||
case TraceFlamegraphState.NO_DATA:
|
||||
return <div>No data found for trace {traceId}</div>;
|
||||
case TraceFlamegraphState.SUCCESS:
|
||||
case TraceFlamegraphState.FETCHING_WITH_OLD_DATA:
|
||||
return (
|
||||
<FlamegraphCanvas
|
||||
spans={spans}
|
||||
firstSpanAtFetchLevel={firstSpanAtFetchLevel}
|
||||
setFirstSpanAtFetchLevel={setFirstSpanAtFetchLevel}
|
||||
onSpanClick={handleSpanClick}
|
||||
traceMetadata={{
|
||||
startTime: data?.payload?.startTimestampMillis || 0,
|
||||
endTime: data?.payload?.endTimestampMillis || 0,
|
||||
}}
|
||||
selectedSpan={selectedSpan}
|
||||
/>
|
||||
);
|
||||
default:
|
||||
return <div>Fetching the trace...</div>;
|
||||
}
|
||||
}, [
|
||||
data?.payload?.endTimestampMillis,
|
||||
data?.payload?.startTimestampMillis,
|
||||
firstSpanAtFetchLevel,
|
||||
flamegraphState,
|
||||
selectedSpan,
|
||||
spans,
|
||||
traceId,
|
||||
handleSpanClick,
|
||||
]);
|
||||
|
||||
return <>{content}</>;
|
||||
}
|
||||
|
||||
export default TraceFlamegraph;
|
||||
@@ -0,0 +1,36 @@
|
||||
export const ROW_HEIGHT = 24;
|
||||
export const SPAN_BAR_HEIGHT = 22;
|
||||
export const SPAN_BAR_Y_OFFSET = Math.floor((ROW_HEIGHT - SPAN_BAR_HEIGHT) / 2);
|
||||
export const EVENT_DOT_SIZE = 6;
|
||||
|
||||
// Span bar sizing relative to row height (used by getFlamegraphRowMetrics)
|
||||
export const SPAN_BAR_HEIGHT_RATIO = SPAN_BAR_HEIGHT / ROW_HEIGHT;
|
||||
export const MIN_SPAN_BAR_HEIGHT = 8;
|
||||
export const MAX_SPAN_BAR_HEIGHT = SPAN_BAR_HEIGHT;
|
||||
|
||||
// Event dot sizing relative to span bar height
|
||||
export const EVENT_DOT_SIZE_RATIO = EVENT_DOT_SIZE / SPAN_BAR_HEIGHT;
|
||||
export const MIN_EVENT_DOT_SIZE = 4;
|
||||
export const MAX_EVENT_DOT_SIZE = EVENT_DOT_SIZE;
|
||||
|
||||
export const LABEL_FONT = '11px Inter, sans-serif';
|
||||
export const LABEL_PADDING_X = 8;
|
||||
export const MIN_WIDTH_FOR_NAME = 30;
|
||||
export const MIN_WIDTH_FOR_NAME_AND_DURATION = 80;
|
||||
|
||||
// Dynamic row height (vertical zoom) -- disabled for now (MIN === MAX)
|
||||
export const MIN_ROW_HEIGHT = 24;
|
||||
export const MAX_ROW_HEIGHT = 24;
|
||||
export const DEFAULT_ROW_HEIGHT = MIN_ROW_HEIGHT;
|
||||
|
||||
// Zoom intensity -- how fast zoom reacts to wheel/pinch delta
|
||||
export const PINCH_ZOOM_INTENSITY_H = 0.01;
|
||||
export const SCROLL_ZOOM_INTENSITY_H = 0.0015;
|
||||
export const PINCH_ZOOM_INTENSITY_V = 0.008;
|
||||
export const SCROLL_ZOOM_INTENSITY_V = 0.001;
|
||||
|
||||
// Minimum visible time span in ms (prevents zooming to sub-pixel)
|
||||
export const MIN_VISIBLE_SPAN_MS = 5;
|
||||
|
||||
// Selected span style (dashed border)
|
||||
export const DASHED_BORDER_LINE_DASH = [4, 2];
|
||||
@@ -0,0 +1,55 @@
|
||||
import { RefObject, useCallback, useEffect } from 'react';
|
||||
|
||||
export function useCanvasSetup(
|
||||
canvasRef: RefObject<HTMLCanvasElement>,
|
||||
containerRef: RefObject<HTMLDivElement>,
|
||||
onDraw: () => void,
|
||||
): void {
|
||||
const updateCanvasSize = useCallback(() => {
|
||||
const canvas = canvasRef.current;
|
||||
const container = containerRef.current;
|
||||
if (!canvas || !container) {
|
||||
return;
|
||||
}
|
||||
|
||||
const dpr = window.devicePixelRatio || 1;
|
||||
const rect = container.getBoundingClientRect();
|
||||
const viewportHeight = container.clientHeight;
|
||||
|
||||
canvas.style.width = `${rect.width}px`;
|
||||
canvas.style.height = `${viewportHeight}px`;
|
||||
|
||||
const newWidth = Math.floor(rect.width * dpr);
|
||||
const newHeight = Math.floor(viewportHeight * dpr);
|
||||
|
||||
if (canvas.width !== newWidth || canvas.height !== newHeight) {
|
||||
canvas.width = newWidth;
|
||||
canvas.height = newHeight;
|
||||
onDraw();
|
||||
}
|
||||
}, [canvasRef, containerRef, onDraw]);
|
||||
|
||||
useEffect(() => {
|
||||
const container = containerRef.current;
|
||||
if (!container) {
|
||||
return (): void => {};
|
||||
}
|
||||
|
||||
const resizeObserver = new ResizeObserver(updateCanvasSize);
|
||||
resizeObserver.observe(container);
|
||||
updateCanvasSize();
|
||||
|
||||
// when dpr changes, update the canvas size
|
||||
const dprQuery = window.matchMedia('(resolution: 1dppx)');
|
||||
dprQuery.addEventListener('change', updateCanvasSize);
|
||||
|
||||
return (): void => {
|
||||
resizeObserver.disconnect();
|
||||
dprQuery.removeEventListener('change', updateCanvasSize);
|
||||
};
|
||||
}, [containerRef, updateCanvasSize]);
|
||||
|
||||
useEffect(() => {
|
||||
onDraw();
|
||||
}, [onDraw]);
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
import {
|
||||
Dispatch,
|
||||
MouseEvent as ReactMouseEvent,
|
||||
MutableRefObject,
|
||||
RefObject,
|
||||
SetStateAction,
|
||||
useCallback,
|
||||
useRef,
|
||||
} from 'react';
|
||||
|
||||
import { ITraceMetadata } from '../types';
|
||||
import { clamp } from '../utils';
|
||||
|
||||
interface UseFlamegraphDragArgs {
|
||||
canvasRef: RefObject<HTMLCanvasElement>;
|
||||
containerRef: RefObject<HTMLDivElement>;
|
||||
traceMetadata: ITraceMetadata;
|
||||
viewStartRef: MutableRefObject<number>;
|
||||
viewEndRef: MutableRefObject<number>;
|
||||
setViewStartTs: Dispatch<SetStateAction<number>>;
|
||||
setViewEndTs: Dispatch<SetStateAction<number>>;
|
||||
scrollTopRef: MutableRefObject<number>;
|
||||
setScrollTop: Dispatch<SetStateAction<number>>;
|
||||
totalHeight: number;
|
||||
}
|
||||
|
||||
interface UseFlamegraphDragResult {
|
||||
handleMouseDown: (e: ReactMouseEvent) => void;
|
||||
handleMouseMove: (e: ReactMouseEvent) => void;
|
||||
handleMouseUp: () => void;
|
||||
handleDragMouseLeave: () => void;
|
||||
suppressClickRef: MutableRefObject<boolean>;
|
||||
isDraggingRef: MutableRefObject<boolean>;
|
||||
}
|
||||
|
||||
const DRAG_THRESHOLD = 5;
|
||||
|
||||
export function useFlamegraphDrag(
|
||||
args: UseFlamegraphDragArgs,
|
||||
): UseFlamegraphDragResult {
|
||||
const {
|
||||
canvasRef,
|
||||
containerRef,
|
||||
traceMetadata,
|
||||
viewStartRef,
|
||||
viewEndRef,
|
||||
setViewStartTs,
|
||||
setViewEndTs,
|
||||
scrollTopRef,
|
||||
setScrollTop,
|
||||
totalHeight,
|
||||
} = args;
|
||||
|
||||
const isDraggingRef = useRef(false);
|
||||
const dragStartRef = useRef<{ x: number; y: number } | null>(null);
|
||||
const dragDistanceRef = useRef(0);
|
||||
const suppressClickRef = useRef(false);
|
||||
|
||||
const clampScrollTop = useCallback(
|
||||
(next: number): number => {
|
||||
const container = containerRef.current;
|
||||
if (!container) {
|
||||
return 0;
|
||||
}
|
||||
const viewportHeight = container.clientHeight;
|
||||
const maxScroll = Math.max(0, totalHeight - viewportHeight);
|
||||
return clamp(next, 0, maxScroll);
|
||||
},
|
||||
[containerRef, totalHeight],
|
||||
);
|
||||
|
||||
const handleMouseDown = useCallback(
|
||||
(event: ReactMouseEvent): void => {
|
||||
if (event.button !== 0) {
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
|
||||
isDraggingRef.current = true;
|
||||
dragStartRef.current = { x: event.clientX, y: event.clientY };
|
||||
dragDistanceRef.current = 0;
|
||||
|
||||
const canvas = canvasRef.current;
|
||||
if (canvas) {
|
||||
canvas.style.cursor = 'grabbing';
|
||||
}
|
||||
},
|
||||
[canvasRef],
|
||||
);
|
||||
|
||||
const handleMouseMove = useCallback(
|
||||
(event: ReactMouseEvent): void => {
|
||||
if (!isDraggingRef.current || !dragStartRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
const canvas = canvasRef.current;
|
||||
if (!canvas) {
|
||||
return;
|
||||
}
|
||||
|
||||
const rect = canvas.getBoundingClientRect();
|
||||
const deltaX = event.clientX - dragStartRef.current.x;
|
||||
const deltaY = event.clientY - dragStartRef.current.y;
|
||||
|
||||
dragDistanceRef.current = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
|
||||
|
||||
// --- Horizontal pan ---
|
||||
const timeSpan = viewEndRef.current - viewStartRef.current;
|
||||
const deltaTime = (deltaX / rect.width) * timeSpan;
|
||||
|
||||
const newStart = viewStartRef.current - deltaTime;
|
||||
const clampedStart = clamp(
|
||||
newStart,
|
||||
traceMetadata.startTime,
|
||||
traceMetadata.endTime - timeSpan,
|
||||
);
|
||||
const clampedEnd = clampedStart + timeSpan;
|
||||
|
||||
viewStartRef.current = clampedStart;
|
||||
viewEndRef.current = clampedEnd;
|
||||
setViewStartTs(clampedStart);
|
||||
setViewEndTs(clampedEnd);
|
||||
|
||||
// --- Vertical scroll pan ---
|
||||
const nextScrollTop = clampScrollTop(scrollTopRef.current - deltaY);
|
||||
scrollTopRef.current = nextScrollTop;
|
||||
setScrollTop(nextScrollTop);
|
||||
|
||||
dragStartRef.current = { x: event.clientX, y: event.clientY };
|
||||
},
|
||||
[
|
||||
canvasRef,
|
||||
traceMetadata,
|
||||
viewStartRef,
|
||||
viewEndRef,
|
||||
setViewStartTs,
|
||||
setViewEndTs,
|
||||
scrollTopRef,
|
||||
setScrollTop,
|
||||
clampScrollTop,
|
||||
],
|
||||
);
|
||||
|
||||
const handleMouseUp = useCallback((): void => {
|
||||
const wasDrag = dragDistanceRef.current > DRAG_THRESHOLD;
|
||||
suppressClickRef.current = wasDrag;
|
||||
|
||||
isDraggingRef.current = false;
|
||||
dragStartRef.current = null;
|
||||
dragDistanceRef.current = 0;
|
||||
|
||||
const canvas = canvasRef.current;
|
||||
if (canvas) {
|
||||
canvas.style.cursor = 'grab';
|
||||
}
|
||||
}, [canvasRef]);
|
||||
|
||||
const handleDragMouseLeave = useCallback((): void => {
|
||||
isDraggingRef.current = false;
|
||||
dragStartRef.current = null;
|
||||
dragDistanceRef.current = 0;
|
||||
|
||||
const canvas = canvasRef.current;
|
||||
if (canvas) {
|
||||
canvas.style.cursor = 'grab';
|
||||
}
|
||||
}, [canvasRef]);
|
||||
|
||||
return {
|
||||
handleMouseDown,
|
||||
handleMouseMove,
|
||||
handleMouseUp,
|
||||
handleDragMouseLeave,
|
||||
suppressClickRef,
|
||||
isDraggingRef,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
import React, { RefObject, useCallback, useRef } from 'react';
|
||||
import { FlamegraphSpan } from 'types/api/trace/getTraceFlamegraph';
|
||||
|
||||
import { SpanRect } from '../types';
|
||||
import {
|
||||
clamp,
|
||||
drawSpanBar,
|
||||
FlamegraphRowMetrics,
|
||||
getFlamegraphRowMetrics,
|
||||
getSpanColor,
|
||||
} from '../utils';
|
||||
|
||||
interface UseFlamegraphDrawArgs {
|
||||
canvasRef: RefObject<HTMLCanvasElement>;
|
||||
containerRef: RefObject<HTMLDivElement>;
|
||||
spans: FlamegraphSpan[][];
|
||||
viewStartTs: number;
|
||||
viewEndTs: number;
|
||||
scrollTop: number;
|
||||
rowHeight: number;
|
||||
selectedSpanId: string | undefined;
|
||||
hoveredSpanId: string;
|
||||
isDarkMode: boolean;
|
||||
spanRectsRef?: React.MutableRefObject<SpanRect[]>;
|
||||
}
|
||||
|
||||
interface UseFlamegraphDrawResult {
|
||||
drawFlamegraph: () => void;
|
||||
spanRectsRef: RefObject<SpanRect[]>;
|
||||
}
|
||||
|
||||
const OVERSCAN_ROWS = 4;
|
||||
|
||||
interface DrawLevelArgs {
|
||||
ctx: CanvasRenderingContext2D;
|
||||
levelSpans: FlamegraphSpan[];
|
||||
levelIndex: number;
|
||||
y: number;
|
||||
viewStartTs: number;
|
||||
timeSpan: number;
|
||||
cssWidth: number;
|
||||
selectedSpanId: string | undefined;
|
||||
hoveredSpanId: string;
|
||||
isDarkMode: boolean;
|
||||
spanRectsArray: SpanRect[];
|
||||
metrics: FlamegraphRowMetrics;
|
||||
}
|
||||
|
||||
function drawLevel(args: DrawLevelArgs): void {
|
||||
const {
|
||||
ctx,
|
||||
levelSpans,
|
||||
levelIndex,
|
||||
y,
|
||||
viewStartTs,
|
||||
timeSpan,
|
||||
cssWidth,
|
||||
selectedSpanId,
|
||||
hoveredSpanId,
|
||||
isDarkMode,
|
||||
spanRectsArray,
|
||||
metrics,
|
||||
} = args;
|
||||
|
||||
const viewEndTs = viewStartTs + timeSpan;
|
||||
|
||||
for (let i = 0; i < levelSpans.length; i++) {
|
||||
const span = levelSpans[i];
|
||||
const spanStartMs = span.timestamp;
|
||||
const spanEndMs = span.timestamp + span.durationNano / 1e6;
|
||||
|
||||
// Time culling -- skip spans entirely outside the visible time window
|
||||
if (spanEndMs < viewStartTs || spanStartMs > viewEndTs) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const leftOffset = ((spanStartMs - viewStartTs) / timeSpan) * cssWidth;
|
||||
const rightEdge = ((spanEndMs - viewStartTs) / timeSpan) * cssWidth;
|
||||
let width = rightEdge - leftOffset;
|
||||
|
||||
// Clamp to visible x-range
|
||||
if (leftOffset < 0) {
|
||||
width += leftOffset;
|
||||
if (width <= 0) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (rightEdge > cssWidth) {
|
||||
width = cssWidth - Math.max(0, leftOffset);
|
||||
if (width <= 0) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// Minimum 1px width so tiny spans remain visible
|
||||
width = clamp(width, 1, Infinity);
|
||||
|
||||
const color = getSpanColor({ span, isDarkMode });
|
||||
|
||||
drawSpanBar({
|
||||
ctx,
|
||||
span,
|
||||
x: Math.max(0, leftOffset),
|
||||
y,
|
||||
width,
|
||||
levelIndex,
|
||||
spanRectsArray,
|
||||
color,
|
||||
isDarkMode,
|
||||
metrics,
|
||||
selectedSpanId,
|
||||
hoveredSpanId,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export function useFlamegraphDraw(
|
||||
args: UseFlamegraphDrawArgs,
|
||||
): UseFlamegraphDrawResult {
|
||||
const {
|
||||
canvasRef,
|
||||
containerRef,
|
||||
spans,
|
||||
viewStartTs,
|
||||
viewEndTs,
|
||||
scrollTop,
|
||||
rowHeight,
|
||||
selectedSpanId,
|
||||
hoveredSpanId,
|
||||
isDarkMode,
|
||||
spanRectsRef: spanRectsRefProp,
|
||||
} = args;
|
||||
|
||||
const spanRectsRefInternal = useRef<SpanRect[]>([]);
|
||||
const spanRectsRef = spanRectsRefProp ?? spanRectsRefInternal;
|
||||
|
||||
const drawFlamegraph = useCallback(() => {
|
||||
const canvas = canvasRef.current;
|
||||
const container = containerRef.current;
|
||||
if (!canvas || !container) {
|
||||
return;
|
||||
}
|
||||
|
||||
const ctx = canvas.getContext('2d');
|
||||
if (!ctx) {
|
||||
return;
|
||||
}
|
||||
|
||||
const dpr = window.devicePixelRatio || 1;
|
||||
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
|
||||
|
||||
const timeSpan = viewEndTs - viewStartTs;
|
||||
if (timeSpan <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const cssWidth = canvas.width / dpr;
|
||||
const metrics = getFlamegraphRowMetrics(rowHeight);
|
||||
|
||||
// ---- Vertical clipping window ----
|
||||
const viewportHeight = container.clientHeight;
|
||||
|
||||
const firstLevel = Math.max(
|
||||
0,
|
||||
Math.floor(scrollTop / metrics.ROW_HEIGHT) - OVERSCAN_ROWS,
|
||||
);
|
||||
const visibleLevelCount =
|
||||
Math.ceil(viewportHeight / metrics.ROW_HEIGHT) + 2 * OVERSCAN_ROWS;
|
||||
const lastLevel = Math.min(spans.length - 1, firstLevel + visibleLevelCount);
|
||||
|
||||
ctx.clearRect(0, 0, cssWidth, viewportHeight);
|
||||
|
||||
const spanRectsArray: SpanRect[] = [];
|
||||
|
||||
// ---- Draw only visible levels ----
|
||||
for (let levelIndex = firstLevel; levelIndex <= lastLevel; levelIndex++) {
|
||||
const levelSpans = spans[levelIndex];
|
||||
if (!levelSpans) {
|
||||
continue;
|
||||
}
|
||||
|
||||
drawLevel({
|
||||
ctx,
|
||||
levelSpans,
|
||||
levelIndex,
|
||||
y: levelIndex * metrics.ROW_HEIGHT - scrollTop,
|
||||
viewStartTs,
|
||||
timeSpan,
|
||||
cssWidth,
|
||||
selectedSpanId,
|
||||
hoveredSpanId,
|
||||
isDarkMode,
|
||||
spanRectsArray,
|
||||
metrics,
|
||||
});
|
||||
}
|
||||
|
||||
spanRectsRef.current = spanRectsArray;
|
||||
}, [
|
||||
canvasRef,
|
||||
containerRef,
|
||||
spanRectsRef,
|
||||
spans,
|
||||
viewStartTs,
|
||||
viewEndTs,
|
||||
scrollTop,
|
||||
rowHeight,
|
||||
selectedSpanId,
|
||||
hoveredSpanId,
|
||||
isDarkMode,
|
||||
]);
|
||||
|
||||
// TODO: spanRectsRef is a flat array — hover scans all visible rects O(N).
|
||||
// Upgrade to per-level buckets: spanRects[levelIndex] = [...] so hover can
|
||||
// compute level from mouseY / ROW_HEIGHT and scan only that row.
|
||||
// Further: binary search within a level by x (spans are sorted by start time)
|
||||
// to reduce hover cost from O(N) to O(log N).
|
||||
return { drawFlamegraph, spanRectsRef };
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
import {
|
||||
Dispatch,
|
||||
MouseEvent as ReactMouseEvent,
|
||||
MutableRefObject,
|
||||
RefObject,
|
||||
SetStateAction,
|
||||
useCallback,
|
||||
useState,
|
||||
} from 'react';
|
||||
import { FlamegraphSpan } from 'types/api/trace/getTraceFlamegraph';
|
||||
|
||||
import { SpanRect } from '../types';
|
||||
import { ITraceMetadata } from '../types';
|
||||
import { getSpanColor } from '../utils';
|
||||
|
||||
function getCanvasPointer(
|
||||
canvas: HTMLCanvasElement,
|
||||
clientX: number,
|
||||
clientY: number,
|
||||
): { cssX: number; cssY: number } | null {
|
||||
const rect = canvas.getBoundingClientRect();
|
||||
const dpr = window.devicePixelRatio || 1;
|
||||
const cssWidth = canvas.width / dpr;
|
||||
const cssHeight = canvas.height / dpr;
|
||||
const cssX = (clientX - rect.left) * (cssWidth / rect.width);
|
||||
const cssY = (clientY - rect.top) * (cssHeight / rect.height);
|
||||
return { cssX, cssY };
|
||||
}
|
||||
|
||||
function findSpanAtPosition(
|
||||
cssX: number,
|
||||
cssY: number,
|
||||
spanRects: SpanRect[],
|
||||
): FlamegraphSpan | null {
|
||||
for (let i = spanRects.length - 1; i >= 0; i--) {
|
||||
const r = spanRects[i];
|
||||
if (
|
||||
cssX >= r.x &&
|
||||
cssX <= r.x + r.width &&
|
||||
cssY >= r.y &&
|
||||
cssY <= r.y + r.height
|
||||
) {
|
||||
return r.span;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export interface TooltipContent {
|
||||
spanName: string;
|
||||
status: 'ok' | 'warning' | 'error';
|
||||
startMs: number;
|
||||
durationMs: number;
|
||||
clientX: number;
|
||||
clientY: number;
|
||||
spanColor: string;
|
||||
}
|
||||
|
||||
interface UseFlamegraphHoverArgs {
|
||||
canvasRef: RefObject<HTMLCanvasElement>;
|
||||
spanRectsRef: MutableRefObject<SpanRect[]>;
|
||||
traceMetadata: ITraceMetadata;
|
||||
viewStartTs: number;
|
||||
viewEndTs: number;
|
||||
isDraggingRef: MutableRefObject<boolean>;
|
||||
suppressClickRef: MutableRefObject<boolean>;
|
||||
onSpanClick: (spanId: string) => void;
|
||||
isDarkMode: boolean;
|
||||
}
|
||||
|
||||
interface UseFlamegraphHoverResult {
|
||||
hoveredSpanId: string | null;
|
||||
setHoveredSpanId: Dispatch<SetStateAction<string | null>>;
|
||||
handleHoverMouseMove: (e: ReactMouseEvent) => void;
|
||||
handleHoverMouseLeave: () => void;
|
||||
handleClick: (e: ReactMouseEvent) => void;
|
||||
tooltipContent: TooltipContent | null;
|
||||
}
|
||||
|
||||
export function useFlamegraphHover(
|
||||
args: UseFlamegraphHoverArgs,
|
||||
): UseFlamegraphHoverResult {
|
||||
const {
|
||||
canvasRef,
|
||||
spanRectsRef,
|
||||
traceMetadata,
|
||||
viewStartTs,
|
||||
viewEndTs,
|
||||
isDraggingRef,
|
||||
suppressClickRef,
|
||||
onSpanClick,
|
||||
isDarkMode,
|
||||
} = args;
|
||||
|
||||
const [hoveredSpanId, setHoveredSpanId] = useState<string | null>(null);
|
||||
const [tooltipContent, setTooltipContent] = useState<TooltipContent | null>(
|
||||
null,
|
||||
);
|
||||
|
||||
const isZoomed =
|
||||
viewStartTs !== traceMetadata.startTime ||
|
||||
viewEndTs !== traceMetadata.endTime;
|
||||
|
||||
const updateCursor = useCallback(
|
||||
(canvas: HTMLCanvasElement, span: FlamegraphSpan | null): void => {
|
||||
if (span) {
|
||||
canvas.style.cursor = 'pointer';
|
||||
} else if (isZoomed) {
|
||||
canvas.style.cursor = 'grab';
|
||||
} else {
|
||||
canvas.style.cursor = 'default';
|
||||
}
|
||||
},
|
||||
[isZoomed],
|
||||
);
|
||||
|
||||
const handleHoverMouseMove = useCallback(
|
||||
(e: ReactMouseEvent): void => {
|
||||
if (isDraggingRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
const canvas = canvasRef.current;
|
||||
if (!canvas) {
|
||||
return;
|
||||
}
|
||||
|
||||
const pointer = getCanvasPointer(canvas, e.clientX, e.clientY);
|
||||
if (!pointer) {
|
||||
return;
|
||||
}
|
||||
|
||||
const span = findSpanAtPosition(
|
||||
pointer.cssX,
|
||||
pointer.cssY,
|
||||
spanRectsRef.current,
|
||||
);
|
||||
|
||||
if (span) {
|
||||
setHoveredSpanId(span.spanId);
|
||||
setTooltipContent({
|
||||
spanName: span.name || 'unknown',
|
||||
status: span.hasError ? 'error' : 'ok',
|
||||
startMs: span.timestamp - traceMetadata.startTime,
|
||||
durationMs: span.durationNano / 1e6,
|
||||
clientX: e.clientX,
|
||||
clientY: e.clientY,
|
||||
spanColor: getSpanColor({ span, isDarkMode }),
|
||||
});
|
||||
updateCursor(canvas, span);
|
||||
} else {
|
||||
setHoveredSpanId(null);
|
||||
setTooltipContent(null);
|
||||
updateCursor(canvas, null);
|
||||
}
|
||||
},
|
||||
[
|
||||
canvasRef,
|
||||
spanRectsRef,
|
||||
traceMetadata.startTime,
|
||||
isDraggingRef,
|
||||
updateCursor,
|
||||
isDarkMode,
|
||||
],
|
||||
);
|
||||
|
||||
const handleHoverMouseLeave = useCallback((): void => {
|
||||
setHoveredSpanId(null);
|
||||
setTooltipContent(null);
|
||||
|
||||
const canvas = canvasRef.current;
|
||||
if (canvas) {
|
||||
updateCursor(canvas, null);
|
||||
}
|
||||
}, [canvasRef, updateCursor]);
|
||||
|
||||
const handleClick = useCallback(
|
||||
(e: ReactMouseEvent): void => {
|
||||
if (suppressClickRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
const canvas = canvasRef.current;
|
||||
if (!canvas) {
|
||||
return;
|
||||
}
|
||||
|
||||
const pointer = getCanvasPointer(canvas, e.clientX, e.clientY);
|
||||
if (!pointer) {
|
||||
return;
|
||||
}
|
||||
|
||||
const span = findSpanAtPosition(
|
||||
pointer.cssX,
|
||||
pointer.cssY,
|
||||
spanRectsRef.current,
|
||||
);
|
||||
|
||||
if (span) {
|
||||
onSpanClick(span.spanId);
|
||||
}
|
||||
},
|
||||
[canvasRef, spanRectsRef, suppressClickRef, onSpanClick],
|
||||
);
|
||||
|
||||
return {
|
||||
hoveredSpanId,
|
||||
setHoveredSpanId,
|
||||
handleHoverMouseMove,
|
||||
handleHoverMouseLeave,
|
||||
handleClick,
|
||||
tooltipContent,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
import {
|
||||
Dispatch,
|
||||
MutableRefObject,
|
||||
RefObject,
|
||||
SetStateAction,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useRef,
|
||||
} from 'react';
|
||||
|
||||
import {
|
||||
DEFAULT_ROW_HEIGHT,
|
||||
MAX_ROW_HEIGHT,
|
||||
MIN_ROW_HEIGHT,
|
||||
MIN_VISIBLE_SPAN_MS,
|
||||
PINCH_ZOOM_INTENSITY_H,
|
||||
PINCH_ZOOM_INTENSITY_V,
|
||||
SCROLL_ZOOM_INTENSITY_H,
|
||||
SCROLL_ZOOM_INTENSITY_V,
|
||||
} from '../constants';
|
||||
import { ITraceMetadata } from '../types';
|
||||
import { clamp } from '../utils';
|
||||
|
||||
interface UseFlamegraphZoomArgs {
|
||||
canvasRef: RefObject<HTMLCanvasElement>;
|
||||
traceMetadata: ITraceMetadata;
|
||||
viewStartRef: MutableRefObject<number>;
|
||||
viewEndRef: MutableRefObject<number>;
|
||||
rowHeightRef: MutableRefObject<number>;
|
||||
setViewStartTs: Dispatch<SetStateAction<number>>;
|
||||
setViewEndTs: Dispatch<SetStateAction<number>>;
|
||||
setRowHeight: Dispatch<SetStateAction<number>>;
|
||||
}
|
||||
|
||||
interface UseFlamegraphZoomResult {
|
||||
handleResetZoom: () => void;
|
||||
isOverFlamegraphRef: MutableRefObject<boolean>;
|
||||
}
|
||||
|
||||
function getCanvasPointer(
|
||||
canvasRef: RefObject<HTMLCanvasElement>,
|
||||
clientX: number,
|
||||
): { cssX: number; cssWidth: number } | null {
|
||||
const canvas = canvasRef.current;
|
||||
if (!canvas) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const rect = canvas.getBoundingClientRect();
|
||||
const dpr = window.devicePixelRatio || 1;
|
||||
const cssWidth = canvas.width / dpr;
|
||||
const cssX = (clientX - rect.left) * (cssWidth / rect.width);
|
||||
|
||||
return { cssX, cssWidth };
|
||||
}
|
||||
|
||||
export function useFlamegraphZoom(
|
||||
args: UseFlamegraphZoomArgs,
|
||||
): UseFlamegraphZoomResult {
|
||||
const {
|
||||
canvasRef,
|
||||
traceMetadata,
|
||||
viewStartRef,
|
||||
viewEndRef,
|
||||
rowHeightRef,
|
||||
setViewStartTs,
|
||||
setViewEndTs,
|
||||
setRowHeight,
|
||||
} = args;
|
||||
|
||||
const isOverFlamegraphRef = useRef(false);
|
||||
const wheelDeltaRef = useRef(0);
|
||||
const rafRef = useRef<number | null>(null);
|
||||
const lastCursorXRef = useRef(0);
|
||||
const lastCssWidthRef = useRef(1);
|
||||
const lastIsPinchRef = useRef(false);
|
||||
const lastWheelClientXRef = useRef<number | null>(null);
|
||||
|
||||
// Prevent browser zoom when pinching over the flamegraph
|
||||
useEffect(() => {
|
||||
const onWheel = (e: WheelEvent): void => {
|
||||
if (isOverFlamegraphRef.current && e.ctrlKey) {
|
||||
e.preventDefault();
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('wheel', onWheel, { passive: false, capture: true });
|
||||
|
||||
return (): void => {
|
||||
window.removeEventListener('wheel', onWheel, {
|
||||
capture: true,
|
||||
} as EventListenerOptions);
|
||||
};
|
||||
}, []);
|
||||
|
||||
const applyWheelZoom = useCallback(() => {
|
||||
rafRef.current = null;
|
||||
|
||||
const cssWidth = lastCssWidthRef.current || 1;
|
||||
const cursorX = lastCursorXRef.current;
|
||||
const fullSpanMs = traceMetadata.endTime - traceMetadata.startTime;
|
||||
|
||||
const oldStart = viewStartRef.current;
|
||||
const oldEnd = viewEndRef.current;
|
||||
const oldSpan = oldEnd - oldStart;
|
||||
|
||||
const deltaY = wheelDeltaRef.current;
|
||||
wheelDeltaRef.current = 0;
|
||||
if (deltaY === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const zoomH = lastIsPinchRef.current
|
||||
? PINCH_ZOOM_INTENSITY_H
|
||||
: SCROLL_ZOOM_INTENSITY_H;
|
||||
const zoomV = lastIsPinchRef.current
|
||||
? PINCH_ZOOM_INTENSITY_V
|
||||
: SCROLL_ZOOM_INTENSITY_V;
|
||||
|
||||
const factorH = Math.exp(deltaY * zoomH);
|
||||
const factorV = Math.exp(deltaY * zoomV);
|
||||
|
||||
// --- Horizontal zoom ---
|
||||
const desiredSpan = oldSpan * factorH;
|
||||
const minSpanMs = Math.max(
|
||||
MIN_VISIBLE_SPAN_MS,
|
||||
oldSpan / Math.max(cssWidth, 1),
|
||||
);
|
||||
const clampedSpan = clamp(desiredSpan, minSpanMs, fullSpanMs);
|
||||
|
||||
const cursorRatio = clamp(cursorX / cssWidth, 0, 1);
|
||||
const anchorTs = oldStart + cursorRatio * oldSpan;
|
||||
|
||||
let nextStart = anchorTs - cursorRatio * clampedSpan;
|
||||
nextStart = clamp(
|
||||
nextStart,
|
||||
traceMetadata.startTime,
|
||||
traceMetadata.endTime - clampedSpan,
|
||||
);
|
||||
const nextEnd = nextStart + clampedSpan;
|
||||
|
||||
// --- Vertical zoom (row height) ---
|
||||
const desiredRow = rowHeightRef.current * (1 / factorV);
|
||||
const nextRow = clamp(desiredRow, MIN_ROW_HEIGHT, MAX_ROW_HEIGHT);
|
||||
|
||||
// Write refs immediately so rapid wheel events read fresh values
|
||||
viewStartRef.current = nextStart;
|
||||
viewEndRef.current = nextEnd;
|
||||
rowHeightRef.current = nextRow;
|
||||
|
||||
setViewStartTs(nextStart);
|
||||
setViewEndTs(nextEnd);
|
||||
setRowHeight(nextRow);
|
||||
}, [
|
||||
traceMetadata,
|
||||
viewStartRef,
|
||||
viewEndRef,
|
||||
rowHeightRef,
|
||||
setViewStartTs,
|
||||
setViewEndTs,
|
||||
setRowHeight,
|
||||
]);
|
||||
|
||||
// Native wheel listener on the canvas (passive: false for reliable preventDefault)
|
||||
useEffect(() => {
|
||||
const canvas = canvasRef.current;
|
||||
if (!canvas) {
|
||||
return (): void => {};
|
||||
}
|
||||
|
||||
const onWheel = (e: WheelEvent): void => {
|
||||
e.preventDefault();
|
||||
|
||||
const pointer = getCanvasPointer(canvasRef, e.clientX);
|
||||
if (!pointer) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Flush accumulated delta if cursor moved significantly
|
||||
if (lastWheelClientXRef.current !== null) {
|
||||
const moved = Math.abs(e.clientX - lastWheelClientXRef.current);
|
||||
if (moved > 6) {
|
||||
wheelDeltaRef.current = 0;
|
||||
}
|
||||
}
|
||||
lastWheelClientXRef.current = e.clientX;
|
||||
|
||||
lastIsPinchRef.current = e.ctrlKey;
|
||||
lastCssWidthRef.current = pointer.cssWidth;
|
||||
lastCursorXRef.current = pointer.cssX;
|
||||
wheelDeltaRef.current += e.deltaY;
|
||||
|
||||
if (rafRef.current == null) {
|
||||
rafRef.current = requestAnimationFrame(applyWheelZoom);
|
||||
}
|
||||
};
|
||||
|
||||
canvas.addEventListener('wheel', onWheel, { passive: false });
|
||||
|
||||
return (): void => {
|
||||
canvas.removeEventListener('wheel', onWheel);
|
||||
};
|
||||
}, [canvasRef, applyWheelZoom]);
|
||||
|
||||
const handleResetZoom = useCallback(() => {
|
||||
viewStartRef.current = traceMetadata.startTime;
|
||||
viewEndRef.current = traceMetadata.endTime;
|
||||
rowHeightRef.current = DEFAULT_ROW_HEIGHT;
|
||||
|
||||
setViewStartTs(traceMetadata.startTime);
|
||||
setViewEndTs(traceMetadata.endTime);
|
||||
setRowHeight(DEFAULT_ROW_HEIGHT);
|
||||
}, [
|
||||
traceMetadata,
|
||||
viewStartRef,
|
||||
viewEndRef,
|
||||
rowHeightRef,
|
||||
setViewStartTs,
|
||||
setViewEndTs,
|
||||
setRowHeight,
|
||||
]);
|
||||
|
||||
return { handleResetZoom, isOverFlamegraphRef };
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
import {
|
||||
Dispatch,
|
||||
MutableRefObject,
|
||||
RefObject,
|
||||
SetStateAction,
|
||||
useEffect,
|
||||
} from 'react';
|
||||
import { FlamegraphSpan } from 'types/api/trace/getTraceFlamegraph';
|
||||
|
||||
import { MIN_VISIBLE_SPAN_MS } from '../constants';
|
||||
import { ITraceMetadata } from '../types';
|
||||
import { clamp, findSpanById, getFlamegraphRowMetrics } from '../utils';
|
||||
|
||||
interface UseScrollToSpanArgs {
|
||||
firstSpanAtFetchLevel: string;
|
||||
spans: FlamegraphSpan[][];
|
||||
traceMetadata: ITraceMetadata;
|
||||
containerRef: RefObject<HTMLDivElement>;
|
||||
viewStartRef: MutableRefObject<number>;
|
||||
viewEndRef: MutableRefObject<number>;
|
||||
scrollTopRef: MutableRefObject<number>;
|
||||
rowHeight: number;
|
||||
setViewStartTs: Dispatch<SetStateAction<number>>;
|
||||
setViewEndTs: Dispatch<SetStateAction<number>>;
|
||||
setScrollTop: Dispatch<SetStateAction<number>>;
|
||||
}
|
||||
|
||||
/**
|
||||
* When firstSpanAtFetchLevel (from URL spanId) changes, scroll and zoom the
|
||||
* flamegraph so the selected span is centered in view.
|
||||
*/
|
||||
export function useScrollToSpan(args: UseScrollToSpanArgs): void {
|
||||
const {
|
||||
firstSpanAtFetchLevel,
|
||||
spans,
|
||||
traceMetadata,
|
||||
containerRef,
|
||||
viewStartRef,
|
||||
viewEndRef,
|
||||
scrollTopRef,
|
||||
rowHeight,
|
||||
setViewStartTs,
|
||||
setViewEndTs,
|
||||
setScrollTop,
|
||||
} = args;
|
||||
|
||||
useEffect(() => {
|
||||
if (!firstSpanAtFetchLevel || spans.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const result = findSpanById(spans, firstSpanAtFetchLevel);
|
||||
if (!result) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { span, levelIndex } = result;
|
||||
const container = containerRef.current;
|
||||
if (!container) {
|
||||
return;
|
||||
}
|
||||
|
||||
const metrics = getFlamegraphRowMetrics(rowHeight);
|
||||
const viewportHeight = container.clientHeight;
|
||||
const totalHeight = spans.length * metrics.ROW_HEIGHT;
|
||||
const maxScroll = Math.max(0, totalHeight - viewportHeight);
|
||||
|
||||
// Vertical: center the span's row in the viewport
|
||||
const targetScrollTop = clamp(
|
||||
levelIndex * metrics.ROW_HEIGHT -
|
||||
viewportHeight / 2 +
|
||||
metrics.ROW_HEIGHT / 2,
|
||||
0,
|
||||
maxScroll,
|
||||
);
|
||||
|
||||
// Horizontal: zoom to span with padding (2x span duration), center it
|
||||
const spanStartMs = span.timestamp;
|
||||
const spanEndMs = span.timestamp + span.durationNano / 1e6;
|
||||
const spanDurationMs = spanEndMs - spanStartMs;
|
||||
const spanCenterMs = (spanStartMs + spanEndMs) / 2;
|
||||
|
||||
const visibleWindowMs = Math.max(spanDurationMs * 2, MIN_VISIBLE_SPAN_MS);
|
||||
const fullSpanMs = traceMetadata.endTime - traceMetadata.startTime;
|
||||
const clampedWindow = clamp(visibleWindowMs, MIN_VISIBLE_SPAN_MS, fullSpanMs);
|
||||
|
||||
let targetViewStart = spanCenterMs - clampedWindow / 2;
|
||||
let targetViewEnd = spanCenterMs + clampedWindow / 2;
|
||||
|
||||
targetViewStart = clamp(
|
||||
targetViewStart,
|
||||
traceMetadata.startTime,
|
||||
traceMetadata.endTime - clampedWindow,
|
||||
);
|
||||
targetViewEnd = targetViewStart + clampedWindow;
|
||||
|
||||
// Apply immediately (instant jump)
|
||||
viewStartRef.current = targetViewStart;
|
||||
viewEndRef.current = targetViewEnd;
|
||||
scrollTopRef.current = targetScrollTop;
|
||||
|
||||
setViewStartTs(targetViewStart);
|
||||
setViewEndTs(targetViewEnd);
|
||||
setScrollTop(targetScrollTop);
|
||||
}, [
|
||||
firstSpanAtFetchLevel,
|
||||
spans,
|
||||
traceMetadata,
|
||||
containerRef,
|
||||
viewStartRef,
|
||||
viewEndRef,
|
||||
scrollTopRef,
|
||||
rowHeight,
|
||||
setViewStartTs,
|
||||
setViewEndTs,
|
||||
setScrollTop,
|
||||
]);
|
||||
}
|
||||
26
frontend/src/pages/TraceDetailsV3/TraceFlamegraph/types.ts
Normal file
26
frontend/src/pages/TraceDetailsV3/TraceFlamegraph/types.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
import { Dispatch, SetStateAction } from 'react';
|
||||
import { FlamegraphSpan } from 'types/api/trace/getTraceFlamegraph';
|
||||
import { Span } from 'types/api/trace/getTraceV2';
|
||||
|
||||
export interface ITraceMetadata {
|
||||
startTime: number;
|
||||
endTime: number;
|
||||
}
|
||||
|
||||
export interface FlamegraphCanvasProps {
|
||||
spans: FlamegraphSpan[][];
|
||||
firstSpanAtFetchLevel: string;
|
||||
setFirstSpanAtFetchLevel: Dispatch<SetStateAction<string>>;
|
||||
onSpanClick: (spanId: string) => void;
|
||||
traceMetadata: ITraceMetadata;
|
||||
selectedSpan: Span | undefined;
|
||||
}
|
||||
|
||||
export interface SpanRect {
|
||||
span: FlamegraphSpan;
|
||||
x: number;
|
||||
y: number;
|
||||
width: number;
|
||||
height: number;
|
||||
level: number;
|
||||
}
|
||||
355
frontend/src/pages/TraceDetailsV3/TraceFlamegraph/utils.ts
Normal file
355
frontend/src/pages/TraceDetailsV3/TraceFlamegraph/utils.ts
Normal file
@@ -0,0 +1,355 @@
|
||||
import { themeColors } from 'constants/theme';
|
||||
import { convertTimeToRelevantUnit } from 'container/TraceDetail/utils';
|
||||
import { generateColor } from 'lib/uPlotLib/utils/generateColor';
|
||||
import { FlamegraphSpan } from 'types/api/trace/getTraceFlamegraph';
|
||||
|
||||
import {
|
||||
DASHED_BORDER_LINE_DASH,
|
||||
EVENT_DOT_SIZE_RATIO,
|
||||
LABEL_FONT,
|
||||
LABEL_PADDING_X,
|
||||
MAX_EVENT_DOT_SIZE,
|
||||
MAX_SPAN_BAR_HEIGHT,
|
||||
MIN_EVENT_DOT_SIZE,
|
||||
MIN_SPAN_BAR_HEIGHT,
|
||||
MIN_WIDTH_FOR_NAME,
|
||||
MIN_WIDTH_FOR_NAME_AND_DURATION,
|
||||
SPAN_BAR_HEIGHT_RATIO,
|
||||
} from './constants';
|
||||
import { SpanRect } from './types';
|
||||
|
||||
export function clamp(v: number, min: number, max: number): number {
|
||||
return Math.max(min, Math.min(max, v));
|
||||
}
|
||||
|
||||
/** Create diagonal stripe pattern for selected/hovered span (repeating-linear-gradient -45deg style). */
|
||||
function createStripePattern(
|
||||
ctx: CanvasRenderingContext2D,
|
||||
color: string,
|
||||
): CanvasPattern | null {
|
||||
const size = 20;
|
||||
const patternCanvas = document.createElement('canvas');
|
||||
patternCanvas.width = size;
|
||||
patternCanvas.height = size;
|
||||
const pCtx = patternCanvas.getContext('2d');
|
||||
if (!pCtx) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Diagonal stripes at -45deg: 10px transparent, 10px colored (0.04 opacity), repeat
|
||||
pCtx.globalAlpha = 0.04;
|
||||
pCtx.strokeStyle = color;
|
||||
pCtx.lineWidth = 10;
|
||||
pCtx.lineCap = 'butt';
|
||||
for (let i = -size; i < size * 2; i += size) {
|
||||
pCtx.beginPath();
|
||||
pCtx.moveTo(i + size, 0);
|
||||
pCtx.lineTo(i, size);
|
||||
pCtx.stroke();
|
||||
}
|
||||
pCtx.globalAlpha = 1;
|
||||
|
||||
return ctx.createPattern(patternCanvas, 'repeat');
|
||||
}
|
||||
|
||||
export function findSpanById(
|
||||
spans: FlamegraphSpan[][],
|
||||
spanId: string,
|
||||
): { span: FlamegraphSpan; levelIndex: number } | null {
|
||||
for (let levelIndex = 0; levelIndex < spans.length; levelIndex++) {
|
||||
const span = spans[levelIndex]?.find((s) => s.spanId === spanId);
|
||||
if (span) {
|
||||
return { span, levelIndex };
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export interface FlamegraphRowMetrics {
|
||||
ROW_HEIGHT: number;
|
||||
SPAN_BAR_HEIGHT: number;
|
||||
SPAN_BAR_Y_OFFSET: number;
|
||||
EVENT_DOT_SIZE: number;
|
||||
}
|
||||
|
||||
export function getFlamegraphRowMetrics(
|
||||
rowHeight: number,
|
||||
): FlamegraphRowMetrics {
|
||||
const spanBarHeight = clamp(
|
||||
Math.round(rowHeight * SPAN_BAR_HEIGHT_RATIO),
|
||||
MIN_SPAN_BAR_HEIGHT,
|
||||
MAX_SPAN_BAR_HEIGHT,
|
||||
);
|
||||
const spanBarYOffset = Math.floor((rowHeight - spanBarHeight) / 2);
|
||||
const eventDotSize = clamp(
|
||||
Math.round(spanBarHeight * EVENT_DOT_SIZE_RATIO),
|
||||
MIN_EVENT_DOT_SIZE,
|
||||
MAX_EVENT_DOT_SIZE,
|
||||
);
|
||||
|
||||
return {
|
||||
ROW_HEIGHT: rowHeight,
|
||||
SPAN_BAR_HEIGHT: spanBarHeight,
|
||||
SPAN_BAR_Y_OFFSET: spanBarYOffset,
|
||||
EVENT_DOT_SIZE: eventDotSize,
|
||||
};
|
||||
}
|
||||
|
||||
interface GetSpanColorArgs {
|
||||
span: FlamegraphSpan;
|
||||
isDarkMode: boolean;
|
||||
}
|
||||
|
||||
export function getSpanColor(args: GetSpanColorArgs): string {
|
||||
const { span, isDarkMode } = args;
|
||||
let color = generateColor(span.serviceName, themeColors.chartcolors);
|
||||
|
||||
if (span.hasError) {
|
||||
color = isDarkMode ? 'rgb(239, 68, 68)' : 'rgb(220, 38, 38)';
|
||||
}
|
||||
|
||||
return color;
|
||||
}
|
||||
|
||||
interface DrawEventDotArgs {
|
||||
ctx: CanvasRenderingContext2D;
|
||||
x: number;
|
||||
y: number;
|
||||
isError: boolean;
|
||||
isDarkMode: boolean;
|
||||
eventDotSize: number;
|
||||
}
|
||||
|
||||
export function drawEventDot(args: DrawEventDotArgs): void {
|
||||
const { ctx, x, y, isError, isDarkMode, eventDotSize } = args;
|
||||
|
||||
ctx.save();
|
||||
ctx.translate(x, y);
|
||||
ctx.rotate(Math.PI / 4);
|
||||
|
||||
if (isError) {
|
||||
ctx.fillStyle = isDarkMode ? 'rgb(239, 68, 68)' : 'rgb(220, 38, 38)';
|
||||
ctx.strokeStyle = isDarkMode ? 'rgb(185, 28, 28)' : 'rgb(153, 27, 27)';
|
||||
} else {
|
||||
ctx.fillStyle = isDarkMode ? 'rgb(14, 165, 233)' : 'rgb(6, 182, 212)';
|
||||
ctx.strokeStyle = isDarkMode ? 'rgb(2, 132, 199)' : 'rgb(8, 145, 178)';
|
||||
}
|
||||
|
||||
ctx.lineWidth = 1;
|
||||
const half = eventDotSize / 2;
|
||||
ctx.fillRect(-half, -half, eventDotSize, eventDotSize);
|
||||
ctx.strokeRect(-half, -half, eventDotSize, eventDotSize);
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
interface DrawSpanBarArgs {
|
||||
ctx: CanvasRenderingContext2D;
|
||||
span: FlamegraphSpan;
|
||||
x: number;
|
||||
y: number;
|
||||
width: number;
|
||||
levelIndex: number;
|
||||
spanRectsArray: SpanRect[];
|
||||
color: string;
|
||||
isDarkMode: boolean;
|
||||
metrics: FlamegraphRowMetrics;
|
||||
selectedSpanId?: string | null;
|
||||
hoveredSpanId?: string | null;
|
||||
}
|
||||
|
||||
export function drawSpanBar(args: DrawSpanBarArgs): void {
|
||||
const {
|
||||
ctx,
|
||||
span,
|
||||
x,
|
||||
y,
|
||||
width,
|
||||
levelIndex,
|
||||
spanRectsArray,
|
||||
color,
|
||||
isDarkMode,
|
||||
metrics,
|
||||
selectedSpanId,
|
||||
hoveredSpanId,
|
||||
} = args;
|
||||
|
||||
const spanY = y + metrics.SPAN_BAR_Y_OFFSET;
|
||||
const isSelected = selectedSpanId === span.spanId;
|
||||
const isHovered = hoveredSpanId === span.spanId;
|
||||
const isSelectedOrHovered = isSelected || isHovered;
|
||||
|
||||
ctx.beginPath();
|
||||
ctx.roundRect(x, spanY, width, metrics.SPAN_BAR_HEIGHT, 2);
|
||||
|
||||
if (isSelectedOrHovered) {
|
||||
// Diagonal stripe pattern (repeating-linear-gradient -45deg style) + border in span color
|
||||
const pattern = createStripePattern(ctx, color);
|
||||
if (pattern) {
|
||||
ctx.fillStyle = pattern;
|
||||
ctx.fill();
|
||||
}
|
||||
if (isSelected) {
|
||||
ctx.setLineDash(DASHED_BORDER_LINE_DASH);
|
||||
}
|
||||
ctx.strokeStyle = color;
|
||||
ctx.lineWidth = isSelected ? 2 : 1;
|
||||
ctx.stroke();
|
||||
if (isSelected) {
|
||||
ctx.setLineDash([]);
|
||||
}
|
||||
} else {
|
||||
ctx.fillStyle = color;
|
||||
ctx.fill();
|
||||
}
|
||||
|
||||
spanRectsArray.push({
|
||||
span,
|
||||
x,
|
||||
y: spanY,
|
||||
width,
|
||||
height: metrics.SPAN_BAR_HEIGHT,
|
||||
level: levelIndex,
|
||||
});
|
||||
|
||||
span.event?.forEach((event) => {
|
||||
const spanDurationMs = span.durationNano / 1e6;
|
||||
if (spanDurationMs <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const eventTimeMs = event.timeUnixNano / 1e6;
|
||||
const eventOffsetPercent =
|
||||
((eventTimeMs - span.timestamp) / spanDurationMs) * 100;
|
||||
const clampedOffset = clamp(eventOffsetPercent, 1, 99);
|
||||
const eventX = x + (clampedOffset / 100) * width;
|
||||
const eventY = spanY + metrics.SPAN_BAR_HEIGHT / 2;
|
||||
|
||||
drawEventDot({
|
||||
ctx,
|
||||
x: eventX,
|
||||
y: eventY,
|
||||
isError: event.isError,
|
||||
isDarkMode,
|
||||
eventDotSize: metrics.EVENT_DOT_SIZE,
|
||||
});
|
||||
});
|
||||
|
||||
drawSpanLabel({
|
||||
ctx,
|
||||
span,
|
||||
x,
|
||||
y: spanY,
|
||||
width,
|
||||
color,
|
||||
isSelectedOrHovered,
|
||||
isDarkMode,
|
||||
spanBarHeight: metrics.SPAN_BAR_HEIGHT,
|
||||
});
|
||||
}
|
||||
|
||||
export function formatDuration(durationNano: number): string {
|
||||
const durationMs = durationNano / 1e6;
|
||||
const { time, timeUnitName } = convertTimeToRelevantUnit(durationMs);
|
||||
return `${parseFloat(time.toFixed(2))}${timeUnitName}`;
|
||||
}
|
||||
|
||||
interface DrawSpanLabelArgs {
|
||||
ctx: CanvasRenderingContext2D;
|
||||
span: FlamegraphSpan;
|
||||
x: number;
|
||||
y: number;
|
||||
width: number;
|
||||
color: string;
|
||||
isSelectedOrHovered: boolean;
|
||||
isDarkMode: boolean;
|
||||
spanBarHeight: number;
|
||||
}
|
||||
|
||||
function drawSpanLabel(args: DrawSpanLabelArgs): void {
|
||||
const {
|
||||
ctx,
|
||||
span,
|
||||
x,
|
||||
y,
|
||||
width,
|
||||
color,
|
||||
isSelectedOrHovered,
|
||||
isDarkMode,
|
||||
spanBarHeight,
|
||||
} = args;
|
||||
|
||||
if (width < MIN_WIDTH_FOR_NAME) {
|
||||
return;
|
||||
}
|
||||
|
||||
const name = span.name;
|
||||
|
||||
ctx.save();
|
||||
|
||||
// Clip text to span bar bounds
|
||||
ctx.beginPath();
|
||||
ctx.rect(x, y, width, spanBarHeight);
|
||||
ctx.clip();
|
||||
|
||||
ctx.font = LABEL_FONT;
|
||||
ctx.fillStyle = isSelectedOrHovered
|
||||
? color
|
||||
: isDarkMode
|
||||
? 'rgba(0, 0, 0, 0.9)'
|
||||
: 'rgba(255, 255, 255, 0.9)';
|
||||
ctx.textBaseline = 'middle';
|
||||
|
||||
const textY = y + spanBarHeight / 2;
|
||||
const leftX = x + LABEL_PADDING_X;
|
||||
const rightX = x + width - LABEL_PADDING_X;
|
||||
const availableWidth = width - LABEL_PADDING_X * 2;
|
||||
|
||||
if (width >= MIN_WIDTH_FOR_NAME_AND_DURATION) {
|
||||
const duration = formatDuration(span.durationNano);
|
||||
const durationWidth = ctx.measureText(duration).width;
|
||||
const minGap = 6;
|
||||
const nameSpace = availableWidth - durationWidth - minGap;
|
||||
|
||||
// Duration right-aligned
|
||||
ctx.textAlign = 'right';
|
||||
ctx.fillText(duration, rightX, textY);
|
||||
|
||||
// Name left-aligned, truncated to fit remaining space
|
||||
if (nameSpace > 20) {
|
||||
ctx.textAlign = 'left';
|
||||
ctx.fillText(truncateText(ctx, name, nameSpace), leftX, textY);
|
||||
}
|
||||
} else {
|
||||
// Name only, truncated to fit
|
||||
ctx.textAlign = 'left';
|
||||
ctx.fillText(truncateText(ctx, name, availableWidth), leftX, textY);
|
||||
}
|
||||
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
function truncateText(
|
||||
ctx: CanvasRenderingContext2D,
|
||||
text: string,
|
||||
maxWidth: number,
|
||||
): string {
|
||||
const ellipsis = '...';
|
||||
const ellipsisWidth = ctx.measureText(ellipsis).width;
|
||||
|
||||
if (ctx.measureText(text).width <= maxWidth) {
|
||||
return text;
|
||||
}
|
||||
|
||||
let lo = 0;
|
||||
let hi = text.length;
|
||||
while (lo < hi) {
|
||||
const mid = Math.ceil((lo + hi) / 2);
|
||||
if (ctx.measureText(text.slice(0, mid)).width + ellipsisWidth <= maxWidth) {
|
||||
lo = mid;
|
||||
} else {
|
||||
hi = mid - 1;
|
||||
}
|
||||
}
|
||||
|
||||
return lo > 0 ? `${text.slice(0, lo)}${ellipsis}` : ellipsis;
|
||||
}
|
||||
57
frontend/src/pages/TraceDetailsV3/index.tsx
Normal file
57
frontend/src/pages/TraceDetailsV3/index.tsx
Normal file
@@ -0,0 +1,57 @@
|
||||
import { useState } from 'react';
|
||||
import { useParams } from 'react-router-dom';
|
||||
import {
|
||||
ResizableHandle,
|
||||
ResizablePanel,
|
||||
ResizablePanelGroup,
|
||||
} from '@signozhq/resizable';
|
||||
import useGetTraceV2 from 'hooks/trace/useGetTraceV2';
|
||||
import { Span, TraceDetailV2URLProps } from 'types/api/trace/getTraceV2';
|
||||
|
||||
import TraceDetailsHeader from './TraceDetailsHeader/TraceDetailsHeader';
|
||||
import TraceFlamegraph from './TraceFlamegraph/TraceFlamegraph';
|
||||
|
||||
function TraceDetailsV3(): JSX.Element {
|
||||
const { id: traceId } = useParams<TraceDetailV2URLProps>();
|
||||
const [selectedSpan, _setSelectedSpan] = useState<Span>();
|
||||
const [uncollapsedNodes] = useState<string[]>([]);
|
||||
|
||||
const { data: traceData } = useGetTraceV2({
|
||||
traceId,
|
||||
uncollapsedSpans: uncollapsedNodes,
|
||||
selectedSpanId: '',
|
||||
isSelectedSpanIDUnCollapsed: false,
|
||||
});
|
||||
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
height: 'calc(100vh - 90px)',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
}}
|
||||
>
|
||||
<TraceDetailsHeader />
|
||||
<ResizablePanelGroup
|
||||
direction="vertical"
|
||||
autoSaveId="trace-details-v3-layout"
|
||||
style={{ flex: 1 }}
|
||||
>
|
||||
<ResizablePanel defaultSize={40} minSize={20} maxSize={80}>
|
||||
<TraceFlamegraph
|
||||
serviceExecTime={traceData?.payload?.serviceNameToTotalDurationMap || {}}
|
||||
startTime={traceData?.payload?.startTimestampMillis || 0}
|
||||
endTime={traceData?.payload?.endTimestampMillis || 0}
|
||||
selectedSpan={selectedSpan}
|
||||
/>
|
||||
</ResizablePanel>
|
||||
<ResizableHandle withHandle />
|
||||
<ResizablePanel defaultSize={60} minSize={20}>
|
||||
<div />
|
||||
</ResizablePanel>
|
||||
</ResizablePanelGroup>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default TraceDetailsV3;
|
||||
Reference in New Issue
Block a user