Saturday, 10 March 2012

Generating resilient HTML

Instead of requiring content to be written off-line and uploaded, many blog hosts including Google's Blogger provide an in-browser editor. Unfortunately, Google's editor is easily confused by HTML in the written document and it will corrupt blog posts. In fact, our last post took four attempts before we were able to create something readable. Of course, code is often hit by this problem.

The following WPF-based F# program produces a window that allows content to be pasted into the text box at the top and converted into raw HTML at the bottom that can then be pasted into blogs with a greatly reduced risk of corruption:

open System.Windows

[<System.STAThread>]
do
   let panel = Controls.StackPanel()
   let input = Controls.TextBox(AcceptsReturn=true)
   let output = Controls.TextBox(AcceptsReturn=true)
   input.TextChanged.Add(fun e ->
      output.Text <-
         [ for c in input.Text do
            match int c with
            | 13 -> ()
            | 10 -> yield "<br />"
            | 32 -> yield "&nbsp;"
            | c -> yield sprintf "&#%d;" c ]
         |> String.concat "")
   panel.Children.Add input |> ignore
   panel.Children.Add output |> ignore
   let content = Controls.ScrollViewer(Content=panel)
   Window(Content=content) |> Application().Run |> ignore

No comments: