frontispiece / apps / frontispiece-editor / src / view / bg.ts
bg.ts
Raw
/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */

import { useLayoutEffect } from 'preact/hooks'
import { useLayoutState } from '../state/layout-state'

export const BG = () => {
	const layoutState = useLayoutState()
	useLayoutEffect(() => {
		const bg = layoutState.bg.get()
		if (!bg) {
			return
		}
		if (bg.startsWith('#')) {
			document.body.style.backgroundImage = 'none'
			document.body.style.backgroundColor = layoutState.bg.get()
			return
		}

		if (bg.startsWith('0x')) {
			let bgColor = '#' + bg.slice(2)
			document.body.style.backgroundImage = 'none'
			document.body.style.backgroundColor = bgColor
			return
		}

		let bgURL = bg

		if (!bg.includes('/')) {
			// assume we want the default asset folder
			bgURL = 'assets/images/' + bg
		}

		document.body.style.backgroundImage = `url(${bgURL})`
	}, [layoutState.bg.get()])
	return null
}