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.

17.1 KB
Raw Blame
import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { forms } from 'kea-forms'
import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'
import { loaders } from 'kea-loaders'
import posthog from 'posthog-js'

import api from 'lib/api'
import { getInsightId } from 'lib/insights/getInsightId'
import { preflightLogic } from 'lib/logic/preflightLogic'
import { organizationLogic } from 'scenes/organizationLogic'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'

import { dashboardsModel } from '~/models/dashboardsModel'
import { AvailableFeature, InsightShortId, OrganizationType, SharingConfigurationType } from '~/types'

export interface SharingLogicProps {
    dashboardId?: number
    insightShortId?: InsightShortId
    recordingId?: string
    notebookShortId?: string
    additionalParams?: Record<string, any>
    onSharingEnabledChange?: (enabled: boolean) => void
}

export interface EmbedConfig {
    width: string
    height: string
}

const defaultIframeConfig = {
    width: '100%',
    height: '400',
}

const defaultSharingSettings = {
    whitelabel: false,
    legend: false,
    noHeader: false,
    showInspector: false,
    hideExtraDetails: false,
    theme: 'system',
}

const propsToApiParams = async (
    props: SharingLogicProps
): Promise<{
    dashboardId?: number
    insightId?: number
    recordingId?: string
    notebookShortId?: string
}> => {
    const insightId = props.insightShortId ? await getInsightId(props.insightShortId) : undefined
    return {
        dashboardId: props.dashboardId,
        insightId,
        recordingId: props.recordingId,
        notebookShortId: props.notebookShortId,
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface sharingLogicValues {
    accessControlAvailable: boolean
    canManagePublicSharing: boolean
    embedCode: string
    embedLink: string
    iframeKey: number
    iframeProperties: {
        allowFullScreen: true
        frameBorder: number
        height: string
        key: number
        sandbox: string
        src: string
        width: string
    }
    isSharingSettingsSubmitting: boolean
    isSharingSettingsValid: boolean
    params: any
    shareLink: string
    sharingAllowed: boolean
    sharingConfiguration: SharingConfigurationType | null
    sharingConfigurationLoading: boolean
    sharingSettings: {
        hideExtraDetails: boolean
        legend: boolean
        noHeader: boolean
        showInspector: boolean
        theme: string
        whitelabel: boolean
    }
    sharingSettingsAllErrors: Record<string, any>
    sharingSettingsChanged: boolean
    sharingSettingsErrors: DeepPartialMap<
        {
            hideExtraDetails: boolean
            legend: boolean
            noHeader: boolean
            showInspector: boolean
            theme: string
            whitelabel: boolean
        },
        ValidationErrorType
    >
    sharingSettingsHasErrors: boolean
    sharingSettingsManualErrors: Record<string, any>
    sharingSettingsTouched: boolean
    sharingSettingsTouches: Record<string, boolean>
    sharingSettingsValidationErrors: DeepPartialMap<
        {
            hideExtraDetails: boolean
            legend: boolean
            noHeader: boolean
            showInspector: boolean
            theme: string
            whitelabel: boolean
        },
        ValidationErrorType
    >
    showPreview: boolean
    showSharingSettingsErrors: boolean
    siteUrl: string | undefined
    whitelabelAvailable: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface sharingLogicActions {
    loadSharingConfiguration: () => any
    loadSharingConfigurationFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadSharingConfigurationSuccess: (
        sharingConfiguration: SharingConfigurationType | null,
        payload?: any
    ) => {
        sharingConfiguration: SharingConfigurationType | null
        payload?: any
    }
    reloadIframe: () => {
        value: true
    }
    resetSharingSettings: (values?: {
        hideExtraDetails: boolean
        legend: boolean
        noHeader: boolean
        showInspector: boolean
        theme: string
        whitelabel: boolean
    }) => {
        values?: {
            hideExtraDetails: boolean
            legend: boolean
            noHeader: boolean
            showInspector: boolean
            theme: string
            whitelabel: boolean
        }
    }
    setIsEnabled: (enabled: boolean) => boolean
    setIsEnabledFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    setIsEnabledSuccess: (
        sharingConfiguration: SharingConfigurationType | null,
        payload?: boolean
    ) => {
        sharingConfiguration: SharingConfigurationType | null
        payload?: boolean
    }
    setPasswordRequired: (password_required: boolean) => boolean
    setPasswordRequiredFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    setPasswordRequiredSuccess: (
        sharingConfiguration: SharingConfigurationType | null,
        payload?: boolean
    ) => {
        sharingConfiguration: SharingConfigurationType | null
        payload?: boolean
    }
    setSharingSettingsManualErrors: (errors: Record<string, any>) => {
        errors: Record<string, any>
    }
    setSharingSettingsValue: (
        key: FieldName,
        value: any
    ) => {
        name: FieldName
        value: any
    }
    setSharingSettingsValues: (
        values: DeepPartial<{
            hideExtraDetails: boolean
            legend: boolean
            noHeader: boolean
            showInspector: boolean
            theme: string
            whitelabel: boolean
        }>
    ) => {
        values: DeepPartial<{
            hideExtraDetails: boolean
            legend: boolean
            noHeader: boolean
            showInspector: boolean
            theme: string
            whitelabel: boolean
        }>
    }
    submitSharingSettings: () => {
        value: boolean
    }
    submitSharingSettingsFailure: (
        error: Error,
        errors: Record<string, any>
    ) => {
        error: Error
        errors: Record<string, any>
    }
    submitSharingSettingsRequest: (sharingSettings: {
        hideExtraDetails: boolean
        legend: boolean
        noHeader: boolean
        showInspector: boolean
        theme: string
        whitelabel: boolean
    }) => {
        sharingSettings: {
            hideExtraDetails: boolean
            legend: boolean
            noHeader: boolean
            showInspector: boolean
            theme: string
            whitelabel: boolean
        }
    }
    submitSharingSettingsSuccess: (sharingSettings: {
        hideExtraDetails: boolean
        legend: boolean
        noHeader: boolean
        showInspector: boolean
        theme: string
        whitelabel: boolean
    }) => {
        sharingSettings: {
            hideExtraDetails: boolean
            legend: boolean
            noHeader: boolean
            showInspector: boolean
            theme: string
            whitelabel: boolean
        }
    }
    togglePreview: () => {
        value: true
    }
    touchSharingSettingsField: (key: string) => {
        key: string
    }
    updateSettings: (settings: Record<string, any>) => Record<string, any>
    updateSettingsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    updateSettingsSuccess: (
        sharingConfiguration: SharingConfigurationType | null,
        payload?: Record<string, any>
    ) => {
        sharingConfiguration: SharingConfigurationType | null
        payload?: Record<string, any>
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface sharingLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        siteUrl: (preflight: null | import('~/types').PreflightStatus) => string | undefined
        whitelabelAvailable: (
            hasAvailableFeature: (feature: AvailableFeature, currentUsage?: number | undefined) => boolean
        ) => boolean
        accessControlAvailable: (
            hasAvailableFeature: (feature: AvailableFeature, currentUsage?: number | undefined) => boolean
        ) => boolean
        canManagePublicSharing: (
            isAdminOrOwner: boolean | null,
            hasAvailableFeature: (feature: AvailableFeature, currentUsage?: number | undefined) => boolean
        ) => boolean
        sharingAllowed: (currentOrganization: OrganizationType | null) => boolean
        params: (arg: any) => any
        shareLink: (
            siteUrl: string | undefined,
            sharingConfiguration: SharingConfigurationType | null,
            params: any
        ) => string
        embedLink: (
            siteUrl: string | undefined,
            sharingConfiguration: SharingConfigurationType | null,
            params: any
        ) => string
        iframeProperties: (
            embedLink: string,
            iframeKey: number
        ) => {
            allowFullScreen: true
            frameBorder: number
            height: string
            key: number
            sandbox: string
            src: string
            width: string
        }
        embedCode: (iframeProperties: {
            allowFullScreen: true
            frameBorder: number
            height: string
            key: number
            sandbox: string
            src: string
            width: string
        }) => string
    }
}

export type sharingLogicType = MakeLogicType<
    sharingLogicValues,
    sharingLogicActions,
    SharingLogicProps,
    sharingLogicMeta
>

export const sharingLogic = kea<sharingLogicType>([
    path(['lib', 'components', 'Sharing', 'sharingLogic']),
    props({} as SharingLogicProps),
    key(
        ({ insightShortId, dashboardId, recordingId, notebookShortId }) =>
            `sharing-${insightShortId || dashboardId || recordingId || notebookShortId || ''}`
    ),
    connect(() => [preflightLogic, userLogic, dashboardsModel, organizationLogic]),

    actions({
        togglePreview: true,
        reloadIframe: true,
    }),
    reducers({
        showPreview: [true, { togglePreview: (state) => !state }],
        iframeKey: [0, { reloadIframe: (state) => state + 1 }],
    }),

    loaders(({ props }) => ({
        sharingConfiguration: [
            null as SharingConfigurationType | null,
            {
                loadSharingConfiguration: async () => {
                    return await api.sharing.get(await propsToApiParams(props))
                },
                setIsEnabled: async (enabled: boolean) => {
                    const sharingConfiguration = await api.sharing.update(await propsToApiParams(props), { enabled })
                    if (sharingConfiguration) {
                        props.onSharingEnabledChange?.(sharingConfiguration.enabled)
                    }
                    return sharingConfiguration
                },
                setPasswordRequired: async (password_required: boolean) => {
                    return await api.sharing.update(await propsToApiParams(props), {
                        password_required,
                    })
                },
                updateSettings: async (settings: Record<string, any>) => {
                    return await api.sharing.update(await propsToApiParams(props), { settings })
                },
            },
        ],
    })),
    listeners(({ props, values, actions }) => ({
        setIsEnabled: (enabled) => {
            if (props.dashboardId) {
                posthog.capture(`dashboard share toggled`, { dashboard_id: props.dashboardId, is_shared: enabled })
            } else if (props.insightShortId) {
                posthog.capture('insight share toggled', { insight_short_id: props.insightShortId, is_shared: enabled })
            }
        },
        setIsEnabledSuccess: () => {
            if (props.dashboardId) {
                dashboardsModel.actions.loadDashboards()
            }
        },
        setSharingSettingsValue: ({ name, value }) => {
            if (name === 'whitelabel' && props.dashboardId) {
                posthog.capture(`dashboard whitelabel toggled`, {
                    dashboard_id: props.dashboardId,
                    is_whitelabelled: value,
                })
            }
            if (name === 'whitelabel' && props.insightShortId) {
                posthog.capture(`insight whitelabel toggled`, { is_whitelabelled: value })
            }
            // Auto-save all embed config changes to settings
            if (values.sharingConfiguration) {
                actions.updateSettings({
                    ...values.sharingConfiguration.settings,
                    [name as string]: value,
                })
            }
        },
        updateSettingsSuccess: () => {
            // Reload iframe when settings are updated
            actions.reloadIframe()
        },
        loadSharingConfigurationSuccess: (result) => {
            if (result) {
                // Load sharing settings from API into the form
                const savedSettings = result.sharingConfiguration?.settings || {}
                const formValues = {
                    ...defaultSharingSettings,
                    ...savedSettings,
                }
                actions.setSharingSettingsValues(formValues)
            }
        },
    })),

    forms({
        sharingSettings: {
            defaults: defaultSharingSettings,
        },
    }),
    selectors({
        siteUrl: [
            () => [preflightLogic.selectors.preflight],
            (preflight: null | import('~/types').PreflightStatus) => preflight?.site_url,
        ],

        whitelabelAvailable: [
            () => [userLogic.selectors.hasAvailableFeature],
            (hasAvailableFeature: (feature: AvailableFeature, currentUsage?: number | undefined) => boolean) =>
                hasAvailableFeature(AvailableFeature.WHITE_LABELLING),
        ],
        accessControlAvailable: [
            () => [userLogic.selectors.hasAvailableFeature],
            (hasAvailableFeature: (feature: AvailableFeature, currentUsage?: number | undefined) => boolean) =>
                hasAvailableFeature(AvailableFeature.ACCESS_CONTROL),
        ],
        canManagePublicSharing: [
            () => [organizationLogic.selectors.isAdminOrOwner, userLogic.selectors.hasAvailableFeature],
            (isAdminOrOwner: boolean | null, hasAvailableFeature: (feature: AvailableFeature) => boolean): boolean =>
                !!isAdminOrOwner && hasAvailableFeature(AvailableFeature.ORGANIZATION_SECURITY_SETTINGS),
        ],

        sharingAllowed: [
            () => [organizationLogic.selectors.currentOrganization],
            (currentOrganization: OrganizationType) => currentOrganization?.allow_publicly_shared_resources ?? true,
        ],

        params: [
            () => [(_, props) => props.additionalParams],
            (additionalParams = {}) => ({
                ...additionalParams,
            }),
        ],

        shareLink: [
            (s) => [s.siteUrl, s.sharingConfiguration, s.params],
            (siteUrl: string | undefined, sharingConfiguration: SharingConfigurationType | null, params) =>
                sharingConfiguration ? siteUrl + urls.shared(sharingConfiguration.access_token, params) : '',
        ],

        embedLink: [
            (s) => [s.siteUrl, s.sharingConfiguration, s.params],
            (siteUrl: string | undefined, sharingConfiguration: SharingConfigurationType | null, params) =>
                sharingConfiguration ? siteUrl + urls.embedded(sharingConfiguration.access_token, params) : '',
        ],

        iframeProperties: [
            (s) => [s.embedLink, s.iframeKey],
            (embedLink: string, iframeKey: number) => ({
                width: defaultIframeConfig.width,
                height: defaultIframeConfig.height,
                frameBorder: 0,
                // React prop casing; embedCode lowercases keys, so the HTML snippet still reads "allowfullscreen"
                allowFullScreen: true,
                src: embedLink,
                key: iframeKey,
                sandbox: 'allow-scripts allow-same-origin allow-popups',
            }),
        ],

        embedCode: [
            (s) => [s.iframeProperties],
            (iframeProperties: {
                allowFullScreen: true
                frameBorder: number
                height: string
                key: number
                sandbox: string
                src: string
                width: string
            }) =>
                `<iframe ${Object.entries(iframeProperties)
                    .map(([key, value]) => {
                        if (value === true) {
                            return key.toLowerCase()
                        }
                        return `${key.toLowerCase()}="${String(value).split('"').join('')}"`
                    })
                    .join(' ')}></iframe>`,
        ],
    }),
    afterMount(({ actions }) => {
        actions.loadSharingConfiguration()
    }),
])