Reference visual · full source
KPI card with sparkline Power BI custom visual: full source
Single-value card built in HTML: value, target and a trend sparkline by period.
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 (45 lines), visual.ts (152 lines), settings.ts (39 lines), style.less (17 lines).
Data roles
| Field well | Role name | Accepts |
|---|---|---|
| Value | measure | Measure |
| Target | target | Measure |
| Trend (by period) | category | Field (grouping) |
DataView mapping: categorical
Format pane
General (general)
- Show title · Toggle
- Background · Colour picker
Value (valueLabel)
- Color · Colour picker
- Text size · Number
- Display units · Dropdown (enum)
Trend (trend)
- Show · Toggle
- Up color · Colour picker
- Down color · Colour picker
Build
- tsc --noEmit
- pass
- pbiviz package
- pass
- pbiviz --certification-audit
- clean
- .pbiviz size
- 28.0 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": "Value", "name": "measure", "kind": "Measure" },
{ "displayName": "Target", "name": "target", "kind": "Measure" },
{ "displayName": "Trend (by period)", "name": "category", "kind": "Grouping" }
],
"dataViewMappings": [
{
"conditions": [{ "category": { "max": 1 }, "measure": { "max": 1 }, "target": { "max": 1 } }],
"categorical": {
"categories": { "for": { "in": "category" }, "dataReductionAlgorithm": { "top": { "count": 365 } } },
"values": { "select": [{ "bind": { "to": "measure" } }, { "bind": { "to": "target" } }] }
}
}
],
"objects": {
"general": {
"properties": {
"showTitle": { "type": { "bool": true } },
"backgroundColor": { "type": { "fill": { "solid": { "color": true } } } }
}
},
"valueLabel": {
"properties": {
"color": { "type": { "fill": { "solid": { "color": true } } } },
"fontSize": { "type": { "formatting": { "fontSize": true } } },
"displayUnits": { "type": { "formatting": { "labelDisplayUnits": true } } }
}
},
"trend": {
"properties": {
"show": { "type": { "bool": true } },
"upColor": { "type": { "fill": { "solid": { "color": true } } } },
"downColor": { "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 IVisualEventService = powerbi.extensibility.IVisualEventService;
import VisualTooltipDataItem = powerbi.extensibility.VisualTooltipDataItem;
import FormattingModel = powerbi.visuals.FormattingModel;
/** KPI card: headline value (last period or single), target delta, and an SVG sparkline. */
export class Visual implements IVisual {
private host: IVisualHost;
private root: HTMLElement;
private titleEl: HTMLElement;
private valueEl: HTMLElement;
private deltaEl: HTMLElement;
private sparkEl: SVGSVGElement;
private selectionManager: ISelectionManager;
private events: IVisualEventService;
private formattingSettingsService = new FormattingSettingsService();
private formattingSettings: VisualFormattingSettingsModel = new VisualFormattingSettingsModel();
constructor(options: VisualConstructorOptions) {
this.host = options.host;
this.events = this.host.eventService;
this.selectionManager = this.host.createSelectionManager();
this.root = options.element;
this.root.classList.add("visual-root", "kpi-card");
this.titleEl = document.createElement("div");
this.titleEl.className = "kpi-title";
this.valueEl = document.createElement("div");
this.valueEl.className = "kpi-value";
this.deltaEl = document.createElement("div");
this.deltaEl.className = "kpi-delta";
this.sparkEl = document.createElementNS("http://www.w3.org/2000/svg", "svg");
this.sparkEl.setAttribute("class", "kpi-spark");
this.root.append(this.titleEl, this.valueEl, this.deltaEl, this.sparkEl);
this.root.addEventListener("contextmenu", (event: MouseEvent) => {
this.selectionManager.showContextMenu({}, { x: event.clientX, y: event.clientY });
event.preventDefault();
});
}
public update(options: VisualUpdateOptions): void {
this.events.renderingStarted(options);
try {
const dv = options.dataViews && options.dataViews[0];
const values = dv?.categorical?.values;
if (!dv || !values || values.length === 0) {
this.setEmpty("Add a measure");
this.events.renderingFinished(options);
return;
}
this.formattingSettings = this.formattingSettingsService
.populateFormattingSettingsModel<VisualFormattingSettingsModel>(VisualFormattingSettingsModel, dv);
const s = this.formattingSettings;
const measureCol = values.find((v) => v.source.roles?.["measure"]) ?? values[0];
const targetCol = values.find((v) => v.source.roles?.["target"]);
const series = measureCol.values.map((v) => Number(v ?? 0)).filter((n) => !isNaN(n));
if (series.length === 0) {
this.setEmpty("No data");
this.events.renderingFinished(options);
return;
}
const current = series[series.length - 1];
const previous = series.length > 1 ? series[series.length - 2] : undefined;
const target = targetCol ? Number(targetCol.values[targetCol.values.length - 1] ?? NaN) : NaN;
const width = Number(options.viewport.width);
const height = Number(options.viewport.height);
this.root.style.background = s.general.backgroundColor.value.value;
this.titleEl.textContent = s.general.showTitle.value ? measureCol.source.displayName : "";
this.titleEl.style.display = s.general.showTitle.value ? "" : "none";
const units = Number(s.valueLabel.displayUnits.value) || 0; // AutoDropdown value is EnumMemberValue (string | number)
this.valueEl.textContent = this.format(current, units);
this.valueEl.style.color = s.valueLabel.color.value.value;
const baseSize = Number(s.valueLabel.fontSize.value) || 32;
this.valueEl.style.fontSize = `${width < 300 ? Math.max(12, baseSize - 8) : baseSize}px`;
const trendOn = s.trend.show.value;
const ref = !isNaN(target) ? target : previous;
if (trendOn && ref !== undefined && ref !== 0) {
const pct = ((current - ref) / Math.abs(ref || 1)) * 100;
const up = pct >= 0;
this.deltaEl.textContent = `${up ? "▲" : "▼"} ${Math.abs(pct).toFixed(1)}% vs ${!isNaN(target) ? "target" : "previous"}`;
this.deltaEl.style.color = up ? s.trend.upColor.value.value : s.trend.downColor.value.value;
this.deltaEl.style.display = "";
} else {
this.deltaEl.style.display = "none";
}
const items: VisualTooltipDataItem[] = [{ displayName: measureCol.source.displayName, value: current.toLocaleString() }];
if (!isNaN(target)) items.push({ displayName: "Target", value: target.toLocaleString() });
this.valueEl.onmouseover = (event: MouseEvent) =>
this.host.tooltipService.show({ coordinates: [event.clientX, event.clientY], isTouchEvent: false, dataItems: items, identities: [] });
this.valueEl.onmouseout = () => this.host.tooltipService.hide({ immediately: true, isTouchEvent: false });
this.renderSparkline(series, width, height, s.trend.upColor.value.value);
} catch (err) {
console.error("[kpi_card] update failed", err);
}
this.events.renderingFinished(options);
}
private renderSparkline(series: number[], width: number, height: number, color: string): void {
const svg = d3.select(this.sparkEl);
svg.selectAll("*").remove();
if (series.length < 2 || height < 100 || width < 120) {
this.sparkEl.style.display = "none";
return;
}
this.sparkEl.style.display = "";
const w = Math.max(10, width - 24);
const h = Math.max(10, Math.min(60, height * 0.3));
svg.attr("width", w).attr("height", h);
const x = d3.scaleLinear().domain([0, series.length - 1]).range([2, w - 2]);
const [lo, hi] = d3.extent(series) as [number, number];
const y = d3.scaleLinear().domain([lo, hi === lo ? lo + 1 : hi]).range([h - 2, 2]);
const line = d3.line<number>().x((_, i) => x(i)).y((d) => y(d)).curve(d3.curveMonotoneX);
svg.append("path").attr("d", line(series) as any).attr("fill", "none")
.attr("stroke", this.host.colorPalette.getColor("sparkline").value || color).attr("stroke-width", 1.5);
}
private format(v: number, units: number): string {
const u = units || (Math.abs(v) >= 1e9 ? 1e9 : Math.abs(v) >= 1e6 ? 1e6 : Math.abs(v) >= 1e3 ? 1e3 : 1);
const suffix = u === 1e12 ? "T" : u === 1e9 ? "bn" : u === 1e6 ? "M" : u === 1e3 ? "K" : "";
return (v / (u || 1)).toLocaleString(undefined, { maximumFractionDigits: suffix ? 1 : 0 }) + suffix;
}
private setEmpty(msg: string): void {
this.titleEl.textContent = "";
this.valueEl.textContent = msg;
this.deltaEl.style.display = "none";
this.sparkEl.style.display = "none";
}
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 ValueLabelCard extends FormattingSettingsCard {
color = new formattingSettings.ColorPicker({ name: "color", displayName: "Color", value: { value: "#252423" } });
fontSize = new formattingSettings.NumUpDown({ name: "fontSize", displayName: "Text size", value: 32 });
displayUnits = new formattingSettings.AutoDropdown({ name: "displayUnits", displayName: "Display units", value: 0 });
name = "valueLabel";
displayName = "Value";
slices: FormattingSettingsSlice[] = [this.color, this.fontSize, this.displayUnits];
}
class TrendCard extends FormattingSettingsCard {
show = new formattingSettings.ToggleSwitch({ name: "show", displayName: "Show", value: true });
upColor = new formattingSettings.ColorPicker({ name: "upColor", displayName: "Up color", value: { value: "#107C10" } });
downColor = new formattingSettings.ColorPicker({ name: "downColor", displayName: "Down color", value: { value: "#A4262C" } });
name = "trend";
displayName = "Trend";
topLevelSlice = this.show;
slices: FormattingSettingsSlice[] = [this.upColor, this.downColor];
}
export class VisualFormattingSettingsModel extends FormattingSettingsModel {
general = new GeneralCard();
valueLabel = new ValueLabelCard();
trend = new TrendCard();
cards: FormattingSettingsCard[] = [this.general, this.valueLabel, this.trend];
}
style.less
The stylesheet pbiviz compiles into the package.
.visual-root.kpi-card {
width: 100%;
height: 100%;
box-sizing: border-box;
padding: 12px;
display: flex;
flex-direction: column;
justify-content: center;
gap: 4px;
overflow: hidden;
font-family: "Segoe UI", wf_segoe-ui_normal, helvetica, arial, sans-serif;
.kpi-title { font-size: 12px; color: #605E5C; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.kpi-value { font-weight: 600; line-height: 1.1; font-variant-numeric: tabular-nums; }
.kpi-delta { font-size: 12px; font-variant-numeric: tabular-nums; }
.kpi-spark { display: block; margin-top: 4px; }
}
More examples
- Bar chartCartesian chart on a categorical DataView: one category, one measure, axes, gridlines and data labels.
- 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.
- 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.
All examples · What a custom visual costs by route · KPI card with sparkline for Power BI