Skip to content

A plugin marketplace for GitHub Copilot and other AI agents that provides Power Platform development plugins, including reusable skills, agents, and commands for building and deploying solutions.

8.4 KB
Raw Blame
import { IInputs, IOutputs } from "./generated/ManifestTypes";
import "./css/{{name}}.css";

type DataSetRecord = ComponentFramework.PropertyHelper.DataSetApi.EntityRecord;

export class {{name}} implements ComponentFramework.StandardControl<IInputs, IOutputs> {
    private container: HTMLDivElement | null = null;
    private table: HTMLTableElement | null = null;
    private message: HTMLDivElement | null = null;
    private previousButton: HTMLButtonElement | null = null;
    private nextButton: HTMLButtonElement | null = null;
    private context: ComponentFramework.Context<IInputs> | null = null;
    private dataSet: ComponentFramework.PropertyTypes.DataSet | null = null;
    private pagingRequestPending = false;

    public init(
        context: ComponentFramework.Context<IInputs>,
        _notifyOutputChanged: () => void,
        _state: ComponentFramework.Dictionary,
        container: HTMLDivElement,
    ): void {
        this.container = container;
        this.context = context;

        const root = document.createElement("div");
        root.className = "{{cssClass}}";

        this.message = document.createElement("div");
        this.message.className = "{{cssMessageClass}}";

        this.table = document.createElement("table");
        this.table.className = "{{nameLower}}-table";

        const pager = document.createElement("div");
        pager.className = "{{nameLower}}-pager";
        this.previousButton = document.createElement("button");
        this.previousButton.type = "button";
        this.previousButton.textContent = "Previous";
        this.previousButton.addEventListener("click", this.loadPreviousPage);
        this.nextButton = document.createElement("button");
        this.nextButton.type = "button";
        this.nextButton.textContent = "Next";
        this.nextButton.addEventListener("click", this.loadNextPage);
        pager.append(this.previousButton, this.nextButton);

        root.append(this.message, this.table, pager);
        container.append(root);
        this.updateView(context);
    }

    public updateView(context: ComponentFramework.Context<IInputs>): void {
        this.context = context;
        this.dataSet = context.parameters.sampleDataSet || null;
        // Paging guarantees a completion update, not an intermediate loading update.
        // See: https://learn.microsoft.com/en-us/power-apps/developer/component-framework/reference/paging
        if (this.pagingRequestPending && (this.dataSet?.loading !== true || this.dataSet?.error === true)) {
            this.clearPagingRequest();
        }
        this.render();
    }

    public getOutputs(): IOutputs {
        return {};
    }

    public destroy(): void {
        this.previousButton?.removeEventListener("click", this.loadPreviousPage);
        this.nextButton?.removeEventListener("click", this.loadNextPage);
        this.container?.replaceChildren();
        this.container = null;
        this.table = null;
        this.message = null;
        this.previousButton = null;
        this.nextButton = null;
        this.context = null;
        this.dataSet = null;
        this.pagingRequestPending = false;
    }

    private readonly loadNextPage = (): void => {
        this.requestPage("next");
    };

    private readonly loadPreviousPage = (): void => {
        this.requestPage("previous");
    };

    private requestPage(direction: "next" | "previous"): void {
        if (!this.dataSet || this.pagingRequestPending || this.dataSet.loading === true) return;
        const paging = this.dataSet.paging;
        const canLoad = direction === "next" ? paging.hasNextPage : paging.hasPreviousPage;
        if (!canLoad) return;

        // Paging methods return void; completion is delivered by a later updateView after the
        // framework finishes loading the page, so the lock cannot be released on a microtask.
        // See: https://learn.microsoft.com/en-us/power-apps/developer/component-framework/reference/paging
        this.pagingRequestPending = true;
        try {
            if (direction === "next") paging.loadNextPage();
            else paging.loadPreviousPage();
        } catch (error) {
            this.clearPagingRequest();
            throw error;
        }
        this.render();
    }

    private clearPagingRequest(): void {
        this.pagingRequestPending = false;
    }

    private render(): void {
        if (!this.table || !this.message || !this.previousButton || !this.nextButton) return;
        const dataSet = this.dataSet;
        this.table.replaceChildren();

        if (!dataSet) {
            this.showMessage("No dataset parameter was provided.");
            return;
        }
        if (dataSet.loading) {
            this.showMessage("Loading records...");
            return;
        }
        if (dataSet.error) {
            this.showMessage(dataSet.errorMessage || "The dataset could not be loaded.");
            return;
        }
        if (dataSet.sortedRecordIds.length === 0) {
            this.showMessage("No records to show.");
            this.updatePaging(dataSet);
            return;
        }

        this.message.hidden = true;
        const thead = document.createElement("thead");
        const headerRow = document.createElement("tr");
        headerRow.append(
            this.header(this.displayColumnName(dataSet)),
            this.header(this.stringResource("Action_Header_Key", "Actions")),
        );
        thead.append(headerRow);

        const tbody = document.createElement("tbody");
        for (const id of dataSet.sortedRecordIds) {
            const record = dataSet.records[id];
            if (!record) continue;
            const row = document.createElement("tr");
            const primaryValue = this.displayValue(record, "sampleProperty");
            row.append(this.cell(primaryValue));
            const action = document.createElement("button");
            action.type = "button";
            action.textContent = "Open";
            action.setAttribute("aria-label", this.format(this.stringResource("Open_Record_Label_Key", "Open {0}"), primaryValue));
            action.addEventListener("click", () => this.openRecord(record));
            const actionCell = document.createElement("td");
            actionCell.append(action);
            row.append(actionCell);
            tbody.append(row);
        }
        this.table.append(thead, tbody);
        this.updatePaging(dataSet);
    }

    private header(text: string): HTMLTableCellElement {
        const header = document.createElement("th");
        header.scope = "col";
        header.textContent = text;
        return header;
    }

    private cell(text: string): HTMLTableCellElement {
        const cell = document.createElement("td");
        cell.textContent = text;
        return cell;
    }

    private displayValue(record: DataSetRecord, columnName: string): string {
        return record.getFormattedValue(columnName) || String(record.getValue(columnName) ?? "");
    }

    private displayColumnName(dataSet: ComponentFramework.PropertyTypes.DataSet): string {
        return dataSet.columns.find((column) => column.name === "sampleProperty")?.displayName
            || this.stringResource("Property_Display_Key", "Value");
    }

    private stringResource(key: string, fallback: string): string {
        return this.context?.resources?.getString(key) || fallback;
    }

    private format(template: string, value: string): string {
        return template.replace("{0}", value);
    }

    private openRecord(record: DataSetRecord): void {
        // Model-driven dataset controls should let the host open the row so navigation matches the
        // app shell instead of constructing URLs in the control.
        // See: https://learn.microsoft.com/power-apps/developer/component-framework/reference/dataset/opendatasetitem
        this.dataSet?.openDatasetItem(record.getNamedReference());
    }

    private showMessage(text: string): void {
        if (!this.message) return;
        this.message.hidden = false;
        this.message.textContent = text;
        if (this.previousButton) this.previousButton.disabled = true;
        if (this.nextButton) this.nextButton.disabled = true;
    }

    private updatePaging(dataSet: ComponentFramework.PropertyTypes.DataSet): void {
        const busy = this.pagingRequestPending || dataSet.loading === true;
        if (this.previousButton) this.previousButton.disabled = busy || !dataSet.paging.hasPreviousPage;
        if (this.nextButton) this.nextButton.disabled = busy || !dataSet.paging.hasNextPage;
    }
}