Adicionar suporte a busca detalhadaAdd Drill-Down support

Os visuais do Power BI podem usar o drill-down do Power BI.Power BI visuals can use Power BI's drill-down.

Leia mais sobre o drill-down no Power BI aquiRead more about Power BI drill-down here

Habilitar o suporte para drill-down no visualEnable drill-down support in the visual

Para dar suporte ao drill-down em seu visual, adicione um novo campo a capabilities.json chamado "drill-Down", que tem uma propriedade:To support drill down in your visual, add a new field to capabilities.json named "drill-down", which has one property:

*roles - the name of the dataRole you want to enable drill-down on.

Observação

A função dataRole de drill-down deve ser do tipo Grouping.The drill-down dataRole must be of Grouping type. A propriedade max nas condições de dataRole deve ser definida como 1.max property in the dataRole conditions must be set to 1.

Depois de você adicionar a função ao drill-down, os usuários podem arrastar vários campos para a função de dados.Once you add the role to drill-down, users can drag multiple fields into the data role.

Exemplo:example:

{
    "dataRoles": [
        {
            "displayName": "Category",
            "name": "category",
            "kind": "Grouping"
        },
        {
            "displayName": "Value",
            "name": "value",
            "kind": "Measure"
        }
    ],
    "drilldown": {
        "roles": [
            "category"
        ]
    },
    "dataViewMappings": [
        {
            "categorical": {
                "categories": {
                    "for": {
                        "in": "category"
                    }
                },
                "values": {
                    "select": [
                        {
                            "bind": {
                                "to": "value"
                            }
                        }
                    ]
                }
            }
        }
    ]
}

Criar o visual com suporte para drill-downCreate the visual with drill-down support

ExecutarRun

pbiviz new testDrillDown -t default

para criar um visual de exemplo padrão.to create a default sample visual. E aplique o exemplo acima de capabilities.json ao visual recém-criado.And apply the above sample of capabilities.json to the newly created visual.

Crie a propriedade para o contêiner div para armazenar elementos HTML do visual:Create the property for div container to hold HTML elements of the visual:

"use strict";

import "core-js/stable";
import "./../style/visual.less";
// imports

export class Visual implements IVisual {
    // visual properties
    // ...
    private div: HTMLDivElement; // <== NEW PROPERTY

    constructor(options: VisualConstructorOptions) {
        // constructor body
        // ...
    }

    public update(options: VisualUpdateOptions) {
        // update method body
        // ...
    }

    private static parseSettings(dataView: DataView): VisualSettings {
        return <VisualSettings>VisualSettings.parse(dataView);
    }

    public enumerateObjectInstances(options: EnumerateVisualObjectInstancesOptions): VisualObjectInstance[] | VisualObjectInstanceEnumerationObject {
        return VisualSettings.enumerateObjectInstances(this.settings || VisualSettings.getDefault(), options);
    }
}

Atualize o construtor do visual:Update the constructor of the visual:


export class Visual implements IVisual {
    // visual properties
    // ...
    private div: HTMLDivElement;

    constructor(options: VisualConstructorOptions) {
        console.log('Visual constructor', options);
        this.target = options.element;
        this.updateCount = 0;

        const new_p: HTMLElement = document.createElement("p");
        new_p.appendChild(document.createTextNode("Hierarchy level:"));
        const new_em: HTMLElement = document.createElement("em");
        this.textNode = document.createTextNode(this.updateCount.toString());
        new_em.appendChild(this.textNode);
        new_p.appendChild(new_em);
        this.target.appendChild(new_p);

        this.div = document.createElement("div"); // <== CREATE DIV ELEMENT
        this.target.appendChild(this.div);
    }
}

Atualize o método update do visual para criar buttons:Update the update method of the visual to create buttons:

export class Visual implements IVisual {
    // ...

    public update(options: VisualUpdateOptions) {
        this.settings = Visual.parseSettings(options && options.dataViews && options.dataViews[0]);
        console.log('Visual update', options);

        const dataView: DataView = options.dataViews[0];
        const categoricalDataView: DataViewCategorical = dataView.categorical;

        // don't create elements if no data
        if (!options.dataViews[0].categorical ||
            !options.dataViews[0].categorical.categories) {
            return
        }

        // to display current level of hierarchy
        if (typeof this.textNode !== undefined) {
            this.textNode.textContent = categoricalDataView.categories[categoricalDataView.categories.length - 1].source.displayName.toString();
        }

        // remove old elements
        // for better performance use D3js pattern:
        // https://d3js.org/#enter-exit
        while (this.div.firstChild) {
            this.div.removeChild(this.div.firstChild);
        }

        // create buttons for each category value
        categoricalDataView.categories[categoricalDataView.categories.length - 1].values.forEach( (category: powerbi.PrimitiveValue, index: number) => {
            let button = document.createElement("button");
            button.innerText = category.toString();

            this.div.appendChild(button);
        })

    }
    // ...

Aplique estilos simples em .\style\visual.less:Apply simple styles in .\style\visual.less:

button {
    margin: 5px;
    min-width: 50px;
    min-height: 50px;
}

Prepare dados de exemplo para testar o visual:Prepare sample data to test the visual:

H1H1 H2H2 H3H3 VALUESVALUES
AA A1A1 A11A11 11
AA A1A1 A12A12 22
AA A2A2 A21A21 33
AA A2A2 A22A22 44
AA A3A3 A31A31 55
AA A3A3 A32A32 66
BB B1B1 B11B11 77
BB B1B1 B12B12 88
BB B2B2 B21B21 99
BB B2B2 B22B22 1010
BB B3B3 B31B31 1111
BB B3B3 B32B32 1212

E crie a hierarquia no Power BI Desktop:And create Hierarchy in Power BI Desktop:

A captura de tela mostra o Power BI Desktop com a opção Nova hierarquia selecionada em um menu contextual.

Inclua todas as colunas de categoria (H1, H2, H3) para a nova hierarquia:Include all category columns (H1, H2, H3) to the new hierarchy:

A captura de tela mostra as colunas de categoria que você pode adicionar à nova hierarquia.

Após essas etapas, você deve obter o seguinte visual:After those steps you should get following visual:

Visual de desenvolvimento com botões

Adicionar menu de contexto aos elementos do visualAdd context menu to visual elements

Nesta etapa, você adicionará o menu de contexto ao botão do visual:In this step you'll add context menu to the button's on the visual:

Menu de contexto no visual

Para criar o menu de contexto, salve objeto host nas propriedades do visual e chame o método createSelectionManager para criar o gerenciador de seleção para exibir um menu de contexto usando a API de Elementos Visuais do Power BI.To create context menu, save host object in the properties of the visual and call createSelectionManager method to the create selection manager to display a context menu by using Power BI Visuals API.

"use strict";

import "core-js/stable";
import "./../style/visual.less";
// imports

import powerbiVisualsApi from "powerbi-visuals-api";
import ISelectionManager = powerbiVisualsApi.extensibility.ISelectionManager;
import ISelectionId = powerbiVisualsApi.visuals.ISelectionId;
import ISelectionIdBuilder = powerbiVisualsApi.visuals.ISelectionIdBuilder;

export class Visual implements IVisual {
    // visual properties
    // ...
    private div: HTMLDivElement;
    private host: IVisualHost; // <== NEW PROPERTY
    private selectionManager: ISelectionManager; // <== NEW PROPERTY

    constructor(options: VisualConstructorOptions) {
        // constructor body
        // save the host in the visuals properties
        this.host = options.host;
        // create selection manager
        this.selectionManager = this.host.createSelectionManager();
        // ...
    }

    public update(options: VisualUpdateOptions) {
        // update method body
        // ...
    }

    // ...
}

Altere o corpo do retorno de chamada da função forEach para:Change the body of forEach function callback to:

    categoricalDataView.categories[categoricalDataView.categories.length - 1].values.forEach( (category: powerbi.PrimitiveValue, index: number) => {
        // create selectionID for each category value
        let selectionID: ISelectionID = this.host.createSelectionIdBuilder()
            .withCategory(categoricalDataView.categories[0], index)
            .createSelectionId();

        let button = document.createElement("button");
        button.innerText = category.toString();

        // add event listener to click event
        button.addEventListener("click", (event) => {
            // call select method in the selection manager
            this.selectionManager.select(selectionID);
        });

        button.addEventListener("contextmenu", (event) => {
            // call showContextMenu method to display context menu on the visual
            this.selectionManager.showContextMenu(selectionID, {
                x: event.clientX,
                y: event.clientY
            });
            event.preventDefault();
        });

        this.div.appendChild(button);
    });

Aplicar os dados ao visual:Apply data to the visual:

A captura de tela mostra a hierarquia com H2 destacado.

Na etapa final, você deve obter o visual com seleções e o menu de contexto:In the final step you should get visual with selections and context menu:

A animação mostra a seleção de Fazer Drill Down e Fazer Drill Up no menu de contexto do visual.

Adicionar suporte de drill-down para mapeamento de exibição de dados de matrizAdd drill-down support for matrix data view mapping

Prepare dados de exemplo para testar o visual com mapeamentos de exibição de dados de matriz:Prepare sample data to test the visual with matrix data view mappings:

Row1Row1 Row2Row2 Row3Row3 Column1Column1 Column2Column2 Column3Column3 ValoresValues
R1R1 R11R11 R111R111 C1C1 C11C11 C111C111 11
R1R1 R11R11 R112R112 C1C1 C11C11 C112C112 22
R1R1 R11R11 R113R113 C1C1 C11C11 C113C113 33
R1R1 R12R12 R121R121 C1C1 C12C12 C121C121 44
R1R1 R12R12 R122R122 C1C1 C12C12 C122C122 55
R1R1 R12R12 R123R123 C1C1 C12C12 C123C123 66
R1R1 R13R13 R131R131 C1C1 C13C13 C131C131 77
R1R1 R13R13 R132R132 C1C1 C13C13 C132C132 88
R1R1 R13R13 R133R133 C1C1 C13C13 C133C133 99
R2R2 R21R21 R211R211 C2C2 C21C21 C211C211 1010
R2R2 R21R21 R212R212 C2C2 C21C21 C212C212 1111
R2R2 R21R21 R213R213 C2C2 C21C21 C213C213 1212
R2R2 R22R22 R221R221 C2C2 C22C22 C221C221 1313
R2R2 R22R22 R222R222 C2C2 C22C22 C222C222 1414
R2R2 R22R22 R223R223 C2C2 C22C22 C223C223 1616
R2R2 R23R23 R231R231 C2C2 C23C23 C231C231 1717
R2R2 R23R23 R232R232 C2C2 C23C23 C232C232 1818
R2R2 R23R23 R233R233 C2C2 C23C23 C233C233 1919

Aplique o seguinte mapeamento de DataView ao visual:Apply following dataview mapping for the visual:

{
    "dataRoles": [
        {
            "displayName": "Columns",
            "name": "columns",
            "kind": "Grouping"
        },
        {
            "displayName": "Rows",
            "name": "rows",
            "kind": "Grouping"
        },
        {
            "displayName": "Value",
            "name": "value",
            "kind": "Measure"
        }
    ],
    "drilldown": {
        "roles": [
            "columns",
            "rows"
        ]
    },
    "dataViewMappings": [
        {
            "matrix": {
                "columns": {
                    "for": {
                        "in": "columns"
                    }
                },
                "rows": {
                    "for": {
                        "in": "rows"
                    }
                },
                "values": {
                    "for": {
                        "in": "value"
                    }
                }
            }
        }
    ]
}

Aplicar os dados ao visual:Apply data to the visual:

A captura de tela mostra MatrixHierarchy com a hierarquia de colunas e linhas e os respectivos membros selecionados.

Importe as interfaces necessárias para processar os mapeamentos de exibição de dados:Import required interfaces to process matrix data view mappings:

// ...
import DataViewMatrix = powerbi.DataViewMatrix;
import DataViewMatrixNode = powerbi.DataViewMatrixNode;
import DataViewHierarchyLevel = powerbi.DataViewHierarchyLevel;
// ...

Crie duas propriedades para duas divs de elementos de linhas e colunas:Create two properties for two divs of rows and columns elements:

export class Visual implements IVisual {
    // ...
    private rowsDiv: HTMLDivElement;
    private colsDiv: HTMLDivElement;
    // ...
    constructor(options: VisualConstructorOptions) {
        // constructor body
        // ...
        // Create div elements and append to main div of the visual
        this.rowsDiv = document.createElement("div");
        this.target.appendChild(this.rowsDiv);

        this.colsDiv = document.createElement("div");
        this.target.appendChild(this.colsDiv);
    }
    // ...
}

Verifique os dados antes de renderizar os elementos e exiba o nível atual da hierarquia:Check the data before rendering elements and display the current level of hierarchy:

export class Visual implements IVisual {
    // ...
    constructor(options: VisualConstructorOptions) {
        // constructor body
    }

    public update(options: VisualUpdateOptions) {
        this.settings = Visual.parseSettings(options && options.dataViews && options.dataViews[0]);
        console.log('Visual update', options);

        const dataView: DataView = options.dataViews[0];
        const matrixDataView: DataViewMatrix = dataView.matrix;

        // if the visual doesn't receive the data no reason to continue rendering
        if (!matrixDataView ||
            !matrixDataView.columns ||
            !matrixDataView.rows ) {
            return
        }

        // to display current level of hierarchy
        if (typeof this.textNode !== undefined) {
            this.textNode.textContent = categoricalDataView.categories[categoricalDataView.categories.length - 1].source.displayName.toString();
        }
        // ...
    }
    // ...
}

Crie a função treeWalker para percorrer a hierarquia:Create function treeWalker for traverse the hierarchy:

export class Visual implements IVisual {
    // ...
    public update(options: VisualUpdateOptions) {
        // ...

        // if the visual doesn't receive the data no reason to continue rendering
        if (!matrixDataView ||
            !matrixDataView.columns ||
            !matrixDataView.rows ) {
            return
        }

        const treeWalker = (matrixNode: DataViewMatrixNode, index: number, levels: DataViewHierarchyLevel[], div: HTMLDivElement)  => {
            // ...
            if (matrixNode.children) {
                // ...
                // traversing child nodes
                matrixNode.children.forEach((node, index) => treeWalker(node, index, levels, childDiv));
            }
        }

        // traversing rows
        const rowRoot: DataViewMatrixNode = matrixDataView.rows.root;
        rowRoot.children.forEach((node, index) => treeWalker(node, index, matrixDataView.rows.levels, this.rowsDiv));

        // traversing columns
        const colRoot = matrixDataView.columns.root;
        colRoot.children.forEach((node, index) => treeWalker(node, index, matrixDataView.columns.levels, this.colsDiv));
    }
    // ...
}

Gere as seleções para pontos de extremidade.Generate the selections for datapoints.

const treeWalker = (matrixNode: DataViewMatrixNode, index: number, levels: DataViewHierarchyLevel[], div: HTMLDivElement)  => {
    // generate selectionID for each node of matrix
    const selectionID: ISelectionID = this.host.createSelectionIdBuilder()
        .withMatrixNode(matrixNode, levels)
        .createSelectionId();
    // ...
    if (matrixNode.children) {
        // ...
        // traversing child nodes
        matrixNode.children.forEach((node, index) => treeWalker(node, index, levels, childDiv));
    }
}

Crie div para cada nível de hierarquia:Create div for each level of hierarchy:

const treeWalker = (matrixNode: DataViewMatrixNode, index: number, levels: DataViewHierarchyLevel[], div: HTMLDivElement)  => {
    // generate selectionID for each node of matrix
    const selectionID: ISelectionID = this.host.createSelectionIdBuilder()
        .withMatrixNode(matrixNode, levels)
        .createSelectionId();
    // ...
    if (matrixNode.children) {
        // create div element for level
        const childDiv = document.createElement("div");
        // add to current div
        div.appendChild(childDiv);
        // create paragraph element to display next
        const p = document.createElement("p");
        // display level name on paragraph element
        const level = levels[matrixNode.level];
        p.innerText = level.sources[level.sources.length - 1].displayName;
        // add paragraph element to created child div
        childDiv.appendChild(p);
        // traversing child nodes
        matrixNode.children.forEach((node, index) => treeWalker(node, index, levels, childDiv));
    }
}

Crie buttons para interagir com o visual e exibir o menu de contexto para pontos de extremidade de matriz:Create buttons to interact with visual and display context menu for matrix datapoints:

const treeWalker = (matrixNode: DataViewMatrixNode, index: number, levels: DataViewHierarchyLevel[], div: HTMLDivElement)  => {
    // generate selectionID for each node of matrix
    const selectionID: ISelectionID = this.host.createSelectionIdBuilder()
        .withMatrixNode(matrixNode, levels)
        .createSelectionId();

    // create button element
    let button = document.createElement("button");
    // display node value/name of the button's text
    button.innerText = matrixNode.value.toString();

    // add event listener on click
    button.addEventListener("click", (event) => {
        // call select method in the selection manager
        this.selectionManager.select(selectionID);
    });

    // display context menu on click
    button.addEventListener("contextmenu", (event) => {
        // call showContextMenu method to display context menu on the visual
        this.selectionManager.showContextMenu(selectionID, {
            x: event.clientX,
            y: event.clientY
        });
        event.preventDefault();
    });

    div.appendChild(button);

    if (matrixNode.children) {
        // ...
    }
}

Desmarque elementos div antes de renderizar os elementos novamente:Clear div elements before render elements again:

public update(options: VisualUpdateOptions) {
    // ...
    const treeWalker = (matrixNode: DataViewMatrixNode, index: number, levels: DataViewHierarchyLevel[], div: HTMLDivElement)  => {
        // ...
    }

    // remove old elements
    // to better performance use D3js pattern:
    // https://d3js.org/#enter-exit
    while (this.rowsDiv.firstChild) {
        this.rowsDiv.removeChild(this.rowsDiv.firstChild);
    }
    // create label for row elements
    const prow = document.createElement("p");
    prow.innerText = "Rows";
    this.rowsDiv.appendChild(prow);

    while (this.colsDiv.firstChild) {
        this.colsDiv.removeChild(this.colsDiv.firstChild);
    }
    // create label for columns elements
    const pcol = document.createElement("p");
    pcol.innerText = "Columns";
    this.colsDiv.appendChild(pcol);

    // render elements for rows
    const rowRoot: DataViewMatrixNode = matrixDataView.rows.root;
    rowRoot.children.forEach((node, index) => treeWalker(node, index, matrixDataView.rows.levels, this.rowsDiv));

    // render elements for columns
    const colRoot = matrixDataView.columns.root;
    colRoot.children.forEach((node, index) => treeWalker(node, index, matrixDataView.columns.levels, this.colsDiv));
}

Na etapa final, você deve obter o visual com o menu de contexto:At the final step you should get visual with context menu:

A animação mostra um menu de contexto do visual com opções de drill down ou drill up.

Próximas etapasNext steps

Para obter mais informações, confira Entender o mapeamento de exibição de dados em visuais do Power BI.For more information, see Understand data view mapping in Power BI visuals.