state.tsx 12 KB

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