SCEditor works by having a BBCode parser and a DOM to BBCode converter (it's a bit ugly at the moment).
Initially the editor converts the BBCode from the textarea
into HTML via the BBCode parser and puts that inside the contentEditable element of the iframe
. The user can then edit the contents of the contentEditable element just like any other HTML WYSIWYG editor.
When the form is submitted or the user wants to view the BBCode source, the DOM is then translated back into BBCode via the converter. Translating from DOM to BBCode can be done accurately since it's essentially what BBCode is parsed into anyway.
So for example, for bold you can check if the node has a style.fontWeight
of bold or if it is a <strong>
or <b>
tag. For other elements like links, you just use the href
attribute and wrap the contents inside a [url]
tag.
Finally the resulting BBCode is parsed a second time by the BBCode parser and outputted with whatever BBCode output options are set. There isn't really a standard for BBCode so things like newlines after block-level elements should be configurable.
Essentially what SCEditor does is:
- BBCode -> DOM
- Edit via contentEditable
- DOM -> BBCode
What I've learned from creating SCEditor is that unless you want to spend years perfecting it, don't write a WYSIWYG editor with contentEditable, just use/build on someone else's. There's an answer on another post by a CKEditor dev saying pretty much the same thing.
If you do want to make your own WYSIWYG editor, using Rangy for the dealing with browser selections should make things a lot easier. The native browser selection APIs are (or at least were) very buggy! Not only that, IE < 9 uses a completely non-standard method of accessing selections. Rangy provides a common API that works with IE's non-standard approach as well as working around browser bugs.