import {iPlcEventType, nextPlcKey, PlcPropsOptions, PlcPublicAttrs, tPlc} from "../utils/plc.utils"; import {computed, ExtractPropTypes, reactive, useNumber, useRefs} from "@peryl/react-compose"; import {PlcCollector} from "../group/PlcGroup"; import {usePlcPropsState} from "./usePlcPropsState"; import {tPlcScopeSlots, tPlcSlots} from "../utils/plc.scope-slots"; import {Validation} from "../../../Form/validate/createValidation"; import {PlainObject} from "@peryl/utils/event"; import {isRuleRequired} from "../../../Form/validate/validate.utils"; import {pick} from "@peryl/utils/pick"; import {PlcExclusion} from "../../standard/PlcExclusion"; export function useBasePlc( { props, event, slots, scopeSlots, }: { props: ExtractPropTypes, event: iPlcEventType, slots: tPlcSlots, scopeSlots: tPlcScopeSlots, } ) { const plcExclusion = PlcExclusion.use.inject(null); const { refs, onRef } = useRefs({ el: HTMLElement }); const childValidator = Validation.useValidationChild(new Proxy(props, { get(target, key) { if (key === 'label') {return target.title;} return (target as any)[key]; }, })); const isRequired = (data: PlainObject) => childValidator.getRules().some(rule => isRuleRequired(rule, data)); /*格式化props*/ const { numberState } = useNumber(props, ['order', 'width']); /*得到可以修改的props state*/ const { propsState, state } = usePlcPropsState(computed(() => ({ ...pick(props, Object.keys(PlcPropsOptions) as (keyof typeof PlcPropsOptions)[]), ...numberState, }) as Omit & typeof numberState)); const plc: tPlc = reactive({ /*PlcPublicAttrs 在 copyPlc中会深度复制一遍,这里适配类型即可*/ ...PlcPublicAttrs, plcKey: `${props.field || ''}_${nextPlcKey()}`, isRequired, group: false, props: propsState, sourceProps: props, slots, scopeSlots, event, refer: () => plc, refs, /*列宽发生调整*/ setDurWidth: (durWidth: number) => plc.setPropsState({ width: Number((propsState.width)) + durWidth }), /*对propsState的state的修改,最好都通过setPropsState来进行,这样可以出发table的onConfigPlc这个hooks*/ setPropsState: (data: any) => { Object.entries(data).forEach(([key, val]) => {(propsState as any)[key] = val;}); // todo // table.emitConfigPlc(); }, /*有时候希望直接修改props的state,可以通过这个方法获取修改,这样的不会触发table的onConfigPlc这个hook*/ getState: () => state as any, getWidth: () => propsState.width }); const isExclude = !!plcExclusion && plcExclusion.props.isExclude(plc); plc.isExclude = () => isExclude; /*collector收集列信息*/ !isExclude && PlcCollector.child({ sort: () => refs.el! }); return { refer: plc, render: () => () }; }