@hienlh/ppm 0.9.71 → 0.9.73
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +26 -0
- package/dist/web/assets/{chat-tab-rHbqenEa.js → chat-tab-ByDDO6Pl.js} +2 -2
- package/dist/web/assets/{code-editor-C34pPIaA.js → code-editor-D8VveTUt.js} +1 -1
- package/dist/web/assets/database-viewer-CcTlsR2D.js +2 -0
- package/dist/web/assets/{diff-viewer-CrUaMMwc.js → diff-viewer-CXU5BvCX.js} +1 -1
- package/dist/web/assets/{extension-webview-EJvlbzMw.js → extension-webview-Dzkyl-2t.js} +1 -1
- package/dist/web/assets/{git-graph-boq7GWXZ.js → git-graph-Ce8pbmQX.js} +1 -1
- package/dist/web/assets/index-B_sM201v.css +2 -0
- package/dist/web/assets/{index-DHr-SBBY.js → index-Y-Kfye7A.js} +3 -3
- package/dist/web/assets/keybindings-store-DoRbfX4Q.js +1 -0
- package/dist/web/assets/{markdown-renderer-BrW4qEBv.js → markdown-renderer-BinWj98E.js} +1 -1
- package/dist/web/assets/{port-forwarding-tab-UB_l73FZ.js → port-forwarding-tab-D15vANLc.js} +1 -1
- package/dist/web/assets/{postgres-viewer-BZE43hDP.js → postgres-viewer-Nlg7DV9i.js} +1 -1
- package/dist/web/assets/{settings-tab-DPx50bZm.js → settings-tab-BY9LX5Du.js} +1 -1
- package/dist/web/assets/{sql-query-editor-CPBBvi1U.js → sql-query-editor-njmHoOsX.js} +1 -1
- package/dist/web/assets/{sqlite-viewer-DbHvVTSs.js → sqlite-viewer-jSYguEYD.js} +1 -1
- package/dist/web/assets/{terminal-tab-Br_Zlw2Z.js → terminal-tab-DUz3dmkj.js} +1 -1
- package/dist/web/assets/{use-monaco-theme-DDZwQjEv.js → use-monaco-theme-Dl6w9X-L.js} +1 -1
- package/dist/web/index.html +2 -2
- package/dist/web/sw.js +1 -1
- package/docs/project-changelog.md +22 -1
- package/docs/system-architecture.md +1 -1
- package/package.json +1 -1
- package/src/providers/claude-agent-sdk.ts +59 -22
- package/src/services/account-selector.service.ts +25 -7
- package/src/types/chat.ts +1 -0
- package/src/web/components/chat/message-list.tsx +5 -0
- package/src/web/components/database/data-grid.tsx +114 -8
- package/src/web/hooks/use-chat.ts +7 -0
- package/dist/web/assets/database-viewer-8Eifo5Ak.js +0 -2
- package/dist/web/assets/index-C4vNxaKi.css +0 -2
- package/dist/web/assets/keybindings-store-CWfygy_t.js +0 -1
|
@@ -18,7 +18,7 @@ import { mcpConfigService } from "../services/mcp-config.service.ts";
|
|
|
18
18
|
import { updateFromSdkEvent } from "../services/claude-usage.service.ts";
|
|
19
19
|
import { getSessionMapping, getSessionProjectPath, setSessionMapping, getSessionTitles } from "../services/db.service.ts";
|
|
20
20
|
import { accountSelector } from "../services/account-selector.service.ts";
|
|
21
|
-
import { accountService } from "../services/account.service.ts";
|
|
21
|
+
import { accountService, type AccountWithTokens } from "../services/account.service.ts";
|
|
22
22
|
import { resolve } from "node:path";
|
|
23
23
|
import { existsSync, readdirSync, unlinkSync } from "node:fs";
|
|
24
24
|
import { homedir } from "node:os";
|
|
@@ -657,28 +657,65 @@ export class ClaudeAgentSdkProvider implements AIProvider {
|
|
|
657
657
|
// Account-based auth injection (multi-account mode)
|
|
658
658
|
// Fallback to existing env (ANTHROPIC_API_KEY) when no accounts configured.
|
|
659
659
|
const accountsEnabled = accountSelector.isEnabled();
|
|
660
|
-
let account
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
const
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
660
|
+
let account: AccountWithTokens | null = null;
|
|
661
|
+
|
|
662
|
+
if (accountsEnabled) {
|
|
663
|
+
const excludeIds = new Set<string>();
|
|
664
|
+
|
|
665
|
+
// Pre-flight loop: select account → refresh token → retry with next if refresh fails
|
|
666
|
+
while (true) {
|
|
667
|
+
yield { type: "status_update" as const, phase: "routing" as const, message: "Selecting account..." };
|
|
668
|
+
account = accountSelector.next(excludeIds);
|
|
669
|
+
|
|
670
|
+
if (!account) {
|
|
671
|
+
const reason = accountSelector.lastFailReason;
|
|
672
|
+
let hint: string;
|
|
673
|
+
if (reason === "all_decrypt_failed") {
|
|
674
|
+
hint = "Account tokens were encrypted with a different machine key. Re-add your accounts in Settings, or copy ~/.ppm/account.key from the original machine.";
|
|
675
|
+
} else if (reason === "all_excluded") {
|
|
676
|
+
hint = "All accounts failed token refresh. Check Settings → Accounts.";
|
|
677
|
+
} else {
|
|
678
|
+
hint = "All accounts are disabled or in cooldown. Check Settings → Accounts.";
|
|
679
|
+
}
|
|
680
|
+
console.error(`[sdk] session=${sessionId} account auth failed (${reason}): ${hint}`);
|
|
681
|
+
yield { type: "error" as const, message: `Authentication failed: ${hint}` };
|
|
682
|
+
yield { type: "done" as const, sessionId, resultSubtype: "error_auth" };
|
|
683
|
+
return;
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
const accountLabel = account.label ?? account.email ?? "Unknown";
|
|
687
|
+
const nowS = Math.floor(Date.now() / 1000);
|
|
688
|
+
const expiresIn = account.expiresAt ? account.expiresAt - nowS : null;
|
|
689
|
+
console.log(`[sdk] Using account ${account.id} (${account.email ?? "no-email"}) token_expires_in=${expiresIn}s`);
|
|
690
|
+
|
|
691
|
+
// Check if token needs refresh
|
|
692
|
+
const isOAuth = account.accessToken.startsWith("sk-ant-oat");
|
|
693
|
+
const needsRefresh = isOAuth && account.expiresAt && (account.expiresAt - nowS <= 3600);
|
|
694
|
+
|
|
695
|
+
if (!needsRefresh) {
|
|
696
|
+
// Token fresh or API key — proceed
|
|
697
|
+
yield { type: "account_info" as const, accountId: account.id, accountLabel };
|
|
698
|
+
break;
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
// Token expiring — attempt refresh
|
|
702
|
+
yield { type: "status_update" as const, phase: "refreshing" as const, message: `Refreshing token for ${accountLabel}...`, accountLabel };
|
|
703
|
+
const fresh = await accountService.ensureFreshToken(account.id);
|
|
704
|
+
|
|
705
|
+
if (fresh) {
|
|
706
|
+
account = fresh;
|
|
707
|
+
const freshLabel = account.label ?? account.email ?? "Unknown";
|
|
708
|
+
yield { type: "account_info" as const, accountId: account.id, accountLabel: freshLabel };
|
|
709
|
+
break;
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
// Refresh failed — cooldown this account, try next
|
|
713
|
+
console.warn(`[sdk] session=${sessionId} pre-flight refresh failed for ${account.id} — trying next account`);
|
|
714
|
+
yield { type: "status_update" as const, phase: "switching" as const, message: `Token expired for ${accountLabel}, trying next account...`, accountLabel };
|
|
715
|
+
accountSelector.onPreflightFail(account.id);
|
|
716
|
+
excludeIds.add(account.id);
|
|
717
|
+
// continue loop → pick next account
|
|
680
718
|
}
|
|
681
|
-
yield { type: "account_info" as const, accountId: account.id, accountLabel: account.label ?? account.email ?? "Unknown" };
|
|
682
719
|
}
|
|
683
720
|
const queryEnv = this.buildQueryEnv(meta.projectPath, account);
|
|
684
721
|
|
|
@@ -40,10 +40,10 @@ class AccountSelectorService {
|
|
|
40
40
|
}
|
|
41
41
|
|
|
42
42
|
/** Reason for the last null return from next() */
|
|
43
|
-
private _lastFailReason: "none" | "no_active" | "all_decrypt_failed" = "none";
|
|
43
|
+
private _lastFailReason: "none" | "no_active" | "all_decrypt_failed" | "all_excluded" = "none";
|
|
44
44
|
|
|
45
45
|
/** Why the last next() call returned null */
|
|
46
|
-
get lastFailReason(): "none" | "no_active" | "all_decrypt_failed" {
|
|
46
|
+
get lastFailReason(): "none" | "no_active" | "all_decrypt_failed" | "all_excluded" {
|
|
47
47
|
return this._lastFailReason;
|
|
48
48
|
}
|
|
49
49
|
|
|
@@ -51,7 +51,7 @@ class AccountSelectorService {
|
|
|
51
51
|
* Pick next available account (skips cooldown/disabled).
|
|
52
52
|
* Returns null if no active accounts available.
|
|
53
53
|
*/
|
|
54
|
-
next(): AccountWithTokens | null {
|
|
54
|
+
next(excludeIds?: Set<string>): AccountWithTokens | null {
|
|
55
55
|
this._lastFailReason = "none";
|
|
56
56
|
const now = Math.floor(Date.now() / 1000);
|
|
57
57
|
const allAccounts = accountService.list();
|
|
@@ -71,17 +71,19 @@ class AccountSelectorService {
|
|
|
71
71
|
}
|
|
72
72
|
|
|
73
73
|
const active = accountService.list().filter((a) => a.status === "active");
|
|
74
|
-
|
|
75
|
-
|
|
74
|
+
// Skip accounts excluded by caller (e.g., pre-flight loop)
|
|
75
|
+
const notExcluded = excludeIds?.size ? active.filter((a) => !excludeIds.has(a.id)) : active;
|
|
76
|
+
if (notExcluded.length === 0) {
|
|
77
|
+
this._lastFailReason = active.length > 0 ? "all_excluded" : "no_active";
|
|
76
78
|
return null;
|
|
77
79
|
}
|
|
78
80
|
|
|
79
81
|
// Proactive: skip accounts whose 5-hour utilization >= 95%
|
|
80
|
-
const usable =
|
|
82
|
+
const usable = notExcluded.filter((a) => {
|
|
81
83
|
const snap = getLatestSnapshotForAccount(a.id);
|
|
82
84
|
return !snap || (snap.five_hour_util ?? 0) < FIVE_HOUR_SKIP_THRESHOLD;
|
|
83
85
|
});
|
|
84
|
-
const candidates = usable.length > 0 ? usable :
|
|
86
|
+
const candidates = usable.length > 0 ? usable : notExcluded; // fallback to all if every account is near limit
|
|
85
87
|
|
|
86
88
|
let pickedId: string;
|
|
87
89
|
const strategy = this.getStrategy();
|
|
@@ -195,6 +197,22 @@ class AccountSelectorService {
|
|
|
195
197
|
console.log(`[accounts] ${accountId} auth error — cooldown ${Math.round(backoffMs / 1000)}s (retry #${retries})`);
|
|
196
198
|
}
|
|
197
199
|
|
|
200
|
+
private static readonly PREFLIGHT_BACKOFF_BASE_MS = 60_000; // 1 minute
|
|
201
|
+
private static readonly PREFLIGHT_BACKOFF_MAX_MS = 5 * 60_000; // 5 minutes
|
|
202
|
+
|
|
203
|
+
/** Called when pre-flight token refresh fails — short cooldown.
|
|
204
|
+
* Shares retryCounts with onRateLimit/onAuthError (cumulative penalty by design). */
|
|
205
|
+
onPreflightFail(accountId: string): void {
|
|
206
|
+
const retries = (this.retryCounts.get(accountId) ?? 0) + 1;
|
|
207
|
+
this.retryCounts.set(accountId, retries);
|
|
208
|
+
const backoffMs = Math.min(
|
|
209
|
+
AccountSelectorService.PREFLIGHT_BACKOFF_BASE_MS * Math.pow(2, retries - 1),
|
|
210
|
+
AccountSelectorService.PREFLIGHT_BACKOFF_MAX_MS,
|
|
211
|
+
);
|
|
212
|
+
accountService.setCooldown(accountId, Date.now() + backoffMs);
|
|
213
|
+
console.log(`[accounts] ${accountId} preflight refresh failed — cooldown ${Math.round(backoffMs / 1000)}s (retry #${retries})`);
|
|
214
|
+
}
|
|
215
|
+
|
|
198
216
|
/** Called on successful request — reset retry count + track usage */
|
|
199
217
|
onSuccess(accountId: string): void {
|
|
200
218
|
this.retryCounts.delete(accountId);
|
package/src/types/chat.ts
CHANGED
|
@@ -120,6 +120,7 @@ export type ChatEvent =
|
|
|
120
120
|
| { type: "session_migrated"; oldSessionId: string; newSessionId: string }
|
|
121
121
|
| { type: "account_info"; accountId: string; accountLabel: string }
|
|
122
122
|
| { type: "account_retry"; reason: string; accountId?: string; accountLabel?: string }
|
|
123
|
+
| { type: "status_update"; phase: "routing" | "refreshing" | "switching"; message: string; accountLabel?: string }
|
|
123
124
|
| { type: "system"; subtype: string }
|
|
124
125
|
| { type: "team_detected"; teamName: string }
|
|
125
126
|
| { type: "team_updated"; teamName: string; team: unknown }
|
|
@@ -618,6 +618,11 @@ function InterleavedEvents({ events, isStreaming, projectName }: { events: ChatE
|
|
|
618
618
|
groups.push({ kind: "thinking", content: thinkingBuffer });
|
|
619
619
|
thinkingBuffer = "";
|
|
620
620
|
}
|
|
621
|
+
if (event.type === "status_update") {
|
|
622
|
+
if (textBuffer) { groups.push({ kind: "text", content: textBuffer }); textBuffer = ""; }
|
|
623
|
+
groups.push({ kind: "text", content: `\n\n> ⟳ ${event.message}\n\n` });
|
|
624
|
+
continue;
|
|
625
|
+
}
|
|
621
626
|
if (event.type === "account_retry") {
|
|
622
627
|
if (textBuffer) { groups.push({ kind: "text", content: textBuffer }); textBuffer = ""; }
|
|
623
628
|
const label = (event as any).accountLabel ?? "another account";
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { useState, useCallback, useMemo, useRef, memo, useEffect } from "react";
|
|
2
|
-
import { Loader2, ChevronLeft, ChevronRight, ChevronUp, ChevronDown, Trash2, Plus, Search, X, Eye, Filter, Pin, PinOff } from "lucide-react";
|
|
2
|
+
import { Loader2, ChevronLeft, ChevronRight, ChevronUp, ChevronDown, Trash2, Plus, Search, X, Eye, Filter, Pin, PinOff, Columns3 } from "lucide-react";
|
|
3
3
|
import { useTabStore } from "@/stores/tab-store";
|
|
4
4
|
import type { DbColumnInfo } from "./use-database";
|
|
5
5
|
import { ExportButton } from "./export-button";
|
|
@@ -55,6 +55,8 @@ export function DataGrid({
|
|
|
55
55
|
const [pinnedCols, setPinnedCols] = useState<Set<string>>(new Set());
|
|
56
56
|
const [pinnedRows, setPinnedRows] = useState<Set<number>>(new Set());
|
|
57
57
|
const [filterOpenCol, setFilterOpenCol] = useState<string | null>(null);
|
|
58
|
+
const [colSearchOpen, setColSearchOpen] = useState(false);
|
|
59
|
+
const scrollRef = useRef<HTMLDivElement>(null);
|
|
58
60
|
|
|
59
61
|
const pkCol = useMemo(() => {
|
|
60
62
|
const explicit = schema.find((c) => c.pk)?.name;
|
|
@@ -63,6 +65,18 @@ export function DataGrid({
|
|
|
63
65
|
return idCol?.name ?? null;
|
|
64
66
|
}, [schema]);
|
|
65
67
|
|
|
68
|
+
const openRowViewer = useCallback((row: Record<string, unknown>) => {
|
|
69
|
+
const json = JSON.stringify(row, null, 2);
|
|
70
|
+
const pk = pkCol ? String(row[pkCol] ?? "") : "";
|
|
71
|
+
openTab({
|
|
72
|
+
type: "editor",
|
|
73
|
+
title: pk ? `Row ${pk}` : "Row",
|
|
74
|
+
projectId: null,
|
|
75
|
+
closable: true,
|
|
76
|
+
metadata: { inlineContent: json, inlineLanguage: "json" },
|
|
77
|
+
});
|
|
78
|
+
}, [openTab, pkCol]);
|
|
79
|
+
|
|
66
80
|
// Refs for cell renderers — avoid column memo rebuild on every state change
|
|
67
81
|
const editingRef = useRef(editingCell);
|
|
68
82
|
editingRef.current = editingCell;
|
|
@@ -180,12 +194,23 @@ export function DataGrid({
|
|
|
180
194
|
const el = containerRef.current;
|
|
181
195
|
if (!el) return;
|
|
182
196
|
const handler = (e: KeyboardEvent) => {
|
|
183
|
-
|
|
184
|
-
if (
|
|
197
|
+
// Escape closes column search from anywhere
|
|
198
|
+
if (e.key === "Escape") { setColSearchOpen(false); return; }
|
|
199
|
+
|
|
185
200
|
// Skip if focus is in an input/textarea
|
|
186
201
|
const tag = (e.target as HTMLElement)?.tagName;
|
|
187
202
|
if (tag === "INPUT" || tag === "TEXTAREA") return;
|
|
188
203
|
|
|
204
|
+
// "/" → open column jump (like VSCode list filter)
|
|
205
|
+
if (e.key === "/") {
|
|
206
|
+
e.preventDefault();
|
|
207
|
+
setColSearchOpen(true);
|
|
208
|
+
return;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
const mod = e.metaKey || e.ctrlKey;
|
|
212
|
+
if (!mod || !tableData) return;
|
|
213
|
+
|
|
189
214
|
if (e.key === "a") {
|
|
190
215
|
e.preventDefault();
|
|
191
216
|
setSelectedRows(new Set(tableData.rows.map((_, i) => i)));
|
|
@@ -293,6 +318,22 @@ export function DataGrid({
|
|
|
293
318
|
return tops;
|
|
294
319
|
}, [headerHeight, pinnedRowData, pinnedRowHeights]);
|
|
295
320
|
|
|
321
|
+
const jumpToColumn = useCallback((col: string) => {
|
|
322
|
+
const container = scrollRef.current;
|
|
323
|
+
const th = container?.querySelector<HTMLElement>(`th[data-col="${col}"]`);
|
|
324
|
+
if (!container || !th) return;
|
|
325
|
+
// Calculate sticky left offset (checkbox + pinned columns)
|
|
326
|
+
let stickyWidth = 0;
|
|
327
|
+
const cbTh = container.querySelector<HTMLElement>(`th[data-col="_cb"]`);
|
|
328
|
+
if (cbTh) stickyWidth += cbTh.offsetWidth;
|
|
329
|
+
for (const [pc, offset] of pinnedColOffsets) {
|
|
330
|
+
if (pc !== col) stickyWidth = Math.max(stickyWidth, offset + (colWidths.get(pc) ?? 0));
|
|
331
|
+
}
|
|
332
|
+
const targetLeft = th.offsetLeft - stickyWidth;
|
|
333
|
+
container.scrollTo({ left: targetLeft, behavior: "smooth" });
|
|
334
|
+
setColSearchOpen(false);
|
|
335
|
+
}, [pinnedColOffsets, colWidths]);
|
|
336
|
+
|
|
296
337
|
if (!tableData) {
|
|
297
338
|
return (
|
|
298
339
|
<div className="flex items-center justify-center h-full text-xs text-muted-foreground">
|
|
@@ -321,6 +362,20 @@ export function DataGrid({
|
|
|
321
362
|
)}
|
|
322
363
|
</div>
|
|
323
364
|
|
|
365
|
+
{/* Column jump */}
|
|
366
|
+
<div className="relative">
|
|
367
|
+
<button type="button" onClick={() => setColSearchOpen(!colSearchOpen)}
|
|
368
|
+
className={`p-0.5 rounded transition-colors ${colSearchOpen ? "text-primary" : "text-muted-foreground hover:text-foreground"}`}
|
|
369
|
+
title="Jump to column ( / )">
|
|
370
|
+
<Columns3 className="size-3.5" />
|
|
371
|
+
</button>
|
|
372
|
+
{colSearchOpen && (
|
|
373
|
+
<ColumnSearchDropdown columns={tableData.columns}
|
|
374
|
+
onSelect={jumpToColumn}
|
|
375
|
+
onClose={() => setColSearchOpen(false)} />
|
|
376
|
+
)}
|
|
377
|
+
</div>
|
|
378
|
+
|
|
324
379
|
{hasSelection && (
|
|
325
380
|
<div className="flex items-center gap-1.5 text-xs">
|
|
326
381
|
<span className="text-muted-foreground">{selectedRows.size} selected</span>
|
|
@@ -377,7 +432,7 @@ export function DataGrid({
|
|
|
377
432
|
)}
|
|
378
433
|
|
|
379
434
|
{/* Table */}
|
|
380
|
-
<div className="flex-1 overflow-auto relative">
|
|
435
|
+
<div ref={scrollRef} className="flex-1 overflow-auto relative">
|
|
381
436
|
{loading && (
|
|
382
437
|
<div className="absolute inset-0 z-30 flex items-center justify-center bg-background/60">
|
|
383
438
|
<Loader2 className="size-5 animate-spin text-primary" />
|
|
@@ -455,7 +510,7 @@ export function DataGrid({
|
|
|
455
510
|
onSetEditValue={setEditValue} showDelete={!!onRowDelete}
|
|
456
511
|
confirmingDelete={confirmDeleteIdx === idx}
|
|
457
512
|
onDelete={handleDelete} onConfirmDelete={setConfirmDeleteIdx}
|
|
458
|
-
onViewCell={openCellViewer}
|
|
513
|
+
onViewCell={openCellViewer} onViewRow={openRowViewer}
|
|
459
514
|
pinned onTogglePin={togglePinRow}
|
|
460
515
|
pinnedCols={pinnedCols} pinnedColOffsets={pinnedColOffsets}
|
|
461
516
|
stickyTop={pinnedRowTops.get(idx) ?? headerHeight}
|
|
@@ -472,7 +527,7 @@ export function DataGrid({
|
|
|
472
527
|
onSetEditValue={setEditValue} showDelete={!!onRowDelete}
|
|
473
528
|
confirmingDelete={confirmDeleteIdx === rowIdx}
|
|
474
529
|
onDelete={handleDelete} onConfirmDelete={setConfirmDeleteIdx}
|
|
475
|
-
onViewCell={openCellViewer}
|
|
530
|
+
onViewCell={openCellViewer} onViewRow={openRowViewer}
|
|
476
531
|
pinned={false} onTogglePin={togglePinRow}
|
|
477
532
|
pinnedCols={pinnedCols} pinnedColOffsets={pinnedColOffsets} />
|
|
478
533
|
);
|
|
@@ -487,6 +542,12 @@ export function DataGrid({
|
|
|
487
542
|
{/* Footer: row count + pagination */}
|
|
488
543
|
<div className="flex items-center justify-between px-3 py-1.5 border-t border-border bg-background shrink-0 text-xs text-muted-foreground">
|
|
489
544
|
<span>{tableData.total.toLocaleString()} rows</span>
|
|
545
|
+
{/* Shortcut hints — desktop only */}
|
|
546
|
+
<div className="hidden md:flex items-center gap-2 text-[10px] text-muted-foreground/50">
|
|
547
|
+
<span><kbd className="px-1 py-0.5 rounded bg-muted text-[9px]">/</kbd> columns</span>
|
|
548
|
+
<span><kbd className="px-1 py-0.5 rounded bg-muted text-[9px]">{"\u2318"}A</kbd> select all</span>
|
|
549
|
+
<span><kbd className="px-1 py-0.5 rounded bg-muted text-[9px]">{"\u2318"}C</kbd> copy</span>
|
|
550
|
+
</div>
|
|
490
551
|
<div className="flex items-center gap-2">
|
|
491
552
|
<button type="button" disabled={page <= 1} onClick={() => onPageChange(page - 1)} className="p-0.5 rounded hover:bg-muted disabled:opacity-30">
|
|
492
553
|
<ChevronLeft className="size-3.5" />
|
|
@@ -534,10 +595,50 @@ function detectLang(text: string): string {
|
|
|
534
595
|
return "plaintext";
|
|
535
596
|
}
|
|
536
597
|
|
|
598
|
+
/** Column search dropdown — owns query/index state internally to avoid re-rendering DataGrid */
|
|
599
|
+
function ColumnSearchDropdown({ columns, onSelect, onClose }: {
|
|
600
|
+
columns: string[]; onSelect: (col: string) => void; onClose: () => void;
|
|
601
|
+
}) {
|
|
602
|
+
const [query, setQuery] = useState("");
|
|
603
|
+
const [idx, setIdx] = useState(0);
|
|
604
|
+
const filtered = useMemo(() => {
|
|
605
|
+
if (!query) return columns;
|
|
606
|
+
const lq = query.toLowerCase();
|
|
607
|
+
return columns.filter((c) => c.toLowerCase().includes(lq));
|
|
608
|
+
}, [columns, query]);
|
|
609
|
+
|
|
610
|
+
const activeRef = useRef<HTMLButtonElement>(null);
|
|
611
|
+
useEffect(() => { activeRef.current?.scrollIntoView({ block: "nearest" }); }, [idx]);
|
|
612
|
+
|
|
613
|
+
return (
|
|
614
|
+
<div className="absolute top-full right-0 mt-1 z-50 w-52 max-h-56 bg-popover border border-border rounded-md shadow-lg overflow-hidden flex flex-col">
|
|
615
|
+
<input autoFocus type="text" value={query}
|
|
616
|
+
onChange={(e) => { setQuery(e.target.value); setIdx(0); }}
|
|
617
|
+
onKeyDown={(e) => {
|
|
618
|
+
if (e.key === "Escape") onClose();
|
|
619
|
+
else if (e.key === "ArrowDown") { e.preventDefault(); setIdx((i) => Math.min(i + 1, filtered.length - 1)); }
|
|
620
|
+
else if (e.key === "ArrowUp") { e.preventDefault(); setIdx((i) => Math.max(i - 1, 0)); }
|
|
621
|
+
else if (e.key === "Enter" && filtered[idx]) onSelect(filtered[idx]);
|
|
622
|
+
}}
|
|
623
|
+
placeholder="Search columns…"
|
|
624
|
+
className="px-2 py-1.5 text-xs bg-transparent outline-none border-b border-border text-foreground placeholder:text-muted-foreground" />
|
|
625
|
+
<div className="overflow-auto flex-1">
|
|
626
|
+
{filtered.map((col, i) => (
|
|
627
|
+
<button key={col} type="button" onClick={() => onSelect(col)}
|
|
628
|
+
ref={i === idx ? activeRef : undefined}
|
|
629
|
+
className={`w-full text-left px-2 py-1 text-xs truncate ${i === idx ? "bg-primary/10 text-primary" : "text-foreground hover:bg-muted"}`}>
|
|
630
|
+
{col}
|
|
631
|
+
</button>
|
|
632
|
+
))}
|
|
633
|
+
</div>
|
|
634
|
+
</div>
|
|
635
|
+
);
|
|
636
|
+
}
|
|
637
|
+
|
|
537
638
|
/** Memoized row — only re-renders when its own props change */
|
|
538
639
|
const DataRow = memo(function DataRow({ row, rowIdx, columns, selected, onToggleSelect, pkCol,
|
|
539
640
|
editingCell, editValue, onStartEdit, onCommitEdit, onCancelEdit, onSetEditValue,
|
|
540
|
-
showDelete, confirmingDelete, onDelete, onConfirmDelete, onViewCell,
|
|
641
|
+
showDelete, confirmingDelete, onDelete, onConfirmDelete, onViewCell, onViewRow,
|
|
541
642
|
pinned, onTogglePin, pinnedCols, pinnedColOffsets, stickyTop, trRef,
|
|
542
643
|
}: {
|
|
543
644
|
row: Record<string, unknown>; rowIdx: number; columns: string[];
|
|
@@ -550,6 +651,7 @@ const DataRow = memo(function DataRow({ row, rowIdx, columns, selected, onToggle
|
|
|
550
651
|
showDelete: boolean; confirmingDelete: boolean;
|
|
551
652
|
onDelete: (i: number) => void; onConfirmDelete: (i: number | null) => void;
|
|
552
653
|
onViewCell: (cell: { col: string; value: string }) => void;
|
|
654
|
+
onViewRow: (row: Record<string, unknown>) => void;
|
|
553
655
|
pinned: boolean; onTogglePin: (i: number) => void;
|
|
554
656
|
pinnedCols: Set<string>; pinnedColOffsets: Map<string, number>;
|
|
555
657
|
stickyTop?: number;
|
|
@@ -561,10 +663,14 @@ const DataRow = memo(function DataRow({ row, rowIdx, columns, selected, onToggle
|
|
|
561
663
|
<tr ref={trRef} className={`group ${pinned ? "" : "hover:bg-muted/30"}`}
|
|
562
664
|
style={pinned ? { position: "sticky", top: stickyTop, zIndex: 15 } : undefined}>
|
|
563
665
|
{pkCol && (
|
|
564
|
-
<td className={`px-
|
|
666
|
+
<td className={`px-2 py-1 border-b border-border/50 ${cellBg}`}
|
|
565
667
|
style={{ position: "sticky", left: 0, zIndex: 12 }}>
|
|
566
668
|
<span className="flex items-center gap-0.5">
|
|
567
669
|
<input type="checkbox" checked={selected} onChange={() => onToggleSelect(rowIdx)} className="size-3 accent-primary" />
|
|
670
|
+
<button type="button" title="View row as JSON" onClick={() => onViewRow(row)}
|
|
671
|
+
className="p-0.5 rounded transition-colors text-muted-foreground/30 md:opacity-0 md:group-hover:opacity-100 hover:text-foreground">
|
|
672
|
+
<Eye className="size-2.5" />
|
|
673
|
+
</button>
|
|
568
674
|
<button type="button" title={pinned ? "Unpin row" : "Pin row"} onClick={() => onTogglePin(rowIdx)}
|
|
569
675
|
className={`p-0.5 rounded transition-colors ${pinned ? "text-primary" : "text-muted-foreground/30 md:opacity-0 md:group-hover:opacity-100 hover:text-foreground"}`}>
|
|
570
676
|
{pinned ? <PinOff className="size-2.5" /> : <Pin className="size-2.5" />}
|
|
@@ -185,6 +185,13 @@ export function useChat(sessionId: string | null, providerId = "claude", project
|
|
|
185
185
|
break;
|
|
186
186
|
}
|
|
187
187
|
|
|
188
|
+
case "status_update": {
|
|
189
|
+
// Surface status as a transient event in the stream
|
|
190
|
+
streamingEventsRef.current.push(ev as ChatEvent);
|
|
191
|
+
syncMessages();
|
|
192
|
+
break;
|
|
193
|
+
}
|
|
194
|
+
|
|
188
195
|
case "text": {
|
|
189
196
|
const pid = ev.parentToolUseId as string | undefined;
|
|
190
197
|
if (pid && routeToParent(ev as ChatEvent, pid)) {
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{o as e}from"./chunk-CFjPhJqf.js";import{t}from"./react-nm2Ru1Pt.js";import{t as n}from"./createLucideIcon-PuMiQgHl.js";import{n as r,t as i}from"./x-D2_KzIET.js";import{t as a}from"./chevron-right-4zq1jPv6.js";import{t as o}from"./jsx-runtime-kMwlnEGE.js";import{t as s}from"./api-client-BfBM3I7n.js";import{Ct as c,Et as l,K as u,Mt as d,Nt as f,Q as p,Tt as m,it as h,mt as g,ot as _,pt as v,rt as y,st as b,tt as x}from"./index-DHr-SBBY.js";import"./use-monaco-theme-DDZwQjEv.js";import{t as S}from"./sql-query-editor-CPBBvi1U.js";import{n as C}from"./csv-parser-CNNw2RVA.js";var w=n(`funnel`,[[`path`,{d:`M10 20a1 1 0 0 0 .553.895l2 1A1 1 0 0 0 14 21v-7a2 2 0 0 1 .517-1.341L21.74 4.67A1 1 0 0 0 21 3H3a1 1 0 0 0-.742 1.67l7.225 7.989A2 2 0 0 1 10 14z`,key:`sc7q7i`}]]),T=e(t(),1);function E(e,t,n,r){return`ppm-db-${e}-${n}.${t}-p${r}`}function D(e,t,n,r){try{let i=sessionStorage.getItem(E(e,t,n,r));return i?JSON.parse(i):null}catch{return null}}function ee(e,t,n,r,i,a){try{sessionStorage.setItem(E(e,t,n,r),JSON.stringify({data:i,cols:a}))}catch{}}function te(e){let t=`/api/db/connections/${e}`,[n,r]=(0,T.useState)(null),[i,a]=(0,T.useState)(`public`),[o,c]=(0,T.useState)(null),[l,u]=(0,T.useState)([]),[d,f]=(0,T.useState)(!1),[p,m]=(0,T.useState)(null),[h,g]=(0,T.useState)(1),[_,v]=(0,T.useState)(null),[y,b]=(0,T.useState)(null),[x,S]=(0,T.useState)(!1),[C,w]=(0,T.useState)(null),[E,te]=(0,T.useState)(`ASC`),O=(0,T.useCallback)(async(r,a,o,l,d)=>{let p=r??n,g=a??i;if(!p)return;f(!0);let _=l===void 0?C:l,v=d??E;try{let n=_?`&orderBy=${encodeURIComponent(_)}&orderDir=${v}`:``,[r,i]=await Promise.all([s.get(`${t}/data?table=${encodeURIComponent(p)}&schema=${g}&page=${o??h}&limit=100${n}`),s.get(`${t}/schema?table=${encodeURIComponent(p)}&schema=${g}`)]);c(r),u(i),ee(e,p,g,o??h,r,i)}catch(e){m(e.message)}finally{f(!1)}},[t,e,n,i,h,C,E]),k=(0,T.useCallback)((t,n=`public`)=>{r(t),a(n),g(1),v(null);let i=D(e,t,n,1);i?(c(i.data),u(i.cols),f(!1),O(t,n,1)):O(t,n,1)},[e,O]),A=(0,T.useCallback)(e=>{g(e),O(void 0,void 0,e)},[O]),j=(0,T.useCallback)(async e=>{S(!0),b(null);try{let r=await s.post(`${t}/query`,{sql:e});v(r),r.changeType===`modify`&&O(n??void 0,i)}catch(e){b(e.message)}finally{S(!1)}},[t,n,i,O]),M=(0,T.useCallback)(async(e,r,a,o)=>{if(!n)return;let c=n,l=i;try{await s.put(`${t}/cell`,{table:c,schema:l,pkColumn:e,pkValue:r,column:a,value:o}),O(c,l)}catch(e){m(e.message)}},[t,n,i,O]),N=(0,T.useCallback)(async(e,r)=>{if(!n)return;let a=n,o=i;try{await s.del(`${t}/row`,{table:a,schema:o,pkColumn:e,pkValue:r}),O(a,o)}catch(e){m(e.message)}},[t,n,i,O]);return{selectedTable:n,selectedSchema:i,selectTable:k,tableData:o,schema:l,loading:d,error:p,page:h,setPage:A,orderBy:C,orderDir:E,toggleSort:(0,T.useCallback)(e=>{let t,n=`ASC`;C===e?E===`ASC`?(t=e,n=`DESC`):(t=null,n=`ASC`):(t=e,n=`ASC`),w(t),te(n),g(1),O(void 0,void 0,1,t,n)},[C,E,O]),queryResult:_,queryError:y,queryLoading:x,executeQuery:j,updateCell:M,deleteRow:N,bulkDelete:(0,T.useCallback)(async(e,r)=>{if(!n)return;let a=n,o=i;try{await s.post(`${t}/rows/delete`,{table:a,schema:o,pkColumn:e,pkValues:r}),O(a,o)}catch(e){m(e.message)}},[t,n,i,O]),insertRow:(0,T.useCallback)(async e=>{if(!n)return;let r=n,a=i;try{await s.post(`${t}/row`,{table:r,schema:a,values:e}),O(r,a)}catch(e){throw m(e.message),e}},[t,n,i,O]),refreshData:O,queryAsTable:(0,T.useCallback)(async e=>{f(!0);try{let n=await s.post(`${t}/query`,{sql:e});n.changeType===`select`&&c({columns:n.columns,rows:n.rows,total:n.rows.length,page:1,limit:n.rows.length})}catch(e){m(e.message)}finally{f(!1)}},[t])}}var O=o();function k(e,t,n){let r=new Blob([t],{type:n}),i=URL.createObjectURL(r),a=document.createElement(`a`);a.href=i,a.download=e,a.click(),URL.revokeObjectURL(i)}function A({columns:e,rows:t,filename:n=`export`,exportAllUrl:r}){let[i,a]=(0,T.useState)(!1),[o,s]=(0,T.useState)(!1),c=(0,T.useRef)(null);(0,T.useEffect)(()=>{if(!i)return;let e=e=>{c.current&&!c.current.contains(e.target)&&a(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[i]);let l=()=>{let r=C(e,t.map(t=>e.map(e=>String(t[e]??``))));k(`${n}.csv`,r,`text/csv`),a(!1)},u=()=>{let e=JSON.stringify(t,null,2);k(`${n}.json`,e,`application/json`),a(!1)},d=async e=>{if(r){s(!0);try{let t=await(await fetch(`${r}&format=${e}&limit=10000`)).text(),i=e===`csv`?`text/csv`:`application/json`;k(`${n}-all.${e}`,t,i)}catch{}s(!1),a(!1)}};return e.length===0||t.length===0?null:(0,O.jsxs)(`div`,{className:`relative`,ref:c,children:[(0,O.jsx)(`button`,{type:`button`,onClick:()=>a(e=>!e),className:`p-1 rounded text-muted-foreground hover:text-foreground transition-colors`,title:`Export`,children:(0,O.jsx)(m,{className:`size-3.5`})}),i&&(0,O.jsxs)(`div`,{className:`absolute right-0 top-full mt-1 z-50 bg-popover border border-border rounded-md shadow-md py-1 min-w-[160px] text-xs`,children:[(0,O.jsx)(`button`,{onClick:l,className:`w-full text-left px-3 py-1.5 hover:bg-muted transition-colors`,children:`Export Page (CSV)`}),(0,O.jsx)(`button`,{onClick:u,className:`w-full text-left px-3 py-1.5 hover:bg-muted transition-colors`,children:`Export Page (JSON)`}),r&&(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(`div`,{className:`border-t border-border my-1`}),(0,O.jsx)(`button`,{onClick:()=>d(`csv`),disabled:o,className:`w-full text-left px-3 py-1.5 hover:bg-muted transition-colors disabled:opacity-50`,children:o?`Exporting…`:`Export All (CSV)`}),(0,O.jsx)(`button`,{onClick:()=>d(`json`),disabled:o,className:`w-full text-left px-3 py-1.5 hover:bg-muted transition-colors disabled:opacity-50`,children:o?`Exporting…`:`Export All (JSON)`})]})]})]})}function j({tableData:e,schema:t,loading:n,page:o,onPageChange:s,onCellUpdate:c,onRowDelete:l,orderBy:m,orderDir:g,onToggleSort:y,onBulkDelete:S,onInsertRow:C,connectionId:E,selectedTable:D,selectedSchema:ee,connectionName:te,columnFilters:k={},onColumnFilter:j}){let[M,N]=(0,T.useState)(null),[P,F]=(0,T.useState)(``),[I,L]=(0,T.useState)(null),[R,ie]=(0,T.useState)(``),[z,B]=(0,T.useState)(new Set),[ae,oe]=(0,T.useState)(!1),[V,H]=(0,T.useState)({}),[se,U]=(0,T.useState)(null),[ce,W]=(0,T.useState)(!1),{openTab:le}=u(),ue=(0,T.useCallback)(e=>{le({type:`editor`,title:e.col,projectId:null,closable:!0,metadata:{inlineContent:e.value,inlineLanguage:ne(e.value)}})},[le]),[G,de]=(0,T.useState)(new Set),[K,fe]=(0,T.useState)(new Set),[pe,me]=(0,T.useState)(null),q=(0,T.useMemo)(()=>t.find(e=>e.pk)?.name||(t.find(e=>e.name.toLowerCase()===`id`)?.name??null),[t]),he=(0,T.useRef)(M);he.current=M;let J=(0,T.useRef)(P);J.current=P;let ge=(0,T.useRef)(z);ge.current=z;let _e=(0,T.useRef)(I);_e.current=I;let ve=(0,T.useCallback)((e,t,n)=>{N({rowIdx:e,col:t}),F(n==null?``:typeof n==`object`?JSON.stringify(n):String(n))},[]),ye=(0,T.useCallback)(()=>{let t=he.current;if(!t||!e||!q)return;let n=e.rows[t.rowIdx];if(!n)return;let r=n[t.col];String(r??``)!==J.current&&c(q,n[q],t.col,J.current===``?null:J.current),N(null)},[e,q,c]),be=(0,T.useCallback)(()=>N(null),[]),xe=(0,T.useCallback)(t=>{if(!e||!q||!l)return;let n=e.rows[t];n&&(l(q,n[q]),L(null))},[e,q,l]),Se=(0,T.useCallback)(e=>{de(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),Ce=(0,T.useCallback)(e=>{fe(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),we=(0,T.useCallback)((e,t)=>{let n={...k};t?n[e]=t:delete n[e],j?.(n)},[k,j]),Te=(0,T.useCallback)(e=>{B(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),Ee=(0,T.useCallback)(()=>{e&&B(t=>t.size===e.rows.length?new Set:new Set(e.rows.map((e,t)=>t)))},[e]),De=(0,T.useCallback)(()=>{!e||!q||!S||(S(q,Array.from(z).map(t=>e.rows[t]?.[q]).filter(e=>e!=null)),B(new Set),W(!1))},[e,q,S,z]),Oe=(0,T.useCallback)(async()=>{if(C){U(null);try{let e={};for(let[t,n]of Object.entries(V))n!==``&&(e[t]=n);await C(e),oe(!1),H({})}catch(e){U(e.message)}}},[C,V]),Y=(0,T.useMemo)(()=>{if(!e||!R)return e?.rows??[];let t=R.toLowerCase();return e.rows.filter(n=>e.columns.some(e=>String(n[e]??``).toLowerCase().includes(t)))},[e,R]),ke=(0,T.useRef)(null);(0,T.useEffect)(()=>{let t=ke.current;if(!t)return;let n=t=>{if(!(t.metaKey||t.ctrlKey)||!e)return;let n=t.target?.tagName;if(!(n===`INPUT`||n===`TEXTAREA`)&&(t.key===`a`&&(t.preventDefault(),B(new Set(e.rows.map((e,t)=>t)))),t.key===`c`&&z.size>0)){t.preventDefault();let n=e.columns,r=n.join(` `),i=Array.from(z).sort((e,t)=>e-t).map(t=>n.map(n=>{let r=e.rows[t]?.[n];return r==null?``:typeof r==`object`?JSON.stringify(r):String(r)}).join(` `));navigator.clipboard.writeText([r,...i].join(`
|
|
2
|
-
`))}};return t.addEventListener(`keydown`,n),()=>t.removeEventListener(`keydown`,n)},[e,z]);let X=(0,T.useMemo)(()=>{if(!e)return[];let t=e.columns.filter(e=>G.has(e)),n=e.columns.filter(e=>!G.has(e));return[...t,...n]},[e?.columns,G]),Ae=(0,T.useRef)(null),[Z,je]=(0,T.useState)(0),[Q,Me]=(0,T.useState)(new Map);(0,T.useEffect)(()=>{let e=Ae.current;if(!e)return;let t=()=>{je(e.offsetHeight);let t=new Map;e.querySelectorAll(`th[data-col]`).forEach(e=>{t.set(e.dataset.col,e.offsetWidth)});let n=e.querySelector(`th[data-col='_cb']`);n&&t.set(`_cb`,n.offsetWidth),Me(t)};t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[e?.columns,G]);let Ne=(0,T.useMemo)(()=>{let e=new Map,t=Q.get(`_cb`)??(q?40:0);for(let n of X){if(!G.has(n))break;e.set(n,t),t+=Q.get(n)??100}return e},[X,G,q,Q]),$=(0,T.useMemo)(()=>Array.from(K).sort((e,t)=>e-t).map(e=>({idx:e,row:Y[e]})).filter(e=>e.row),[K,Y]),Pe=(0,T.useRef)(new Map),[Fe,Ie]=(0,T.useState)(new Map),Le=(0,T.useCallback)((e,t)=>{t?Pe.current.set(e,t):Pe.current.delete(e)},[]);(0,T.useEffect)(()=>{if($.length===0){Fe.size>0&&Ie(new Map);return}let e=requestAnimationFrame(()=>{let e=new Map;for(let{idx:t}of $){let n=Pe.current.get(t);n&&e.set(t,n.offsetHeight)}Ie(e)});return()=>cancelAnimationFrame(e)},[$,e]);let Re=(0,T.useMemo)(()=>{let e=new Map,t=Z;for(let{idx:n}of $)e.set(n,t),t+=Fe.get(n)??28;return e},[Z,$,Fe]);if(!e)return(0,O.jsx)(`div`,{className:`flex items-center justify-center h-full text-xs text-muted-foreground`,children:n?(0,O.jsx)(v,{className:`size-4 animate-spin`}):`Select a table`});let ze=Math.ceil(e.total/e.limit)||1,Be=z.size>0,Ve=z.size===e.rows.length&&e.rows.length>0;return(0,O.jsxs)(`div`,{ref:ke,tabIndex:0,className:`flex flex-col h-full overflow-hidden outline-none`,children:[(0,O.jsxs)(`div`,{className:`flex items-center gap-2 px-2 py-1 border-b border-border bg-background shrink-0`,children:[(0,O.jsxs)(`div`,{className:`flex items-center gap-1 flex-1`,children:[(0,O.jsx)(x,{className:`size-3 text-muted-foreground`}),(0,O.jsx)(`input`,{type:`text`,value:R,onChange:e=>ie(e.target.value),placeholder:`Search current page…`,className:`flex-1 text-xs bg-transparent outline-none text-foreground placeholder:text-muted-foreground`}),R&&(0,O.jsx)(`button`,{type:`button`,onClick:()=>ie(``),className:`text-muted-foreground hover:text-foreground`,children:(0,O.jsx)(i,{className:`size-3`})})]}),Be&&(0,O.jsxs)(`div`,{className:`flex items-center gap-1.5 text-xs`,children:[(0,O.jsxs)(`span`,{className:`text-muted-foreground`,children:[z.size,` selected`]}),S&&q&&(ce?(0,O.jsxs)(`span`,{className:`flex items-center gap-1`,children:[(0,O.jsxs)(`button`,{type:`button`,onClick:De,className:`text-destructive text-[10px] font-medium hover:underline`,children:[`Delete `,z.size,`?`]}),(0,O.jsx)(`button`,{type:`button`,onClick:()=>W(!1),className:`text-muted-foreground text-[10px] hover:underline`,children:`Cancel`})]}):(0,O.jsx)(`button`,{type:`button`,onClick:()=>W(!0),className:`p-0.5 text-muted-foreground hover:text-destructive`,children:(0,O.jsx)(p,{className:`size-3`})})),(0,O.jsx)(A,{columns:e.columns,rows:Array.from(z).map(t=>e.rows[t]).filter(Boolean),filename:`${te??`db`}-selected`})]}),C&&(0,O.jsx)(`button`,{type:`button`,onClick:()=>{oe(!0),H({}),U(null)},className:`p-0.5 rounded text-muted-foreground hover:text-primary transition-colors`,title:`Insert row`,children:(0,O.jsx)(h,{className:`size-3.5`})})]}),ae&&(0,O.jsxs)(`div`,{className:`px-2 py-1.5 border-b border-border bg-muted/30 text-xs space-y-1`,children:[(0,O.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:t.filter(e=>!e.pk).map(e=>(0,O.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,O.jsx)(`label`,{className:`text-muted-foreground text-[10px] w-16 truncate`,title:e.name,children:e.name}),(0,O.jsx)(`input`,{value:V[e.name]??``,onChange:t=>H(n=>({...n,[e.name]:t.target.value})),placeholder:e.defaultValue??(e.nullable?`NULL`:``),className:`h-5 w-24 text-[11px] px-1 rounded border border-border bg-background outline-none focus:border-primary`})]},e.name))}),(0,O.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,O.jsx)(`button`,{type:`button`,onClick:Oe,className:`text-[10px] px-2 py-0.5 rounded bg-primary text-primary-foreground hover:bg-primary/90`,children:`Save`}),(0,O.jsx)(`button`,{type:`button`,onClick:()=>oe(!1),className:`text-[10px] text-muted-foreground hover:underline`,children:`Cancel`}),se&&(0,O.jsx)(`span`,{className:`text-[10px] text-destructive`,children:se})]})]}),(0,O.jsxs)(`div`,{className:`flex-1 overflow-auto relative`,children:[n&&(0,O.jsx)(`div`,{className:`absolute inset-0 z-30 flex items-center justify-center bg-background/60`,children:(0,O.jsx)(v,{className:`size-5 animate-spin text-primary`})}),(0,O.jsxs)(`table`,{className:`w-full text-xs`,style:{borderCollapse:`separate`,borderSpacing:0},children:[(0,O.jsx)(`thead`,{ref:Ae,className:`sticky top-0 z-20 bg-muted`,children:(0,O.jsxs)(`tr`,{children:[q&&(0,O.jsx)(`th`,{"data-col":`_cb`,className:`px-2 py-1.5 text-left font-medium text-muted-foreground border-b border-border w-10 bg-muted`,style:{position:`sticky`,left:0,zIndex:30},children:(0,O.jsx)(`input`,{type:`checkbox`,checked:Ve,onChange:Ee,className:`size-3 accent-primary`})}),X.map(e=>{let n=t.find(t=>t.name===e)?.pk,a=m===e,o=G.has(e),s=!!k[e],c=pe===e,l=Ne.get(e);return(0,O.jsxs)(`th`,{"data-col":e,className:`group/th px-2 py-1.5 text-left font-medium text-muted-foreground border-b border-border whitespace-nowrap bg-muted ${o?`border-r border-r-primary/20`:``}`,style:l==null?void 0:{position:`sticky`,left:l,zIndex:25},children:[(0,O.jsxs)(`div`,{className:`flex items-center gap-0.5`,children:[(0,O.jsxs)(`button`,{type:`button`,onClick:()=>y(e),className:`flex items-center gap-0.5 ${n?`font-bold`:``} hover:text-foreground transition-colors`,children:[e,a&&g===`ASC`&&(0,O.jsx)(d,{className:`size-3`}),a&&g===`DESC`&&(0,O.jsx)(r,{className:`size-3`})]}),j&&(0,O.jsx)(`button`,{type:`button`,title:`Filter column`,onClick:()=>me(c?null:e),className:`p-0.5 rounded transition-colors ${s||c?`text-primary`:`text-muted-foreground/40 md:opacity-0 md:group-hover/th:opacity-100 hover:text-foreground`}`,children:(0,O.jsx)(w,{className:`size-2.5`})}),(0,O.jsx)(`button`,{type:`button`,title:o?`Unpin column`:`Pin column`,onClick:()=>Se(e),className:`p-0.5 rounded transition-colors ${o?`text-primary`:`text-muted-foreground/40 md:opacity-0 md:group-hover/th:opacity-100 hover:text-foreground`}`,children:o?(0,O.jsx)(b,{className:`size-2.5`}):(0,O.jsx)(_,{className:`size-2.5`})})]}),c&&(0,O.jsxs)(`div`,{className:`mt-1 flex items-center gap-1`,children:[(0,O.jsx)(`input`,{autoFocus:!0,type:`text`,value:k[e]??``,placeholder:`ILIKE filter…`,onChange:t=>we(e,t.target.value),onKeyDown:e=>{e.key===`Escape`&&me(null)},className:`w-full h-5 text-[10px] px-1 rounded border border-border bg-background outline-none focus:border-primary`}),s&&(0,O.jsx)(`button`,{type:`button`,onClick:()=>we(e,``),className:`text-muted-foreground hover:text-foreground`,children:(0,O.jsx)(i,{className:`size-2.5`})})]})]},e)}),l&&q&&(0,O.jsx)(`th`,{className:`px-2 py-1.5 border-b border-border w-14 bg-muted`})]})}),(0,O.jsxs)(`tbody`,{children:[$.map(({idx:e,row:t})=>(0,O.jsx)(re,{row:t,rowIdx:e,columns:X,selected:z.has(e),onToggleSelect:Te,pkCol:q,editingCell:M,editValue:P,onStartEdit:ve,onCommitEdit:ye,onCancelEdit:be,onSetEditValue:F,showDelete:!!l,confirmingDelete:I===e,onDelete:xe,onConfirmDelete:L,onViewCell:ue,pinned:!0,onTogglePin:Ce,pinnedCols:G,pinnedColOffsets:Ne,stickyTop:Re.get(e)??Z,trRef:t=>Le(e,t)},`pin-${e}`)),Y.map((e,t)=>K.has(t)?null:(0,O.jsx)(re,{row:e,rowIdx:t,columns:X,selected:z.has(t),onToggleSelect:Te,pkCol:q,editingCell:M,editValue:P,onStartEdit:ve,onCommitEdit:ye,onCancelEdit:be,onSetEditValue:F,showDelete:!!l,confirmingDelete:I===t,onDelete:xe,onConfirmDelete:L,onViewCell:ue,pinned:!1,onTogglePin:Ce,pinnedCols:G,pinnedColOffsets:Ne},t)),Y.length===0&&(0,O.jsx)(`tr`,{children:(0,O.jsx)(`td`,{colSpan:X.length+2,className:`px-2 py-8 text-center text-muted-foreground`,children:`No data`})})]})]})]}),(0,O.jsxs)(`div`,{className:`flex items-center justify-between px-3 py-1.5 border-t border-border bg-background shrink-0 text-xs text-muted-foreground`,children:[(0,O.jsxs)(`span`,{children:[e.total.toLocaleString(),` rows`]}),(0,O.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,O.jsx)(`button`,{type:`button`,disabled:o<=1,onClick:()=>s(o-1),className:`p-0.5 rounded hover:bg-muted disabled:opacity-30`,children:(0,O.jsx)(f,{className:`size-3.5`})}),(0,O.jsxs)(`span`,{children:[o,` / `,ze]}),(0,O.jsx)(`button`,{type:`button`,disabled:o>=ze,onClick:()=>s(o+1),className:`p-0.5 rounded hover:bg-muted disabled:opacity-30`,children:(0,O.jsx)(a,{className:`size-3.5`})})]})]})]})}function M(e){return e==null?`NULL`:typeof e==`object`?JSON.stringify(e):String(e)}var N=200;function P(e){if(e==null)return!1;if(typeof e==`object`)return!0;let t=String(e);if(t.length>=N)return!0;let n=t.trimStart();return!!((n[0]===`{`||n[0]===`[`)&&(n.endsWith(`}`)||n.endsWith(`]`))||n.startsWith(`<?xml`)||n.startsWith(`<`)&&n.endsWith(`>`))}function ne(e){let t=e.trimStart();if(t[0]===`{`||t[0]===`[`)try{return JSON.parse(t),`json`}catch{}return t.startsWith(`<?xml`)||t.startsWith(`<`)&&/<\/\w+>/.test(t)?`xml`:t.startsWith(`---`)||/^\w+:\s/m.test(t)?`yaml`:`plaintext`}var re=(0,T.memo)(function({row:e,rowIdx:t,columns:n,selected:r,onToggleSelect:i,pkCol:a,editingCell:o,editValue:s,onStartEdit:l,onCommitEdit:u,onCancelEdit:d,onSetEditValue:f,showDelete:m,confirmingDelete:h,onDelete:g,onConfirmDelete:v,onViewCell:y,pinned:x,onTogglePin:S,pinnedCols:C,pinnedColOffsets:w,stickyTop:T,trRef:E}){let D=x?`bg-muted`:r?`bg-primary/5`:`bg-background`;return(0,O.jsxs)(`tr`,{ref:E,className:`group ${x?``:`hover:bg-muted/30`}`,style:x?{position:`sticky`,top:T,zIndex:15}:void 0,children:[a&&(0,O.jsx)(`td`,{className:`px-1 py-1 border-b border-border/50 ${D}`,style:{position:`sticky`,left:0,zIndex:12},children:(0,O.jsxs)(`span`,{className:`flex items-center gap-0.5`,children:[(0,O.jsx)(`input`,{type:`checkbox`,checked:r,onChange:()=>i(t),className:`size-3 accent-primary`}),(0,O.jsx)(`button`,{type:`button`,title:x?`Unpin row`:`Pin row`,onClick:()=>S(t),className:`p-0.5 rounded transition-colors ${x?`text-primary`:`text-muted-foreground/30 md:opacity-0 md:group-hover:opacity-100 hover:text-foreground`}`,children:x?(0,O.jsx)(b,{className:`size-2.5`}):(0,O.jsx)(_,{className:`size-2.5`})})]})}),n.map(n=>{let r=o?.rowIdx===t&&o?.col===n,i=e[n],p=!r&&P(i),m=C.has(n),h=w.get(n);return(0,O.jsx)(`td`,{className:`px-2 py-1 max-w-[300px] border-b border-border/50 ${m?`border-r border-r-primary/20`:``} ${m||x?D:``}`,style:h==null?void 0:{position:`sticky`,left:h,zIndex:10},children:r?(0,O.jsx)(`input`,{autoFocus:!0,className:`w-full bg-transparent border border-primary/50 rounded px-1 py-0 text-xs outline-none`,value:s,onChange:e=>f(e.target.value),onBlur:u,onKeyDown:e=>{e.key===`Enter`&&u(),e.key===`Escape`&&d()}}):(0,O.jsxs)(`span`,{className:`flex items-center gap-0.5`,children:[(0,O.jsx)(`span`,{className:`cursor-pointer truncate flex-1 ${i==null?`text-muted-foreground/40 italic`:``}`,onDoubleClick:()=>a&&l(t,n,i),title:M(i),children:M(i)}),p&&(0,O.jsx)(`button`,{type:`button`,title:`View full content`,onClick:()=>y({col:n,value:M(i)}),className:`shrink-0 p-0.5 rounded text-muted-foreground/50 hover:text-foreground transition-colors`,children:(0,O.jsx)(c,{className:`size-3`})})]})},n)}),m&&a&&(0,O.jsx)(`td`,{className:`px-2 py-1 border-b border-border/50 ${x?D:``}`,children:h?(0,O.jsxs)(`span`,{className:`flex items-center gap-1 whitespace-nowrap`,children:[(0,O.jsx)(`button`,{type:`button`,onClick:()=>g(t),className:`text-destructive text-[10px] font-medium hover:underline`,children:`Confirm`}),(0,O.jsx)(`button`,{type:`button`,onClick:()=>v(null),className:`text-muted-foreground text-[10px] hover:underline`,children:`Cancel`})]}):(0,O.jsx)(`button`,{type:`button`,onClick:()=>v(t),className:`p-0.5 rounded md:opacity-0 md:group-hover:opacity-100 hover:bg-destructive/10 hover:text-destructive transition-opacity`,title:`Delete row`,children:(0,O.jsx)(p,{className:`size-3`})})})]})});function F(e){let t={},n=/"(\w+)"\s+ILIKE\s+'%([^']*?)%'/gi,r;for(;(r=n.exec(e))!==null;)t[r[1]]=r[2].replace(/''/g,`'`);return t}function I({metadata:e}){let t=e?.connectionId,n=e?.connectionName,r=e?.tableName,i=e?.schemaName??`public`,a=e?.initialSql,o=te(t),[c,u]=(0,T.useState)([]),[d,f]=(0,T.useState)(180),p=(0,T.useRef)(null),[m,h]=(0,T.useState)({}),_=(0,T.useMemo)(()=>{if(a&&!o.selectedTable)return a;if(o.selectedTable){let e=`SELECT * FROM "${o.selectedTable}"`,t=Object.entries(m).filter(([,e])=>e.trim()).map(([e,t])=>`"${e}" ILIKE '%${t.replace(/'/g,`''`)}%'`);t.length>0&&(e+=` WHERE ${t.join(` AND `)}`),o.orderBy&&(e+=` ORDER BY "${o.orderBy}" ${o.orderDir}`);let n=(o.page-1)*100;return e+=` LIMIT 100`,n>0&&(e+=` OFFSET ${n}`),e}return`SELECT * FROM `},[a,o.selectedTable,o.orderBy,o.orderDir,o.page,m]),v=(0,T.useCallback)(e=>{h(e)},[]),b=(0,T.useRef)(void 0);(0,T.useEffect)(()=>{if(!(!o.selectedTable||Object.keys(m).length===0))return clearTimeout(b.current),b.current=setTimeout(()=>{o.queryAsTable(_)},500),()=>clearTimeout(b.current)},[m]);let x=(0,T.useCallback)(e=>{e.preventDefault();let t=e.clientY,n=d,r=e=>{let r=e.clientY-t;f(Math.max(80,Math.min(n+r,(p.current?.clientHeight??600)-100)))},i=()=>{document.removeEventListener(`mousemove`,r),document.removeEventListener(`mouseup`,i)};document.addEventListener(`mousemove`,r),document.addEventListener(`mouseup`,i)},[d]);(0,T.useEffect)(()=>{s.get(`/api/db/connections/${t}/tables?cached=1`).then(e=>u(e.map(e=>({name:e.name,schema:e.schema})))).catch(()=>{})},[t]);let C=(0,T.useMemo)(()=>{if(c.length!==0)return{tables:c,getColumns:async(e,n)=>await s.get(`/api/db/connections/${t}/schema?table=${encodeURIComponent(e)}${n?`&schema=${encodeURIComponent(n)}`:``}`)}},[t,c]),w=(0,T.useRef)(!1);(0,T.useEffect)(()=>{w.current||(w.current=!0,a?o.executeQuery(a):r&&o.selectTable(r,i))},[r,i,a]);let[E,D]=(0,T.useState)(!!a),ee=(0,T.useCallback)(e=>{let t=e.trim();if(o.selectedTable&&RegExp(`^SELECT\\s+\\*\\s+FROM\\s+"?${o.selectedTable.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}"?\\b`,`i`).test(t)){h(F(t)),o.queryAsTable(t);return}D(!0),o.executeQuery(e)},[o.executeQuery,o.queryAsTable,o.selectedTable]),k=(0,T.useCallback)(e=>{D(!1),o.toggleSort(e)},[o.toggleSort]),M=(0,T.useCallback)(e=>{D(!1),o.setPage(e)},[o.setPage]),N=o.queryResult,P=E&&!!(N||o.queryError),ne=o.selectedTable&&!P;return(0,O.jsx)(`div`,{ref:p,className:`flex h-full w-full overflow-hidden`,children:(0,O.jsxs)(`div`,{className:`flex-1 flex flex-col overflow-hidden`,children:[(0,O.jsxs)(`div`,{className:`flex items-center gap-2 px-3 py-1.5 border-b border-border bg-background shrink-0`,children:[(0,O.jsx)(l,{className:`size-3.5 text-muted-foreground`}),(0,O.jsx)(`span`,{className:`text-xs text-muted-foreground truncate`,children:n??`Database`}),o.selectedTable&&(0,O.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[`/ `,o.selectedTable]}),(0,O.jsxs)(`div`,{className:`ml-auto flex items-center gap-1`,children:[o.tableData&&(0,O.jsx)(A,{columns:o.tableData.columns,rows:o.tableData.rows,filename:n?`${n}-${o.selectedTable??`data`}`:o.selectedTable??`data`,exportAllUrl:o.selectedTable?`/api/db/connections/${t}/export?table=${encodeURIComponent(o.selectedTable)}&schema=${o.selectedSchema}`:void 0}),(0,O.jsx)(`button`,{type:`button`,onClick:()=>o.refreshData(),title:`Reload data`,className:`p-1 rounded text-muted-foreground hover:text-foreground transition-colors`,children:(0,O.jsx)(y,{className:`size-3 ${o.loading?`animate-spin`:``}`})})]})]}),(0,O.jsx)(`div`,{className:`shrink-0 border-b border-border`,style:{height:d},children:(0,O.jsx)(S,{onExecute:ee,loading:o.queryLoading,defaultValue:_,schemaInfo:C})}),(0,O.jsx)(`div`,{onMouseDown:x,className:`shrink-0 h-1.5 cursor-row-resize bg-border/50 hover:bg-primary/30 flex items-center justify-center transition-colors`,children:(0,O.jsx)(g,{className:`size-3 text-muted-foreground/50`})}),(0,O.jsxs)(`div`,{className:`flex-1 overflow-hidden`,children:[ne&&(0,O.jsx)(j,{tableData:o.tableData,schema:o.schema,loading:o.loading,page:o.page,onPageChange:M,onCellUpdate:o.updateCell,onRowDelete:o.deleteRow,orderBy:o.orderBy,orderDir:o.orderDir,onToggleSort:k,onBulkDelete:o.bulkDelete,onInsertRow:o.insertRow,connectionId:t,selectedTable:o.selectedTable,selectedSchema:o.selectedSchema,connectionName:n,columnFilters:m,onColumnFilter:v}),P&&(0,O.jsx)(R,{result:N,error:o.queryError,loading:o.queryLoading,schema:o.schema,connectionName:n})]})]})})}var L=()=>{};function R({result:e,error:t,loading:n,schema:r,connectionName:i}){let a=(0,T.useMemo)(()=>e?.changeType===`select`&&e.rows.length>0?{columns:e.columns,rows:e.rows,total:e.rows.length,limit:e.rows.length}:null,[e]),o=(0,T.useMemo)(()=>r?.length?r:(e?.columns??[]).map(e=>({name:e,type:`text`,nullable:!0,pk:!1,defaultValue:null})),[r,e?.columns]);return(0,O.jsxs)(`div`,{className:`flex flex-col h-full overflow-hidden text-xs`,children:[t&&(0,O.jsx)(`div`,{className:`px-3 py-2 text-destructive bg-destructive/5 shrink-0`,children:t}),e?.changeType===`modify`&&(0,O.jsxs)(`div`,{className:`px-3 py-2 text-green-500 shrink-0`,children:[e.rowsAffected,` row(s) affected`,e.executionTimeMs!=null&&(0,O.jsxs)(`span`,{className:`text-muted-foreground ml-2`,children:[e.executionTimeMs,`ms`]})]}),a&&(0,O.jsxs)(`div`,{className:`flex-1 overflow-hidden`,children:[(0,O.jsx)(j,{tableData:a,schema:o,loading:!!n,page:1,onPageChange:L,onCellUpdate:L,orderBy:null,orderDir:`ASC`,onToggleSort:L,connectionName:i}),e?.executionTimeMs!=null&&(0,O.jsxs)(`div`,{className:`px-3 py-0.5 border-t border-border text-[10px] text-muted-foreground shrink-0`,children:[e.rows.length,` rows · `,e.executionTimeMs,`ms`]})]}),e?.changeType===`select`&&e.rows.length===0&&(0,O.jsxs)(`div`,{className:`px-3 py-2 text-muted-foreground shrink-0`,children:[`No results`,e.executionTimeMs!=null&&(0,O.jsxs)(`span`,{className:`ml-2 text-muted-foreground/60`,children:[e.executionTimeMs,`ms`]})]}),!e&&!t&&(0,O.jsx)(`div`,{className:`flex items-center justify-center h-full text-muted-foreground`,children:n?(0,O.jsx)(v,{className:`size-4 animate-spin`}):`Run a query to see results`})]})}export{I as DatabaseViewer};
|