import React from 'react' import dynamic from 'next/dynamic' import Dropdown from '../Dropdown' import { managePopout } from '../Popout' import ThemeIcon from '../svg/Theme' import RemoveIcon from '../svg/Remove' import { THEMES, COLORS, DEFAULT_THEME } from '../../lib/constants' import { getThemes, saveThemes, stringifyRGBA, generateId } from '../../lib/util' const ThemeCreate = dynamic(() => import('./ThemeCreate'), { loading: () => null }) const ThemeItem = ({ children, item, isSelected, onClick }) => (
{children} {item.custom && !isSelected && (
)}
) const themeIcon = class Themes extends React.PureComponent { selectedTheme = DEFAULT_THEME state = { themes: THEMES, preset: this.props.theme, highlights: {}, name: 'Custom Theme', selected: null } componentDidMount() { const storedThemes = getThemes(localStorage) || [] this.setState(({ themes }) => { const newThemes = [...storedThemes, ...themes] const name = `Custom Theme ${newThemes.filter(({ name }) => name.startsWith('Custom Theme')) .length + 1}` this.selectedTheme = newThemes.find(({ id }) => id === this.props.theme) || DEFAULT_THEME return { themes: newThemes, highlights: this.selectedTheme.highlights, name } }) } applyPreset = preset => this.setState(({ themes }) => ({ preset, highlights: themes.find(({ id }) => id === preset).highlights })) handleDropdown = ({ id }) => { if (id === 'create') { this.props.toggleVisibility() } else { this.props.updateTheme(id) } } updateName = ({ target: { value: name } }) => this.setState({ name }) selectHighlight = highlight => () => this.setState(({ selected }) => ({ selected: selected === highlight ? null : highlight })) updateHighlight = ({ rgb }) => this.setState({ highlights: { ...this.state.highlights, [this.state.selected]: stringifyRGBA(rgb) } }) removeTheme = id => event => { event.stopPropagation() const { themes } = this.state const newThemes = themes.filter(t => t.id !== id) saveThemes(localStorage, newThemes.filter(({ custom }) => custom)) if (this.props.theme === id) { this.props.updateTheme(DEFAULT_THEME.id) } else { this.setState({ themes: newThemes }) } } createTheme = () => { const { themes, name, highlights } = this.state const id = `theme:${generateId()}` const newTheme = { id, name, highlights, custom: true } const customThemes = [newTheme, ...themes.filter(({ custom }) => custom)] saveThemes(localStorage, customThemes) this.props.updateTheme(id) } itemWrapper = props => render() { const { theme, isVisible, toggleVisibility } = this.props const { name, themes, highlights, selected, preset } = this.state const dropdownValue = isVisible ? { name } : { id: theme, name: this.selectedTheme.name } const dropdownList = [ { id: 'create', name: 'Create +' }, ...themes ] return (
{isVisible && ( )}
) } } export default managePopout(Themes)