import {each, is} from './utils' import {Controller} from './Controller' import {Lookup, ControllerUpdate} from './types' export interface MixingRef{ current: Controller[] each (eachFn: {(ctrl: Controller): any}): this add (ctrl: Controller): void del (ctrl: Controller): void set (values: Partial): this pause (keys: string | string[]): this resume (keys: string | string[]): this update(props: ControllerUpdate): this start(): any stop(): this _getProps ( arg: ControllerUpdate | { (i: number, ctrl: Controller): ControllerUpdate }, ctrl: Controller, index: number ): ControllerUpdate } export function MixingRef() { const current: Controller[] = [] const ref: MixingRef = (props: any) => { const results: any[] = [] each(current, (ctrl, i) => { if (is.und(props)) { results.push(ctrl.start()) } else { const update = ref._getProps(props, ctrl, i) if (update) { results.push(ctrl.start(update)) } } }) return results } ref.current = current ref.each = (eachFn) => { each(current as any[], eachFn) return this } ref.add = (ctrl: Controller) => { if (!current.includes(ctrl)) current.push(ctrl) } ref.del = (ctrl: Controller) => { const i = current.indexOf(ctrl) if (~i) current.splice(i, 1) } ref.set = (...args) => ref.each(ctrl => ctrl.set(...args)) ref.pause = (...args) => ref.each(ctrl => ctrl.pause(...args)) ref.resume = (...args) => ref.each(ctrl => ctrl.resume(...args)) ref.start = (...args) => ref.each(ctrl => ctrl.start(...args)) ref.stop = (...args) => ref.each(ctrl => ctrl.stop(...args)) ref.update = (...args) => ref.each(ctrl => ctrl.update(...args)) ref._getProps = (arg, ctrl, index) => { return typeof arg === "function"? arg(index, ctrl): arg } return ref }