# HG changeset patch
# User souliane <souliane@mailoo.org>
# Date 1452872077 -3600
# Node ID d32b754265a0e135c01a99c6e478a64c0536bfdd
# Parent  7dafa5ee809a584da5a0d78d7ac0cf6090ba9ea2
browser (strings, editor): add javascript version of fixXHTMLLinks and use it for displaying the rich blog messages (add links' missing scheme and open them in new tab)

diff -r 7dafa5ee809a -r d32b754265a0 src/browser/sat_browser/editor_widget.py
--- a/src/browser/sat_browser/editor_widget.py	Fri Jan 15 16:33:08 2016 +0100
+++ b/src/browser/sat_browser/editor_widget.py	Fri Jan 15 16:34:37 2016 +0100
@@ -294,6 +294,7 @@
             text = strings.addURLToText(text)
         if self.CONVERT_NEW_LINES:
             text = html_tools.convertNewLinesToXHTML(text)
+        text = strings.fixXHTMLLinks(text)
         self.display.setHTML(text)
 
     def setFocus(self, focus):
diff -r 7dafa5ee809a -r d32b754265a0 src/browser/sat_browser/strings.py
--- a/src/browser/sat_browser/strings.py	Fri Jan 15 16:33:08 2016 +0100
+++ b/src/browser/sat_browser/strings.py	Fri Jan 15 16:34:37 2016 +0100
@@ -71,3 +71,31 @@
         return '<a href="' + src + '" target="_blank">' + img + '</a>';
     })""")
 
+def fixXHTMLLinks(xhtml):
+    """Add http:// if the scheme is missing and force opening in a new window.
+
+    @param string (unicode): XHTML Content
+    """
+    # FIXME: Pyjamas re module is not stable so we use pure JS instead, base method in sat.frontends.tools.strings
+    JS("""var subs = [];
+    var tag_re = /<a(?: \w+="[^"]*")* ?\/?>/g;
+    var result;
+    while ((result = tag_re.exec(xhtml)) !== null) {
+        tag = result[0];
+        var link_result = /href="([^"]*)"/.exec(tag);
+        if (link_result) {  // found a link
+            var link = link_result[0];
+            var url = link_result[1];
+            if (! /target="([^"]*)"/.test(tag)) {  // no target
+                subs.push([tag, '<a target="_blank"' + tag.slice(2, tag.length)]);
+            }
+            if (! /^\w+:\/\//.test(url)) {  // no scheme
+                subs.push([link, 'href="http://' + url + '"']);
+            }
+        }
+    }
+    for (i in subs) {
+        xhtml = xhtml.replace(subs[i][0], subs[i][1]);
+    }
+    """)
+    return xhtml