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.

10.4 KB
Raw Blame
import { useActions, useValues } from 'kea'
import { Form } from 'kea-forms'

import { IconCopy, IconInfo } from '@posthog/icons'
import { LemonInput, LemonSelect, LemonSkeleton, LemonTable } from '@posthog/lemon-ui'
import { Button } from '@posthog/quill'

import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonField } from 'lib/lemon-ui/LemonField'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
import { copyToClipboard } from 'lib/utils/copyToClipboard'
import { SceneExport } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'

import { SceneContent } from '~/layout/scenes/components/SceneContent'
import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
import { VariableSpecificFields } from '~/queries/nodes/DataVisualization/Components/Variables/VariableForm'
import { Variable, VariableType } from '~/queries/nodes/DataVisualization/types'

import { VARIABLE_TYPE_OPTIONS, formatVariableReference, getCodeName } from './constants'
import { VARIABLE_INSIGHT_COLUMNS } from './insightColumns'
import {
    SqlVariableEditSceneLogicProps,
    sqlVariableEditSceneLogic,
    variableToFormValues,
} from './sqlVariableEditSceneLogic'

export const scene: SceneExport<SqlVariableEditSceneLogicProps> = {
    component: SqlVariableEditScene,
    logic: sqlVariableEditSceneLogic,
    paramsToProps: ({ params: { id } }) => ({ id }),
}

function VariableTypeFields(): JSX.Element {
    const { variableType, variableForm } = useValues(sqlVariableEditSceneLogic)
    const { setVariableFormValues } = useActions(sqlVariableEditSceneLogic)
    const variable = {
        id: '',
        name: '',
        code_name: '',
        default_value: '',
        ...variableForm,
        type: variableType,
        ...(variableType === 'List' && { values: 'values' in variableForm ? (variableForm.values ?? []) : [] }),
    } as Variable

    return (
        <VariableSpecificFields
            variable={variable}
            updateVariable={(updatedVariable) => setVariableFormValues(updatedVariable)}
            onSave={() => {}}
        />
    )
}

export function SqlVariableEditScene(): JSX.Element {
    const {
        isNew,
        variableLoading,
        variableType,
        isVariableFormSubmitting,
        variableForm,
        insightsUsingVariable,
        insightsUsingVariableLoading,
        hasChanges,
        variable,
    } = useValues(sqlVariableEditSceneLogic)
    const { setVariableType, setVariableFormValues, submitVariableForm, resetVariableForm } =
        useActions(sqlVariableEditSceneLogic)
    const todayRailNav = useFeatureFlag('TODAY_RAIL_NAV')

    const discardChanges = (): void => {
        if (variable) {
            resetVariableForm(variableToFormValues(variable))
            setVariableType(variable.type)
        }
    }

    const title = isNew ? 'New variable' : variableForm.name || 'Edit variable'
    const codeNameFallback = getCodeName(variableForm.name ?? '')
    const referenceCodeName = variableForm.code_name || codeNameFallback
    const nameLabel = (
        <span className="inline-flex items-center gap-1">
            Name
            <Tooltip title="Variable name must be alphanumeric and can only contain spaces and underscores">
                <IconInfo className="text-xl text-secondary shrink-0" />
            </Tooltip>
        </span>
    )

    return (
        <Form logic={sqlVariableEditSceneLogic} formKey="variableForm" enableFormOnSubmit>
            <SceneContent>
                <SceneTitleSection
                    name={title}
                    resourceType={{ type: 'variable' }}
                    forceBackTo={{
                        path: urls.variables(),
                        name: 'SQL variables',
                        key: 'variables',
                    }}
                    actions={
                        todayRailNav ? (
                            <>
                                <Button
                                    data-attr="discard-variable-changes"
                                    variant="outline"
                                    disabledReason={!isNew && !hasChanges ? 'No changes to discard' : undefined}
                                    onClick={discardChanges}
                                >
                                    Discard changes
                                </Button>
                                <Button
                                    data-attr="save-variable"
                                    variant="primary"
                                    onClick={submitVariableForm}
                                    loading={isVariableFormSubmitting}
                                    disabledReason={!isNew && !hasChanges ? 'No changes to save' : undefined}
                                >
                                    Save
                                </Button>
                            </>
                        ) : (
                            <>
                                <LemonButton
                                    data-attr="discard-variable-changes"
                                    type="secondary"
                                    size="small"
                                    disabledReason={!isNew && !hasChanges ? 'No changes to discard' : undefined}
                                    onClick={discardChanges}
                                >
                                    Discard changes
                                </LemonButton>
                                <LemonButton
                                    data-attr="save-variable"
                                    type="primary"
                                    size="small"
                                    onClick={submitVariableForm}
                                    loading={isVariableFormSubmitting}
                                    disabledReason={!isNew && !hasChanges ? 'No changes to save' : undefined}
                                >
                                    Save
                                </LemonButton>
                            </>
                        )
                    }
                />

                {variableLoading ? (
                    <div className="space-y-4">
                        <LemonSkeleton className="h-10 w-1/3" />
                        <LemonSkeleton className="h-6 w-1/2" />
                        <LemonSkeleton className="h-30 w-1/2" />
                    </div>
                ) : (
                    <>
                        <div className="space-y-4 max-w-xl">
                            <LemonField name="name" label={nameLabel}>
                                {({ value }) => (
                                    <LemonInput
                                        placeholder="e.g., Start Date"
                                        value={value}
                                        onChange={(newValue) => {
                                            const filteredValue = newValue.replace(/[^a-zA-Z0-9\s_]/g, '')
                                            if (isNew) {
                                                const shouldUpdateCodeName =
                                                    !variableForm.code_name ||
                                                    variableForm.code_name === getCodeName(variableForm.name ?? '')
                                                setVariableFormValues({
                                                    name: filteredValue,
                                                    code_name: shouldUpdateCodeName
                                                        ? getCodeName(filteredValue)
                                                        : variableForm.code_name,
                                                })
                                            } else {
                                                setVariableFormValues({ name: filteredValue })
                                            }
                                        }}
                                    />
                                )}
                            </LemonField>

                            {referenceCodeName && (
                                <div className="text-sm text-secondary">
                                    Use this variable by referencing{' '}
                                    <code className="bg-bg-3000 px-1 py-0.5 rounded">
                                        {formatVariableReference(referenceCodeName)}
                                    </code>
                                    <LemonButton
                                        className="inline-block align-middle"
                                        icon={<IconCopy />}
                                        type="tertiary"
                                        size="xsmall"
                                        onClick={() => {
                                            copyToClipboard(formatVariableReference(referenceCodeName), 'code')
                                        }}
                                        tooltip="Copy to clipboard"
                                    />
                                </div>
                            )}

                            <LemonField.Pure label="Type">
                                <LemonSelect<VariableType>
                                    value={variableType}
                                    onChange={(value) => value && setVariableType(value)}
                                    options={VARIABLE_TYPE_OPTIONS}
                                />
                            </LemonField.Pure>

                            <VariableTypeFields />
                        </div>

                        {!isNew && (
                            <div className="mt-8">
                                <h3 className="text-base font-semibold mb-4">Insights using this variable</h3>
                                <LemonTable
                                    loading={insightsUsingVariableLoading}
                                    dataSource={insightsUsingVariable}
                                    columns={VARIABLE_INSIGHT_COLUMNS}
                                    rowKey="id"
                                    emptyState="No insights use this variable"
                                />
                            </div>
                        )}
                    </>
                )}
            </SceneContent>
        </Form>
    )
}