🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
refactor(web): Create design-system ConfirmationDialogController (#17492)
Ben Bachem1c1504fc8916
diff --git a/packages/config-eslint/next.js b/packages/config-eslint/next.jsindex b77cf277c2..75b99b2c64 100644--- a/packages/config-eslint/next.js+++ b/packages/config-eslint/next.js@@ -155,7 +155,6 @@ export default [},},rules: {- "@repo/no-abstracted-overlay-trigger": "warn","@repo/no-tailwind-overflow-scroll": "warn",// Custom rules from old config"@typescript-eslint/consistent-type-imports": [@@ -195,7 +194,6 @@ export default ["**/*.stories.{ts,tsx}",],rules: {- "@repo/no-abstracted-overlay-trigger": "off","@repo/no-tailwind-overflow-scroll": "off",},},diff --git a/packages/eslint-plugin/src/react-components.ts b/packages/eslint-plugin/src/react-components.tsindex db8b6a42eb..72e67f08a1 100644--- a/packages/eslint-plugin/src/react-components.ts+++ b/packages/eslint-plugin/src/react-components.ts@@ -433,6 +433,18 @@ function visitReturnExpressionsInStatement(}}+export function visitFunctionReturnExpressions(+ node: TSESTree.ArrowFunctionExpression | TSESTree.FunctionExpression,+ onReturnExpression: (node: TSESTree.Expression) => void,+) {+ if (node.type === AST_NODE_TYPES.ArrowFunctionExpression && node.expression) {+ onReturnExpression(node.body);+ return;+ }++ visitReturnExpressionsInStatement(node.body, onReturnExpression);+}+/*** Visits complete expressions returned by React components. Unlike the root* element visitor, this preserves fragments and sibling relationships fordiff --git a/packages/eslint-plugin/src/rules/no-abstracted-overlay-trigger.test.ts b/packages/eslint-plugin/src/rules/no-abstracted-overlay-trigger.test.tsindex 97d99c5ec8..8a4373ccff 100644--- a/packages/eslint-plugin/src/rules/no-abstracted-overlay-trigger.test.ts+++ b/packages/eslint-plugin/src/rules/no-abstracted-overlay-trigger.test.ts@@ -3,6 +3,59 @@ import * as typescriptEslintParser from "@typescript-eslint/parser";import rule from "./no-abstracted-overlay-trigger.js";+const ruleOptions = {+ overlayFamilies: [+ {+ module: "@/src/components/ui/dialog",+ root: "Dialog",+ trigger: "DialogTrigger",+ contents: ["DialogContent"],+ },+ {+ module: "@/src/components/ui/alert-dialog",+ root: "AlertDialog",+ trigger: "AlertDialogTrigger",+ contents: ["AlertDialogContent"],+ },+ {+ module: "@/src/components/ui/dropdown-menu",+ root: "DropdownMenu",+ trigger: "DropdownMenuTrigger",+ contents: ["DropdownMenuContent", "DropdownMenuSubContent"],+ },+ {+ module: "@/src/components/ui/drawer",+ root: "Drawer",+ trigger: "DrawerTrigger",+ contents: ["DrawerContent"],+ },+ {+ module: "@/src/components/ui/popover",+ root: "Popover",+ trigger: "PopoverTrigger",+ contents: ["PopoverContent"],+ },+ {+ module: "@/src/components/ui/sheet",+ root: "Sheet",+ trigger: "SheetTrigger",+ contents: ["SheetContent"],+ },+ ],+ overlayControllerFamilies: [+ {+ module:+ "@/src/components/design-system/ConfirmationDialogController/ConfirmationDialogController",+ root: "ConfirmationDialogController",+ },+ {+ module:+ "@/src/components/design-system/DialogController/DialogController",+ root: "DialogController",+ },+ ],+};+const ruleTester = new RuleTester({languageOptions: {parser: typescriptEslintParser,@@ -28,6 +81,31 @@ ruleTester.run("no-abstracted-overlay-trigger", rule, {`function Component({ fallback }) { if (fallback === null) return; if (!fallback) return <main />; return fallback; }`,`export default function () { return <main />; }`,`export default class Component {}`,+ `+ import { ConfirmationDialogController } from "@/src/components/design-system/ConfirmationDialogController/ConfirmationDialogController";++ export function ControllerOnly() {+ return <ConfirmationDialogController />;+ }+ `,+ `+ import { DialogController } from "@/src/components/design-system/DialogController/DialogController";++ export function ControllerOnly() {+ return <DialogController />;+ }+ `,+ `+ import { DialogController } from "@/src/components/design-system/DialogController/DialogController";++ export function DelegatingController({ children }) {+ return (+ <DialogController>+ {({ openDialog }) => children({ openDialog })}+ </DialogController>+ );+ }+ `,`import { Dialog, DialogContent } from "@/src/components/ui/dialog";@@ -191,8 +269,83 @@ ruleTester.run("no-abstracted-overlay-trigger", rule, {}}`,- ],+ ].map((test) =>+ typeof test === "string" ? { code: test, options: [ruleOptions] } : test,+ ),invalid: [+ {+ code: `+ import { DialogController } from "@/src/components/design-system/DialogController/DialogController";++ export function DeletePrompt() {+ return (+ <DialogController>+ {() => <><button>Delete</button></>}+ </DialogController>+ );+ }+ `,+ errors: [{ messageId: "abstractedTrigger" }],+ },+ {+ code: `+ import { DialogController } from "@/src/components/design-system/DialogController/DialogController";++ export function DeletePrompt() {+ return (+ <DialogController>+ {({ openDialog }) => <button onClick={openDialog}>Delete</button>}+ </DialogController>+ );+ }+ `,+ errors: [+ {+ messageId: "abstractedTrigger",+ data: { overlay: "DialogController" },+ },+ ],+ },+ {+ code: `+ import { DialogController } from "@/src/components/design-system/DialogController/DialogController";++ export function DeletePrompt() {+ return (+ <DialogController>+ {({ openDialog }) => {+ return <button onClick={openDialog}>Delete</button>;+ }}+ </DialogController>+ );+ }+ `,+ errors: [+ {+ messageId: "abstractedTrigger",+ data: { overlay: "DialogController" },+ },+ ],+ },+ {+ code: `+ import { ConfirmationDialogController } from "@/src/components/design-system/ConfirmationDialogController/ConfirmationDialogController";++ export function ArchiveButton({ children }) {+ return (+ <ConfirmationDialogController>+ {({ openDialog }) => <button onClick={openDialog}>Archive</button>}+ </ConfirmationDialogController>+ );+ }+ `,+ errors: [+ {+ messageId: "abstractedTrigger",+ data: { overlay: "ConfirmationDialogController" },+ },+ ],+ },{code: `import {@@ -550,5 +703,12 @@ ruleTester.run("no-abstracted-overlay-trigger", rule, {`,errors: [{ messageId: "abstractedTrigger" }],},- ],+ ].map((test) => ({+ ...test,+ errors: test.errors.map((error) => ({+ ...error,+ messageId: "abstractedTrigger" as const,+ })),+ options: [ruleOptions],+ })),});diff --git a/packages/eslint-plugin/src/rules/no-abstracted-overlay-trigger.ts b/packages/eslint-plugin/src/rules/no-abstracted-overlay-trigger.tsindex ae9f3ccf82..8b9c4d4c84 100644--- a/packages/eslint-plugin/src/rules/no-abstracted-overlay-trigger.ts+++ b/packages/eslint-plugin/src/rules/no-abstracted-overlay-trigger.ts@@ -1,46 +1,25 @@import { AST_NODE_TYPES, type TSESTree } from "@typescript-eslint/utils";-import { createComponentReturnExpressionVisitors } from "../react-components.js";+import {+ createComponentReturnExpressionVisitors,+ visitFunctionReturnExpressions,+} from "../react-components.js";import { createRule } from "../util.js";-const OVERLAY_FAMILIES = [+type Options = [{- module: "@/src/components/ui/dialog",- root: "Dialog",- trigger: "DialogTrigger",- contents: ["DialogContent"],+ overlayFamilies: Array<{+ module: string;+ root: string;+ trigger: string;+ contents: string[];+ }>;+ overlayControllerFamilies: Array<{+ module: string;+ root: string;+ }>;},- {- module: "@/src/components/ui/alert-dialog",- root: "AlertDialog",- trigger: "AlertDialogTrigger",- contents: ["AlertDialogContent"],- },- {- module: "@/src/components/ui/dropdown-menu",- root: "DropdownMenu",- trigger: "DropdownMenuTrigger",- contents: ["DropdownMenuContent", "DropdownMenuSubContent"],- },- {- module: "@/src/components/ui/drawer",- root: "Drawer",- trigger: "DrawerTrigger",- contents: ["DrawerContent"],- },- {- module: "@/src/components/ui/popover",- root: "Popover",- trigger: "PopoverTrigger",- contents: ["PopoverContent"],- },- {- module: "@/src/components/ui/sheet",- root: "Sheet",- trigger: "SheetTrigger",- contents: ["SheetContent"],- },-] as const;+];type JsxRenderableNode =| TSESTree.Expression@@ -120,6 +99,29 @@ function getEffectiveRoots(node: JsxRenderableNode): TSESTree.JSXElement[] {return child ? getEffectiveRoots(child) : [];}+function expressionRendersJsx(node: TSESTree.Expression): boolean {+ return (+ node.type === AST_NODE_TYPES.JSXElement ||+ node.type === AST_NODE_TYPES.JSXFragment+ );+}++function controllerOwnsPresentation(node: TSESTree.JSXElement): boolean {+ const child = getMeaningfulChild(node.children);+ if (+ child?.type !== AST_NODE_TYPES.ArrowFunctionExpression &&+ child?.type !== AST_NODE_TYPES.FunctionExpression+ ) {+ return false;+ }++ let ownsPresentation = false;+ visitFunctionReturnExpressions(child, (returnExpression) => {+ if (expressionRendersJsx(returnExpression)) ownsPresentation = true;+ });+ return ownsPresentation;+}+function jsxSubtreeContainsName(node: TSESTree.JSXElement | TSESTree.JSXFragment,names: Set<string>,@@ -150,7 +152,7 @@ function jsxSubtreeContainsName(return false;}-const rule = createRule<[], "abstractedTrigger">({+const rule = createRule<Options, "abstractedTrigger">({name: "no-abstracted-overlay-trigger",meta: {type: "problem",@@ -158,14 +160,52 @@ const rule = createRule<[], "abstractedTrigger">({description:"Disallow components that abstract an overlay trigger and its floating content together.",},- schema: [],+ schema: [+ {+ type: "object",+ additionalProperties: false,+ required: ["overlayFamilies", "overlayControllerFamilies"],+ properties: {+ overlayFamilies: {+ type: "array",+ items: {+ type: "object",+ additionalProperties: false,+ required: ["module", "root", "trigger", "contents"],+ properties: {+ module: { type: "string", minLength: 1 },+ root: { type: "string", minLength: 1 },+ trigger: { type: "string", minLength: 1 },+ contents: {+ type: "array",+ minItems: 1,+ items: { type: "string", minLength: 1 },+ },+ },+ },+ },+ overlayControllerFamilies: {+ type: "array",+ items: {+ type: "object",+ additionalProperties: false,+ required: ["module", "root"],+ properties: {+ module: { type: "string", minLength: 1 },+ root: { type: "string", minLength: 1 },+ },+ },+ },+ },+ },+ ],messages: {abstractedTrigger:"Do not abstract `{{overlay}}` trigger and content together. Keep the trigger in the parent tree and expose the overlay behavior through a controller/render prop.",},},- defaultOptions: [],- create(context) {+ defaultOptions: [{ overlayFamilies: [], overlayControllerFamilies: [] }],+ create(context, [{ overlayFamilies, overlayControllerFamilies }]) {const localImports = new Map<string, string>();const returnVisitors = createComponentReturnExpressionVisitors({@@ -174,7 +214,21 @@ const rule = createRule<[], "abstractedTrigger">({const localRootName = getJsxElementName(rootNode);if (!localRootName) continue;- for (const family of OVERLAY_FAMILIES) {+ for (const family of overlayControllerFamilies) {+ if (+ localImports.get(`${family.module}:${family.root}`) ===+ localRootName &&+ controllerOwnsPresentation(rootNode)+ ) {+ context.report({+ node: rootNode.openingElement,+ messageId: "abstractedTrigger",+ data: { overlay: family.root },+ });+ }+ }++ for (const family of overlayFamilies) {if (localImports.get(`${family.module}:${family.root}`) !==localRootName@@ -208,10 +262,15 @@ const rule = createRule<[], "abstractedTrigger">({return {ImportDeclaration(node) {- const family = OVERLAY_FAMILIES.find(+ const family = overlayFamilies.find(({ module }) => module === node.source.value,);- if (!family) return;+ const controllerFamily = overlayControllerFamilies.find(+ ({ module }) => module === node.source.value,+ );+ if (!family && !controllerFamily) {+ return;+ }for (const specifier of node.specifiers) {if (specifier.type !== AST_NODE_TYPES.ImportSpecifier) continue;@@ -220,7 +279,7 @@ const rule = createRule<[], "abstractedTrigger">({? specifier.imported.name: String(specifier.imported.value);localImports.set(- `${family.module}:${importedName}`,+ `${node.source.value}:${importedName}`,specifier.local.name,);}diff --git a/web/eslint.config.mjs b/web/eslint.config.mjsindex 319760ef2f..6dd1fd9824 100644--- a/web/eslint.config.mjs+++ b/web/eslint.config.mjs@@ -77,6 +77,74 @@ export default ["@repo/storybook-play-requires-test-name": "error",},},+ {+ name: "langfuse/web/no-abstracted-overlay-trigger",+ files: ["src/**/*.{ts,tsx}"],+ ignores: [+ "src/**/*.clienttest.{ts,tsx}",+ "src/**/*.servertest.{ts,tsx}",+ "src/**/*.test.{ts,tsx}",+ "src/**/*.story.{ts,tsx}",+ "src/**/*.stories.{ts,tsx}",+ ],+ rules: {+ "@repo/no-abstracted-overlay-trigger": [+ "warn",+ {+ overlayFamilies: [+ {+ module: "@/src/components/ui/dialog",+ root: "Dialog",+ trigger: "DialogTrigger",+ contents: ["DialogContent"],+ },+ {+ module: "@/src/components/ui/alert-dialog",+ root: "AlertDialog",+ trigger: "AlertDialogTrigger",+ contents: ["AlertDialogContent"],+ },+ {+ module: "@/src/components/ui/dropdown-menu",+ root: "DropdownMenu",+ trigger: "DropdownMenuTrigger",+ contents: ["DropdownMenuContent", "DropdownMenuSubContent"],+ },+ {+ module: "@/src/components/ui/drawer",+ root: "Drawer",+ trigger: "DrawerTrigger",+ contents: ["DrawerContent"],+ },+ {+ module: "@/src/components/ui/popover",+ root: "Popover",+ trigger: "PopoverTrigger",+ contents: ["PopoverContent"],+ },+ {+ module: "@/src/components/ui/sheet",+ root: "Sheet",+ trigger: "SheetTrigger",+ contents: ["SheetContent"],+ },+ ],+ overlayControllerFamilies: [+ {+ module:+ "@/src/components/design-system/ConfirmationDialogController/ConfirmationDialogController",+ root: "ConfirmationDialogController",+ },+ {+ module:+ "@/src/components/design-system/DialogController/DialogController",+ root: "DialogController",+ },+ ],+ },+ ],+ },+ },{...tailwindcssRecommendedConfig,ignores: [diff --git a/web/src/components/deleteButton.tsx b/web/src/components/deleteButton.tsxindex 8ed0889b05..95170b201c 100644--- a/web/src/components/deleteButton.tsx+++ b/web/src/components/deleteButton.tsx@@ -14,10 +14,9 @@ import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccesimport { type ProjectScope } from "@langfuse/shared";import { api } from "@/src/utils/api";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";-import { Input } from "@/src/components/ui/input";-import { Label } from "@/src/components/ui/label";import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";import { useHasEntitlement } from "@/src/features/entitlements/hooks";+import { ConfirmationDialogController } from "@/src/components/design-system/ConfirmationDialogController/ConfirmationDialogController";export type DeleteButtonProps = {itemId: string;@@ -88,7 +87,6 @@ export function DeleteButton({const [open, setOpen] = useState(false);const router = useRouter();const capture = usePostHogClientCapture();- const [deleteConfirmationInput, setDeleteConfirmationInput] = useState("");const hasAccess = useHasProjectAccess({ projectId, scope: scope });@@ -109,15 +107,76 @@ export function DeleteButton({capture,]);+ if (!deleteBlocker) {+ return (+ <ConfirmationDialogController+ title={`Delete ${entityToDeleteName}?`}+ text={+ customDeletePrompt ??+ `This action cannot be undone. It removes all the data associated with this ${entityToDeleteName}. If this is the project default, it will be deleted for all users.`+ }+ confirmationText={deleteConfirmation}+ confirmLabel={`Delete ${entityToDeleteName}`}+ variant="destructive"+ loading={isDeleteMutationLoading || isDeleted}+ onConfirm={() => executeDeleteMutation(onDeleteSuccess)}+ >+ {({ openDialog }) =>+ icon ? (+ <IconOnlyButton+ icon={<TrashIcon className="h-4 w-4" />}+ label={title ?? "Delete"}+ aria-label={ariaLabel ?? "delete"}+ disabledReason={+ hasAccess+ ? undefined+ : `You don't have permission to delete this ${entityToDeleteName}.`+ }+ variant={variant ?? "outline"}+ size={size ?? "icon"}+ className={className}+ disabled={!enabled}+ onClick={(event) => {+ event.stopPropagation();+ captureDeleteOpen(capture, isTableAction);+ onPopoverOpenChange?.(true);+ openDialog();+ }}+ />+ ) : (+ <Button+ variant={variant ?? "ghost"}+ size={size ?? "default"}+ title={title}+ aria-label={ariaLabel}+ className={className}+ disabled={!hasAccess || !enabled}+ onClick={(event) => {+ event.stopPropagation();+ captureDeleteOpen(capture, isTableAction);+ onPopoverOpenChange?.(true);+ openDialog();+ }}+ >+ {hasAccess ? (+ <TrashIcon className="mr-2 h-4 w-4" />+ ) : (+ <LockIcon className="mr-2 h-4 w-4" />+ )}+ Delete+ </Button>+ )+ }+ </ConfirmationDialogController>+ );+ }+return (<Popoverkey={itemId ?? "delete-action"}open={open}onOpenChange={(o) => {setOpen(o);- // Reset the type-to-confirm input on close so the confirmation must be- // re-typed each time (the component now stays mounted per table row).- if (!o) setDeleteConfirmationInput("");onPopoverOpenChange?.(o);}}>@@ -175,47 +234,7 @@ export function DeleteButton({</PopoverTrigger>)}<PopoverContent onClick={(e) => e.stopPropagation()}>- {deleteBlocker ?? (- <>- <h2 className="mb-3 font-bold">Please confirm</h2>- <p className="mb-3 max-w-72 text-sm">- {customDeletePrompt ??- `This action cannot be undone. It removes all the data associated with- this ${entityToDeleteName}. If this is the project default, it will be deleted for all users.`}- </p>- {deleteConfirmation && (- <div className="mb-4 grid w-full gap-1.5">- <Label htmlFor="delete-confirmation">- Type "{deleteConfirmation}" to confirm- </Label>- <Input- id="delete-confirmation"- value={deleteConfirmationInput}- onChange={(e) => setDeleteConfirmationInput(e.target.value)}- />- </div>- )}- <div className="flex justify-end space-x-4">- <Button- type="button"- variant="destructive"- loading={isDeleteMutationLoading || isDeleted}- onClick={() => {- if (- deleteConfirmation &&- deleteConfirmationInput !== deleteConfirmation- ) {- alert("Please type the correct confirmation");- return;- }- executeDeleteMutation(onDeleteSuccess);- }}- >- Delete {entityToDeleteName}- </Button>- </div>- </>- )}+ {deleteBlocker}</PopoverContent></Popover>);diff --git a/web/src/components/design-system/ConfirmationDialogController/ConfirmationDialogController.stories.tsx b/web/src/components/design-system/ConfirmationDialogController/ConfirmationDialogController.stories.tsxnew file mode 100644index 0000000000..75f4ac58a7--- /dev/null+++ b/web/src/components/design-system/ConfirmationDialogController/ConfirmationDialogController.stories.tsx@@ -0,0 +1,98 @@+import { expect, fn, userEvent, waitFor, within } from "storybook/test";++import preview from "../../../../.storybook/preview";+import { Button } from "@/src/components/ui/button";++import { ConfirmationDialogController } from "./ConfirmationDialogController";++const meta = preview.meta({+ component: ConfirmationDialogController,+ parameters: { layout: "centered" },+});++const onConfirm = fn();++export const StandardExample = meta.story({+ name: "Standard",+ args: {+ title: "Archive score config",+ text: "This score config will no longer be available for new scores.",+ confirmLabel: "Archive",+ variant: "destructive",+ onConfirm,+ children: ({ openDialog }) => (+ <Button onClick={openDialog}>Archive score config</Button>+ ),+ },+});++export const TypeToConfirmExample = meta.story({+ name: "Type to confirm",+ args: {+ title: "Delete project",+ text: "This action cannot be undone.",+ confirmationText: "my-project",+ confirmLabel: "Delete project",+ variant: "destructive",+ onConfirm,+ children: ({ openDialog }) => (+ <Button onClick={openDialog}>Delete project</Button>+ ),+ },+});++export const Standard = meta.story({+ name: "(Test) Standard",+ args: {+ title: "Archive score config",+ text: "This score config will no longer be available for new scores.",+ confirmLabel: "Archive",+ variant: "destructive",+ onConfirm,+ children: ({ openDialog }) => (+ <Button onClick={openDialog}>Archive score config</Button>+ ),+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const body = within(canvasElement.ownerDocument.body);+ onConfirm.mockClear();++ await userEvent.click(+ canvas.getByRole("button", { name: "Archive score config" }),+ );+ await userEvent.click(body.getByRole("button", { name: "Archive" }));++ await waitFor(() => expect(onConfirm).toHaveBeenCalledOnce());+ await waitFor(() =>+ expect(body.queryByRole("dialog")).not.toBeInTheDocument(),+ );+ },+});++export const TypeToConfirm = meta.story({+ name: "(Test) Type to confirm",+ args: {+ title: "Delete project",+ text: "This action cannot be undone.",+ confirmationText: "my-project",+ confirmLabel: "Delete project",+ variant: "destructive",+ onConfirm,+ children: ({ openDialog }) => (+ <Button onClick={openDialog}>Delete project</Button>+ ),+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const body = within(canvasElement.ownerDocument.body);+ await userEvent.click(+ canvas.getByRole("button", { name: "Delete project" }),+ );++ const confirmButton = body.getByRole("button", { name: "Delete project" });+ expect(confirmButton).toBeDisabled();+ await userEvent.type(body.getByRole("textbox"), "my-project");+ expect(confirmButton).toBeEnabled();+ },+});diff --git a/web/src/components/design-system/ConfirmationDialogController/ConfirmationDialogController.tsx b/web/src/components/design-system/ConfirmationDialogController/ConfirmationDialogController.tsxnew file mode 100644index 0000000000..7c393eef58--- /dev/null+++ b/web/src/components/design-system/ConfirmationDialogController/ConfirmationDialogController.tsx@@ -0,0 +1,105 @@+/* eslint-disable boundaries/dependencies */+"use client";++import * as React from "react";++import { Dialog } from "@/src/components/design-system/Dialog/Dialog";+import { DialogController } from "@/src/components/design-system/DialogController/DialogController";+import { Input } from "@/src/components/ui/input";+import { Label } from "@/src/components/ui/label";++function ConfirmationDialogController({+ children,+ confirmationText,+ confirmLabel,+ disabled = false,+ error,+ loading = false,+ onConfirm,+ text,+ title,+ variant,+}: {+ children: (control: {+ isOpen: boolean;+ openDialog: () => void;+ }) => React.ReactNode;+ confirmationText?: string;+ confirmLabel: string;+ disabled?: boolean;+ error?: string;+ loading?: boolean;+ onConfirm: () => void | Promise<void>;+ text: string;+ title: string;+ variant: "default" | "destructive";+}) {+ const [confirmationInput, setConfirmationInput] = React.useState("");+ const confirmationInputId = React.useId();+ const requiresConfirmationInput = Boolean(confirmationText);++ return (+ <DialogController+ onBeforeClose={() => !loading}+ onDismiss={() => setConfirmationInput("")}+ renderDialog={({ closeDialog }) => (+ <Dialog+ title={title}+ actions={[+ {+ disabled:+ disabled ||+ (requiresConfirmationInput &&+ confirmationInput !== confirmationText),+ label: confirmLabel,+ loading,+ onClick: async () => {+ try {+ await onConfirm();+ } catch {+ return;+ }+ closeDialog();+ setConfirmationInput("");+ },+ variant,+ },+ ]}+ >+ <Dialog.Body>+ <p className="text-muted-foreground text-sm">{text}</p>+ {error ? (+ <div className="rounded border border-red-200 bg-red-50 p-3 text-sm text-red-700">+ <p className="font-bold">Error:</p>+ <p className="whitespace-pre-wrap">{error}</p>+ </div>+ ) : null}+ {requiresConfirmationInput ? (+ <div className="grid gap-2">+ <Label+ htmlFor={confirmationInputId}+ className="flex flex-wrap items-center gap-1.5"+ >+ <span>To confirm, enter the required value:</span>+ <code className="bg-muted text-foreground rounded px-1.5 py-0.5 font-mono text-sm leading-none">+ {confirmationText}+ </code>+ </Label>+ <Input+ id={confirmationInputId}+ value={confirmationInput}+ onChange={(event) => setConfirmationInput(event.target.value)}+ disabled={loading}+ />+ </div>+ ) : null}+ </Dialog.Body>+ </Dialog>+ )}+ >+ {children}+ </DialogController>+ );+}++export { ConfirmationDialogController };diff --git a/web/src/components/table/use-cases/score-configs.tsx b/web/src/components/table/use-cases/score-configs.tsxindex c812aeeabc..290ab948d2 100644--- a/web/src/components/table/use-cases/score-configs.tsx+++ b/web/src/components/table/use-cases/score-configs.tsx@@ -31,7 +31,7 @@ import {DropdownMenuContent,DropdownMenuItem,} from "@/src/components/ui/dropdown-menu";-import { ArchiveScoreConfigPopoverController } from "@/src/features/score-configs/components/ArchiveScoreConfigButton";+import { ArchiveScoreConfigDialogController } from "@/src/features/score-configs/components/ArchiveScoreConfigDialogController";import { UpsertScoreConfigDialogController } from "@/src/features/score-configs/components/UpsertScoreConfigDialogController";type ScoreConfigTableRow = {@@ -174,21 +174,19 @@ export function ScoreConfigsTable({ projectId }: { projectId: string }) {}}>{({ disabled: editDisabled, Trigger }) => (- <ArchiveScoreConfigPopoverController+ <ArchiveScoreConfigDialogControllerconfigId={configId}projectId={projectId}isArchived={isArchived}name={name}>- {({ Anchor, disabled, openPopover }) => (+ {({ disabled, openDialog }) => (<DropdownMenu>- <Anchor asChild>- <DropdownMenuTrigger asChild>- <Button variant="ghost">- <MoreVertical className="h-4 w-4" />- </Button>- </DropdownMenuTrigger>- </Anchor>+ <DropdownMenuTrigger asChild>+ <Button variant="ghost">+ <MoreVertical className="h-4 w-4" />+ </Button>+ </DropdownMenuTrigger><DropdownMenuContent><Trigger asChild><DropdownMenuItem@@ -205,7 +203,7 @@ export function ScoreConfigsTable({ projectId }: { projectId: string }) {disabled={disabled !== undefined}title={disabled?.reason}onClick={(event) => event.stopPropagation()}- onSelect={openPopover}+ onSelect={openDialog}><Archive className="mr-2 h-4 w-4" />Archive@@ -213,7 +211,7 @@ export function ScoreConfigsTable({ projectId }: { projectId: string }) {</DropdownMenuContent></DropdownMenu>)}- </ArchiveScoreConfigPopoverController>+ </ArchiveScoreConfigDialogController>)}</UpsertScoreConfigDialogController>);diff --git a/web/src/features/evals/components/deactivate-config.tsx b/web/src/features/evals/components/deactivate-config.tsxindex 3a9e3e3af9..8fc29b1134 100644--- a/web/src/features/evals/components/deactivate-config.tsx+++ b/web/src/features/evals/components/deactivate-config.tsx@@ -3,13 +3,7 @@ import { useHasProjectAccess } from "@/src/features/rbac";import { EvaluatorStatus } from "@/src/features/evals/types";import { usePostHogClientCapture } from "@/src/features/posthog-analytics";import { api, type RouterOutputs } from "@/src/utils/api";-import { useState } from "react";-import {- Popover,- PopoverContent,- PopoverTrigger,-} from "@/src/components/ui/popover";-import { Button } from "@/src/components/ui/button";+import { ConfirmationDialogController } from "@/src/components/design-system/ConfirmationDialogController/ConfirmationDialogController";import { Switch } from "@/src/components/design-system/Switch/Switch";import { isLegacyEvalTarget } from "@/src/features/evals/utils/typeHelpers";import { useEvalCapabilities } from "@/src/features/evals/hooks/useEvalCapabilities";@@ -30,7 +24,6 @@ export function DeactivateEvalConfig({scope: "evaluationRule:CUD",});const { allowLegacy } = useEvalCapabilities(projectId);- const [isOpen, setIsOpen] = useState(false);const capture = usePostHogClientCapture();const isActive = evalConfig?.status === EvaluatorStatus.ACTIVE;// Where new legacy setups are not allowed (cloud), deactivating a legacy@@ -47,14 +40,12 @@ export function DeactivateEvalConfig({},});- const onClick = async () => {+ const onConfirm = async () => {if (!projectId) {console.error("Project ID is missing");return;}- // The popover trigger wraps the switch, so guard the action itself too.if (reactivationBlocked) {- setIsOpen(false);return;}@@ -68,10 +59,10 @@ export function DeactivateEvalConfig({status: isActive ? EvaluatorStatus.INACTIVE : EvaluatorStatus.ACTIVE,},});- } catch {+ } catch (error) {// The default mutation error toast reports the failure; the status is- // unchanged, so keep the popover open and skip the change callbacks.- return;+ // unchanged, so keep the dialog open and skip the change callbacks.+ throw error;}capture(prevStatus === EvaluatorStatus.ACTIVE@@ -79,12 +70,22 @@ export function DeactivateEvalConfig({: "eval_config:activate",);onStatusChange?.();- setIsOpen(false);};return (- <Popover open={isOpen} onOpenChange={() => setIsOpen(!isOpen)}>- <PopoverTrigger asChild>+ <ConfirmationDialogController+ title={isActive ? "Deactivate evaluator?" : "Activate evaluator?"}+ text={+ isActive+ ? "This action will deactivate the evaluator. No more traces will be evaluated based on this evaluator."+ : "This action will activate the evaluator. New traces will be evaluated based on this evaluator."+ }+ confirmLabel={isActive ? "Deactivate" : "Activate"}+ variant={isActive ? "destructive" : "default"}+ loading={mutEvaluator.isPending}+ onConfirm={onConfirm}+ >+ {({ openDialog }) => (<div className="flex items-center"><Switchdisabled={@@ -95,33 +96,14 @@ export function DeactivateEvalConfig({}checked={isActive}color="green"+ onClick={openDialog}{...(reactivationBlocked && {title:"Deprecated evaluators cannot be reactivated. Migrate to the new evaluators instead.",})}/></div>- </PopoverTrigger>- <PopoverContent>- <h2 className="mb-3 font-bold">Please confirm</h2>- <p className="mb-3 text-sm">- {evalConfig?.status === "ACTIVE"- ? "This action will deactivate the evaluator. No more traces will be evaluated based on this evaluator."- : "This action will activate the evaluator. New traces will be evaluated based on this evaluator."}- </p>- <div className="flex justify-end space-x-4">- <Button- type="button"- variant={- evalConfig?.status === "ACTIVE" ? "destructive" : "default"- }- loading={mutEvaluator.isPending}- onClick={onClick}- >- {evalConfig?.status === "ACTIVE" ? "Deactivate" : "Activate"}- </Button>- </div>- </PopoverContent>- </Popover>+ )}+ </ConfirmationDialogController>);}diff --git a/web/src/features/evals/components/default-eval-model-setup.tsx b/web/src/features/evals/components/default-eval-model-setup.tsxindex 69defe46b3..944f6c6aad 100644--- a/web/src/features/evals/components/default-eval-model-setup.tsx+++ b/web/src/features/evals/components/default-eval-model-setup.tsx@@ -1,4 +1,4 @@-/* eslint-disable @repo/no-abstracted-overlay-trigger, @repo/no-style-props */+/* eslint-disable @repo/no-style-props, @repo/no-abstracted-overlay-trigger */import { useHasProjectAccess } from "@/src/features/rbac";import { ModelParameters } from "@/src/components/ModelParameters";import { CardContent, Card } from "@/src/components/ui/card";@@ -18,13 +18,7 @@ import {} from "@/src/components/ui/dialog";import { getFinalModelParams } from "@/src/utils/getFinalModelParams";import { Pencil } from "lucide-react";-import {- Popover,- PopoverContent,- PopoverTrigger,-} from "@/src/components/ui/popover";-import { Label } from "@/src/components/ui/label";-import { Input } from "@/src/components/ui/input";+import { ConfirmationDialogController } from "@/src/components/design-system/ConfirmationDialogController/ConfirmationDialogController";type DefaultEvalModelSuccessMessage = {title: string;@@ -228,6 +222,7 @@ export function DefaultEvalModelSetup({<UpdateButtonprojectId={projectId}isLoading={setup.isUpsertLoading}+ error={setup.formError ?? undefined}executeUpsertMutation={setup.executeUpsertMutation}/>) : (@@ -295,68 +290,41 @@ export function InlineDefaultEvalModelSetup({function UpdateButton({projectId,isLoading,+ error,executeUpsertMutation,}: {projectId: string;isLoading: boolean;- executeUpsertMutation: () => void;+ error?: string;+ executeUpsertMutation: () => Promise<void>;}) {- const [confirmationInput, setConfirmationInput] = useState("");const hasWriteAccess = useHasProjectAccess({projectId,scope: "evalDefaultModel:CUD",});- const CONFIRMATION = "update";-return (- <Popover key="update-action">- <PopoverTrigger asChild>+ <ConfirmationDialogController+ title="Update default model?"+ text="Updating the default model will impact any currently running evaluators that use it. Please confirm that you want to proceed with this change."+ confirmationText="update"+ confirmLabel="Confirm"+ variant="default"+ loading={isLoading}+ error={error}+ onConfirm={executeUpsertMutation}+ >+ {({ openDialog }) => (<Buttondisabled={!hasWriteAccess}onClick={(e) => {e.stopPropagation();+ openDialog();}}>Update</Button>- </PopoverTrigger>- <PopoverContent- onClick={(e) => e.stopPropagation()}- className="w-fit max-w-[500px]"- >- <h2 className="mb-3 font-bold">Please confirm</h2>- <p className="mb-3 text-sm">- Updating the default model will impact any currently running- evaluators that use it. Please confirm that you want to proceed with- this change.- </p>- <div className="mb-4 grid w-full gap-1.5">- <Label htmlFor="update-confirmation">- Type "{CONFIRMATION}" to confirm- </Label>- <Input- id="update-confirmation"- value={confirmationInput}- onChange={(e) => setConfirmationInput(e.target.value)}- />- </div>- <div className="flex justify-end space-x-4">- <Button- type="button"- loading={isLoading}- onClick={() => {- if (confirmationInput !== CONFIRMATION) {- alert("Please type the correct confirmation");- return;- }- executeUpsertMutation();- }}- >- Confirm- </Button>- </div>- </PopoverContent>- </Popover>+ )}+ </ConfirmationDialogController>);}diff --git a/web/src/features/models/components/DeleteModelButton.tsx b/web/src/features/models/components/DeleteModelButton.tsxindex 333d6f1caa..5d9c8fc810 100644--- a/web/src/features/models/components/DeleteModelButton.tsx+++ b/web/src/features/models/components/DeleteModelButton.tsx@@ -1,16 +1,11 @@/* eslint-disable @repo/no-abstracted-overlay-trigger */import { useHasProjectAccess } from "@/src/features/rbac";-import { useState } from "react";-import { Button } from "@/src/components/ui/button";-import {- Popover,- PopoverContent,- PopoverTrigger,-} from "@/src/components/ui/popover";+import { ConfirmationDialogController } from "@/src/components/design-system/ConfirmationDialogController/ConfirmationDialogController";import { type GetModelResult } from "@/src/features/models/validation";import { usePostHogClientCapture } from "@/src/features/posthog-analytics";-import { api } from "@/src/utils/api";+import { api, reportTrpcErrorWithoutToast } from "@/src/utils/api";+import { useState } from "react";export const DeleteModelButton = ({modelData,@@ -21,14 +16,16 @@ export const DeleteModelButton = ({projectId: string;onSuccess?: () => void;}) => {- const [isOpen, setIsOpen] = useState(false);const utils = api.useUtils();const capture = usePostHogClientCapture();+ const [error, setError] = useState<string | undefined>();const mut = api.models.delete.useMutation({onSuccess: () => {utils.models.invalidate();+ setError(undefined);onSuccess?.();},+ onError: (error) => setError(error.message),});const hasAccess = useHasProjectAccess({@@ -37,41 +34,40 @@ export const DeleteModelButton = ({});return (- <Popover open={isOpen} onOpenChange={() => setIsOpen(!isOpen)}>- <PopoverTrigger asChild>+ <ConfirmationDialogController+ title="Delete model?"+ text="This action permanently deletes this model definition."+ confirmLabel="Delete model"+ variant="destructive"+ error={error}+ loading={mut.isPending}+ onConfirm={async () => {+ capture("models:delete_button_click");+ try {+ await mut.mutateAsync({+ projectId,+ modelId: modelData.id,+ });+ } catch (error) {+ reportTrpcErrorWithoutToast(error, "models");+ throw error;+ }+ }}+ >+ {({ openDialog }) => (<Buttonvariant="outline"title="Delete model"disabled={!hasAccess}className="border-light-red flex items-center"+ onClick={() => {+ setError(undefined);+ openDialog();+ }}><span className="text-dark-red">Delete</span></Button>- </PopoverTrigger>- <PopoverContent>- <h2 className="mb-3 font-bold">Please confirm</h2>- <p className="mb-3 text-sm">- This action permanently deletes this model definition.- </p>- <div className="flex justify-end space-x-4">- <Button- type="button"- variant="destructive"- loading={mut.isPending}- onClick={() => {- capture("models:delete_button_click");- mut.mutateAsync({- projectId,- modelId: modelData.id,- });-- setIsOpen(false);- }}- >- Delete Model- </Button>- </div>- </PopoverContent>- </Popover>+ )}+ </ConfirmationDialogController>);};diff --git a/web/src/features/score-configs/components/ArchiveScoreConfigButton.tsx b/web/src/features/score-configs/components/ArchiveScoreConfigButton.tsxdeleted file mode 100644index 8c19eb15aa..0000000000--- a/web/src/features/score-configs/components/ArchiveScoreConfigButton.tsx+++ /dev/null@@ -1,97 +0,0 @@-import { useHasProjectAccess } from "@/src/features/rbac";-import { Button } from "@/src/components/ui/button";-import { PopoverController } from "@/src/components/ui/popover";-import type * as React from "react";-import { usePostHogClientCapture } from "@/src/features/posthog-analytics";-import { api } from "@/src/utils/api";-import { useEmptyScoreConfigs } from "@/src/features/scores";--type ArchiveScoreConfigPopoverControllerProps = {- children: (- control: Omit<- Parameters<React.ComponentProps<typeof PopoverController>["children"]>[0],- "disabled"- > & { disabled: { reason: string } | undefined },- ) => React.ReactNode;- configId: string;- projectId: string;- isArchived: boolean;- name: string;-};--export const ArchiveScoreConfigPopoverController = ({- children,- configId,- projectId,- isArchived,- name,-}: ArchiveScoreConfigPopoverControllerProps) => {- const capture = usePostHogClientCapture();- const { emptySelectedConfigIds, setEmptySelectedConfigIds } =- useEmptyScoreConfigs();-- const hasAccess = useHasProjectAccess({- projectId: projectId,- scope: "scoreConfigs:CUD",- });-- const utils = api.useUtils();- const configMutation = api.scoreConfigs.update.useMutation({- onSuccess: () => utils.scoreConfigs.invalidate(),- });-- const disabled = hasAccess- ? undefined- : { reason: "You don't have permission to archive this score config." };-- return (- <PopoverController- align="center"- contentClassName="max-w-[500px]"- disabled={disabled !== undefined}- modal- onOpenChange={(isOpen) => {- if (isOpen && hasAccess) {- capture("score_configs:archive_form_open");- }- }}- renderContent={() => (- <>- <h2 className="mb-3 font-bold">- {isArchived ? "Restore config" : "Archive config"}- </h2>- <p className="mb-3 text-sm">- Your config is currently{" "}- {isArchived- ? `archived. Restore if you want to use "${name}" in annotation again.`- : `active. Archive if you no longer want to use "${name}" in annotation. Historic "${name}" scores will still be shown and can be deleted. You can restore your config at any point.`}- </p>- <div className="flex justify-end space-x-4">- <Button- type="button"- variant={isArchived ? "default" : "destructive"}- loading={configMutation.isPending}- onClick={() => {- configMutation.mutateAsync({- projectId,- id: configId,- isArchived: !isArchived,- });- setEmptySelectedConfigIds(- emptySelectedConfigIds.filter((id) => id !== configId),- );- capture("score_configs:archive_form_submit");- }}- >- Confirm- </Button>- </div>- </>- )}- >- {({ Anchor, isOpen, openPopover, Trigger }) =>- children({ disabled, isOpen, openPopover, Anchor, Trigger })- }- </PopoverController>- );-};diff --git a/web/src/features/score-configs/components/ArchiveScoreConfigDialogController.tsx b/web/src/features/score-configs/components/ArchiveScoreConfigDialogController.tsxnew file mode 100644index 0000000000..be526710ee--- /dev/null+++ b/web/src/features/score-configs/components/ArchiveScoreConfigDialogController.tsx@@ -0,0 +1,78 @@+import type * as React from "react";++import { ConfirmationDialogController } from "@/src/components/design-system/ConfirmationDialogController/ConfirmationDialogController";+import { useHasProjectAccess } from "@/src/features/rbac";+import { usePostHogClientCapture } from "@/src/features/posthog-analytics";+import { useEmptyScoreConfigs } from "@/src/features/scores";+import { api } from "@/src/utils/api";++type ArchiveScoreConfigDialogControllerProps = {+ children: (control: {+ disabled: { reason: string } | undefined;+ isOpen: boolean;+ openDialog: () => void;+ }) => React.ReactNode;+ configId: string;+ projectId: string;+ isArchived: boolean;+ name: string;+};++export const ArchiveScoreConfigDialogController = ({+ children,+ configId,+ projectId,+ isArchived,+ name,+}: ArchiveScoreConfigDialogControllerProps) => {+ const capture = usePostHogClientCapture();+ const { emptySelectedConfigIds, setEmptySelectedConfigIds } =+ useEmptyScoreConfigs();+ const hasAccess = useHasProjectAccess({+ projectId,+ scope: "scoreConfigs:CUD",+ });+ const utils = api.useUtils();+ const configMutation = api.scoreConfigs.update.useMutation({+ onSuccess: () => utils.scoreConfigs.invalidate(),+ });+ const disabled = hasAccess+ ? undefined+ : { reason: "You don't have permission to archive this score config." };++ return (+ <ConfirmationDialogController+ title={isArchived ? "Restore config" : "Archive config"}+ text={+ isArchived+ ? `Your config is currently archived. Restore if you want to use "${name}" in annotation again.`+ : `Your config is currently active. Archive if you no longer want to use "${name}" in annotation. Historic "${name}" scores will still be shown and can be deleted. You can restore your config at any point.`+ }+ confirmLabel="Confirm"+ variant={isArchived ? "default" : "destructive"}+ loading={configMutation.isPending}+ onConfirm={async () => {+ await configMutation.mutateAsync({+ projectId,+ id: configId,+ isArchived: !isArchived,+ });+ setEmptySelectedConfigIds(+ emptySelectedConfigIds.filter((id) => id !== configId),+ );+ capture("score_configs:archive_form_submit");+ }}+ >+ {({ isOpen, openDialog }) =>+ children({+ disabled,+ isOpen,+ openDialog: () => {+ capture("score_configs:archive_form_open");+ openDialog();+ },+ })+ }+ </ConfirmationDialogController>+ );+};