site logo

Nov 18, 2024

Dark Mode in Power BI Embedded

ByPascal Kiefer

Dark Mode in Power BI Embedded

JSON Themes in Power BI Embedded

When showing a Power BI Report in an Embedded solution, by default, it looks like the regular Power BI Report. But what if you want to change the look and feel of it? Did you know you can dynamically adjust the appearance using JSON themes? This guide explores why applying themes programmatically is a powerful feature, especially for accessibility and user customization, and provides a technical walkthrough on how to do it using the Power BI Embedded API.

Enhancing User Experience with Programmatic JSON Themes

Dynamic theme application in Power BI Embedded offers unparalleled flexibility and accessibility. By using JSON themes, you can cater to user preferences like dark mode, assist users with visual impairments, and maintain brand consistency across reports. Here's how you can leverage this capability programmatically.

Technical Walkthrough: Applying JSON Themes

Let's dive into the technical steps of embedding a Power BI report and applying a JSON theme programmatically using the Power BI Embedded API.

Step 1: Initialize the Report

This first step is not related to changing the JSON theme, this simply initializes the Power BI report embedding process. The `embedConfig` object specifies report details and user interface settings. The `powerbi.embed` method embeds the report into the designated HTML container. Learn more about the basics of Embedding Power BI content in our blog.
1 var models = window['powerbi-client'].models;
2  var embedConfig = {
3  type: 'report',                         // Specifies the type of embedded object (report in this case).
4  id: '<report-id>',                      // Unique ID of the report to embed.
5  embedUrl: '<embed-url>',                // The URL to embed the report from Power BI.
6  accessToken: '<access-token>',          // The token for authentication and authorization.
7  settings: {
8    panes: {                              // Custom settings to control UI elements.
9      filters: { visible: false },        // Hides the filter pane.
10      pageNavigation: { visible: false }  // Hides the page navigation.
11          }
12      }
13  };
14
15  var reportContainer = document.getElementById('reportContainer');   // HTML container to embedded the report.
16  var report = powerbi.embed(reportContainer, embedConfig);           // Embeds the report into the container.

Step 2: Apply the JSON Theme

Next, we have to define a custom theme and apply it using the `setTheme` method. This method updates the report's appearance dynamically, and the promise handles success or errors.
1 var customTheme = {
2    "name": "Custom Dark Mode", // Name of the theme for identification
3    "dataColors": ["#1b1f23", "#21262d", "#30363d"], // Colors for data visuals (e.g., charts and graphs)
4    "background": "#0d1117", // Background color of the report canvas
5    "foreground": "#c9d1d9", // Text color for report elements (e.g., titles, labels)
6    "tableAccent": "#58a6ff" // Accent color for table visuals (e.g., highlights, headers)
7};
8
9// Apply the custom theme to the embedded Power BI report
10report.setTheme(customTheme)
11    .then(() => {
12        // Callback for successful theme application
13        console.log("Theme applied successfully");
14    })
15    .catch(error => {
16        // Handle any errors that occur during theme application
17        console.error("Error applying theme:", error);
18    });
Some useful websites that can help creating a Power BI Theme are:
  • BIBB: A simple and powerful way to generate Power BI JSON Themes in the web.
  • PowerBI.tips: A powerful Theme Generator that allows to change nearly any setting there is in Power BI related to design.
  • Step 3: Allow Users to Toggle Themes

    Now the part that's very individual depending on the application you're building. In any case, the theme should most likely be applied from a user activity. Let's say users have a radio button to switch between different themes. In that case, the change of the theme is applied if a user clicks on a specific button. This can be done with an event listener as shown in the code below which shows an example of switching between light and dark mode.
    1 // Add an event listener to the element with the ID "toggleTheme".
    2// This listens for a "click" event, triggering the provided callback function when the button is clicked.
    3document.getElementById('toggleTheme').addEventListener('click', () => {
    4    
    5    // Check if the "dark-mode" class is currently applied to the body element.
    6    // If it is present, use the "lightTheme", otherwise, use the "darkTheme".
    7    var theme = document.body.classList.contains('dark-mode') ? lightTheme : darkTheme;
    8    
    9    // Apply the selected theme to the embedded Power BI report using the "setTheme" method.
    10    report.setTheme(theme);
    11    
    12    // Toggle the "dark-mode" class on the body element.
    13    // This switches the visual mode of the application (e.g., toggling between light and dark modes).
    14    document.body.classList.toggle('dark-mode');
    15});

    Loading JSON Theme from File

    Instead of defining your JSON theme directly in the code, you can retrieve it from an external file. This method is useful if your Embedded solution has some sort of backend where users/admins can upload JSON Themes. Here’s how you can fetch and apply a theme from an external JSON file:
    1// Fetch the theme JSON from an external file
    2fetch('/themes/darkTheme.json') // Replace with the actual path to your theme file
    3  .then(response => response.json()) // Parse the JSON response
    4  .then(theme => {
    5      // Apply the fetched theme to the report
    6      report.setTheme(theme)
    7          .then(() => {
    8              console.log('External theme applied successfully');
    9          })
    10          .catch(error => {
    11              console.error('Error applying external theme:', error);
    12          });
    13  })
    14  .catch(error => {
    15      console.error('Error fetching theme:', error); // Handle fetch errors
    16  });

    Use Cases

    Dynamic JSON themes offer a wealth of opportunities to tailor Power BI reports for different audiences and scenarios. Below are several practical use cases to highlight their versatility.

    Corporate Branding

    Manually applying corporate branding to each Power BI report is very time-consuming. By defining a corporate theme in a JSON file, you can instantly apply the desired design to any report, ensuring a consistent look and feel. This approach not only streamlines the initial setup but also makes it significantly easier to update reports if corporate design guidelines change.

    High-Contrast Mode for Accessibility

    Accessibility is crucial for creating inclusive environments. High-contrast themes improve readability for users with visual impairments. By dynamically applying these themes based on user preferences or accessibility settings, organizations can ensure reports are accessible to everyone. Unfortunately, this topic doesn't get the importance it deserves.

    Seasonal or Event-Based Themes

    Organizations can use dynamic themes to reflect seasonal changes or special events, such as holidays, similar to what Google does on their landing page.

    Region-Based Localization

    For multinational companies, reports can be adapted to reflect regional preferences or cultural nuances. Dynamic themes can adjust color schemes or styles to resonate with specific audiences in different geographic locations, enhancing user comfort and engagement.

    Key Takeaway

    Power BI Embedded offers extensive customization options through dynamic theming, allowing you to create tailored, user-friendly, and brand-aligned reports. Given that Power BI Embedded is used across diverse applications, specific theming requirements can vary greatly from one app to another. Providing a way for users or admins to easily apply themes—whether predefined or dynamically chosen—is essential for delivering a user-friendly experience.

    If you’re facing any challenges with Power BI Embedded, from implementing themes to optimizing performance, don’t hesitate to reach out. Our team at Embedsy is here to help answer your questions and ensure you’re getting the most out of embedded analytics.