From 96c7b9e15b33e8c2de1e559ea2735f7086213911 Mon Sep 17 00:00:00 2001 From: Arthur Clemens Date: Mon, 6 Mar 2023 17:13:52 +0100 Subject: [PATCH] Add grouping --- README.md | 39 +++++++++++++++++++++++++--- demo/index.html | 7 +++++ demo/js/circledrawer.js | 11 ++++++++ demo/js/demo.js | 12 ++++++++- lib/undomanager.js | 45 ++++++++++++++++++++------------ package-lock.json | 4 +-- package.json | 2 +- spec/SpecRunner.html | 54 +++++++++++++++++++++++++++++++++++++++ spec/undomanager.spec.js | 55 +++++++++++++++++++++++++++++++++------- 9 files changed, 197 insertions(+), 32 deletions(-) create mode 100644 spec/SpecRunner.html diff --git a/README.md b/README.md index c729916..2314bdb 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,7 @@ Simple undo manager to provide undo and redo actions in JavaScript applications. - [Installation](#installation) - [Example](#example) - [Methods](#methods) + - [add](#add) - [undo](#undo) - [redo](#redo) - [clear](#clear) @@ -49,8 +50,7 @@ undoManager.add({ }); ``` -To make an action undoable, you'd add an undo/redo pair to the undo manager: - +To make an action undoable, you'd add an undo/redo command pair to the undo manager: ```js const undoManager = new UndoManager(); @@ -93,6 +93,34 @@ console.log(people); // logs: {101: "John"} ## Methods +### add + +Adds an undo/redo command pair to the stack. + +```js +function createPerson(id, name) { + // first creation + addPerson(id, name); + + // make undoable + undoManager.add({ + undo: () => removePerson(id), + redo: () => addPerson(id, name) + }); +} +``` + +Optionally add a `groupId` to identify related command pairs. Undo and redo actions will then be performed on all adjacent command pairs with that group id. + +```js +undoManager.add({ + groupId: 'auth', + undo: () => removePerson(id), + redo: () => addPerson(id, name) +}); +``` + + ### undo Performs the undo action. @@ -101,6 +129,8 @@ Performs the undo action. undoManager.undo(); ``` +If a `groupId` was set, the undo action will be performed on all adjacent command pairs with that group id. + ### redo Performs the redo action. @@ -109,6 +139,8 @@ Performs the redo action. undoManager.redo(); ``` +If a `groupId` was set, the redo action will be performed on all adjacent command pairs with that group id. + ### clear Clears all stored states. @@ -159,10 +191,11 @@ const index = undoManager.getIndex(); ### getCommands -Returns the list of queued commands. +Returns the list of queued commands, optionally filtered by group id. ```js const commands = undoManager.getCommands(); +const commands = undoManager.getCommands(groupId); ``` ## Use with CommonJS diff --git a/demo/index.html b/demo/index.html index f31baaf..f1edb53 100644 --- a/demo/index.html +++ b/demo/index.html @@ -34,6 +34,13 @@ placeholder="Limit: 0" />
+