Code that types itself

The code block below holds all of its text from the start. The canvas draws only the characters that have been typed so far, with a caret, a glow on the newest characters and an occasional wrong key that is corrected. The wrong characters exist only in the picture. Select the text or press Copy while it's typing: the selection and the clipboard get the whole block. The code shown is the function that draws it.

 

Show the code a clip over one drawElementImage() call
  1. The block. A <pre> in the canvas. The script puts the text of reveal() into it.
  2. The styles. Syntax colours are ::highlight() rules.
  3. The colours. Ranges over the text node, registered with the CSS Custom Highlight API.
  4. The boxes. One for each character, measured with a Range.
  5. The reveal. Clip to the boxes of the typed characters, then draw the element. This is the text in the demo.
  6. The glow, the wrong keys and the caret. Pieces of the same element drawn again.

How it works

The <pre> is a child of the canvas and contains the complete code as one text node. The page measures a box for every character with Range.getClientRects(). On each paint it builds a clip path from the boxes of the first n characters and calls drawElementImage() once. The clip hides the characters that aren't typed yet.

The syntax colours come from the CSS Custom Highlight API: the script registers ranges for comments, strings, keywords, numbers and calls, and ::highlight() rules colour them. So the text needs no spans, and character n of the text node is character n of the animation.

A wrong key is drawn with the nine-argument drawElementImage(): the box of a different letter somewhere else in the block is copied to the caret position, held for a moment and then removed. The text node never changes. The element's hit region covers the whole block, so text that isn't drawn yet can still be selected, and the boxes of the selection are added to the clip so that selected text shows.

Live checks

These run on their own fixtures in the corner of the window, after a tap on the button.

Findings