Skip to content

Commit

Permalink
update
Browse files Browse the repository at this point in the history
  • Loading branch information
zhangfisher committed Aug 27, 2024
1 parent 0dc90fe commit 5aad2f6
Show file tree
Hide file tree
Showing 31 changed files with 188 additions and 100 deletions.
6 changes: 6 additions & 0 deletions .oxlintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"rules": {
"eqeqeq": ["warn"]
},
"ignore": ["node_modules","dist","packages/**/__tests__/**/*"]
}
6 changes: 0 additions & 6 deletions oxlintrc.json

This file was deleted.

5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
"scripts": {
"docs:dev": "cd docs && pnpm dev",
"docs:build": "cd docs && pnpm build",
"storybook":"cd storybook && pnpm storybook",
"lint":"oxlint"
"storybook": "cd storybook && pnpm storybook",
"lint": "oxlint --fix -c=.oxlintrc.json"
},
"keywords": [],
"author": "",
Expand All @@ -25,6 +25,7 @@
"@types/react": "^18.3.4",
"@vitejs/plugin-react": "^4.3.1",
"jsdom": "^23.0.1",
"oxlint": "^0.9.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"ts-node": "^10.9.2",
Expand Down
2 changes: 1 addition & 1 deletion packages/components/src/Button.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ export const Button:React.FC<ButtonProps> = (props)=>{
}}>{props.error}</span> : ''
}
{/* 显示取消按钮 */}
{props.loading && typeof(cancel)=='function' ?
{props.loading && typeof(cancel) === 'function' ?
<button onClick={cancel} style={{
padding:"4px",
color:"red",
Expand Down
2 changes: 1 addition & 1 deletion packages/components/src/Field.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ export const Field:ReactFC<FieldProps> = (props)=>{
flexDirection:'row',
alignItems:'center',
color: enable===false ? 'gray' : 'inherit'
}}>{typeof(children)=='function' ? '' : children}{memo && <span style={{color:'gray'}}>{memo}</span>}</span>
}}>{typeof(children) === 'function' ? '' : children}{memo && <span style={{color:'gray'}}>{memo}</span>}</span>

<ValidResult {...props}/>
{/* <ColorBlock style={{
Expand Down
2 changes: 1 addition & 1 deletion packages/components/src/Tips.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import React from "react"
}
export const Tips:React.FC<RichLabelProps> =(props:RichLabelProps)=>{
const {text,color='#ff6c00' } = props
const colors:Record<string,string> = typeof(color)=='string' ? {default:color} : Object.assign({default:""},color)
const colors:Record<string,string> = typeof(color) === 'string' ? {default:color} : Object.assign({default:""},color)
const html = text.replace(/\{\s?(.*?)\s?\}/gm,(match,word)=>{
return `<span style='color: ${ word in colors ? colors[word] : colors.default}'>${word}</span>`
}).replaceAll("undefined","空值")
Expand Down
6 changes: 3 additions & 3 deletions packages/core/src/action.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ function useActionRunner<State extends FormActionState=FormActionState>(actionSt
const run = getAction<State>(actionState,opts)
return (event:any)=>{
run()
if(event && opts.preventDefault && typeof(event.preventDefault)=='function'){
if(event && opts.preventDefault && typeof(event.preventDefault) === 'function'){
event.preventDefault()
}
}
Expand All @@ -200,7 +200,7 @@ function useActionCanceller<State>(state:State,valuePath:string | string[]){
return useCallback((event:any)=>{
const execute = getValueByPath(state,[...Array.isArray(valuePath) ? valuePath : valuePath.split(".") ,'execute'])
execute.cancel()
if(event && typeof(event.preventDefault)=='function'){
if(event && typeof(event.preventDefault) === 'function'){
event.preventDefault()
}
},[])
Expand All @@ -225,7 +225,7 @@ function createActionRenderProps<State extends FormActionState=FormActionState>(

export const ActionChildren = React.memo((props: {actionProps:ActionRenderProps<any>,children:any})=>{
return <>{
typeof(props.children)=='function' && props.children(props.actionProps as any)
typeof(props.children) === 'function' && props.children(props.actionProps as any)
}</>
},(oldProps, newProps)=>{
return Object.entries(oldProps.actionProps).every(([key,value]:[key:string,value:any])=>{
Expand Down
6 changes: 3 additions & 3 deletions packages/core/src/field.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -102,12 +102,12 @@ function useFieldUpdater(valuePath:string[],setState:any){
if(debounceValue!==debounce && debounce>0) setDebounce(debounce)
const updateFn = (updater:any)=>{
return (ev:any)=>{
if(typeof(updater)=="function"){
if(typeof(updater) === "function"){
setState((draft:any)=>updater.call(draft,draft.fields))
}else{
setState((draft:any)=>setVal(draft,valuePath,updater))
}
if(typeof(ev.preventDefault)=='function'){
if(typeof(ev.preventDefault) === 'function'){
ev.preventDefault()
}
}
Expand All @@ -125,7 +125,7 @@ function useFieldUpdater(valuePath:string[],setState:any){
*/
export const FieldChildren = React.memo((props: {fieldProps:FieldRenderProps<any> ,children:any})=>{
return <>{
typeof(props.children)=='function' && props.children(props.fieldProps as any)
typeof(props.children) === 'function' && props.children(props.fieldProps as any)
}</>
},(oldProps, newProps)=>{
return Object.entries(oldProps.fieldProps).every(([key,value]:[key:string,value:any])=>{
Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/field2.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -74,12 +74,12 @@ function createFieldProps(name:string,value:any,syncer:any,filedUpdater:any){
if(debounceValue!==debounce && debounce>0) setDebounce(debounce)
const updateFn = (updater:any)=>{
return (ev:any)=>{
if(typeof(updater)=="function"){
if(typeof(updater) === "function"){
setState((draft:any)=>updater.call(draft,draft.fields))
}else{
setState((draft:any)=>setVal(draft,valuePath,updater))
}
if(typeof(ev.preventDefault)=='function'){
if(typeof(ev.preventDefault) === 'function'){
ev.preventDefault()
}
}
Expand Down
6 changes: 3 additions & 3 deletions packages/core/src/form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@ function createActionHook(valuePath:string[],options:ComputedOptions){
if(options.scope.length>0 && options.scope[0]!=FIELDS_STATE_KEY){
options.scope.unshift(FIELDS_STATE_KEY)
}
}else if(typeof(options.scope)=='string'){
}else if(typeof(options.scope) === 'string'){
if(!options.scope.startsWith(FIELDS_STATE_KEY)){
options.scope = `${FIELDS_STATE_KEY}.${options.scope}`
}
Expand All @@ -256,7 +256,7 @@ function createDepsHook(valuePath:string[],options:ComputedOptions){
options.depends.forEach((depend,i)=>{
if(Array.isArray(depend) && (depend.length>0 && depend[0]!=FIELDS_STATE_KEY)){
options.depends![i] = [FIELDS_STATE_KEY,...depend]
}else if(typeof(depend)=='string' && !depend.startsWith(`${FIELDS_STATE_KEY}.`)){
}else if(typeof(depend) === 'string' && !depend.startsWith(`${FIELDS_STATE_KEY}.`)){
options.depends![i] = `${FIELDS_STATE_KEY}.${depend}`
}
})
Expand Down Expand Up @@ -432,7 +432,7 @@ function createFormComponent<State extends FormDefine>(store: FormStore<State>,f
// 运行表单校验
if(formOptions.validAt==='submit' || props.valid!==false){
if(scope && scope.length>0){ // 指定了提交范围
const scopeValue = typeof(scope)=='string' ? scope.split(OBJECT_PATH_DELIMITER) : scope
const scopeValue = typeof(scope) === 'string' ? scope.split(OBJECT_PATH_DELIMITER) : scope
await store.computedObjects.run((cobj)=>{
if(cobj.path.length>1 && cobj.path[0]==FIELDS_STATE_KEY && cobj.path[cobj.path.length-1]==='validate'){

Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/submit.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ function createBehaviorRenderProps<State extends FormBehaviorState=FormBehaviorS

const BehaviorChildren = React.memo((props:{submitProps:BehaviorRenderProps<any>,children:any})=>{
return <>{
typeof(props.children)=='function' && props.children(props.submitProps as any)
typeof(props.children) === 'function' && props.children(props.submitProps as any)
}</>
},(oldProps, newProps)=>{
return Object.entries(oldProps.submitProps).every(([key,value]:[key:string,value:any])=>{
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/types.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { AsyncComputedObject,ComputedDescriptor } from "@speedform/reactive";
import { ComputedDescriptor } from "@speedform/reactive";


// 用来声明表单定义中的动态计算属性
Expand Down
6 changes: 3 additions & 3 deletions packages/core/src/validate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ export function validate(options?:ValidateOptions){
// 只侦听entry下的所有字段
if(!pathStartsWith(entry ? entry : watchObject.path,path)) return
// validate属性是一个boolean
if(typeof(value)=='boolean'){
if(typeof(value) === 'boolean'){
const srcKey = path.join(OBJECT_PATH_DELIMITER)
if(value){
delete watchObject.cache[srcKey]
Expand All @@ -82,9 +82,9 @@ export function validate(options?:ValidateOptions){
* @param tips
*/
export function assert(condition:boolean | ((...args:any[])=>boolean),tips:string | (()=>string)){
const cond = typeof(condition)=='function' ? condition() : condition
const cond = typeof(condition) === 'function' ? condition() : condition
if(!cond){
throw new ValidationError(typeof(tips)=='function' ? tips() : tips)
throw new ValidationError(typeof(tips) === 'function' ? tips() : tips)
}
}

Expand Down
2 changes: 1 addition & 1 deletion packages/reactive/src/__tests__/watch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ function getBookShop(opts?: {listener?:watchParams[0],depends?:watchParams[1],op
total:watch<number,number>((path,value,watchObj)=>{
return listener(path,value,watchObj) as number
},(path:string[],value:any)=>{
return typeof(depends)=='function' ? depends!(path,value) : path[path.length-1]=='count'
return typeof(depends) === 'function' ? depends!(path,value) : path[path.length-1]=='count'
},{
id:"total",
initial:1,
Expand Down
4 changes: 2 additions & 2 deletions packages/reactive/src/computed/async.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ async function executeComputedGetter<T extends Dict>(draft:any,computedRunContex
if(timeoutValue>0){
timerId = setTimeout(()=>{
hasTimeout=true
if(typeof(timeoutCallback)=='function') timeoutCallback()
if(typeof(timeoutCallback) === 'function') timeoutCallback()
if(!hasError){
clearInterval(countdownId)
updateAsyncComputedState(setState,resultPath,{loading:false,error:"TIMEOUT",timeout:0})
Expand Down Expand Up @@ -302,7 +302,7 @@ export function asyncComputedObject<T extends Dict =Dict>(initial:AsyncComputedO
error : null,
result : undefined,
progress: 0,
run : markRaw(skipComputed((args:Dict) => {})),
run : markRaw(skipComputed(() => {})),
cancel : markRaw(skipComputed(() => {}))
},initial) as AsyncComputedObject<T>
}
4 changes: 2 additions & 2 deletions packages/reactive/src/computed/computed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export function computed<R = any,Scope=any,ExtraAttrs extends Dict = {}>( getter
export function computed<R = any,Scope=any,ExtraAttrs extends Dict = {}>( getter: ComputedGetter<R,Scope>, options?: ComputedOptions<R,ExtraAttrs>): R
export function computed<R = any,Scope=any,ExtraAttrs extends Dict = {}>( getter: any,depends?:any, options?: ComputedOptions<R,ExtraAttrs>):any {

if (typeof getter != "function") throw new Error("computed getter must be a function");
if (typeof getter !== "function") throw new Error("computed getter must be a function");

// 解析参数:同时支持同步和异步计算函数两种方式声明
let deps:ComputedDepends = []
Expand All @@ -42,7 +42,7 @@ export function computed<R = any,Scope=any,ExtraAttrs extends Dict = {}>( getter
}else if(arguments.length==2){
if(Array.isArray(arguments[1])){
deps = arguments[1]
}else if(typeof(arguments[1])=='object'){
}else if(typeof(arguments[1]) === 'object'){
Object.assign(opts,arguments[1])
}else{
throw new Error("invalid arguments")
Expand Down
2 changes: 1 addition & 1 deletion packages/reactive/src/computed/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,7 @@ export type ComputedDescriptorDefine<R=any,Scope extends Dict = Dict> = {


export interface ComputedDescriptor<R=any,Scope extends Dict = Dict> {
():ComputedDescriptorDefine<R>
():ComputedDescriptorDefine<R,Scope>
__COMPUTED__: 'sync' | 'async' | 'watch'
}

Expand Down
4 changes: 2 additions & 2 deletions packages/reactive/src/computed/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@ import { skipComputed } from "../utils";
*/
export function executeStoreHooks<T extends Dict>(valuePath:string[],getter:any,store:IStore<T>,computedOptions:ComputedOptions){
const { onCreateComputed } = store.options;
if (typeof onCreateComputed == "function" && typeof getter === "function") {
if (typeof onCreateComputed === "function" && typeof getter === "function") {
const newGetter = onCreateComputed.call(store,valuePath, getter, computedOptions);
if(!computedOptions.scope) computedOptions.scope = ComputedScopeRef.Current
if (typeof newGetter == "function") getter = newGetter
if (typeof newGetter === "function") getter = newGetter
}
}

Expand Down
6 changes: 3 additions & 3 deletions packages/reactive/src/reactives/helux.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,18 +69,18 @@ export class HeluxReactiveable<State extends Dict =Dict> extends Reactiveable<St
this._stateCtx.mutate({
// 收集依赖
deps: (state: any) =>{
return typeof(depends)=='function' ? depends(state) : null
return typeof(depends) === 'function' ? depends(state) : null
},
// 初始化计算属性
fn: (draft, params) => {
if (params.isFirstCall) {
if(typeof(initial)=='function') initial(draft, params)
if(typeof(initial) === 'function') initial(draft, params)
}
},
// 此函数在依赖变化时执行,用来异步计算
// extraArgs是在调用run方法时传入的额外计算参数,可用来覆盖计算参数
task: async ({ draft, setState, input, extraArgs }) => {
if(typeof(onComputed)=='function'){// @ts-ignore
if(typeof(onComputed) === 'function'){// @ts-ignore
return onComputed({draft,setState,values:input,options:Object.assign({},extraArgs)})
}
},
Expand Down
8 changes: 4 additions & 4 deletions packages/reactive/src/scope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ import { Dict } from "./types";
*/
function getScopeOptions(state: any,valuePath:string[],computedScope?: ComputedScope,storeScope?: ComputedScope) {
let scope = computedScope == undefined ? storeScope : computedScope;
if (typeof scope == "function") {
if (typeof scope === "function") {
try { scope = scope.call(state, state) } catch { }
}
return scope == undefined ? (storeScope == undefined ? ComputedScopeRef.Current: storeScope) : scope;
Expand Down Expand Up @@ -71,7 +71,7 @@ export function getComputedScope<T extends Dict = Dict>(store:IStore<T>,computed

let rootDraft = draft;
// 1. 执行hook:可以在hook函数中修改计算函数的根上下文以及相关配置参数
if (typeof store.options.getRootScope == "function") {
if (typeof store.options.getRootScope === "function") {
const newDraft = store.options.getRootScope.call(draft,draft,{computedType,valuePath});
if (newDraft !== undefined) {
rootDraft = newDraft;
Expand All @@ -93,9 +93,9 @@ export function getComputedScope<T extends Dict = Dict>(store:IStore<T>,computed
}else if (scopeRef === ComputedScopeRef.Root) {
scope = rootDraft;
}else if (scopeRef === ComputedScopeRef.Depends) { // 异步计算的依赖值
scope = Array.isArray(dependValues) ? dependValues.map(dep=>typeof(dep)=='function' ? dep() : dep) : [];
scope = Array.isArray(dependValues) ? dependValues.map(dep=>typeof(dep) === 'function' ? dep() : dep) : [];
}else{
if (typeof scopeRef == "string") {
if (typeof scopeRef === "string") {
// 当scope是以@开头的字符串时,代表是一个路径指向,如:@./user,代表其scope是由user属性值指向的对象路径
if(scopeRef.startsWith("@")){ //
scope = getComputedScope(store,{
Expand Down
2 changes: 1 addition & 1 deletion packages/reactive/src/store/useState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export function createUseState<T extends Dict>(store:IStore<T>){
const value = getter(state as StateType)
// @ts-ignore
let setValue = setState
if( typeof(setter)=='function' ){
if( typeof(setter) === 'function' ){
// @ts-ignore
setValue=(value:SetValue)=>{
// @ts-ignore
Expand Down
2 changes: 1 addition & 1 deletion packages/reactive/src/utils/forEachObject.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export function forEachObject<T extends Dict>(obj:T,callback?:(params:{key:strin
function _forEachObject(obj:T,key:string[]){
for(let k in obj){
const value = obj[k]
if(typeof(callback)=='function'){
if(typeof(callback) === 'function'){
callback({value,key:k,parent:obj,path:key.concat(k)})
}
if(typeof(value)==='object'){
Expand Down
2 changes: 1 addition & 1 deletion packages/reactive/src/utils/getRelValuePath.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ export function getRelValuePath(curPath:string[],relPath:'self' | 'root' | 'pare
relPath = relPath.replace(/^(\/)*/,"")
return relPath.split(OBJECT_PATH_DELIMITER)
}else{
return isRelPath ? [...curPath.slice(0,-1),...relPath.split(OBJECT_PATH_DELIMITER)] : [...relPath.split(OBJECT_PATH_DELIMITER)]
return isRelPath ? [...curPath.slice(0,-1),...relPath.split(OBJECT_PATH_DELIMITER)] : relPath.split(OBJECT_PATH_DELIMITER)
}
}else if(Array.isArray(relPath)){
return relPath
Expand Down
2 changes: 1 addition & 1 deletion packages/reactive/src/utils/getValueByPath.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ export function getValueByPath(state:any,path?:string | string[] | ((state:any)=
if(typeof(path)=== 'function'){
path = path.call(state,state)
}
paths = Array.isArray(path) ? path : (typeof(path)=='string' ? path.split(delimiter) : [])
paths = Array.isArray(path) ? path : (typeof(path) === 'string' ? path.split(delimiter) : [])
return paths.length > 0 ? getVal(state,paths) : state
}catch(e){
console.warn(e)
Expand Down
6 changes: 3 additions & 3 deletions packages/reactive/src/utils/isAsyncComputedDescriptor.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@

export function isAsyncComputedDescriptor(obj:any){
return typeof(obj)=='object'
return typeof(obj) === 'object'
&& obj.hasOwnProperty("__COMPUTED__")
&& ["async","sync"].includes(obj.__COMPUTED__)
&& obj.hasOwnProperty("fn") && typeof(obj.fn)=='function'
&& obj.hasOwnProperty("options") && typeof(obj.options)=='object'
&& obj.hasOwnProperty("fn") && typeof(obj.fn) === 'function'
&& obj.hasOwnProperty("options") && typeof(obj.options) === 'object'
}
2 changes: 1 addition & 1 deletion packages/reactive/src/utils/isAsyncComputedObject.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,5 @@
* @returns
*/
export function isAsyncComputedObject(obj:any){
return typeof(obj)=='object' && ["result","loading","timeout","retry","run"].every(s=>obj.hasOwnProperty(s))
return typeof(obj) === 'object' && ["result","loading","timeout","retry","run"].every(s=>obj.hasOwnProperty(s))
}
2 changes: 1 addition & 1 deletion packages/reactive/src/utils/isPromise.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export function isPromise(obj:any){
return (typeof(obj)=='function' && obj.then && typeof(obj.then)=='function') || (obj && obj instanceof Promise)
return (typeof(obj) === 'function' && obj.then && typeof(obj.then) === 'function') || (obj && obj instanceof Promise)

}
2 changes: 1 addition & 1 deletion packages/reactive/src/utils/normalizeDeps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export function normalizeDeps(arg:ComputedDepends | undefined):(string | string[
return (arg || []).map((dep: any) =>{
if(Array.isArray(dep)){
return dep
}else if(typeof(dep)=='string'){
}else if(typeof(dep) === 'string'){
if(['/',"./","../"].some(c=>dep.startsWith(c))){
return dep
}else{
Expand Down
2 changes: 1 addition & 1 deletion packages/reactive/src/watch/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export function normalizedWatchFilter(on:WatchDependParams=[]): WatchDepends{
if(on.length===0) return ()=>true
return (path:string[])=>{
return on.map(item=>
typeof(item)=='string' ?
typeof(item) === 'string' ?
item.split(OBJECT_PATH_DELIMITER)
: (Array.isArray(item) ? item : [String(item)])
).some(item=>joinValuePath(path)==joinValuePath(item))
Expand Down
2 changes: 1 addition & 1 deletion packages/reactive/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,6 @@ export default defineConfig({
globals: true,
environment: 'jsdom',
setupFiles: './vitest-setup.ts',
include:['**\/*.{test,spec}.ts']
include:['**/*.{test,spec}.ts']
},
});
Loading

0 comments on commit 5aad2f6

Please sign in to comment.