Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions src/lib/components/Sidebar.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -1669,10 +1669,13 @@
[c.name, c.type, c.host, c.database, /** @type {any} */ (c).filePath].some((v) => v && String(v).toLowerCase().includes(q)),
)
})
/** This workspace's connections: pinned first, then most recently used. */
/**
* This workspace's connections: pinned first, then most recently used. The
* same rows the connection dialog lists and the workspace switcher counts,
* so a Docker container or local server you connected to is here too.
*/
const wsConnections = $derived(
inWorkspace(connections, $activeWorkspaceId, $workspaces)
.filter((c) => !(/** @type {any} */ (c).origin))
.slice()
.sort((a, b) => (Number(!!b.pinned) - Number(!!a.pinned)) || ((b.lastConnectedAt ?? 0) - (a.lastConnectedAt ?? 0))),
)
Expand Down
11 changes: 10 additions & 1 deletion src/lib/components/StudioShell.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -313,6 +313,7 @@
upsertConnection,
engineFamily,
} from '$lib/stores/connections.js'
import { workspaces, activeWorkspaceId, setActiveWorkspace, workspaceOf } from '$lib/stores/workspaces.js'
import { hasPro, FREE_CONNECTION_LIMIT } from '$lib/stores/license.js'
import { engineSupports, engineLabel, isKeyValue } from '$lib/db-capabilities.js'
import * as Dialog from '$lib/components/ui/dialog/index.js'
Expand Down Expand Up @@ -7823,7 +7824,15 @@ let rowSearch = $state('')
// Persist last-used ID and bump timestamp
if (savedId) {
setLastConnectionId(savedId)
upsertConnection({ ...conn, id: savedId, lastConnectedAt: Date.now() })
savedConnections = upsertConnection({ ...conn, id: savedId, lastConnectedAt: Date.now() })
// The workspace follows the database that is open. Connecting to one
// filed elsewhere (a provider's database saved under "Work" while on
// Personal) otherwise left the sidebar listing a workspace without it.
const row = savedConnections.find((c) => c.id === savedId)
if (row) {
const ws = workspaceOf(row, get(workspaces))
if (ws !== get(activeWorkspaceId)) setActiveWorkspace(ws)
}
}
tableFilter = ''
error = ''
Expand Down
20 changes: 15 additions & 5 deletions src/lib/components/WorkspaceSwitcher.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@
let managerOpen = $state(false)
let editing = $state(/** @type {import('$lib/stores/workspaces.js').Workspace | null} */ (null))

/** "1 connection", "40 connections". @param {number} n */
const countLabel = (n) => `${n} connection${n === 1 ? '' : 's'}`

/** @param {import('$lib/stores/workspaces.js').Workspace | null} w */
function openDialog(w) {
editing = w
Expand All @@ -41,11 +44,18 @@
<DropdownMenu.Root>
<DropdownMenu.Trigger
class={cn(
cn('group flex min-w-0 items-center rounded-md text-left', !compact && 'hover:bg-accent/60 data-[state=open]:bg-accent/60'),
compact ? 'size-[calc(28px*var(--app-scale))] justify-center rounded-md outline-none focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring' : 'h-8 gap-2 px-1.5',
'group flex min-w-0 items-center rounded-md text-left outline-none focus-visible:outline-2 focus-visible:outline-ring',
// Full size it heads a sidebar list, so it takes the list's tokens, and a
// hairline frame: the same height and radius as the rows under it, it
// otherwise read as the first connection rather than the picker that
// decides which connections are listed.
compact
? 'size-[calc(28px*var(--app-scale))] justify-center focus-visible:outline-offset-1'
: 'h-8 gap-2 border border-sidebar-border px-1.5 transition-colors duration-150 hover:bg-sidebar-accent/60 focus-visible:outline-offset-2 data-[state=open]:bg-sidebar-accent',
className,
)}
title={`Workspace: ${active?.name ?? ""}`}
title={`Workspace: ${active?.name ?? ""} · ${countLabel(count)}`}
aria-label={`Workspace: ${active?.name ?? ""}, ${countLabel(count)}. Switch workspace`}
>
<!-- The workspace's mark (its colour and initial), here and in the menu, so
the same tile means the same workspace everywhere. -->
Expand All @@ -57,7 +67,7 @@
class={compact ? 'transition-[scale,filter] duration-150 ease-out group-hover:brightness-110 group-hover:ring-2 group-hover:ring-foreground/15 group-active:scale-90 group-data-[state=open]:ring-2 group-data-[state=open]:ring-ring/50' : ''}
/>
{#if !compact}<span class="min-w-0 flex-1 truncate text-ui-sm font-medium text-foreground">{active?.name}</span>{/if}
{#if !compact}<span class="shrink-0 text-ui-2xs tabular-nums text-muted-foreground">{count}</span>{/if}
{#if !compact}<span class="shrink-0 font-mono text-ui-2xs tabular-nums text-muted-foreground" aria-hidden="true">{count}</span>{/if}
{#if !compact}<ChevronsUpDown class="size-3.5 shrink-0 text-muted-foreground/70 group-hover:text-muted-foreground" />{/if}
</DropdownMenu.Trigger>
<DropdownMenu.Content align="start" class="min-w-60">
Expand All @@ -67,7 +77,7 @@
<WorkspaceMark workspace={w} size="xs" />
<span data-slot="menu-label" class={cn('min-w-0 flex-1 truncate', on && 'text-foreground')}>{w.name}</span>
<span data-slot="command-trailing" class="ml-auto flex shrink-0 items-center gap-1.5 pl-3">
<span class="text-ui-2xs tabular-nums text-muted-foreground">{inWorkspace(connections, w.id, $workspaces).length}</span>
<span class="font-mono text-ui-2xs tabular-nums text-muted-foreground" title={countLabel(inWorkspace(connections, w.id, $workspaces).length)}>{inWorkspace(connections, w.id, $workspaces).length}</span>
<Check class={cn('size-3.5 shrink-0', on ? 'text-foreground' : 'invisible')} />
</span>
</DropdownMenu.Item>
Expand Down
48 changes: 42 additions & 6 deletions src/lib/stores/connections.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { invoke } from '@tauri-apps/api/core'
import { saveSqlDraft, saveSqlTabs } from '$lib/stores/sql-draft.js'
import { notifyLocalChange, recordDeletion } from '$lib/sync/changes.js'
import { activeWorkspaceId, DEFAULT_WORKSPACE_ID } from '$lib/stores/workspaces.js'
import { get } from 'svelte/store'

const STORAGE_KEY = 'stroke:connections'
/**
Expand Down Expand Up @@ -336,13 +338,35 @@ export async function hydrateConnectionsFromDisk() {
}
}

/**
* Where a connection is filed and how it looks, set by the person rather than
* by whatever dialled it. The one-click paths (a provider's database, a Docker
* container, a local server, D1) build a fresh row on every connect, so writing
* that row over the saved one dropped these and sent the connection back to
* the default workspace. A caller that names one of them (the edit form always
* does, even to clear it) sets it; one that leaves it out keeps the saved value.
*/
const FILING_FIELDS = /** @type {const} */ (['workspaceId', 'color', 'group'])

/**
* The workspace a brand-new row lands in: the one on screen, so connecting to
* a provider's database from the "Work" workspace files it under Work.
* @returns {string | undefined}
*/
function workspaceForNew() {
const id = get(activeWorkspaceId)
return id && id !== DEFAULT_WORKSPACE_ID ? id : undefined
}

/**
* @param {SavedConnection} conn
* @param {{ revive?: boolean }} [opts] `revive` lets an explicit re-add (the
* Sample Database button) bring back an id that was deleted. Everything else
* that writes an existing connection back is a no-op for a deleted one.
* @param {{ revive?: boolean, exact?: boolean }} [opts] `revive` lets an
* explicit re-add (the Sample Database button) bring back an id that was
* deleted. Everything else that writes an existing connection back is a
* no-op for a deleted one. `exact` stores the row as given, with no filing
* kept or added: sync, whose record is the truth from another device.
*/
export function upsertConnection(conn, { revive = false } = {}) {
export function upsertConnection(conn, { revive = false, exact = false } = {}) {
const deleted = loadDeletedIds()
if (deleted.has(conn.id)) {
if (!revive) {
Expand All @@ -359,8 +383,20 @@ export function upsertConnection(conn, { revive = false } = {}) {
// A pin is set only through setConnectionMeta; a live copy written back
// here (connect, database switch, edit) must not drop or revive it.
const { pinned: _stale, ...rest } = conn
list[idx] = list[idx].pinned ? { ...rest, pinned: true } : rest
} else list.push(conn)
/** @type {SavedConnection} */
const next = list[idx].pinned ? { ...rest, pinned: true } : rest
if (!exact) {
const prev = /** @type {Record<string, any>} */ (list[idx])
for (const f of FILING_FIELDS) {
if (!(f in conn) && prev[f] != null) /** @type {Record<string, any>} */ (next)[f] = prev[f]
}
}
list[idx] = next
} else if (exact || 'workspaceId' in conn) list.push(conn)
else {
const ws = workspaceForNew()
list.push(ws ? { ...conn, workspaceId: ws } : conn)
}
_persistFailed = !saveConnections(list)
return list
}
Expand Down
52 changes: 52 additions & 0 deletions src/lib/stores/connections.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -213,3 +213,55 @@ describe('set-aside pools on edit and delete', () => {
expect(closedParked).toEqual(['p'])
})
})

// Workspaces: a one-click connect (provider, Docker, local server, D1) builds a
// fresh row each time, and writing it over the saved one used to drop its
// workspace, colour and group, sending it back to Personal.
describe('workspace filing on save', () => {
beforeEach(() => {
installLocalStorage()
vi.resetModules()
})

it('files a new connection under the workspace on screen', async () => {
const { upsertConnection, loadSavedConnections } = await import('./connections.js')
const ws = await import('./workspaces.js')
ws.activeWorkspaceId.set('work')
upsertConnection({ id: 'n', type: 'postgres', name: 'neon-db', host: 'ep.neon.tech' })
expect(loadSavedConnections()[0].workspaceId).toBe('work')
})

it('leaves a new connection in the default workspace when that is on screen', async () => {
const { upsertConnection, loadSavedConnections } = await import('./connections.js')
upsertConnection({ id: 'n', type: 'postgres', name: 'x' })
expect(loadSavedConnections()[0].workspaceId).toBeUndefined()
})

it('keeps the workspace, colour and group when a fresh row is written over a saved one', async () => {
const { upsertConnection, loadSavedConnections } = await import('./connections.js')
upsertConnection({ id: 'local-pg', type: 'postgres', name: 'pg', workspaceId: 'work', color: 'red', group: 'Local' })
// What connectionFor / providerToSaved hand back on the next connect.
upsertConnection({ id: 'local-pg', type: 'postgres', name: 'pg', host: '127.0.0.1', lastConnectedAt: 5 })
const row = loadSavedConnections()[0]
expect([row.workspaceId, row.color, row.group, row.lastConnectedAt]).toEqual(['work', 'red', 'Local', 5])
})

it('lets the edit form move or clear them by naming the field', async () => {
const { upsertConnection, loadSavedConnections } = await import('./connections.js')
upsertConnection({ id: 'a', type: 'postgres', name: 'a', workspaceId: 'work', color: 'red' })
upsertConnection({ id: 'a', type: 'postgres', name: 'a', workspaceId: undefined, color: 'blue' })
const row = loadSavedConnections()[0]
expect([row.workspaceId, row.color]).toEqual([undefined, 'blue'])
})

it('stores a synced row exactly as it came', async () => {
const { upsertConnection, loadSavedConnections } = await import('./connections.js')
const ws = await import('./workspaces.js')
ws.activeWorkspaceId.set('work')
upsertConnection({ id: 'a', type: 'postgres', name: 'a', workspaceId: 'home', color: 'red' })
upsertConnection({ id: 'a', type: 'postgres', name: 'a' }, { exact: true })
upsertConnection({ id: 'b', type: 'postgres', name: 'b' }, { exact: true })
const [a, b] = loadSavedConnections()
expect([a.workspaceId, a.color, b.workspaceId]).toEqual([undefined, undefined, undefined])
})
})
4 changes: 2 additions & 2 deletions src/lib/sync/runtime.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,11 @@ const adapters = {
const prev = loadSavedConnections().find((c) => c.id === data.id)
const conn = prev?.lastConnectedAt != null ? { ...data, lastConnectedAt: prev.lastConnectedAt } : data
// Through the normal save path, so secrets go to the keychain.
upsertConnection(conn, { revive: true })
upsertConnection(conn, { revive: true, exact: true })
},
remove: (id) => void removeConnection(id),
conflictCopy: (data) =>
upsertConnection({ ...data, id: newConnectionId(), name: `${data.name || 'Connection'} (conflicted copy)` }),
upsertConnection({ ...data, id: newConnectionId(), name: `${data.name || 'Connection'} (conflicted copy)` }, { exact: true }),
},
// One saved query per record (the editor's Saved list).
query: {
Expand Down
Loading