Power BI Visual Tools (pbiviz)

repository·main·Indexed 19 days ago

https://github.com/microsoft/powerbi-visuals-tools

A command-line interface (CLI) for developing, testing, and packaging custom Power BI visuals. It provides tools for project scaffolding, TypeScript and Less compilation, live reloading, and packaging into .pbiviz files. Version 7.2.1 requires NodeJS 18.0+. Includes a Preview MCP server for AI assistant integration to provide auditing, security scanning, and API discovery.

Tokens
7.9K
Snippets
25
Records
30
Agent score
63%

What's inside powerbi-visuals-tools

  1. Install PowerBI Visual Tools (pbiviz) via npm

    main

    Install the powerbi-visuals-tools command line interface globally using npm. This toolset provides visual project generation, TypeScript and Less compilation, automatic live reload, and packaging for distribution.

    npm install -g powerbi-visuals-tools
  2. Handle visual rendering lifecycle with IVisualEventService

    main

    When implementing the update method in your Visual class, you should use the IVisualEventService (accessed via options.host.eventService) to communicate the rendering state to the Power BI host. This allows the host to manage loading indicators and error states correctly.

    Use the following methods within your update method:

    • renderingStarted(options): Call at the beginning of the update cycle.
    • renderingFinished(options): Call after successful rendering.
    • renderingFailed(options, errorString): Call within a catch block if an error occurs during the update process.
    public update(options: VisualUpdateOptions) {
        this.events.renderingStarted(options);
        try {
            // ... rendering logic ...
            this.events.renderingFinished(options);
        }
        catch (error) {
            this.events.renderingFailed(options, String(error));
        }
    }
  3. Visual Project Configuration Files

    main

    A Power BI Visual project is defined by three core configuration files located in the project root. Understanding these files is essential for managing visual metadata, capabilities, and dependencies:

    1. pbiviz.json: Contains the primary visual metadata, including the visual's name, display name, unique GUID, version, API version, author information, and support URL.
    2. capabilities.json: Defines the visual's interaction with Power BI, including data roles, data view mappings, format objects (settings), and feature support (e.g., highlighting, keyboard focus, landing pages).
    3. package.json: Manages the project's Node.js dependencies and development dependencies.

    If pbiviz.json is missing, the directory is not recognized as a valid Power BI Visual project. You can initialize a new project using:

    pbiviz new <visual-name>
  4. Inject HTML from Base64 payload in RHTML visuals

    main

    To render HTML content generated externally (e.g., from R), decode the payloadBase64 string found in dataView.scriptResult.payloadBase64.

    The implementation follows these steps:

    1. Call resetInjector() to clear previous state.
    2. Decode the string using window.atob(payloadBase64).
    3. Parse the <head> section of the decoded HTML and inject nodes into document.head. To optimize performance, you can use the updateHTMLHead flag to ensure head nodes are only updated during the initial render.
    4. Parse the <body> section and inject nodes into the visual's rootElement.
    5. Call runHTMLWidgetRenderer() to finalize the rendering of injected components.

    Note: Ensure you manage headNodes and bodyNodes arrays to properly remove old elements before injecting new ones to prevent DOM bloat.

    private injectCodeFromPayload(payloadBase64: string): void {
        resetInjector();
        // ... decoding logic ...
        // 1. Inject <head> nodes to document.head
        // 2. Inject <body> nodes to this.rootElement
        runHTMLWidgetRenderer();
    }
  5. Structure formatting cards and slices

    main

    Formatting settings are organized hierarchically:

    1. Model (FormattingSettingsModel): The top-level container for all formatting options.
    2. Card (FormattingSettingsCard): A logical grouping of settings (e.g., "General", "Colors") that appears as a section in the Power BI formatting pane. It requires a name (internal ID) and a displayName (UI label).
    3. Slice (FormattingSettingsSlice): An individual setting within a card (e.g., a toggle, a color picker, or a text input).

    In a FormattingSettingsCard, you define your slices as properties and include them in the slices array.

  6. Implement the IVisual interface for RHTML visuals

    main

    When building an RHTML-based visual, you must implement the IVisual interface. The core logic resides in the constructor and the update method.

    In the update method, you receive VisualUpdateOptions which contains the dataViews. For RHTML visuals, the HTML content is typically passed via dataView.scriptResult.payloadBase64.

    Key lifecycle steps in the template:

    1. Constructor: Initialize the FormattingSettingsService and capture the rootElement from VisualConstructorOptions.
    2. Update:
      • Check for payloadBase64 in the first data view.
      • Use injectCodeFromPayload to decode the Base64 string and inject the resulting HTML into the document's <head> and the visual's rootElement (the <body> equivalent).
      • Call runHTMLWidgetRenderer() to initialize any injected widgets.
    3. Resizing: Handle viewport changes via the onResizing method when options.type matches resize events.
    export class Visual implements IVisual {
        public constructor(options: VisualConstructorOptions) {
            // Initialize services and root element
        }
    
        public update(options: VisualUpdateOptions): void {
            // Handle data updates and HTML injection
        }
    
        public onResizing(finalViewport: IViewport): void {
            // Handle viewport resizing
        }
    }
  7. Configure formatting settings for RHTML visuals

    main

    To enable user-configurable properties (like colors) in the Power BI formatting pane for an RHTML visual, you must perform two steps:

    1. Update capabilities.json: Define the properties under the objects key so Power BI recognizes them.
      "settings": {
          "properties": {
              "lineColor": {
                  "type": { "fill": { "solid": { "color": true }}} 
              }
          }
      }
    2. Implement getFormattingModel: In your Visual class, use the FormattingSettingsService to build the model that Power BI uses to populate the properties pane.
    public getFormattingModel(): powerbi.visuals.FormattingModel {
        return this.formattingSettingsService.buildFormattingModel(this.formattingSettings);
    }
  8. Configure the Power BI Visuals MCP Server

    main

    The Power BI Visuals MCP (Model Context Protocol) server is currently in Preview. It allows AI coding agents (like GitHub Copilot) to interact with your Power BI visual project by providing specialized tools for auditing, security scanning, and API discovery.

    To enable MCP support in your project, you can use the initMcpConfig function (or the corresponding CLI command if available) which generates a .vscode/mcp.json file. This configuration tells VS Code how to launch the pbiviz MCP server using npx.

    Next Steps after configuration:

    1. Restart VS Code to activate the MCP server.
    2. Use Copilot Chat to ask questions such as:
      • "Check my visual for certification readiness"
      • "What are the best practices for Power BI visuals?"
      • "Show me available APIs for tooltips"
    {
        "servers": {
            "pbiviz": {
                "command": "npx",
                "args": [
                    "-y",
                    "powerbi-visuals-tools",
                    "mcp"
                ]
            }
        }
    }
  9. Configure ESLint for Power BI Visuals using eslint-plugin-powerbi-visuals

    main

    When developing Power BI visuals, you can use the eslint-plugin-powerbi-visuals plugin to apply recommended linting rules specifically tailored for the Power BI Visuals environment. This is typically done by importing the plugin's recommended configuration and applying it to your eslint.config.mjs file.

    To avoid linting unnecessary files, it is recommended to include an ignores block for directories like node_modules, dist, .vscode, and .tmp.

    import powerbiVisualsConfigs from "eslint-plugin-powerbi-visuals";
    
    export default [
        powerbiVisualsConfigs.configs.recommended,
        {
            ignores: ["node_modules/**", "dist/**", ".vscode/**", ".tmp/**"],
        },
    ];
  10. Configure ESLint for Power BI Visuals

    main

    When developing Power BI visuals, you can use the eslint-plugin-powerbi-visuals plugin to apply recommended linting rules specifically designed for the Power BI visuals environment. This is typically done by importing powerbiVisualsConfigs and spreading its recommended configuration into your ESLint configuration array.

    import powerbiVisualsConfigs from "eslint-plugin-powerbi-visuals";
    
    export default [
        powerbiVisualsConfigs.configs.recommended,
        {
            ignores: ["node_modules/**", "dist/**", ".vscode/**", ".tmp/**"],
        },
    ];