index.ts 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import { AnyFun } from "queenjs/typing";
  2. import { EditorModule } from "../../module";
  3. import { Action, HistoryController } from "./HistoryController";
  4. import { get } from "lodash";
  5. export class HistoryCtrl {
  6. history: HistoryController;
  7. historyActionDoing = false;
  8. historyCombine = false;
  9. safeList = ["layout.size"];
  10. constructor(protected module: EditorModule, historyTotal = 50) {
  11. this.history = new HistoryController();
  12. this.history.state.maxLen = historyTotal;
  13. }
  14. record(
  15. root: any,
  16. type: Action["type"],
  17. paths: string[],
  18. value: any,
  19. oldValue: any
  20. ) {
  21. if (this.historyActionDoing) {
  22. if (
  23. type === "set" &&
  24. !this.safeList.some((str) => paths.slice(0, -1).join(".").includes(str))
  25. ) {
  26. const parent = paths.length > 1 ? get(root, paths.slice(0, -1)) : root;
  27. if (parent instanceof Array) {
  28. console.warn(
  29. `操作警告[set:${paths.join(
  30. "."
  31. )}],应将数组整体替换赋值,不要操作原数组对象`
  32. );
  33. }
  34. }
  35. const action = new Action(type, root, paths.join("."), value, oldValue);
  36. this.history.record(action, { combine: this.historyCombine });
  37. }
  38. }
  39. bindActions(actNames: string[]) {
  40. const actions: any = this.module.actions;
  41. actNames.forEach((actName) => {
  42. const action = actions[actName];
  43. actions[actName] = this.proxyAction.bind(this, action);
  44. });
  45. }
  46. async proxyAction(action: AnyFun, ...args: any[]) {
  47. const { history } = this;
  48. if (this.historyActionDoing) {
  49. return await action(...args);
  50. }
  51. try {
  52. this.historyActionDoing = true;
  53. await action(...args);
  54. history.submit();
  55. } catch (error) {
  56. console.error(error);
  57. history.cacheGroupAction.undo();
  58. history.cacheGroupAction.actions = [];
  59. } finally {
  60. this.historyActionDoing = false;
  61. }
  62. }
  63. }