]> jfr.im git - irc/quakenet/qwebirc.git/blob - js/ui/url.js
d2cb734344096df3fe52ff27b55d4754cd22c769
[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.href = "#";
38 a.addClass("hyperlink-channel");
39 a.addEvent("click", function(e) {
40 new Event(e).stop();
41 execfn("/JOIN " + newtext);
42 });
43 a.appendChild(document.createTextNode(newtext));
44 element.appendChild(a);
45
46 return punct;
47 };
48
49 var appendURL = function(text, appendfn) {
50 var url = text.replace(punct_re, "");
51 var punct = text.substring(url.length);
52
53 var href = "";
54 var fn = null;
55 var target = "new";
56 var disptext = url;
57 var elementType = "a";
58 var addClass;
59
60 var ma = url.match(/^qwebirc:\/\/(.*)$/);
61 if(ma) {
62 var m = ma[1].match(/^([^\/]+)\/([^\/]+)\/?(.*)$/);
63 if(!m) {
64 appendfn(text);
65 return;
66 }
67
68 var cmd = cmdfn(m[1], window);
69 if(cmd) {
70 addClass = m[1];
71 elementType = cmd[0];
72 if(cmd[0] != "a") {
73 url = null;
74 } else {
75 url = "#";
76 }
77 fn = cmd[1];
78 disptext = unescape(m[2]);
79 target = null;
80 } else {
81 appendfn(text);
82 return;
83 }
84 if(m[3])
85 punct = m[3] + punct;
86 } else {
87 if(url.match(/^www\./))
88 url = "http://" + url;
89 }
90
91 var a = new Element(elementType);
92 if(addClass)
93 a.addClass("hyperlink-" + addClass);
94
95 if(url) {
96 a.href = url;
97
98 if(target)
99 a.target = target;
100 }
101 addedText.push(disptext);
102 a.appendChild(document.createTextNode(disptext));
103
104 element.appendChild(a);
105 if($defined(fn))
106 a.addEvent("click", function(e) { new Event(e).stop(); fn(disptext); });
107
108 return punct;
109 };
110
111 txtprocess(text, /\b((https?|ftp|qwebirc):\/\/|www\.)[^ ]+/, function(text) {
112 txtprocess(text, /\B#[^ ,]+/, appendText, appendChan);
113 }, appendURL);
114
115 return addedText.join("");
116 }