state.ts 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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 { PluginContext } from '../../context';
  8. import { StateTree, Transform, State } from 'mol-state';
  9. export function registerDefault(ctx: PluginContext) {
  10. SetCurrentObject(ctx);
  11. Update(ctx);
  12. ApplyAction(ctx);
  13. RemoveObject(ctx);
  14. ToggleExpanded(ctx);
  15. ToggleVisibility(ctx);
  16. }
  17. export function SetCurrentObject(ctx: PluginContext) {
  18. PluginCommands.State.SetCurrentObject.subscribe(ctx, ({ state, ref }) => state.setCurrent(ref));
  19. }
  20. export function Update(ctx: PluginContext) {
  21. PluginCommands.State.Update.subscribe(ctx, ({ state, tree }) => ctx.runTask(state.update(tree)));
  22. }
  23. export function ApplyAction(ctx: PluginContext) {
  24. PluginCommands.State.ApplyAction.subscribe(ctx, ({ state, action, ref }) => ctx.runTask(state.apply(action.action, action.params, ref)));
  25. }
  26. export function RemoveObject(ctx: PluginContext) {
  27. PluginCommands.State.RemoveObject.subscribe(ctx, ({ state, ref }) => {
  28. const tree = state.tree.build().delete(ref).getTree();
  29. return ctx.runTask(state.update(tree));
  30. });
  31. }
  32. export function ToggleExpanded(ctx: PluginContext) {
  33. PluginCommands.State.ToggleExpanded.subscribe(ctx, ({ state, ref }) => state.updateCellState(ref, ({ isCollapsed }) => ({ isCollapsed: !isCollapsed })));
  34. }
  35. export function ToggleVisibility(ctx: PluginContext) {
  36. PluginCommands.State.ToggleVisibility.subscribe(ctx, ({ state, ref }) => setVisibility(state, ref, !state.tree.cellStates.get(ref).isHidden));
  37. }
  38. function setVisibility(state: State, root: Transform.Ref, value: boolean) {
  39. StateTree.doPreOrder(state.tree, state.tree.transforms.get(root), { state, value }, setVisibilityVisitor);
  40. }
  41. function setVisibilityVisitor(t: Transform, tree: StateTree, ctx: { state: State, value: boolean }) {
  42. ctx.state.updateCellState(t.ref, { isHidden: ctx.value });
  43. }