asset-manager.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /**
  2. * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author Alexander Rose <alexander.rose@weirdbyte.de>
  5. */
  6. import { UUID } from '../../mol-util';
  7. import { PluginContext } from '../context';
  8. import { iterableToArray } from '../../mol-data/util';
  9. export { AssetManager };
  10. class AssetManager {
  11. private files = new Map<UUID, File>()
  12. private ids = new Map<File, UUID>()
  13. get list() {
  14. return iterableToArray(this.ids.entries());
  15. }
  16. set(id: UUID, file: File) {
  17. this.files.set(id, file);
  18. this.ids.set(file, id);
  19. }
  20. remove(id: UUID) {
  21. if (this.files.has(id)) {
  22. const file = this.files.get(id)!;
  23. this.files.delete(id);
  24. this.ids.delete(file);
  25. }
  26. }
  27. has(id: UUID) {
  28. return this.files.has(id);
  29. }
  30. get(id: UUID) {
  31. return this.files.get(id);
  32. }
  33. /** For use with `JSON.stringify` */
  34. replacer = (key: string, value: any) => {
  35. if (value instanceof File) {
  36. const id = this.ids.get(value);
  37. if (!id) {
  38. // TODO throw?
  39. console.warn(`No asset found for '${value.name}'`);
  40. }
  41. return id ? AssetManager.Item(id, value.name) : {};
  42. } else {
  43. return value;
  44. }
  45. }
  46. constructor(public ctx: PluginContext) {
  47. ctx.state.data.events.object.removed.subscribe(e => {
  48. const id = e.obj?.id;
  49. if (id) ctx.managers.asset.remove(id);
  50. });
  51. }
  52. }
  53. namespace AssetManager {
  54. export type Item = { kind: 'asset-item', id: UUID, name: string };
  55. export function Item(id: UUID, name: string): Item {
  56. return { kind: 'asset-item', id, name };
  57. }
  58. export function isItem(x?: any): x is Item {
  59. return !!x && x?.kind === 'asset-item';
  60. }
  61. }