Skip to content

The platform for continuously improving AI agents.

15.9 KB
Raw Blame
import { type ReactNode, useState } from "react";

import { ProviderLogo } from "@/components/model-provider-chip";
import { Button } from "@/components/ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuRadioGroup,
  DropdownMenuRadioItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Icon } from "@/components/ui/icons";
import { Input } from "@/components/ui/input";
import { PopoverContent } from "@/components/ui/popover";
import { Switch } from "@/components/ui/switch";
import { cn } from "@/lib/utils";

export interface EventField {
  label: string;
  operators: string[];
  type: string;
  options?: { value: string; label: string; provider?: string }[];
}
export function conditionOptions(
  field: EventField | undefined,
  rule: EventRule,
  value: string | number
) {
  if (!field?.options?.length) return undefined;
  const provider = rule.conditions.find(
    (condition) => condition.field === "provider" && condition.operator === "is"
  )?.value;
  const options = [
    ...new Map(
      field.options
        .filter((option) => !option.provider || !provider || option.provider === provider)
        .map((option) => [option.value, option])
    ).values(),
  ];
  if (value !== "" && !options.some((option) => option.value === String(value)))
    options.unshift({ label: String(value), value: String(value) });
  return options;
}

export interface EventPartner {
  id: string;
  label: string;
  connected: boolean;
  events: { id: string; label: string; fields: Record<string, EventField> }[];
}
export interface EventRule {
  partner: string;
  event: string;
  conditions: { field: string; operator: string; value: string | number }[];
}
const operatorLabel: Record<string, string> = {
  at_least: "is at least",
  at_most: "is at most",
  includes: "includes",
  is: "is",
  starts_with: "starts with",
};

export function RuleMenu({
  label,
  value,
  options,
  onChange,
  disabled,
}: {
  label: string;
  value: string;
  options: { value: string; label: string }[];
  onChange: (value: string) => void;
  disabled?: boolean;
}) {
  const shown = options.find((option) => option.value === value)?.label;
  return (
    <DropdownMenu>
      <DropdownMenuTrigger
        aria-label={label}
        className={cn(
          "inline-flex h-7 max-w-full min-w-0 cursor-pointer items-center gap-1.5 rounded-full border-0 bg-muted px-2.5 text-[13px] leading-5 font-medium text-card-foreground transition-[background-color,scale] duration-150 ease-out hover:bg-accent active:scale-[0.97] disabled:cursor-default disabled:active:scale-100 motion-reduce:transition-none focus-visible:ring-2 focus-visible:ring-ring/60 focus-visible:outline-none",
          !shown && "border border-border bg-transparent text-muted-foreground"
        )}
        data-slot="event-trigger-pill"
        disabled={disabled}
      >
        {label === "Integration partner" && value === "openrouter" && (
          <ProviderLogo providerLabel="OpenRouter" providerSlug="openrouter" />
        )}
        <span className="min-w-0 truncate">{shown ?? label}</span>
      </DropdownMenuTrigger>
      <DropdownMenuContent
        align="start"
        className="max-h-72 w-auto max-w-80 min-w-44 overflow-y-auto"
      >
        <DropdownMenuRadioGroup onValueChange={onChange} value={value}>
          {options.map((option) => (
            <DropdownMenuRadioItem
              className="gap-2 text-[13px]"
              key={option.value}
              value={option.value}
            >
              <span className="min-w-0 flex-1 truncate">{option.label}</span>
            </DropdownMenuRadioItem>
          ))}
        </DropdownMenuRadioGroup>
      </DropdownMenuContent>
    </DropdownMenu>
  );
}

export function EventTrigger({
  partners,
  rule,
  onChange,
  enabled,
  onEnabledChange,
  disabled,
  reason,
  preview,
}: {
  partners: EventPartner[];
  rule: EventRule;
  onChange: (rule: EventRule) => void;
  enabled: boolean;
  onEnabledChange: (enabled: boolean) => void;
  disabled?: boolean;
  reason?: string;
  preview?: { total: number; matched: number; models: { id: string; name?: string }[] };
}) {
  const [show, setShow] = useState(false);
  const [added, setAdded] = useState<number | null>(null);
  const partner = partners.find((item) => item.id === rule.partner);
  const event = partner?.events.find((item) => item.id === rule.event);
  const fields = event?.fields ?? {};
  const incomplete =
    !event ||
    rule.conditions.some((condition) => !fields[condition.field] || condition.value === "");
  const blocked =
    reason ||
    (!partner?.connected
      ? "Connect this integration to turn it on."
      : incomplete
        ? "Finish the rule to turn it on."
        : "");
  return (
    <section
      aria-label={`${partner?.label ?? "App"} event`}
      className="flex w-full min-w-0 flex-col gap-2.5 rounded-2xl bg-card p-3 text-card-foreground"
      data-slot="event-trigger"
    >
      <div className="flex h-6 min-w-0 items-center gap-2">
        <span className="flex min-w-0 flex-1 items-center gap-2 text-[13px] leading-tight font-medium tracking-[-0.01em]">
          <span
            className={cn(
              "inline-flex size-6 items-center justify-center rounded-md bg-muted",
              !enabled && "opacity-50 grayscale"
            )}
          >
            <ProviderLogo
              providerLabel={partner?.label ?? "Integration"}
              providerSlug={partner?.id}
            />
          </span>
          {partner?.label ?? "Integration"} event
        </span>
        <Switch
          aria-label="Enable event trigger"
          checked={enabled}
          className="rounded-full [&_[data-slot=switch-thumb]]:rounded-full"
          disabled={disabled || (!enabled && !!blocked)}
          onCheckedChange={onEnabledChange}
          size="sm"
        />
      </div>
      <div className="flex min-w-0 flex-col" data-slot="event-trigger-rule">
        <div className="flex min-w-0 items-start gap-1.5">
          <span className="w-9 flex-none text-[13px] leading-7 text-muted-foreground">When</span>
          <div className="flex min-w-0 flex-1 flex-wrap items-center gap-1.5">
            <RuleMenu
              disabled={disabled}
              label="Integration partner"
              onChange={(value) => {
                const next = partners.find((item) => item.id === value);
                onChange({ conditions: [], event: next?.events[0]?.id ?? "", partner: value });
              }}
              options={partners.map((item) => ({ label: item.label, value: item.id }))}
              value={rule.partner}
            />
            <RuleMenu
              disabled={disabled}
              label="Integration event"
              onChange={(value) => onChange({ ...rule, conditions: [], event: value })}
              options={(partner?.events ?? []).map((item) => ({
                label: item.label,
                value: item.id,
              }))}
              value={rule.event}
            />
          </div>
        </div>
        <div className="mt-0.75 -mb-0.75 flex min-w-0 flex-col">
          {rule.conditions.map((condition, index) => (
            <div
              className="group/condition flex min-w-0 items-start gap-1.5 py-0.75"
              data-slot="event-trigger-condition"
              key={`${index}:${condition.field}`}
            >
              <span className="w-9 flex-none text-[13px] leading-7 text-muted-foreground">and</span>
              <div className="flex min-w-0 flex-1 flex-wrap items-center gap-1.5">
                <span className="inline-flex max-w-full min-w-0 items-center gap-1.5">
                  <RuleMenu
                    disabled={disabled}
                    label={`Condition ${index + 1} field`}
                    onChange={(field) =>
                      onChange({
                        ...rule,
                        conditions: rule.conditions.map((item, i) =>
                          i === index
                            ? { field, operator: fields[field].operators[0], value: "" }
                            : item
                        ),
                      })
                    }
                    options={Object.entries(fields).map(([value, field]) => ({
                      label: field.label,
                      value,
                    }))}
                    value={condition.field}
                  />
                  {(fields[condition.field]?.operators.length ?? 0) > 1 ? (
                    <RuleMenu
                      disabled={disabled}
                      label={`Condition ${index + 1} comparison`}
                      onChange={(operator) =>
                        onChange({
                          ...rule,
                          conditions: rule.conditions.map((item, i) =>
                            i === index ? { ...item, operator } : item
                          ),
                        })
                      }
                      options={(fields[condition.field]?.operators ?? []).map((value) => ({
                        label: operatorLabel[value] ?? value,
                        value,
                      }))}
                      value={condition.operator}
                    />
                  ) : (
                    <span className="flex-none text-[13px] leading-7 text-muted-foreground">
                      {operatorLabel[condition.operator]}
                    </span>
                  )}
                </span>
                {conditionOptions(fields[condition.field], rule, condition.value) ? (
                  <RuleMenu
                    disabled={disabled}
                    label={`Value for ${fields[condition.field]?.label ?? "condition"}`}
                    onChange={(value) =>
                      onChange({
                        ...rule,
                        conditions: rule.conditions.map((item, i) =>
                          i === index ? { ...item, value } : item
                        ),
                      })
                    }
                    options={conditionOptions(fields[condition.field], rule, condition.value) ?? []}
                    value={String(condition.value)}
                  />
                ) : (
                  <Input
                    aria-label={`Value for ${fields[condition.field]?.label ?? "condition"}`}
                    autoComplete="off"
                    className="[field-sizing:content] h-7 w-auto max-w-full min-w-16 rounded-full border border-border bg-card px-2.5 text-[13px] leading-5 font-medium"
                    disabled={disabled}
                    min={0}
                    onChange={(event) =>
                      onChange({
                        ...rule,
                        conditions: rule.conditions.map((item, i) =>
                          i === index
                            ? {
                                ...item,
                                value:
                                  fields[item.field]?.type === "number" && event.target.value !== ""
                                    ? Number(event.target.value)
                                    : event.target.value,
                              }
                            : item
                        ),
                      })
                    }
                    onKeyDown={(event) => {
                      if (
                        event.key === "Backspace" &&
                        condition.value === "" &&
                        !event.nativeEvent.isComposing
                      ) {
                        event.preventDefault();
                        onChange({
                          ...rule,
                          conditions: rule.conditions.filter((_, i) => i !== index),
                        });
                      }
                    }}
                    placeholder="value"
                    ref={(element) => {
                      if (element && added === index) {
                        element.focus({ preventScroll: true });
                        setAdded(null);
                      }
                    }}
                    spellCheck={false}
                    style={{ width: `${Math.max(5, String(condition.value).length + 1)}ch` }}
                    type={fields[condition.field]?.type === "number" ? "number" : "text"}
                    value={condition.value}
                  />
                )}
              </div>
              <Button
                aria-label={`Remove condition ${index + 1}`}
                className="mt-0.5 flex-none rounded-full opacity-0 group-hover/condition:opacity-100 group-focus-within/condition:opacity-100 pointer-coarse:opacity-100"
                disabled={disabled}
                onClick={() =>
                  onChange({ ...rule, conditions: rule.conditions.filter((_, i) => i !== index) })
                }
                size="icon-xs"
                variant="ghost"
              >
                <Icon.close />
              </Button>
            </div>
          ))}
        </div>
        <div className="mt-1.5 flex min-h-7 min-w-0 items-center pl-[42px]">
          <Button
            className="-ml-2 h-7 rounded-full px-2 text-[13px] text-muted-foreground"
            disabled={disabled || !event || rule.conditions.length >= 20}
            onClick={() => {
              const field =
                Object.keys(fields).find(
                  (key) => !rule.conditions.some((item) => item.field === key)
                ) ?? Object.keys(fields)[0];
              if (field) {
                setAdded(rule.conditions.length);
                onChange({
                  ...rule,
                  conditions: [
                    ...rule.conditions,
                    { field, operator: fields[field].operators[0], value: "" },
                  ],
                });
              }
            }}
            size="xs"
            variant="ghost"
          >
            <Icon.add />
            Add a condition
          </Button>
        </div>
        {blocked && (
          <p className="m-0 px-0.5 pt-2 text-xs leading-4 text-muted-foreground" role="status">
            {blocked}
          </p>
        )}
      </div>
      {preview && (
        <div
          className="flex min-w-0 flex-col rounded-xl bg-background px-2.5 py-2"
          data-slot="event-trigger-match"
        >
          <div className="flex min-w-0 items-baseline gap-2">
            <output
              aria-live="polite"
              className="min-w-0 flex-1 text-[13px] leading-5 text-pretty tabular-nums"
            >
              Matches {preview.matched} of {preview.total} current models.
            </output>
            {preview.matched > 0 && (
              <button
                aria-expanded={show}
                className="flex-none cursor-pointer text-xs font-medium text-muted-foreground hover:text-card-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
                onClick={() => setShow(!show)}
                type="button"
              >
                {show ? "Hide" : "Show"}
              </button>
            )}
          </div>
          {show && preview.matched > 0 && (
            <ul className="m-0 flex min-w-0 list-none flex-col gap-1 p-0 pt-1.5">
              {preview.models.slice(0, 5).map((model) => (
                <li
                  className="truncate text-xs leading-4 text-muted-foreground"
                  key={model.id}
                  title={model.id}
                >
                  {model.name || model.id}
                </li>
              ))}
              {preview.matched > 5 && (
                <li className="text-xs leading-4 text-muted-foreground">
                  and {preview.matched - 5} more
                </li>
              )}
            </ul>
          )}
        </div>
      )}
    </section>
  );
}

export function EventTriggerPanel({ children }: { children: ReactNode }) {
  return (
    <PopoverContent
      align="end"
      className="w-[480px] max-w-[calc(100vw-1.5rem)] max-h-[80vh] overflow-auto rounded-2xl bg-card p-0"
    >
      {children}
    </PopoverContent>
  );
}