@wwog/react 1.1.8 → 1.2.1
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/README.md +38 -1
- package/dist/index.d.mts +125 -26
- package/dist/index.js +1 -1
- package/package.json +2 -3
- package/src/ProcessControl/Toggle.tsx +116 -0
- package/src/ProcessControl/index.ts +2 -1
- package/src/hooks/index.ts +1 -0
- package/src/hooks/useControlled.ts +73 -0
- package/src/index.ts +1 -0
package/README.md
CHANGED
|
@@ -141,6 +141,35 @@ function Example({ isActive }) {
|
|
|
141
141
|
- `<True condition={...}>`:当 condition 为 true 时渲染子内容。
|
|
142
142
|
- `<False condition={...}>`:当 condition 为 false 时渲染子内容。
|
|
143
143
|
|
|
144
|
+
#### `<Toggle>` (v1.2.0+)
|
|
145
|
+
|
|
146
|
+
声明式切换组件,在预定义选项中切换值,并通过指定属性传递给子组件,支持自定义切换逻辑。
|
|
147
|
+
|
|
148
|
+
> v1.2.1 Indexing is now used to fix bugs with arbitrary values
|
|
149
|
+
|
|
150
|
+
```tsx
|
|
151
|
+
import { Toggle } from "@wwog/react";
|
|
152
|
+
|
|
153
|
+
interface ThemeChildProps {
|
|
154
|
+
theme: string;
|
|
155
|
+
toggleTheme: () => void;
|
|
156
|
+
}
|
|
157
|
+
const ThemeChild: React.FC<ThemeChildProps> = ({ theme, toggleTheme }) => (
|
|
158
|
+
<div onClick={toggleTheme}>当前主题: {theme}</div>
|
|
159
|
+
);
|
|
160
|
+
|
|
161
|
+
<Toggle source="light" options={["light", "dark"]} target="theme" toggleTarget="toggleTheme">
|
|
162
|
+
<ThemeChild />
|
|
163
|
+
</Toggle>
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
- `options`:可切换的值数组。
|
|
167
|
+
- `index`:默认:0。
|
|
168
|
+
- `target`:传递切换值给子节点的属性名,默认 value。
|
|
169
|
+
- `toggleTarget`:传递切换函数给子节点的属性名,默认 toggle。
|
|
170
|
+
- `next`:自定义切换逻辑函数。
|
|
171
|
+
- `children`:渲染内容。
|
|
172
|
+
|
|
144
173
|
### 通用组件
|
|
145
174
|
|
|
146
175
|
#### `<ArrayRender>`
|
|
@@ -265,12 +294,20 @@ function Layout() {
|
|
|
265
294
|
|
|
266
295
|
- Loop:灵活的迭代渲染,支持数组、对象和范围。
|
|
267
296
|
- Try:封装异步逻辑,处理 Promise 状态。
|
|
268
|
-
- Toggle:基于布尔状态切换 on 和 off 内容。
|
|
269
297
|
- Pick:轻量版值选择渲染,类似枚举匹配。
|
|
270
298
|
- Render:动态渲染函数,简化复杂渲染逻辑。
|
|
271
299
|
- Once:确保内容仅渲染一次,适合初始化。
|
|
272
300
|
- Each:增强列表渲染,支持过滤和排序。
|
|
273
301
|
|
|
302
|
+
### hooks
|
|
303
|
+
|
|
304
|
+
- 一些常用的hooks的封装
|
|
305
|
+
|
|
306
|
+
### useControlled (v1.2.0+)
|
|
307
|
+
|
|
308
|
+
- 受控组件和非受控组件的切换,方便组件开发
|
|
309
|
+
|
|
310
|
+
|
|
274
311
|
## License
|
|
275
312
|
|
|
276
313
|
MIT
|
package/dist/index.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import React, { ReactNode, FC } from 'react';
|
|
1
|
+
import React$1, { ReactNode, FC, Dispatch } from 'react';
|
|
2
2
|
|
|
3
3
|
interface SwitchProps<T> {
|
|
4
4
|
value: T;
|
|
@@ -7,7 +7,7 @@ interface SwitchProps<T> {
|
|
|
7
7
|
* @description_en optional compare function, default to () => a === b
|
|
8
8
|
**/
|
|
9
9
|
compare?: (a: T, b: T) => boolean;
|
|
10
|
-
children?: React.ReactNode;
|
|
10
|
+
children?: React$1.ReactNode;
|
|
11
11
|
/**
|
|
12
12
|
* @description 是否严格模式,默认 false.建议跟随开发环境变化,严格模式下,会循环所有节点来提供更多的错误提示
|
|
13
13
|
* @description_en strict mode, default to false. It is recommended to follow the development environment changes. In strict mode, all nodes will be looped to provide more error prompts
|
|
@@ -22,58 +22,58 @@ interface SwitchProps<T> {
|
|
|
22
22
|
}
|
|
23
23
|
interface SwitchCaseProps<T> {
|
|
24
24
|
value: T;
|
|
25
|
-
children?: React.ReactNode;
|
|
25
|
+
children?: React$1.ReactNode;
|
|
26
26
|
}
|
|
27
27
|
interface SwitchDefaultProps {
|
|
28
|
-
children?: React.ReactNode;
|
|
28
|
+
children?: React$1.ReactNode;
|
|
29
29
|
}
|
|
30
30
|
/**
|
|
31
31
|
* @description Switch 组件用于根据传入的 value 渲染不同的子组件
|
|
32
32
|
* @description_en The Switch component is used to render different child components based on the passed value
|
|
33
33
|
*/
|
|
34
34
|
declare const Switch: {
|
|
35
|
-
<T>(props: SwitchProps<T>): React.ReactElement | null;
|
|
35
|
+
<T>(props: SwitchProps<T>): React$1.ReactElement | null;
|
|
36
36
|
displayName: string;
|
|
37
37
|
Case: {
|
|
38
|
-
<T>(props: SwitchCaseProps<T>): React.ReactElement;
|
|
38
|
+
<T>(props: SwitchCaseProps<T>): React$1.ReactElement;
|
|
39
39
|
displayName: string;
|
|
40
40
|
};
|
|
41
41
|
Default: {
|
|
42
|
-
(props: SwitchDefaultProps): React.ReactElement;
|
|
42
|
+
(props: SwitchDefaultProps): React$1.ReactElement;
|
|
43
43
|
displayName: string;
|
|
44
44
|
};
|
|
45
45
|
createTyped<T>(): {
|
|
46
|
-
Switch: (props: SwitchProps<T>) => React.ReactElement | null;
|
|
47
|
-
Case: (props: SwitchCaseProps<T>) => React.ReactElement;
|
|
48
|
-
Default: (props: SwitchDefaultProps) => React.ReactElement;
|
|
46
|
+
Switch: (props: SwitchProps<T>) => React$1.ReactElement | null;
|
|
47
|
+
Case: (props: SwitchCaseProps<T>) => React$1.ReactElement;
|
|
48
|
+
Default: (props: SwitchDefaultProps) => React$1.ReactElement;
|
|
49
49
|
};
|
|
50
50
|
};
|
|
51
51
|
|
|
52
52
|
interface IfProps {
|
|
53
53
|
condition: boolean;
|
|
54
|
-
children?: React.ReactNode;
|
|
54
|
+
children?: React$1.ReactNode;
|
|
55
55
|
}
|
|
56
56
|
interface ThenProps {
|
|
57
|
-
children?: React.ReactNode;
|
|
57
|
+
children?: React$1.ReactNode;
|
|
58
58
|
}
|
|
59
59
|
interface ElseProps {
|
|
60
|
-
children?: React.ReactNode;
|
|
60
|
+
children?: React$1.ReactNode;
|
|
61
61
|
}
|
|
62
62
|
interface ElseIfProps {
|
|
63
63
|
condition: boolean;
|
|
64
|
-
children?: React.ReactNode;
|
|
64
|
+
children?: React$1.ReactNode;
|
|
65
65
|
}
|
|
66
66
|
declare const If: {
|
|
67
|
-
({ condition, children, }: IfProps): React.ReactElement | null;
|
|
67
|
+
({ condition, children, }: IfProps): React$1.ReactElement | null;
|
|
68
68
|
displayName: string;
|
|
69
|
-
Then: React.FC<ThenProps>;
|
|
70
|
-
ElseIf: React.FC<ElseIfProps>;
|
|
71
|
-
Else: React.FC<ElseProps>;
|
|
69
|
+
Then: React$1.FC<ThenProps>;
|
|
70
|
+
ElseIf: React$1.FC<ElseIfProps>;
|
|
71
|
+
Else: React$1.FC<ElseProps>;
|
|
72
72
|
createTyped(): {
|
|
73
|
-
If: (props: IfProps) => React.ReactElement | null;
|
|
74
|
-
Then: (props: ThenProps) => React.ReactElement;
|
|
75
|
-
ElseIf: (props: ElseIfProps) => React.ReactElement;
|
|
76
|
-
Else: (props: ElseProps) => React.ReactElement;
|
|
73
|
+
If: (props: IfProps) => React$1.ReactElement | null;
|
|
74
|
+
Then: (props: ThenProps) => React$1.ReactElement;
|
|
75
|
+
ElseIf: (props: ElseIfProps) => React$1.ReactElement;
|
|
76
|
+
Else: (props: ElseProps) => React$1.ReactElement;
|
|
77
77
|
};
|
|
78
78
|
};
|
|
79
79
|
interface TrueProps {
|
|
@@ -190,6 +190,78 @@ interface PipeProps {
|
|
|
190
190
|
*/
|
|
191
191
|
declare const Pipe: FC<PipeProps>;
|
|
192
192
|
|
|
193
|
+
interface ToggleProps<T = boolean> {
|
|
194
|
+
/**
|
|
195
|
+
* @description_en The initial value to toggle.
|
|
196
|
+
* @description_zh 初始切换值。
|
|
197
|
+
* @default 0
|
|
198
|
+
*/
|
|
199
|
+
index?: number;
|
|
200
|
+
/**
|
|
201
|
+
* @description_en Array of values to toggle between.
|
|
202
|
+
* @description_zh 可切换的值数组。
|
|
203
|
+
*/
|
|
204
|
+
options: T[];
|
|
205
|
+
/**
|
|
206
|
+
* @description_en The prop name to pass the toggled value to children.
|
|
207
|
+
* @description_zh 将切换后的值传递给子节点的属性名。
|
|
208
|
+
* @default 'value'
|
|
209
|
+
*/
|
|
210
|
+
target?: string;
|
|
211
|
+
/**
|
|
212
|
+
* @description_en The prop name to pass the toggle function to children.
|
|
213
|
+
* @description_zh 将切换函数传递给子节点的属性名。
|
|
214
|
+
* @default 'toggle'
|
|
215
|
+
*/
|
|
216
|
+
toggleTarget?: string;
|
|
217
|
+
/**
|
|
218
|
+
* @description_en Function to determine the next value index in the toggle sequence.
|
|
219
|
+
* @description_zh 确定切换序列中下一个值索引的函数。
|
|
220
|
+
* @optional
|
|
221
|
+
*/
|
|
222
|
+
next?: (curIndex: number, options: T[]) => number;
|
|
223
|
+
/**
|
|
224
|
+
* @description_en Content to render, receiving the toggled value and toggle function via the target and toggleTarget props.
|
|
225
|
+
* @description_zh 渲染的内容,通过 target 和 toggleTarget 属性接收切换后的值和切换函数。
|
|
226
|
+
*/
|
|
227
|
+
children: ReactNode;
|
|
228
|
+
}
|
|
229
|
+
/**
|
|
230
|
+
* @description_zh 一个声明式组件,用于在预定义选项中切换值并通过指定属性传递给子组件,支持自定义切换逻辑。
|
|
231
|
+
* @description_en A declarative component for toggling between predefined values and passing them to children via specified props, supporting custom toggle logic.
|
|
232
|
+
* @component
|
|
233
|
+
* @example
|
|
234
|
+
* ```tsx
|
|
235
|
+
* interface ThemeChildProps {
|
|
236
|
+
* theme: string;
|
|
237
|
+
* toggleTheme: () => void;
|
|
238
|
+
* }
|
|
239
|
+
* const ThemeChild: FC<ThemeChildProps> = ({ theme, toggleTheme }) => (
|
|
240
|
+
* <div onClick={toggleTheme}>当前主题: {theme}</div>
|
|
241
|
+
* );
|
|
242
|
+
*
|
|
243
|
+
* <Toggle source="light" options={["light", "dark"]} target="theme" toggleTarget="toggleTheme">
|
|
244
|
+
* <ThemeChild />
|
|
245
|
+
* </Toggle>
|
|
246
|
+
* ```
|
|
247
|
+
*
|
|
248
|
+
* @example
|
|
249
|
+
* ```tsx
|
|
250
|
+
* <Toggle
|
|
251
|
+
* source={1}
|
|
252
|
+
* options={[1, 2, 3]}
|
|
253
|
+
* target="value"
|
|
254
|
+
* toggleTarget="toggleValue"
|
|
255
|
+
* next={(currentIndex, options) => {
|
|
256
|
+
* return (currentIndex + 1) % options.length;
|
|
257
|
+
* }}
|
|
258
|
+
* >
|
|
259
|
+
* <ValueChild />
|
|
260
|
+
* </Toggle>
|
|
261
|
+
* ```
|
|
262
|
+
*/
|
|
263
|
+
declare const Toggle: <T>(props: ToggleProps<T>) => (string | number | bigint | Iterable<React$1.ReactNode> | Promise<string | number | bigint | boolean | React$1.ReactPortal | React$1.ReactElement<unknown, string | React$1.JSXElementConstructor<any>> | Iterable<React$1.ReactNode> | null | undefined> | React$1.ReactElement<unknown, string | React$1.JSXElementConstructor<any>>)[] | null | undefined;
|
|
264
|
+
|
|
193
265
|
interface SizeBoxProps {
|
|
194
266
|
size?: number | string;
|
|
195
267
|
height?: number | string;
|
|
@@ -206,7 +278,7 @@ declare const SizeBox: FC<SizeBoxProps>;
|
|
|
206
278
|
|
|
207
279
|
interface ArrayRenderProps<T> {
|
|
208
280
|
items: T[];
|
|
209
|
-
renderItem: (item: T, index: number) => React.ReactNode;
|
|
281
|
+
renderItem: (item: T, index: number) => React$1.ReactNode;
|
|
210
282
|
filter?: (item: T) => boolean;
|
|
211
283
|
}
|
|
212
284
|
declare function ArrayRender<T>(props: ArrayRenderProps<T>): ReactNode;
|
|
@@ -270,7 +342,34 @@ declare const Scope: FC<ScopeProps>;
|
|
|
270
342
|
* @description 性能优化,替代 React.Children.forEach, 回调可以返回 false 来中断循环
|
|
271
343
|
* @description_en Replace React.Children.forEach, the callback can return false to interrupt the loop
|
|
272
344
|
*/
|
|
273
|
-
declare function childrenLoop(children: React.ReactNode | undefined, callback: (child: React.ReactNode, index: number) => boolean | void): void;
|
|
345
|
+
declare function childrenLoop(children: React$1.ReactNode | undefined, callback: (child: React$1.ReactNode, index: number) => boolean | void): void;
|
|
346
|
+
|
|
347
|
+
interface UseControlledOptions<T> {
|
|
348
|
+
/**
|
|
349
|
+
* @description - 非受控模式下的默认值,会被受控模式下的值覆盖
|
|
350
|
+
* @description_en - Default value in uncontrolled mode, will be overridden by the value in controlled mode
|
|
351
|
+
*/
|
|
352
|
+
defaultValue: T;
|
|
353
|
+
/**
|
|
354
|
+
* @description - 值变更前的回调函数,可用于拦截或修改新值
|
|
355
|
+
* @description_en - Callback function before the value changes, can be used to intercept or modify the new value
|
|
356
|
+
*/
|
|
357
|
+
onBeforeChange?: (newValue: T, currentValue: T) => boolean | void;
|
|
358
|
+
/**
|
|
359
|
+
* @description - 当值发生变化时触发的回调函数名
|
|
360
|
+
* @description_en - Callback function name triggered when the value changes
|
|
361
|
+
* @default - onChange
|
|
362
|
+
*/
|
|
363
|
+
trigger?: string;
|
|
364
|
+
/**
|
|
365
|
+
* @description - 值的属性名
|
|
366
|
+
* @description_en - Property name of the value
|
|
367
|
+
* @default - value
|
|
368
|
+
*/
|
|
369
|
+
valuePropName?: string;
|
|
370
|
+
props: Record<string, any>;
|
|
371
|
+
}
|
|
372
|
+
declare function useControlled<T>(options: UseControlledOptions<T>): [T, Dispatch<React.SetStateAction<T>>];
|
|
274
373
|
|
|
275
|
-
export { ArrayRender, False, If, Pipe, Scope, SizeBox, Switch, True, When, childrenLoop };
|
|
276
|
-
export type { ArrayRenderProps, ElseIfProps, ElseProps, FalseProps, IfProps, PipeProps, ScopeProps, SwitchCaseProps, SwitchDefaultProps, SwitchProps, ThenProps, TrueProps, WhenProps };
|
|
374
|
+
export { ArrayRender, False, If, Pipe, Scope, SizeBox, Switch, Toggle, True, When, childrenLoop, useControlled };
|
|
375
|
+
export type { ArrayRenderProps, ElseIfProps, ElseProps, FalseProps, IfProps, PipeProps, ScopeProps, SwitchCaseProps, SwitchDefaultProps, SwitchProps, ThenProps, ToggleProps, TrueProps, UseControlledOptions, WhenProps };
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import n,{useMemo as
|
|
1
|
+
import n,{useMemo as y,useEffect as C,useState as S,Fragment as T,useCallback as x}from"react";function I(e,l){if(e===void 0)return;let t=0;if(Array.isArray(e)){for(const a of e)if(l(a,t++)===!1)break}else l(e,t)}const $=(e,l)=>e===l,g=e=>n.createElement(n.Fragment,null,e.children);g.displayName="Switch_Case";const E=e=>n.createElement(n.Fragment,null,e.children);E.displayName="Switch_Default";const p=e=>{const{value:l,compare:t=$,children:a,strict:o=!1}=e,r=new Set;let i=null,u=null,h=!1;return I(a,(s,d)=>{if(!n.isValidElement(s))throw new Error(`Switch Children only accepts valid React elements at index ${d}`);const c=s.type;if(c.displayName===g.displayName){const m=s.props;if(r.has(m.value))throw new Error(`Switch found duplicate Case value at index ${d}: ${JSON.stringify(m.value)}${o?" (detected in strict mode)":""}`);if(r.add(m.value),!i&&t(l,m.value)&&(i=m.children,o===!1))return!1}else if(c.displayName===E.displayName){if(h)throw new Error(`Switch can only have one Default child at index ${d}`);if(h=!0,u=s.props.children,!o&&i)return!1}else throw new Error(`Switch Children only accepts 'Case' or 'Default' elements, found: ${String(c.displayName||c.name||c)} at index ${d}`)}),n.createElement(n.Fragment,null,i??u)};p.displayName="Switch",p.Case=g,p.Default=E,p.createTyped=function(){return{Switch:p,Case:g,Default:E}};const w=e=>n.createElement(n.Fragment,null,e.children),N=({children:e})=>n.createElement(n.Fragment,null,e),v=e=>n.createElement(n.Fragment,null,e.children);w.displayName="If_Then",N.displayName="If_Else",v.displayName="If_ElseIf";const f=({condition:e,children:l})=>{let t=null,a=null;const o=[];if(n.Children.forEach(l,r=>{if(!n.isValidElement(r))throw new Error("If component only accepts valid React elements");const i=r.type;if(i.displayName===w.displayName){if(t)throw new Error("If component can only have one Then child");t=r}else if(i.displayName===v.displayName)o.push(r);else if(i.displayName===N.displayName){if(a)throw new Error("If component can only have one Else child");a=r}else throw new Error(`If component only accepts 'Then', 'ElseIf', or 'Else' elements as children, found: ${String(i.displayName||i.name||i)}`)}),e)return t?n.createElement(n.Fragment,null,t.props.children):null;for(const r of o)if(r.props.condition)return n.createElement(n.Fragment,null,r.props.children);return a?n.createElement(n.Fragment,null,a.props.children):null};f.displayName="If",f.Then=w,f.ElseIf=v,f.Else=N,f.createTyped=function(){return{If:f,Then:w,ElseIf:v,Else:N}};const b=({condition:e,children:l})=>e?n.createElement(n.Fragment,null,l):null,k=({condition:e,children:l})=>e===!1?n.createElement(n.Fragment,null,l):null,D=({all:e,any:l,none:t,children:a,fallback:o})=>y(()=>(e&&(l||t)&&console.warn('When: Multiple condition types (all, any, none) provided; "all" takes precedence.'),!!(e&&e.length>0&&e.every(Boolean)||l&&l.length>0&&l.some(Boolean)||t&&t.length>0&&t.every(r=>!r))),[e,l,t])?n.createElement(n.Fragment,null,a):n.createElement(n.Fragment,null,o||null),_=({data:e,transform:l,render:t,fallback:a})=>{const o=y(()=>l.reduce((r,i)=>i(r),e),[e,l]);return o==null?n.createElement(n.Fragment,null,a||null):n.createElement(n.Fragment,null,t(o))},A=e=>{const{index:l=0,options:t,target:a="value",toggleTarget:o="toggle",next:r,children:i}=e;C(()=>{if(t.length<l+1)throw new Error(`Index ${l} is out of bounds for options array of length ${t.length}. Defaulting to first option.`)},[l,t]);const[u,h]=S(l),s=()=>r?r(u,t):(u+1)%t.length,d=()=>{h(c=>t.length?s():c)};return n.Children.map(i,c=>n.isValidElement(c)?n.cloneElement(c,{[a]:u,[o]:d}):c)},B=e=>{const{children:l,h:t,w:a,size:o,height:r,width:i,className:u}=e;return n.createElement("div",{style:{width:o||a||i,height:o||t||r,flexShrink:0},className:u},l)};function O(e){const{items:l,renderItem:t,filter:a}=e;return l?n.createElement(T,null,l.map((o,r)=>a&&!a(o)?null:t(o,r))):(console.error("ArrayRender: items is null"),null)}const R=({let:e,props:l,children:t,fallback:a})=>{const o=y(()=>typeof e=="function"?e(l):e,[e,l]);return!t||!Object.keys(o).length?n.createElement(n.Fragment,null,a||null):n.createElement(n.Fragment,null,t(o))},V="onChange",P="value";function j(e){const{defaultValue:l,onBeforeChange:t,trigger:a=V,valuePropName:o=P,props:r}=e,i=Object.prototype.hasOwnProperty.call(r,o),[u,h]=S(l),s=i?r[o]:u,d=y(()=>r[a],[r,a]),c=x(m=>{const F=typeof m=="function"?m(s):m;t&&t(F,s)===!1||(i||h(F),d&&d(F))},[i,t,a,s,d]);return[s,c]}export{O as ArrayRender,k as False,f as If,_ as Pipe,R as Scope,B as SizeBox,p as Switch,A as Toggle,b as True,D as When,I as childrenLoop,j as useControlled};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@wwog/react",
|
|
3
|
-
"version": "1.1
|
|
3
|
+
"version": "1.2.1",
|
|
4
4
|
"description": "",
|
|
5
5
|
"keywords": [],
|
|
6
6
|
"author": "wwog",
|
|
@@ -19,8 +19,7 @@
|
|
|
19
19
|
"format": "biome format --write src",
|
|
20
20
|
"check": "biome check --apply src",
|
|
21
21
|
"test": "pnpm check && pnpm test:types && vitest run --coverage",
|
|
22
|
-
"test:types": "tsc --noEmit --skipLibCheck"
|
|
23
|
-
"preinstall": "npx only-allow pnpm"
|
|
22
|
+
"test:types": "tsc --noEmit --skipLibCheck"
|
|
24
23
|
},
|
|
25
24
|
"devDependencies": {
|
|
26
25
|
"@biomejs/biome": "^1.9.4",
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import React, { ReactNode, useState, useMemo, useEffect } from "react";
|
|
2
|
+
|
|
3
|
+
export interface ToggleProps<T = boolean> {
|
|
4
|
+
/**
|
|
5
|
+
* @description_en The initial value to toggle.
|
|
6
|
+
* @description_zh 初始切换值。
|
|
7
|
+
* @default 0
|
|
8
|
+
*/
|
|
9
|
+
index?: number;
|
|
10
|
+
/**
|
|
11
|
+
* @description_en Array of values to toggle between.
|
|
12
|
+
* @description_zh 可切换的值数组。
|
|
13
|
+
*/
|
|
14
|
+
options: T[];
|
|
15
|
+
/**
|
|
16
|
+
* @description_en The prop name to pass the toggled value to children.
|
|
17
|
+
* @description_zh 将切换后的值传递给子节点的属性名。
|
|
18
|
+
* @default 'value'
|
|
19
|
+
*/
|
|
20
|
+
target?: string;
|
|
21
|
+
/**
|
|
22
|
+
* @description_en The prop name to pass the toggle function to children.
|
|
23
|
+
* @description_zh 将切换函数传递给子节点的属性名。
|
|
24
|
+
* @default 'toggle'
|
|
25
|
+
*/
|
|
26
|
+
toggleTarget?: string;
|
|
27
|
+
/**
|
|
28
|
+
* @description_en Function to determine the next value index in the toggle sequence.
|
|
29
|
+
* @description_zh 确定切换序列中下一个值索引的函数。
|
|
30
|
+
* @optional
|
|
31
|
+
*/
|
|
32
|
+
next?: (curIndex: number, options: T[]) => number;
|
|
33
|
+
/**
|
|
34
|
+
* @description_en Content to render, receiving the toggled value and toggle function via the target and toggleTarget props.
|
|
35
|
+
* @description_zh 渲染的内容,通过 target 和 toggleTarget 属性接收切换后的值和切换函数。
|
|
36
|
+
*/
|
|
37
|
+
children: ReactNode;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* @description_zh 一个声明式组件,用于在预定义选项中切换值并通过指定属性传递给子组件,支持自定义切换逻辑。
|
|
42
|
+
* @description_en A declarative component for toggling between predefined values and passing them to children via specified props, supporting custom toggle logic.
|
|
43
|
+
* @component
|
|
44
|
+
* @example
|
|
45
|
+
* ```tsx
|
|
46
|
+
* interface ThemeChildProps {
|
|
47
|
+
* theme: string;
|
|
48
|
+
* toggleTheme: () => void;
|
|
49
|
+
* }
|
|
50
|
+
* const ThemeChild: FC<ThemeChildProps> = ({ theme, toggleTheme }) => (
|
|
51
|
+
* <div onClick={toggleTheme}>当前主题: {theme}</div>
|
|
52
|
+
* );
|
|
53
|
+
*
|
|
54
|
+
* <Toggle source="light" options={["light", "dark"]} target="theme" toggleTarget="toggleTheme">
|
|
55
|
+
* <ThemeChild />
|
|
56
|
+
* </Toggle>
|
|
57
|
+
* ```
|
|
58
|
+
*
|
|
59
|
+
* @example
|
|
60
|
+
* ```tsx
|
|
61
|
+
* <Toggle
|
|
62
|
+
* source={1}
|
|
63
|
+
* options={[1, 2, 3]}
|
|
64
|
+
* target="value"
|
|
65
|
+
* toggleTarget="toggleValue"
|
|
66
|
+
* next={(currentIndex, options) => {
|
|
67
|
+
* return (currentIndex + 1) % options.length;
|
|
68
|
+
* }}
|
|
69
|
+
* >
|
|
70
|
+
* <ValueChild />
|
|
71
|
+
* </Toggle>
|
|
72
|
+
* ```
|
|
73
|
+
*/
|
|
74
|
+
export const Toggle = <T,>(props: ToggleProps<T>) => {
|
|
75
|
+
const {
|
|
76
|
+
index = 0,
|
|
77
|
+
options,
|
|
78
|
+
target = "value",
|
|
79
|
+
toggleTarget = "toggle",
|
|
80
|
+
next,
|
|
81
|
+
children,
|
|
82
|
+
} = props;
|
|
83
|
+
|
|
84
|
+
useEffect(() => {
|
|
85
|
+
if (options.length < index + 1) {
|
|
86
|
+
throw new Error(
|
|
87
|
+
`Index ${index} is out of bounds for options array of length ${options.length}. Defaulting to first option.`
|
|
88
|
+
);
|
|
89
|
+
}
|
|
90
|
+
}, [index, options]);
|
|
91
|
+
|
|
92
|
+
const [curIndex, setCurIndex] = useState<number>(index);
|
|
93
|
+
const nextIndex = () => {
|
|
94
|
+
if (next) {
|
|
95
|
+
return next(curIndex, options);
|
|
96
|
+
}
|
|
97
|
+
return (curIndex + 1) % options.length;
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
const toggle = () => {
|
|
101
|
+
setCurIndex((prev) => {
|
|
102
|
+
if (!options.length) return prev;
|
|
103
|
+
return nextIndex();
|
|
104
|
+
});
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
return React.Children.map(children, (child) => {
|
|
108
|
+
if (React.isValidElement(child)) {
|
|
109
|
+
return React.cloneElement(child, {
|
|
110
|
+
[target]: curIndex,
|
|
111
|
+
[toggleTarget]: toggle,
|
|
112
|
+
} as { [key: string]: any });
|
|
113
|
+
}
|
|
114
|
+
return child;
|
|
115
|
+
});
|
|
116
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "./useControlled";
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { useCallback, useMemo, useState, type Dispatch } from "react";
|
|
2
|
+
|
|
3
|
+
const DEFAULT_TRIGGER = "onChange";
|
|
4
|
+
const DEFAULT_VALUE_PROP_NAME = "value";
|
|
5
|
+
|
|
6
|
+
export interface UseControlledOptions<T> {
|
|
7
|
+
/**
|
|
8
|
+
* @description - 非受控模式下的默认值,会被受控模式下的值覆盖
|
|
9
|
+
* @description_en - Default value in uncontrolled mode, will be overridden by the value in controlled mode
|
|
10
|
+
*/
|
|
11
|
+
defaultValue: T;
|
|
12
|
+
/**
|
|
13
|
+
* @description - 值变更前的回调函数,可用于拦截或修改新值
|
|
14
|
+
* @description_en - Callback function before the value changes, can be used to intercept or modify the new value
|
|
15
|
+
*/
|
|
16
|
+
onBeforeChange?: (newValue: T, currentValue: T) => boolean | void;
|
|
17
|
+
/**
|
|
18
|
+
* @description - 当值发生变化时触发的回调函数名
|
|
19
|
+
* @description_en - Callback function name triggered when the value changes
|
|
20
|
+
* @default - onChange
|
|
21
|
+
*/
|
|
22
|
+
trigger?: string;
|
|
23
|
+
/**
|
|
24
|
+
* @description - 值的属性名
|
|
25
|
+
* @description_en - Property name of the value
|
|
26
|
+
* @default - value
|
|
27
|
+
*/
|
|
28
|
+
valuePropName?: string;
|
|
29
|
+
props: Record<string, any>;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function useControlled<T>(
|
|
33
|
+
options: UseControlledOptions<T>
|
|
34
|
+
): [T, Dispatch<React.SetStateAction<T>>] {
|
|
35
|
+
const {
|
|
36
|
+
defaultValue,
|
|
37
|
+
onBeforeChange,
|
|
38
|
+
trigger = DEFAULT_TRIGGER,
|
|
39
|
+
valuePropName = DEFAULT_VALUE_PROP_NAME,
|
|
40
|
+
props,
|
|
41
|
+
} = options;
|
|
42
|
+
const isControlled = Object.prototype.hasOwnProperty.call(
|
|
43
|
+
props,
|
|
44
|
+
valuePropName
|
|
45
|
+
);
|
|
46
|
+
const [internalValue, setInternalValue] = useState<T>(defaultValue);
|
|
47
|
+
const value = isControlled ? props[valuePropName] : internalValue;
|
|
48
|
+
const onChange = useMemo(() => props[trigger], [props, trigger]);
|
|
49
|
+
|
|
50
|
+
const setValue = useCallback<Dispatch<React.SetStateAction<T>>>(
|
|
51
|
+
(newValue) => {
|
|
52
|
+
const resolvedValue =
|
|
53
|
+
typeof newValue === "function"
|
|
54
|
+
? (newValue as (prev: T) => T)(value)
|
|
55
|
+
: newValue;
|
|
56
|
+
if (onBeforeChange) {
|
|
57
|
+
const shouldProceed = onBeforeChange(resolvedValue, value);
|
|
58
|
+
if (shouldProceed === false) {
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
if (!isControlled) {
|
|
63
|
+
setInternalValue(resolvedValue);
|
|
64
|
+
}
|
|
65
|
+
if (onChange) {
|
|
66
|
+
onChange(resolvedValue);
|
|
67
|
+
}
|
|
68
|
+
},
|
|
69
|
+
[isControlled, onBeforeChange, trigger, value, onChange]
|
|
70
|
+
);
|
|
71
|
+
|
|
72
|
+
return [value, setValue];
|
|
73
|
+
}
|
package/src/index.ts
CHANGED