import { isString, isNumber, isArray, isPlainObject, isFunction } from '../../internal/base' import { looseCurryN } from '../../functional' import { TERMINATOR } from '../metas' import { Data, Mutation, isAtomLike, DEFAULT_MUTATION_OPTIONS } from '../atoms' import { pipeAtom, binaryTweenPipeAtom } from '../helpers' import { replayWithLatest } from '../mediators' import type { Vacuo, Terminator } from '../metas' import type { TransformationLiftPositions, MutatorOriginalTransformationUnion, MutatorTransformation, LiftBothTransformation, LiftLeftTransformation, LiftRightTransformation } from '../particles' import type { MutationOptions, AtomLikeOfOutput } from '../atoms' // S -> Single, M -> Multi /****************************************************************************************************** * * Utils Types * ******************************************************************************************************/ /** * */ type TupleToUnion = T[number] type ObjectToUnion> = T[keyof T] type ToUnion> = T extends any[] ? TupleToUnion : T extends Record ? ObjectToUnion: never interface WrapP { key: K, value: P | Vacuo } type WrapArrayPs = Ps extends [infer F, ...infer R] ? [WrapP, ...WrapArrayPs] : [] type WrapObjectPs> = { [K in keyof Ps]: { key: K, value: Ps[K] | Vacuo } } type WrapPs> = Ps extends any[] ? WrapArrayPs : Ps extends Record ? WrapObjectPs : never type ToBooleanTuple = T extends [infer _, ...infer R] ? [boolean, ...ToBooleanTuple] : [] type ToUndefinedableTuple = T extends [infer F, ...infer R] ? [F | undefined, ...ToUndefinedableTuple] : [] type ToBooleanObject> = { [K in keyof T]: boolean } type ToUndefinedableObject> = { [K in keyof T]?: T[K] | undefined } /****************************************************************************************************** * * MS Tache Common * ******************************************************************************************************/ /** * */ type CustomizeTypes = 'partly' | 'fully' type LiftTypes = Exclude /** * @typeParam AN - The type of acceptNonAtom * @typeParam CT - The type of customizeTypes * @typeParam LT - The type of MutationLiftPosition */ interface MSTacheCommonConfig< Ps extends any[] | Record, C, Contexts extends any[] = any[], AN extends boolean = boolean, CT extends CustomizeTypes = CustomizeTypes, LT extends LiftTypes = LiftTypes > { /** * Default to `true`. */ acceptNonAtom?: AN /** * Default to `partly`. */ customizeType?: CT options?: MutationOptions, C, Contexts> & { lift?: { position?: LT }} /** * Default to `true`. */ autoUpdateContexts?: boolean sourcesType: 'array' | 'object' } const DEFAULT_MS_TACHE_COMMON_CONFIG: Omit>, 'sourcesType'> = { acceptNonAtom: true, customizeType: 'partly', options: DEFAULT_MUTATION_OPTIONS as any, autoUpdateContexts: true } /****************************************************************************************************** * * Array MS Tache * ******************************************************************************************************/ /** * */ interface ArrayMSTacheTrunkBaseContexts { arity: number TERMINATOR: Terminator } type ArrayMSTacheFullyTransformation = (contexts: ArrayMSTacheTrunkBaseContexts) => LT extends 'both' ? LiftBothTransformation>, C> : LT extends 'left' ? LiftLeftTransformation>, C> : LT extends 'right' ? LiftRightTransformation>, C> : LT extends 'none' ? MutatorTransformation>, C> : never interface ArrayMSTacheTrunkContextsForPartly extends ArrayMSTacheTrunkBaseContexts { states: ToBooleanTuple values: ToUndefinedableTuple [key: string]: any } interface ArrayMSTacheConfig< Ps extends any[], C, AN extends boolean = boolean, CT extends CustomizeTypes = CustomizeTypes, LT extends LiftTypes = LiftTypes > extends MSTacheCommonConfig { /** * Indicate how many sources will take into account for the generated Tache. * If is provided, the generated Tache will be loose curried with the number of sources. * * Default to `undefined`, which means the generated Tache will not be curried, the number of sources * took into account is the same as the number of sources passed in. */ arity?: number transformation: CT extends 'partly' ? ( LT extends 'both' ? LiftBothTransformation>, C, [ArrayMSTacheTrunkContextsForPartly]> : LT extends 'left' ? LiftLeftTransformation>, C, [ArrayMSTacheTrunkContextsForPartly]> : LT extends 'right' ? LiftRightTransformation>, C, [ArrayMSTacheTrunkContextsForPartly]> : LT extends 'none' ? MutatorTransformation>, C, [ArrayMSTacheTrunkContextsForPartly]> : never ) : CT extends 'fully' ? ArrayMSTacheFullyTransformation : never sourcesType: 'array' } type WrapArrayToAtomLikeOfOutput = T extends [infer F, ...infer R] ? [AN extends true ? AtomLikeOfOutput | F : AtomLikeOfOutput, ...WrapArrayToAtomLikeOfOutput] : [] /** * @typeParam AN - The type of acceptNonAtom */ export type ArrayMSTache = (...sources: WrapArrayToAtomLikeOfOutput | [WrapArrayToAtomLikeOfOutput]) => Data /** * @typeParam AN - The type of acceptNonAtom * @typeParam CT - The type of customizeTypes * @typeParam LT - The type of MutationLiftPosition */ export function createArrayMSTache< Ps extends any[], C, AN extends boolean = boolean, CT extends CustomizeTypes = CustomizeTypes, LT extends LiftTypes = LiftTypes > ( config: ArrayMSTacheConfig ): ArrayMSTache { if (!isPlainObject(config)) { throw (new TypeError('"config" is expected to be type of "PlainObject".')) } const { arity, acceptNonAtom, customizeType, options, transformation, autoUpdateContexts } = { ...DEFAULT_MS_TACHE_COMMON_CONFIG as Omit>, 'sourcesType'>, ...config } if (!isString(customizeType)) { throw (new TypeError('"customizeType" is expected to be type of "String".')) } if (customizeType !== 'partly' && customizeType !== 'fully') { throw (new TypeError('"customizeType" is expected to be "fully" | "partly".')) } if (transformation === undefined) { throw (new TypeError('"transformation" is required.')) } if (!isFunction(transformation)) { throw (new TypeError('"transformation" is expected to be type of "Function".')) } type ValidSource = AtomLikeOfOutput /** * @return Data */ const tache: ArrayMSTache = (...sources) => { let preparedSources: ValidSource[] let _sources: ValidSource[] if (sources.length === 1 && isArray(sources[0])) { _sources = sources[0] } else { _sources = sources as ValidSource[] } if (!acceptNonAtom) { _sources.forEach(source => { if (!isAtomLike(source)) { throw (new TypeError('"source" is expected to be type of "AtomLike".')) } }) preparedSources = _sources } else { preparedSources = _sources.map(source => { return (isAtomLike(source) ? source : replayWithLatest(1, Data.of(source))) as ValidSource }) } const length = arity ?? preparedSources.length // TODO: add more accurate types const wrapMutations: Mutation[] = Array.from({ length }).map((_, index) => Mutation.ofLiftLeft(prev => ({ key: index, value: prev })) ) const wrappedDatas: Data[] = Array.from({ length }).map(() => Data.empty()) const trunkM = Mutation.ofLift((() => { const baseContexts: ArrayMSTacheTrunkBaseContexts = { arity: length, TERMINATOR } if (customizeType === 'fully') { const contexts: ArrayMSTacheTrunkBaseContexts = { ...baseContexts } const actualTransformation = (transformation as ArrayMSTacheFullyTransformation)(contexts) if (!isFunction(actualTransformation)) { throw (new TypeError('"transformation" is expected to return a "Function" when "customizeType" is specified to "fully".')) } return actualTransformation } else if (customizeType === 'partly') { const contexts = { ...baseContexts, states: Array.from({ length: length }), values: Array.from({ length: length }) } // actual transformation which will takes prevDatar(or its value) & datar(ot its value) as argument const actualTransformation: MutatorOriginalTransformationUnion>, C | Terminator> = (prev: any, cur: any, mutation: any, ...args: any[]): any => { if (autoUpdateContexts) { const { key, value } = prev contexts.states[key] = true contexts.values[key] = value } return transformation(prev, cur, mutation, contexts, ...args) } return actualTransformation } })() as MutatorOriginalTransformationUnion>, C | Terminator>, options) const output = Data.empty() pipeAtom(trunkM, output) wrappedDatas.forEach(data => { pipeAtom(data, trunkM) }) wrapMutations.forEach((wrapMutation, idx) => { pipeAtom(wrapMutation, wrappedDatas[idx]) }) preparedSources.forEach((source, idx) => { binaryTweenPipeAtom(source, wrapMutations[idx]) }) return output } if (isNumber(arity)) { return looseCurryN(arity, tache) } else { return tache } } /****************************************************************************************************** * * Object MS Tache * ******************************************************************************************************/ /** * */ interface ObjectMSTacheTrunkBaseContexts { keysOfSources: Array TERMINATOR: Terminator } type ObjectMSTacheFullyTransformation, C, LT extends LiftTypes = LiftTypes> = (contexts: ObjectMSTacheTrunkBaseContexts) => LT extends 'both' ? LiftBothTransformation>, C> : LT extends 'left' ? LiftLeftTransformation>, C> : LT extends 'right' ? LiftRightTransformation>, C> : LT extends 'none' ? MutatorTransformation>, C> : never interface ObjectMSTacheTrunkContextsForPartly = Record> extends ArrayMSTacheTrunkBaseContexts { states: ToBooleanObject values: ToUndefinedableObject [key: string]: any } interface ObjectMSTacheConfig< Ps extends Record, C, AN extends boolean = boolean, CT extends CustomizeTypes = CustomizeTypes, LT extends LiftTypes = LiftTypes > extends MSTacheCommonConfig { transformation: CT extends 'partly' ? ( LT extends 'both' ? LiftBothTransformation>, C, [ObjectMSTacheTrunkContextsForPartly]> : LT extends 'left' ? LiftLeftTransformation>, C, [ObjectMSTacheTrunkContextsForPartly]> : LT extends 'right' ? LiftRightTransformation>, C, [ObjectMSTacheTrunkContextsForPartly]> : LT extends 'none' ? MutatorTransformation>, C, [ObjectMSTacheTrunkContextsForPartly]> : never ) : CT extends 'fully' ? ObjectMSTacheFullyTransformation : never sourcesType: 'object' } type WrapObjectToAtomLikeOfOutput, AN> = { [K in keyof T]: AN extends true ? T[K] | AtomLikeOfOutput : AtomLikeOfOutput } /** * @typeParam AN - The type of acceptNonAtom */ export type ObjectMSTache = (sources: WrapObjectToAtomLikeOfOutput) => Data /** * @typeParam AN - The type of acceptNonAtom * @typeParam CT - The type of customizeTypes * @typeParam LT - The type of MutationLiftPosition */ export const createObjectMSTache = < Ps extends Record, C, AN extends boolean = boolean, CT extends CustomizeTypes = CustomizeTypes, LT extends LiftTypes = LiftTypes >( config: ObjectMSTacheConfig ): ObjectMSTache => { if (!isPlainObject(config)) { throw (new TypeError('"config" is expected to be type of "PlainObject".')) } const { acceptNonAtom, customizeType, options, transformation, autoUpdateContexts } = { ...DEFAULT_MS_TACHE_COMMON_CONFIG as Omit>, 'sourcesType'>, ...config } if (!isString(customizeType)) { throw (new TypeError('"customizeType" is expected to be type of "String".')) } if (customizeType !== 'partly' && customizeType !== 'fully') { throw (new TypeError('"customizeType" is expected to be "fully" | "partly".')) } if (transformation === undefined) { throw (new TypeError('"transformation" is required when use makeArrayMSTache to make tache.')) } if (!isFunction(transformation)) { throw (new TypeError('"transformation" is expected to be type of "Function".')) } type ValidSource = AtomLikeOfOutput type ValidSources = Record /** * @param sources Object * @accept ({ name: Atom | Any, ...}) * @return Data */ const tache: ObjectMSTache = (sources) => { if (!isPlainObject(sources)) { throw (new TypeError('"sources" is expected to be type of "PlainObject".')) } let preparedSources: ValidSources if (!acceptNonAtom) { Object.values(sources).forEach(source => { if (!isAtomLike(source)) { throw (new TypeError('"source" is expected to be type of "AtomLike".')) } }) preparedSources = sources } else { preparedSources = Object.entries(sources).reduce( (newSources, [name, source]) => { newSources[name] = newSources[name] ?? (isAtomLike(source) ? source : replayWithLatest(1, Data.of(source))) return newSources }, {} ) } // TODO: add more accurate types const wrapMutations = Object.entries(preparedSources).reduce>( (mutations, [key]) => { mutations[key] = Mutation.ofLiftLeft((prev) => ({ key: key, value: prev })) return mutations }, {}) const wrappedDatas = Object.entries(preparedSources).reduce>( (datas, [key]) => { datas[key] = Data.empty() return datas }, {}) const trunkM = Mutation.ofLift((() => { const baseContexts: ObjectMSTacheTrunkBaseContexts = { keysOfSources: Object.keys(preparedSources), TERMINATOR } if (customizeType === 'fully') { const contexts = { ...baseContexts } const actualTransformation = (transformation as ObjectMSTacheFullyTransformation)(contexts) if (!isFunction(actualTransformation)) { throw (new TypeError('"transformation" is expected to return a "Function" when "customizeType" is specified to "fully".')) } return actualTransformation } else if (customizeType === 'partly') { const contexts = { ...baseContexts, states: Object.keys(preparedSources).reduce>((acc, key) => { acc[key] = false return acc }, {}), values: Object.keys(preparedSources).reduce>((acc, key) => { acc[key] = undefined return acc }, {}) } // actual transformation which will takes prevDatar(or its value) & datar(ot its value) as argument const actualTransformation: MutatorOriginalTransformationUnion>, C | Terminator> = (prev: any, cur: any, mutation: any, ...args: any[]): any => { if (autoUpdateContexts) { const { key, value } = prev contexts.states[key] = true contexts.values[key] = value } return transformation(prev, cur, mutation, contexts, ...args) } return actualTransformation } })() as MutatorOriginalTransformationUnion>, C | Terminator>, options) const output = Data.empty() pipeAtom(trunkM, output) Object.values(wrappedDatas).forEach(data => { pipeAtom(data, trunkM) }) Object.entries(wrapMutations).forEach(([key, wrapMutation]) => { pipeAtom(wrapMutation, wrappedDatas[key]) }) Object.entries(sources).forEach(([key, source]) => { binaryTweenPipeAtom(source, wrapMutations[key]) }) return output } return tache } interface ICreateMSTache { ( config: ArrayMSTacheConfig ): ArrayMSTache , C, AN extends boolean = boolean, CT extends CustomizeTypes = CustomizeTypes, LT extends LiftTypes = LiftTypes>( config: ObjectMSTacheConfig ): ObjectMSTache } /** * @return TacheMaker */ export const createMSTache: ICreateMSTache = (config: any): any => { if (!isPlainObject(config)) { throw (new TypeError(`"config" is expected to be type of "PlainObject", but received "${typeof config}".`)) } const { sourcesType } = config if (sourcesType === 'array') { return createArrayMSTache(config as any) } else if (sourcesType === 'object') { return createObjectMSTache(config as any) } return (...sources: any[]) => { if (sources.length === 1 && isPlainObject(sources[0])) { return createObjectMSTache(config as any)(sources[0]) } if (sources.length === 1 && isArray(sources[0])) { return createArrayMSTache(config as any)(...sources[0] as any) } if (sources.length > 1) { return createArrayMSTache(config as any)(...sources as any) } } }