useRecentSearches.ts 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. // Copyright (C) 2012-2025 Zammad Foundation, https://zammad-foundation.org/
  2. import { useLocalStorage } from '@vueuse/core'
  3. import { useSessionStore } from '#shared/stores/session.ts'
  4. const RECENTLY_SEARCHES_MAX_LENGTH = 10
  5. export const useRecentSearches = () => {
  6. const { userId } = useSessionStore()
  7. const recentSearches = useLocalStorage<string[]>(
  8. `${userId}-recentSearches`,
  9. [],
  10. )
  11. const addSearch = (search: string) => {
  12. // Remove the search term if it already exists to avoid duplicates
  13. recentSearches.value = recentSearches.value.filter(
  14. (item) => item !== search,
  15. )
  16. // Add the new search term
  17. recentSearches.value.push(search)
  18. // Remove the oldest search if we exceed the maximum length
  19. if (recentSearches.value.length > RECENTLY_SEARCHES_MAX_LENGTH) {
  20. recentSearches.value.shift()
  21. }
  22. }
  23. const removeSearch = (search: string) => {
  24. recentSearches.value = recentSearches.value.filter(
  25. (item) => item !== search,
  26. )
  27. }
  28. const clearSearches = () => {
  29. recentSearches.value = []
  30. }
  31. return {
  32. recentSearches,
  33. addSearch,
  34. removeSearch,
  35. clearSearches,
  36. }
  37. }