From e8a93fa56b98887a3aaf3bad8a60be80436e4306 Mon Sep 17 00:00:00 2001 From: Jeremy Ruston Date: Thu, 9 Feb 2012 13:36:46 +0000 Subject: [PATCH] Refactored link macro To handle external links correctly, and URI encode internal links --- js/macros/link.js | 39 +++++++++++++++++++++++++++++++-------- 1 file changed, 31 insertions(+), 8 deletions(-) diff --git a/js/macros/link.js b/js/macros/link.js index 4cd93dfdf..c95056e0e 100644 --- a/js/macros/link.js +++ b/js/macros/link.js @@ -10,6 +10,11 @@ title: js/macros/link.js var HTML = require("../HTML.js").HTML, utils = require("../Utils.js"); +var isLinkExternal = function(target) { + var externalRegExp = /(?:file|http|https|mailto|ftp|irc|news|data):[^\s'"]+(?:\/|\b)/i; + return externalRegExp.test(target); +}; + exports.macro = { name: "link", wrapperTag: "span", @@ -19,19 +24,37 @@ exports.macro = { }, events: { click: function(event,node,tiddler,store,params) { - var navEvent = document.createEvent("Event"); - navEvent.initEvent("tw-navigate",true,true); - navEvent.navigateTo = params.target; - node.dispatchEvent(navEvent); - event.preventDefault(); - return false; + if(isLinkExternal(params.target)) { + event.target.setAttribute("target","_blank"); + return true; + } else { + var navEvent = document.createEvent("Event"); + navEvent.initEvent("tw-navigate",true,true); + navEvent.navigateTo = params.target; + node.dispatchEvent(navEvent); + event.preventDefault(); + return false; + } } }, render: function(type,tiddler,store,params,content) { + var classes = ["tw-tiddlylink"], + target = params.target; + if(isLinkExternal(params.target)) { + classes.push("tw-tiddlylink-external"); + } else { + classes.push("tw-tiddlylink-internal"); + if(store.tiddlerExists(params.target)) { + classes.push("tw-tiddlylink-resolves"); + } else { + classes.push("tw-tiddlylink-missing"); + } + target = encodeURIComponent(target); + } return HTML(HTML.elem( "a",{ - href: params.target, - "class": store.adjustClassesForLink([],params.target) + href: target, + "class": classes },[ HTML.raw(content) ]