usePlaylistItems.tsx 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import { useCallback, useState } from 'react';
  2. import { DashboardPickerItem } from 'app/core/components/editors/DashboardPickerByID';
  3. import { PlaylistItem } from './types';
  4. export function usePlaylistItems(playlistItems?: PlaylistItem[]) {
  5. const [items, setItems] = useState<PlaylistItem[]>(playlistItems ?? []);
  6. const addById = useCallback(
  7. (dashboard?: DashboardPickerItem) => {
  8. if (!dashboard || items.find((item) => item.id === dashboard.id)) {
  9. return;
  10. }
  11. const newItem: PlaylistItem = {
  12. id: dashboard.id,
  13. title: dashboard.label as string,
  14. type: 'dashboard_by_id',
  15. value: dashboard.id.toString(10),
  16. order: items.length + 1,
  17. };
  18. setItems([...items, newItem]);
  19. },
  20. [items]
  21. );
  22. const addByTag = useCallback(
  23. (tags: string[]) => {
  24. const tag = tags[0];
  25. if (!tag || items.find((item) => item.value === tag)) {
  26. return;
  27. }
  28. const newItem: PlaylistItem = {
  29. title: tag,
  30. type: 'dashboard_by_tag',
  31. value: tag,
  32. order: items.length + 1,
  33. };
  34. setItems([...items, newItem]);
  35. },
  36. [items]
  37. );
  38. const movePlaylistItem = useCallback(
  39. (item: PlaylistItem, offset: number) => {
  40. const newItems = [...items];
  41. const currentPosition = newItems.indexOf(item);
  42. const newPosition = currentPosition + offset;
  43. if (newPosition >= 0 && newPosition < newItems.length) {
  44. newItems.splice(currentPosition, 1);
  45. newItems.splice(newPosition, 0, item);
  46. }
  47. setItems(newItems);
  48. },
  49. [items]
  50. );
  51. const moveUp = useCallback(
  52. (item: PlaylistItem) => {
  53. movePlaylistItem(item, -1);
  54. },
  55. [movePlaylistItem]
  56. );
  57. const moveDown = useCallback(
  58. (item: PlaylistItem) => {
  59. movePlaylistItem(item, 1);
  60. },
  61. [movePlaylistItem]
  62. );
  63. const deleteItem = useCallback(
  64. (item: PlaylistItem) => {
  65. setItems(items.filter((i) => i !== item));
  66. },
  67. [items]
  68. );
  69. return { items, addById, addByTag, deleteItem, moveDown, moveUp };
  70. }