import React, { useRef, useState, useEffect } from 'react'; import config, { SuccessOrFailType } from '../config/config'; import apiKeyInvalid from '../utils/apiKey'; import { logUserIn } from '../utils/user'; import Alert from './Alert'; import SitesList from './SitesList'; interface State { alertText: string; alertType: SuccessOrFailType; apiKey: string; blacklist: string; displayAlert: boolean; loading: boolean; loggingStyle: string; loggingType: string; theme: string; whitelist: string; } export default function Options(): JSX.Element { const [state, setState] = useState({ alertText: config.alert.success.text, alertType: config.alert.success.type, apiKey: '', blacklist: '', displayAlert: false, loading: false, loggingStyle: config.loggingStyle, loggingType: config.loggingType, theme: config.theme, whitelist: '', }); const loggingStyleRef = useRef(null); const restoreSettings = async (): Promise => { const items = await browser.storage.sync.get({ apiKey: config.apiKey, blacklist: '', loggingStyle: config.loggingStyle, loggingType: config.loggingType, theme: config.theme, whitelist: '', }); setState({ ...state, apiKey: items.apiKey as string, blacklist: items.blacklist as string, loggingStyle: items.loggingStyle as string, loggingType: items.loggingType as string, theme: items.theme as string, whitelist: items.whitelist as string, }); }; useEffect(() => { void restoreSettings(); }, []); useEffect(() => { if (state.displayAlert) { setTimeout(function () { setState({ ...state, displayAlert: false, loading: false }); }, 2500); } }, [state.displayAlert]); const handleSubmit = async () => { if (state.loading) return; setState({ ...state, loading: true }); const apiKey = state.apiKey; const theme = state.theme; const loggingType = state.loggingType; const loggingStyle = state.loggingStyle; // Trimming blacklist and whitelist removes blank lines and spaces. const blacklist = state.blacklist.trim(); const whitelist = state.whitelist.trim(); // Sync options with google storage. await browser.storage.sync.set({ apiKey, blacklist, loggingStyle, loggingType, theme, whitelist, }); // Set state to be newly entered values. setState({ ...state, apiKey, blacklist, displayAlert: true, loggingStyle, loggingType, theme, whitelist, }); await logUserIn(state.apiKey); }; const updateBlacklistState = (sites: string) => { setState({ ...state, blacklist: sites, }); }; const updateWhitelistState = (sites: string) => { setState({ ...state, whitelist: sites, }); }; const loggingStyle = function () { if (state.loggingStyle == 'blacklist') { return ( ); } return ( ); }; const alert = () => { return (
); }; const isApiKeyValid = apiKeyInvalid(state.apiKey) === ''; return (
{alert()}
setState({ ...state, apiKey: e.target.value })} />
{loggingStyle()}
); }