Reference visual · full source

Heatmap Power BI custom visual: full source

Matrix grid: row and column groupings with a colour scale on the value.

A hand-written reference visual from the VizForge build server, in the same four files the generator writes and built the same way. It was not generated from a prompt, so there is no prompt to show, and no screenshot of it is stored, so none is shown. Files: capabilities.json (47 lines), visual.ts (188 lines), settings.ts (37 lines), style.less (16 lines).

Data roles

Data roles in capabilities.json
Field wellRole nameAccepts
RowsrowsField (grouping)
ColumnscolumnsField (grouping)
ValuemeasureMeasure

DataView mapping: categorical

Format pane

General (general)

  • Show title · Toggle
  • Background · Colour picker

Color scale (colorScale)

  • Minimum · Colour picker
  • Maximum · Colour picker

Cells (cells)

  • Show values · Toggle
  • Text size · Number
  • Cell gap · Number

Build

tsc --noEmit
pass
pbiviz package
pass
pbiviz --certification-audit
clean
.pbiviz size
25.3 KB
Build time
14 s

Built November 10, 2026with the build server's scripts/build-goldens.sh (powerbi-visuals-tools 7.2.1, TypeScript 5.9.3, powerbi-visuals-api 5.11.1, d3 7.9.0, Node.js 22). Size and time are from that one run.

capabilities.json

Data roles, the DataView mapping and the format-pane objects Power BI reads.

{
    "privileges": [],
    "dataRoles": [
        { "displayName": "Rows", "name": "rows", "kind": "Grouping" },
        { "displayName": "Columns", "name": "columns", "kind": "Grouping" },
        { "displayName": "Value", "name": "measure", "kind": "Measure" }
    ],
    "dataViewMappings": [
        {
            "conditions": [{ "rows": { "max": 1 }, "columns": { "max": 1 }, "measure": { "max": 1 } }],
            "categorical": {
                "categories": {
                    "select": [{ "for": { "in": "rows" } }, { "for": { "in": "columns" } }],
                    "dataReductionAlgorithm": { "top": { "count": 2000 } }
                },
                "values": { "select": [{ "bind": { "to": "measure" } }] }
            }
        }
    ],
    "objects": {
        "general": {
            "properties": {
                "showTitle": { "type": { "bool": true } },
                "backgroundColor": { "type": { "fill": { "solid": { "color": true } } } }
            }
        },
        "colorScale": {
            "properties": {
                "minColor": { "type": { "fill": { "solid": { "color": true } } } },
                "maxColor": { "type": { "fill": { "solid": { "color": true } } } }
            }
        },
        "cells": {
            "properties": {
                "showValues": { "type": { "bool": true } },
                "fontSize": { "type": { "formatting": { "fontSize": true } } },
                "gap": { "type": { "numeric": true } }
            }
        }
    },
    "supportsHighlight": false,
    "supportsKeyboardFocus": true,
    "supportsMultiVisualSelection": false,
    "supportsSynchronizingFilterState": true,
    "supportsLandingPage": true,
    "sorting": { "default": {} }
}

visual.ts

The IVisual class: constructor, update(), selection, tooltips and the formatting model hook.

"use strict";

import powerbi from "powerbi-visuals-api";
import * as d3 from "d3";
import { FormattingSettingsService } from "powerbi-visuals-utils-formattingmodel";
import { VisualFormattingSettingsModel } from "./settings";
import "./../style/visual.less";

import VisualConstructorOptions = powerbi.extensibility.visual.VisualConstructorOptions;
import VisualUpdateOptions = powerbi.extensibility.visual.VisualUpdateOptions;
import IVisual = powerbi.extensibility.visual.IVisual;
import IVisualHost = powerbi.extensibility.visual.IVisualHost;
import ISelectionManager = powerbi.extensibility.ISelectionManager;
import ISelectionId = powerbi.visuals.ISelectionId;
import IVisualEventService = powerbi.extensibility.IVisualEventService;
import VisualTooltipDataItem = powerbi.extensibility.VisualTooltipDataItem;
import FormattingModel = powerbi.visuals.FormattingModel;
import DataViewCategoryColumn = powerbi.DataViewCategoryColumn;

interface Cell {
    row: string;
    col: string;
    value: number;
    selectionId: ISelectionId;
}

export class Visual implements IVisual {
    private host: IVisualHost;
    private svg: d3.Selection<any, any, any, any>;
    private selectionManager: ISelectionManager;
    private events: IVisualEventService;
    private formattingSettingsService = new FormattingSettingsService();
    private formattingSettings: VisualFormattingSettingsModel = new VisualFormattingSettingsModel();
    private cells: Cell[] = [];
    private rowKeys: string[] = [];
    private colKeys: string[] = [];

    constructor(options: VisualConstructorOptions) {
        this.host = options.host;
        this.events = this.host.eventService;
        this.selectionManager = this.host.createSelectionManager();
        this.selectionManager.registerOnSelectCallback((ids: powerbi.extensibility.ISelectionId[]) => this.syncSelectionState(ids as ISelectionId[]));
        options.element.classList.add("visual-root");
        this.svg = d3.select(options.element).append("svg").attr("class", "heatmap");
        options.element.addEventListener("contextmenu", (event: MouseEvent) => {
            this.selectionManager.showContextMenu({}, { x: event.clientX, y: event.clientY });
            event.preventDefault();
        });
        this.svg.on("click", () => {
            if (!this.host.hostCapabilities.allowInteractions) return;
            this.selectionManager.clear().then(() => this.syncSelectionState([]));
        });
    }

    public update(options: VisualUpdateOptions): void {
        this.events.renderingStarted(options);
        try {
            const dv = options.dataViews && options.dataViews[0];
            const cats = dv?.categorical?.categories ?? [];
            const vals = dv?.categorical?.values?.[0];
            if (!dv || cats.length === 0 || !vals || cats[0].values.length === 0) {
                this.svg.selectAll("*").remove();
                this.events.renderingFinished(options);
                return;
            }
            this.formattingSettings = this.formattingSettingsService
                .populateFormattingSettingsModel<VisualFormattingSettingsModel>(VisualFormattingSettingsModel, dv);

            const rowCat: DataViewCategoryColumn = cats.find((c) => c.source.roles?.["rows"]) ?? cats[0];
            const colCat: DataViewCategoryColumn | undefined = cats.find((c) => c.source.roles?.["columns"] && c !== rowCat);
            const n = rowCat.values.length;
            this.cells = [];
            for (let i = 0; i < n; i++) {
                const v = Number(vals.values[i] ?? NaN);
                if (isNaN(v)) continue;
                const builder = this.host.createSelectionIdBuilder().withCategory(rowCat, i);
                if (colCat) builder.withCategory(colCat, i);
                this.cells.push({
                    row: String(rowCat.values[i] ?? ""),
                    col: colCat ? String(colCat.values[i] ?? "") : vals.source.displayName,
                    value: v,
                    selectionId: builder.createSelectionId(),
                });
            }
            this.rowKeys = Array.from(new Set(this.cells.map((c) => c.row)));
            this.colKeys = Array.from(new Set(this.cells.map((c) => c.col)));

            const width = Number(options.viewport.width);
            const height = Number(options.viewport.height);
            if (width < 120 || height < 100 || this.cells.length === 0) {
                this.svg.selectAll("*").remove();
            } else {
                this.render(width, height);
            }
        } catch (err) {
            console.error("[heatmap] update failed", err);
        }
        this.events.renderingFinished(options);
    }

    private render(width: number, height: number): void {
        const s = this.formattingSettings;
        const rowLabelW = Math.min(120, Math.max(40, width * 0.2));
        const margin = { top: 24, right: 8, bottom: 8, left: rowLabelW };
        const w = Math.max(10, width - margin.left - margin.right);
        const h = Math.max(10, height - margin.top - margin.bottom);
        this.svg.attr("width", width).attr("height", height).style("background", s.general.backgroundColor.value.value);
        this.svg.selectAll("*").remove();
        const g = this.svg.append("g").attr("transform", `translate(${margin.left},${margin.top})`);

        const x = d3.scaleBand<string>().domain(this.colKeys).range([0, w]);
        const y = d3.scaleBand<string>().domain(this.rowKeys).range([0, h]);
        const gap = Math.max(0, Number(s.cells.gap.value) || 0);
        const [lo, hi] = d3.extent(this.cells, (c) => c.value) as [number, number];
        const color = d3.scaleLinear<string>()
            .domain([lo, hi === lo ? lo + 1 : hi])
            .range([s.colorScale.minColor.value.value, s.colorScale.maxColor.value.value])
            .interpolate(d3.interpolateRgb as any);

        const rects = g.selectAll<SVGRectElement, Cell>("rect.data-element").data(this.cells).join("rect")
            .attr("class", "cell data-element")
            .attr("x", (c) => (x(c.col) ?? 0) + gap / 2)
            .attr("y", (c) => (y(c.row) ?? 0) + gap / 2)
            .attr("width", Math.max(1, x.bandwidth() - gap))
            .attr("height", Math.max(1, y.bandwidth() - gap))
            .attr("rx", 2)
            .attr("fill", (c) => color(c.value));
        this.bindInteractivity(rects);

        const fontSize = width < 300 ? Math.max(7, Number(s.cells.fontSize.value) - 1) : Number(s.cells.fontSize.value);
        if (s.cells.showValues.value && x.bandwidth() > 28 && y.bandwidth() > 14) {
            g.selectAll("text.cell-value").data(this.cells).join("text")
                .attr("class", "cell-value")
                .attr("x", (c) => (x(c.col) ?? 0) + x.bandwidth() / 2)
                .attr("y", (c) => (y(c.row) ?? 0) + y.bandwidth() / 2)
                .attr("dy", "0.35em").attr("text-anchor", "middle")
                .style("font-size", `${fontSize}px`)
                .style("fill", (c) => (d3.hsl(color(c.value)).l < 0.5 ? "#FFFFFF" : "#252423"))
                .text((c) => c.value.toLocaleString(undefined, { maximumFractionDigits: 1 }));
        }

        const truncate = (t: string, max: number) => (t.length > max ? t.slice(0, max - 1) + "…" : t);
        g.selectAll("text.col-label").data(this.colKeys).join("text").attr("class", "col-label")
            .attr("x", (k) => (x(k) ?? 0) + x.bandwidth() / 2).attr("y", -6).attr("text-anchor", "middle")
            .style("font-size", `${fontSize}px`).text((k) => truncate(k, Math.max(3, Math.floor(x.bandwidth() / 6))));
        g.selectAll("text.row-label").data(this.rowKeys).join("text").attr("class", "row-label")
            .attr("x", -6).attr("y", (k) => (y(k) ?? 0) + y.bandwidth() / 2).attr("dy", "0.35em").attr("text-anchor", "end")
            .style("font-size", `${fontSize}px`).text((k) => truncate(k, Math.max(3, Math.floor(rowLabelW / 6))));
    }

    private bindInteractivity(sel: d3.Selection<any, any, any, any>): void {
        const allow = this.host.hostCapabilities.allowInteractions;
        sel.style("cursor", allow ? "pointer" : "default")
            .on("click", (event: MouseEvent, c: Cell) => {
                if (!allow) return;
                this.selectionManager.select(c.selectionId, event.ctrlKey || event.metaKey)
                    .then((ids: powerbi.extensibility.ISelectionId[]) => this.syncSelectionState(ids as ISelectionId[]));
                event.stopPropagation();
            })
            .on("contextmenu", (event: MouseEvent, c: Cell) => {
                this.selectionManager.showContextMenu(c.selectionId, { x: event.clientX, y: event.clientY });
                event.preventDefault();
                event.stopPropagation();
            })
            .on("mouseover", (event: MouseEvent, c: Cell) => {
                const items: VisualTooltipDataItem[] = [
                    { displayName: "Row", value: c.row },
                    { displayName: "Column", value: c.col },
                    { displayName: "Value", value: c.value.toLocaleString() },
                ];
                this.host.tooltipService.show({ coordinates: [event.clientX, event.clientY], isTouchEvent: false, dataItems: items, identities: [c.selectionId] });
            })
            .on("mousemove", (event: MouseEvent) => {
                this.host.tooltipService.move({ coordinates: [event.clientX, event.clientY], isTouchEvent: false, dataItems: [], identities: [] });
            })
            .on("mouseout", () => this.host.tooltipService.hide({ immediately: true, isTouchEvent: false }));
    }

    private syncSelectionState(ids: ISelectionId[]): void {
        const has = ids.length > 0;
        this.svg.selectAll<SVGRectElement, Cell>("rect.data-element")
            .style("opacity", (c) => (!has || ids.some((id) => id.equals(c.selectionId)) ? 1 : 0.3));
    }

    public getFormattingModel(): FormattingModel {
        return this.formattingSettingsService.buildFormattingModel(this.formattingSettings);
    }
}

settings.ts

The formatting model: one card class per format-pane card, each setting a typed slice.

import { formattingSettings } from "powerbi-visuals-utils-formattingmodel";

import FormattingSettingsCard = formattingSettings.SimpleCard;
import FormattingSettingsSlice = formattingSettings.Slice;
import FormattingSettingsModel = formattingSettings.Model;

class GeneralCard extends FormattingSettingsCard {
    showTitle = new formattingSettings.ToggleSwitch({ name: "showTitle", displayName: "Show title", value: true });
    backgroundColor = new formattingSettings.ColorPicker({ name: "backgroundColor", displayName: "Background", value: { value: "#FFFFFF" } });
    name = "general";
    displayName = "General";
    slices: FormattingSettingsSlice[] = [this.showTitle, this.backgroundColor];
}

class ColorScaleCard extends FormattingSettingsCard {
    minColor = new formattingSettings.ColorPicker({ name: "minColor", displayName: "Minimum", value: { value: "#DEECF9" } });
    maxColor = new formattingSettings.ColorPicker({ name: "maxColor", displayName: "Maximum", value: { value: "#004578" } });
    name = "colorScale";
    displayName = "Color scale";
    slices: FormattingSettingsSlice[] = [this.minColor, this.maxColor];
}

class CellsCard extends FormattingSettingsCard {
    showValues = new formattingSettings.ToggleSwitch({ name: "showValues", displayName: "Show values", value: true });
    fontSize = new formattingSettings.NumUpDown({ name: "fontSize", displayName: "Text size", value: 9 });
    gap = new formattingSettings.NumUpDown({ name: "gap", displayName: "Cell gap", value: 2 });
    name = "cells";
    displayName = "Cells";
    slices: FormattingSettingsSlice[] = [this.showValues, this.fontSize, this.gap];
}

export class VisualFormattingSettingsModel extends FormattingSettingsModel {
    general = new GeneralCard();
    colorScale = new ColorScaleCard();
    cells = new CellsCard();
    cards: FormattingSettingsCard[] = [this.general, this.colorScale, this.cells];
}

style.less

The stylesheet pbiviz compiles into the package.

.visual-root {
    width: 100%;
    height: 100%;
    overflow: hidden;
    font-family: "Segoe UI", wf_segoe-ui_normal, helvetica, arial, sans-serif;

    svg.heatmap { width: 100%; height: 100%; display: block; }

    .cell {
        transition: opacity 0.15s ease, stroke-width 0.15s ease;
        stroke: transparent;
        &:hover { stroke: #252423; stroke-width: 1.5px; }
    }
    .cell-value { pointer-events: none; }
    .col-label, .row-label { fill: #605E5C; }
}

More examples

All examples · What a custom visual costs by route · Heatmap for Power BI

Make the report.
Then make it yours.

The Design Studio, templates and tools are free with no account (exports carry a small VizForge mark until you sign in). Sign up when you want AI: 5 credits on us, no card.

Generated visuals are type-checked and built before you download them; one that fails the quality SLA refunds its credits. See all features or pricing.