Archive for December 25th, 2013

This is a plugin for bililiteRange that implements a simple undo/redo stack. It listens for input events (so to use it in IE<10 you need some kind of polyfill) and records the old text each time, so it's pretty memory-inefficient, but it works for what I want to do.

See the code on github.

See a demo with the Prism editor (control-z to undo, control-y to redo).

Usage is simple:

bililiteRange(element).undo(0); // initializes the event listener without trying to undo anything; safe to call multiple times
bililiteRange(element).undo(); // restores the text from the last undo point
bililiteRange(element).undo(-1); // redo--undoes the last undo

bililiteRange(element).undo(n) for any n works and will undo (for positive n) or redo (for negative n) that many times, though I'm not sure how useful that would be.

There are convenience methods to be used as event handlers:

bililiteRange.undo(event);
bililiteRange.redo(event);

So a simple keyboard shortcut handler would be:

		bililiteRange(editor).undo(0); // initialize
		editor.addEventListener ('keydown', function(evt){
			// control z
			if (evt.ctrlKey && evt.which == 90) bililiteRange.undo(evt);
			// control y
			if (evt.ctrlKey && evt.which == 89) bililiteRange.redo(evt);
		});

or, if you use my hotkeys jQuery plugin,


$(editor).on('keydown', {keys: '^z'}, bililiteRange.undo);
$(editor).on('keydown', {keys: '^y'}, bililiteRange.redo);

Hope that this is useful to someone.

It tries to be sophisticated about typing, and bunches all typing done in a row into one, so that undo undoes the entire line. Backspacing, moving the insertion point, or typing a newline starts a new undo point.

Restoring the insertion point isn't as sophisticated as in a real word processor yet; moving the insertion point then typing then undoing moves the insertion point back to where is was originally, not to the start of typing.