@wwog/react 1.3.9 → 1.3.11
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/dist/index.d.mts +6 -1
- package/dist/index.js +1 -1
- package/package.json +1 -1
- package/src/utils/createExternalState.ts +21 -12
- package/src/utils/promise.ts +15 -0
package/dist/index.d.mts
CHANGED
|
@@ -709,6 +709,11 @@ declare class Counter {
|
|
|
709
709
|
}
|
|
710
710
|
|
|
711
711
|
declare const safePromiseTry: <T, U extends unknown[]>(callbackFn: (...args: U) => T | PromiseLike<T>, ...args: U) => Promise<Awaited<T>>;
|
|
712
|
+
declare const safePromiseWithResolvers: <T>() => {
|
|
713
|
+
promise: Promise<unknown>;
|
|
714
|
+
resolve: (value: T) => void;
|
|
715
|
+
reject: (reason?: any) => void;
|
|
716
|
+
};
|
|
712
717
|
|
|
713
718
|
declare const breakpoints: readonly ["base", "xs", "sm", "md", "lg", "xl", "2xl", "3xl"];
|
|
714
719
|
declare const DefBreakpointDesc: BreakpointDesc;
|
|
@@ -769,5 +774,5 @@ declare function ruleChecker<T extends Record<string, unknown>, R extends RuleDe
|
|
|
769
774
|
declare function getCurrentBreakpoint(breakpointDesc: BreakpointDesc, width: number): BreakpointName;
|
|
770
775
|
declare function useScreen(breakpointDesc?: BreakpointDesc): "base" | "xs" | "sm" | "md" | "lg" | "xl" | "2xl" | "3xl";
|
|
771
776
|
|
|
772
|
-
export { ArrayRender, Counter, DateRender, DefBreakpointDesc, False, If, Observer, Pipe, Scope, SizeBox, Styles, Switch, Toggle, True, When, breakpoints, childrenLoop, createExternalState, createStorageState, cx, formatDate, getCurrentBreakpoint, ruleChecker, safePromiseTry, useControlled, useScreen };
|
|
777
|
+
export { ArrayRender, Counter, DateRender, DefBreakpointDesc, False, If, Observer, Pipe, Scope, SizeBox, Styles, Switch, Toggle, True, When, breakpoints, childrenLoop, createExternalState, createStorageState, cx, formatDate, getCurrentBreakpoint, ruleChecker, safePromiseTry, safePromiseWithResolvers, useControlled, useScreen };
|
|
773
778
|
export type { ApplyRules, ArrayRenderProps, ArrayRule, ArraySpecificProps, BaseRule, BooleanRule, BreakpointDesc, BreakpointName, CreateStateListener, CxInput, DateRenderProps, ElseIfProps, ElseProps, ExternalSideEffect, ExternalState, ExternalStateOptions, ExternalWithKernel, FalseProps, FieldRule, IfProps, LengthRuleProps, NumberRangeProps, NumberRule, ObserverProps, PipeProps, Responsive, RuleDescription, ScopeProps, StorageStateOptions, StringRule, StringSpecificProps, StylesDescriptor, StylesProps, StylesType, SwitchCaseProps, SwitchDefaultProps, SwitchProps, ThenProps, ToggleProps, Transform, TrueProps, UseControlledOptions, WhenProps };
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import u,{useMemo as S,Fragment as F,Children as Z,isValidElement as q,cloneElement as U,useEffect as b,useState as I,useRef as O,useCallback as G}from"react";function R(e,n){if(e===void 0)return;let t=0;if(Array.isArray(e)){for(const l of e)if(n(l,t++)===!1)break}else n(e,t)}const K=(e,n)=>e===n,N=e=>u.createElement(u.Fragment,null,e.children);N.displayName="Switch_Case";const D=e=>u.createElement(u.Fragment,null,e.children);D.displayName="Switch_Default";const w=e=>{const{value:n,compare:t=K,children:l,strict:r=!1}=e,o=new Set;let a=null,i=null,f=!1;return R(l,(s,c)=>{if(!u.isValidElement(s))throw new Error(`Switch Children only accepts valid React elements at index ${c}`);const d=s.type;if(d.displayName===N.displayName){const m=s.props;if(o.has(m.value))throw new Error(`Switch found duplicate Case value at index ${c}: ${JSON.stringify(m.value)}${r?" (detected in strict mode)":""}`);if(o.add(m.value),!a&&t(n,m.value)&&(a=m.children,r===!1))return!1}else if(d.displayName===D.displayName){if(f)throw new Error(`Switch can only have one Default child at index ${c}`);if(f=!0,i=s.props.children,!r&&a)return!1}else throw new Error(`Switch Children only accepts 'Case' or 'Default' elements, found: ${String(d.displayName||d.name||d)} at index ${c}`)}),u.createElement(u.Fragment,null,a??i)};w.displayName="Switch",w.Case=N,w.Default=D,w.createTyped=function(){return{Switch:w,Case:N,Default:D}};const A=e=>u.createElement(u.Fragment,null,e.children),x=({children:e})=>u.createElement(u.Fragment,null,e),M=e=>u.createElement(u.Fragment,null,e.children);A.displayName="If_Then",x.displayName="If_Else",M.displayName="If_ElseIf";const E=({condition:e,children:n})=>{let t=null,l=null;const r=[];if(u.Children.forEach(n,o=>{if(!u.isValidElement(o))throw new Error("If component only accepts valid React elements");const a=o.type;if(a.displayName===A.displayName){if(t)throw new Error("If component can only have one Then child");t=o}else if(a.displayName===M.displayName)r.push(o);else if(a.displayName===x.displayName){if(l)throw new Error("If component can only have one Else child");l=o}else throw new Error(`If component only accepts 'Then', 'ElseIf', or 'Else' elements as children, found: ${String(a.displayName||a.name||a)}`)}),e)return t?u.createElement(u.Fragment,null,t.props.children):null;for(const o of r)if(o.props.condition)return u.createElement(u.Fragment,null,o.props.children);return l?u.createElement(u.Fragment,null,l.props.children):null};E.displayName="If",E.Then=A,E.ElseIf=M,E.Else=x,E.createTyped=function(){return{If:E,Then:A,ElseIf:M,Else:x}};const Q=({condition:e,children:n})=>e?u.createElement(u.Fragment,null,n):null,X=({condition:e,children:n})=>e===!1?u.createElement(u.Fragment,null,n):null,ee=({all:e,any:n,none:t,children:l,fallback:r})=>S(()=>(e&&(n||t)&&console.warn('When: Multiple condition types (all, any, none) provided; "all" takes precedence.'),!!(e&&e.length>0&&e.every(Boolean)||n&&n.length>0&&n.some(Boolean)||t&&t.length>0&&t.every(o=>!o))),[e,n,t])?u.createElement(u.Fragment,null,l):u.createElement(u.Fragment,null,r||null),te=({data:e,transform:n,render:t,fallback:l})=>{const r=S(()=>n.reduce((o,a)=>a(o),e),[e,n]);return r==null?u.createElement(u.Fragment,null,l||null):u.createElement(u.Fragment,null,t(r))},ne=e=>{const{children:n,h:t,w:l,size:r,height:o,width:a,className:i}=e;return u.createElement("div",{style:{width:r||l||a,height:r||t||o,flexShrink:0},className:i},n)},re=({let:e,props:n,children:t,fallback:l})=>{const r=S(()=>typeof e=="function"?e(n):e,[e,n]);return!t||!Object.keys(r).length?u.createElement(u.Fragment,null,l||null):u.createElement(u.Fragment,null,t(r))};function C(...e){const n=new Set;for(const t of e)if(t){if(typeof t=="string")n.add(t);else if(Array.isArray(t))t.forEach(l=>n.add(l));else if(typeof t=="object")for(const[l,r]of Object.entries(t))r&&n.add(l)}return Array.from(n).join(" ")}const le=e=>typeof e=="object"&&!!e,T=({className:e,children:n,asWrapper:t=!1})=>{if(!n)return null;if(!e)return u.createElement(F,null,n);const l=typeof e=="string"?e:C(...Object.values(e));if(t)return u.createElement(t===!0?"div":t,{className:l},n);if(Z.count(n)>1)return console.error("<Styles>: children has more than one child. Please check your code."),u.createElement(F,null,n);if(q(n)){const r=n;let o=r?.props?.className;return r?.type?.displayName===T.displayName&&le(o)&&(o=C(...Object.values(o))),U(n,{className:C(l,o)})}return console.error("<Styles>: children is not a valid React element. Please check your code."),u.createElement(F,null,n)};T.displayName="W/Styles";const oe=e=>{const{index:n=0,options:t,next:l,render:r}=e;b(()=>{if(t.length<n+1)throw new Error(`Index ${n} is out of bounds for options array of length ${t.length}. Defaulting to first option.`)},[n,t]);const[o,a]=I(n),i=()=>{a(f=>t.length?l?l(f,t):(f+1)%t.length:f)};return r(t[o],i)},ae=({onIntersect:e,threshold:n=.1,root:t=null,rootMargin:l="0px",triggerOnce:r=!1,disabled:o=!1,children:a,className:i,style:f})=>{const s=O(null),c=O(null),d=O(!1);return b(()=>{if(o||!s.current)return;if(!window.IntersectionObserver){console.warn("IntersectionObserver is not supported in this browser");return}const m=s.current,g=y=>{y.forEach($=>{r&&d.current||(e($,c.current),r&&(d.current=!0,c.current?.unobserve(m)))})};return c.current=new IntersectionObserver(g,{root:t,rootMargin:l,threshold:n}),c.current.observe(m),()=>{c.current&&c.current.disconnect()}},[e,n,t,l,r,o]),b(()=>{r||(d.current=!1)},[r]),u.createElement("div",{ref:s,className:i,style:f},a)};function se(e){const{items:n,renderItem:t,filter:l,renderEmpty:r,sort:o}=e;if(!n)return console.error("ArrayRender: items is null"),null;if(n.length===0)return r?r():null;if(o){let a=[...n];return l&&(a=a.filter(l)),a=a.sort(o),a.length===0?r?r():null:u.createElement(F,null,a.map((i,f)=>t(i,f)))}return u.createElement(F,null,n.map((a,i)=>l&&!l(a)?null:t(a,i)))}function ue({source:e,format:n,children:t}){const l=S(()=>{if(e instanceof Date)return e;if(typeof e=="string"||typeof e=="number"){const o=new Date(e);return isNaN(o.getTime())?null:o}return null},[e]),r=S(()=>l?n?n(l):l.toLocaleString():null,[l,n]);return!r||!t?null:u.createElement(u.Fragment,null,t(r))}const ie="onChange",ce="value";function fe(e){const{defaultValue:n,onBeforeChange:t,trigger:l=ie,valuePropName:r=ce,props:o}=e,a=Object.prototype.hasOwnProperty.call(o,r),[i,f]=I(n),s=a?o[r]:i,c=S(()=>o[l],[o,l]),d=G(m=>{const g=typeof m=="function"?m(s):m;t&&t(g,s)===!1||(a||f(g),c&&c(g))},[a,t,s,c]);return[s,d]}function de(e,...n){try{const t=e(...n);return t instanceof Promise?t:Promise.resolve(t)}catch(t){return Promise.reject(t)}}const J=typeof Promise.try=="function"?Promise.try.bind(Promise):de;function W(e,n={}){let t=typeof e=="function"?e():e;const l=[],{sideEffect:r,transform:o}=n,a=()=>{const s=t;return o?.get?o.get(s):s},i=s=>{const c=t,d=o?.get?o.get(c):c;t=o?.set?o.set(typeof s=="function"?s(d):s):typeof s=="function"?s(d):s,l.forEach(m=>m(t)),r&&J(r,t,c).catch(m=>{console.error("Error in external state side effect, Please do it within side effects:",m)})},f=()=>{const[s,c]=u.useState(t);return u.useEffect(()=>(l.push(c),()=>{const d=l.indexOf(c);d>-1&&l.splice(d,1)}),[]),[o?.get?o.get(s):s,i]};return{get:a,set:i,use:f,useGetter:()=>{const[s]=f();return s},__listeners:l}}function me(e,n,t){const{storageType:l="local",sideEffect:r,transform:o}=t??{},a=l==="local"?localStorage:sessionStorage;let i=n;const f=a.getItem(e);if(f)try{i=JSON.parse(f)}catch(s){console.warn(`Failed to parse ${l}Storage value for key "${e}", using initial state:`,s),i=n}return W(i,{sideEffect:s=>{a.setItem(e,JSON.stringify(s)),r?.(s)},transform:o})}function he(e,n){const t=n||new Date,l=t.getFullYear(),r=t.getMonth()+1,o=t.getDate(),a=t.getHours(),i=t.getMinutes(),f=t.getSeconds(),s=t.getMilliseconds(),c=t.getDay(),d=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],m=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],g=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],y=["January","February","March","April","May","June","July","August","September","October","November","December"],$=m[c],Y=d[c],j=r-1,_=y[j],H=g[j],z={YY:l.toString().slice(2),YYYY:l.toString(),M:r.toString(),MM:r.toString().padStart(2,"0"),MMM:H,MMMM:_,D:o.toString(),DD:o.toString().padStart(2,"0"),d:c.toString(),dd:Y,ddd:Y,dddd:$,H:a.toString(),HH:a.toString().padStart(2,"0"),h:(a%12).toString(),hh:(a%12).toString().padStart(2,"0"),m:i.toString(),mm:i.toString().padStart(2,"0"),s:f.toString(),ss:f.toString().padStart(2,"0"),SSS:s.toString().padStart(3,"0"),Z:"+08:00",ZZ:"+0800",A:a<12?"AM":"PM",a:a<12?"am":"pm"};return e.replace(/YYYY|YY|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|m{1,2}|s{1,2}|SSS|Z{1,2}|A|a/g,V=>z[V])}class pe{count=0;next(){return this.count++}}const v=["base","xs","sm","md","lg","xl","2xl","3xl"],L={xs:475,sm:640,md:768,lg:1024,xl:1280,"2xl":1536,"3xl":1920};function h(e,n,t){t&&(e[n]||(e[n]=[]),e[n].push(t))}function ge(e){return e==null?!1:typeof e=="string"?e.trim().length>0:Array.isArray(e)?e.length>0:!0}function ye(e){return e!=null}function p(e,n){return`${String(e)} ${n}`}const k={email:/^[^\s@]+@[^\s@]+\.[^\s@]+$/,url:/^(https?:\/\/)?([\w.-]+)\.([a-z]{2,6})([/\w .-]*)*\/?$/,phone:/^1[3-9]\d{9}$/};function B(e,n,t,l,r){const o=ge(n),a=ye(n);if(t.required&&!o){h(r,e,t.message??p(e,"\u4E3A\u5FC5\u586B\u9879"));return}if(!(!a&&!t.required)){if(t.dependsOn){const i=t.dependsOn(l);i===!1?h(r,e,t.message??p(e,"\u4F9D\u8D56\u6761\u4EF6\u672A\u6EE1\u8DB3")):typeof i=="string"&&h(r,e,i)}if(typeof n=="string"){const i=t,{len:f,min:s,max:c,regex:d,email:m,url:g,phone:y}=i;typeof f=="number"&&n.length!==f&&h(r,e,t.message??p(e,`\u957F\u5EA6\u5FC5\u987B\u4E3A ${f}`)),typeof s=="number"&&n.length<s&&h(r,e,t.message??p(e,`\u957F\u5EA6\u4E0D\u80FD\u5C11\u4E8E ${s}`)),typeof c=="number"&&n.length>c&&h(r,e,t.message??p(e,`\u957F\u5EA6\u4E0D\u80FD\u8D85\u8FC7 ${c}`)),d&&!d.test(n)&&h(r,e,t.message??p(e,"\u683C\u5F0F\u4E0D\u6B63\u786E")),m&&!k.email.test(n)&&h(r,e,t.message??p(e,"\u4E0D\u662F\u6709\u6548\u7684\u90AE\u7BB1")),g&&!k.url.test(n)&&h(r,e,t.message??p(e,"\u4E0D\u662F\u6709\u6548\u7684URL")),y&&!k.phone.test(n)&&h(r,e,t.message??p(e,"\u4E0D\u662F\u6709\u6548\u7684\u624B\u673A\u53F7"))}if(typeof n=="number"){const i=t,{min:f,max:s}=i;typeof f=="number"&&n<f&&h(r,e,t.message??p(e,`\u4E0D\u80FD\u5C0F\u4E8E ${f}`)),typeof s=="number"&&n>s&&h(r,e,t.message??p(e,`\u4E0D\u80FD\u5927\u4E8E ${s}`))}if(Array.isArray(n)){const i=t,{len:f,min:s,max:c,unique:d,elementRule:m}=i;typeof f=="number"&&n.length!==f&&h(r,e,t.message??p(e,`\u957F\u5EA6\u5FC5\u987B\u4E3A ${f}`)),typeof s=="number"&&n.length<s&&h(r,e,t.message??p(e,`\u957F\u5EA6\u4E0D\u80FD\u5C0F\u4E8E ${s}`)),typeof c=="number"&&n.length>c&&h(r,e,t.message??p(e,`\u957F\u5EA6\u4E0D\u80FD\u5927\u4E8E ${c}`)),d&&new Set(n).size!==n.length&&h(r,e,t.message??p(e,"\u5143\u7D20\u5FC5\u987B\u552F\u4E00")),m&&n.forEach((g,y)=>{B(`${String(e)}[${y}]`,g,m,l,r)})}if(t.validator){const i=t.validator?.(n,l);i===!1?h(r,e,t.message??p(e,"\u6821\u9A8C\u672A\u901A\u8FC7")):typeof i=="string"&&h(r,e,i)}}}function Ee(e,n){const t={};for(const r in n){const o=r,a=n[o];if(!a)continue;const i=e[o];if(Array.isArray(a))for(const f of a)B(o,i,f,e,t);else B(o,i,a,e,t)}const l=Object.values(t).reduce((r,o)=>(o&&r.push(...o),r),[]);return l.length>0?{valid:!1,errors:l,fieldErrors:t}:{valid:!0,data:e}}const Se=[...v].reverse();function P(e,n){for(const t of Se){const l=e[t];if(l!==void 0&&!Number.isNaN(l)&&n>=l)return t}return"base"}function we(e=L){const[n,t]=I(P(e,window.innerWidth));return b(()=>{let l=[],r=[];const o=()=>{r.forEach(c=>c()),l=[],r=[];const a=P(e,window.innerWidth);t(a);const i=v.indexOf(a),f=v[i+1];if(f&&e[f]!==void 0){const c=e[f];if(Number.isNaN(c))throw new Error(`Invalid breakpoint value for ${f}: ${e[f]}`);{const d=window.matchMedia(`(min-width: ${c}px)`);l.push(d);const m=()=>o();d.addEventListener("change",m),r.push(()=>d.removeEventListener("change",m))}}const s=v[i-1];if(s&&e[s]!==void 0){const c=e[s];if(Number.isNaN(c))throw new Error(`Invalid breakpoint value for ${s}: ${e[s]}`);{const d=window.matchMedia(`(max-width: ${c-1}px)`);l.push(d);const m=()=>o();d.addEventListener("change",m),r.push(()=>d.removeEventListener("change",m))}}};return o(),()=>{r.forEach(a=>a())}},[e]),n}export{se as ArrayRender,pe as Counter,ue as DateRender,L as DefBreakpointDesc,X as False,E as If,ae as Observer,te as Pipe,re as Scope,ne as SizeBox,T as Styles,w as Switch,oe as Toggle,Q as True,ee as When,v as breakpoints,R as childrenLoop,W as createExternalState,me as createStorageState,C as cx,he as formatDate,P as getCurrentBreakpoint,Ee as ruleChecker,J as safePromiseTry,fe as useControlled,we as useScreen};
|
|
1
|
+
import a,{useMemo as S,Fragment as v,Children as Z,isValidElement as q,cloneElement as G,useEffect as b,useState as I,useRef as O,useCallback as U}from"react";function j(e,n){if(e===void 0)return;let t=0;if(Array.isArray(e)){for(const o of e)if(n(o,t++)===!1)break}else n(e,t)}const K=(e,n)=>e===n,N=e=>a.createElement(a.Fragment,null,e.children);N.displayName="Switch_Case";const D=e=>a.createElement(a.Fragment,null,e.children);D.displayName="Switch_Default";const w=e=>{const{value:n,compare:t=K,children:o,strict:r=!1}=e,l=new Set;let s=null,u=null,f=!1;return j(o,(i,c)=>{if(!a.isValidElement(i))throw new Error(`Switch Children only accepts valid React elements at index ${c}`);const d=i.type;if(d.displayName===N.displayName){const m=i.props;if(l.has(m.value))throw new Error(`Switch found duplicate Case value at index ${c}: ${JSON.stringify(m.value)}${r?" (detected in strict mode)":""}`);if(l.add(m.value),!s&&t(n,m.value)&&(s=m.children,r===!1))return!1}else if(d.displayName===D.displayName){if(f)throw new Error(`Switch can only have one Default child at index ${c}`);if(f=!0,u=i.props.children,!r&&s)return!1}else throw new Error(`Switch Children only accepts 'Case' or 'Default' elements, found: ${String(d.displayName||d.name||d)} at index ${c}`)}),a.createElement(a.Fragment,null,s??u)};w.displayName="Switch",w.Case=N,w.Default=D,w.createTyped=function(){return{Switch:w,Case:N,Default:D}};const A=e=>a.createElement(a.Fragment,null,e.children),x=({children:e})=>a.createElement(a.Fragment,null,e),M=e=>a.createElement(a.Fragment,null,e.children);A.displayName="If_Then",x.displayName="If_Else",M.displayName="If_ElseIf";const E=({condition:e,children:n})=>{let t=null,o=null;const r=[];if(a.Children.forEach(n,l=>{if(!a.isValidElement(l))throw new Error("If component only accepts valid React elements");const s=l.type;if(s.displayName===A.displayName){if(t)throw new Error("If component can only have one Then child");t=l}else if(s.displayName===M.displayName)r.push(l);else if(s.displayName===x.displayName){if(o)throw new Error("If component can only have one Else child");o=l}else throw new Error(`If component only accepts 'Then', 'ElseIf', or 'Else' elements as children, found: ${String(s.displayName||s.name||s)}`)}),e)return t?a.createElement(a.Fragment,null,t.props.children):null;for(const l of r)if(l.props.condition)return a.createElement(a.Fragment,null,l.props.children);return o?a.createElement(a.Fragment,null,o.props.children):null};E.displayName="If",E.Then=A,E.ElseIf=M,E.Else=x,E.createTyped=function(){return{If:E,Then:A,ElseIf:M,Else:x}};const Q=({condition:e,children:n})=>e?a.createElement(a.Fragment,null,n):null,X=({condition:e,children:n})=>e===!1?a.createElement(a.Fragment,null,n):null,ee=({all:e,any:n,none:t,children:o,fallback:r})=>S(()=>(e&&(n||t)&&console.warn('When: Multiple condition types (all, any, none) provided; "all" takes precedence.'),!!(e&&e.length>0&&e.every(Boolean)||n&&n.length>0&&n.some(Boolean)||t&&t.length>0&&t.every(l=>!l))),[e,n,t])?a.createElement(a.Fragment,null,o):a.createElement(a.Fragment,null,r||null),te=({data:e,transform:n,render:t,fallback:o})=>{const r=S(()=>n.reduce((l,s)=>s(l),e),[e,n]);return r==null?a.createElement(a.Fragment,null,o||null):a.createElement(a.Fragment,null,t(r))},ne=e=>{const{children:n,h:t,w:o,size:r,height:l,width:s,className:u}=e;return a.createElement("div",{style:{width:r||o||s,height:r||t||l,flexShrink:0},className:u},n)},re=({let:e,props:n,children:t,fallback:o})=>{const r=S(()=>typeof e=="function"?e(n):e,[e,n]);return!t||!Object.keys(r).length?a.createElement(a.Fragment,null,o||null):a.createElement(a.Fragment,null,t(r))};function C(...e){const n=new Set;for(const t of e)if(t){if(typeof t=="string")n.add(t);else if(Array.isArray(t))t.forEach(o=>n.add(o));else if(typeof t=="object")for(const[o,r]of Object.entries(t))r&&n.add(o)}return Array.from(n).join(" ")}const oe=e=>typeof e=="object"&&!!e,P=({className:e,children:n,asWrapper:t=!1})=>{if(!n)return null;if(!e)return a.createElement(v,null,n);const o=typeof e=="string"?e:C(...Object.values(e));if(t)return a.createElement(t===!0?"div":t,{className:o},n);if(Z.count(n)>1)return console.error("<Styles>: children has more than one child. Please check your code."),a.createElement(v,null,n);if(q(n)){const r=n;let l=r?.props?.className;return r?.type?.displayName===P.displayName&&oe(l)&&(l=C(...Object.values(l))),G(n,{className:C(o,l)})}return console.error("<Styles>: children is not a valid React element. Please check your code."),a.createElement(v,null,n)};P.displayName="W/Styles";const le=e=>{const{index:n=0,options:t,next:o,render:r}=e;b(()=>{if(t.length<n+1)throw new Error(`Index ${n} is out of bounds for options array of length ${t.length}. Defaulting to first option.`)},[n,t]);const[l,s]=I(n),u=()=>{s(f=>t.length?o?o(f,t):(f+1)%t.length:f)};return r(t[l],u)},se=({onIntersect:e,threshold:n=.1,root:t=null,rootMargin:o="0px",triggerOnce:r=!1,disabled:l=!1,children:s,className:u,style:f})=>{const i=O(null),c=O(null),d=O(!1);return b(()=>{if(l||!i.current)return;if(!window.IntersectionObserver){console.warn("IntersectionObserver is not supported in this browser");return}const m=i.current,g=y=>{y.forEach($=>{r&&d.current||(e($,c.current),r&&(d.current=!0,c.current?.unobserve(m)))})};return c.current=new IntersectionObserver(g,{root:t,rootMargin:o,threshold:n}),c.current.observe(m),()=>{c.current&&c.current.disconnect()}},[e,n,t,o,r,l]),b(()=>{r||(d.current=!1)},[r]),a.createElement("div",{ref:i,className:u,style:f},s)};function ae(e){const{items:n,renderItem:t,filter:o,renderEmpty:r,sort:l}=e;if(!n)return console.error("ArrayRender: items is null"),null;if(n.length===0)return r?r():null;if(l){let s=[...n];return o&&(s=s.filter(o)),s=s.sort(l),s.length===0?r?r():null:a.createElement(v,null,s.map((u,f)=>t(u,f)))}return a.createElement(v,null,n.map((s,u)=>o&&!o(s)?null:t(s,u)))}function ie({source:e,format:n,children:t}){const o=S(()=>{if(e instanceof Date)return e;if(typeof e=="string"||typeof e=="number"){const l=new Date(e);return isNaN(l.getTime())?null:l}return null},[e]),r=S(()=>o?n?n(o):o.toLocaleString():null,[o,n]);return!r||!t?null:a.createElement(a.Fragment,null,t(r))}const ue="onChange",ce="value";function fe(e){const{defaultValue:n,onBeforeChange:t,trigger:o=ue,valuePropName:r=ce,props:l}=e,s=Object.prototype.hasOwnProperty.call(l,r),[u,f]=I(n),i=s?l[r]:u,c=S(()=>l[o],[l,o]),d=U(m=>{const g=typeof m=="function"?m(i):m;t&&t(g,i)===!1||(s||f(g),c&&c(g))},[s,t,i,c]);return[i,d]}function de(e,...n){try{const t=e(...n);return t instanceof Promise?t:Promise.resolve(t)}catch(t){return Promise.reject(t)}}const J=typeof Promise.try=="function"?Promise.try.bind(Promise):de,me=typeof Promise.withResolvers=="function"?Promise.withResolvers.bind(Promise):()=>{let e,n;return{promise:new Promise((t,o)=>{e=t,n=o}),resolve:e,reject:n}};function W(e,n={}){let t=typeof e=="function"?e():e;const o=[],{sideEffect:r,transform:l}=n,s=()=>{const i=t;return l?.get?l.get(i):i},u=i=>{const c=t,d=l?.get?l.get(c):c;t=l?.set?l.set(typeof i=="function"?i(d):i):typeof i=="function"?i(d):i,o.forEach(m=>m(t)),r&&J(r,t,c).catch(m=>{console.error("Error in external state side effect, Please do it within side effects:",m)})},f=()=>{const[i,c]=a.useState(t);return a.useEffect(()=>(o.push(c),()=>{const d=o.indexOf(c);d>-1&&o.splice(d,1)}),[]),[l?.get?l.get(i):i,u]};return{get:s,set:u,use:f,useGetter:()=>{const[i]=f();return i},__listeners:o}}function pe(e,n,t){const{storageType:o="local",sideEffect:r,transform:l}=t??{};let s=n;if(typeof window<"u"){const u=(o==="local"?localStorage:sessionStorage).getItem(e);if(u)try{s=JSON.parse(u)}catch(f){console.warn(`Failed to parse ${o}Storage value for key "${e}", using initial state:`,f),s=n}}return W(s,{sideEffect:u=>{typeof window<"u"&&(o==="local"?localStorage:sessionStorage).setItem(e,JSON.stringify(u)),r?.(u)},transform:l})}function he(e,n){const t=n||new Date,o=t.getFullYear(),r=t.getMonth()+1,l=t.getDate(),s=t.getHours(),u=t.getMinutes(),f=t.getSeconds(),i=t.getMilliseconds(),c=t.getDay(),d=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],m=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],g=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],y=["January","February","March","April","May","June","July","August","September","October","November","December"],$=m[c],Y=d[c],R=r-1,_=y[R],H=g[R],z={YY:o.toString().slice(2),YYYY:o.toString(),M:r.toString(),MM:r.toString().padStart(2,"0"),MMM:H,MMMM:_,D:l.toString(),DD:l.toString().padStart(2,"0"),d:c.toString(),dd:Y,ddd:Y,dddd:$,H:s.toString(),HH:s.toString().padStart(2,"0"),h:(s%12).toString(),hh:(s%12).toString().padStart(2,"0"),m:u.toString(),mm:u.toString().padStart(2,"0"),s:f.toString(),ss:f.toString().padStart(2,"0"),SSS:i.toString().padStart(3,"0"),Z:"+08:00",ZZ:"+0800",A:s<12?"AM":"PM",a:s<12?"am":"pm"};return e.replace(/YYYY|YY|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|m{1,2}|s{1,2}|SSS|Z{1,2}|A|a/g,V=>z[V])}class ge{count=0;next(){return this.count++}}const F=["base","xs","sm","md","lg","xl","2xl","3xl"],L={xs:475,sm:640,md:768,lg:1024,xl:1280,"2xl":1536,"3xl":1920};function p(e,n,t){t&&(e[n]||(e[n]=[]),e[n].push(t))}function ye(e){return e==null?!1:typeof e=="string"?e.trim().length>0:Array.isArray(e)?e.length>0:!0}function Ee(e){return e!=null}function h(e,n){return`${String(e)} ${n}`}const T={email:/^[^\s@]+@[^\s@]+\.[^\s@]+$/,url:/^(https?:\/\/)?([\w.-]+)\.([a-z]{2,6})([/\w .-]*)*\/?$/,phone:/^1[3-9]\d{9}$/};function k(e,n,t,o,r){const l=ye(n),s=Ee(n);if(t.required&&!l){p(r,e,t.message??h(e,"\u4E3A\u5FC5\u586B\u9879"));return}if(!(!s&&!t.required)){if(t.dependsOn){const u=t.dependsOn(o);u===!1?p(r,e,t.message??h(e,"\u4F9D\u8D56\u6761\u4EF6\u672A\u6EE1\u8DB3")):typeof u=="string"&&p(r,e,u)}if(typeof n=="string"){const u=t,{len:f,min:i,max:c,regex:d,email:m,url:g,phone:y}=u;typeof f=="number"&&n.length!==f&&p(r,e,t.message??h(e,`\u957F\u5EA6\u5FC5\u987B\u4E3A ${f}`)),typeof i=="number"&&n.length<i&&p(r,e,t.message??h(e,`\u957F\u5EA6\u4E0D\u80FD\u5C11\u4E8E ${i}`)),typeof c=="number"&&n.length>c&&p(r,e,t.message??h(e,`\u957F\u5EA6\u4E0D\u80FD\u8D85\u8FC7 ${c}`)),d&&!d.test(n)&&p(r,e,t.message??h(e,"\u683C\u5F0F\u4E0D\u6B63\u786E")),m&&!T.email.test(n)&&p(r,e,t.message??h(e,"\u4E0D\u662F\u6709\u6548\u7684\u90AE\u7BB1")),g&&!T.url.test(n)&&p(r,e,t.message??h(e,"\u4E0D\u662F\u6709\u6548\u7684URL")),y&&!T.phone.test(n)&&p(r,e,t.message??h(e,"\u4E0D\u662F\u6709\u6548\u7684\u624B\u673A\u53F7"))}if(typeof n=="number"){const u=t,{min:f,max:i}=u;typeof f=="number"&&n<f&&p(r,e,t.message??h(e,`\u4E0D\u80FD\u5C0F\u4E8E ${f}`)),typeof i=="number"&&n>i&&p(r,e,t.message??h(e,`\u4E0D\u80FD\u5927\u4E8E ${i}`))}if(Array.isArray(n)){const u=t,{len:f,min:i,max:c,unique:d,elementRule:m}=u;typeof f=="number"&&n.length!==f&&p(r,e,t.message??h(e,`\u957F\u5EA6\u5FC5\u987B\u4E3A ${f}`)),typeof i=="number"&&n.length<i&&p(r,e,t.message??h(e,`\u957F\u5EA6\u4E0D\u80FD\u5C0F\u4E8E ${i}`)),typeof c=="number"&&n.length>c&&p(r,e,t.message??h(e,`\u957F\u5EA6\u4E0D\u80FD\u5927\u4E8E ${c}`)),d&&new Set(n).size!==n.length&&p(r,e,t.message??h(e,"\u5143\u7D20\u5FC5\u987B\u552F\u4E00")),m&&n.forEach((g,y)=>{k(`${String(e)}[${y}]`,g,m,o,r)})}if(t.validator){const u=t.validator?.(n,o);u===!1?p(r,e,t.message??h(e,"\u6821\u9A8C\u672A\u901A\u8FC7")):typeof u=="string"&&p(r,e,u)}}}function Se(e,n){const t={};for(const r in n){const l=r,s=n[l];if(!s)continue;const u=e[l];if(Array.isArray(s))for(const f of s)k(l,u,f,e,t);else k(l,u,s,e,t)}const o=Object.values(t).reduce((r,l)=>(l&&r.push(...l),r),[]);return o.length>0?{valid:!1,errors:o,fieldErrors:t}:{valid:!0,data:e}}const we=[...F].reverse();function B(e,n){for(const t of we){const o=e[t];if(o!==void 0&&!Number.isNaN(o)&&n>=o)return t}return"base"}function ve(e=L){const[n,t]=I(B(e,window.innerWidth));return b(()=>{let o=[],r=[];const l=()=>{r.forEach(c=>c()),o=[],r=[];const s=B(e,window.innerWidth);t(s);const u=F.indexOf(s),f=F[u+1];if(f&&e[f]!==void 0){const c=e[f];if(Number.isNaN(c))throw new Error(`Invalid breakpoint value for ${f}: ${e[f]}`);{const d=window.matchMedia(`(min-width: ${c}px)`);o.push(d);const m=()=>l();d.addEventListener("change",m),r.push(()=>d.removeEventListener("change",m))}}const i=F[u-1];if(i&&e[i]!==void 0){const c=e[i];if(Number.isNaN(c))throw new Error(`Invalid breakpoint value for ${i}: ${e[i]}`);{const d=window.matchMedia(`(max-width: ${c-1}px)`);o.push(d);const m=()=>l();d.addEventListener("change",m),r.push(()=>d.removeEventListener("change",m))}}};return l(),()=>{r.forEach(s=>s())}},[e]),n}export{ae as ArrayRender,ge as Counter,ie as DateRender,L as DefBreakpointDesc,X as False,E as If,se as Observer,te as Pipe,re as Scope,ne as SizeBox,P as Styles,w as Switch,le as Toggle,Q as True,ee as When,F as breakpoints,j as childrenLoop,W as createExternalState,pe as createStorageState,C as cx,he as formatDate,B as getCurrentBreakpoint,Se as ruleChecker,J as safePromiseTry,me as safePromiseWithResolvers,fe as useControlled,ve as useScreen};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@wwog/react",
|
|
3
|
-
"version": "1.3.
|
|
3
|
+
"version": "1.3.11",
|
|
4
4
|
"description": "A practical React component library providing declarative flow control and common UI utility components to make your React code more concise and readable.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"react",
|
|
@@ -213,23 +213,32 @@ export function createStorageState<T, U = T>(
|
|
|
213
213
|
options?: StorageStateOptions<T, U>
|
|
214
214
|
) {
|
|
215
215
|
const { storageType = "local", sideEffect, transform } = options ?? {};
|
|
216
|
-
const storage = storageType === "local" ? localStorage : sessionStorage;
|
|
217
216
|
let _initState: T = initialState;
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
)
|
|
227
|
-
|
|
217
|
+
|
|
218
|
+
// 只在客户端环境中读取存储
|
|
219
|
+
if (typeof window !== 'undefined') {
|
|
220
|
+
const storage = storageType === "local" ? localStorage : sessionStorage;
|
|
221
|
+
const storedValue = storage.getItem(key);
|
|
222
|
+
if (storedValue) {
|
|
223
|
+
try {
|
|
224
|
+
_initState = JSON.parse(storedValue);
|
|
225
|
+
} catch (error) {
|
|
226
|
+
console.warn(
|
|
227
|
+
`Failed to parse ${storageType}Storage value for key "${key}", using initial state:`,
|
|
228
|
+
error
|
|
229
|
+
);
|
|
230
|
+
_initState = initialState;
|
|
231
|
+
}
|
|
228
232
|
}
|
|
229
233
|
}
|
|
234
|
+
|
|
230
235
|
return createExternalState(_initState, {
|
|
231
236
|
sideEffect: (newState) => {
|
|
232
|
-
|
|
237
|
+
// 只在客户端环境中写入存储
|
|
238
|
+
if (typeof window !== 'undefined') {
|
|
239
|
+
const storage = storageType === "local" ? localStorage : sessionStorage;
|
|
240
|
+
storage.setItem(key, JSON.stringify(newState));
|
|
241
|
+
}
|
|
233
242
|
sideEffect?.(newState);
|
|
234
243
|
},
|
|
235
244
|
transform,
|
package/src/utils/promise.ts
CHANGED
|
@@ -35,3 +35,18 @@ export const safePromiseTry = (() => {
|
|
|
35
35
|
}
|
|
36
36
|
return promiseTry;
|
|
37
37
|
})();
|
|
38
|
+
|
|
39
|
+
export const safePromiseWithResolvers = (() => {
|
|
40
|
+
if (typeof Promise.withResolvers === "function") {
|
|
41
|
+
return Promise.withResolvers.bind(Promise);
|
|
42
|
+
}
|
|
43
|
+
return <T>() => {
|
|
44
|
+
let resolve!: (value: T) => void;
|
|
45
|
+
let reject!: (reason?: any) => void;
|
|
46
|
+
const promise = new Promise((res, rej) => {
|
|
47
|
+
resolve = res;
|
|
48
|
+
reject = rej;
|
|
49
|
+
});
|
|
50
|
+
return { promise, resolve, reject };
|
|
51
|
+
};
|
|
52
|
+
})();
|