ProjectVisBug icon indicating copy to clipboard operation
ProjectVisBug copied to clipboard

Add undo and redo history

Open Kitenite opened this issue 10 months ago • 5 comments

Summary

This is a POC for undo redo. Only working for colors but is simple to add for any edit types. Adapting changes from my own internal repo so please excuse some poor formatting.

Testing

I added some unit test but you can also test this by applying a background change then CMD+Z to undo and CMD+SHIFT+Z to redo.

Description

The idea is to store reversible events for any edits, then have an applyEvent call that can call the reverse event (akin to the command pattern).

Possible improvements

One possible improvement to this is to save the old style as a parameter in the element. This way, the old style is always ensured to be the original style. This requires some refactoring of the way styles are applied in Visbug but is how we do it in my project.

let oldStyles = element.dataset.oldStyles
        ? JSON.parse(element.dataset.oldStyles)
        : {};

      // Save the current style value to the map before updating, only if it doesn't exist
      if (oldStyles[key] === undefined) {
        const oldStyle = element.style[key];
        if (oldStyle !== undefined) {
          // Save only if there's a current value
          oldStyles[key] = oldStyle;
          element.dataset.oldStyles = JSON.stringify(oldStyles); // Serialize and save back to dataset
        }
      }

      // Update the style
      element.style[key] = value;
      // Emit event
      handleEditEvent({
        el: element,
        editType: EditType.STYLE,
        newValue: { [key]: value },
        oldValue: { [key]: oldStyles[key] },
      });

Kitenite avatar Mar 31 '24 16:03 Kitenite