Post by Peter on Feb 12, 2013 6:20:45 GMT -8
If I was to think about trying this, one thing I'd do is make it so that eventually you'll end up not needing to use it (for new posts at least) because you'll be using the built-in style attribute (which works on tables, divs, spans, images and probably more). The difficulties in making this code come with getting it to work out what tags correspond to what and what to do with the faux classes and properties that aren't supported in V5. I imagine that people wouldn't want to change each old post individually but, as evidenced by iPokemon's plugin being removed, this is difficult to do without security problems. Lastly, there is the problem of how to get around people who'd just end up using the conversion part and never bothering to learn the V5 attribute format (ie. like actual HTML/CSS).
I suppose what you could do is write a parser for the messages to validate the CSS property names and making the values safe.
I wrote this on the fly, so not sure if it will work, but hopefully this will help someone who does go down this route...
var styles = (function(){
return {
span: document.createElement("span"),
parse: function(content){
var parsed = content;
if(content && content.toString().length){
var str = content.toString();
if(str.match(/(\[style=(.+?)\]).+?(\[\/style\])/gim)){
var open = RegExp.$1;
var close = RegExp.$3;
var css = RegExp.$2;
var css_parts = css.split(";");
var valid_css = [];
for(var p = 0, l = css_parts.length; p < l; p ++){
var prop_parts = css_parts[p].replace(/\s/g, "").split(":");
if(prop_parts.length == 2){
var prop_name = prop_parts[0];
var prop_val = this.make_safe(prop_parts[1]);
if(this.valid_property(prop_name)){
valid_css.push([prop_name, prop_val]);
}
}
}
parsed = str.replace(open, "<span style=\"" + this.build_inline_css(valid_css) + "\">").replace(close, "</span>");
}
}
return parsed;
},
build_inline_css: function(css){
var inline = "";
if(css.length){
for(var p = 0, l = css.length; p < l; p ++){
inline += css[p][0] + ": " + css[p][1] + ";";
}
}
return inline;
},
valid_property: function(prop){
var prop_name = this.convert_property_name(prop);
if(prop_name in this.span.style){
return true;
}
return false;
},
make_safe: function(str){
this.span.innerHTML = "";
this.span.appendChild(document.createTextNode(str || ""));
return this.span.innerHTML;
},
convert_property_name: function(name){
return name.replace(/-([a-z])/g, function(m, p1){
return p1.toUpperCase();
});
}
};
})();
// Single example of converting 1 post.
var html = $(".post").find(".message").html();
$(".post").find(".message").html(styles.parse(html));
Not 100% sure if it will work, as I wrote it in the Firebug console while live editing a post with style ubbc. Security should be looked at though, however I have put in some basic methods to validate the property name (prop in obj.style), and made the property value safe (though needs testing).