import { isArray, isFunction } from 'lodash'; import { reactive, UnwrapRef, watch } from '@vue/composition-api'; import { CellValue, SyncWatchMass } from '@/lib/types'; export const parseWatcher = (config) => { const [watcher, cb] = config; const watchKeys = isArray(watcher) ? watcher : [watcher]; return [watchKeys, cb]; }; export const buildWatchers = ( watchKeys: string[], dataWatcher: (key: string) => () => any, watchCb: Function, dataGetter: () => any, valueMass: SyncWatchMass, inputHandler?: (value: T) => void, immediate = true, ) => { watchKeys.forEach((key) => watch( dataWatcher(key), () => { valueMass.unused = false; valueMass.value = watchCb(dataGetter()); inputHandler && inputHandler(valueMass.value); }, { immediate }, ), ); }; export const useWatchSyncValue = ( defaultValue: T, config: | undefined | [string | string[], (rowData: Record) => T] | ((rowData: Record) => T), dataWatcher: (key: string) => () => any, dataGetter: () => any, inputHandler?: (value: UnwrapRef) => void, immediate = true, ) => { const valueMass = reactive({ unused: true, value: defaultValue as T, }); if (!config) { return valueMass; } if (isFunction(config)) { valueMass.unused = false; valueMass.value = config(dataGetter()) as UnwrapRef; } if (isArray(config)) { const [watchKeys, cb] = parseWatcher(config); buildWatchers(watchKeys, dataWatcher, cb, dataGetter, valueMass, inputHandler, immediate); } return valueMass; };