Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

1.6 KB
Raw Blame
import { DASHBOARD_WIDGET_CATALOG, type DashboardWidgetCatalogKey } from '../widget_types/catalog'

export type AddWidgetPayload = {
    widgetType: string
    config: Record<string, unknown>
}

export function getAddButtonLabel(selectedCount: number): string {
    if (selectedCount <= 1) {
        return 'Add widget'
    }
    return `Add ${selectedCount} widgets`
}

export function getAddWidgetDisabledReason(loading: boolean | undefined, selectedCount: number): string | undefined {
    if (loading) {
        return 'Adding widgets…'
    }
    if (selectedCount === 0) {
        return 'Select at least one widget type'
    }
    return undefined
}

export function buildAddWidgetPayloads(selectedTypes: Iterable<string>): AddWidgetPayload[] {
    const payloads: AddWidgetPayload[] = []

    for (const widgetType of selectedTypes) {
        const catalogEntry = DASHBOARD_WIDGET_CATALOG[widgetType as DashboardWidgetCatalogKey]
        if (!catalogEntry || ('hideFromPicker' in catalogEntry && catalogEntry.hideFromPicker)) {
            continue
        }
        payloads.push({ widgetType, config: catalogEntry.defaultConfig })
    }

    return payloads
}

export async function submitAddWidgetPayloads(
    selectedTypes: Set<string>,
    onAdd: (payloads: AddWidgetPayload[]) => Promise<void>,
    onClose: () => void
): Promise<void> {
    if (selectedTypes.size === 0) {
        return
    }

    const payloads = buildAddWidgetPayloads(selectedTypes)
    if (payloads.length === 0) {
        return
    }

    // onAdd (dashboardLogic.addWidgetTiles) toasts and rethrows on failure — keep the modal open.
    await onAdd(payloads)
    onClose()
}