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.

14.1 KB
Raw Blame
import { IInputs, IOutputs } from "./generated/ManifestTypes";
import { loadGridPage, normalizeGuid, GridRow } from "./fetchXmlData";
import "./css/{{name}}.css";

const DEFAULT_PAGE_SIZE = 25;
const MIN_PAGE_SIZE = 1;
const MAX_PAGE_SIZE = 100;

const STRINGS = {
    caption: "ContextualGrid_Caption",
    loading: "ContextualGrid_Loading",
    unsaved: "ContextualGrid_Unsaved",
    configure: "ContextualGrid_Configure",
    permission: "ContextualGrid_Permission",
    invalidRecord: "ContextualGrid_InvalidRecord",
    missingToken: "ContextualGrid_MissingToken",
    empty: "ContextualGrid_Empty",
    error: "ContextualGrid_Error",
    loadMore: "ContextualGrid_LoadMore",
} as const;

const FALLBACKS: Record<string, string> = {
    [STRINGS.caption]: "Related rows",
    [STRINGS.loading]: "Loading related rows...",
    [STRINGS.unsaved]: "Save this {0} record before related rows can be shown.",
    [STRINGS.configure]: "Configure entityId, entityName and FetchXML before using this grid.",
    [STRINGS.permission]: "You do not have permission to read this contextual grid configuration.",
    [STRINGS.invalidRecord]: "The current record id is not a valid GUID.",
    [STRINGS.missingToken]: "FetchXML must contain the {recordId} token.",
    [STRINGS.empty]: "No related rows were found.",
    [STRINGS.error]: "Unable to load related rows.",
    [STRINGS.loadMore]: "Load more rows",
};

type State = "idle" | "loading" | "ready" | "empty" | "message" | "error";

export class {{name}} implements ComponentFramework.StandardControl<IInputs, IOutputs> {
    private root: HTMLDivElement | null = null;
    private status: HTMLDivElement | null = null;
    private tableHost: HTMLDivElement | null = null;
    private loadMoreButton: HTMLButtonElement | null = null;
    private context: ComponentFramework.Context<IInputs> | null = null;
    private rows: GridRow[] = [];
    private nextOptions: string | undefined;
    private loadToken = 0;
    private state: State = "idle";
    private message = "";
    private strings = FALLBACKS;
    private currentQueryKey = "";

    private readonly onLoadMore = (): void => {
        if (!this.context || !this.nextOptions || this.state === "loading") return;
        this.startLoad(this.context, this.nextOptions, false);
    };

    public init(
        context: ComponentFramework.Context<IInputs>,
        _notifyOutputChanged: () => void,
        _state: ComponentFramework.Dictionary,
        container: HTMLDivElement,
    ): void {
        this.context = context;
        this.strings = Object.fromEntries(
            Object.entries(FALLBACKS).map(([key, fallback]) => [key, stringResource(context, key, fallback)]),
        );

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

        this.status = document.createElement("div");
        this.status.className = "{{cssMessageClass}}";
        this.status.setAttribute("role", "status");

        this.tableHost = document.createElement("div");
        this.tableHost.className = "{{cssClass}}-tableWrap";

        this.loadMoreButton = document.createElement("button");
        this.loadMoreButton.type = "button";
        this.loadMoreButton.className = "{{cssClass}}-loadMore";
        this.loadMoreButton.textContent = this.strings[STRINGS.loadMore];
        this.loadMoreButton.addEventListener("click", this.onLoadMore);

        this.root.append(this.status, this.tableHost, this.loadMoreButton);
        container.append(this.root);
        this.updateView(context);
    }

    public updateView(context: ComponentFramework.Context<IInputs>): void {
        this.context = context;
        const config = this.readConfiguration(context);
        if (!config.ok) {
            this.rows = [];
            this.nextOptions = undefined;
            this.loadToken += 1;
            this.currentQueryKey = "";
            this.render(config.state, config.message);
            return;
        }

        const queryKey = gridQueryKey(config);
        if (queryKey === this.currentQueryKey) {
            const inFlight = this.state === "loading";
            const state = inFlight ? "loading" : this.rows.length ? "ready" : this.state;
            const message = inFlight ? this.message : this.rows.length ? "" : this.message;
            this.render(state, message);
            return;
        }
        this.currentQueryKey = queryKey;
        this.rows = [];
        this.nextOptions = undefined;
        this.startLoad(context, undefined, true);
    }

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

    public destroy(): void {
        this.loadToken += 1;
        this.loadMoreButton?.removeEventListener("click", this.onLoadMore);
        this.root?.remove();
        this.root = null;
        this.status = null;
        this.tableHost = null;
        this.loadMoreButton = null;
        this.context = null;
    }

    private startLoad(context: ComponentFramework.Context<IInputs>, nextOptions: string | undefined, replaceRows: boolean): void {
        const config = this.readConfiguration(context);
        if (!config.ok) {
            this.rows = [];
            this.nextOptions = undefined;
            this.currentQueryKey = "";
            this.render(config.state, config.message);
            return;
        }

        const token = ++this.loadToken;
        this.render("loading", this.strings[STRINGS.loading]);
        void loadGridPage(context, { ...config, nextOptions })
            .then((page) => {
                if (token !== this.loadToken) return undefined;
                this.rows = replaceRows ? page.rows : [...this.rows, ...page.rows];
                this.nextOptions = page.nextOptions;
                this.render(this.rows.length ? "ready" : "empty", this.rows.length ? "" : this.strings[STRINGS.empty]);
                return undefined;
            })
            .catch(() => {
                if (token !== this.loadToken) return undefined;
                this.nextOptions = undefined;
                this.render("error", this.strings[STRINGS.error]);
                return undefined;
            });
    }

    private readConfiguration(context: ComponentFramework.Context<IInputs>):
        | { ok: true; entityName: string; fetchXmlTemplate: string; recordId: string; pageSize: number }
        | { ok: false; state: State; message: string } {
        const entityId = context.parameters.entityId;
        const entityName = context.parameters.entityName;
        const fetchXmlTemplate = context.parameters.fetchXmlTemplate;
        if (!entityId || !entityName || !fetchXmlTemplate) {
            return { ok: false, state: "message", message: this.strings[STRINGS.configure] };
        }

        if (entityId.security?.readable === false || entityName.security?.readable === false || fetchXmlTemplate.security?.readable === false) {
            return { ok: false, state: "message", message: this.strings[STRINGS.permission] };
        }

        const rawEntityName = String(entityName.raw ?? "").trim();
        const rawFetchXml = String(fetchXmlTemplate.raw ?? "").trim();
        const rawRecordId = String(entityId.raw ?? "").trim();
        if (!rawEntityName || !rawFetchXml) {
            return { ok: false, state: "message", message: this.strings[STRINGS.configure] };
        }

        if (!rawRecordId) {
            return { ok: false, state: "message", message: this.strings[STRINGS.unsaved].replace("{0}", rawEntityName) };
        }

        if (!normalizeGuid(rawRecordId)) {
            return { ok: false, state: "message", message: this.strings[STRINGS.invalidRecord] };
        }

        if (!rawFetchXml.includes("{recordId}")) {
            return { ok: false, state: "message", message: this.strings[STRINGS.missingToken] };
        }

        return {
            ok: true,
            entityName: rawEntityName,
            fetchXmlTemplate: rawFetchXml,
            recordId: rawRecordId,
            pageSize: readPageSize(context.parameters.pageSize?.raw),
        };
    }

    private render(state: State, message: string): void {
        if (!this.status || !this.tableHost || !this.loadMoreButton || !this.context) return;
        this.state = state;
        this.message = message;
        this.status.textContent = message;
        this.status.hidden = !message;
        this.tableHost.replaceChildren();

        if (this.rows.length) {
            this.tableHost.append(renderTable(this.rows, this.strings[STRINGS.caption], this.context.mode.isControlDisabled));
        }

        this.loadMoreButton.hidden = !this.nextOptions;
        this.loadMoreButton.disabled = this.context.mode.isControlDisabled || state === "loading";
    }
}

function gridQueryKey(config: { entityName: string; fetchXmlTemplate: string; recordId: string; pageSize: number }): string {
    // The page size is part of the query: rows and the continuation link were fetched at one size,
    // so a configured change restarts at the first page rather than mixing sizes on "Load more".
    return [
        config.entityName.trim().toLowerCase(),
        normalizeGuid(config.recordId) ?? config.recordId.trim().toLowerCase(),
        config.fetchXmlTemplate,
        String(config.pageSize),
    ].join("\n");
}

function stringResource(context: ComponentFramework.Context<IInputs>, key: string, fallback: string): string {
    if (typeof context.resources?.getString !== "function") return fallback;
    return context.resources.getString(key) || fallback;
}

function readPageSize(raw: unknown): number {
    const numeric = typeof raw === "number" && Number.isFinite(raw) ? Math.trunc(raw) : DEFAULT_PAGE_SIZE;
    return Math.min(MAX_PAGE_SIZE, Math.max(MIN_PAGE_SIZE, numeric));
}

interface ColumnDescriptor {
    key: string;
    label: string;
}

// PCF Learn documents retrieveMultipleRecords as returning key/value entities, but does not state
// whether formatted annotations are included by default. Xrm.WebApi examples use the same Entity
// result shape, so this display layer uses Dataverse's standard annotation if the host returns it
// and keeps a raw fallback for non-lookup values. See:
// https://learn.microsoft.com/power-apps/developer/component-framework/reference/webapi/retrievemultiplerecords
const FORMATTED_VALUE_SUFFIX = "@OData.Community.Display.V1.FormattedValue";

function renderTable(rows: GridRow[], captionText: string, disabled: boolean): HTMLTableElement {
    const table = document.createElement("table");
    table.className = "{{cssClass}}-table";
    table.setAttribute("aria-disabled", disabled ? "true" : "false");
    const caption = document.createElement("caption");
    caption.textContent = captionText;
    table.append(caption);

    const columns = visibleColumns(rows);
    const thead = document.createElement("thead");
    const headRow = document.createElement("tr");
    for (const column of columns) {
        const th = document.createElement("th");
        th.scope = "col";
        th.textContent = column.label;
        headRow.append(th);
    }
    thead.append(headRow);
    table.append(thead);

    const tbody = document.createElement("tbody");
    for (const row of rows) {
        const tr = document.createElement("tr");
        for (const column of columns) {
            const cell = document.createElement("td");
            cell.textContent = formatCell(row, column.key);
            tr.append(cell);
        }
        tbody.append(tr);
    }
    table.append(tbody);
    return table;
}

function visibleColumns(rows: GridRow[]): ColumnDescriptor[] {
    const columns: ColumnDescriptor[] = [];
    for (const row of rows) {
        for (const key of Object.keys(row)) {
            if (isAnnotationKey(key)) continue;
            const label = displayColumnName(key);
            if (!columns.some((column) => column.key === key)) columns.push({ key, label });
        }
    }
    return columns.length ? columns : [{ key: "id", label: "id" }];
}

function formatCell(row: GridRow, key: string): string {
    const formatted = row[`${key}${FORMATTED_VALUE_SUFFIX}`];
    if (formatted != null) return String(formatted);

    const value = row[key];
    if (value == null) return "";
    if (isGuidLike(value) && (isLookupResultKey(key) || isAliasedResultKey(key))) return "";
    if (value instanceof Date) return value.toLocaleString();
    return String(value);
}

function isAnnotationKey(key: string): boolean {
    // Dataverse Web API annotations are appended after `@`, for example
    // a lookup-logical-name key in the Dataverse CRM annotation namespace; FetchXML attribute names come from
    // Dataverse logical names and cannot contain `@`, so any key containing `@` is metadata rather
    // than a display column. See:
    // https://learn.microsoft.com/power-apps/developer/data-platform/fetchxml/select-columns#column-aliases
    return key.includes("@");
}

function displayColumnName(key: string): string {
    return isLookupResultKey(key) ? key.slice(1, -"_value".length) : key;
}

function isLookupResultKey(key: string): boolean {
    return key.startsWith("_") && key.endsWith("_value");
}

function isAliasedResultKey(key: string): boolean {
    // Learn documents FetchXML link-entity results as alias-qualified keys such as
    // `contact.fullname`, and Web API alias examples show lookup alias keys such as `whocreated`
    // carrying formatted-value and lookup-logical-name annotations when annotations are included.
    // Without those annotations the only safe display for a GUID-shaped alias value is blank: showing
    // the GUID would expose an implementation id instead of the intended lookup name.
    // See: https://learn.microsoft.com/power-apps/developer/data-platform/fetchxml/select-columns#column-aliases
    return key.includes(".");
}

function isGuidLike(value: unknown): boolean {
    if (typeof value !== "string") return false;
    // Any 8-4-4-4-12 hexadecimal value, as Dataverse ids are (no RFC 4122 version or variant bits).
    return /^\{?[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\}?$/.test(value.trim());
}