Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

refactor(web): Migrate PosthogIntegrationSettings to use design system components (#17558)

Ben Bachem16d024f1e09f
diff --git a/web/eslint.config.mjs b/web/eslint.config.mjs
index 6dd1fd9824..5c039d56c8 100644
--- a/web/eslint.config.mjs
+++ b/web/eslint.config.mjs
@@ -281,12 +281,13 @@ export default [
// Root design-system components follow `Name/Name.tsx`, optionally alongside
// `Name/Name.stories.tsx`. Files must be directly inside a PascalCase folder,
// match that folder's name, and expose a matching named runtime export. The
- // table and internal subtrees are domain-specific exceptions with their own
- // structure.
+ // factories, table, and internal subtrees are domain-specific exceptions
+ // with their own structure.
{
name: "langfuse/web/design-system-component-structure",
files: ["src/components/design-system/**/*.{ts,tsx}"],
ignores: [
+ "src/components/design-system/factories/**",
"src/components/design-system/internal/**",
"src/components/design-system/table/**",
],
diff --git a/web/src/components/design-system/Button/Button.stories.tsx b/web/src/components/design-system/Button/Button.stories.tsx
new file mode 100644
index 0000000000..0a025550c4
--- /dev/null
+++ b/web/src/components/design-system/Button/Button.stories.tsx
@@ -0,0 +1,95 @@
+import { expect, fn, userEvent, within } from "storybook/test";
+
+import preview from "../../../../.storybook/preview";
+import { Button } from "./Button";
+
+const meta = preview.meta({
+ component: Button,
+ args: {
+ text: "Save",
+ },
+});
+
+export const Primary = meta.story({
+ args: {
+ onClick: fn(),
+ },
+});
+
+export const ExternalLangfuseLink = meta.story({
+ name: "(Test) External Langfuse Link",
+ args: {
+ href: "https://langfuse.com/docs",
+ text: "View docs",
+ variant: "secondary",
+ },
+ play: async ({ canvasElement }) => {
+ const link = within(canvasElement).getByRole("link");
+ await expect(link).toHaveAttribute("target", "_blank");
+ await expect(link).toHaveAttribute("rel", "noopener");
+ await expect(link.querySelector("svg")).not.toBeNull();
+ },
+});
+
+export const ExternalLink = meta.story({
+ name: "(Test) External Link",
+ args: {
+ href: "https://example.com/docs",
+ text: "External docs",
+ variant: "secondary",
+ },
+ play: async ({ canvasElement }) => {
+ const link = within(canvasElement).getByRole("link");
+ await expect(link).toHaveAttribute("target", "_blank");
+ await expect(link).toHaveAttribute("rel", "noopener noreferrer");
+ await expect(link.querySelector("svg")).not.toBeNull();
+ },
+});
+
+export const SecondaryLink = meta.story({
+ name: "(Test) Secondary Link",
+ args: {
+ href: "/docs",
+ text: "View docs",
+ variant: "secondary",
+ },
+ play: async ({ canvasElement }) => {
+ await expect(within(canvasElement).getByRole("link")).toHaveAttribute(
+ "href",
+ "/docs",
+ );
+ },
+});
+
+export const Ghost = meta.story({
+ args: {
+ onClick: fn(),
+ text: "Reset",
+ variant: "ghost",
+ },
+});
+
+export const Loading = meta.story({
+ name: "(Test) Loading",
+ args: {
+ loading: true,
+ onClick: fn(),
+ },
+ play: async ({ canvasElement }) => {
+ await expect(within(canvasElement).getByRole("button")).toBeDisabled();
+ },
+});
+
+const onClick = fn();
+
+export const TestClick = meta.story({
+ name: "(Test) Click",
+ args: {
+ onClick,
+ },
+ play: async ({ canvasElement }) => {
+ onClick.mockClear();
+ await userEvent.click(within(canvasElement).getByRole("button"));
+ await expect(onClick).toHaveBeenCalledOnce();
+ },
+});
diff --git a/web/src/components/design-system/Button/Button.tsx b/web/src/components/design-system/Button/Button.tsx
new file mode 100644
index 0000000000..896b2a74b8
--- /dev/null
+++ b/web/src/components/design-system/Button/Button.tsx
@@ -0,0 +1,106 @@
+import { cva } from "class-variance-authority";
+import { ExternalLink } from "lucide-react";
+import Link from "next/link";
+import { type Ref } from "react";
+
+import { Spinner } from "@/src/components/design-system/Spinner/Spinner";
+
+const buttonVariants = cva(
+ "inline-flex h-8 items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-sm ring-offset-background transition-colors focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
+ {
+ variants: {
+ variant: {
+ primary: "bg-primary text-primary-foreground hover:bg-primary/90",
+ secondary:
+ "bg-secondary text-secondary-foreground hover:bg-secondary/80",
+ ghost: "hover:bg-accent hover:text-accent-foreground",
+ },
+ },
+ defaultVariants: {
+ variant: "primary",
+ },
+ },
+);
+
+type ButtonProps = {
+ text: string;
+ variant?: "primary" | "secondary" | "ghost";
+} & (
+ | {
+ href: string;
+ ref?: Ref<HTMLAnchorElement>;
+ disabled?: never;
+ loading?: never;
+ onClick?: never;
+ type?: never;
+ }
+ | ({
+ href?: never;
+ ref?: Ref<HTMLButtonElement>;
+ disabled?: boolean;
+ loading?: boolean;
+ } & (
+ | {
+ type?: "button";
+ onClick: () => void;
+ }
+ | {
+ type: "submit";
+ onClick?: never;
+ }
+ ))
+);
+
+export function Button(props: ButtonProps) {
+ const className = buttonVariants({ variant: props.variant });
+
+ if (props.href !== undefined) {
+ const isExternal =
+ props.href.startsWith("https://") || props.href.startsWith("http://");
+
+ if (isExternal) {
+ const hostname = new URL(props.href).hostname;
+ const isLangfuseDomain =
+ hostname === "langfuse.com" || hostname.endsWith(".langfuse.com");
+
+ return (
+ <a
+ className={`${className} gap-1`}
+ href={props.href}
+ ref={props.ref}
+ target="_blank"
+ rel={isLangfuseDomain ? "noopener" : "noopener noreferrer"}
+ >
+ {props.text}
+ <ExternalLink className="size-3" aria-hidden />
+ </a>
+ );
+ }
+
+ return (
+ <Link className={className} href={props.href} ref={props.ref}>
+ {props.text}
+ </Link>
+ );
+ }
+
+ return (
+ <button
+ className={className}
+ ref={props.ref}
+ type={props.type ?? "button"}
+ disabled={props.disabled || props.loading}
+ onClick={props.loading || props.disabled ? undefined : props.onClick}
+ aria-busy={props.loading}
+ aria-label={props.text}
+ >
+ {props.loading ? (
+ <span className="flex h-1/2 items-center justify-center">
+ <Spinner size="full" />
+ </span>
+ ) : (
+ props.text
+ )}
+ </button>
+ );
+}
diff --git a/web/src/components/design-system/Form/Form.stories.tsx b/web/src/components/design-system/Form/Form.stories.tsx
new file mode 100644
index 0000000000..3738810e88
--- /dev/null
+++ b/web/src/components/design-system/Form/Form.stories.tsx
@@ -0,0 +1,73 @@
+import { useForm } from "react-hook-form";
+import { expect, fn, userEvent, within } from "storybook/test";
+
+import preview from "../../../../.storybook/preview";
+import { Input } from "@/src/components/design-system/Input/Input";
+import { Form } from "./Form";
+
+function FormExample({
+ onCancel,
+ onSubmit,
+}: {
+ onCancel: () => void;
+ onSubmit: (values: { name: string }) => void;
+}) {
+ const form = useForm<{ name: string }>({
+ defaultValues: { name: "" },
+ });
+
+ return (
+ <Form
+ onSubmit={form.handleSubmit((values) => onSubmit(values))}
+ actions={[
+ { id: "save", type: "submit", text: "Save" },
+ {
+ id: "cancel",
+ type: "button",
+ text: "Cancel",
+ variant: "ghost",
+ onClick: onCancel,
+ },
+ ]}
+ >
+ <Form.Field control={form.control} name="name" label="Name">
+ {(field) => (
+ <Input
+ id={field.id}
+ name={field.name}
+ value={field.value}
+ onBlur={field.onBlur}
+ onChange={field.onChange}
+ ref={field.ref}
+ aria-describedby={field.inputDescribedById}
+ aria-invalid={Boolean(field.error)}
+ error={Boolean(field.error)}
+ />
+ )}
+ </Form.Field>
+ </Form>
+ );
+}
+
+const onCancel = fn();
+const onSubmit = fn();
+
+const meta = preview.meta({
+ component: FormExample,
+ args: { onCancel, onSubmit },
+});
+
+export const Default = meta.story({});
+
+export const Submits = meta.story({
+ name: "(Test) Submits",
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ onSubmit.mockClear();
+
+ await userEvent.type(canvas.getByLabelText("Name"), "PostHog");
+ await userEvent.click(canvas.getByRole("button", { name: "Save" }));
+
+ await expect(onSubmit).toHaveBeenCalledWith({ name: "PostHog" });
+ },
+});
diff --git a/web/src/components/design-system/Form/Form.tsx b/web/src/components/design-system/Form/Form.tsx
new file mode 100644
index 0000000000..575499b10d
--- /dev/null
+++ b/web/src/components/design-system/Form/Form.tsx
@@ -0,0 +1,67 @@
+import { type FormHTMLAttributes, type ReactNode } from "react";
+
+import { Button } from "@/src/components/design-system/Button/Button";
+import { FormField } from "@/src/components/design-system/FormField/FormField";
+
+export type FormAction = {
+ id: string;
+ text: string;
+ variant?: "primary" | "secondary" | "ghost";
+ disabled?: boolean;
+ loading?: boolean;
+} & (
+ | {
+ type: "submit";
+ onClick?: never;
+ }
+ | {
+ type: "button";
+ onClick: () => void;
+ }
+);
+
+export type FormProps = {
+ actions: FormAction[];
+ children: ReactNode;
+ onSubmit: FormHTMLAttributes<HTMLFormElement>["onSubmit"];
+};
+
+function FormRoot({ actions, children, onSubmit }: FormProps) {
+ return (
+ <form className="space-y-8" onSubmit={onSubmit}>
+ <div className="space-y-5">{children}</div>
+ <div className="flex gap-2">
+ {actions.map((action) => {
+ if (action.type === "submit") {
+ return (
+ <Button
+ key={action.id}
+ type="submit"
+ text={action.text}
+ variant={action.variant}
+ disabled={action.disabled}
+ loading={action.loading}
+ />
+ );
+ }
+
+ return (
+ <Button
+ key={action.id}
+ type="button"
+ text={action.text}
+ variant={action.variant}
+ disabled={action.disabled}
+ loading={action.loading}
+ onClick={action.onClick}
+ />
+ );
+ })}
+ </div>
+ </form>
+ );
+}
+
+export const Form = Object.assign(FormRoot, {
+ Field: FormField,
+});
diff --git a/web/src/components/design-system/FormField/FormField.stories.tsx b/web/src/components/design-system/FormField/FormField.stories.tsx
new file mode 100644
index 0000000000..68b6c75172
--- /dev/null
+++ b/web/src/components/design-system/FormField/FormField.stories.tsx
@@ -0,0 +1,119 @@
+import { useEffect } from "react";
+import { useForm } from "react-hook-form";
+import { expect, within } from "storybook/test";
+
+import preview from "../../../../.storybook/preview";
+import { CustomTooltip } from "@/src/components/design-system/CustomTooltip/CustomTooltip";
+import { Input } from "@/src/components/design-system/Input/Input";
+import { FormField } from "./FormField";
+
+function FormFieldExample({
+ description,
+ error,
+}: {
+ description?: string;
+ error?: string;
+}) {
+ const form = useForm<{ name: string }>({
+ defaultValues: { name: "" },
+ });
+
+ useEffect(() => {
+ if (error) {
+ form.setError("name", { message: error });
+ }
+ }, [error, form]);
+
+ return (
+ <FormField
+ control={form.control}
+ name="name"
+ label="Name"
+ description={description}
+ >
+ {(field) => (
+ <Input
+ id={field.id}
+ name={field.name}
+ value={field.value}
+ onBlur={field.onBlur}
+ onChange={field.onChange}
+ ref={field.ref}
+ aria-describedby={field.inputDescribedById}
+ aria-invalid={Boolean(field.error)}
+ error={Boolean(field.error)}
+ />
+ )}
+ </FormField>
+ );
+}
+
+const meta = preview.meta({
+ component: FormFieldExample,
+ args: {},
+});
+
+export const Default = meta.story({});
+
+export const WithDescription = meta.story({
+ name: "(Test) Description",
+ args: {
+ description: "Enter a descriptive name.",
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const input = canvas.getByLabelText("Name");
+ const description = canvas.getByText("Enter a descriptive name.");
+
+ await expect(input).toHaveAttribute("aria-describedby", description.id);
+ },
+});
+
+export const WithError = meta.story({
+ name: "(Test) Error",
+ args: {
+ description: "Enter a descriptive name.",
+ error: "Name is required.",
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const input = canvas.getByLabelText("Name");
+ const error = await canvas.findByText("Name is required.");
+
+ await expect(input).toHaveAttribute("aria-invalid", "true");
+ await expect(input.getAttribute("aria-describedby")).toContain(error.id);
+ },
+});
+
+export const WithLabelInfo = meta.story({
+ render: () => {
+ const form = useForm<{ name: string }>({ defaultValues: { name: "" } });
+
+ return (
+ <CustomTooltip content={<span>Additional context</span>} delay={0}>
+ {({ getTriggerProps }) => (
+ <FormField
+ control={form.control}
+ name="name"
+ label="Name"
+ registerLabelTooltip={getTriggerProps}
+ >
+ {(field) => (
+ <Input
+ id={field.id}
+ name={field.name}
+ value={field.value}
+ onBlur={field.onBlur}
+ onChange={field.onChange}
+ ref={field.ref}
+ aria-describedby={field.inputDescribedById}
+ aria-invalid={Boolean(field.error)}
+ error={Boolean(field.error)}
+ />
+ )}
+ </FormField>
+ )}
+ </CustomTooltip>
+ );
+ },
+});
diff --git a/web/src/components/design-system/FormField/FormField.tsx b/web/src/components/design-system/FormField/FormField.tsx
new file mode 100644
index 0000000000..179bca6b53
--- /dev/null
+++ b/web/src/components/design-system/FormField/FormField.tsx
@@ -0,0 +1,113 @@
+"use client";
+
+import { Info } from "lucide-react";
+import { useId, type ComponentProps, type ReactElement } from "react";
+import {
+ Controller,
+ type ControllerRenderProps,
+ type Control,
+ type FieldError,
+ type FieldPath,
+ type FieldValues,
+} from "react-hook-form";
+
+import { type CustomTooltip } from "@/src/components/design-system/CustomTooltip/CustomTooltip";
+
+type TooltipTriggerPropsGetter = Parameters<
+ ComponentProps<typeof CustomTooltip>["children"]
+>[0]["getTriggerProps"];
+
+export type FormFieldProps<
+ TFieldValues extends FieldValues,
+ TName extends FieldPath<TFieldValues>,
+ TTransformedValues extends FieldValues = TFieldValues,
+> = {
+ control: Control<TFieldValues, undefined, TTransformedValues>;
+ children: (
+ field: ControllerRenderProps<TFieldValues, TName> & {
+ error: FieldError | undefined;
+ id: string;
+ inputDescribedById: string | undefined;
+ },
+ ) => ReactElement;
+ description?: string;
+ label: string;
+ name: TName;
+ registerLabelTooltip?: TooltipTriggerPropsGetter;
+};
+
+export function FormField<
+ TFieldValues extends FieldValues,
+ TName extends FieldPath<TFieldValues>,
+ TTransformedValues extends FieldValues = TFieldValues,
+>({
+ control,
+ children,
+ description,
+ label,
+ name,
+ registerLabelTooltip,
+}: FormFieldProps<TFieldValues, TName, TTransformedValues>) {
+ const id = useId();
+ const controlId = `${id}-control`;
+ const descriptionId = `${id}-description`;
+ const errorId = `${id}-error`;
+
+ return (
+ <Controller
+ control={control}
+ name={name}
+ render={({ field, fieldState }) => {
+ const errorMessage = fieldState.error?.message;
+ const inputDescribedById = [
+ errorMessage ? errorId : undefined,
+ description ? descriptionId : undefined,
+ ]
+ .filter((value) => value !== undefined)
+ .join(" ");
+ return (
+ <div className="space-y-2">
+ <div className="flex items-center gap-1.5">
+ <label
+ htmlFor={controlId}
+ className="text-sm leading-none font-bold"
+ >
+ {label}
+ </label>
+ {registerLabelTooltip ? (
+ <button
+ type="button"
+ {...registerLabelTooltip()}
+ aria-label={`About ${label}`}
+ >
+ <Info
+ aria-hidden
+ className="text-muted-foreground size-3.5"
+ />
+ </button>
+ ) : null}
+ </div>
+ <div className="space-y-1">
+ {children({
+ ...field,
+ error: fieldState.error,
+ id: controlId,
+ inputDescribedById: inputDescribedById || undefined,
+ })}
+ {errorMessage ? (
+ <p id={errorId} className="text-destructive text-sm">
+ {errorMessage}
+ </p>
+ ) : null}
+ </div>
+ {description ? (
+ <p id={descriptionId} className="text-muted-foreground text-sm">
+ {description}
+ </p>
+ ) : null}
+ </div>
+ );
+ }}
+ />
+ );
+}
diff --git a/web/src/components/design-system/Input/Input.stories.tsx b/web/src/components/design-system/Input/Input.stories.tsx
index aa44c91522..8ac2d83669 100644
--- a/web/src/components/design-system/Input/Input.stories.tsx
+++ b/web/src/components/design-system/Input/Input.stories.tsx
@@ -26,6 +26,7 @@ export const Invalid = meta.story({
"aria-label": "Dataset name",
"aria-invalid": true,
defaultValue: "Existing dataset",
+ error: true,
},
});
diff --git a/web/src/components/design-system/Input/Input.tsx b/web/src/components/design-system/Input/Input.tsx
index 9dd10ca193..047d3a17d6 100644
--- a/web/src/components/design-system/Input/Input.tsx
+++ b/web/src/components/design-system/Input/Input.tsx
@@ -27,12 +27,18 @@ type InputProps = Pick<
| "value"
> & {
allowPasswordManager?: boolean;
+ error?: boolean;
ref?: Ref<HTMLInputElement>;
};
-export function Input({ allowPasswordManager, ref, ...props }: InputProps) {
+export function Input({
+ allowPasswordManager,
+ error,
+ ref,
+ ...props
+}: InputProps) {
return (
- <InputControl contentLayout="text">
+ <InputControl contentLayout="text" error={error}>
<input
{...props}
{...(!allowPasswordManager && { "data-1p-ignore": true })}
diff --git a/web/src/components/design-system/MultiSelectInput/MultiSelectInput.tsx b/web/src/components/design-system/MultiSelectInput/MultiSelectInput.tsx
index 7616af8972..982f39c0f9 100644
--- a/web/src/components/design-system/MultiSelectInput/MultiSelectInput.tsx
+++ b/web/src/components/design-system/MultiSelectInput/MultiSelectInput.tsx
@@ -25,6 +25,7 @@ type MultiSelectInputProps<V> = {
selectedLabel: string;
searchPlaceholder: string;
emptyMessage: string;
+ error?: boolean;
} & Pick<
React.ComponentPropsWithoutRef<"button">,
"id" | "aria-describedby" | "aria-invalid"
@@ -39,6 +40,7 @@ function MultiSelectInputInner<V extends string>(
selectedLabel,
searchPlaceholder,
emptyMessage,
+ error,
...triggerProps
}: MultiSelectInputProps<V>,
ref: React.ForwardedRef<HTMLButtonElement>,
@@ -51,7 +53,7 @@ function MultiSelectInputInner<V extends string>(
return (
<PopoverPrimitive.Root open={open} onOpenChange={setOpen}>
- <InputControl contentLayout="spread">
+ <InputControl contentLayout="spread" error={error}>
<PopoverPrimitive.Trigger
ref={ref}
type="button"
diff --git a/web/src/components/design-system/PasswordInput/PasswordInput.tsx b/web/src/components/design-system/PasswordInput/PasswordInput.tsx
index bc08b7f7a4..6711626161 100644
--- a/web/src/components/design-system/PasswordInput/PasswordInput.tsx
+++ b/web/src/components/design-system/PasswordInput/PasswordInput.tsx
@@ -23,16 +23,23 @@ type PasswordInputProps = Pick<
| "tabIndex"
| "value"
> & {
+ error?: boolean;
ref?: Ref<HTMLInputElement>;
};
-export function PasswordInput({ ref, disabled, ...props }: PasswordInputProps) {
+export function PasswordInput({
+ ref,
+ disabled,
+ error,
+ ...props
+}: PasswordInputProps) {
const [isPasswordVisible, setIsPasswordVisible] = useState(false);
const VisibilityIcon = isPasswordVisible ? EyeOff : Eye;
return (
<InputControl
contentLayout="text"
+ error={error}
trailingAction={{
label: isPasswordVisible ? "Hide password" : "Show password",
icon: VisibilityIcon,
diff --git a/web/src/components/design-system/SelectInput/SelectInput.tsx b/web/src/components/design-system/SelectInput/SelectInput.tsx
index f4f0d4f9f4..0b78bb422f 100644
--- a/web/src/components/design-system/SelectInput/SelectInput.tsx
+++ b/web/src/components/design-system/SelectInput/SelectInput.tsx
@@ -39,6 +39,7 @@ type SelectInputProps<V> = {
options: SelectInputNode<V>[];
onValueChange: (newValue: V) => void;
placeholder: string;
+ error?: boolean;
} & Pick<
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>,
"id" | "aria-describedby" | "aria-invalid" | "aria-label" | "disabled"
@@ -54,6 +55,7 @@ function SelectInputInner<V extends string>(
options,
onValueChange,
placeholder,
+ error,
...triggerProps
}: SelectInputProps<V>,
ref: React.ForwardedRef<HTMLButtonElement>,
@@ -124,7 +126,7 @@ function SelectInputInner<V extends string>(
open={open}
onOpenChange={setOpen}
>
- <InputControl contentLayout="spread">
+ <InputControl contentLayout="spread" error={error}>
<SelectPrimitive.Trigger
ref={ref}
title={selectedOption?.label}
diff --git a/web/src/components/design-system/SwitchInput/SwitchInput.stories.tsx b/web/src/components/design-system/SwitchInput/SwitchInput.stories.tsx
new file mode 100644
index 0000000000..494f2c7edb
--- /dev/null
+++ b/web/src/components/design-system/SwitchInput/SwitchInput.stories.tsx
@@ -0,0 +1,42 @@
+import { useState } from "react";
+import { expect, userEvent, within } from "storybook/test";
+
+import preview from "../../../../.storybook/preview";
+import { SwitchInput } from "./SwitchInput";
+
+function SwitchInputExample() {
+ const [checked, setChecked] = useState(true);
+
+ return (
+ <SwitchInput
+ id="integration-enabled"
+ aria-label="Enable integration"
+ description="Send data to PostHog while this integration is active."
+ checked={checked}
+ onCheckedChange={setChecked}
+ />
+ );
+}
+
+const meta = preview.meta({
+ component: SwitchInputExample,
+});
+
+export const Default = meta.story({});
+
+export const ChangesValue = meta.story({
+ name: "(Test) Changes value",
+ play: async ({ canvasElement }) => {
+ const control = within(canvasElement).getByRole("switch", {
+ name: "Enable integration",
+ });
+
+ await expect(control).toBeChecked();
+ await userEvent.click(
+ within(canvasElement).getByText(
+ "Send data to PostHog while this integration is active.",
+ ),
+ );
+ await expect(control).not.toBeChecked();
+ },
+});
diff --git a/web/src/components/design-system/SwitchInput/SwitchInput.tsx b/web/src/components/design-system/SwitchInput/SwitchInput.tsx
new file mode 100644
index 0000000000..6676e6f0d3
--- /dev/null
+++ b/web/src/components/design-system/SwitchInput/SwitchInput.tsx
@@ -0,0 +1,50 @@
+"use client";
+
+import { type ComponentPropsWithoutRef, type Ref } from "react";
+
+import { Switch } from "@/src/components/design-system/Switch/Switch";
+
+type SwitchInputProps = Pick<
+ ComponentPropsWithoutRef<typeof Switch>,
+ | "aria-describedby"
+ | "aria-invalid"
+ | "aria-label"
+ | "checked"
+ | "disabled"
+ | "name"
+ | "onBlur"
+ | "onCheckedChange"
+> & {
+ description: string;
+ id: string;
+ ref?: Ref<HTMLButtonElement>;
+};
+
+export function SwitchInput({
+ "aria-describedby": ariaDescribedBy,
+ description,
+ id,
+ ref,
+ ...props
+}: SwitchInputProps) {
+ const descriptionId = `${id}-description`;
+
+ return (
+ <label
+ htmlFor={id}
+ className="border-input bg-background flex min-h-8 cursor-pointer items-center justify-between gap-4 rounded-md border px-3 py-2"
+ >
+ <p id={descriptionId} className="text-muted-foreground min-w-0 text-sm">
+ {description}
+ </p>
+ <Switch
+ {...props}
+ id={id}
+ ref={ref}
+ aria-describedby={[descriptionId, ariaDescribedBy]
+ .filter((value) => value !== undefined)
+ .join(" ")}
+ />
+ </label>
+ );
+}
diff --git a/web/src/components/design-system/factories/createForm.tsx b/web/src/components/design-system/factories/createForm.tsx
new file mode 100644
index 0000000000..5a7639163a
--- /dev/null
+++ b/web/src/components/design-system/factories/createForm.tsx
@@ -0,0 +1,103 @@
+import { createContext, useContext, type ReactNode } from "react";
+import {
+ useForm as useReactHookForm,
+ type FieldPath,
+ type FieldValues,
+ type SubmitHandler,
+ type UseFormProps,
+ type UseFormReturn,
+} from "react-hook-form";
+
+import {
+ Form,
+ type FormAction,
+} from "@/src/components/design-system/Form/Form";
+import {
+ FormField,
+ type FormFieldProps,
+} from "@/src/components/design-system/FormField/FormField";
+
+/**
+ * Creates a form family whose root, fields, and hooks share the same value
+ * types. A factory is required because JSX children cannot infer their generic
+ * types from a parent component.
+ *
+ * `TInput` represents values before resolver transformation and `TOutput`
+ * represents the values passed to `onSubmit` afterward.
+ */
+export function createForm<
+ TInput extends FieldValues,
+ TOutput extends FieldValues = TInput,
+>() {
+ // Each form family gets an isolated context, preventing fields created by one
+ // factory call from accidentally consuming another family's form instance.
+ const FormContext = createContext<
+ UseFormReturn<TInput, undefined, TOutput> | undefined
+ >(undefined);
+
+ function useBoundFormContext() {
+ const form = useContext(FormContext);
+
+ if (!form) {
+ throw new Error(
+ "Form components must be rendered within their bound Form",
+ );
+ }
+
+ return form;
+ }
+
+ function BoundField<TName extends FieldPath<TInput>>({
+ children,
+ description,
+ label,
+ name,
+ registerLabelTooltip,
+ }: Omit<FormFieldProps<TInput, TName, TOutput>, "control">) {
+ const form = useBoundFormContext();
+
+ return (
+ <FormField
+ control={form.control}
+ name={name}
+ label={label}
+ description={description}
+ registerLabelTooltip={registerLabelTooltip}
+ >
+ {children}
+ </FormField>
+ );
+ }
+
+ function BoundForm({
+ actions,
+ children,
+ form,
+ onSubmit,
+ }: {
+ actions: FormAction[];
+ children: ReactNode;
+ form: UseFormReturn<TInput, undefined, TOutput>;
+ onSubmit: SubmitHandler<TOutput>;
+ }) {
+ return (
+ <FormContext.Provider value={form}>
+ <Form actions={actions} onSubmit={form.handleSubmit(onSubmit)}>
+ {children}
+ </Form>
+ </FormContext.Provider>
+ );
+ }
+
+ function useBoundForm(props: UseFormProps<TInput, undefined, TOutput>) {
+ return useReactHookForm<TInput, undefined, TOutput>(props);
+ }
+
+ // Object.assign preserves the compound-component API while exposing hooks
+ // that retain this factory invocation's input and output types.
+ return Object.assign(BoundForm, {
+ Field: BoundField,
+ useForm: useBoundForm,
+ useFormContext: useBoundFormContext,
+ });
+}
diff --git a/web/src/components/design-system/internal/InputControl/InputControl.tsx b/web/src/components/design-system/internal/InputControl/InputControl.tsx
index 0b0499e162..a89d366ea0 100644
--- a/web/src/components/design-system/internal/InputControl/InputControl.tsx
+++ b/web/src/components/design-system/internal/InputControl/InputControl.tsx
@@ -4,7 +4,7 @@ import { type LucideIcon } from "lucide-react";
import { type ComponentPropsWithoutRef } from "react";
const inputControlVariants = cva(
- "border-input bg-background ring-offset-background placeholder:text-foreground-tertiary focus-visible:ring-ring disabled:bg-muted/50 h-8 w-full rounded-md border px-3 py-2 text-sm file:border-0 file:bg-transparent file:text-sm file:font-bold focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-hidden disabled:cursor-not-allowed disabled:opacity-50",
+ "bg-background ring-offset-background placeholder:text-foreground-tertiary focus-visible:ring-ring disabled:bg-muted/50 h-8 w-full rounded-md border px-3 py-2 text-sm file:border-0 file:bg-transparent file:text-sm file:font-bold focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-hidden disabled:cursor-not-allowed disabled:opacity-50",
{
variants: {
contentLayout: {
@@ -15,6 +15,13 @@ const inputControlVariants = cva(
true: "pr-10",
false: null,
},
+ error: {
+ true: "border-destructive [&_svg]:text-destructive",
+ false: "border-input",
+ },
+ },
+ defaultVariants: {
+ error: false,
},
},
);
@@ -24,6 +31,7 @@ type InputControlProps = Omit<
"className"
> & {
contentLayout: "text" | "spread";
+ error?: boolean;
trailingAction?: {
label: string;
icon: LucideIcon;
@@ -41,6 +49,7 @@ type InputControlProps = Omit<
*/
export function InputControl({
contentLayout,
+ error,
trailingAction,
...props
}: InputControlProps) {
@@ -48,6 +57,7 @@ export function InputControl({
<Slot
className={inputControlVariants({
contentLayout,
+ error,
trailingAction: Boolean(trailingAction),
})}
{...props}
@@ -73,7 +83,9 @@ export function InputControl({
>
<TrailingActionIcon
aria-hidden="true"
- className="text-muted-foreground size-4"
+ className={
+ error ? "text-destructive size-4" : "text-muted-foreground size-4"
+ }
/>
</button>
</div>
diff --git a/web/src/features/posthog-integration/components/PostHogIntegrationForm.stories.tsx b/web/src/features/posthog-integration/components/PostHogIntegrationForm.stories.tsx
new file mode 100644
index 0000000000..1f7535b0e9
--- /dev/null
+++ b/web/src/features/posthog-integration/components/PostHogIntegrationForm.stories.tsx
@@ -0,0 +1,81 @@
+import { expect, fn, userEvent, within } from "storybook/test";
+
+import preview from "../../../../.storybook/preview";
+import { PostHogIntegrationForm } from "./PostHogIntegrationForm";
+
+const exportSourceContext = {
+ isCloud: false,
+ enrichedAvailable: true,
+ legacyWritesActive: true,
+};
+
+const meta = preview.meta({
+ component: PostHogIntegrationForm,
+ args: {
+ actionState: "idle" as const,
+ configurationState: "new" as const,
+ defaultValues: {
+ enabled: false,
+ exportSource: "EVENTS" as const,
+ posthogHostname: "https://us.posthog.com",
+ posthogProjectApiKey: "",
+ },
+ exportSourceContext,
+ onReset: fn(),
+ onSubmit: fn(),
+ },
+});
+
+export const NewIntegration = meta.story({});
+
+export const ExistingIntegration = meta.story({
+ args: {
+ configurationState: "configured" as const,
+ projectApiKeyDisplay: "phc_...cdef",
+ defaultValues: {
+ enabled: true,
+ exportSource: "EVENTS" as const,
+ posthogHostname: "https://eu.posthog.com",
+ posthogProjectApiKey: "",
+ },
+ },
+});
+
+export const ValidationErrors = meta.story({
+ name: "(Test) Validation errors",
+ args: {
+ defaultValues: {
+ enabled: false,
+ exportSource: "EVENTS" as const,
+ posthogHostname: "",
+ posthogProjectApiKey: "",
+ },
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+
+ await userEvent.click(canvas.getByRole("button", { name: "Save" }));
+
+ await expect(
+ canvas.getByText("PostHog Project API Key is required"),
+ ).toBeInTheDocument();
+ },
+});
+
+export const UnavailableExportSource = meta.story({
+ args: {
+ configurationState: "configured" as const,
+ projectApiKeyDisplay: "phc_...cdef",
+ defaultValues: {
+ enabled: true,
+ exportSource: "TRACES_OBSERVATIONS" as const,
+ posthogHostname: "https://us.posthog.com",
+ posthogProjectApiKey: "",
+ },
+ exportSourceContext: {
+ isCloud: false,
+ enrichedAvailable: true,
+ legacyWritesActive: false,
+ },
+ },
+});
diff --git a/web/src/features/posthog-integration/components/PostHogIntegrationForm.tsx b/web/src/features/posthog-integration/components/PostHogIntegrationForm.tsx
new file mode 100644
index 0000000000..2c7ddefb27
--- /dev/null
+++ b/web/src/features/posthog-integration/components/PostHogIntegrationForm.tsx
@@ -0,0 +1,267 @@
+/* eslint-disable @repo/no-abstracted-overlay-trigger */
+import { zodResolver } from "@hookform/resolvers/zod";
+import {
+ validateExportSource,
+ type ExportSourceContext,
+} from "@langfuse/shared";
+import { ExternalLink } from "lucide-react";
+import { useMemo } from "react";
+import { useWatch } from "react-hook-form";
+import { type z } from "zod";
+
+import { Alert } from "@/src/components/design-system/Alert/Alert";
+import { ConfirmationDialogController } from "@/src/components/design-system/ConfirmationDialogController/ConfirmationDialogController";
+import { CustomTooltip } from "@/src/components/design-system/CustomTooltip/CustomTooltip";
+import { createForm } from "@/src/components/design-system/factories/createForm";
+import { Input } from "@/src/components/design-system/Input/Input";
+import { PasswordInput } from "@/src/components/design-system/PasswordInput/PasswordInput";
+import { SelectInput } from "@/src/components/design-system/SelectInput/SelectInput";
+import { SwitchInput } from "@/src/components/design-system/SwitchInput/SwitchInput";
+import {
+ getExportSourceFieldState,
+ getExportSourceUnavailableMessage,
+ isExportSourceSelectable,
+} from "@/src/features/analytics-integrations/exportSource";
+import { posthogIntegrationFormSchema } from "@/src/features/posthog-integration/types";
+
+type PostHogIntegrationFormInput = z.input<typeof posthogIntegrationFormSchema>;
+
+export type PostHogIntegrationFormValues = z.output<
+ typeof posthogIntegrationFormSchema
+>;
+
+const PostHogForm = createForm<
+ PostHogIntegrationFormInput,
+ PostHogIntegrationFormValues
+>();
+const { useForm } = PostHogForm;
+
+type PostHogIntegrationFormProps = {
+ actionState: "idle" | "saving" | "resetting";
+ configurationState: "new" | "configured";
+ defaultValues: Required<PostHogIntegrationFormValues>;
+ // Required to validate the selected export source against deployment policy.
+ exportSourceContext: ExportSourceContext;
+ onReset: () => void | Promise<void>;
+ onSubmit: (values: PostHogIntegrationFormValues) => void;
+ projectApiKeyDisplay?: string;
+ resetError?: string;
+};
+
+export function PostHogIntegrationForm({
+ actionState,
+ configurationState,
+ defaultValues,
+ exportSourceContext,
+ onReset,
+ onSubmit,
+ projectApiKeyDisplay,
+ resetError,
+}: PostHogIntegrationFormProps) {
+ const { options: exportSourceOptions, showField: showExportSourceField } =
+ getExportSourceFieldState(defaultValues.exportSource, exportSourceContext);
+ const formSchema = useMemo(
+ () =>
+ posthogIntegrationFormSchema.superRefine((data, ctx) => {
+ if (configurationState === "new" && !data.posthogProjectApiKey) {
+ ctx.addIssue({
+ code: "custom",
+ path: ["posthogProjectApiKey"],
+ message: "PostHog Project API Key is required",
+ });
+ }
+ if (!isExportSourceSelectable(data.exportSource, exportSourceContext)) {
+ ctx.addIssue({
+ code: "custom",
+ path: ["exportSource"],
+ message:
+ "This export source is not available on this deployment. Select an available export source to save.",
+ });
+ }
+ }),
+ [configurationState, exportSourceContext],
+ );
+ const form = useForm({
+ resolver: zodResolver(formSchema),
+ defaultValues,
+ });
+ const exportSource = useWatch({
+ control: form.control,
+ name: "exportSource",
+ });
+ const exportSourceValidation = exportSource
+ ? validateExportSource(exportSource, exportSourceContext)
+ : ({ ok: true } as const);
+
+ return (
+ <ConfirmationDialogController
+ title="Reset PostHog integration?"
+ text="This resets the PostHog integration for this project."
+ confirmLabel="Reset integration"
+ variant="destructive"
+ disabled={configurationState === "new"}
+ loading={actionState === "resetting"}
+ error={resetError}
+ onConfirm={onReset}
+ >
+ {({ openDialog }) => (
+ <PostHogForm
+ form={form}
+ onSubmit={onSubmit}
+ actions={[
+ {
+ id: "save",
+ type: "submit",
+ text: "Save",
+ loading: actionState === "saving",
+ },
+ {
+ id: "reset",
+ type: "button",
+ text: "Reset",
+ variant: "ghost",
+ disabled: configurationState === "new",
+ onClick: openDialog,
+ },
+ ]}
+ >
+ <PostHogForm.Field
+ name="posthogHostname"
+ label="Posthog Hostname"
+ description="US region: https://us.posthog.com; EU region: https://eu.posthog.com"
+ >
+ {(field) => (
+ <Input
+ id={field.id}
+ name={field.name}
+ value={field.value}
+ onBlur={field.onBlur}
+ onChange={field.onChange}
+ ref={field.ref}
+ aria-describedby={field.inputDescribedById}
+ aria-invalid={Boolean(field.error)}
+ error={Boolean(field.error)}
+ />
+ )}
+ </PostHogForm.Field>
+ <PostHogForm.Field
+ name="posthogProjectApiKey"
+ label="Posthog Project API Key"
+ description={
+ configurationState === "configured"
+ ? "Leave blank to keep the current API key."
+ : undefined
+ }
+ >
+ {(field) => (
+ <PasswordInput
+ id={field.id}
+ name={field.name}
+ value={field.value}
+ onBlur={field.onBlur}
+ onChange={field.onChange}
+ ref={field.ref}
+ aria-describedby={field.inputDescribedById}
+ aria-invalid={Boolean(field.error)}
+ error={Boolean(field.error)}
+ placeholder={
+ configurationState === "configured"
+ ? projectApiKeyDisplay
+ : undefined
+ }
+ />
+ )}
+ </PostHogForm.Field>
+ {showExportSourceField ? (
+ <CustomTooltip
+ placement="bottom"
+ content={
+ <div className="space-y-2 py-1.5">
+ {exportSourceOptions.map((option) => (
+ <div key={option.value} className="space-y-0.5">
+ <div className="font-bold">{option.label}</div>
+ <div className="text-muted-foreground text-xs">
+ {option.description}
+ </div>
+ </div>
+ ))}
+ <div className="border-t pt-2">
+ <a
+ href="https://langfuse.com/docs/integrations/export-sources"
+ target="_blank"
+ rel="noopener noreferrer"
+ className="text-muted-foreground hover:text-primary inline-flex items-center gap-1 text-xs hover:underline"
+ >
+ For further information see
+ <ExternalLink className="size-3" />
+ </a>
+ </div>
+ </div>
+ }
+ >
+ {({ getTriggerProps }) => (
+ <PostHogForm.Field
+ name="exportSource"
+ label="Export Source"
+ description="Choose which data sources to export to PostHog. Scores are always included."
+ registerLabelTooltip={getTriggerProps}
+ >
+ {(field) => (
+ <SelectInput
+ id={field.id}
+ value={field.value}
+ onValueChange={field.onChange}
+ aria-describedby={field.inputDescribedById}
+ aria-invalid={Boolean(field.error)}
+ error={Boolean(field.error)}
+ placeholder="Select data to export"
+ options={exportSourceOptions.map((option) => {
+ if (option.unavailable) {
+ return {
+ value: option.value,
+ label: `${option.label} (not available on this deployment)`,
+ disabled: true as const,
+ disabledReason: "Not available on this deployment.",
+ };
+ }
+
+ return { value: option.value, label: option.label };
+ })}
+ />
+ )}
+ </PostHogForm.Field>
+ )}
+ </CustomTooltip>
+ ) : null}
+ {!exportSourceValidation.ok ? (
+ <Alert variant="destructive">
+ <Alert.Title>
+ Saved export source is no longer available
+ </Alert.Title>
+ <Alert.Description>
+ {getExportSourceUnavailableMessage(
+ exportSourceValidation.reason,
+ )}
+ </Alert.Description>
+ </Alert>
+ ) : null}
+ <PostHogForm.Field name="enabled" label="Enabled">
+ {(field) => (
+ <SwitchInput
+ id={field.id}
+ description="Send data to PostHog while this integration is active."
+ name={field.name}
+ checked={field.value}
+ onBlur={field.onBlur}
+ onCheckedChange={field.onChange}
+ ref={field.ref}
+ aria-describedby={field.inputDescribedById}
+ aria-invalid={Boolean(field.error)}
+ />
+ )}
+ </PostHogForm.Field>
+ </PostHogForm>
+ )}
+ </ConfirmationDialogController>
+ );
+}
diff --git a/web/src/features/posthog-integration/types.ts b/web/src/features/posthog-integration/types.ts
index a7debedb3a..8198de44a7 100644
--- a/web/src/features/posthog-integration/types.ts
+++ b/web/src/features/posthog-integration/types.ts
@@ -1,4 +1,3 @@
-import { AnalyticsIntegrationExportSource } from "@langfuse/shared";
import { z } from "zod";
export const posthogIntegrationFormSchema = z.object({
@@ -14,6 +13,6 @@ export const posthogIntegrationFormSchema = z.object({
.optional(),
enabled: z.boolean(),
exportSource: z
- .enum(AnalyticsIntegrationExportSource)
- .default(AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS),
+ .enum(["EVENTS", "TRACES_OBSERVATIONS", "TRACES_OBSERVATIONS_EVENTS"])
+ .default("TRACES_OBSERVATIONS"),
});
diff --git a/web/src/pages/project/[projectId]/settings/integrations/posthog.tsx b/web/src/pages/project/[projectId]/settings/integrations/posthog.tsx
index 20439b89f8..4be4dae38c 100644
--- a/web/src/pages/project/[projectId]/settings/integrations/posthog.tsx
+++ b/web/src/pages/project/[projectId]/settings/integrations/posthog.tsx
@@ -2,56 +2,33 @@ import { PostHogLogo } from "@/src/components/PosthogLogo";
import Header from "@/src/components/layouts/header";
import ContainerPage from "@/src/components/layouts/container-page";
import { StatusBadge } from "@/src/components/ui/StatusBadge/StatusBadge";
-import { Button } from "@/src/components/ui/button";
-import {
- Form,
- FormControl,
- FormDescription,
- FormField,
- FormItem,
- FormLabel,
- FormMessage,
-} from "@/src/components/ui/form";
-import { Input } from "@/src/components/ui/input";
-import { PasswordInput } from "@/src/components/design-system/PasswordInput/PasswordInput";
-import { SelectInput } from "@/src/components/design-system/SelectInput/SelectInput";
-import { Switch } from "@/src/components/design-system/Switch/Switch";
-import {
- Tooltip,
- TooltipTrigger,
- TooltipContent,
-} from "@/src/components/ui/tooltip";
+import { Button } from "@/src/components/design-system/Button/Button";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
-import { posthogIntegrationFormSchema } from "@/src/features/posthog-integration/types";
import { PostHogStatusSection } from "@/src/features/posthog-integration/components/PostHogStatusSection";
+import {
+ PostHogIntegrationForm,
+ type PostHogIntegrationFormValues,
+} from "@/src/features/posthog-integration/components/PostHogIntegrationForm";
import {
LEGACY_ANALYTICS_EXPORTER_CUTOFF,
- validateExportSource,
type V4WriteMode,
type ExportSourceContext,
} from "@langfuse/shared";
-import { Alert } from "@/src/components/design-system/Alert/Alert";
// Shared export-source UI adapters; policy in export-source-policy.ts.
import {
buildExportSourceContext,
- getExportSourceFieldState,
- getExportSourceUnavailableMessage,
- isExportSourceSelectable,
+ getExportSourceFormValue,
} from "@/src/features/analytics-integrations/exportSource";
import { useLangfuseCloudRegion } from "@/src/features/organizations/hooks";
import { useQueryProject } from "@/src/features/projects/hooks";
import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
import { api } from "@/src/utils/api";
import { type RouterOutput } from "@/src/utils/types";
-import { zodResolver } from "@hookform/resolvers/zod";
import { Card } from "@/src/components/ui/card";
import { IntegrationSettingsSkeleton } from "@/src/features/analytics-integrations/components/IntegrationSettingsSkeleton";
import Link from "next/link";
import { useRouter } from "next/router";
import { useMemo } from "react";
-import { useForm } from "react-hook-form";
-import { type z } from "zod";
-import { Info, ExternalLink } from "lucide-react";
export default function PosthogIntegrationSettings() {
const router = useRouter();
@@ -90,11 +67,11 @@ export default function PosthogIntegrationSettings() {
],
actionButtonsLeft: <>{status && <StatusBadge type={status} />}</>,
actionButtonsRight: (
- <Button asChild variant="secondary">
- <Link href="https://langfuse.com/integrations/analytics/posthog">
- Integration Docs ↗
- </Link>
- </Button>
+ <Button
+ href="https://langfuse.com/integrations/analytics/posthog"
+ text="Integration Docs"
+ variant="secondary"
+ />
),
}}
>
@@ -123,7 +100,7 @@ export default function PosthogIntegrationSettings() {
{!state.data || !project ? (
<IntegrationSettingsSkeleton />
) : (
- <PostHogIntegrationSettings
+ <ConnectedPostHogIntegrationForm
// Draft lifetime = entity identity, so background refetches
// cannot reset a draft in progress.
key={`${projectId}:${state.data.config ? "configured" : "new"}`}
@@ -143,7 +120,7 @@ export default function PosthogIntegrationSettings() {
);
}
-const PostHogIntegrationSettings = ({
+const ConnectedPostHogIntegrationForm = ({
state,
projectId,
writeMode,
@@ -172,53 +149,11 @@ const PostHogIntegrationSettings = ({
}),
[writeMode, isLangfuseCloud, projectCreatedAt, integrationCreatedAt],
);
- const {
- options: exportSourceOptions,
- showField: showExportSourceField,
- defaultValue: defaultExportSource,
- } = getExportSourceFieldState(state?.exportSource, exportSourceCtx);
-
- // Blocked-save validation instead of silent rewrite.
- const formSchema = useMemo(
- () =>
- posthogIntegrationFormSchema.superRefine((data, ctx) => {
- // The credential is write-only: blank keeps the saved key, so it is
- // only required when no integration exists yet.
- if (!state && !data.posthogProjectApiKey) {
- ctx.addIssue({
- code: "custom",
- path: ["posthogProjectApiKey"],
- message: "PostHog Project API Key is required",
- });
- }
- if (!isExportSourceSelectable(data.exportSource, exportSourceCtx)) {
- ctx.addIssue({
- code: "custom",
- path: ["exportSource"],
- message:
- "This export source is not available on this deployment. Select an available export source to save.",
- });
- }
- }),
- [exportSourceCtx, state],
+ const defaultExportSource = getExportSourceFormValue(
+ state?.exportSource,
+ exportSourceCtx,
);
- const posthogForm = useForm({
- resolver: zodResolver(formSchema),
- defaultValues: {
- posthogHostname: state?.posthogHostName ?? "",
- posthogProjectApiKey: "",
- enabled: state?.enabled ?? false,
- exportSource: defaultExportSource,
- },
- });
-
- const watchedExportSource = posthogForm.watch("exportSource");
- const watchedValidation =
- watchedExportSource != null
- ? validateExportSource(watchedExportSource, exportSourceCtx)
- : ({ ok: true } as const);
-
const utils = api.useUtils();
const mut = api.posthogIntegration.update.useMutation({
onSuccess: () => {
@@ -231,9 +166,7 @@ const PostHogIntegrationSettings = ({
},
});
- async function onSubmit(
- values: z.infer<typeof posthogIntegrationFormSchema>,
- ) {
+ function onSubmit(values: PostHogIntegrationFormValues) {
capture("integrations:posthog_form_submitted");
mut.mutate({
projectId,
@@ -242,167 +175,22 @@ const PostHogIntegrationSettings = ({
}
return (
- <Form {...posthogForm}>
- <form className="space-y-3" onSubmit={posthogForm.handleSubmit(onSubmit)}>
- <FormField
- control={posthogForm.control}
- name="posthogHostname"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Posthog Hostname</FormLabel>
- <FormControl>
- <Input {...field} />
- </FormControl>
- <FormDescription>
- US region: https://us.posthog.com; EU region:
- https://eu.posthog.com
- </FormDescription>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={posthogForm.control}
- name="posthogProjectApiKey"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Posthog Project API Key</FormLabel>
- <FormControl>
- <PasswordInput
- {...field}
- placeholder={state?.posthogApiKeyDisplay}
- />
- </FormControl>
- {state && (
- <FormDescription>
- Leave blank to keep the current API key.
- </FormDescription>
- )}
- <FormMessage />
- </FormItem>
- )}
- />
- {showExportSourceField && (
- <FormField
- control={posthogForm.control}
- name="exportSource"
- render={({ field }) => (
- <FormItem>
- <FormLabel className="flex items-center gap-1.5 pt-2">
- Export Source
- <Tooltip>
- <TooltipTrigger>
- <Info className="text-muted-foreground h-3.5 w-3.5" />
- </TooltipTrigger>
- <TooltipContent
- side="bottom"
- className="max-w-[350px] space-y-2 p-3"
- >
- {exportSourceOptions.map((option) => (
- <div key={option.value} className="space-y-0.5">
- <div className="font-bold">{option.label}</div>
- <div className="text-muted-foreground text-xs">
- {option.description}
- </div>
- </div>
- ))}
- <div className="border-t pt-2">
- <a
- href="https://langfuse.com/docs/integrations/export-sources"
- target="_blank"
- rel="noopener noreferrer"
- className="text-muted-foreground hover:text-primary inline-flex items-center gap-1 text-xs hover:underline"
- >
- For further information see
- <ExternalLink className="h-3 w-3" />
- </a>
- </div>
- </TooltipContent>
- </Tooltip>
- </FormLabel>
- <FormControl>
- <SelectInput
- onValueChange={field.onChange}
- value={field.value}
- placeholder="Select data to export"
- options={exportSourceOptions.map((option) => {
- if (option.unavailable) {
- return {
- value: option.value,
- label: `${option.label} (not available on this deployment)`,
- disabled: true as const,
- disabledReason: "Not available on this deployment.",
- };
- }
-
- return { value: option.value, label: option.label };
- })}
- />
- </FormControl>
- <FormDescription>
- Choose which data sources to export to PostHog. Scores are
- always included.
- </FormDescription>
- <FormMessage />
- </FormItem>
- )}
- />
- )}
- {!watchedValidation.ok && (
- <Alert variant="destructive">
- <Alert.Title>
- Saved export source is no longer available
- </Alert.Title>
- <Alert.Description>
- {getExportSourceUnavailableMessage(watchedValidation.reason)}
- </Alert.Description>
- </Alert>
- )}
- <FormField
- control={posthogForm.control}
- name="enabled"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Enabled</FormLabel>
- <FormControl>
- <div className="mt-1 ml-4">
- <Switch
- id="posthog-integration-enabled"
- checked={field.value}
- onCheckedChange={() => {
- field.onChange(!field.value);
- }}
- />
- </div>
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- </form>
- <div className="mt-8 flex gap-2">
- <Button
- loading={mut.isPending}
- onClick={posthogForm.handleSubmit(onSubmit)}
- >
- Save
- </Button>
- <Button
- variant="ghost"
- loading={mutDelete.isPending}
- disabled={!state}
- onClick={() => {
- if (
- confirm(
- "Are you sure you want to reset the PostHog integration for this project?",
- )
- )
- mutDelete.mutate({ projectId });
- }}
- >
- Reset
- </Button>
- </div>
- </Form>
+ <PostHogIntegrationForm
+ actionState={
+ mut.isPending ? "saving" : mutDelete.isPending ? "resetting" : "idle"
+ }
+ configurationState={state ? "configured" : "new"}
+ defaultValues={{
+ posthogHostname: state?.posthogHostName ?? "",
+ posthogProjectApiKey: "",
+ enabled: state?.enabled ?? false,
+ exportSource: defaultExportSource,
+ }}
+ exportSourceContext={exportSourceCtx}
+ projectApiKeyDisplay={state?.posthogApiKeyDisplay}
+ resetError={mutDelete.error?.message}
+ onSubmit={onSubmit}
+ onReset={() => mutDelete.mutateAsync({ projectId })}
+ />
);
};