useMetaTitle.ts 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. // Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. import { isString } from 'lodash-es'
  3. import { computed, reactive, watch } from 'vue'
  4. import { i18n } from '#shared/i18n.ts'
  5. import { useApplicationStore } from '#shared/stores/application.ts'
  6. const viewMetaHeader = reactive({
  7. title: '',
  8. translateTitle: true,
  9. })
  10. const currentTitle = computed(() => {
  11. const application = useApplicationStore()
  12. const productName = application.config.product_name as string
  13. if (!viewMetaHeader.title) return productName
  14. const transformedTitle = viewMetaHeader.translateTitle
  15. ? i18n.t(viewMetaHeader.title)
  16. : viewMetaHeader.title
  17. return `${productName} - ${transformedTitle}`
  18. })
  19. const initializeMetaTitle = () => {
  20. watch(
  21. currentTitle,
  22. (newTitle, oldTitle) => {
  23. if (isString(newTitle) && newTitle !== oldTitle && document)
  24. document.title = newTitle
  25. },
  26. { immediate: true },
  27. )
  28. }
  29. export default function useMetaTitle() {
  30. const setViewTitle = (title: string, translate = true) => {
  31. Object.assign(viewMetaHeader, { title, translateTitle: translate })
  32. }
  33. return {
  34. initializeMetaTitle,
  35. setViewTitle,
  36. currentTitle,
  37. }
  38. }