🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
Add autocapture event tracking and update translations for multiple languages
Bill Yang48408998561e
diff --git a/client/messages/cs.json b/client/messages/cs.jsonindex 8e65df1f5..82d46c17b 100644--- a/client/messages/cs.json+++ b/client/messages/cs.json@@ -488,7 +488,7 @@"rIc2Hm": "Aktualizovat trychtýř","m1czzY": "Událost","KP63fg": "",- "baRFiF": "",+ "baRFiF": "Formulář","29V0Ci": "relací","lHFZhY": "{count} odpadlo","zIaJNz": "Dosáhlo ({count})",@@ -1603,5 +1603,14 @@"QOaR8l": "","IQ5tZg": "","+B+qvw": "",- "vDpLV2": ""+ "vDpLV2": "",+ "E2rh1p": "Tlačítka",+ "yGsZm0": "Formuláře",+ "y3qXTf": "Kopie",+ "eHclX+": "Odeslání formulářů",+ "d6avGo": "Odeslání",+ "JaJoAk": "Text tlačítka",+ "UgH9Vn": "Zkopírovaný text",+ "J+At6e": "Naposledy odesláno",+ "LovNd5": "Naposledy zkopírováno"}diff --git a/client/messages/de.json b/client/messages/de.jsonindex ad0c713f3..971e83a33 100644--- a/client/messages/de.json+++ b/client/messages/de.json@@ -488,7 +488,7 @@"rIc2Hm": "Trichter aktualisieren","m1czzY": "Ereignis","KP63fg": "",- "baRFiF": "",+ "baRFiF": "Formular","29V0Ci": "Sitzungen","lHFZhY": "{count} abgebrochen","zIaJNz": "Erreicht ({count})",@@ -1603,5 +1603,14 @@"QOaR8l": "Formular an \"{action}\" gesendet","IQ5tZg": "Formular abgesendet","+B+qvw": "{type}eingabefeld \"{name}\" geändert",- "vDpLV2": "{type}eingabefeld geändert"+ "vDpLV2": "{type}eingabefeld geändert",+ "E2rh1p": "Buttons",+ "yGsZm0": "Formulare",+ "y3qXTf": "Kopien",+ "eHclX+": "Formular-Übermittlungen",+ "d6avGo": "Übermittlungen",+ "JaJoAk": "Button-Text",+ "UgH9Vn": "Kopierter Text",+ "J+At6e": "Zuletzt übermittelt",+ "LovNd5": "Zuletzt kopiert"}diff --git a/client/messages/en.json b/client/messages/en.jsonindex b3b68c2da..caa67ce03 100644--- a/client/messages/en.json+++ b/client/messages/en.json@@ -1603,5 +1603,14 @@"QOaR8l": "Submitted form to \"{action}\"","IQ5tZg": "Submitted form","+B+qvw": "Changed {type}input \"{name}\"",- "vDpLV2": "Changed {type}input"+ "vDpLV2": "Changed {type}input",+ "E2rh1p": "Buttons",+ "yGsZm0": "Forms",+ "y3qXTf": "Copies",+ "eHclX+": "Form Submissions",+ "d6avGo": "Submissions",+ "JaJoAk": "Button Text",+ "UgH9Vn": "Copied Text",+ "J+At6e": "Last Submitted",+ "LovNd5": "Last Copied"}diff --git a/client/messages/es.json b/client/messages/es.jsonindex 01fe8d13b..e0e3396b6 100644--- a/client/messages/es.json+++ b/client/messages/es.json@@ -488,7 +488,7 @@"rIc2Hm": "Actualizar embudo","m1czzY": "Evento","KP63fg": "",- "baRFiF": "",+ "baRFiF": "Formulario","29V0Ci": "sesiones","lHFZhY": "{count} abandonados","zIaJNz": "Alcanzados ({count})",@@ -1603,5 +1603,14 @@"QOaR8l": "Formulario enviado a \"{action}\"","IQ5tZg": "Formulario enviado","+B+qvw": "{type}campo de entrada \"{name}\" cambiado",- "vDpLV2": "{type}campo de entrada cambiado"+ "vDpLV2": "{type}campo de entrada cambiado",+ "E2rh1p": "Botones",+ "yGsZm0": "Formularios",+ "y3qXTf": "Copias",+ "eHclX+": "Envíos de Formularios",+ "d6avGo": "Envíos",+ "JaJoAk": "Texto del botón",+ "UgH9Vn": "Texto copiado",+ "J+At6e": "Último envío",+ "LovNd5": "Última copia"}diff --git a/client/messages/fr.json b/client/messages/fr.jsonindex f26e3f27b..4b145a912 100644--- a/client/messages/fr.json+++ b/client/messages/fr.json@@ -488,7 +488,7 @@"rIc2Hm": "Mettre à jour l'entonnoir","m1czzY": "Événement","KP63fg": "",- "baRFiF": "",+ "baRFiF": "Formulaire","29V0Ci": "Vues d'écran","lHFZhY": "{count} abandonnées","zIaJNz": "Atteint ({count})",@@ -1603,5 +1603,14 @@"QOaR8l": "Formulaire soumis à \"{action}\"","IQ5tZg": "Formulaire soumis","+B+qvw": "{type}champ de saisie \"{name}\" modifié",- "vDpLV2": "{type}champ de saisie modifié"+ "vDpLV2": "{type}champ de saisie modifié",+ "E2rh1p": "Boutons",+ "yGsZm0": "Formulaires",+ "y3qXTf": "Copies",+ "eHclX+": "Soumissions de formulaires",+ "d6avGo": "Soumissions",+ "JaJoAk": "Texte du bouton",+ "UgH9Vn": "Texte copié",+ "J+At6e": "Dernière soumission",+ "LovNd5": "Dernière copie"}diff --git a/client/messages/it.json b/client/messages/it.jsonindex 754984d33..8f919bf41 100644--- a/client/messages/it.json+++ b/client/messages/it.json@@ -488,7 +488,7 @@"rIc2Hm": "Aggiorna Funnel","m1czzY": "Evento","KP63fg": "",- "baRFiF": "",+ "baRFiF": "Modulo","29V0Ci": "sessioni","lHFZhY": "{count} abbandonati","zIaJNz": "Raggiunti ({count})",@@ -1603,5 +1603,14 @@"QOaR8l": "Modulo inviato a \"{action}\"","IQ5tZg": "Modulo inviato","+B+qvw": "{type}campo di input \"{name}\" modificato",- "vDpLV2": "{type}campo di input modificato"+ "vDpLV2": "{type}campo di input modificato",+ "E2rh1p": "Pulsanti",+ "yGsZm0": "Moduli",+ "y3qXTf": "Copie",+ "eHclX+": "Invii dei Moduli",+ "d6avGo": "Invii",+ "JaJoAk": "Testo del Pulsante",+ "UgH9Vn": "Testo Copiato",+ "J+At6e": "Ultimo Invio",+ "LovNd5": "Ultima Copia"}diff --git a/client/messages/ja.json b/client/messages/ja.jsonindex 958169492..ff80ab7cc 100644--- a/client/messages/ja.json+++ b/client/messages/ja.json@@ -488,7 +488,7 @@"rIc2Hm": "ファネルを更新","m1czzY": "イベント","KP63fg": "",- "baRFiF": "",+ "baRFiF": "フォーム","29V0Ci": "セッション","lHFZhY": "{count}件離脱","zIaJNz": "到達({count})",@@ -1603,5 +1603,14 @@"QOaR8l": "「{action}」にフォームを送信しました","IQ5tZg": "フォームを送信しました","+B+qvw": "{type}入力フィールド「{name}」を変更しました",- "vDpLV2": "{type}入力フィールドを変更しました"+ "vDpLV2": "{type}入力フィールドを変更しました",+ "E2rh1p": "ボタン",+ "yGsZm0": "フォーム",+ "y3qXTf": "コピー",+ "eHclX+": "フォーム送信",+ "d6avGo": "送信",+ "JaJoAk": "ボタンテキスト",+ "UgH9Vn": "コピーされたテキスト",+ "J+At6e": "最終送信",+ "LovNd5": "最終コピー"}diff --git a/client/messages/ko.json b/client/messages/ko.jsonindex f721d6e61..783b229fc 100644--- a/client/messages/ko.json+++ b/client/messages/ko.json@@ -488,7 +488,7 @@"rIc2Hm": "퍼널 업데이트","m1czzY": "이벤트","KP63fg": "",- "baRFiF": "",+ "baRFiF": "양식","29V0Ci": "세션","lHFZhY": "{count}명 이탈","zIaJNz": "도달 ({count})",@@ -1603,5 +1603,14 @@"QOaR8l": "\"{action}\"에 양식 제출됨","IQ5tZg": "양식 제출됨","+B+qvw": "{type}입력 필드 \"{name}\" 변경됨",- "vDpLV2": "{type}입력 필드 변경됨"+ "vDpLV2": "{type}입력 필드 변경됨",+ "E2rh1p": "버튼",+ "yGsZm0": "양식",+ "y3qXTf": "복사",+ "eHclX+": "양식 제출",+ "d6avGo": "제출",+ "JaJoAk": "버튼 텍스트",+ "UgH9Vn": "복사된 텍스트",+ "J+At6e": "마지막 제출",+ "LovNd5": "마지막 복사"}diff --git a/client/messages/pl.json b/client/messages/pl.jsonindex ba8047039..cdd34fe79 100644--- a/client/messages/pl.json+++ b/client/messages/pl.json@@ -488,7 +488,7 @@"rIc2Hm": "Zaktualizuj lejek","m1czzY": "Zdarzenie","KP63fg": "",- "baRFiF": "",+ "baRFiF": "Formularz","29V0Ci": "sesje","lHFZhY": "{count} porzuciło","zIaJNz": "Dotarło ({count})",@@ -1603,5 +1603,14 @@"QOaR8l": "Przesłano formularz do \"{action}\"","IQ5tZg": "Przesłano formularz","+B+qvw": "Zmieniono {type}pole wprowadzania \"{name}\"",- "vDpLV2": "Zmieniono {type}pole wprowadzania"+ "vDpLV2": "Zmieniono {type}pole wprowadzania",+ "E2rh1p": "Przyciski",+ "yGsZm0": "Formularze",+ "y3qXTf": "Kopie",+ "eHclX+": "Przesłania formularzy",+ "d6avGo": "Przesłania",+ "JaJoAk": "Tekst przycisku",+ "UgH9Vn": "Skopiowany tekst",+ "J+At6e": "Ostatnio przesłano",+ "LovNd5": "Ostatnio skopiowano"}diff --git a/client/messages/pt.json b/client/messages/pt.jsonindex 3d1bb110c..9c69d71e7 100644--- a/client/messages/pt.json+++ b/client/messages/pt.json@@ -488,7 +488,7 @@"rIc2Hm": "Atualizar Funil","m1czzY": "Evento","KP63fg": "",- "baRFiF": "",+ "baRFiF": "Formulário","29V0Ci": "sessões","lHFZhY": "{count} abandonaram","zIaJNz": "Alcançaram ({count})",@@ -1603,5 +1603,14 @@"QOaR8l": "Formulário enviado para \"{action}\"","IQ5tZg": "Formulário enviado","+B+qvw": "{type}campo de entrada \"{name}\" alterado",- "vDpLV2": "{type}campo de entrada alterado"+ "vDpLV2": "{type}campo de entrada alterado",+ "E2rh1p": "Botões",+ "yGsZm0": "Formulários",+ "y3qXTf": "Cópias",+ "eHclX+": "Envios de Formulários",+ "d6avGo": "Envios",+ "JaJoAk": "Texto do Botão",+ "UgH9Vn": "Texto Copiado",+ "J+At6e": "Último Envio",+ "LovNd5": "Última Cópia"}diff --git a/client/messages/uk.json b/client/messages/uk.jsonindex c9f954117..f12a4671c 100644--- a/client/messages/uk.json+++ b/client/messages/uk.json@@ -488,7 +488,7 @@"rIc2Hm": "Оновити воронку","m1czzY": "Подія","KP63fg": "",- "baRFiF": "",+ "baRFiF": "Форма","29V0Ci": "сеанси","lHFZhY": "Відпало: {count}","zIaJNz": "Досягли ({count})",@@ -1603,5 +1603,14 @@"QOaR8l": "","IQ5tZg": "","+B+qvw": "",- "vDpLV2": ""+ "vDpLV2": "",+ "E2rh1p": "Кнопки",+ "yGsZm0": "Форми",+ "y3qXTf": "Копіювання",+ "eHclX+": "Надсилання форм",+ "d6avGo": "Надсилання",+ "JaJoAk": "Текст кнопки",+ "UgH9Vn": "Скопійований текст",+ "J+At6e": "Останнє надсилання",+ "LovNd5": "Останнє копіювання"}diff --git a/client/messages/zh.json b/client/messages/zh.jsonindex e13c913ea..5ceaac915 100644--- a/client/messages/zh.json+++ b/client/messages/zh.json@@ -488,7 +488,7 @@"rIc2Hm": "更新漏斗","m1czzY": "事件","KP63fg": "",- "baRFiF": "",+ "baRFiF": "表单","29V0Ci": "个会话","lHFZhY": "{count} 人流失","zIaJNz": "已到达 ({count})",@@ -1603,5 +1603,14 @@"QOaR8l": "已提交表单到 \"{action}\"","IQ5tZg": "已提交表单","+B+qvw": "已更改 {type}输入框 \"{name}\"",- "vDpLV2": "已更改 {type}输入框"+ "vDpLV2": "已更改 {type}输入框",+ "E2rh1p": "按钮",+ "yGsZm0": "表单",+ "y3qXTf": "复制次数",+ "eHclX+": "表单提交",+ "d6avGo": "提交次数",+ "JaJoAk": "按钮文本",+ "UgH9Vn": "复制的文本",+ "J+At6e": "最后提交时间",+ "LovNd5": "最后复制时间"}diff --git a/client/src/api/analytics/endpoints/events.ts b/client/src/api/analytics/endpoints/events.tsindex f5bd55bf9..87c3ff045 100644--- a/client/src/api/analytics/endpoints/events.ts+++ b/client/src/api/analytics/endpoints/events.ts@@ -73,6 +73,14 @@ export type OutboundLink = {lastClicked: string;};+// Autocapture events (button clicks, form submissions, copies) grouped by+// their display value+export type AutocaptureEvent = {+ value: string;+ count: number;+ lastOccurred: string;+};+// Event counts over timeexport type EventBucketedPoint = {time: string;@@ -204,6 +212,27 @@ export async function fetchOutboundLinks(return response.data;}+/**+ * Fetch autocapture events of a type (button clicks, form submissions,+ * copies) grouped by display value, with counts and last occurrence+ * GET /api/sites/:site/events/autocapture+ */+export async function fetchAutocaptureEvents(+ site: string | number,+ params: CommonApiParams & { type: string }+): Promise<AutocaptureEvent[]> {+ const queryParams = {+ ...toQueryParams(params),+ type: params.type,+ };++ const response = await authedFetch<{ data: AutocaptureEvent[] }>(+ `/sites/${site}/events/autocapture`,+ queryParams+ );+ return response.data;+}+/*** Fetch common values for an autocapture event type (outbound urls, button* texts, form names/ids, copied texts)diff --git a/client/src/api/analytics/endpoints/index.ts b/client/src/api/analytics/endpoints/index.tsindex 3a9954294..da94c8ee6 100644--- a/client/src/api/analytics/endpoints/index.ts+++ b/client/src/api/analytics/endpoints/index.ts@@ -25,6 +25,7 @@ export {fetchEventsCursor,fetchEventNames,fetchEventProperties,+ fetchAutocaptureEvents,fetchAutocaptureValues,fetchOutboundLinks,fetchSiteEventCount,@@ -36,6 +37,7 @@ export type {CursorEventsResponse,EventName,EventProperty,+ AutocaptureEvent,AutocaptureValue,OutboundLink,EventBucketedParams,diff --git a/client/src/api/analytics/hooks/events/useGetAutocaptureEvents.ts b/client/src/api/analytics/hooks/events/useGetAutocaptureEvents.tsnew file mode 100644index 000000000..429c39907--- /dev/null+++ b/client/src/api/analytics/hooks/events/useGetAutocaptureEvents.ts@@ -0,0 +1,21 @@+import { useQuery } from "@tanstack/react-query";+import { AutocaptureTargetType } from "../../../../lib/events";+import { EVENT_FILTERS } from "../../../../lib/filterGroups";+import { getFilteredFilters, useStore } from "../../../../lib/store";+import { buildApiParams } from "../../../utils";+import { fetchAutocaptureEvents } from "../../endpoints";++export function useGetAutocaptureEvents(type: AutocaptureTargetType) {+ const { site, time, timezone } = useStore();++ const filteredFilters = getFilteredFilters(EVENT_FILTERS);+ const params = buildApiParams(time, {+ filters: filteredFilters.length > 0 ? filteredFilters : undefined,+ });++ return useQuery({+ queryKey: ["autocapture-events", site, type, time, filteredFilters, timezone],+ enabled: !!site,+ queryFn: () => fetchAutocaptureEvents(site, { ...params, type }),+ });+}diff --git a/client/src/app/[site]/events/components/AutocaptureEventsList.tsx b/client/src/app/[site]/events/components/AutocaptureEventsList.tsxnew file mode 100644index 000000000..f068903bb--- /dev/null+++ b/client/src/app/[site]/events/components/AutocaptureEventsList.tsx@@ -0,0 +1,130 @@+"use client";++import NumberFlow from "@number-flow/react";+import { Info } from "lucide-react";+import { useExtracted } from "next-intl";+import { memo } from "react";+import { AutocaptureEvent } from "../../../../api/analytics/endpoints";+import { ScrollArea } from "../../../../components/ui/scroll-area";+import { cn, truncateString } from "../../../../lib/utils";++// Skeleton component for AutocaptureEventsList+const AutocaptureEventsListSkeleton = memo(({ size = "small" }: { size?: "small" | "large" }) => {+ // Generate widths following Pareto principle with top item at 100%+ const widths = Array.from({ length: 10 }, (_, i) => {+ if (i === 0) {+ return 100;+ } else if (i === 1) {+ return 60 + Math.random() * 20;+ } else {+ const factor = 1 - (i - 2) / 8;+ return 10 + factor * 30;+ }+ });++ const labelWidths = Array.from({ length: 10 }, (_, i) => {+ return i < 3 ? 150 + Math.random() * 100 : 80 + Math.random() * 120;+ });++ const valueWidths = Array.from({ length: 10 }, () => 20 + Math.random() * 40);++ return (+ <div className="flex flex-col gap-2 pr-2">+ {Array.from({ length: 10 }).map((_, index) => (+ <div key={index} className={cn("relative flex items-center", size === "small" ? "h-6" : "h-9")}>+ <div+ className="absolute inset-0 bg-neutral-150/50 dark:bg-neutral-800 py-2 rounded-md animate-pulse"+ style={{ width: `${widths[index]}%` }}+ ></div>+ <div+ className={cn(+ "z-5 mx-2 flex justify-between items-center w-full",+ size === "small" ? "text-xs" : "text-sm"+ )}+ >+ <div+ className="h-4 bg-neutral-200 dark:bg-neutral-800 rounded animate-pulse"+ style={{ width: `${labelWidths[index]}px` }}+ ></div>+ <div+ className="h-4 bg-neutral-200 dark:bg-neutral-800 rounded animate-pulse"+ style={{ width: `${valueWidths[index]}px` }}+ ></div>+ </div>+ </div>+ ))}+ </div>+ );+});++interface AutocaptureEventsListProps {+ events: AutocaptureEvent[];+ isLoading: boolean;+ size?: "small" | "large";+}++export function AutocaptureEventsList({ events, isLoading, size = "small" }: AutocaptureEventsListProps) {+ const t = useExtracted();++ if (isLoading) {+ return <AutocaptureEventsListSkeleton size={size} />;+ }++ if (!events || events.length === 0) {+ return (+ <div className="text-neutral-500 dark:text-neutral-300 w-full text-center mt-6 flex flex-row gap-2 items-center justify-center">+ <Info className="w-5 h-5" />+ {t("No Data")}+ </div>+ );+ }++ const totalCount = events.reduce((sum, event) => sum + event.count, 0);+ const maxCount = Math.max(...events.map(event => event.count));++ return (+ /* [&>div]:!block forces Radix's display:table viewport wrapper to block so value truncate is bounded */+ <ScrollArea className="h-[394px]" viewportClassName="[&>div]:!block">+ <div className="flex flex-col gap-2 pr-2 overflow-x-hidden">+ {events.map((event, index) => {+ const percentageOfMax = (event.count / maxCount) * 100;+ const percentage = (event.count / totalCount) * 100;++ return (+ <div+ key={`${event.value}-${index}`}+ className={cn(+ "relative flex items-center hover:bg-neutral-100 dark:hover:bg-neutral-850 group px-2 rounded-md",+ size === "small" ? "h-6" : "h-9"+ )}+ >+ <div+ className="absolute inset-0 bg-dataviz py-2 opacity-25 rounded-md"+ style={{ width: `${percentageOfMax}%` }}+ ></div>+ <div+ className={cn(+ "z-10 flex justify-between items-center w-full",+ size === "small" ? "text-xs" : "text-sm"+ )}+ >+ <div+ className="font-medium truncate max-w-[70%] text-neutral-900 dark:text-neutral-100"+ title={event.value}+ >+ {truncateString(event.value, 100)}+ </div>+ <div className={cn("text-sm flex gap-2 items-center", size === "small" ? "text-xs" : "text-sm")}>+ <div className="hidden group-hover:block text-neutral-600 dark:text-neutral-400 text-xs">+ {Math.round(percentage * 10) / 10}%+ </div>+ <NumberFlow respectMotionPreference={false} value={event.count} format={{ notation: "compact" }} />+ </div>+ </div>+ </div>+ );+ })}+ </div>+ </ScrollArea>+ );+}diff --git a/client/src/app/[site]/events/components/OutboundLinksList.tsx b/client/src/app/[site]/events/components/OutboundLinksList.tsxindex 2702d0029..aedeb7908 100644--- a/client/src/app/[site]/events/components/OutboundLinksList.tsx+++ b/client/src/app/[site]/events/components/OutboundLinksList.tsx@@ -89,7 +89,8 @@ export function OutboundLinksList({ outboundLinks, isLoading, size = "small" }:const maxCount = Math.max(...outboundLinks.map(link => link.count));return (- <ScrollArea className="h-[394px]">+ /* [&>div]:!block forces Radix's display:table viewport wrapper to block so url truncate is bounded */+ <ScrollArea className="h-[394px]" viewportClassName="[&>div]:!block"><div className="flex flex-col gap-2 pr-2 overflow-x-hidden">{outboundLinks.map((link, index) => {const percentageOfMax = (link.count / maxCount) * 100;diff --git a/client/src/app/[site]/main/components/sections/AutocaptureEventsDialog.tsx b/client/src/app/[site]/main/components/sections/AutocaptureEventsDialog.tsxnew file mode 100644index 000000000..14e0d06ce--- /dev/null+++ b/client/src/app/[site]/main/components/sections/AutocaptureEventsDialog.tsx@@ -0,0 +1,179 @@+"use client";++import { Input } from "@/components/ui/input";+import { getTimezone } from "@/lib/store";+import { useDebounce, useIntersectionObserver } from "@uidotdev/usehooks";+import { DateTime } from "luxon";+import { ChevronDown, ChevronUp, Loader2, Search } from "lucide-react";+import { useExtracted } from "next-intl";+import { useEffect, useMemo, useState } from "react";+import { useDateTimeFormat } from "../../../../../hooks/useDateTimeFormat";+import { AutocaptureEvent } from "../../../../../api/analytics/endpoints";+import { cn } from "../../../../../lib/utils";++interface AutocaptureEventsDialogBodyProps {+ events: AutocaptureEvent[];+ valueLabel: string;+ countLabel: string;+ lastLabel: string;+}++const INITIAL_ROWS = 100;+const BATCH_SIZE = 100;++type SortKey = "value" | "count" | "percentage" | "lastOccurred";++export function AutocaptureEventsDialogBody({ events, valueLabel, countLabel, lastLabel }: AutocaptureEventsDialogBodyProps) {+ const t = useExtracted();+ const { formatRelative } = useDateTimeFormat();+ const [searchTerm, setSearchTerm] = useState("");+ const debouncedSearchTerm = useDebounce(searchTerm, 200);+ const [sortKey, setSortKey] = useState<SortKey>("count");+ const [sortDesc, setSortDesc] = useState<boolean>(true);+ const [visibleCount, setVisibleCount] = useState(INITIAL_ROWS);++ // Compute total for percentages+ const totalCount = useMemo(() => events.reduce((sum, e) => sum + e.count, 0), [events]);++ // Prepare data with percentage and filter+ const filteredAll = useMemo(() => {+ const base = events.map(e => ({ ...e, percentage: totalCount ? (e.count / totalCount) * 100 : 0 }));+ if (!debouncedSearchTerm) return base;+ const q = debouncedSearchTerm.toLowerCase();+ return base.filter(e => e.value.toLowerCase().includes(q));+ }, [events, totalCount, debouncedSearchTerm]);++ // Reset visible rows when filter changes+ useEffect(() => {+ setVisibleCount(INITIAL_ROWS);+ }, [debouncedSearchTerm]);++ // Intersection observer to grow visible rows+ const [ref, entry] = useIntersectionObserver({ threshold: 0, root: null, rootMargin: "0px 0px 200px 0px" });+ const hasMore = visibleCount < filteredAll.length;+ useEffect(() => {+ if (entry?.isIntersecting && hasMore) {+ setVisibleCount(c => Math.min(c + BATCH_SIZE, filteredAll.length));+ }+ }, [entry?.isIntersecting, hasMore, filteredAll.length]);++ const sorted = useMemo(() => {+ const arr = filteredAll.slice();+ arr.sort((a, b) => {+ const mul = sortDesc ? -1 : 1;+ switch (sortKey) {+ case "value":+ return mul * a.value.localeCompare(b.value);+ case "count":+ return mul * (a.count - b.count);+ case "percentage":+ return mul * (a.percentage - b.percentage);+ case "lastOccurred": {+ const aMs = DateTime.fromSQL(a.lastOccurred, { zone: "utc" }).toMillis();+ const bMs = DateTime.fromSQL(b.lastOccurred, { zone: "utc" }).toMillis();+ return mul * (aMs - bMs);+ }+ }+ });+ return arr;+ }, [filteredAll, sortKey, sortDesc]);++ const visible = sorted.slice(0, visibleCount);++ function toggleSort(key: SortKey) {+ if (key === sortKey) {+ setSortDesc(d => !d);+ } else {+ setSortKey(key);+ setSortDesc(key === "count" || key === "percentage" || key === "lastOccurred");+ }+ }++ const headers: { key: SortKey; label: string; align: "left" | "right" }[] = [+ { key: "value", label: valueLabel, align: "left" },+ { key: "count", label: countLabel, align: "right" },+ { key: "percentage", label: "%", align: "right" },+ { key: "lastOccurred", label: lastLabel, align: "right" },+ ];++ return (+ <div className="flex min-h-0 flex-1 flex-col gap-2">+ <div className="relative mb-2">+ <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-neutral-600 dark:text-neutral-400" />+ <Input+ type="text"+ placeholder={t("Filter {count} items...", { count: String(events.length) })}+ className="pl-9 bg-white dark:bg-neutral-900 border-neutral-200 dark:border-neutral-700 text-xs"+ value={searchTerm}+ onChange={e => setSearchTerm(e.target.value)}+ />+ </div>+ <div className="flex min-h-0 flex-1 flex-col gap-2 overflow-x-auto">+ <div className="min-h-0 flex-1 overflow-y-auto">+ <table className="w-full text-xs text-left min-w-max">+ <thead className="bg-neutral-100 dark:bg-neutral-900 text-neutral-600 dark:text-neutral-400 sticky top-0 z-10">+ <tr>+ {headers.map(header => (+ <th+ key={header.key}+ className={cn(+ "px-2 py-1 font-medium whitespace-nowrap cursor-pointer select-none",+ header.align === "right" ? "text-right" : "text-left"+ )}+ onClick={() => toggleSort(header.key)}+ >+ <div className={cn("flex items-center gap-1", header.align === "right" && "justify-end")}>+ {header.label}+ {sortKey === header.key &&+ (sortDesc ? <ChevronDown className="h-3 w-3" /> : <ChevronUp className="h-3 w-3" />)}+ </div>+ </th>+ ))}+ </tr>+ </thead>+ <tbody>+ {visible.map((row, rowIndex) => (+ <tr+ key={`${row.value}-${rowIndex}`}+ className={cn(+ "border-b border-neutral-300 dark:border-neutral-800 hover:bg-neutral-150 dark:hover:bg-neutral-850",+ rowIndex % 2 === 0 ? "bg-white dark:bg-neutral-900" : "bg-neutral-50 dark:bg-neutral-950"+ )}+ >+ <td className="p-2">+ <div className="truncate max-w-[600px]" title={row.value}>+ {row.value}+ </div>+ </td>+ <td className="p-2 text-right">{row.count.toLocaleString()}</td>+ <td className="p-2 text-right">{row.percentage.toFixed(1)}%</td>+ <td className="p-2 text-right text-neutral-600 dark:text-neutral-300">+ {(() => {+ try {+ const dt = DateTime.fromSQL(row.lastOccurred, { zone: "utc" }).setZone(getTimezone());+ return formatRelative(dt);+ } catch {+ return "-";+ }+ })()}+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ {filteredAll.length > visibleCount && (+ <div ref={ref} className="py-4 flex justify-center">+ <div className="flex items-center gap-2 text-neutral-600 dark:text-neutral-400 text-xs">+ <Loader2 className="h-4 w-4 animate-spin" />+ {t("Loading more...")}+ </div>+ </div>+ )}+ {!hasMore && (+ <div className="py-4 text-center text-neutral-500 dark:text-neutral-500 text-xs">{t("All items loaded")}</div>+ )}+ </div>+ </div>+ </div>+ );+}diff --git a/client/src/app/[site]/main/components/sections/Events.tsx b/client/src/app/[site]/main/components/sections/Events.tsxindex db053cb60..bc46faf2a 100644--- a/client/src/app/[site]/main/components/sections/Events.tsx+++ b/client/src/app/[site]/main/components/sections/Events.tsx@@ -1,14 +1,18 @@import { useExtracted } from "next-intl";+import { useGetAutocaptureEvents } from "../../../../../api/analytics/hooks/events/useGetAutocaptureEvents";import { useGetEventNames } from "../../../../../api/analytics/hooks/events/useGetEventNames";import { useGetOutboundLinks } from "../../../../../api/analytics/hooks/events/useGetOutboundLinks";import { CardLoader } from "../../../../../components/ui/card";import { ScrollArea } from "../../../../../components/ui/scroll-area";+import { AutocaptureTargetType } from "../../../../../lib/events";+import { AutocaptureEventsList } from "../../../events/components/AutocaptureEventsList";import { EventList } from "../../../events/components/EventList";import { OutboundLinksList } from "../../../events/components/OutboundLinksList";import { TabbedSectionCard, type TabbedSectionItem } from "../../../components/shared/TabbedSectionCard";+import { AutocaptureEventsDialogBody } from "./AutocaptureEventsDialog";import { OutboundLinksDialogBody } from "./OutboundLinksDialog";-type Tab = "events" | "outbound";+type Tab = "events" | "outbound" | "buttons" | "forms" | "copies";function EventsContent() {const { data: eventNamesData, isLoading: isLoadingEventNames } = useGetEventNames();@@ -26,7 +30,8 @@ function EventsContent() {<div>{t("Custom Events")}</div><div>{t("Count")}</div></div>- <ScrollArea className="h-[394px]">+ {/* [&>div]:!block forces Radix's display:table viewport wrapper to block so name truncate is bounded */}+ <ScrollArea className="h-[394px]" viewportClassName="[&>div]:!block"><EventList events={eventNamesData || []} isLoading={isLoadingEventNames} /></ScrollArea></div>@@ -61,6 +66,57 @@ function OutboundLinksDialogContent() {return <OutboundLinksDialogBody outboundLinks={outboundLinksData || []} />;}+function AutocaptureContent({+ type,+ valueLabel,+ countLabel,+}: {+ type: AutocaptureTargetType;+ valueLabel: string;+ countLabel: string;+}) {+ const { data, isLoading } = useGetAutocaptureEvents(type);++ return (+ <>+ {isLoading && (+ <div className="absolute top-[-8px] left-0 w-full h-full">+ <CardLoader />+ </div>+ )}+ <div className="relative">+ <div className="flex flex-row gap-2 justify-between pr-1 text-xs text-neutral-600 dark:text-neutral-400 mb-2">+ <div>{valueLabel}</div>+ <div>{countLabel}</div>+ </div>+ <AutocaptureEventsList events={data || []} isLoading={isLoading} />+ </div>+ </>+ );+}++function AutocaptureDialogContent({+ type,+ valueLabel,+ countLabel,+ lastLabel,+}: {+ type: AutocaptureTargetType;+ valueLabel: string;+ countLabel: string;+ lastLabel: string;+}) {+ const { data } = useGetAutocaptureEvents(type);+ return (+ <AutocaptureEventsDialogBody+ events={data || []}+ valueLabel={valueLabel}+ countLabel={countLabel}+ lastLabel={lastLabel}+ />+ );+}+export function Events() {const t = useExtracted();@@ -72,11 +128,53 @@ export function Events() {},{value: "outbound",- label: t("Outbound Links"),+ label: t("Outbound"),content: <OutboundLinksContent />,dialogContent: <OutboundLinksDialogContent />,dialogTitle: t("Outbound Links"),},+ {+ value: "buttons",+ label: t("Buttons"),+ content: <AutocaptureContent type="button_click" valueLabel={t("Buttons")} countLabel={t("Clicks")} />,+ dialogContent: (+ <AutocaptureDialogContent+ type="button_click"+ valueLabel={t("Button Text")}+ countLabel={t("Clicks")}+ lastLabel={t("Last Clicked")}+ />+ ),+ dialogTitle: t("Button Clicks"),+ },+ {+ value: "forms",+ label: t("Forms"),+ content: <AutocaptureContent type="form_submit" valueLabel={t("Forms")} countLabel={t("Submissions")} />,+ dialogContent: (+ <AutocaptureDialogContent+ type="form_submit"+ valueLabel={t("Form")}+ countLabel={t("Submissions")}+ lastLabel={t("Last Submitted")}+ />+ ),+ dialogTitle: t("Form Submissions"),+ },+ {+ value: "copies",+ label: t("Copies"),+ content: <AutocaptureContent type="copy" valueLabel={t("Copied Text")} countLabel={t("Copies")} />,+ dialogContent: (+ <AutocaptureDialogContent+ type="copy"+ valueLabel={t("Copied Text")}+ countLabel={t("Copies")}+ lastLabel={t("Last Copied")}+ />+ ),+ dialogTitle: t("Copies"),+ },];return <TabbedSectionCard defaultValue="events" tabs={tabs} className="h-[483px]" />;diff --git a/server/src/api/analytics/events/getAutocaptureEvents.ts b/server/src/api/analytics/events/getAutocaptureEvents.tsnew file mode 100644index 000000000..ee0effad8--- /dev/null+++ b/server/src/api/analytics/events/getAutocaptureEvents.ts@@ -0,0 +1,85 @@+import { FastifyReply, FastifyRequest } from "fastify";+import SqlString from "sqlstring";+import { clickhouse } from "../../../db/clickhouse/clickhouse.js";+import { getTimeStatement, processResults } from "../utils/utils.js";+import { FilterParams } from "@rybbit/shared";+import { getFilterStatement } from "../utils/getFilterStatement.js";+import { AutocaptureTargetType, isAutocaptureTargetType } from "../utils/eventConditions.js";++export type GetAutocaptureEventsResponse = {+ value: string;+ count: number;+ lastOccurred: string;+}[];++export interface GetAutocaptureEventsRequest {+ Params: {+ siteId: string;+ };+ Querystring: FilterParams<{+ type: string;+ }>;+}++// The single display value each event of a type is grouped by. Unlike+// AUTOCAPTURE_PATTERN_PROPS (which matches goal patterns against every prop),+// form_submit collapses to its first non-empty identifier so one submission+// counts once.+const VALUE_EXPRESSIONS: Record<AutocaptureTargetType, string> = {+ outbound: "JSONExtractString(toString(props), 'url')",+ button_click: "JSONExtractString(toString(props), 'text')",+ copy: "JSONExtractString(toString(props), 'text')",+ form_submit:+ "coalesce(nullIf(JSONExtractString(toString(props), 'formName'), ''), nullIf(JSONExtractString(toString(props), 'formId'), ''), nullIf(JSONExtractString(toString(props), 'formAction'), ''), '')",+};++// Returns autocapture events of a type (button clicks, form submissions,+// copies) grouped by their display value, with counts and last occurrence.+export async function getAutocaptureEvents(req: FastifyRequest<GetAutocaptureEventsRequest>, res: FastifyReply) {+ const { type, filters } = req.query;+ const site = req.params.siteId;++ if (!type || !isAutocaptureTargetType(type)) {+ return res.status(400).send({ error: "Invalid autocapture event type" });+ }++ const timeStatement = getTimeStatement(req.query);+ const filterStatement = filters ? getFilterStatement(filters, Number(site), timeStatement) : "";+ const valueExpression = VALUE_EXPRESSIONS[type];++ const query = `+ SELECT+ ${valueExpression} AS value,+ COUNT(*) AS count,+ toString(MAX(timestamp)) AS lastOccurred+ FROM events+ WHERE+ site_id = {siteId:Int32}+ AND type = ${SqlString.escape(type)}+ AND ${valueExpression} != ''+ ${timeStatement}+ ${filterStatement}+ GROUP BY value+ ORDER BY count DESC+ LIMIT 1000+ `;++ try {+ const result = await clickhouse.query({+ query,+ format: "JSONEachRow",+ query_params: {+ siteId: Number(site),+ },+ });++ const data = await processResults<GetAutocaptureEventsResponse[number]>(result);+ // processResults coerces any column that looks numeric into a number; `value`+ // is free-form captured text (e.g. a button labeled "100") and must stay a string.+ return res.send({ data: data.map(row => ({ ...row, value: String(row.value) })) });+ } catch (error) {+ console.error("Generated Query:", query);+ console.error("Error fetching autocapture events:", error);+ return res.status(500).send({ error: "Failed to fetch autocapture events" });+ }+}diff --git a/server/src/api/analytics/index.ts b/server/src/api/analytics/index.tsindex 845c82360..cc3b4ad90 100644--- a/server/src/api/analytics/index.ts+++ b/server/src/api/analytics/index.ts@@ -1,4 +1,5 @@// Events+export { getAutocaptureEvents } from "./events/getAutocaptureEvents.js";export { getAutocaptureValues } from "./events/getAutocaptureValues.js";export { getEventBucketed } from "./events/getEventBucketed.js";export { getEventNames } from "./events/getEventNames.js";diff --git a/server/src/index.ts b/server/src/index.tsindex 808842ad9..80ae3fefe 100644--- a/server/src/index.ts+++ b/server/src/index.ts@@ -33,6 +33,7 @@ import {generateCustomQuery,getEventBucketed,getEventNames,+ getAutocaptureEvents,getAutocaptureValues,getEventProperties,getEvents,@@ -342,6 +343,7 @@ async function analyticsRoutes(fastify: FastifyInstance) {fastify.get("/sites/:siteId/experiments/:experimentId/results", authSite, getExperimentResults);fastify.get("/sites/:siteId/events/names", publicSite, getEventNames);fastify.get("/sites/:siteId/events/properties", publicSite, getEventProperties);+ fastify.get("/sites/:siteId/events/autocapture", publicSite, getAutocaptureEvents);fastify.get("/sites/:siteId/events/autocapture-values", publicSite, getAutocaptureValues);fastify.get("/sites/:siteId/events/outbound", publicSite, getOutboundLinks);fastify.get("/org-event-count/:organizationId", orgMember, getOrgEventCount);