Skip to content
Open
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,251 @@
import { useCallback, useEffect, useMemo } from 'react'

import { useCollection, useTracks } from '@audius/common/api'
import { ID } from '@audius/common/models'
import { cacheCollectionsActions, toastActions } from '@audius/common/store'
import {
Button,
Flex,
IconCopy,
IconTrash,
Text,
useTheme
} from '@audius/harmony'
import { useDispatch } from 'react-redux'

import { usePlaylistEditMode } from '../PlaylistEditModeContext'

import { useTrackHistoryContext } from './TrackHistoryContext'
import { useTrackSelection } from './TrackSelectionContext'

const { removeTrackFromPlaylist, addTrackToPlaylist } = cacheCollectionsActions
const { toast } = toastActions

const messages = {
selected: (n: number) => `${n} selected`,
copy: 'Copy URLs',
remove: 'Remove',
clear: 'Clear',
selectAll: 'Select all',
undo: 'Undo',
redo: 'Redo',
copiedOne: 'Copied 1 track URL to clipboard',
copiedMany: (n: number) => `Copied ${n} track URLs to clipboard`,
copyFailed: 'Could not copy URLs to clipboard',
removed: (n: number) => (n === 1 ? 'Removed 1 track' : `Removed ${n} tracks`)
}

type Props = {
collectionId: ID
orderedTrackIds: ID[]
}

export const TrackBulkActionsBar = (props: Props) => {
const { collectionId, orderedTrackIds } = props
const dispatch = useDispatch()
const { color } = useTheme()
const editMode = usePlaylistEditMode()
const selection = useTrackSelection()
const history = useTrackHistoryContext()

const { data: collection } = useCollection(collectionId)
const selectedIds = useMemo(
() => orderedTrackIds.filter((id) => selection.isSelected(id)),
[orderedTrackIds, selection]
)
const { data: selectedTracks } = useTracks(selectedIds)

const copyUrls = useCallback(async () => {
if (!selectedTracks?.length) return
const origin =
typeof window !== 'undefined'
? window.location.origin
: 'https://audius.co'
const urls = selectedTracks
.map((t) => (t?.permalink ? `${origin}${t.permalink}` : null))
.filter((u): u is string => !!u)
.join('\n')
try {
await navigator.clipboard.writeText(urls)
dispatch(
toast({
content:
urls.split('\n').length === 1
? messages.copiedOne
: messages.copiedMany(urls.split('\n').length)
})
)
} catch {
dispatch(toast({ content: messages.copyFailed }))
}
}, [dispatch, selectedTracks])

const removeSelected = useCallback(() => {
if (!collection) return
const trackIds = selectedIds
if (trackIds.length === 0) return
// Record each removal in history so it can be undone.
trackIds.forEach((trackId) => {
const entry = collection.playlist_contents.track_ids.find(
(t) => t.track === trackId
)
if (!entry) return
const index = collection.playlist_contents.track_ids.findIndex(
(t) => t.track === trackId && t.time === entry.time
)
const timestamp = entry.metadata_time ?? entry.time
history.push({ type: 'remove', trackId, index, timestamp })
dispatch(removeTrackFromPlaylist(trackId, collectionId, timestamp))
})
dispatch(toast({ content: messages.removed(trackIds.length) }))
selection.clear()
}, [collection, collectionId, dispatch, history, selectedIds, selection])

const handleUndo = useCallback(() => {
history.undo((inverse) => {
if (inverse.type === 'add') {
dispatch(
addTrackToPlaylist(inverse.trackId, collectionId, { silent: true })
)
}
})
}, [collectionId, dispatch, history])

const handleRedo = useCallback(() => {
history.redo()
}, [history])

// Keyboard shortcuts: only active while in edit mode
useEffect(() => {
if (!editMode.isEditMode || editMode.collectionId !== collectionId) return
const onKey = (e: KeyboardEvent) => {
const target = e.target as HTMLElement | null
const isInputFocused =
target &&
['INPUT', 'TEXTAREA'].includes(target.tagName) &&
!target.dataset.bulkActions
if (isInputFocused) return
const mod = e.metaKey || e.ctrlKey
if (mod && e.key.toLowerCase() === 'a') {
e.preventDefault()
selection.selectAll(orderedTrackIds)
return
}
if (mod && e.key.toLowerCase() === 'z' && !e.shiftKey) {
e.preventDefault()
handleUndo()
return
}
if (
(mod && e.key.toLowerCase() === 'z' && e.shiftKey) ||
(mod && e.key.toLowerCase() === 'y')
) {
e.preventDefault()
handleRedo()
return
}
if (e.key === 'Escape') {
if (selection.count > 0) {
e.preventDefault()
selection.clear()
}
}
if (
(e.key === 'Delete' || e.key === 'Backspace') &&
selection.count > 0
) {
e.preventDefault()
removeSelected()
}
}
window.addEventListener('keydown', onKey)
return () => window.removeEventListener('keydown', onKey)
}, [
collectionId,
editMode.collectionId,
editMode.isEditMode,
handleRedo,
handleUndo,
orderedTrackIds,
removeSelected,
selection
])

if (!editMode.isEditMode || editMode.collectionId !== collectionId) {
return null
}
if (selection.count === 0 && !history.canUndo && !history.canRedo) {
return null
}

return (
<Flex
data-bulk-actions
css={{
position: 'sticky',
top: 0,
zIndex: 4,
backgroundColor: color.background.surface1,
borderBottom: `1px solid ${color.border.strong}`
}}
p='m'
gap='m'
alignItems='center'
justifyContent='space-between'
>
<Flex gap='m' alignItems='center'>
<Text variant='body' strength='strong'>
{messages.selected(selection.count)}
</Text>
{selection.count > 0 ? (
<Button variant='secondary' size='small' onClick={selection.clear}>
{messages.clear}
</Button>
) : null}
<Button
variant='secondary'
size='small'
onClick={() => selection.selectAll(orderedTrackIds)}
>
{messages.selectAll}
</Button>
</Flex>
<Flex gap='m' alignItems='center'>
<Button
variant='secondary'
size='small'
iconLeft={IconCopy}
disabled={selection.count === 0}
onClick={copyUrls}
>
{messages.copy}
</Button>
<Button
variant='destructive'
size='small'
iconLeft={IconTrash}
disabled={selection.count === 0}
onClick={removeSelected}
>
{messages.remove}
</Button>
<Button
variant='secondary'
size='small'
disabled={!history.canUndo}
onClick={handleUndo}
>
{messages.undo}
</Button>
<Button
variant='secondary'
size='small'
disabled={!history.canRedo}
onClick={handleRedo}
>
{messages.redo}
</Button>
</Flex>
</Flex>
)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
import {
createContext,
ReactNode,
useCallback,
useContext,
useMemo,
useRef,
useState
} from 'react'

import { ID } from '@audius/common/models'
import { cacheCollectionsActions, toastActions } from '@audius/common/store'
import { useDispatch } from 'react-redux'

const { addTrackToPlaylist, removeTrackFromPlaylist } = cacheCollectionsActions
const { toast } = toastActions

export type TrackHistoryEntry =
| {
type: 'remove'
trackId: ID
// best-effort original position; not used to re-insert into the same
// slot because the existing addTrackToPlaylist saga always appends.
index: number
// timestamp captured at the time of removal for the saga call.
timestamp: number
}
| {
type: 'add'
trackId: ID
}

type TrackHistoryContextValue = {
canUndo: boolean
canRedo: boolean
push: (entry: TrackHistoryEntry) => void
undo: (applyInverse: (entry: TrackHistoryEntry) => void) => void
redo: () => void
}

const TrackHistoryContext = createContext<TrackHistoryContextValue | null>(null)

type ProviderProps = {
collectionId?: ID
children: ReactNode
}

const messages = {
noMoreUndo: 'Nothing to undo',
noMoreRedo: 'Nothing to redo'
}

export const TrackHistoryProvider = ({
collectionId,
children
}: ProviderProps) => {
const dispatch = useDispatch()
const undoStackRef = useRef<TrackHistoryEntry[]>([])
const redoStackRef = useRef<TrackHistoryEntry[]>([])
const [, force] = useState(0)
const bump = useCallback(() => force((v) => v + 1), [])

const push = useCallback(
(entry: TrackHistoryEntry) => {
undoStackRef.current.push(entry)
redoStackRef.current = []
bump()
},
[bump]
)

const undo = useCallback(
(applyInverse: (entry: TrackHistoryEntry) => void) => {
const entry = undoStackRef.current.pop()
if (!entry) {
dispatch(toast({ content: messages.noMoreUndo }))
return
}
redoStackRef.current.push(entry)
bump()
const inverse: TrackHistoryEntry =
entry.type === 'remove'
? { type: 'add', trackId: entry.trackId }
: { type: 'remove', trackId: entry.trackId, index: -1, timestamp: 0 }
applyInverse(inverse)
},
[bump, dispatch]
)

const redo = useCallback(() => {
const entry = redoStackRef.current.pop()
if (!entry) {
dispatch(toast({ content: messages.noMoreRedo }))
return
}
undoStackRef.current.push(entry)
bump()
if (!collectionId) return
if (entry.type === 'remove') {
dispatch(
removeTrackFromPlaylist(entry.trackId, collectionId, entry.timestamp)
)
} else if (entry.type === 'add') {
dispatch(
addTrackToPlaylist(entry.trackId, collectionId, { silent: true })
)
}
}, [bump, collectionId, dispatch])

const value = useMemo<TrackHistoryContextValue>(
() => ({
canUndo: undoStackRef.current.length > 0,
canRedo: redoStackRef.current.length > 0,
push,
undo,
redo
}),
// Intentionally include bump tick via undoStackRef.current.length read
// eslint-disable-next-line react-hooks/exhaustive-deps
[push, undo, redo, undoStackRef.current.length, redoStackRef.current.length]
)

return (
<TrackHistoryContext.Provider value={value}>
{children}
</TrackHistoryContext.Provider>
)
}

export const useTrackHistoryContext = (): TrackHistoryContextValue => {
const ctx = useContext(TrackHistoryContext)
if (!ctx) {
return {
canUndo: false,
canRedo: false,
push: () => {},
undo: () => {},
redo: () => {}
}
}
return ctx
}
Loading
Loading