snapshots.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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 { PluginCommands } from '../../command';
  7. import * as React from 'react';
  8. import { PluginUIComponent, PurePluginUIComponent } from '../base';
  9. import { shallowEqual } from '../../../mol-util';
  10. import { OrderedMap } from 'immutable';
  11. import { ParameterControls } from '../controls/parameters';
  12. import { ParamDefinition as PD} from '../../../mol-util/param-definition';
  13. import { PluginState } from '../../state';
  14. import { urlCombine } from '../../../mol-util/url';
  15. import { IconButton, Icon, SectionHeader } from '../controls/common';
  16. import { formatTimespan } from '../../../mol-util/now';
  17. export class StateSnapshots extends PluginUIComponent<{ }> {
  18. downloadToFile = () => {
  19. PluginCommands.State.Snapshots.DownloadToFile.dispatch(this.plugin, { });
  20. }
  21. open = (e: React.ChangeEvent<HTMLInputElement>) => {
  22. if (!e.target.files || !e.target.files![0]) return;
  23. PluginCommands.State.Snapshots.OpenFile.dispatch(this.plugin, { file: e.target.files![0] });
  24. }
  25. render() {
  26. return <div>
  27. <SectionHeader icon='floppy' title='Plugin State' />
  28. <LocalStateSnapshots />
  29. <LocalStateSnapshotList />
  30. {this.plugin.spec.components?.remoteState !== 'none' && <RemoteStateSnapshots />}
  31. <div className='msp-btn-row-group' style={{ marginTop: '10px' }}>
  32. <button className='msp-btn msp-btn-block msp-form-control' onClick={this.downloadToFile}>Download JSON</button>
  33. <div className='msp-btn msp-btn-block msp-btn-action msp-loader-msp-btn-file'>
  34. {'Open JSON'} <input onChange={this.open} type='file' multiple={false} accept='.json' />
  35. </div>
  36. </div>
  37. </div>;
  38. }
  39. }
  40. class LocalStateSnapshots extends PluginUIComponent<
  41. { },
  42. { params: PD.Values<typeof LocalStateSnapshots.Params> }> {
  43. state = { params: PD.getDefaultValues(LocalStateSnapshots.Params) };
  44. static Params = {
  45. name: PD.Text(),
  46. options: PD.Group({
  47. description: PD.Text(),
  48. ...PluginState.GetSnapshotParams
  49. })
  50. };
  51. add = () => {
  52. PluginCommands.State.Snapshots.Add.dispatch(this.plugin, {
  53. name: this.state.params.name,
  54. description: this.state.params.options.description,
  55. params: this.state.params.options
  56. });
  57. this.setState({
  58. params: {
  59. name: '',
  60. options: {
  61. ...this.state.params.options,
  62. description: ''
  63. }
  64. }
  65. });
  66. }
  67. clear = () => {
  68. PluginCommands.State.Snapshots.Clear.dispatch(this.plugin, {});
  69. }
  70. shouldComponentUpdate(nextProps: any, nextState: any) {
  71. return !shallowEqual(this.props, nextProps) || !shallowEqual(this.state, nextState);
  72. }
  73. render() {
  74. // TODO: proper styling
  75. return <div>
  76. <ParameterControls params={LocalStateSnapshots.Params} values={this.state.params} onEnter={this.add} onChange={p => {
  77. const params = { ...this.state.params, [p.name]: p.value };
  78. this.setState({ params } as any);
  79. this.plugin.state.snapshots.currentGetSnapshotParams = params.options;
  80. }}/>
  81. <div className='msp-btn-row-group'>
  82. {/* <button className='msp-btn msp-btn-block msp-form-control' onClick={this.add}><Icon name='floppy' /> Save</button> */}
  83. <button className='msp-btn msp-btn-block msp-form-control' onClick={this.add}>Save</button>
  84. {/* <button className='msp-btn msp-btn-block msp-form-control' onClick={this.upload} disabled={this.state.isUploading}>Upload</button> */}
  85. <button className='msp-btn msp-btn-block msp-form-control' onClick={this.clear}>Clear</button>
  86. </div>
  87. </div>;
  88. }
  89. }
  90. class LocalStateSnapshotList extends PluginUIComponent<{ }, { }> {
  91. componentDidMount() {
  92. this.subscribe(this.plugin.events.state.snapshots.changed, () => this.forceUpdate());
  93. }
  94. apply = (e: React.MouseEvent<HTMLElement>) => {
  95. const id = e.currentTarget.getAttribute('data-id');
  96. if (!id) return;
  97. PluginCommands.State.Snapshots.Apply.dispatch(this.plugin, { id });
  98. }
  99. remove = (e: React.MouseEvent<HTMLElement>) => {
  100. const id = e.currentTarget.getAttribute('data-id');
  101. if (!id) return;
  102. PluginCommands.State.Snapshots.Remove.dispatch(this.plugin, { id });
  103. }
  104. moveUp = (e: React.MouseEvent<HTMLElement>) => {
  105. const id = e.currentTarget.getAttribute('data-id');
  106. if (!id) return;
  107. PluginCommands.State.Snapshots.Move.dispatch(this.plugin, { id, dir: -1 });
  108. }
  109. moveDown = (e: React.MouseEvent<HTMLElement>) => {
  110. const id = e.currentTarget.getAttribute('data-id');
  111. if (!id) return;
  112. PluginCommands.State.Snapshots.Move.dispatch(this.plugin, { id, dir: 1 });
  113. }
  114. replace = (e: React.MouseEvent<HTMLElement>) => {
  115. const id = e.currentTarget.getAttribute('data-id');
  116. if (!id) return;
  117. PluginCommands.State.Snapshots.Replace.dispatch(this.plugin, { id, params: this.plugin.state.snapshots.currentGetSnapshotParams });
  118. }
  119. render() {
  120. const current = this.plugin.state.snapshots.state.current;
  121. return <ul style={{ listStyle: 'none' }} className='msp-state-list'>
  122. {this.plugin.state.snapshots.state.entries.map(e => <li key={e!.snapshot.id}>
  123. <button data-id={e!.snapshot.id} className='msp-btn msp-btn-block msp-form-control' onClick={this.apply}>
  124. <span style={{ fontWeight: e!.snapshot.id === current ? 'bold' : void 0}}>
  125. {e!.name || new Date(e!.timestamp).toLocaleString()}</span> <small>
  126. {`${e!.snapshot.durationInMs ? formatTimespan(e!.snapshot.durationInMs, false) + `${e!.description ? ', ' : ''}` : ''}${e!.description ? e!.description : ''}`}
  127. </small>
  128. </button>
  129. <div>
  130. <IconButton data-id={e!.snapshot.id} icon='up-thin' title='Move Up' onClick={this.moveUp} isSmall={true} />
  131. <IconButton data-id={e!.snapshot.id} icon='down-thin' title='Move Down' onClick={this.moveDown} isSmall={true} />
  132. <IconButton data-id={e!.snapshot.id} icon='switch' title='Replace' onClick={this.replace} isSmall={true} />
  133. <IconButton data-id={e!.snapshot.id} icon='remove' title='Remove' onClick={this.remove} isSmall={true} />
  134. </div>
  135. </li>)}
  136. </ul>;
  137. }
  138. }
  139. type RemoteEntry = { url: string, removeUrl: string, timestamp: number, id: string, name: string, description: string, isSticky?: boolean }
  140. class RemoteStateSnapshots extends PluginUIComponent<
  141. { },
  142. { params: PD.Values<typeof RemoteStateSnapshots.Params>, entries: OrderedMap<string, RemoteEntry>, isBusy: boolean }> {
  143. state = { params: PD.getDefaultValues(RemoteStateSnapshots.Params), entries: OrderedMap<string, RemoteEntry>(), isBusy: false };
  144. static Params = {
  145. name: PD.Text(),
  146. options: PD.Group({
  147. description: PD.Text(),
  148. playOnLoad: PD.Boolean(false),
  149. serverUrl: PD.Text('https://webchem.ncbr.muni.cz/molstar-state')
  150. })
  151. };
  152. componentDidMount() {
  153. this.refresh();
  154. // this.subscribe(UploadedEvent, this.refresh);
  155. }
  156. serverUrl(q?: string) {
  157. if (!q) return this.state.params.options.serverUrl;
  158. return urlCombine(this.state.params.options.serverUrl, q);
  159. }
  160. refresh = async () => {
  161. try {
  162. this.setState({ isBusy: true });
  163. const json = (await this.plugin.runTask<RemoteEntry[]>(this.plugin.fetch({ url: this.serverUrl('list'), type: 'json' }))) || [];
  164. json.sort((a, b) => {
  165. if (a.isSticky === b.isSticky) return a.timestamp - b.timestamp;
  166. return a.isSticky ? -1 : 1;
  167. });
  168. const entries = OrderedMap<string, RemoteEntry>().asMutable();
  169. for (const e of json) {
  170. entries.set(e.id, {
  171. ...e,
  172. url: this.serverUrl(`get/${e.id}`),
  173. removeUrl: this.serverUrl(`remove/${e.id}`)
  174. });
  175. }
  176. this.setState({ entries: entries.asImmutable(), isBusy: false })
  177. } catch (e) {
  178. this.plugin.log.error('Fetching Remote Snapshots: ' + e);
  179. this.setState({ entries: OrderedMap(), isBusy: false })
  180. }
  181. }
  182. upload = async () => {
  183. this.setState({ isBusy: true });
  184. if (this.plugin.state.snapshots.state.entries.size === 0) {
  185. await PluginCommands.State.Snapshots.Add.dispatch(this.plugin, {
  186. name: this.state.params.name,
  187. description: this.state.params.options.description,
  188. params: this.plugin.state.snapshots.currentGetSnapshotParams
  189. });
  190. }
  191. await PluginCommands.State.Snapshots.Upload.dispatch(this.plugin, {
  192. name: this.state.params.name,
  193. description: this.state.params.options.description,
  194. playOnLoad: this.state.params.options.playOnLoad,
  195. serverUrl: this.state.params.options.serverUrl
  196. });
  197. this.setState({ isBusy: false });
  198. this.plugin.log.message('Snapshot uploaded.');
  199. this.refresh();
  200. }
  201. fetch = async (e: React.MouseEvent<HTMLElement>) => {
  202. const id = e.currentTarget.getAttribute('data-id');
  203. if (!id) return;
  204. const entry = this.state.entries.get(id);
  205. if (!entry) return;
  206. this.setState({ isBusy: true });
  207. try {
  208. await PluginCommands.State.Snapshots.Fetch.dispatch(this.plugin, { url: entry.url });
  209. } finally {
  210. this.setState({ isBusy: false });
  211. }
  212. }
  213. remove = async (e: React.MouseEvent<HTMLElement>) => {
  214. const id = e.currentTarget.getAttribute('data-id');
  215. if (!id) return;
  216. const entry = this.state.entries.get(id);
  217. if (!entry) return;
  218. this.setState({ entries: this.state.entries.remove(id) });
  219. try {
  220. await fetch(entry.removeUrl);
  221. } catch { }
  222. }
  223. render() {
  224. return <div>
  225. <SectionHeader icon='floppy' title='Remote States' />
  226. <ParameterControls params={RemoteStateSnapshots.Params} values={this.state.params} onEnter={this.upload} onChange={p => {
  227. this.setState({ params: { ...this.state.params, [p.name]: p.value } } as any);
  228. }} isDisabled={this.state.isBusy}/>
  229. <div className='msp-btn-row-group'>
  230. <button className='msp-btn msp-btn-block msp-form-control' onClick={this.upload} disabled={this.state.isBusy}><Icon name='upload' /> Upload</button>
  231. <button className='msp-btn msp-btn-block msp-form-control' onClick={this.refresh} disabled={this.state.isBusy}>Refresh</button>
  232. </div>
  233. <RemoteStateSnapshotList entries={this.state.entries} isBusy={this.state.isBusy} serverUrl={this.state.params.options.serverUrl}
  234. fetch={this.fetch} remove={this.remove} />
  235. </div>;
  236. }
  237. }
  238. class RemoteStateSnapshotList extends PurePluginUIComponent<
  239. { entries: OrderedMap<string, RemoteEntry>, serverUrl: string, isBusy: boolean, fetch: (e: React.MouseEvent<HTMLElement>) => void, remove: (e: React.MouseEvent<HTMLElement>) => void },
  240. { }> {
  241. open = async (e: React.MouseEvent<HTMLElement>) => {
  242. const id = e.currentTarget.getAttribute('data-id');
  243. if (!id) return;
  244. const entry = this.props.entries.get(id);
  245. if (!entry) return;
  246. e.preventDefault();
  247. let url = `${window.location}`, qi = url.indexOf('?');
  248. if (qi > 0) url = url.substr(0, qi);
  249. window.open(`${url}?snapshot-url=${encodeURIComponent(entry.url)}`, '_blank');
  250. }
  251. render() {
  252. return <ul style={{ listStyle: 'none' }} className='msp-state-list'>
  253. {this.props.entries.valueSeq().map(e =><li key={e!.id}>
  254. <button data-id={e!.id} className='msp-btn msp-btn-block msp-form-control' onClick={this.props.fetch}
  255. disabled={this.props.isBusy} onContextMenu={this.open} title='Click to download, right-click to open in a new tab.'>
  256. {e!.name || new Date(e!.timestamp).toLocaleString()} <small>{e!.description}</small>
  257. </button>
  258. {!e!.isSticky && <div>
  259. <IconButton data-id={e!.id} icon='remove' title='Remove' onClick={this.props.remove} disabled={this.props.isBusy} />
  260. </div>}
  261. </li>)}
  262. </ul>;
  263. }
  264. }