-
Notifications
You must be signed in to change notification settings - Fork 2
/
setting.component.tsx
256 lines (237 loc) · 8.4 KB
/
setting.component.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
import localizationDataService from '@shared/services/localization.service';
import { ChangeEvent, useCallback, useMemo, useState } from 'react';
import {
ProjectSettingNames,
ProjectSettingTypes,
SettingNames,
SettingTypes,
} from 'papi-shared-types';
import {
Checkbox,
Input,
LanguageInfo,
SettingsListItem,
UiLanguageSelector,
} from 'platform-bible-react';
import { debounce, getErrorMessage } from 'platform-bible-utils';
import { DataProviderUpdateInstructions } from '@shared/models/data-provider.model';
import { SettingDataTypes } from '@shared/services/settings.service-model';
import logger from '@shared/services/logger.service';
import { useData, useLocalizedStrings } from '@renderer/hooks/papi-hooks';
/** Props shared between the user and project setting components */
type BaseSettingProps<TSettingKey, TSettingValue> = {
/** Key of the setting */
settingKey: TSettingKey;
/** Setting label */
label: string;
/** Setting description */
description?: string;
/** Default value of the setting */
defaultSetting: TSettingValue;
};
/**
* Combines properties and controls with optional validation functions for both project and user
* settings
*/
type SettingProps<TProps, TControls, TValidateProject, TValidateUser> = TProps &
TControls & {
validateProjectSetting?: TValidateProject;
validateUserSetting?: TValidateUser;
};
/** Values of ProjectSettingTypes */
export type ProjectSettingValues = ProjectSettingTypes[keyof ProjectSettingTypes];
/** Props for the ProjectSetting component */
export type ProjectSettingProps = BaseSettingProps<ProjectSettingNames, ProjectSettingValues> & {
projectId: string;
};
/** Values from the useProjectSetting hook to manage the setting */
type ProjectSettingsControls = {
setting: ProjectSettingValues;
// Necessary for flexibility in handleChangeSetting, ProjectSettingValues and
// UserSettingValues are not the same so it couldn't assign
// eslint-disable-next-line @typescript-eslint/no-explicit-any
setSetting: ((newSetting: any) => void) | undefined;
isLoading: boolean;
};
/** Values of SettingTypes */
export type UserSettingValues = SettingTypes[keyof SettingTypes];
/** Props for the UserSetting component */
export type UserSettingProps = BaseSettingProps<SettingNames, UserSettingValues>;
/** Values from the useSetting hook to manage the setting */
type UserSettingsControls = {
setting: UserSettingValues;
// Necessary for flexibility in handleChangeSetting, ProjectSettingValues and
// UserSettingValues are not the same so it couldn't assign
// eslint-disable-next-line @typescript-eslint/no-explicit-any
setSetting: (newSetting: any) => Promise<DataProviderUpdateInstructions<SettingDataTypes>>;
isLoading: boolean;
};
/**
* Represents either project or user settings, includes properties, controls, and validation
* function
*/
type CombinedSettingProps =
| SettingProps<
Omit<ProjectSettingProps, 'defaultSetting' | 'projectId'>,
ProjectSettingsControls,
// Necessary for flexibility in handleChangeSetting, couldn't use unknown
// and keep types in ProjectSetting component
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(settingKey: any, newValue: any, currentValue: any) => Promise<boolean>,
never
>
| SettingProps<
Omit<UserSettingProps, 'defaultSetting'>,
UserSettingsControls,
never,
// Necessary for flexibility in handleChangeSetting, couldn't use unknown
// and keep types in ProjectSetting component
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(settingKey: any, newValue: any, currentValue: any) => Promise<boolean>
>;
/**
* Renders a setting component based on the type of setting (string, number, boolean, or object) and
* includes validating the setting and displaying errors
*/
export default function Setting({
settingKey,
setting,
setSetting,
isLoading,
validateUserSetting,
validateProjectSetting,
label,
description,
}: CombinedSettingProps) {
const validateSetting = validateUserSetting || validateProjectSetting;
const defaultLanguages: Record<string, LanguageInfo> = {
en: { autonym: 'English' },
es: { autonym: 'Español', uiNames: { en: 'Spanish', de: 'Spanisch' } },
fr: { autonym: 'Français', uiNames: { en: 'French', de: 'Französisch', es: 'francés' } },
};
const [languages, , isLoadingLanguages] = useData(
localizationDataService.dataProviderName,
).AvailableInterfaceLanguages(undefined, defaultLanguages);
const [errorMessage, setErrorMessage] = useState<string | undefined>(undefined);
/**
* Validate and change a setting
*
* @param event `ChangeEvent<HTMLInputElement>` is for `Input`; `boolean | 'indeterminate'` is for
* `Checkbox`
*/
const handleChangeSetting = async (
event: ChangeEvent<HTMLInputElement> | boolean | 'indeterminate',
) => {
let newValue: unknown;
if (typeof event === 'string')
// This event came from a `Checkbox` component. It should not be indeterminate
logger.warn(`Setting checkbox attempted to set to 'indeterminate' for some reason`);
else if (typeof event === 'boolean') {
// This event came from a `Checkbox` component
newValue = event;
} else {
// This event came from an `Input` component
const { value } = event.target;
if (typeof setting === 'number') {
const numericValue = parseInt(value, 10);
if (Number.isNaN(numericValue)) {
setErrorMessage('Invalid number');
return;
}
newValue = numericValue;
} else if (typeof setting === 'boolean' || typeof setting === 'string') {
newValue = value;
} else if (typeof setting === 'object') {
try {
newValue = JSON.parse(value);
} catch {
setErrorMessage('Invalid JSON');
return;
}
} else {
newValue = value;
}
}
try {
if (validateSetting && (await validateSetting(settingKey, newValue, setting))) {
setErrorMessage(undefined);
if (setSetting) setSetting(newValue);
} else {
setErrorMessage('Invalid value');
}
} catch (error) {
setErrorMessage(getErrorMessage(error));
}
};
const debouncedHandleChange = debounce(handleChangeSetting, 500);
const loadingSettingKey = '%settings_defaultMessage_loadingSetting%';
const selectFallbackLanguagesKey = '%settings_uiLanguageSelector_selectFallbackLanguages%';
const [localizedStrings] = useLocalizedStrings(
useMemo(() => [loadingSettingKey, selectFallbackLanguagesKey], []),
);
const localizedLoadingSetting = localizedStrings[loadingSettingKey];
const generateComponent = useCallback(() => {
let component = <p>No setting component</p>;
if (typeof setting === 'string' || typeof setting === 'number')
component = (
<Input key={settingKey} onChange={debouncedHandleChange} defaultValue={setting} />
);
else if (typeof setting === 'boolean')
component = (
<Checkbox
key={settingKey}
onCheckedChange={debouncedHandleChange}
defaultChecked={setting}
/>
);
else if (typeof setting === 'object')
if (Array.isArray(setting) && settingKey === 'platform.interfaceLanguage') {
component = (
<UiLanguageSelector
key={settingKey}
className="tw-w-64"
knownUiLanguages={languages}
primaryLanguage={setting[0]}
fallbackLanguages={setting.slice(1)}
handleLanguageChanges={(newUiLanguages) => {
if (!isLoadingLanguages) setSetting(newUiLanguages);
}}
localizedStrings={localizedStrings}
/>
);
} else {
component = (
<Input
key={settingKey}
onChange={debouncedHandleChange}
defaultValue={JSON.stringify(setting, undefined, 2)}
/>
);
}
return (
<div>
{component}
{errorMessage && <div style={{ color: 'red' }}>{errorMessage}</div>}
</div>
);
}, [
setting,
settingKey,
debouncedHandleChange,
errorMessage,
languages,
isLoadingLanguages,
localizedStrings,
setSetting,
]);
return (
<SettingsListItem
primary={label}
secondary={description}
isLoading={isLoading}
loadingMessage={localizedLoadingSetting}
>
{generateComponent()}
</SettingsListItem>
);
}