Skip to content

Commit

Permalink
fix: avoid setting defaults in inputs
Browse files Browse the repository at this point in the history
  • Loading branch information
2color committed Oct 23, 2024
1 parent 89c79a3 commit cf4192c
Show file tree
Hide file tree
Showing 6 changed files with 16 additions and 31 deletions.
14 changes: 8 additions & 6 deletions src/components/local-storage-input.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useEffect, useState } from 'react'
import React, { useCallback, useEffect, useState } from 'react'

export interface LocalStorageInputProps extends React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement> {
localStorageKey: string
Expand Down Expand Up @@ -45,18 +45,20 @@ export default ({ resetKey, localStorageKey, label, placeholder, validationFn, d
validationFn = defaultValidationFunction
}

useEffect(() => {
const saveValue = useCallback((e: React.ChangeEvent<HTMLTextAreaElement>) => {
const newValue = e.target.value
try {
const err = validationFn?.(value)
const err = validationFn?.(newValue)
if (err != null) {
throw err
}
localStorage.setItem(localStorageKey, preSaveFormat?.(value) ?? value)
setValue(newValue)
localStorage.setItem(localStorageKey, preSaveFormat?.(newValue) ?? newValue)
setError(null)
} catch (err) {
setError(err as Error)
}
}, [value])
}, [validationFn, localStorageKey, preSaveFormat])

props = {
...props,
Expand All @@ -73,7 +75,7 @@ export default ({ resetKey, localStorageKey, label, placeholder, validationFn, d
name={localStorageKey}
placeholder={placeholder}
value={value}
onChange={(e) => { setValue(e.target.value) }}
onChange={saveValue}
/>
{error != null && <span className='db lh-copy red pt1 tr f6 w-100'>{error.message}</span>}
</div>
Expand Down
1 change: 0 additions & 1 deletion src/components/local-storage-toggle.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,6 @@ export const LocalStorageToggle: React.FC<LocalStorageToggleProps> = ({
function getLocalStorageValue (localStorageKey: string, defaultValue: boolean): boolean {
const savedValue = localStorage.getItem(localStorageKey)
if (savedValue == null) {
localStorage.setItem(localStorageKey, String(defaultValue))
return defaultValue
}

Expand Down
19 changes: 5 additions & 14 deletions src/lib/config-db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ export interface ConfigDb extends BaseDbConfig {
gateways: string[]
routers: string[]
dnsJsonResolvers: Record<string, string>
autoReload: boolean
enableWss: boolean
enableWebTransport: boolean
enableGatewayProviders: boolean
Expand All @@ -27,18 +26,17 @@ export const defaultEnableGatewayProviders = true

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

export async function loadConfigFromLocalStorage (): Promise<void> {
export async function localStorageToIdb (): Promise<void> {
if (typeof globalThis.localStorage !== 'undefined') {
await configDb.open()
const localStorage = globalThis.localStorage
const localStorageGatewaysString = localStorage.getItem(LOCAL_STORAGE_KEYS.config.gateways) ?? JSON.stringify(defaultGateways)
const localStorageRoutersString = localStorage.getItem(LOCAL_STORAGE_KEYS.config.routers) ?? JSON.stringify(defaultRouters)
const localStorageDnsResolvers = localStorage.getItem(LOCAL_STORAGE_KEYS.config.dnsJsonResolvers) ?? JSON.stringify(defaultDnsJsonResolvers)
const autoReload = localStorage.getItem(LOCAL_STORAGE_KEYS.config.autoReload) === 'true'
const enableRecursiveGateways = localStorage.getItem(LOCAL_STORAGE_KEYS.config.enableRecursiveGateways) === 'true'
const enableWss = localStorage.getItem(LOCAL_STORAGE_KEYS.config.enableWss) === 'true'
const enableWebTransport = localStorage.getItem(LOCAL_STORAGE_KEYS.config.enableWebTransport) === 'true'
const enableGatewayProviders = localStorage.getItem(LOCAL_STORAGE_KEYS.config.enableGatewayProviders) === 'true'
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'
const debug = localStorage.getItem(LOCAL_STORAGE_KEYS.config.debug) ?? ''
const gateways = JSON.parse(localStorageGatewaysString)
const routers = JSON.parse(localStorageRoutersString)
Expand All @@ -48,7 +46,6 @@ export async function loadConfigFromLocalStorage (): Promise<void> {
await configDb.put('gateways', gateways)
await configDb.put('routers', routers)
await configDb.put('dnsJsonResolvers', dnsJsonResolvers)
await configDb.put('autoReload', autoReload)
await configDb.put('enableRecursiveGateways', enableRecursiveGateways)
await configDb.put('enableWss', enableWss)
await configDb.put('enableWebTransport', enableWebTransport)
Expand All @@ -66,8 +63,6 @@ export async function resetConfig (): Promise<void> {
await configDb.put('routers', defaultRouters)
localStorage.removeItem(LOCAL_STORAGE_KEYS.config.dnsJsonResolvers)
await configDb.put('dnsJsonResolvers', defaultDnsJsonResolvers)
localStorage.removeItem(LOCAL_STORAGE_KEYS.config.autoReload)
await configDb.put('autoReload', false)
localStorage.removeItem(LOCAL_STORAGE_KEYS.config.enableWss)
await configDb.put('enableWss', defaultEnableWss)
localStorage.removeItem(LOCAL_STORAGE_KEYS.config.enableWebTransport)
Expand All @@ -94,7 +89,6 @@ export async function setConfig (config: ConfigDb, logger: ComponentLogger): Pro
await configDb.put('enableWss', config.enableWss)
await configDb.put('enableWebTransport', config.enableWebTransport)
await configDb.put('enableGatewayProviders', config.enableGatewayProviders)
await configDb.put('autoReload', config.autoReload)
await configDb.put('debug', config.debug ?? '')
configDb.close()
}
Expand All @@ -108,7 +102,6 @@ export async function getConfig (logger: ComponentLogger): Promise<ConfigDb> {
let enableWss
let enableWebTransport
let enableGatewayProviders
let autoReload = false

let debug = ''

Expand All @@ -126,7 +119,6 @@ export async function getConfig (logger: ComponentLogger): Promise<ConfigDb> {
enableWebTransport = await configDb.get('enableWebTransport') ?? defaultEnableWebTransport
enableGatewayProviders = await configDb.get('enableGatewayProviders') ?? defaultEnableGatewayProviders

autoReload = await configDb.get('autoReload') ?? false
debug = await configDb.get('debug') ?? ''
configDb.close()
debugLib.enable(debug)
Expand All @@ -150,7 +142,6 @@ export async function getConfig (logger: ComponentLogger): Promise<ConfigDb> {
gateways,
routers,
dnsJsonResolvers,
autoReload,
enableRecursiveGateways,
enableWss,
enableWebTransport,
Expand Down
1 change: 0 additions & 1 deletion src/lib/local-storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ export const LOCAL_STORAGE_KEYS = {
enableWebTransport: getLocalStorageKey('config', 'enableWebTransport'),
enableRecursiveGateways: getLocalStorageKey('config', 'enableRecursiveGateways'),
enableGatewayProviders: getLocalStorageKey('config', 'enableGatewayProviders'),
autoReload: getLocalStorageKey('config', 'autoReload'),
dnsJsonResolvers: getLocalStorageKey('config', 'dnsJsonResolvers'),
debug: getLocalStorageKey('config', 'debug')
},
Expand Down
4 changes: 2 additions & 2 deletions src/pages/config.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { 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 { defaultDnsJsonResolvers, defaultEnableGatewayProviders, defaultEnableRecursiveGateways, defaultEnableWebTransport, defaultEnableWss, defaultGateways, defaultRouters, getConfig, loadConfigFromLocalStorage, resetConfig } from '../lib/config-db.js'
import { defaultDnsJsonResolvers, defaultEnableGatewayProviders, defaultEnableRecursiveGateways, defaultEnableWebTransport, defaultEnableWss, defaultGateways, defaultRouters, getConfig, localStorageToIdb, resetConfig } from '../lib/config-db.js'
import { LOCAL_STORAGE_KEYS, convertDnsResolverInputToObject, convertDnsResolverObjectToInput, convertUrlArrayToInput, convertUrlInputToArray } from '../lib/local-storage.js'
import { getUiComponentLogger, uiLogger } from '../lib/logger.js'
import './default-page-styles.css'
Expand Down Expand Up @@ -113,7 +113,7 @@ function ConfigPage (): React.JSX.Element | null {

const saveConfig = useCallback(async () => {
try {
await loadConfigFromLocalStorage()
await localStorageToIdb()
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
8 changes: 1 addition & 7 deletions test-e2e/fixtures/set-sw-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
*
* Note that this was only tested and confirmed working for subdomain pages.
*/
import { getConfigAutoReloadInput, getConfigAutoReloadInputIframe, getConfigButton, getConfigButtonIframe, getConfigGatewaysInput, getConfigGatewaysInputIframe, getConfigPage, getConfigPageSaveButton, getConfigPageSaveButtonIframe, getConfigRoutersInput, getConfigRoutersInputIframe } from './locators.js'
import { getConfigAutoReloadInputIframe, getConfigButton, getConfigButtonIframe, getConfigGatewaysInput, getConfigGatewaysInputIframe, getConfigPage, getConfigPageSaveButton, getConfigPageSaveButtonIframe, getConfigRoutersInput, getConfigRoutersInputIframe } from './locators.js'
import { waitForServiceWorker } from './wait-for-service-worker.js'
import type { ConfigDb } from '../../src/lib/config-db.js'
import type { Page } from '@playwright/test'
Expand Down Expand Up @@ -35,12 +35,6 @@ export async function setConfigViaUi ({ page, config }: { page: Page, config: Pa
await getConfigButton(page).click()
await getConfigPage(page).isVisible()

for (const [key] of Object.entries(config)) {
if (key === 'autoReload') {
await getConfigAutoReloadInput(page).click()
}
}

await getConfigGatewaysInput(page).locator('input').fill(JSON.stringify([process.env.KUBO_GATEWAY]))
await getConfigRoutersInput(page).locator('input').fill(JSON.stringify([process.env.KUBO_GATEWAY]))

Expand Down

0 comments on commit cf4192c

Please sign in to comment.