### Using Handles in Runtime Source: https://mindbox.pages.yandexcloud.net/development/frontend/frontend-visualization/llms/deep-dive-opaque-handles.txt Examples of using handles to interact with datasets and presentations at runtime. ```tsx // Convenience: line() возвращает PresentationHandle const revenuePresentation = chart.line({ label: 'Выручка', y: (d) => d.revenue }); // Advanced: addDataset() возвращает DatasetBuilder, asLine() — PresentationHandle const ds = chart.addDataset({ label: 'Заказы', y: (d) => d.orders }); const ordersLine = ds.asLine(); const ordersBars = ds.asBars(); // Потом в runtime: api.datasets.visibility.toggle(revenuePresentation); // скрыть/показать конкретную линию api.datasets.highlight.highlight(ordersLine); // подсветить конкретную презентацию ``` -------------------------------- ### Default Skeleton Example Source: https://mindbox.pages.yandexcloud.net/development/frontend/frontend-visualization/llms/components-skeleton.txt Illustrates the default appearance and behavior of the ChartSkeleton when no specific props are provided, highlighting its animated wave effect. ```APIDOC ## POST /api/chart-skeleton/default ### Description This example demonstrates the default usage of the `ChartSkeleton` component. It displays a basic loading skeleton with an animated wave effect, generated using `requestAnimationFrame` for smooth interpolation between keyframes. The grid and wave are colored in `gray.300`. This is typically used as a placeholder for a `ChartView` while data is being fetched. ### Method POST ### Endpoint /api/chart-skeleton/default ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (uses default props) ### Request Example ```json { "message": "Displaying default chart skeleton." } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the success of the operation. - **data** (object) - Contains information about the default skeleton. - **animation** (string) - Description of the animation effect. - **color** (string) - The default color of the grid and wave. #### Response Example ```json { "status": "success", "data": { "animation": "JS path morphing via requestAnimationFrame", "color": "gray.300" } } ``` ``` -------------------------------- ### Custom Size Example Source: https://mindbox.pages.yandexcloud.net/development/frontend/frontend-visualization/llms/components-skeleton.txt Demonstrates how to explicitly set the width and height of the ChartSkeleton using the `width` and `height` props. ```APIDOC ## POST /api/chart-skeleton/custom-size ### Description This example shows how to explicitly set the dimensions of the `ChartSkeleton` component using the `width` and `height` props. The `width` and `height` props can accept either a number (in pixels) or a string (representing any CSS unit). If these props are not provided, the component will occupy the full width of its parent and a default minimum height. ### Method POST ### Endpoint /api/chart-skeleton/custom-size ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **width** (number | string) - Required - The desired width of the skeleton. Can be in pixels or any CSS unit. - **height** (number | string) - Required - The desired height of the skeleton. Can be in pixels or any CSS unit. ### Request Example ```json { "width": 400, "height": 200 } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the success of the operation. - **message** (string) - A confirmation message. #### Response Example ```json { "status": "success", "message": "Skeleton dimensions updated successfully." } ``` ``` -------------------------------- ### ChartTooltip - Quick Start (Function-as-Children) Source: https://mindbox.pages.yandexcloud.net/development/frontend/frontend-visualization/llms/guides-tooltip.txt The simplest way to use ChartTooltip is via the function-as-children pattern. This automatically renders a default container with background, padding, and shadow. Positioning is handled automatically. ```APIDOC ## Quick Start The simplest option is function-as-children. The container with background, padding, and shadow is rendered automatically. Positioning is managed by `ChartTooltip` automatically – you don't need to worry about `ref`, `style`, or wrapper `div`s. ``` -------------------------------- ### Configure ChartLegend with Mute Mode Source: https://mindbox.pages.yandexcloud.net/development/frontend/frontend-visualization/llms/components-legend.txt Example demonstrating the setup of a Cartesian chart with a legend in 'mute' mode using the @mindbox-cloud/frontend-visualization library. ```tsx meta.story({ name: 'Default (Mute Mode)', args: { columnGap: 'L', rowGap: 'XS', justify: 'flex-end', marginTop: 'L', itemMaxWidth: 200 }, parameters: { docs: { source: storySource` import { Chart } from '@mindbox-cloud/frontend-visualization/cartesian'; import { ChartView, ChartTooltip, ChartLegend } from '@mindbox-cloud/frontend-visualization/react'; const data = [ { month: 'Jan', revenue: 1_200_000, costs: 750_000, profit: 450_000 }, { month: 'Feb', revenue: 1_450_000, costs: 920_000, profit: 530_000 }, { month: 'Mar', revenue: 980_000, costs: 680_000, profit: 300_000 }, { month: 'Apr', revenue: 1_650_000, costs: 1_050_000, profit: 600_000 }, { month: 'May', revenue: 2_100_000, costs: 1_280_000, profit: 820_000 }, ]; const chart = new Chart({ data, x: (d) => d.month }) .withBottomAxis() .withLeftAxis() .withTooltip() .withLegend({ mode: 'mute' }); chart.line({ label: 'Revenue', y: (d) => d.revenue }); chart.line({ label: 'Costs', y: (d) => d.costs }); chart.line({ label: 'Profit', y: (d) => d.profit }); function ChartWithLegend() { return ( { const datum = items[0]?.datum; if (!datum) return null; return (
{datum.month}
Revenue: {datum.revenue.toLocaleString()}
Costs: {datum.costs.toLocaleString()}
Profit: {datum.profit.toLocaleString()}
); }} />
); } ` } }, render: args => { const chart = useMemo(() => { const c = new Chart({ data: kpiData, x: d => d.month }).withBottomAxis().withLeftAxis().withTooltip().withLegend({ mode: 'mute' }); c.line({ label: 'Revenue', y: d => d.revenue }); c.line({ label: 'Costs', y: d => d.costs }); c.line({ label: 'Profit', y: d => d.profit }); return c; }, []); return > > {({ items }) => { const datum = items[0].datum; if (!datum) return null; return
{datum.month}
Revenue: {datum.revenue.toLocaleString()}
Costs: {datum.costs.toLocaleString()}
Profit: {datum.profit.toLocaleString()}
; }}
; }, play: async ({ canvas, userEvent, step }) => { await step('All legend items are visible initially', async () => { const items = canvas.getAllByTestId('legend-item'); for (const item of items) { expect(item).not.toHaveAttribute('data-hidden'); } }); await step('Click Revenue to mute it', async () => { const revenue = canvas.getAllByTestId('legend-item').find(el => el.dataset.label === 'Revenue')!; await userEvent.click(revenue); expect(revenue).toHaveAttribute('data-hidden'); }); await step('Click Revenue again to restore it', async () => { const revenue = canvas.getAllByTestId('legend-item').find(el => el.dataset.label === 'Revenue')!; await userEvent.click(revenue); expect(revenue).not.toHaveAttribute('data-hidden'); }); } }) ``` -------------------------------- ### Default Example Source: https://mindbox.pages.yandexcloud.net/development/frontend/frontend-visualization/llms/components-placeholder.txt Illustrates the default appearance of the ChartPlaceholder when no specific props are provided, showing a static green wave over a gray grid. ```APIDOC ## POST /api/placeholder/default ### Description This example demonstrates the default state of the `ChartPlaceholder` component. It displays a static green wave (`green.300`) over a gray grid (`gray.300`). This serves as a visual placeholder when data is missing or insufficient for a chart. The `width`, `height`, and `bgColor` props can be controlled via UI controls. ### Method POST ### Endpoint /api/placeholder/default ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) This endpoint does not return a specific response body, but the UI will render the default placeholder. #### Response Example None ``` -------------------------------- ### With Children Example Source: https://mindbox.pages.yandexcloud.net/development/frontend/frontend-visualization/llms/components-placeholder.txt Demonstrates how to include custom content within the ChartPlaceholder, which will be centered over the placeholder's background. ```APIDOC ## POST /api/placeholder/with-children ### Description This example shows how to place custom content inside the `ChartPlaceholder`. The `children` are absolutely centered within the placeholder using flexbox. This is useful for displaying messages like "No data available" or user guidance directly on top of the placeholder wave. ### Method POST ### Endpoint /api/placeholder/with-children ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body ```json { "width": "string | number | undefined", "height": "string | number | undefined", "children": "ReactNode" } ``` ### Request Example ```json { "width": 600, "height": 300, "children": "Нет данных для отображения" } ``` ### Response #### Success Response (200) This endpoint does not return a specific response body, but the UI will render the placeholder with the provided child content. #### Response Example None ``` -------------------------------- ### Skeleton With Children Example Source: https://mindbox.pages.yandexcloud.net/development/frontend/frontend-visualization/llms/components-skeleton.txt Demonstrates how to place custom content, such as loading messages or spinners, directly on top of the ChartSkeleton's animated wave. ```APIDOC ## POST /api/chart-skeleton/with-children ### Description This example shows how to include child elements within the `ChartSkeleton`. These children are absolutely centered within the skeleton's container using flexbox, allowing you to overlay messages like "Loading data..." or spinners directly onto the skeleton's animation. This is useful for providing more specific loading feedback. ### Method POST ### Endpoint /api/chart-skeleton/with-children ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **children** (ReactNode) - Optional - Content to be displayed on top of the skeleton. This content will be centered. ### Request Example ```json { "children": "Загрузка данных..." } ``` ### Response #### Success Response (200) - **status** (string) - Indicates successful rendering with children. - **message** (string) - Confirmation that children were overlaid. #### Response Example ```json { "status": "success", "message": "Chart skeleton rendered with overlaid content." } ``` ``` -------------------------------- ### No Data State Example Source: https://mindbox.pages.yandexcloud.net/development/frontend/frontend-visualization/llms/components-emptystate-no-data.txt Demonstrates the 'no-data' preset for ChartEmptyState. This state is active when data series exist but have no points, and loading is false. The button simulates a loading state to show that 'no-data' is hidden during loading. ```tsx meta.story({ name: 'No Data (пустые данные)', parameters: { docs: { source: storySource` import { useMemo } from 'react'; import { Chart } from '@mindbox-cloud/frontend-visualization/cartesian'; import { ChartView, ChartLegend, ChartEmptyState } from '@mindbox-cloud/frontend-visualization/react'; type Datum = { month: string; revenue: number }; const data: Datum[] = []; const chart = new Chart({ data, x: (d) => d.month }) .withBottomAxis() .withLeftAxis() .withLegend(); chart.line({ label: 'Revenue', y: (d) => d.revenue }); function MyChart() { return (
Нет данных
Попробуйте изменить фильтры
); } ` } }, render: () => { const [loading, setLoading] = useState(false); const chart = useMemo(() => { const c = new Chart({ data: emptyData, x: (d: Datum) => d.month }).withBottomAxis().withLeftAxis().withLegend(); c.line({ label: 'Revenue', y: (d: Datum) => d.revenue }); return c; }, []); return
Нет данных
Попробуйте изменить фильтры
; }, play: async ({ canvas, step }) => { await step('Overlay is visible for empty data when loading=false', async () => { expect(canvas.getByText('Нет данных')).toBeTruthy(); }); } }) ``` -------------------------------- ### Configure Flip at Right Edge for Cartesian Chart Source: https://mindbox.pages.yandexcloud.net/development/frontend/frontend-visualization/llms/components-tooltip-flip.txt Example showing the initialization of a chart with a tooltip configured to flip horizontally when space is constrained. ```tsx meta.story({ name: 'Flip at Right Edge', args: testArgs, parameters: { docs: { source: storySource` import { Chart } from '@mindbox-cloud/frontend-visualization/cartesian'; import { ChartView, ChartTooltip } from '@mindbox-cloud/frontend-visualization/react'; // Тултип автоматически переворачивается влево, когда справа // от якорной точки недостаточно места. const chart = new Chart({ data, x: (d) => d.month }) .withBottomAxis() .withLeftAxis() .withTooltip({ placementX: 'right', placementY: 'bottom', anchorOffsetPx: 8, paddingPx: 8, crosshair: { vertical: true, horizontal: true }, }); chart.line({ label: 'Revenue', y: (d) => d.revenue }); ` } }, render: renderTestGrouped({ placementX: 'right', placementY: 'bottom', anchorOffsetPx: 8, paddingPx: 8, crosshair: { vertical: true, horizontal: true } }), play: async ({ canvas, userEvent, step }) => { const sensor = canvas.getByTestId('tooltip-sensor'); await waitFor(() => expect(sensor.getBoundingClientRect().width).toBeGreaterThan(0)); await step('Hover at the last data point (Jun, index 5) — right edge of chart', async () => { await hoverAtDataPoint(userEvent, sensor, 5, DATA_COUNT); }); await step('Tooltip is flipped to the left of the anchor', async () => { const tooltip = await waitForTooltipMeasured(canvas, 'tooltip-content-grouped'); const tooltipPos = parseTranslate3d(tooltip); const anchor = getAnchorFromCrosshair(canvas); // Flipped left: tooltip right edge = anchor.x - offset const tooltipRightEdge = tooltipPos.x + TOOLTIP_W; expectApprox(tooltipRightEdge, anchor.x - 8); }); await step('Tooltip shows Jun (correct datum for last point)', async () => { const monthEl = canvas.getByTestId('tooltip-month'); expect(monthEl.textContent).toBe('Jun'); }); } }) ``` -------------------------------- ### Custom Size Example Source: https://mindbox.pages.yandexcloud.net/development/frontend/frontend-visualization/llms/components-placeholder.txt Demonstrates how to explicitly set the width and height of the ChartPlaceholder using the `width` and `height` props. ```APIDOC ## POST /api/placeholder/custom-size ### Description This example shows how to explicitly set the dimensions of the `ChartPlaceholder` component using the `width` and `height` props. These props accept either a number (in pixels) or a string (any CSS unit). If not provided, the component defaults to full width and a minimum height based on padding. ### Method POST ### Endpoint /api/placeholder/custom-size ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body ```json { "width": "number | string", "height": "number | string" } ``` ### Request Example ```json { "width": 400, "height": 200 } ``` ### Response #### Success Response (200) This endpoint does not return a specific response body, but the UI will render the placeholder with the specified dimensions. #### Response Example None ``` -------------------------------- ### Custom Tick Rendering Example Source: https://mindbox.pages.yandexcloud.net/development/frontend/frontend-visualization/llms/components-axis-override.txt Demonstrates custom tick rendering for the bottom axis using the `renderTick` prop. The left axis is configured declaratively for currency formatting and tick count. This example shows how to achieve full control over tick appearance with custom SVG elements. ```tsx import { Chart } from '@mindbox-cloud/frontend-visualization/cartesian'; import { ChartView, ChartAxis } from '@mindbox-cloud/frontend-visualization/react'; const data = [ { month: 'Jan', revenue: 1_200_000 }, { month: 'Feb', revenue: 1_450_000 }, { month: 'Mar', revenue: 980_000 }, { month: 'Apr', revenue: 1_650_000 }, { month: 'May', revenue: 2_100_000 }, ]; const chart = new Chart({ data, x: (d) => d.month }) .withBottomAxis() .withLeftAxis({ format: (v) => `${(Number(v) / 1_000_000).toFixed(1)} млн ₲`, ticks: 4, }); chart.line({ label: 'Revenue', y: (d) => d.revenue }); function ChartWithCustomAxis() { return ( ( {String(tick.value).toUpperCase()} )} /> ); } ``` -------------------------------- ### Tooltip Measurement Lifecycle Example Source: https://mindbox.pages.yandexcloud.net/development/frontend/frontend-visualization/llms/components-tooltip-lifecycle.txt Demonstrates the two-phase lifecycle of the tooltip. Initially rendered with opacity 0 for measurement via ResizeObserver, it is then positioned and becomes visible (opacity 1). This prevents visual jumps on initial render. Requires Chart and ChartView/ChartTooltip imports. ```tsx meta.story({ name: 'Measurement Lifecycle', args: testArgs, parameters: { docs: { source: storySource` import { Chart } from '@mindbox-cloud/frontend-visualization/cartesian'; import { ChartView, ChartTooltip } from '@mindbox-cloud/frontend-visualization/react'; // Двухфазный жизненный цикл: сначала тултип рендерится невидимым (opacity: 0) // для измерения размеров через ResizeObserver, затем позиционируется и появляется. const chart = new Chart({ data, x: (d) => d.month }) .withBottomAxis() .withLeftAxis() .withTooltip({ placementX: 'right', placementY: 'bottom', crosshair: { vertical: true }, }); chart.line({ label: 'Revenue', y: (d) => d.revenue }); ` } }, render: renderTestGrouped({ placementX: 'right', placementY: 'bottom', crosshair: { vertical: true } }), play: async ({ canvas, userEvent, step }) => { const sensor = canvas.getByTestId('tooltip-sensor'); await waitFor(() => expect(sensor.getBoundingClientRect().width).toBeGreaterThan(0)); await step('Hover at data point', async () => { await hoverAtDataPoint(userEvent, sensor, 2, DATA_COUNT); }); await step('Tooltip eventually becomes visible (opacity: 1) with non-zero position', async () => { const tooltip = await waitForTooltipMeasured(canvas, 'tooltip-content-grouped'); const pos = parseTranslate3d(tooltip); // After measurement, position should be non-trivial (not at 0,0) expect(pos.x > 0 || pos.y > 0).toBe(true); }); } }) ``` -------------------------------- ### Render Linear Scale Chart Source: https://mindbox.pages.yandexcloud.net/development/frontend/frontend-visualization/llms/components-axis-scale-types.txt Demonstrates how to create and render a chart with a linear scale for numerical data. It includes setup for axes and line series. Use for metrics where proportional representation is important. ```tsx import { Chart } from '@mindbox-cloud/frontend-visualization/cartesian'; import { ChartView } from '@mindbox-cloud/frontend-visualization/react'; const data = [ { month: 'Jan', revenue: 420_000 }, { month: 'Feb', revenue: 610_000 }, { month: 'Mar', revenue: 530_000 }, { month: 'Apr', revenue: 780_000 }, { month: 'May', revenue: 720_000 }, { month: 'Jun', revenue: 890_000 }, ]; const chart = new Chart({ data, x: (d) => d.month }) .withBottomAxis() .withLeftAxis({ title: 'Revenue, ₽', format: (v) => `${(Number(v) / 1_000).toFixed(0)}K`, }); chart.line({ label: 'Revenue', y: (d) => d.revenue }); function Chart() { return ; } ``` -------------------------------- ### Initial Visibility Setting Source: https://mindbox.pages.yandexcloud.net/development/frontend/frontend-visualization/llms/guides-legend.txt Set the initial visibility state for a dataset upon registration using `'visible'`, `'muted'`, or `'excluded'`. The legend will render the item with the correct state from the start. ```javascript api.datasets.create({ // ... initialVisibility: 'muted' }); ``` -------------------------------- ### Customize Tooltip Container with Style Props (Isolated) Source: https://mindbox.pages.yandexcloud.net/development/frontend/frontend-visualization/llms/guides-tooltip.txt Customize the appearance of the 'Isolated' tooltip container with compact padding. This example demonstrates minimal styling for a compact isolated tooltip. ```javascript ChartTooltip.Isolated({ padding: 'xs' }) ``` -------------------------------- ### Inside ChartEmptyState (auto height) Example Source: https://mindbox.pages.yandexcloud.net/development/frontend/frontend-visualization/llms/components-placeholder.txt Shows how ChartPlaceholder behaves when nested within ChartEmptyState, automatically adjusting its height to fill the available space. ```APIDOC ## POST /api/placeholder/inside-empty-state ### Description This example illustrates the `ChartPlaceholder` component used within a `ChartEmptyState` overlay. When nested this way, `ChartPlaceholder` automatically sets its height to `100%`, adapting to the chart's height. The `covers="full"` prop ensures the overlay covers the entire widget, including legends and axes. The `children` prop, as a function receiving `ChartAPI`, allows rendering dynamic content like series lists directly within the placeholder. ### Method POST ### Endpoint /api/placeholder/inside-empty-state ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body ```json { "isEmpty": "boolean", "covers": "'full' | undefined", "children": "(api) => ReactNode" } ``` ### Request Example ```json { "isEmpty": true, "covers": "full", "children": "(api) => \"Нет данных\"" } ``` ### Response #### Success Response (200) This endpoint does not return a specific response body, but the UI will render the chart with an empty state and placeholder. #### Response Example None ``` -------------------------------- ### Deterministic Tick Count Example Source: https://mindbox.pages.yandexcloud.net/development/frontend/frontend-visualization/llms/components-axis-deterministic-ticks.txt Configures three charts with different data ranges to display exactly 5 ticks on their left axes. This ensures consistent visual division regardless of the data's scale. ```tsx meta.story({ name: 'Deterministic Tick Count', parameters: { docs: { source: storySource` import { Chart } from '@mindbox-cloud/frontend-visualization/cartesian'; import { ChartView } from '@mindbox-cloud/frontend-visualization/react'; // Маленький домен: 10–60 const chart1 = new Chart({ data: smallData, x: (d) => d.month }) .withBottomAxis() .withLeftAxis({ ticks: 5 }); chart1.line({ label: 'Value', y: (d) => d.value }); // Большой домен: 0–2.5M const chart2 = new Chart({ data: largeData, x: (d) => d.month }) .withBottomAxis() .withLeftAxis({ ticks: 5 }); chart2.line({ label: 'Value', y: (d) => d.value }); // Неравномерный домен: 137–2041 const chart3 = new Chart({ data: unevenData, x: (d) => d.month }) .withBottomAxis() .withLeftAxis({ ticks: 5 }); chart3.line({ label: 'Value', y: (d) => d.value }); ` } }, render: () => { const chart1 = useMemo(() => { const c = new Chart({ data: smallDomainData, x: d => d.month }).withBottomAxis().withLeftAxis({ ticks: 5 }); c.line({ label: 'Value', y: d => d.value }); return c; }, []); const chart2 = useMemo(() => { const c = new Chart({ data: largeDomainData, x: d => d.month }).withBottomAxis().withLeftAxis({ ticks: 5 }); c.line({ label: 'Value', y: d => d.value }); return c; }, []); const chart3 = useMemo(() => { const c = new Chart({ data: unevenDomainData, x: d => d.month }).withBottomAxis().withLeftAxis({ ticks: 5 }); c.line({ label: 'Value', y: d => d.value }); return c; }, []); return

Small domain (10–60)

Large domain (0–2.5M)

Uneven domain (137–2041)

; }, play: async ({ canvas, step }) => { await step('All three charts render tick labels', async () => { const ticks = canvas.getAllByTestId('axis-left-tick'); expect(ticks.length).toBeGreaterThan(0); }); } }) ``` -------------------------------- ### Implement X-Snap Selection with Tooltip Source: https://mindbox.pages.yandexcloud.net/development/frontend/frontend-visualization/llms/components-tooltip-snap.txt Use the 'x' snap strategy for tooltips to select the nearest data point based on horizontal distance only. Configure the tooltip to be grouped and use a vertical crosshair for better visual guidance. This setup is ideal for linear and bar charts with regular x-axis intervals. ```tsx import { Chart } from '@mindbox-cloud/frontend-visualization/cartesian'; import { ChartView, ChartTooltip } from '@mindbox-cloud/frontend-visualization/react'; const chart = new Chart({ data, x: (d) => d.month }) .withBottomAxis() .withLeftAxis() .withTooltip({ snap: 'x', mode: 'grouped', crosshair: { vertical: true }, }); chart.line({ label: 'Revenue', y: (d) => d.revenue }); chart.line({ label: 'Costs', y: (d) => d.costs }); function ChartWithXSnap() { return ( ); } ``` -------------------------------- ### Apply Custom Global Grid Styles Source: https://mindbox.pages.yandexcloud.net/development/frontend/frontend-visualization/llms/components-grid-styling.txt Use the `style` object within the `withGrid` configuration to apply global styles to all grid lines. Supported properties include `stroke`, `strokeWidth`, `strokeDasharray`, and `opacity`. This example demonstrates setting a custom color and dash pattern for the grid. ```tsx import { Chart } from '@mindbox-cloud/frontend-visualization/cartesian'; import { ChartView } from '@mindbox-cloud/frontend-visualization/react'; const chart = new Chart({ data, x: (d) => d.month }) .withBottomAxis() .withLeftAxis() .withGrid({ y: true, style: { stroke: '#a0a0ff', strokeDasharray: [8, 4], strokeWidth: 2, }, }); chart.line({ label: 'Revenue', y: (d) => d.revenue }); ``` ```tsx const chart = useMemo(() => { const c = new Chart({ data: salesData, x: d => d.month }).withBottomAxis().withLeftAxis().withGrid({ y: true, style: { stroke: '#a0a0ff', strokeDasharray: [8, 4], strokeWidth: 2 } }); c.line({ label: 'Revenue', y: d => d.revenue }); return c; }, []); return ; ``` -------------------------------- ### Basic Chart Configuration and Rendering Source: https://mindbox.pages.yandexcloud.net/development/frontend/frontend-visualization/llms/getting-started.txt This snippet demonstrates the fundamental steps for creating a chart. It involves initializing the chart with data, adding axes, defining a line dataset, and rendering it with the ChartView component. Ensure you have the necessary data and accessor functions defined. ```javascript new Chart({ data, x }) .withLeftAxis() .withBottomAxis() .line({ label: "", y }) ``` -------------------------------- ### All Hidden Chart Empty State Example Source: https://mindbox.pages.yandexcloud.net/development/frontend/frontend-visualization/llms/components-emptystate-all-hidden.txt Use ChartEmptyState with when="all-hidden" to show a message when no segments are selected. The covers="container" attribute ensures the overlay does not obscure the legend, allowing users to re-enable series. This example is for React. ```tsx import { Chart } from '@mindbox-cloud/frontend-visualization/cartesian'; import { ChartView, ChartLegend, ChartEmptyState } from '@mindbox-cloud/frontend-visualization/react'; const chart = new Chart({ data, x: (d) => d.month }) .withBottomAxis() .withLeftAxis() .withLegend({ mode: 'mute' }); chart.line({ label: 'Revenue', y: (d) => d.revenue }); chart.line({ label: 'Costs', y: (d) => d.costs }); chart.line({ label: 'Profit', y: (d) => d.profit }); function Chart() { return (
Не выбран ни один сегмент
Выберите сегменты для сравнения
); } ``` -------------------------------- ### Implement Loading Initial State in React Source: https://mindbox.pages.yandexcloud.net/development/frontend/frontend-visualization/llms/components-emptystate-loading.txt Demonstrates using the 'loading-initial' preset with ChartEmptyState and ChartSkeleton to provide visual feedback during initial data fetching. ```tsx meta.story({ name: 'Loading Initial (первая загрузка)', parameters: { enableDebug: false, docs: { source: storySource` import { useMemo, useState } from 'react'; import { Chart } from '@mindbox-cloud/frontend-visualization/cartesian'; import { ChartView, ChartLegend, ChartEmptyState, ChartSkeleton, } from '@mindbox-cloud/frontend-visualization/react'; const data = [ { month: 'Jan', revenue: 1_200_000, costs: 750_000 }, { month: 'Feb', revenue: 1_450_000, costs: 920_000 }, { month: 'Mar', revenue: 980_000, costs: 680_000 }, { month: 'Apr', revenue: 1_650_000, costs: 1_050_000 }, { month: 'May', revenue: 2_100_000, costs: 1_280_000 }, ]; function MyChart() { const [loading, setLoading] = useState(true); const chart = useMemo(() => { const c = new Chart({ data, x: (d) => d.month }) .withBottomAxis() .withLeftAxis() .withLegend(); c.line({ label: 'Revenue', y: (d) => d.revenue }); c.line({ label: 'Costs', y: (d) => d.costs }); return c; }, []); return ( ); } ` } }, render: () => { const [loading, setLoading] = useState(true); const chart = useMemo(() => { const c = new Chart({ data, x: d => d.month }).withBottomAxis().withLeftAxis().withLegend(); c.line({ label: 'Revenue', y: d => d.revenue }); c.line({ label: 'Costs', y: d => d.costs }); return c; }, []); return
Скелетон — первая загрузка данных…
; } }) ``` -------------------------------- ### Create a Basic Line Chart in React Source: https://mindbox.pages.yandexcloud.net/development/frontend/frontend-visualization/llms/components-chart.txt Initializes a chart instance with data and renders it using the ChartView component. The ChartView automatically handles resizing via ResizeObserver. ```tsx meta.story({ name: 'Basic Line Chart', args: { height: 300 }, parameters: { docs: { source: storySource` import { Chart } from '@mindbox-cloud/frontend-visualization/cartesian'; import { ChartView } from '@mindbox-cloud/frontend-visualization/react'; const data = [ { month: 'Jan', revenue: 1_200_000 }, { month: 'Feb', revenue: 1_450_000 }, { month: 'Mar', revenue: 980_000 }, { month: 'Apr', revenue: 1_650_000 }, { month: 'May', revenue: 2_100_000 }, { month: 'Jun', revenue: 1_870_000 }, ]; const chart = new Chart({ data, x: (d) => d.month }) .withBottomAxis() .withLeftAxis() .withTooltip(); chart.line({ label: 'Revenue', y: (d) => d.revenue }); function RevenueChart() { return ; } ` } }, render: args => { const chart = useMemo(() => { const c = new Chart({ data: salesData, x: d => d.month }).withBottomAxis().withLeftAxis().withTooltip(); c.line({ label: 'Revenue', y: d => d.revenue }); return c; }, []); return ; }, play: async ({ canvas, step }) => { await step('SVG renders with a line presentation', async () => { expect(canvas.getByTestId('chart-canvas')).toBeInTheDocument(); const line = canvas.getAllByTestId('presentation').find(el => el.dataset.kind === 'line'); expect(line).toBeInTheDocument(); }); } }) ``` -------------------------------- ### Configure Pow Scale in Storybook Source: https://mindbox.pages.yandexcloud.net/development/frontend/frontend-visualization/llms/components-axis-scale-types.txt Demonstrates how to implement a power scale with a configurable exponent in a Storybook story. ```tsx meta.story({ name: 'Pow Scale', args: { exponent: 0.5 }, argTypes: { exponent: { control: { type: 'range', min: 0.1, max: 2, step: 0.1 }, description: 'Power scale exponent. 0.5 = sqrt (default), 1 = linear, >1 emphasizes large values.' } }, parameters: { docs: { source: storySource` import { Chart } from '@mindbox-cloud/frontend-visualization/cartesian'; import { ChartView } from '@mindbox-cloud/frontend-visualization/react'; const data = [ { month: 'Jan', area: 5 }, { month: 'Feb', area: 20 }, { month: 'Mar', area: 55 }, { month: 'Apr', area: 180 }, { month: 'May', area: 600 }, { month: 'Jun', area: 2_000 }, ]; const chart = new Chart({ data, x: (d) => d.month }) .withYScale({ side: 'left', type: 'pow', exponent: 0.5 }) .withBottomAxis() .withLeftAxis({ title: 'Area, m²' }); chart.line({ label: 'Area', y: (d) => d.area }); function Chart() { return ; } ` } }, render: ({ exponent = 0.5 }) => { const data = useMemo(() => [{ month: 'Jan', area: 5 }, { month: 'Feb', area: 20 }, { month: 'Mar', area: 55 }, { month: 'Apr', area: 180 }, { month: 'May', area: 600 }, { month: 'Jun', area: 2_000 }], []); const chart = useMemo(() => { const c = new Chart({ data, x: d => d.month }).withYScale({ side: 'left', type: 'pow', exponent }).withBottomAxis().withLeftAxis({ title: 'Area, m²' }); c.line({ label: 'Area', y: d => d.area }); return c; }, [data, exponent]); return ; }, play: async ({ canvas, step }) => { await step('Axis title is rendered', async () => { expect(canvas.getByText('Area, m²')).toBeInTheDocument(); }); } }) ``` -------------------------------- ### Visibility API: Get Current State Source: https://mindbox.pages.yandexcloud.net/development/frontend/frontend-visualization/llms/guides-legend.txt Retrieve the current visibility state of a dataset using `getVisibility(handle)`. The state can be `'visible'`, `'muted'`, or `'excluded'`. ```javascript const visibility = api.datasets.visibility.getVisibility(datasetHandle); // visibility is 'visible', 'muted', or 'excluded' ``` -------------------------------- ### ChartTooltip - Boundary and Placement Source: https://mindbox.pages.yandexcloud.net/development/frontend/frontend-visualization/llms/guides-tooltip.txt Configure the tooltip's boundary constraints and placement. Options include boundary ('plot', 'container', 'viewport') and placement ('left', 'center', 'right' for X; 'top', 'middle', 'bottom' for Y). Includes offset and padding settings, with automatic flipping if the tooltip doesn't fit. ```APIDOC ## Boundary and Placement | Parameter | Default | Description | | --- | --- | --- | | `boundary` | `'plot'` | Constraint area: `'viewport'`, `'container'`, `'plot'` | | `placementX` | `'right'` | Horizontal positioning: `'left'`, `'center'`, `'right'` | | `placementY` | `'bottom'` | Vertical positioning: `'top'`, `'middle'`, `'bottom'` | | `anchorOffsetPx` | `8` | Offset from the anchor point | | `paddingPx` | `8` | Minimum offset from boundary edges | If the tooltip does not fit, it will automatically flip along the axes. ### Boundary Values - **`'plot'`** (default) – the tooltip is kept strictly within the area between the axes. - **`'container'`** – the tooltip can extend beyond the plot area into the axis and padding space, using the entire chart container. - **`'viewport'`** – the tooltip is positioned relative to the browser's viewport. Provides maximum space but requires a `portal` if the container has `overflow: hidden`. ```