@wwog/react 1.1.6 → 1.1.7

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 CHANGED
@@ -5,6 +5,10 @@
5
5
  [![npm version](https://img.shields.io/npm/v/@wwog/react.svg)](https://www.npmjs.com/package/@wwog/react)
6
6
  [![ESM](https://img.shields.io/badge/📦-ESM%20only-brightgreen.svg)](https://nodejs.org/api/esm.html)
7
7
 
8
+ ---
9
+
10
+ [English Documentation](./README_en.md)
11
+
8
12
  ## 安装
9
13
 
10
14
  ```bash
@@ -161,6 +165,67 @@ function UserList({ users }) {
161
165
  }
162
166
  ```
163
167
 
168
+ #### `<Pipe>` (v1.1.7+)
169
+
170
+ 声明式的数据管道处理组件,适合多步骤数据转换和链式处理。
171
+
172
+ > 声明式数据处理,替代嵌套函数调用。
173
+ > 提高代码可读性,逻辑清晰。
174
+ > 适合数据清洗、格式化等场景。
175
+
176
+ ```tsx
177
+ import { Pipe } from "@wwog/react";
178
+
179
+ function Example({ users }) {
180
+ return (
181
+ <Pipe
182
+ data={users}
183
+ transform={[
184
+ (data) => data.filter(user => user.active),
185
+ (data) => data.map(user => user.name)
186
+ ]}
187
+ render={(names) => <div>{names.join(", ")}</div>}
188
+ fallback={<div>No Data</div>}
189
+ />
190
+ );
191
+ }
192
+ ```
193
+
194
+ - `data`:初始数据。
195
+ - `transform`:数据转换函数数组,按顺序依次处理。
196
+ - `render`:渲染最终结果。
197
+ - `fallback`:结果为 null/undefined 时的兜底内容。
198
+
199
+ #### `<Scope>` (v1.1.7+)
200
+
201
+ 为子节点提供局部作用域,声明式定义临时变量,简化复杂渲染逻辑。
202
+
203
+ > 避免在组件外定义临时状态或计算。
204
+ > 声明式定义局部变量,增强代码自包含性。
205
+ > 适合表单、计算密集型渲染等场景。
206
+
207
+ ```tsx
208
+ import { Scope } from "@wwog/react";
209
+
210
+ function Example() {
211
+ return (
212
+ <Scope let={{ count: 1, text: "Hello" }}>
213
+ {({ count, text }) => <div>{text} {count}</div>}
214
+ </Scope>
215
+ );
216
+ }
217
+
218
+ // 支持函数式 let
219
+ <Scope let={(props) => ({ total: props.items.length })} props={{ items: [1, 2] }} fallback={<div>Empty</div>}>
220
+ {({ total }) => <div>Total: {total}</div>}
221
+ </Scope>
222
+ ```
223
+
224
+ - `let`:对象或函数,定义作用域变量。
225
+ - `props`:传递给 let 函数的参数。
226
+ - `children`:作用域变量的渲染函数。
227
+ - `fallback`:无内容时的兜底渲染。
228
+
164
229
  #### `<SizeBox>`
165
230
 
166
231
  创建固定尺寸的容器,用于布局调整和间距控制。
@@ -184,6 +249,21 @@ function Layout() {
184
249
  }
185
250
  ```
186
251
 
252
+ ### Ideas
253
+
254
+ > 需求不高,但有用的组件
255
+
256
+ - Loop:灵活的迭代渲染,支持数组、对象和范围。
257
+ - Try:封装异步逻辑,处理 Promise 状态。
258
+ - Toggle:基于布尔状态切换 on 和 off 内容。
259
+ - Pick:轻量版值选择渲染,类似枚举匹配。
260
+ - Render:动态渲染函数,简化复杂渲染逻辑。
261
+ - Once:确保内容仅渲染一次,适合初始化。
262
+ - Each:增强列表渲染,支持过滤和排序。
263
+
264
+
187
265
  ## License
188
266
 
189
267
  MIT
268
+
269
+
package/dist/index.d.mts CHANGED
@@ -138,6 +138,58 @@ interface WhenProps {
138
138
  */
139
139
  declare const When: FC<WhenProps>;
140
140
 
141
+ /**
142
+ * Props for the `Pipe` component.
143
+ *
144
+ * @interface PipeProps
145
+ * @property {any} data - The initial data to process.
146
+ * @property {((input: any) => any)[]} transform - Array of functions to transform the data.
147
+ * @property {(result: any) => ReactNode} render - Function to render the transformed data.
148
+ * @property {ReactNode} [fallback] - Content to render if the result is null or undefined.
149
+ */
150
+ interface PipeProps {
151
+ /**
152
+ * @description_en The initial data to process.
153
+ * @description_zh 要处理的初始数据。
154
+ */
155
+ data: any;
156
+ /**
157
+ * @description_en Array of functions to transform the data.
158
+ * @description_zh 转换数据的函数数组。
159
+ */
160
+ transform: ((input: any) => any)[];
161
+ /**
162
+ * @description_en Function to render the transformed data.
163
+ * @description_zh 渲染转换后数据的函数。
164
+ */
165
+ render: (result: any) => ReactNode;
166
+ /**
167
+ * @description_en Content to render if the result is null or undefined.
168
+ * @description_zh 如果结果为 null 或 undefined 时渲染的内容。
169
+ * @optional
170
+ * @default null
171
+ */
172
+ fallback?: ReactNode;
173
+ }
174
+ /**
175
+ * @description_zh 一个声明式组件,用于通过管道式处理数据并渲染,简化多步骤数据转换。
176
+ * @description_en A declarative component for processing data through a pipeline and rendering, simplifying multi-step data transformations.
177
+ * @component
178
+ * @example
179
+ * ```tsx
180
+ * <Pipe
181
+ * data={users}
182
+ * transform={[
183
+ * (data) => data.filter(user => user.active),
184
+ * (data) => data.map(user => user.name)
185
+ * ]}
186
+ * render={(names) => <div>{names.join(", ")}</div>}
187
+ * fallback={<div>No Data</div>}
188
+ * />
189
+ * ```
190
+ */
191
+ declare const Pipe: FC<PipeProps>;
192
+
141
193
  interface SizeBoxProps {
142
194
  size?: number | string;
143
195
  height?: number | string;
@@ -158,11 +210,66 @@ interface ArrayRenderProps<T> {
158
210
  }
159
211
  declare function ArrayRender<T>(props: ArrayRenderProps<T>): ReactNode;
160
212
 
213
+ /**
214
+ * Props for the `Scope` component.
215
+ *
216
+ * @interface ScopeProps
217
+ * @property {Record<string, any> | ((props: any) => Record<string, any>)} let - An object or function defining local variables for the scope.
218
+ * @property {any} [props] - Optional props passed to the let function.
219
+ * @property {(scope: Record<string, any>) => ReactNode} [children] - Render function to access the scope variables.
220
+ * @property {ReactNode} [fallback] - Content to render if children or scope is empty.
221
+ */
222
+ interface ScopeProps {
223
+ /**
224
+ * @description_en An object or function defining local variables for the scope.
225
+ * @description_zh 定义作用域局部变量的对象或函数。
226
+ */
227
+ let: Record<string, any> | ((props: any) => Record<string, any>);
228
+ /**
229
+ * @description_en Optional props passed to the let function.
230
+ * @description_zh 传递给 let 函数的可选属性。
231
+ * @optional
232
+ */
233
+ props?: any;
234
+ /**
235
+ * @description_en Render function to access the scope variables.
236
+ * @description_zh 访问作用域变量的渲染函数。
237
+ * @optional
238
+ */
239
+ children?: (scope: Record<string, any>) => ReactNode;
240
+ /**
241
+ * @description_en Content to render if children or scope is empty.
242
+ * @description_zh 如果 children 或 scope 为空时渲染的内容。
243
+ * @optional
244
+ * @default null
245
+ */
246
+ fallback?: ReactNode;
247
+ }
248
+ /**
249
+ * @description_zh 一个声明式组件,为子节点提供局部作用域,简化临时状态或上下文管理。
250
+ * @description_en A declarative component that provides a local scope for children, simplifying temporary state or context management.
251
+ * @component
252
+ * @example
253
+ * ```tsx
254
+ * <Scope let={{ count: 1, text: "Hello" }}>
255
+ * {({ count, text }) => <div>{text} {count}</div>}
256
+ * </Scope>
257
+ * ```
258
+ *
259
+ * @example
260
+ * ```tsx
261
+ * <Scope let={(props) => ({ total: props.items.length })} props={{ items: [1, 2] }} fallback={<div>Empty</div>}>
262
+ * {({ total }) => <div>Total: {total}</div>}
263
+ * </Scope>
264
+ * ```
265
+ */
266
+ declare const Scope: FC<ScopeProps>;
267
+
161
268
  /**
162
269
  * @description 性能优化,替代 React.Children.forEach, 回调可以返回 false 来中断循环
163
270
  * @description_en Replace React.Children.forEach, the callback can return false to interrupt the loop
164
271
  */
165
272
  declare function childrenLoop(children: React.ReactNode | undefined, callback: (child: React.ReactNode, index: number) => boolean | void): void;
166
273
 
167
- export { ArrayRender, False, If, SizeBox, Switch, True, When, childrenLoop };
168
- export type { ArrayRenderProps, ElseIfProps, ElseProps, FalseProps, IfProps, SwitchCaseProps, SwitchDefaultProps, SwitchProps, ThenProps, TrueProps, WhenProps };
274
+ export { ArrayRender, False, If, Pipe, Scope, SizeBox, Switch, True, When, childrenLoop };
275
+ export type { ArrayRenderProps, ElseIfProps, ElseProps, FalseProps, IfProps, PipeProps, ScopeProps, SwitchCaseProps, SwitchDefaultProps, SwitchProps, ThenProps, TrueProps, WhenProps };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import n,{useMemo as F,Fragment as I}from"react";function v(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 S=(e,l)=>e===l,f=e=>n.createElement(n.Fragment,null,e.children);f.displayName="Switch_Case";const p=e=>n.createElement(n.Fragment,null,e.children);p.displayName="Switch_Default";const c=e=>{const{value:l,compare:t=S,children:a,strict:i=!1}=e,r=new Set;let o=null,g=null,N=!1;return v(a,(h,u)=>{if(!n.isValidElement(h))throw new Error(`Switch Children only accepts valid React elements at index ${u}`);const d=h.type;if(d.displayName===f.displayName){const m=h.props;if(r.has(m.value))throw new Error(`Switch found duplicate Case value at index ${u}: ${JSON.stringify(m.value)}${i?" (detected in strict mode)":""}`);if(r.add(m.value),!o&&t(l,m.value)&&(o=m.children,i===!1))return!1}else if(d.displayName===p.displayName){if(N)throw new Error(`Switch can only have one Default child at index ${u}`);if(N=!0,g=h.props.children,!i&&o)return!1}else throw new Error(`Switch Children only accepts 'Case' or 'Default' elements, found: ${String(d.displayName||d.name||d)} at index ${u}`)}),n.createElement(n.Fragment,null,o??g)};c.displayName="Switch",c.Case=f,c.Default=p,c.createTyped=function(){return{Switch:c,Case:f,Default:p}};const y=e=>n.createElement(n.Fragment,null,e.children),E=({children:e})=>n.createElement(n.Fragment,null,e),w=e=>n.createElement(n.Fragment,null,e.children);y.displayName="If_Then",E.displayName="If_Else",w.displayName="If_ElseIf";const s=({condition:e,children:l})=>{let t=null,a=null;const i=[];if(n.Children.forEach(l,r=>{if(!n.isValidElement(r))throw new Error("If component only accepts valid React elements");const o=r.type;if(o.displayName===y.displayName){if(t)throw new Error("If component can only have one Then child");t=r}else if(o.displayName===w.displayName)i.push(r);else if(o.displayName===E.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(o.displayName||o.name||o)}`)}),e)return t?n.createElement(n.Fragment,null,t.props.children):null;for(const r of i)if(r.props.condition)return n.createElement(n.Fragment,null,r.props.children);return a?n.createElement(n.Fragment,null,a.props.children):null};s.displayName="If",s.Then=y,s.ElseIf=w,s.Else=E,s.createTyped=function(){return{If:s,Then:y,ElseIf:w,Else:E}};const C=({condition:e,children:l})=>e?n.createElement(n.Fragment,null,l):null,T=({condition:e,children:l})=>e===!1?n.createElement(n.Fragment,null,l):null,x=({all:e,any:l,none:t,children:a,fallback:i})=>F(()=>(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,i||null),$=e=>{const{children:l,h:t,w:a,size:i,height:r,width:o}=e;return n.createElement("div",{style:{width:i||a||o,height:i||t||r}},l)};function D(e){const{items:l,renderItem:t,filter:a}=e;return l?n.createElement(I,null,l.map((i,r)=>a&&!a(i)?null:t(i,r))):(console.error("ArrayRender: items is null"),null)}export{D as ArrayRender,T as False,s as If,$ as SizeBox,c as Switch,C as True,x as When,v as childrenLoop};
1
+ import n,{useMemo as g,Fragment as S}from"react";function v(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 I=(e,l)=>e===l,f=e=>n.createElement(n.Fragment,null,e.children);f.displayName="Switch_Case";const p=e=>n.createElement(n.Fragment,null,e.children);p.displayName="Switch_Default";const s=e=>{const{value:l,compare:t=I,children:a,strict:r=!1}=e,i=new Set;let c=null,N=null,F=!1;return v(a,(u,h)=>{if(!n.isValidElement(u))throw new Error(`Switch Children only accepts valid React elements at index ${h}`);const d=u.type;if(d.displayName===f.displayName){const m=u.props;if(i.has(m.value))throw new Error(`Switch found duplicate Case value at index ${h}: ${JSON.stringify(m.value)}${r?" (detected in strict mode)":""}`);if(i.add(m.value),!c&&t(l,m.value)&&(c=m.children,r===!1))return!1}else if(d.displayName===p.displayName){if(F)throw new Error(`Switch can only have one Default child at index ${h}`);if(F=!0,N=u.props.children,!r&&c)return!1}else throw new Error(`Switch Children only accepts 'Case' or 'Default' elements, found: ${String(d.displayName||d.name||d)} at index ${h}`)}),n.createElement(n.Fragment,null,c??N)};s.displayName="Switch",s.Case=f,s.Default=p,s.createTyped=function(){return{Switch:s,Case:f,Default:p}};const y=e=>n.createElement(n.Fragment,null,e.children),E=({children:e})=>n.createElement(n.Fragment,null,e),w=e=>n.createElement(n.Fragment,null,e.children);y.displayName="If_Then",E.displayName="If_Else",w.displayName="If_ElseIf";const o=({condition:e,children:l})=>{let t=null,a=null;const r=[];if(n.Children.forEach(l,i=>{if(!n.isValidElement(i))throw new Error("If component only accepts valid React elements");const c=i.type;if(c.displayName===y.displayName){if(t)throw new Error("If component can only have one Then child");t=i}else if(c.displayName===w.displayName)r.push(i);else if(c.displayName===E.displayName){if(a)throw new Error("If component can only have one Else child");a=i}else throw new Error(`If component only accepts 'Then', 'ElseIf', or 'Else' elements as children, found: ${String(c.displayName||c.name||c)}`)}),e)return t?n.createElement(n.Fragment,null,t.props.children):null;for(const i of r)if(i.props.condition)return n.createElement(n.Fragment,null,i.props.children);return a?n.createElement(n.Fragment,null,a.props.children):null};o.displayName="If",o.Then=y,o.ElseIf=w,o.Else=E,o.createTyped=function(){return{If:o,Then:y,ElseIf:w,Else:E}};const C=({condition:e,children:l})=>e?n.createElement(n.Fragment,null,l):null,T=({condition:e,children:l})=>e===!1?n.createElement(n.Fragment,null,l):null,k=({all:e,any:l,none:t,children:a,fallback:r})=>g(()=>(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(i=>!i))),[e,l,t])?n.createElement(n.Fragment,null,a):n.createElement(n.Fragment,null,r||null),x=({data:e,transform:l,render:t,fallback:a})=>{const r=g(()=>l.reduce((i,c)=>c(i),e),[e,l]);return r==null?n.createElement(n.Fragment,null,a||null):n.createElement(n.Fragment,null,t(r))},$=e=>{const{children:l,h:t,w:a,size:r,height:i,width:c}=e;return n.createElement("div",{style:{width:r||a||c,height:r||t||i}},l)};function b(e){const{items:l,renderItem:t,filter:a}=e;return l?n.createElement(S,null,l.map((r,i)=>a&&!a(r)?null:t(r,i))):(console.error("ArrayRender: items is null"),null)}const D=({let:e,props:l,children:t,fallback:a})=>{const r=g(()=>typeof e=="function"?e(l):e,[e,l]);return!t||!Object.keys(r).length?n.createElement(n.Fragment,null,a||null):n.createElement(n.Fragment,null,t(r))};export{b as ArrayRender,T as False,o as If,x as Pipe,D as Scope,$ as SizeBox,s as Switch,C as True,k as When,v as childrenLoop};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wwog/react",
3
- "version": "1.1.6",
3
+ "version": "1.1.7",
4
4
  "description": "",
5
5
  "keywords": [],
6
6
  "author": "wwog",
@@ -0,0 +1,77 @@
1
+ import React, { FC, ReactNode, useMemo } from "react";
2
+
3
+ /**
4
+ * Props for the `Scope` component.
5
+ *
6
+ * @interface ScopeProps
7
+ * @property {Record<string, any> | ((props: any) => Record<string, any>)} let - An object or function defining local variables for the scope.
8
+ * @property {any} [props] - Optional props passed to the let function.
9
+ * @property {(scope: Record<string, any>) => ReactNode} [children] - Render function to access the scope variables.
10
+ * @property {ReactNode} [fallback] - Content to render if children or scope is empty.
11
+ */
12
+ export interface ScopeProps {
13
+ /**
14
+ * @description_en An object or function defining local variables for the scope.
15
+ * @description_zh 定义作用域局部变量的对象或函数。
16
+ */
17
+ let: Record<string, any> | ((props: any) => Record<string, any>);
18
+ /**
19
+ * @description_en Optional props passed to the let function.
20
+ * @description_zh 传递给 let 函数的可选属性。
21
+ * @optional
22
+ */
23
+ props?: any;
24
+ /**
25
+ * @description_en Render function to access the scope variables.
26
+ * @description_zh 访问作用域变量的渲染函数。
27
+ * @optional
28
+ */
29
+ children?: (scope: Record<string, any>) => ReactNode;
30
+ /**
31
+ * @description_en Content to render if children or scope is empty.
32
+ * @description_zh 如果 children 或 scope 为空时渲染的内容。
33
+ * @optional
34
+ * @default null
35
+ */
36
+ fallback?: ReactNode;
37
+ }
38
+ /*
39
+ 设计原因
40
+ 避免在组件外定义临时状态或计算。
41
+ 声明式定义局部变量,增强代码自包含性。
42
+ 适合表单、计算密集型渲染等场景。
43
+ */
44
+ /**
45
+ * @description_zh 一个声明式组件,为子节点提供局部作用域,简化临时状态或上下文管理。
46
+ * @description_en A declarative component that provides a local scope for children, simplifying temporary state or context management.
47
+ * @component
48
+ * @example
49
+ * ```tsx
50
+ * <Scope let={{ count: 1, text: "Hello" }}>
51
+ * {({ count, text }) => <div>{text} {count}</div>}
52
+ * </Scope>
53
+ * ```
54
+ *
55
+ * @example
56
+ * ```tsx
57
+ * <Scope let={(props) => ({ total: props.items.length })} props={{ items: [1, 2] }} fallback={<div>Empty</div>}>
58
+ * {({ total }) => <div>Total: {total}</div>}
59
+ * </Scope>
60
+ * ```
61
+ */
62
+ export const Scope: FC<ScopeProps> = ({
63
+ let: letValue,
64
+ props,
65
+ children,
66
+ fallback,
67
+ }) => {
68
+ const scope = useMemo(() => {
69
+ return typeof letValue === "function" ? letValue(props) : letValue;
70
+ }, [letValue, props]);
71
+
72
+ if (!children || !Object.keys(scope).length) {
73
+ return <>{fallback || null}</>;
74
+ }
75
+
76
+ return <>{children(scope)}</>;
77
+ };
@@ -1,2 +1,3 @@
1
1
  export * from "./SizeBox";
2
2
  export * from "./ArrayRender";
3
+ export * from "./Scope";
@@ -0,0 +1,64 @@
1
+ import React, { FC, ReactNode, useMemo } from "react";
2
+
3
+ /**
4
+ * Props for the `Pipe` component.
5
+ *
6
+ * @interface PipeProps
7
+ * @property {any} data - The initial data to process.
8
+ * @property {((input: any) => any)[]} transform - Array of functions to transform the data.
9
+ * @property {(result: any) => ReactNode} render - Function to render the transformed data.
10
+ * @property {ReactNode} [fallback] - Content to render if the result is null or undefined.
11
+ */
12
+ export interface PipeProps {
13
+ /**
14
+ * @description_en The initial data to process.
15
+ * @description_zh 要处理的初始数据。
16
+ */
17
+ data: any;
18
+ /**
19
+ * @description_en Array of functions to transform the data.
20
+ * @description_zh 转换数据的函数数组。
21
+ */
22
+ transform: ((input: any) => any)[];
23
+ /**
24
+ * @description_en Function to render the transformed data.
25
+ * @description_zh 渲染转换后数据的函数。
26
+ */
27
+ render: (result: any) => ReactNode;
28
+ /**
29
+ * @description_en Content to render if the result is null or undefined.
30
+ * @description_zh 如果结果为 null 或 undefined 时渲染的内容。
31
+ * @optional
32
+ * @default null
33
+ */
34
+ fallback?: ReactNode;
35
+ }
36
+
37
+ /**
38
+ * @description_zh 一个声明式组件,用于通过管道式处理数据并渲染,简化多步骤数据转换。
39
+ * @description_en A declarative component for processing data through a pipeline and rendering, simplifying multi-step data transformations.
40
+ * @component
41
+ * @example
42
+ * ```tsx
43
+ * <Pipe
44
+ * data={users}
45
+ * transform={[
46
+ * (data) => data.filter(user => user.active),
47
+ * (data) => data.map(user => user.name)
48
+ * ]}
49
+ * render={(names) => <div>{names.join(", ")}</div>}
50
+ * fallback={<div>No Data</div>}
51
+ * />
52
+ * ```
53
+ */
54
+ export const Pipe: FC<PipeProps> = ({ data, transform, render, fallback }) => {
55
+ const result = useMemo(() => {
56
+ return transform.reduce((acc, fn) => fn(acc), data);
57
+ }, [data, transform]);
58
+
59
+ if (result == null) {
60
+ return <>{fallback || null}</>;
61
+ }
62
+
63
+ return <>{render(result)}</>;
64
+ };
@@ -1,3 +1,4 @@
1
1
  export * from "./Switch";
2
2
  export * from "./If";
3
3
  export * from "./When";
4
+ export * from "./Pipe";