drag-and-drop.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /**
  2. * Copyright (c) 2023 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author David Sehnal <david.sehnal@gmail.com>
  5. */
  6. import { OpenFiles } from '../actions/file';
  7. import { Asset } from '../../mol-util/assets';
  8. import { PluginCommands } from '../../mol-plugin/commands';
  9. import { PluginContext } from '../../mol-plugin/context';
  10. export type PluginDragAndDropHandler = (files: File[], plugin: PluginContext) => Promise<boolean> | boolean
  11. export class DragAndDropManager {
  12. private handlers: [name: string, handler: PluginDragAndDropHandler][] = [];
  13. addHandler(name: string, handler: PluginDragAndDropHandler) {
  14. const index = this.handlers.findIndex(h => h[0] === name);
  15. if (index < 0) this.handlers.push([name, handler]);
  16. else this.handlers[index][1] = handler;
  17. }
  18. removeHandler(name: string) {
  19. const index = this.handlers.findIndex(h => h[0] === name);
  20. if (index >= 0) this.handlers.splice(index, 1);
  21. }
  22. async handle(files: File[]) {
  23. for (let i = this.handlers.length - 1; i >= 0; i--) {
  24. const handler = this.handlers[i][1];
  25. const handled = await handler(files, this.plugin);
  26. if (handled) return;
  27. }
  28. defaultDragAndDropHandler(this.plugin, files);
  29. }
  30. constructor(public plugin: PluginContext) {
  31. }
  32. }
  33. function defaultDragAndDropHandler(plugin: PluginContext, files: File[]) {
  34. const sessions = files.filter(f => {
  35. const fn = f.name.toLowerCase();
  36. return fn.endsWith('.molx') || fn.endsWith('.molj');
  37. });
  38. if (sessions.length > 0) {
  39. PluginCommands.State.Snapshots.OpenFile(plugin, { file: sessions[0] });
  40. } else {
  41. plugin.runTask(plugin.state.data.applyAction(OpenFiles, {
  42. files: files.map(f => Asset.File(f)),
  43. format: { name: 'auto', params: {} },
  44. visuals: true
  45. }));
  46. }
  47. }