// MyComponent.provider.tsx import { type ReactNode, useEffect, useState } from 'react'; import { post } from '../utils/post'; import { OptionsContextProvider } from './Options.context'; import { ScottyOptions } from './types'; type OptionsProviderProps = { children: ReactNode; }; export const OptionsProvider = ({ children }: OptionsProviderProps) => { const [options, setOptions] = useState(window.NSScottyPluginMantine.preferences); // get the preferences useEffect(() => { async function fetchOptions() { try { const response = await post('get_preferences'); setOptions(response); } catch (error) { // eslint-disable-next-line no-console -- surfaced for debugging; the UI shows its own error. console.error('Failed to load preferences:', error); } } fetchOptions(); }, []); function updateOptions(path: string, value: string) { const newOptions = () => { const newData: Record = { ...options }; let current: Record = newData; path.split('.').forEach((key: string, index: number, arr) => { if (index === arr.length - 1) { current[key] = value; } else { current[key] = { ...current[key] }; current = current[key]; } }); return newData; }; const data = newOptions(); post('update_preferences', { preferences: JSON.stringify(data) }).catch((error) => // eslint-disable-next-line no-console -- surfaced for debugging; the UI shows its own error. console.error('Failed to update preferences:', error) ); setOptions(data as ScottyOptions); } function getOptions(path: string) { return path.split('.').reduce((acc, key) => acc?.[key], options as Record); } function _setOptions(newOptions: any) { post('update_preferences', { preferences: JSON.stringify(newOptions) }).catch((error) => // eslint-disable-next-line no-console -- surfaced for debugging; the UI shows its own error. console.error('Failed to set preferences:', error) ); setOptions({ ...newOptions }); } async function resetOptions() { try { await post('reset_options'); const response = await post('get_preferences'); setOptions(response); } catch (error) { // eslint-disable-next-line no-console -- surfaced for debugging; the UI shows its own error. console.error('Failed to reset preferences:', error); } } return ( {children} ); };