Reference visual · full source
Bar chart Power BI custom visual: full source
Cartesian chart on a categorical DataView: one category, one measure, axes, gridlines and data labels.
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 (184 lines), settings.ts (51 lines), style.less (20 lines).
Data roles
| Field well | Role name | Accepts |
|---|---|---|
| Category | category | Field (grouping) |
| Value | measure | Measure |
DataView mapping: categorical
Format pane
General (general)
- Show title · Toggle
- Background · Colour picker
X axis (xAxis)
- Show · Toggle
- Color · Colour picker
- Text size · Number
Y axis (yAxis)
- Show · Toggle
- Color · Colour picker
- Text size · Number
Data labels (dataLabels)
- Show · Toggle
- Color · Colour picker
- Text size · Number
- Decimal places · Number
Gridlines (gridlines)
- Show · Toggle
- Color · Colour picker
Build
- tsc --noEmit
- pass
- pbiviz package
- pass
- pbiviz --certification-audit
- clean
- .pbiviz size
- 26.0 KB
- Build time
- 15 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": "Category", "name": "category", "kind": "Grouping" },
{ "displayName": "Value", "name": "measure", "kind": "Measure" }
],
"dataViewMappings": [
{
"conditions": [{ "category": { "max": 1 }, "measure": { "max": 1 } }],
"categorical": {
"categories": { "for": { "in": "category" }, "dataReductionAlgorithm": { "top": { "count": 500 } } },
"values": { "select": [{ "bind": { "to": "measure" } }] }
}
}
],
"objects": {
"general": {
"properties": {
"showTitle": { "type": { "bool": true } },
"backgroundColor": { "type": { "fill": { "solid": { "color": true } } } }
}
},
"xAxis": {
"properties": {
"show": { "type": { "bool": true } },
"color": { "type": { "fill": { "solid": { "color": true } } } },
"fontSize": { "type": { "formatting": { "fontSize": true } } }
}
},
"yAxis": {
"properties": {
"show": { "type": { "bool": true } },
"color": { "type": { "fill": { "solid": { "color": true } } } },
"fontSize": { "type": { "formatting": { "fontSize": true } } }
}
},
"dataLabels": {
"properties": {
"show": { "type": { "bool": true } },
"color": { "type": { "fill": { "solid": { "color": true } } } },
"fontSize": { "type": { "formatting": { "fontSize": true } } },
"decimalPlaces": { "type": { "numeric": true } }
}
},
"gridlines": {
"properties": {
"show": { "type": { "bool": true } },
"color": { "type": { "fill": { "solid": { "color": 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 BarDatum {
category: string;
value: number;
color: string;
selectionId: ISelectionId;
}
export class Visual implements IVisual {
private host: IVisualHost;
private target: HTMLElement;
private svg: d3.Selection<any, any, any, any>;
private selectionManager: ISelectionManager;
private events: IVisualEventService;
private formattingSettingsService: FormattingSettingsService;
private formattingSettings: VisualFormattingSettingsModel = new VisualFormattingSettingsModel();
private data: BarDatum[] = [];
constructor(options: VisualConstructorOptions) {
this.host = options.host;
this.target = options.element;
this.events = this.host.eventService;
this.formattingSettingsService = new FormattingSettingsService();
this.selectionManager = this.host.createSelectionManager();
this.selectionManager.registerOnSelectCallback((ids: powerbi.extensibility.ISelectionId[]) => this.syncSelectionState(ids as ISelectionId[]));
this.target.classList.add("visual-root");
this.svg = d3.select(this.target).append("svg").attr("class", "bar-chart");
this.target.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: Number(vals.values[i] ?? 0) || 0,
color: palette.getColor(String(c ?? i)).value,
selectionId: this.host.createSelectionIdBuilder().withCategory(cat, i).createSelectionId(),
}));
const width = Number(options.viewport.width);
const height = Number(options.viewport.height);
if (width < 120 || height < 100) {
this.svg.selectAll("*").remove();
this.events.renderingFinished(options);
return;
}
this.render(width, height);
} catch (err) {
console.error("[bar_chart] update failed", err);
}
this.events.renderingFinished(options);
}
private render(width: number, height: number): void {
const s = this.formattingSettings;
const margin = { top: 16, right: 16, bottom: 48, left: 52 };
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.data.map((d) => d.category)).range([0, w]).padding(0.2);
const maxVal = this.data.length > 0 ? (d3.max(this.data, (d) => d.value) ?? 0) : 0;
const y = d3.scaleLinear().domain([0, (maxVal || 1) * 1.1]).range([h, 0]);
if (s.gridlines.show.value) {
g.append("g").attr("class", "grid")
.call(d3.axisLeft(y).ticks(5).tickSize(-w).tickFormat(() => "") as any)
.selectAll("line").attr("stroke", s.gridlines.color.value.value);
}
const bars = g.selectAll<SVGRectElement, BarDatum>("rect.data-element")
.data(this.data)
.join("rect")
.attr("class", "bar data-element")
.attr("x", (d) => x(d.category) ?? 0)
.attr("y", (d) => y(Math.max(0, d.value)))
.attr("width", x.bandwidth())
.attr("height", (d) => Math.abs(y(0) - y(d.value)))
.attr("fill", (d) => d.color);
this.bindInteractivity(bars);
if (s.xAxis.show.value) {
const axis = g.append("g").attr("transform", `translate(0,${h})`).call(d3.axisBottom(x) as any);
const labels = axis.selectAll("text")
.style("font-size", `${s.xAxis.fontSize.value}px`)
.style("fill", s.xAxis.color.value.value)
.text((d: any) => (String(d).length > 15 ? String(d).slice(0, 14) + "…" : String(d)));
if (x.bandwidth() < 40) {
labels.attr("transform", "rotate(-45)").attr("text-anchor", "end").attr("dx", "-0.4em").attr("dy", "0.2em");
}
}
if (s.yAxis.show.value) {
g.append("g").call(d3.axisLeft(y).ticks(5) as any)
.selectAll("text").style("font-size", `${s.yAxis.fontSize.value}px`).style("fill", s.yAxis.color.value.value);
}
if (s.dataLabels.show.value) {
const dp = Math.max(0, Math.min(10, Number(s.dataLabels.decimalPlaces.value) || 0));
g.selectAll("text.label").data(this.data).join("text").attr("class", "label")
.attr("x", (d) => (x(d.category) ?? 0) + x.bandwidth() / 2)
.attr("y", (d) => y(Math.max(0, d.value)) - 4)
.attr("text-anchor", "middle")
.style("font-size", `${s.dataLabels.fontSize.value}px`)
.style("fill", s.dataLabels.color.value.value)
.text((d) => d.value.toLocaleString(undefined, { maximumFractionDigits: dp }));
}
}
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, d: BarDatum) => {
if (!allow) return;
this.selectionManager.select(d.selectionId, event.ctrlKey || event.metaKey)
.then((ids: powerbi.extensibility.ISelectionId[]) => this.syncSelectionState(ids as ISelectionId[]));
event.stopPropagation();
})
.on("contextmenu", (event: MouseEvent, d: BarDatum) => {
this.selectionManager.showContextMenu(d.selectionId, { x: event.clientX, y: event.clientY });
event.preventDefault();
event.stopPropagation();
})
.on("mouseover", (event: MouseEvent, d: BarDatum) => {
const items: VisualTooltipDataItem[] = [
{ displayName: "Category", value: d.category },
{ displayName: "Value", value: d.value.toLocaleString() },
];
this.host.tooltipService.show({ coordinates: [event.clientX, event.clientY], isTouchEvent: false, dataItems: items, identities: [d.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, BarDatum>("rect.data-element")
.style("opacity", (d) => (!has || ids.some((id) => id.equals(d.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 AxisCard extends FormattingSettingsCard {
show = new formattingSettings.ToggleSwitch({ name: "show", displayName: "Show", value: true });
color = new formattingSettings.ColorPicker({ name: "color", displayName: "Color", value: { value: "#605E5C" } });
fontSize = new formattingSettings.NumUpDown({ name: "fontSize", displayName: "Text size", value: 10 });
topLevelSlice = this.show;
slices: FormattingSettingsSlice[] = [this.color, this.fontSize];
constructor(public name: string, public displayName: string) { super(); }
}
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 });
decimalPlaces = new formattingSettings.NumUpDown({ name: "decimalPlaces", displayName: "Decimal places", value: 0 });
name = "dataLabels";
displayName = "Data labels";
topLevelSlice = this.show;
slices: FormattingSettingsSlice[] = [this.color, this.fontSize, this.decimalPlaces];
}
class GridlinesCard extends FormattingSettingsCard {
show = new formattingSettings.ToggleSwitch({ name: "show", displayName: "Show", value: true });
color = new formattingSettings.ColorPicker({ name: "color", displayName: "Color", value: { value: "#E1DFDD" } });
name = "gridlines";
displayName = "Gridlines";
topLevelSlice = this.show;
slices: FormattingSettingsSlice[] = [this.color];
}
export class VisualFormattingSettingsModel extends FormattingSettingsModel {
general = new GeneralCard();
xAxis = new AxisCard("xAxis", "X axis");
yAxis = new AxisCard("yAxis", "Y axis");
dataLabels = new DataLabelsCard();
gridlines = new GridlinesCard();
cards: FormattingSettingsCard[] = [this.general, this.xAxis, this.yAxis, this.dataLabels, this.gridlines];
}
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.bar-chart {
width: 100%;
height: 100%;
display: block;
}
.bar {
transition: opacity 0.15s ease;
&:hover { opacity: 0.85; }
}
.grid line { stroke-opacity: 0.6; }
.grid path { display: none; }
}
More examples
- Donut chartPart-to-whole chart: per-slice colours, a label-style dropdown and a centre label.
- HeatmapMatrix grid: row and column groupings with a colour scale on the value.
- KPI card with sparklineSingle-value card built in HTML: value, target and a trend sparkline by period.
- Multi-series line chartCartesian chart with grouped series: an axis field, a legend field and values, with a legend card.
- TableTable DataView rendered as HTML (no d3): header and row formatting cards.