Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
185 changes: 185 additions & 0 deletions pages/03-core/events-sync-demo.page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

import { useRef, useState } from "react";
import Highcharts from "highcharts";
import { omit } from "lodash";

import ColumnLayout from "@cloudscape-design/components/column-layout";
import {
colorChartsPaletteCategorical1,
colorChartsPaletteCategorical2,
colorChartsPaletteCategorical3,
} from "@cloudscape-design/design-tokens";

import { ChartSeriesMarker } from "../../lib/components/internal/components/series-marker";
import CoreChart from "../../lib/components/internal-do-not-use/core-chart";
import { CoreLegend } from "../../lib/components/internal-do-not-use/core-legend";
import { CoreChartProps } from "../../src/core/interfaces";
import { LegendItem } from "../../src/internal/components/interfaces";
import { dateFormatter } from "../common/formatters";
import { useChartSettings } from "../common/page-settings";
import { Page } from "../common/templates";
import pseudoRandom from "../utils/pseudo-random";

function randomInt(min: number, max: number) {
return min + Math.floor(pseudoRandom() * (max - min));
}

const baseline = [
{ x: 1600984800000, y: 58020 },
{ x: 1600985700000, y: 102402 },
{ x: 1600986600000, y: 104920 },
{ x: 1600987500000, y: 94031 },
{ x: 1600988400000, y: 125021 },
{ x: 1600989300000, y: 159219 },
{ x: 1600990200000, y: 193082 },
{ x: 1600991100000, y: 162592 },
{ x: 1600992000000, y: 274021 },
{ x: 1600992900000, y: 264286 },
];

const dataA = baseline.map(({ x, y }) => ({ x, y }));
const dataB = baseline.map(({ x, y }) => ({ x, y: y === null ? null : y + randomInt(-100000, 100000) }));
const dataC = baseline.map(({ x, y }) => ({ x, y: y === null ? null : y + randomInt(-150000, 50000) }));

const series = [
{
name: "Series A",
type: "line" as const,
data: dataA,
color: colorChartsPaletteCategorical1,
},
{
name: "Series B",
type: "line" as const,
data: dataB,
color: colorChartsPaletteCategorical2,
},
{
name: "Series C",
type: "line" as const,
data: dataC,
color: colorChartsPaletteCategorical3,
},
];

export default function LegendEventsDemo() {
const [visibleItems, setVisibleItems] = useState(new Set<string>(["Series A", "Series B", "Series C"]));
const [highlightedItem, setHighlightedItem] = useState<null | string>(null);

const { chartProps } = useChartSettings();
const chart1API = useRef<CoreChartProps.ChartAPI>(null) as React.MutableRefObject<CoreChartProps.ChartAPI>;
const chart2API = useRef<CoreChartProps.ChartAPI>(null) as React.MutableRefObject<CoreChartProps.ChartAPI>;

const createOnItemHighlight =
(referrer: "legend" | "chart1" | "chart2") =>
({ detail }: { detail: { item: LegendItem } }) => {
setHighlightedItem(detail.item.name);
if (referrer !== "chart1") {
chart1API.current.highlightItems([detail.item.name]);
}
if (referrer !== "chart2") {
chart2API.current.highlightItems([detail.item.name]);
}
};
const createOnClearHighlight =
(referrer: "legend" | "chart1" | "chart2") =>
({ detail }: { detail: { isApiCall: boolean } }) => {
if (!detail.isApiCall) {
setHighlightedItem(null);
if (referrer !== "chart1") {
chart1API.current.clearChartHighlight();
}
if (referrer !== "chart2") {
chart2API.current.clearChartHighlight();
}
}
};
const createOnHighlight =
(referrer: "chart1" | "chart2") =>
({ detail }: { detail: { point: null | Highcharts.Point; isApiCall: boolean } }) => {
if (detail.point && !detail.isApiCall) {
setHighlightedItem(detail.point.name);
if (referrer !== "chart1") {
chart1API.current.highlightChartPoint(detail.point);
}
if (referrer !== "chart2") {
chart2API.current.highlightChartPoint(detail.point);
}
}
};

const legendItems: LegendItem[] = series.map((s) => ({
id: s.name,
name: s.name,
marker: <ChartSeriesMarker color={s.color} type="line" />,
visible: visibleItems.has(s.name),
highlighted: highlightedItem === s.name,
}));

return (
<Page
title="Events sync"
subtitle="Demonstrates the highlight synchronization between standalone legends and charts"
>
<ColumnLayout columns={2}>
<CoreLegend
items={legendItems}
title="Standalone legend 1"
onItemHighlight={createOnItemHighlight("legend")}
onClearHighlight={createOnClearHighlight("legend")?.bind(null, { detail: { isApiCall: false } })}
onVisibleItemsChange={({ detail }) => setVisibleItems(new Set(detail.items))}
/>

<CoreLegend
items={legendItems}
title="Standalone legend 2"
onItemHighlight={createOnItemHighlight("legend")}
onClearHighlight={createOnClearHighlight("legend")?.bind(null, { detail: { isApiCall: false } })}
onVisibleItemsChange={({ detail }) => setVisibleItems(new Set(detail.items))}
/>

<CoreChart
{...omit(chartProps.cartesian, "ref")}
highcharts={Highcharts}
callback={(chartApi) => (chart1API.current = chartApi)}
ariaLabel="Chart 1"
options={{
series: series,
xAxis: [{ type: "datetime", title: { text: "Time (UTC)" }, valueFormatter: dateFormatter }],
yAxis: [{ title: { text: "Events" } }],
}}
legend={{ title: "Chart legend 1" }}
onLegendItemHighlight={createOnItemHighlight("chart1")}
onClearHighlight={createOnClearHighlight("chart1")}
onHighlight={createOnHighlight("chart1")}
visibleItems={[...visibleItems]}
onVisibleItemsChange={({ detail }) =>
setVisibleItems(new Set(detail.items.filter((i) => i.visible).map((i) => i.name)))
}
/>

<CoreChart
{...omit(chartProps.cartesian, "ref")}
highcharts={Highcharts}
callback={(chartApi) => (chart2API.current = chartApi)}
ariaLabel="Chart 2"
options={{
series: series,
xAxis: [{ type: "datetime", title: { text: "Time (UTC)" }, valueFormatter: dateFormatter }],
yAxis: [{ title: { text: "Events" } }],
}}
legend={{ title: "Chart legend 2" }}
onLegendItemHighlight={createOnItemHighlight("chart2")}
onClearHighlight={createOnClearHighlight("chart2")}
onHighlight={createOnHighlight("chart2")}
visibleItems={[...visibleItems]}
onVisibleItemsChange={({ detail }) =>
setVisibleItems(new Set(detail.items.filter((i) => i.visible).map((i) => i.name)))
}
/>
</ColumnLayout>
</Page>
);
}
4 changes: 1 addition & 3 deletions src/core/__tests__/chart-core-api.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@ import { CoreChartProps } from "../../../lib/components/core/interfaces";
import { renderChart, selectLegendItem } from "./common";
import { HighchartsTestHelper } from "./highcharts-utils";

const clearHighlightPause = () => new Promise((resolve) => setTimeout(resolve, 100));

const hc = new HighchartsTestHelper(highcharts);

const series: Highcharts.SeriesOptionsType[] = [
Expand Down Expand Up @@ -68,7 +66,7 @@ describe("CoreChart: API tests", () => {

act(() => hc.highlightChartPoint(0, 0));
act(() => hc.leaveChartPoint(0, 0));
await clearHighlightPause();
await hc.clearHighlightPause();

expect(onClearHighlight).toHaveBeenCalledWith(expect.objectContaining({ detail: { isApiCall: false } }));
});
Expand Down
6 changes: 2 additions & 4 deletions src/core/__tests__/chart-core-highlight.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,6 @@ import { HighchartsTestHelper } from "./highcharts-utils";

const hc = new HighchartsTestHelper(highcharts);

const clearHighlightPause = () => new Promise((resolve) => setTimeout(resolve, 100));

describe("CoreChart: highlight", () => {
test("highlights linked errorbar when target series is highlighted", async () => {
renderChart({
Expand Down Expand Up @@ -55,7 +53,7 @@ describe("CoreChart: highlight", () => {
expect(hc.getChartSeries(3).state).toBe("hover");

act(() => hc.leaveChartPoint(1, 0));
await clearHighlightPause();
await hc.clearHighlightPause();

expect(hc.getChartSeries(0).state).toBe("");
expect(hc.getChartSeries(1).state).toBe("");
Expand Down Expand Up @@ -90,7 +88,7 @@ describe("CoreChart: highlight", () => {
expect(hc.getChartPoint(1, 1).state).toBe("inactive");

act(() => hc.leaveChartPoint(1, 0));
await clearHighlightPause();
await hc.clearHighlightPause();

expect(hc.getChartSeries(0).state).toBe("");
expect(hc.getChartPoint(0, 0).state).toBe("");
Expand Down
51 changes: 41 additions & 10 deletions src/core/__tests__/chart-core-legend.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
createChartWrapper,
hoverLegendItem,
hoverSecondaryLegendItem,
leaveLegendItem,
renderChart,
renderStatefulChart,
selectSecondaryLegendItem,
Expand Down Expand Up @@ -51,6 +52,8 @@ const series: Highcharts.SeriesOptionsType[] = [
},
];

const lineSeries = series.filter((s) => s.type === "line");

const yAxes: Highcharts.YAxisOptions[] = [
{ id: "primary", opposite: false },
{ id: "secondary", opposite: true },
Expand Down Expand Up @@ -88,7 +91,6 @@ const getItem = (index: number, options?: { active?: boolean; dimmed?: boolean }
createChartWrapper().findLegend()!.findAll(getItemSelector(options))[index];
const mouseOver = (element: HTMLElement) => element.dispatchEvent(new MouseEvent("mouseover", { bubbles: true }));
const mouseOut = (element: HTMLElement) => element.dispatchEvent(new MouseEvent("mouseout", { bubbles: true }));
const clearHighlightPause = () => new Promise((resolve) => setTimeout(resolve, 100));
const mouseLeavePause = () => new Promise((resolve) => setTimeout(resolve, 300));

describe("CoreChart: legend", () => {
Expand Down Expand Up @@ -180,7 +182,7 @@ describe("CoreChart: legend", () => {
expect(hc.getPlotLinesById("L3").map((l) => l.svgElem.opacity)).toEqual([1, 1]);

act(() => mouseOut(getItem(0).getElement()));
await clearHighlightPause();
await hc.clearHighlightPause();
expect(getItems({ dimmed: false, active: true }).map((w) => w.getElement().textContent)).toEqual([
"L1",
"Line 3",
Expand Down Expand Up @@ -213,7 +215,7 @@ describe("CoreChart: legend", () => {
expect(hc.getChartPoint(0, 2).state).toBe(undefined);

act(() => mouseOut(getItem(0).getElement()));
await clearHighlightPause();
await hc.clearHighlightPause();
expect(getItems({ dimmed: false, active: true }).map((w) => w.getElement().textContent)).toEqual(["P1", "Pie 3"]);
expect(hc.getChartPoint(0, 0).state).toBe("");
expect(hc.getChartPoint(0, 2).state).toBe("");
Expand All @@ -225,7 +227,7 @@ describe("CoreChart: legend", () => {
expect(hc.getChartPoint(0, 2).state).toBe("hover");

act(() => mouseOut(getItem(2).getElement()));
await clearHighlightPause();
await hc.clearHighlightPause();
expect(getItems({ dimmed: false, active: true }).map((w) => w.getElement().textContent)).toEqual(["P1", "Pie 3"]);
expect(hc.getChartPoint(0, 0).state).toBe("");
expect(hc.getChartPoint(0, 2).state).toBe("");
Expand Down Expand Up @@ -255,7 +257,7 @@ describe("CoreChart: legend", () => {

act(() => hc.leaveChartPoint(2, 0));
await mouseLeavePause();
await clearHighlightPause();
await hc.clearHighlightPause();
expect(getItems({ dimmed: false, active: true }).map((w) => w.getElement().textContent)).toEqual([
"L1",
"Line 3",
Expand Down Expand Up @@ -283,7 +285,7 @@ describe("CoreChart: legend", () => {

act(() => hc.leaveChartPoint(0, 2));
await mouseLeavePause();
await clearHighlightPause();
await hc.clearHighlightPause();
expect(getItems({ dimmed: false, active: true }).map((w) => w.getElement().textContent)).toEqual(["P1", "Pie 3"]);
},
);
Expand Down Expand Up @@ -388,7 +390,7 @@ describe("CoreChart: legend", () => {

act(() => mouseOut(getItem(2).getElement()));

await clearHighlightPause();
await hc.clearHighlightPause();
expect(wrapper.findLegend()!.findItemTooltip()).toBe(null);
});

Expand Down Expand Up @@ -447,7 +449,7 @@ describe("CoreChart: legend", () => {

act(() => mouseOut(getItem(2).getElement()));

await clearHighlightPause();
await hc.clearHighlightPause();
expect(wrapper.findLegend()!.findItemTooltip()).toBe(null);
});

Expand Down Expand Up @@ -476,9 +478,10 @@ describe("CoreChart: legend", () => {
});
});

test("calls onLegendItemHighlight when hovering over a legend item", () => {
test("calls onLegendItemHighlight and onClearHighlight when hovering over a legend item", async () => {
const onLegendItemHighlight = vi.fn();
const { wrapper } = renderChart({ highcharts, options: { series }, onLegendItemHighlight });
const onClearHighlight = vi.fn();
const { wrapper } = renderChart({ highcharts, options: { series }, onLegendItemHighlight, onClearHighlight });

hoverLegendItem(0, wrapper);

Expand All @@ -495,6 +498,34 @@ describe("CoreChart: legend", () => {
},
}),
);

leaveLegendItem(0, wrapper);
await hc.clearHighlightPause();

expect(onClearHighlight).toHaveBeenCalled();
});

test("legend highlight state stays after re-render", () => {
const { wrapper, rerender } = renderChart({ highcharts, options: { series } });

hoverLegendItem(0, wrapper);
expect(getItems({ dimmed: false, active: true }).map((w) => w.getElement().textContent)).toEqual(["L1"]);

rerender({ highcharts, options: { series } });
expect(getItems({ dimmed: false, active: true }).map((w) => w.getElement().textContent)).toEqual(["L1"]);
});

test("legend highlight state is reset after re-render if items structure change", () => {
const { wrapper, rerender } = renderChart({ highcharts, options: { series: lineSeries } });

hoverLegendItem(0, wrapper);
expect(getItems({ dimmed: false, active: true }).map((w) => w.getElement().textContent)).toEqual(["L1"]);

rerender({ highcharts, options: { series: lineSeries.filter((s) => s.name !== "L2") } });
expect(getItems({ dimmed: false, active: true }).map((w) => w.getElement().textContent)).toEqual(["L1"]);

rerender({ highcharts, options: { series: lineSeries.filter((s) => s.name !== "L1") } });
expect(getItems({ dimmed: false, active: true }).map((w) => w.getElement().textContent)).toEqual(["L2", "Line 3"]);
});
});

Expand Down
5 changes: 5 additions & 0 deletions src/core/__tests__/common.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,11 @@ export function hoverLegendItem(index: number, wrapper: BaseChartWrapper = creat
fireEvent.mouseOver(wrapper.findLegend()!.findItems()[index].getElement());
});
}
export function leaveLegendItem(index: number, wrapper: BaseChartWrapper = createChartWrapper()) {
act(() => {
fireEvent.mouseLeave(wrapper.findLegend()!.findItems()[index].getElement());
});
}

export function selectSecondaryLegendItem(index: number, wrapper: ExtendedTestWrapper = createChartWrapper()) {
act(() => wrapper.findSecondaryLegend()!.findItems()[index].click());
Expand Down
4 changes: 4 additions & 0 deletions src/core/__tests__/highcharts-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,10 @@ export class HighchartsTestHelper {
.axes.flatMap((axis) => (axis as any).plotLinesAndBands)
.filter((plotLine) => plotLine.options.id === id);
}

public clearHighlightPause() {
return new Promise((resolve) => setTimeout(resolve, 100));
}
}

export class ChartRendererStub {
Expand Down
Loading
Loading