diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs index b9cdbf06..c340ab6c 100644 --- a/src-tauri/src/commands.rs +++ b/src-tauri/src/commands.rs @@ -276,6 +276,52 @@ pub async fn read_file(path: String) -> Result { /// building a WebView2 window there deadlocks on Windows (tauri-apps/wry#583): /// the window never appeared, and every other window froze with it, so the /// app could not even be closed. +/// A dashboard on its own: a window with nothing but that dashboard's cards, +/// for a second screen. One window per dashboard; asking again focuses it. +/// It runs its queries on the connection the app has open, like any window. +#[tauri::command] +pub async fn open_dashboard_window(app: tauri::AppHandle, dashboard_id: String, connection_id: String, title: String) -> Result<(), String> { + let safe = |s: &str| s.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_'); + if dashboard_id.is_empty() || !safe(&dashboard_id) || !safe(&connection_id) { + return Err("That isn't a dashboard".into()); + } + let label = format!("main-dashboard-{}", dashboard_id.chars().filter(|c| c.is_ascii_alphanumeric()).take(40).collect::()); + if let Some(w) = app.webview_windows().get(label.as_str()) { + let _ = w.unminimize(); + let _ = w.set_focus(); + return Ok(()); + } + let url = format!("/?view=dashboard&dash={dashboard_id}&conn={connection_id}"); + let mut builder = tauri::WebviewWindowBuilder::new(&app, &label, tauri::WebviewUrl::App(url.into())) + .title(if title.trim().is_empty() { "Dashboard".to_string() } else { title }) + .inner_size(1440.0, 900.0) + .min_inner_size(640.0, 420.0) + .resizable(true) + .visible(false) + .background_color(tauri::window::Color(8, 8, 8, 255)) + .devtools(cfg!(debug_assertions)) + .zoom_hotkeys_enabled(false) + .on_navigation(crate::navigation_allowed); + #[cfg(target_os = "macos")] + { + builder = builder + .title_bar_style(tauri::TitleBarStyle::Overlay) + .hidden_title(true) + .traffic_light_position(crate::mac_chrome::traffic_light_position()); + } + #[cfg(not(target_os = "macos"))] + { + builder = builder.decorations(false); + } + let window = builder.build().map_err(|e| e.to_string())?; + let surface = crate::surface_for_theme(window.theme().unwrap_or(tauri::Theme::Dark)); + let _ = window.set_background_color(Some(surface)); + crate::set_webview_backdrop(&window, surface); + crate::guard_webview(&window); + crate::arm_reveal_failsafe(&window); + Ok(()) +} + #[tauri::command] pub async fn open_new_window(app: tauri::AppHandle) -> Result<(), String> { // Labels must be unique and stable-ish; the counter restarts with the app, diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 9fc1e053..9e0dc0fb 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -689,6 +689,7 @@ pub fn run() { commands::ai_fetch_page, commands::read_file, commands::open_new_window, + commands::open_dashboard_window, launch::take_open_request, commands::reveal_window, commands::restart_app, diff --git a/src/App.svelte b/src/App.svelte index 0d4a5395..b2fe8fc0 100644 --- a/src/App.svelte +++ b/src/App.svelte @@ -3,6 +3,11 @@ import { onMount } from 'svelte' import { Toaster } from '$lib/components/ui/sonner/index.js' import StudioShell from './lib/components/StudioShell.svelte' + import DashboardWindow from './lib/components/DashboardWindow.svelte' + + // A window opened for one dashboard (open_dashboard_window) shows only that. + const params = typeof location !== 'undefined' ? new URLSearchParams(location.search) : new URLSearchParams() + const dashboardView = params.get('view') === 'dashboard' ? { dash: params.get('dash') ?? '', conn: params.get('conn') ?? '' } : null import LicenseGate from './lib/components/LicenseGate.svelte' import AppLockGate from './lib/components/AppLockGate.svelte' import AppErrorBoundary from './lib/components/AppErrorBoundary.svelte' @@ -96,7 +101,11 @@ behind it runs - not the license check, not a reconnect. --> - + {#if dashboardView} + + {:else} + + {/if} diff --git a/src/lib/components/DashboardPage.svelte b/src/lib/components/DashboardPage.svelte index d30badee..605d657c 100644 --- a/src/lib/components/DashboardPage.svelte +++ b/src/lib/components/DashboardPage.svelte @@ -17,10 +17,13 @@ setItemSpan, setItemSize, reorderItems, + addQueryToDashboard, + updateItem, } from "$lib/stores/dashboards.js"; + import { listSavedQueries, queryTitle } from "$lib/stores/query-history.js"; import { executeSql } from "$lib/api.js"; import { isWriteSql } from "$lib/sql-write.js"; - import { cardView, createQueue, agoText, formatKpi } from "$lib/dashboard-live.js"; + import { cardView, createQueue, agoText, formatKpi, queryView, QUERY_VIEWS } from "$lib/dashboard-live.js"; import RefreshCw from "@lucide/svelte/icons/refresh-cw"; import SquareTerminal from "@lucide/svelte/icons/square-terminal"; import SearchIcon from "@lucide/svelte/icons/search"; @@ -42,6 +45,9 @@ import MoreHorizontal from "@lucide/svelte/icons/more-horizontal"; import * as DropdownMenu from "$lib/components/ui/dropdown-menu/index.js"; import SelectMenu from "./SelectMenu.svelte"; + import FileCode from "@lucide/svelte/icons/file-code"; + import AppWindow from "@lucide/svelte/icons/app-window"; + import { toast } from "$lib/components/ui/sonner/toast.svelte.js"; let { /** @type {import('$lib/stores/connections.js').SavedConnection | null} */ @@ -71,29 +77,44 @@ /** @param {import('$lib/stores/saved-charts.js').SavedChart | null} chart */ const canRun = (chart) => !!chart?.sql?.trim() && !isWriteSql(chart.sql); - /** @param {string} chartId */ - async function refreshChart(chartId) { - const chart = getChart(chartId); - if (!canRun(chart) || live[chartId]?.loading) return; - live[chartId] = { ...live[chartId], loading: true, error: "" }; + /** @typedef {import('$lib/stores/dashboards.js').DashItem} DashItem */ + /** Where a card's numbers live: its saved query's own key, or the chart's id (shared when a chart is on twice). @param {DashItem} item */ + const keyOf = (item) => (item.query ? `q:${item.id}` : item.chartId ?? `x:${item.id}`); + /** The read-only SQL a card runs, or null when it only has a snapshot. @param {DashItem} item */ + function sqlOf(item) { + const sql = item.query?.sql ?? getChart(item.chartId)?.sql ?? ""; + return sql.trim() && !isWriteSql(sql) ? sql : null; + } + + /** @param {DashItem} item */ + async function refreshItem(item) { + const key = keyOf(item); + const sql = sqlOf(item); + if (!sql || live[key]?.loading) return; + live[key] = { ...live[key], loading: true, error: "" }; try { - const result = await runQueue(() => executeSql(/** @type {string} */ (chart?.sql))); - live[chartId] = { result, at: Date.now(), loading: false, error: "" }; + const result = await runQueue(() => executeSql(sql)); + live[key] = { result, at: Date.now(), loading: false, error: "" }; } catch (e) { - live[chartId] = { ...live[chartId], loading: false, error: String(/** @type {any} */ (e)?.message ?? e) }; + live[key] = { ...live[key], loading: false, error: String(/** @type {any} */ (e)?.message ?? e) }; } } function refreshAll() { if (!activeDash) return; - for (const id of new Set(activeDash.items.map((i) => i.chartId).filter(Boolean))) void refreshChart(/** @type {string} */ (id)); + const seen = new Set(); + for (const item of activeDash.items) { + if (seen.has(keyOf(item))) continue; + seen.add(keyOf(item)); + void refreshItem(item); + } } // First run for cards that have none yet, whenever the dashboard is on screen. $effect(() => { if (!active || !activeDash) return; - const ids = activeDash.items.map((i) => i.chartId).filter(Boolean); - untrack(() => { for (const id of ids) if (!live[/** @type {string} */ (id)]) void refreshChart(/** @type {string} */ (id)); }); + const items = activeDash.items; + untrack(() => { for (const item of items) if (!live[keyOf(item)]) void refreshItem(item); }); }); // Auto refresh, only while the tab and the window are in front. $effect(() => { @@ -115,6 +136,69 @@ } const SIZE_H = { s: 200, m: 280, l: 400 }; + /** A card's height: resized by hand, or its s/m/l preset. @param {DashItem} item */ + const heightOf = (item) => item.h ?? SIZE_H[item.size ?? "m"]; + + /** What a saved-query card draws from its last run. @param {DashItem} item */ + function queryViewFor(item) { + const r = live[keyOf(item)]?.result; + if (!r || !item.query) return null; + try { return queryView(r, item.query.type, $isCurrentThemeDark); } catch { return null; } + } + + // ── Resize ───────────────────────────────────────────────────────────────── + // The corner handle: width snaps to whole columns, height to 20px steps. + // The card follows the pointer; the store is written once, on release. + /** @type {{ id: string, span: number, h: number } | null} */ + let resizing = $state(null); + const GRID_GAP = 12; + + /** @param {PointerEvent} e @param {DashItem} item */ + function startResize(e, item) { + if (!activeDash || !gridEl) return; + e.preventDefault(); + e.stopPropagation(); + const dash = activeDash; + const cols = dash.columns; + const colW = (gridEl.clientWidth - GRID_GAP * (cols - 1)) / cols; + const x0 = e.clientX, y0 = e.clientY; + const span0 = Math.min(item.span, cols), h0 = heightOf(item); + const w0 = span0 * colW + (span0 - 1) * GRID_GAP; + resizing = { id: item.id, span: span0, h: h0 }; + const el = /** @type {HTMLElement} */ (e.currentTarget); + el.setPointerCapture(e.pointerId); + /** @param {PointerEvent} ev */ + const move = (ev) => { + const span = Math.max(1, Math.min(cols, Math.round((w0 + ev.clientX - x0 + GRID_GAP) / (colW + GRID_GAP)))); + const h = Math.max(120, Math.min(900, Math.round((h0 + ev.clientY - y0) / 20) * 20)); + resizing = { id: item.id, span, h }; + }; + const up = () => { + el.removeEventListener("pointermove", move); + el.removeEventListener("pointerup", up); + el.removeEventListener("pointercancel", up); + if (resizing && (resizing.span !== span0 || resizing.h !== h0)) updateItem(dash.id, item.id, { span: resizing.span, h: resizing.h }); + resizing = null; + }; + el.addEventListener("pointermove", move); + el.addEventListener("pointerup", up); + el.addEventListener("pointercancel", up); + } + + /** Keyboard resize on the handle: arrows change width and height. @param {KeyboardEvent} e @param {DashItem} item */ + function resizeKey(e, item) { + if (!activeDash) return; + const span = Math.min(item.span, activeDash.columns), h = heightOf(item); + const next = + e.key === "ArrowLeft" ? { span: Math.max(1, span - 1) } + : e.key === "ArrowRight" ? { span: Math.min(activeDash.columns, span + 1) } + : e.key === "ArrowUp" ? { h: Math.max(120, h - 20) } + : e.key === "ArrowDown" ? { h: Math.min(900, h + 20) } + : null; + if (!next) return; + e.preventDefault(); + updateItem(activeDash.id, item.id, next); + } /** A chart option shrunk to a thumbnail: the marks only, no axes, labels or tooltip. @param {any} o */ function thumbOption(o) { @@ -176,12 +260,51 @@ } } + /** The dashboard on its own, in a window for a second screen. */ + async function openWindow() { + if (!activeDash || !connection?.id) return; + try { + const { invoke } = await import("@tauri-apps/api/core"); + await invoke("open_dashboard_window", { dashboardId: activeDash.id, connectionId: connection.id, title: activeDash.name }); + } catch (e) { + toast.error("Could not open the window", { description: String(e) }); + } + } + // ── Chart picker modal ───────────────────────────────────────────────────── let pickerOpen = $state(false); let pickerQuery = $state(""); let pickerGroup = $state(""); + /** @type {'charts' | 'queries'} */ + let pickerTab = $state("charts"); + /** @type {{ id: string, name: string, sql: string }[]} */ + let savedQs = $state([]); $effect(() => { if (!pickerOpen) { pickerQuery = ""; pickerGroup = ""; } }); + // Open on what there is to add: saved queries when there are no charts yet. + $effect(() => { if (pickerOpen) untrack(() => { pickerTab = $savedCharts.length ? "charts" : "queries"; }); }); + // The connection's saved queries, read fresh each time the picker opens. + $effect(() => { + if (!pickerOpen || !connection?.id) return; + const id = connection.id; + void listSavedQueries(id).then((qs) => { if (pickerOpen && connection?.id === id) savedQs = qs.filter((q) => q.sql?.trim()); }); + }); + const queryName = (/** @type {{ name?: string, sql: string }} */ q) => q.name?.trim() || queryTitle(q.sql); + const pickerQueries = $derived( + savedQs.filter((q) => { + const t = pickerQuery.trim().toLowerCase(); + return !t || queryName(q).toLowerCase().includes(t) || q.sql.toLowerCase().includes(t); + }), + ); + /** The card already showing this query. @param {string} sql */ + const queryOnDash = (sql) => activeDash?.items.find((i) => i.query?.sql.trim() === sql.trim()) ?? null; + /** @param {{ name?: string, sql: string }} q */ + function pickQuery(q) { + if (!activeDash) return; + const there = queryOnDash(q.sql); + if (there) removeChartFromDashboard(activeDash.id, there.id); + else addQueryToDashboard(activeDash.id, { sql: q.sql, name: queryName(q) }); + } const pickerGroups = $derived([...new Set($savedCharts.map((c) => c.group).filter(Boolean))]); const pickerCharts = $derived( $savedCharts.filter((c) => { @@ -265,7 +388,7 @@ const layoutKey = $derived( activeDash ? `${activeDash.id}|${activeDash.columns}|${presenting}|${activeDash.items - .map((i) => `${i.id}:${Math.min(i.span, activeDash.columns)}`) + .map((i) => `${i.id}:${Math.min(i.span, activeDash.columns)}:${i.h ?? i.size ?? ""}`) .join(",")}` : "none", ); @@ -425,7 +548,7 @@ Columns - {#each [1, 2, 3, 4] as cols (cols)} + {#each [1, 2, 3, 4, 5, 6] as cols (cols)} updateDashboard(activeDash.id, { columns: cols })}> {cols} {cols === 1 ? "column" : "columns"} {#if activeDash.columns === cols}{/if} @@ -457,12 +580,15 @@ items={REFRESH_CHOICES.map(([v, l]) => ({ value: String(v), label: v ? `Every ${l}` : "Auto off" }))} /> - + {/if} {/if} @@ -479,7 +605,7 @@

No dashboard yet

- Create a dashboard to arrange your saved charts + Saved charts and queries on one screen, refreshed live

@@ -496,14 +622,14 @@
-

Add charts to build your dashboard

+

Add saved charts or queries

@@ -512,10 +638,14 @@
{#each activeDash.items as item (item.id)} {@const chart = getChart(item.chartId)} - {@const span = effectiveSpan(item)} - {@const l = chart ? live[chart.id] : null} - {@const view = viewFor(chart)} - {@const h = SIZE_H[item.size ?? "m"] + (presenting ? 40 : 0)} + {@const rz = resizing?.id === item.id ? resizing : null} + {@const span = rz ? rz.span : effectiveSpan(item)} + {@const l = live[keyOf(item)]} + {@const view = item.query ? queryViewFor(item) : viewFor(chart)} + {@const h = (rz ? rz.h : heightOf(item)) + (presenting ? 40 : 0)} + {@const title = item.query?.name ?? chart?.name ?? "Missing chart"} + {@const runs = !!sqlOf(item)} + {@const status = l?.loading ? "loading" : l?.error ? "error" : l?.at ? "ok" : "idle"}
-
+
{#if !presenting}
{/if} - {chart?.name ?? "Missing chart"} - {#if l?.loading} - - {:else if l?.error} - - {:else if l?.at} + + + {title} + {#if l?.at && !l.error} {agoText(l.at, now)} - {:else if chart && !canRun(chart)} - snapshot + {:else if !runs && chart} + snapshot {/if} {#if !presenting}
- {#if chart && canRun(chart)} - {/if} @@ -560,11 +699,24 @@ + {#if item.query} + + Show as + + {#each QUERY_VIEWS as v (v)} + item.query && updateItem(activeDash.id, item.id, { query: { ...item.query, type: v } })}> + {v === "auto" ? "Automatic" : v[0].toUpperCase() + v.slice(1)} + {#if (item.query.type ?? "auto") === v}{/if} + + {/each} + + + {/if} Width {#each Array.from({ length: activeDash.columns }, (_, i) => i + 1) as w (w)} - setItemSpan(activeDash.id, item.id, /** @type {1|2|3} */ (w))}> + setItemSpan(activeDash.id, item.id, w)}> {w === activeDash.columns ? "Full width" : `${w} of ${activeDash.columns}`} {#if span === w}{/if} @@ -575,15 +727,15 @@ Height {#each [["s", "Small"], ["m", "Medium"], ["l", "Large"]] as [k, label] (k)} - setItemSize(activeDash.id, item.id, /** @type {'s'|'m'|'l'} */ (k))}> + { updateItem(activeDash.id, item.id, { h: undefined }); setItemSize(activeDash.id, item.id, /** @type {'s'|'m'|'l'} */ (k)); }}> {label} - {#if (item.size ?? "m") === k}{/if} + {#if !item.h && (item.size ?? "m") === k}{/if} {/each} - {#if chart?.sql && onopensql} - chart && onopensql?.(chart.sql, chart.name)}>Open query + {#if (item.query?.sql ?? chart?.sql) && onopensql} + onopensql?.(item.query?.sql ?? chart?.sql ?? "", title)}>Open query {/if} removeChartFromDashboard(activeDash.id, item.id)}>Remove from dashboard @@ -594,11 +746,41 @@
- {#if view?.kpi} + {#if l?.error} + +
+

Query failed

+

{l.error}

+ +
+ {:else if view?.kpi}
- = 280 ? "text-ui-3xl" : "text-ui-2xl")}>{formatKpi(view.kpi.value)} + = 240 ? "text-ui-3xl" : "text-ui-2xl")}>{formatKpi(view.kpi.value)} {view.kpi.label}
+ {:else if view && "table" in view && view.table} +
+ + + + {#each view.table.columns as c, ci (ci)} + + {/each} + + + + {#each view.table.rows as row, ri (ri)} + + {#each row as cell, ci (ci)} + + {/each} + + {/each} + +
{c}
{cell === null ? "NULL" : typeof cell === "object" ? JSON.stringify(cell) : String(cell)}
+
{:else if view?.option} {:else if chart?.previewOption && Object.keys(chart.previewOption).length > 0} @@ -607,13 +789,31 @@
+ {:else if l?.loading || (runs && !l)} +
+ +
{:else}
- {chart ? "No preview" : "This chart was deleted"} + {item.query ? "No rows" : chart ? "No preview" : "This chart was deleted"}
{/if}
+ + {#if !presenting} + + + {/if}
{/each} @@ -630,15 +830,65 @@ - Add a chart - - {$savedCharts.length - ? `Pick charts for ${activeDash?.name ?? "this dashboard"}. Click again to take one off.` - : "Charts you save from query results show up here."} - + Add to {activeDash?.name ?? "dashboard"} + Pick saved charts or saved queries. Pick one again to take it off. +
+ {#each [["charts", "Charts", $savedCharts.length], ["queries", "Saved queries", savedQs.length]] as [id, label, n] (id)} + + {/each} +
- {#if $savedCharts.length === 0} + {#if pickerTab === "queries"} +
+ +
+
+
    + {#each pickerQueries as q (q.id)} + {@const there = !!queryOnDash(q.sql)} + {@const writes = isWriteSql(q.sql)} +
  • + +
  • + {/each} +
+ {#if !pickerQueries.length} +

{savedQs.length ? "No saved queries match." : "Queries you save in the SQL editor show up here."}

+ {/if} +
+
+ {activeDash?.items.length ?? 0} on {activeDash?.name ?? "this dashboard"} + +
+ {:else if $savedCharts.length === 0}