danlucraft

HTML & JavaScript Plugins in Redcar

April 2010

In the 0.3 line of Redcar, one of my top goals is to make writing plugins both easy and awesome. I believe that people will enjoy writing plugins more if the process is familiar to them, and makes use of skills they already have.

Here’s one of the APIs we’re developing that will let you write plugins using web technologies.

task manager screenshot

HTML Tabs

The HtmlTab embeds a browser into Redcar, so you can display information using HTML and CSS.

The screenshot shows the task manager, which is an example of an HtmlTab.

So far so normal. Many editors and IDEs use embedded browsers like this in order to preview HTML.

Textmate makes extensive use of HTML windows to show information from commands, and this has been terrific for Textmate because it allows users to write commands that output attractive HTML, and lots of people have done that.

Taking it further

But the HtmlTab in Redcar can do much more than just display static HTML. Redcar supports two-way communication between JavaScript in the browser and Ruby in the editor.

Here’s the implementation of that Task Manager. The controller defines a title that goes into the tab. The index method is like a Rails action, which is automatically run and the result sent for display in browser widget in the HtmlTab.

The cancel_task method is like an Ajax action (that in this case doesn’t return anything to the browser.) It’s job is to respond when the user clicks on a cancel Task link in the Tab.

class TaskManagerController < Redcar::HtmlController
  # This appears in the tab.
  def title
    "Tasks"
  end
  
  # This action is loaded and run automatically when the tab is opened
  def index
    render :index
  end
  
  # This action is called from JavaScript when the user clicks on a cancel task button
  def cancel_task(id)
    if task = Redcar.app.task_queue.pending.detect {|t| t.id == id}
      task.cancel
    end
  end

In the index.html.erb file, which contains Erb that renders the page from the instance variables in the index action, there is also a snippet of JavaScript:

$(".cancel-link").click(function(e) { 
  var id = ... // get from link
  Controller.cancelTask(id);
});

When the user clicks on a cancel task link, the callback is triggered. The Controller object is the Ruby TaskManagerController, made available to the JavaScript. So when the JavaScript calls Controller.cancelTask, this is actually calling the Ruby method TaskManagerController#cancel_task, with the id argument passed along.

So we’ve now written a Task Manager for Redcar without having to use a single line of GUI code!

What’s the point?

NB. The render method is not implemented yet, at the moment you have to manually process the ERB.

blog comments powered by Disqus