Jun 29

Having fun with Canvas, but the aim is to have to use it less and less; Performance wars move from raw JS to DOM

JavaScript, Tech with tags: , 2 Comments »

canvasbg

We are having a great time using Canvas for Bespin and a few other projects. Having text, images, and boxes as the primitives on the Web just isn’t good enough, so leap frogging to HTML5-land where we have the ability to arbitrarily paint pixels is fantastic. Mix this with the ability to directly manipulate video, and you have new opportunities.

However, Canvas also has obvious issues. How do you make it accessible? Or searchable? We have some ideas there, but they are a long way off. The goal has never been to use Canvas as the shiny toy. With Bespin, we actually tried to do it with DOM, and it wasn’t so much chutzpah as “can’t get it to perform”-pah that lead us down the path of Canvas. The usual suspects in the stack weren’t working for us, whereas others were blazing (e.g. JavaScript performance has blown us away, as has Canvas itself).

With major browsers like Firefox 3.5 (Safari 4, Chrome 2, etc) I am very much excited to work with browsers (say, the great Firefox team :) to kick into gear on the next level of improvements. The current batch have been competing on the performance of JavaScript. The new engines are fantastic, and really change the game on what can be done. Add in Web Workers to the magnitude speed bump of JS and Web devs can truly build responsive low-latency applications. We are now seeing improvements to the DOM, the next frontier. It is all well and good to have your JS run nice and speedy, but if the DOM can’t keep up then we are still in trouble. This is why we had to go to Canvas for Bespin in the first place! I am hoping that we will be able to push on DOM and other APIs to get to a point where our DOM based Bespin can come back to town.

There is a time and a place for Canvas though. Rather than running the show, I much prefer the unobtrusive extensions that you can provide. I am also looking forward to seeing more tools that use a server side component to do some image manipulation… now work on the client through Canvas and ImageData. Vlad pondered why CSS spriting tools are all server-side for example.

Christian Effenberger has been doing this kind of work for a long time, and there is room for a lot more. I really like having Canvas available in more places, such as anywhere an image can be used (e.g. WebKit CSS extensions where you can use a Canvas as a background-image). That gives you full control to style something in zany ways, while still staying in DOM land. It also means that things can play together really nice. We continue to push more into CSS (transitions, gradients, etc.) and animation libraries (Scripty2 looks nice!).

There is still much work to be done on putting the pieces together. I don’t know about you, but doing some common things with layout and UI still drive me nuts. Having the low level new tools like border-image are cool, but I really long for a tool that graphically lets me take a mock, cut it up, and build it out as a generalized component (stretches in the right place etc). The tool could then spit out more than just a border-image version, but old style divs + CSS to make it work everywhere. One tool, run output anywhere.

csstools

So, time to take a breath, take a look at what bleeding edge folk are doing to get rich experiences, and push it into the core platform itself. This will mean less Canvas, but used in the right places, and we will move down the stack again. If we don’t push use cases down into the core, then we are doomed to stagnate or fork the Web.

May 26

Icky? Using strings to add legacy features in languages

JavaScript, Tech 6 Comments »

strings

A contingent in the JavaScript community is pretty much solely focused on securing the language. Security is always important, but even more-so when you are dealing with a language that runs in a user agent to run the Web.

Whenever you try to add a feature to a language you are instantly dealing with legacy and backwards compatibility.

Perl has a strict mode that is very popular in the community. I remember projects where if I checked in a module without use strict; and -w I would get beaten up.

Back to JavaScript, how can we apply stricter rules on what we do in the JavaScript runtime after the face? One solution that the ECMAScript Edition 5 folks came up with is borrowing use strict but since they couldn’t add it to the language itself, they have you put it in a string "use strict";. You can place it at the top of the file, or even as the first statement in a function.

I find it incredibly ugly, yet pragmatic. It works.

However, then I saw some new items:

"use strict,cajita";

And currently you can’t switch the order around? It looks for absolute keys? That seems a little crazy. Surely all of these should be possible:

"use cajita,strict";
"use strict,cajita";
"use strict";
"use cajita";

Then this little pragmatic hack starts to get real messy. I start to joking imagine a ludicrous world like this:

(function() {
  "use strict";
  "use let"; // let's get let in there!
  "use cramda"; // I love Alex's cramda, let me use it!
  "use e4x"; // XML inline. Screw templates
 
  // If I see a var with the same name, REALLY use let instead
  "let x;"
  var x;
 
  // Now I can use the cramda
  "x = #(a, b) { "\
  " ... logic here ... "\
  "};"
 
  // And the let... ironic that it is in a string now
  "let y = <xml></xml>";
 
  // Annotations come to JavaScript!
  "@Serializable"
  function someThing() {}
})();

I like to think of myself as pragmatic, but why do I feel so cranky about "use strict";? :)

May 20

Write Once, Pwn Everywhere…. oh and Jetpacking around

Java, JavaScript, Tech with tags: 3 Comments »

By now you have probably read about the critical Java vulnerability and how easy it is to take over a machine from a web page via a Java applet.

Apparently, Sun fixed it fairly quickly, but even then some people say their fix was too specific and thus there are still problems. Apple on the other hand, were not diligent and are still yet to provide a fix. Ouch.

Painful news as JavaOne approaches and Sun tries to push JavaFX. I was trying to think of a Java applet that I have used (knowingly) in the recent past, and I think the only candidate is the Facebook photo uploader.

I have been watching some research for a talk on JavaFX and I am really torn. In theory, the Java platform is phenomenal and should be a great choice for doing this kind of development. The scene graph work in JavaFX is very nicely done, but the implementation seems to be a touch off in much of what I have seen. Scrolling causing the applet to go blank? Browser crashes? Ouch. But, JavaFX is new, and has a chance to get better. Their problem is that they are squeezed from both sides. The browser platform itself is accelerating quickly, and it has the advantage of being native. Once you go to plugin land you are competing with Flash with its large share and proven ability.

Getting webby

I find myself wanting to get more and more webby. This is why I was excited to work with the Jetpack project that we just launched today at Mozilla Labs. Being able to extend the browser using Web technology itself is going to open the door for more playing. People have created 7000 addons for Firefox alone, but as someone who has done a touch of XUL, I am happy to stay in my familiar territory of HTML, CSS, JS. Jetpack has just been born, and is incredibly early stage, but I can’t wait to see it grow and get the APIs that people want in a secure extensible model.

You will see a lot of Bespin in there too. Below is a screencast where I create a Jetpack feature on the fly (no reloads!) using Bespin, and once you install Jetpack it embeds the puppy into the tutorial and the developer area too. Much more than can be done though!

Apr 10

Browser storage: Do we need SQL? Or would a JSON approach be better?

Ajax, JavaScript, Tech with tags: , 16 Comments »

jsondata

Ian Hickson: “I expect I’ll be reverse-engineering SQLite and speccing that, if nothing better is picked first. As it is, people are starting to use the database feature in actual Web apps (e.g. mobile GMail, iirc).”

When I read that comment to Vlad’s post on HTML 5 Web Storage I gulped. This would basically make SQLite the HTML 5 for storage in the browser. You would have to be a little crazy to re-write the exact semantics (including bugs) of SQLite and its dialect. What if you couldn’t use the public domain code?

Gears lead out strong with making a relational database part of the toolbox for developers. It embedded its own SQLite, in fact one that was customized to have the very cool full text search ability. However, this brings up the point of “which SQLite do you standardize on?”

The beauty of using SQL and SQLite is that many developers already know it. RDBMS has been mainstream for donkey’s years; we have tools to manage SQL, to view the model, and to tweak for performance. It has gone through the test of time.

However, SQL has always been at odds with many developers. Ted Neward brought up ORM as the vietnam of computer science (which is going a touch far ;). I was just lamenting with a friend at Microsoft on how developers spend 90% of their time munging data. Our life is one of transformations, and that is why I am interested in a world of JavaScript on client and server AND database. We aren’t there yet, but hopefully we can make progress.

One of Vlad’s main questions is “Is SQL the right API for Web developers?” and it is a valid one. I quickly found that for most of my tasks with the DB I just wanted to deal with JSON and hence created a wrapper GearsDB to let me insert/update/select/delete the database with a JSON view of the world. You probably wouldn’t want to do this on large production applications for performance reasons, but it works well for me.

Now a days, we have interesting APIs such as JSONQuery which Persevere (and other databases) use. I would love to see Firefox and other browsers support something like this and let us live in JSON throughout the stack. It feels so much more Webby, and also, some of the reasons that made us stay with SQL don’t matter as much in the client side world. For example, when OODBMS took off in some Enterprises, I remember having all of these Versant to Oracle exports just so people could report on the darn data. On the client the database is used for a very different reason (local storage) so lets use JSON!

That being said, at this point there are applications such as Gmail, MySpace search, Zoho, and many iPhone Web applications that use the SQL storage in browsers. In fact, if we had the API in Firefox I would have Bespin using it right now! We had a version of this that abstracted on top of stores, but it was a pain. I would love to just use HTML 5 storage and be done.

So, I think that Firefox should actually support this for practical reasons (and we have SQLite right there!) but should push JSON APIs and let developers decide. I hope that JSON wins, you? I also hope that Hixie doesn’t have to spec SQLite :/

Related
It was also interesting to just read this post Abusing Web Storage via Sam Ruby:

Alberto Trivero: The aim of this white paper is to analyze security implications of the new HTML 5 client-side storage technology, showing how different attacks can be conduct in order to steal storage data in the client’s machine.

Apr 08

Google App Engine and The Java Web; The Wrong Java?

Ajax, Google, HTML, JavaScript 6 Comments »

I had the pleasure of being at the Google Campfire event that launched the worst kept secret, App Engine supports Java and Google has a preview for you to check out if you signup in time.

Java is a huge ecosystem, which is a big win, but what interested me was the nuance. The Secure Data Connector feature that gives us a glimpse of “on premise” type functionality (that Microsoft is touting with Azure) is a big one, and something that enterprises need.

The GWT pitch and the Google plugin for Eclipse is another interesting one. I am always so incredibly torn here. GWT is fantastic technology. Because of the way it works, it gets to do things that pure JavaScript libraries would love to be able to do but can’t. The team is great, and the hard core tech is incredibly impressive. I understand why people use it.

My personal issue is that it feels so funny to see the two messages from Google.

Now, these aren’t mutually exclusive of course. GWT can wrap all of the HTML 5 stuff and both can be happy. But it just feels weird to me. The idea that JavaScript is the assembler of the Web, when it is such a high level language is hard to wrap my mind around. It can be moulded to do so much more than Java can with its static nature (which has downsides too of course!)

Another thing. Writing your applications using Java in this world is about the source code and the language but not about the VM. For me this is hard to wrap my head around too. I get to use a language I *personally* don’t like as much (Java the language) and have it run on a runtime that isn’t as good as the Java VM. Hmm. And, since there isn’t the VM there (on the client, there is with App Engine!), I don’t get the pleasure of writing in any of the very interesting languages available on the JVM (Scala, Clojure, JRuby, Groovy, etc). They have picked the wrong Java for my taste!

Now, Paul Hammant has a very detailed post about building a rich Ruby application on top of AppEngine4J. He flips from a jQuery view to a Ruby client using Swiby to a Ruby Shoes app and beyond. Then, at the end, he says something very interesting:

If Google made changes to GWT to make it a viable thick/desktop/offline technology then AppEngine might shift up a gear with online/offline apps.

Since you are writing Java code, why not ship down a jar file for browsers that support Java (still a fair few) and run the application natively within the browser? Kinda bizarre, but imagine if Gears had been done in Java, and people could add functionality easily that way (this is where Yahoo! BrowserPlus is interesting… how you can write services in Ruby and the like). And now you are sending down a jar, you could write the applications using any JVM language you want. Huh. That would be an interesting direction.

Who knows where this ends. When you get practical though, Google have delivered a nice experience for people that like Java, and that is a large group still.

I am still in the camp of DSLs and lightweight and all that jazz, and agree that one great thing about the Web is that some people can come in and make a change here and there at a very high level and make something their own.

Fun times!

Apr 06

Creating custom scrollbars with CSS; How CSS isn’t great for every task

Ajax, Bespin, JavaScript, Web Browsing with tags: , , 6 Comments »

Have you tried to create a nice rich experience and then been fighting the “defaults” to go the extra mile? This reared its head with me recently with Bespin. There are certain commands that pull up divs of content and we need to scroll through it. The problem is that the native scroll bar looks so out of place:

uglyscrollbar

WebKit recently released the ability to style scrollbars in HTML elements (but not the main window, which you have been able to do in IE for donkeys years much to many peoples chagrin).

I decided to take it for a spin and loaded up the examples that show you being able to do every type of scrollbar that you can imagine:

manyscrollbars

So, it shouldn’t be so hard should it. From the blog post I see a few magically ::-webkit-scrollbar CSS properties that I can plugin and be on my way. But looking at the example view source you see many pieces like this:

:not(.none):not(.double-start)::-webkit-scrollbar-track-piece:vertical:end:single-button,
:not(.none):not(.double-start)::-webkit-scrollbar-track-piece:vertical:end:double-button,
.single::-webkit-scrollbar-track-piece:vertical:end,
.double-end::-webkit-scrollbar-track-piece:vertical:end,
.double-both::-webkit-scrollbar-track-piece:vertical:end {
    margin-bottom: -6px;
}

Holy pseudo classes batman! To be fair, this is partly due to the example page having many types of scrollbars in one (hence the not this and not that but the other) but there are still nested classes that you need to grok to get this going.

I quickly built a debug scrollbar where I styled the various pieces with simple colors and borders so I can see which was which. I also went about making the scrollbar have one up arrow on top, and one down arrow on the bottom.

debugscrollbar

The parts and pieces of a scrollbar are quite simple:

  • Thumb: This is the piece that shows you where you are in the scrollbar. This is the chap that you can move around
  • Track: This is the area of the scrollbar that you can move the thumb up and down, or along (depending on the orientation). There is both the area between the top and the thumb, and between the bottom of the thumb and the bottom of the scrollbar
  • Buttons: There may be buttons that you can click to increment or decrement the selection (which moves the thumb). There are various styles (single button, double button, etc)
  • Resizer: This can change the are of the element (e.g. enlarge of shrink)
  • Corner: This area may show up with both horizontal and vertical scrollbars open

The debug scrollbar kinda shows these areas off in a simple visual way. Note how using display: block|none enabled me to setup the single button on top and bottom functionality:

/* Turn on a 13x13 scrollbar */
::-webkit-scrollbar {
    width: 13px;
    height: 13px;
}
 
::-webkit-scrollbar-button:vertical {
    background-color: red;
    border: 1px dashed blue;
}
 
/* Turn on single button up on top, and down on bottom */
::-webkit-scrollbar-button:start:decrement,
::-webkit-scrollbar-button:end:increment {
    display: block;
}
 
/* Turn off the down area up on top, and up area on bottom */
::-webkit-scrollbar-button:vertical:start:increment,
::-webkit-scrollbar-button:vertical:end:decrement {
    display: none;
}
 
/* Place The scroll down button at the bottom */
::-webkit-scrollbar-button:vertical:increment {
    background-color: black;
    border: 1px dashed blue;
}
 
/* Place The scroll up button at the up */
::-webkit-scrollbar-button:vertical:decrement {
    background-color: purple;
    border: 1px dashed blue;
}
 
::-webkit-scrollbar-track:vertical {
    background-color: blue;
    border: 1px dashed pink;
}
 
/* Top area above thumb and below up button */
::-webkit-scrollbar-track-piece:vertical:start {
    border: 1px solid #000;
}
 
/* Bottom area below thumb and down button */
::-webkit-scrollbar-track-piece:vertical:end {
    border: 1px dashed pink;
}
 
/* Track below and above */
::-webkit-scrollbar-track-piece {
    background-color: green;
}
 
/* The thumb itself */
::-webkit-scrollbar-thumb:vertical {
    height: 50px;
    background-color: yellow;
}
 
/* Corner */
::-webkit-scrollbar-corner:vertical {
    background-color: black;
}
 
/* Resizer */
::-webkit-scrollbar-resizer:vertical {
    background-color: gray;
}

By moving the scrollbar around I could quickly see how this all worked, and it got me to this point which enabled me to plugin the images to make this puppy work for Bespin:

bespinscrollbar

There were a couple of key tweaks needed to make this work:

Getting the buttons working

I used the same trick used in the debug example to turn on the up area above, and the down area below, and then it was just a matter of targeting the correct area for the arrow images:

/* Turn on single button up on top, and down on bottom */
::-webkit-scrollbar-button:start:decrement,
::-webkit-scrollbar-button:end:increment {
    display: block;
}
 
/* Turn off the down area up on top, and up area on bottom */
::-webkit-scrollbar-button:start:increment,
::-webkit-scrollbar-button:end:decrement {
    display: none;
}
 
/* Place The scroll down button at the bottom */
::-webkit-scrollbar-button:end:increment {
    background-image: url(images/scroll_cntrl_dwn.png);
}
 
/* Place The scroll up button at the up */
::-webkit-scrollbar-button:start:decrement {
    background-image: url(images/scroll_cntrl_up.png);
}

Get the track pieces to show

Next up was getting the gutter to show up. As mentioned early on, there is one track, but two areas that can show…. before the thumb and after. You can target these areas via -webkit-scrollbar-track-piece:start || :end and then it is a matter of using the multiple background ability available in new browsers. First we have the top of the gutter, and then a recurring background (and the same for the bottom). This way it just grows with the area that it gets:

/* Top area above thumb and below up button */
::-webkit-scrollbar-track-piece:vertical:start {
    background-image: url(images/scroll_gutter_top.png), url(images/scroll_gutter_mid.png);
    background-repeat: no-repeat, repeat-y;
}
 
/* Bottom area below thumb and down button */
::-webkit-scrollbar-track-piece:vertical:end {
    background-image: url(images/scroll_gutter_btm.png), url(images/scroll_gutter_mid.png);
    background-repeat: no-repeat, repeat-y;
    background-position: bottom left, 0 0;
}

The Thumb

To get the thumb working, I thought I would do the same background image trick with three images (top of thumb, bottom of thumb, and background for the middle). Unfortunately this didn’t seem to work for me as I couldn’t get the middle to not go through the top and bottom. So, instead, I went with another new CSS trick: border-image. Here I splice the top and bottom of a thumb (the top and bottom 8 pixels) and stretch the rest:

/* The thumb itself */
::-webkit-scrollbar-thumb:vertical {
    height: 56px;
    -webkit-border-image: url(images/scroll_thumb.png) 8 0 8 0 stretch stretch;
    border-width: 8 0 8 0;
}

John Resig has a nice readable post on border-image.

And, there you have it. Now we can have nice Bespin-y scrollbars throughout Bespin. This may not be complete though, as we have the ability to also tie in :active and :hover work if we wish (change the color when selecting etc).

Of course, many people had “custom scrollbars”. There are plenty of comments on the original Surfin’ Safari post, and various rants about Flash versions. I agree that we have all seen bizarre Flash versions of scrollbars that don’t look like them at all, and where the designer didn’t bother to put in support for the mousescroll ability etc, but this is a bit different. It let’s you merge in your look and feel, yet with native scrollbar functionality.

And, with Google recreating the button maybe we can feel a little bit better about tweaking the look of common UI elements as long as they are familiar enough to users to still make natural sense.

Now, the CSS declarative way to do scrollbars seems to get pretty ugly to me with all of he pseudo classes and various magic to get the functionality that you would like. I have to admit to liking Kevin’s demo of Flash Catalyst at Web 2.0 Expo and how it lets designers build out a scrollbar. We should be inspired to do tools like this. What if we had an API that wasn’t CSS, but let us say: “I want a Mac style double on the bottom button scrollbar. And, here is a thumb, here is a track, go for it”.

That being said, at least we do have the ability to do this kind of thing now. I hope that other browsers follow WebKit in this instance.

Mar 30

Dealing with JavaScript scope issues; The tale of Alex kindly indulging me

Ajax, JavaScript, Tech with tags: 7 Comments »

Dealing with JavaScript scope issues; The tale of Alex kindly indulging me

JavaScript is about run-time. Run-time is great and all, but especially when dealing with the browser, and how your Web page has to bootstrap the entire world on every load, Ajax developers have to think about issues that other people don’t. Problems that others can compile away, or know that “that happens once when I start up the puppy on the server” are here for us to stay.

This often seems to mean that we have to deal with writing our applications in ways that aren’t as clean as we may like. We run across problems where for the Nth time someone was bitten as somewhere code did a “for in” that wasn’t guarded with hasOwnProperty and then someone throws up there arms. Never Again. Dojo does a lot of things out of this experience. It is out of real-world pain that choices were made in the toolkit. One of these is how they are very careful not to pollute the global namespace. This is great in that you don’t run into collisions, especially in a world where code is being sucked in from who knows where (e.g. some Ad code is sucking in things). As the author of some JavaScript code, you don’t actually know what else may get into your global area when running, so you need to guard against it.

The problem is that this means that you can lose out. Prototype feels so right to me in many ways as it is less of a “JavaScript library” than a “way in which JavaScript should have evolved”. We have seen some of its goodness get into ES 3.1 (e.g. bind()) but at that rate of progress we will get four more methods in 20 years ;)

"some content   ".trim(); // feels right
dojo.trim("some content   "); // doesn't feel right

I have to take a second to tease here. Did you notice that there are two trim methods in Dojo? dojo.trim and dojo.string.trim. This is a good example of the crazy things that we have to think about. It appears that dojo.trim is lean code, so it gets into base, but dojo.string.trim is more code, but it runs faster. Wow :)

Once you get a lot of code going, you suddenly realise that the word “dojo” appears 50 times per screen of code. It makes me want to create a Bespin plugin that change the shade of that one word. It feels like Java. Unlike Java, you can’t import away some of the pain. You can try to var foo = some.really.big.package; but that gets annoying quickly.

So, to the point of the blog post. When I saw Alex Russell at a nice wine bar in San Francisco last week, I told him how I would die for the ability to have the best of both worlds of Dojo and Prototype:

I want to be able to write code the way that feels right, without the verboseness, but ALSO not run into the scoping issues. I would even take a performance hit for this. What if I could have:

runSomeCodeWithMagic(function() {
    // in here I am in the lovely land where "some content   ".trim() works
    // and I can just forEach instead of dojo.forEach
    // but the outside world isn't affected
});

Well, Alex listened to me blather on, probably thinking I was a total idiot, and then went on to quickly indulge me by giving me a little of my wish by giving me dojo.runWith:

dojo._runWithObjs = [];
dojo.runWith = function(objs, func){
	if(!dojo.isFunction(func)){
		console.error("runWith must be passed a function to invoke!");
		return;
	}
	var rwo = dojo._runWithObjs;
	var iLength = rwo.length;
	// console.debug(func.toString());
	if(!dojo.isArray(objs)){
		objs = [ objs ];
	}
	var catchall = dojo.delegate(dojo.global);
	var fstr = [ "(", func.toString(), ")()" ];
	objs.unshift(catchall);
	var locals = {};
	objs.push(locals);
	objs = objs.reverse();
	dojo.forEach(objs, function(i){
		var idx = rwo.length;
		rwo.push(i);
		fstr.unshift("with(dojo._runWithObjs["+idx+"]){");
		fstr.push("}");
	});
	(new Function(fstr.join("")))();
	// allow us to GC objs passed as contexts, but don't rewind
	// further than we started (allowing nested calls)
	rwo.length = iLength;
	// TODO:
	//		iterate on locals and look for new properties that
	//		might have been assigned. Maybe give the with-caller a
	//		way to handle them or specify a policy like "make
	//		global"?
};

To use it I can do something like this:

<html>
    <head>
        <script src="http://o.aolcdn.com/dojo/1.3.0/dojo/dojo.xd.js"></script>
        <script src="runwith.js"></script>
        <script>
        dojo.addOnLoad(function() {
            dojo.runWith([ dojo ], function() {
                var sum = 0;
                forEach([1, 2, 3, 4], function(i) {
                    sum += i;
                });
                byId("result").value = "The sum is: " + sum;
            });
        });
        </script>
    </head>
    <body>
        <h1>Run with Wolves</h1>
 
        <input type="text" id="result">
    </body>
</html>

Very nice! Only a couple of dojo’s in sight!

Here are some of the thoughts from Alex himself:

Note/warning about the runtime cost: If your browser parses things fully in it’s JS engine up front, this function may hurt. A lot. It de-compiles a function using the toString() method, meaning that it does an uneval + eval + string concat + with() call. Each of these operations alone might be painful in a slow engine. Together they could be fatal. On the other hand, if you’re using these functions in, e.g., Chrome/V8, this could turn out to be relatively cheap, particularly as this is run-once kinda thing. The runtime cost involves namespace misses on locals, and that can be significant. I dunno. You’ll have to test to find out.

Note that you won’t easily be able to define globals from here by dropping a “var”. This might be a feature or a bug, depending on how you think about it.

Anyway, hope it’s useful. I’d imagine that you’d structure your files like this:

// something.js
dojo.provide("thinger.something");
dojo.require("thinger.blah");
 
dojo.runWith([ dojo, thinger ], function(){
       ...
});

What about getting the magic on the core objects? Again, only within the magically land of that scope do we want String to have the trim method…. and code outside of it shouldn’t see it. Can we swap onto the objects and their prototypes? Alex has some thoughts here too:

I think I can proxy intrinsics at some additional cost. I’d like to make it a protocol, though, so that you might be able to have a list or function that handles your extensions. E.g.:

var contextObj = {
    ":intrinsics": {
        "String": { ... },
        "Number": { ... },
            // ...
    }
};
 
dojo.runWith([ contextObj, ... ], ... );

This would give us a way to un-install them later, but I don’t have a solution for aync code as we do with with(){ … } which actually binds definitions at declaration time.

I might try to proxy intrinsic prototypes somehow, but I need to spend more time thinking about how to get that to work well. I’d like these things not to place big constraints on how you think about or use this system.

Wicked. This also ties into Pete Higgins and some of the very interesting work he is doing in similar but different veins with his dojotype and plugd which munge Dojo into interesting forms.

Since Dojo has pretty much everything that any other library has, you can start thinking about how you can bend it to look and feel like others, take on their APIs when it makes sense, and bend it to your whim.

With research like Alex’s we could see an interesting view when you can create worlds which don’t affect each other, let you have a view that makes sense for your code, but doesn’t affect others.

Even if you poo-poo some of it for the performance aspects, this is why it is incredibly exciting to see the latest JavaScript Vm work. With these guys running, they can optimize a lot of this a way, and things that used to be bottlenecks in the code will cease to be.

Thanks to Alex and Pete for indulging me, and taking the time to listen and produce really interesting solutions!

Updated: Using the Dojo Loader

James Burke has a very cool follow up on how to give a solution to this kind of problem using the Dojo Loader itself:

Setup your locals

dojo.provide("coolio.locals");
 
dojo.setLocalVars("coolio", {
 trim: "dojo.hitch(dojo, 'trim')",
 $: "dojo.hitch(dojo, 'query')",
 id: "dojo.hitch(dojo, 'byId')"
});

Now setup your actions that will use the locals:

dojo.provide("coolio.actions");
 
coolio.actions = {
 init: function(){
  $("#trimButton").onclick(coolio.actions, function(evt){
   id("trimOutput").value = trim(id("trimOutput").value);
  });
 }
}

Finally, use HTML to auto load:

<script type="text/javascript" src="dojo/dojo.js" djConfig="require: ['coolio.locals']"><script>
Mar 24

Event Driven Architecture in JavaScript is fun; Bespin Extensibility

Ajax, Bespin, JavaScript, Tech No Comments »

In former times (I love how Germans say that) I spent time working on event driven systems and busses. Those unfortunate enough to work with Enterprise JavaBeans were happy when Message Driven beans were announced as they could tell the pointy hair chaps that they were indeed doing EJB, and would continue working in their MOM architecture.

Now I fast forward to my days with JavaScript, and I remember getting excited to see the common JavaScript libraries support custom events. I now had a very nice way to work with my library to use event driven architecture on the client side, which is actually quite natural to do too. We see this pattern in desktop APIs such as Cocoa, and it helps enforce the practice of responsive applications for end users.

I may have taken this notion to the extreme a little in Bespin.

We have a general event system to put general work and you will also find that most of the components of Bespin also have their own events.js. A component will often load up the events by doing something like this:

// from within the editor itself, pass into the event system so the events are in scope
new bespin.editor.Events(this);

The event class will take in that component, put it in scope, and then an event can just use it. Note the use of editor here:

dojo.declare("bespin.editor.Events", null, {
    constructor: function(editor) {
        bespin.subscribe("editor:openfile:opensuccess", function(event) {
            editor.model.insertDocument(event.file.content);
            editor.cursorManager.moveCursor({ row: 0, col: 0 });
        });
    }
 
    // ... all of the events
});

As new events come into play for the editor, this is where they will naturally be placed.

There have been some really nice fall outs of this approach. It has been really nice to have the notion of “this just happened, if anyone is interested, here is some info.” There is no need to find an object and call a method on it…. the event bus just takes care of it all for you.

There has been a nice side effect in the case of sharing commands across different parts of the application. Take the dashboard vs. the editor itself. Both have a command called newfile that looks a bit like this:

bespin.cmd.commands.add({
    name: 'newfile',
    takes: ['filename', 'project'],
    preview: 'create a new buffer for file',
    completeText: 'optionally, name the new filename first, and then the name of the project second',
    withKey: "CTRL SHIFT N",
    execute: function(self, args) {
        if (args.filename) {
            args.newfilename = args.filename;
            delete args.filename;
        }
        bespin.publish("editor:newfile", args || {});
    }
});

The core piece is that the command basically just sends an event of type editor:newfile. On the other side of the coin, who is listening to this event? Well, in the case of the dashboard, it changes the URL to the editor itself, but if you are already in the editor itself, you don’t need to do that, and can just clear the editor buffer and file state.

Having commands at this high level means that they are easy to share.

We do need to do some more thinking about when it makes sense to promote something to be a full fledged event. In general I like the idea that people can write plugins and extension code that only requires them to grok some events and they are in and out in a jiffy.

However, some team members have brought me down to Earth and I realize that if we go too far here we will be reinventing method dispatch itself, and in a way that is only asynchronous :)

We don’t want to go that far. The no-brainer use cases are for typical call backs such as “a file has opened, care?” Something that an event asking for something to be done (e.g. newfile above) is a more subtle item and shouldn’t be over used.

Another side effect from using this model is that I remember exactly how much I like named parameters, which is why you will see the pattern is publish(eventName, argumentsHash). Dojo allows you to pass in multiple arguments, and in fact makes it harder to only send in one object as you have to dojo.publish(eventName, [ one ]). The [ ... ] looked ugly, so we wrapped the mechanism as bespin.publish(...). We also did this because we wanted to be a layer above the implementation. The Prototype version used Element.observe() and Element.bind() and we had to change all of that work in the port. Hopefully we won’t have to do this if a major change happens in the future.

Fun times! I will also write-up the effects of this, and how extensibility kicks in with Bespin on commands, your configuration, and plugins.

Mar 04

Supporting the system clipboard in your Web Applications: Part Two

Bespin, JavaScript, Tech with tags: 16 Comments »

paste
Courtesy SierraBlair

I had a rather long post on the pain of dealing with the system clipboard in Web applications now that Flash went and fixed some security hole :/

The solution in place at that time worked well in Safari, with the on[cut|copy|paste] and unfortunately not great with Firefox due to one crucial big of data being omitted.

Then Tom Robinson and a couple of others made the great point that I could get ALMOST everything I wanted with just the hidden textaraea trick. Instead of tying the trick to the on[cut|copy|paste] events, I can just manually grab the Cmd/Ctrl-C X V commands. The only downside to this is that if the user goes to the Edit menu and chooses something, it won’t work. Annoying, but that’s the world of the hacky Web sometimes.

I added in this new tactic, and copy and paste works OK for Firefox in the latest version of Bespin in code (not deployed to bespin.mozilla.com at the time of this writing):

dojo.declare("bespin.util.clipboard.HiddenWorld", null, {
    install: function() {
        // * Configure the hidden copynpaster element
        var copynpaster = dojo.create("textarea", {
            tabIndex: '-1',
            autocomplete: 'off',
            id: 'copynpaster',
            style: "position: absolute; z-index: -400; top: -100px; left: -100px; width: 0; height: 0; border: none;"
        }, dojo.body());
 
        var grabAndGo = function(text) {
            copynpaster.value = text;
            focusSelectAndGo();
        };
 
        var focusSelectAndGo = function() {
            copynpaster.focus();
            copynpaster.select();
            setTimeout(function() {
                dojo.byId('canvas').focus();
            }, 0);
        };
 
        this.keyDown = dojo.connect(document, "keydown", function(e) {
            if ((bespin.util.isMac() && e.metaKey) || e.ctrlKey) {
                // Copy
                if (e.keyCode == 67 /*c*/) {
                    // place the selection into the textarea
                    var selectionText = _editor.getSelectionAsText();
 
                    if (selectionText && selectionText != '') {
                        grabAndGo(selectionText);
                    }
 
                // Cut
                } else if (e.keyCode == 88 /*x*/) {
                    // place the selection into the textarea
                    var selectionObject = _editor.getSelection();
 
                    if (selectionObject) {
                        var selectionText = _editor.model.getChunk(selectionObject);
 
                        if (selectionText && selectionText != '') {
                            grabAndGo(selectionText);
                            _editor.ui.actions.deleteSelection(selectionObject);
                        }
                    }
 
                // Paste
                } else if (e.keyCode == 86 /*v*/) {
                    focusSelectAndGo();
 
                    setTimeout(function() { // wait just a TOUCH to make sure that it is selected
                        var args = bespin.editor.utils.buildArgs();    
                        args.chunk = copynpaster.value;
                        if (args.chunk) _editor.ui.actions.insertChunk(args);
                    }, 1);
                }
            }
        });
    },
 
    uninstall: function() {
        dojo.disconnect(this.keyDown);
    }
});

Because of the issues, I took out the UI buttons for cut/copy/paste, and am in fact wondering if the editor needs that row at all. I wonder if we can consolidate the header to one line, giving us more vertical space. A code editor for developers is not like Google Docs for average Joe users, so having the visual cues probably doesn’t matter in the same way for items like copy.

There are a few subtle annoyances such as running an action like killLine (Ctrl-K) which cuts the selection but has to do so in a non-work with the clipboard way.

End result: getting there, but still need to work on making this generally viable for any application on the Open Web Platform. What do you think?

UPDATE: Used the copynpaster variable throughout, and added a setTimeout around the paste operation as I found some people needed to hit the paste key twice as the focus()/select() was taking a little too long.

Jan 07

TokenObject: A strange little piece of code that creates objects for me

JavaScript 2 Comments »

Do you ever write random bits of code and wonder why you are doing it? Something that seems worth it at the time and then you really wonder?

I just did this with a class that I call TokenObject. The goal of this trivial class is to take a string, and give me a nice way to get pieces out of it. Normally I would use split and grab the right piece, but I was doing so much conversion from “command line string” to an object, that I ended up with something that lets me do this:

var userpass = "dion password";
var up = new TokenObject(userpass, {params: "user pass"});
// up.user;
// up.pass;
// Can also get via: up.param('user'); up.param(0);

Funny huh? :)

/*
 * TokenObject: Given a string, make a token object that holds positions and has name access
 */
 
var TokenObject = function(input, options) {
	this._input = input;
	this._options = options;
	this._splitterRegex = new RegExp(this._options.splitBy || '\\s+');
	this._pieces = input.split(this._splitterRegex);
 
	if (this._options.params) { // -- create a hash for name based access
		this._nametoindex = {};
		var namedparams = this._options.params.split(' ');
		for (var x = 0; x < namedparams.length; x++) {
			this._nametoindex[namedparams[x]] = x;
 
			if (!this._options['noshortcutvalues']) { // side step if you really don't want this
				this[namedparams[x]] = this._pieces[x];
			}
		}
 
	}
}
 
TokenObject.prototype.param = function(index) {
	return (typeof index == "number") ? this._pieces[index] : this._pieces[this._nametoindex[index]];
}
 
TokenObject.prototype.length = function() {
	return this._pieces.length;
}