state.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  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 '../../mol-plugin/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 '../../mol-plugin/state';
  14. import { urlCombine } from '../../mol-util/url';
  15. import { IconButton, Icon } 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. <div className='msp-section-header'><Icon name='code' /> State</div>
  28. <LocalStateSnapshots />
  29. <LocalStateSnapshotList />
  30. <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.upload} disabled={this.state.isUploading}>Upload</button> */}
  84. <button className='msp-btn msp-btn-block msp-form-control' onClick={this.clear}>Clear</button>
  85. </div>
  86. </div>;
  87. }
  88. }
  89. class LocalStateSnapshotList extends PluginUIComponent<{ }, { }> {
  90. componentDidMount() {
  91. this.subscribe(this.plugin.events.state.snapshots.changed, () => this.forceUpdate());
  92. }
  93. apply = (e: React.MouseEvent<HTMLElement>) => {
  94. const id = e.currentTarget.getAttribute('data-id');
  95. if (!id) return;
  96. PluginCommands.State.Snapshots.Apply.dispatch(this.plugin, { id });
  97. }
  98. remove = (e: React.MouseEvent<HTMLElement>) => {
  99. const id = e.currentTarget.getAttribute('data-id');
  100. if (!id) return;
  101. PluginCommands.State.Snapshots.Remove.dispatch(this.plugin, { id });
  102. }
  103. moveUp = (e: React.MouseEvent<HTMLElement>) => {
  104. const id = e.currentTarget.getAttribute('data-id');
  105. if (!id) return;
  106. PluginCommands.State.Snapshots.Move.dispatch(this.plugin, { id, dir: -1 });
  107. }
  108. moveDown = (e: React.MouseEvent<HTMLElement>) => {
  109. const id = e.currentTarget.getAttribute('data-id');
  110. if (!id) return;
  111. PluginCommands.State.Snapshots.Move.dispatch(this.plugin, { id, dir: 1 });
  112. }
  113. replace = (e: React.MouseEvent<HTMLElement>) => {
  114. const id = e.currentTarget.getAttribute('data-id');
  115. if (!id) return;
  116. PluginCommands.State.Snapshots.Replace.dispatch(this.plugin, { id, params: this.plugin.state.snapshots.currentGetSnapshotParams });
  117. }
  118. render() {
  119. const current = this.plugin.state.snapshots.state.current;
  120. return <ul style={{ listStyle: 'none' }} className='msp-state-list'>
  121. {this.plugin.state.snapshots.state.entries.map(e => <li key={e!.snapshot.id}>
  122. <button data-id={e!.snapshot.id} className='msp-btn msp-btn-block msp-form-control' onClick={this.apply}>
  123. <span style={{ fontWeight: e!.snapshot.id === current ? 'bold' : void 0}}>
  124. {e!.name || new Date(e!.timestamp).toLocaleString()}</span> <small>
  125. {`${e!.snapshot.durationInMs ? formatTimespan(e!.snapshot.durationInMs, false) + `${e!.description ? ', ' : ''}` : ''}${e!.description ? e!.description : ''}`}
  126. </small>
  127. </button>
  128. <div>
  129. <IconButton data-id={e!.snapshot.id} icon='up-thin' title='Move Up' onClick={this.moveUp} isSmall={true} />
  130. <IconButton data-id={e!.snapshot.id} icon='down-thin' title='Move Down' onClick={this.moveDown} isSmall={true} />
  131. <IconButton data-id={e!.snapshot.id} icon='switch' title='Replace' onClick={this.replace} isSmall={true} />
  132. <IconButton data-id={e!.snapshot.id} icon='remove' title='Remove' onClick={this.remove} isSmall={true} />
  133. </div>
  134. </li>)}
  135. </ul>;
  136. }
  137. }
  138. type RemoteEntry = { url: string, removeUrl: string, timestamp: number, id: string, name: string, description: string, isSticky?: boolean }
  139. class RemoteStateSnapshots extends PluginUIComponent<
  140. { },
  141. { params: PD.Values<typeof RemoteStateSnapshots.Params>, entries: OrderedMap<string, RemoteEntry>, isBusy: boolean }> {
  142. state = { params: PD.getDefaultValues(RemoteStateSnapshots.Params), entries: OrderedMap<string, RemoteEntry>(), isBusy: false };
  143. static Params = {
  144. name: PD.Text(),
  145. options: PD.Group({
  146. description: PD.Text(),
  147. playOnLoad: PD.Boolean(false),
  148. serverUrl: PD.Text('https://webchem.ncbr.muni.cz/molstar-state')
  149. })
  150. };
  151. componentDidMount() {
  152. this.refresh();
  153. // this.subscribe(UploadedEvent, this.refresh);
  154. }
  155. serverUrl(q?: string) {
  156. if (!q) return this.state.params.options.serverUrl;
  157. return urlCombine(this.state.params.options.serverUrl, q);
  158. }
  159. refresh = async () => {
  160. try {
  161. this.setState({ isBusy: true });
  162. const json = (await this.plugin.runTask<RemoteEntry[]>(this.plugin.fetch({ url: this.serverUrl('list'), type: 'json' }))) || [];
  163. json.sort((a, b) => {
  164. if (a.isSticky === b.isSticky) return a.timestamp - b.timestamp;
  165. return a.isSticky ? -1 : 1;
  166. });
  167. const entries = OrderedMap<string, RemoteEntry>().asMutable();
  168. for (const e of json) {
  169. entries.set(e.id, {
  170. ...e,
  171. url: this.serverUrl(`get/${e.id}`),
  172. removeUrl: this.serverUrl(`remove/${e.id}`)
  173. });
  174. }
  175. this.setState({ entries: entries.asImmutable(), isBusy: false })
  176. } catch (e) {
  177. this.plugin.log.error('Fetching Remote Snapshots: ' + e);
  178. this.setState({ entries: OrderedMap(), isBusy: false })
  179. }
  180. }
  181. upload = async () => {
  182. this.setState({ isBusy: true });
  183. if (this.plugin.state.snapshots.state.entries.size === 0) {
  184. await PluginCommands.State.Snapshots.Add.dispatch(this.plugin, {
  185. name: this.state.params.name,
  186. description: this.state.params.options.description,
  187. params: this.plugin.state.snapshots.currentGetSnapshotParams
  188. });
  189. }
  190. await PluginCommands.State.Snapshots.Upload.dispatch(this.plugin, {
  191. name: this.state.params.name,
  192. description: this.state.params.options.description,
  193. playOnLoad: this.state.params.options.playOnLoad,
  194. serverUrl: this.state.params.options.serverUrl
  195. });
  196. this.setState({ isBusy: false });
  197. this.plugin.log.message('Snapshot uploaded.');
  198. this.refresh();
  199. }
  200. fetch = async (e: React.MouseEvent<HTMLElement>) => {
  201. const id = e.currentTarget.getAttribute('data-id');
  202. if (!id) return;
  203. const entry = this.state.entries.get(id);
  204. if (!entry) return;
  205. this.setState({ isBusy: true });
  206. try {
  207. await PluginCommands.State.Snapshots.Fetch.dispatch(this.plugin, { url: entry.url });
  208. } finally {
  209. this.setState({ isBusy: false });
  210. }
  211. }
  212. remove = async (e: React.MouseEvent<HTMLElement>) => {
  213. const id = e.currentTarget.getAttribute('data-id');
  214. if (!id) return;
  215. const entry = this.state.entries.get(id);
  216. if (!entry) return;
  217. this.setState({ entries: this.state.entries.remove(id) });
  218. try {
  219. await fetch(entry.removeUrl);
  220. } catch { }
  221. }
  222. render() {
  223. return <div>
  224. <div className='msp-section-header'><Icon name='code' /> Remote State</div>
  225. <ParameterControls params={RemoteStateSnapshots.Params} values={this.state.params} onEnter={this.upload} onChange={p => {
  226. this.setState({ params: { ...this.state.params, [p.name]: p.value } } as any);
  227. }} isDisabled={this.state.isBusy}/>
  228. <div className='msp-btn-row-group'>
  229. <button className='msp-btn msp-btn-block msp-form-control' onClick={this.upload} disabled={this.state.isBusy}><Icon name='upload' /> Upload</button>
  230. <button className='msp-btn msp-btn-block msp-form-control' onClick={this.refresh} disabled={this.state.isBusy}>Refresh</button>
  231. </div>
  232. <RemoteStateSnapshotList entries={this.state.entries} isBusy={this.state.isBusy} serverUrl={this.state.params.options.serverUrl}
  233. fetch={this.fetch} remove={this.remove} />
  234. </div>;
  235. }
  236. }
  237. class RemoteStateSnapshotList extends PurePluginUIComponent<
  238. { entries: OrderedMap<string, RemoteEntry>, serverUrl: string, isBusy: boolean, fetch: (e: React.MouseEvent<HTMLElement>) => void, remove: (e: React.MouseEvent<HTMLElement>) => void },
  239. { }> {
  240. open = async (e: React.MouseEvent<HTMLElement>) => {
  241. const id = e.currentTarget.getAttribute('data-id');
  242. if (!id) return;
  243. const entry = this.props.entries.get(id);
  244. if (!entry) return;
  245. e.preventDefault();
  246. let url = `${window.location}`, qi = url.indexOf('?');
  247. if (qi > 0) url = url.substr(0, qi);
  248. window.open(`${url}?snapshot-url=${encodeURIComponent(entry.url)}`, '_blank');
  249. }
  250. render() {
  251. return <ul style={{ listStyle: 'none' }} className='msp-state-list'>
  252. {this.props.entries.valueSeq().map(e =><li key={e!.id}>
  253. <button data-id={e!.id} className='msp-btn msp-btn-block msp-form-control' onClick={this.props.fetch}
  254. disabled={this.props.isBusy} onContextMenu={this.open} title='Click to download, right-click to open in a new tab.'>
  255. {e!.name || new Date(e!.timestamp).toLocaleString()} <small>{e!.description}</small>
  256. </button>
  257. {!e!.isSticky && <div>
  258. <IconButton data-id={e!.id} icon='remove' title='Remove' onClick={this.props.remove} disabled={this.props.isBusy} />
  259. </div>}
  260. </li>)}
  261. </ul>;
  262. }
  263. }