Walter - A WYSIWYG HTML editor that runs purely on JavaScript : Editor : GUI Components JAVASCRIPT DHTML TUTORIALS


JAVASCRIPT DHTML TUTORIALS » GUI Components » Editor »

 

Walter - A WYSIWYG HTML editor that runs purely on JavaScript




<html>
<head>
<title>Walter - A WYSIWYG HTML editor that runs purely on JavaScript</title>
<style>
#cursor {color: red; background-color: #ffdddd}
</style>
</head>
<body id="body"
  onload="load_walter();">
<div id="text">
     <p>This is a wysiwyg HTML-editor. You can write text directly into the browser window:</p>
     <p><span id="cursor">I</span>
     </p>
</div>
<hr />
<script language="JavaScript" type="text/javascript" >

/*
LICENSE

Walter is Open Source (http://www.opensource.org/)
You can freely use, copy and develop it in any way you see fit,
according to the following license (the MIT License):

Copyright (c) 2003 Henrik Ingo

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.

  WALTER - an in-browser WYSIWYG HTML editor written in JavaScript

  Walter will intercept your keystrokes and insert text to the webpage you
  are viewing in your broswer. The idea is to turn your browser into a
  WYSIWYG HTML editor.

  Main uses for Walter might be as a replacement for a <textarea> in
   - chats and bulletinboards
   - content management systems
  ...given that Linux IMHO currently has no WYsIWYG HTML-editors, I
  could see Walter becoming one. But let's not get carried away.

  MAIN PHILOSOPHY

  Main philosophy of Walter is:
    - the wysiwyg part is handled by the fact, that we are doing this in
      a browser
    - The W3C DOM allows any kind of manipulation of the HTML in a page
    - We just have to intercept keystrokes and commands from the user
      (this is a little tricky) and actually implementing the DOM manipulation
      (first release of walter already had 790 lines of JavaScript)

  CURRENT FEATURES

  Walter currently knows how to write and erase (backspace) text. Enter makes
  a new paragraph, shift+enter a br. Any inline tags can work (b, i, img, a)
  but only the most common are exposed as buttons.

  p and heading elements are supported, but not tables, lists or other "large"
  block elements.

  There is no support for mouse movements and also no other way of marking text.
  Thus bold and other effects can only be used while writing, you cannot format
  text afterwards. You can move with left and right arrows (only Opera on windows)
  up and down are not implemented.

  The current GUI is a simple auto-generated set of buttons that purposefully
  exposes the inner logic of walter. When more things work a real GUI needs to
  be built.

  MAIN CHALLENGES

  Altough the DOM is a great API, listening to keyboard and especially mouse
  events is not very standardised. Early experiences suggest that keystrokes
  will not be a problem, mouse-events might need some imagination (not tried
  yet). Non-characters (arrows, delete...) have different keycodes in
  different browsers, which will be a major challence.

  BROWSERS
  Walter works on the following browsers:

  IE4, NS4
  Will not work, we use DOM.

  IE5 and above
  As for JavaScript support, this will work on IE5 and above,
  but at least IE6 will crash after a few keystrokes. It simply
  can't take the pounding

  Mozilla and derivatives
  Works great

  Opera
  Works great
  Arrows and some other keys have different keycodes in Opera than in
  Moz and IE

  Konqueror 3.1.0
  Doesn't seem to do anything. Have not checked why this is.


  LICENSE

  Walter is Open Source (http://www.opensource.org/)
  You can freely use, copy and develop it in any way you see fit,
  according to the following license (the MIT License):

  Copyright (c) 2003 Henrik Ingo

  Permission is hereby granted, free of charge, to any person obtaining a
  copy of this software and associated documentation files (the "Software"),
  to deal in the Software without restriction, including without limitation
  the rights to use, copy, modify, merge, publish, distribute, sublicense,
  and/or sell copies of the Software, and to permit persons to whom the
  Software is furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included
  in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  IN THE SOFTWARE.

*/


// Developer section starts here //

// Known bugs
// - No point in even keeping track yet, a lot is simply missing
// The parts that exist should work though!

//TODO-list
//TODO: implement delete
//TODO: implement up and down arrows
//TODO: isn't right arrow and left arrow mirrors of each other? same with del and backspace?

//TODO: alt+b (html acceskey) for bold etc...
//TODO: make View HTML such that you can switch back to WYSIWYG
//TODO: format the HTML with nice indents and linebreaks before showing it
//TODO: also somehow remove empty elements that are sometimes left behind
//      and merge adjacent textnodes into one
//TODO: make it possible to mark text and apply formatting
//TODO: make it possible to use the mouse for that
//TODO: We might need a special "command mode" (like vi!)
//      because in Moz and IE keycodes for arrows etc...
//      overlap with characters
//      The other solution is to define a lot of buttons and
//      accesskeys for them (alt-l for left arrow etc...)
//TODO: make a nice GUI
//TODO: Make walter able to "hijack" a given textarea or to make any
//      other given (by id) element editable

//**********************************************************
//      Some common "constants"
//dom constants
var ELEMENT_NODE = 1;
var TEXT_NODE = 3;

var debug_mode = true;

//**********************************************************
//Supported elements

/* Walter divides HTML-elements into four groups.
   Inline elements are divided into *empty* elements
   and *inline* elements. "Empty elements" are those
   like <img> and <br>. It's an error to try to insert
   anything into an empty element (and the browser will
   let you know...). "Inline elements" are all the other
   inline elements like <b>, <i>, <a>...

   Block elements are divided into *paragraph* and *block*
   elements of which the latter are not yet supported.
   Paragraph elements are <p>, <h1> and so forth. Everything
   else are block elements.

   A lot of logic depends on a rule that the cursor will always
   be inside exactly one paragraph element (a <p> for instance).
   Obviously (it follows from the above rule and the HTML standard)
   all inline and empty elements must also be inside exactly one such
   element.

   You can add an element that is not supported simply by adding
   appropriate lines below. All creation and manipulation of
   elements relies on information from this elements-object.
   Even the GUI buttons are currently created automatically from that.
*/
var elements = new Object();
elements.Empty = new Array();
elements.Empty[0new Object();
//text to show on button or as a tooltip
elements.Empty[0].show = "image";
//when using image-type buttons, the url to the image
elements.Empty[0].image = "";
//the actual html element to insert
elements.Empty[0].tagname = "img";
//attributes that need to be set
elements.Empty[0].attributes = new Array();
elements.Empty[0].attributes[0new Object();
elements.Empty[0].attributes[0].name = "src";
elements.Empty[0].attributes[0].prompttext = "Give address of the image to be inserted:";
//optional attributes (some kind of "advanced" or "more" options) can be defined like this
elements.Empty[0].attributes[1new Object();
elements.Empty[0].attributes[1].name = "border";
elements.Empty[0].attributes[1].prompttext = "Width of border:";
elements.Empty[0].attributes[1].optional = true;

elements.Empty[1new Object();
elements.Empty[1].show = "br";
elements.Empty[1].tagname = "br";

elements.Empty[2new Object();
elements.Empty[2].show = "form input field";
elements.Empty[2].tagname = "input";
elements.Empty[2].attributes = new Array();
elements.Empty[2].attributes[0new Object();
elements.Empty[2].attributes[0].name = "type";
elements.Empty[2].attributes[0].prompttext =
    "What type of input field to insert? " +
    "(text, password, checkbox, radio, button, submit, reset):";
elements.Empty[2].attributes[1new Object();
elements.Empty[2].attributes[1].name = "name";
elements.Empty[2].attributes[1].prompttext =
    "Give the name of the element:";

elements.Inline = new Array();
elements.Inline[0new Object();
elements.Inline[0].show = " b ";
elements.Inline[0].tagname = "b";
elements.Inline[1new Object();
elements.Inline[1].show = " i ";
elements.Inline[1].tagname = "i";
elements.Inline[2new Object();
elements.Inline[2].show = " u ";
elements.Inline[2].tagname = "u";
elements.Inline[3new Object();
elements.Inline[3].show = "hyperlink (a href)";
elements.Inline[3].tagname = "a";
elements.Inline[3].attributes = new Array();
elements.Inline[3].attributes[0new Object();
elements.Inline[3].attributes[0].name = "href";
elements.Inline[3].attributes[0].prompttext = "Give the URL of this link:";
elements.Inline[4new Object();
elements.Inline[4].show = "anchor (a name)";
elements.Inline[4].tagname = "a";
elements.Inline[4].attributes = new Array();
elements.Inline[4].attributes[0new Object();
elements.Inline[4].attributes[0].name = "name";
elements.Inline[4].attributes[0].prompttext = "Give the name of this anchor:";

elements.Paragraph = new Array();
elements.Paragraph[0new Object();
elements.Paragraph[0].show = "Normal text";
elements.Paragraph[0].tagname = "p";
elements.Paragraph[1new Object();
elements.Paragraph[1].show = "Heading 1";
elements.Paragraph[1].tagname = "h1";
elements.Paragraph[2new Object();
elements.Paragraph[2].show = "Heading 2";
elements.Paragraph[2].tagname = "h2";
elements.Paragraph[3new Object();
elements.Paragraph[3].show = "Heading 3";
elements.Paragraph[3].tagname = "h3";
elements.Paragraph[4new Object();
elements.Paragraph[4].show = "Preformatted";
elements.Paragraph[4].tagname = "pre";



//****************************************************************************
//Create a table that functions as a lookup index to the elements[] table
var myElementsByTagName = new Array();
for(set in elements){
  for(i = 0; elements[set][i]; i++){
    myElementsByTagName[elements[set][i].tagname= i;
  }
}


//******************************************************************************
//Create a panel with buttons
//This panel is inserted at the place where the <script> element is in the html
document.write('<div id="walter_controls">'+
     '<p>This is the box that reads the letters you type. <br />' +
     'If nothing happens, click here and try again <br />' +
     '-><input type="text" id="walter_input" /></p>' +
     '<p><input type="button" value="View HTML" onclick="editor_viewHTML(this);" /></p>');

//This prints buttons to move left right etc...
document.write('<p><input type="button" value="&lt;-" onclick="cursor_move_left();" '
      'title="move left (alt+f)" accesskey="f" />'
      '<input type="button" value="-&gt;" onclick="cursor_move_right();" '
      'title="move right (alt+h)" accesskey="h" />'
      '</p>');


//This prints the buttons to create various elements
for(set in elements){
  document.write('<p>' + set + ' elements:<br />');
  for(i = 0; elements[set][i]; i++){
    document.write('<input type="button" value="' + elements[set][i].show +
                 '" onclick="' + set + '_clicked(' + i +');" />');
                 //notice the weird construction of the onclick handler above
                 //which is Empty_clicked() and Inline_clicked() and so on...
  }
  document.write('</p>');
}
document.write('</div>');



//******************************************************************************
//  FUNCTIONS START HERE

//  TABLE OF CONTENTS:
//        EDITOR MAIN FUNCTIONS
//        GENERALLY HELPFUL FUNCTIONS
//        RESPONSES TO THE DIFFERENT BUTTONS (mostly insert or toggle an element)
//        DELETIONS AND MOVEMENTS





//******************************************************************************
//        EDITOR MAIN FUNCTIONS

//Call this from <body onload=""> or whenever you want to start walter
function load_walter(){
  //register event listeners
  //TODO: There might be browsers that require this to be done
  //on the input-element instead
  document.getElementById('body').onkeypress=editor;
  document.getElementById('body').onkeydown=editor_specialkeys;

  //TODO: We would also want to insert the cursor automatically here
  //and perhaps take the editable elements id (inside which the cursor needs to be)
  //as an argument

  //move focus to the input box
  document.getElementById('walter_input').focus();
}


//This function gets called when someone presses a key in the input box
//Here we do the main job of deciding what to do
function editor(e)
{
  var code;
  //look for the keycode in different places for IE and other browsers
  if (!evar e = window.event;
  if (e.keyCodecode = e.keyCode;
  else if (e.whichcode = e.which;

//  alert(e.DOM_VK_LEFT);
  //alert(code);

  //if ctrl or alt are down, it's not counted as writing
  //some browsers (opera) report the actual keydown of shift as a keypress-event too
  //and that is also not counted as writing (shift is not a character in it self!)
  if(e.altKey || e.ctrlKey || isSpecialKey(code)){
    document.getElementById('walter_input').value = '';
    return false;
  }

  //Did he press enter?
  if(code == 13){
    //was it just enter or maybe shift+enter?
    if(e.shiftKey){
      Empty_clicked(myElementsByTagName['br']);
    }else{
      newParagraph('p');
    }
  }
  else{
    var character = String.fromCharCode(code);

    var cursor = document.getElementById('cursor');
    var ins = document.createTextNode(character);
    cursor.parentNode.insertBefore(ins, cursor);
    if(cursor.parentNode.normalize)
      //removes multiple spaces etc...
      cursor.parentNode.normalize();
  }


  //prevent the character from actually showing up in the input-box
  document.getElementById('walter_input').value = '';
  return false;
}

function editor_specialkeys(e){
  var code;
  //look for the keycode in different places for IE and other browsers
  if (!evar e = window.event;
  if (e.keyCodecode = e.keyCode;
  else if (e.whichcode = e.which;

  //check for different keys and do stuff
  if(code == 8)
    key_backsp();
}


//**********************************************************************
//        GENERALLY HELPFUL FUNCTIONS

//TODO: I should probably think through the handling of these special characters
//once more.
//The big numbers occur in Opera, the small in IE and Moz.
function isSpecialKey(code){
  //in order of appearance:
  // shift,                         backspace,
  if(code == 16 || code == 57389 || code == 8)
    return true;

  return false;
}


//Paragraph elements are those that are defined in the elements.Paragraph[]
//array (p, h1 etc...).
function isParagraphElement(e){
  for(var i = 0; elements.Paragraph[i]; i++){
    if(elements.Paragraph[i].tagname.toLowerCase() == e.nodeName.toLowerCase()){
      return true;
    }
  }
  return false;
}

//returns the previousSibling node
//but skips textnodes that are empty
//if cursor is the firstChild (not counting empty textnodes) null is returned
function getPreviousSiblingNode(cursor){
  //Problem: Between any two elements there seems to always exist a textnode, so
  //previousSibling is not false, even if we think we are the first element
  //solution: skip empty non-elements
  var prev = cursor.previousSibling;
  while( (prev&& prev.nodeType != ELEMENT_NODE && (!prev.nodeValue) ){
    prev = prev.previousSibling;
  }
  return prev;
}


function getNextSiblingNode(cursor){
  //Problem: Between any two elements there seems to always exist a textnode, so
  //nextSibling is not null, even if we think we are the first element
  //solution: skip empty non-elements
  var nextE = cursor.nextSibling;
  while( (nextE&& nextE.nodeType != ELEMENT_NODE && (!nextE.nodeValue) ){
    nextE = nextE.nextSibling;
  }
  return nextE;
}

//**********************************************************************
//        RESPONSES TO THE DIFFERENT BUTTONS (mostly insert or toggle an element)

// note that the naming of the *_clicked functions corresponds to the name
// in the elements.* collection

//this function toggles inline elements (like b or i) on or off
function Inline_clicked(i){
  var cursor = document.getElementById('cursor');
  var doclosing = false;

  //find out whether we are closing an element or opening
  //browse through parents until we get to <p>
  var lookup = cursor;
  while(!isParagraphElement(lookup.parentNode&& !doclosing){
    if(lookup.parentNode.nodeName.toLowerCase() == elements.Inline[i].tagname.toLowerCase()){
      doclosing = true;
    }
    lookup.chainToClosing = lookup.parentNode;
    var temp = lookup;
    lookup = lookup.parentNode;
    lookup.chainToCursor = temp;
  }

  if(doclosing){
    Inline_close(i, cursor, lookup);
  }else{
    Inline_open(i, cursor);
  }

  //move focus to the input box
  document.getElementById('walter_input').focus();
}

function Inline_close(i, cursor, lookup){
  //in case the element we are closing isn't the innermost one
  //we need to remember all elements between it and the cursor first
  //then get outside the actual element and finally reopen all the others again
  //this information is contained in lookup

  //move cursor behind the closing element
  cursor = cursor.parentNode.removeChild(cursor);
  if(lookup.nextSibling)
    lookup.parentNode.insertBefore(cursor, lookup.nextSibling);
  else
    lookup.parentNode.appendChild(cursor);

  //then reopen any elements that were open between the cursor and closing element
  var clone = lookup.chainToCursor;
  while(clone != cursor){
    var newE = clone.cloneNode(false);
    cursor.parentNode.insertBefore(newE, cursor);
    cursor = cursor.parentNode.removeChild(cursor);
    newE.appendChild(cursor);
    clone = clone.chainToCursor;
  }
}

function Inline_open(i, cursor){
  var parent = cursor.parentNode;
  var newE = document.createElement(elements.Inline[i].tagname);
  setElementAttributes(newE, elements.Inline[i]false);
  if(cursor.nextSibling)
    cursor.parentNode.insertBefore(newE, cursor.nextSibling);
  else
    cursor.parentNode.appendChild(newE);
  //move cursor to the new node
  cursor = parent.removeChild(cursor);
  newE.appendChild(cursor);
}

//This function adds empty elements (like br or img) to the cursor position
function Empty_clicked(i){

  var cursor = document.getElementById('cursor');
  var parent = cursor.parentNode;
  var newE = document.createElement(elements.Empty[i].tagname);
  setElementAttributes(newE, elements.Empty[i]false);
  parent.insertBefore(newE, cursor);


  //move focus to the input box
  document.getElementById('walter_input').focus();
}

function Paragraph_clicked(i){
  newParagraph(elements.Paragraph[i].tagname);
}


function setElementAttributes(DOMelement, OURelement, setOptional){
  for(var i=0; OURelement.attributes && OURelement.attributes[i]; i++){
    if(OURelement.attributes[i].optional){
      if(!setOptional){
        break;
      }
    }
    DOMelement.setAttribute(OURelement.attributes[i].name,
                prompt(OURelement.attributes[i].prompttext, "",
                      "Set attribute: " + OURelement.attributes[i].name));
  }
}

function newParagraph(tagname){
  var cursor = document.getElementById('cursor');

  //find out whether there are inline elements between cursor and p
  //that need to be closed now and reopened in the next p
  var p = cursor;
  while(!isParagraphElement(p)){
    p.chainToP = p.parentNode;
    var temp = p;
    p = p.parentNode;
    p.chainToCursor = temp;
  }

  //Make a new paragraph element
  var newP = document.createElement(tagname);
  if(p.nextSibling)
    p.parentNode.insertBefore(newP, p.nextSibling);
  else
    p.parentNode.appendChild(newP);

  //move cursor to the new node
  cursor = cursor.parentNode.removeChild(cursor);
  newP.appendChild(cursor);

  //then reopen any elements that were open between the cursor and closing element
  var clone = p.chainToCursor;
  while(clone != cursor){
    var newE = clone.cloneNode(false);
    cursor.parentNode.insertBefore(newE, cursor);
    cursor = cursor.parentNode.removeChild(cursor);
    newE.appendChild(cursor);
    clone = clone.chainToCursor;
  }
}

function editor_viewHTML(button){
  var cursor = document.getElementById('cursor');
  //cursor = cursor.parentNode.removeChild(cursor);

  var textdiv = document.getElementById('text');
  var contents = textdiv.innerHTML;
  while(textdiv.hasChildNodes()){
    textdiv.removeChild(textdiv.lastChild);
  }
  var newE = document.createElement('textarea');
  newE.rows = 10; newE.cols = 60;
  textdiv.appendChild(newE);
  newE.value = contents;
}

//**********************************************************************
//        DELETIONS AND MOVEMENTS


//function that deletes something to the left of the cursor...
function key_backsp(){
  var cursor = document.getElementById('cursor');
  var prev;

  //Start with positioning the cursor so
  //that there is something to the left of it to delete

  //if we are the first child of a node, there is no previousSibling.
  //example: abc<b>[cursor]abc</b>abc
  //solution for inline elements: just position yourself outside of them (before them)
  prev = getPreviousSiblingNode(cursor);
  while( (!prev&& (!isParagraphElement(cursor.parentNode)) ){
    var e = cursor.parentNode;
    cursor = e.removeChild(cursor);
    e.parentNode.insertBefore(cursor, e);

    prev = getPreviousSiblingNode(cursor);
  }

  //solution when you are the first child of a paragraph: move to end of previous
  //example: ...abc</p><p>[cursor]abc...
  while( (!prev&& isParagraphElement(cursor.parentNode)){
    var p = cursor.parentNode;

    //Watch out for textnodes (and other garbage?) between
    //Find the previous p, it's not necessarily previousSibling
    //TODO: This will skip <hr> and other block-elements, when they are implemented
    prev = p.previousSibling;
    while(!isParagraphElement(prev)){
      prev = prev.previousSibling;
      if(!prev){
        if(debug_modealert('we are now at the beginning of this document');
        return;
      }
    }

    cursor = p.removeChild(cursor);
    prev.appendChild(cursor);

    //In fact, when moving to the end of the previous paragraph, in the users
    //mind we have deleted one "enter", so that's all for now!
    return;
  }

  //And if the cursor is immediately behind an inline-element
  //like this: abc<b>abc</b>[cursor]abc
  //we have to move it so that it's inside that element
  prev = getPreviousSiblingNode(cursor);
  whileprev && prev.nodeType == ELEMENT_NODE ){
    //It's an error to try to move inside an empty element (like br or img)
    //Instead, the user probably expects that element to disappear
    //Check for empty elements here
    for(var i = 0; elements.Empty[i]; i++){
      if(prev.tagName.toUpperCase() == elements.Empty[i].tagname.toUpperCase()){
        prev.parentNode.removeChild(prev);
        //that was a deletion, no need to continue
        document.getElementById('walter_input').focus();
        return;
      }
    }

    //Not an Empty-element, so it's an Inline-element
    cursor = cursor.parentNode.removeChild(cursor);
    prev.appendChild(cursor, prev);
    prev = getPreviousSiblingNode(cursor);
  }

  //Last problem: If we landed inside an empty inline element in the previous
  //phase, (example: from aaa<b></b>[cursor]aaa to aaa<b>[cursor]</b>aaa)
  //there still isn't anything to delete to the left of cursor.
  //Easiest solution is by recursion: start all over again...
  prev = getPreviousSiblingNode(cursor);
  if(!prev){
    key_backsp();
    //But now we have already deleted a character, in the topmost recursion
    //so that's it for now
    return;
  }

  //This is the actual deletion. We should now be in a position where this is trivial
  //prev = cursor.previousSibling;
  prev = getPreviousSiblingNode(cursor);
  if(prev){
    if(prev.nodeType == TEXT_NODE){
      prev.nodeValue = prev.nodeValue.substring(0,prev.nodeValue.length -1);

      //TODO: If there are multiple whitespace characters after each other
      //they will only look like one in the browser but they will be deleted
      //separately, giving an impression that nothing is happening until the last
      //whitespace is deleted. Solution: Either prohibit the existence of
      //multiple whitespace or add some extra checks here
    }
  }

  //TODO: Now we are leaving behind lot's of empty elements
  //They are not really disturbing anyone, but sooner or later
  //we'll have to clean up

  //move focus to the input box
  document.getElementById('walter_input').focus();
}

//TODO: key_backsp() shares a lot of functionality with this. They could
//share a lot of code. same goes for cursor_move_right() et al...
function cursor_move_left(){
  var cursor = document.getElementById('cursor');
  var prev;

  //We might have to move left several times before we get to something that
  //actually looks like the cursor is moving in the eyes of the user
  //text and empty elements count as movements, moving around other tags don't

  //A lot of this is similar to what happens in key_backsp()

  //if we are the first child of a node, there is no previousSibling.
  //example: abc<b>[cursor]abc</b>abc
  //solution for inline elements: just position yourself outside of them (before them)
  prev = getPreviousSiblingNode(cursor);
  while( (!prev&& (!isParagraphElement(cursor.parentNode)) ){
    var e = cursor.parentNode;
    cursor = e.removeChild(cursor);
    e.parentNode.insertBefore(cursor, e);

    prev = getPreviousSiblingNode(cursor);
  }

  //solution when you are the first child of a paragraph: move to end of previous
  //example: ...abc</p><p>[cursor]abc...
  while( (!prev&& isParagraphElement(cursor.parentNode)){
    var p = cursor.parentNode;

    //Watch out for textnodes (and other garbage?) between
    //Find the previous p, it's not necessarily previousSibling
    //TODO: This will skip <hr> and other block-elements, when they are implemented
    prev = p.previousSibling;
    while(!isParagraphElement(prev)){
      prev = prev.previousSibling;
      if(!prev){
        //if(debug_mode) alert('we are now at the beginning of this document');
        return;
      }
    }

    cursor = p.removeChild(cursor);
    prev.appendChild(cursor);

    //In fact, when moving to the end of the previous paragraph, in the users
    //mind we did move, so that's all for now!
    return;
  }

  //And if the cursor is immediately behind an inline-element
  //like this: abc<b>abc</b>[cursor]abc
  //we have to move it so that it's inside that element
  prev = getPreviousSiblingNode(cursor);
  whileprev && prev.nodeType == ELEMENT_NODE ){
    //It's an error to try to move inside an empty element (like br or img)
    //Instead, we should move past it
    //Check for empty elements here
    for(var i = 0; elements.Empty[i]; i++){
      if(prev.tagName.toUpperCase() == elements.Empty[i].tagname.toUpperCase()){
        cursor.parentNode.removeChild(cursor);
        prev.parentNode.insertBefore(cursor, prev);
        //that was a movement, no need to continue
        document.getElementById('walter_input').focus();
        return;
      }
    }

    //Not an Empty-element, so it's an Inline-element
    cursor = cursor.parentNode.removeChild(cursor);
    prev.appendChild(cursor, prev);
    prev = getPreviousSiblingNode(cursor);
  }

  //Last problem: If we landed inside an empty inline element in the previous
  //phase, (example: from aaa<b></b>[cursor]aaa to aaa<b>[cursor]</b>aaa)
  //there still isn't anything to the left of cursor.
  //Easiest solution is by recursion: start all over again...
  prev = getPreviousSiblingNode(cursor);
  if(!prev){
    cursor_move_left();
    //But now we have already moved, in the topmost recursion
    //so that's it for now
    return;
  }

  //This is the actual movement. We should now be in a position where this is trivial
  //prev = cursor.previousSibling;
  prev = getPreviousSiblingNode(cursor);
  if(prev){
    if(prev.nodeType == TEXT_NODE){
      //what's the last character in the text to our left
      var oneCharacter = prev.nodeValue.substring(
                         prev.nodeValue.length -1, prev.nodeValue.length);
      //remove it
      prev.nodeValue = prev.nodeValue.substring(0,prev.nodeValue.length -1);
      //and re-insert it after the cursor
      var e = document.createTextNode(oneCharacter);
      if(cursor.nextSibling){
        cursor.parentNode.insertBefore(e, cursor.nextSibling);
      }else{
        cursor.parentNode.appendChild(e);
      }

      //TODO: If there are multiple whitespace characters after each other
      //they will only look like one in the browser but they will be deleted
      //separately, giving an impression that nothing is happening until the last
      //whitespace is deleted. Solution: Either prohibit the existence of
      //multiple whitespace or add some extra checks here
    }
  }
  //move focus to the input box
  document.getElementById('walter_input').focus();
}

function cursor_move_right(){
  var cursor = document.getElementById('cursor');
  var nextE;

  //We might have to move right several times before we get to something that
  //actually looks like the cursor is moving in the eyes of the user
  //text and empty elements count as movements, moving around other tags don't

  //This function is like cursor_move_left() all backwards

  //if we are the last child of a node, there is no nextSibling.
  //example: abc<b>abc[cursor]</b>abc
  //solution for inline elements: just position yourself outside of them (after them)
  nextE = getNextSiblingNode(cursor);
  while( (!nextE&& (!isParagraphElement(cursor.parentNode)) ){
    var e = cursor.parentNode;
    cursor = e.removeChild(cursor);
    if(e.nextSibling){
      e.parentNode.insertBefore(cursor, e.nextSibling);
    }else{
      e.parentNode.appendChild(cursor);
    }

    nextE = getNextSiblingNode(cursor);
  }

  //solution when you are the last child of a paragraph: move to beginning of next
  //example: ...abc[cursor]</p><p>abc...
  while( (!nextE&& isParagraphElement(cursor.parentNode)){
    var p = cursor.parentNode;

    //Watch out for textnodes (and other garbage?) between
    //Find the previous p, it's not necessarily previousSibling
    //TODO: This will skip <hr> and other block-elements, when they are implemented
    nextE = p.nextSibling;
    while(!isParagraphElement(nextE)){
      nextE = nextE.nextSibling;
      if(!nextE){
        //if(debug_mode) alert('we are now at the end of this document');
        return;
      }
    }

    cursor = p.removeChild(cursor);
    if(nextE.firstChild){
      nextE.insertBefore(cursor, nextE.firstChild);
    }else{
      nextE.appendChild(cursor);
    }

    //In fact, when moving to the beginning of the next paragraph, in the users
    //mind we did move, so that's all for now!
    return;
  }

  //And if the cursor is immediately before an inline-element
  //like this: abc[cursor]<b>abc</b>abc
  //we have to move it so that it's inside that element
  nextE = getNextSiblingNode(cursor);
  whilenextE && nextE.nodeType == ELEMENT_NODE ){
    //It's an error to try to move inside an empty element (like br or img)
    //Instead, we should move past it
    //Check for empty elements here
    for(var i = 0; elements.Empty[i]; i++){
      if(nextE.tagName.toUpperCase() == elements.Empty[i].tagname.toUpperCase()){
        cursor.parentNode.removeChild(cursor);
        if(nextE.nextSibling){
          nextE.parentNode.insertBefore(cursor, nextE.nextSibling);
        }else{
          nextE.parentNode.appendChild(cursor);
        }
        //that was a movement, no need to continue
        document.getElementById('walter_input').focus();
        return;
      }
    }

    //Not an Empty-element, so it's an Inline-element
    cursor = cursor.parentNode.removeChild(cursor);
    if(nextE.firstChild){
      nextE.insertBefore(cursor, nextE.firstChild);
    }else{
      nextE.appendChild(cursor);
    }
    nextE = getNextSiblingNode(cursor);
  }

  //Last problem: If we landed inside an empty inline element in the previous
  //phase, (example: from aaa[cursor]<b></b>aaa to aaa<b>[cursor]</b>aaa)
  //there still isn't anything to the right of cursor.
  //Easiest solution is by recursion: start all over again...
  nextE = getNextSiblingNode(cursor);
  if(!nextE){
    cursor_move_right();
    //But now we have already moved, in the topmost recursion
    //so that's it for now
    return;
  }

  //This is the actual movement. We should now be in a position where this is trivial
  //prev = cursor.previousSibling;
  nextE = getNextSiblingNode(cursor);
  if(nextE){
    if(nextE.nodeType == TEXT_NODE){
      //what's the first character in the text to our right
      var oneCharacter = nextE.nodeValue.substring(01);
      //remove it
      nextE.nodeValue = nextE.nodeValue.substring(1,nextE.nodeValue.length);
      //and re-insert it before the cursor
      var e = document.createTextNode(oneCharacter);
      cursor.parentNode.insertBefore(e, cursor);

      //TODO: If there are multiple whitespace characters after each other
      //they will only look like one in the browser but they will be deleted
      //separately, giving an impression that nothing is happening until the last
      //whitespace is deleted. Solution: Either prohibit the existence of
      //multiple whitespace or add some extra checks here
    }
  }
  //move focus to the input box
  document.getElementById('walter_input').focus();
}




</script>

</body>
</html>

           
       



-

Leave a Comment / Note


 
Verification is used to prevent unwanted posts (spam). .

Follow Navioo On Twitter

JAVASCRIPT DHTML TUTORIALS

 Navioo GUI Components
» Editor