document.ts 853 B

1234567891011121314151617181920212223242526272829303132
  1. import { useConfig } from '@/hooks'
  2. import type { ProviderProps} from 'react'
  3. import { createContext, createElement, useEffect, useState } from 'react'
  4. export interface DocumentState {
  5. clearTitle(): void
  6. setTitle(title: string): void
  7. }
  8. export const DocumentContext = createContext({} as DocumentState)
  9. export function DocumentProvider({ children }: ProviderProps<undefined>) {
  10. const { config } = useConfig()
  11. const [title, setTitle] = useState<string>()
  12. function clearTitle() {
  13. setTitle(undefined)
  14. }
  15. useEffect(() => {
  16. if (title) {
  17. document.title = `${title} - ${config.document.titleSuffix}`
  18. } else {
  19. document.title = config.document.titleSuffix
  20. }
  21. }, [config.document.titleSuffix, title])
  22. const value = { clearTitle, setTitle }
  23. return createElement(DocumentContext.Provider, { value }, children)
  24. }