Track position in playlist can now be typed

This commit is contained in:
patben8 committed 2026-10-05 21:01:25 +02:00
1 parent 0fac84cb73
commit c8b86100f0
5 files changed
+180 -1

No files matched your search

+36
View File
@@ -0,0 +1,36 @@
import { describe, expect, it } from 'vitest'
import { maxPosition, moveToPosition } from './playlistOrder'
const order = ['A', 'B', 'C', 'D', 'E', 'F', 'G']
const move = (ids: string[], position: number) => moveToPosition(order, new Set(ids), position).join('')
describe('moveToPosition', () => {
it('puts the track AT the position, moving down or up', () => {
expect(move(['B'], 5)).toBe('ACDEBFG')
expect(move(['F'], 2)).toBe('AFBCDEG')
expect(move(['A'], 1)).toBe('ABCDEFG')
})
it('moves a selection as one block in playlist order', () => {
expect(move(['F', 'B'], 2)).toBe('ABFCDEG')
expect(move(['G', 'A', 'D'], 3)).toBe('BCADGEF')
})
it('clamps past either end', () => {
expect(move(['B', 'C'], 99)).toBe('ADEFGBC')
expect(move(['C'], 0)).toBe('CABDEFG')
})
it('moves every entry of a track listed twice', () => {
expect(moveToPosition(['A', 'B', 'A', 'C'], new Set(['A']), 2).join('')).toBe('BAAC')
})
})
describe('maxPosition', () => {
it('leaves room for the block behind its first track', () => {
expect(maxPosition(order, new Set(['B']))).toBe(7)
expect(maxPosition(order, new Set(['B', 'C', 'D']))).toBe(5)
expect(move(['B', 'C', 'D'], 5)).toBe('AEFGBCD')
})
})
+17
View File
@@ -0,0 +1,17 @@
/** A playlist's entry order with `moving` lifted out as one block, kept in
* their PLAYLIST order, and put back so the block's first track lands at the
* 1-based `position` of the result. A position past the end puts the block
* last. A track listed twice in the playlist moves with both entries, since a
* selection is by track id. */
export function moveToPosition(order: string[], moving: ReadonlySet<string>, position: number): string[] {
const block = order.filter((id) => moving.has(id))
const rest = order.filter((id) => !moving.has(id))
const at = Math.min(Math.max(Math.floor(position), 1) - 1, rest.length)
return [...rest.slice(0, at), ...block, ...rest.slice(at)]
}
/** The highest position the block's first track can take: the block's own
* length is what sits behind it. */
export function maxPosition(order: string[], moving: ReadonlySet<string>): number {
return order.length - order.filter((id) => moving.has(id)).length + 1
}