Category: MooTools

  • TrackPerformer update

    I’ve added in some really exciting new features to my TrackPerformer project, as well as three new performances: We Three Kings, Carol of the Bells, and Joy to the World.

    Filters

    It’s now possible to add filters, or effects, into the processing chain. These filters can be applied before any performers (pre-filters) or after all performers (post-filters). At the moment, the included filters are:

    • FPS: Calculates the average framerate across the performance, optionally displaying it in a DOM element.
    • Grid: Draws a grid to the canvas. The grid may be a simple intersection grid (points), or lines. Both the X and Y axes may be independently configured.
    • Pick: Probably the most interesting (and processor-intensive) part of TrackPerformer. The Pick filter will randomly swap a pixel with one of its neighbours. It’s used at full intensity on both We three Kings and Joy to the World, and, when toned down a little for Carol of the Bells, provides a softening, organic effect.

    I’ve got some ideas for more filters down the track… The only difficulty is keeping performance acceptable: manipulation of the canvas pixel by pixel is quite slow in current browsers.

    Performers

    There are a couple of new performers, and some minor updates to some of the existing ones. The Oscillator performer, in particular, is rapidly becoming the most flexible and useful of the performers.

    • There’s a new ShimmerGrid performer, which is great for adding texture and movement to the entire canvas. You can see it in action particularly well on Joy to the World.
    • The Swarm performer can now draw its particles as knots (like the SignalTracker), as well as as dots.
    • The Oscillator now has the ability to draw sustained notes, and to increase the longevity of notes. Take a look at Carol of the Bells to see these new options in use.
    • Notes can now be filtered based not only on their pitch, but also their velocity (volume).

    There are a couple of other changes here and there, but these are the main ones.

    We Three Kings

    The three new example tracks are all taken from We Three Kings, my new Christmas remix album. Why not go and have a listen?

  • TrackPerformer

    TrackPerformer provides a visual stage for your music, using HTML5 canvas and audio. On that stage, performers “play” the instruments in the music visually. In other words, it’s a visualisation system for music, but based on the notation (the abstract) rather than the audio (the manifestation).

    Essentially, you take a piece of music, convert it into a format that TrackPerformer understands (JSON), describe how you want it to be performed, and then watch! You can, of course, write your own performers.

    Before going any further, let’s see it in action. The music is “Colony”, a new piece that I wrote about a week ago.

    Note: You won’t be able to view the performance linked above in Internet Explorer, due to its over-aggressive script-blocking: the scripts served from GitHub have the wrong mime-type, so IE won’t let them run.

    Take a look at the project on GitHub to see how it all fits together. TrackPerformer itself resides in the “Source” directory; in “Examples”, you’ll find the performance of Colony; in “Utilities”, there’s a JavaScript macro for Komodo IDE/Edit that will help you to translate copied-and-pasted OpenMPT pattern data into TrackPerformer’s JSON format.

    You can find more information on the TrackPerformer wiki, including an outline of the format, and some basic instructions for getting started. I’ll be adding more information to the wiki over the next few days, and I’ll post updates here too.

    Let me know what you think!

  • Paired sort in JavaScript

    Sometimes, you’ll have two arrays of associated data, and you’ll need to sort them. You can’t just call sort() on both arrays, because that will potentially break the associations between them. What you need is a way to sort one of the arrays, and shuffle the elements of the second array to match. Here’s a simple MooTools function that does just that (using quicksort):

    [sourcecode language=”javascript”]Array.implement({
    pairedSort: function(other, reverse) {
    if (this.length === other.length) {
    for (var i = 0, len = this.length; i < len; i++) { var curr = this[i]; var currOth = other[i]; var j = i - 1; while ((j >= 0) && (this[j] > curr)) {
    this[j + 1] = this[j];
    other[j + 1] = other[j];
    j–;
    }
    this[j + 1] = curr;
    other[j + 1] = currOth;
    }
    }
    if (reverse) {
    this.reverse();
    other.reverse();
    }
    return this;
    }
    });[/sourcecode]

    Using this function is quite straightforward:

    [sourcecode language=”javascript”]var alpha = [3,2,1,6,5,4];
    var beta = [1,2,3,4,5,6];
    alpha.pairedSort(beta);
    // alpha == [1,2,3,4,5,6]
    // beta == [3,2,1,6,5,4][/sourcecode]

    When would this actually be useful? Let’s say you’ve got an object which maps numeric assessment scores to an alphabetic grade:
    [sourcecode language=”javascript”]var mapping = {
    ‘A’: 80,
    ‘B’: 60,
    ‘C’: 40,
    ‘D’: 20,
    ‘E’: 0
    }[/sourcecode]
    Unfortunately, objects in JavaScript have no intrinsic order on their keys — this is because they’re essentially just hashmaps. What we need to do to be able to make use of these data, then, is create an array of keys, and one of values, and then sort them. The pairedSort() function allows us to do this easily. (In fact, it’s for this exact application that I wrote the method!)

  • Generative Music

    Continuing my HTML5 and canvas experiments, I’ve put together a generative music system. Essentially, a series of particles move across a field, occasionally triggering sounds — the sound triggered depends on their location in the field.

    There is, of course, a little bit more to it than that. Under the hood, I’ve got a series of HTML5 Audio objects that are used to provide polyphonic audio using a simple round-robin algorithm (I encoded the audio in OGG, so you’ll need to use an OGG-friendly browser, like Firefox). The particles are much simpler than those in my previous canvas dalliance, in that they don’t swarm, and their motion is more linear.

  • Canvas Swarms

    I’ve been meaning to start playing with the HTML5 <canvas> element for a while now, and yesterday I took the opportunity. I translated a Processing sketch I made a while ago into JavaScript (with a few minor enhancements).

    Essentially, 1 to 3 swarms of particles move around the canvas, reproducing when the conditions are just right, and dying of old age. Quite simple, but the patterns produced can be really quite pretty.

    One interesting thing that I discovered whilst doing this is that you can’t pass around a canvas’ context at the instantiation of a MooTools class — it complains about wrapped natives. That’s why, if you like in the source JavaScript, you’ll see me pass the actual context around to various functions. I’d be interested in hearing if anyone has a workaround for this, because this is, well, a bit clunky.

  • Javascript: Print a single element

    Sometimes, you’ll want to allow users the ability to print only a part of your page; for example, a table but not the various links around the page. It’s possible to use a printing stylesheet, but this can cause severe headaches when you need different parts printed at different times. Really, we want to be able to just say element.printElement(), and have it just work. That’s what the MooTools function below does. It’s loosely based around the concepts outlined at this website.

    [sourcecode language=”javascript”]Element.implement({
    printElement: function(docTitle) {
    var strName = ‘printer-‘ + (new Date()).getTime();
    var styles = [];
    $$(‘link[type=text/css]’).each(function(style) {
    styles.push(‘‘);
    });
    var title = docTitle || document.title;
    var that = this.getParent();
    var iframe = new IFrame({
    name: strName,
    styles: {
    width: 1,
    height: 1,
    position: ‘absolute’,
    left: -9999
    },
    events: {
    load: function() {
    var doc = window.frames[strName].document,
    win = window.frames[strName];
    var f = function() {
    if (!doc.head) {
    f.delay(10);
    return;
    }
    // We need to delay printing so that styles are applied.
    (function() {
    doc.title = title;
    // IE7 won’t let us adopt() here for some reason, and we can’t do anything to the head.
    doc.body.innerHTML = styles.join(”) + that.innerHTML;
    (function() {
    win.focus(); // IE needs the window to be focused.
    win.print();
    }).delay(100);
    }).delay(200);
    };
    f();
    }
    }
    }).inject($(document.body));
    (function() {
    iframe.dispose();
    }).delay(30000);
    }
    });[/sourcecode]

  • Limiting the contents of a string via RegEx

    Often, you will need to prevent users from entering data that doesn’t conform to a specific pattern. For example, you may want to allow users to enter only numbers or only valid email addresses. To this end, I’ve written a little utility function that returns the “standardised” version of a string, according to the regex you supply.

    [sourcecode language=”javascript”]String.implement({
    limitContent: function(allowedRegex) {
    return $splat(this.match(allowedRegex)).join(”);
    }
    });[/sourcecode]

    Basically, the function takes the result of evaluating the regular expression on the string, converts it into an array if it isn’t one, and then joins the array’s elements together with an empty string.

    Examples:

    [sourcecode language=”javascript”]console.log(“12345”.limitContent(/.{4}/)); // Only allow four characters
    console.log(“joe@mail.com”.limitContent(/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}/)); // Only allow email addresses
    [/sourcecode]

  • MooTools object messaging

    Events

    In JavaScript, we often tend to use events all over the place. In MooTools, the custom ‘domready’ event is particularly prevalent. However, events suffer from a few drawbacks:

    You can’t attach events to non-existent objects.

    Pretty self-explanatory, really. What this means in practice, though, is that you can’t easily let object A know when object B exists.

    If an object starts to listen for an event after it’s already fired, it’ll never hear it.

    Because content on the web isn’t always delivered in perfect order (especially when you’re loading scripts synchronously), it’s possible for an object to try to listen for an event after it’s already been fired. Obviously, this means that your listener object will never run the code that’s dependent on that event, which could be Bad Thing™.

    It’s not particularly easy to know which object is listening for which events.

    There are ways around this, but you can’t just dir() the listeners in Firebug.

    A messaging system

    For all of these reasons (and probably a few more that I’ve forgotten about), a messaging system can be an invaluable addition to your arsenal when writing JavaScript. How does a messaging system work? Well, interested objects ‘register’ themselves as listeners for particular message ‘handles’, and other objects can send messages using those ‘handles’. Below is a very simple MooTools messaging system that I knocked up, which has a few cool features, including:

    • When you register() a listener, you can have its callback immediately fire if that message has ever been sent before.
    • You can very easily see which callbacks are associated with which messages by simply dir()-ing the ‘listeners’ member.
    • You can unregister() a listener at any time (provided you’ve got a reference to the function and the handle).
    • Handles can be any valid JavaScript type — Strings, Numbers, even Objects.

    Feel free to use and extend this system — as I mentioned, this is a very simple system. If you do extend it, let me know in the comments!

    Let me know what you think about this system in the comments.

    [sourcecode language=”javascript”]
    barryvan.base.Messaging = new Class({
    listeners: $H(),
    sentMessages: [],

    initialize: function() {

    },

    /**
    * Register a listener for a particular handle.
    * handle [String]: The message ‘handle’ to listen for.
    * callback [Function]: The function to be called when the handle is sent a message. The contents of the messages will be included in the function call.
    * dontCheck [Boolean]: If falsey and the handle has had a message sent to it, immediately call the callback function (without contents), and continue to add the listener as normal.
    */
    register: function(handle, callback, dontCheck) {
    if ($type(callback) !== ‘function’) return;

    if (!dontCheck && this.sentMessages[handle]) {
    callback();
    }

    if (!this.listeners.has(handle)) this.listeners[handle] = [];
    this.listeners[handle].push(callback);
    },

    /**
    * Unregister a listener for a particular handle.
    * handle [String]: The message ‘handle’ to cease listening for.
    * callback [Function]: The function which was earlier assigned as the callback for the messages.
    */
    unregister: function(handle, callback) {
    if (this.listeners.has(handle)) {
    this.listeners[handle].erase(callback);
    }
    },

    /**
    * Send a message to the given handle with the given contents — send the contents to all the registered listeners for that handle.
    * handle [String]: The message ‘handle’ to transmit to.
    * contents [Mixed]: The contents to be sent to the listeners.
    */
    send: function(handle, contents) {
    this.sentMessages.include(handle);
    if (this.listeners.has(handle)) {
    this.listeners[handle].each(function(callback) {
    callback(contents);
    });
    }
    }
    });
    [/sourcecode]

  • Quicksort an array of objects

    Often, you will need to sort an array of objects in Javascript. The inbuilt sort() function can’t do this, but here is a Quicksort implementation for doing just this.

    Parameters

    array The array to be sorted. (See below for an implementation on the Array Native itself, which makes this variable unnecessary).

    key The key to sort by. Make sure every object in your array has this key.

    Examples

    [sourcecode language=’javascript’]
    var objs = [
    {fruit:”cherry”},
    {fruit:”apple”},
    {fruit:”banana”}
    ];

    console.log(objs.sortObjects(‘fruit’));
    // Logs [{fruit:”apple”},{fruit:”banana”},{fruit:”cherry”}] to the console
    [/sourcecode]

    The code

    [sourcecode language=’javascript’]
    sortObjects: function(array, key) {
    for (var i = 0; i < array.length; i++) { var currVal = array[i][key]; var currElem = array[i]; var j = i - 1; while ((j >= 0) && (array[j][key] > currVal)) {
    array[j + 1] = array[j];
    j–;
    }
    array[j + 1] = currElem;
    }
    }
    [/sourcecode]

    Implemented on the Array native:

    [sourcecode language=’javascript’]
    Array.implement({
    sortObjects: function(key) {
    for (var i = 0; i < this.length; i++) { var currVal = this[i][key]; var currElem = this[i]; var j = i - 1; while ((j >= 0) && (this[j][key] > currVal)) {
    this[j + 1] = this[j];
    j–;
    }
    this[j + 1] = currElem;
    }
    }
    });
    [/sourcecode]

  • Javascript string ellipsising

    Putting ellipses into strings that are too long has been around for a very long time. Unfortunately, Javascript doesn’t offer a native method of doing this, so below is a little function that’ll do it for you.

    This function returns a copy of the string it’s called on, ellipsised, and takes three parameters:

    toLength (required) The number of characters to truncate the string to (or 0 to disable ellipsising)

    where (optional, default ‘end’) A string representing where the ellipsis should be placed — ‘front’, ‘middle’, or ‘end’

    ellipsis (option, default ‘\u2026’) A string to be used as the ellipsis.

    Examples

    [sourcecode language=’javascript’]
    // Our clichéd string
    var s = ‘Jackdaws love my great big sphinx of quartz’;

    alert(s.ellipsise(10));
    // Alerts “Jackdaws l…”

    alert(s.ellipsise(10, ‘front’));
    // Alerts “… of quartz”

    alert(s.ellipsise(10, ‘middle’, ‘pony’));
    // Alerts “Jackdponyuartz”[/sourcecode]

    The code

    [sourcecode language=’javascript’]String.implement({
    ellipsise: function(toLength, where, ellipsis) { // Where is one of [‘front’,’middle’,’end’] — default is ‘end’
    if (toLength < 1) return this; ellipsis = ellipsis || '\u2026'; if (this.length < toLength) return this; switch (where) { case 'front': return ellipsis + this.substr(this.length - toLength); break; case 'middle': return this.substr(0, toLength / 2) + ellipsis + this.substr(this.length - toLength / 2) break; case 'end': default: return this.substr(0, toLength) + ellipsis; break; } } });[/sourcecode]If you're not using MooTools, you can use this variant instead:[sourcecode language='javascript']String.prototype.ellipsise = function(toLength, where, ellipsis) { // Where is one of ['front','middle','end'] -- default is 'end' if (toLength < 1) return this; ellipsis = ellipsis || '\u2026'; if (this.length < toLength) return this; switch (where) { case 'front': return ellipsis + this.substr(this.length - toLength); break; case 'middle': return this.substr(0, toLength / 2) + ellipsis + this.substr(this.length - toLength / 2) break; case 'end': default: return this.substr(0, toLength) + ellipsis; break; } }[/sourcecode]

  • Javascript-generated tables and rowspan

    At work, I’ve recently been putting together a nice little calendar-like utility using Javascript. Basically, it has to generate a table consisting of cells which may span multiple rows. Surely the solution is simple enough: just set the rowspan on each td as we create it. Unfortunately, that doesn’t work, at least not in Firefox.

    It appears that in Firefox, if you create a td and set its rowspan to some value when there are no rows for it to expand into, the attribute will be completely ignored, even if you add rows afterwards! Needless to say, this is very annoying. The solution? Build your table backwards.

    The code I have now is something like this (note that I’m developing using the Mootools framework):

    [sourcecode language=’javascript’]var tbl = new Element(‘table’);
    var trs = [];

    for (var i = 0; i < 4; i++) { var tr = new Element('tr'); tr.grab(new Element('td', { 'html': 'Cell ' + i })); if (i % 2 == 0) { tr.grab(new Element('td', { 'rowspan': 2, 'html': 'Span ' + (i / 2) })); } trs.push(tr); }for (var i = trs.length - 1; i >= 0; i–) {
    tbl.grab(trs[i], ‘top’);
    }[/sourcecode]

    What does this code do? Well basically, we’re creating a table with ten rows and two columns; the cells in the right-hand column each occupy two rows. The result will be something like this:

    Cell 1Span 1
    Cell 2
    Cell 3Span 2
    Cell 4
  • MooTools and OO Javascript development

    I’ve started work on a new project at my job — a fairly complex AJAX application for the education sector. For this project, I’ve been allowed to essentially choose my own direction, and I’ve chosen to implement the clientside Javascript using the MooTools framework. I’ll say it right here: I’m absolutely loving it.

    What I’m really enjoying about MooTools is the object-orientedness it brings to development. Although syntactically it’s a little bit weird at first, the ability to create, extend, and implement classes makes my development progress much more quickly, and in a more efficient way. Add to that the plethora of utilities (like the .each prototype for arrays) and shorthand functions (like $ to replace document.getElementById), and all of a sudden Javascript development becomes a bit more, well, flexible.

    I’m not saying that you can’t accomplish cool things in Javascript outside of MooTools (or other frameworks, for that matter); my point is that I believe you can accomplish cool things in Javascript more quickly using a good framework, which should really come as no surprise. Perhaps the reason I’m so enjoying this type of development, to the point of blogging about it, is that up till now, I’ve been stuck working in a non-frameworked, very non-OO Javascript development paradigm.

    I mentioned the curious syntax that accompanies MooTools.  To create a new class, for example, you would probably write something like this:
    [sourcecode language=’javascript’]var myClass = new Class({
    Implements: Options,
    options: {
    optionA: ‘monkey’,
    optionB: ‘pony’
    },
    initializer: function(options) {
    this.setOptions(options);
    this.doSomeStuff();
    },
    doSomeStuff: function() {
    alert(this.options.optionA + ‘ eats ‘ + this.options.optionsB);
    }
    });[/sourcecode]
    And then you would initialise it like this:
    [sourcecode language=’javascript’]var myInstance = new myClass({
    optionA: ‘Big Pony’
    });[/sourcecode]
    Although it looks a bit weird, it’s actually not too bad. There are really only two problems I have with it:

    1. Remembering to put commas in all the right spots.
    2. Geany, my preferred IDE (cf. Geany IDE: Tango dark colour scheme) can’t pick up classes and members properly (actually, at all) in this style.

    Other than that, though, I’m really enjoying it.