common.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  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 { State, StateTransform, StateTransformer, StateAction, StateObject } from '../../mol-state';
  7. import * as React from 'react';
  8. import { PurePluginUIComponent } from '../base';
  9. import { ParameterControls, ParamOnChange } from '../controls/parameters';
  10. import { PluginContext } from '../../mol-plugin/context';
  11. import { ParamDefinition as PD } from '../../mol-util/param-definition';
  12. import { Subject } from 'rxjs';
  13. import { Icon, IconName } from '../controls/icons';
  14. import { ExpandGroup, ToggleButton, Button } from '../controls/common';
  15. export { StateTransformParameters, TransformControlBase };
  16. class StateTransformParameters extends PurePluginUIComponent<StateTransformParameters.Props> {
  17. validate(params: any) {
  18. // TODO
  19. return void 0;
  20. }
  21. areInitial(params: any) {
  22. return PD.areEqual(this.props.info.params, params, this.props.info.initialValues);
  23. }
  24. onChange: ParamOnChange = ({ name, value }) => {
  25. const params = { ...this.props.params, [name]: value };
  26. this.props.events.onChange(params, this.areInitial(params), this.validate(params));
  27. };
  28. render() {
  29. return <ParameterControls params={this.props.info.params} values={this.props.params} onChange={this.onChange} onEnter={this.props.events.onEnter} isDisabled={this.props.isDisabled} />;
  30. }
  31. }
  32. namespace StateTransformParameters {
  33. export interface Props {
  34. info: {
  35. params: PD.Params,
  36. initialValues: any,
  37. isEmpty: boolean
  38. },
  39. events: {
  40. onChange: (params: any, areInitial: boolean, errors?: string[]) => void,
  41. onEnter: () => void,
  42. }
  43. params: any,
  44. isDisabled?: boolean,
  45. a?: StateObject,
  46. b?: StateObject
  47. }
  48. export type Class = React.ComponentClass<Props>
  49. function areParamsEmpty(params: PD.Params) {
  50. const keys = Object.keys(params);
  51. for (const k of keys) {
  52. if (!params[k].isHidden) return false;
  53. }
  54. return true;
  55. }
  56. export function infoFromAction(plugin: PluginContext, state: State, action: StateAction, nodeRef: StateTransform.Ref): Props['info'] {
  57. const source = state.cells.get(nodeRef)!.obj!;
  58. const params = action.definition.params ? action.definition.params(source, plugin) : { };
  59. const initialValues = PD.getDefaultValues(params);
  60. return {
  61. initialValues,
  62. params,
  63. isEmpty: areParamsEmpty(params)
  64. };
  65. }
  66. export function infoFromTransform(plugin: PluginContext, state: State, transform: StateTransform): Props['info'] {
  67. const cell = state.cells.get(transform.ref)!;
  68. // const source: StateObjectCell | undefined = (cell.sourceRef && state.cells.get(cell.sourceRef)!) || void 0;
  69. // const create = transform.transformer.definition.params;
  70. // const params = create ? create((source && source.obj) as any, plugin) : { };
  71. const params = (cell.params && cell.params.definition) || { };
  72. const initialValues = (cell.params && cell.params.values) || { };
  73. return {
  74. initialValues,
  75. params,
  76. isEmpty: areParamsEmpty(params)
  77. }
  78. }
  79. }
  80. namespace TransformControlBase {
  81. export interface ComponentState {
  82. params: any,
  83. error?: string,
  84. busy: boolean,
  85. isInitial: boolean,
  86. simpleOnly?: boolean,
  87. isCollapsed?: boolean
  88. }
  89. export interface CommonProps {
  90. simpleApply?: { header: string, icon: IconName, title?: string },
  91. noMargin?: boolean,
  92. applyLabel?: string,
  93. onApply?: () => void,
  94. autoHideApply?: boolean,
  95. wrapInExpander?: boolean,
  96. expanderHeaderLeftMargin?: string
  97. }
  98. }
  99. abstract class TransformControlBase<P, S extends TransformControlBase.ComponentState> extends PurePluginUIComponent<P & TransformControlBase.CommonProps, S> {
  100. abstract applyAction(): Promise<void>;
  101. abstract getInfo(): StateTransformParameters.Props['info'];
  102. abstract getHeader(): StateTransformer.Definition['display'] | 'none';
  103. abstract canApply(): boolean;
  104. abstract getTransformerId(): string;
  105. abstract canAutoApply(newParams: any): boolean;
  106. abstract applyText(): string;
  107. abstract isUpdate(): boolean;
  108. abstract getSourceAndTarget(): { a?: StateObject, b?: StateObject };
  109. abstract state: S;
  110. private busy: Subject<boolean> = new Subject();
  111. private onEnter = () => {
  112. if (this.state.error) return;
  113. this.apply();
  114. }
  115. private autoApplyHandle: number | undefined = void 0;
  116. private clearAutoApply() {
  117. if (this.autoApplyHandle !== void 0) {
  118. clearTimeout(this.autoApplyHandle);
  119. this.autoApplyHandle = void 0;
  120. }
  121. }
  122. events: StateTransformParameters.Props['events'] = {
  123. onEnter: this.onEnter,
  124. onChange: (params, isInitial, errors) => {
  125. this.clearAutoApply();
  126. this.setState({ params, isInitial, error: errors && errors[0] }, () => {
  127. if (!isInitial && !this.state.error && this.canAutoApply(params)) {
  128. this.clearAutoApply();
  129. this.autoApplyHandle = setTimeout(this.apply, 50) as any as number;
  130. }
  131. });
  132. }
  133. }
  134. apply = async () => {
  135. this.clearAutoApply();
  136. this.setState({ busy: true });
  137. try {
  138. await this.applyAction();
  139. } catch {
  140. // eat errors because they should be handled elsewhere
  141. } finally {
  142. this.props.onApply?.();
  143. this.busy.next(false);
  144. }
  145. }
  146. componentDidMount() {
  147. this.subscribe(this.plugin.behaviors.state.isBusy, b => {
  148. if (this.state.busy !== b) this.busy.next(b);
  149. });
  150. this.subscribe(this.busy, busy => {
  151. if (this.state.busy !== busy) this.setState({ busy })
  152. });
  153. }
  154. refresh = () => {
  155. this.setState({ params: this.getInfo().initialValues, isInitial: true, error: void 0 });
  156. }
  157. setDefault = () => {
  158. const info = this.getInfo();
  159. const params = PD.getDefaultValues(info.params);
  160. this.setState({ params, isInitial: PD.areEqual(info.params, params, info.initialValues), error: void 0 });
  161. }
  162. toggleExpanded = () => {
  163. this.setState({ isCollapsed: !this.state.isCollapsed });
  164. }
  165. renderApply() {
  166. // const showBack = this.isUpdate() && !(this.state.busy || this.state.isInitial);
  167. const canApply = this.canApply();
  168. if (this.props.autoHideApply && (!canApply || this.canAutoApply(this.state.params))) return null;
  169. return <div className='msp-transform-apply-wrap'>
  170. <button className='msp-btn msp-btn-block msp-form-control msp-transform-default-params' onClick={this.setDefault} disabled={this.state.busy} title='Set default params'><Icon name='cw' /></button>
  171. {/* {showBack && <Button className='msp-btn msp-btn-block msp-form-control msp-transform-refresh msp-form-control' title='Refresh params' onClick={this.refresh} disabled={this.state.busy || this.state.isInitial}>
  172. <Icon name='back' /> Back
  173. </Button>}
  174. <div className={`msp-transform-apply${!showBack ? ' msp-transform-apply-wider' : ''}`}> */}
  175. <div className={`msp-transform-apply-wider`}>
  176. <Button icon={canApply ? 'ok' : void 0} className={`msp-btn-commit msp-btn-commit-${canApply ? 'on' : 'off'}`} onClick={this.apply} disabled={!canApply}>
  177. {this.props.applyLabel || this.applyText()}
  178. </Button>
  179. </div>
  180. </div>;
  181. }
  182. renderDefault() {
  183. const info = this.getInfo();
  184. const isEmpty = info.isEmpty && this.isUpdate();
  185. const display = this.getHeader();
  186. const tId = this.getTransformerId();
  187. const ParamEditor: StateTransformParameters.Class = this.plugin.customParamEditors.has(tId)
  188. ? this.plugin.customParamEditors.get(tId)!
  189. : StateTransformParameters;
  190. const wrapClass = this.state.isCollapsed
  191. ? 'msp-transform-wrapper msp-transform-wrapper-collapsed'
  192. : 'msp-transform-wrapper';
  193. let params = null;
  194. if (!isEmpty && !this.state.isCollapsed) {
  195. const { a, b } = this.getSourceAndTarget();
  196. const applyControl = this.renderApply();
  197. params = <>
  198. <ParamEditor info={info} a={a} b={b} events={this.events} params={this.state.params} isDisabled={this.state.busy} />
  199. {applyControl}
  200. </>
  201. }
  202. const ctrl = <div className={wrapClass} style={{ marginBottom: this.props.noMargin ? 0 : void 0 }}>
  203. {display !== 'none' && !this.props.wrapInExpander && <div className='msp-transform-header'>
  204. <Button onClick={this.toggleExpanded} title={display.description}>
  205. {!isEmpty && <Icon name={this.state.isCollapsed ? 'expand' : 'collapse'} />}
  206. {display.name}
  207. </Button>
  208. </div>}
  209. {params}
  210. </div>;
  211. if (isEmpty || !this.props.wrapInExpander) return ctrl;
  212. return <ExpandGroup header={this.isUpdate() ? `Update ${display === 'none' ? '' : display.name}` : `Apply ${display === 'none' ? '' : display.name}` } headerLeftMargin={this.props.expanderHeaderLeftMargin}>
  213. {ctrl}
  214. </ExpandGroup>;
  215. }
  216. renderSimple() {
  217. const info = this.getInfo();
  218. const canApply = this.canApply();
  219. const apply = <div className='msp-flex-row'>
  220. <Button icon={this.props.simpleApply?.icon} title={this.props.simpleApply?.title} disabled={this.state.busy || !canApply} onClick={this.apply} style={{ textAlign: 'left' }}>
  221. {this.props.simpleApply?.header}
  222. </Button>
  223. {!info.isEmpty && <ToggleButton icon='cog' label='' title='Options' toggle={this.toggleExpanded} isSelected={!this.state.isCollapsed} disabled={this.state.busy} style={{ flex: '0 0 40px', padding: 0 }} />}
  224. </div>
  225. if (this.state.isCollapsed) return apply;
  226. const tId = this.getTransformerId();
  227. const ParamEditor: StateTransformParameters.Class = this.plugin.customParamEditors.has(tId)
  228. ? this.plugin.customParamEditors.get(tId)!
  229. : StateTransformParameters;
  230. const { a, b } = this.getSourceAndTarget();
  231. return <>
  232. {apply}
  233. <ParamEditor info={info} a={a} b={b} events={this.events} params={this.state.params} isDisabled={this.state.busy} />
  234. </>
  235. }
  236. render() {
  237. // console.log('rendering', ((this.props as any)?.transform?.transformer || (this.props as any)?.action)?.definition.display.name, +new Date)
  238. return this.props.simpleApply ? this.renderSimple() : this.renderDefault();
  239. }
  240. }