@jsb188/app-settings-web 1.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json ADDED
@@ -0,0 +1,26 @@
1
+ {
2
+ "name": "@jsb188/app-settings-web",
3
+ "version": "1.1.2",
4
+ "description": "App settings module for web.",
5
+ "license": "ISC",
6
+ "author": "jsb188",
7
+ "type": "module",
8
+ "exports": {
9
+ ".": "./src/main.ts"
10
+ },
11
+ "peerDependencies": {
12
+ "@jsb188/app": "1.1.2",
13
+ "@jsb188/graphql": "1.1.2",
14
+ "@jsb188/react": "1.1.2",
15
+ "@jsb188/react-web": "1.1.2",
16
+ "jotai": "^2.20.2",
17
+ "react": "^19.3.0",
18
+ "react-dom": "^19.3.0",
19
+ "react-router": "^8.4.0",
20
+ "@jsb188/form": "1.1.2"
21
+ },
22
+ "scripts": {
23
+ "test": "echo \"Error: no test specified\" && exit 1",
24
+ "build": "tsc"
25
+ }
26
+ }
@@ -0,0 +1 @@
1
+ declare module '*.css';
package/src/main.ts ADDED
@@ -0,0 +1,3 @@
1
+ export * from './modules/AppSettingsLayout';
2
+ export * from './modules/AppSettingsTable';
3
+ export * from './modules/ChangeCredentialsLayout';
@@ -0,0 +1,331 @@
1
+ import { useIsKeyboardLayerActive } from '@jsb188/react/states/keyboardLayer';
2
+ import { useElementSize } from '@jsb188/react-web/hooks/use-element-size';
3
+ import { getErrorMessageContent } from '@jsb188/react-web/modules/layout/MainLayout';
4
+ import { Icon } from '@jsb188/react-web/svgs/Icon';
5
+ import Markdown from '@jsb188/react-web/ui/Markdown';
6
+ import { splitTableListGridTracks } from '@jsb188/react-web/modules/TableList.helpers';
7
+ import { getTableGridTemplateColumns, getTableWidthStyle } from '@jsb188/react-web/modules/table/layout';
8
+ import { TableDataCell, TableDataRow, TableEmptyCell, TableHeaderRow, TableRoot } from '@jsb188/react-web/ui/TableUI';
9
+ import type { ModalHandlerProps, OpenModalPopUpFn } from '@jsb188/react/states';
10
+ import { useClosePopOver } from '@jsb188/react/states';
11
+ import { useCallback, useEffect, useMemo, useState, type ComponentType, type ReactNode } from 'react';
12
+ import {
13
+ AppSettingsContentContainer,
14
+ AppSettingsFloatingSaveButton,
15
+ AppSettingsSideNav,
16
+ type AppSettingsSideNavOption,
17
+ } from '../ui/AppSettingsUI';
18
+
19
+ const FILE_CONSTANTS = {
20
+ mockRowCount: 10,
21
+ };
22
+
23
+ /**
24
+ * Types
25
+ */
26
+
27
+ interface ControllerState {
28
+ switchCase: string;
29
+ hasChanges: boolean;
30
+ saving: boolean;
31
+ saveCounter: number;
32
+ resetCounter: number;
33
+ }
34
+
35
+ export interface AppSettingsSwitchCaseProps extends ControllerState {
36
+ onSave: () => void;
37
+ onChangeDiff: (hasChanges?: boolean, saving?: boolean) => void;
38
+ openModalPopUp: OpenModalPopUpFn;
39
+ }
40
+
41
+ export interface AppSettingsTableContentProps {
42
+ notReady?: boolean;
43
+ gridLayoutStyle: string;
44
+ children?: ReactNode;
45
+ error?: any;
46
+ }
47
+
48
+ /*
49
+ * Match the settings table's gutter, header, row sizing, and dividers while data loads.
50
+ */
51
+ const AppSettingsTableMock = (p: { gridLayoutStyle: string }) => {
52
+ // Settings grids end with an actions track; the table primitives provide that track themselves.
53
+ const columns = useMemo(
54
+ () =>
55
+ splitTableListGridTracks(p.gridLayoutStyle)
56
+ .slice(0, -1)
57
+ .map((width, index) => ({
58
+ key: `mock-${index}`,
59
+ width,
60
+ header: {
61
+ headerContent: (
62
+ <span
63
+ className='mock alt bl min_w_20'
64
+ style={{ width: '40%' }}
65
+ >
66
+ ....
67
+ </span>
68
+ ),
69
+ },
70
+ })),
71
+ [p.gridLayoutStyle],
72
+ );
73
+
74
+ return (
75
+ <div
76
+ aria-busy='true'
77
+ className='-mx_50 min_w_0 ft_sm mt_md'
78
+ >
79
+ <div
80
+ aria-hidden
81
+ className='pl_40 min_w_0 rel'
82
+ >
83
+ <div className='abs_l w_40 bd_r_1 bd_lt noclick' />
84
+ <TableRoot style={{ gridTemplateColumns: getTableGridTemplateColumns(columns, {}), width: getTableWidthStyle(columns, {}) }}>
85
+ <TableHeaderRow
86
+ addHorizontalPadding
87
+ columns={columns}
88
+ showColumnDividers
89
+ />
90
+ <div className='table_grid_body'>
91
+ {Array.from({ length: FILE_CONSTANTS.mockRowCount }, (_, rowIndex) => (
92
+ <TableDataRow key={rowIndex}>
93
+ {columns.map((column, columnIndex) => (
94
+ <TableDataCell
95
+ key={column.key}
96
+ addHorizontalPadding
97
+ columnIndex={columnIndex}
98
+ isLastColumn={columnIndex === columns.length - 1}
99
+ showColumnDivider={columnIndex > 0}
100
+ showRowDivider
101
+ showBottomDivider={rowIndex === FILE_CONSTANTS.mockRowCount - 1}
102
+ >
103
+ <span
104
+ className='mock alt bl min_w_20'
105
+ style={{ width: `${50 + ((rowIndex + columnIndex) % 4) * 10}%` }}
106
+ >
107
+ ....
108
+ </span>
109
+ </TableDataCell>
110
+ ))}
111
+ <TableEmptyCell
112
+ showColumnDivider
113
+ showRowDivider
114
+ className={rowIndex === FILE_CONSTANTS.mockRowCount - 1 ? 'bd_b_1 bd_lt' : undefined}
115
+ />
116
+ </TableDataRow>
117
+ ))}
118
+ </div>
119
+ </TableRoot>
120
+ </div>
121
+ </div>
122
+ );
123
+ };
124
+
125
+ /**
126
+ * App settings table content helper with a built-in loading table state
127
+ */
128
+
129
+ export const AppSettingsTableContent = (p: AppSettingsTableContentProps) => {
130
+ const { notReady, gridLayoutStyle, children, error } = p;
131
+
132
+ if (notReady) {
133
+ if (error) {
134
+ const errObj = getErrorMessageContent(error);
135
+ return (
136
+ <div className='h_item gap_df'>
137
+ <div className='bd_2 bd_lt w_80 h_80 v_center r_df ic_lg ft_md rel pattern_texture medium_bf of'>
138
+ <span className='rel'>
139
+ <Icon
140
+ tryColor
141
+ name={errObj.titleIconName}
142
+ backupName='alert-circle'
143
+ />
144
+ </span>
145
+ </div>
146
+
147
+ <div className='lh_2'>
148
+ <div className='ft_medium ft_df mt_1 mb_4'>{errObj.title}</div>
149
+ <Markdown
150
+ as='p'
151
+ preset='article'
152
+ className='ft_sm cl_lt'
153
+ >
154
+ {errObj.message}
155
+ </Markdown>
156
+ </div>
157
+ </div>
158
+ );
159
+ }
160
+
161
+ return <AppSettingsTableMock gridLayoutStyle={gridLayoutStyle} />;
162
+ }
163
+
164
+ return children;
165
+ };
166
+
167
+ /**
168
+ * App settings layout
169
+ */
170
+
171
+ export const AppSettingsLayout = (
172
+ p: ModalHandlerProps & {
173
+ switchCase: string;
174
+ SwitchCaseComponent: ComponentType<AppSettingsSwitchCaseProps>;
175
+ options: AppSettingsSideNavOption[][];
176
+ // biome-ignore lint/suspicious/noConfusingVoidType: Ordinary void callbacks and an explicit false navigation veto are both supported.
177
+ onClickNavItem?: (value: string) => boolean | void; // If "false" is returned, it denies the switchCase change
178
+ },
179
+ ) => {
180
+ const { SwitchCaseComponent, openModalPopUp, options } = p;
181
+ const isKeyboardLayerActive = useIsKeyboardLayerActive();
182
+ const closePopOver = useClosePopOver();
183
+ const { elementRef: scrollAreaRef, rightInset } = useElementSize<HTMLDivElement>();
184
+ const { elementRef: saveBarRef, height: saveBarHeight } = useElementSize<HTMLDivElement>();
185
+
186
+ const [controller, setController] = useState<ControllerState & { mountCounter: number }>({
187
+ switchCase: p.switchCase,
188
+ hasChanges: false,
189
+ saving: false,
190
+ saveCounter: 0,
191
+ resetCounter: 0,
192
+ mountCounter: 0,
193
+ });
194
+ // Keep each draft's identity private and unique even when returning to a previously visited section.
195
+ const { mountCounter, ...screenController } = controller;
196
+
197
+ /*
198
+ * Switch sections only after the caller accepts the navigation.
199
+ */
200
+ const onClickNavItem = (value: string) => {
201
+ const handlerValue = p.onClickNavItem?.(value);
202
+ if (handlerValue !== false && value !== controller.switchCase) {
203
+ closePopOver();
204
+ setController((current) => ({
205
+ switchCase: value,
206
+ hasChanges: false,
207
+ saving: false,
208
+ saveCounter: 0,
209
+ resetCounter: 0,
210
+ mountCounter: current.mountCounter + 1,
211
+ }));
212
+ }
213
+ };
214
+
215
+ /*
216
+ * Request a save using the latest dirty and submission state.
217
+ */
218
+ const onSave = useCallback(() => {
219
+ setController((current) =>
220
+ current.hasChanges && !current.saving ? { ...current, saveCounter: current.saveCounter + 1 } : current,
221
+ );
222
+ }, []);
223
+
224
+ /*
225
+ * Discard the current draft by remounting the section once saving has finished.
226
+ */
227
+ const onReset = () => {
228
+ setController((current) =>
229
+ current.hasChanges && !current.saving
230
+ ? { ...current, hasChanges: false, resetCounter: current.resetCounter + 1, mountCounter: current.mountCounter + 1 }
231
+ : current,
232
+ );
233
+ };
234
+
235
+ /*
236
+ * Merge partial form status updates without overwriting queued changes or another section's state.
237
+ */
238
+ const onChangeDiff = (hasChanges?: boolean, saving?: boolean) => {
239
+ setController((current) => {
240
+ if (current.mountCounter !== mountCounter) {
241
+ return current;
242
+ }
243
+ const nextHasChanges = typeof hasChanges === 'boolean' ? hasChanges : current.hasChanges;
244
+ const nextSaving = typeof saving === 'boolean' ? saving : current.saving;
245
+ return current.hasChanges === nextHasChanges && current.saving === nextSaving
246
+ ? current
247
+ : { ...current, hasChanges: nextHasChanges, saving: nextSaving };
248
+ });
249
+ };
250
+
251
+ useEffect(() => {
252
+ /*
253
+ * Save settings only while this modal owns the keyboard.
254
+ */
255
+ const onKeyDown = (event: KeyboardEvent) => {
256
+ if (
257
+ !isKeyboardLayerActive(event) ||
258
+ event.defaultPrevented ||
259
+ event.isComposing ||
260
+ !(event.metaKey || event.ctrlKey) ||
261
+ event.key.toLowerCase() !== 's'
262
+ )
263
+ return;
264
+ event.preventDefault();
265
+ if (!event.repeat) {
266
+ onSave();
267
+ }
268
+ };
269
+ window.addEventListener('keydown', onKeyDown);
270
+ return () => window.removeEventListener('keydown', onKeyDown);
271
+ }, [isKeyboardLayerActive, onSave]);
272
+
273
+ useEffect(() => {
274
+ // Listen to scroll events inside scrollAreaRef
275
+
276
+ const scrollArea = scrollAreaRef.current;
277
+ if (!scrollArea) {
278
+ return;
279
+ }
280
+
281
+ /*
282
+ * Close the open popover without treating the scroll event as a dismissal filter.
283
+ */
284
+ const onScroll = () => closePopOver();
285
+ scrollArea.addEventListener('scroll', onScroll, { passive: true });
286
+
287
+ return () => {
288
+ scrollArea.removeEventListener('scroll', onScroll);
289
+ };
290
+ }, [closePopOver]);
291
+
292
+ return (
293
+ <div className='w_f h_top f rel of'>
294
+ <AppSettingsSideNav
295
+ selectedValue={controller.switchCase}
296
+ options={options}
297
+ onClickItem={onClickNavItem}
298
+ />
299
+
300
+ <div className='f h_f min_w_0 rel'>
301
+ <AppSettingsContentContainer
302
+ ref={scrollAreaRef}
303
+ addFooterPadding
304
+ addYOverflow
305
+ fadeBottom={controller.hasChanges}
306
+ bottomFadeOffset={saveBarHeight}
307
+ rightInset={rightInset}
308
+ >
309
+ <div className='f py_md px_50'>
310
+ <SwitchCaseComponent
311
+ key={mountCounter}
312
+ onSave={onSave}
313
+ onChangeDiff={onChangeDiff}
314
+ openModalPopUp={openModalPopUp}
315
+ {...screenController}
316
+ />
317
+ </div>
318
+ </AppSettingsContentContainer>
319
+
320
+ <AppSettingsFloatingSaveButton
321
+ ref={saveBarRef}
322
+ rightInset={rightInset}
323
+ hasChanges={controller.hasChanges}
324
+ saving={controller.saving}
325
+ onSave={onSave}
326
+ onReset={onReset}
327
+ />
328
+ </div>
329
+ </div>
330
+ );
331
+ };
@@ -0,0 +1,70 @@
1
+ import { useCurrentAccount } from '@jsb188/react/states';
2
+ import {
3
+ getEditableTableColumnWidthStorageKey,
4
+ getStoredEditableTableColumnWidths,
5
+ saveEditableTableColumnWidths,
6
+ } from '@jsb188/react-web/modules/TableList.helpers';
7
+ import type { EditableTableColumnWidthStorageConfig } from '@jsb188/react-web/modules/TableList';
8
+ import { getTableColumnPixelWidth } from '@jsb188/react-web/modules/table/layout';
9
+ import { useCallback, useMemo, useState } from 'react';
10
+ import { AppSettingsTableUI, type AppSettingsTableUIProps } from '../ui/AppSettingsTableUI';
11
+
12
+ export type AppSettingsTableProps = AppSettingsTableUIProps & {
13
+ columnWidthStorage?: EditableTableColumnWidthStorageConfig;
14
+ };
15
+
16
+ /*
17
+ * Preserve account-scoped column widths while presenting a nonvirtualized settings table.
18
+ */
19
+ export const AppSettingsTable = (p: AppSettingsTableProps) => {
20
+ const { columnWidthStorage, columnWidths, onColumnResizeCommit, ...tableProps } = p;
21
+ const { account } = useCurrentAccount();
22
+ const storageKey = getEditableTableColumnWidthStorageKey(account?.id, columnWidthStorage);
23
+ const [stored, setStored] = useState(() => ({ storageKey, widths: getStoredEditableTableColumnWidths(storageKey) }));
24
+ const columns = p.tableDesign.columns;
25
+
26
+ // Reset before rendering the child table so account/table switches never commit another scope's widths or defaults.
27
+ if (stored.storageKey !== storageKey) {
28
+ setStored({ storageKey, widths: getStoredEditableTableColumnWidths(storageKey) });
29
+ }
30
+
31
+ const savedColumnWidths = useMemo(() => {
32
+ if (stored.storageKey !== storageKey) return {};
33
+
34
+ return columns.reduce<Record<string, number>>((widths, column, index) => {
35
+ // Legacy widths use source indexes; flexible tracks must retain their natural sizing.
36
+ if (getTableColumnPixelWidth(column.width) !== null && Number.isFinite(stored.widths[index])) {
37
+ widths[column.key] = stored.widths[index];
38
+ }
39
+ return widths;
40
+ }, {});
41
+ }, [columns, storageKey, stored]);
42
+
43
+ /*
44
+ * Persist keyed VZTable widths in the existing source-index storage format.
45
+ */
46
+ const commitColumnWidths = useCallback(
47
+ (widths: Record<string, number>) => {
48
+ const indexedWidths = columns.reduce<Record<number, number>>((result, column, index) => {
49
+ if (getTableColumnPixelWidth(column.width) !== null && Number.isFinite(widths[column.key])) {
50
+ result[index] = widths[column.key];
51
+ }
52
+ return result;
53
+ }, {});
54
+ setStored({ storageKey, widths: indexedWidths });
55
+ saveEditableTableColumnWidths(storageKey, indexedWidths);
56
+ onColumnResizeCommit?.(widths);
57
+ },
58
+ [columns, onColumnResizeCommit, storageKey],
59
+ );
60
+
61
+ // Discard any in-progress resize when the account or table storage scope changes.
62
+ return (
63
+ <AppSettingsTableUI
64
+ key={storageKey}
65
+ {...tableProps}
66
+ columnWidths={columnWidths ?? savedColumnWidths}
67
+ onColumnResizeCommit={commitColumnWidths}
68
+ />
69
+ );
70
+ };
@@ -0,0 +1,347 @@
1
+ import i18n from '@jsb188/app/i18n/index.ts';
2
+ import { useConfirmPassword } from '@jsb188/graphql/hooks/use-auth-mtn';
3
+ import { FormOptions, Input, SMSCodeInput } from '@jsb188/form/modules/Form';
4
+ import { AlertPopUp, ModalErrorMessage } from '@jsb188/react-web/ui/ModalUI';
5
+ import type { ModalPopUpComponentProps } from '@jsb188/react/states';
6
+ import { useState } from 'react';
7
+
8
+ const FILE_CONSTANTS = {
9
+ smsCodeLength: 5,
10
+ };
11
+
12
+ export interface ConfirmPasswordProps extends ModalPopUpComponentProps {
13
+ confirmPasswordTitle?: string;
14
+ confirmPasswordMessage?: string;
15
+ onPasswordVerified?: (password: string) => void;
16
+ }
17
+
18
+ export interface ChangeCredentialsFinishedProps extends ModalPopUpComponentProps {
19
+ finishedIconName?: string;
20
+ finishedTitle?: string;
21
+ finishedMessage?: string;
22
+ }
23
+
24
+ export interface ChangeCredentialsProps extends ConfirmPasswordProps {
25
+ iconName: string;
26
+ skipPassword?: boolean;
27
+ title: string;
28
+ message: string;
29
+
30
+ finishedIconName?: string;
31
+ finishedTitle?: string;
32
+ finishedMessage?: string;
33
+
34
+ verifyIconName?: string;
35
+ verifyTitle?: string;
36
+ verifyMessage?: string;
37
+
38
+ confirmText?: string;
39
+ confirmSMSCodeText?: string;
40
+ status: 'WAITING_FOR_INPUT' | 'WAITING_FOR_VERIFICATION' | 'WAITING_FOR_SMS_CODE' | 'FINISHED';
41
+ onSubmit: (values: string[], confirmedPassword?: string) => void;
42
+ onSubmitSMSCode?: (smsCode: string, values: string[], confirmedPassword?: string) => void;
43
+
44
+ loading?: boolean;
45
+ error: any;
46
+ resetErrors: () => void;
47
+ inputs: (
48
+ | {
49
+ __type: 'TEXT_INPUT';
50
+ type?: 'text' | 'password';
51
+ label: string;
52
+ placeholder?: string;
53
+ }
54
+ | {
55
+ __type: 'OPTIONS_LIST';
56
+ label: string;
57
+ defaultValue?: string;
58
+ options: {
59
+ text: string;
60
+ value: string;
61
+ disabled?: boolean;
62
+ }[];
63
+ }
64
+ )[];
65
+ }
66
+
67
+ /**
68
+ * Render credential errors consistently across password, input, and SMS steps.
69
+ */
70
+
71
+ const CredentialsErrorMessage = (p: Pick<ChangeCredentialsProps, 'error' | 'resetErrors'>) =>
72
+ p.error ? (
73
+ <div className='px_md mt_md -mb_df'>
74
+ <ModalErrorMessage
75
+ error={p.error}
76
+ resetErrors={p.resetErrors}
77
+ />
78
+ </div>
79
+ ) : null;
80
+
81
+ /*
82
+ * Confirm the current password before changing sensitive account settings.
83
+ */
84
+
85
+ const ConfirmPasswordForm = (p: ConfirmPasswordProps) => {
86
+ const { onCloseModal, confirmPasswordTitle, confirmPasswordMessage, onPasswordVerified } = p;
87
+ const [password, setPassword] = useState('');
88
+
89
+ const { confirmPassword, error, resetErrors, saving } = useConfirmPassword({
90
+ onCompleted: (data: { confirmPassword?: boolean }, _error, variables) => {
91
+ if (data.confirmPassword && typeof variables?.password === 'string') {
92
+ onPasswordVerified?.(variables.password);
93
+ }
94
+ },
95
+ onError: () => {
96
+ setPassword('');
97
+ },
98
+ });
99
+
100
+ /*
101
+ * Share the same submission guard between the button and keyboard shortcut.
102
+ */
103
+ const onConfirmPassword = () => {
104
+ if (!password || saving) return;
105
+ confirmPassword({
106
+ variables: {
107
+ password,
108
+ },
109
+ });
110
+ };
111
+
112
+ /*
113
+ * Ignore repeated or composing Enter and prevent a second native submission.
114
+ */
115
+ const onPressEnter = (e: React.KeyboardEvent) => {
116
+ if (e.key !== 'Enter' || e.defaultPrevented || e.repeat || e.nativeEvent.isComposing) return;
117
+ e.preventDefault();
118
+ onConfirmPassword();
119
+ };
120
+
121
+ return (
122
+ <AlertPopUp
123
+ doNotExitOnConfirm
124
+ loading={saving}
125
+ iconName='password-lock-2'
126
+ confirmText={i18n.t('c.authenticate')}
127
+ cancelText={i18n.t('c.cancel')}
128
+ onConfirm={onConfirmPassword}
129
+ onCloseModal={onCloseModal}
130
+ disabledConfirm={!password || saving}
131
+ title={confirmPasswordTitle ?? i18n.t('account.enter_password')}
132
+ message={confirmPasswordMessage ?? i18n.t('account.enter_password_msg')}
133
+ >
134
+ <CredentialsErrorMessage
135
+ error={error}
136
+ resetErrors={resetErrors}
137
+ />
138
+
139
+ <div className='mt_df mx_md'>
140
+ <Input
141
+ type='password'
142
+ autoComplete='current-password'
143
+ disabled={saving}
144
+ label={i18n.t('account.password')}
145
+ placeholder='••••'
146
+ value={password}
147
+ onChange={(e) => setPassword(e.target.value)}
148
+ onKeyDown={onPressEnter}
149
+ autoFocus
150
+ />
151
+ </div>
152
+ </AlertPopUp>
153
+ );
154
+ };
155
+
156
+ /**
157
+ * Change account settings that require confirmations (such as credentials)
158
+ */
159
+
160
+ export const ChangeCredentialsLayout = (p: ChangeCredentialsProps) => {
161
+ const {
162
+ iconName,
163
+ skipPassword,
164
+ title,
165
+ message,
166
+ confirmText,
167
+ confirmSMSCodeText,
168
+ loading,
169
+ error,
170
+ resetErrors,
171
+ inputs,
172
+ onSubmit,
173
+ onSubmitSMSCode,
174
+ status,
175
+ finishedIconName,
176
+ finishedTitle,
177
+ finishedMessage,
178
+ verifyIconName,
179
+ verifyTitle,
180
+ verifyMessage,
181
+ onPasswordVerified,
182
+ ...rest
183
+ } = p;
184
+ const { onCloseModal } = rest;
185
+ const [confirmedPassword, setConfirmedPassword] = useState<string | null>(null);
186
+ const [smsCode, setSMSCode] = useState('');
187
+ const [values, setValues] = useState(() => inputs.map((input) => (input.__type === 'OPTIONS_LIST' ? input.defaultValue || '' : '')));
188
+ const hasValidInputs = inputs.length > 0 && inputs.every((_input, index) => !!values[index]?.trim());
189
+ const hasSMSCode = smsCode.length === FILE_CONSTANTS.smsCodeLength;
190
+
191
+ /*
192
+ * Retain the verified password and notify the caller when authentication completes.
193
+ */
194
+ const onVerified = (password: string) => {
195
+ setConfirmedPassword(password);
196
+ onPasswordVerified?.(password);
197
+ };
198
+
199
+ /*
200
+ * Preserve other field updates when React batches changes to multiple inputs.
201
+ */
202
+ const onChangeValue = (index: number, value: string) => {
203
+ setValues((current) => {
204
+ const nextValues = [...current];
205
+ nextValues[index] = value;
206
+ return nextValues;
207
+ });
208
+ };
209
+
210
+ /*
211
+ * Submit only complete credential values while no request is pending.
212
+ */
213
+ const onConfirm = () => {
214
+ if (!hasValidInputs || loading) return;
215
+ onSubmit(values, confirmedPassword ?? '');
216
+ };
217
+
218
+ /*
219
+ * Validate both automatic SMS submissions and explicit confirmation identically.
220
+ */
221
+ const onConfirmSMSCode = (code: string) => {
222
+ const normalizedCode = code.trim();
223
+ if (loading || normalizedCode.length !== FILE_CONSTANTS.smsCodeLength || !/^\d+$/.test(normalizedCode)) return;
224
+ onSubmitSMSCode?.(normalizedCode, values, confirmedPassword ?? '');
225
+ };
226
+
227
+ /*
228
+ * Use the button's validation and loading guards for keyboard submission too.
229
+ */
230
+ const onPressEnter = (e: React.KeyboardEvent) => {
231
+ if (e.key !== 'Enter' || e.defaultPrevented || e.repeat || e.nativeEvent.isComposing) return;
232
+ e.preventDefault();
233
+ onConfirm();
234
+ };
235
+
236
+ switch (status) {
237
+ case 'FINISHED':
238
+ return (
239
+ <AlertPopUp
240
+ onCloseModal={onCloseModal}
241
+ iconName={finishedIconName || 'circle-check'}
242
+ title={finishedTitle || i18n.t('c.success_')}
243
+ message={finishedMessage || i18n.t('c.your_request_is_completed_msg')}
244
+ />
245
+ );
246
+ case 'WAITING_FOR_VERIFICATION':
247
+ return (
248
+ <AlertPopUp
249
+ onCloseModal={onCloseModal}
250
+ iconName={verifyIconName || iconName}
251
+ title={verifyTitle || i18n.t('c.please_verify')}
252
+ message={verifyMessage || i18n.t('c.request_will_complete_once_verified_msg')}
253
+ />
254
+ );
255
+ case 'WAITING_FOR_SMS_CODE':
256
+ return (
257
+ <AlertPopUp
258
+ iconName={verifyIconName || iconName}
259
+ loading={loading}
260
+ onCloseModal={onCloseModal}
261
+ doNotExitOnConfirm
262
+ onConfirm={() => onConfirmSMSCode(smsCode)}
263
+ title={verifyTitle || i18n.t('c.please_verify')}
264
+ message={verifyMessage || i18n.t('c.request_will_complete_once_verified_msg')}
265
+ confirmText={confirmSMSCodeText || i18n.t('c.ok')}
266
+ cancelText={i18n.t('c.cancel')}
267
+ disabledConfirm={!hasSMSCode || loading || !onSubmitSMSCode}
268
+ >
269
+ <CredentialsErrorMessage
270
+ error={error}
271
+ resetErrors={resetErrors}
272
+ />
273
+
274
+ <div className='mt_md mx_md'>
275
+ <SMSCodeInput
276
+ codeLength={FILE_CONSTANTS.smsCodeLength}
277
+ saving={loading}
278
+ error={error}
279
+ onChangeCode={setSMSCode}
280
+ onSubmit={onConfirmSMSCode}
281
+ />
282
+ </div>
283
+ </AlertPopUp>
284
+ );
285
+ }
286
+
287
+ if (confirmedPassword === null && !skipPassword) {
288
+ return (
289
+ <ConfirmPasswordForm
290
+ {...rest}
291
+ onPasswordVerified={onVerified}
292
+ />
293
+ );
294
+ }
295
+
296
+ return (
297
+ <AlertPopUp
298
+ iconName={iconName}
299
+ doNotExitOnConfirm
300
+ loading={loading}
301
+ onCloseModal={onCloseModal}
302
+ onConfirm={onConfirm}
303
+ title={title}
304
+ message={message}
305
+ confirmText={confirmText}
306
+ cancelText={i18n.t('c.cancel')}
307
+ disabledConfirm={!hasValidInputs || loading}
308
+ >
309
+ <CredentialsErrorMessage
310
+ error={error}
311
+ resetErrors={resetErrors}
312
+ />
313
+
314
+ <div className='mt_df mx_md'>
315
+ {inputs.map((input, index) => {
316
+ if (input.__type === 'OPTIONS_LIST') {
317
+ return (
318
+ <FormOptions
319
+ key={index}
320
+ name={input.label}
321
+ label={input.label}
322
+ value={values[index]}
323
+ options={input.options}
324
+ disabled={loading}
325
+ onChange={(_e, _name, value) => onChangeValue(index, value === null ? '' : String(value))}
326
+ />
327
+ );
328
+ }
329
+
330
+ return (
331
+ <Input
332
+ key={index}
333
+ type={input.type || 'text'}
334
+ label={input.label}
335
+ placeholder={input.placeholder}
336
+ disabled={loading}
337
+ value={values[index]}
338
+ onChange={(e) => onChangeValue(index, e.target.value)}
339
+ onKeyDown={onPressEnter}
340
+ autoFocus={!index}
341
+ />
342
+ );
343
+ })}
344
+ </div>
345
+ </AlertPopUp>
346
+ );
347
+ };
@@ -0,0 +1,96 @@
1
+ import { cn } from '@jsb188/app/utils/string.ts';
2
+ import { VZTable } from '@jsb188/react-web/table/Table';
3
+ import { HorizontalScrollIndicators } from '@jsb188/react-web/modules/Scroll';
4
+ import { EndOfTableFooter, type TableDesign } from '@jsb188/react-web/ui/TableUI';
5
+ import { type ComponentProps, useCallback, useMemo, useRef, useState } from 'react';
6
+ import { createPortal } from 'react-dom';
7
+
8
+ export type AppSettingsTableUIProps = Omit<
9
+ ComponentProps<typeof VZTable>,
10
+ | 'fillAvailableRows'
11
+ | 'hasParentScrollArea'
12
+ | 'listDataOffset'
13
+ | 'listEndIndex'
14
+ | 'listStartIndex'
15
+ | 'tableDesign'
16
+ | 'virtualizedBody'
17
+ > & {
18
+ className?: string;
19
+ endOfListMessage?: string;
20
+ tableDesign: TableDesign;
21
+ };
22
+
23
+ /*
24
+ * Render an edge-to-edge settings table within the layout's existing scroll area.
25
+ */
26
+ export const AppSettingsTableUI = (p: AppSettingsTableUIProps) => {
27
+ const { className, endOfListMessage, footerNode, headers, tableDesign, ...tableProps } = p;
28
+ const loadedDataSize = p.listData?.length;
29
+ const tableAreaRef = useRef<HTMLDivElement>(null);
30
+ const scrollAreaRef = useRef<HTMLElement>(null);
31
+ const [indicatorFrame, setIndicatorFrame] = useState<HTMLElement | null>(null);
32
+
33
+ /*
34
+ * Bind the portal and scroll owner before indicator effects subscribe to its events.
35
+ */
36
+ const setTableAreaRef = useCallback((element: HTMLDivElement | null) => {
37
+ tableAreaRef.current = element;
38
+ const scrollArea = element?.closest<HTMLElement>('.app_scr') || null;
39
+ scrollAreaRef.current = scrollArea;
40
+ setIndicatorFrame(scrollArea?.parentElement || null);
41
+ }, []);
42
+ const renderHeaders = useMemo(
43
+ () => (headers === undefined ? tableDesign.columns.map((column) => column.header || {}) : headers),
44
+ [headers, tableDesign],
45
+ );
46
+ const renderDesign = useMemo(
47
+ () => ({ ...tableDesign, dividers: { rows: true, columns: true, ...tableDesign.dividers } }),
48
+ [tableDesign],
49
+ );
50
+
51
+ return (
52
+ <div className={cn('-mx_50 min_w_0 ft_sm', className)}>
53
+ <div
54
+ ref={setTableAreaRef}
55
+ className='pl_40 min_w_0 rel'
56
+ >
57
+ {/* Keep the gutter border scoped to the header and rows, above the footer. */}
58
+ <div
59
+ aria-hidden
60
+ className='abs_l w_40 bd_r_1 bd_lt noclick'
61
+ />
62
+ <VZTable
63
+ borderStyle='BORDER'
64
+ resizableColumns
65
+ rowMenuZClassName='z8'
66
+ showBottomDivider
67
+ {...tableProps}
68
+ headers={renderHeaders}
69
+ tableDesign={renderDesign}
70
+ hasParentScrollArea
71
+ />
72
+ </div>
73
+ {indicatorFrame &&
74
+ createPortal(
75
+ <HorizontalScrollIndicators
76
+ scrollRef={scrollAreaRef}
77
+ contentRef={tableAreaRef}
78
+ />,
79
+ indicatorFrame,
80
+ )}
81
+ {(footerNode || loadedDataSize !== undefined) && (
82
+ <div className='pl_40'>
83
+ {footerNode}
84
+ {loadedDataSize !== undefined && (
85
+ <EndOfTableFooter
86
+ alwaysShow
87
+ endOfListMessage={endOfListMessage}
88
+ loadedDataSize={loadedDataSize}
89
+ maxFetchLimit={Infinity}
90
+ />
91
+ )}
92
+ </div>
93
+ )}
94
+ </div>
95
+ );
96
+ };
@@ -0,0 +1,223 @@
1
+ import i18n from '@jsb188/app/i18n/index.ts';
2
+ import { cn } from '@jsb188/app/utils/string.ts';
3
+ import { Icon } from '@jsb188/react-web/svgs/Icon';
4
+ import type { ReactDivElement } from '@jsb188/react-web/types/dom.d';
5
+ import { ActivityDots, BigLoading } from '@jsb188/react-web/ui/Loading';
6
+ import { ShortcutKey } from '@jsb188/react-web/ui/OtherUI';
7
+ import { forwardRef, type CSSProperties } from 'react';
8
+
9
+ interface AppSettingsNavSubtitleProps {
10
+ __type: 'LIST_SUBTITLE';
11
+ text: string;
12
+ selected?: unknown;
13
+ value?: unknown;
14
+ onClick?: unknown;
15
+ }
16
+
17
+ interface AppSettingsNavItemProps {
18
+ __type: 'LIST_ITEM';
19
+ value: string;
20
+ iconName: string;
21
+ text: string;
22
+ rightIconName?: string;
23
+ selected?: boolean;
24
+ onClick?: (value: string) => void;
25
+ }
26
+
27
+ export type AppSettingsSideNavOption = AppSettingsNavSubtitleProps | AppSettingsNavItemProps;
28
+
29
+ interface AppSettingsFloatingSaveButtonProps {
30
+ hasChanges: boolean;
31
+ rightInset: number;
32
+ saving: boolean;
33
+ onSave: () => void;
34
+ onReset: () => void;
35
+ }
36
+
37
+ interface AppSettingsContentContainerProps extends ReactDivElement {
38
+ notReady?: boolean;
39
+ addFooterPadding?: boolean;
40
+ addYOverflow?: boolean;
41
+ fadeBottom?: boolean;
42
+ bottomFadeOffset?: number;
43
+ rightInset?: number;
44
+ }
45
+
46
+ /**
47
+ * Render the app settings content container.
48
+ */
49
+
50
+ export const AppSettingsContentContainer = forwardRef<HTMLDivElement, AppSettingsContentContainerProps>((p, ref) => {
51
+ const {
52
+ notReady,
53
+ addFooterPadding,
54
+ addYOverflow,
55
+ fadeBottom,
56
+ bottomFadeOffset = 0,
57
+ rightInset = 0,
58
+ className,
59
+ style,
60
+ children,
61
+ ...other
62
+ } = p;
63
+ return (
64
+ <div
65
+ ref={ref}
66
+ className={cn(
67
+ 'f h_f min_w_0 r_df mask_fade_bottom_200',
68
+ addYOverflow && 'app_scr auto_x',
69
+ addFooterPadding && 'pb_lg',
70
+ className,
71
+ notReady && 'v_center',
72
+ )}
73
+ style={
74
+ {
75
+ ...style,
76
+ '--mask-scrollbar-inset': `${rightInset}px`,
77
+ '--mask-bottom-offset': `${bottomFadeOffset}px`,
78
+ '--mask-fade-progress': fadeBottom ? 1 : 0,
79
+ } as CSSProperties
80
+ }
81
+ {...other}
82
+ >
83
+ {notReady ? <BigLoading color='alt' /> : children}
84
+ </div>
85
+ );
86
+ });
87
+
88
+ AppSettingsContentContainer.displayName = 'AppSettingsContentContainer';
89
+
90
+ /**
91
+ * Render one app settings navigation item.
92
+ */
93
+
94
+ const AppSettingsSideNavItem = (p: AppSettingsSideNavOption) => {
95
+ if (p.__type === 'LIST_SUBTITLE') {
96
+ return (
97
+ <div className='px_xs py_4 ml_2 mb_2 title'>
98
+ <span className='cl_lt ft_sm ft_medium'>{p.text}</span>
99
+ </div>
100
+ );
101
+ }
102
+
103
+ const { value, text, selected, onClick, iconName, rightIconName } = p;
104
+
105
+ return (
106
+ <button
107
+ type='button'
108
+ aria-current={selected ? 'page' : undefined}
109
+ disabled={!onClick}
110
+ className={cn('r_sm h_item mb_2 w_f link px_xs py_4', selected ? '_bg shadow_line_soft disabled cl_df' : 'bg_hv cl_df')}
111
+ onClick={onClick && !selected ? () => onClick(value) : undefined}
112
+ >
113
+ {iconName && (
114
+ <span className='w_25 h_center shift_left mr_4 ft_sm'>
115
+ <Icon name={iconName} />
116
+ </span>
117
+ )}
118
+
119
+ <span className='ellip pb_1 shift_down lh_1'>{text}</span>
120
+
121
+ {rightIconName && (
122
+ <span className='ic_sm ml_xs'>
123
+ <Icon name={rightIconName} />
124
+ </span>
125
+ )}
126
+ </button>
127
+ );
128
+ };
129
+
130
+ /**
131
+ * Render app settings side navigation.
132
+ */
133
+
134
+ export const AppSettingsSideNav = (p: {
135
+ selectedValue: string;
136
+ options: AppSettingsSideNavOption[][];
137
+ onClickItem: (value: string) => void;
138
+ }) => {
139
+ const { selectedValue, options, onClickItem } = p;
140
+
141
+ return (
142
+ <nav className='f_stretch w_270 py_lg bg_fade y_scr always'>
143
+ {options.map((list, i) => (
144
+ <div
145
+ className='px_df py_10'
146
+ key={i}
147
+ >
148
+ {list.map((item) => (
149
+ <AppSettingsSideNavItem
150
+ key={item.__type === 'LIST_ITEM' ? item.value : `subtitle_${item.text}`}
151
+ {...item}
152
+ selected={selectedValue === item.value}
153
+ onClick={onClickItem}
154
+ />
155
+ ))}
156
+ </div>
157
+ ))}
158
+ </nav>
159
+ );
160
+ };
161
+
162
+ /**
163
+ * Render app settings save and reset controls.
164
+ */
165
+
166
+ export const AppSettingsFloatingSaveButton = forwardRef<HTMLDivElement, AppSettingsFloatingSaveButtonProps>((p, ref) => {
167
+ const { hasChanges, rightInset, saving, onSave, onReset } = p;
168
+
169
+ return (
170
+ <div
171
+ ref={ref}
172
+ aria-hidden={!hasChanges}
173
+ inert={!hasChanges}
174
+ style={{ right: rightInset }}
175
+ className={cn(
176
+ 'abs_b mx_df p_12 bg_primary_fd_solid h_spread rt_df z1 anim_move_up_center target anim_inner spd_1',
177
+ hasChanges ? 'visible shadow_line_alt' : 'noclick',
178
+ )}
179
+ >
180
+ <div className='h_item px_xs'>{i18n.t('c.unsaved_changes_msg')}</div>
181
+
182
+ <div className='h_right'>
183
+ <div className='pill pill_sm h_center mr_xs'>
184
+ <button
185
+ type='button'
186
+ className='text'
187
+ disabled={!hasChanges || saving}
188
+ onClick={onReset}
189
+ >
190
+ <span className='h_right'>
191
+ <Icon name='arrow-back-up' />
192
+ <span className='ml_xs'>{i18n.t('c.undo_changes')}</span>
193
+ </span>
194
+ </button>
195
+ </div>
196
+
197
+ <button
198
+ type='button'
199
+ className={cn('pill pill_df r bg_primary', saving && 'loading')}
200
+ aria-busy={saving || undefined}
201
+ disabled={!hasChanges || saving}
202
+ onClick={onSave}
203
+ >
204
+ {saving && (
205
+ <div className='abs_full v_center'>
206
+ <ActivityDots />
207
+ </div>
208
+ )}
209
+ <span>
210
+ {/* Need the extra <span /> to use the :last-child rule in <ShortcutKey /> */}
211
+ {i18n.t('c.save_changes')}
212
+ </span>
213
+ <ShortcutKey
214
+ letter='S'
215
+ className='bg_darker_3 shift_up ml_7'
216
+ />
217
+ </button>
218
+ </div>
219
+ </div>
220
+ );
221
+ });
222
+
223
+ AppSettingsFloatingSaveButton.displayName = 'AppSettingsFloatingSaveButton';
package/tsconfig.json ADDED
@@ -0,0 +1,13 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ESNext",
4
+ "module": "ESNext",
5
+ "moduleResolution": "Bundler",
6
+ "allowImportingTsExtensions": true,
7
+ "jsx": "react-jsx",
8
+ "noEmit": true,
9
+ "strict": true,
10
+ "esModuleInterop": true
11
+ },
12
+ "include": ["src/**/*"]
13
+ }