mirror of
https://github.com/SigNoz/signoz.git
synced 2026-11-19 14:51:11 +00:00
Compare commits
4 Commits
keystone-p
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ebc2ba4fee | ||
|
|
edcb9028ce | ||
|
|
d74035f233 | ||
|
|
d41447d4ee |
@@ -261,8 +261,8 @@ alertmanager:
|
||||
nflog:
|
||||
# Interval between garbage collection and snapshotting of the notification logs. The snapshot will be stored in the state store.
|
||||
maintenance_interval: 15m
|
||||
# Retention of the notification logs.
|
||||
retention: 120h
|
||||
# Retention of the notification logs. Must be at least twice the longest repeat interval, which is 8760h for rules with re-notify off.
|
||||
retention: 17520h
|
||||
|
||||
##################### Emailing #####################
|
||||
emailing:
|
||||
|
||||
@@ -76,49 +76,3 @@
|
||||
Object.defineProperty(window, 'Date', { value: FrozenDate, writable: true });
|
||||
})();
|
||||
</script>
|
||||
|
||||
<script>
|
||||
// Storybook has no microphone. Chromium's recognizer asks for one and for
|
||||
// Google's speech service, and the `not-allowed` or `network` it reports makes
|
||||
// the assistant hide its mic for the rest of the tab. This one starts
|
||||
// listening at once and hears only what a story passes to `hear`.
|
||||
(() => {
|
||||
class StorySpeechRecognition extends EventTarget {
|
||||
static listening = null;
|
||||
lang = 'en-US';
|
||||
continuous = false;
|
||||
interimResults = false;
|
||||
onstart = null;
|
||||
onresult = null;
|
||||
onerror = null;
|
||||
onend = null;
|
||||
|
||||
start() {
|
||||
StorySpeechRecognition.listening = this;
|
||||
setTimeout(() => this.onstart?.());
|
||||
}
|
||||
|
||||
stop() {
|
||||
if (StorySpeechRecognition.listening === this) {
|
||||
StorySpeechRecognition.listening = null;
|
||||
}
|
||||
setTimeout(() => this.onend?.());
|
||||
}
|
||||
|
||||
abort() {
|
||||
this.stop();
|
||||
}
|
||||
|
||||
/** An interim result: the words so far, still listening. */
|
||||
hear(transcript) {
|
||||
const result = Object.assign([{ transcript, confidence: 1 }], {
|
||||
isFinal: false,
|
||||
});
|
||||
this.onresult?.({ resultIndex: 0, results: [result] });
|
||||
}
|
||||
}
|
||||
|
||||
window.SpeechRecognition = StorySpeechRecognition;
|
||||
window.webkitSpeechRecognition = StorySpeechRecognition;
|
||||
})();
|
||||
</script>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import React, { Dispatch, SetStateAction, useState } from 'react';
|
||||
import { Check, Plus, X } from '@signozhq/icons';
|
||||
import { Button, Flex } from 'antd';
|
||||
import { Button } from 'antd';
|
||||
import Flex from 'periscope/components/Flex/Flex';
|
||||
import { Pill } from '@signozhq/ui/pill';
|
||||
import Input from 'components/Input';
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useCallback, useMemo, useState } from 'react';
|
||||
import { Row, Select, Spin } from 'antd';
|
||||
import { Select, Spin } from 'antd';
|
||||
import { TelemetrytypesFieldContextDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import Row from 'periscope/components/Row/Row';
|
||||
import { navigate } from 'lib/router/navigation';
|
||||
import { useAppLocation } from 'lib/router/useAppLocation';
|
||||
import {
|
||||
|
||||
@@ -6,15 +6,15 @@ import { Loader, Search } from '@signozhq/icons';
|
||||
import { Color } from '@signozhq/design-tokens';
|
||||
import {
|
||||
Button,
|
||||
Flex,
|
||||
Input,
|
||||
InputRef,
|
||||
Space,
|
||||
Spin,
|
||||
TableColumnsType,
|
||||
TableColumnType,
|
||||
Tooltip,
|
||||
} from 'antd';
|
||||
import Space from 'periscope/components/Space/Space';
|
||||
import Flex from 'periscope/components/Flex/Flex';
|
||||
import { Progress } from '@signozhq/ui/progress';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import type { FilterDropdownProps } from 'antd/lib/table/interface';
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { useCallback, useMemo, useState } from 'react';
|
||||
// eslint-disable-next-line no-restricted-imports
|
||||
import { useDispatch, useSelector } from 'react-redux';
|
||||
import { Col, Row } from 'antd';
|
||||
import Col from 'periscope/components/Col/Col';
|
||||
import Row from 'periscope/components/Row/Row';
|
||||
import { navigate } from 'lib/router/navigation';
|
||||
import { useAppLocation } from 'lib/router/useAppLocation';
|
||||
import logEvent from 'api/common/logEvent';
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Dispatch, SetStateAction, useMemo } from 'react';
|
||||
import { Col, Row } from 'antd';
|
||||
import Col from 'periscope/components/Col/Col';
|
||||
import Row from 'periscope/components/Row/Row';
|
||||
import logEvent from 'api/common/logEvent';
|
||||
import { QueryParams } from 'constants/query';
|
||||
import useUrlQuery from 'hooks/useUrlQuery';
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { useMutation } from 'react-query';
|
||||
import { Check, ChevronsDown, ScrollText, X } from '@signozhq/icons';
|
||||
import { Button, Flex, Modal } from 'antd';
|
||||
import { Button, Modal } from 'antd';
|
||||
import Flex from 'periscope/components/Flex/Flex';
|
||||
import updateUserPreference from 'api/v1/user/preferences/name/update';
|
||||
import cx from 'classnames';
|
||||
import { USER_PREFERENCES } from 'constants/userPreferences';
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import type { ComponentProps } from 'react';
|
||||
import type { Meta, StoryObj } from '@storybook/react-vite';
|
||||
import { fn } from 'storybook/test';
|
||||
|
||||
import type { GlobalMockArgs } from '@/storybook/globals';
|
||||
|
||||
import ChangelogModal from '../ChangelogModal';
|
||||
import { changelog } from './__story_mockdata__/changelog';
|
||||
|
||||
type ChangelogModalArgs = ComponentProps<typeof ChangelogModal> &
|
||||
GlobalMockArgs;
|
||||
|
||||
const meta = {
|
||||
title: 'Components/Changelog Modal',
|
||||
component: ChangelogModal,
|
||||
args: { changelog, onClose: fn() },
|
||||
} satisfies Meta<ChangelogModalArgs>;
|
||||
|
||||
export default meta;
|
||||
|
||||
type Story = StoryObj<ChangelogModalArgs>;
|
||||
|
||||
/** A cloud workspace: no upgrade actions, since cloud updates itself. */
|
||||
export const Default: Story = {};
|
||||
|
||||
/** A self-hosted workspace, offered Skip for now and Update my workspace. */
|
||||
export const SelfHosted: Story = {
|
||||
args: { license: 'enterprise' },
|
||||
};
|
||||
65
frontend/src/components/ChangelogModal/stories/__story_mockdata__/changelog.ts
generated
Normal file
65
frontend/src/components/ChangelogModal/stories/__story_mockdata__/changelog.ts
generated
Normal file
@@ -0,0 +1,65 @@
|
||||
/**
|
||||
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
|
||||
* Do not hand-edit: regenerate instead.
|
||||
*/
|
||||
|
||||
import {
|
||||
ChangelogSchema,
|
||||
DeploymentType,
|
||||
} from 'types/api/changelog/getChangelogByVersion';
|
||||
|
||||
const PUBLISHED_AT = '2026-08-12T09:00:00.000Z';
|
||||
|
||||
const feature = (
|
||||
id: number,
|
||||
title: string,
|
||||
description: string,
|
||||
): ChangelogSchema['features'][number] => ({
|
||||
id,
|
||||
documentId: `feature-${id}`,
|
||||
title,
|
||||
sort_order: id,
|
||||
createdAt: PUBLISHED_AT,
|
||||
updatedAt: PUBLISHED_AT,
|
||||
publishedAt: PUBLISHED_AT,
|
||||
description,
|
||||
deployment_type: DeploymentType.ALL,
|
||||
// Media stays null so no story reaches out to the CMS for an image.
|
||||
media: null,
|
||||
});
|
||||
|
||||
export const changelog: ChangelogSchema = {
|
||||
id: 1,
|
||||
documentId: 'changelog-v0-99-0',
|
||||
version: 'v0.99.0',
|
||||
release_date: '2026-08-12',
|
||||
createdAt: PUBLISHED_AT,
|
||||
updatedAt: PUBLISHED_AT,
|
||||
publishedAt: PUBLISHED_AT,
|
||||
features: [
|
||||
feature(
|
||||
1,
|
||||
'Metrics explorer',
|
||||
'Browse every metric you send, inspect its labels and turn it into a panel without writing a query.\n\n- Search metrics by name, type or unit\n- See cardinality per label before you group by it\n- Open any metric straight in the query builder\n\nRead more in the [metrics explorer docs](https://signoz.io/docs/metrics-management/metrics-explorer/).',
|
||||
),
|
||||
feature(
|
||||
2,
|
||||
'Trace funnels',
|
||||
'Measure conversion and drop-off across a multi-service request path. Define each step as a span filter, then compare the latency and error rate between any two steps.',
|
||||
),
|
||||
feature(
|
||||
3,
|
||||
'Saved views for logs',
|
||||
'Save a logs query with its columns and time range, share it with your team and pin the ones you open most.',
|
||||
),
|
||||
feature(
|
||||
4,
|
||||
'Alert history',
|
||||
'Every alert now keeps a timeline of its state changes, with the value that crossed the threshold and the labels it fired for.',
|
||||
),
|
||||
],
|
||||
bug_fixes:
|
||||
'- Fixed dashboard variables losing their selection on refresh.\n- Fixed alert history pagination skipping a page.\n- Fixed the logs list jumping to the top after a live tail update.',
|
||||
maintenance:
|
||||
'- Upgraded the query service to Go 1.24.\n- Reduced the ClickHouse memory used by trace aggregation queries.',
|
||||
};
|
||||
28
frontend/src/components/DotGrid/DotGrid.module.scss
Normal file
28
frontend/src/components/DotGrid/DotGrid.module.scss
Normal file
@@ -0,0 +1,28 @@
|
||||
.dotGrid {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.canvas {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
// Read by the snake as its colour on the light page.
|
||||
color: var(--l1-foreground);
|
||||
}
|
||||
|
||||
// The Snake score line, faint in the grid's bottom-left corner.
|
||||
.label {
|
||||
position: absolute;
|
||||
left: var(--spacing-6);
|
||||
bottom: var(--spacing-1);
|
||||
font-family: var(--font-mono, monospace);
|
||||
font-size: var(--periscope-font-size-small);
|
||||
letter-spacing: 0.34em;
|
||||
text-transform: uppercase;
|
||||
white-space: nowrap;
|
||||
color: var(--l3-foreground);
|
||||
pointer-events: none;
|
||||
user-select: none;
|
||||
}
|
||||
35
frontend/src/components/DotGrid/DotGrid.tsx
Normal file
35
frontend/src/components/DotGrid/DotGrid.tsx
Normal file
@@ -0,0 +1,35 @@
|
||||
import { useRef } from 'react';
|
||||
import cx from 'classnames';
|
||||
import { useIsDarkMode } from 'hooks/useDarkMode';
|
||||
|
||||
import { useDotGrid } from './useDotGrid';
|
||||
|
||||
import styles from './DotGrid.module.scss';
|
||||
|
||||
interface DotGridProps {
|
||||
/** Sizes and places the grid; it fills whatever box it gets. */
|
||||
className?: string;
|
||||
/** Called when a Snake game starts or ends. */
|
||||
onGameChange?: (isPlaying: boolean) => void;
|
||||
}
|
||||
|
||||
/** Aurora dot grid that drifts on its own and lights up under the cursor. */
|
||||
export default function DotGrid({
|
||||
className,
|
||||
onGameChange,
|
||||
}: DotGridProps): JSX.Element {
|
||||
const canvasRef = useRef<HTMLCanvasElement>(null);
|
||||
const isDarkMode = useIsDarkMode();
|
||||
const label = useDotGrid(canvasRef, isDarkMode, onGameChange);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cx(styles.dotGrid, className)}
|
||||
data-testid="ai-dot-grid"
|
||||
aria-hidden
|
||||
>
|
||||
<canvas ref={canvasRef} className={styles.canvas} />
|
||||
{label && <span className={styles.label}>{label}</span>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
103
frontend/src/components/DotGrid/__tests__/DotGrid.test.tsx
Normal file
103
frontend/src/components/DotGrid/__tests__/DotGrid.test.tsx
Normal file
@@ -0,0 +1,103 @@
|
||||
import { useRef } from 'react';
|
||||
import { act, render, screen, userEvent } from 'tests/test-utils';
|
||||
|
||||
import DotGrid from '../DotGrid';
|
||||
import { useDotGrid } from '../useDotGrid';
|
||||
|
||||
const KONAMI =
|
||||
'{ArrowUp}{ArrowUp}{ArrowDown}{ArrowDown}{ArrowLeft}{ArrowRight}{ArrowLeft}{ArrowRight}ba';
|
||||
|
||||
function Chat({
|
||||
onGameChange,
|
||||
}: {
|
||||
onGameChange: (isPlaying: boolean) => void;
|
||||
}): JSX.Element {
|
||||
return (
|
||||
<div>
|
||||
<DotGrid onGameChange={onGameChange} />
|
||||
<textarea data-testid="chat-textarea" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ThemedGrid({ isDarkMode }: { isDarkMode: boolean }): JSX.Element {
|
||||
const canvasRef = useRef<HTMLCanvasElement>(null);
|
||||
const label = useDotGrid(canvasRef, isDarkMode);
|
||||
return (
|
||||
<>
|
||||
<canvas ref={canvasRef} />
|
||||
<span data-testid="score-line">{label}</span>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
describe('DotGrid Snake', () => {
|
||||
beforeEach(() => {
|
||||
jest.useFakeTimers();
|
||||
// jsdom has no canvas or layout: a 9 × 7 game grid is enough for a snake.
|
||||
jest
|
||||
.spyOn(HTMLCanvasElement.prototype, 'getContext')
|
||||
.mockReturnValue(
|
||||
new Proxy({}, { get: () => jest.fn() }) as CanvasRenderingContext2D,
|
||||
);
|
||||
jest.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockReturnValue(120);
|
||||
jest.spyOn(HTMLElement.prototype, 'clientHeight', 'get').mockReturnValue(120);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.useRealTimers();
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('quits the game on Esc and hands the keyboard back', async () => {
|
||||
const user = userEvent.setup({
|
||||
advanceTimers: (ms) => jest.advanceTimersByTime(ms),
|
||||
});
|
||||
const onGameChange = jest.fn();
|
||||
render(<Chat onGameChange={onGameChange} />);
|
||||
|
||||
await user.keyboard(KONAMI);
|
||||
expect(onGameChange).toHaveBeenLastCalledWith(true);
|
||||
expect(screen.getByTestId('ai-dot-grid')).toHaveTextContent(
|
||||
'Snake · score 0 · ↑ ↓ ← → · Esc to quit',
|
||||
);
|
||||
|
||||
await user.keyboard('{Escape}');
|
||||
|
||||
expect(onGameChange).toHaveBeenLastCalledWith(false);
|
||||
expect(screen.getByTestId('ai-dot-grid')).not.toHaveTextContent('Snake');
|
||||
});
|
||||
|
||||
it('leaves arrows in the chat input alone after game over', async () => {
|
||||
const user = userEvent.setup({
|
||||
advanceTimers: (ms) => jest.advanceTimersByTime(ms),
|
||||
});
|
||||
const onGameChange = jest.fn();
|
||||
render(<Chat onGameChange={onGameChange} />);
|
||||
await user.keyboard(KONAMI);
|
||||
// Heading right, the snake reaches the wall within a few steps.
|
||||
act(() => {
|
||||
jest.advanceTimersByTime(1500);
|
||||
});
|
||||
expect(screen.getByTestId('ai-dot-grid')).toHaveTextContent('Game over');
|
||||
onGameChange.mockClear();
|
||||
|
||||
await user.click(screen.getByTestId('chat-textarea'));
|
||||
await user.keyboard('{ArrowUp}');
|
||||
|
||||
expect(onGameChange).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('drops the score line when the theme changes mid-game', async () => {
|
||||
const user = userEvent.setup({
|
||||
advanceTimers: (ms) => jest.advanceTimersByTime(ms),
|
||||
});
|
||||
const { rerender } = render(<ThemedGrid isDarkMode />);
|
||||
await user.keyboard(KONAMI);
|
||||
expect(screen.getByTestId('score-line')).toHaveTextContent('Snake · score 0');
|
||||
|
||||
rerender(<ThemedGrid isDarkMode={false} />);
|
||||
|
||||
expect(screen.getByTestId('score-line')).toBeEmptyDOMElement();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,32 @@
|
||||
import { getSnakeColors } from '../dotGridTheme';
|
||||
|
||||
function canvasWithInk(ink: string): HTMLCanvasElement {
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.style.color = ink;
|
||||
document.body.appendChild(canvas);
|
||||
return canvas;
|
||||
}
|
||||
|
||||
describe('getSnakeColors', () => {
|
||||
afterEach(() => {
|
||||
document.body.innerHTML = '';
|
||||
});
|
||||
|
||||
it('keeps the snake white on the dark page', () => {
|
||||
expect(getSnakeColors(canvasWithInk('rgb(30, 31, 36)'), true)).toStrictEqual({
|
||||
head: 'rgba(255,255,255,1)',
|
||||
body: 'rgba(232,238,245,0.92)',
|
||||
food: 'rgba(255,255,255,0.97)',
|
||||
});
|
||||
});
|
||||
|
||||
it('draws the snake in the page ink on the light page', () => {
|
||||
expect(getSnakeColors(canvasWithInk('rgb(30, 31, 36)'), false)).toStrictEqual(
|
||||
{
|
||||
head: 'rgba(30,31,36,1)',
|
||||
body: 'rgba(30,31,36,0.85)',
|
||||
food: 'rgba(30,31,36,0.95)',
|
||||
},
|
||||
);
|
||||
});
|
||||
});
|
||||
112
frontend/src/components/DotGrid/__tests__/snakeGame.test.ts
Normal file
112
frontend/src/components/DotGrid/__tests__/snakeGame.test.ts
Normal file
@@ -0,0 +1,112 @@
|
||||
import { SnakeGame, startSnake, stepSnake } from '../snakeGame';
|
||||
|
||||
const COLS = 10;
|
||||
const ROWS = 6;
|
||||
|
||||
function newGame(): SnakeGame {
|
||||
const game = startSnake(COLS, ROWS);
|
||||
if (!game) {
|
||||
throw new Error('a 10 × 6 grid fits a game');
|
||||
}
|
||||
return game;
|
||||
}
|
||||
|
||||
describe('snakeGame', () => {
|
||||
beforeEach(() => {
|
||||
// Food lands on the first free cell, the top-left corner.
|
||||
jest.spyOn(Math, 'random').mockReturnValue(0);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('needs at least an 8 × 6 grid', () => {
|
||||
expect(startSnake(7, 6)).toBeNull();
|
||||
expect(startSnake(8, 5)).toBeNull();
|
||||
});
|
||||
|
||||
it('starts four cells long in the middle, heading right', () => {
|
||||
expect(newGame()).toStrictEqual({
|
||||
body: [
|
||||
{ c: 5, r: 3 },
|
||||
{ c: 4, r: 3 },
|
||||
{ c: 3, r: 3 },
|
||||
{ c: 2, r: 3 },
|
||||
],
|
||||
dir: { c: 1, r: 0 },
|
||||
nextDir: { c: 1, r: 0 },
|
||||
food: { c: 0, r: 0 },
|
||||
score: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it('moves one cell in its direction', () => {
|
||||
const next = stepSnake(newGame(), COLS, ROWS);
|
||||
|
||||
expect(next?.body).toStrictEqual([
|
||||
{ c: 6, r: 3 },
|
||||
{ c: 5, r: 3 },
|
||||
{ c: 4, r: 3 },
|
||||
{ c: 3, r: 3 },
|
||||
]);
|
||||
expect(next?.score).toBe(0);
|
||||
});
|
||||
|
||||
it('grows and scores when it eats', () => {
|
||||
const next = stepSnake({ ...newGame(), food: { c: 6, r: 3 } }, COLS, ROWS);
|
||||
|
||||
expect(next?.body).toHaveLength(5);
|
||||
expect(next?.score).toBe(1);
|
||||
});
|
||||
|
||||
it('ends when it hits a wall', () => {
|
||||
const atEdge: SnakeGame = {
|
||||
...newGame(),
|
||||
body: [
|
||||
{ c: 9, r: 3 },
|
||||
{ c: 8, r: 3 },
|
||||
{ c: 7, r: 3 },
|
||||
{ c: 6, r: 3 },
|
||||
],
|
||||
};
|
||||
|
||||
expect(stepSnake(atEdge, COLS, ROWS)).toBeNull();
|
||||
});
|
||||
|
||||
it('ends when it runs into itself', () => {
|
||||
const coiled: SnakeGame = {
|
||||
...newGame(),
|
||||
body: [
|
||||
{ c: 5, r: 3 },
|
||||
{ c: 5, r: 4 },
|
||||
{ c: 6, r: 4 },
|
||||
{ c: 6, r: 3 },
|
||||
{ c: 7, r: 3 },
|
||||
],
|
||||
};
|
||||
|
||||
expect(stepSnake(coiled, COLS, ROWS)).toBeNull();
|
||||
});
|
||||
|
||||
it('moves into the cell its tail is leaving', () => {
|
||||
const up = { c: 0, r: -1 };
|
||||
const turnedDownThenLeft: SnakeGame = {
|
||||
...newGame(),
|
||||
body: [
|
||||
{ c: 4, r: 4 },
|
||||
{ c: 5, r: 4 },
|
||||
{ c: 5, r: 3 },
|
||||
{ c: 4, r: 3 },
|
||||
],
|
||||
nextDir: up,
|
||||
};
|
||||
|
||||
expect(stepSnake(turnedDownThenLeft, COLS, ROWS)?.body).toStrictEqual([
|
||||
{ c: 4, r: 3 },
|
||||
{ c: 4, r: 4 },
|
||||
{ c: 5, r: 4 },
|
||||
{ c: 5, r: 3 },
|
||||
]);
|
||||
});
|
||||
});
|
||||
53
frontend/src/components/DotGrid/dotGridField.ts
Normal file
53
frontend/src/components/DotGrid/dotGridField.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
export const DOT_SPACING = 12;
|
||||
export const DOT_RADIUS = 1.15;
|
||||
|
||||
export const TRAIL_RADIUS = 72;
|
||||
export const TRAIL_LIFT = 0.24;
|
||||
export const TRAIL_MAX_POINTS = 18;
|
||||
export const TRAIL_LIFE_MS = 1000;
|
||||
export const TRAIL_MIN_STEP = 7;
|
||||
|
||||
// Time the field rests at when motion is reduced.
|
||||
export const STILL_TIME_MS = 12000;
|
||||
|
||||
type Rgb = [number, number, number];
|
||||
|
||||
// Green, teal, blue, violet and pink, in the order the field drifts through them.
|
||||
const AURORA: Rgb[] = [
|
||||
[64, 224, 150],
|
||||
[48, 200, 210],
|
||||
[90, 130, 245],
|
||||
[170, 110, 245],
|
||||
[235, 110, 200],
|
||||
];
|
||||
|
||||
/** Brightness of the field at a point, between -1 and 1. */
|
||||
export function auroraBrightness(x: number, y: number, t: number): number {
|
||||
return (
|
||||
(Math.sin(x * 0.009 + t * 0.0006) +
|
||||
Math.sin(y * 0.015 - t * 0.00085 + x * 0.002) +
|
||||
Math.sin((x + y) * 0.006 + t * 0.0011) +
|
||||
Math.sin((x - y) * 0.0048 - t * 0.0007)) /
|
||||
4
|
||||
);
|
||||
}
|
||||
|
||||
/** Colour of the field at a point, blended along the aurora palette. */
|
||||
export function auroraColor(x: number, y: number, t: number): Rgb {
|
||||
const position =
|
||||
((Math.sin(x * 0.0035 + t * 0.00018) +
|
||||
Math.sin(y * 0.005 - t * 0.00026) +
|
||||
Math.sin((x + y) * 0.0028 + t * 0.0002)) /
|
||||
3 +
|
||||
1) /
|
||||
2;
|
||||
const scaled = position * (AURORA.length - 1);
|
||||
const from = AURORA[Math.floor(scaled)];
|
||||
const to = AURORA[Math.min(Math.floor(scaled) + 1, AURORA.length - 1)];
|
||||
const mix = scaled - Math.floor(scaled);
|
||||
return [
|
||||
from[0] + (to[0] - from[0]) * mix,
|
||||
from[1] + (to[1] - from[1]) * mix,
|
||||
from[2] + (to[2] - from[2]) * mix,
|
||||
];
|
||||
}
|
||||
34
frontend/src/components/DotGrid/dotGridTheme.ts
Normal file
34
frontend/src/components/DotGrid/dotGridTheme.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
// Colours for the dot grid that depend on the page behind it.
|
||||
|
||||
export interface SnakeColors {
|
||||
head: string;
|
||||
body: string;
|
||||
food: string;
|
||||
}
|
||||
|
||||
const DARK_SNAKE: SnakeColors = {
|
||||
head: 'rgba(255,255,255,1)',
|
||||
body: 'rgba(232,238,245,0.92)',
|
||||
food: 'rgba(255,255,255,0.97)',
|
||||
};
|
||||
|
||||
function withAlpha(rgb: string, alpha: number): string {
|
||||
const channels = rgb.match(/\d+(\.\d+)?/g)?.slice(0, 3) ?? ['0', '0', '0'];
|
||||
return `rgba(${channels.join(',')},${alpha})`;
|
||||
}
|
||||
|
||||
/** Snake colours: white on the dark page, the canvas's ink (`color`) on the light one. */
|
||||
export function getSnakeColors(
|
||||
canvas: HTMLCanvasElement,
|
||||
isDarkMode: boolean,
|
||||
): SnakeColors {
|
||||
if (isDarkMode) {
|
||||
return DARK_SNAKE;
|
||||
}
|
||||
const ink = getComputedStyle(canvas).color;
|
||||
return {
|
||||
head: withAlpha(ink, 1),
|
||||
body: withAlpha(ink, 0.85),
|
||||
food: withAlpha(ink, 0.95),
|
||||
};
|
||||
}
|
||||
102
frontend/src/components/DotGrid/drawDots.ts
Normal file
102
frontend/src/components/DotGrid/drawDots.ts
Normal file
@@ -0,0 +1,102 @@
|
||||
// Painting for the dot grid: the aurora field with the cursor's glow, and plain dots.
|
||||
|
||||
import {
|
||||
auroraBrightness,
|
||||
auroraColor,
|
||||
DOT_RADIUS,
|
||||
TRAIL_LIFE_MS,
|
||||
TRAIL_LIFT,
|
||||
TRAIL_RADIUS,
|
||||
} from './dotGridField';
|
||||
|
||||
// Coloured dots on white read fainter than lit ones on black.
|
||||
const LIGHT_ALPHA_BOOST = 1.6;
|
||||
|
||||
export interface TrailPoint {
|
||||
x: number;
|
||||
y: number;
|
||||
born: number;
|
||||
}
|
||||
|
||||
interface AuroraFrame {
|
||||
/** Field time; frozen when motion is reduced. */
|
||||
t: number;
|
||||
now: number;
|
||||
height: number;
|
||||
trail: TrailPoint[];
|
||||
isGameOn: boolean;
|
||||
/** Light adds up on the dark page; on the light one colours sit on the paper instead. */
|
||||
isDarkMode: boolean;
|
||||
/** Dots below this stay dark. */
|
||||
cutoffY: number;
|
||||
}
|
||||
|
||||
/** The faint light that washes up from the bottom while the game is on. */
|
||||
export function gameFloor(y: number, height: number): number {
|
||||
return 0.07 + 0.16 * (y / height);
|
||||
}
|
||||
|
||||
export function drawDot(
|
||||
ctx: CanvasRenderingContext2D,
|
||||
x: number,
|
||||
y: number,
|
||||
radius: number,
|
||||
fill: string,
|
||||
): void {
|
||||
ctx.beginPath();
|
||||
ctx.fillStyle = fill;
|
||||
ctx.arc(x, y, radius, 0, Math.PI * 2);
|
||||
ctx.fill();
|
||||
}
|
||||
|
||||
/** Paints the aurora dots, brightest at the top and lit along the cursor's trail. */
|
||||
export function drawAuroraDots(
|
||||
ctx: CanvasRenderingContext2D,
|
||||
dots: { x: number; y: number }[],
|
||||
{ t, now, height, trail, isGameOn, isDarkMode, cutoffY }: AuroraFrame,
|
||||
): void {
|
||||
// Overlapping glows add up, as light does.
|
||||
ctx.globalCompositeOperation = isDarkMode ? 'lighter' : 'source-over';
|
||||
dots.forEach(({ x, y }) => {
|
||||
if (y > cutoffY) {
|
||||
return;
|
||||
}
|
||||
// Brightest at the top, fading toward the content below.
|
||||
const topWeight = 1 - 0.82 * Math.min(1, y / height);
|
||||
const lum = Math.max(0, auroraBrightness(x, y, t)) ** 1.6;
|
||||
let intensity = (0.06 + lum * 0.4) * topWeight * (isGameOn ? 0.5 : 1);
|
||||
if (isGameOn) {
|
||||
intensity += gameFloor(y, height);
|
||||
}
|
||||
|
||||
let glow = 0;
|
||||
trail.forEach((point) => {
|
||||
const distance2 = (x - point.x) ** 2 + (y - point.y) ** 2;
|
||||
if (distance2 < TRAIL_RADIUS ** 2) {
|
||||
const life = 1 - (now - point.born) / TRAIL_LIFE_MS;
|
||||
glow += (1 - distance2 / TRAIL_RADIUS ** 2) ** 3 * life;
|
||||
}
|
||||
});
|
||||
intensity += Math.min(glow, 1.3) * TRAIL_LIFT * topWeight;
|
||||
|
||||
if (intensity <= 0.02) {
|
||||
return;
|
||||
}
|
||||
const [red, green, blue] = auroraColor(x, y, t);
|
||||
// The hottest dots burn toward white on the dark page and deepen on the light one.
|
||||
const heat = Math.min(1, Math.max(0, intensity - 0.9)) * 0.9;
|
||||
const toward = isDarkMode ? 255 : 0;
|
||||
const mix = isDarkMode ? heat : heat * 0.4;
|
||||
const rgb = `${Math.round(red + (toward - red) * mix)},${Math.round(
|
||||
green + (toward - green) * mix,
|
||||
)},${Math.round(blue + (toward - blue) * mix)}`;
|
||||
const alpha = Math.min(1, intensity * (isDarkMode ? 1 : LIGHT_ALPHA_BOOST));
|
||||
const radius = DOT_RADIUS + Math.min(intensity, 1.2) * 0.7;
|
||||
|
||||
if (intensity > 0.6) {
|
||||
drawDot(ctx, x, y, radius * 2.6, `rgba(${rgb},${alpha * 0.06})`);
|
||||
}
|
||||
drawDot(ctx, x, y, radius, `rgba(${rgb},${alpha})`);
|
||||
});
|
||||
ctx.globalCompositeOperation = 'source-over';
|
||||
}
|
||||
100
frontend/src/components/DotGrid/snakeGame.ts
Normal file
100
frontend/src/components/DotGrid/snakeGame.ts
Normal file
@@ -0,0 +1,100 @@
|
||||
// Snake on the dot grid, the easter egg the Konami code unlocks.
|
||||
|
||||
interface Cell {
|
||||
c: number;
|
||||
r: number;
|
||||
}
|
||||
|
||||
export interface SnakeGame {
|
||||
body: Cell[];
|
||||
dir: Cell;
|
||||
nextDir: Cell;
|
||||
food: Cell;
|
||||
score: number;
|
||||
}
|
||||
|
||||
export const SNAKE_STEP_MS = 110;
|
||||
|
||||
// Lowercase: keys are lowercased before matching, so B/b and A/a both count.
|
||||
export const KONAMI_CODE = [
|
||||
'arrowup',
|
||||
'arrowup',
|
||||
'arrowdown',
|
||||
'arrowdown',
|
||||
'arrowleft',
|
||||
'arrowright',
|
||||
'arrowleft',
|
||||
'arrowright',
|
||||
'b',
|
||||
'a',
|
||||
];
|
||||
|
||||
export const SNAKE_DIRECTIONS: Record<string, Cell> = {
|
||||
arrowup: { c: 0, r: -1 },
|
||||
w: { c: 0, r: -1 },
|
||||
arrowdown: { c: 0, r: 1 },
|
||||
s: { c: 0, r: 1 },
|
||||
arrowleft: { c: -1, r: 0 },
|
||||
a: { c: -1, r: 0 },
|
||||
arrowright: { c: 1, r: 0 },
|
||||
d: { c: 1, r: 0 },
|
||||
};
|
||||
|
||||
const isOn = (cells: Cell[], cell: Cell): boolean =>
|
||||
cells.some(({ c, r }) => c === cell.c && r === cell.r);
|
||||
|
||||
/** A free cell for the food, or null when the snake fills the grid. */
|
||||
function placeFood(body: Cell[], cols: number, rows: number): Cell | null {
|
||||
const free: Cell[] = [];
|
||||
for (let r = 0; r < rows; r += 1) {
|
||||
for (let c = 0; c < cols; c += 1) {
|
||||
if (!isOn(body, { c, r })) {
|
||||
free.push({ c, r });
|
||||
}
|
||||
}
|
||||
}
|
||||
return free.length ? free[Math.floor(Math.random() * free.length)] : null;
|
||||
}
|
||||
|
||||
/** A four-cell snake in the middle heading right, or null when the grid is too small. */
|
||||
export function startSnake(cols: number, rows: number): SnakeGame | null {
|
||||
if (cols < 8 || rows < 6) {
|
||||
return null;
|
||||
}
|
||||
const c = Math.floor(cols / 2);
|
||||
const r = Math.floor(rows / 2);
|
||||
const body = [0, 1, 2, 3].map((i) => ({ c: c - i, r }));
|
||||
const food = placeFood(body, cols, rows);
|
||||
if (!food) {
|
||||
return null;
|
||||
}
|
||||
const right = { c: 1, r: 0 };
|
||||
return { body, dir: right, nextDir: right, food, score: 0 };
|
||||
}
|
||||
|
||||
/** Moves the snake one cell; null when it hits a wall, itself, or fills the grid. */
|
||||
export function stepSnake(
|
||||
game: SnakeGame,
|
||||
cols: number,
|
||||
rows: number,
|
||||
): SnakeGame | null {
|
||||
const dir = game.nextDir;
|
||||
const head = { c: game.body[0].c + dir.c, r: game.body[0].r + dir.r };
|
||||
const ate = head.c === game.food.c && head.r === game.food.r;
|
||||
const kept = ate ? game.body : game.body.slice(0, -1);
|
||||
if (
|
||||
head.c < 0 ||
|
||||
head.c >= cols ||
|
||||
head.r < 0 ||
|
||||
head.r >= rows ||
|
||||
isOn(kept, head)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
const body = [head, ...kept];
|
||||
const food = ate ? placeFood(body, cols, rows) : game.food;
|
||||
if (!food) {
|
||||
return null;
|
||||
}
|
||||
return { ...game, body, dir, food, score: game.score + (ate ? 1 : 0) };
|
||||
}
|
||||
320
frontend/src/components/DotGrid/useDotGrid.ts
Normal file
320
frontend/src/components/DotGrid/useDotGrid.ts
Normal file
@@ -0,0 +1,320 @@
|
||||
import { RefObject, useEffect, useLayoutEffect, useRef, useState } from 'react';
|
||||
|
||||
import {
|
||||
DOT_RADIUS,
|
||||
DOT_SPACING,
|
||||
STILL_TIME_MS,
|
||||
TRAIL_LIFE_MS,
|
||||
TRAIL_MAX_POINTS,
|
||||
TRAIL_MIN_STEP,
|
||||
TRAIL_RADIUS,
|
||||
} from './dotGridField';
|
||||
import { drawAuroraDots, drawDot, gameFloor, TrailPoint } from './drawDots';
|
||||
import {
|
||||
KONAMI_CODE,
|
||||
SNAKE_DIRECTIONS,
|
||||
SNAKE_STEP_MS,
|
||||
SnakeGame,
|
||||
startSnake,
|
||||
stepSnake,
|
||||
} from './snakeGame';
|
||||
import { getSnakeColors } from './dotGridTheme';
|
||||
|
||||
const GAME_OVER_LABEL_MS = 4000;
|
||||
const REPLAY_LABEL = '↑ to replay';
|
||||
const playingLabel = (score: number): string =>
|
||||
`Snake · score ${score} · ↑ ↓ ← → · Esc to quit`;
|
||||
|
||||
// Unlocked once per page load; after that a click on the dots starts a game.
|
||||
let isSnakeUnlocked = false;
|
||||
// Room left under the snake's lowest row for the score line, so the two never touch.
|
||||
const SCORE_LINE_CLEARANCE = 30;
|
||||
|
||||
const isField = (target: EventTarget | null): target is HTMLElement =>
|
||||
target instanceof HTMLElement &&
|
||||
Boolean(target.closest('input, textarea, select, [contenteditable="true"]'));
|
||||
|
||||
/** Draws the aurora dot grid; the Konami code turns it into Snake. Returns the score line. */
|
||||
export function useDotGrid(
|
||||
canvasRef: RefObject<HTMLCanvasElement>,
|
||||
isDarkMode: boolean,
|
||||
onGameChange?: (isPlaying: boolean) => void,
|
||||
): string | null {
|
||||
const [label, setLabel] = useState<string | null>(null);
|
||||
const onGameChangeRef = useRef(onGameChange);
|
||||
useLayoutEffect(() => {
|
||||
onGameChangeRef.current = onGameChange;
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
const canvas = canvasRef.current;
|
||||
const ctx = canvas?.getContext('2d');
|
||||
if (!canvas || !ctx) {
|
||||
return undefined;
|
||||
}
|
||||
const isStill = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
|
||||
const snakeColors = getSnakeColors(canvas, isDarkMode);
|
||||
|
||||
let width = 0;
|
||||
let height = 0;
|
||||
let cols = 0;
|
||||
let rows = 0;
|
||||
let gameRows = 0;
|
||||
let left = 0;
|
||||
let dots: { x: number; y: number }[] = [];
|
||||
const trail: TrailPoint[] = [];
|
||||
let frame = 0;
|
||||
let game: SnakeGame | null = null;
|
||||
let lastStep = 0;
|
||||
// With reduced motion the field stands still, so frames repaint only after a change.
|
||||
let needsDraw = true;
|
||||
let isScoreLineShown = false;
|
||||
const showScoreLine = (text: string | null): void => {
|
||||
isScoreLineShown = text !== null;
|
||||
needsDraw = true;
|
||||
setLabel(text);
|
||||
};
|
||||
const recentKeys: string[] = [];
|
||||
let labelTimer = 0;
|
||||
// An arrow key replays while the game over line is up.
|
||||
let canReplay = false;
|
||||
const showPlayCursor = (): void => {
|
||||
canvas.style.cursor = isSnakeUnlocked && !game ? 'pointer' : '';
|
||||
};
|
||||
|
||||
const cellCenter = (c: number, r: number): { x: number; y: number } => ({
|
||||
x: left + c * DOT_SPACING,
|
||||
y: DOT_SPACING + r * DOT_SPACING,
|
||||
});
|
||||
|
||||
const play = (): void => {
|
||||
game = startSnake(cols, gameRows);
|
||||
lastStep = performance.now();
|
||||
canReplay = false;
|
||||
window.clearTimeout(labelTimer);
|
||||
showScoreLine(game ? playingLabel(0) : null);
|
||||
showPlayCursor();
|
||||
onGameChangeRef.current?.(game !== null);
|
||||
};
|
||||
const quit = (): void => {
|
||||
game = null;
|
||||
canReplay = false;
|
||||
window.clearTimeout(labelTimer);
|
||||
showScoreLine(null);
|
||||
showPlayCursor();
|
||||
onGameChangeRef.current?.(false);
|
||||
};
|
||||
const endGame = (score: number): void => {
|
||||
game = null;
|
||||
canReplay = true;
|
||||
showScoreLine(`Game over · score ${score} · ${REPLAY_LABEL}`);
|
||||
showPlayCursor();
|
||||
onGameChangeRef.current?.(false);
|
||||
labelTimer = window.setTimeout(() => {
|
||||
canReplay = false;
|
||||
showScoreLine(null);
|
||||
}, GAME_OVER_LABEL_MS);
|
||||
};
|
||||
|
||||
const layout = (): void => {
|
||||
const dpr = Math.min(window.devicePixelRatio || 1, 2);
|
||||
width = canvas.clientWidth;
|
||||
height = canvas.clientHeight;
|
||||
canvas.width = Math.floor(width * dpr);
|
||||
canvas.height = Math.floor(height * dpr);
|
||||
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
|
||||
|
||||
cols = Math.max(0, Math.floor((width - DOT_SPACING) / DOT_SPACING));
|
||||
rows = Math.max(0, Math.floor((height - DOT_SPACING) / DOT_SPACING));
|
||||
gameRows = Math.min(
|
||||
rows,
|
||||
Math.max(0, Math.floor((height - SCORE_LINE_CLEARANCE) / DOT_SPACING)),
|
||||
);
|
||||
left = (width - cols * DOT_SPACING) / 2 + DOT_SPACING / 2;
|
||||
dots = [];
|
||||
for (let r = 0; r < rows; r += 1) {
|
||||
for (let c = 0; c < cols; c += 1) {
|
||||
dots.push(cellCenter(c, r));
|
||||
}
|
||||
}
|
||||
needsDraw = true;
|
||||
// A game carries on through a resize unless it no longer fits.
|
||||
if (
|
||||
game &&
|
||||
[...game.body, game.food].some(({ c, r }) => c >= cols || r >= gameRows)
|
||||
) {
|
||||
play();
|
||||
}
|
||||
};
|
||||
|
||||
const onPointer = (event: PointerEvent): void => {
|
||||
const rect = canvas.getBoundingClientRect();
|
||||
const x = event.clientX - rect.left;
|
||||
const y = event.clientY - rect.top;
|
||||
if (
|
||||
x < -TRAIL_RADIUS ||
|
||||
y < -TRAIL_RADIUS ||
|
||||
x > width + TRAIL_RADIUS ||
|
||||
y > height + TRAIL_RADIUS
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const head = trail[trail.length - 1];
|
||||
// Barely moved: keep the head lit instead of stacking points.
|
||||
if (head && Math.hypot(x - head.x, y - head.y) < TRAIL_MIN_STEP) {
|
||||
head.born = performance.now();
|
||||
return;
|
||||
}
|
||||
trail.push({ x, y, born: performance.now() });
|
||||
if (trail.length > TRAIL_MAX_POINTS) {
|
||||
trail.shift();
|
||||
}
|
||||
};
|
||||
|
||||
// Keys typed into a field outside this chat belong to that field.
|
||||
const isOtherField = (target: EventTarget | null): boolean => {
|
||||
if (!isField(target)) {
|
||||
return false;
|
||||
}
|
||||
let chat = canvas.parentElement;
|
||||
while (chat && !chat.querySelector('textarea')) {
|
||||
chat = chat.parentElement;
|
||||
}
|
||||
return !chat?.contains(target);
|
||||
};
|
||||
|
||||
const onKeyDown = (event: KeyboardEvent): void => {
|
||||
if (isOtherField(event.target)) {
|
||||
return;
|
||||
}
|
||||
const key = event.key.toLowerCase();
|
||||
if (game) {
|
||||
if (key === 'escape') {
|
||||
event.preventDefault();
|
||||
quit();
|
||||
return;
|
||||
}
|
||||
const next = SNAKE_DIRECTIONS[key];
|
||||
if (next) {
|
||||
// Steering keys drive the snake, not the input; no turning back onto the neck.
|
||||
event.preventDefault();
|
||||
if (next.c !== -game.dir.c || next.r !== -game.dir.r) {
|
||||
game.nextDir = next;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
// Arrows in the chat's input move its caret instead.
|
||||
if (canReplay && key.startsWith('arrow') && !isField(event.target)) {
|
||||
event.preventDefault();
|
||||
play();
|
||||
return;
|
||||
}
|
||||
recentKeys.push(key);
|
||||
if (recentKeys.length > KONAMI_CODE.length) {
|
||||
recentKeys.shift();
|
||||
}
|
||||
if (recentKeys.join() === KONAMI_CODE.join()) {
|
||||
recentKeys.length = 0;
|
||||
isSnakeUnlocked = true;
|
||||
play();
|
||||
}
|
||||
};
|
||||
|
||||
const onClick = (): void => {
|
||||
if (isSnakeUnlocked && !game) {
|
||||
play();
|
||||
}
|
||||
};
|
||||
|
||||
// The snake and its food: flat white dots the size of their neighbours.
|
||||
const stepAndDrawSnake = (now: number): void => {
|
||||
if (game && now - lastStep >= SNAKE_STEP_MS) {
|
||||
lastStep = now;
|
||||
const next = stepSnake(game, cols, gameRows);
|
||||
if (next) {
|
||||
if (next.score !== game.score) {
|
||||
showScoreLine(playingLabel(next.score));
|
||||
}
|
||||
game = next;
|
||||
} else {
|
||||
endGame(game.score);
|
||||
}
|
||||
}
|
||||
if (game) {
|
||||
const sizeAt = (y: number): number =>
|
||||
DOT_RADIUS + Math.min(gameFloor(y, height), 1.2) * 0.7;
|
||||
const food = cellCenter(game.food.c, game.food.r);
|
||||
drawDot(ctx, food.x, food.y, sizeAt(food.y), snakeColors.food);
|
||||
game.body.forEach((cell, i) => {
|
||||
const { x, y } = cellCenter(cell.c, cell.r);
|
||||
drawDot(
|
||||
ctx,
|
||||
x,
|
||||
y,
|
||||
sizeAt(y),
|
||||
i === 0 ? snakeColors.head : snakeColors.body,
|
||||
);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const draw = (now: number): void => {
|
||||
const hadTrail = trail.length > 0;
|
||||
for (let i = trail.length - 1; i >= 0; i -= 1) {
|
||||
if (now - trail[i].born >= TRAIL_LIFE_MS) {
|
||||
trail.splice(i, 1);
|
||||
}
|
||||
}
|
||||
if (isStill && !game && !hadTrail && !needsDraw) {
|
||||
frame = requestAnimationFrame(draw);
|
||||
return;
|
||||
}
|
||||
needsDraw = false;
|
||||
|
||||
const t = isStill ? STILL_TIME_MS : now;
|
||||
ctx.clearRect(0, 0, width, height);
|
||||
|
||||
drawAuroraDots(ctx, dots, {
|
||||
t,
|
||||
now,
|
||||
height,
|
||||
trail,
|
||||
isGameOn: game !== null,
|
||||
isDarkMode,
|
||||
// Keeps the score line's strip clear of dots.
|
||||
cutoffY: isScoreLineShown ? gameRows * DOT_SPACING : Infinity,
|
||||
});
|
||||
|
||||
stepAndDrawSnake(now);
|
||||
|
||||
frame = requestAnimationFrame(draw);
|
||||
};
|
||||
|
||||
const observer = new ResizeObserver(layout);
|
||||
observer.observe(canvas);
|
||||
layout();
|
||||
window.addEventListener('pointermove', onPointer);
|
||||
window.addEventListener('pointerdown', onPointer);
|
||||
window.addEventListener('keydown', onKeyDown);
|
||||
canvas.addEventListener('click', onClick);
|
||||
showPlayCursor();
|
||||
frame = requestAnimationFrame(draw);
|
||||
|
||||
return (): void => {
|
||||
cancelAnimationFrame(frame);
|
||||
observer.disconnect();
|
||||
window.clearTimeout(labelTimer);
|
||||
setLabel(null);
|
||||
if (game) {
|
||||
onGameChangeRef.current?.(false);
|
||||
}
|
||||
window.removeEventListener('pointermove', onPointer);
|
||||
window.removeEventListener('pointerdown', onPointer);
|
||||
window.removeEventListener('keydown', onKeyDown);
|
||||
canvas.removeEventListener('click', onClick);
|
||||
};
|
||||
}, [canvasRef, isDarkMode]);
|
||||
|
||||
return label;
|
||||
}
|
||||
@@ -157,6 +157,7 @@ function RawLogView({
|
||||
|
||||
return (
|
||||
<RawLogViewContainer
|
||||
className="raw-log-row"
|
||||
data-testid={`logs-raw-row-${data.id}`}
|
||||
onClick={handleClickExpand}
|
||||
wrap={false}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { blue } from '@ant-design/colors';
|
||||
import { Color } from '@signozhq/design-tokens';
|
||||
import { Col, Row, Space } from 'antd';
|
||||
import Space from 'periscope/components/Space/Space';
|
||||
import Col from 'periscope/components/Col/Col';
|
||||
import Row from 'periscope/components/Row/Row';
|
||||
import { FontSize } from 'container/OptionsMenu/types';
|
||||
import { Info } from '@signozhq/icons';
|
||||
import styled from 'styled-components';
|
||||
|
||||
@@ -1,2 +1,26 @@
|
||||
/** Shared hover copy for every Noz entry point (header, floating trigger, sidebar). */
|
||||
export const NOZ_TOOLTIP_TITLE = 'Noz, your AI teammate';
|
||||
|
||||
/** The mascot's colours, shared by every drawing of Noz. */
|
||||
export const NOZ_COLORS = {
|
||||
body: '#E5484D',
|
||||
eye: '#F5F5F5',
|
||||
pupil: '#0A0C10',
|
||||
hat: '#4E74F8',
|
||||
} as const;
|
||||
|
||||
export const NOZ_BODY = {
|
||||
x: 4.35938,
|
||||
y: 8.49908,
|
||||
width: 15.4569,
|
||||
height: 11.978,
|
||||
rx: 1.76147,
|
||||
} as const;
|
||||
|
||||
export const NOZ_EYE = { cx: 12.0217, cy: 14.4881, r: 3.87523 } as const;
|
||||
|
||||
export const NOZ_PUPIL_PATH =
|
||||
'M12.0237 12.8024C12.0237 13.7328 11.2673 14.4892 10.337 14.4892C10.0339 14.4892 9.74926 14.4101 9.50152 14.2678C9.47517 14.5551 9.49888 14.8502 9.57795 15.1428C9.93901 16.4921 11.3279 17.2933 12.6773 16.9323C14.0267 16.5712 14.8279 15.1823 14.4668 13.8329C14.1453 12.6285 13.0041 11.8616 11.8023 11.967C11.942 12.2121 12.0237 12.4967 12.0237 12.8024Z';
|
||||
|
||||
export const NOZ_HAT_PATH =
|
||||
'M8.33833 7.94578L9.83358 4.31319C10.1302 3.59261 10.6676 2.99939 11.355 2.63299L13.9181 1.26684C14.1327 1.15169 14.3804 1.34885 14.3194 1.58439L13.6703 4.06892C13.6511 4.14046 13.6424 4.21374 13.6424 4.28876C13.6424 4.39868 13.6633 4.5086 13.7052 4.61154L15.0382 7.94578H11.4248L11.6307 7.32813L12.3356 7.09259C12.449 7.05421 12.5257 6.94778 12.5257 6.82739C12.5257 6.707 12.449 6.60057 12.3356 6.56218L11.6307 6.32664L11.3951 5.62176C11.3568 5.51009 11.2503 5.43333 11.1299 5.43333C11.0096 5.43333 10.9031 5.5101 10.8647 5.6235L10.6292 6.32839L9.92431 6.56393C9.8109 6.60231 9.73413 6.70874 9.73413 6.82913C9.73413 6.94952 9.8109 7.05595 9.92431 7.09434L10.6292 7.32988L10.8351 7.94752H8.33833V7.94578ZM12.1 3.43558C12.0808 3.378 12.0285 3.33962 11.9674 3.33962C11.9064 3.33962 11.854 3.378 11.8348 3.43558L11.7179 3.78802L11.3655 3.90492C11.3079 3.92411 11.2695 3.97645 11.2695 4.03752C11.2695 4.09859 11.3079 4.15093 11.3655 4.17012L11.7179 4.28702L11.8348 4.63946C11.854 4.69704 11.9064 4.73542 11.9674 4.73542C12.0285 4.73542 12.0808 4.69704 12.1 4.63946L12.2169 4.28702L12.5694 4.17012C12.6269 4.15093 12.6653 4.09859 12.6653 4.03752C12.6653 3.97645 12.6269 3.92411 12.5694 3.90492L12.2169 3.78802L12.1 3.43558ZM7.78 7.91088H15.5965C15.9053 7.91088 16.1548 8.16038 16.1548 8.4692C16.1548 8.77803 15.9053 9.02753 15.5965 9.02753H7.78C7.47118 9.02753 7.22168 8.77803 7.22168 8.4692C7.22168 8.16038 7.47118 7.91088 7.78 7.91088Z';
|
||||
|
||||
@@ -1,5 +1,13 @@
|
||||
import cx from 'classnames';
|
||||
|
||||
import {
|
||||
NOZ_BODY,
|
||||
NOZ_COLORS,
|
||||
NOZ_EYE,
|
||||
NOZ_HAT_PATH,
|
||||
NOZ_PUPIL_PATH,
|
||||
} from './Noz.constants';
|
||||
|
||||
import styles from './Noz.module.scss';
|
||||
|
||||
interface NozProps {
|
||||
@@ -30,14 +38,7 @@ export default function Noz({ size = 24, className }: NozProps): JSX.Element {
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
{/* body */}
|
||||
<rect
|
||||
x="4.35938"
|
||||
y="8.49908"
|
||||
width="15.4569"
|
||||
height="11.978"
|
||||
rx="1.76147"
|
||||
fill="#E5484D"
|
||||
/>
|
||||
<rect {...NOZ_BODY} fill={NOZ_COLORS.body} />
|
||||
{/* legs */}
|
||||
<rect
|
||||
x="6.87012"
|
||||
@@ -45,7 +46,7 @@ export default function Noz({ size = 24, className }: NozProps): JSX.Element {
|
||||
width="3.34679"
|
||||
height="3.69908"
|
||||
rx="0.880734"
|
||||
fill="#E5484D"
|
||||
fill={NOZ_COLORS.body}
|
||||
/>
|
||||
<rect
|
||||
x="13.916"
|
||||
@@ -53,7 +54,7 @@ export default function Noz({ size = 24, className }: NozProps): JSX.Element {
|
||||
width="3.34679"
|
||||
height="3.69908"
|
||||
rx="0.880734"
|
||||
fill="#E5484D"
|
||||
fill={NOZ_COLORS.body}
|
||||
/>
|
||||
{/* right arm (static) */}
|
||||
<rect
|
||||
@@ -62,7 +63,7 @@ export default function Noz({ size = 24, className }: NozProps): JSX.Element {
|
||||
width="2.11376"
|
||||
height="3.69908"
|
||||
rx="0.880734"
|
||||
fill="#E5484D"
|
||||
fill={NOZ_COLORS.body}
|
||||
/>
|
||||
{/* left arm: outer group does the "lift", inner does the wiggle */}
|
||||
<g className="noz-arm-left">
|
||||
@@ -73,21 +74,15 @@ export default function Noz({ size = 24, className }: NozProps): JSX.Element {
|
||||
width="2.11376"
|
||||
height="3.69908"
|
||||
rx="0.880734"
|
||||
fill="#E5484D"
|
||||
fill={NOZ_COLORS.body}
|
||||
/>
|
||||
</g>
|
||||
</g>
|
||||
{/* head: face + eye + hat tilt together */}
|
||||
<g className="noz-head">
|
||||
<circle cx="12.0217" cy="14.4881" r="3.87523" fill="#F5F5F5" />
|
||||
<path
|
||||
d="M12.0237 12.8024C12.0237 13.7328 11.2673 14.4892 10.337 14.4892C10.0339 14.4892 9.74926 14.4101 9.50152 14.2678C9.47517 14.5551 9.49888 14.8502 9.57795 15.1428C9.93901 16.4921 11.3279 17.2933 12.6773 16.9323C14.0267 16.5712 14.8279 15.1823 14.4668 13.8329C14.1453 12.6285 13.0041 11.8616 11.8023 11.967C11.942 12.2121 12.0237 12.4967 12.0237 12.8024Z"
|
||||
fill="#0A0C10"
|
||||
/>
|
||||
<path
|
||||
d="M8.33833 7.94578L9.83358 4.31319C10.1302 3.59261 10.6676 2.99939 11.355 2.63299L13.9181 1.26684C14.1327 1.15169 14.3804 1.34885 14.3194 1.58439L13.6703 4.06892C13.6511 4.14046 13.6424 4.21374 13.6424 4.28876C13.6424 4.39868 13.6633 4.5086 13.7052 4.61154L15.0382 7.94578H11.4248L11.6307 7.32813L12.3356 7.09259C12.449 7.05421 12.5257 6.94778 12.5257 6.82739C12.5257 6.707 12.449 6.60057 12.3356 6.56218L11.6307 6.32664L11.3951 5.62176C11.3568 5.51009 11.2503 5.43333 11.1299 5.43333C11.0096 5.43333 10.9031 5.5101 10.8647 5.6235L10.6292 6.32839L9.92431 6.56393C9.8109 6.60231 9.73413 6.70874 9.73413 6.82913C9.73413 6.94952 9.8109 7.05595 9.92431 7.09434L10.6292 7.32988L10.8351 7.94752H8.33833V7.94578ZM12.1 3.43558C12.0808 3.378 12.0285 3.33962 11.9674 3.33962C11.9064 3.33962 11.854 3.378 11.8348 3.43558L11.7179 3.78802L11.3655 3.90492C11.3079 3.92411 11.2695 3.97645 11.2695 4.03752C11.2695 4.09859 11.3079 4.15093 11.3655 4.17012L11.7179 4.28702L11.8348 4.63946C11.854 4.69704 11.9064 4.73542 11.9674 4.73542C12.0285 4.73542 12.0808 4.69704 12.1 4.63946L12.2169 4.28702L12.5694 4.17012C12.6269 4.15093 12.6653 4.09859 12.6653 4.03752C12.6653 3.97645 12.6269 3.92411 12.5694 3.90492L12.2169 3.78802L12.1 3.43558ZM7.78 7.91088H15.5965C15.9053 7.91088 16.1548 8.16038 16.1548 8.4692C16.1548 8.77803 15.9053 9.02753 15.5965 9.02753H7.78C7.47118 9.02753 7.22168 8.77803 7.22168 8.4692C7.22168 8.16038 7.47118 7.91088 7.78 7.91088Z"
|
||||
fill="#4E74F8"
|
||||
/>
|
||||
<circle {...NOZ_EYE} fill={NOZ_COLORS.eye} />
|
||||
<path d={NOZ_PUPIL_PATH} fill={NOZ_COLORS.pupil} />
|
||||
<path d={NOZ_HAT_PATH} fill={NOZ_COLORS.hat} />
|
||||
</g>
|
||||
</svg>
|
||||
</span>
|
||||
|
||||
@@ -215,7 +215,8 @@
|
||||
padding-left: 8px;
|
||||
|
||||
.qb-formula {
|
||||
.ant-row {
|
||||
.formula-row,
|
||||
.formula-container {
|
||||
row-gap: 8px !important;
|
||||
}
|
||||
|
||||
@@ -229,7 +230,7 @@
|
||||
padding: 8px;
|
||||
margin-left: 74px;
|
||||
|
||||
.ant-col {
|
||||
.formula-item {
|
||||
&::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
|
||||
@@ -4,7 +4,8 @@ import type {
|
||||
TableColumnsType as ColumnsType,
|
||||
TableColumnType as ColumnType,
|
||||
} from 'antd';
|
||||
import { Button, Flex } from 'antd';
|
||||
import { Button } from 'antd';
|
||||
import Flex from 'periscope/components/Flex/Flex';
|
||||
import { Dropdown, type DropdownItemType } from '@signozhq/ui/dropdown';
|
||||
import { Switch } from '@signozhq/ui/switch';
|
||||
import logEvent from 'api/common/logEvent';
|
||||
|
||||
@@ -1,14 +1,11 @@
|
||||
import { HTMLAttributes } from 'react';
|
||||
import {
|
||||
Button,
|
||||
ButtonProps,
|
||||
Col,
|
||||
ColProps,
|
||||
Row,
|
||||
RowProps,
|
||||
Space,
|
||||
SpaceProps,
|
||||
} from 'antd';
|
||||
import { Button, ButtonProps } from 'antd';
|
||||
import Space from 'periscope/components/Space/Space';
|
||||
import type { SpaceProps } from 'periscope/components/Space/types';
|
||||
import Col from 'periscope/components/Col/Col';
|
||||
import type { ColProps } from 'periscope/components/Col/types';
|
||||
import Row from 'periscope/components/Row/Row';
|
||||
import type { RowProps } from 'periscope/components/Row/types';
|
||||
import {
|
||||
Typography,
|
||||
TypographyTextProps,
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
.panel:global(.floating-panel) {
|
||||
background: var(--l2-background);
|
||||
}
|
||||
|
||||
.header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -5,7 +9,7 @@
|
||||
padding: 8px;
|
||||
border-bottom: 1px solid var(--l1-border);
|
||||
flex-shrink: 0;
|
||||
background: var(--l1-background);
|
||||
background: var(--l2-background);
|
||||
}
|
||||
|
||||
.title {
|
||||
|
||||
@@ -106,6 +106,7 @@ export default function AIAssistantPanel(): JSX.Element | null {
|
||||
<VariantContext.Provider value="panel">
|
||||
<FloatingPanel
|
||||
isOpen
|
||||
className={styles.panel}
|
||||
width={PANEL_WIDTH}
|
||||
height={panelHeight}
|
||||
minWidth={PANEL_MIN_WIDTH}
|
||||
|
||||
@@ -3,6 +3,41 @@
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
overflow: hidden;
|
||||
|
||||
// The full page sits the thread in a faint pane whose bottom edge runs behind the input.
|
||||
&.fullPage {
|
||||
position: relative;
|
||||
// Lets the pane sit behind the thread without dropping under the page.
|
||||
isolation: isolate;
|
||||
container-type: inline-size;
|
||||
// Shared by the thread and the input: 768px on laptops, wider on big screens.
|
||||
--noz-page-column: clamp(768px, 70cqi, 1040px);
|
||||
padding: calc(var(--spacing-6) + 1px) calc(var(--spacing-6) + 1px) 0 1px;
|
||||
|
||||
&::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
z-index: -1;
|
||||
inset: var(--spacing-6) var(--spacing-6) var(--spacing-16) 0;
|
||||
border: 1px solid var(--l2-border);
|
||||
border-radius: var(--radius-3);
|
||||
background: var(--l2-background-60);
|
||||
opacity: 0.4;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
// Fades the pane's foot into the page on either side of the input.
|
||||
&::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
height: calc(var(--spacing-20) + var(--spacing-3));
|
||||
background: linear-gradient(to bottom, transparent, var(--l1-background));
|
||||
pointer-events: none;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.loading {
|
||||
@@ -34,7 +69,18 @@
|
||||
border-top: 1px solid var(--l1-border);
|
||||
|
||||
&.compact {
|
||||
padding: 8px;
|
||||
padding: 0;
|
||||
// Same colour as the panel's outline.
|
||||
border-top-color: var(--l2-border);
|
||||
}
|
||||
|
||||
&.fullPage {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
width: min(var(--noz-page-column), 100%);
|
||||
margin: 0 auto;
|
||||
padding: 0 0 var(--spacing-6);
|
||||
border-top: none;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import cx from 'classnames';
|
||||
import { useAppLocation } from 'lib/router/useAppLocation';
|
||||
|
||||
@@ -17,6 +17,8 @@ import { useVariant } from '../VariantContext';
|
||||
|
||||
import styles from './ConversationView.module.scss';
|
||||
|
||||
const SNAKE_PLACEHOLDER = 'Playing Snake · Esc to quit';
|
||||
|
||||
interface ConversationViewProps {
|
||||
conversationId: string;
|
||||
}
|
||||
@@ -26,8 +28,18 @@ export default function ConversationView({
|
||||
}: ConversationViewProps): JSX.Element {
|
||||
const variant = useVariant();
|
||||
const isCompact = variant === 'panel';
|
||||
const isFullPage = variant === 'page';
|
||||
const location = useAppLocation();
|
||||
|
||||
const [isPlayingSnake, setIsPlayingSnake] = useState(false);
|
||||
const [inputFocusRequest, setInputFocusRequest] = useState(0);
|
||||
const handleSnakeGameChange = useCallback((isPlaying: boolean): void => {
|
||||
setIsPlayingSnake(isPlaying);
|
||||
if (!isPlaying) {
|
||||
setInputFocusRequest((n) => n + 1);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const conversation = useAIAssistantStore(
|
||||
(s) => s.conversations[conversationId],
|
||||
);
|
||||
@@ -109,38 +121,35 @@ export default function ConversationView({
|
||||
[sendMessage, analyticsCtx, pendingClarificationHere],
|
||||
);
|
||||
|
||||
// Wall-clock timestamp of the current streaming start, used to compute
|
||||
// `secondsSinceStart` on Cancel clicked. Cleared whenever streaming ends.
|
||||
const streamStartedAtRef = useRef<number | null>(null);
|
||||
useEffect(() => {
|
||||
if (!isStreamingHere) {
|
||||
streamStartedAtRef.current = null;
|
||||
return;
|
||||
}
|
||||
if (streamStartedAtRef.current === null) {
|
||||
streamStartedAtRef.current = Date.now();
|
||||
}
|
||||
}, [isStreamingHere]);
|
||||
// When the current reply began, kept with the stream so a reopened view carries on from it.
|
||||
const streamStartedAt = useAIAssistantStore((s) => {
|
||||
const stream = s.streams[conversationId];
|
||||
return stream?.isStreaming ? stream.startedAt : null;
|
||||
});
|
||||
|
||||
const handleCancel = useCallback(() => {
|
||||
const startedAt = streamStartedAtRef.current;
|
||||
void logEvent(AIAssistantEvents.CancelClicked, {
|
||||
threadId: analyticsCtx.threadId,
|
||||
secondsSinceStart:
|
||||
startedAt !== null ? Math.round((Date.now() - startedAt) / 1000) : null,
|
||||
streamStartedAt !== null
|
||||
? Math.round((Date.now() - streamStartedAt) / 1000)
|
||||
: null,
|
||||
});
|
||||
cancelStream(conversationId);
|
||||
}, [cancelStream, conversationId, analyticsCtx.threadId]);
|
||||
}, [cancelStream, conversationId, analyticsCtx.threadId, streamStartedAt]);
|
||||
|
||||
const messages = conversation?.messages ?? [];
|
||||
const showDisclaimer = messages.length > 0;
|
||||
const inputDisabled =
|
||||
isPlayingSnake ||
|
||||
isStreamingHere ||
|
||||
isLoadingThread ||
|
||||
Boolean(pendingApprovalHere) ||
|
||||
Boolean(pendingClarificationHere);
|
||||
let inputDisabledTooltip: string | undefined;
|
||||
if (isStreamingHere) {
|
||||
if (isPlayingSnake) {
|
||||
inputDisabledTooltip = SNAKE_PLACEHOLDER;
|
||||
} else if (isStreamingHere) {
|
||||
inputDisabledTooltip = 'Wait for the response to finish';
|
||||
} else if (isLoadingThread) {
|
||||
inputDisabledTooltip = 'Wait for the conversation to load';
|
||||
@@ -150,8 +159,12 @@ export default function ConversationView({
|
||||
inputDisabledTooltip = 'Answer the pending question first';
|
||||
}
|
||||
|
||||
const conversationClass = cx(styles.conversation, {
|
||||
[styles.fullPage]: isFullPage,
|
||||
});
|
||||
const inputWrapperClass = cx(styles.inputWrapper, {
|
||||
[styles.compact]: isCompact,
|
||||
[styles.fullPage]: isFullPage,
|
||||
});
|
||||
const disclaimerClass = cx(styles.disclaimer, {
|
||||
[styles.compact]: isCompact,
|
||||
@@ -165,7 +178,7 @@ export default function ConversationView({
|
||||
const isHydrating = Boolean(conversation?.isHydrating);
|
||||
if ((isLoadingThread || isHydrating) && messages.length === 0) {
|
||||
return (
|
||||
<div className={styles.conversation}>
|
||||
<div className={conversationClass}>
|
||||
<ConversationSkeleton />
|
||||
<div className={inputWrapperClass}>
|
||||
<ChatInput
|
||||
@@ -182,12 +195,13 @@ export default function ConversationView({
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={styles.conversation}>
|
||||
<div className={conversationClass}>
|
||||
<VirtualizedMessages
|
||||
key={conversationId}
|
||||
conversationId={conversationId}
|
||||
messages={messages}
|
||||
isStreaming={isStreamingHere}
|
||||
onSnakeGameChange={handleSnakeGameChange}
|
||||
onSendSuggestedPrompt={(text): void => {
|
||||
handleSend(
|
||||
text,
|
||||
@@ -208,7 +222,11 @@ export default function ConversationView({
|
||||
onCancel={handleCancel}
|
||||
disabled={inputDisabled}
|
||||
disabledTooltip={inputDisabledTooltip}
|
||||
placeholder={isPlayingSnake ? SNAKE_PLACEHOLDER : undefined}
|
||||
focusRequest={inputFocusRequest}
|
||||
isStreaming={isStreamingHere}
|
||||
streamStartedAt={streamStartedAt}
|
||||
showNozPeek={messages.length === 0 && !isStreamingHere}
|
||||
autoContexts={autoContexts}
|
||||
onDismissAutoContext={handleDismissAutoContext}
|
||||
/>
|
||||
|
||||
@@ -37,7 +37,25 @@ jest.mock('container/AIAssistant/hooks/useAIAssistantAnalyticsContext', () => ({
|
||||
// ConversationView imports for its dismissed-context filter.
|
||||
jest.mock('container/AIAssistant/components/ChatInput', () => ({
|
||||
__esModule: true,
|
||||
default: (): JSX.Element => <div data-testid="chat-input" />,
|
||||
default: ({
|
||||
streamStartedAt,
|
||||
disabled,
|
||||
placeholder,
|
||||
focusRequest,
|
||||
}: {
|
||||
streamStartedAt?: number | null;
|
||||
disabled?: boolean;
|
||||
placeholder?: string;
|
||||
focusRequest?: number;
|
||||
}): JSX.Element => (
|
||||
<div
|
||||
data-testid="chat-input"
|
||||
data-stream-started-at={streamStartedAt ?? ''}
|
||||
data-disabled={String(Boolean(disabled))}
|
||||
data-placeholder={placeholder ?? ''}
|
||||
data-focus-request={focusRequest ?? 0}
|
||||
/>
|
||||
),
|
||||
autoContextKey: (): string => '',
|
||||
}));
|
||||
|
||||
@@ -53,6 +71,28 @@ jest.mock('components/Noz/Noz', () => ({
|
||||
default: (): JSX.Element => <div data-testid="noz" />,
|
||||
}));
|
||||
|
||||
jest.mock('components/DotGrid/DotGrid', () => ({
|
||||
__esModule: true,
|
||||
default: ({
|
||||
onGameChange,
|
||||
}: {
|
||||
onGameChange?: (isPlaying: boolean) => void;
|
||||
}): JSX.Element => (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
data-testid="start-snake"
|
||||
onClick={(): void => onGameChange?.(true)}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
data-testid="end-snake"
|
||||
onClick={(): void => onGameChange?.(false)}
|
||||
/>
|
||||
</>
|
||||
),
|
||||
}));
|
||||
|
||||
jest.mock('container/AIAssistant/components/MessageBubble', () => ({
|
||||
__esModule: true,
|
||||
default: (): null => null,
|
||||
@@ -139,3 +179,86 @@ describe('ConversationView — empty-state chip context', () => {
|
||||
expect(sendMessage).toHaveBeenCalledWith(CHIP_TEXT, undefined, undefined);
|
||||
});
|
||||
});
|
||||
|
||||
describe('ConversationView — reply start time', () => {
|
||||
afterEach(() => {
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('carries on from when the reply began when the view is reopened mid-reply', () => {
|
||||
jest.spyOn(Date, 'now').mockReturnValue(5000);
|
||||
useAIAssistantStore.setState({
|
||||
conversations: {
|
||||
[CONVERSATION_ID]: {
|
||||
id: CONVERSATION_ID,
|
||||
messages: [],
|
||||
createdAt: 1,
|
||||
updatedAt: 1,
|
||||
},
|
||||
},
|
||||
streams: {
|
||||
[CONVERSATION_ID]: {
|
||||
isStreaming: true,
|
||||
streamingContent: '',
|
||||
streamingStatus: '',
|
||||
streamingEvents: [],
|
||||
streamingMessageId: null,
|
||||
streamingActions: null,
|
||||
pendingApproval: null,
|
||||
pendingClarification: null,
|
||||
startedAt: 1000,
|
||||
},
|
||||
},
|
||||
activeConversationId: CONVERSATION_ID,
|
||||
isLoadingThread: false,
|
||||
});
|
||||
|
||||
const { getByTestId } = renderView('panel');
|
||||
|
||||
expect(getByTestId('chat-input')).toHaveAttribute(
|
||||
'data-stream-started-at',
|
||||
'1000',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('ConversationView — Snake on the empty state', () => {
|
||||
beforeEach(() => {
|
||||
useAIAssistantStore.setState({
|
||||
conversations: {
|
||||
[CONVERSATION_ID]: {
|
||||
id: CONVERSATION_ID,
|
||||
messages: [],
|
||||
createdAt: 1,
|
||||
updatedAt: 1,
|
||||
},
|
||||
},
|
||||
streams: {},
|
||||
activeConversationId: CONVERSATION_ID,
|
||||
isLoadingThread: false,
|
||||
});
|
||||
});
|
||||
|
||||
it('disables the input while Snake runs', () => {
|
||||
const { getByTestId } = renderView('page');
|
||||
|
||||
fireEvent.click(getByTestId('start-snake'));
|
||||
|
||||
expect(getByTestId('chat-input')).toHaveAttribute('data-disabled', 'true');
|
||||
expect(getByTestId('chat-input')).toHaveAttribute(
|
||||
'data-placeholder',
|
||||
'Playing Snake · Esc to quit',
|
||||
);
|
||||
});
|
||||
|
||||
it('gives the input back, focused, once the game ends', () => {
|
||||
const { getByTestId } = renderView('page');
|
||||
fireEvent.click(getByTestId('start-snake'));
|
||||
|
||||
fireEvent.click(getByTestId('end-snake'));
|
||||
|
||||
expect(getByTestId('chat-input')).toHaveAttribute('data-disabled', 'false');
|
||||
expect(getByTestId('chat-input')).toHaveAttribute('data-placeholder', '');
|
||||
expect(getByTestId('chat-input')).toHaveAttribute('data-focus-request', '1');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,24 +3,32 @@
|
||||
.input {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
background: var(--l1-background);
|
||||
border-radius: var(--radius-2);
|
||||
padding: 8px;
|
||||
border: 1px solid var(--l1-border);
|
||||
background: var(--l2-background);
|
||||
border: 1px solid var(--l2-border);
|
||||
border-radius: var(--radius-3);
|
||||
box-shadow: var(--shadow-dialog);
|
||||
position: relative;
|
||||
|
||||
// The panel already frames it.
|
||||
&.compact {
|
||||
border: none;
|
||||
border-radius: 0;
|
||||
box-shadow: none;
|
||||
}
|
||||
}
|
||||
|
||||
.attachments {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
padding: var(--spacing-4) var(--spacing-5) 0;
|
||||
}
|
||||
|
||||
.contextTags {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
padding: var(--spacing-4) var(--spacing-5) 0;
|
||||
}
|
||||
|
||||
.contextTag {
|
||||
@@ -91,86 +99,78 @@
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.composer {
|
||||
background: var(--l2-background);
|
||||
border: 1px solid var(--l2-border);
|
||||
border-radius: var(--radius-2);
|
||||
padding: 4px;
|
||||
transition:
|
||||
border-color 0.15s,
|
||||
box-shadow 0.15s;
|
||||
|
||||
// Scope the focus ring to the textarea row only — the surrounding
|
||||
// chrome (context chips, "Add Context", mic, send) sits outside this
|
||||
// element and stays unaffected when the cursor enters the textarea.
|
||||
&:focus-within {
|
||||
border-color: var(--accent-primary);
|
||||
box-shadow: 0 0 0 1px
|
||||
color-mix(in srgb, var(--accent-primary), transparent 70%);
|
||||
}
|
||||
position: relative;
|
||||
padding: calc(var(--spacing-4) + 1px) var(--spacing-8);
|
||||
}
|
||||
|
||||
.footer {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
justify-content: flex-end;
|
||||
padding: var(--spacing-2) var(--spacing-5) var(--spacing-4);
|
||||
}
|
||||
|
||||
.leftActions,
|
||||
.rightActions {
|
||||
.actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
--button-height: 28px;
|
||||
--button-width: 28px;
|
||||
--button-max-width: 28px;
|
||||
--button-border-radius: var(--radius-round);
|
||||
|
||||
.attachBtn {
|
||||
color: var(--l3-foreground);
|
||||
}
|
||||
|
||||
.contextBtn {
|
||||
flex-shrink: 0;
|
||||
gap: 6px;
|
||||
border-style: dashed !important;
|
||||
padding-inline: 12px !important;
|
||||
// Send stays a solid grey until there is something to send.
|
||||
[data-color='primary'][aria-disabled='true'] {
|
||||
--button-primary-background-color: var(--l3-background);
|
||||
--button-primary-solid-foreground: var(--l2-foreground);
|
||||
--button-disabled-opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
.textarea {
|
||||
display: block;
|
||||
width: 100%;
|
||||
padding: 0;
|
||||
background: transparent;
|
||||
border: none;
|
||||
outline: none;
|
||||
resize: none;
|
||||
color: var(--l1-foreground);
|
||||
font-size: 12px;
|
||||
line-height: 1.5;
|
||||
font-size: var(--periscope-font-size-base);
|
||||
line-height: var(--line-height-20);
|
||||
letter-spacing: -0.005em;
|
||||
overflow-y: auto;
|
||||
font-family: inherit;
|
||||
// ComposerCaret draws the caret.
|
||||
caret-color: transparent;
|
||||
@include scrollbar(0.2rem);
|
||||
|
||||
&::placeholder {
|
||||
color: var(--l3-foreground);
|
||||
color: var(--l2-foreground);
|
||||
opacity: 0.6;
|
||||
}
|
||||
|
||||
&::selection {
|
||||
background: var(--accent-primary);
|
||||
color: var(--l1-background);
|
||||
}
|
||||
|
||||
&:disabled {
|
||||
opacity: 0.2;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
caret-color: auto;
|
||||
}
|
||||
}
|
||||
|
||||
.charWarning {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
width: 100%;
|
||||
margin: 0 var(--spacing-5);
|
||||
padding: 6px 8px;
|
||||
font-size: 11px;
|
||||
font-weight: 500;
|
||||
@@ -180,24 +180,9 @@
|
||||
border-radius: var(--radius-2);
|
||||
}
|
||||
|
||||
.sendBtn {
|
||||
flex-shrink: 0;
|
||||
border-radius: var(--radius-2);
|
||||
|
||||
&.stop {
|
||||
background: var(--accent-cherry) !important;
|
||||
border-color: var(--accent-cherry) !important;
|
||||
|
||||
&:hover {
|
||||
opacity: 0.85;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.contextPopover {
|
||||
width: 480px !important;
|
||||
max-width: min(92vw, 480px);
|
||||
margin-left: 16px;
|
||||
border: 1px solid var(--l2-border);
|
||||
border-radius: var(--radius-2);
|
||||
background: var(--l1-background);
|
||||
@@ -338,75 +323,3 @@
|
||||
overflow-wrap: anywhere;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.micRecording {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
background: var(--l2-background);
|
||||
border-radius: 999px;
|
||||
padding: 2px;
|
||||
gap: 0;
|
||||
flex-shrink: 0;
|
||||
overflow: hidden;
|
||||
--button-icon-size: 12px;
|
||||
|
||||
> :last-child {
|
||||
--button-icon-size: 9px;
|
||||
--button-variant-ghost-color: var(--accent-cherry);
|
||||
--button-variant-ghost-hover-color: var(--accent-cherry);
|
||||
}
|
||||
}
|
||||
|
||||
.micWaves {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 2px;
|
||||
height: 20px;
|
||||
padding: 0 6px;
|
||||
|
||||
span {
|
||||
display: block;
|
||||
width: 2px;
|
||||
border-radius: 2px;
|
||||
background: var(--l1-foreground);
|
||||
animation: voiceWave 0.9s ease-in-out infinite;
|
||||
|
||||
&:nth-child(1) {
|
||||
animation-delay: 0s;
|
||||
}
|
||||
&:nth-child(2) {
|
||||
animation-delay: 0.1s;
|
||||
}
|
||||
&:nth-child(3) {
|
||||
animation-delay: 0.2s;
|
||||
}
|
||||
&:nth-child(4) {
|
||||
animation-delay: 0.3s;
|
||||
}
|
||||
&:nth-child(5) {
|
||||
animation-delay: 0.4s;
|
||||
}
|
||||
&:nth-child(6) {
|
||||
animation-delay: 0.3s;
|
||||
}
|
||||
&:nth-child(7) {
|
||||
animation-delay: 0.2s;
|
||||
}
|
||||
&:nth-child(8) {
|
||||
animation-delay: 0.1s;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes voiceWave {
|
||||
0%,
|
||||
100% {
|
||||
height: 2px;
|
||||
opacity: 0.4;
|
||||
}
|
||||
50% {
|
||||
height: 12px;
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,11 +11,8 @@ import { Badge } from '@signozhq/ui/badge';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { Input } from '@signozhq/ui/input';
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@signozhq/ui/popover';
|
||||
import { toast } from '@signozhq/ui/sonner';
|
||||
import { Tooltip } from '@signozhq/ui/tooltip';
|
||||
import type { UploadFile } from 'antd';
|
||||
import getSessionStorage from 'api/browser/sessionstorage/get';
|
||||
import setSessionStorage from 'api/browser/sessionstorage/set';
|
||||
import {
|
||||
getListDashboardsForUserV2QueryKey,
|
||||
useListDashboardsForUserV2,
|
||||
@@ -31,34 +28,29 @@ import type {
|
||||
ListRulesV3200,
|
||||
ListRulesV3Params,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import logEvent from 'api/common/logEvent';
|
||||
import { useQueryService } from 'hooks/useQueryService';
|
||||
// eslint-disable-next-line
|
||||
import { useSelector } from 'react-redux';
|
||||
import { AppState } from 'store/reducers';
|
||||
import { GlobalReducer } from 'types/reducer/globalTime';
|
||||
|
||||
import {
|
||||
AIAssistantEvents,
|
||||
VoiceInputSource,
|
||||
getBrowserInfo,
|
||||
} from '../../events';
|
||||
import { useAIAssistantAnalyticsContext } from '../../hooks/useAIAssistantAnalyticsContext';
|
||||
import { useSpeechRecognition } from '../../hooks/useSpeechRecognition';
|
||||
import { MessageAttachment } from '../../types';
|
||||
import { useVariant } from '../../VariantContext';
|
||||
import { MessageContext } from '../../../../api/ai-assistant/chat';
|
||||
import {
|
||||
Mic,
|
||||
Plus,
|
||||
ArrowUp,
|
||||
AtSign,
|
||||
Search,
|
||||
Send,
|
||||
Square,
|
||||
TriangleAlert,
|
||||
X,
|
||||
} from '@signozhq/icons';
|
||||
|
||||
import styles from './ChatInput.module.scss';
|
||||
import ComposerCaret from './ComposerCaret/ComposerCaret';
|
||||
import ContextPickerEmptyState from './ContextPickerEmptyState';
|
||||
import EdgeSweep from './EdgeSweep/EdgeSweep';
|
||||
import NozPeek from './NozPeek/NozPeek';
|
||||
import {
|
||||
CONTEXT_CATEGORIES,
|
||||
CONTEXT_CATEGORY_ICONS,
|
||||
@@ -74,7 +66,14 @@ interface ChatInputProps {
|
||||
onCancel?: () => void;
|
||||
disabled?: boolean;
|
||||
disabledTooltip?: string;
|
||||
placeholder?: string;
|
||||
/** Focuses the textarea each time it changes. */
|
||||
focusRequest?: number;
|
||||
isStreaming?: boolean;
|
||||
/** When the current stream began; drives the top-edge sweep. */
|
||||
streamStartedAt?: number | null;
|
||||
/** Noz peeks over the top edge; meant for an empty conversation. */
|
||||
showNozPeek?: boolean;
|
||||
/**
|
||||
* URL-derived `source: 'auto'` contexts representing the page the user is
|
||||
* currently looking at. Rendered as chips alongside the user's `@`-mention
|
||||
@@ -171,8 +170,6 @@ const WARNING_THRESHOLD = 15000;
|
||||
// squeezed in tighter container variants (e.g. the floating panel).
|
||||
const TEXTAREA_MAX_HEIGHT_PX = 200;
|
||||
const HOME_SERVICES_INTERVAL = 30 * 60 * 1000;
|
||||
/** sessionStorage key for the "voice input failed this tab" flag. */
|
||||
const VOICE_UNAVAILABLE_KEY = 'ai-assistant-voice-unavailable';
|
||||
/**
|
||||
* The picker filters client-side, so it pulls one large page instead of
|
||||
* paginating. Shared with `getQueryData` below — the params are part of the
|
||||
@@ -242,13 +239,18 @@ export default function ChatInput({
|
||||
onCancel,
|
||||
disabled,
|
||||
disabledTooltip,
|
||||
placeholder = 'Ask Noz…',
|
||||
focusRequest,
|
||||
isStreaming = false,
|
||||
streamStartedAt = null,
|
||||
showNozPeek = false,
|
||||
autoContexts,
|
||||
onDismissAutoContext,
|
||||
}: ChatInputProps): JSX.Element {
|
||||
const { selectedTime } = useSelector<AppState, GlobalReducer>(
|
||||
(state) => state.globalTime,
|
||||
);
|
||||
const isCompact = useVariant() === 'panel';
|
||||
const [text, setText] = useState('');
|
||||
const [pendingFiles, setPendingFiles] = useState<UploadFile[]>([]);
|
||||
const [selectedContexts, setSelectedContexts] = useState<
|
||||
@@ -288,8 +290,6 @@ export default function ChatInput({
|
||||
endTime: now,
|
||||
};
|
||||
});
|
||||
// Stores the already-committed final text so interim results don't overwrite it
|
||||
const committedTextRef = useRef('');
|
||||
const textareaRef = useRef<HTMLTextAreaElement>(null);
|
||||
const inputRootRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
@@ -343,7 +343,6 @@ export default function ChatInput({
|
||||
const next =
|
||||
text.slice(0, mentionRange.start) + text.slice(mentionRange.end);
|
||||
setText(next);
|
||||
committedTextRef.current = next;
|
||||
setMentionRange(null);
|
||||
}
|
||||
},
|
||||
@@ -356,7 +355,6 @@ export default function ChatInput({
|
||||
(prompt: string) => {
|
||||
const next = capText(prompt);
|
||||
setText(next);
|
||||
committedTextRef.current = next;
|
||||
setMentionRange(null);
|
||||
setPickerSearchQuery('');
|
||||
setIsContextPickerOpen(false);
|
||||
@@ -447,6 +445,12 @@ export default function ChatInput({
|
||||
textareaRef.current?.focus();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (focusRequest) {
|
||||
textareaRef.current?.focus();
|
||||
}
|
||||
}, [focusRequest]);
|
||||
|
||||
// Auto-grow the textarea so long prompts aren't trapped in a 2-line
|
||||
// scrolling porthole. Reset to `auto` first to let the field shrink back
|
||||
// down when the user deletes content, then snap to scrollHeight capped at
|
||||
@@ -497,7 +501,6 @@ export default function ChatInput({
|
||||
contexts.length > 0 ? contexts : undefined,
|
||||
);
|
||||
setText('');
|
||||
committedTextRef.current = '';
|
||||
setPendingFiles([]);
|
||||
setSelectedContexts([]);
|
||||
textareaRef.current?.focus();
|
||||
@@ -532,209 +535,6 @@ export default function ChatInput({
|
||||
[],
|
||||
);
|
||||
|
||||
// ── Voice input ────────────────────────────────────────────────────────────
|
||||
|
||||
const analyticsCtx = useAIAssistantAnalyticsContext();
|
||||
// Captured at the start of a voice session, consumed when it ends.
|
||||
// Tracks both the trigger (button vs. PTT shortcut) and the wall-clock
|
||||
// start time so we can attribute `durationMs` on the Voice input used
|
||||
// event regardless of which control ended the session.
|
||||
const voiceStartedAtRef = useRef<number | null>(null);
|
||||
const voiceSourceRef = useRef<VoiceInputSource | null>(null);
|
||||
// Set to true after a `network`, `not-allowed`, or `not-supported` failure
|
||||
// so we hide the mic button for the rest of the tab session — silent
|
||||
// retries don't help, and Chromium derivatives without the Google Speech
|
||||
// API key always fail with `network` no matter how many times the user
|
||||
// clicks. Persisted to sessionStorage so a page reload doesn't surface the
|
||||
// button again (closing the tab still resets, in case the user fixed
|
||||
// permissions or switched browsers).
|
||||
const [voiceUnavailable, setVoiceUnavailable] = useState(
|
||||
() => getSessionStorage(VOICE_UNAVAILABLE_KEY) === 'true',
|
||||
);
|
||||
const markVoiceUnavailable = useCallback((): void => {
|
||||
setVoiceUnavailable(true);
|
||||
setSessionStorage(VOICE_UNAVAILABLE_KEY, 'true');
|
||||
}, []);
|
||||
|
||||
const {
|
||||
isListening,
|
||||
isSupported,
|
||||
permission: micPermission,
|
||||
start,
|
||||
discard,
|
||||
} = useSpeechRecognition({
|
||||
onTranscript: (transcriptText, isFinal) => {
|
||||
if (isFinal) {
|
||||
// Commit: append to whatever the user has already typed
|
||||
const separator = committedTextRef.current ? ' ' : '';
|
||||
const next = capText(committedTextRef.current + separator + transcriptText);
|
||||
committedTextRef.current = next;
|
||||
setText(next);
|
||||
} else {
|
||||
// Interim: live preview appended to committed text, not yet persisted
|
||||
const separator = committedTextRef.current ? ' ' : '';
|
||||
setText(capText(committedTextRef.current + separator + transcriptText));
|
||||
}
|
||||
},
|
||||
onError: (error) => {
|
||||
// Guard against double-fire: Chrome can fire `onerror` more than
|
||||
// once per session when `continuous = true` (it retries internally
|
||||
// before giving up). Only fire the analytics event for the first
|
||||
// error in a given session — voiceSourceRef being null means we've
|
||||
// already handled it.
|
||||
const source = voiceSourceRef.current;
|
||||
if (source === null) {
|
||||
return;
|
||||
}
|
||||
voiceStartedAtRef.current = null;
|
||||
voiceSourceRef.current = null;
|
||||
void logEvent(AIAssistantEvents.VoiceInputFailed, {
|
||||
...analyticsCtx,
|
||||
...getBrowserInfo(),
|
||||
source,
|
||||
errorType: error,
|
||||
});
|
||||
if (error === 'network') {
|
||||
markVoiceUnavailable();
|
||||
toast.error('Voice input unavailable in this browser', {
|
||||
description:
|
||||
'This browser cannot reach the speech recognition service. Try Google Chrome or Microsoft Edge.',
|
||||
});
|
||||
} else if (error === 'not-allowed') {
|
||||
markVoiceUnavailable();
|
||||
toast.error('Microphone access denied', {
|
||||
description:
|
||||
'Grant microphone permission in your browser settings to use voice input.',
|
||||
});
|
||||
} else if (error === 'not-supported') {
|
||||
markVoiceUnavailable();
|
||||
toast.error('Voice input is not supported in this browser.');
|
||||
}
|
||||
// `no-speech` is benign (just silence) — don't toast or hide.
|
||||
},
|
||||
});
|
||||
|
||||
const showMic = isSupported && micPermission !== 'denied' && !voiceUnavailable;
|
||||
|
||||
const startVoiceInput = useCallback(
|
||||
(source: VoiceInputSource) => {
|
||||
// Defense in depth: the button is hidden when `voiceUnavailable` is
|
||||
// true, but the PTT shortcut listener can still call us. Bailing here
|
||||
// keeps a single source of truth and prevents repeat `Voice input
|
||||
// failed` events in the same session.
|
||||
if (voiceUnavailable) {
|
||||
return;
|
||||
}
|
||||
voiceStartedAtRef.current = Date.now();
|
||||
voiceSourceRef.current = source;
|
||||
start();
|
||||
},
|
||||
[start, voiceUnavailable],
|
||||
);
|
||||
|
||||
const fireVoiceInputEvent = useCallback(
|
||||
(outcome: 'sent' | 'discarded') => {
|
||||
const startedAt = voiceStartedAtRef.current;
|
||||
const source = voiceSourceRef.current;
|
||||
voiceStartedAtRef.current = null;
|
||||
voiceSourceRef.current = null;
|
||||
if (startedAt === null || source === null) {
|
||||
return;
|
||||
}
|
||||
void logEvent(AIAssistantEvents.VoiceInputUsed, {
|
||||
...analyticsCtx,
|
||||
...getBrowserInfo(),
|
||||
source,
|
||||
outcome,
|
||||
durationMs: Date.now() - startedAt,
|
||||
});
|
||||
},
|
||||
[analyticsCtx],
|
||||
);
|
||||
|
||||
// Stop recording and immediately send whatever is in the textarea.
|
||||
const handleStopAndSend = useCallback(async () => {
|
||||
// Promote the displayed text (interim included) to committed so handleSend sees it.
|
||||
committedTextRef.current = capText(text);
|
||||
// Stop recognition without triggering onTranscript again (would double-append).
|
||||
discard();
|
||||
fireVoiceInputEvent('sent');
|
||||
await handleSend();
|
||||
}, [text, discard, handleSend, capText, fireVoiceInputEvent]);
|
||||
|
||||
// Stop recording and revert the textarea to what it was before voice started.
|
||||
const handleDiscard = useCallback(() => {
|
||||
discard();
|
||||
fireVoiceInputEvent('discarded');
|
||||
setText(committedTextRef.current);
|
||||
textareaRef.current?.focus();
|
||||
}, [discard, fireVoiceInputEvent]);
|
||||
|
||||
// ── Push-to-talk (Cmd/Ctrl + Shift + Space) ────────────────────────────────
|
||||
// Hold the combo to record; release Space to submit. We track which key
|
||||
// triggered PTT in a ref so a late-released modifier (Cmd/Shift) doesn't
|
||||
// accidentally stop the session. Auto-repeat is suppressed via a
|
||||
// "session active" ref so a held key only calls `start()` once.
|
||||
const pttActiveRef = useRef(false);
|
||||
useEffect(() => {
|
||||
if (!isSupported || micPermission === 'denied' || voiceUnavailable) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const handleKeyDown = (e: KeyboardEvent): void => {
|
||||
const isComboKey =
|
||||
(e.metaKey || e.ctrlKey) &&
|
||||
e.shiftKey &&
|
||||
(e.code === 'Space' || e.key === ' ');
|
||||
if (!isComboKey || disabled || isStreaming) {
|
||||
return;
|
||||
}
|
||||
e.preventDefault();
|
||||
if (pttActiveRef.current) {
|
||||
return; // ignore auto-repeat
|
||||
}
|
||||
pttActiveRef.current = true;
|
||||
startVoiceInput(VoiceInputSource.Shortcut);
|
||||
};
|
||||
|
||||
const handleKeyUp = (e: KeyboardEvent): void => {
|
||||
if (!pttActiveRef.current) {
|
||||
return;
|
||||
}
|
||||
// End on the *first* released key in the combo. macOS browsers
|
||||
// frequently swallow keyup of regular keys (incl. Space) while
|
||||
// Cmd is held, so we can't rely on Space-up alone — releasing
|
||||
// Cmd/Ctrl/Shift must also stop the session.
|
||||
const isComboKey =
|
||||
e.code === 'Space' ||
|
||||
e.key === ' ' ||
|
||||
e.key === 'Meta' ||
|
||||
e.key === 'Control' ||
|
||||
e.key === 'Shift';
|
||||
if (!isComboKey) {
|
||||
return;
|
||||
}
|
||||
pttActiveRef.current = false;
|
||||
e.preventDefault();
|
||||
void handleStopAndSend();
|
||||
};
|
||||
|
||||
window.addEventListener('keydown', handleKeyDown);
|
||||
window.addEventListener('keyup', handleKeyUp);
|
||||
return (): void => {
|
||||
window.removeEventListener('keydown', handleKeyDown);
|
||||
window.removeEventListener('keyup', handleKeyUp);
|
||||
};
|
||||
}, [
|
||||
isSupported,
|
||||
micPermission,
|
||||
voiceUnavailable,
|
||||
disabled,
|
||||
isStreaming,
|
||||
startVoiceInput,
|
||||
handleStopAndSend,
|
||||
]);
|
||||
|
||||
// Each list hook fetches only when its picker tab is actively shown,
|
||||
// AND treats already-cached data as never stale (`staleTime: Infinity`)
|
||||
// so an open with a populated cache doesn't trigger a background
|
||||
@@ -900,7 +700,12 @@ export default function ChatInput({
|
||||
const showTextWarning = currentLength >= WARNING_THRESHOLD;
|
||||
|
||||
return (
|
||||
<div className={styles.input} ref={inputRootRef}>
|
||||
<div
|
||||
className={cx(styles.input, { [styles.compact]: isCompact })}
|
||||
ref={inputRootRef}
|
||||
>
|
||||
<EdgeSweep startedAt={streamStartedAt} />
|
||||
{showNozPeek && <NozPeek />}
|
||||
{pendingFiles.length > 0 && (
|
||||
<div className={styles.attachments}>
|
||||
{pendingFiles.map((f) => (
|
||||
@@ -983,20 +788,20 @@ export default function ChatInput({
|
||||
<textarea
|
||||
ref={textareaRef}
|
||||
className={styles.textarea}
|
||||
placeholder="Ask anything… (Shift+Enter for new line)"
|
||||
data-testid="ai-chat-input-textarea"
|
||||
placeholder={placeholder}
|
||||
value={text}
|
||||
onChange={(e): void => {
|
||||
const next = capText(e.target.value);
|
||||
setText(next);
|
||||
// Keep committed text in sync when the user edits manually
|
||||
committedTextRef.current = next;
|
||||
syncContextPickerFromText(next, e.target.selectionStart ?? next.length);
|
||||
}}
|
||||
onKeyDown={handleKeyDown}
|
||||
disabled={disabled}
|
||||
maxLength={MAX_INPUT_LENGTH}
|
||||
rows={3}
|
||||
rows={2}
|
||||
/>
|
||||
<ComposerCaret textareaRef={textareaRef} value={text} />
|
||||
</div>
|
||||
{showTextWarning && (
|
||||
<div className={styles.charWarning} role="status">
|
||||
@@ -1009,7 +814,7 @@ export default function ChatInput({
|
||||
)}
|
||||
|
||||
<div className={styles.footer}>
|
||||
<div className={styles.leftActions}>
|
||||
<div className={styles.actions}>
|
||||
<Popover
|
||||
open={isContextPickerOpen}
|
||||
onOpenChange={(open): void => {
|
||||
@@ -1020,22 +825,26 @@ export default function ChatInput({
|
||||
}
|
||||
}}
|
||||
>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
disabledTooltip={disabledTooltip}
|
||||
variant="solid"
|
||||
color="secondary"
|
||||
size="md"
|
||||
disabled={disabled}
|
||||
onClick={(): void => {
|
||||
setActiveContextCategory('Dashboards');
|
||||
setPickerSearchQuery('');
|
||||
}}
|
||||
prefix={<Plus size={10} />}
|
||||
>
|
||||
Add Context
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<Tooltip title="Add context">
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
disabledTooltip={disabledTooltip}
|
||||
variant="ghost"
|
||||
color="secondary"
|
||||
size="sm"
|
||||
icon
|
||||
disabled={disabled}
|
||||
onClick={(): void => {
|
||||
setActiveContextCategory('Dashboards');
|
||||
setPickerSearchQuery('');
|
||||
}}
|
||||
testId="ai-chat-input-add-context"
|
||||
aria-label="Add context"
|
||||
>
|
||||
<AtSign size={14} />
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
</Tooltip>
|
||||
<PopoverContent
|
||||
className={styles.contextPopover}
|
||||
side="top"
|
||||
@@ -1099,6 +908,7 @@ export default function ChatInput({
|
||||
<Input
|
||||
type="text"
|
||||
placeholder={`Search ${activeContextCategory.toLowerCase()}…`}
|
||||
testId="ai-context-search"
|
||||
className={styles.contextPopoverSearchInput}
|
||||
value={pickerSearchQuery}
|
||||
onChange={(e): void => setPickerSearchQuery(e.target.value)}
|
||||
@@ -1164,82 +974,18 @@ export default function ChatInput({
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
</div>
|
||||
|
||||
<div className={styles.rightActions}>
|
||||
{showMic &&
|
||||
(isListening ? (
|
||||
<div
|
||||
className={styles.micRecording}
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
aria-label="Recording voice input"
|
||||
>
|
||||
<Tooltip title="Discard recording">
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="md"
|
||||
icon
|
||||
color="secondary"
|
||||
onClick={handleDiscard}
|
||||
aria-label="Discard recording"
|
||||
>
|
||||
<X size={12} />
|
||||
</Button>
|
||||
</Tooltip>
|
||||
<span className={styles.micWaves} aria-hidden="true">
|
||||
<span />
|
||||
<span />
|
||||
<span />
|
||||
<span />
|
||||
<span />
|
||||
<span />
|
||||
<span />
|
||||
<span />
|
||||
</span>
|
||||
<Tooltip title="Stop and send">
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="md"
|
||||
icon
|
||||
color="secondary"
|
||||
onClick={handleStopAndSend}
|
||||
aria-label="Stop and send"
|
||||
>
|
||||
<Square size={9} fill="currentColor" strokeWidth={0} />
|
||||
</Button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
) : (
|
||||
<Tooltip title="Voice input">
|
||||
<Button
|
||||
disabledTooltip={disabledTooltip}
|
||||
color="secondary"
|
||||
variant="ghost"
|
||||
size="md"
|
||||
icon
|
||||
onClick={(): void => startVoiceInput(VoiceInputSource.Button)}
|
||||
disabled={disabled}
|
||||
aria-label="Start voice input"
|
||||
>
|
||||
<Mic size={14} />
|
||||
</Button>
|
||||
</Tooltip>
|
||||
))}
|
||||
|
||||
{isStreaming && onCancel ? (
|
||||
<Tooltip title="Stop generating">
|
||||
<Button
|
||||
variant="solid"
|
||||
size="md"
|
||||
size="sm"
|
||||
icon
|
||||
color="danger"
|
||||
onClick={onCancel}
|
||||
aria-label="Stop generating"
|
||||
>
|
||||
<Square size={10} fill="currentColor" strokeWidth={0} />
|
||||
<Square size={14} fill="currentColor" />
|
||||
</Button>
|
||||
</Tooltip>
|
||||
) : (
|
||||
@@ -1247,14 +993,14 @@ export default function ChatInput({
|
||||
<Button
|
||||
disabledTooltip={disabled ? disabledTooltip : 'Type a message first'}
|
||||
variant="solid"
|
||||
size="md"
|
||||
size="sm"
|
||||
icon
|
||||
color="primary"
|
||||
onClick={isListening ? handleStopAndSend : handleSend}
|
||||
onClick={handleSend}
|
||||
disabled={disabled || (!text.trim() && pendingFiles.length === 0)}
|
||||
aria-label="Send message"
|
||||
>
|
||||
<Send size={14} />
|
||||
<ArrowUp size={14} />
|
||||
</Button>
|
||||
</Tooltip>
|
||||
)}
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
.caret {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 2px;
|
||||
// Overhangs the glyph box by 1px each way, like the native caret.
|
||||
margin: -1px 0 0 -1px;
|
||||
padding: 1px 0;
|
||||
border-radius: 1px;
|
||||
pointer-events: none;
|
||||
background: var(--accent-primary);
|
||||
transition: transform 0.05s linear;
|
||||
animation: caretBlink 1s step-end infinite;
|
||||
|
||||
// Solid while keys are going, then blinks again.
|
||||
&.isTyping {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
|
||||
.trail {
|
||||
position: absolute;
|
||||
pointer-events: none;
|
||||
opacity: 0.4;
|
||||
background: var(--accent-primary);
|
||||
animation: trailFade 0.3s ease-out 0.4s forwards;
|
||||
|
||||
&.isFaint {
|
||||
opacity: 0.2;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes caretBlink {
|
||||
0%,
|
||||
100% {
|
||||
opacity: 1;
|
||||
}
|
||||
50% {
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes trailFade {
|
||||
to {
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.caret,
|
||||
.trail {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import { RefObject } from 'react';
|
||||
import cx from 'classnames';
|
||||
|
||||
import { useComposerCaret } from './useComposerCaret';
|
||||
|
||||
import styles from './ComposerCaret.module.scss';
|
||||
|
||||
interface ComposerCaretProps {
|
||||
textareaRef: RefObject<HTMLTextAreaElement>;
|
||||
value: string;
|
||||
}
|
||||
|
||||
export default function ComposerCaret({
|
||||
textareaRef,
|
||||
value,
|
||||
}: ComposerCaretProps): JSX.Element {
|
||||
const { caret, isTyping, trails, removeTrail } = useComposerCaret(
|
||||
textareaRef,
|
||||
value,
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
{trails.map((trail) => (
|
||||
<span
|
||||
key={trail.id}
|
||||
className={cx(styles.trail, { [styles.isFaint]: trail.faint })}
|
||||
style={{
|
||||
left: trail.left,
|
||||
top: trail.top,
|
||||
width: trail.width,
|
||||
height: trail.height,
|
||||
}}
|
||||
onAnimationEnd={(): void => removeTrail(trail.id)}
|
||||
aria-hidden
|
||||
/>
|
||||
))}
|
||||
{caret && (
|
||||
<span
|
||||
className={cx(styles.caret, { [styles.isTyping]: isTyping })}
|
||||
data-testid="ai-composer-caret"
|
||||
style={{
|
||||
transform: `translate(${caret.left}px, ${caret.top}px)`,
|
||||
height: caret.height,
|
||||
}}
|
||||
aria-hidden
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
import { useRef, useState } from 'react';
|
||||
import { fireEvent, render, screen, userEvent } from 'tests/test-utils';
|
||||
import { getCaretCoordinates } from 'utils/getCaretCoordinates';
|
||||
|
||||
import ComposerCaret from '../ComposerCaret';
|
||||
|
||||
jest.mock('utils/getCaretCoordinates');
|
||||
|
||||
const CHAR_WIDTH = 8;
|
||||
|
||||
function Composer(): JSX.Element {
|
||||
const textareaRef = useRef<HTMLTextAreaElement>(null);
|
||||
const [value, setValue] = useState('');
|
||||
return (
|
||||
<>
|
||||
<textarea
|
||||
ref={textareaRef}
|
||||
data-testid="composer"
|
||||
value={value}
|
||||
onChange={(event): void => setValue(event.target.value)}
|
||||
onKeyDown={(event): void => {
|
||||
if (event.key === 'Enter') {
|
||||
event.preventDefault();
|
||||
setValue('');
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<button type="button" data-testid="elsewhere">
|
||||
Elsewhere
|
||||
</button>
|
||||
<ComposerCaret textareaRef={textareaRef} value={value} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
describe('ComposerCaret', () => {
|
||||
beforeEach(() => {
|
||||
// jsdom has no layout; the caret only shows inside the textarea's visible height.
|
||||
jest
|
||||
.spyOn(HTMLElement.prototype, 'offsetHeight', 'get')
|
||||
.mockImplementation(function offsetHeight(this: HTMLElement) {
|
||||
return this instanceof HTMLTextAreaElement ? 40 : 0;
|
||||
});
|
||||
// One line of fixed-width text, so the caret's left tracks its index.
|
||||
jest.mocked(getCaretCoordinates).mockImplementation((_, position) => ({
|
||||
left: position * CHAR_WIDTH,
|
||||
top: 0,
|
||||
height: 16,
|
||||
}));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('draws its caret while the composer has focus', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
render(<Composer />);
|
||||
|
||||
await user.click(screen.getByTestId('composer'));
|
||||
|
||||
expect(screen.getByTestId('ai-composer-caret')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('hides its caret once the composer loses focus', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
render(<Composer />);
|
||||
await user.click(screen.getByTestId('composer'));
|
||||
|
||||
await user.click(screen.getByTestId('elsewhere'));
|
||||
|
||||
expect(screen.queryByTestId('ai-composer-caret')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('hides its caret while text is selected', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
render(<Composer />);
|
||||
const composer = screen.getByTestId<HTMLTextAreaElement>('composer');
|
||||
await user.type(composer, 'checkout latency');
|
||||
|
||||
composer.setSelectionRange(0, 8);
|
||||
// jsdom fires no selectionchange for setSelectionRange.
|
||||
fireEvent(document, new Event('selectionchange'));
|
||||
|
||||
expect(screen.queryByTestId('ai-composer-caret')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('moves its caret when code changes the text', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
render(<Composer />);
|
||||
await user.type(screen.getByTestId('composer'), 'checkout');
|
||||
expect(screen.getByTestId('ai-composer-caret')).toHaveStyle({
|
||||
transform: `translate(${8 * CHAR_WIDTH}px, 0px)`,
|
||||
});
|
||||
|
||||
await user.keyboard('{Enter}');
|
||||
|
||||
expect(screen.getByTestId('ai-composer-caret')).toHaveStyle({
|
||||
transform: 'translate(0px, 0px)',
|
||||
});
|
||||
});
|
||||
|
||||
it('hides its caret once the composer scrolls it out of view', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
render(<Composer />);
|
||||
const composer = screen.getByTestId<HTMLTextAreaElement>('composer');
|
||||
await user.type(composer, 'checkout latency');
|
||||
|
||||
composer.scrollTop = 30;
|
||||
fireEvent.scroll(composer);
|
||||
|
||||
expect(screen.queryByTestId('ai-composer-caret')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,11 @@
|
||||
export interface CaretBox {
|
||||
left: number;
|
||||
top: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
export interface CaretTrail extends CaretBox {
|
||||
id: number;
|
||||
width: number;
|
||||
faint: boolean;
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
import {
|
||||
RefObject,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useLayoutEffect,
|
||||
useRef,
|
||||
useState,
|
||||
} from 'react';
|
||||
import { getCaretCoordinates } from 'utils/getCaretCoordinates';
|
||||
|
||||
import type { CaretBox, CaretTrail } from './types';
|
||||
|
||||
interface UseComposerCaretResult {
|
||||
caret: CaretBox | null;
|
||||
isTyping: boolean;
|
||||
trails: CaretTrail[];
|
||||
removeTrail: (id: number) => void;
|
||||
}
|
||||
|
||||
const TYPING_IDLE_MS = 800;
|
||||
const MAX_TRAILS = 4;
|
||||
const ARROW_KEYS = new Set(['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown']);
|
||||
const EDIT_KEYS = new Set(['Backspace', 'Delete']);
|
||||
|
||||
export function useComposerCaret(
|
||||
textareaRef: RefObject<HTMLTextAreaElement>,
|
||||
value: string,
|
||||
): UseComposerCaretResult {
|
||||
const [caret, setCaret] = useState<CaretBox | null>(null);
|
||||
const [isTyping, setIsTyping] = useState(false);
|
||||
const [trails, setTrails] = useState<CaretTrail[]>([]);
|
||||
const lastCaretRef = useRef<CaretBox | null>(null);
|
||||
const trailIdRef = useRef(0);
|
||||
const typingTimerRef = useRef<number>();
|
||||
|
||||
const measure = useCallback((): CaretBox | null => {
|
||||
const el = textareaRef.current;
|
||||
if (
|
||||
!el ||
|
||||
document.activeElement !== el ||
|
||||
el.selectionStart !== el.selectionEnd
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
const box = getCaretCoordinates(el, el.selectionEnd);
|
||||
const top = el.offsetTop + box.top - el.scrollTop;
|
||||
const isInView =
|
||||
top >= el.offsetTop && top + box.height <= el.offsetTop + el.offsetHeight;
|
||||
if (!isInView) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
left: el.offsetLeft + box.left - el.scrollLeft,
|
||||
top,
|
||||
height: box.height,
|
||||
};
|
||||
}, [textareaRef]);
|
||||
|
||||
const update = useCallback((): void => {
|
||||
const next = measure();
|
||||
lastCaretRef.current = next;
|
||||
setCaret(next);
|
||||
}, [measure]);
|
||||
|
||||
// Leaves a fading streak over a sideways jump on the same line.
|
||||
const addTrail = useCallback((from: CaretBox, to: CaretBox): void => {
|
||||
if (Math.abs(to.top - from.top) >= 5 || Math.abs(to.left - from.left) <= 2) {
|
||||
return;
|
||||
}
|
||||
trailIdRef.current += 1;
|
||||
const id = trailIdRef.current;
|
||||
setTrails((prev) =>
|
||||
[
|
||||
...prev,
|
||||
{
|
||||
id,
|
||||
left: Math.min(from.left, to.left),
|
||||
top: to.top,
|
||||
width: Math.abs(to.left - from.left),
|
||||
height: to.height,
|
||||
faint: prev.length === 0,
|
||||
},
|
||||
].slice(-MAX_TRAILS),
|
||||
);
|
||||
}, []);
|
||||
|
||||
const removeTrail = useCallback((id: number): void => {
|
||||
setTrails((prev) => prev.filter((trail) => trail.id !== id));
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const el = textareaRef.current;
|
||||
if (!el) {
|
||||
return undefined;
|
||||
}
|
||||
let frame = 0;
|
||||
|
||||
const onKeyDown = (event: KeyboardEvent): void => {
|
||||
const isArrow = ARROW_KEYS.has(event.key);
|
||||
if (!isArrow && !EDIT_KEYS.has(event.key) && event.key.length !== 1) {
|
||||
return;
|
||||
}
|
||||
setIsTyping(true);
|
||||
window.clearTimeout(typingTimerRef.current);
|
||||
typingTimerRef.current = window.setTimeout(
|
||||
() => setIsTyping(false),
|
||||
TYPING_IDLE_MS,
|
||||
);
|
||||
if (isArrow) {
|
||||
const from = lastCaretRef.current;
|
||||
cancelAnimationFrame(frame);
|
||||
frame = requestAnimationFrame(() => {
|
||||
const to = measure();
|
||||
if (from && to) {
|
||||
addTrail(from, to);
|
||||
}
|
||||
lastCaretRef.current = to;
|
||||
setCaret(to);
|
||||
});
|
||||
}
|
||||
};
|
||||
const onSelectionChange = (): void => {
|
||||
if (document.activeElement === el) {
|
||||
update();
|
||||
}
|
||||
};
|
||||
const hide = (): void => {
|
||||
lastCaretRef.current = null;
|
||||
setCaret(null);
|
||||
};
|
||||
const observer = new ResizeObserver(() => update());
|
||||
|
||||
el.addEventListener('keydown', onKeyDown);
|
||||
el.addEventListener('focus', update);
|
||||
el.addEventListener('blur', hide);
|
||||
el.addEventListener('scroll', update);
|
||||
document.addEventListener('selectionchange', onSelectionChange);
|
||||
observer.observe(el);
|
||||
update();
|
||||
|
||||
return (): void => {
|
||||
el.removeEventListener('keydown', onKeyDown);
|
||||
el.removeEventListener('focus', update);
|
||||
el.removeEventListener('blur', hide);
|
||||
el.removeEventListener('scroll', update);
|
||||
document.removeEventListener('selectionchange', onSelectionChange);
|
||||
observer.disconnect();
|
||||
cancelAnimationFrame(frame);
|
||||
window.clearTimeout(typingTimerRef.current);
|
||||
};
|
||||
}, [textareaRef, measure, update, addTrail]);
|
||||
|
||||
// Text set from code (prefill, @-mentions, send) moves the caret without a key.
|
||||
useLayoutEffect(() => {
|
||||
update();
|
||||
}, [value, update]);
|
||||
|
||||
return { caret, isTyping, trails, removeTrail };
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
// Offsets are from the input's padding box; its top edge, border or separator, sits at -1px.
|
||||
|
||||
.edgeSweep {
|
||||
position: absolute;
|
||||
top: -11px;
|
||||
left: 0;
|
||||
right: 0;
|
||||
height: 20px;
|
||||
overflow: hidden;
|
||||
opacity: 0;
|
||||
z-index: 2;
|
||||
pointer-events: none;
|
||||
transition: opacity 0.3s ease;
|
||||
mask-image: linear-gradient(
|
||||
to right,
|
||||
transparent 11px,
|
||||
var(--l1-background) 60px,
|
||||
var(--l1-background) calc(100% - 60px),
|
||||
transparent calc(100% - 11px)
|
||||
);
|
||||
|
||||
&.isVisible {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
.line {
|
||||
position: absolute;
|
||||
top: 9px;
|
||||
left: 0;
|
||||
width: 40%;
|
||||
height: 2px;
|
||||
animation: edgeSweep 2s ease-in-out infinite alternate;
|
||||
|
||||
&::before,
|
||||
&::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
left: 0;
|
||||
right: 0;
|
||||
background: linear-gradient(
|
||||
to right,
|
||||
transparent,
|
||||
var(--accent-primary) 20%,
|
||||
var(--accent-primary) 80%,
|
||||
transparent
|
||||
);
|
||||
}
|
||||
|
||||
&::before {
|
||||
top: 1px;
|
||||
height: 1px;
|
||||
}
|
||||
|
||||
&::after {
|
||||
top: 0;
|
||||
height: 2px;
|
||||
filter: blur(4px);
|
||||
opacity: 0.7;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes edgeSweep {
|
||||
from {
|
||||
transform: translateX(-50%);
|
||||
}
|
||||
to {
|
||||
transform: translateX(200%);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { useState } from 'react';
|
||||
import cx from 'classnames';
|
||||
|
||||
import styles from './EdgeSweep.module.scss';
|
||||
|
||||
interface EdgeSweepProps {
|
||||
/** When the current stream began; null while idle. */
|
||||
startedAt: number | null;
|
||||
}
|
||||
|
||||
interface SweepRun {
|
||||
startedAt: number;
|
||||
elapsedMs: number;
|
||||
}
|
||||
|
||||
/** Gradient sweeping the input's top edge while Noz replies. */
|
||||
export default function EdgeSweep({ startedAt }: EdgeSweepProps): JSX.Element {
|
||||
// Outlives the stream so the line keeps moving while it fades out.
|
||||
const [run, setRun] = useState<SweepRun | null>(() =>
|
||||
startedAt === null ? null : { startedAt, elapsedMs: Date.now() - startedAt },
|
||||
);
|
||||
// A new stream restarts from the left; a remount mid-stream picks up where it was.
|
||||
if (startedAt !== null && startedAt !== run?.startedAt) {
|
||||
setRun({ startedAt, elapsedMs: Date.now() - startedAt });
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cx(styles.edgeSweep, { [styles.isVisible]: startedAt !== null })}
|
||||
data-testid="ai-input-edge-sweep"
|
||||
onTransitionEnd={(): void => {
|
||||
if (startedAt === null) {
|
||||
setRun(null);
|
||||
}
|
||||
}}
|
||||
aria-hidden
|
||||
>
|
||||
{run && (
|
||||
<div
|
||||
key={run.startedAt}
|
||||
className={styles.line}
|
||||
data-testid="ai-input-edge-sweep-line"
|
||||
style={{ animationDelay: `${-run.elapsedMs}ms` }}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { render, screen } from 'tests/test-utils';
|
||||
|
||||
import EdgeSweep from '../EdgeSweep';
|
||||
|
||||
const NOW = 10_000;
|
||||
|
||||
describe('EdgeSweep', () => {
|
||||
beforeEach(() => {
|
||||
jest.spyOn(Date, 'now').mockReturnValue(NOW);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('stays still while Noz is idle', () => {
|
||||
render(<EdgeSweep startedAt={null} />);
|
||||
|
||||
expect(
|
||||
screen.queryByTestId('ai-input-edge-sweep-line'),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('picks up a reply already under way instead of restarting', () => {
|
||||
render(<EdgeSweep startedAt={NOW - 1500} />);
|
||||
|
||||
expect(screen.getByTestId('ai-input-edge-sweep-line')).toHaveStyle({
|
||||
animationDelay: '-1500ms',
|
||||
});
|
||||
});
|
||||
|
||||
it('restarts from the left for the next reply', () => {
|
||||
const { rerender } = render(<EdgeSweep startedAt={NOW - 1500} />);
|
||||
|
||||
rerender(<EdgeSweep startedAt={NOW} />);
|
||||
|
||||
expect(screen.getByTestId('ai-input-edge-sweep-line')).toHaveStyle({
|
||||
animationDelay: '0ms',
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,109 @@
|
||||
// Offsets are from the input's padding box; its top edge, border or separator, sits at -1px.
|
||||
|
||||
.body {
|
||||
position: absolute;
|
||||
top: -29px;
|
||||
right: 6px;
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
pointer-events: none;
|
||||
// Hides what is below the top edge, as if Noz stood behind the input.
|
||||
clip-path: inset(-50% -50% 12px -50%);
|
||||
}
|
||||
|
||||
.bodySvg {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
overflow: visible;
|
||||
animation: bodyPeek 0.7s cubic-bezier(0.34, 1.45, 0.5, 1) 0.95s both;
|
||||
}
|
||||
|
||||
.head {
|
||||
transform-origin: 12px 16px;
|
||||
animation: headBob 0.5s ease-in-out 1.05s 2;
|
||||
}
|
||||
|
||||
.pupil {
|
||||
transition: transform 0.13s ease-out;
|
||||
}
|
||||
|
||||
.hands {
|
||||
position: absolute;
|
||||
top: -5px;
|
||||
right: 9px;
|
||||
width: 34px;
|
||||
height: 7px;
|
||||
pointer-events: none;
|
||||
// Behind the top edge on the way up, in front of it on the way down.
|
||||
animation: handsClip 0.7s 0.6s both;
|
||||
}
|
||||
|
||||
.handsSvg {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
overflow: visible;
|
||||
animation: handsPeek 0.7s cubic-bezier(0.22, 1, 0.36, 1) 0.6s both;
|
||||
}
|
||||
|
||||
@keyframes bodyPeek {
|
||||
from {
|
||||
transform: translateY(34px);
|
||||
}
|
||||
to {
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes headBob {
|
||||
0%,
|
||||
100% {
|
||||
transform: translateY(0) rotate(0deg);
|
||||
}
|
||||
50% {
|
||||
transform: translateY(-1px) rotate(-6deg);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes handsPeek {
|
||||
0% {
|
||||
transform: translateY(16px);
|
||||
opacity: 0;
|
||||
}
|
||||
20% {
|
||||
opacity: 1;
|
||||
}
|
||||
50%,
|
||||
51% {
|
||||
transform: translateY(-7px);
|
||||
}
|
||||
100% {
|
||||
transform: translateY(2px);
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes handsClip {
|
||||
0%,
|
||||
50% {
|
||||
clip-path: inset(-20px -20px 3px -20px);
|
||||
}
|
||||
51%,
|
||||
100% {
|
||||
clip-path: inset(-20px);
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.bodySvg,
|
||||
.head,
|
||||
.hands,
|
||||
.handsSvg {
|
||||
animation: none;
|
||||
}
|
||||
|
||||
.handsSvg {
|
||||
transform: translateY(2px);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import { useRef } from 'react';
|
||||
import {
|
||||
NOZ_BODY,
|
||||
NOZ_COLORS,
|
||||
NOZ_EYE,
|
||||
NOZ_HAT_PATH,
|
||||
NOZ_PUPIL_PATH,
|
||||
} from 'components/Noz/Noz.constants';
|
||||
|
||||
import { useNozPupilTracking } from './useNozPupilTracking';
|
||||
|
||||
import styles from './NozPeek.module.scss';
|
||||
|
||||
/** Noz climbs over the input's top edge, hands first, then watches the cursor. */
|
||||
export default function NozPeek(): JSX.Element {
|
||||
const eyeRef = useRef<SVGCircleElement>(null);
|
||||
const pupilRef = useRef<SVGGElement>(null);
|
||||
useNozPupilTracking(eyeRef, pupilRef);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className={styles.body} data-testid="ai-noz-peek" aria-hidden>
|
||||
<svg
|
||||
className={styles.bodySvg}
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<rect {...NOZ_BODY} fill={NOZ_COLORS.body} />
|
||||
<g className={styles.head}>
|
||||
<circle ref={eyeRef} {...NOZ_EYE} fill={NOZ_COLORS.eye} />
|
||||
<g
|
||||
ref={pupilRef}
|
||||
className={styles.pupil}
|
||||
data-testid="ai-noz-peek-pupil"
|
||||
>
|
||||
<path d={NOZ_PUPIL_PATH} fill={NOZ_COLORS.pupil} />
|
||||
</g>
|
||||
<path d={NOZ_HAT_PATH} fill={NOZ_COLORS.hat} />
|
||||
</g>
|
||||
</svg>
|
||||
</div>
|
||||
<div className={styles.hands} aria-hidden>
|
||||
<svg
|
||||
className={styles.handsSvg}
|
||||
viewBox="0 0 34 7"
|
||||
fill="none"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<rect
|
||||
width="3.52294"
|
||||
height="6.16514"
|
||||
rx="1.46789"
|
||||
fill={NOZ_COLORS.body}
|
||||
/>
|
||||
<rect
|
||||
x="30.4775"
|
||||
width="3.52294"
|
||||
height="6.16514"
|
||||
rx="1.46789"
|
||||
fill={NOZ_COLORS.body}
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import { render, screen, userEvent } from 'tests/test-utils';
|
||||
|
||||
import NozPeek from '../NozPeek';
|
||||
|
||||
describe('NozPeek', () => {
|
||||
beforeEach(() => {
|
||||
jest.useFakeTimers();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.useRealTimers();
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('keeps its eye still while it is still climbing over the edge', async () => {
|
||||
const user = userEvent.setup({
|
||||
advanceTimers: (ms) => jest.advanceTimersByTime(ms),
|
||||
});
|
||||
render(<NozPeek />);
|
||||
|
||||
await user.pointer({
|
||||
target: document.body,
|
||||
coords: { clientX: 200, clientY: 0 },
|
||||
});
|
||||
|
||||
expect(screen.getByTestId('ai-noz-peek-pupil').style.transform).toBe('');
|
||||
});
|
||||
|
||||
it('follows the cursor with its eye once it has settled', async () => {
|
||||
const user = userEvent.setup({
|
||||
advanceTimers: (ms) => jest.advanceTimersByTime(ms),
|
||||
});
|
||||
render(<NozPeek />);
|
||||
jest.advanceTimersByTime(1900);
|
||||
|
||||
await user.pointer({
|
||||
target: document.body,
|
||||
coords: { clientX: 200, clientY: 0 },
|
||||
});
|
||||
|
||||
expect(screen.getByTestId('ai-noz-peek-pupil').style.transform).toBe(
|
||||
'translate(1.250px, 0.000px)',
|
||||
);
|
||||
});
|
||||
|
||||
it('keeps its eye still with reduced motion, even once it has settled', async () => {
|
||||
jest
|
||||
.spyOn(window, 'matchMedia')
|
||||
.mockImplementation((query: string): MediaQueryList => ({
|
||||
matches: query === '(prefers-reduced-motion: reduce)',
|
||||
media: query,
|
||||
onchange: null,
|
||||
addListener: jest.fn(),
|
||||
removeListener: jest.fn(),
|
||||
addEventListener: jest.fn(),
|
||||
removeEventListener: jest.fn(),
|
||||
dispatchEvent: jest.fn(),
|
||||
}));
|
||||
const user = userEvent.setup({
|
||||
advanceTimers: (ms) => jest.advanceTimersByTime(ms),
|
||||
});
|
||||
render(<NozPeek />);
|
||||
jest.advanceTimersByTime(1900);
|
||||
|
||||
await user.pointer({
|
||||
target: document.body,
|
||||
coords: { clientX: 200, clientY: 0 },
|
||||
});
|
||||
|
||||
expect(screen.getByTestId('ai-noz-peek-pupil').style.transform).toBe('');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
import { RefObject, useEffect } from 'react';
|
||||
|
||||
// Noz has settled on the edge by now.
|
||||
const SETTLE_MS = 1900;
|
||||
// Furthest the pupil moves, in SVG units.
|
||||
const MAX_OFFSET = 1.25;
|
||||
// Cursor distance, in px, at which the pupil reaches MAX_OFFSET.
|
||||
const FULL_REACH_PX = 160;
|
||||
|
||||
export function useNozPupilTracking(
|
||||
eyeRef: RefObject<SVGCircleElement>,
|
||||
pupilRef: RefObject<SVGGElement>,
|
||||
): void {
|
||||
useEffect(() => {
|
||||
// With reduced motion Noz stays still, so the eye does not follow the cursor.
|
||||
if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
|
||||
return undefined;
|
||||
}
|
||||
let isSettled = false;
|
||||
const timer = window.setTimeout(() => {
|
||||
isSettled = true;
|
||||
}, SETTLE_MS);
|
||||
|
||||
const onMouseMove = (event: MouseEvent): void => {
|
||||
const eye = eyeRef.current;
|
||||
const pupil = pupilRef.current;
|
||||
if (!isSettled || !eye || !pupil) {
|
||||
return;
|
||||
}
|
||||
const rect = eye.getBoundingClientRect();
|
||||
const dx = event.clientX - (rect.left + rect.width / 2);
|
||||
const dy = event.clientY - (rect.top + rect.height / 2);
|
||||
const distance = Math.hypot(dx, dy) || 1;
|
||||
const reach = Math.min(1, distance / FULL_REACH_PX) * MAX_OFFSET;
|
||||
pupil.style.transform = `translate(${((dx / distance) * reach).toFixed(3)}px, ${((dy / distance) * reach).toFixed(3)}px)`;
|
||||
};
|
||||
|
||||
window.addEventListener('mousemove', onMouseMove);
|
||||
return (): void => {
|
||||
window.clearTimeout(timer);
|
||||
window.removeEventListener('mousemove', onMouseMove);
|
||||
};
|
||||
}, [eyeRef, pupilRef]);
|
||||
}
|
||||
@@ -23,24 +23,6 @@ jest.mock('hooks/useQueryService', () => ({
|
||||
}),
|
||||
}));
|
||||
|
||||
jest.mock('../../../hooks/useSpeechRecognition', () => ({
|
||||
useSpeechRecognition: (): unknown => ({
|
||||
isListening: false,
|
||||
isSupported: false,
|
||||
permission: 'prompt',
|
||||
start: jest.fn(),
|
||||
discard: jest.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
jest.mock('../../../hooks/useAIAssistantAnalyticsContext', () => ({
|
||||
useAIAssistantAnalyticsContext: (): unknown => ({
|
||||
threadId: undefined,
|
||||
page: '/',
|
||||
mode: 'sidepane',
|
||||
}),
|
||||
}));
|
||||
|
||||
// eslint-disable-next-line import/first
|
||||
import ChatInput from '../ChatInput';
|
||||
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import { render, screen } from 'tests/test-utils';
|
||||
|
||||
import ChatInput from '../ChatInput';
|
||||
|
||||
describe('ChatInput composer', () => {
|
||||
it('asks the user to ask Noz', () => {
|
||||
render(<ChatInput onSend={jest.fn()} />);
|
||||
|
||||
expect(screen.getByTestId('ai-chat-input-textarea')).toHaveAttribute(
|
||||
'placeholder',
|
||||
'Ask Noz…',
|
||||
);
|
||||
});
|
||||
|
||||
it('focuses the textarea when asked again', () => {
|
||||
const { rerender } = render(
|
||||
<ChatInput onSend={jest.fn()} focusRequest={0} />,
|
||||
);
|
||||
const textarea = screen.getByTestId('ai-chat-input-textarea');
|
||||
textarea.blur();
|
||||
|
||||
rerender(<ChatInput onSend={jest.fn()} focusRequest={1} />);
|
||||
|
||||
expect(textarea).toHaveFocus();
|
||||
});
|
||||
});
|
||||
@@ -3,7 +3,7 @@ import { render, screen, userEvent } from 'tests/test-utils';
|
||||
import ChatInput from '../ChatInput';
|
||||
|
||||
function getComposer(): HTMLTextAreaElement {
|
||||
return screen.getByPlaceholderText(/Ask anything/i) as HTMLTextAreaElement;
|
||||
return screen.getByTestId<HTMLTextAreaElement>('ai-chat-input-textarea');
|
||||
}
|
||||
|
||||
describe('ChatInput — @ mention trigger', () => {
|
||||
@@ -13,7 +13,7 @@ describe('ChatInput — @ mention trigger', () => {
|
||||
await userEvent.type(getComposer(), 'check @');
|
||||
|
||||
await expect(
|
||||
screen.findByPlaceholderText(/search dashboards/i),
|
||||
screen.findByTestId('ai-context-search'),
|
||||
).resolves.toBeInTheDocument();
|
||||
});
|
||||
|
||||
@@ -23,8 +23,6 @@ describe('ChatInput — @ mention trigger', () => {
|
||||
await userEvent.type(getComposer(), 'mail user@example.com');
|
||||
|
||||
expect(getComposer()).toHaveValue('mail user@example.com');
|
||||
expect(
|
||||
screen.queryByPlaceholderText(/search dashboards/i),
|
||||
).not.toBeInTheDocument();
|
||||
expect(screen.queryByTestId('ai-context-search')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -29,26 +29,6 @@ jest.mock('hooks/useQueryService', () => ({
|
||||
}),
|
||||
}));
|
||||
|
||||
// Irrelevant to the prefill flow and otherwise require browser APIs / extra
|
||||
// context providers, so stub them out.
|
||||
jest.mock('../../../hooks/useSpeechRecognition', () => ({
|
||||
useSpeechRecognition: (): unknown => ({
|
||||
isListening: false,
|
||||
isSupported: false,
|
||||
permission: 'prompt',
|
||||
start: jest.fn(),
|
||||
discard: jest.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
jest.mock('../../../hooks/useAIAssistantAnalyticsContext', () => ({
|
||||
useAIAssistantAnalyticsContext: (): unknown => ({
|
||||
threadId: undefined,
|
||||
page: '/',
|
||||
mode: 'sidepane',
|
||||
}),
|
||||
}));
|
||||
|
||||
// eslint-disable-next-line import/first
|
||||
// eslint-disable-next-line import/first
|
||||
import ChatInput from '../ChatInput';
|
||||
@@ -58,7 +38,7 @@ function renderChatInput(): void {
|
||||
}
|
||||
|
||||
function getComposer(): HTMLTextAreaElement {
|
||||
return screen.getByPlaceholderText(/Ask anything/i) as HTMLTextAreaElement;
|
||||
return screen.getByTestId<HTMLTextAreaElement>('ai-chat-input-textarea');
|
||||
}
|
||||
|
||||
describe('ChatInput — empty-state CTA prefill flow', () => {
|
||||
@@ -69,11 +49,8 @@ describe('ChatInput — empty-state CTA prefill flow', () => {
|
||||
await userEvent.type(getComposer(), 'show me something');
|
||||
|
||||
// Open the picker and search for an entity that does not exist.
|
||||
await userEvent.click(screen.getByRole('button', { name: /add context/i }));
|
||||
await userEvent.type(
|
||||
await screen.findByPlaceholderText(/search dashboards/i),
|
||||
'chk',
|
||||
);
|
||||
await userEvent.click(screen.getByTestId('ai-chat-input-add-context'));
|
||||
await userEvent.type(await screen.findByTestId('ai-context-search'), 'chk');
|
||||
|
||||
const cta = await screen.findByTestId('ai-context-empty-cta-Dashboards');
|
||||
expect(cta).toHaveTextContent('Create a dashboard for "chk"');
|
||||
@@ -96,7 +73,7 @@ describe('ChatInput — empty-state CTA prefill flow', () => {
|
||||
it('seeds only the prefix (with trailing space) in the onboarding case', async () => {
|
||||
renderChatInput();
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: /add context/i }));
|
||||
await userEvent.click(screen.getByTestId('ai-chat-input-add-context'));
|
||||
|
||||
const cta = await screen.findByTestId('ai-context-empty-cta-Dashboards');
|
||||
expect(cta).toHaveTextContent('Ask me to create one');
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
import './__fixtures__/speechRecognitionSupport';
|
||||
|
||||
import { render, screen } from 'tests/test-utils';
|
||||
|
||||
import ChatInput from '../ChatInput';
|
||||
|
||||
describe('ChatInput without voice input', () => {
|
||||
it('offers no voice input, even where the browser supports speech', () => {
|
||||
render(<ChatInput onSend={jest.fn()} />);
|
||||
|
||||
// The removed mic button never had a test ID, so it is looked up by its label.
|
||||
expect(
|
||||
screen.queryByRole('button', { name: /voice input/i }),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,5 @@
|
||||
// Imported before ChatInput: speech support was read once, at module load.
|
||||
Object.defineProperty(window, 'webkitSpeechRecognition', {
|
||||
configurable: true,
|
||||
value: class SpeechRecognitionStub {},
|
||||
});
|
||||
@@ -37,6 +37,11 @@
|
||||
.assistant & {
|
||||
align-items: flex-start;
|
||||
}
|
||||
|
||||
// The full page's column is already narrow, so replies use all of it.
|
||||
.assistant &.fullPage {
|
||||
max-width: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
.bubble {
|
||||
@@ -50,9 +55,11 @@
|
||||
max-width: 100%;
|
||||
|
||||
.user & {
|
||||
background: var(--accent-primary);
|
||||
color: var(--primary-foreground);
|
||||
border-bottom-right-radius: var(--radius-2);
|
||||
padding: var(--spacing-4) var(--spacing-6);
|
||||
border-radius: var(--radius-3);
|
||||
background: var(--l3-background-60);
|
||||
color: var(--l1-foreground);
|
||||
font-size: var(--periscope-font-size-base);
|
||||
}
|
||||
|
||||
.assistant & {
|
||||
|
||||
@@ -141,7 +141,10 @@ export default function MessageBubble({
|
||||
[styles.compact]: isCompact,
|
||||
},
|
||||
);
|
||||
const bodyClass = cx(styles.body, { [styles.compact]: isCompact });
|
||||
const bodyClass = cx(styles.body, {
|
||||
[styles.compact]: isCompact,
|
||||
[styles.fullPage]: variant === 'page',
|
||||
});
|
||||
|
||||
return (
|
||||
<div className={messageClass} data-testid={`ai-message-${message.id}`}>
|
||||
|
||||
@@ -49,7 +49,7 @@ export default function UserMessageActions({
|
||||
onClick={handleCopy}
|
||||
aria-label={copied ? 'Copied' : 'Copy message'}
|
||||
>
|
||||
{copied ? <Check size={12} /> : <Copy size={12} />}
|
||||
{copied ? <Check size={14} /> : <Copy size={14} />}
|
||||
</Button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
@use '../../../_scrollbar' as *;
|
||||
|
||||
.empty {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding: var(--spacing-6);
|
||||
overflow-y: auto;
|
||||
@include scrollbar;
|
||||
|
||||
// Matches the dot grid's share of the height, so the content stays centred.
|
||||
&::after {
|
||||
content: '';
|
||||
flex: 1 1 0;
|
||||
}
|
||||
|
||||
// The panel sits it above the input, clear of the Noz peeking over its corner.
|
||||
&.compact {
|
||||
padding-right: var(--spacing-24);
|
||||
|
||||
&::after {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fills the empty space above the content, edge to edge.
|
||||
.dotGrid {
|
||||
display: block;
|
||||
flex: 1 1 0;
|
||||
min-height: 0;
|
||||
margin: calc(-1 * var(--spacing-6)) calc(-1 * var(--spacing-6))
|
||||
var(--spacing-6);
|
||||
|
||||
.compact & {
|
||||
margin-right: calc(-1 * var(--spacing-24));
|
||||
}
|
||||
}
|
||||
|
||||
.emptyContent {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: var(--spacing-10);
|
||||
max-width: calc(var(--spacing-56) * 3);
|
||||
// Auto margins centre it without clipping the top when it outgrows the view.
|
||||
margin: auto;
|
||||
|
||||
.compact & {
|
||||
margin: auto 0 0;
|
||||
}
|
||||
}
|
||||
|
||||
.emptyIntro {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: var(--spacing-5);
|
||||
}
|
||||
|
||||
.emptyHeading {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: var(--spacing-4);
|
||||
}
|
||||
|
||||
.emptyTitle {
|
||||
margin: 0;
|
||||
font-size: var(--periscope-font-size-large);
|
||||
font-weight: var(--font-weight-medium);
|
||||
line-height: 1;
|
||||
color: var(--l1-foreground);
|
||||
}
|
||||
|
||||
.emptySubtitle {
|
||||
margin: 0;
|
||||
font-size: var(--periscope-font-size-base);
|
||||
line-height: var(--line-height-20);
|
||||
letter-spacing: -0.005em;
|
||||
color: var(--l2-foreground);
|
||||
}
|
||||
|
||||
.suggestions {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: var(--spacing-4);
|
||||
--button-height: auto;
|
||||
--button-padding: var(--spacing-3) var(--spacing-5);
|
||||
--button-border-radius: var(--radius-3);
|
||||
--button-font-weight: var(--font-weight-normal);
|
||||
--button-size-line-height: var(--line-height-20);
|
||||
--button-white-space: normal;
|
||||
--button-label-white-space: normal;
|
||||
--button-variant-ghost-background-color: var(--l3-background-60);
|
||||
--button-variant-ghost-color: var(--l2-foreground);
|
||||
--button-variant-ghost-hover-background-color: var(--l3-background);
|
||||
--button-variant-ghost-hover-color: var(--l1-foreground);
|
||||
|
||||
// Buttons don't inherit the page font, and long prompts wrap from the left.
|
||||
> [data-slot='button'] {
|
||||
font-family: inherit;
|
||||
text-align: left;
|
||||
}
|
||||
}
|
||||
|
||||
// The same box as a chip; the prompt inside is invisible and only sets the size.
|
||||
.suggestionSkeleton {
|
||||
position: relative;
|
||||
max-width: 100%;
|
||||
padding: var(--spacing-3) var(--spacing-5);
|
||||
border-radius: var(--radius-3);
|
||||
overflow: hidden;
|
||||
font-size: var(--periscope-font-size-base);
|
||||
line-height: var(--line-height-20);
|
||||
letter-spacing: -0.005em;
|
||||
color: transparent;
|
||||
user-select: none;
|
||||
|
||||
// Nested so it outranks the skeleton's own `position: relative`.
|
||||
.suggestionSkeletonFill {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
--skeleton-background: var(--l3-background-60);
|
||||
--skeleton-shimmer-color: color-mix(
|
||||
in srgb,
|
||||
var(--l2-foreground),
|
||||
transparent 92%
|
||||
);
|
||||
--skeleton-input-height: 100%;
|
||||
--skeleton-input-border-radius: var(--radius-3);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
import cx from 'classnames';
|
||||
import { Badge } from '@signozhq/ui/badge';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { Skeleton } from '@signozhq/ui/skeleton';
|
||||
|
||||
import logEvent from 'api/common/logEvent';
|
||||
import DotGrid from 'components/DotGrid/DotGrid';
|
||||
|
||||
import { AIAssistantEvents, SuggestedPromptCategory } from '../../../events';
|
||||
import { useVariant } from '../../../VariantContext';
|
||||
import { EMPTY_STATE_CHIPS_FALLBACK } from '../emptyStateChipsFallback';
|
||||
import { useEmptyStateChips } from '../useEmptyStateChips';
|
||||
|
||||
import styles from './EmptyState.module.scss';
|
||||
|
||||
interface EmptyStateProps {
|
||||
onSendSuggestedPrompt: (text: string) => void;
|
||||
onSnakeGameChange?: (isPlaying: boolean) => void;
|
||||
}
|
||||
|
||||
/** A new chat: the dot grid, Noz's intro and the suggested prompts. */
|
||||
export default function EmptyState({
|
||||
onSendSuggestedPrompt,
|
||||
onSnakeGameChange,
|
||||
}: EmptyStateProps): JSX.Element {
|
||||
const isCompact = useVariant() === 'panel';
|
||||
const { chips: emptyStateChips, isLoading: areChipsLoading } =
|
||||
useEmptyStateChips(true);
|
||||
|
||||
return (
|
||||
<div className={cx(styles.empty, { [styles.compact]: isCompact })}>
|
||||
<DotGrid className={styles.dotGrid} onGameChange={onSnakeGameChange} />
|
||||
<div className={styles.emptyContent}>
|
||||
<div className={styles.emptyIntro}>
|
||||
<div className={styles.emptyHeading}>
|
||||
<h3 className={styles.emptyTitle}>Noz</h3>
|
||||
<Badge color="secondary" variant="outlined">
|
||||
beta
|
||||
</Badge>
|
||||
</div>
|
||||
<p className={styles.emptySubtitle}>
|
||||
I can help you understand and be the all-seeing eye over your entire
|
||||
infrastructure. What do you need?
|
||||
</p>
|
||||
</div>
|
||||
<div className={styles.suggestions} aria-busy={areChipsLoading}>
|
||||
{/* As many as the backend sends, each the width of a real prompt. */}
|
||||
{areChipsLoading &&
|
||||
EMPTY_STATE_CHIPS_FALLBACK.map((chip) => (
|
||||
<span
|
||||
key={chip.id}
|
||||
className={styles.suggestionSkeleton}
|
||||
data-testid="empty-state-chip-skeleton"
|
||||
aria-hidden
|
||||
>
|
||||
<Skeleton.Input
|
||||
active
|
||||
block
|
||||
className={styles.suggestionSkeletonFill}
|
||||
/>
|
||||
{chip.text}
|
||||
</span>
|
||||
))}
|
||||
{emptyStateChips.map((chip) => (
|
||||
<Button
|
||||
key={chip.id}
|
||||
variant="ghost"
|
||||
color="secondary"
|
||||
size="md"
|
||||
onClick={(): void => {
|
||||
void logEvent(AIAssistantEvents.SuggestedPromptClicked, {
|
||||
promptId: chip.id,
|
||||
category: SuggestedPromptCategory.EmptyState,
|
||||
});
|
||||
onSendSuggestedPrompt(chip.text);
|
||||
}}
|
||||
testId={`empty-state-chip-${chip.id}`}
|
||||
>
|
||||
{chip.text}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { render, screen, userEvent } from 'tests/test-utils';
|
||||
|
||||
import { EMPTY_STATE_CHIPS_FALLBACK } from '../../emptyStateChipsFallback';
|
||||
import { useEmptyStateChips } from '../../useEmptyStateChips';
|
||||
import EmptyState from '../EmptyState';
|
||||
|
||||
jest.mock('../../useEmptyStateChips');
|
||||
|
||||
const mockChips = jest.mocked(useEmptyStateChips);
|
||||
|
||||
describe('EmptyState', () => {
|
||||
it('holds a placeholder for every prompt while they load', () => {
|
||||
mockChips.mockReturnValue({ chips: [], isLoading: true });
|
||||
|
||||
render(<EmptyState onSendSuggestedPrompt={jest.fn()} />);
|
||||
|
||||
expect(screen.getAllByTestId('empty-state-chip-skeleton')).toHaveLength(
|
||||
EMPTY_STATE_CHIPS_FALLBACK.length,
|
||||
);
|
||||
});
|
||||
|
||||
it('sends a suggestion when it is clicked', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const onSend = jest.fn();
|
||||
mockChips.mockReturnValue({
|
||||
chips: [{ id: 'slow_queries', text: 'Find slow database queries' }],
|
||||
isLoading: false,
|
||||
});
|
||||
render(<EmptyState onSendSuggestedPrompt={onSend} />);
|
||||
|
||||
await user.click(screen.getByTestId('empty-state-chip-slow_queries'));
|
||||
|
||||
expect(onSend).toHaveBeenCalledWith('Find slow database queries');
|
||||
});
|
||||
});
|
||||
@@ -15,69 +15,8 @@
|
||||
}
|
||||
}
|
||||
|
||||
.empty {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
// `safe` falls back to the top once the content overflows, so it stays scrollable.
|
||||
justify-content: safe center;
|
||||
padding: 32px 24px;
|
||||
gap: 8px;
|
||||
text-align: center;
|
||||
@include scrollbar;
|
||||
}
|
||||
|
||||
.emptyIcon {
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.emptyTitle {
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
color: var(--l1-foreground);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.emptySubtitle {
|
||||
font-size: 13px;
|
||||
color: var(--l3-foreground);
|
||||
margin: 0 0 12px;
|
||||
max-width: 320px;
|
||||
line-height: 1.45;
|
||||
}
|
||||
|
||||
.suggestions {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
width: 100%;
|
||||
max-width: 360px;
|
||||
}
|
||||
|
||||
.suggestion {
|
||||
box-sizing: border-box;
|
||||
width: 100%;
|
||||
padding: 10px 14px;
|
||||
border: 1px solid var(--l2-border);
|
||||
border-radius: var(--radius-2);
|
||||
background: var(--l1-background);
|
||||
color: var(--l2-foreground);
|
||||
font-size: 12.5px;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
transition:
|
||||
background 0.15s ease,
|
||||
border-color 0.15s ease,
|
||||
color 0.15s ease;
|
||||
line-height: 1.35;
|
||||
overflow-wrap: anywhere;
|
||||
|
||||
&:hover {
|
||||
background: var(--l2-background);
|
||||
border-color: var(--l3-border);
|
||||
color: var(--l1-foreground);
|
||||
}
|
||||
// As wide as the full-page input; the extra 32px is the rows' own gutters.
|
||||
.row.fullPage {
|
||||
max-width: calc(var(--noz-page-column) + 32px);
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
@@ -1,18 +1,19 @@
|
||||
import { useCallback, useEffect, useRef } from 'react';
|
||||
import { Virtuoso, VirtuosoHandle } from 'react-virtuoso';
|
||||
import Noz from 'components/Noz/Noz';
|
||||
import cx from 'classnames';
|
||||
|
||||
import logEvent from 'api/common/logEvent';
|
||||
|
||||
import { AIAssistantEvents, SuggestedPromptCategory } from '../../events';
|
||||
import { AIAssistantEvents } from '../../events';
|
||||
import { useAIAssistantAnalyticsContext } from '../../hooks/useAIAssistantAnalyticsContext';
|
||||
import { useAIAssistantStore } from '../../store/useAIAssistantStore';
|
||||
import { Message, StreamingEventItem } from '../../types';
|
||||
import { useVariant } from '../../VariantContext';
|
||||
import MessageBubble from '../MessageBubble';
|
||||
import StreamingMessage from '../StreamingMessage';
|
||||
|
||||
import EmptyState from './EmptyState/EmptyState';
|
||||
import styles from './VirtualizedMessages.module.scss';
|
||||
import { useEmptyStateChips } from './useEmptyStateChips';
|
||||
|
||||
const EMPTY_EVENTS: StreamingEventItem[] = [];
|
||||
|
||||
@@ -26,6 +27,8 @@ interface VirtualizedMessagesProps {
|
||||
* page/mode/context attribution as a normal send.
|
||||
*/
|
||||
onSendSuggestedPrompt: (text: string) => void;
|
||||
/** A Snake game on the empty state's dot grid started or ended. */
|
||||
onSnakeGameChange?: (isPlaying: boolean) => void;
|
||||
}
|
||||
|
||||
export default function VirtualizedMessages({
|
||||
@@ -33,6 +36,7 @@ export default function VirtualizedMessages({
|
||||
messages,
|
||||
isStreaming,
|
||||
onSendSuggestedPrompt,
|
||||
onSnakeGameChange,
|
||||
}: VirtualizedMessagesProps): JSX.Element {
|
||||
const regenerateAssistantMessage = useAIAssistantStore(
|
||||
(s) => s.regenerateAssistantMessage,
|
||||
@@ -73,6 +77,7 @@ export default function VirtualizedMessages({
|
||||
// the user was scrolled — sending a message and not seeing it is worse
|
||||
// than the anti-yank guarantee.
|
||||
const lastSeenUserMessageIdRef = useRef<string | null>(null);
|
||||
const isFullPage = useVariant() === 'page';
|
||||
|
||||
const handleRegenerate = useCallback(
|
||||
(messageId: string): void => {
|
||||
@@ -155,37 +160,13 @@ export default function VirtualizedMessages({
|
||||
const showStreamingSlot =
|
||||
isStreaming || Boolean(pendingApproval) || Boolean(pendingClarification);
|
||||
const isEmptyState = messages.length === 0 && !showStreamingSlot;
|
||||
const { chips: emptyStateChips } = useEmptyStateChips(isEmptyState);
|
||||
|
||||
if (isEmptyState) {
|
||||
return (
|
||||
<div className={styles.empty}>
|
||||
<div className={`${styles.emptyIcon} noz-wave`}>
|
||||
<Noz size={48} />
|
||||
</div>
|
||||
<h3 className={styles.emptyTitle}>Noz</h3>
|
||||
<p className={styles.emptySubtitle}>
|
||||
Ask questions about your traces, logs, metrics, and infrastructure.
|
||||
</p>
|
||||
<div className={styles.suggestions}>
|
||||
{emptyStateChips.map((chip) => (
|
||||
<div
|
||||
key={chip.id}
|
||||
className={styles.suggestion}
|
||||
onClick={(): void => {
|
||||
void logEvent(AIAssistantEvents.SuggestedPromptClicked, {
|
||||
promptId: chip.id,
|
||||
category: SuggestedPromptCategory.EmptyState,
|
||||
});
|
||||
onSendSuggestedPrompt(chip.text);
|
||||
}}
|
||||
data-testid={`empty-state-chip-${chip.id}`}
|
||||
>
|
||||
{chip.text}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<EmptyState
|
||||
onSendSuggestedPrompt={onSendSuggestedPrompt}
|
||||
onSnakeGameChange={onSnakeGameChange}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -204,36 +185,41 @@ export default function VirtualizedMessages({
|
||||
atBottomThreshold={64}
|
||||
initialTopMostItemIndex={Math.max(0, totalCount - 1)}
|
||||
itemContent={(index): JSX.Element => {
|
||||
const rowClass = cx(styles.row, { [styles.fullPage]: isFullPage });
|
||||
if (index < messages.length) {
|
||||
const msg = messages[index];
|
||||
const isLastAssistant =
|
||||
msg.role === 'assistant' &&
|
||||
messages.slice(index + 1).every((m) => m.role !== 'assistant');
|
||||
return (
|
||||
<MessageBubble
|
||||
message={msg}
|
||||
onRegenerate={
|
||||
isLastAssistant && !showStreamingSlot
|
||||
? (): void => handleRegenerate(msg.id)
|
||||
: undefined
|
||||
}
|
||||
onRetry={
|
||||
msg.isError && isLastAssistant && !showStreamingSlot
|
||||
? handleRetry
|
||||
: undefined
|
||||
}
|
||||
isLastAssistant={isLastAssistant}
|
||||
/>
|
||||
<div className={rowClass}>
|
||||
<MessageBubble
|
||||
message={msg}
|
||||
onRegenerate={
|
||||
isLastAssistant && !showStreamingSlot
|
||||
? (): void => handleRegenerate(msg.id)
|
||||
: undefined
|
||||
}
|
||||
onRetry={
|
||||
msg.isError && isLastAssistant && !showStreamingSlot
|
||||
? handleRetry
|
||||
: undefined
|
||||
}
|
||||
isLastAssistant={isLastAssistant}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<StreamingMessage
|
||||
conversationId={conversationId}
|
||||
events={streamingEvents}
|
||||
status={streamingStatus}
|
||||
pendingApproval={pendingApproval}
|
||||
pendingClarification={pendingClarification}
|
||||
/>
|
||||
<div className={rowClass}>
|
||||
<StreamingMessage
|
||||
conversationId={conversationId}
|
||||
events={streamingEvents}
|
||||
status={streamingStatus}
|
||||
pendingApproval={pendingApproval}
|
||||
pendingClarification={pendingClarification}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
|
||||
@@ -11,12 +11,13 @@ import { EMPTY_STATE_CHIPS_FALLBACK } from './emptyStateChipsFallback';
|
||||
|
||||
interface UseEmptyStateChipsResult {
|
||||
chips: ChipDTO[];
|
||||
isLoading: boolean;
|
||||
}
|
||||
|
||||
export function useEmptyStateChips(enabled: boolean): UseEmptyStateChipsResult {
|
||||
const pageType = useResolvePageType();
|
||||
|
||||
const { data, isError } = useQuery(
|
||||
const { data, isError, isLoading } = useQuery(
|
||||
[REACT_QUERY_KEY.AI_ASSISTANT_EMPTY_STATE_CHIPS, pageType],
|
||||
({ signal }) => getEmptyStateChips(pageType, signal),
|
||||
{ enabled },
|
||||
@@ -29,5 +30,5 @@ export function useEmptyStateChips(enabled: boolean): UseEmptyStateChipsResult {
|
||||
return data ?? [];
|
||||
}, [data, isError]);
|
||||
|
||||
return { chips };
|
||||
return { chips, isLoading };
|
||||
}
|
||||
|
||||
@@ -4,58 +4,6 @@
|
||||
* requested, Limit hit) are not declared here — they fire from the AI service.
|
||||
*/
|
||||
|
||||
export interface BrowserInfo {
|
||||
browserName: string;
|
||||
browserVersion: string;
|
||||
}
|
||||
|
||||
type NavigatorWithBrandHints = Navigator & {
|
||||
userAgentData?: { brands: { brand: string; version: string }[] };
|
||||
brave?: { isBrave: () => Promise<boolean> };
|
||||
};
|
||||
|
||||
/**
|
||||
* We mainly need to distinguish Chrome / Edge (Speech API works) from Chromium
|
||||
* derivatives (no Google API key → voice fails with `network`). UA sniffing is
|
||||
* the source of truth for derivative identification; `userAgentData` is used
|
||||
* only as a fast happy path for Chrome / Edge. Brave needs its own probe — it
|
||||
* advertises Chrome in both UA and brand hints.
|
||||
*/
|
||||
export function getBrowserInfo(): BrowserInfo {
|
||||
if (typeof navigator === 'undefined') {
|
||||
return { browserName: 'unknown', browserVersion: 'unknown' };
|
||||
}
|
||||
const nav = navigator as NavigatorWithBrandHints;
|
||||
const ua = nav.userAgent;
|
||||
|
||||
// Order matters: derivatives put "Chrome" in their UA; Chrome puts "Safari".
|
||||
const matchers: { name: string; re: RegExp }[] = [
|
||||
{ name: 'Edge', re: /Edg(?:e|A|iOS)?\/([\d.]+)/ },
|
||||
{ name: 'Opera', re: /OPR\/([\d.]+)/ },
|
||||
{ name: 'Vivaldi', re: /Vivaldi\/([\d.]+)/ },
|
||||
{ name: 'Chrome', re: /Chrome\/([\d.]+)/ },
|
||||
{ name: 'Firefox', re: /Firefox\/([\d.]+)/ },
|
||||
{ name: 'Safari', re: /Version\/([\d.]+).*Safari/ },
|
||||
];
|
||||
let browserName = 'unknown';
|
||||
let browserVersion = 'unknown';
|
||||
for (const { name, re } of matchers) {
|
||||
const m = ua.match(re);
|
||||
if (m) {
|
||||
browserName = name;
|
||||
browserVersion = m[1];
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Brave hides as Chrome in UA + brand hints; its probe is the only tell.
|
||||
if (nav.brave?.isBrave) {
|
||||
browserName = 'Brave';
|
||||
}
|
||||
|
||||
return { browserName, browserVersion };
|
||||
}
|
||||
|
||||
export const SuggestedPromptCategory = {
|
||||
FollowUp: 'follow_up',
|
||||
EmptyState: 'empty_state',
|
||||
@@ -76,15 +24,6 @@ export const AIAssistantOpenSource = {
|
||||
export type AIAssistantOpenSource =
|
||||
(typeof AIAssistantOpenSource)[keyof typeof AIAssistantOpenSource];
|
||||
|
||||
// `source` attribute on the `VoiceInputUsed` event — which surface initiated
|
||||
// the recording.
|
||||
export const VoiceInputSource = {
|
||||
Button: 'button',
|
||||
Shortcut: 'shortcut',
|
||||
} as const;
|
||||
export type VoiceInputSource =
|
||||
(typeof VoiceInputSource)[keyof typeof VoiceInputSource];
|
||||
|
||||
export enum AIAssistantEvents {
|
||||
Opened = 'AI Assistant: Opened',
|
||||
MessageSent = 'AI Assistant: Message sent',
|
||||
@@ -98,7 +37,5 @@ export enum AIAssistantEvents {
|
||||
DocOpened = 'AI Assistant: Doc opened',
|
||||
ApplyFilterClicked = 'AI Assistant: Apply filter clicked',
|
||||
ThreadOpenedFromHistory = 'AI Assistant: Thread opened from history',
|
||||
VoiceInputUsed = 'AI Assistant: Voice input used',
|
||||
VoiceInputFailed = 'AI Assistant: Voice input failed',
|
||||
NewChatClicked = 'AI Assistant: New chat clicked',
|
||||
}
|
||||
|
||||
@@ -1,268 +0,0 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
|
||||
// ── Web Speech API types (not yet in lib.dom.d.ts) ────────────────────────────
|
||||
|
||||
interface SpeechRecognitionResult {
|
||||
readonly length: number;
|
||||
readonly isFinal: boolean;
|
||||
[index: number]: { transcript: string; confidence: number };
|
||||
}
|
||||
|
||||
interface SpeechRecognitionResultList {
|
||||
readonly length: number;
|
||||
[index: number]: SpeechRecognitionResult;
|
||||
}
|
||||
|
||||
interface SpeechRecognitionEvent extends Event {
|
||||
readonly resultIndex: number;
|
||||
readonly results: SpeechRecognitionResultList;
|
||||
}
|
||||
|
||||
interface SpeechRecognitionErrorEvent extends Event {
|
||||
readonly error: string;
|
||||
readonly message: string;
|
||||
}
|
||||
|
||||
interface ISpeechRecognition extends EventTarget {
|
||||
lang: string;
|
||||
continuous: boolean;
|
||||
interimResults: boolean;
|
||||
onstart: (() => void) | null;
|
||||
onend: (() => void) | null;
|
||||
onresult: ((event: SpeechRecognitionEvent) => void) | null;
|
||||
onerror: ((event: SpeechRecognitionErrorEvent) => void) | null;
|
||||
start(): void;
|
||||
stop(): void;
|
||||
abort(): void;
|
||||
}
|
||||
|
||||
type SpeechRecognitionConstructor = new () => ISpeechRecognition;
|
||||
|
||||
// ── Vendor-prefix shim for Safari / older browsers ────────────────────────────
|
||||
|
||||
// Some hardened/enterprise browsers install a getter
|
||||
// on window.SpeechRecognition that THROWS on access ("Web Speech API is disabled
|
||||
// due to your security policy") instead of leaving the property undefined.
|
||||
// Because this resolves at module-evaluation time, an uncaught throw here aborts
|
||||
// the entire bundle and the app renders a blank page. Read defensively so a
|
||||
// throwing getter degrades to "unsupported" rather than crashing the app.
|
||||
function resolveSpeechRecognitionAPI(): SpeechRecognitionConstructor | null {
|
||||
if (typeof window === 'undefined') {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return (
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(window as any).SpeechRecognition ??
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(window as any).webkitSpeechRecognition ??
|
||||
null
|
||||
);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const SpeechRecognitionAPI: SpeechRecognitionConstructor | null =
|
||||
resolveSpeechRecognitionAPI();
|
||||
|
||||
export type SpeechRecognitionError =
|
||||
| 'not-supported'
|
||||
| 'not-allowed'
|
||||
| 'no-speech'
|
||||
| 'network'
|
||||
| 'unknown';
|
||||
|
||||
export type MicrophonePermission = 'prompt' | 'granted' | 'denied';
|
||||
|
||||
interface UseSpeechRecognitionOptions {
|
||||
onError?: (error: SpeechRecognitionError) => void;
|
||||
/**
|
||||
* Called directly from browser recognition events — no React state intermediary.
|
||||
* `isFinal=false` → interim (live preview), `isFinal=true` → committed text.
|
||||
*/
|
||||
onTranscript?: (text: string, isFinal: boolean) => void;
|
||||
lang?: string;
|
||||
}
|
||||
|
||||
interface UseSpeechRecognitionReturn {
|
||||
isListening: boolean;
|
||||
isSupported: boolean;
|
||||
/**
|
||||
* Browser microphone permission. Starts as `'prompt'` (or whatever the
|
||||
* Permissions API reports on mount), flips to `'granted'` once a session
|
||||
* successfully starts, and to `'denied'` if the user blocks access.
|
||||
*/
|
||||
permission: MicrophonePermission;
|
||||
start: () => void;
|
||||
stop: () => void;
|
||||
/** Stop recognition and discard any pending interim text (no onTranscript call). */
|
||||
discard: () => void;
|
||||
}
|
||||
|
||||
export function useSpeechRecognition({
|
||||
onError,
|
||||
onTranscript,
|
||||
lang = 'en-US',
|
||||
}: UseSpeechRecognitionOptions = {}): UseSpeechRecognitionReturn {
|
||||
const [isListening, setIsListening] = useState(false);
|
||||
const [permission, setPermission] = useState<MicrophonePermission>('prompt');
|
||||
const recognitionRef = useRef<ISpeechRecognition | null>(null);
|
||||
const isDiscardingRef = useRef(false);
|
||||
const isSupported = SpeechRecognitionAPI !== null;
|
||||
|
||||
// Seed `permission` from the Permissions API and keep it in sync with
|
||||
// external changes (e.g. user resets the site permission in browser
|
||||
// settings). Falls back silently if the API is unavailable (Safari) —
|
||||
// the recognition lifecycle below will still flip the state on grant
|
||||
// or deny.
|
||||
useEffect(() => {
|
||||
if (typeof navigator === 'undefined' || !navigator.permissions?.query) {
|
||||
return undefined;
|
||||
}
|
||||
let status: PermissionStatus | null = null;
|
||||
let cancelled = false;
|
||||
const handleChange = (): void => {
|
||||
if (status) {
|
||||
setPermission(status.state as MicrophonePermission);
|
||||
}
|
||||
};
|
||||
navigator.permissions
|
||||
.query({ name: 'microphone' as PermissionName })
|
||||
.then((permStatus) => {
|
||||
if (cancelled) {
|
||||
return;
|
||||
}
|
||||
status = permStatus;
|
||||
setPermission(permStatus.state as MicrophonePermission);
|
||||
permStatus.addEventListener('change', handleChange);
|
||||
})
|
||||
.catch(() => {
|
||||
// Permissions API rejected (some browsers don't recognise the
|
||||
// 'microphone' descriptor) — leave permission as 'prompt'.
|
||||
});
|
||||
return (): void => {
|
||||
cancelled = true;
|
||||
status?.removeEventListener('change', handleChange);
|
||||
};
|
||||
}, []);
|
||||
|
||||
// Always-current refs — updated synchronously on every render so closures
|
||||
// inside recognition event handlers always call the latest version.
|
||||
const onErrorRef = useRef(onError);
|
||||
onErrorRef.current = onError;
|
||||
|
||||
const onTranscriptRef = useRef(onTranscript);
|
||||
onTranscriptRef.current = onTranscript;
|
||||
|
||||
const stop = useCallback(() => {
|
||||
recognitionRef.current?.stop();
|
||||
}, []);
|
||||
|
||||
const discard = useCallback(() => {
|
||||
isDiscardingRef.current = true;
|
||||
recognitionRef.current?.stop();
|
||||
}, []);
|
||||
|
||||
// eslint-disable-next-line sonarjs/cognitive-complexity
|
||||
const start = useCallback(() => {
|
||||
if (!isSupported) {
|
||||
onErrorRef.current?.('not-supported');
|
||||
return;
|
||||
}
|
||||
|
||||
// If already listening, stop
|
||||
if (recognitionRef.current) {
|
||||
recognitionRef.current.stop();
|
||||
return;
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
const recognition = new SpeechRecognitionAPI!();
|
||||
recognition.lang = lang;
|
||||
recognition.continuous = true; // keep listening until user clicks stop
|
||||
recognition.interimResults = true; // live updates while speaking
|
||||
|
||||
// Track the last interim text so we can commit it as final in onend —
|
||||
// Chrome often skips the isFinal result when stop() is called manually.
|
||||
let pendingInterim = '';
|
||||
|
||||
recognition.onstart = (): void => {
|
||||
setIsListening(true);
|
||||
setPermission('granted');
|
||||
};
|
||||
|
||||
recognition.onresult = (event): void => {
|
||||
// Browser fires a final `onresult` after `recognition.stop()` —
|
||||
// when the caller invoked `discard()` (e.g. stop-and-send) the
|
||||
// React state has already been cleared / the message has
|
||||
// already been dispatched, so a late transcript would
|
||||
// repopulate the textarea. Drop these events while discarding.
|
||||
if (isDiscardingRef.current) {
|
||||
pendingInterim = '';
|
||||
return;
|
||||
}
|
||||
|
||||
let interim = '';
|
||||
let finalText = '';
|
||||
|
||||
for (let i = event.resultIndex; i < event.results.length; i++) {
|
||||
const text = event.results[i][0].transcript;
|
||||
if (event.results[i].isFinal) {
|
||||
finalText += text;
|
||||
} else {
|
||||
interim += text;
|
||||
}
|
||||
}
|
||||
|
||||
if (finalText) {
|
||||
pendingInterim = '';
|
||||
onTranscriptRef.current?.(finalText, true);
|
||||
} else if (interim) {
|
||||
pendingInterim = interim;
|
||||
onTranscriptRef.current?.(interim, false);
|
||||
}
|
||||
};
|
||||
|
||||
recognition.onerror = (event): void => {
|
||||
pendingInterim = '';
|
||||
let mapped: SpeechRecognitionError = 'unknown';
|
||||
if (event.error === 'not-allowed' || event.error === 'service-not-allowed') {
|
||||
mapped = 'not-allowed';
|
||||
setPermission('denied');
|
||||
} else if (event.error === 'no-speech') {
|
||||
mapped = 'no-speech';
|
||||
} else if (event.error === 'network') {
|
||||
mapped = 'network';
|
||||
}
|
||||
onErrorRef.current?.(mapped);
|
||||
};
|
||||
|
||||
recognition.onend = (): void => {
|
||||
// Commit any interim text that never received a final result,
|
||||
// unless the session was explicitly discarded.
|
||||
if (!isDiscardingRef.current && pendingInterim) {
|
||||
const committed = pendingInterim;
|
||||
pendingInterim = '';
|
||||
onTranscriptRef.current?.(committed, true);
|
||||
}
|
||||
isDiscardingRef.current = false;
|
||||
pendingInterim = '';
|
||||
setIsListening(false);
|
||||
recognitionRef.current = null;
|
||||
};
|
||||
|
||||
recognitionRef.current = recognition;
|
||||
recognition.start();
|
||||
}, [isSupported, lang]);
|
||||
|
||||
// Clean up on unmount
|
||||
useEffect(
|
||||
() => (): void => {
|
||||
recognitionRef.current?.abort();
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
return { isListening, isSupported, permission, start, stop, discard };
|
||||
}
|
||||
@@ -261,3 +261,53 @@ describe('useAIAssistantStore — streaming error handling', () => {
|
||||
expect(chat.sendMessage).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('useAIAssistantStore — resumed replies', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
useAIAssistantStore.setState((s) => {
|
||||
s.conversations = {};
|
||||
s.streams = {};
|
||||
s.activeConversationId = null;
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
'approveAction',
|
||||
(id: string): Promise<void> =>
|
||||
useAIAssistantStore.getState().approveAction(id, 'approval-1'),
|
||||
],
|
||||
[
|
||||
'submitClarification',
|
||||
(id: string): Promise<void> =>
|
||||
useAIAssistantStore.getState().submitClarification(id, 'clar-1', {}),
|
||||
],
|
||||
])('%s stamps startedAt on a stream loaded without one', (_, resume) => {
|
||||
chat.approveExecution.mockReturnValue(new Promise(() => {}));
|
||||
chat.clarifyExecution.mockReturnValue(new Promise(() => {}));
|
||||
useAIAssistantStore.setState((s) => {
|
||||
s.streams['conv-1'] = {
|
||||
isStreaming: false,
|
||||
streamingContent: '',
|
||||
streamingStatus: 'awaiting_approval',
|
||||
streamingEvents: [],
|
||||
streamingMessageId: null,
|
||||
streamingActions: null,
|
||||
pendingApproval: null,
|
||||
pendingClarification: null,
|
||||
startedAt: null,
|
||||
};
|
||||
});
|
||||
|
||||
jest.spyOn(Date, 'now').mockReturnValue(5000);
|
||||
|
||||
void resume('conv-1');
|
||||
|
||||
expect(useAIAssistantStore.getState().streams['conv-1'].startedAt).toBe(5000);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -203,6 +203,7 @@ function resetStreamingState(
|
||||
streamingActions: null,
|
||||
pendingApproval: null,
|
||||
pendingClarification: null,
|
||||
startedAt: Date.now(),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -973,6 +974,7 @@ export const useAIAssistantStore = create<AIAssistantStore>()(
|
||||
// compatible with the SSE event DTOs used by ConversationStreamState.
|
||||
pendingApproval: detail.pendingApproval ?? null,
|
||||
pendingClarification: detail.pendingClarification ?? null,
|
||||
startedAt: null,
|
||||
};
|
||||
}
|
||||
s.isLoadingThread = false;
|
||||
@@ -1281,6 +1283,7 @@ export const useAIAssistantStore = create<AIAssistantStore>()(
|
||||
st.pendingApproval = null;
|
||||
st.isStreaming = true;
|
||||
st.streamingStatus = 'resumed';
|
||||
st.startedAt ??= Date.now();
|
||||
} else {
|
||||
resetStreamingState(s, conversationId);
|
||||
}
|
||||
@@ -1408,6 +1411,7 @@ export const useAIAssistantStore = create<AIAssistantStore>()(
|
||||
st.pendingClarification = null;
|
||||
st.isStreaming = true;
|
||||
st.streamingStatus = 'resumed';
|
||||
st.startedAt ??= Date.now();
|
||||
} else {
|
||||
resetStreamingState(s, conversationId);
|
||||
}
|
||||
|
||||
@@ -183,4 +183,6 @@ export interface ConversationStreamState {
|
||||
streamingActions: MessageActionDTO[] | null;
|
||||
pendingApproval: ApprovalEventDTO | null;
|
||||
pendingClarification: ClarificationEventDTO | null;
|
||||
/** When the reply began; null when nothing is streaming. */
|
||||
startedAt: number | null;
|
||||
}
|
||||
|
||||
@@ -6,7 +6,9 @@ import { useQueries } from 'react-query';
|
||||
import { useSelector } from 'react-redux';
|
||||
import { AppLink } from 'lib/router/AppLink';
|
||||
import { useAppLocation } from 'lib/router/useAppLocation';
|
||||
import { Button, Card, Input, Space, TableProps, Tooltip, Flex } from 'antd';
|
||||
import { Button, Card, Input, TableProps, Tooltip } from 'antd';
|
||||
import Space from 'periscope/components/Space/Space';
|
||||
import Flex from 'periscope/components/Flex/Flex';
|
||||
import { Search } from '@signozhq/icons';
|
||||
import type { ColumnType, TablePaginationConfig } from 'antd/es/table';
|
||||
import type { FilterValue, SorterResult } from 'antd/es/table/interface';
|
||||
|
||||
@@ -15,7 +15,7 @@ import { useAppLocation } from 'lib/router/useAppLocation';
|
||||
import * as Sentry from '@sentry/react';
|
||||
import { Toaster } from '@signozhq/ui/sonner';
|
||||
import { TooltipProvider } from '@signozhq/ui/tooltip';
|
||||
import { Flex } from 'antd';
|
||||
import Flex from 'periscope/components/Flex/Flex';
|
||||
import getLocalStorageApi from 'api/browser/localstorage/get';
|
||||
import setLocalStorageApi from 'api/browser/localstorage/set';
|
||||
import getChangelogByVersion from 'api/changelog/getChangelogByVersion';
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Layout as LayoutComponent } from 'antd';
|
||||
import LayoutComponent from 'periscope/components/Layout/Layout';
|
||||
import styled from 'styled-components';
|
||||
|
||||
export const Layout = styled(LayoutComponent)`
|
||||
|
||||
@@ -5,15 +5,10 @@ import React, { useCallback, useEffect, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useMutation } from 'react-query';
|
||||
import { CircleCheck, Landmark, MonitorDown } from '@signozhq/icons';
|
||||
import {
|
||||
Card,
|
||||
Col,
|
||||
Flex,
|
||||
Row,
|
||||
Skeleton,
|
||||
Table,
|
||||
TableColumnsType as ColumnsType,
|
||||
} from 'antd';
|
||||
import { Card, Skeleton, Table, TableColumnsType as ColumnsType } from 'antd';
|
||||
import Col from 'periscope/components/Col/Col';
|
||||
import Row from 'periscope/components/Row/Row';
|
||||
import Flex from 'periscope/components/Flex/Flex';
|
||||
import { Badge } from '@signozhq/ui/badge';
|
||||
import logEvent from 'api/common/logEvent';
|
||||
import type {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useCallback, useMemo, useRef } from 'react';
|
||||
import { Card, Flex } from 'antd';
|
||||
import { Card } from 'antd';
|
||||
import Flex from 'periscope/components/Flex/Flex';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import BarChart from 'lib/visualization/charts/BarChart/BarChart';
|
||||
import { useIsDarkMode } from 'hooks/useDarkMode';
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Button, Flex, SelectProps } from 'antd';
|
||||
import { Button, SelectProps } from 'antd';
|
||||
import Flex from 'periscope/components/Flex/Flex';
|
||||
import { Switch } from '@signozhq/ui/switch';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import type { BaseOptionType, DefaultOptionType } from 'antd/es/select';
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useMemo } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Row } from 'antd';
|
||||
import Row from 'periscope/components/Row/Row';
|
||||
import { Badge } from '@signozhq/ui/badge';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import logEvent from 'api/common/logEvent';
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { useState } from 'react';
|
||||
import { CloudDownload } from '@signozhq/icons';
|
||||
import { Dropdown, type DropdownItemType } from '@signozhq/ui/dropdown';
|
||||
import { Button, Flex } from 'antd';
|
||||
import { Button } from 'antd';
|
||||
import Flex from 'periscope/components/Flex/Flex';
|
||||
import { unparse } from 'papaparse';
|
||||
|
||||
import { DownloadProps } from './Download.types';
|
||||
|
||||
@@ -2,7 +2,8 @@ import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useQuery } from 'react-query';
|
||||
import { useAppLocation } from 'lib/router/useAppLocation';
|
||||
import { Button, Space } from 'antd';
|
||||
import { Button } from 'antd';
|
||||
import Space from 'periscope/components/Space/Space';
|
||||
import { Divider } from '@signozhq/ui/divider';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import logEvent from 'api/common/logEvent';
|
||||
|
||||
@@ -8,7 +8,9 @@ import {
|
||||
useState,
|
||||
} from 'react';
|
||||
import { Input as SignozInput } from '@signozhq/ui/input';
|
||||
import { Col, Row, Select } from 'antd';
|
||||
import { Select } from 'antd';
|
||||
import Col from 'periscope/components/Col/Col';
|
||||
import Row from 'periscope/components/Row/Row';
|
||||
import { useGetTenantLicense } from 'hooks/useGetTenantLicense';
|
||||
import { find } from 'lodash-es';
|
||||
import { TTTLType } from 'types/api/settings/common';
|
||||
|
||||
@@ -2,7 +2,8 @@ import { useMemo } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { green, orange, volcano } from '@ant-design/colors';
|
||||
import { SolidInfoCircle } from '@signozhq/icons';
|
||||
import { Card, Col } from 'antd';
|
||||
import { Card } from 'antd';
|
||||
import Col from 'periscope/components/Col/Col';
|
||||
import { TStatus } from 'types/api/settings/getRetention';
|
||||
|
||||
import { convertHoursValueToRelevantUnitString } from './utils';
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Col, Input as InputComponent } from 'antd';
|
||||
import { Input as InputComponent } from 'antd';
|
||||
import Col from 'periscope/components/Col/Col';
|
||||
import { Typography as TypographyComponent } from '@signozhq/ui/typography';
|
||||
import styled from 'styled-components';
|
||||
|
||||
|
||||
@@ -60,7 +60,7 @@
|
||||
background: var(--primary);
|
||||
}
|
||||
|
||||
:global(.ant-row) {
|
||||
:global(.raw-log-row) {
|
||||
width: fit-content;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,19 +7,19 @@ import { Badge } from '@signozhq/ui/badge';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { Input } from '@signozhq/ui/input';
|
||||
import {
|
||||
Col,
|
||||
Collapse,
|
||||
DatePicker,
|
||||
Form,
|
||||
InputNumber,
|
||||
Modal,
|
||||
Row,
|
||||
Select,
|
||||
Table,
|
||||
TablePaginationConfig,
|
||||
TableProps as AntDTableProps,
|
||||
Tooltip,
|
||||
} from 'antd';
|
||||
import Col from 'periscope/components/Col/Col';
|
||||
import Row from 'periscope/components/Row/Row';
|
||||
import { Switch } from '@signozhq/ui/switch';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import type { NotificationInstance } from 'antd/es/notification/interface';
|
||||
|
||||
@@ -2,7 +2,8 @@ import { useState } from 'react';
|
||||
import { useAppParams } from 'lib/router/useAppParams';
|
||||
import { navigate } from 'lib/router/navigation';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { Flex, Skeleton } from 'antd';
|
||||
import { Skeleton } from 'antd';
|
||||
import Flex from 'periscope/components/Flex/Flex';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import ROUTES from 'constants/routes';
|
||||
import { useGetIntegration } from 'hooks/Integrations/useGetIntegration';
|
||||
|
||||
@@ -4,7 +4,7 @@ import { Button } from '@signozhq/ui/button';
|
||||
import { DialogWrapper } from '@signozhq/ui/dialog';
|
||||
import { Input } from '@signozhq/ui/input';
|
||||
import { toast } from '@signozhq/ui/sonner';
|
||||
import { Flex } from 'antd';
|
||||
import Flex from 'periscope/components/Flex/Flex';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import logEvent from 'api/common/logEvent';
|
||||
import ROUTES from 'constants/routes';
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
} from 'react';
|
||||
// eslint-disable-next-line no-restricted-imports
|
||||
import { useSelector } from 'react-redux';
|
||||
import { Space } from 'antd';
|
||||
import Space from 'periscope/components/Space/Space';
|
||||
import ErrorInPlace from 'components/ErrorInPlace/ErrorInPlace';
|
||||
import ExportMenu from 'components/ExportMenu/ExportMenu';
|
||||
import { ENTITY_VERSION_V5 } from 'constants/app';
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
background: var(--l3-background);
|
||||
}
|
||||
|
||||
.ant-row {
|
||||
.raw-log-row {
|
||||
width: fit-content;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useMemo, useState } from 'react';
|
||||
import { Empty } from 'antd';
|
||||
import Empty from 'periscope/components/Empty/Empty';
|
||||
import SignozRadioGroup from 'components/SignozRadioGroup/SignozRadioGroup';
|
||||
import { History, Table } from '@signozhq/icons';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Empty } from 'antd';
|
||||
import Empty from 'periscope/components/Empty/Empty';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
|
||||
import styles from './EmptyMeterSearch.module.scss';
|
||||
|
||||
@@ -4,13 +4,12 @@
|
||||
gap: var(--spacing-5);
|
||||
width: 100%;
|
||||
|
||||
:global(.builder-units-filter) {
|
||||
.unitsFilter {
|
||||
padding: 0 var(--spacing-4);
|
||||
margin-bottom: 0 !important;
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
:global(.builder-units-filter-label) {
|
||||
margin-bottom: 0 !important;
|
||||
.unitsFilterLabel {
|
||||
font-size: 12px;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -109,7 +109,12 @@ function TimeSeries({
|
||||
|
||||
return (
|
||||
<div className={styles.meterTimeSeriesContainer}>
|
||||
<BuilderUnitsFilter onChange={onUnitChange} yAxisUnit={yAxisUnit} />
|
||||
<BuilderUnitsFilter
|
||||
onChange={onUnitChange}
|
||||
yAxisUnit={yAxisUnit}
|
||||
className={styles.unitsFilter}
|
||||
labelClassName={styles.unitsFilterLabel}
|
||||
/>
|
||||
<div className={styles.timeSeriesContainer} ref={graphRef}>
|
||||
{!hasMetricSelected && <EmptyMeterSearch />}
|
||||
{isCancelled && hasMetricSelected && (
|
||||
|
||||
@@ -3,7 +3,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useDispatch } from 'react-redux';
|
||||
import { useAppLocation } from 'lib/router/useAppLocation';
|
||||
import { useAppParams } from 'lib/router/useAppParams';
|
||||
import { Col } from 'antd';
|
||||
import Col from 'periscope/components/Col/Col';
|
||||
import logEvent from 'api/common/logEvent';
|
||||
import { ENTITY_VERSION_V5 } from 'constants/app';
|
||||
import { QueryParams } from 'constants/query';
|
||||
|
||||
@@ -3,7 +3,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useDispatch } from 'react-redux';
|
||||
import { useAppLocation } from 'lib/router/useAppLocation';
|
||||
import { useAppParams } from 'lib/router/useAppParams';
|
||||
import { Col } from 'antd';
|
||||
import Col from 'periscope/components/Col/Col';
|
||||
import logEvent from 'api/common/logEvent';
|
||||
import { ENTITY_VERSION_V5 } from 'constants/app';
|
||||
import { QueryParams } from 'constants/query';
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { ReactNode, useMemo } from 'react';
|
||||
import { useAppParams } from 'lib/router/useAppParams';
|
||||
import { Space } from 'antd';
|
||||
import Space from 'periscope/components/Space/Space';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import TextToolTip from 'components/TextToolTip';
|
||||
import {
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
import {
|
||||
Card as CardComponent,
|
||||
Col as ColComponent,
|
||||
Row as RowComponent,
|
||||
} from 'antd';
|
||||
import { Card as CardComponent } from 'antd';
|
||||
import ColComponent from 'periscope/components/Col/Col';
|
||||
import RowComponent from 'periscope/components/Row/Row';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import styled from 'styled-components';
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Empty } from 'antd';
|
||||
import Empty from 'periscope/components/Empty/Empty';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
|
||||
interface EmptyMetricsSearchProps {
|
||||
|
||||
@@ -2,7 +2,8 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useQueryClient } from 'react-query';
|
||||
import * as Sentry from '@sentry/react';
|
||||
import { Color } from '@signozhq/design-tokens';
|
||||
import { Button, Drawer, Empty, Skeleton } from 'antd';
|
||||
import { Button, Drawer, Skeleton } from 'antd';
|
||||
import Empty from 'periscope/components/Empty/Empty';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import logEvent from 'api/common/logEvent';
|
||||
import { useGetMetricMetadata } from 'api/generated/services/metrics';
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { useCallback, useMemo } from 'react';
|
||||
import type { TableColumnsType as ColumnsType } from 'antd';
|
||||
import { Card, Flex, Table } from 'antd';
|
||||
import { Card, Table } from 'antd';
|
||||
import Flex from 'periscope/components/Flex/Flex';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
|
||||
import { InspectMetricsSeries } from './types';
|
||||
import { TableViewProps } from './types';
|
||||
import { InspectMetricsSeries, TableViewProps } from './types';
|
||||
import { formatTimestampToFullDateTime } from './utils';
|
||||
|
||||
function TableView({
|
||||
|
||||
@@ -1,14 +1,6 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import {
|
||||
Button,
|
||||
Empty,
|
||||
Input,
|
||||
InputRef,
|
||||
Menu,
|
||||
MenuRef,
|
||||
Popover,
|
||||
Spin,
|
||||
} from 'antd';
|
||||
import { Button, Input, InputRef, Menu, MenuRef, Popover, Spin } from 'antd';
|
||||
import Empty from 'periscope/components/Empty/Empty';
|
||||
import {
|
||||
getListMetricsQueryKey,
|
||||
useListMetrics,
|
||||
@@ -158,9 +150,19 @@ function MetricNameSearch({
|
||||
if (isLoadingMetricNameFilterValues) {
|
||||
items.push(<Spin />);
|
||||
} else if (isErrorMetricNameFilterValues) {
|
||||
items.push(<Empty description="Error fetching metric names" />);
|
||||
items.push(
|
||||
<Empty
|
||||
className="metric-name-search-popover__empty"
|
||||
description="Error fetching metric names"
|
||||
/>,
|
||||
);
|
||||
} else if (metricNameFilterValues?.length === 0) {
|
||||
items.push(<Empty description="No metric names found" />);
|
||||
items.push(
|
||||
<Empty
|
||||
className="metric-name-search-popover__empty"
|
||||
description="No metric names found"
|
||||
/>,
|
||||
);
|
||||
} else {
|
||||
items.push(
|
||||
...metricNameFilterValues.map((filterValue, index) => (
|
||||
|
||||
@@ -2,7 +2,8 @@ import { useCallback, useMemo } from 'react';
|
||||
import { useWindowSize } from 'react-use';
|
||||
import { Group } from '@visx/group';
|
||||
import { Treemap } from '@visx/hierarchy';
|
||||
import { Empty, Select, Skeleton, Tooltip } from 'antd';
|
||||
import { Select, Skeleton, Tooltip } from 'antd';
|
||||
import Empty from 'periscope/components/Empty/Empty';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import { MetricsexplorertypesTreemapModeDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import ErrorInPlace from 'components/ErrorInPlace/ErrorInPlace';
|
||||
|
||||
@@ -250,7 +250,7 @@
|
||||
|
||||
.ant-menu {
|
||||
.ant-spin,
|
||||
.ant-empty {
|
||||
.metric-name-search-popover__empty {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
|
||||
@@ -1,15 +1,9 @@
|
||||
import React, { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { ArrowRight, Check, Goal, Search, UserPlus, X } from '@signozhq/icons';
|
||||
import {
|
||||
Button,
|
||||
Flex,
|
||||
Input,
|
||||
Layout,
|
||||
Modal,
|
||||
Skeleton,
|
||||
Space,
|
||||
Steps,
|
||||
} from 'antd';
|
||||
import { Button, Input, Modal, Skeleton, Steps } from 'antd';
|
||||
import Layout from 'periscope/components/Layout/Layout';
|
||||
import Space from 'periscope/components/Space/Space';
|
||||
import Flex from 'periscope/components/Flex/Flex';
|
||||
import { Button as SignozButton } from '@signozhq/ui/button';
|
||||
import { toast } from '@signozhq/ui/sonner';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
backdrop-filter: blur(20px);
|
||||
padding: 12px 0px;
|
||||
|
||||
&--sticky {
|
||||
&.setup-flow__header--sticky {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding: 0px 1rem;
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user