fix(dashboards): treemap zoom, totals, defaults, labels and drilldown path (#17004)

This commit is contained in:
Abhay Padamani authored and GitHub committed 2026-11-19 11:55:03 +00:00
1 parent 8416d13d5d
commit bfc21b4af6
44 files changed
+765 -51

No files matched your search

@@ -597,6 +597,7 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
@series-limit-update="handleSeriesLimitUpdate"
@region-join-update="handleRegionJoinUpdate"
@sankey-notice-update="handleSankeyNoticeUpdate"
@treemap-notice-update="handleTreemapNoticeUpdate"
@panel-diagnostics-update="handlePanelDiagnosticsUpdate"
@result-metadata-update="handleResultMetadataUpdate"
@last-triggered-at-update="handleLastTriggeredAtUpdate"
@@ -1032,6 +1033,7 @@ export default defineComponent({
panelDiagnostics,
seriesLimit,
sankeyNotice,
treemapNotice,
maxQueryRangeWarning,
noticeProps,
handleResultMetadataUpdate,
@@ -1039,6 +1041,7 @@ export default defineComponent({
handleSeriesLimitUpdate,
handleRegionJoinUpdate,
handleSankeyNoticeUpdate,
handleTreemapNoticeUpdate,
} = usePanelNotices(() => store.state.timezone);
// to store and show when the panel was last loaded
@@ -1129,6 +1132,7 @@ export default defineComponent({
!!noticeProps.value.regionJoin ||
!!sankeyNotice.value?.returnLinks ||
!!sankeyNotice.value?.skippedRows ||
!!treemapNotice.value?.skippedRows ||
!!panelDiagnostics.value?.serverPartial ||
injectedPartial.value ||
!!panelDiagnostics.value?.functionErrors?.length ||
@@ -1704,6 +1708,7 @@ export default defineComponent({
handleSeriesLimitUpdate,
handleRegionJoinUpdate,
handleSankeyNoticeUpdate,
handleTreemapNoticeUpdate,
canEditFromNotice,
canRefreshFromNotice,
panelNoticeProps,
@@ -356,6 +356,7 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
@series-limit-update="handleSeriesLimitUpdate"
@region-join-update="handleRegionJoinUpdate"
@sankey-notice-update="handleSankeyNoticeUpdate"
@treemap-notice-update="handleTreemapNoticeUpdate"
@limit-number-of-series-warning-message-update="
handleLimitNumberOfSeriesWarningMessage
"
@@ -719,6 +720,7 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
@series-limit-update="handleSeriesLimitUpdate"
@region-join-update="handleRegionJoinUpdate"
@sankey-notice-update="handleSankeyNoticeUpdate"
@treemap-notice-update="handleTreemapNoticeUpdate"
@limit-number-of-series-warning-message-update="
handleLimitNumberOfSeriesWarningMessage
"
@@ -1015,6 +1017,7 @@ const {
handleSeriesLimitUpdate,
handleRegionJoinUpdate,
handleSankeyNoticeUpdate,
handleTreemapNoticeUpdate,
metaDataValue,
seriesDataUpdate,
collapseFieldList: baseCollapseFieldList,
@@ -137,6 +137,7 @@ export function usePanelEditor(options: UsePanelEditorOptions) {
handleSeriesLimitUpdate,
handleRegionJoinUpdate,
handleSankeyNoticeUpdate,
handleTreemapNoticeUpdate,
} = usePanelNotices(() => store.state.timezone);
/** Series limit warning message */
@@ -876,6 +877,7 @@ export function usePanelEditor(options: UsePanelEditorOptions) {
handleSeriesLimitUpdate,
handleRegionJoinUpdate,
handleSankeyNoticeUpdate,
handleTreemapNoticeUpdate,
metaDataValue,
seriesDataUpdate,
collapseFieldList,
@@ -501,6 +501,17 @@ describe("PanelErrorButtons", () => {
wrapper.unmount();
});
it("counts treemap rows skipped for a size that is not a positive number", async () => {
const wrapper = mountAttached({ treemapNotice: { skippedRows: 2 } });
const chip = wrapper.find('[data-test="panel-notice-chip-skipped-rows"]');
expect(chip.text()).toBe("2 rows skipped");
await openTooltip(chip.element);
expect(bubble()?.textContent).toContain(
"2 rows have a size that is not a positive number, so they are not drawn or counted in the totals.",
);
wrapper.unmount();
});
it("shows server partial and client interruption as separate chips", () => {
const wrapper = mountAttached({
serverPartial: true,
@@ -259,6 +259,7 @@ import PanelNoticeContent from "@/components/dashboards/PanelNoticeContent.vue";
import type { SeriesLimitInfo } from "@/utils/dashboard/panelDiagnostics";
import type { RegionJoinInfo } from "@/utils/dashboard/convertMapsData";
import type { SankeyNotice } from "@/utils/dashboard/convertSankeyData";
import type { TreemapNotice } from "@/utils/dashboard/convertTreemapData";
import {
buildPanelNotices,
seriesTotalBoundOf,
@@ -312,6 +313,10 @@ export default defineComponent({
type: Object as PropType<SankeyNotice | null>,
default: null,
},
treemapNotice: {
type: Object as PropType<TreemapNotice | null>,
default: null,
},
serverPartial: {
type: Boolean,
default: false,
@@ -395,6 +400,7 @@ export default defineComponent({
serverPartial: props.serverPartial,
}),
sankeyNotice: props.sankeyNotice,
treemapNotice: props.treemapNotice,
serverPartial: props.serverPartial,
partialReasons: props.serverPartialReasons,
interrupted: props.isPartialData && !props.isPanelLoading,
@@ -457,6 +457,7 @@ import { detectChunkingDirection } from "@/utils/dashboard/chunkingDirection";
import type { SeriesLimitInfo } from "@/utils/dashboard/panelDiagnostics";
import type { RegionJoinInfo } from "@/utils/dashboard/convertMapsData";
import type { SankeyNotice } from "@/utils/dashboard/convertSankeyData";
import type { TreemapNotice } from "@/utils/dashboard/convertTreemapData";
interface CustomChartVariable {
name: string;
@@ -717,6 +718,7 @@ export default defineComponent({
"series-limit-update",
"region-join-update",
"sankey-notice-update",
"treemap-notice-update",
"panel-diagnostics-update",
"sparkline-warning-update",
"is-partial-data-update",
@@ -792,6 +794,7 @@ export default defineComponent({
const seriesLimit = ref<SeriesLimitInfo | null>(null);
const regionJoin = shallowRef<RegionJoinInfo | null>(null);
const sankeyNotice = ref<SankeyNotice | null>(null);
const treemapNotice = ref<TreemapNotice | null>(null);
const chartPanelStyle = ref({
height: "100%",
@@ -1732,6 +1735,7 @@ export default defineComponent({
seriesLimit.value = panelData.value?.extras?.seriesLimit ?? null;
regionJoin.value = panelData.value?.extras?.regionJoin ?? null;
sankeyNotice.value = panelData.value?.extras?.sankeyNotice ?? null;
treemapNotice.value = panelData.value?.extras?.treemapNotice ?? null;
// A new run reports its own outcome; with no run left there is nothing to report it.
if (!showsCustomChartError.value || !customChartRun.value) {
@@ -1748,6 +1752,7 @@ export default defineComponent({
}
regionJoin.value = null;
sankeyNotice.value = null;
treemapNotice.value = null;
errorDetail.value = {
message: error?.message,
code: error?.code || "",
@@ -1756,6 +1761,7 @@ export default defineComponent({
} else {
regionJoin.value = null;
sankeyNotice.value = null;
treemapNotice.value = null;
// if no data is available, then show the default data
// if there is an error config in the panel schema, then show the default data on error
// if no default data on error is set, then show the custom error message
@@ -2141,6 +2147,13 @@ export default defineComponent({
},
{ immediate: true },
);
watch(
treemapNotice,
(value) => {
emit("treemap-notice-update", value);
},
{ immediate: true },
);
watch(
() => panelDiagnostics?.value,
@@ -451,6 +451,21 @@ describe("DashboardQueryEditor", () => {
panelData.type = previousType;
});
it("offers no second query for a treemap, which draws one measure", async () => {
wrapper = createWrapper();
const panelData = wrapper.vm.dashboardPanelData.data;
const previousType = panelData.type;
const addButton = () => wrapper.find('[data-test="dashboard-panel-query-tab-add"]');
panelData.type = "line";
await wrapper.vm.$nextTick();
expect(addButton().exists()).toBe(true);
panelData.type = "treemap";
await wrapper.vm.$nextTick();
expect(addButton().exists()).toBe(false);
panelData.type = previousType;
});
it("should handle query index changes", async () => {
wrapper = createWrapper();
@@ -153,6 +153,7 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
</OTabs>
</div>
<OButton
v-if="dashboardPanelData.data.type !== 'treemap'"
:aria-label="t('dashboard.newTab')"
variant="ghost"
size="icon"
@@ -635,6 +635,16 @@ describe("DrilldownPopUp", () => {
expect(selectedValues.some((val: any) => val.value === "${series.__value}")).toBe(true);
});
it("offers a treemap tile's full path beside its name and value", () => {
mockDashboardPanelData.data.type = "treemap";
wrapper = createWrapper();
const values = wrapper.vm.options.selectedValue.map((val: { value: string }) => val.value);
expect(values).toEqual(
expect.arrayContaining(["${series.__name}", "${series.__value}", "${series.__path}"]),
);
});
it("should generate correct values for metric type", () => {
mockDashboardPanelData.data.type = "metric";
wrapper = createWrapper();
@@ -642,8 +642,15 @@ export default defineComponent({
});
});
});
} else if (dashboardPanelData.data.type === "treemap") {
selectedValues = [
{ label: t("dashboard.seriesName"), value: "${series.__name}" },
{ label: t("dashboard.seriesValue"), value: "${series.__value}" },
{ label: t("dashboard.treemapTilePath"), value: "${series.__path}" },
...variableListName,
];
} else if (
["pie", "donut", "gauge", "bar-gauge", "treemap", "sunburst", "funnel", "boxplot"].includes(
["pie", "donut", "gauge", "bar-gauge", "sunburst", "funnel", "boxplot"].includes(
dashboardPanelData.data.type,
)
) {
@@ -234,6 +234,7 @@
@series-limit-update="handleSeriesLimitUpdate"
@region-join-update="handleRegionJoinUpdate"
@sankey-notice-update="handleSankeyNoticeUpdate"
@treemap-notice-update="handleTreemapNoticeUpdate"
@limit-number-of-series-warning-message-update="
handleLimitNumberOfSeriesWarningMessage
"
@@ -501,6 +502,7 @@ export default defineComponent({
handleSeriesLimitUpdate,
handleRegionJoinUpdate,
handleSankeyNoticeUpdate,
handleTreemapNoticeUpdate,
} = usePanelNotices(() => store.state.timezone);
const limitNumberOfSeriesWarningMessage = ref("");
const sparklineWarning = ref("");
@@ -1087,6 +1089,7 @@ export default defineComponent({
handleSeriesLimitUpdate,
handleRegionJoinUpdate,
handleSankeyNoticeUpdate,
handleTreemapNoticeUpdate,
canEditFromNotice,
onNoticeEditPanel,
limitNumberOfSeriesWarningMessage,
@@ -639,6 +639,18 @@ describe("usePanelAggregation", () => {
expect(fields.breakdown).toEqual([{ alias: "b1" }]);
});
it("drops a time bucket from the group levels", () => {
const panelData = makePanelData("treemap");
const fields = panelData.data.queries[0].fields;
fields.x = [
{ alias: "x_axis_1", column: "_timestamp", functionName: "histogram" },
{ alias: "x_axis_2", functionName: null },
];
fields.y = [yField("count")];
makeAggregation(panelData).resetAggregationFunction();
expect(fields.x).toEqual([{ alias: "x_axis_2", functionName: null }]);
});
it("turns a size a parent tile cannot add up into a count, and keeps a sum", () => {
const panelData = makePanelData("treemap");
const fields = panelData.data.queries[0].fields;
@@ -689,6 +701,15 @@ describe("usePanelAggregation", () => {
args: [{ type: "field" }, { type: "extra" }],
});
it("drops a time bucket from the rings", () => {
const sunburst = makePanelData("sunburst");
const ring = sunburst.data.queries[0].fields;
ring.x = [{ alias: "x_axis_1", column: "_timestamp", functionName: "histogram" }];
ring.y = [yField("count")];
makeAggregation(sunburst).resetAggregationFunction();
expect(ring.x).toEqual([]);
});
it("keeps every x ring, one y counted and one breakdown", () => {
const sunburst = makePanelData("sunburst");
const ring = sunburst.data.queries[0].fields;
@@ -444,7 +444,10 @@ export const usePanelAggregation = ({
itemY.args = itemY.args.length ? [itemY?.args?.[0]] : [];
}
});
query.fields.x = query.fields.x.slice(0, TREEMAP_MAX_LEVELS);
// A time bucket is not a useful tile label, so only plain fields stay as levels.
query.fields.x = query.fields.x
.filter((itemX: { functionName?: string | null }) => itemX.functionName !== "histogram")
.slice(0, TREEMAP_MAX_LEVELS);
query.fields.y = query.fields.y.slice(0, 1);
query.fields.z = [];
query.fields.breakdown = query.fields.breakdown.slice(
@@ -473,8 +476,10 @@ export const usePanelAggregation = ({
itemY.args = itemY.args.length ? [itemY?.args?.[0]] : [];
}
});
// Each x field is a ring, so keep them up to the cap, leaving room for one breakdown ring.
query.fields.x = query.fields.x.slice(0, SUNBURST_MAX_LEVELS);
// Each plain x field is a ring, kept up to the cap with room for one breakdown ring; a time bucket makes no useful ring.
query.fields.x = query.fields.x
.filter((itemX: { functionName?: string | null }) => itemX.functionName !== "histogram")
.slice(0, SUNBURST_MAX_LEVELS);
query.fields.y = query.fields.y.slice(0, 1);
query.fields.z = [];
query.fields.breakdown = query.fields.breakdown.slice(
@@ -46,6 +46,17 @@ vi.mock("@/services/search", async (importOriginal) => {
});
});
const commonsMock = vi.hoisted(() => ({
getFoldersList: vi.fn(),
getAllDashboardsByFolderId: vi.fn(),
getDashboard: vi.fn(),
}));
vi.mock("@/utils/commons", async (importOriginal) => ({
...(await importOriginal<typeof import("@/utils/commons")>()),
...commonsMock,
}));
vi.mock("@/utils/zincutils", () => ({
b64EncodeUnicode: (v: string) => `b64(${v})`,
escapeSingleQuotes: (v: string) => v,
@@ -1428,6 +1439,173 @@ describe("usePanelDrilldown", () => {
openSpy.mockRestore();
});
describe("treemap tile drilldowns", () => {
const treemapDeps = (drilldown: Record<string, unknown>) => {
const deps = makeDeps();
deps.panelSchema.value.type = "treemap";
Object.assign(deps.panelSchema.value.config, { drilldown: [drilldown] });
return {
...deps,
panelData: { value: { options: { xAxis: [{ data: [] }], series: [{ type: "treemap" }] } } },
};
};
const emptyTile = {
componentType: "series",
seriesIndex: 0,
name: "(empty)",
value: 4,
data: {
name: "(empty)",
rawName: "",
value: 4,
path: ["us east", "a/b", "(empty)"],
rawPath: ["us east", "a/b", ""],
},
event: { offsetX: 1, offsetY: 1 },
};
const nullTile = {
componentType: "series",
seriesIndex: 0,
name: "(null)",
value: 2,
data: { name: "(null)", rawName: null, value: 2, path: ["(null)"], rawPath: [null] },
event: { offsetX: 1, offsetY: 1 },
};
it("hands a URL drilldown the blank behind an empty tile and its path encoded per segment", async () => {
const openSpy = vi.spyOn(window, "open").mockImplementation(() => null);
const api = usePanelDrilldown(
treemapDeps({
name: "Link",
type: "byUrl",
targetBlank: true,
data: { url: "https://example.com/?n=${series.__name}&p=${series.__path}" },
}),
);
await api.onChartClick(emptyTile);
await api.openDrilldown(0);
expect(openSpy).toHaveBeenCalledWith(
"https://example.com/?n=&p=us%20east/a%2Fb/",
"_blank",
"noopener,noreferrer",
);
openSpy.mockRestore();
});
it("hands a dashboard drilldown the raw tile path", async () => {
commonsMock.getFoldersList.mockResolvedValue(undefined);
commonsMock.getAllDashboardsByFolderId.mockResolvedValue([
{ title: "Target", dashboardId: "d-1" },
]);
commonsMock.getDashboard.mockResolvedValue({
dashboardId: "d-1",
tabs: [{ name: "Main", tabId: "t-1" }],
});
const deps = treemapDeps({
name: "Dash",
type: "byDashboard",
targetBlank: false,
data: {
folder: "default",
dashboard: "Target",
tab: "Main",
passAllVariables: false,
variables: [{ name: "p", value: "${series.__path}" }],
},
});
Object.assign(deps.store.state, {
organizationData: { folders: [{ name: "default", folderId: "f-1" }] },
});
const api = usePanelDrilldown(deps);
await api.onChartClick(emptyTile);
await api.openDrilldown(0);
expect(deps.router.push).toHaveBeenCalledWith({
path: "/dashboards/view",
query: expect.objectContaining({ "var-p": "us east/a/b/" }),
});
});
it.each([
["path", "${series.__path}", emptyTile, "'us east/a/b/'"],
["axis value of a null tile", "${series.__axisValue}", nullTile, "''"],
])("hands a logs drilldown the raw %s", async (_label, placeholder, tile, expected) => {
const deps = treemapDeps({
name: "Logs",
type: "logs",
targetBlank: false,
data: { logsMode: "custom", logsQuery: `SELECT * FROM "default" WHERE p = ${placeholder}` },
});
const api = usePanelDrilldown(deps);
await api.onChartClick(tile);
await api.openDrilldown(0);
await vi.waitFor(() =>
expect(deps.router.push).toHaveBeenCalledWith(
expect.objectContaining({
query: expect.objectContaining({
query: `b64(SELECT * FROM "default" WHERE p = ${expected})`,
}),
}),
),
);
});
it.each([
["empty", emptyTile, "2"],
["null", nullTile, "3"],
])("opens a cross-link with the row behind the %s tile", async (_label, tile, expected) => {
const openSpy = vi.spyOn(window, "open").mockImplementation(() => null);
resultSchemaMock.mockResolvedValue({
data: {
cross_links: {
stream_links: [
{
name: "Link",
url: "https://x.example/${field.__value}",
fields: [{ name: "f", alias: "f" }],
},
],
org_links: [],
},
},
});
const deps = treemapDeps({
name: "None",
type: "byUrl",
data: { url: "https://example.com" },
});
deps.panelSchema.value.config.drilldown = [];
Object.assign(deps.panelSchema.value.queries[0].fields, { x: [{ alias: "x" }] });
Object.assign(deps.data, {
value: [
{
result: [
{ x: "a", f: "1" },
{ x: "", f: "2" },
{ x: null, f: "3" },
],
},
],
});
const api = usePanelDrilldown(deps);
await api.onChartClick(tile);
await api.openDrilldown(0);
expect(openSpy).toHaveBeenCalledWith(
`https://x.example/${expected}`,
"_blank",
"noopener,noreferrer",
);
openSpy.mockRestore();
});
});
describe("sankey return nodes", () => {
const sankeyDeps = (drilldown: any) => {
const deps = makeDeps();
@@ -52,6 +52,11 @@ import { hostmapDrilldownSeries, hostmapEntityColumn } from "@/utils/dashboard/c
// A click on these lands on a named item (slice, bar, tile), not on a named series.
const NAMED_ITEM_TYPES = ["pie", "donut", "bar-gauge", "treemap", "sunburst", "funnel"];
interface NamedItemParams {
name?: string;
data?: { rawName?: string | null; path?: string[]; rawPath?: (string | null)[] };
}
export function usePanelDrilldown({
panelSchema,
variablesData,
@@ -281,13 +286,25 @@ export function usePanelDrilldown({
}
if (panelSchema.value.type === "bar-gauge") return barGaugeDrilldownSeries(params);
return {
__name: NAMED_ITEM_TYPES.includes(panelSchema.value.type) ? params?.name : params?.seriesName,
__name: NAMED_ITEM_TYPES.includes(panelSchema.value.type)
? drilldownItemName(params)
: params?.seriesName,
__value: value,
// A gauge dial named "(empty)" stands in for a blank label; drilldowns filter on the blank.
__axisValue: params?.value?.[0] ?? params?.data?.rawName ?? params?.name,
__axisValue: params?.value?.[0] ?? drilldownItemName(params),
// Tiles of the same name sit under different parents, so the path tells them apart.
...(panelSchema.value.type === "treemap"
? { __path: treemapPathSegments(params).join("/") }
: {}),
};
};
// An item shown as "(empty)" or "(null)" stands in for a blank group; drilldowns filter on the blank.
const drilldownItemName = (params: NamedItemParams | undefined) =>
params?.data?.rawName !== undefined ? (params.data.rawName ?? "") : params?.name;
const treemapPathSegments = (params: NamedItemParams | undefined): string[] =>
(params?.data?.rawPath ?? params?.data?.path ?? []).map((segment) => segment ?? "");
// get offset from parent
function getOffsetFromParent(parent: any, child: any) {
const parentRect = parent.getBoundingClientRect();
@@ -810,7 +827,11 @@ export function usePanelDrilldown({
let xAxisValue: any;
if (isPieOrDonut) {
xAxisValue = drilldownParams[0]?.name;
// A stand-in tile matches the rows of the null or empty group it represents.
xAxisValue =
drilldownParams[0]?.data?.rawName !== undefined
? drilldownParams[0].data.rawName
: drilldownParams[0]?.name;
} else if (chartType === "heatmap") {
xAxisValue = drilldownParams[0]?.value?.[0];
} else {
@@ -831,7 +852,12 @@ export function usePanelDrilldown({
for (const row of queryResult) {
let matches = true;
if (xFields.length > 0 && xAxisValue !== undefined) {
if (String(row[xFields[0].alias]) !== String(xAxisValue)) matches = false;
const cell = row[xFields[0].alias];
const mismatch =
xAxisValue === null
? cell !== null && cell !== undefined
: String(cell) !== String(xAxisValue);
if (mismatch) matches = false;
}
if (matches && breakdownFields.length > 0 && seriesName && !isPieOrDonut) {
if (String(row[breakdownFields[0].alias]) !== String(seriesName)) matches = false;
@@ -1164,7 +1190,20 @@ export function usePanelDrilldown({
// save time, but that is client-side only: a direct dashboard PUT
// stores anything, and dashboards saved before the schema existed
// are still in the DB. A variable VALUE can also carry a scheme.
const resolved = replacePlaceholders(drilldownData.data.url, drilldownVariables);
const urlVariables =
drilldownVariables.series?.__path === undefined
? drilldownVariables
: {
...drilldownVariables,
series: {
...drilldownVariables.series,
// Each segment is encoded on its own so a "/" inside a group value stays one segment.
__path: treemapPathSegments(drilldownParams[0])
.map((segment) => encodeURIComponent(segment))
.join("/"),
},
};
const resolved = replacePlaceholders(drilldownData.data.url, urlVariables);
if (!isSafeNavigableUrl(resolved)) return;
// open url
return window.open(
@@ -70,6 +70,7 @@ describe("usePanelNotices", () => {
seriesLimit: { shown: 100, total: 1000, cap: 100 },
regionJoin: null,
sankeyNotice: { returnLinks: 2, skippedRows: 1 },
treemapNotice: null,
serverPartial: true,
rowsCapped: true,
serverPartialReasons: ["Warn: results are capped to meet default limit"],
@@ -82,6 +83,15 @@ describe("usePanelNotices", () => {
expect(notices.maxQueryRangeWarning.value).toBe("");
});
it("passes the treemap's skipped rows to PanelErrorButtons and clears them on reset", () => {
const notices = usePanelNotices(() => "UTC");
notices.handleTreemapNoticeUpdate({ skippedRows: 2 });
expect(notices.noticeProps.value.treemapNotice).toEqual({ skippedRows: 2 });
notices.resetNotices();
expect(notices.noticeProps.value.treemapNotice).toBeNull();
});
it("passes the maps region join to PanelErrorButtons and clears it on reset", () => {
const notices = usePanelNotices(() => "UTC");
const join = { unmatched: ["us-east-1"], unmatchedTotal: 1 };
@@ -22,6 +22,7 @@ import {
} from "@/utils/dashboard/panelDiagnostics";
import type { RegionJoinInfo } from "@/utils/dashboard/convertMapsData";
import type { SankeyNotice } from "@/utils/dashboard/convertSankeyData";
import type { TreemapNotice } from "@/utils/dashboard/convertTreemapData";
/**
* The notice state a PanelSchemaRenderer host keeps for PanelErrorButtons: server diagnostics,
@@ -33,6 +34,7 @@ export const usePanelNotices = (timezone: () => string) => {
const seriesLimit = shallowRef<SeriesLimitInfo | null>(null);
const regionJoin = shallowRef<RegionJoinInfo | null>(null);
const sankeyNotice = shallowRef<SankeyNotice | null>(null);
const treemapNotice = shallowRef<TreemapNotice | null>(null);
// Writable, so a host can still clear it with its other warnings.
const maxQueryRangeWarning = ref("");
@@ -68,12 +70,17 @@ export const usePanelNotices = (timezone: () => string) => {
sankeyNotice.value = notice;
};
const handleTreemapNoticeUpdate = (notice: TreemapNotice | null) => {
treemapNotice.value = notice;
};
const resetNotices = () => {
resultMetadata.value = null;
panelDiagnostics.value = null;
seriesLimit.value = null;
regionJoin.value = null;
sankeyNotice.value = null;
treemapNotice.value = null;
maxQueryRangeWarning.value = "";
};
@@ -82,6 +89,7 @@ export const usePanelNotices = (timezone: () => string) => {
seriesLimit: seriesLimit.value,
regionJoin: regionJoin.value,
sankeyNotice: sankeyNotice.value,
treemapNotice: treemapNotice.value,
serverPartial: panelDiagnostics.value?.serverPartial ?? false,
rowsCapped: panelDiagnostics.value?.rowsCapped ?? false,
serverPartialReasons: panelDiagnostics.value?.partialReasons ?? [],
@@ -92,6 +100,7 @@ export const usePanelNotices = (timezone: () => string) => {
panelDiagnostics,
seriesLimit,
sankeyNotice,
treemapNotice,
maxQueryRangeWarning,
noticeProps,
handleResultMetadataUpdate,
@@ -99,6 +108,7 @@ export const usePanelNotices = (timezone: () => string) => {
handleSeriesLimitUpdate,
handleRegionJoinUpdate,
handleSankeyNoticeUpdate,
handleTreemapNoticeUpdate,
resetNotices,
};
};
+5
View File
@@ -8223,6 +8223,7 @@
"hostmapGroupByHint": "أضف حتى حقلين",
"hostmapCellName": "اسم الخلية",
"hostmapCellGroup": "مجموعة الخلية",
"treemapTilePath": "مسار المربع",
"stateTimelineDisplay": "العرض",
"stateTimelineDisplayTooltip": "الأشرطة تدمج القيم المتساوية في شريط واحد؛ الخلايا ترسم كتلة لكل فترة زمنية.",
"stateTimelineDisplayBands": "أشرطة",
@@ -9634,6 +9635,7 @@
"skippedRowsChip": "تم تخطي {count} صف | تم تخطي {count} صفوف",
"skippedRowsTitle": "صفوف لم تُرسم",
"skippedRowsBody": "لا يحتوي {count} صف على مصدر أو هدف، أو على قيمة ليست رقمًا موجبًا، لذا لا يُرسم. | لا تحتوي {count} صفوف على مصدر أو هدف، أو على قيمة ليست رقمًا موجبًا، لذا لا تُرسم.",
"treemapSkippedRowsBody": "{count} صف له حجم ليس رقمًا موجبًا، لذلك لا يُرسم ولا يُحتسب في المجاميع. | {count} صفوف لها حجم ليس رقمًا موجبًا، لذلك لا تُرسم ولا تُحتسب في المجاميع.",
"collapsedChip": "{count} مشكلة | المشكلات: {count}",
"collapsedTitle": "{count} مشكلة في هذه اللوحة | {count} من المشكلات في هذه اللوحة",
"useTopN": "استخدام أهم N",
@@ -9929,6 +9931,9 @@
"hostmapAtLeast": "{value} أو أكثر",
"hostmapTooManyGroups": "يمكن لخريطة المضيفين التجميع حسب {count} حقول كحد أقصى",
"treemapTooManyLevels": "يمكن للمخطط الشجري أن يتداخل حتى {count} مستويات كحد أقصى",
"treemapOneQuery": "يعرض مخطط الشجرة مقياسًا واحدًا، لذا يقبل استعلامًا مرئيًا واحدًا فقط. احذف الاستعلامات الأخرى أو أخفها.",
"categoryNullGroup": "(null)",
"categoryEmptyGroup": "(فارغ)",
"stateTimelineStart": "البداية",
"stateTimelineEnd": "النهاية",
"stateTimelineDuration": "المدة",
+5
View File
@@ -8223,6 +8223,7 @@
"hostmapGroupByHint": "Bis zu zwei Felder hinzufügen",
"hostmapCellName": "Zellenname",
"hostmapCellGroup": "Zellengruppe",
"treemapTilePath": "Kachelpfad",
"stateTimelineDisplay": "Darstellung",
"stateTimelineDisplayTooltip": "Bänder fassen gleiche Werte zu einem Balken zusammen; Zellen zeichnen einen Block pro Zeitintervall.",
"stateTimelineDisplayBands": "Bänder",
@@ -9634,6 +9635,7 @@
"skippedRowsChip": "{count} Zeile übersprungen | {count} Zeilen übersprungen",
"skippedRowsTitle": "Zeilen nicht gezeichnet",
"skippedRowsBody": "{count} Zeile hat keine Quelle, kein Ziel oder einen Wert, der keine positive Zahl ist, und wird daher nicht gezeichnet. | {count} Zeilen haben keine Quelle, kein Ziel oder einen Wert, der keine positive Zahl ist, und werden daher nicht gezeichnet.",
"treemapSkippedRowsBody": "{count} Zeile hat eine Größe, die keine positive Zahl ist, daher wird sie nicht gezeichnet und nicht in den Summen gezählt. | {count} Zeilen haben eine Größe, die keine positive Zahl ist, daher werden sie nicht gezeichnet und nicht in den Summen gezählt.",
"collapsedChip": "{count} Problem | {count} Probleme",
"collapsedTitle": "{count} Problem in diesem Panel | {count} Probleme in diesem Panel",
"useTopN": "Top N verwenden",
@@ -9929,6 +9931,9 @@
"hostmapAtLeast": "{value} oder mehr",
"hostmapTooManyGroups": "Die Host-Map kann nach höchstens {count} Feldern gruppieren",
"treemapTooManyLevels": "Die Treemap kann höchstens {count} Ebenen verschachteln",
"treemapOneQuery": "Eine Treemap zeigt eine Kennzahl und nimmt daher nur eine sichtbare Abfrage an. Entfernen oder verbergen Sie die anderen Abfragen.",
"categoryNullGroup": "(null)",
"categoryEmptyGroup": "(leer)",
"stateTimelineStart": "Start",
"stateTimelineEnd": "Ende",
"stateTimelineDuration": "Dauer",
+5
View File
@@ -8385,6 +8385,7 @@
"hostmapGroupByHint": "Add up to two fields",
"hostmapCellName": "Cell name",
"hostmapCellGroup": "Cell group",
"treemapTilePath": "Tile path",
"stateTimelineDisplay": "Display",
"stateTimelineDisplayTooltip": "Bands join equal values into one bar; cells draw one block per time bucket.",
"stateTimelineDisplayBands": "Bands",
@@ -9794,6 +9795,7 @@
"skippedRowsChip": "{count} row skipped | {count} rows skipped",
"skippedRowsTitle": "Rows not drawn",
"skippedRowsBody": "{count} row has no source or target, or a value that is not a positive number, so it is not drawn. | {count} rows have no source or target, or a value that is not a positive number, so they are not drawn.",
"treemapSkippedRowsBody": "{count} row has a size that is not a positive number, so it is not drawn or counted in the totals. | {count} rows have a size that is not a positive number, so they are not drawn or counted in the totals.",
"collapsedChip": "{count} issue | {count} issues",
"collapsedTitle": "{count} issue on this panel | {count} issues on this panel",
"useTopN": "Use Top N",
@@ -10089,6 +10091,9 @@
"hostmapAtLeast": "{value} or more",
"hostmapTooManyGroups": "Host map can group by at most {count} fields",
"treemapTooManyLevels": "Treemap can nest at most {count} levels",
"treemapOneQuery": "Treemap draws one measure, so it takes one visible query. Remove or hide the other queries.",
"categoryNullGroup": "(null)",
"categoryEmptyGroup": "(empty)",
"stateTimelineStart": "Start",
"stateTimelineEnd": "End",
"stateTimelineDuration": "Duration",
+5
View File
@@ -8223,6 +8223,7 @@
"hostmapGroupByHint": "Añade hasta dos campos",
"hostmapCellName": "Nombre de la celda",
"hostmapCellGroup": "Grupo de la celda",
"treemapTilePath": "Ruta del mosaico",
"stateTimelineDisplay": "Visualización",
"stateTimelineDisplayTooltip": "Las bandas unen valores iguales en una barra; las celdas dibujan un bloque por intervalo de tiempo.",
"stateTimelineDisplayBands": "Bandas",
@@ -9634,6 +9635,7 @@
"skippedRowsChip": "{count} fila omitida | {count} filas omitidas",
"skippedRowsTitle": "Filas no dibujadas",
"skippedRowsBody": "{count} fila no tiene origen ni destino, o tiene un valor que no es un número positivo, por lo que no se dibuja. | {count} filas no tienen origen ni destino, o tienen un valor que no es un número positivo, por lo que no se dibujan.",
"treemapSkippedRowsBody": "{count} fila tiene un tamaño que no es un número positivo, por lo que no se dibuja ni se cuenta en los totales. | {count} filas tienen un tamaño que no es un número positivo, por lo que no se dibujan ni se cuentan en los totales.",
"collapsedChip": "{count} problema | {count} problemas",
"collapsedTitle": "{count} problema en este panel | {count} problemas en este panel",
"useTopN": "Usar Top N",
@@ -9929,6 +9931,9 @@
"hostmapAtLeast": "{value} o más",
"hostmapTooManyGroups": "El mapa de hosts puede agrupar por un máximo de {count} campos",
"treemapTooManyLevels": "El mapa de árbol admite como máximo {count} niveles",
"treemapOneQuery": "Un treemap muestra una sola medida, por lo que admite una sola consulta visible. Elimine u oculte las demás consultas.",
"categoryNullGroup": "(null)",
"categoryEmptyGroup": "(vacío)",
"stateTimelineStart": "Inicio",
"stateTimelineEnd": "Fin",
"stateTimelineDuration": "Duración",
+5
View File
@@ -8223,6 +8223,7 @@
"hostmapGroupByHint": "Ajoutez jusqu'à deux champs",
"hostmapCellName": "Nom de la cellule",
"hostmapCellGroup": "Groupe de la cellule",
"treemapTilePath": "Chemin de la tuile",
"stateTimelineDisplay": "Affichage",
"stateTimelineDisplayTooltip": "Les bandes regroupent les valeurs égales en une barre ; les cellules dessinent un bloc par intervalle de temps.",
"stateTimelineDisplayBands": "Bandes",
@@ -9634,6 +9635,7 @@
"skippedRowsChip": "{count} ligne ignorée | {count} lignes ignorées",
"skippedRowsTitle": "Lignes non dessinées",
"skippedRowsBody": "{count} ligne n'a pas de source ni de cible, ou a une valeur qui n'est pas un nombre positif ; elle n'est donc pas dessinée. | {count} lignes n'ont pas de source ni de cible, ou ont une valeur qui n'est pas un nombre positif ; elles ne sont donc pas dessinées.",
"treemapSkippedRowsBody": "{count} ligne a une taille qui n'est pas un nombre positif, elle n'est donc ni dessinée ni comptée dans les totaux. | {count} lignes ont une taille qui n'est pas un nombre positif, elles ne sont donc ni dessinées ni comptées dans les totaux.",
"collapsedChip": "{count} problème | {count} problèmes",
"collapsedTitle": "{count} problème sur ce panneau | {count} problèmes sur ce panneau",
"useTopN": "Utiliser Top N",
@@ -9929,6 +9931,9 @@
"hostmapAtLeast": "{value} ou plus",
"hostmapTooManyGroups": "La carte des hôtes peut regrouper au maximum {count} champs",
"treemapTooManyLevels": "Le treemap peut imbriquer au plus {count} niveaux",
"treemapOneQuery": "Un treemap affiche une seule mesure et n'accepte donc qu'une requête visible. Supprimez ou masquez les autres requêtes.",
"categoryNullGroup": "(null)",
"categoryEmptyGroup": "(vide)",
"stateTimelineStart": "Début",
"stateTimelineEnd": "Fin",
"stateTimelineDuration": "Durée",
+5
View File
@@ -8223,6 +8223,7 @@
"hostmapGroupByHint": "Aggiungi fino a due campi",
"hostmapCellName": "Nome cella",
"hostmapCellGroup": "Gruppo cella",
"treemapTilePath": "Percorso del riquadro",
"stateTimelineDisplay": "Visualizzazione",
"stateTimelineDisplayTooltip": "Le bande uniscono i valori uguali in una barra; le celle disegnano un blocco per intervallo di tempo.",
"stateTimelineDisplayBands": "Bande",
@@ -9634,6 +9635,7 @@
"skippedRowsChip": "{count} riga ignorata | {count} righe ignorate",
"skippedRowsTitle": "Righe non disegnate",
"skippedRowsBody": "{count} riga non ha un'origine o una destinazione, oppure un valore che non è un numero positivo, quindi non viene disegnata. | {count} righe non hanno un'origine o una destinazione, oppure un valore che non è un numero positivo, quindi non vengono disegnate.",
"treemapSkippedRowsBody": "{count} riga ha una dimensione che non è un numero positivo, quindi non viene disegnata né conteggiata nei totali. | {count} righe hanno una dimensione che non è un numero positivo, quindi non vengono disegnate né conteggiate nei totali.",
"collapsedChip": "{count} problema | {count} problemi",
"collapsedTitle": "{count} problema su questo pannello | {count} problemi su questo pannello",
"useTopN": "Usa Top N",
@@ -9929,6 +9931,9 @@
"hostmapAtLeast": "{value} o più",
"hostmapTooManyGroups": "La mappa host può raggruppare per un massimo di {count} campi",
"treemapTooManyLevels": "La treemap può annidare al massimo {count} livelli",
"treemapOneQuery": "Una treemap mostra una sola misura, quindi accetta una sola query visibile. Rimuovi o nascondi le altre query.",
"categoryNullGroup": "(null)",
"categoryEmptyGroup": "(vuoto)",
"stateTimelineStart": "Inizio",
"stateTimelineEnd": "Fine",
"stateTimelineDuration": "Durata",
+5
View File
@@ -8223,6 +8223,7 @@
"hostmapGroupByHint": "最大 2 つまでフィールドを追加できます",
"hostmapCellName": "セル名",
"hostmapCellGroup": "セルグループ",
"treemapTilePath": "タイルのパス",
"stateTimelineDisplay": "表示",
"stateTimelineDisplayTooltip": "バンドは同じ値を1本のバーにまとめ、セルは時間バケットごとに1ブロックを描画します。",
"stateTimelineDisplayBands": "バンド",
@@ -9634,6 +9635,7 @@
"skippedRowsChip": "{count} 行をスキップしました | {count} 行をスキップしました",
"skippedRowsTitle": "描画されない行",
"skippedRowsBody": "{count} 行にはソースまたはターゲットがないか、正の数ではない値が含まれているため、描画されません。 | {count} 行にはソースまたはターゲットがないか、正の数ではない値が含まれているため、描画されません。",
"treemapSkippedRowsBody": "{count} 行のサイズが正の数ではないため、描画されず合計にも含まれません。 | {count} 行のサイズが正の数ではないため、描画されず合計にも含まれません。",
"collapsedChip": "{count} 件の問題 | {count} 件の問題",
"collapsedTitle": "このパネルに {count} 件の問題 | このパネルに {count} 件の問題",
"useTopN": "Top N を使用",
@@ -9929,6 +9931,9 @@
"hostmapAtLeast": "{value} 以上",
"hostmapTooManyGroups": "ホストマップでグループ化できるフィールドは最大 {count} 個です",
"treemapTooManyLevels": "ツリーマップの階層は最大 {count} までです",
"treemapOneQuery": "ツリーマップは 1 つの指標を表示するため、表示できるクエリは 1 つだけです。他のクエリを削除するか非表示にしてください。",
"categoryNullGroup": "(null)",
"categoryEmptyGroup": "(空)",
"stateTimelineStart": "開始",
"stateTimelineEnd": "終了",
"stateTimelineDuration": "期間",
+5
View File
@@ -8223,6 +8223,7 @@
"hostmapGroupByHint": "필드를 최대 두 개까지 추가하세요",
"hostmapCellName": "셀 이름",
"hostmapCellGroup": "셀 그룹",
"treemapTilePath": "타일 경로",
"stateTimelineDisplay": "표시",
"stateTimelineDisplayTooltip": "밴드는 같은 값을 하나의 막대로 합치고, 셀은 시간 구간마다 블록 하나를 그립니다.",
"stateTimelineDisplayBands": "밴드",
@@ -9634,6 +9635,7 @@
"skippedRowsChip": "{count}개 행 건너뜀 | {count}개 행 건너뜀",
"skippedRowsTitle": "그려지지 않은 행",
"skippedRowsBody": "{count}개 행에 소스 또는 대상이 없거나 양수가 아닌 값이 있어 그려지지 않습니다. | {count}개 행에 소스 또는 대상이 없거나 양수가 아닌 값이 있어 그려지지 않습니다.",
"treemapSkippedRowsBody": "{count}개 행의 크기가 양수가 아니므로 그려지지 않고 합계에도 포함되지 않습니다. | {count}개 행의 크기가 양수가 아니므로 그려지지 않고 합계에도 포함되지 않습니다.",
"collapsedChip": "{count}개 문제 | {count}개 문제",
"collapsedTitle": "이 패널의 문제 {count}개 | 이 패널의 문제 {count}개",
"useTopN": "Top N 사용",
@@ -9929,6 +9931,9 @@
"hostmapAtLeast": "{value} 이상",
"hostmapTooManyGroups": "호스트 맵은 최대 {count}개 필드로 그룹화할 수 있습니다",
"treemapTooManyLevels": "트리맵은 최대 {count}개 수준까지 중첩할 수 있습니다",
"treemapOneQuery": "트리맵은 하나의 측정값을 표시하므로 표시되는 쿼리는 하나만 사용할 수 있습니다. 다른 쿼리를 제거하거나 숨기세요.",
"categoryNullGroup": "(null)",
"categoryEmptyGroup": "(비어 있음)",
"stateTimelineStart": "시작",
"stateTimelineEnd": "끝",
"stateTimelineDuration": "기간",
+5
View File
@@ -8223,6 +8223,7 @@
"hostmapGroupByHint": "Voeg maximaal twee velden toe",
"hostmapCellName": "Celnaam",
"hostmapCellGroup": "Celgroep",
"treemapTilePath": "Tegelpad",
"stateTimelineDisplay": "Weergave",
"stateTimelineDisplayTooltip": "Banden voegen gelijke waarden samen tot één balk; cellen tekenen één blok per tijdsinterval.",
"stateTimelineDisplayBands": "Banden",
@@ -9634,6 +9635,7 @@
"skippedRowsChip": "{count} rij overgeslagen | {count} rijen overgeslagen",
"skippedRowsTitle": "Niet-getekende rijen",
"skippedRowsBody": "{count} rij heeft geen bron of doel, of een waarde die geen positief getal is, en wordt daarom niet getekend. | {count} rijen hebben geen bron of doel, of een waarde die geen positief getal is, en worden daarom niet getekend.",
"treemapSkippedRowsBody": "{count} rij heeft een grootte die geen positief getal is, dus wordt niet getekend of meegeteld in de totalen. | {count} rijen hebben een grootte die geen positief getal is, dus worden niet getekend of meegeteld in de totalen.",
"collapsedChip": "{count} probleem | {count} problemen",
"collapsedTitle": "{count} probleem op dit paneel | {count} problemen op dit paneel",
"useTopN": "Top N gebruiken",
@@ -9929,6 +9931,9 @@
"hostmapAtLeast": "{value} of meer",
"hostmapTooManyGroups": "Hostmap kan op maximaal {count} velden groeperen",
"treemapTooManyLevels": "De treemap kan maximaal {count} niveaus nesten",
"treemapOneQuery": "Een treemap toont één maat en accepteert daarom één zichtbare query. Verwijder of verberg de andere query's.",
"categoryNullGroup": "(null)",
"categoryEmptyGroup": "(leeg)",
"stateTimelineStart": "Start",
"stateTimelineEnd": "Einde",
"stateTimelineDuration": "Duur",
+5
View File
@@ -8223,6 +8223,7 @@
"hostmapGroupByHint": "Dodaj maksymalnie dwa pola",
"hostmapCellName": "Nazwa komórki",
"hostmapCellGroup": "Grupa komórki",
"treemapTilePath": "Ścieżka kafelka",
"stateTimelineDisplay": "Wyświetlanie",
"stateTimelineDisplayTooltip": "Pasma łączą równe wartości w jeden pasek; komórki rysują jeden blok na przedział czasu.",
"stateTimelineDisplayBands": "Pasma",
@@ -9634,6 +9635,7 @@
"skippedRowsChip": "{count} wiersz pominięty | {count} wierszy pominięto",
"skippedRowsTitle": "Pominięte wiersze",
"skippedRowsBody": "{count} wiersz: brak źródła lub celu albo wartość nie jest liczbą dodatnią, więc nie jest rysowany. | {count} wierszy: brak źródła lub celu albo wartość nie jest liczbą dodatnią, więc nie są rysowane.",
"treemapSkippedRowsBody": "{count} wiersz ma rozmiar, który nie jest liczbą dodatnią, więc nie jest rysowany ani liczony w sumach. | {count} wierszy ma rozmiar, który nie jest liczbą dodatnią, więc nie są rysowane ani liczone w sumach.",
"collapsedChip": "{count} problem | problemy: {count}",
"collapsedTitle": "{count} problem na tym panelu | Problemy na tym panelu: {count}",
"useTopN": "Użyj Top N",
@@ -9929,6 +9931,9 @@
"hostmapAtLeast": "{value} lub więcej",
"hostmapTooManyGroups": "Mapa hostów może grupować według co najwyżej {count} pól",
"treemapTooManyLevels": "Mapa drzewa może zagnieżdżać najwyżej {count} poziomów",
"treemapOneQuery": "Treemap pokazuje jedną miarę, więc przyjmuje tylko jedno widoczne zapytanie. Usuń lub ukryj pozostałe zapytania.",
"categoryNullGroup": "(null)",
"categoryEmptyGroup": "(puste)",
"stateTimelineStart": "Początek",
"stateTimelineEnd": "Koniec",
"stateTimelineDuration": "Czas trwania",
+5
View File
@@ -8223,6 +8223,7 @@
"hostmapGroupByHint": "Adicione até dois campos",
"hostmapCellName": "Nome da célula",
"hostmapCellGroup": "Grupo da célula",
"treemapTilePath": "Caminho do bloco",
"stateTimelineDisplay": "Apresentação",
"stateTimelineDisplayTooltip": "As faixas juntam valores iguais numa barra; as células desenham um bloco por intervalo de tempo.",
"stateTimelineDisplayBands": "Faixas",
@@ -9634,6 +9635,7 @@
"skippedRowsChip": "{count} linha ignorada | {count} linhas ignoradas",
"skippedRowsTitle": "Linhas não desenhadas",
"skippedRowsBody": "{count} linha não tem origem ou destino, ou tem um valor que não é um número positivo, pelo que não é desenhada. | {count} linhas não têm origem ou destino, ou têm um valor que não é um número positivo, pelo que não são desenhadas.",
"treemapSkippedRowsBody": "{count} linha tem um tamanho que não é um número positivo, por isso não é desenhada nem contada nos totais. | {count} linhas têm um tamanho que não é um número positivo, por isso não são desenhadas nem contadas nos totais.",
"collapsedChip": "{count} problema | {count} problemas",
"collapsedTitle": "{count} problema neste painel | {count} problemas neste painel",
"useTopN": "Usar Top N",
@@ -9929,6 +9931,9 @@
"hostmapAtLeast": "{value} ou mais",
"hostmapTooManyGroups": "O mapa de hosts pode agrupar por, no máximo, {count} campos",
"treemapTooManyLevels": "O mapa de árvore pode aninhar no máximo {count} níveis",
"treemapOneQuery": "Um treemap mostra uma única medida, por isso aceita apenas uma consulta visível. Remova ou oculte as outras consultas.",
"categoryNullGroup": "(null)",
"categoryEmptyGroup": "(vazio)",
"stateTimelineStart": "Início",
"stateTimelineEnd": "Fim",
"stateTimelineDuration": "Duração",
+5
View File
@@ -8223,6 +8223,7 @@
"hostmapGroupByHint": "Добавьте до двух полей",
"hostmapCellName": "Имя ячейки",
"hostmapCellGroup": "Группа ячеек",
"treemapTilePath": "Путь плитки",
"stateTimelineDisplay": "Отображение",
"stateTimelineDisplayTooltip": "Полосы объединяют одинаковые значения в одну полосу; ячейки рисуют один блок на каждый интервал времени.",
"stateTimelineDisplayBands": "Полосы",
@@ -9634,6 +9635,7 @@
"skippedRowsChip": "{count} строка пропущена | Пропущено строк: {count}",
"skippedRowsTitle": "Строки не отображены",
"skippedRowsBody": "{count} строка не имеет источника или цели либо имеет значение, не являющееся положительным числом, поэтому не отображается. | Пропущено строк: {count}. Нет источника или цели либо значение не является положительным числом, поэтому они не отображаются.",
"treemapSkippedRowsBody": "{count} строка имеет размер, который не является положительным числом, поэтому она не отображается и не учитывается в итогах. | {count} строк имеют размер, который не является положительным числом, поэтому они не отображаются и не учитываются в итогах.",
"collapsedChip": "{count} проблема | Проблем: {count}",
"collapsedTitle": "{count} проблема на этой панели | Проблем на этой панели: {count}",
"useTopN": "Использовать топ N",
@@ -9929,6 +9931,9 @@
"hostmapAtLeast": "{value} или больше",
"hostmapTooManyGroups": "Карта хостов поддерживает группировку не более чем по {count} полям",
"treemapTooManyLevels": "Древовидная карта может иметь не более {count} уровней вложенности",
"treemapOneQuery": "Treemap показывает одну меру, поэтому принимает только один видимый запрос. Удалите или скройте остальные запросы.",
"categoryNullGroup": "(null)",
"categoryEmptyGroup": "(пусто)",
"stateTimelineStart": "Начало",
"stateTimelineEnd": "Конец",
"stateTimelineDuration": "Длительность",
+5
View File
@@ -8222,6 +8222,7 @@
"hostmapGroupByHint": "Add up to two fields",
"hostmapCellName": "Cell name",
"hostmapCellGroup": "Cell group",
"treemapTilePath": "เส้นทางของไทล์",
"stateTimelineDisplay": "การแสดงผล",
"stateTimelineDisplayTooltip": "แถบจะรวมค่าที่เท่ากันไว้เป็นแท่งเดียว ส่วนเซลล์จะวาดหนึ่งบล็อกต่อหนึ่งบัคเก็ตเวลา",
"stateTimelineDisplayBands": "แถบ",
@@ -9631,6 +9632,7 @@
"skippedRowsChip": "{count} row skipped | {count} rows skipped",
"skippedRowsTitle": "Rows not drawn",
"skippedRowsBody": "{count} row has no source or target, or a value that is not a positive number, so it is not drawn. | {count} rows have no source or target, or a value that is not a positive number, so they are not drawn.",
"treemapSkippedRowsBody": "{count} แถวมีขนาดที่ไม่ใช่จำนวนบวก จึงไม่ถูกวาดและไม่นับรวมในยอดรวม | {count} แถวมีขนาดที่ไม่ใช่จำนวนบวก จึงไม่ถูกวาดและไม่นับรวมในยอดรวม",
"collapsedChip": "{count} issue | {count} issues",
"collapsedTitle": "{count} issue on this panel | {count} issues on this panel",
"useTopN": "Use Top N",
@@ -9926,6 +9928,9 @@
"hostmapAtLeast": "{value} or more",
"hostmapTooManyGroups": "Host map can group by at most {count} fields",
"treemapTooManyLevels": "Treemap ซ้อนได้สูงสุด {count} ระดับ",
"treemapOneQuery": "Treemap แสดงค่าวัดเพียงค่าเดียว จึงรับได้เพียงหนึ่งคิวรีที่มองเห็น ลบหรือซ่อนคิวรีอื่น",
"categoryNullGroup": "(null)",
"categoryEmptyGroup": "(empty)",
"stateTimelineStart": "Start",
"stateTimelineEnd": "End",
"stateTimelineDuration": "ระยะเวลา",
+5
View File
@@ -8223,6 +8223,7 @@
"hostmapGroupByHint": "En fazla iki alan ekleyin",
"hostmapCellName": "Hücre adı",
"hostmapCellGroup": "Hücre grubu",
"treemapTilePath": "Kutucuk yolu",
"stateTimelineDisplay": "Görünüm",
"stateTimelineDisplayTooltip": "Bantlar eşit değerleri tek bir çubukta birleştirir; hücreler her zaman aralığı için bir blok çizer.",
"stateTimelineDisplayBands": "Bantlar",
@@ -9634,6 +9635,7 @@
"skippedRowsChip": "{count} satır atlandı | {count} satır atlandı",
"skippedRowsTitle": "Çizilmeyen satırlar",
"skippedRowsBody": "{count} satırın kaynağı veya hedefi yok ya da değeri pozitif bir sayı değil; bu nedenle çizilmedi. | {count} satırın kaynağı veya hedefi yok ya da değeri pozitif bir sayı değil; bu nedenle çizilmedi.",
"treemapSkippedRowsBody": "{count} satırın boyutu pozitif bir sayı değil, bu yüzden çizilmiyor ve toplamlara dahil edilmiyor. | {count} satırın boyutu pozitif bir sayı değil, bu yüzden çizilmiyor ve toplamlara dahil edilmiyor.",
"collapsedChip": "{count} sorun | {count} sorun",
"collapsedTitle": "Bu panelde {count} sorun | Bu panelde {count} sorun",
"useTopN": "İlk N'yi kullan",
@@ -9929,6 +9931,9 @@
"hostmapAtLeast": "{value} veya daha fazla",
"hostmapTooManyGroups": "Ana bilgisayar haritası en fazla {count} alana göre gruplandırabilir",
"treemapTooManyLevels": "Ağaç haritası en fazla {count} düzey iç içe olabilir",
"treemapOneQuery": "Treemap tek bir ölçü gösterir, bu yüzden yalnızca bir görünür sorgu alır. Diğer sorguları kaldırın veya gizleyin.",
"categoryNullGroup": "(null)",
"categoryEmptyGroup": "(boş)",
"stateTimelineStart": "Başlangıç",
"stateTimelineEnd": "Bitiş",
"stateTimelineDuration": "Süre",
+5
View File
@@ -8223,6 +8223,7 @@
"hostmapGroupByHint": "Thêm tối đa hai trường",
"hostmapCellName": "Tên ô",
"hostmapCellGroup": "Nhóm ô",
"treemapTilePath": "Đường dẫn ô",
"stateTimelineDisplay": "Hiển thị",
"stateTimelineDisplayTooltip": "Dải gộp các giá trị bằng nhau thành một thanh; ô vẽ một khối cho mỗi khoảng thời gian.",
"stateTimelineDisplayBands": "Dải",
@@ -9634,6 +9635,7 @@
"skippedRowsChip": "{count} hàng bị bỏ qua | {count} hàng bị bỏ qua",
"skippedRowsTitle": "Hàng không được vẽ",
"skippedRowsBody": "{count} hàng không có nguồn hoặc đích, hoặc có giá trị không phải số dương, nên không được vẽ. | {count} hàng không có nguồn hoặc đích, hoặc có giá trị không phải số dương, nên không được vẽ.",
"treemapSkippedRowsBody": "{count} hàng có kích thước không phải là số dương nên không được vẽ và không được tính vào tổng. | {count} hàng có kích thước không phải là số dương nên không được vẽ và không được tính vào tổng.",
"collapsedChip": "{count} vấn đề | {count} vấn đề",
"collapsedTitle": "{count} vấn đề trên panel này | {count} vấn đề trên panel này",
"useTopN": "Dùng Top N",
@@ -9929,6 +9931,9 @@
"hostmapAtLeast": "{value} trở lên",
"hostmapTooManyGroups": "Bản đồ máy chủ chỉ có thể nhóm theo tối đa {count} trường",
"treemapTooManyLevels": "Biểu đồ dạng cây lồng tối đa {count} cấp",
"treemapOneQuery": "Treemap hiển thị một thước đo nên chỉ nhận một truy vấn hiển thị. Hãy xóa hoặc ẩn các truy vấn khác.",
"categoryNullGroup": "(null)",
"categoryEmptyGroup": "(trống)",
"stateTimelineStart": "Bắt đầu",
"stateTimelineEnd": "Kết thúc",
"stateTimelineDuration": "Thời lượng",
+5
View File
@@ -8223,6 +8223,7 @@
"hostmapGroupByHint": "最多添加两个字段",
"hostmapCellName": "单元格名称",
"hostmapCellGroup": "单元格分组",
"treemapTilePath": "图块路径",
"stateTimelineDisplay": "显示方式",
"stateTimelineDisplayTooltip": "色带将相同的值合并为一条;单元格为每个时间段绘制一个色块。",
"stateTimelineDisplayBands": "色带",
@@ -9634,6 +9635,7 @@
"skippedRowsChip": "{count} 行已跳过 | {count} 行已跳过",
"skippedRowsTitle": "未绘制的行",
"skippedRowsBody": "{count} 行没有源或目标,或者其值不是正数,因此未绘制。 | {count} 行没有源或目标,或者其值不是正数,因此未绘制。",
"treemapSkippedRowsBody": "{count} 行的大小不是正数,因此不会绘制,也不计入总计。 | {count} 行的大小不是正数,因此不会绘制,也不计入总计。",
"collapsedChip": "{count} 个问题 | {count} 个问题",
"collapsedTitle": "此面板上有 {count} 个问题 | 此面板上有 {count} 个问题",
"useTopN": "使用 Top N",
@@ -9929,6 +9931,9 @@
"hostmapAtLeast": "{value} 及以上",
"hostmapTooManyGroups": "主机地图最多可按 {count} 个字段分组",
"treemapTooManyLevels": "矩形树图最多可嵌套 {count} 层",
"treemapOneQuery": "矩形树图只显示一个度量,因此只能有一个可见查询。请删除或隐藏其他查询。",
"categoryNullGroup": "(null)",
"categoryEmptyGroup": "(空)",
"stateTimelineStart": "开始",
"stateTimelineEnd": "结束",
"stateTimelineDuration": "持续时间",
+5
View File
@@ -8223,6 +8223,7 @@
"hostmapGroupByHint": "最多可新增兩個欄位",
"hostmapCellName": "儲存格名稱",
"hostmapCellGroup": "儲存格群組",
"treemapTilePath": "圖塊路徑",
"stateTimelineDisplay": "顯示方式",
"stateTimelineDisplayTooltip": "色帶將相同的值合併為一條;儲存格為每個時間區段繪製一個色塊。",
"stateTimelineDisplayBands": "色帶",
@@ -9629,6 +9630,7 @@
"skippedRowsChip": "{count} 列已略過 | {count} 列已略過",
"skippedRowsTitle": "未繪製的列",
"skippedRowsBody": "{count} 列沒有來源或目標,或其值不是正數,因此不會繪製。 | {count} 列沒有來源或目標,或其值不是正數,因此不會繪製。",
"treemapSkippedRowsBody": "{count} 列的大小不是正數,因此不會繪製,也不計入總計。 | {count} 列的大小不是正數,因此不會繪製,也不計入總計。",
"collapsedChip": "{count} 個問題 | {count} 個問題",
"collapsedTitle": "此面板有 {count} 個問題 | 此面板有 {count} 個問題",
"useTopN": "使用 Top N",
@@ -9924,6 +9926,9 @@
"hostmapAtLeast": "{value} 或以上",
"hostmapTooManyGroups": "主機地圖最多只能依 {count} 個欄位分組",
"treemapTooManyLevels": "矩形樹狀圖最多可巢狀 {count} 層",
"treemapOneQuery": "矩形樹狀圖只顯示一個度量,因此只能有一個可見查詢。請刪除或隱藏其他查詢。",
"categoryNullGroup": "(null)",
"categoryEmptyGroup": "(空)",
"stateTimelineStart": "開始",
"stateTimelineEnd": "結束",
"stateTimelineDuration": "持續時間",
+26 -2
View File
@@ -60,7 +60,7 @@ const rows = [
describe("category nodes", () => {
it("nests by x then breakdown, sums values and sorts tiles largest first", () => {
const nodes = buildTreemapNodes(
const { nodes } = buildTreemapNodes(
panel("pie", { x: [serviceX], y: [count], breakdown: [regionB] }),
[rows],
);
@@ -75,10 +75,34 @@ describe("category nodes", () => {
});
it("makes flat tiles without a breakdown", () => {
const nodes = buildTreemapNodes(panel("pie", { x: [serviceX], y: [count] }), [rows]);
const { nodes } = buildTreemapNodes(panel("pie", { x: [serviceX], y: [count] }), [rows]);
expect(nodes).toEqual([
{ name: "web", value: 50, path: ["web"] },
{ name: "api", value: 40, path: ["api"] },
]);
});
it('keeps a missing, an empty and a literal "(null)" group apart, each with its own value', () => {
const { nodes } = buildTreemapNodes(panel("pie", { x: [serviceX], y: [count] }), [
[
{ x_axis_1: null, y_axis_1: 3 },
{ x_axis_1: "", y_axis_1: 2 },
{ y_axis_1: 1 },
{ x_axis_1: "(null)", y_axis_1: 7 },
],
]);
expect(nodes).toEqual([
{ name: "(null)", value: 7, path: ["(null)"] },
{ name: "(null)", rawName: null, value: 4, path: ["(null)"], rawPath: [null] },
{ name: "(empty)", rawName: "", value: 2, path: ["(empty)"], rawPath: [""] },
]);
});
it("counts the rows without a positive value it leaves out of the totals", () => {
const { nodes, skippedRows } = buildTreemapNodes(panel("pie", { x: [serviceX], y: [count] }), [
[...rows, { x_axis_1: "api", y_axis_1: -5 }],
]);
expect(skippedRows).toBe(3);
expect(nodes.find((node) => node.name === "api")?.value).toBe(40);
});
});
+52 -15
View File
@@ -13,6 +13,7 @@
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
import { gt } from "@/types/i18n";
import { getDataValue } from "./aliasUtils";
import { getSeriesColor } from "./colorPalette";
import { echartsPaletteColor } from "./thresholds";
@@ -20,8 +21,12 @@ import { echartsPaletteColor } from "./thresholds";
/** A category tree node; leaves carry the summed value, parents add up their children. */
export interface TreemapNode {
name: string;
/** The group's own value when the shown name stands in for a missing (null) or empty one. */
rawName?: string | null;
value: number;
path: string[];
/** The groups' own values from the root, when the shown path stands in for a missing or empty one. */
rawPath?: (string | null)[];
children?: TreemapNode[];
itemStyle?: { color: string };
label?: { color?: string; show?: boolean; rotate?: "radial" | "tangential" };
@@ -36,9 +41,27 @@ const toNumber = (value: unknown): number | null => {
const byValue = (a: TreemapNode, b: TreemapNode) => b.value - a.value;
/** Nests rows by the x fields and then the breakdown field, summing the first y field into the leaves. */
export const buildTreemapNodes = (panelSchema: any, data: any[]): TreemapNode[] => {
const root: TreemapNode = { name: "", value: 0, path: [], children: [] };
// A missing and an empty group are different answers, so each gets its own visible tile.
const groupName = (key: string | null): string => {
if (key === null) return gt("dashboard.utils.categoryNullGroup");
return key === "" ? gt("dashboard.utils.categoryEmptyGroup") : key;
};
const isStandIn = (key: string | null) => key === null || key === "";
/** The query parts the category builder reads: the group levels, the size field and whether the query is hidden. */
export interface CategoryQuery {
fields?: { x?: { alias: string }[]; y?: { alias: string }[]; breakdown?: { alias: string }[] };
config?: { hide?: boolean };
}
/** Nests rows by the x fields and then the breakdown field, summing the first y field into the leaves and counting the rows left out. */
export const buildTreemapNodes = (
panelSchema: { queries?: CategoryQuery[] } | null | undefined,
data: unknown[],
): { nodes: TreemapNode[]; skippedRows: number } => {
const root: TreemapNode = { name: "", value: 0, path: [], rawPath: [], children: [] };
let skippedRows = 0;
(panelSchema?.queries ?? []).forEach((query: any, index: number) => {
const rows = data?.[index];
const value = query?.fields?.y?.[0];
@@ -46,13 +69,29 @@ export const buildTreemapNodes = (panelSchema: any, data: any[]): TreemapNode[]
if (!Array.isArray(rows) || !value || !levels.length || query?.config?.hide) return;
rows.forEach((row: any) => {
const amount = toNumber(getDataValue(row, value.alias));
if (amount === null || amount <= 0) return;
// A tile's area is its value, so a row without a positive one cannot be drawn.
if (amount === null || amount <= 0) {
skippedRows++;
return;
}
let node = root;
levels.forEach((level: any) => {
const name = String(getDataValue(row, level.alias) ?? "");
let child = node.children!.find((candidate) => candidate.name === name);
const raw = getDataValue(row, level.alias);
const key = raw === null || raw === undefined ? null : String(raw);
// Tiles are told apart by their own value, so a real "(null)" never joins the missing group.
let child = node.children!.find(
(candidate) => candidate.rawPath![candidate.rawPath!.length - 1] === key,
);
if (!child) {
child = { name, value: 0, path: [...node.path, name], children: [] };
const name = groupName(key);
child = {
name,
...(isStandIn(key) ? { rawName: key } : {}),
value: 0,
path: [...node.path, name],
rawPath: [...node.rawPath!, key],
children: [],
};
node.children!.push(child);
}
child.value += amount;
@@ -61,14 +100,12 @@ export const buildTreemapNodes = (panelSchema: any, data: any[]): TreemapNode[]
});
});
const tidy = (nodes: TreemapNode[]): TreemapNode[] =>
nodes
.sort(byValue)
.map((node) =>
node.children?.length
? { ...node, children: tidy(node.children) }
: { name: node.name, value: node.value, path: node.path },
);
return tidy(root.children!);
nodes.sort(byValue).map(({ children, rawPath, ...node }) => ({
...node,
...(rawPath?.some(isStandIn) ? { rawPath } : {}),
...(children?.length ? { children: tidy(children) } : {}),
}));
return { nodes: tidy(root.children!), skippedRows };
};
/** Colours each named item from the panel Color palette, shading by value range; a classic palette falls back to the chart colours. */
@@ -55,6 +55,20 @@ describe("withoutEntrance", () => {
});
});
it("switches a treemap's animation off, so a data re-render cannot morph its tiles", () => {
const still = withoutEntrance({
series: [{ type: "treemap", animationDuration: 400 }, { type: "pie" }],
});
const [treemap, pie] = still.series as Record<string, unknown>[];
expect(treemap).toMatchObject({
animation: false,
animationDuration: 0,
animationDurationUpdate: 0,
});
expect(pie).toMatchObject({ animationDuration: 0, animationDurationUpdate: 0 });
expect(pie).not.toHaveProperty("animation");
});
it("adds no series to options that have none and leaves empty entries", () => {
expect(withoutEntrance({ title: { text: "x" } })).not.toHaveProperty("series");
expect(withoutEntrance({ series: [null] }).series).toEqual([null]);
+8 -2
View File
@@ -19,8 +19,14 @@ const NO_ENTRANCE = { animationDuration: 0, animationDurationUpdate: 0 };
export const withoutEntrance = (options: Record<string, unknown>): Record<string, unknown> => {
const { series } = options;
// A series' own duration overrides the root one, so each series is zeroed too.
const still = (entry: unknown) =>
entry && typeof entry === "object" ? { ...entry, ...NO_ENTRANCE } : entry;
const still = (entry: unknown) => {
if (!entry || typeof entry !== "object") return entry;
// A treemap stuck at a 0 update duration never lands a zoom; switched off, it draws every render and zoom at once.
if ((entry as { type?: unknown }).type === "treemap") {
return { ...entry, ...NO_ENTRANCE, animation: false };
}
return { ...entry, ...NO_ENTRANCE };
};
return {
...options,
...NO_ENTRANCE,
@@ -79,7 +79,7 @@ export const convertSunburstData = (
chartPanelRef?: any,
) => {
const config = panelSchema?.config ?? {};
const nodes = buildTreemapNodes(panelSchema, Array.isArray(data) ? data : []);
const { nodes } = buildTreemapNodes(panelSchema, Array.isArray(data) ? data : []);
if (!nodes.length) return { options: { series: [] }, extras: { panelId: panelSchema?.id } };
paintByPalette(nodes, config, store?.state?.theme);
@@ -36,6 +36,7 @@ const field = (alias: string, label: string, functionName: string | null = null)
label,
alias,
column: alias,
type: "build",
functionName,
args: [{ type: "field", value: { field: alias } }],
});
@@ -213,6 +214,85 @@ describe("treemap through convertPanelData", () => {
expect(options.series[0].upperLabel.show).toBe(false);
});
it("does not zoom on click when the breadcrumb that leads back out is hidden", async () => {
const { options } = await viaPanel(
panel("treemap", { x: [serviceX], y: [count] }, { treemap_show_breadcrumb: false }),
[rows],
);
expect(options.series[0].nodeClick).toBe(false);
});
it("reports the rows left out for a size that is not a positive number", async () => {
const { options, extras } = await viaPanel(panel("treemap", { x: [serviceX], y: [count] }), [
[...rows, { x_axis_1: "api", y_axis_1: -500 }],
]);
expect(extras.treemapNotice).toEqual({ skippedRows: 3 });
expect(options.series[0].data.find((node: { name: string }) => node.name === "api").value).toBe(
40,
);
});
it("draws only the first visible query of a saved multi-query panel, never a sum of measures", async () => {
const schema = panel("treemap", { x: [serviceX], y: [count] });
const second = JSON.parse(JSON.stringify(schema.queries[0]));
schema.queries = [{ ...schema.queries[0], config: { hide: true } }, second, second];
const { options } = await viaPanel(schema, [
[{ x_axis_1: "api", y_axis_1: 1000 }],
[{ x_axis_1: "api", y_axis_1: 7 }],
[{ x_axis_1: "api", y_axis_1: 500 }],
]);
expect(
options.series[0].data.map((node: { name: string; value: number }) => [
node.name,
node.value,
]),
).toEqual([["api", 7]]);
});
it("shows No Data with the skipped rows when no row has a positive size", async () => {
const { options, extras } = await viaPanel(panel("treemap", { x: [serviceX], y: [count] }), [
[
{ x_axis_1: "neg", y_axis_1: -500 },
{ x_axis_1: "zero", y_axis_1: 0 },
],
]);
expect(options.series).toEqual([]);
expect(extras.treemapNotice).toEqual({ skippedRows: 2 });
});
it("shows a count as a whole number whatever the decimals, unless a unit is set", async () => {
const label = async (size: ReturnType<typeof field>, config: Record<string, unknown>) => {
const { options } = await viaPanel(panel("treemap", { x: [serviceX], y: [size] }, config), [
rows,
]);
return options.series[0].label.formatter({ name: "api", value: 40 });
};
expect(await label(count, { decimals: undefined })).toBe("api\n40");
expect(await label(count, { decimals: 2 })).toBe("api\n40");
expect(await label(field("y_axis_1", "Bytes", "sum"), { decimals: 2 })).toBe("api\n40.00");
expect(await label(count, { decimals: 2, unit: "percent" })).toBe("api\n40.00%");
});
it("keeps the decimals of a custom SQL value labelled count", async () => {
const schema = panel("treemap", { x: [serviceX], y: [count] }, { decimals: 2 });
schema.queries[0].customQuery = true;
const { options } = await viaPanel(schema, [rows]);
expect(options.series[0].label.formatter({ name: "api", value: 12.67 })).toBe("api\n12.67");
});
it("draws every level when the breadcrumb is hidden, since a click cannot zoom", async () => {
const levels = {
x: [field("x_axis_1", "Region"), field("x_axis_2", "Service"), field("x_axis_3", "Host")],
y: [count],
};
const deep = [{ x_axis_1: "eu", x_axis_2: "api", x_axis_3: "h1", y_axis_1: 5 }];
const [series] = (
await viaPanel(panel("treemap", levels, { treemap_show_breadcrumb: false }), [deep])
).options.series;
expect(series.nodeClick).toBe(false);
expect(series.leafDepth).toBeUndefined();
});
it("gives each tile the label colour that reads on it, with no halo, and the root the body colour", async () => {
const { options } = await viaPanel(
panel("treemap", { x: [serviceX], y: [count], breakdown: [regionB] }),
+40 -12
View File
@@ -32,12 +32,19 @@ const LABEL_PADDING = 10;
const CHILD_LIGHTNESS: [number, number] = [0.35, 0.6];
const LABEL_FONT_SIZE = 12;
/** Rows the treemap left out because their size is not a positive number. */
export interface TreemapNotice {
skippedRows: number;
}
let measureContext: OffscreenCanvasRenderingContext2D | null | undefined;
const rootName = (panelSchema: any): string => {
const query = panelSchema?.queries?.[0];
const rootName = (
query: { fields?: { y?: { alias?: string }[] }; customQuery?: boolean } | undefined,
config: unknown,
): string => {
const value = query?.fields?.y?.[0];
return getFieldLabel(value, panelSchema?.config, query?.customQuery) || value?.alias || "";
return getFieldLabel(value, config, query?.customQuery) || value?.alias || "";
};
const labelContext = (): OffscreenCanvasRenderingContext2D | null => {
@@ -113,15 +120,37 @@ export const contrastLabels = (nodes: TreemapNode[]) => {
/** Converts SQL rows into a treemap: the x field names the outer tiles, the breakdown splits them. */
export const convertTreemapData = (panelSchema: any, data: any, store: any) => {
const config = panelSchema?.config ?? {};
const nodes = buildTreemapNodes(panelSchema, Array.isArray(data) ? data : []);
if (!nodes.length) return { options: { series: [] }, extras: { panelId: panelSchema?.id } };
const rows = Array.isArray(data) ? data : [];
// A tile adds up one measure, so a saved panel with more queries draws only its first visible one.
const queries: { config?: { hide?: boolean } }[] = panelSchema?.queries ?? [];
const drawn = queries.findIndex((query) => !query?.config?.hide);
const { nodes, skippedRows } = buildTreemapNodes(
{ ...panelSchema, queries: drawn < 0 ? [] : [panelSchema.queries[drawn]] },
drawn < 0 ? [] : [rows[drawn]],
);
const treemapNotice: TreemapNotice = { skippedRows };
if (!nodes.length) {
return { options: { series: [] }, extras: { panelId: panelSchema?.id, treemapNotice } };
}
paintByPalette(nodes, config, store?.state?.theme);
contrastLabels(nodes);
const drawnQuery = panelSchema.queries[drawn];
const size = drawnQuery?.fields?.y?.[0];
// A builder count is a whole number; in custom SQL "count" is only the field's label.
const isBuilderCount =
!drawnQuery?.customQuery &&
size?.type === "build" &&
!size?.isDerived &&
size?.functionName === "count";
const decimals =
isBuilderCount && (!config.unit || config.unit === "default") ? 0 : config.decimals;
const format = (value: unknown) =>
formatUnitValue(getUnitValue(value, config.unit, config.unit_custom, config.decimals));
formatUnitValue(getUnitValue(value, config.unit, config.unit_custom, decimals));
const nested = nodes.some((node) => node.children?.length);
const hasDrilldown = (config.drilldown?.length ?? 0) > 0;
// A click opens the drilldown menu instead, and without the breadcrumb a zoom has no way back.
const zooms = !hasDrilldown && config.treemap_show_breadcrumb !== false;
const surface = chartColor("--color-surface-base");
const options = {
@@ -143,17 +172,16 @@ export const convertTreemapData = (panelSchema: any, data: any, store: any) => {
{
type: "treemap",
// The breadcrumb's root reads the series name.
name: panelSchema?.title || rootName(panelSchema),
name: panelSchema?.title || rootName(panelSchema.queries[drawn], config),
data: nodes,
top: 8,
left: 8,
right: 8,
bottom: config.treemap_show_breadcrumb === false ? 8 : 32,
roam: false,
// Without a leaf depth the breadcrumb names whatever tile sits under the panel centre; a drilldown blocks zooming, so then every level is drawn.
leafDepth: !nested ? 1 : hasDrilldown ? undefined : 2,
// A click opens the drilldown menu, so it must not also zoom the tile away under it.
nodeClick: hasDrilldown ? false : "zoomToNode",
// Without a leaf depth the breadcrumb names whatever tile sits under the panel centre; without zooming, every level is drawn.
leafDepth: !nested ? 1 : zooms ? 2 : undefined,
nodeClick: zooms ? "zoomToNode" : false,
breadcrumb: {
show: config.treemap_show_breadcrumb !== false,
bottom: 4,
@@ -199,5 +227,5 @@ export const convertTreemapData = (panelSchema: any, data: any, store: any) => {
},
],
};
return { options, extras: { panelId: panelSchema?.id } };
return { options, extras: { panelId: panelSchema?.id, treemapNotice } };
};
+35 -9
View File
@@ -18,6 +18,7 @@ import type { IconName } from "@/lib/core/Icon/OIcon.icons";
import { addCommasToNumber } from "@/utils/formatters";
import type { RegionJoinInfo } from "./convertMapsData";
import type { SankeyNotice } from "./convertSankeyData";
import type { TreemapNotice } from "./convertTreemapData";
import type { PanelDiagnostics, SeriesLimitInfo } from "./panelDiagnostics";
export type PanelNoticeId =
@@ -50,6 +51,7 @@ export interface PanelNoticeInput {
seriesLimitMessage?: string;
seriesTotalBound?: SeriesTotalBound;
sankeyNotice?: SankeyNotice | null;
treemapNotice?: TreemapNotice | null;
serverPartial?: boolean;
partialReasons?: string[];
interrupted?: boolean;
@@ -172,6 +174,20 @@ const unmatchedRegionsNotice = (join: RegionJoinInfo, t: TranslateFn): PanelNoti
};
};
const skippedRowsNotice = (count: number, body: I18nText, t: TranslateFn): PanelNotice => ({
id: "skipped-rows",
tone: "warning",
icon: "visibility-off",
chipLabel: t(
"dashboard.panelErrorButtons.skippedRowsChip",
{ count: addCommasToNumber(count) },
count,
),
title: t("dashboard.panelErrorButtons.skippedRowsTitle"),
body,
details: [],
});
/** The header notices in severity order: errors first, then what was hidden, then what was cut short. */
export const buildPanelNotices = (input: PanelNoticeInput, t: TranslateFn): PanelNotice[] => {
const notices: PanelNotice[] = [];
@@ -219,15 +235,25 @@ export const buildPanelNotices = (input: PanelNoticeInput, t: TranslateFn): Pane
const skippedRows = input.sankeyNotice?.skippedRows ?? 0;
if (skippedRows) {
const count = addCommasToNumber(skippedRows);
notices.push({
id: "skipped-rows",
tone: "warning",
icon: "visibility-off",
chipLabel: t("dashboard.panelErrorButtons.skippedRowsChip", { count }, skippedRows),
title: t("dashboard.panelErrorButtons.skippedRowsTitle"),
body: t("dashboard.panelErrorButtons.skippedRowsBody", { count }, skippedRows),
details: [],
});
notices.push(
skippedRowsNotice(
skippedRows,
t("dashboard.panelErrorButtons.skippedRowsBody", { count }, skippedRows),
t,
),
);
}
const skippedTiles = input.treemapNotice?.skippedRows ?? 0;
if (skippedTiles) {
const count = addCommasToNumber(skippedTiles);
notices.push(
skippedRowsNotice(
skippedTiles,
t("dashboard.panelErrorButtons.treemapSkippedRowsBody", { count }, skippedTiles),
t,
),
);
}
if (input.serverPartial) {
@@ -1698,3 +1698,64 @@ describe("validatePanel on logs", () => {
expect(errors.filter((error) => /unsupported|not supported/i.test(error))).toEqual([]);
});
});
describe("validatePanel on a treemap with more than one query", () => {
const field = (alias: string) => ({
alias,
column: alias,
label: alias,
type: "raw",
rawQuery: alias,
});
const query = (hide = false) => ({
customQuery: false,
query: "SELECT 1",
fields: { x: [field("region")], y: [field("count")], breakdown: [], z: [] },
config: { hide },
});
const run = (queries: ReturnType<typeof query>[]) => {
const errors: string[] = [];
validatePanel(
gt,
{ data: { type: "treemap", queryType: "sql", config: {}, queries }, layout: {} },
errors,
true,
[],
"dashboard",
{ state: { zoConfig: {} } },
() => true,
);
return errors;
};
const oneQuery = gt("dashboard.utils.treemapOneQuery");
it("rejects two visible queries and accepts one visible beside a hidden one", () => {
expect(run([query(), query()])).toContain(oneQuery);
expect(run([query(), query(true)])).toEqual([]);
expect(run([query()])).toEqual([]);
});
it("still imports a saved multi-query treemap, which draws its first visible query", () => {
const errors = validateDashboardJson(gt, {
dashboardId: "d",
title: "t",
version: "v3",
tabs: [
{
tabId: "default",
name: "Default",
panels: [
{
type: "treemap",
id: "p-tree",
title: "t",
layout: { x: 0, y: 0, w: 1, h: 1, i: "tree" },
queries: [query(), query()],
},
],
},
],
});
expect(errors.some((error) => error.includes(oneQuery))).toBe(false);
});
});
@@ -902,6 +902,19 @@ const validatePanelContentByType = (t: TranslateFn, panel: any, errors: string[]
}
};
// Only the editor asks for one query; an imported multi-query treemap still loads and draws its first visible query.
const validateTreemapQueries = (
t: TranslateFn,
panel: { type?: string; queries?: { config?: { hide?: boolean } }[] } | null | undefined,
errors: string[],
) => {
if (panel?.type !== "treemap") return;
const queries = panel?.queries ?? [];
if (queries.filter((query) => !query?.config?.hide).length > 1) {
errors.push(t("dashboard.utils.treemapOneQuery"));
}
};
const validateJoinField = (t: TranslateFn, join: any, errors: string[], joinIndex: number) => {
// validate stream
if (!join?.stream) {
@@ -1403,6 +1416,7 @@ export const validatePanel = (
// Validate panel content based on type
validatePanelContentByType(t, panelData?.data, errors);
validateTreemapQueries(t, panelData?.data, errors);
validateHeatmapConfig(t, panelData, errors, isPromQLMode);
validateCartesianConfig(t, panelData, errors, isPromQLMode);
validatePanelTypeConfig(t, panelData, errors);