refactor: consolidate vault ordering

This commit is contained in:
lucaronin
2026-05-15 02:16:38 +02:00
parent 9b28f60be0
commit 0c8be62831
3 changed files with 208 additions and 52 deletions

View File

@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest'
import type { VaultOption } from '../components/status-bar/types'
import { canMoveVaultPath, moveVaultPath, orderVaultsByPath } from './vaultOrdering'
import { canMoveVaultPath, moveVaultPath, orderVaultsByPath, reorderVaultPath, vaultPathList } from './vaultOrdering'
const vaults: VaultOption[] = [
{ label: 'Laputa', path: '/laputa' },
@@ -9,6 +9,10 @@ const vaults: VaultOption[] = [
]
describe('vaultOrdering', () => {
it('extracts vault paths in display order', () => {
expect(vaultPathList(vaults)).toEqual(['/laputa', '/research', '/archive'])
})
it('orders vaults by a complete path list', () => {
expect(orderVaultsByPath(vaults, ['/archive', '/laputa', '/research'])).toEqual([
vaults[2],
@@ -27,6 +31,17 @@ describe('vaultOrdering', () => {
expect(moveVaultPath(vaults, '/research', 'down')).toEqual(['/laputa', '/archive', '/research'])
})
it('reorders a dragged vault path to the hovered path index', () => {
expect(reorderVaultPath(vaults, '/laputa', '/archive')).toEqual(['/research', '/archive', '/laputa'])
expect(reorderVaultPath(vaults, '/archive', '/laputa')).toEqual(['/archive', '/laputa', '/research'])
})
it('ignores no-op or unknown drag reorder paths', () => {
expect(reorderVaultPath(vaults, '/research', '/research')).toBeNull()
expect(reorderVaultPath(vaults, '/missing', '/archive')).toBeNull()
expect(reorderVaultPath(vaults, '/archive', '/missing')).toBeNull()
})
it('reports whether a vault can move in a direction', () => {
expect(canMoveVaultPath(vaults, '/laputa', 'up')).toBe(false)
expect(canMoveVaultPath(vaults, '/laputa', 'down')).toBe(true)

View File

@@ -2,7 +2,7 @@ import type { VaultOption } from '../components/status-bar/types'
export type VaultMoveDirection = 'up' | 'down'
function vaultPathList(vaults: VaultOption[]): string[] {
export function vaultPathList(vaults: VaultOption[]): string[] {
return vaults.map((vault) => vault.path)
}
@@ -35,6 +35,20 @@ export function moveVaultPath(vaults: VaultOption[], path: string, direction: Va
return nextPaths
}
export function reorderVaultPath(vaults: VaultOption[], activePath: string, overPath: string): string[] | null {
if (activePath === overPath) return null
const orderedPaths = vaultPathList(vaults)
const activeIndex = orderedPaths.indexOf(activePath)
const overIndex = orderedPaths.indexOf(overPath)
if (activeIndex === -1 || overIndex === -1) return null
const nextPaths = [...orderedPaths]
const [movedPath] = nextPaths.splice(activeIndex, 1)
nextPaths.splice(overIndex, 0, movedPath)
return nextPaths
}
export function canMoveVaultPath(vaults: VaultOption[], path: string, direction: VaultMoveDirection): boolean {
return moveVaultPath(vaults, path, direction) !== null
}