Bookmarklet/Favelet Generator #

I don't know what prolific authors of favelets/bookmarklets do when they code them, but I find the process rather annoying. Having to strip out all newlines, and preferably all extraneous whitespace (for the sake of shorter URLs) gets tedious when revising a script that's more than a few lines long.

As a result, I've come up with the following Perl script that transmogrifies a readable JavaScript source file into a single compressed line, ready to be used as a favelet:

#!/usr/bin/perl -w

use strict;

my $bookmarklet = 'javascript:';
my $inComment = 0;

while (<>)
  s/^\s*(.*)\s*$/$1/;         # whitespace preceding/succeeding a line
  s/([^:])\/\/.*$/$1/;        # single-line comments ([^:] is to ignore double slashes in URLs)
  s/^\/\/.*$//;               # whole-line single-line comments
  s/\s*([;=(<>!:,+])\s*/$1/g; # whitespace around operators
  s/"/'/g;                    # prevent double quotes from terminating a href value early
  # multi-line comments
  if ($inComment)
    if (s/^.*\*\/\s*//) # comment is ending
      $inComment = 0;
  elsif (s/\s*\/\*.*$//) # comment is beginning
    $inComment = 1;
    $bookmarklet .= $_; # we have to append what we have have so far, since
                        # the line below won't get triggered
  $bookmarklet .= $_ if (!$inComment);

print $bookmarklet;

print STDERR "Bookmarklet length: " . length($bookmarklet) . "\n";

The contents of your .js file should obviously serve as the standard input of the script, and for maximum efficiency (on Mac OS X) its output should be piped to pbcopy so that it can be pasted into a browser's location bar for easy testing. The length of the favelet is also printed, since some browsers impose a maximum URL length.

Not quite a favelet IDE, but it certainly makes life easier.

Post a Comment