plugin.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. /**
  2. * Copyright (c) 2018-2023 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author David Sehnal <david.sehnal@gmail.com>
  5. * @author Alexander Rose <alexander.rose@weirdbyte.de>
  6. */
  7. import { List } from 'immutable';
  8. import * as React from 'react';
  9. import { formatTime } from '../mol-util';
  10. import { LogEntry } from '../mol-util/log-entry';
  11. import { PluginReactContext, PluginUIComponent } from './base';
  12. import { AnimationViewportControls, DefaultStructureTools, LociLabels, StateSnapshotViewportControls, TrajectoryViewportControls, SelectionViewportControls } from './controls';
  13. import { LeftPanelControls } from './left-panel';
  14. import { SequenceView } from './sequence';
  15. import { BackgroundTaskProgress, OverlayTaskProgress } from './task';
  16. import { Toasts } from './toast';
  17. import { Viewport, ViewportControls } from './viewport';
  18. import { PluginCommands } from '../mol-plugin/commands';
  19. import { PluginUIContext } from './context';
  20. import { OpenFiles } from '../mol-plugin-state/actions/file';
  21. import { Asset } from '../mol-util/assets';
  22. import { BehaviorSubject } from 'rxjs';
  23. import { useBehavior } from './hooks/use-behavior';
  24. export function Plugin({ plugin }: { plugin: PluginUIContext }) {
  25. if (plugin.isInitialized) {
  26. return <PluginReactContext.Provider value={plugin}>
  27. <Layout />
  28. </PluginReactContext.Provider>;
  29. }
  30. return <PluginInitWrapper plugin={plugin} />;
  31. }
  32. type LoadState =
  33. | { kind: 'initialized' }
  34. | { kind: 'pending' }
  35. | { kind: 'error', message: string }
  36. function PluginInitWrapper({ plugin }: { plugin: PluginUIContext }) {
  37. const [state, setState] = React.useState<LoadState>({ kind: 'pending' });
  38. React.useEffect(() => {
  39. setState({ kind: 'pending' });
  40. let mounted = true;
  41. plugin.initialized.then(() => {
  42. if (mounted) setState({ kind: 'initialized' });
  43. }).catch(err => {
  44. if (mounted) setState({ kind: 'error', message: `${err}` });
  45. });
  46. return () => { mounted = false; };
  47. }, [plugin]);
  48. if (state.kind === 'pending') return null;
  49. if (state.kind === 'error') {
  50. return <div className='msp-plugin'>
  51. <div className='msp-plugin-init-error'>Initialization error: {state.message}</div>
  52. </div>;
  53. }
  54. return <PluginReactContext.Provider value={plugin}>
  55. <Layout />
  56. </PluginReactContext.Provider>;
  57. }
  58. export class PluginContextContainer extends React.Component<{ plugin: PluginUIContext, children?: any }> {
  59. render() {
  60. return <PluginReactContext.Provider value={this.props.plugin}>
  61. <div className='msp-plugin'>
  62. {this.props.children}
  63. </div>
  64. </PluginReactContext.Provider>;
  65. }
  66. }
  67. type RegionKind = 'top' | 'left' | 'right' | 'bottom' | 'main'
  68. class Layout extends PluginUIComponent {
  69. componentDidMount() {
  70. this.subscribe(this.plugin.layout.events.updated, () => this.forceUpdate());
  71. }
  72. region(kind: RegionKind, Element?: React.ComponentClass) {
  73. return <div className={`msp-layout-region msp-layout-${kind}`}>
  74. <div className='msp-layout-static'>
  75. {Element ? <Element /> : null}
  76. </div>
  77. </div>;
  78. }
  79. get layoutVisibilityClassName() {
  80. const layout = this.plugin.layout.state;
  81. const controls = this.plugin.spec.components?.controls ?? {};
  82. const classList: string[] = [];
  83. if (controls.top === 'none' || !layout.showControls || layout.regionState.top === 'hidden') {
  84. classList.push('msp-layout-hide-top');
  85. }
  86. if (controls.left === 'none' || !layout.showControls || layout.regionState.left === 'hidden') {
  87. classList.push('msp-layout-hide-left');
  88. } else if (layout.regionState.left === 'collapsed') {
  89. classList.push('msp-layout-collapse-left');
  90. }
  91. if (controls.right === 'none' || !layout.showControls || layout.regionState.right === 'hidden') {
  92. classList.push('msp-layout-hide-right');
  93. }
  94. if (controls.bottom === 'none' || !layout.showControls || layout.regionState.bottom === 'hidden') {
  95. classList.push('msp-layout-hide-bottom');
  96. }
  97. return classList.join(' ');
  98. }
  99. get layoutClassName() {
  100. const layout = this.plugin.layout.state;
  101. const classList: string[] = ['msp-plugin-content'];
  102. if (layout.isExpanded) {
  103. classList.push('msp-layout-expanded');
  104. } else {
  105. classList.push('msp-layout-standard', `msp-layout-standard-${layout.controlsDisplay}`);
  106. }
  107. return classList.join(' ');
  108. }
  109. onDrop = (ev: React.DragEvent<HTMLDivElement>) => {
  110. ev.preventDefault();
  111. const files: File[] = [];
  112. if (ev.dataTransfer.items) {
  113. // Use DataTransferItemList interface to access the file(s)
  114. for (let i = 0; i < ev.dataTransfer.items.length; i++) {
  115. if (ev.dataTransfer.items[i].kind !== 'file') continue;
  116. const file = ev.dataTransfer.items[i].getAsFile();
  117. if (file) files.push(file);
  118. }
  119. } else {
  120. for (let i = 0; i < ev.dataTransfer.files.length; i++) {
  121. const file = ev.dataTransfer.files[i];
  122. if (file) files.push(file);
  123. }
  124. }
  125. const sessions = files.filter(f => {
  126. const fn = f.name.toLowerCase();
  127. return fn.endsWith('.molx') || fn.endsWith('.molj');
  128. });
  129. if (sessions.length > 0) {
  130. PluginCommands.State.Snapshots.OpenFile(this.plugin, { file: sessions[0] });
  131. } else {
  132. this.plugin.runTask(this.plugin.state.data.applyAction(OpenFiles, {
  133. files: files.map(f => Asset.File(f)),
  134. format: { name: 'auto', params: {} },
  135. visuals: true
  136. }));
  137. }
  138. };
  139. onDragOver = (ev: React.DragEvent<HTMLDivElement>) => {
  140. ev.preventDefault();
  141. };
  142. private showDragOverlay = new BehaviorSubject(false);
  143. onDragEnter = () => this.showDragOverlay.next(true);
  144. render() {
  145. const layout = this.plugin.layout.state;
  146. const controls = this.plugin.spec.components?.controls || {};
  147. const viewport = this.plugin.spec.components?.viewport?.view || DefaultViewport;
  148. return <div className='msp-plugin'>
  149. <div className={this.layoutClassName} onDragEnter={this.onDragEnter}>
  150. <div className={this.layoutVisibilityClassName}>
  151. {this.region('main', viewport)}
  152. {layout.showControls && controls.top !== 'none' && this.region('top', controls.top || SequenceView)}
  153. {layout.showControls && controls.left !== 'none' && this.region('left', controls.left || LeftPanelControls)}
  154. {layout.showControls && controls.right !== 'none' && this.region('right', controls.right || ControlsWrapper)}
  155. {layout.showControls && controls.bottom !== 'none' && this.region('bottom', controls.bottom || Log)}
  156. </div>
  157. {!this.plugin.spec.components?.hideTaskOverlay && <OverlayTaskProgress />}
  158. {!this.plugin.spec.components?.disableDragOverlay && <DragOverlay plugin={this.plugin} showDragOverlay={this.showDragOverlay} />}
  159. </div>
  160. </div>;
  161. }
  162. }
  163. function dropFiles(ev: React.DragEvent<HTMLDivElement>, plugin: PluginUIContext, showDragOverlay: BehaviorSubject<boolean>) {
  164. ev.preventDefault();
  165. ev.stopPropagation();
  166. showDragOverlay.next(false);
  167. const files: File[] = [];
  168. if (ev.dataTransfer.items) {
  169. // Use DataTransferItemList interface to access the file(s)
  170. for (let i = 0; i < ev.dataTransfer.items.length; i++) {
  171. if (ev.dataTransfer.items[i].kind !== 'file') continue;
  172. const file = ev.dataTransfer.items[i].getAsFile();
  173. if (file) files.push(file);
  174. }
  175. } else {
  176. for (let i = 0; i < ev.dataTransfer.files.length; i++) {
  177. const file = ev.dataTransfer.files[i];
  178. if (file) files.push(file);
  179. }
  180. }
  181. plugin.managers.dragAndDrop.handle(files);
  182. }
  183. function DragOverlay({ plugin, showDragOverlay }: { plugin: PluginUIContext, showDragOverlay: BehaviorSubject<boolean> }) {
  184. const show = useBehavior(showDragOverlay);
  185. const preventDrag = (e: React.DragEvent) => {
  186. e.dataTransfer.dropEffect = 'copy';
  187. e.preventDefault();
  188. e.stopPropagation();
  189. };
  190. return <div
  191. className='msp-drag-drop-overlay'
  192. style={{ display: show ? 'flex' : 'none' }}
  193. onDragEnter={preventDrag}
  194. onDragOver={preventDrag}
  195. onDragLeave={() => showDragOverlay.next(false)}
  196. onDrop={e => dropFiles(e, plugin, showDragOverlay)}
  197. >
  198. Load File(s)
  199. </div>;
  200. }
  201. export class ControlsWrapper extends PluginUIComponent {
  202. render() {
  203. const StructureTools = this.plugin.spec.components?.structureTools || DefaultStructureTools;
  204. return <div className='msp-scrollable-container'>
  205. <StructureTools />
  206. </div>;
  207. }
  208. }
  209. export class DefaultViewport extends PluginUIComponent {
  210. render() {
  211. const VPControls = this.plugin.spec.components?.viewport?.controls || ViewportControls;
  212. return <>
  213. <Viewport />
  214. <div className='msp-viewport-top-left-controls'>
  215. <AnimationViewportControls />
  216. <TrajectoryViewportControls />
  217. <StateSnapshotViewportControls />
  218. </div>
  219. <SelectionViewportControls />
  220. <VPControls />
  221. <BackgroundTaskProgress />
  222. <div className='msp-highlight-toast-wrapper'>
  223. <LociLabels />
  224. <Toasts />
  225. </div>
  226. </>;
  227. }
  228. }
  229. export class Log extends PluginUIComponent<{}, { entries: List<LogEntry> }> {
  230. private wrapper = React.createRef<HTMLDivElement>();
  231. componentDidMount() {
  232. this.subscribe(this.plugin.events.log, () => this.setState({ entries: this.plugin.log.entries }));
  233. }
  234. componentDidUpdate() {
  235. this.scrollToBottom();
  236. }
  237. state = { entries: this.plugin.log.entries };
  238. private scrollToBottom() {
  239. const log = this.wrapper.current;
  240. if (log) log.scrollTop = log.scrollHeight - log.clientHeight - 1;
  241. }
  242. render() {
  243. // TODO: ability to show full log
  244. // showing more entries dramatically slows animations.
  245. const maxEntries = 10;
  246. const xs = this.state.entries, l = xs.size;
  247. const entries: JSX.Element[] = [];
  248. for (let i = Math.max(0, l - maxEntries), o = 0; i < l; i++) {
  249. const e = xs.get(i);
  250. entries.push(<li key={o++}>
  251. <div className={'msp-log-entry-badge msp-log-entry-' + e!.type} />
  252. <div className='msp-log-timestamp'>{formatTime(e!.timestamp)}</div>
  253. <div className='msp-log-entry'>{e!.message}</div>
  254. </li>);
  255. }
  256. return <div ref={this.wrapper} className='msp-log' style={{ position: 'absolute', top: '0', right: '0', bottom: '0', left: '0', overflowY: 'auto' }}>
  257. <ul className='msp-list-unstyled'>{entries}</ul>
  258. </div>;
  259. }
  260. }