Ajax Bestiary: A Javascript Field Guide
 
Ajax Bestiary: A Javascript Field Guide
 
 

Converting Between Wiki Markup & HTML with Prototype: Part 2 ListsAt

Posted by Don Albrecht

At the end of part 1 of the series, the system could easily handle direct replacement of certain html entities with their wiki markup counterparts.  Unfortunately this was a pretty limited implementation that could only handle those entities that had a direct, symmetrical relationship with html.  In the case of lists, we have to keep track of depth and better cleanup the input text.  We also need to enforce default behavior on the input stream.

Since lists are dependent on dedicated whitespace as part of their markup, we need to clear out all unnecessary white space from the html before processing it.  To do this, we simply replace all whitespace characters with an innocuous single space to remove any extra new lines.

$(textNode).innerHTML = $(textNode).innerHTML.gsub( '\s', '' );

Next we need to cleanup the recursion.  Since we need to know significantly more about the given node to properly assess it.  We can replace the Prototype templates with simple curried function calls and migrate the recursion to the curried methods.

var ConverterTable = {
strong: Converter.curry("'''", null, true),
b:  Converter.curry("'''" , null, true),
em: Converter.curry( "''"  , null, true ),
i:  Converter.curry( "''"  , null, true ),
h1: Converter.curry( '='  , null, false ),
h2: Converter.curry( '=='  , null, false ),
h3: Converter.curry( '==='  , null, false ),
h4: Converter.curry( '===='  , null, false ),
h5: Converter.curry( '====='  , null, false ),
h6: Converter.curry( '======' , null, false ),
ul: Converter.curry('', {li:Converter.curry(['* ', ''], null, false)}, false),
ol: Converter.curry('', {li:Converter.curry(['# ', ''], null, false)}, false),
p:  Converter.curry(['','\n'], null, false)
};

The parameters passed into the individual rules are
The Markup String or an array of strings for start and end tags
An optional library of child rules.  These rules will be applied to any children of the given node before the default rules are applied.
An indication as to the ‘inline-ability’ of the given tag.  This controls the bracketing of the resulting markup with ‘\n’ characters.

The modified Converter now looks to apply rules in the following order
If the node is marked as a stopping point, no recursion proceeds on the branch.
If any over-ridden child rules exist for the given tag, those rules are applied and a memo is passed on to child nodes to denote the depth of the recursion.
Any default rules are processed as per the earlier versions of the code.  Note.  A prototype template is no longer used in favor of simple string construction.
The node itself is removed from the DOM.

function Converter( markupString, nestedRules, inline, textNode, memo ){

var startString, endString;
inline = inline ? ” : ‘\n’;
memo = memo ? memo : ”;
var children =  textNode.childElements();

if( typeof markupString == ‘object’){
startString = inline + markupString[0];
endString = markupString[1] + inline;
} else {
startString = inline + markupString;
endString = markupString + inline;
}

for( i in children){
if( typeof children[i] != ‘function’){
if( nestedRules && typeof nestedRules[children[i].tagName.toLowerCase()] == ‘function’){
startString =  memo.strip() + startString;
nestedRules[ children[i].tagName.toLowerCase() ]( children[i], startString);
} else if( typeof ConverterTable[children[i].tagName.toLowerCase()] == ‘function’){
ConverterTable[children[i].tagName.toLowerCase() ](children[i]);
} else { Converter( ”, nestedRules, true, children[i]), memo }
}
}
textNode.replace(  startString + textNode.innerHTML + endString  );
}

Converting Between Wiki Markup & HTML with Prototype

Posted by Don Albrecht

Wiki’s are amazing and powerful tools, unfortunately their dependence on specialized markup creates a huge barrier to their general adoption in many organizations.  This is a first step at building a wysiwyg editor for wiki markup.  While I will be focussing on the syntax unique to the popular MediaWiki platform, these techniques should be applicable to any wiki system.

The general flow of the converter is as follows:

  1. Converter is passed the root node of an html fragment to translate.
  2. Converter recurses through each of the child nodes and converts them.
  3. Root node tag is replaced with wiki markup.

There’s really only 2 key components involved in this first pass. A converter object and the recursive method.

The Converter Object

The converter object is little more than a collection of name value pairs.  The name corresponds to an html tag.  The value is a Prototype template to use in the direct replacement of the given node. By convention we’ll write all of the tag names for the converter object in lower case.

var Converter = {
strong: new Template("'''#{body}'''"),
b:  new Template("'''#{body}'''"),
em: new Template("''#{body}''"),
i:  new Template("''#{body}''"),
h1: new Template('=#{body}='),
h2: new Template('===#{body}=='),

h3: new Template(‘===#{body}===’),
h4: new Template(‘====#{body}====’),
h5: new Template(‘=====#{body}=====’),
h6: new Template(‘======#{body}======’)  }

The Converter Function

The Converter function always performs 2 checks before attempting to convert a given node.  First it ensures that the node is in fact a node and not a stray function from the Prototype enhanced object.  Next it verifies that a converter exists for the tag.  The toLowerCase() on the tagName is necessary due to the inconsistent behavior browsers demonstrate with this attribute.  While all browsers return the variable in all caps for traditional html, they are not reliable about returning lower case values for xhtml markup.

function convertToWiki( textNode ){
//make sure textNode isn't a function on the object
if( typeof textNode != 'function'){

//provide a way to stop execution on select sub trees
if( !textNode.hasClassName( 'stop')){
$(textNode).childElements().each( convertToWiki );
}

//make sure a converter exists for the given tag
if( liteConverter[ textNode.tagName.toLowerCase() ] ){

//replace the text node with a converted version of itself
textNode.replace( liteConverter[textNode.tagName.toLowerCase()]
.evaluate({body:textNode.innerHTML}));
} } }

WysiHat Prototype Based Rich Text Editor

Posted by Don Albrecht

37 Signals has recently announced a new open source rich text editor built on protoype.

It’s a unique take on the Rich Text Editor that focuses on developers over the kitchen sink.

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.

Check it out here:
 http://github.com/37signals/wysihat/tree/master

And Read the announcement here:
Introducing WysiHat: An eventually better open source WYSIWYG editor

Ajax24’s Drop Tabs. A Creative Take on The Tab Box for Scriptaculous

Posted by Don Albrecht

Tab Boxes are one of the most ubiquitous and popular of widgets. They pop up in everything from news sites to accounting software and for good reason. After all, tabs are one of the simplest and most efficient ways to cram more into a given block of screen real-estate than would fit otherwise.

Ajax24’s drop tabs replace the normal tab-box behavior concept with a twist. THese tabs pull blocks of content down from a tab bar to make them available and float them above the background content. (think window blinds or drawers as opposed to tabbed sheets of paper). I have a few reservations about the use of a widget with such slightly unconventional behavior. But all in all, the smooth motions of the widget and it’s novelty surely warrant exploration in more playful interfaces.

You can find the widget at

http://www.flash-free.org/en/2008/04/05/e24tabmenu-–-menu-desplegable-ajax/

Templates in Prototype

Posted by Don Albrecht

 As much as I love jQuery, prototype templates have made it into more than one of my projects because of their versatility and ease of use.  They are a capable and amazing tool for formatting and displaying output on the client side and I thought I’d take a few minutes to dive into them.

So what are templates.  In short they are a string with symbols embedded that are replaced at the time of evaluation to create a new string.  For example:

var apple = { fruit: "apple", variety: "honeycrisp" };

var templ = new Template( "My favorite fruit are #{variety} #{apple}s."  );

console.log(  templ.evalaluate( apple ));

>>> My favorite fruit are honeycrisp apples.

This basic example is really all there is to templates.  But, they can be incredibly useful for formatting and displaying JSON data. and repurposing things in universal ways across an app.

Widget.Blender Smooth Image Morphs For Prototype

Posted by Don Albrecht

Widget.Blender is a handy prototype class to smoothly animate a fade/morph transition between images

Features

  • Start & Stop can be triggered by events
  • Autosizing & Wrapping can be controlled
  • Ability to set a standard base url / dir for all images
  • Ability to start at any arbitrary image
  • Ability to run arbitrary function before blend (Useful for setting caption to display along with image)
  • Supported Browsers:
    • Firefox 2
    • Opera 9
    • IE 6
    • IE 7
    • Safari

Check out Widget.Blender at:

http://www.eternal.co.za/scripts/blender/index.html 

Making The Browser "Aware" of AJAX Requests

Posted by Don Albrecht

I recently discovered a fascinating prototype extension called LOAJAX. While the effect of the extension is a bit hard to describe, it’s immediately obvious when you try the demo’s with and without it. Basically, LOAJAX uses an iFrame crutch to make the browser display all of the interface elements associated with a page load.

How it works:

  1. A normal AJAX XMLHttpRequest is triggered by the AJAX application.
  2. LOAJAX creates a hidden iframe that points to a server script.
  3. The browser displays loading behavior while the iframe loads its source.
  4. The Server Script consists of a massive wait so the load never completes.
  5. When the XMLHttpRequest is completed, LOAJAX stops the iframe load and removes it from the DOM.
  6. The browser stops displaying page load indicators.

You can find more about LOAJAX and check out the demo here:

http://blog.loajax.com/

Proto.IPS A Fast and Easy Prototype Based Type In Place Combo Box

Posted by Don Albrecht

Prototype In Place Select

Meet Proto.IPS a fast and easy prototype based combo box modeled after the gMail Chat Widget.

Features:

  • Automatically saved when user clicks outside the widget (on blur)
  • Ability to select predefined or enter new value

You can find it at Perfection Kills

ProtoCorners: Simple Corner Styling for Prototype

Posted by Don Albrecht

Proto CornerAlright, so sometimes you need to throw a little extra style into a project, a bevel there, rounded corner here.  Proto.Corners allows you to simply generate them programatically. Get it at nurey.com

A New Version of Proto.Menu has landed

Posted by Don Albrecht

Proto.Menu .5
 Proto.Menu is an amazing prototype based context menu.  It’s packaged as a prototype extension and is quite honestly, one of the best ways to through a context menu into the mix on your next project.Features:  

  • iFrame Shim so IE6 plays nice
  • explicit z-Index control
  • Callbacks (“beforeShow”, “beforeHide”, “beforeSelect”)
  • Improved Callbacks for Menu Items
  • “className” option
  • Semantic Markup

You can find the new version here: http://thinkweb2.com/projects/prototype/2007/12/03/protomenu-gets-facelift/ P.S.Whether or not you use prototype in your development process, I encourage all of you to take a few minutes and read  Kangax’s excellent write up of the release.  It’s a valuable look into the decision process that went into making an excellent widget significantly better.