Reference visual · full source

Donut chart Power BI custom visual: full source

Part-to-whole chart: per-slice colours, a label-style dropdown and a centre label.

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 (58 lines), visual.ts (177 lines), settings.ts (63 lines), style.less (17 lines).

Data roles

Data roles in capabilities.json
Field wellRole nameAccepts
LegendcategoryField (grouping)
ValuesmeasureMeasure

DataView mapping: categorical

Format pane

General (general)

  • Show title · Toggle
  • Background · Colour picker

Slices (slices)

  • Inner radius (%) · Number
  • Gap (deg) · Number

Data labels (dataLabels)

  • Show · Toggle
  • Color · Colour picker
  • Text size · Number
  • Label style · Dropdown

Center label (centerLabel)

  • Show · Toggle
  • Text · Text

Build

tsc --noEmit
pass
pbiviz package
pass
pbiviz --certification-audit
clean
.pbiviz size
26.6 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": "Legend", "name": "category", "kind": "Grouping" },
        { "displayName": "Values", "name": "measure", "kind": "Measure" }
    ],
    "dataViewMappings": [
        {
            "conditions": [{ "category": { "max": 1 }, "measure": { "max": 1 } }],
            "categorical": {
                "categories": { "for": { "in": "category" }, "dataReductionAlgorithm": { "top": { "count": 100 } } },
                "values": { "select": [{ "bind": { "to": "measure" } }] }
            }
        }
    ],
    "objects": {
        "general": {
            "properties": {
                "showTitle": { "type": { "bool": true } },
                "backgroundColor": { "type": { "fill": { "solid": { "color": true } } } }
            }
        },
        "slices": {
            "properties": {
                "innerRadius": { "type": { "numeric": true } },
                "padAngle": { "type": { "numeric": true } }
            }
        },
        "dataLabels": {
            "properties": {
                "show": { "type": { "bool": true } },
                "color": { "type": { "fill": { "solid": { "color": true } } } },
                "fontSize": { "type": { "formatting": { "fontSize": true } } },
                "labelStyle": {
                    "type": {
                        "enumeration": [
                            { "value": "percent", "displayName": "Percent" },
                            { "value": "value", "displayName": "Value" },
                            { "value": "category", "displayName": "Category" }
                        ]
                    }
                }
            }
        },
        "centerLabel": {
            "properties": {
                "show": { "type": { "bool": true } },
                "text": { "type": { "text": 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;

interface SliceDatum {
    category: string;
    value: number;
    color: string;
    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 data: SliceDatum[] = [];

    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", "donut-chart");
        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 cat = dv?.categorical?.categories?.[0];
            const vals = dv?.categorical?.values?.[0];
            if (!dv || !cat || !vals || cat.values.length === 0) {
                this.svg.selectAll("*").remove();
                this.events.renderingFinished(options);
                return;
            }
            this.formattingSettings = this.formattingSettingsService
                .populateFormattingSettingsModel<VisualFormattingSettingsModel>(VisualFormattingSettingsModel, dv);
            const palette = this.host.colorPalette;
            this.data = cat.values
                .map((c, i) => ({
                    category: String(c ?? ""),
                    value: Math.max(0, Number(vals.values[i] ?? 0) || 0),
                    color: palette.getColor(String(c ?? i)).value,
                    selectionId: this.host.createSelectionIdBuilder().withCategory(cat, i).createSelectionId(),
                }))
                .filter((d) => d.value > 0);

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

    private showNoData(width: number, height: number): void {
        this.svg.attr("width", width).attr("height", height)
            .append("text").attr("class", "no-data").attr("x", width / 2).attr("y", height / 2)
            .attr("text-anchor", "middle").text("No data");
    }

    private render(width: number, height: number): void {
        const s = this.formattingSettings;
        this.svg.attr("width", width).attr("height", height).style("background", s.general.backgroundColor.value.value);
        this.svg.selectAll("*").remove();
        const radius = Math.max(10, Math.min(width, height) / 2 - 12);
        const innerPct = Math.min(90, Math.max(0, Number(s.slicesCard.innerRadius.value) || 0)) / 100;
        const pad = (Math.max(0, Number(s.slicesCard.padAngle.value) || 0) * Math.PI) / 180;
        const g = this.svg.append("g").attr("transform", `translate(${width / 2},${height / 2})`);

        const pie = d3.pie<SliceDatum>().value((d) => d.value).sort(null).padAngle(pad);
        const arc = d3.arc<d3.PieArcDatum<SliceDatum>>().innerRadius(radius * innerPct).outerRadius(radius);
        const labelArc = d3.arc<d3.PieArcDatum<SliceDatum>>().innerRadius(radius * 0.75).outerRadius(radius * 0.75);
        const arcs = pie(this.data);
        const total = d3.sum(this.data, (d) => d.value) || 1;

        const paths = g.selectAll<SVGPathElement, d3.PieArcDatum<SliceDatum>>("path.data-element").data(arcs).join("path")
            .attr("class", "slice data-element")
            .attr("d", (d) => arc(d) as any)
            .attr("fill", (d) => d.data.color);
        this.bindInteractivity(paths, total);

        if (s.dataLabels.show.value && width >= 250) {
            const style = String(s.dataLabels.labelStyle.value.value);
            g.selectAll("text.label").data(arcs.filter((d) => d.endAngle - d.startAngle > 0.25)).join("text")
                .attr("class", "label")
                .attr("transform", (d) => `translate(${labelArc.centroid(d)})`)
                .attr("text-anchor", "middle")
                .style("font-size", `${s.dataLabels.fontSize.value}px`)
                .style("fill", s.dataLabels.color.value.value)
                .text((d) => style === "value" ? d.data.value.toLocaleString()
                    : style === "category" ? d.data.category
                    : `${((d.data.value / total) * 100).toFixed(0)}%`);
        }

        if (s.centerLabel.show.value && innerPct > 0.3) {
            const text = String(s.centerLabel.text.value || "").trim();
            g.append("text").attr("class", "center-value").attr("text-anchor", "middle").attr("dy", text ? "-0.1em" : "0.35em")
                .style("font-size", `${Math.max(10, radius * innerPct * 0.4)}px`).text(total.toLocaleString());
            if (text) {
                g.append("text").attr("class", "center-label").attr("text-anchor", "middle").attr("dy", "1.2em")
                    .style("font-size", `${Math.max(8, radius * innerPct * 0.2)}px`).text(text);
            }
        }
    }

    private bindInteractivity(sel: d3.Selection<any, any, any, any>, total: number): void {
        const allow = this.host.hostCapabilities.allowInteractions;
        sel.style("cursor", allow ? "pointer" : "default")
            .on("click", (event: MouseEvent, d: d3.PieArcDatum<SliceDatum>) => {
                if (!allow) return;
                this.selectionManager.select(d.data.selectionId, event.ctrlKey || event.metaKey)
                    .then((ids: powerbi.extensibility.ISelectionId[]) => this.syncSelectionState(ids as ISelectionId[]));
                event.stopPropagation();
            })
            .on("contextmenu", (event: MouseEvent, d: d3.PieArcDatum<SliceDatum>) => {
                this.selectionManager.showContextMenu(d.data.selectionId, { x: event.clientX, y: event.clientY });
                event.preventDefault();
                event.stopPropagation();
            })
            .on("mouseover", (event: MouseEvent, d: d3.PieArcDatum<SliceDatum>) => {
                const items: VisualTooltipDataItem[] = [
                    { displayName: "Category", value: d.data.category },
                    { displayName: "Value", value: d.data.value.toLocaleString() },
                    { displayName: "Share", value: `${((d.data.value / total) * 100).toFixed(1)}%` },
                ];
                this.host.tooltipService.show({ coordinates: [event.clientX, event.clientY], isTouchEvent: false, dataItems: items, identities: [d.data.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<SVGPathElement, d3.PieArcDatum<SliceDatum>>("path.data-element")
            .style("opacity", (d) => (!has || ids.some((id) => id.equals(d.data.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 powerbi from "powerbi-visuals-api";
import { formattingSettings } from "powerbi-visuals-utils-formattingmodel";

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

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 SlicesCard extends FormattingSettingsCard {
    innerRadius = new formattingSettings.NumUpDown({
        name: "innerRadius", displayName: "Inner radius (%)", value: 60,
        options: {
            minValue: { type: powerbi.visuals.ValidatorType.Min, value: 0 },
            maxValue: { type: powerbi.visuals.ValidatorType.Max, value: 90 },
        },
    });
    padAngle = new formattingSettings.NumUpDown({ name: "padAngle", displayName: "Gap (deg)", value: 1 });
    name = "slices";
    displayName = "Slices";
    slices: FormattingSettingsSlice[] = [this.innerRadius, this.padAngle];
}

const LABEL_STYLES: IEnumMember[] = [
    { value: "percent", displayName: "Percent" },
    { value: "value", displayName: "Value" },
    { value: "category", displayName: "Category" },
];

class DataLabelsCard extends FormattingSettingsCard {
    show = new formattingSettings.ToggleSwitch({ name: "show", displayName: "Show", value: true });
    color = new formattingSettings.ColorPicker({ name: "color", displayName: "Color", value: { value: "#252423" } });
    fontSize = new formattingSettings.NumUpDown({ name: "fontSize", displayName: "Text size", value: 10 });
    labelStyle = new formattingSettings.ItemDropdown({ name: "labelStyle", displayName: "Label style", items: LABEL_STYLES, value: LABEL_STYLES[0] });
    name = "dataLabels";
    displayName = "Data labels";
    topLevelSlice = this.show;
    slices: FormattingSettingsSlice[] = [this.color, this.fontSize, this.labelStyle];
}

class CenterLabelCard extends FormattingSettingsCard {
    show = new formattingSettings.ToggleSwitch({ name: "show", displayName: "Show", value: true });
    text = new formattingSettings.TextInput({ name: "text", displayName: "Text", value: "", placeholder: "Total" });
    name = "centerLabel";
    displayName = "Center label";
    topLevelSlice = this.show;
    slices: FormattingSettingsSlice[] = [this.text];
}

export class VisualFormattingSettingsModel extends FormattingSettingsModel {
    general = new GeneralCard();
    slicesCard = new SlicesCard();
    dataLabels = new DataLabelsCard();
    centerLabel = new CenterLabelCard();
    cards: FormattingSettingsCard[] = [this.general, this.slicesCard, this.dataLabels, this.centerLabel];
}

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.donut-chart { width: 100%; height: 100%; display: block; }

    .slice {
        stroke: #FFFFFF;
        stroke-width: 1px;
        transition: opacity 0.15s ease;
        &:hover { opacity: 0.85; }
    }
    .center-value { font-weight: 600; fill: #252423; }
    .center-label, .no-data { fill: #605E5C; }
}

More examples

All examples · What a custom visual costs by route

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.