param-mapping.ts 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. /**
  2. * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author David Sehnal <david.sehnal@gmail.com>
  5. */
  6. import { ParamDefinition as PD } from './param-definition';
  7. import { produce } from 'immer';
  8. import { Mutable } from './type-helpers';
  9. export interface ParamMapping<S, T, Ctx> {
  10. params(ctx: Ctx): PD.For<S>,
  11. getTarget(ctx: Ctx): T,
  12. getValues(t: T, ctx: Ctx): S,
  13. update(s: S, ctx: Ctx): T,
  14. apply(t: T, ctx: Ctx): void | Promise<void>
  15. }
  16. export function ParamMapping<S, T, Ctx>(def: {
  17. params: ((ctx: Ctx) => PD.For<S>) | PD.For<S>,
  18. target(ctx: Ctx): T
  19. }): (options: {
  20. values(t: T, ctx: Ctx): S,
  21. update(s: S, t: Mutable<T>, ctx: Ctx): void,
  22. apply?(t: T, ctx: Ctx): void | Promise<void>
  23. }) => ParamMapping<S, T, Ctx> {
  24. return ({ values, update, apply }) => ({
  25. params: typeof def.params === 'function' ? def.params as any : ctx => def.params,
  26. getTarget: def.target,
  27. getValues: values,
  28. update(s, ctx) {
  29. const t = def.target(ctx);
  30. return produce(t, (t1: Mutable<T>) => update(s, t1, ctx));
  31. },
  32. apply: apply ? apply : () => { }
  33. });
  34. }