commandManager.js 931 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import { shallowRef, computed } from 'vue';
  2. export function useCommandManager({ maxHistory = 100 } = {}) {
  3. const position = shallowRef(0);
  4. let history = [null];
  5. const state = computed(() => ({
  6. position: position.value,
  7. historyLen: history.length,
  8. canUndo: position.value > 0,
  9. canRedo: position.value < history.length - 1,
  10. }));
  11. return {
  12. state,
  13. add(command) {
  14. if (position.value < history.length - 1) {
  15. history = history.slice(0, position.value + 1);
  16. }
  17. if (history.length > maxHistory) {
  18. history.shift();
  19. }
  20. history.push(command);
  21. position.value += 1;
  22. },
  23. undo() {
  24. if (position.value > 0) {
  25. history[position.value].undo();
  26. position.value -= 1;
  27. }
  28. },
  29. redo() {
  30. if (position.value < history.length - 1) {
  31. position.value += 1;
  32. history[position.value].execute();
  33. }
  34. },
  35. };
  36. }