Skip to content

🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.

Update translations and enhance export functionality

Bill Yangf357b8f3ab94
diff --git a/client/messages/cs.json b/client/messages/cs.json
index f57ef6a82..e9bdc393f 100644
--- a/client/messages/cs.json
+++ b/client/messages/cs.json
@@ -240,6 +240,7 @@
"8Nc/jD": "Zatím žádné weby",
"8O/fqy": "",
"8O9cAb": "",
+ "8UzT6d": "",
"8apB7W": "Odebrat tohoto člena z organizace.",
"8eQ7FM": "Pokračovat přes GitHub",
"8ekFRM": "Žádné trychtýře nenalezeny",
@@ -284,6 +285,7 @@
"9qBH5R": "",
"9tjZ7S": "Nepodařilo se vytvořit uživatele",
"9uKBh7": "",
+ "9y9QQh": "",
"A/lLjO": "Generuji...",
"A4AHkc": "min",
"A5E371": "Stránka, kterou hledáš, neexistuje nebo byla přesunuta. Pojďme tě vrátit k analýze tvých dat.",
@@ -746,6 +748,7 @@
"SDTG4X": "",
"SElbF+": "",
"SQJto2": "Přihlásit se",
+ "SVwJTM": "",
"SWvHLr": "Tento týden",
"SX126d": "Exportovat data",
"Sb7oIl": "Výkon podle operačního systému",
@@ -1303,6 +1306,7 @@
"pW4lxD": "Vzor",
"pZrL8g": "Exportováno {fileCount} souborů",
"pm+3nT": "",
+ "pmt5UZ": "",
"pnkSRp": "Kraje",
"poMLbD": "",
"poXmsM": "Zadej svou emailovou adresu a my ti pošleme ověřovací kód pro obnovení hesla.",
diff --git a/client/messages/de.json b/client/messages/de.json
index 67e8d3f05..c662ba73e 100644
--- a/client/messages/de.json
+++ b/client/messages/de.json
@@ -240,6 +240,7 @@
"8Nc/jD": "Noch keine Websites",
"8O/fqy": "Verknüpfen Sie dieses Experiment mit einem Ziel, das Sie bereits verfolgen.",
"8O9cAb": "Letzte 24 Stunden",
+ "8UzT6d": "",
"8apB7W": "Dieses Mitglied aus der Organisation entfernen.",
"8eQ7FM": "Mit GitHub fortfahren",
"8ekFRM": "Keine Trichter gefunden",
@@ -284,6 +285,7 @@
"9qBH5R": "Keine Feature-Flags gefunden",
"9tjZ7S": "Benutzer konnte nicht erstellt werden",
"9uKBh7": "Remote-Konfiguration",
+ "9y9QQh": "",
"A/lLjO": "Wird generiert...",
"A4AHkc": "Min",
"A5E371": "Die gesuchte Seite existiert nicht oder wurde verschoben. Kehren Sie zur Datenanalyse zurück.",
@@ -746,6 +748,7 @@
"SDTG4X": "Das primäre Ziel ist das Konversionsevent oder der Seitenaufruf, der zum Variantenvergleich verwendet wird.",
"SElbF+": "Filter speichern",
"SQJto2": "Anmelden",
+ "SVwJTM": "",
"SWvHLr": "Diese Woche",
"SX126d": "Daten exportieren",
"Sb7oIl": "Leistung nach Betriebssystem",
@@ -1303,6 +1306,7 @@
"pW4lxD": "Muster",
"pZrL8g": "{fileCount} Dateien exportiert",
"pm+3nT": "React Native SDK",
+ "pmt5UZ": "",
"pnkSRp": "Regionen",
"poMLbD": "Experimente filtern",
"poXmsM": "Geben Sie Ihre E-Mail-Adresse ein und wir senden Ihnen einen Bestätigungscode zum Zurücksetzen Ihres Passworts.",
diff --git a/client/messages/en.json b/client/messages/en.json
index c007daafa..cde85fc57 100644
--- a/client/messages/en.json
+++ b/client/messages/en.json
@@ -240,6 +240,7 @@
"8Nc/jD": "No websites yet",
"8O/fqy": "Connect this experiment to a goal you already track.",
"8O9cAb": "Last 24 hours",
+ "8UzT6d": "CSV",
"8apB7W": "Remove this member from the organization.",
"8eQ7FM": "Continue with GitHub",
"8ekFRM": "No funnels found",
@@ -284,6 +285,7 @@
"9qBH5R": "No feature flags found",
"9tjZ7S": "Failed to create user",
"9uKBh7": "Remote config",
+ "9y9QQh": "JSON",
"A/lLjO": "Generating...",
"A4AHkc": "Min",
"A5E371": "The page you're looking for doesn't exist or has been moved. Let's get you back to analyzing your data.",
@@ -746,6 +748,7 @@
"SDTG4X": "The primary goal is the conversion event or page visit used to compare variants.",
"SElbF+": "Save filter",
"SQJto2": "Sign in",
+ "SVwJTM": "Export",
"SWvHLr": "This Week",
"SX126d": "Export data",
"Sb7oIl": "Performance by Operating System",
@@ -1303,6 +1306,7 @@
"pW4lxD": "Pattern",
"pZrL8g": "Exported {fileCount} files",
"pm+3nT": "React Native SDK",
+ "pmt5UZ": "Download results",
"pnkSRp": "Subdivisions",
"poMLbD": "Filter experiments",
"poXmsM": "Enter your email address and we'll send you a verification code to reset your password.",
diff --git a/client/messages/es.json b/client/messages/es.json
index fbcc78907..db4a24741 100644
--- a/client/messages/es.json
+++ b/client/messages/es.json
@@ -240,6 +240,7 @@
"8Nc/jD": "No hay sitios web aún",
"8O/fqy": "Conecta este experimento a un objetivo que ya rastreas.",
"8O9cAb": "Últimas 24 horas",
+ "8UzT6d": "",
"8apB7W": "Eliminar este miembro de la organización.",
"8eQ7FM": "Continuar con GitHub",
"8ekFRM": "No se encontraron embudos",
@@ -284,6 +285,7 @@
"9qBH5R": "No se encontraron banderas de funcionalidad",
"9tjZ7S": "Error al crear el usuario",
"9uKBh7": "Configuración remota",
+ "9y9QQh": "",
"A/lLjO": "Generando...",
"A4AHkc": "min",
"A5E371": "La página que buscas no existe o ha sido movida. Volvamos a analizar tus datos.",
@@ -746,6 +748,7 @@
"SDTG4X": "El objetivo principal es el evento de conversión o visita de página usado para comparar variantes.",
"SElbF+": "Guardar filtro",
"SQJto2": "Iniciar sesión",
+ "SVwJTM": "",
"SWvHLr": "Esta semana",
"SX126d": "Exportar datos",
"Sb7oIl": "Rendimiento por sistema operativo",
@@ -1303,6 +1306,7 @@
"pW4lxD": "Patrón",
"pZrL8g": "{fileCount} archivos exportados",
"pm+3nT": "React Native SDK",
+ "pmt5UZ": "",
"pnkSRp": "Subdivisiones",
"poMLbD": "Filtrar experimentos",
"poXmsM": "Introduce tu correo electrónico y te enviaremos un código de verificación para restablecer tu contraseña.",
diff --git a/client/messages/fr.json b/client/messages/fr.json
index 36837ceda..5882f788c 100644
--- a/client/messages/fr.json
+++ b/client/messages/fr.json
@@ -240,6 +240,7 @@
"8Nc/jD": "Aucun site web pour le moment",
"8O/fqy": "Associez cette expérience à un objectif que vous suivez déjà.",
"8O9cAb": "Dernières 24 heures",
+ "8UzT6d": "",
"8apB7W": "Supprimer ce membre de l'organisation.",
"8eQ7FM": "Continuer avec GitHub",
"8ekFRM": "Aucun entonnoir trouvé",
@@ -284,6 +285,7 @@
"9qBH5R": "Aucun feature flag trouvé",
"9tjZ7S": "Échec de la création de l'utilisateur",
"9uKBh7": "Config distante",
+ "9y9QQh": "",
"A/lLjO": "Génération en cours...",
"A4AHkc": "min",
"A5E371": "La page que vous recherchez n'existe pas ou a été déplacée. Retournons à l'analyse de vos données.",
@@ -746,6 +748,7 @@
"SDTG4X": "L'objectif principal est l'événement de conversion ou la visite de page utilisée pour comparer les variantes.",
"SElbF+": "Sauvegarder le filtre",
"SQJto2": "Se connecter",
+ "SVwJTM": "",
"SWvHLr": "Cette semaine",
"SX126d": "Exporter les données",
"Sb7oIl": "Performance par système d'exploitation",
@@ -1303,6 +1306,7 @@
"pW4lxD": "Modèle",
"pZrL8g": "{fileCount} fichiers exportés",
"pm+3nT": "SDK React Native",
+ "pmt5UZ": "",
"pnkSRp": "Subdivisions",
"poMLbD": "Filtrer les expériences",
"poXmsM": "Saisissez votre adresse e-mail et nous vous enverrons un code de vérification pour réinitialiser votre mot de passe.",
diff --git a/client/messages/it.json b/client/messages/it.json
index 4ccb83f0f..39ff2d01f 100644
--- a/client/messages/it.json
+++ b/client/messages/it.json
@@ -240,6 +240,7 @@
"8Nc/jD": "Ancora nessun sito web",
"8O/fqy": "Collega questo esperimento a un obiettivo che già monitori.",
"8O9cAb": "Ultime 24 ore",
+ "8UzT6d": "",
"8apB7W": "Rimuovi questo membro dall'organizzazione.",
"8eQ7FM": "Continua con GitHub",
"8ekFRM": "Nessun funnel trovato",
@@ -284,6 +285,7 @@
"9qBH5R": "Nessun feature flag trovato",
"9tjZ7S": "Impossibile creare l'utente",
"9uKBh7": "Configurazione remota",
+ "9y9QQh": "",
"A/lLjO": "Generazione in corso...",
"A4AHkc": "min",
"A5E371": "La pagina che stai cercando non esiste o è stata spostata. Torniamo ad analizzare i tuoi dati.",
@@ -746,6 +748,7 @@
"SDTG4X": "L'obiettivo principale è l'evento di conversione o la visita alla pagina usata per confrontare le varianti.",
"SElbF+": "Salva filtro",
"SQJto2": "Accedi",
+ "SVwJTM": "",
"SWvHLr": "Questa Settimana",
"SX126d": "Esporta dati",
"Sb7oIl": "Prestazioni per Sistema Operativo",
@@ -1303,6 +1306,7 @@
"pW4lxD": "Modello",
"pZrL8g": "Esportati {fileCount} file",
"pm+3nT": "SDK React Native",
+ "pmt5UZ": "",
"pnkSRp": "Suddivisioni",
"poMLbD": "Filtra esperimenti",
"poXmsM": "Inserisci il tuo indirizzo email e ti invieremo un codice di verifica per reimpostare la tua password.",
diff --git a/client/messages/ja.json b/client/messages/ja.json
index 30edfa288..ec79919c0 100644
--- a/client/messages/ja.json
+++ b/client/messages/ja.json
@@ -240,6 +240,7 @@
"8Nc/jD": "ウェブサイトがまだありません",
"8O/fqy": "すでに追跡しているゴールにこの実験を紐付けます。",
"8O9cAb": "過去24時間",
+ "8UzT6d": "",
"8apB7W": "このメンバーを組織から削除します。",
"8eQ7FM": "GitHubで続行",
"8ekFRM": "ファネルが見つかりません",
@@ -284,6 +285,7 @@
"9qBH5R": "フィーチャーフラグが見つかりません",
"9tjZ7S": "ユーザーの作成に失敗しました",
"9uKBh7": "リモート設定",
+ "9y9QQh": "",
"A/lLjO": "生成中...",
"A4AHkc": "分",
"A5E371": "お探しのページは存在しないか、移動されました。データ分析に戻りましょう。",
@@ -746,6 +748,7 @@
"SDTG4X": "主要ゴールは、バリアントを比較するために使用するコンバージョンイベントまたはページ訪問です。",
"SElbF+": "フィルターを保存",
"SQJto2": "サインイン",
+ "SVwJTM": "",
"SWvHLr": "今週",
"SX126d": "データをエクスポート",
"Sb7oIl": "OS別パフォーマンス",
@@ -1303,6 +1306,7 @@
"pW4lxD": "パターン",
"pZrL8g": "{fileCount}ファイルをエクスポートしました",
"pm+3nT": "React Native SDK",
+ "pmt5UZ": "",
"pnkSRp": "地域区分",
"poMLbD": "実験を絞り込む",
"poXmsM": "メールアドレスを入力してください。パスワードリセット用の確認コードを送信します。",
diff --git a/client/messages/ko.json b/client/messages/ko.json
index 976dfa9a9..e4cd98bdd 100644
--- a/client/messages/ko.json
+++ b/client/messages/ko.json
@@ -240,6 +240,7 @@
"8Nc/jD": "아직 웹사이트가 없습니다",
"8O/fqy": "이 실험을 이미 추적 중인 목표에 연결하세요.",
"8O9cAb": "최근 24시간",
+ "8UzT6d": "",
"8apB7W": "이 멤버를 조직에서 제거합니다.",
"8eQ7FM": "GitHub로 계속",
"8ekFRM": "퍼널을 찾을 수 없음",
@@ -284,6 +285,7 @@
"9qBH5R": "기능 플래그를 찾을 수 없습니다",
"9tjZ7S": "사용자 생성에 실패했습니다",
"9uKBh7": "원격 설정",
+ "9y9QQh": "",
"A/lLjO": "생성 중...",
"A4AHkc": "분",
"A5E371": "찾고 있는 페이지가 존재하지 않거나 이동되었습니다. 데이터 분석으로 돌아가겠습니다.",
@@ -746,6 +748,7 @@
"SDTG4X": "주요 목표는 변형을 비교하는 데 사용되는 전환 이벤트 또는 페이지 방문입니다.",
"SElbF+": "필터 저장",
"SQJto2": "로그인",
+ "SVwJTM": "",
"SWvHLr": "이번 주",
"SX126d": "데이터 내보내기",
"Sb7oIl": "운영 체제별 성능",
@@ -1303,6 +1306,7 @@
"pW4lxD": "패턴",
"pZrL8g": "{fileCount}개 파일 내보내기 완료",
"pm+3nT": "React Native SDK",
+ "pmt5UZ": "",
"pnkSRp": "하위 지역",
"poMLbD": "실험 필터",
"poXmsM": "이메일 주소를 입력하면 비밀번호 재설정을 위한 인증 코드를 보내드립니다.",
diff --git a/client/messages/pl.json b/client/messages/pl.json
index 10640c71a..61d784516 100644
--- a/client/messages/pl.json
+++ b/client/messages/pl.json
@@ -240,6 +240,7 @@
"8Nc/jD": "Brak stron",
"8O/fqy": "Połącz ten eksperyment z celem, który już śledzisz.",
"8O9cAb": "Ostatnie 24 godziny",
+ "8UzT6d": "",
"8apB7W": "Usuń tego członka z organizacji.",
"8eQ7FM": "Kontynuuj z GitHub",
"8ekFRM": "Nie znaleziono lejków",
@@ -284,6 +285,7 @@
"9qBH5R": "Nie znaleziono flag funkcji",
"9tjZ7S": "Nie udało się utworzyć użytkownika",
"9uKBh7": "Zdalna konfiguracja",
+ "9y9QQh": "",
"A/lLjO": "Generowanie...",
"A4AHkc": "min",
"A5E371": "Strona, której szukasz, nie istnieje lub została przeniesiona. Wróćmy do analizy Twoich danych.",
@@ -746,6 +748,7 @@
"SDTG4X": "Główny cel to zdarzenie konwersji lub odsłona strony używana do porównywania wariantów.",
"SElbF+": "Zapisz filtr",
"SQJto2": "Zaloguj się",
+ "SVwJTM": "",
"SWvHLr": "Ten tydzień",
"SX126d": "Eksportuj dane",
"Sb7oIl": "Wydajność według systemu operacyjnego",
@@ -1303,6 +1306,7 @@
"pW4lxD": "Wzorzec",
"pZrL8g": "Wyeksportowano {fileCount} plików",
"pm+3nT": "React Native SDK",
+ "pmt5UZ": "",
"pnkSRp": "Podregiony",
"poMLbD": "Filtruj eksperymenty",
"poXmsM": "Wprowadź swój adres e-mail, a wyślemy Ci kod weryfikacyjny do zresetowania hasła.",
diff --git a/client/messages/pt.json b/client/messages/pt.json
index 462e8d4dd..4b0fb5a25 100644
--- a/client/messages/pt.json
+++ b/client/messages/pt.json
@@ -240,6 +240,7 @@
"8Nc/jD": "Nenhum site ainda",
"8O/fqy": "Vincule este experimento a uma meta que você já rastreia.",
"8O9cAb": "Últimas 24 horas",
+ "8UzT6d": "",
"8apB7W": "Remover este membro da organização.",
"8eQ7FM": "Continuar com GitHub",
"8ekFRM": "Nenhum funil encontrado",
@@ -284,6 +285,7 @@
"9qBH5R": "Nenhuma feature flag encontrada",
"9tjZ7S": "Falha ao criar usuário",
"9uKBh7": "Config remota",
+ "9y9QQh": "",
"A/lLjO": "Gerando...",
"A4AHkc": "min",
"A5E371": "A página que você procura não existe ou foi movida. Vamos levá-lo de volta para analisar seus dados.",
@@ -746,6 +748,7 @@
"SDTG4X": "A meta principal é o evento de conversão ou visita de página usado para comparar as variantes.",
"SElbF+": "Salvar filtro",
"SQJto2": "Entrar",
+ "SVwJTM": "",
"SWvHLr": "Esta Semana",
"SX126d": "Exportar dados",
"Sb7oIl": "Desempenho por Sistema Operacional",
@@ -1303,6 +1306,7 @@
"pW4lxD": "Padrão",
"pZrL8g": "Exportados {fileCount} arquivos",
"pm+3nT": "SDK do React Native",
+ "pmt5UZ": "",
"pnkSRp": "Subdivisões",
"poMLbD": "Filtrar experimentos",
"poXmsM": "Digite seu endereço de email e enviaremos um código de verificação para redefinir sua senha.",
diff --git a/client/messages/uk.json b/client/messages/uk.json
index d6683c780..0da59618d 100644
--- a/client/messages/uk.json
+++ b/client/messages/uk.json
@@ -240,6 +240,7 @@
"8Nc/jD": "Вебсайтів ще немає",
"8O/fqy": "",
"8O9cAb": "",
+ "8UzT6d": "",
"8apB7W": "Видалити цього учасника з організації.",
"8eQ7FM": "Продовжити через GitHub",
"8ekFRM": "Воронок не знайдено",
@@ -284,6 +285,7 @@
"9qBH5R": "",
"9tjZ7S": "Не вдалося створити користувача",
"9uKBh7": "",
+ "9y9QQh": "",
"A/lLjO": "Генерування...",
"A4AHkc": "Мін.",
"A5E371": "Сторінки, яку ви шукаєте, не існує або її було переміщено. Давайте повернемося до аналізу ваших даних.",
@@ -746,6 +748,7 @@
"SDTG4X": "",
"SElbF+": "",
"SQJto2": "Увійти",
+ "SVwJTM": "",
"SWvHLr": "Цього тижня",
"SX126d": "Експортувати дані",
"Sb7oIl": "Продуктивність за ОС",
@@ -1303,6 +1306,7 @@
"pW4lxD": "Шаблон",
"pZrL8g": "Експортовано {fileCount} файлів",
"pm+3nT": "",
+ "pmt5UZ": "",
"pnkSRp": "Підрозділи (Регіони)",
"poMLbD": "",
"poXmsM": "Введіть вашу електронну адресу, і ми надішлемо вам код підтвердження для скидання пароля.",
diff --git a/client/messages/zh.json b/client/messages/zh.json
index eeffe9b64..906bc0874 100644
--- a/client/messages/zh.json
+++ b/client/messages/zh.json
@@ -240,6 +240,7 @@
"8Nc/jD": "还没有网站",
"8O/fqy": "将此实验关联到您已追踪的目标。",
"8O9cAb": "过去 24 小时",
+ "8UzT6d": "",
"8apB7W": "从组织中移除此成员。",
"8eQ7FM": "继续使用 GitHub",
"8ekFRM": "未找到漏斗",
@@ -284,6 +285,7 @@
"9qBH5R": "未找到功能标志",
"9tjZ7S": "创建用户失败",
"9uKBh7": "远程配置",
+ "9y9QQh": "",
"A/lLjO": "正在生成...",
"A4AHkc": "分钟",
"A5E371": "您正在寻找的页面不存在或已被移动。让我们带您回到数据分析的轨道。",
@@ -746,6 +748,7 @@
"SDTG4X": "主要目标是用于比较各变体的转化事件或页面访问。",
"SElbF+": "保存筛选器",
"SQJto2": "登录",
+ "SVwJTM": "",
"SWvHLr": "本周",
"SX126d": "导出数据",
"Sb7oIl": "按操作系统划分的性能",
@@ -1303,6 +1306,7 @@
"pW4lxD": "模式",
"pZrL8g": "导出了 {fileCount} 个文件",
"pm+3nT": "React Native SDK",
+ "pmt5UZ": "",
"pnkSRp": "子区域",
"poMLbD": "筛选实验",
"poXmsM": "输入您的电子邮件地址,我们将向您发送验证码以重置您的密码。",
diff --git a/client/src/app/[site]/dashboards/components/DashboardCardView.tsx b/client/src/app/[site]/dashboards/components/DashboardCardView.tsx
index 3b5f5bdf1..749c0dd9c 100644
--- a/client/src/app/[site]/dashboards/components/DashboardCardView.tsx
+++ b/client/src/app/[site]/dashboards/components/DashboardCardView.tsx
@@ -6,6 +6,7 @@ import { useMemo, useState } from "react";
import { useDashboardCard } from "../../../../api/analytics/hooks/useDashboardCard";
import { cn } from "../../../../lib/utils";
import { Button } from "../../../../components/ui/button";
+import { QueryResultsExportMenu } from "../../query/components/QueryResultsExportMenu";
import { ResultsTable } from "../../query/components/ResultsTable";
import type { SortState } from "../../query/types";
import { getColumns, sortRows } from "../../query/utils";
@@ -65,22 +66,36 @@ export function DashboardCardView({ siteId, card, editMode, onEdit, onClone, onR
</span>
)}
</div>
- {editMode && (
+ {(rows.length > 0 || editMode) && (
<div className="dashboard-card-no-drag flex shrink-0 items-center gap-0.5">
- <Button type="button" size="smIcon" variant="ghost" onClick={onEdit} aria-label="Edit card">
- <Pencil className="h-3.5 w-3.5" />
- </Button>
- <Button type="button" size="smIcon" variant="ghost" onClick={onClone} aria-label="Duplicate card">
- <Copy className="h-3.5 w-3.5" />
- </Button>
- <Button type="button" size="smIcon" variant="ghost" onClick={onRemove} aria-label="Remove card">
- <Trash2 className="h-3.5 w-3.5 text-red-500" />
- </Button>
+ {rows.length > 0 && (
+ <QueryResultsExportMenu
+ rows={sortedRows}
+ columns={columns}
+ filenameBase={`dashboard-${card.title || "card"}`}
+ compact
+ />
+ )}
+ {editMode && (
+ <>
+ <Button type="button" size="smIcon" variant="ghost" onClick={onEdit} aria-label="Edit card">
+ <Pencil className="h-3.5 w-3.5" />
+ </Button>
+ <Button type="button" size="smIcon" variant="ghost" onClick={onClone} aria-label="Duplicate card">
+ <Copy className="h-3.5 w-3.5" />
+ </Button>
+ <Button type="button" size="smIcon" variant="ghost" onClick={onRemove} aria-label="Remove card">
+ <Trash2 className="h-3.5 w-3.5 text-red-500" />
+ </Button>
+ </>
+ )}
</div>
)}
</div>
- <div className={cn("relative flex min-h-0 flex-1 flex-col p-1", isTable ? "overflow-hidden" : "overflow-visible")}>
+ <div
+ className={cn("relative flex min-h-0 flex-1 flex-col p-1", isTable ? "overflow-hidden" : "overflow-visible")}
+ >
{isLoading ? (
<div className="flex h-full items-center justify-center">
<Loader2 className="h-5 w-5 animate-spin text-neutral-400" />
diff --git a/client/src/app/[site]/query/components/QueryResultsExportMenu.tsx b/client/src/app/[site]/query/components/QueryResultsExportMenu.tsx
new file mode 100644
index 000000000..3917539c0
--- /dev/null
+++ b/client/src/app/[site]/query/components/QueryResultsExportMenu.tsx
@@ -0,0 +1,91 @@
+"use client";
+
+import { Braces, Download, FileText } from "lucide-react";
+import { useExtracted } from "next-intl";
+import type { CustomQueryRow } from "../../../../api/analytics/endpoints";
+import { Button } from "../../../../components/ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from "../../../../components/ui/dropdown-menu";
+import { Tooltip, TooltipContent, TooltipTrigger } from "../../../../components/ui/tooltip";
+import { downloadCSV, downloadJSON, formatDateForFilename } from "../../../../lib/export";
+import { cn } from "../../../../lib/utils";
+
+type QueryResultsExportMenuProps = {
+ rows: CustomQueryRow[];
+ columns: string[];
+ filenameBase: string;
+ disabled?: boolean;
+ compact?: boolean;
+ className?: string;
+};
+
+function sanitizeFilename(value: string) {
+ return (
+ value
+ .trim()
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, "-")
+ .replace(/^-+|-+$/g, "")
+ .slice(0, 80) || "query-results"
+ );
+}
+
+export function QueryResultsExportMenu({
+ rows,
+ columns,
+ filenameBase,
+ disabled,
+ compact = false,
+ className,
+}: QueryResultsExportMenuProps) {
+ const t = useExtracted();
+ const canExport = !disabled && rows.length > 0;
+ const filename = `${sanitizeFilename(filenameBase)}-${formatDateForFilename()}`;
+
+ const handleExportCsv = () => {
+ if (!canExport) return;
+ downloadCSV(`${filename}.csv`, rows, columns);
+ };
+
+ const handleExportJson = () => {
+ if (!canExport) return;
+ downloadJSON(`${filename}.json`, rows);
+ };
+
+ return (
+ <DropdownMenu>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <DropdownMenuTrigger asChild>
+ <Button
+ type="button"
+ variant="ghost"
+ size={compact ? "smIcon" : "xs"}
+ disabled={!canExport}
+ aria-label={t("Download results")}
+ className={cn(compact ? "h-7 w-7" : "h-7 px-2", className)}
+ >
+ <Download className="h-3.5 w-3.5" />
+ {!compact && <span>{t("Export")}</span>}
+ </Button>
+ </DropdownMenuTrigger>
+ </TooltipTrigger>
+ <TooltipContent>{t("Download results")}</TooltipContent>
+ </Tooltip>
+ <DropdownMenuContent align="end" className="w-36">
+ <DropdownMenuItem onClick={handleExportCsv} disabled={!canExport}>
+ <FileText className="h-4 w-4" />
+ {t("CSV")}
+ </DropdownMenuItem>
+ <DropdownMenuItem onClick={handleExportJson} disabled={!canExport}>
+ <Braces className="h-4 w-4" />
+ {t("JSON")}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
diff --git a/client/src/app/[site]/query/components/ResultsPanel.tsx b/client/src/app/[site]/query/components/ResultsPanel.tsx
index c0649b829..90a8ab993 100644
--- a/client/src/app/[site]/query/components/ResultsPanel.tsx
+++ b/client/src/app/[site]/query/components/ResultsPanel.tsx
@@ -4,6 +4,7 @@ import { AlertCircle } from "lucide-react";
import { useExtracted } from "next-intl";
import type { CustomQueryRow } from "../../../../api/analytics/endpoints";
import type { QueryTab, SortState } from "../types";
+import { QueryResultsExportMenu } from "./QueryResultsExportMenu";
import { ResultsTable } from "./ResultsTable";
type ResultsPanelProps = {
@@ -21,16 +22,21 @@ export function ResultsPanel({ activeTab, columns, rows, sort, onSortChange }: R
<div className="flex min-h-0 flex-1 flex-col overflow-hidden rounded-lg border border-neutral-150 bg-white dark:border-neutral-850 dark:bg-neutral-900">
<div className="flex h-10 items-center justify-between border-b border-neutral-100 px-3 dark:border-neutral-850">
<div className="text-sm font-medium text-neutral-900 dark:text-neutral-100">{t("Results")}</div>
- <div className="text-xs text-neutral-500 dark:text-neutral-400">
- {activeTab?.resultError ? (
- <span className="inline-flex items-center gap-1 text-red-600 dark:text-red-400">
- <AlertCircle className="h-3.5 w-3.5" />
- {t("Error")}
- </span>
- ) : activeTab?.hasRun ? (
- t("{count} rows", { count: activeTab.rows.length.toLocaleString() })
- ) : (
- t("Not run")
+ <div className="flex items-center gap-2">
+ <div className="text-xs text-neutral-500 dark:text-neutral-400">
+ {activeTab?.resultError ? (
+ <span className="inline-flex items-center gap-1 text-red-600 dark:text-red-400">
+ <AlertCircle className="h-3.5 w-3.5" />
+ {t("Error")}
+ </span>
+ ) : activeTab?.hasRun ? (
+ t("{count} rows", { count: activeTab.rows.length.toLocaleString() })
+ ) : (
+ t("Not run")
+ )}
+ </div>
+ {activeTab?.hasRun && !activeTab.resultError && rows.length > 0 && (
+ <QueryResultsExportMenu rows={rows} columns={columns} filenameBase={activeTab.name || "query-results"} />
)}
</div>
</div>
diff --git a/client/src/lib/export.ts b/client/src/lib/export.ts
index 75660e22e..2f92affde 100644
--- a/client/src/lib/export.ts
+++ b/client/src/lib/export.ts
@@ -16,13 +16,51 @@ export function generateCSV(data: Record<string, unknown>[]): string {
return Papa.unparse(data);
}
+function normalizeCsvValue(value: unknown): unknown {
+ if (value === null || value === undefined) return "";
+ if (typeof value === "object") return JSON.stringify(value);
+ return value;
+}
+
+export function generateCSVWithColumns(data: Record<string, unknown>[], columns: string[]): string {
+ if (data.length === 0 && columns.length === 0) {
+ return "";
+ }
+
+ return Papa.unparse({
+ fields: columns,
+ data: data.map(row => columns.map(column => normalizeCsvValue(row[column]))),
+ });
+}
+
+export function downloadBlob(filename: string, blob: Blob): void {
+ const url = URL.createObjectURL(blob);
+ const link = document.createElement("a");
+ link.href = url;
+ link.download = filename;
+ document.body.appendChild(link);
+ link.click();
+ document.body.removeChild(link);
+ URL.revokeObjectURL(url);
+}
+
+export function downloadFile(filename: string, content: string, type: string): void {
+ downloadBlob(filename, new Blob([content], { type }));
+}
+
+export function downloadCSV(filename: string, data: Record<string, unknown>[], columns?: string[]): void {
+ const csvContent = columns ? generateCSVWithColumns(data, columns) : generateCSV(data);
+ downloadFile(filename, csvContent, "text/csv;charset=utf-8");
+}
+
+export function downloadJSON(filename: string, data: unknown): void {
+ downloadFile(filename, JSON.stringify(data, null, 2), "application/json;charset=utf-8");
+}
+
/**
* Create a ZIP file containing multiple CSVs and trigger download
*/
-export async function downloadZip(
- files: CSVFile[],
- zipFilename: string
-): Promise<void> {
+export async function downloadZip(files: CSVFile[], zipFilename: string): Promise<void> {
const zip = new JSZip();
for (const file of files) {
@@ -34,15 +72,7 @@ export async function downloadZip(
const blob = await zip.generateAsync({ type: "blob" });
- // Create download link and trigger download
- const url = URL.createObjectURL(blob);
- const link = document.createElement("a");
- link.href = url;
- link.download = zipFilename;
- document.body.appendChild(link);
- link.click();
- document.body.removeChild(link);
- URL.revokeObjectURL(url);
+ downloadBlob(zipFilename, blob);
}
/**