Archive for the ‘Javascript’ Category

See the demo.
See the source code, which depends on bililiteRange.

Modern browsers won't let synthetic events (triggered with dispatchEvent) execute their default actions (meaning the action that would occur if the event was triggered by a user action). The Event object has a read-only field called isTrusted that is false for anything but unmodified user-initiated events. These are called "trusted events", and I understand the justification, but they go too far. It makes it impossible to implement a virtual keyboard, since triggering keydown or keypress events aren't trusted and won't insert the character (the default action).

Fortunately, bililiteRange and especially bililiteRange.sendkeys can insert characters and do other manipulations on the page. So I created a jQuery plugin that uses bililiteRange.sendkeys to catch keydown events and implement them as well as possible.
Just include the source code and keydown events get a new default handler (so it can be cancelled by preventDefault) that looks at the key field. If it is a single character, that character is inserted at the selection. If it is more than one character long, it is assumed to be a sendkeys command like ArrowLeft and is sent as sendkeys('{'+key+'}').
I used the modern Event.key rather than Event.which, so I don't have to translate keyCodes. If you need to use the old way, see my keymap plugin.

Thus now, $('textarea').trigger({type: 'keydown', key: 'A'}) will work as expected, as will $('textarea').trigger({type: 'keydown', key: 'Backspace'}).

The actual plugin

Under the hood, this uses a very simple jQuery plugin that just calls bililiteRange.sendkeys(). It also turns '\n' in the string into '{Enter}', which I thought would be useful but has actually not turned out that way. Putting the '\n' in braces ('{\n}' prevents the replacement.
The plugin itself is:

$.fn.sendkeys = function (x){
  x = x.replace(/([^{])\n/g, '$1{enter}'); // turn line feeds into explicit break insertions, but not if escaped
  return this.each( function(){
    bililiteRange(this).bounds('selection').sendkeys(x).select();
    this.focus();
  });
};



Demo


$('.selectoutput').click(function(){
	$('.output').removeClass('selected');
	var index = $(this).parents('th').index();
	$('.output').eq(index).addClass('selected').focus();
});
$('div.test input:button').click(function(){
	$('.output.selected').sendkeys($('div.test input:text').val());
});
$('div.wrap input:button').click(function(){
	var tag = $('div.wrap select').val();
	$('.output.selected').sendkeys('<'+tag+'>{selection}{mark}</'+tag+'>');
});
$('.phonepad input').click(function(){
	$('.output.selected').trigger({type: 'keydown', key: this.name || this.value});
});
$('.output').each(function(){
	bililiteRange(this); // initialize the selection tracking
}).on('keydown', function(evt){
	if ($('#overridepad').is(':checked')){
		alert (evt.key);
		evt.preventDefault();
	}
}).on('keypress', function(evt){
	$('#keypress').text($('#keypress').text()+' '+evt.which);
}).on('sendkeys', function(evt){
	$('#sendkeys').text($('#sendkeys').text()+' '+evt.which);
}).on('focus', function(){
	var index = $(this).parents('td').index();
	$('.output').removeClass('selected');
	$('.output').eq(index).addClass('selected')
	$('.selectoutput').eq(index).attr('checked',true);;
});

<div>
	<table style="width: 100%" border="2" id="demo" >
		<thead>
			<tr>
				<th><label>
					<input type="radio" class="selectoutput" name="selectoutput" checked="checked" />
					<code>&lt;input&gt;</code>
				</label></th>
				<th><label>
					<input type="radio" class="selectoutput" name="selectoutput" />
					<code>&lt;textarea&gt;</code>
				</label></th>
				<th><label>
					<input type="radio" class="selectoutput" name="selectoutput" />
					<code>&lt;div contenteditable&gt;</code>
				</label></th>
				<th><label>
					<input type="radio" class="selectoutput" name="selectoutput" />
					<code>&lt;div&gt;</code>
				</label></th>
			</tr>
		</thead>
		<tbody>
			<tr>
				<td><input type="text" class="output selected" /></td>
				<td><textarea class="output"></textarea></td>
				<td><div class="output" contentEditable="true"></div></td>
				<td><div class="output" >This is not editable text</div></td>
			</tr>
		</tbody>
	</table>
<div class="phonepad">
<input type="button" name="ArrowLeft" value="&larr;"/><input type="button" name="ArrowRight" value="&rarr;"/><input type="button" name="Backspace" value="BS"/><input type="button" name="selectall" value="All"/><br/>
<input type="button" value="7" /><input type="button" value="8" /><input type="button" value="9" /><br/>
<input type="button" value="4" /><input type="button" value="5" /><input type="button" value="6" /><br/>
<input type="button" value="1" /><input type="button" value="2" /><input type="button" value="3" /><br/>
<input type="button" value="*" /><input type="button" value="0" /><input type="button" value="#" /><input type="button" name="Enter" value="&crarr;"/>
</div>
<label>Alert on keydown event: <input type=checkbox id=overridepad /></label>
<div class="test"><input type="text" /><input type="button" value="test"/></div>
<div class="wrap"><select><option>em</option><option>strong</option><option>del</option></select><input type="button" value="Wrap Selection"/></div>

<div id="keypress">keypress event.which:</div>
<div id="sendkeys">sendkeys event.which:</div>
</div>
<div style="clear:both" />

The phone pad keys use $().trigger({type: 'keydown', key: key}). The test button does $().sendkeys(textbox.value). The wrap button does $().sendkeys('<tag>{selection}{mark}</tag>'). Note that the trigger code does not affect the non-editable DIV, while sendkeys does.
The "Alert on keydown event" checkbox attaches a handler to the keydown event which calls event.preventDefault, showing that the text entry and keypress events do not occur.

bililiteRange.text() works well to insert text into ranges, but I wanted to be able to simulate other keys, ala Microsoft's SendKeys. bililiteRange.sendkeys() does exactly that. It basically executes text(string, 'end') but interprets any text between braces ('{key}') as a command representing a special key. For security reasons, the browser won't let you do anything outside of the text of the page itself, but I've implemented the following (the key names are from the proposed DOM3 standard)::

Backspace
Delete backwards
Delete
Delete forwards
ArrowRight
Move the insertion point to the right
ArrowLeft
Move the insertion point to the left
Enter
Insert a newline, with bililiteRange.insertEOL(). Warning: In contenteditable elements, Enter is flaky and inconsistent across browsers. This is due to the flakiness of contenteditable itself; I can't figure out what to do about this.

For backwards-compatibility with older versions, the following synonyms also work: backspace, del, rightarrow, leftarrow and enter.

So, for example, bililiteRange(el).sendkeys('foo') replaces the current range with 'foo' and sets the range to just after that string. bililiteRange(el).sendkeys('foo{Delete}{ArrowLeft}{ArrowLeft}') replaces the current range with 'foo', removes the character just after that string and sets the range to between the 'f' and the 'o'.

To manipulate the selection, use the usual bililiteRange methods. Thus, to simulate a backspace key, use bililiteRange(el).bounds('selection').sendkeys('{Backspace}').select().
To insert a '{', use an unmatched brace, bililiteRange(el).sendkeys('this is a left brace: {'), or {{}, as in bililiteRange(el).sendkeys('function() {{} whatever }');.

If anyone knows how to implement an up or down arrow, or page up/down, please let me know.

Other Commands

To make life easier for me, there are a few other "keys" that implement specific actions:

selectall
Select the entire field
tab
Insert a '\t' character. $().sendkeys('\t') would work just as well, but there are circumstances when I wanted to avoid having to escape backslashes.
newline
Insert a '\n' character, without the mangling that {enter} does.
selection
Inserts the text of the original selection (useful for creating "wrapping" functions, like "<em>{selection}</em>").
mark
Remembers the current insertion point and restores it after the sendkeys call. Thus "<p>{mark}</p>" inserts <p></p> and leaves the insertion point between the tags.

So to wrap the text of a range in HTML tags, use range.sendkeys('<strong>{selection}</strong>'). To create a hyperlink, use range.sendkeys('<a href="{mark}">{selection}</a>') which leaves the range between the quote marks rather than at the end.

Plugins

Adding new commands is easy. All the commands are in the bililiteRange.sendkeys object, indexed by the name of the command in braces (since that made parsing easier). The commands are of the form function (rng, c, simplechar) where rng is the target bililiteRange, c is the command name (in braces), and simplechar is a function simplechar (range, string) that will insert string into the range. range.data().sendkeysOriginalText is set to the original text of the range, and rng.data().sendkeysBounds is the argument for bililiteRange.bounds() that will be used at the end.

So, for example:

bililiteRange.sendkeys['{tab}'] = function (range, c, simplechar) { simplechar(rng, '\t') };
bililiteRange['{Backspace}'] = function (range, c, simplechar){
  var b = rng.bounds();
  if (b[0] == b[1]) rng.bounds([b[0]-1, b[0]]); // no characters selected; it's just an insertion point. Remove the previous character
  rng.text('', 'end'); // delete the characters and update the selection
};
bililiteRange.sendkeys['{selectall}'] = function (range, c, simplechar) { rng.bounds('all') };

So to have a reverse-string command:

bililiteRange['{reverse}'] = function (range, c, simplechar){
  simplechar(range, range.sendkeysOriginalText.split('').reverse().join(''));
};

Or, to annoy the anti-WordPress crowd, a Hello, Dolly command:

bililiteRange['{dolly}'] = function (range, c, simplechar){
  var lyrics = [
    "Hello, Dolly",
    "Well, hello, Dolly",
    "It's so nice to have you back where you belong",
    "You're lookin' swell, Dolly",
    "I can tell, Dolly",
    "You're still glowin', you're still crowin'",
    "You're still goin' strong"];
  simplechar (range, lyrics[Math.floor(Math.random() * lyrics.length)];
};

Events

After each printing character (not the specials, unless they call simplechar) it triggers a keydown event with event.which, event.keyCode and event.charCode set to the Unicode value of the character.
After the entire string is processed, it triggers a custom sendkeys event with event.which set to the original string.

Download the code.

See the demo.

See the hotkeys demo.

Dealing with keydown events is a pain, since the event object has always encoded the key as an arbitrary numeric code, so any program that deals with key-related events has something like:

var charcodes = {
	 32	: ' ',
	  8	: 'Backspace',
	 20	: 'CapsLock',
	 46	: 'Delete',
	 13	: 'Enter',
	 27	: 'Escape',
	 45	: 'Insert',
	144	: 'NumLock',
	  9	: 'Tab'
};

And so on. There is a proposal to add a key field that uses standardized names for the keys, but only Firefox and IE implement that right now. The time is ripe for a polyfill to bring Chrome and Safari into the twenty-first century, and I'd already worked on something similar with my $.keymap plugin.

So I updated that plugin to simply implement the key field in keydown and keyup events. Now just include the plugin and you can do things like:

$('textarea').keydown(function(event){
  if (event.key == 'Escape') { do something useful }
});

Continue reading ‘Rethinking $.keymap’ »

I suppose everyone knows about this, but I just discovered CodeMirror, a javascript, drop-in (not dependent on any other library) text editor that does syntax highlighting. It's smooth and fast. I'm still going to be playing with my editor (as part of the bililiteRange package), since it's been a useful learning experience, but if you want a professional-level editor, go there. I won't be insulted.

There have been lots of times that I've wanted to be able to keep my hand on the keyboard when editing, rather than running off to the mouse all the time. There's an implementation of VIM in Javascript but I figured I would learn something by doing it myself. My goal is vi, not vim, since I don't need anything that sophisticated.

The first step is implementing the line-oriented part of vi, called ex, based on the manual from the sourceforge project. My version is based on bililiteRange, and depends on the bililiteRange utilities and undo plugin.

Use it simply as bililiteRange(textarea).ex('%s/foo/bar/');, passing the ex command to the ex() function. The biggest difference from real ex is that this uses javascript regular expressions, rather than the original ex ones. Thus s/\w/x/ rather than s/[:class:]/x/, and use ?/.../ rather than ?...? to search backwards (the question mark is used in Javascript regular expressions so I don't want to use it as a delimiter).

See a demo.

See the code on github.

Continue reading ‘New bililiteRange plugin, ex’ »

Try the demo in Internet Explorer 11 and in a real browser.

IE now implements Range objects, representing a range of text that may span several elements. It's the basis for the standards-based part of bililiteRange. And it almost works. It's a little flaky: inserting text that contains '\n' without '\r', what I consider the "normal" way, automatically inserts the '\r'. Then using node.nodeValue returns a string without the '\r', but Range.toString() includes them. But that I can hack around.

The real bug is that ranges cannot end with a '\n'. If you try, the range is truncated. I can't find any way around that, so I had to change the way bililiteRange returned text: I went from range.toString() to element.textContent.slice(). Since that works with no other changes, I suspect that the error is in IE's toString() function itself rather than reflecting an underlying error in the Range.

Now to report that to Microsoft.

Evidently I'm doing test-driven development wrong. Or at least it could be easier. I will have to look at Google's karma to automate the testing (rather than running the test suite in each browser individually). That of course means I need to start using Node's npm package manager (which I probably should anyway, since all the cool kids are). I've been using chocolatey for installing programs, but it explicitly is designed to not overlap with Node and its package manager (though it will install Node itself).

This post will have to be my reminder to start hacking with all of this sooner rather than later. Now I have to see patients...

Turns out Internet Explorer is even worse than imagined. It's right at the bottom of the Uncanny Valley--close enough to a real browser to make it look like it works, but lots of near-impossible-to-track-down bugs that make life miserable. Turns out that Node.normalize is broken (see the bug reports and a workaround), so I had to add a test in bililiteRange to check for that, and not bother normalizing text if it's broken. Normalization just means merging adjacent text nodes, so losing it makes things less efficient but it should still work. I'm not going to lose sleep over Internet Explorer's inefficiencies.

Trying to debug bililiteRange in IE11; some of the problems were easily fixed with .replace(/\r/g, '') liberally scattered about, since IE really likes its return characters in <div>s (anything that is not a <textarea> or an <input> and will add them even if I am just inserting a newline.

I'm still getting a WrongDocumentError on some tests, but when I run them individually they pass; there must be some subtle global interaction that I am just not getting. I will consider those passed for now, though it is annoying seeing the red when I run the tests.

That leaves one error in find, one error in sendkeys, and whole bunch in ex, which isn't officially working yet anyway. Progress!

Well, I ran the test code for bililiteRange and got "132 assertions of 151 passed, 19 failed." Better than none passed, I suppose, but it means I've got some work ahead of me. Or I could just give up on IE, but IE11 is supposed to be standards-compliant, so the errors might actually reflect a problem.

Some of the results are weird: the expected and actual results look identical, so I imagine there's some '\r's rearing their ugly heads, even in IE11. The selection is not being retained on losing focus in input elements; that might be a real problem. And then some tests are failing with a "WrongDocumentError". Never seen that before.

I'll add this to my list of things to get to eventually.