How to make a real-time in-browser editor with the HTML5′s contenteditable attribute

Lots of fun here. Some days ago I just read a very cool comment on html5doctor:

Here is a fun example with the contenteditable attribute.

Just paste this data-url to your browser and then edit the title or the style of the whole page

data:text/html,<title contenteditable>Hello World</title> <style contenteditable>head, title, style {display: block;}</style>

Another thing is that you can create a notepad with just one short url:

data:text/html,<html contenteditable></html>

Pretty cool I think.

Cat with eyes shining bright This just made my eyes shine brighter than ever. I think there’s a lot of potential here: do you imagine how many things you could realize with the contenteditable attribute?

For example, you can even do this:

script {
  display: block;
}

The result? A JavaScript in-browser editor.


Can I really build an HTML5 editor in my browser?

Absolutely. This tutorial is focused on how to build a simple but powerful editor, directly within your browser, making it possible to edit your page content in real time. It may sound like a lot of work, but don’t worry: actually it’s easier than it seems, for two main reasons:

  1. The browser already shows content in real time. When you open Firebug on Firefox, Chrome DevTools, Opera Dragonfly, or whatever, and you edit the CSS or JS, the browser automatically re-renders its window.
  2. You don’t need any parser. Again, and unsurprisingly, the browser is already capable to interpret your code.

In fewer words, this means you already have the tools. Just use your imagination to build something awesome.

In this tutorial I won’t talk about everything, but only of the problems I’ve encountered while building an editor, and how to solve them.

Displaying the <script> and <style> tags

This is actually very simple. You only need to match them by CSS, and apply display: block to them. For example:

style, script {
  display: block;
}

However I’d recommend to apply this rule only to the elements that have the contenteditable attribute. You can do this with:

[contenteditable] { 
  /* will match all elements with contenteditable attribute */
  display: block;
}

How to make it look like real code

Real editors use monospace fonts. We can also make <script> and <style> behave like the <pre> tag. All we need is the following code.

style, script {
  font-family: monospace;  /* monospace font */
  white-space: pre;        /* behave like <pre> */
}

You can even install a syntax highlighter like the Google code prettify, if you want.

Make the page title editable

This one is real fun. It’s ridicolously easy to show the title directly in the browser, but pay attention because the <title> tag is inside <head>, that is hidden by default! So you must display the title and the head, as a block:

head, title {
  display: block;
}

Then just make it contenteditable and you’re done.

<title contenteditable>The page title</title>

Executing the JavaScript in real time

Now the tricky part. Your scripts actually get executed only the first time, on page load. So the question is, how can we re-execute the JavaScript every time it changes?

Well, I’m sure there are many solutions. Mine is quite straightforward: I dynamically create a new <script> element every time the user adds something new. For the sake of simplicity I’ve created this function:

function executeCode() {
  var script = document.createElement("script");
  script.innerHTML = js.innerHTML;
  js.parentNode.insertBefore(script, js);
}
// the code we want to execute is contained here:
var js = document.getElementById('js');

Why I’ve put the js variable outside of the function? You’ll find it out soon.

We need to call the executeCode() function during an event in order make it work properly. I think the onkeyup event will be perfect in this situation: it gets fired as soon as the user has finished typing.

js.onkeyup = function(event) {
  executeCode();
};

However, this approach has a flaw. What if I type, say, alert('foobar')? I won’t see an alert, but… 15 alerts! This because the onkeyup event would get fired 15 times in this case — one for each character. How can we solve this problem?

Again, there can be many solutions. I chose to use window.setTimeout(). My implementation is fairly simple: I just tell the browser to wait 2000 milliseconds (2 seconds) before executing the new code, but if the user modifies the code in the meanwhile, I reset the timer. This is the key to prevent the code getting executed more than once.

Here’s a full example, feel free to copy-paste and try it directly in your browser:

<h1>Sample JavaScript real-time in-browser execution</h1>

<script id="js" style="display: block" contenteditable>
alert('foo'); // edit me!
</script>

<script>
(function() {

  var timer,
      js = document.getElementById('js'),
      delay = 2000;

  js.onkeyup = function(event) {
  
    if (typeof timer != "undefined") {

      clearTimeout(timer);
      timer = 0;
    }

    timer = setTimeout(executeCode, delay);
  };

 function executeCode() {
    var script = document.createElement("script");
    script.innerHTML = js.innerHTML;
    js.parentNode.insertBefore(script, js);
 }

})();
</script>

It’s your turn now!

I just demonstrated that it’s definitely possible to build an HTML5 editor that works directly in your browser. Imagine a full-featured WYSIWYG in-browser editor: it could potentially improve your productivity, enabling real-time collaboration and a lot more. Your only limit is your imagination.

Need inspiration?

Demo

|

Download

js

Git cheat sheet

Git is an awesome tool for developers, but can be a bit hard to grasp at a first glance. Fortunately, the concepts you need to learn to be immediately productive are very few: I’ll briefly illustrate them in this Git cheat sheet.

1. Basics

# start a Git repository from scratch
$ git init

# copy an existing repository into the current directory
$ git clone https://github.com/username/repository.git

$ git status  # check current status

2. Snapshotting

# Add files to staging area
$ git add filename  # add a single file
$ git add .         # add all files, but not deleted ones
$ git add --all     # add everything

# Stashing takes the current state of the working directory and
# puts it on a stack for later
$ git stash        # add current changes to the stack
$ git stash list   # see what's in the stack
$ git stash apply  # bring back the saved changes

3. Committing

$ git commit            # open the text editor (usually vi)
$ git commit -a         # automatically stage modified files
$ git commit -m "foo"   # commit with message "foo"
$ git commit -am "foo"  # both stage files and commit with message "foo"

# View commits log (in a pretty way)
$ git log --oneline --decorate --graph

4. Managing remotes

$ git remote add origin https://github.com/user/repo.git
# You can also add your GitHub username and password on the remote URL:
$ git remote add origin https://user:password@github.com/user/repo.git
$ git remote rm origin  # removes the `origin` remote

5. Pushing

$ git push -u origin master
# -u here tells git to remember the parameters 
# so that next time we can simply run:
$ git push

6. Branching

$ git checkout -b new_branch
# -b is to checkout and create a branch at the same time.
# This is the same thing as doing:
$ git branch new_branch
$ git checkout new_branch

7. Merging

$ git checkout master   # return to master branch
$ git merge foobar      # merge `master` branch with `foobar` branch 
$ git branch -d foobar  # delete branch (optional)

8. Tagging

$ git tag -a v1.3.37               # tag the HEAD (most recent commit)
$ git tag -a v0.6b f49a23c         # tag the commit with SHA `f49a23c`
$ git tag -a v4.2 -m "jelly bean"  # append a message

That’s all, folks. I know I could have explained much more every single command, but that’s not the point of this article. I just wanted to give you a quick-start pragmatic reference; in fact, these are the commands I personally use more frequently.

Do you think some very useful commands are missing in this cheat sheet? Leave a reply.

  • Update march 5: added tagging.
  • Update april 23: just made some “refactoring” and added git stash.
git

onclick vs addEventListener

What’s the difference between these two lines of code?

element.onclick = function() { /* do stuff */ }
element.addEventListener('click', function(){ /* do stuff */ }, false);

They apparently do the same thing: listen for the click event and execute a callback function. Nevertheless, they’re not equivalent. If you ever need to choose between the two, this could help you to figure out which one is the best for you.

The main difference is that onclick is just a property, and like all object properties, if you write on more than once, it will be overwritten. With addEventListener() instead, we can simply bind an event handler to the element, and we can call it each time we need it without being worried of any overwritten properties.

In first place I was tempted to keep using onclick, because it’s shorter and looks simpler… and in fact it is. But I don’t recommend using it anymore. It’s just like using inline JavaScript. Using something like <button onclick="doSomething()">that‘s inline JavaScript – is highly discouraged nowadays (inline CSS is discouraged too, but that’s another topic).

However, the addEventListener() function, despite it’s the standard, just doesn’t work in old browsers (Internet Explorer below version 9), and this is another big difference. If you need to support these ancient browsers, you should follow the onclick way. But you could also use jQuery (or one of its alternatives): it basically simplifies your work and reduces the differences between browsers, therefore can save you a lot of time.

js

How to setup OS X 10.8 for Ruby on Rails

Looks like almost every Rails developer is using OS X as development environment, so in this brief walkthrough I’ll explain you how to prepare your machine for Ruby on Rails development: nothing more, nothing less. I assume you are already running Mac OS X 10.8 Mountain Lion.

Install Command Line Tools for Xcode

Download it from developer.apple.com (you need an Apple ID).

As an alternative you can use osx-gcc-installer or install it via the Xcode GUI.

Install Homebrew

$ ruby -e "$(curl -fsSkL raw.github.com/mxcl/homebrew/go)"

Install RVM (Ruby Version Manager)

You can:
  1. Download and install JewelryBox
  2. Or from the command line:
    $ curl -L https://get.rvm.io | bash -s stable --ruby

Install and configure Git

You can:
  1. Get the latest version from the official website
  2. Or install it via Homebrew:
    $ brew install git
$ git config --global user.name "Your Name"
$ git config --global user.email "your@email.com"

Install Ruby via RVM

$ rvm install ruby-2.0.0

Install Rails via RubyGem

Notice: you may need to restart your terminal session before installing Rails.

$ gem install rails -v 3.2.13

And you’re ready to ride Ruby on Rails! Yee-ha!

Problems? Suggestions? Leave a comment.

ror

101 Web Socket Protocol Handshake

So you want to set up a web socket server, but you don’t know how. Maybe you just landed here after a bunch of Google searches. Well, keep reading: you’re in the right place.

The Web Socket in a nutshell: a pragmatic guide

The new protocol is revolutionizing the whole Internet.

The Web Socket protocol is the new alternative to the very popular HTTP protocol. The logic of the latter is well known: the client requests, the server responds. Request, response. Stop. This is what we call a simplex connection. It worked for decades, but has severe limitations therefore it’s not ideal for rich web applications, which would work better under a persistent connection. We need to serve content in real time; that’s why the new protocol is born.

The WebSocket is awesome, especially if your goal is to build a chat, a VoIP server, or even a RTS game! Sounds good, huh? Let’s see how it works.

Roll your own Web Socket server and client

This guide is focused on the official W3C’s WebSocket API specification for the client part; we’ll use a Node.js WebSocket implementation as the server. If you’re curious on how Node.js works, just check it out: there are tons of resources out there.

Okay, let’s get started with the client: nothing fussy, It’s just a simple HTML page. Call it index.html.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>WebSocket Client</title>
</head>
<body>
  <h1>WebSocket Client</h1>
  <p>Open the JavaScript console to see the response!</p>
  <form>
    <label for="message">Send a message</label>
    <input id="message" name="message" type="text">
    <button id="send" name="send">Send</button>
  </form>
  <script src="ws_client.js"></script>
</body>
</html>

You may have noticed the script tag:

<script src="ws_client.js"></script>

Of course we need a bit of JavaScript in order to make it work, but don’t worry! Initializing a web socket server is just as simple as the following line of code. Create the file ws_client.js and write:

var ws = new WebSocket("ws://localhost:1337");

If you’re already familiar with object-oriented programming, you should know we have been built a new instance of the WebSocket object, that’s built-in in all modern browsers. The ws://localhost:1337 part just tells the WebSocket API to initialize a new connection on localhost:1337 using the ws protocol.

Now let’s code some event handlers. I won’t elaborate, they’re self-descriptive:

ws.onopen = function(ev) {
  console.log('Connection opened.');
}
ws.onmessage = function(ev) {
  console.log('Response from server: ' + ev.data);
}
ws.onclose = function(ev) {
  console.log('Connection closed.');
}
ws.onerror = function(ev) {
  console.log('An error occurred. Sorry for that.');
}

Since we want to send a message to the server, we should use the WebSocket.send() function; but it doesn’t have a callback return value, so I’ll define a new function, sendMessage(), that does exactly the same plus logging the message on the console.

WebSocket.prototype.sendMessage = function(msg) {
  this.send(msg);
  console.log('Message sent: ' + msg);
}

Finally I get the button to work by attaching an event handler to it:

var sendBtn = document.getElementById('send');
sendBtn.addEventListener('click', function(ev) {
  var message = document.getElementById('message').value;
  ws.sendMessage(message);
  ev.preventDefault();
});

Basically, when we click on the button we send a message to the server. That’s it. You may wonder what does ev.preventDefault() do; it just makes sure that when we click the Send button, the form doesn’t get submitted.


At this stage you should have downloaded and installed Node.js: the procedure is slightly different for every operating system; just make sure to download the right installer.

Node comes with npm, the official package manager, that makes the WebSocket-Node package installation ridiculously easy:

$ npm install websocket

This shell command should install the WS implementation for Node.js on your machine. Now open the Node installation folder (if you don’t know where it is and you’re using a UNIX-based operating system, try which node) and create the file that will host our server:

$ cd ~/local/node
$ touch ws_server.js

Since this file will be executed by Node itself, it must start with the following:

#!/usr/bin/env node

Require the WS server and the HTTP protocol APIs:

var WebSocketServer = require('websocket').server;
var http = require('http');

Then you can define the HTTP server itself:

var server = http.createServer(function(request, response) {
  console.log('Received request from ' + request.url);
  response.writeHead(404);
  response.end();
});

The server must be listening on a port. I’ve chosen the 1337 port, but it can be almost anything.

server.listen(1337, function() {
    console.log('Server is listening on port 1337.');
});

Our WebSocket server is based on the HTTP server we have just created above, with a bit of security rules:

wsServer = new WebSocketServer({
    httpServer: server,
    autoAcceptConnections: false // because security matters
});

The autoAcceptConnections parameter is absolutely necessary here, because we don’t want to allow connections from any source domain! That’s why I wrote a custom function that accepts or discards an incoming remote connection: it accepts only requests from 127.0.0.1 or http://localhost, but you can of course allow any origin you want.

function isAllowedOrigin(origin) {
  valid_origins = ['http://localhost', '127.0.0.1'];
  if (valid_origins.indexOf(origin) != -1) { // is in array
    console.log('Connection accepted from origin ' + origin);
    return true;
  }
  return false;
}

This way we can easily filter connections based on the origin:

wsServer.on('request', function(request) {
  var connection = isAllowedOrigin(request.origin) ?
    request.accept() :
    request.reject();
}

How can we check if a client sends us a message? We can do it by using the message event:

connection.on('message', function(message) {
    console.log('Received Message: ' + message.utf8Data);
}

The message must be in UTF-8 format; we must inspect the message.type attribute. If the type is correct, we can process the request and define the response accordingly. Here’s my demonstrative implementation:

if (message.type === 'utf8') {

  var response = '';

  switch (message.utf8Data) {
    case 'hi':
      response = 'Hey there';
      break;
    case 'hello':
      response = 'Heya!';
      break;  
    case 'xyzzy':
      response = 'Nothing happens.';
      break;
    case 'desu':
      response = 'Keep typing, man. Keep typing.';
      break;
    default:
      response = "Hello. Uh... what am I supposed to do with '" + 
      message.utf8Data + "'?";
  }
  connection.sendUTF(response);
}

It’s always a good idea to log when the connection starts and gets closed:

wsServer.on('connection', function(webSocketConnection) {
  console.log('Connection started.');
});

connection.on('close', function(reasonCode, description) {
  console.log(connection.remoteAddress + ' has been disconnected.');
});

And that’s all. We now have a basic WebSocket server implementation and we’re ready for the handshake.

Establish a connection between server and client

We can now test our brand new WebSocket server. Open the command prompt and start the server with:

$ node ws_server.js
Server is listening on port 1337.

Finally open the client (index.html) with your favourite browser and try to send a message.

When you send a web socket request as a client, you’ll send an HTTP header like this one:

GET / HTTP/1.1
Host: localhost:1337
User-Agent: Mozilla/5.0 [...]
Upgrade: websocket
...

And the server will respond something like:

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
...

This means you just established a full-duplex connection between the client and the server. If everything went as expected, the console should say something like:

Connection accepted from origin: http://localhost

And from this point every message will be logged on the console. Of course you shouldn’t close the console or the server will go down. If you want to close the connection you can both press Ctrl + C or close the browser’s window.


I hope you enjoyed following this guide. You can read the full source code of this tutorial on GitHub, or download it directly. The demo also comes with a file for testing your actual browser support for the WebSocket API.

js

Fuzzy matching with CSS3

There are special cases where a simple CSS selector is not enough. Like yesterday, when I wanted to match all the uploaded images in my blog, regardless of the container and the content.

Let’s see an example markup:

<p>
  <a href="/blog/wp-content/uploads/2012/11/cat-eat.gif">
    <img src="/blog/wp-content/uploads/2012/11/cat-eat-300x225.gif" 
         alt="" title="Cat Eat" width="300" height="225"
         class="alignnone size-medium wp-image-361" />
  </a>
  <a href="/blog/wp-content/uploads/2012/11/cat-help.jpg">
    <img src="/blog/wp-content/uploads/2012/11/cat-help.jpg" 
         alt="" title="Cat Help" width="500" height="457"
         class="aligncenter size-full wp-image-367" />
  </a>
</p>

How do we match only the images?

Well, there are many solutions. The simplest is certainly to use the img selector; but this way we’d match all the images, which isn’t our goal. We just want to match the uploaded ones.

Let’s examine the markup above. See, WordPress uses some classes in order to apply the correct size or alignment, and finally applies a unique class with a progressive number (wp-image-*), just in case we want to match a single element. So we could do this:

.wp-image-361,
.wp-image-367 {
  /* some fancy CSS code here */  
}

The solution above works, but it is not handy because – as you may have guessed – we should update the selector each time we upload a new image.

Hey, are we supposed to hard-code all the classes?

No, absolutely! That’s an absurd solution. Let’s explore other options.

The official W3C Selectors Level 3 specification offers a freaky set of selectors, for the joy of the craziest web designers!

In our specific case, this would do the trick:

img[class^="wp-image-"] { 
  /* matches an img element whose "class" attribute value begins exactly with the string "wp-image-" */
}

Note that I’m talking about CSS3, so if you need to support older browsers, don’t lean on it.

Cool. What else?

The table of selectors presents a whole bunch of possibilities, even though the usefulness isn’t always evident. But I’m sure you can find an example for every selector listed there. So, whether you are a CSS wizard or not, my final advice is: go create cool stuff, because practice makes perfect.

css

Git FTP Push FTW!

Git is a wonderful tool that makes possible having your local repo and your GitHub repo always perfectly synchronized. This is cool and all, but — what about the production server?

If you are in a shared hosting that doesn’t have git or SSH support, you’ll probably find stressful to manually update your application via FTP each time, even for the tiniest of the edits.

Well, if that’s your case you really should check out git-ftp by René Moser.

Git-ftp is a straightforward way to connect to your FTP and automagically transfer only the files that changed since the last commit.

The usage is fairly simple:

$ git ftp push --user <user> --passwd <password> ftp://example.com/public

And you can make it even simpler by just setting defaults in your project’s .git/config file:

$ git config git-ftp.user john
$ git config git-ftp.url ftp.example.com
$ git config git-ftp.password secr3t

Now you can just do:

$ git ftp push

Et voilà! Your production server is up-to-date.

git

Fushi PHP Boilerplate Released!

Fushi PHP Boilerplate logoHooray! I just released the version 0.8 of my very own PHP framework / boilerplate.

It has a lot of interesting features: it comes with a simple but powerful template system, as well as a secure and object-oriented backend engine. It’s also studied to be user friendly and SEO friendly. It’s based on the popular HTML5 Boilerplate.

I’ve been used it for some of my projects since march 2012. I surely can’t say Fushi is versatile like Smarty or mature like CodeIgniter; I’m not even sure on what design pattern it actually implements (update: found it: Front Controller Pattern). But I can say I successfully deployed some nice web applications based on Fushi, from the real estate agency to the musician‘s website. This demonstrates that Fushi can be used in a large variety of projects, small and big.

Fushi is open source software released under the MIT license, so feel free to use, copy, modify, merge, publish, distribute and contribute to this project. Fushi was initially born on december 14, 2011, with the sole purpose of learning new programming techniques; but now, months of hard work are at your disposal. Try it, and you won’t regret.

php

How to create a web bug (aka beacon image)

Have you ever wondered why some web pages include a 1×1 GIF image? Well, they’re called web bugs, and they track you.

The beacon images (better known as web bugs) are basically just hidden scripts behind images. They can easily be spotted because they usually don’t end with a common image format, like gif, jpeg or png.
An example of web beacon could be this:

<img src="beacon.php" width="1" height="1" alt="">

As you can see, the src attribute contains a PHP script. It’s easy to find (and block) web bugs when you see that an image is served as PHP.

By the way, more generally speaking, if you see that a file ends with .jpg (it’s an image, you think) or just doesn’t have an extension (I’m inside a folder, you think)… well, you could be wrong. I can easily execute a script when an user requests a simple image ending with .jpg, and I’ll explain you how.

In order to create an hidden web bug, you need to enable the Apache’s URL rewriting module (mod_rewrite). Create a new .htaccess file and put the following code in it:

RewriteEngine On
RewriteRule ^(.*).(png|jpg|gif)$ script.php

Now create the script.php file and write some random code:

<?php
$fullpath  = $_SERVER['REQUEST_URI'];
$filename  = basename($fullpath);
$ip        = $_SERVER["REMOTE_ADDR"];
$useragent = $_SERVER["HTTP_USER_AGENT"];

echo "Path: $fullpath;<br>
File: $filename;<br>
IP address: $ip;<br>
User agent: $useragent";

a surprised catAnd now try to navigate through an image, let’s say cat.gif. You’ll go to http://yoursite.com/path/to/cat.gif and you’ll expect to see a cat. Instead, you’ll see something like this:

Path: /path/to/cat.gif;
File: cat.gif;
IP address: 127.0.0.1;
User agent: Mozilla/5.0 [...];

Take a quick look at the URL in your browser’s address bar. You requested a cat.gif, but script.php has been executed instead. Kind of creepy, isn’t it? Imagine what else you could do. You can execute code. Possibilities are infinite.

php

How to install the Google Code Prettify plugin

If you have a WordPress blog and want to add some cool syntax highlighting for your code, you can try Google Code Prettify.

WordPress plugins are usually quite simple to use, but there are some little precautions to follow. First of all:

You shouldn’t activate it immediately, because if you do an edit while your plugin is activated, you could break it: some files could display an (inactive) label next to the file name, and all you can do to repair it is to delete and reinstall the whole plugin. Read more about this problem.

Once you enabled your plugin, you should wrap <pre class="prettyprint"> for every instance of code you have in all your articles. This can be tremendously annoying if you already have hundreds of articles in your WordPress blog, so I’ll tell you 5 quick ‘n’ straightforward steps to get around this problem.

  1. Edit google_code_prettify.php and search for this line:
    return preg_replace_callback("/<pres+.*classs*="prettyprint">(.*)</pre>/siU",
  2. Substitute the above line with the line below:
    return preg_replace_callback("/<pre><code>(.*)</code></pre>/siU",
  3. Open prettify.js and search for this line:
    if (cs.className && cs.className.indexOf('prettyprint') >= 0) {
  4. Substitute the above line with the line below:
    if (true) {
  5. Go edit your prettify.css and delete the reference about the .prettyprint class. Then you’ll want to add some more code to avoid the awful text overflow, that often causes layout problems. Have a look at this short article from CSS-Tricks: you need that code. I’m (shamelessly) copy pasting it below:
    pre {
     white-space: pre-wrap;       /* css-3 */
     white-space: -moz-pre-wrap;  /* Mozilla, since 1999 */
     white-space: -pre-wrap;      /* Opera 4-6 */
     white-space: -o-pre-wrap;    /* Opera 7 */
     word-wrap: break-word;       /* Internet Explorer 5.5+ */
    }

And that’s all. You can now enable your plugin and see your cute and readable code. ;-)

However, my solution is a bit hackish. I mean, when a new plugin update will be released, you’ll lost all the edits. If you don’t want this to happen, don’t update your plugin. Or if you’re looking for a separate, cleaner solution, I’ll suggest you reading this article.

wp