useThemeUpdate.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. import { computed, ref } from 'vue'
  3. import {
  4. NotificationTypes,
  5. useNotifications,
  6. } from '#shared/components/CommonNotifications/index.ts'
  7. import { EnumAppearanceTheme } from '#shared/graphql/types.ts'
  8. import MutationHandler from '#shared/server/apollo/handler/MutationHandler.ts'
  9. import { useSessionStore } from '#shared/stores/session.ts'
  10. import { useUserCurrentAppearanceMutation } from '../graphql/mutations/userCurrentAppearance.api.ts'
  11. export const useThemeUpdate = (showSuccessNotification = false) => {
  12. const setThemeMutation = new MutationHandler(
  13. useUserCurrentAppearanceMutation(),
  14. {
  15. errorNotificationMessage: __('The appearance could not be updated.'),
  16. },
  17. )
  18. const savingTheme = ref(false)
  19. const session = useSessionStore()
  20. const { notify } = useNotifications()
  21. const setTheme = async (theme: string) => {
  22. const oldTheme = session.user?.preferences?.theme
  23. // Do it before the mutation to avoid a laggy UI.
  24. session.setUserPreference('theme', theme)
  25. return setThemeMutation
  26. .send({ theme: theme as EnumAppearanceTheme })
  27. .catch(() => {
  28. session.setUserPreference('theme', oldTheme)
  29. })
  30. }
  31. const currentTheme = computed({
  32. get: () => session.user?.preferences?.theme || 'auto',
  33. set: (value: EnumAppearanceTheme) => {
  34. if (value === session.user?.preferences?.theme || savingTheme.value) {
  35. return
  36. }
  37. savingTheme.value = true
  38. setTheme(value)
  39. .then(() => {
  40. if (showSuccessNotification) {
  41. notify({
  42. id: 'theme-update',
  43. message: __('Profile appearance updated successfully.'),
  44. type: NotificationTypes.Success,
  45. })
  46. }
  47. })
  48. .finally(() => {
  49. savingTheme.value = false
  50. })
  51. },
  52. })
  53. return {
  54. currentTheme,
  55. savingTheme,
  56. setTheme,
  57. }
  58. }