Asking for undo/redo events in html/javascript
Asked Answered
R

1

2

I have an interactive html5 canvas thing where sometimes users will want to undo their actions. I have the logic for doing that implemented, but I'm not sure of how to properly catch the "user wants to undo" event.

Currently, I just listen to keyboard events and interpret "CTRL+Z" as a request-to-undo, like this:

document.addEventListener("keydown", e => {
    const Z_KEY = 90;
    let isUndo = e.keyCode == Z_KEY && e.ctrlKey && !e.shiftKey;
    if (isUndo) {
        restore(revision.undo());
    }
});

The problem is that the standard shortcut for undo-ing varies by OS, and there are totally orthogonal ways to trigger it (such as shaking your phone).

What I want is to somehow tell the browser that I'm supporting undo, and that it should forward all the crazy OS-specific ways of triggering undo to a method I specify. As things stand now, the browser has no idea the user is doing anything that would involve undo-ing. All the browser sees is a canvas being clicked on and drawn to.

Is there a standard way to ask the browser to catch all the undo events for me? In a future-proof way that keeps working even as vendors invent new undo actions? What about a hacky workaround? Or perhaps there's a library whose focus is to solve this particular problem?

Notes:

Radiculitis answered 2/5, 2016 at 4:2 Comment(0)
W
5

There's no standard javascript way of hooking things like undo/redo as there is no specific event for them.

Maybe Mousetrap does what you want. It's a library for abstracting keyboard events in javascript and includes a way to do a generic [system modifier]+key hotkey kind of thing.

That said, you'll probably need a button somewhere if you want mobile. (I'm not familiar with the shake-to-undo action. That seems like new age hippy nonsense. =P )

Wendel answered 2/5, 2016 at 4:12 Comment(3)
Unfortunately, catching the keyboard events isn't the difficult part. Very unfortunate that there's no standard signal.Radiculitis
@CraigGidney I suspect this is why we see a lot of web-page-in-an-app kinds of things. Doing it that way means you get the convenience of generic web development combined with access to device-specific capabilities.Wendel
@CraigGidney I saw this article which talks about how to hijack a hidden input field such that you can make it act as a proxy for the browser's native undo capability.Wendel

© 2022 - 2024 — McMap. All rights reserved.