overleaf/services/web/frontend/js/features/editor-left-menu/hooks/use-set-overall-theme.tsx
Jakob Ackermann aa480a2663 Merge pull request #18898 from overleaf/jpa-no-window
[web] migrate from window attributes to getMeta

GitOrigin-RevId: 3dcf1ab6b01155e5e4abeb3e78d0fa9053e055bc
2024-06-19 08:04:21 +00:00

74 lines
2.4 KiB
TypeScript

import { useCallback, useEffect, useState } from 'react'
import _ from 'lodash'
import useScopeValue from '../../../shared/hooks/use-scope-value'
import type { OverallThemeMeta } from '../../../../../types/project-settings'
import { saveUserSettings } from '../utils/api'
import { UserSettings } from '../../../../../types/user-settings'
import { useUserSettingsContext } from '@/shared/context/user-settings-context'
import getMeta from '@/utils/meta'
export default function useSetOverallTheme() {
const [chosenTheme, setChosenTheme] = useState<OverallThemeMeta | null>(null)
const [loadingStyleSheet, setLoadingStyleSheet] = useScopeValue<boolean>(
'ui.loadingStyleSheet'
)
const { userSettings, setUserSettings } = useUserSettingsContext()
const { overallTheme } = userSettings
const setOverallTheme = useCallback(
(overallTheme: UserSettings['overallTheme']) => {
setUserSettings(settings => ({ ...settings, overallTheme }))
},
[setUserSettings]
)
useEffect(() => {
const docHeadEl = document.querySelector('head')
const oldStyleSheetEl = document.getElementById('main-stylesheet')
const newStyleSheetEl = document.createElement('link')
newStyleSheetEl.setAttribute('rel', 'stylesheet')
newStyleSheetEl.setAttribute('id', 'main-stylesheet')
newStyleSheetEl.setAttribute('href', chosenTheme?.path ?? '')
const loadEventCallback = () => {
setLoadingStyleSheet(false)
if (docHeadEl && oldStyleSheetEl) {
docHeadEl.removeChild(oldStyleSheetEl)
}
}
if (loadingStyleSheet) {
newStyleSheetEl.addEventListener('load', loadEventCallback, {
once: true,
})
docHeadEl?.appendChild(newStyleSheetEl)
}
return () => {
newStyleSheetEl.removeEventListener('load', loadEventCallback)
}
}, [loadingStyleSheet, setLoadingStyleSheet, chosenTheme?.path])
return useCallback(
(newOverallTheme: UserSettings['overallTheme']) => {
if (overallTheme !== newOverallTheme) {
const chosenTheme = _.find(
getMeta('ol-overallThemes'),
theme => theme.val === newOverallTheme
)
if (chosenTheme) {
setLoadingStyleSheet(true)
setChosenTheme(chosenTheme)
setOverallTheme(newOverallTheme)
saveUserSettings('overallTheme', newOverallTheme)
}
}
},
[overallTheme, setLoadingStyleSheet, setOverallTheme]
)
}