choice.ts 1.2 KB

1234567891011121314151617181920212223242526272829303132333435
  1. /**
  2. * Copyright (c) 2018-2022 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author Adam Midlik <midlik@gmail.com>
  5. */
  6. import { ParamDefinition as PD } from '../../mol-util/param-definition';
  7. /**
  8. * Represents a set of values to choose from, with a default value. Example:
  9. * ```
  10. * export const MyChoice = new Choice({ yes: 'I agree', no: 'Nope' }, 'yes');
  11. * export type MyChoiceType = Choice.Values<typeof MyChoice>; // 'yes'|'no'
  12. * ```
  13. */
  14. export class Choice<T extends string, D extends T> {
  15. readonly defaultValue: D;
  16. readonly options: [T, string][];
  17. private readonly nameDict: { [value in T]: string };
  18. constructor(opts: { [value in T]: string }, defaultValue: D) {
  19. this.defaultValue = defaultValue;
  20. this.options = Object.keys(opts).map(k => [k as T, opts[k as T]]);
  21. this.nameDict = opts;
  22. }
  23. PDSelect(defaultValue?: T, info?: PD.Info): PD.Select<T> {
  24. return PD.Select<T>(defaultValue ?? this.defaultValue, this.options, info);
  25. }
  26. prettyName(value: T): string {
  27. return this.nameDict[value];
  28. }
  29. }
  30. export namespace Choice {
  31. export type Values<T extends Choice<any, any>> = T extends Choice<infer R, any> ? R : any;
  32. }