custom-property-registry.ts 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /**
  2. * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author David Sehnal <david.sehnal@gmail.com>
  5. */
  6. import { ModelPropertyDescriptor, Model } from 'mol-model/structure';
  7. import { OrderedMap } from 'immutable';
  8. import { ParamDefinition } from 'mol-util/param-definition';
  9. import { Task } from 'mol-task';
  10. export { CustomPropertyRegistry }
  11. class CustomPropertyRegistry {
  12. private providers = OrderedMap<string, CustomPropertyRegistry.Provider>().asMutable();
  13. getSelect(model: Model) {
  14. const values = this.providers.values();
  15. const options: [string, string][] = [], selected: string[] = [];
  16. while (true) {
  17. const v = values.next();
  18. if (v.done) break;
  19. if (!v.value.attachableTo(model)) continue;
  20. options.push(v.value.option);
  21. if (v.value.defaultSelected) selected.push(v.value.option[0]);
  22. }
  23. return ParamDefinition.MultiSelect(selected, options);
  24. }
  25. getDefault(model: Model) {
  26. const values = this.providers.values();
  27. const selected: string[] = [];
  28. while (true) {
  29. const v = values.next();
  30. if (v.done) break;
  31. if (!v.value.attachableTo(model)) continue;
  32. if (v.value.defaultSelected) selected.push(v.value.option[0]);
  33. }
  34. return selected;
  35. }
  36. get(name: string) {
  37. const prop = this.providers.get(name);
  38. if (!prop) throw new Error(`Custom prop '${name}' is not registered.`);
  39. return this.providers.get(name);
  40. }
  41. register(provider: CustomPropertyRegistry.Provider) {
  42. this.providers.set(provider.descriptor.name, provider);
  43. }
  44. unregister(name: string) {
  45. this.providers.delete(name);
  46. }
  47. }
  48. namespace CustomPropertyRegistry {
  49. export interface Provider {
  50. option: [string, string],
  51. defaultSelected: boolean,
  52. descriptor: ModelPropertyDescriptor<any, any>,
  53. attachableTo: (model: Model) => boolean,
  54. attach: (model: Model) => Task<boolean>
  55. }
  56. }