]> jfr.im git - irc/quakenet/qwebirc.git/blob - js/ui/url.js
Merge pull request #305 from retropc/master
[irc/quakenet/qwebirc.git] / js / ui / url.js
1 qwebirc.ui.urlificate = function(element, text, execfn, cmdfn, window) {
2 var punct_re = /[[\)|\]>]?(\.*|[\,;])$/;
3 var addedText = [];
4
5 var txtprocess = function(text, regex, appendfn, matchfn) {
6 for(;;) {
7 var index = text.search(regex);
8 if(index == -1) {
9 appendfn(text);
10 break;
11 }
12 var match = text.match(regex);
13
14 var before = text.substring(0, index);
15 var matched = match[0];
16 var after = text.substring(index + matched.length);
17
18 appendfn(before);
19 var more = matchfn(matched, appendfn);
20 if(!more)
21 more = "";
22 text = more + after;
23 }
24 };
25
26 var appendText = function(text) {
27 addedText.push(text);
28 qwebirc.util.NBSPCreate(text, element);
29 };
30
31 var appendChan = function(text) {
32 var newtext = text.replace(punct_re, "");
33 addedText.push(newtext);
34 var punct = text.substring(newtext.length);
35
36 var a = new Element("span");
37 a.addClass("hyperlink-channel");
38 a.addEvent("click", function(e) {
39 new Event(e).stop();
40 execfn("/JOIN " + newtext);
41 });
42 a.appendChild(document.createTextNode(newtext));
43 element.appendChild(a);
44
45 return punct;
46 };
47
48 var appendURL = function(text, appendfn) {
49 var url = text.replace(punct_re, "");
50 var punct = text.substring(url.length);
51
52 var href = "";
53 var fn = null;
54 var target = "_blank";
55 var disptext = url;
56 var elementType = "a";
57 var addClass;
58
59 var ma = url.match(/^qwebirc:\/\/(.*)$/);
60 if(ma) {
61 var m = ma[1].match(/^([^\/]+)\/([^\/]+)\/?(.*)$/);
62 if(!m) {
63 appendfn(text);
64 return;
65 }
66
67 var cmd = cmdfn(m[1], window);
68 if(cmd) {
69 addClass = m[1];
70 elementType = cmd[0];
71 if(cmd[0] != "a") {
72 url = null;
73 } else {
74 url = "#";
75 }
76 fn = cmd[1];
77 disptext = unescape(m[2]);
78 target = null;
79 } else {
80 appendfn(text);
81 return;
82 }
83 if(m[3])
84 punct = m[3] + punct;
85 } else {
86 if(url.match(/^www\./))
87 url = "http://" + url;
88 }
89
90 var a = new Element(elementType);
91 if(addClass)
92 a.addClass("hyperlink-" + addClass);
93
94 if(url) {
95 a.href = url;
96
97 if(target)
98 a.target = target;
99 }
100 addedText.push(disptext);
101 a.appendChild(document.createTextNode(disptext));
102
103 element.appendChild(a);
104 if($defined(fn))
105 a.addEvent("click", function(e) { new Event(e).stop(); fn(disptext); });
106
107 return punct;
108 };
109
110 txtprocess(text, /\b((https?|ftp|qwebirc):\/\/|www\.)[^ ]+/, function(text) {
111 txtprocess(text, /\B#[^ ,]+/, appendText, appendChan);
112 }, appendURL);
113
114 return addedText.join("");
115 }