Compartir a través de


Utilidades en objetos: asistente de subselección (versión preliminar)

HTMLSubSelectionHelper proporciona una manera sencilla de que el objeto visual personalizado de Power BI emita subselecciones a Power BI, y obtenga y represente contornos.

HTMLSubSelectionHelper es una clase auxiliar diseñada para facilitar la creación y la administración posterior de contornos de subselección. Contiene métodos para buscar elementos de tipo subselectable.

Las utilidades exportan clases y atributos CSS, lo que facilita que el objeto visual defina y mantenga las subselecciones.

Nota:

Use la versión 6.0.1 o posterior de las utilidades.

Para definir elementos de tipo subselectable, también es necesario agregar una clase a cada elemento deseado.

Clase CSS Propósito Obligatorio
subselectable Proporciona un selector para que HTMLSubSelectionHelper busque posibles subselecciones

Para definir subselecciones para el objeto visual, hay algunos atributos que deben agregarse a los elementos deseados.

Nombre del atributo Attribute Propósito Obligatorio Tipo Ejemplo
SubSelectableDisplayNameAttribute data-sub-selection-display-name Proporciona una cadena localizada para el nombre para mostrar del elemento subseleccionado string data-sub-selection-display-name="Visual Title"
SubSelectableObjectNameAttribute data-sub-selection-object-name Proporciona un nombre de objeto para asociarse a métodos abreviados de subselección y estilo string data-sub-selection-object-name="title"
SubSelectableTypeAttribute data-sub-selection-type Proporciona el tipo del estilo subseleccionado SubSelectionStylesType data-sub-selection-type="1"
SubSelectableDirectEdit data-sub-selection-direct-edit Proporciona referencias de edición de texto directo, incluidos CardUID, GroupUID y la orientación del cuadro de texto no SubSelectableDirectEdit debe proporcionarse como una cadena data-sub-selection-direct-edit="{"reference":{"cardUid":"Visual-title","groupUid":"title-text","sliceUid":"title-text-text"},"style":0}"
SubSelectableHideOutlineAttribute data-sub-selection-hide-outline Proporciona un valor booleano para los elementos de tipo subselectable que no deberían tener un contorno mostrado no boolean data-sub-selection-hide-outline="true"
SubSelectableRestrictingElementAttribute data-sub-selection-restricting-element Se usa para indicar el elemento que se restringirá, los contornos y el tipo de restricción (abrazadera o clip) no SubSelectionOutlineRestrictionType data-sub-selection-restricting-element="1"
SubSelectableSubSelectedAttribute data-sub-selection-sub-selected Indica si el subselectable está seleccionado o no No, el asistente lo asigna a los elementos cuando sea necesario Booleano data-subselection-sub-selected="true"

Modo de formato

Cuando el objeto visual entra en modo de formato, debe deshabilitar su interactividad, ya que esperamos que el usuario seleccione el objeto visual y el elemento visual para iniciar el formato.

Métodos públicos HTMLSubSelectionHelper

HTMLSubSelectionHelper tiene algunos métodos públicos que puede usar, pero hay dos métodos principales y el asistente hace el resto.

Los dos métodos son setFormatMode y updateOutlinesFromSubSelections.

Los métodos públicos del asistente incluyen:

  • createHtmlSubselectionHelper(args: HtmlSubselectionHelperArgs): HtmlSubSelectionHelper: se trata de un método estático que toma argumentos de tipo HtmlSubselectionHelperArgs y devuelve una instancia de HTMLSubSelectionHelper.

  • setFormatMode(isFormatMode: boolean): void: este método establece el modo de formato para HTMLSubSelectionHelper, Si isFormatMode es true, el asistente adjunta agentes de escucha de eventos pertinentes al elemento host para habilitar la funcionalidad del modo de formato (subselección, contornos de representación).

  • getSubSelectionSourceFromEvent(event: PointerEvent): HtmlSubSelectionSource o undefined: devuelve un objeto HtmlSubSelectionSource que se compila según el parámetro de evento.

  • onVisualScroll(): void: indica a htmlSubSelectionHelper que el desplazamiento se está produciendo actualmente. El desplazamiento debe quitar los contornos hasta que finalice el desplazamiento.

  • updateElementOutlines(elements: HTMLElement[], visibility: SubSelectionOutlineVisibility, suppressRender: boolean = false): SubSelectionRegionOutlineId[] : actualiza los contornos de los elementos (y los emite a Power BI para representarse).

  • clearHoveredOutline(): void: si existen, este método borra los contornos sobre los que se ha mantenido el puntero.

  • updateRegionOutlines(regionOutlines: HelperSubSelectionRegionOutline[], suppressRender: boolean = false): void - actualiza y emite los contornos especificados para representarse.

  • getElementsFromSubSelections(subSelections: CustomVisualSubSelection[]): HTMLElement[] - dado subSelections, este método devuelve los HTMLElements pertinentes.

  • updateOutlinesFromSubSelections(subSelections: CustomVisualSubSelection[], clearExistingOutlines?: boolean, suppressRender?: boolean): void - actualiza y representa los contornos de la subselección especificada con respecto a suppressRender y clearExistingOutlines.

  • hideAllOutlines(suppressRender: boolean = false): void: oculta todos los contornos con respecto a suppressRender.

  • getAllSubSelectables(filterType?: SubSelectionStylesType): CustomVisualSubSelection[] : devuelve todos los subSelectables según filterType.

  • createVisualSubSelectionForSingleObject(createVisualSubSelectionArgs: CreateVisualSubSelectionFromObjectArgs): CustomVisualSubSelection: crea el objeto CustomVisualSubSelection a partir de createVisualSubSelectionArgs.

  • setDataForElement(el: HTMLElement | SVGElement, data: SubSelectionElementData): void: un método estático que establece los datos de los elementos.

  • getDataForElement(el: HTMLElement | SVGElement): SubSelectionElementData: un método estático que obtiene el asociado asignado previamente mediante setDataForElement.

HtmlSubselectionHelperArgs

interface HtmlSubselectionHelperArgs {
    /** Element which contains the items that can be sub-selected */
    hostElement: HTMLElement; // The host element, the helper will attach the listeners to this element
    subSelectionService: powerbi.extensibility.IVisualSubSelectionService;// subSelectionService which is provided in powerbi-visuals-api
    selectionIdCallback?: ((e: HTMLElement) => ISelectionId);// a callback that gets the selectionId for the specific element
    customOutlineCallback?: ((subSelection: CustomVisualSubSelection) => SubSelectionRegionOutlineFragment[]);// a callback to get custom outline for the specific subSelection
    customElementCallback?: ((subSelection: CustomVisualSubSelection) => HTMLElement[]);
    subSelectionMetadataCallback?: ((subSelectionElement: HTMLElement) => unknown);// a callback to attatch any meta data to the subSelection.
}

SubSelectionStylesType

const enum SubSelectionStylesType {
            None = 0,
            Text = 1,
            NumericText = 2,
            Shape = 3,
}

SubSelectableDirectEdit

interface SubSelectableDirectEdit {
            reference: SliceFormattingModelReference;
            style: SubSelectableDirectEditStyle;
            displayValue?: string;
}

SubSelectionOutlineRestrictionType

const enum SubSelectionOutlineRestrictionType {
            /**
             * A clamping element will adjust the outline to prevent it from extending beyond
             * the restricting element.
             */
            Clamp,
            /**
             * A clipping element will make parts of the outline not visible if the outline extends beyond the
             * restricting element's bounds. 
             */
            Clip
        }

Para agregar opciones de restricción a un elemento específico, use con HTMLSubSelectionHelper setDataForElement este tipo de datos, el asistente usa los datos para actualizar los esquemas:

interface SubSelectionElementData {
    outlineRestrictionOptions?: SubSelectionOutlineRestrictionOptions;
}

/** Options used to indicate if a restricting element should allow outlines more space to
  * generate by adding padding or if the restricting element should constrict the outline more
  * by adding a margin.
  */
export interface SubSelectionOutlineRestrictionOptions {
        padding?: IOffset;
        margin?: IOffset;
  }

Ejemplo

En este ejemplo, implementamos customOutlineCallback y selectionIdCallback: el código siguiente está en Visual Code. Tenemos un objeto en el objeto visual denominado arcElement. Queremos representar el contorno cuando se mantenga el puntero sobre el elemento o se subseleccione.

import ISelectionId = powerbi.visuals.ISelectionId;

const enum BarChartObjectNames {
    ArcElement = 'arcElement',
    ColorSelector = 'colorSelector',
    …..
}

private ArcOutlines(subSelection: CustomVisualSubSelection): powerbi.visuals.SubSelectionRegionOutlineFragment[] {
        const outlines: powerbi.visuals.SubSelectionRegionOutlineFragment[] = []
        if (subSelection?.customVisualObjects[0].objectName === BarChartObjectNames.ArcElement) {
            const outline: powerbi.visuals.ArcSubSelectionOutline = {
                type: powerbi.visuals.SubSelectionOutlineType.Arc,
                center: { x: this.arcCenterX, y: this.arcCenterY },
                startAngle: this.arcStartAngle,
                endAngle: this.arcEndAngle,
                innerRadius: this.arcInnerRadius,
                outerRadius: this.arcOuterRadius
            };
            outlines.push({
                id: BarChartObjectNames.ArcElement,
                outline
            });
            return outlines;
        }
    }

public selectionIdCallback(e: Element): ISelectionId {
        const elementType: string = d3.select(e).attr(SubSelectableObjectNameAttribute);
        switch (elementType) {
            case BarChartObjectNames.ColorSelector:
                const datum = d3.select<Element, BarChartDataPoint>(e).datum();
                return datum.selectionId;
            default:
                return undefined;
        }
    }

Importe el HtmlSubSelectionHelper:

import { HtmlSubSelectionHelper } from 'powerbi-visuals-utils-onobjectutils';

En el código del constructor, cree el htmlSubSelectionHelper:

constructor(options: VisualConstructorOptions) {
    …….
    this.subSelectionHelper = HtmlSubSelectionHelper.createHtmlSubselectionHelper({
                hostElement: options.element,
                subSelectionService: options.host.subSelectionService,
                selectionIdCallback: (e) => this.selectionIdCallback(e),
                customOutlineCallback: (e) => this.ArcOutlines(e),
            });
    ….
}

En el método de actualización del objeto visual, agregue el código siguiente para actualizar los contornos de subSeselection, actualice el estado del modo de formato para las interacciones HTMLSubSelectionHelper y deshabilite las interacciones que no son para el modo de formato si el modo de formato está activado:

public update(options: VisualUpdateOptions) {
 …
 
 if (this.formatMode) {// disabling interaction with the visual data in format mode
             barSelectionMerged.on('click', null);
             this.svg.on('click', null);
             this.svg.on('contextmenu', null);
         } else {
             this.handleBarClick(barSelectionMerged);
             this.handleClick(barSelectionMerged);
             this.handleContextMenu();
         }
         this.subSelectionHelper.setFormatMode(options.formatMode);
         const shouldUpdateSubSelection = options.type & powerbi.VisualUpdateType.Data
             || options.type & powerbi.VisualUpdateType.Resize
             || options.type & powerbi.VisualUpdateType.FormattingSubSelectionChange;
         if (this.formatMode && shouldUpdateSubSelection) {
             this.subSelectionHelper.updateOutlinesFromSubSelections(options.subSelections, true);
         }
 …
}