2022-12-23 18:06:19 -05:00
|
|
|
import { useCallback, useEffect, useState } from 'react'
|
|
|
|
import _ from 'lodash'
|
|
|
|
import useScopeValue from '../../../shared/hooks/use-scope-value'
|
2023-01-03 12:46:37 -05:00
|
|
|
import type { OverallThemeMeta } from '../../../../../types/project-settings'
|
2023-01-04 07:17:50 -05:00
|
|
|
import { saveUserSettings, type UserSettings } from '../utils/api'
|
2022-12-23 18:06:19 -05:00
|
|
|
|
|
|
|
export default function useSetOverallTheme() {
|
|
|
|
const [chosenTheme, setChosenTheme] = useState<OverallThemeMeta | null>(null)
|
2022-12-23 18:43:46 -05:00
|
|
|
const [loadingStyleSheet, setLoadingStyleSheet] = useScopeValue<boolean>(
|
|
|
|
'ui.loadingStyleSheet'
|
|
|
|
)
|
2023-01-04 07:17:50 -05:00
|
|
|
const [overallTheme, setOverallTheme] = useScopeValue<
|
|
|
|
UserSettings['overallTheme']
|
2023-01-03 12:46:37 -05:00
|
|
|
>('settings.overallTheme')
|
2022-12-23 18:06:19 -05:00
|
|
|
|
|
|
|
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])
|
|
|
|
|
2023-01-04 07:17:50 -05:00
|
|
|
return useCallback(
|
|
|
|
(newOverallTheme: UserSettings['overallTheme']) => {
|
|
|
|
if (overallTheme !== newOverallTheme) {
|
2022-12-23 18:06:19 -05:00
|
|
|
const chosenTheme = _.find(
|
|
|
|
window.overallThemes,
|
2023-01-04 07:17:50 -05:00
|
|
|
theme => theme.val === newOverallTheme
|
2022-12-23 18:06:19 -05:00
|
|
|
)
|
|
|
|
|
|
|
|
if (chosenTheme) {
|
|
|
|
setLoadingStyleSheet(true)
|
|
|
|
setChosenTheme(chosenTheme)
|
2023-01-04 07:17:50 -05:00
|
|
|
setOverallTheme(newOverallTheme)
|
2023-01-06 09:29:03 -05:00
|
|
|
saveUserSettings('overallTheme', newOverallTheme)
|
2022-12-23 18:06:19 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
},
|
2023-01-04 07:17:50 -05:00
|
|
|
[overallTheme, setLoadingStyleSheet, setOverallTheme]
|
2022-12-23 18:06:19 -05:00
|
|
|
)
|
|
|
|
}
|