Skip to content

Commit

Permalink
fix: input toggles dont use localStorage
Browse files Browse the repository at this point in the history
  • Loading branch information
SgtPooki committed Nov 13, 2024
1 parent 6215473 commit 0f75ac7
Show file tree
Hide file tree
Showing 7 changed files with 116 additions and 147 deletions.
File renamed without changes.
65 changes: 65 additions & 0 deletions src/components/input-toggle.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/**
Inspiration from https://dev.to/codebubb/create-a-simple-on-off-slide-toggle-with-css-db8
*/
import React, { useMemo } from 'react'
import './input-toggle.css'
import { InputDescription } from './input-description.js'
import { InputLabel } from './input-label.js'

interface LocalStorageToggleProps {
label: string
value: boolean
description?: string
className?: string
onClick?: React.MouseEventHandler<HTMLDivElement>
onChange(value: boolean): void
resetKey: number
}

export const InputToggle: React.FC<LocalStorageToggleProps> = ({
label,
description = '',
value,
resetKey,
onChange,
...props
}) => {
/**
* Lowercase and no spaces
*/
const id: string = useMemo(() => {
return label.toLowerCase().replace(/\s/g, '-')
}, [label])

const handleChange = (event: React.ChangeEvent<HTMLInputElement>): void => {
const newValue = event.target.checked
onChange(newValue)
}

return (
<div {...props} className={`${props.className}`}>
<InputLabel label={label} />
<InputDescription description={description} />

<input
type="checkbox"
id={id}
checked={value}
onChange={handleChange}
className="dn"
/>
<label
htmlFor={id}
className={`relative dib h1 w2 flex-shrink-0 pointer br4 ${
value ? 'bg-green' : 'bg-dark-gray'
} transition-all duration-200 ease-in-out`}
>
<span
className={`absolute top-0 left-0 dib h1 w1 br-100 bg-white shadow-1 ${
value ? 'translate-x-100' : 'translate-x-0'
} transition-transform duration-200 ease-in-out`}
/>
</label>
</div>
)
}
76 changes: 0 additions & 76 deletions src/components/local-storage-toggle.tsx

This file was deleted.

56 changes: 35 additions & 21 deletions src/context/config-context.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React, { createContext, useCallback, useEffect, useState } from 'react'
import { getConfig, type ConfigDb } from '../lib/config-db.js'
import { defaultDnsJsonResolvers, defaultEnableGatewayProviders, defaultEnableRecursiveGateways, defaultEnableWebTransport, defaultEnableWss, defaultGateways, defaultRouters, getConfig, resetConfig, type ConfigDb } from '../lib/config-db.js'
import { isConfigPage } from '../lib/is-config-page.js'
import { getUiComponentLogger } from '../lib/logger.js'

Expand All @@ -10,12 +10,14 @@ export interface ConfigContextType extends ConfigDb {
isConfigExpanded: boolean
setConfigExpanded(value: boolean): void
setConfig(key: ConfigKey, value: any): void
resetConfig(): Promise<void>
}

export const ConfigContext = createContext<ConfigContextType>({
isConfigExpanded: isLoadedInIframe,
setConfigExpanded: (value: boolean) => {},
setConfig: (key, value) => {},
resetConfig: async () => Promise.resolve(),
gateways: [],
routers: [],
dnsJsonResolvers: {},
Expand All @@ -28,30 +30,36 @@ export const ConfigContext = createContext<ConfigContextType>({

export const ConfigProvider = ({ children }: { children: JSX.Element[] | JSX.Element, expanded?: boolean }): JSX.Element => {
const [isConfigExpanded, setConfigExpanded] = useState(isConfigPage(window.location.hash))
const [gateways, setGateways] = useState<string[]>([])
const [routers, setRouters] = useState<string[]>([])
const [dnsJsonResolvers, setDnsJsonResolvers] = useState<Record<string, string>>({})
const [enableWss, setEnableWss] = useState(false)
const [enableWebTransport, setEnableWebTransport] = useState(false)
const [enableGatewayProviders, setEnableGatewayProviders] = useState(false)
const [enableRecursiveGateways, setEnableRecursiveGateways] = useState(false)
const [debug, setDebug] = useState('')
const [gateways, setGateways] = useState<string[]>(defaultGateways)
const [routers, setRouters] = useState<string[]>(defaultRouters)
const [dnsJsonResolvers, setDnsJsonResolvers] = useState<Record<string, string>>(defaultDnsJsonResolvers)
const [enableWss, setEnableWss] = useState(defaultEnableWss)
const [enableWebTransport, setEnableWebTransport] = useState(defaultEnableWebTransport)
const [enableGatewayProviders, setEnableGatewayProviders] = useState(defaultEnableGatewayProviders)
const [enableRecursiveGateways, setEnableRecursiveGateways] = useState(defaultEnableRecursiveGateways)
const [debug, setDebug] = useState('helia:sw-gateway*,helia:sw-gateway*:trace')
const isExplicitlyLoadedConfigPage = isConfigPage(window.location.hash)
const logger = getUiComponentLogger('config-context')
const log = logger.forComponent('main')

async function loadConfig (): Promise<void> {
const config = await getConfig(logger)
setGateways(config.gateways)
setRouters(config.routers)
setDnsJsonResolvers(config.dnsJsonResolvers)
setEnableWss(config.enableWss)
setEnableWebTransport(config.enableWebTransport)
setEnableGatewayProviders(config.enableGatewayProviders)
setEnableRecursiveGateways(config.enableRecursiveGateways)
setDebug(config.debug)
}
/**
* We need to make sure that the configDb types are loaded with the values from IDB
*/
useEffect(() => {
void (async () => {
const config = await getConfig(getUiComponentLogger('config-context'))
setGateways(config.gateways)
setRouters(config.routers)
setDnsJsonResolvers(config.dnsJsonResolvers)
setEnableWss(config.enableWss)
setEnableWebTransport(config.enableWebTransport)
setEnableGatewayProviders(config.enableGatewayProviders)
setEnableRecursiveGateways(config.enableRecursiveGateways)
setDebug(config.debug)
})()
void loadConfig().catch((err) => {
log.error('Error loading config', err)
})
}, [])

/**
Expand Down Expand Up @@ -84,10 +92,16 @@ export const ConfigProvider = ({ children }: { children: JSX.Element[] | JSX.Ele
setDebug(value)
break
default:
log.error(`Unknown config key: ${key}`)
throw new Error(`Unknown config key: ${key}`)
}
}, [])

const resetConfigLocal = async (): Promise<void> => {
await resetConfig()
await loadConfig()
}

const setConfigExpandedWrapped = (value: boolean): void => {
if (isLoadedInIframe || isExplicitlyLoadedConfigPage) {
// ignore it
Expand All @@ -97,7 +111,7 @@ export const ConfigProvider = ({ children }: { children: JSX.Element[] | JSX.Ele
}

return (
<ConfigContext.Provider value={{ isConfigExpanded, setConfigExpanded: setConfigExpandedWrapped, setConfig: setConfigLocal, gateways, routers, dnsJsonResolvers, enableWss, enableWebTransport, enableGatewayProviders, enableRecursiveGateways, debug }}>
<ConfigContext.Provider value={{ isConfigExpanded, setConfigExpanded: setConfigExpandedWrapped, setConfig: setConfigLocal, resetConfig: resetConfigLocal, gateways, routers, dnsJsonResolvers, enableWss, enableWebTransport, enableGatewayProviders, enableRecursiveGateways, debug }}>
{children}
</ConfigContext.Provider>
)
Expand Down
27 changes: 0 additions & 27 deletions src/lib/config-db.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { type ComponentLogger, enable } from '@libp2p/logger'
import { GenericIDB, type BaseDbConfig } from './generic-db.js'
import { LOCAL_STORAGE_KEYS } from './local-storage.js'

export interface ConfigDb extends BaseDbConfig {
gateways: string[]
Expand All @@ -25,40 +24,14 @@ export const defaultEnableGatewayProviders = true

const configDb = new GenericIDB<ConfigDb>('helia-sw', 'config')

export async function localStorageToIdb ({ gateways, routers, dnsJsonResolvers, debug }: Pick<ConfigDb, 'gateways' | 'routers' | 'dnsJsonResolvers' | 'debug'>): Promise<void> {
if (typeof globalThis.localStorage !== 'undefined') {
await configDb.open()
const localStorage = globalThis.localStorage
const enableRecursiveGateways = localStorage.getItem(LOCAL_STORAGE_KEYS.config.enableRecursiveGateways) === null ? defaultEnableRecursiveGateways : localStorage.getItem(LOCAL_STORAGE_KEYS.config.enableRecursiveGateways) === 'true'
const enableWss = localStorage.getItem(LOCAL_STORAGE_KEYS.config.enableWss) === null ? defaultEnableWss : localStorage.getItem(LOCAL_STORAGE_KEYS.config.enableWss) === 'true'
const enableWebTransport = localStorage.getItem(LOCAL_STORAGE_KEYS.config.enableWebTransport) === null ? defaultEnableWebTransport : localStorage.getItem(LOCAL_STORAGE_KEYS.config.enableWebTransport) === 'true'
const enableGatewayProviders = localStorage.getItem(LOCAL_STORAGE_KEYS.config.enableGatewayProviders) === null ? defaultEnableGatewayProviders : localStorage.getItem(LOCAL_STORAGE_KEYS.config.enableGatewayProviders) === 'true'
enable(debug)

await configDb.put('gateways', gateways)
await configDb.put('routers', routers)
await configDb.put('dnsJsonResolvers', dnsJsonResolvers)
await configDb.put('enableRecursiveGateways', enableRecursiveGateways)
await configDb.put('enableWss', enableWss)
await configDb.put('enableWebTransport', enableWebTransport)
await configDb.put('enableGatewayProviders', enableGatewayProviders)
await configDb.put('debug', debug)
configDb.close()
}
}

export async function resetConfig (): Promise<void> {
await configDb.open()
await configDb.put('gateways', defaultGateways)
await configDb.put('routers', defaultRouters)
await configDb.put('dnsJsonResolvers', defaultDnsJsonResolvers)
localStorage.removeItem(LOCAL_STORAGE_KEYS.config.enableWss)
await configDb.put('enableWss', defaultEnableWss)
localStorage.removeItem(LOCAL_STORAGE_KEYS.config.enableWebTransport)
await configDb.put('enableWebTransport', defaultEnableWebTransport)
localStorage.removeItem(LOCAL_STORAGE_KEYS.config.enableRecursiveGateways)
await configDb.put('enableRecursiveGateways', defaultEnableRecursiveGateways)
localStorage.removeItem(LOCAL_STORAGE_KEYS.config.enableGatewayProviders)
await configDb.put('enableGatewayProviders', defaultEnableGatewayProviders)
await configDb.put('debug', '')
configDb.close()
Expand Down
6 changes: 0 additions & 6 deletions src/lib/local-storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,6 @@ export function getLocalStorageKey (root: LocalStorageRoots, key: string): strin
}

export const LOCAL_STORAGE_KEYS = {
config: {
enableWss: getLocalStorageKey('config', 'enableWss'),
enableWebTransport: getLocalStorageKey('config', 'enableWebTransport'),
enableRecursiveGateways: getLocalStorageKey('config', 'enableRecursiveGateways'),
enableGatewayProviders: getLocalStorageKey('config', 'enableGatewayProviders')
},
forms: {
requestPath: getLocalStorageKey('forms', 'requestPath')
}
Expand Down
33 changes: 16 additions & 17 deletions src/pages/config.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,15 @@ import React, { useCallback, useContext, useEffect, useState } from 'react'
import Header from '../components/Header.jsx'
import { Collapsible } from '../components/collapsible.jsx'
import { InputSection } from '../components/input-section.jsx'
import { LocalStorageToggle } from '../components/local-storage-toggle.jsx'
import { InputToggle } from '../components/input-toggle.jsx'
import { ServiceWorkerReadyButton } from '../components/sw-ready-button.jsx'
import Input from '../components/textarea-input.jsx'
import { ConfigContext, ConfigProvider } from '../context/config-context.jsx'
import { RouteContext } from '../context/router-context.jsx'
import { ServiceWorkerProvider } from '../context/service-worker-context.jsx'
import { HeliaServiceWorkerCommsChannel } from '../lib/channel.js'
import { defaultEnableGatewayProviders, defaultEnableRecursiveGateways, defaultEnableWebTransport, defaultEnableWss, getConfig, localStorageToIdb, resetConfig } from '../lib/config-db.js'
import { getConfig, setConfig as storeConfig } from '../lib/config-db.js'
import { convertDnsResolverInputToObject, convertDnsResolverObjectToInput, convertUrlArrayToInput, convertUrlInputToArray } from '../lib/input-helpers.js'
import { LOCAL_STORAGE_KEYS } from '../lib/local-storage.js'
import { getUiComponentLogger, uiLogger } from '../lib/logger.js'
import './default-page-styles.css'

Expand Down Expand Up @@ -79,7 +78,7 @@ const dnsJsonValidationFn = (value: string): Error | null => {

function ConfigPage (): React.JSX.Element | null {
const { gotoPage } = useContext(RouteContext)
const { setConfig, gateways, routers, dnsJsonResolvers, debug } = useContext(ConfigContext)
const { setConfig, resetConfig, gateways, routers, dnsJsonResolvers, debug, enableGatewayProviders, enableRecursiveGateways, enableWss, enableWebTransport } = useContext(ConfigContext)
const [error, setError] = useState<Error | null>(null)
const [resetKey, setResetKey] = useState(0)

Expand Down Expand Up @@ -111,7 +110,7 @@ function ConfigPage (): React.JSX.Element | null {

const saveConfig = useCallback(async () => {
try {
await localStorageToIdb({ gateways, routers, dnsJsonResolvers, debug })
await storeConfig({ gateways, routers, dnsJsonResolvers, debug, enableGatewayProviders, enableRecursiveGateways, enableWss, enableWebTransport }, uiComponentLogger)
log.trace('config-page: sending RELOAD_CONFIG to service worker')
// update the BASE_URL service worker
await channel.messageAndWaitForResponse('SW', { target: 'SW', action: 'RELOAD_CONFIG' })
Expand Down Expand Up @@ -141,28 +140,28 @@ function ConfigPage (): React.JSX.Element | null {
<main className='e2e-config-page pa4-l bg-snow mw7 center pa4'>
<Collapsible collapsedLabel="View config" expandedLabel='Hide config' collapsed={isLoadedInIframe}>
<InputSection label='Direct Retrieval'>
<LocalStorageToggle
<InputToggle
className="e2e-config-page-input"
label="Enable Delegated HTTP Gateway Providers"
description="Use gateway providers returned from delegated routers for direct retrieval."
defaultValue={defaultEnableGatewayProviders}
localStorageKey={LOCAL_STORAGE_KEYS.config.enableGatewayProviders}
value={enableGatewayProviders}
onChange={(value) => { setConfig('enableGatewayProviders', value) }}
resetKey={resetKey}
/>
<LocalStorageToggle
<InputToggle
className="e2e-config-page-input"
label="Enable Secure WebSocket Providers"
description="Use Secure WebSocket providers returned from delegated routers for direct retrieval."
defaultValue={defaultEnableWss}
localStorageKey={LOCAL_STORAGE_KEYS.config.enableWss}
value={enableWss}
onChange={(value) => { setConfig('enableWss', value) }}
resetKey={resetKey}
/>
<LocalStorageToggle
<InputToggle
className="e2e-config-page-input"
label="Enable WebTransport Providers"
description="Use WebTransport providers returned from delegated routers for direct retrieval."
defaultValue={defaultEnableWebTransport}
localStorageKey={LOCAL_STORAGE_KEYS.config.enableWebTransport}
value={enableWebTransport}
onChange={(value) => { setConfig('enableWebTransport', value) }}
resetKey={resetKey}
/>
<Input
Expand All @@ -177,12 +176,12 @@ function ConfigPage (): React.JSX.Element | null {
/>
</InputSection>
<InputSection label='Fallback Retrieval'>
<LocalStorageToggle
<InputToggle
className="e2e-config-page-input"
label="Enable Recursive Gateways"
description="Use recursive gateways configured below for retrieval of content."
defaultValue={defaultEnableRecursiveGateways}
localStorageKey={LOCAL_STORAGE_KEYS.config.enableRecursiveGateways}
value={enableRecursiveGateways}
onChange={(value) => { setConfig('enableRecursiveGateways', value) }}
resetKey={resetKey}
/>
<Input
Expand Down

0 comments on commit 0f75ac7

Please sign in to comment.