Showing posts with label code-editor. Show all posts
Showing posts with label code-editor. Show all posts

Friday, January 3, 2014

Packing Old Polymers for New Browsers


This is crazy. Somehow I do not have a running sample of an <ice-code-editor> Polymer available anywhere. At various times I had gotten this working. I even have a post from last year that worked at one point. But now nothing. Since I wanted to explore wrapping Polymer around existing, large codebases anyway, this seems a good opportunity.

First, it has been a while since I last tried to Polymerize the ICE Code Editor. None of the samples that I include in the web directory are working anymore. A quick scan of git log reveals that my last Polymer work was pre-Dart 1.0:



I cherry-pick that 1.0 commit (git cherry-pick f698145) rather than rebasing the polymer branch onto the latest master branch. Hopefully that is all I need to get things working again and it seems less likely to (a) devolve into resolving multiple merge conflicts and (b) introduce other, unrelated problems.

And that does get most of the examples working. It even gets an embedded example working:



But that was a pre-Polymer attempt at a similar solution. Unfortunately, I seem to have a Polymer bug. Hopefully it is just an old-version-of-polymer bug:
Internal error: 'package:polymer_expressions/polymer_expressions.dart': Error: line 53 pos 34: cannot resolve class 'BindingDelegate' from 'PolymerExpressions'
class PolymerExpressions extends BindingDelegate {
                                 ^ 
And, holy cow, I am using an old, modified, locally installed version of Polymer per my pubspec.yaml:
name: ice_code_editor
# ...
dependencies:
  crypto: any
  js: any
  ctrl_alt_foo: any
  json: any
  polymer: {path: /home/chris/repos/dart/dart/pkg/polymer}
Heh. Any time I think I am living too close to the bleeding edge for Patterns in Polymer I can now remind myself that at least this kind of hacking is no longer necessary.

I switch to the latest, packaged Polymer:
name: ice_code_editor
# ...
dependencies:
  crypto: any
  js: any
  ctrl_alt_foo: any
  json: any
  polymer: any
After that change, I pub get, which gets me to one of my favorite games: “my, how things have changed!”

Instead of the old combination of JavaScript boot script and Polymer import, I switch to the new export-init-script:
<head>
  <!-- Load component(s) -->
  <link rel="import" href="packages/ice_code_editor/polymer/ice_code_editor.html">
  <!-- Load Polymer -->
  <script type="application/dart">
    export 'package:polymer/init.dart';
  </script>
</head>
In the olden days of 2013, I had to mixin an observable class into my Polymer definition—no more. There used to be a create() lifecycle method as in the JavaScript version of Polymer—now it is a named constructor. Lastly, to manipulate the DOM of the current element, I previously had to go through the host property—now I can call append() directly.

The end result looks much more familiar to me after my recent 1.5 month deep-dive into all things Polymer:
import 'package:polymer/polymer.dart';

import 'dart:html';
import 'package:ice_code_editor/ice.dart' as ICE;

@CustomTag('ice-code-editor')
class IceCodeEditorElement extends PolymerElement {
  @published String src;
  @published int line_number = 0;
  ICE.Editor editor;

  IceCodeEditorElement.created(): super.created() {
    var container = new DivElement()
      ..id = 'ice-${this.hashCode}'
      ..style.width = '600px'
      ..style.height = '400px';

    append(container);
    // ...
  }
  // ...
}
And that does the trick. I have my custom <ice-code-editor> element back and am able to embed multiple instances of it:



But that is only half of tonight's battle. I also wanted to deploy this. That raises a very important question: how the heck do you deploy Polymer.dart code?

I know that I need at least one thing added to make that happen—a Pub transformer. To make ready its custom elements, Polymer.dart includes a build “transformer” that does all of the necessary work. Specifying a transformer is done in the pubspec.yaml file:
name: ice_code_editor
# ...
dependencies:
  crypto: any
  js: any
  ctrl_alt_foo: any
  json: any
  polymer: any
transformers:
- polymer:
    entry_points: web/polymer.html
But, even though this worked fine from Dartium, the resultant pub serve fails. When I load the polymer.html test page, I get a 404 for http://localhost:8080/polymer.html_bootstrap.dart.js. Checking the output from the pub serve web server log, I see a bunch of warnings and errors—errors like:
Build error:
Transform Dart2JS on ice_code_editor|web/polymer.html_bootstrap.dart threw error: 'file:///mnt/data/b/build/slave/dart-editor-linux-stable/build/dart/
sdk/lib/_internal/pub/lib/src/barback/dart2js_transformer.dart': malformed type: line 118: type 'CompilerException' is not loaded
                if (error is CompilerException) return; 
                             ^
malformed type used.
../../../../mnt/data/b/build/slave/dart-editor-linux-stable/build/dart/sdk/lib/_internal/pub/lib/src/barback/dart2js_transformer.dart 118  Dart2JSTransformer.apply.<fn>.<fn>
Eventually, I read enough of the errors to realize that one of them contains useful information. It seems that I have one last holdover from the ancient 2013 version of Polymer.dart. The method signature for attributeChanged(), which I am overriding in my Polymer, has changed:
packages/ice_code_editor/polymer/ice_code_editor_element.dart:33:8: Error: Cannot override method 'attributeChanged' in 'Polymer'; the parameters do not match.
  void attributeChanged(String name, String oldValue) {
       ^^^^^^^^^^^^^^^^
After fixing that (it now requires a third, newValue parameter), I am in business. My <ice-code-editor> Polymer works in Chrome just like it did in Dartium:



Once that is working, I can pub build my page, which dumps output into the build subdirectory. Once it is done, I start a simple HTTP server in there:
➜  build git:(polymer) ✗ python -m SimpleHTTPServer 8000
Serving HTTP on 0.0.0.0 port 8000 ...
With that, I can access my Polymer from any static site with any modern web browser:



Nice! I still need to build for production (this includes some debug code). I would also like to see if I can shrink the codesize down some. Between the editor and the visualization layer, there is a lot of code. Still the current 2.5 MB seems excessive. But hopefully the hard part is out of the way.

Day #985

Saturday, November 9, 2013

Giving Up on KeyEvents until after Dart 1.0


I think it safe to say that KeyEvent won't be fixed in time for the Dart 1.0 release. This makes me sad, but I understand the various moving parts making this a problem. Since whining won't help, it is time to give up the ghost and move onto workarounds.

I already have a separate keyboard shortcut library that boasts some testing and isolates the untestable features for a later time when KeyEvent is fully implemented. What is still not working (or at least not tested, which is the same thing, right?) in the ICE Code Editor is navigation with arrow kyes, hitting enter in text fields and hitting escape anywhere to hide dialogs. To move on, I think it best to give up trying to generate real or fake KeyEvents.

Instead I am going to fallback to the old standby of hidden buttons. These buttons can be created with style="display:none" so that they will never be seen by humans. They can be clicked by tests and, when clicked, they can call the same methods used by the keyboard handlers. I do this with a heavy heart (OK, so I'm not entirely done whining).

The first test that I would like to get passing verifies what happens after a project list is filtered and then the down arrow key is pressed twice. In the UI, it looks something like:



My test looks like:
      test("down arrow key moves forward in list", (){
        helpers.typeCtrl('O');
        helpers.typeIn('project 1');

        // project 11
        // project 10 *
        // project 1

        helpers.arrowDown(2);

        expect(
          document.activeElement.text,
          equals('Project 10')
        );
      });
Aside from the minor nuisance that the test does not work, I am rather proud of this acceptance test. It reads well and (ideally) verifies real human behavior.

Since I cannot create an event with the DOWN keyCode, this is a case in which I need a fake button. I will assume that my fake button for the down arrow key will have an ID of fake_down_key. If present, the helpers.arrowDown() method needs to click this fake down button instead of trying to generate a keydown event:
arrowDown([times=1]) {
  // var e = new KeyEvent('keydown', keyCode: KeyCode.DOWN).wrapped;
  var fake_button = document.query('#fake_down_key');
  if (fake_button == null) return;

  new Iterable.generate(times, (i) {
    // document.activeElement.dispatchEvent(e);
    fake_button.click();
  }).toList();
}
My test is still failing because there is no such button in the UI. So I add one:
class OpenDialog extends Dialog implements MenuAction {
  Element menu;
  open() {
    menu = new Element.html(
      '''
      <div class=ice-menu>
      <h1>Saved Projects</h1>
      ${filterField}
      <ul></ul>
      <button id=fake_down_key></button>
      </div>
      '''
    );
    menu.
      queryAll('button').
      forEach((b){ b.style.display = 'none';});
    // ...
    _handleArrowKeys(menu);
  }
  // ...
}
Next, I need to add the same event handler for when the fake button is clicked as when the down arrow key is pressed:
  _handleArrowKeys(el) {
    el.onKeyDown.listen(_handleDown);
    el.onKeyDown.listen(_handleUp);

    // Hacks in lieu of KeyEvent tests
    menu.query('#fake_down_key').onClick.listen(_handleDown);
  }
I can almost live with these changes. I have not changed any functionality, I have only added some useless code from the human perspective. Unfortunately, the test will not work as-is because it includes a check for keycodes, which there will be none for click events. So I have to amend the initial guard clause to only apply to keydown events:
  _handleDown(e) {
    if (e.type == 'keydown' && e.keyCode != KeyCode.DOWN) return;
    // ...
  }
Not ideal, but I have a passing test again:
PASS: Keyboard Shortcuts Open Projects Dialog down arrow key moves forward in list
I am going to have some fun in store for when the Enter key is ambiguous, but I think this will mostly work. It gives me some assurance that keyboard interaction is working. It should be fairly easy to back out once KeyEvent is fixed. Most importantly, it does not affect the existing human-facing functionality.



Day #930

Sunday, November 3, 2013

Still Can't KeyEvent in Dart


I have not been pushing my #pairwithme sessions much of late, in part because Dart's keyboard events were broken for a long time. I don't have tons of time in the upcoming weeks, but I would at least get to a point where #pairwithme is a possibility again, so let's see if I can fix the build in ICE Code Editor.

When I first tried the build with the most recent version of Dart, there were some 130+ failing tests. As has been the case quite often of late, this was due to one or more libraries undergoing some breaking changes—this time the js-interop. Most of those changes were actually rather pleasant—of the remove old, unnecessary method calls variety. After doing that, I am down to 30 or so, which mostly seem to involve my ctrl-alt-foo keyboard shortcut library.

And, unfortunately, there still seem to be the same old bugs in Dart's KeyEvent—namely that I cannot use it to create a wrapped KeyboardEvent with an actual keycode. Even more unfortunately, the static class hack that I devised no longer seems to be working for me.

To review, I cannot dispatchEvent() because there is no way to generate custom keyboard events with data in tests. I cannot add events to CustomStream because the elements on which I am trying to listen for events are dynamically created.

In other words, if I try to listen for Enter events with the onKeyDown property:
  _handleEnter(el) {
    el.onKeyDown.listen((e){
      if (e.keyCode != KeyCode.ENTER) return;
      // Try to do stuff here...
    });
  }
This will not work with my tests because the wrapped KeyboardEvent—which I try to generate in tests—always has a zero keyCode.

And, If I use the EventStreamProvider interface:
  _handleEnter(el) {
    KeyEvent.keyDownEvent.forTarget(el).listen((e) {
      // Try to do stuff here...
    });
  }
Then Dartium generates the following when I try to use the application itself:
Exception: InvalidStateError: Internal Dartium Exception
(with no stacktrace)

Bummer. I think that I have an open bug for the second problem. I really need to make sure that I have the first one in the system. All I can do is wait patiently after that.


Day #924

Tuesday, October 15, 2013

Yet Another Awful Hack Needed to Test Keyboard Events in Dart


I really want to be done with this. But at the same time, I cannot leave code broken when is likely to sit for a while.

To summarize: it is currently impossible to generate custom keyboard events in Dart. This is a problem because it is quite difficult to test applications that involve keyboard interaction. This makes me sad.

Hope is not all lost. Recent changes to the bleeding edge of Dart have begun to reintroduce the ability to dynamically create keyboard events. More than just generate keyboard events, the KeyEvent class promises to normalize keyboard behavior across browsers. But since this is bleeding edge, there are problems:
  1. When used in live code, KeyEvent listeners do not work, throwing “Internal Dartium Errors”
  2. Even in test code, tests relying on KeyEvent streams need access to the same event stream used by the application—dispatching to elements is not sufficient
  3. Creating a KeyEvent wraps a corresponding low-level KeyboardEvent that can be dispatched to elements, but it lacks actual keyboard data (keyCode, charCode)
  4. Dispatching the high-level KeyEvent generates Internal Dartium Errors—in test and application code
In a desperate attempt to get my tests passing and useful I have come up with two workarounds. The first addresses #1 and #2. Instead of listening to a stream of KeyEvent, I listen to Element “on” properties like onKeyDown. I still get Internal Dartium Errors, but somehow these do not halt execution. Instead they are seen as warnings, allowing the code to proceed. I still need to accommodate #2, but I do so by caching a single stream in a class. And where I have used that workaround, my code is actually better for it. Reusing a single stream rather than creating new ones each time a listener is needed is a help.

But there are times that I need to dispatch to dynamically created elements, like menu systems. For that, I can use #3 above, though the application code needs to accept zero valued keyCode properties on events. That is not too horrible. The structure of the code remains unaffected for now and once KeyEvent wrapped keyboard events support setting values—I only need remove checks for zero values. I had hoped this would be the end of it until Dart's KeyEvent class stabilized.

Unfortunately, my hack for #3 works when dispatching only one event to an element. My text input fields tend only to need to listen for an Enter keydown event. If there is any keydown event with keyCode equals zero, I can safely assume that I am trying to dynamically create an Enter keydown. Unfortunately for me, the ICE Code Editor also include an arrow-key navigatiable menu system. My tests had been fairly nice thanks to some nice helper code:
      test("down arrow key moves forward in list", (){
        helpers.typeCtrl('o');
        helpers.typeIn('project 1');
        // project 11
        // project 10 *
        // project 1

        helpers.arrowDown(2);

        expect(
          document.activeElement.text,
          equals('Project 10')
        );
      });
And so, finally, I believe that I am out of luck keeping things somewhat sane. Because the menu is dynamically generated, my test cannot easily gain access to a stream to add custom events. So my workaround for #1 and #2 is out. Because I need to distinguish between up and down events, my workaround for #3 is out. I really, really want to stop working on this, but I cannot leave the tests failing. I do not want to skip tests and hope that I come back to fix them later. I need to record the last dynamically created keycode somewhere. If I cannot do that on the event being dispatched, then I will set it in a common class:
class Keys {
  static int _lastKeyCode;
  static set lastKeyCode(v) { _lastKeyCode = v; }
  static get lastKeyCode {
    print('Horrible hack. FIXME ASAP!!!!');
    return _lastKeyCode;
  }
  // ...
}
I use a private, static variable, _lastKeyCode, to hold the value. I define a static getter and setter that wrap this private variable, making it seem like the Keys class has a lastKeyCode property. But in there, I print out a FIXME message that I am not going to ignore for long. To complete my horrid hack, my helpers need to set the “property”:
arrowDown([times=1]) {
  var e = new KeyEvent('keydown', keyCode: KeyCode.DOWN).wrapped;
  Keys.lastKeyCode = KeyCode.DOWN;

  new Iterable.generate(times, (i) {
    document.activeElement.dispatchEvent(e);
  }).toList();
}
And my application code needs to honor it:
  _handleDown(e) {
    if (e.keyCode != KeyCode.DOWN && Keys.lastKeyCode != KeyCode.DOWN) return;
    // ...
  }

Yup, that's pretty ugly. But I have my keyboard handling tests passing again for the first time in two months. I am in no rush to push this to production, but hopefully I am better prepared for the stabilization of KeyEvent. All in all, this is a tough problem to solve—especially given that Dart needs to compile to JavaScript that normalizes behavior across browsers. Light is at the end of the tunnel and I think I have enough duct tape to keep this thing running until the end is reached.

Day #905

Saturday, October 12, 2013

KeyEvents are for Unit Tests


It took me a while, but I think that I have finally realized that the latest KeyEvent changes in Dart are for unit tests, not acceptance tests. I like unit tests for driving new functionality, but rather prefer having acceptance tests around as being better at catching bugs—or at least giving me the confidence that swaths of the application are behaving more or less as designed. Still, unit tests are pretty nice and I hope to put them to use tonight.

Toward that end, I give up (at least temporarily) the hope to get the acceptance tests in the ICE Code Editor working. Instead, I am going to see if I can get the ctrl_alt_foo shortcut library working again.

Actually, working again is not quite right. It works now and the build has never once failed. But it works through an absolutely insane hack involving dynamically created JavaScript code. For the record, I opted for that hack not because Dart lacks keyboard handling, but because it lacked the ability to test it well.

With the JavaScript hack and various Dart hacks that preceded it, I tried my best to stay close to existing Dart APIs. Where Dart has KeyEvent, ctrl_alt_foo has KeyEventX. Where Dart has KeyboardEventStream, ctrl_alt_foo has KeyboardEventStreamX. My sincere hope is that, even though acceptance tests may be out of the question, the recent KeyEvent patched to Dart's bleeding edge are sufficient to remove my “X” versions of Dart core classes.

From what I learned yesterday, I don't think that removing these is an option just yet. For one thing, I need to keep some of the decoration that I add to KeyEvent (e.g. isCtrl, isChar, etc). More pertinent to testing, I need to keep KeyboardEventStreamX because I need it to return the same stream every time.

As I found yesterday, adding custom keyboard events to a stream for testing only works if I am adding to the same stream on which the code is listening. What this means in practice is that it is not (currently) possible to dispatch events to elements in Dart as is possible in JavaScript. Dart limits developers to adding events to streams. If I create multiple streams for an element, then add an event to the last stream, only the last stream will see the event—not all of the streams listening to the same element.

In other words, my existing approach to KeyboardEventStreamX is not going to work because it returns a new stream every time its “on” class methods are invoked:
class KeyboardEventStreamX extends KeyboardEventStream {
  static Stream onKeyDown(EventTarget target) {
    return Element.
      keyDownEvent.
      forTarget(target).
      map((e)=> new KeyEventX(e));
  }
}
Instead, I switch to ShortCut, which needs a way to always use the same stream, but also to return a stream that wraps normal KeyEvent instances in KeyEventX. I settle on returning a static stream controller stream, which will wrap KeyEventX instances and also exposing a static dispatchEvent() method for placing events directly on the single instance of the document.body stream:
class ShortCut {
  // ...
  static var _stream = KeyboardEventStream.onKeyDown(document.body);
  static var _streamController = new StreamController.broadcast();

  static get stream {
    _stream.listen((e) {_streamController.add(new KeyEventX(e));});
    return _streamController.stream;
  }

  static void dispatchEvent(KeyEvent e)=> _stream.add(e);
  // ...
}
I then use this to dispatch events as:
type(String key) {
  ShortCut.dispatchEvent(
    new KeyEvent('keydown', keyCode: keyCodeFor(key))
  );
And can test that the events are working with:
  test("can listen for key events", (){
    _s = ShortCut.stream.listen(expectAsync1((e) {
      expect(e.isKey('A'), true);
    }));

    type('A');
  });
That works:
PASS: can listen for key events 
But I don't know if that makes my life much easier. I am guaranteed one stream for listening to events. The _stream static variable is assigned when ShortCut is loaded. If I limit my testing to dispatching keyboard events through ShortCut.dispatchEvent() that same stream will always be used. So I have side-stepped the multi-stream problem. But the ShortCut.stream value is just a regular Stream, not a CustomStream that supports add(). Forcing events through dispatchEvent() seems likely to cause confusion in the future.

I will call it a night here and think on this approach.


Day #902

Friday, October 11, 2013

Trying to Figure Out What I Can Test with KeyEvent


Still stinging from last night's defeat, I try to pick up the broken pieces of my soul tonight.

I mean, how cool would it have been to get custom keyboard events working in Dart on the 900th day of the current chain? Having dutifully file the requisite bug, I move on tonight to see what I can salvage from last night's effort.

I start by pulling down the latest Dart DSK (Dart VM version: 0.1.2.0_r28552 (Fri Oct 11 14:06:31 2013) on "linux_x64") from the continuous build archive. The first two listeners in the following still generate errors:
import 'dart:html';
main(){
  var subscription = KeyboardEventStream.onKeyDown(document.body).listen(
      (e) => print('KeyboardEventStream listener'));
  var subscription2 = KeyEvent.keyDownEvent.forTarget(document.body).listen(
      (e) => print('KeyEvent listener'));
  var subscription3 = document.body.onKeyDown.listen(
      (e) => print('regular listener'));
}
Only subscription3 from the document.body.onDown stream give me results when I hit a key:
regular listener 
The other two spew multiple Dartium errors:
Exception: InvalidStateError: Internal Dartium Exception 
undefined
As far as I can tell, the first two streams (from KeyboardEventStream and KeyEvent) are both useless in user-facing code. Even if I run the unit tests for the new KeyEvent in Dartium, hitting any key after running the test generates oodles of Internal Dartium Exceptions. But maybe the onKeyDown can be of some use?

Well, no. The onKeyDown property is a _ElementEventStreamImpl. Sadly that is not a subclass of the new CustomStream and therefore does not support the add() method for dispatching events:
Exception: Class '_ElementEventStreamImpl' has no instance method 'add'.

NoSuchMethodError : method not found: 'add'
Receiver: Instance of '_ElementEventStreamImpl@0x3918afae'
Arguments: [Instance of 'KeyEvent']
Bummer. I suppose this is the purpose of the KeyboardEventStream and KeyEvent wrappers. But still… bummer.

Well, it seems that I remain at a dead-end in ICE Code Editor—at least until my bug is addressed. I can write testable code that crashes the browser or non-testable code because the working property does not support dispatching events. In my mind, testing trumps runnable code. At some point the testable code will work—and maybe it already does when compiled to JavaScript.

Even this proves difficult. Consider if I stick with the KeyEvent class and listen for keydown events:
  var subscription2 = KeyEvent.keyDownEvent.forTarget(document.body).listen(
      (e) => print('KeyEvent listener'));

  // Trigger / listen for event on document.body
  var streamDown = KeyEvent.keyDownEvent.forTarget(document.body);
  var subscription4 = streamDown.listen(
      (e) => print('streamDown listener ${e.keyCode}'));
  streamDown.add(new KeyEvent('keydown', keyCode: 4, charCode: 0));

  // Trigger / listen for event on the H1
  var h1Down = KeyEvent.keyDownEvent.forTarget(query('h1'));
  var subscription5 = h1Down.listen(
      (e) => print('h1Down listener ${e.keyCode}'));
  h1Down.add(new KeyEvent('keydown', keyCode: 5, charCode: 0));
Both subscription2 and subscription4 listen for keydown events on document.body. When I add a new keydown KeyEvent to the stream from the second group, I expect to see both event listeners fire. But it turns out that I am adding the KeyEvent to the second stream and only the second stream. I am not generating an event that will be seen by all listeners on document.body—only an event that will be seen by that second stream. Worse, when I add an event to the keydown stream of an <h1>, it is again only to the <h1> tag's stream and it does not bubble up.

I expect the above code to trigger both the document.body listeners twice—both should see the custom keyboard event on document.body and both should see the <h1> event bubble. But I only see the direct events:
streamDown listener 4 undefined:1
h1Down listener 5 
This is of very limited use for me. For instance, if I want to test that a keydown in the ICE project filter shows all the projects that start with “a” I need access to the KeyEvent stream that actually listens to the corresponding text field. For that to work, I would need to expose the filter stream (and every other stream) in the ICE code as a public property. There is no way I am doing that just to support testing.

Bother.

As depressing as all of that is, hope is not completely lost. I do believe that the keyboard shortcut code ought to be somewhat testable. Given what I learned today, I doubt that I will be able to add a custom KeyEvent for Ctrl+O to a stream in ICE to test that the open dialog appears. Still, I think the keyboard shortcut library itself ought to be testable. And perhaps I can expose some high-level testing methods from that same package to support limited keyboard testing in ICE. Something for tomorrow. Hope.


Day #901

Saturday, July 27, 2013

Dart in the ICE Code Editor


During a brief exchange with Seth Ladd, he suggested that the ICE Code Editor might be able to perform Dart coding similar to try.dartlang.org. I am not quite convinced that the additional compile time would make for a satisfactory experience (there is already a 2 second delay between the end of typing and an auto-update). But, it an intriguing enough idea that I am going to explore it.

First up, can I edit and run Dart code in ICE with the Dartium browser? Yes I can:



As an aside I would really like to suppress those Application Cache messages. They are really, really annoying. Anyhow…

I am going to get those editor warnings since the JavaScript syntax highlighter is in action. I will have to live with them for a bit. Next I add another warning by importing the dart:html library and doing something simple with it:
<body></body>
<script src="/ice/packages/browser/dart.js"></script>
<script type="application/dart">
import 'dart:html';
main() {
  print("Yay Dart!!!");
  document.body
    ..append(new Element.html('<h1>Howdy Space Cowboy!</h1>'))
    ..style.margin = '250px';
}
</script>
That works as well. The <h1> element is successfully appended to the preview frame behind the code:



I have no reason to think that Three.dart would not work in there as well.

At this point, I am sufficiently satisfied that I am ready to dive into a try.dartlang.org-like implementation for non-Dart browsers (i.e. all of them). This is likely a multi-night exploration, but I need to start somewhere. That somewhere is to pull in the compiled JavaScript that try.dartlang.org currently uses:
<!-- ... -->
<script src="http://try.dartlang.org/leap.dart.js"></script>
Unsurprisingly, that does not work, failing while trying to call appendChild() on null. In other words, that leap.dart.js expects the page in which it is embedded to contain a DOM structure nearly identical to that of try.dartlang.org.

So I spend some time digging through the leap.dart code used on try.dartlang.org. Happily, it looks like I will not need large sections of it (parsing syntax highlighting and communicating with iframes) as ICE already does that. I will need to be able to extract the Dart code between <script> tags, so I will pick up there tomorrow and see if I can pull enough of leap.dart into my own library to get it working on a local copy of ICE.

This should be fun, mostly because I have a built-in excuse to dig through someone else's code for a few days. I love reading other people's code!

Day #825

Saturday, July 20, 2013

Bare Minimum: File Size and Numbers for Dart Deployment (Application Cache)


Following up on last night's deployment improvements in the Dart version of the ICE Code Editor, I hope to be able to finish up today. Whereas yesterday I shrunk the application payload with the --minify option in dart2js, today I would like to shrink the payload by being a bit more judicious with what needs to be downloaded.

Taking a look at http://gamingjs.com/ice-beta/ (which currently holds the Dart version of ICE) in an incognito browser session, I find:


18 requests  ❘  190 KB transferred  ❘  1.66 s (load: 1.64 s, DOMContentLoaded: 139 ms)
In some respects, that is not bad. This is the non-minified version of ICE, meaning that the compiled JavaScript is 912 KB alone. That, plus the 17 other requests that are needed to download ICE should push the payload up to well over 1 MB. Since the actual data transferred is only 190 KB, it would seem that gzip encoding of the resources is producing some nice bandwidth savings. Combined that with the 60% decrease in the compiled JavaScript from the --minify option, and ICE should be in fine shape.

And yet…

There is an obvious gap in the transfer of files. What gives? And if I can eliminate it, will the download go even faster?

The answer to the first question—the cause of the gap in transferring files—lives in the JavaScript console. There are many lines of output (around 100, in fact) ending with:
...
Application Cache Progress event (95 of 100) http://gamingjs.com/ice-beta/part.js.map
Application Cache Progress event (96 of 100) http://gamingjs.com/ice-beta/packages/unittest/src/utils.dart
Application Cache Progress event (97 of 100) http://gamingjs.com/ice-beta/packages/ice_code_editor/full/rename_dialog.dart
Application Cache Progress event (98 of 100) http://gamingjs.com/ice-beta/packages/unittest/src/test_case.dart
Application Cache Progress event (99 of 100) http://gamingjs.com/ice-beta/packages/js/src/wrapping/typed_proxy.dart
Application Cache Progress event (100 of 100) 
Application Cache Cached event
Document was loaded from Application Cache with manifest http://gamingjs.com/ice-beta/editor.appcache
So it seems that I may be putting just a little too much into application cache. Well, maybe a lot. Considering that loading the editor and the default project only required 18 requests, I am almost certainly loading way too much.

A closer inspection shows that #96 and #98 of the application cache files are unit test files—those certainly are not needed in application cache. They probably do not need to exist on the server at all. But even more so, there is absolutely no reason to jam a single Dart file into application cache. There is not a single production browser that supports raw Dart, so I am forcing ICE users on http://gamingjs.com/ice-beta to download a bunch of files for no reason whatsoever. Sorry about that.

Application cache beasts, like the ICE Code Editor, need a manifest file on the document's <html> tag:
<!DOCTYPE html>
<html manifest="editor.appcache">
  <head>
    <title>code editor</title>
    <meta charset="utf-8">
    <script src="appcache.js"></script>
    <script src="packages/browser/dart.js"></script>
    <script src="packages/browser/interop.js"></script>
    <script src="main.dart" type="application/dart"></script>
  </head>
  <body>
  </body>
</html>
This manifest file informs browsers what they need to down for the application to function properly:
CACHE MANIFEST
# 2013-07-10

CACHE:
/favicon.ico
/Three.js
/Tween.js
/Detector.js
/physi.js
/Mouse.js
/Scoreboard.js
/ChromeFixes.js
/ammo.js
/physijs_worker.js

part.js
main.dart
index.html
main.dart.js.map
main.dart.js
packages/js/js.dart
packages/js/src/wrapping/js/object_to_map_adapter.dart
# Many, many, many more files...

NETWORK:
*
The asterisk in the NETWORK section of my manifest says that anything not explicitly listed in the CACHE session should downloaded over the network. I really ought to allow all of the Dart code, along with any supporting resources, to get served up over the network. I can still leave them on the server, in case a Dartium browser comes along, but not place it in application cache.

After excluding a bunch of files, I get my list down from 100 to 33:
➜  ice-beta git:(gh-pages) ✗ cat editor.appcache | grep -v \\.dart$ | \
  grep -v pubspec\\. | \
  grep -v unittest | \
  grep -v inconsolata | \
  grep \\. | \
  wc -l
33
That is much, much better because, as everyone knows, individual files have a much greater impact on download speeds than do large files.

I find that I can generate the same list of worthy application files with a grep statement that whitelists HTML, JavaScript, and source map files:
➜  ice-beta git:(gh-pages) ✗ find | \
  grep -e \\.js$ -e \\.map$ -e \\.html$ -e \\.css$ | \
  grep -v -e unittest -e /lib/ | \
  wc -l           
22
There is some duplication in the lib/ sub-directory that I do not fully understand (it may just be how I coped it last night). That is something for another day. For now I ignore them in the grep -v (ignore) statement.

I am explicitly ignoring the .deps file that dart2js generates. I should probably dot-gitignore that file—it includes local file URLs:
file:///home/chris/local/dart/dart-sdk/lib/_collection_dev/arrays.dart
file:///home/chris/local/dart/dart-sdk/lib/_collection_dev/collection_dev.dart
...

I do need to manually add the main.dart script to the application cache manifest—the browser does request it even if it does not know how to process it (because it is in a <script> tag in the HTML). With those changes, my entire manifest file contains:
CACHE MANIFEST
# 2013-07-20

CACHE:
/favicon.ico
/Three.js
/Tween.js
/Detector.js
/physi.js
/Mouse.js
/Scoreboard.js
/ChromeFixes.js
/ammo.js
/physijs_worker.js

main.dart

part.js
index.html
main.dart.js.map
main.dart.js
packages/js/dart_interop.js
packages/browser/interop.js
packages/browser/dart.js
packages/ice_code_editor/js/deflate/rawinflate.js
packages/ice_code_editor/js/deflate/rawdeflate.js
packages/ice_code_editor/js/ace/mode-css.js
packages/ice_code_editor/js/ace/ace.js
packages/ice_code_editor/js/ace/theme-textmate.js
packages/ice_code_editor/js/ace/theme-chrome.js
packages/ice_code_editor/js/ace/ext-searchbox.js
packages/ice_code_editor/js/ace/mode-html.js
packages/ice_code_editor/js/ace/worker-javascript.js
packages/ice_code_editor/js/ace/keybinding-emacs.js
packages/ice_code_editor/js/ace/mode-javascript.js
packages/ice_code_editor/css/ice.css
packages/ice_code_editor/html/preview_frame.html
part.js.map
appcache.js

NETWORK:
*
After pushing that to http://gamingjs.com/ice-beta and firing up a new incognito window, I find:


18 requests  ❘  103 KB transferred  ❘  1.39 s (load: 1.37 s, DOMContentLoaded: 187 ms)

That is a 16% decrease in load time when compared to the previous Dart version of ICE, but it is still 30% slower than the old pure JavaScript version of ICE.

Ultimately it does not matter too much. I am still looking at a load time of less than 1.5 seconds for the first access, which is pretty darn good. Subsequent access will be even better since it never even touches the the network—the benefits of being stored in application cache. The dart2js tool is only going to make smaller compiled JavaScript, though I would guess that the changes from here on out will be smaller—that we will not see compiled Dart smaller by many orders of magnitude.

And if I find that I need much better, there is always SPDY!


Day #818

Tuesday, July 2, 2013

New Beta to Test Dart FF Fix

‹prev | My Chain | next›

After a bit of detective work last night, with a #pairwithme assist from Jon Kirkman, I found that the Firefox load issue in the Dart version of the ICE Code Editor is a timing issue.

Last night we found that we could ensure that the preview layer would load if we delayed the preview layer by 1000 milliseconds:
class Editor {
  // ...
  updatePreview() {
    if (this.edit_only) return;

    this.removePreview();
    var iframe = this.createPreviewIframe();

    var wait = new Duration(milliseconds: 1000);
    new Timer(wait, (){
      if (iframe.contentWindow == null) return;
      // Do iframe-y stuff here...
    });
  }
  // ...
}
Obviously that is not much of a long term solution—3D Game Programming for Kids programmers should not have to wait any longer than necessary for preview updates.

Might it be sufficient to listen to the onLoad stream? I give it a try, replacing the timer:
class Editor {
  // ...
    if (this.edit_only) return;

    this.removePreview();

    var iframe = this.createPreviewIframe();
    iframe.onLoad.listen((_) {
      if (iframe.contentWindow == null) return;
      // Do iframe-y stuff here...
    });
  }
  // ...
}
And that seems to do it. At least locally. There is still the nagging issue of ensuring that it works in application in production. But first…

I have been messing around with the new GitHub release feature today. I am hopeful that it will encourage me to produce useful release notes. So far I have:



One thing that I have to figure out is the difference between the title and the tag. For now, I tag with the semantic version (v0.0.6) and title with something a little more meaningful if it makes sense (0.1-beta1). The semantic version corresponds to version in my pubspec.yaml—the version that will be used for packaging on Dart Pub.

To try my fix out in its ultimate destination, appcache in http://gamingjs.com/ice-beta, I need to publish to pub, then install it on the gamingjs.com site. So I start by updating ICE's pubspec.yaml:
name: ice_code_editor
version: 0.0.7
#...
Then I pub lish my package to Dart Pub, then pub update the gamingjs site:
➜  ice-beta git:(gh-pages) ✗ pub update
Resolving dependencies..........
Downloading ice_code_editor 0.0.7 from hosted...
Dependencies updated!
Dart pub still does not work well with static sites like GitHub pages, so I am forced to manually remove the symbolic links and replace them with actual copies:
➜  ice-beta git:(gh-pages) ✗ cd packages
➜  packages git:(gh-pages) ✗ ls -l
total 24
lrwxrwxrwx 1 chris chris 65 Jul  2 23:58 browser -> /home/chris/.pub-cache/hosted/pub.dartlang.org/browser-0.5.20/lib
lrwxrwxrwx 1 chris chris 64 Jul  2 23:58 crypto -> /home/chris/.pub-cache/hosted/pub.dartlang.org/crypto-0.5.20/lib
lrwxrwxrwx 1 chris chris 72 Jul  2 23:58 ice_code_editor -> /home/chris/.pub-cache/hosted/pub.dartlang.org/ice_code_editor-0.0.7/lib
lrwxrwxrwx 1 chris chris 60 Jul  2 23:58 js -> /home/chris/.pub-cache/hosted/pub.dartlang.org/js-0.0.22/lib
lrwxrwxrwx 1 chris chris 62 Jul  2 23:58 meta -> /home/chris/.pub-cache/hosted/pub.dartlang.org/meta-0.5.20/lib
lrwxrwxrwx 1 chris chris 66 Jul  2 23:58 unittest -> /home/chris/.pub-cache/hosted/pub.dartlang.org/unittest-0.5.20/lib
➜  packages git:(gh-pages) ✗ rm *
➜  packages git:(gh-pages) ✗ cp -r /home/chris/.pub-cache/hosted/pub.dartlang.org/browser-0.5.20/lib browser
➜  packages git:(gh-pages) ✗ cp -r /home/chris/.pub-cache/hosted/pub.dartlang.org/crypto-0.5.20/lib crypto
➜  packages git:(gh-pages) ✗ cp -r /home/chris/.pub-cache/hosted/pub.dartlang.org/ice_code_editor-0.0.7/lib ice_code_editor
➜  packages git:(gh-pages) ✗ cp -r /home/chris/.pub-cache/hosted/pub.dartlang.org/js-0.0.22/lib js
➜  packages git:(gh-pages) ✗ cp -r /home/chris/.pub-cache/hosted/pub.dartlang.org/meta-0.5.20/lib meta
➜  packages git:(gh-pages) ✗ cp -r /home/chris/.pub-cache/hosted/pub.dartlang.org/unittest-0.5.20/lib unittest
With that, I am ready to compile my Dart into JavaScript:
➜  packages git:(gh-pages) ✗ cd ..
➜  ice-beta git:(gh-pages) ✗ dart2js  -omain.dart.js main.dart
And then push my changes to the GitHub repository:
➜  ice-beta git:(gh-pages) ✗ git ci -m "Bump ICE beta to pick up FF fix attempt" -a
➜  ice-beta git:(gh-pages) ✗ gp origin gh-pages
Finally, I load it up in Firefox and voilà! It works:



The preview show when the page loads and all is well. So last, but not least, I document this new release on GitHub:



And call it a day there.

At some point I need to decide if subsequent betas should get their own releases or if new line items should just go into an existing beta release. That's something for another day—as in after I actually reach 0.1 and releases take on more importance. For now, I am excited that release notes seem so do-able without severely impacting my existing workflow.


Day #800

Monday, July 1, 2013

Debugging Dart Applications in FireFox

‹prev | My Chain | next›

I have a problem with the ICE Code Editor, but only in Firefox. When Firefox first loads the editor, the preview layer is not showing. Strangely, this works in IE and Chrome, but not Firefox.

Since ICE is written in Dart, I am at something of a loss to explain this—after all, the whole point of Dart is to smooth out the differences between browser implementations. Still, this may not be so much Dart as it is a problem with application cache (which is where it resides in beta) or even a deployment issue.

Before I jump to conclusions, I need to start somewhere. That somewhere is setting a breakpoint on the preview layer's update callback in Firefox:



I do like the capabilities and the feel of the debugging tools in the newer versions of Firefox (I am using 22 here). What I see is that, when I load the editor the preview layer callbacks are not, in fact being called. If I press the Update button, then the callback is invoked as expected.

So why isn't the preview layer being told to update? Looking through the code, I do not see any obvious explanation. The content of the editor is being set correctly to the most recent entry in localStorage. As far as I can tell, this should always result in the preview layer being notified. In fact, I have several tests that attest to this and Chrome and IE similarly seem to agree.

And yet it is not working.

My next step is to try a non-appcache version of the editor. That is fairly easy—I have a full screen version of the editor in the example sub-directory of the ICE project. And I find... that it loads just fine locally:



I am unsure if I can eliminate any particular cause given this success. What I do know is that Firefox is definitely capable of displaying the preview correctly, but something in the beta setup is preventing this from occurring.

My next step it so try this locally in appcache. I can do this with the GitHub pages version of http://gamingjs.com/. In the root directory of my gh-pages branch, I fire up jekyll, which is the underlying technology behind GitHub pages:
➜  gamingjs git:(gh-pages) ✗ jekyll --auto --server
/home/chris/.rvm/gems/ruby-1.9.3-p194@gamingjs-site/gems/maruku-0.6.0/lib/maruku/input/parse_doc.rb:22:in `': iconv will be deprecated in the future, use String#encode instead.
Configuration from /home/chris/repos/gamingjs/_config.yml
Auto-regenerating enabled: /home/chris/repos/gamingjs -> /home/chris/repos/gamingjs/_site
[2013-07-01 22:17:28] regeneration: 385 files changed
[2013-07-01 22:17:28] INFO  WEBrick 1.3.1
[2013-07-01 22:17:28] INFO  ruby 1.9.3 (2012-04-20) [x86_64-linux]
[2013-07-01 22:17:28] WARN  TCPServer Error: Address already in use - bind(2)
[2013-07-01 22:17:28] INFO  WEBrick::HTTPServer#start: pid=17269 port=4000
...
Then I hit the page locally in Firefox to find:



It does not work locally either.

There should not be any differences between the gamingjs.com version of ICE and the version in my example directory, but to be sure, I remove the application cache manifest locally, force reload and find:



It works. Sigh.

I set the problem aside for tonight's #pairwithme session with Jon Kirkman. The #pairwithme session goes swimmingly (added the beginning of validations to prevent blank project names) and afterwards Jon starts asking questions about my Firefox issue. Eventually those questions result in some exploratory code and shortly thereafter we realize that the updatePreview() method is being called in all cases, but is having no effect under certain conditions in Firefox. Further exploratory code suggests that there is a race condition in here and, sure enough, if we add a 1000 millisecond delay between before actually updating the preview:
  updatePreview() {
    // ...
    var wait = new Duration(milliseconds: 1000);
    new Timer(wait, (){
      if (iframe.contentWindow == null) return;
      // ...
    });
  }
Then it works—even in Firefox.

Huge thanks to Jon for talking me through that problem—I had been banging my head against it too long to be in a position to make headway with it.

With the problem understood, I am ready to fix it. Tomorrow.



Day #799

Sunday, June 30, 2013

Dart Testing with Lots of Events

‹prev | My Chain | next›

The ICE Code Editor boasts a minimal set of controls:



The subject of tonight's exploration is the Update button—more specifically the checkbox in the Update button which governs auto-update. If checked, code changes are reflected automatically in the preview layer. If unchecked, then the only way to force an update is to click the Update button. That all works fine and is well tested, thanks to Dart's lovely unittest library.

What could work a little better is checking the auto-update checkbox. A programmer clicking that checkbox wants auto-update re-enabled—and that works. But it is also almost certainly true that she wants any code changes since auto-update was disabled to be reflected immediately. And that does not work.

I think I have a fairly good idea how to implement that. More perplexing is how to test that. Thanks to Dart's iframe security restrictions, I cannot (easily) query the contents of the preview iframe to verify that the update occurred correctly. Instead I have to rely on secondary indicators like the onPreviewChanged event stream. This is how existing tests verify the update feature:
    test("updates the preview layer", (){
      helpers.createProject("My Project");
      document.activeElement.
        dispatchEvent(new TextEvent('textInput', data: '<h1>Hello</h1>'));

      editor.onPreviewChange.listen(expectAsync1((_)=> true));

      helpers.click('button', text: " Update");
    });
Here, I am using unittest's expectAsync1(), which will poll until a callback is invoked with a single argument, to test my expectation. As long as the onPreviewChange event occurs, this test passes.

For my code tonight, I need to first uncheck the checkbox (by clicking it), then sending a text event with new content, and finally re-checking the auto-update checkbox and verifying that a change event occurs. Something like this ought to do the trick:
    test("checking the checkbox updates the preview layer", (){
      var button = helpers.queryWithContent("button","Update");
      var checkbox = button.query("input[type=checkbox]");
      checkbox.click();

      document.activeElement.
        dispatchEvent(new TextEvent('textInput', data: '<h1>Hello</h1>'));

      editor.onPreviewChange.listen(expectAsync1((_)=> true));

      checkbox.click();
    });
That ought to work, except it passes. That is, even though I know that the feature is not working, my test does not capture this.

After messing around a bit, I find that… this really ought to work. I confirm that the checkbox is unchecked and rechecked. I confirm that the event does not propagate (clicking the Update button to manually update the preview). I confirm that the editor is, indeed, disabled from auto-updating—at least for a little while.

And that little while turns out to be the key. I am dispatching a text event and then immediately unchecking the auto-update box. This immediate unchecking winds update re-enabling auto-update before the text event propagates through the editor. So that, by the time the editor is aware that an update has occurred, it is already in auto-update mode.

To fix, I need a little delay:
    test("checking the checkbox updates the preview layer", (){
      var button = helpers.queryWithContent("button","Update");
      var checkbox = button.query("input[type=checkbox]");
      checkbox.click();

      document.activeElement.
        dispatchEvent(new TextEvent('textInput', data: '<h1>Hello</h1>'));

      editor.onPreviewChange.listen(expectAsync1((_)=> true));

      var wait = new Duration(milliseconds: 100);
      new Timer(wait, (){
        checkbox.click();
      });
    });
That does the trick. I now have a failing test that accurately captures my buggy behavior. When I fix it, I know that I will have a test that can catch regressions.

And as expected, fixing the bug turns out to be fairly easy. I make use of the iterable nature of stream by adding a where() clause to the checkbox's onClick stream. I only want to listen to streams that contain events in which the checkbox is checked:
    return _update_button = new Element.html('''
        <button>
           <input checked type=checkbox/>
           Update
         </button>'''
      )
      // other listeners here...
      ..query("input").onChange.
          where((e) => e.target.checked).
          listen((e)=> ice.updatePreview());
With that, I have another feature complete and am comforted in the knowledge that I have a strong test describing it. That is a good win.


Day #798

Saturday, June 29, 2013

The Very Best Format for Dart Optional Constructor Parameters

‹prev | My Chain | next›

I dearly love optional parameters in Dart methods, functions and especially constructors. That said…

A long list of constructor arguments tends to raise my code-too-wide hackles. Consider the constructor for the Editor class in the ICE Code Editor. It has one required argument, a DOM element to hold the editor, and four optional, named parameters:
class Editor {
  Editor(this._el, {this.edit_only:false, this.autoupdate:true, this.title, this.enable_javascript_mode:true}) {
    this._startAce();
    this._applyStyles();
  }
  // ...
}
I like to keep my lines of code under 60 characters wide. This is partially superstition and partially legitimate suspicion. The suspicion is that wide code is hiding complexity, which is a natural enemy of maintainability.

It is hard to get too worked up about constructor arguments, but they do have a significant effect on behavior. The above constructor accepts an edit_only parameter, which defaults to false. It accepts autoupdate, which defaults to true. It accepts title, which is null by default. Finally it accepts enable_javascript_mode, which defaults to true.

OK, so maybe it is easy to get worked up about it when I list those out. Each of those have behavior implications and burying defaults in a long line of unrelated defaults seems like a good way to make the code and intent less readable.

I am not a fan of placing one parameter per line as it then becomes difficult to distinguish between constructor arguments and constructor body:
class Editor {
  Editor(this._el, {
    this.edit_only:false,
    this.autoupdate:true,
    this.title,
    this.enable_javascript_mode:true
  }) {
    this._startAce();
    this._applyStyles();
  }
  // ...
}
In my day dreams, it might be nice to use Dart's redirecting constructors to set optional parameters and then redirect to a “real” constructor:
class Editor {
  Editor.config(this._el, {
    this.edit_only:false,
    this.autoupdate:true,
    this.title,
    this.enable_javascript_mode:true
  }) : this();

  Editor() {
    this._startAce();
    this._applyStyles();
  }
  // ...
}
But that will not work because redirecting constructors cannot use field initializers like that.

So I am left to decide how best to format my largish constructor for optimum readability. It should be obvious that the list of parameters and constructor body are logically separate. It should be obvious that optional parameters are of less importance than required parameters. Perhaps something like this:
class Editor {
  Editor(
    this._el, {
      this.edit_only:false,
      this.autoupdate:true,
      this.title,
      this.enable_javascript_mode:true
    }) 
  { this._start(); }
  // ...
}
I think I can live with that. The constructor name, Editor, has the same indent level as the constructor body (which I squash into a single line). The required parameter, which is assigned to the _el private variable via field initialization, is clearly part of the constructor parameters. By indenting it, it makes the body stand out as logically different that parameters. Finally, by indenting the optional, named parameters, it further aids to distinguish between constructor parameters and body while also suggesting that the optional parameters are less important than the required parameter.

I think I can live with that. I may even like it. Except…

Now that I have the parameters unrolled like that, I finally ask myself if they are needed at all. In fact, the title parameter is never used in the Editor, so I eliminate that right away. The edit_only and autoupdate parameters are not used in any of the code or tests written so far, so neither needs to be in the parameter list (though their default values still need to be set). This leaves me with:
class Editor {
  Editor(this._el, {this.enable_javascript_mode:true}) {
    this._startAce();
    this._applyStyles();
    this._edit_only = false;
    this.autoupdate = true;
  }
  // ...
}
Actually, there are better ways to set default values for instance variables than setting them in constructors. Simply declaring them with default values will work fine:
class Editor {
  bool autoupdate = true;
  bool _edit_only = false;

  Editor(this._el, {this.enable_javascript_mode:true}) {
    this._startAce();
    this._applyStyles();
  }
  // ...
}
That is a lot better. The only thing that really stand out now is the enable_javascript_mode instance variable. In addition to visually standing out, it also bothers me that the only reason this instance variable exists is to support testing (it disables a web worker, which will not work with a file:// URL like test pages). In the setup of many of my tests in ICE, I use this to disable JavaScript mode:
    test("defaults to auto-update the preview", () {
      var it = new Editor('#ice-${currentTestCase.id}', enable_javascript_mode: false);
      expect(it.autoupdate, equals(true));
      expect(it.editorReady, completes);
    });
Now that I think about it—now that re-organizing my code forced me to think about it—that does not need to be an instance variable. Instead, I can make it a static variable:
class Editor {
  bool autoupdate = true;
  bool _edit_only = false;

  static bool disableJavaScriptWorker = false;

  Editor(this._el) {
    this._startAce();
    this._applyStyles();
  }
  // ...
}
Then, I can remove all of those enable_javascript_mode constructor parameters and instead set that static variable once:
library ice_test;

main(){
  Editor.disableJavaScriptWorker = true;
  // ...
}
So in the end, I think that I have a decent format for a large number of constructor arguments. But I think that I have an even better constructor without any optional parameters at all—ironically because I worked so hard to organize the same parameters in the first place. Regardless, the code is in better, more readable, maintainable shape, which is what is really important.


Day #797

Friday, June 28, 2013

Still Can't Dynamically Create Keyboard Events in Dart (But Getting Closer)

‹prev | My Chain | next›

For all the work that I have doing recently with it, I should really write a book about Dart testing. It really is a blast and is so nice to have a solid client-side testing library that can also be easily run under continuous integration. The problem, of course, it that I know too much about it now—I would break my code for writing books and based on the last season of Dexter, breaking a code is clearly a bad thing.

Anyhow, tonight's exploration of Dart testing came from a comment from Don Olmstead on an earlier post about what a pain it is to test (or simulate) keyboard events in Dart. As an aside, if the measure of knowing a technology is understanding its weaknesses, I am certainly getting there. Don suggested that I investigate KeyName.ENTER rather than keyCode .

The KeyName values are string representations of non-string things like the Enter and Escape keys, which are really what I want to test (I used TextEvent to test “real” input). The documentation for KeyName mentions that these values are the things that would be returned from KeyEvent.getKeyboardIdentifier, but there does not seem to be a getKeyBoardIdentifier (or any variation of that name) in KeyEvent or the underlying KeyboardEvent. For now, I latch onto the only string values in KeyboardEvent, which are keyIdentifier in the constructor and the $dom_keyIdentifier getter.

So my testing helpers for hitting the Enter and Escape keys become:
hitEnter()=> type(KeyName.ENTER);
hitEscape()=> type(KeyName.ESC);

type(String key) {
  document.activeElement.dispatchEvent(
    new KeyboardEvent(
      'keyup',
      keyIdentifier: key
    )
  );
}
I now use the KeyName values for Enter and Escape, which are strings, and supply them to the keyIdentifier optional parameter in the KeyboardEvent constructor.

In my application code, based on my earlier unsuccessful attempts to legitimately simulate keyboard events in Dart, I have two helper methods that determine if key presses are Escape and Enter keys:
_isEscapeKey(e) =>
  e.keyCode == 27 || e.$dom_keyIdentifier.codeUnits.first == 27;

_isEnterKey(e) =>
  e.keyCode == 13 || e.$dom_keyIdentifier.codeUnits.first == 13;
The first part the boolean OR statements are the standard keyCode checks. The second part of the booleans were my hack for testing. My hope is that I can actually get rid of the keyCode portion of the boolean and compare the $dom_keyIdentifier with the appropriate KeyName value:
_isEscapeKey(e) =>
  e.$dom_keyIdentifier == KeyName.ESC;

_isEnterKey(e) =>
  e.$dom_keyIdentifier == KeyName.ENTER;
And that actually seems to work. With that change, all 125+ tests in the ICE Code Editor are again passing.

That is not quite the end of the story, however. This only means that I have been able to satisfactorily simulate keyboard events in my tests. What about in real life?

Unfortunately, real life betrays me. When I try this out in Dartium, the Enter key works, but the Escape key does not. Further investigation reveals that the codeUnits (the underlying bytes of the string) of the escape key event, [85, 43, 48, 48, 49, 66], do not match the KeyName code units, [69, 115, 99]. The number of bytes is not even correct—let alone the bytes matching up. Interestingly, the Enter key also has five bytes and, since the event and the KeyName seem to agree, it would seem the KeyName value for Escape is simply wrong.

So, my nice, compact _isEnterKey(e) application method becomes:
_isEscapeKey(e) {
  return e.$dom_keyIdentifier == KeyName.ESC ||
    e.$dom_keyIdentifier == new String.fromCharCodes([85, 43, 48, 48, 49, 66]);
}
With that, I have all tests passing and it works in real life. But I am still not quite done.

Since Dart lacks a keyIdentifier getter for KeyboardEvent objects, I am stuck reaching under the covers with the $dom_keyIdentifier getter. The problem is that not all browsers may support this. So I have to compile my example down into JavaScript to test in FireFox and Internet Explorer.

And, unfortunately, this fails to work in either. I get an error about trying to read get$codeunits from an undefined or null reference because the keyboard event in both FireFox and IE do not support this property. Bugger.

So, in the end, I am forced to settle for a slightly better KeyName-based implementation. Instead of mucking about with codeUnits:
_isEnterKey(e) =>
-  e.keyCode == 13 || e.$dom_keyIdentifier.codeUnits.first == 13;
I can now be explicit about the key in question:
_isEnterKey(e) =>
  e.keyCode == 13 || e.$dom_keyIdentifier == KeyName.ENTER;
As frustrating as this is, it does amount to progress. One has to assume that Dart will support keyIdentifier at some point—in either KeyboardEvent or KeyEvent, normalizing all of this stuff for developers. I do believe that I will surf through bug.dartlang.org bit tonight to see if any of this is in the works and possibly add an issue or two.


Day #796

Thursday, June 27, 2013

Manually Cleaning Up Dart Stream Subscriptions

‹prev | My Chain | next›

I had another wildly successful #pairwithme session last night with Santiago Arias. “Wildly successful” in my mind is completing a feature in one session that I had expected to require multiple #pairwithme sessions. Alas, this means that I have to queue up the next meaty project for #pairwithme, but that is a good problem to have™.

The feature was the ability to filter projects in the ICE Code Editor:



As usual, we made extensive use of the unit test libraries in Dart to drive this feature and it all came off swimmingly. Except…

We now have approximately 496 of the following exceptions being noted in the test suite:
Exception: Bad state: No elements                dart:collection/list.dart:20
Object&ListMixin.first                           dart:collection/list.dart:20
_isEscapeKey                                     package:ice_code_editor/full.dart:259
Full._attachKeyboardHandlers.<anonymous closure> package:ice_code_editor/full.dart:165
OK, “approximately” is not the right word. “Exactly” is the right word. We have 496 of those exceptions being logged. All 126 of the tests all still pass, but they now produce those errors.

Actually, it is not 126 test that produce those errors—it is only 4 of the new tests that produce the errors. I know what is causing the errors. The stacktrace makes it pretty plain that the errors are being caused by my solution to generating keyboard events in Dart. The hacky solution that I use is to check the key identifier when the keyCode property is not available:
_isEscapeKey(e) =>
  e.keyCode == 27 || e.$dom_keyIdentifier.codeUnits.first == 27;
The reason that this popped up last night was that we used a different, TextEvent-based keyup strategy for generating input. So the obvious fix is to accommodate text events in my silly hack (or to switch from text events in our new tests).

I can address that later. What concerns me now are those errors. They are the result of keyboard listeners from old instances of the ICE editor sticking around after tests. I have been cleaning up after tests by removing the DOM element and allowing garbage collection to do the rest:
    tearDown(() {
      document.query('#ice').remove();
      editor.store..clear()..freeze();
    });
Unfortunately, it seems garbage collection is not enough in the case of Dart stream subscriptions. Instead, I have squirrel away a copy of the stream subscription so that a new, custom-built remove() method can manually remove the stream subscription:
class Full {
  // ...
  void remove() {
    _keyUpSubscription.cancel();
    el.remove();
  }
  // ...
}
With that, I can remove every instance of the DOM element removal with a call to the editor's remove() method that both removes the DOM element and the stream subscription:
    tearDown(() {
      editor.remove();
      editor.store..clear()..freeze();
    });
And that seems to do the trick.

I am not thrilled to have to do this, especially since it only seems to be of use in tests. It would be nice if stream subscriptions would be removed once the objects that created them go out of scope. Then again, the obvious case of a subscription factory would be foiled by such a strategy, so I suppose I can understand why it works this way. It makes for small pain in tests, but I can live with it.


Day #795

Monday, June 24, 2013

Doing Bad Things with Web Components

‹prev | My Chain | next›

Tonight, I continue to explore web components in the web-ui packages for Dart. I was able to get a proof of concept web component up and running last night, using the ICE Code Editor Dart code that I have been so heavily involved with recently.

As web components go, it was fairly useless—there was no data binding, composition, extension. Heck, in the end, I did not even use the <template>, making my web component little more than a cheap, albeit pretty, way to instantiate a full-screen IDE-lite version of ICE. Tonight, I would like to explore supplying data to the web component constructor.

Based on what I know about web components, which admittedly is not much at this point, my sense is that what I want is not a valid web component use-case. But that never stopped me before!

(and really, abusing any kind of technology is the best way to understand it)

What I want is to supply content to be consumed, but not immediately inserted in the web page DOM. I want to supply code for the ICE Code Editor to edit, not to be displayed right away. In other words, something like the following should create an instance of the code editor with the following already loaded into the editor:
  <ice-code-editor>
    <body></body>
    <script>
      console.log("Don't want to see this on page load");
      document.addEventListener('keydown', function(e) {
        console.log(e.keyCode);
      });
    </script>
  </ice-code-editor>
This should prove a challenge because (a) depending on how the <body> tags are interpreted, problems could ensue and (b) I do not want any of that JavaScript actually executed.

So the question becomes, can I slurp that into my web component before it is interpreted by the DOM and/or executed? The answer to the first challenge is that I am not even going to get a chance—compiling my web component chokes on those extra <body> tags:
➜  public git:(web-ui) ✗ dart --package-root=packages/ packages/web_ui/dwc.dart --out web_ui/ web_ui.html
warning web_ui.html:9:5: Unexpected start tag (body).
    <body></body>
    ^^^^^^
warning web_ui.html:9:11: Unexpected end tag (ice-code-editor). Missing end tag (body).
    <body></body>
          ^^^^^^^
warning web_ui.html:10:5: Unexpected start tag token (script) in the after body phase.
    <script>
    ^^^^^^^^
I may still have options there, but I want to focus on answering the second challenge first. Can I prevent the JavaScript from being executed? To find out, I temporarily remove the <body> tags from the <ice-code-editor> tag, leaving just the JavaScript that I want to consume, but not evaluate:
  <ice-code-editor>
    <script>
      console.log("Don't want to see this on page load");
      document.addEventListener('keydown', function(e) {
        console.log(e.keyCode);
      });
    </script>
  </ice-code-editor>
Now, in the web component class, I print the contents of the element as soon as possible. In the case of Dart's WebComponent, that seems to be the create() callback method:
  <element name="ice-code-editor" extends="div">
    <template>
      <!-- Placeholder for template. Live elements added to BODY. -->
    </template>
    <script type="application/dart">
      import 'package:ice_code_editor/ice.dart' as ICE;
      import 'package:web_ui/web_ui.dart';

      class IceCodeEditor extends WebComponent {
        Full ide_lite;
        IceCodeEditor() {
          ide_lite = new ICE.Full();
        }
        created() {
          print(innerHtml);
        }
      }
    </script>
  </element>
If I have any hope of removing the <script> tags before they are evaluated the web component will have to print before the <script> code does. Unfortunately, the <script> tag code is evaluated before the web component code. When I recompile the web component and reload, I see the following output in the JavaScript console:
Don't want to see this on page load web_ui.html:10

    <script>
      console.log("Don't want to see this on page load");
      document.addEventListener('keydown', function(e) {
        console.log(e.keyCode);
      });
    </script>
Ah well, that is not too surprising. It would have been nice to be able to insert raw HTML (including <body> and <script> tags) inside my web component element, but there are other approaches. If there is a silver lining to this experiment, I have a way to read that content with the innerHtml property of WebComponent, which works as early as the create() callback (it does not work in the constructor).

Armed with that bit of knowledge, I believe that including the content in an HTML comment might work:
  <ice-code-editor>
<!--
<body></body>
<script>
  console.log("Don't want to see this on page load");
  document.addEventListener('keydown', function(e) {
    console.log(e.keyCode);
  });
</script>
-->
  </ice-code-editor>
To see this in action, I switch from the full-screen version of ICE to just the core ICE (the editor + preview). I do not need the constructor anymore—all of the action takes place in the created() and inserted() callbacks. Once the web component is created, I set the ID and some styles and grab the content of <ice-code-editor>. Then, when the web component is inserted into the DOM, I create an instance of the ICE editor:
<element name="ice-code-editor" extends="div">
    <template>
      <!-- Placeholder for template. Live elements added to BODY. -->
    </template>
    <script type="application/dart">
      import 'package:ice_code_editor/ice.dart' as ICE;
      import 'package:web_ui/web_ui.dart';

      class IceCodeEditor extends WebComponent {
        ICE.Editor ice;
        String content;

        created() {
          id = 'ice';
          style
           ..width = '600px'
           ..height = '400px';

          content = innerHtml.
            replaceFirst(new RegExp(r'^\s*<!--\s*', multiLine: true), '').
            replaceFirst(new RegExp(r'\s*-->\s*$', multiLine: true), '');
        }

        inserted() {
          ice = new ICE.Editor('#ice');
          ice.content= content;
        }
      }
    </script>
  </element>
And that actually seems to do the trick. When I first load up the page, the code from the comment is in the editor:



And I can edit the code and see the preview change:



So it all seems to works. For good measure, I even try loading a semi-sophisticated Three.js code example and that too works:



To be clear, I still believe that I am heartily abusing web components here. I am making no use whatsoever of data binding or real templates. Even so, this is pretty cool. I still might prefer to be able to get this working without the HTML comments, but even with them, this seems a fairly promising approach.


Day #792