diff src/browser/sat_browser/strings.py @ 848:7dafa5ee809a

browser: replace re module usage by pure javascript
author souliane <souliane@mailoo.org>
date Fri, 15 Jan 2016 16:33:08 +0100
parents 73cc4658f431
children d32b754265a0
line wrap: on
line diff
--- a/src/browser/sat_browser/strings.py	Fri Jan 15 12:30:21 2016 +0100
+++ b/src/browser/sat_browser/strings.py	Fri Jan 15 16:33:08 2016 +0100
@@ -17,7 +17,6 @@
 # You should have received a copy of the GNU Affero General Public License
 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-import re
 from __pyjamas__ import JS
 
 
@@ -50,25 +49,25 @@
     @param string (unicode): text to process
     @param new_target (bool): if True, make the link open in a new window
     """
-    # XXX: Workaround for a pyjamas bug with regex, base method in sat.frontends.tools.strings
+    # FIXME: Workaround for a pyjamas bug with regex, base method in sat.frontends.tools.strings
     # In some case, Pyjamas' re module get crazy and freeze browsers (tested with Iceweasel and Chromium).
     # we use javascript as a workaround
     # This method is inspired from https://stackoverflow.com/questions/1500260/detect-urls-in-text-with-javascript
-    target = ' target="_blank"' if new_target else ''
     JS("""var urlRegex = /(https?:\/\/[^\s]+)/g;
+    var target = new_target ? ' target="_blank"' : '';
     return text.replace(urlRegex, function(url) {
         return '<a href="' + url + '"' + target + ' class="url">' + url + '</a>';
     })""")
 
 
-def addURLToImage(string):
+def addURLToImage(text):
     """Check a XHTML text for what looks like an imageURL and make it clickable.
 
-    @param string (unicode): text to process
+    @param text (unicode): text to process
     """
-    # XXX: Workaround for a pyjamas bug with regex, base method in sat.frontends.tools.strings
-    def repl(match):
-        url = match.group(1)
-        return '<a href="%s" target="_blank">%s</a>' % (url, match.group(0))
-    pattern = r"""<img[^>]* src="([^"]+)"[^>]*>"""
-    return re.sub(pattern, repl, string)
+    # FIXME: Pyjamas re module is not stable so we use pure JS instead, base method in sat.frontends.tools.strings
+    JS("""var imgRegex = /<img[^>]* src="([^"]+)"[^>]*>/g;
+    return text.replace(imgRegex, function(img, src) {
+        return '<a href="' + src + '" target="_blank">' + img + '</a>';
+    })""")
+