Feb 13

In Part I of the Wysihat tutorial, I went through some simple examples of how to use Wysihat. This time around, I’m going to go through adding a button that prompts for an image URL and inserts the image into the editor. I’ll show how to use CSS to turn the links Wysihat produces into buttons. DecoyMusic launched version 1.1 in early January with a Wyishat-enabled WYSIWYG editor. I’ve encountered several problems which will close out the second half of this series.

As I mentioned in my first tutorial, there are several examples provided in the Wysihat repository. The ‘link selection’ example (found in the examples/ directory) shows you how to go about allowing the user to add links to a piece of selected text. The user first makes a selection, then hits the link button, and is prompted for the URL. The prompt is a standard Javascript prompt, but the code to send the user value back to the editor is up to us. Wysihat doesn’t provide this out of the box. Take a look at that example again. Here is the meat of it.

    var LinkSelection = {
      promptLinkSelection: function() {
        var node = this.selection.getNode();
        if (node.tagName == 'A') {
          if (confirm("Remove link?"))
            this.execCommand('unlink');
        } else {
          var value = prompt("Enter a URL", "http://www.google.com/");
          if (value)
            this.linkSelection(value);
        }
      },
 
      queryLink: function() {
        var node = this.selection.getNode();
        return node ? node.tagName == 'A' : false;
      }
    }
 
    Event.observe(window, 'load', function() {
      var editor = WysiHat.Editor.attach('content');
      var toolbar = new WysiHat.Toolbar(editor);
 
      Object.extend(editor, LinkSelection);
 
      toolbar.addButton(
        { name: 'link', label: "Link" }, function(editor) {
          editor.promptLinkSelection();
      });
    });

We’re using the pseudo-object-oriented nature of Javascript to cram some functionality into LinkSelection which we later on give to an editor through extension. Examine PromptLinkSelection. Ignoring some of the other stuff that is going on there. What it is doing for us is prompting for a value from the user, and then passing it to the linkSelection function of the editor. The rest of the code should look familiar if you read Part I. It sets up the button and adds it to the toolbar. The one exotic looking line is where the prompt function gets added to the editor. All this does is make it trivial to call the PromptLinkSelection function  from a button event further down.

Realize that there’s not much difference between creating a <a> tag on a page and creating an <img> tag. They both minimally take a URL and that’s it. We’ve just gone over how to add a button that prompts for a link. Thus, it’s not too much of a stretch to figure out how to make a button to insert an image. Why not just add the function to LinkSelection? The reasons are clear. I won’t go over it here, but there is bound to be some common code between these two very similar tasks that could be factored out. It’s also helpful to know that Wysihat provides us with an insertImage function.

    var LinkSelection = {
      promptImageURLSelection: function() {
        var node = this.selection.getNode();
        if (node.tagName == 'A') {
          if (confirm("Remove link?"))
            this.execCommand('unlink');
        } else {
          var value = prompt("Enter a URL", "http://www.example.com/images/my_image.png");
          if (value)
            this.insertImage(value);
        }
      }
  }

I’ve removed the irrelevant parts here. When you boil it down, the only difference between this and the link selection example is you call insertImage instead of linkSelection. You can use this idea to further extend the editor to your needs. One thing I intend to do eventually is create an embed media button like the blogging engine Wordpress has.

In my introduction to Wysihat, I showed off the basic editor. At that time, I mentioned it is possible to style the links as buttons and I would show you how later. Now is that time!

Basic Wysihat Form

Basic Wysihat Form


<div class="editor_toolbar clearfix">
  <a class="button bold" href="#"><span>Bold</span></a>
  <a class="button underline" href="#"><span>Underline</span></a>
  <a class="button italics" href="#"><span>Italic</span></a>
</div>

Take a look at the HTML that is generated for the toolbar. Not surprisingly, the toolbar is a div and has a class of editor_toolbar. Each button has 2 classes: button and it’s name. This allows you to target all buttons with the same style or each button individually.

DecoyMusic.com WYSIWYG Editor

DecoyMusic.com WYSIWYG Editor

The above screenshot is taken from DecoyMusic.com. This is an example of what you can put together with some CSS. That is the exact same markup as I went over. Let’s take a look at the corresponding CSS. I’m only showing the relevant parts for the editor. I’ll let you explore the clearfix technique as well as how I’ve styled the rest of the page on your own. There would also be a style for each button, but here I’ve only shown bold.

.editor_toolbar {
  background-color:#CCCCCC;
  border-left:1px solid #333333;
  border-right:1px solid #6D6D6D;
  border-top:1px solid #6D6D6D;
  margin-right:1px;
  padding:0.3em;
}
 
.editor_toolbar .button {
 height:16px;
 width:16px;
 overflow:hidden;
 text-indent:-100em;
 cursor:pointer;
 float:left;
 margin-right:0.3em;
 vertical-align:bottom;
}
 
.editor_toolbar .button.bold {
  background:#CCCCCC url(/images/icons/bold.gif) no-repeat scroll 0 0;
}

The toolbar itself is basically a solid block with a background color and a border. I’ve given the bottom and right borders a different color from the other sides so that the editor has a little bit of dimension to it. The next style is where most of the magic happens. The width and height are first set. I’ve used 16 by 16 pixel buttons, so I set mine to 16.

The next two rules are key. They shove the link text that Wysihat inserts by default. You can’t control the contents of the links as they are spit out by Wysihat. A CSS trick to hide text like this is to shove it way off the screen. It’s still in the document, but the stylesheet pushes it so far off the screen, you wouldn’t even see it large resolutions. So, set your overflow to hidden and your text-indent to some very large negative number of ems. The rest of the rules simply add a few nice things like spacing out the buttons and giving us a pointer finger cursor when we hover over the buttons. The final piece is to style each button itself. This is where you specify the button image you want to use. It is actually a background image, but combined with all of the other CSS it behaves as a button.

Keep in mind this is only one way of styling your WYSIWYG buttons. You could also leave the text in place and add some kind of background to give the impression of a button. There are also ways of giving the button hover states which provide feedback for your users.

Wysihat is a somewhat immature project (at release 0.2 at the time of writing). As with early adoption of anything there will be some bugs to deal with. Not to say that it is buggy. The project will mature and gain support; it will get better. You can contribute if you’re a javascript developer. I have no doubts by the time it hits 1.0, 37 Signals and the community will have come up with a fine tool. However, the people that use my site have reported some issues. After initially being loaded, the editor is “locked” and will not allow you to delete text. This is apparently only an issue in Firefox 3. If you first add something, even a space, it’s refreshes itself or something and you can use delete. Do not paste any content copied from a Word document and expect it to look anything like what you copied. It won’t and it’s futile to try to correct it within the editor. I also have one person reporting that the editor hangs and stalls when he is editing a large article. I myself witnessed this on a large piece of content containing several images.

Jan 25

Do I have you thoroughly confused with the title yet? I’ve neglected the blog here since October and that’s mostly because I talk about my day-to-day adventures on Twitter. Something I have decided to do is write some posts that are more technical. I’ve probably learned more about Rails via blogs than I have from any Rails books I read. The topic I’ve chosen for today’s post is something I couldn’t find much material on myself. I hope it helps someone.

First, let’s get something out of the way. WYSIWYG stands for “What you see is what you get.” It’s surprising how often people don’t know what that means. Given that this is supposed to be a “technical” blog post I won’t go into detail about what a WYSIWYG editor is. Let’s assume you know what it is, you’ve tried TinyMCE, FCK-Editor, or others. Let’s also assume you’ve gone through considerable pain attempting to integrate these editors into your site, or styling these editors for your site. It never quite works out right. The editor doesn’t work right when used with AJAX, or the interface and buttons are completely foreign to your layout and design. Sometimes these things can be fixed, but it usually involves a lot of hacking. Leave it to the guys at 37Signals to make it all better.

Wysihat was introduced in October 2008 by Jason Fried on the 37Signals blog, Signal vs. Noise.

WysiHat is a WYSIWYG JavaScript framework that provides an extensible foundation to design your own rich text editor. WysiHat stays out of your way and leaves the UI design to you. Although WysiHat lets you get up and running with a few lines of code, the focus is on letting you customize it.

Normally, I would read that with a skeptical eye, but given that this is 37 Signals, there might actually be something to Wysihat. Wysihat is open source and, hosted on Github. It’s also small. Wysihat weighs in at 20k uncompressed, and a mere 4.8k when delivered gzipped through my Apache server. To be fair, this minuscule size is due to Wysihat’s dependence on Prototype. I’m a Rails developer and Rails defaults to Prototype, so I’m OK with that. It is worth noting that you will need to make sure wysihat.js loads after prototype.js or this won’t work.

Note: If you clone the repository on Github, you’ll quickly notice there is no wysihat.js file anywhere to be found. All you need to do is switch into the directory where you cloned the wysihat repository and run the ‘rake’ command without any arguments. It will build the Javascript in dist/. Of course this is also in the README, but you were so excited to get started you forgot to read that, right?

After all that praise you’d think that all you have to do is add Wysihat source to your page and your forms are suddenly improved with editor goodness. Not quite. Wysihat is intended to be used as unobtrusive Javascript that decorates the text fields of your choice. You have you write the part that initializes the editor and sets up the toolbar with the buttons you need.

Event.observe(window, 'load', function() {
  var editor = WysiHat.Editor.attach('content');
  new WysiHat.Toolbar(editor, {buttonSet: WysiHat.Toolbar.ButtonSets.Basic});
});

In the four lines of Javascript above, The first line simply makes sure the page DOM is set before we do anything like adding an editor to it. Then, we have to initialize the editor. All you have to do is pass in the ID of the text area you want to add the editor to. Here it is saved to a variable so we can then add the default toolbar (bold, italics, underline) to the editor. Without that line, we’d get an editor without buttons. That’s it! However, for your four lines of code, you only get a basic looking editor.

Event.observe(window, 'load', function() {
      var editor = WysiHat.Editor.attach('content');
      var toolbar = new WysiHat.Toolbar(editor);
 
      toolbar.addButton(
        { name: 'bold', label: "Bold" }, function(editor) {
        editor.boldSelection();
      });
 
      toolbar.addButton(
        { name: 'underline', label: "Underline" }, function(editor) {
        editor.underlineSelection();
      });
 
      toolbar.addButton(
        { name: 'italic', label: "Italic" }, function(editor) {
        editor.italicSelection();
      });
});

The above code looks more complex, but it really is not. Again we wait for the DOM to be set, and initialize our editor. Instead of using Wysihat’s basic toolbar, we want to customize our own. Only the editor is passed in to the toolbar init line, leaving us add the buttons.

We use addButton and passing a Hash with the name and label. The name will become a CSS class on the link that gets inserted and the label is the link text. The final argument for addButton is a function inside of which we call another editor method boldSelection(). This does what you would expect and bolds some selected text in the editor.

The underline and italics buttons can be done the same way and there are also existing methods making selected text underlined or italics too. If you take a peek at the Wysihat source around line 65 you’ll see WysiHat.Commands. Below that are all the functions the editor can call for doing other common tasks such as creating lists, links, images, etc.

With what I’ve covered so far, you should be able to add an editor to a page and add any number of buttons using the built-in Wysihat editor functions. All of the code I’ve shown is taken from the examples directory of the project (this is also stated in the README). In Part II of this post, I will show how to write your own custom button functions and how to make the editor not look so boring by adding some simple CSS. Finally, I’ll finish up with some of the problems and pitfalls I’ve found so far using Wysihat in one of my projects.

Update: Part II has been posted!

Oct 22

In my final semester at St. John’s, I was required to take up a research project, give a presentation on the topic, and then write a lengthy paper. Naturally, the topic was also required to be from the field of Computer Science. I knew right away that I wanted to do something with Linux. Through some guidance from my professor, I came to the topic of Free and Open Source Software. One of the first important people I came across in my research was Richard Stallman. So when I discovered a few weeks ago that Stallman was giving a talk at the University of Minnesota, I made sure my calendar was free.

After wandering around the U of M campus for the first time, I managed to find my way to Wiley Hall Room 175 just in time. Stallman took the stage moments later and began what would amount to 2 straight hours of speaking, evangelism, and laughs.

If you aren’t familiar with who Stallman is, well, I’m not surprised. Have you ever heard of the term ‘hacker?’ Stallman was one of the first. Ever heard of GNU, Linux, or Emacs? He either made them himself, or made them possible. If you’re still lost, then maybe you should stop reading here.

RMS began by explaining the four freedoms of free software.

  • Freedom 0: The freedom to use software as you wish
  • Freedom 1: The freedom to view the source code and modify it as you wish
  • Freedom 2: The freedom to distribute copies of the software to others
  • Freedom 3: The freedom to make improvements to the program and distribute those modifications to others

These four freedoms all must be true in order to call a piece of software ‘free.’ From there things really went everywhere.  There was much badmouthing of proprietary software and all the problems and hassles it brings. Stallman’s primary message was to refuse to use proprietary software, evangelise free software, and the computing world will become a much better place. Oh and there were a few jabs at the US government, Microsoft, large corporations that I’ll admit I laughed at.

RMS was also endlessly quotable:

“Ms. Clinton… probably mentions freedom more often than I do, but says much less about the substance of it.”

“If you see someone drowning, and there’s no one else around, and it’s not Bush, you have an obligation to save that person.”

“I am St Ignucius of the Church of Emacs.”

“Vi vi vi is the ‘Editor of the Beast’, but using a free implementation of vi is not a sin, it’s a penance.”

I can’t completely agree with Stallman though. It’s tough because I have a lot of respect for the man for what he’s accomplished and the views we share. Free software is great and so is the idea that we all should share and help each other out. However, that view is unrealistic. I think proprietary software has its place in the world too. And the world certainly isn’t as amiable and agreeable as Stallman would like it to be. I’m not about to give up my DVD movies, my Macbook Pro, or playing Warhammer Online, all of which are, run, or use proprietary software.

Most people probably don’t think about the freedoms they give when running proprietary software, but at the same time I think if they did, most would make the same choice. Because of that, Stallman’s vision of a utopia for free software will never exist. Nonetheless, I encourage Stallman and the Free Software Foundation to continue their work. He is exactly the kind of person you want to lead a movement. He’s pure, uncorruptable, and unflinchingly loyal. He’s made it his life’s purpose to bring his vision to reality. If only some of our politicians and world leaders had the same passion and outlook.

Sep 8
©: Tony Webster

©: Tony Webster

In case you live outside the US or you live under a rock, you probably noticed last week the Republications held their quad-annual national convention last week in St. Paul. Being close to all the action definitely revealed some insights.

After the 35W bridge collapse last August, estimates came in for the rebuilding project and I was surprised to see they were all anticipating completion by December 2008. Considering that I’ve had to deal with construction in the 35W/62 commons area for over a year, I figured it might be a couple of years before the new bridge would be finished. The schedule was obviously influenced by the extra spotlight that was going to be on the Twin Cities the following September.

The months leading up to the RNC saw much back and forth between government officials and those intending to protest the convention. Protesters were denied routes that brought them anywhere near the Xcel where the convention would be held. Lawsuits were filed, but I never heard of them going to court before the convention. There were some compromises on both sides with the routes and lengths of protests though. To be honest, I wasn’t expecting much to result from the protests These things always seem to have a louder voice than their numbers suggest.

A big news story leading up to the convention was the installation of security cameras covering all of downtown St. Paul. This was made possible by a $50,000 grant from the federal government. I’m not denying that a major event like the RNC is cause for extra security, but these cameras will remain in operation following the convention.

September finally came and the Republications flocked to the Twin Cities. So much so that you couldn’t find a vacant hotel closer than 50 miles away. Between 3,600-3,700 additional law enforcement officers were brought into the city. St. Paul went into lockdown. Over 600 people were arrested over the 4 days the convention was in town. A third of those arrests came on the first night of the convention. Interestingly, at the Democratic national convention there were less than 200 arrested.

Why were the numbers so much higher at the RNC? If I had seen the numbers without context, I might have guessed because this country is sick of what the Republication run White House, Senate, and Congress have done. That is no doubt partially the reason. However, I think the real reason is that the increased police presence provoked it. The usual atmosphere around St. Paul is much different from the one I felt during the convention.

I was lucky enough to score tickets to a taping of the Daily Show with Jon Stewart. Of course this meant going into downtown St. Paul during the convention. Finding parking was hard because half the parking ramps I saw were barricaded with police vehicles. Once I found a suitable place to park, I walked to the theatre where the taping was being held. You couldn’t go half block without seeing some kind of law enforcement. Forget about talking to one of them or asking for directions. The only phrases the zombies knew were “Move along” and “Get on the ground, you’re under arrest.” I heard a few stories of innocent people who got trapped in raids or were merely prevented from getting to where they parked their car. My friends and I were able to make it in and out without a confrontation though.

On the third night of the convention, Rage Against the Machine played a show in Minneapolis. Following the show, 100 people were arrested. Now if that’s all you heard, you might be inclined to think that a bunch of radical extremists were incited by RATM who is known for their political dissidence. However, you might change your mind if you knew a few facts. First of all, the show was in Minneapolis, not St. Paul. The two metro areas are separated by several miles. All of the protesting and any clashing between police up to that point had been in St. Paul. Second, Zack de la Rocha, lead vocals for RATM specifically told the crowd NOT to cause a disturbance. There are videos of him urging people to show more restraint than police. Third, concert goers were greeted with a line of police in full riot gear when exiting the arena.

UPDATE: An investigation into how police handled arrests after the Rage Against the Machine show will be done.

Now, someone going to a Rage Against the Machine show is probably the type that is going to be more inclined to protest. I highly doubt they’re going to turn into a violent, dangerous person merely by going to a politically charged show though. That’s why I see the riot squad as provocation. It’s like putting a hungry lion across the street from a bunch of zebras and expecting that it won’t kill any of the zebars. Why couldn’t you place a team or two a block away ready to be called in? Why did they need to be lined up directly across the street? The only word that comes to mind is overreaction.

Aug 1

Gone Away and Back Again

Posted: 10:08AM Tagged: Apple, Life, Technology, Work

Tuesday started innocently enough. I got to work, felt groggy, and went over to grab a latte at the local coffee shop. My first sip was cautious, but not enough to avoid the burning. I jerked back a little bit and spilled a drop of latte the size of maybe a quarter on the arrow keys of my Macbook. That’s when the trouble started.

First it was left shift + ‘i’ that wouldn’t work. Then it was the arrow keys. Finally, the whole damn keyboard just stopped working. Now I’d doused the laptop in much worse in the time I’ve had it so I didn’t think much of this relatively small spill. Given how fast things progressed, I was concerned.

The next few hours I spent researching keyboard replacement. Let’s just say there’s a reason Apple doesn’t just send you a replacement keyboard and let you fix yourself. Take the battery out, unscrew the memory cover plate, remove the bottom cover, remove the non-conductive black tape, remove a dozen screws, unclip ribbon cable… you get the idea.

So it was either use an external keyboard, send the thing into Apple for a few hundred dollars and a couple of weeks of time, or try to fix a replacement and fix it myself. The external keyboard worked fine in the office, but I wasn’t going to be lugging around a keyboard with me for work away from the office. Instead, I started searching for a replacement keyboard online. They were at least $70. At that point, I decided an Apple Wireless Keyboard was in order as it would cost just as much and have no installation. It’s also small and easily tossed in my laptop bag.

Consequently a few hours after I got the new keyboard, the Macbook keyboard started working again. It’s not back 100% though because random arrow keys get triggered from time to time. It also won’t sleep reliably as it keeps getting input from the keyboard. Things seemed to have gotten better since yesterday, but I’ll still be taking this external keyboard around with me for at least awhile.

Jul 7

Last weekend was the Great Virginia Get Together. That is nothing more than a fancy name for an all class reunion. Being that I’ve only been out of high school for 8 years, I haven’t had many reunions to go to. I don’t think there was a 5 year reunion and I surely wouldn’t have gone if there was. I probably don’t even need to mention that I skipped this one as well.

From a friend who was in town for the event, I heard that four (of about 150) people showed up to my class’s brunch/social thing. First of all, had it been some kind of kegger, I’m sure you’d have gotten a few of the lifers (people who never left Virginia) to show up. Second, I think reunions are a thing of the past.

The reasons you hold a high school reunion in the first place is to get people back in contact with people that they may have lost touch with over the years. At worst, you showed up to see if all the jocks are working dead end jobs and if all the geeks are rich and married to supermodels.

The problem is, staying in touch these days isn’t that hard. Email can be blasted out to whole address books to keep old friends informed. People can follow your blog. Sign up for an account on Facebook. The list goes on.

I wouldn’t expect my parents to replace their high school reunions with online social networks, but for the generation that doesn’t know a world without the Internet, you can be sure it will for them.