Repository navigation
Expand file tree
/
Copy pathlink_helper.js
More file actions
301 lines (262 loc) · 9.68 KB
/
Copy pathlink_helper.js
File metadata and controls
301 lines (262 loc) · 9.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
/*global Utils */
(function() {
'use strict';
/*
The LinkHelper exposes functionality to apply the regexp
on the input strings and replace them with corresponding
anchor links for url, phone, email.
*/
var KNOWN_TLDS = [
'aero', 'asia', 'biz', 'cat', 'com', 'coop', 'info',
'int', 'jobs', 'mobi', 'museum', 'name', 'net', 'org', 'post', 'pro',
'tel', 'travel', 'xxx', 'edu', 'gov', 'mil', 'nyc', 'ac',
'ad', 'ae', 'af', 'ag', 'ai', 'al', 'am', 'an', 'ao', 'aq', 'ar',
'as', 'at', 'au', 'aw', 'ax', 'az', 'ba', 'bb', 'bd', 'be', 'bf',
'bg', 'bh', 'bi', 'bj', 'bm', 'bn', 'bo', 'br', 'bs', 'bt', 'bv',
'no', 'bw', 'by', 'bz', 'ca', 'cc', 'cd', 'cf', 'cg', 'ch', 'ci',
'ck', 'cl', 'cm', 'cn', 'co', 'cr', 'cs', 'cu', 'cv', 'cx', 'cy',
'cz', 'dd', 'de', 'dj', 'dk', 'dm', 'do', 'dz', 'ec', 'ee', 'eg',
'eh', 'er', 'es', 'et', 'eu', 'fi', 'fj', 'fk', 'fm', 'fo', 'fr',
'ga', 'gb', 'gd', 'ge', 'gf', 'gg', 'gh', 'gi', 'gl', 'gm', 'gn',
'gp', 'gq', 'gr', 'gs', 'gt', 'gu', 'gw', 'gy', 'hk', 'hm', 'hn',
'hr', 'ht', 'hu', 'id', 'ie', 'il', 'im', 'in', 'io', 'iq', 'ir',
'is', 'it', 'je', 'jm', 'jo', 'jp', 'ke', 'kg', 'kh', 'ki', 'km',
'kn', 'kp', 'kr', 'kw', 'ky', 'kz', 'la', 'lb', 'lc', 'li', 'lk',
'lr', 'ls', 'lt', 'lu', 'lv', 'ly', 'ma', 'mc', 'md', 'me', 'mg',
'mh', 'mk', 'ml', 'mm', 'mn', 'mn', 'mo', 'mp', 'mq', 'mr', 'ms',
'mt', 'mu', 'mv', 'mw', 'mx', 'my', 'mz', 'na', 'nc', 'ne', 'nf',
'ng', 'ni', 'nl', 'no', 'np', 'nr', 'nu', 'nz', 'om', 'pa', 'pe',
'pf', 'pg', 'ph', 'pk', 'pl', 'pm', 'pn', 'pr', 'ps', 'pt', 'pw',
'py', 'qa', 're', 'ro', 'rs', 'ru', 'su', 'рф', 'rw', 'sa', 'sb',
'sc', 'sd', 'se', 'sg', 'sh', 'si', 'sj', 'no', 'sk', 'sl', 'sm',
'sn', 'so', 'sr', 'ss', 'st', 'su', 'sv', 'sx', 'sy', 'sz', 'tc',
'td', 'tf', 'tg', 'th', 'tj', 'tk', 'tl', 'tp', 'tm', 'tn', 'to',
'tp', 'tl', 'tr', 'tt', 'tv', 'tw', 'tz', 'ua', 'ug', 'uk', 'us',
'gov', 'uy', 'uz', 'va', 'vc', 've', 'vg', 'vi', 'vn', 'vu', 'wf',
'ws', 'ye', 'yt', 'yu', 'za', 'zm', 'zw'
];
var ipv4part = '(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)';
var ipv4RegExp = new RegExp('^(?:' + ipv4part + '\\.){3}' + ipv4part + '$');
var leadingDigitsRegExp = /^[+0-9]+/;
// ensure that each part of the domain is long enough
function checkDomain(domain) {
// Check for a specific IPv4 address
if (ipv4RegExp.test(domain)) {
return true;
} else {
// Don't add many restrictions,
// just the tld to be non numeric and length > 1
var parts = domain.split('.');
var lastPart = parts[parts.length - 1];
// We want the last part not to be a number
return lastPart.length > 1 && !isFinite(lastPart);
}
}
// defines things that can match right before to be a "safe" link
var safeStart = /[\s,:;\(>]/;
const MINIMUM_DIGITS_IN_PHONE_NUMBER = 5;
const LEADING_DIGIT_BREAKPOINT = 7;
/**
* For each category of links:
* The key is the link type
* order matters - defined first means higher priority if two matches equal
*
* regexp: The regular expression to match potential links
* matchFilter: (optional) A function that is passed the matched part, and
* the linkSpec.
* Should return the linkSpec, or false if not to be matched
* transform: A function that converts the match data to a html link string
* Is passed the matched part and the linkSpec.
*/
8000
var LINK_TYPES = {
phone: {
regexp: new RegExp([
// sddp: space, dot, dash or parens
'(?:\\+\\d{1,4}[ \\t.()-]{0,3}|\\()?' + // (\+<digits><sddp>|\()?
'(?:\\d{1,4}[ \\t.()-]{0,3})?' + // <digits><sdd>*
'(?:\\d[\\d \\t.()-]{0,12}\\d)' + // <digit><digit|sddp>*<digit>
'\\b' // must end on a word boundary
].join(''), 'g'),
matchFilter: function phoneMatchFilter(phone, link) {
var >
if (onlyDigits.length < MINIMUM_DIGITS_IN_PHONE_NUMBER) {
return false;
}
if (onlyDigits.length === MINIMUM_DIGITS_IN_PHONE_NUMBER &&
phone.length !== onlyDigits.length) {
return false;
}
var leadingDigits = leadingDigitsRegExp.exec(phone);
if (leadingDigits &&
leadingDigits[0].length >= LEADING_DIGIT_BREAKPOINT) {
link.end = link.start + leadingDigits[0].length;
}
return link;
},
transform: function phoneTransform(phone, link) {
return '<a data-dial="' + phone +
'" data-action="dial-link">' + phone + '</a>';
}
},
url: {
regexp: new RegExp([
// must begin at start of string, after whitespace,
// {1} match the protocol https?:// (optional)
'(https?://)?',
// {2} match "server name": . must be followed by at least one letter
'((?:\\.?[-\\w]){1,256})',
// {3} match a . followed by one or more domain valid chars
'(\\.\\w{1,10})',
// optional :port
'(?::[0-9]{1,5})?',
// start the "query" capture group by matching an optional dot then /
'(?:\\.?/',
// anything other than a sentence ender
// a sentence ender not followed by whitespace
// match 0 - 2048 characters in the url
'(?:[^\\s.,?:;!]|[.,?:;!](?!\\s|$)){0,2048}',
// end the "query" capture group (optional)
')?'
].join(''), 'mgi'),
matchFilter: function urlMatchFilter(url, linkSpec) {
var match = linkSpec.match;
var scheme, tld;
if (!checkDomain(match[2] + match[3])) {
return false;
}
scheme = match[1];
tld = match[3] && match[3].slice(1);
// For Cases where:
//
// 1. There was no scheme (eg, "http", "https")
// 2. The matched tld is not a number
// 3. The matched tld is not a known tld
//
// ... Do not create a clickable link
if (!scheme && (!isFinite(tld) && KNOWN_TLDS.indexOf(tld) === -1)) {
return false;
}
// strip a trailing ) if there isn't a ( in the url
if (url.slice(-1) === ')' && url.indexOf('(') === -1) {
linkSpec.end--;
}
return linkSpec;
},
transform: function urlTransform(url, linkSpec) {
var href = url;
if (!linkSpec.match[1]) {
href = 'http://' + href;
}
return '<a data-url="' + href + '" data-action="url-link" >' + url +
'</a>';
}
},
email: {
regexp: /[\w.+-]+@[\w.-]+\.[a-z.]{2,6}/mgi,
transform: function emailTransform(email) {
return [
'<a data-email="',
'" data-action="email-link">',
'</a>'
].join(email);
}
}
};
var LINK_TYPES_KEYS = Object.keys(LINK_TYPES);
function searchForLinks(type, string) {
var linkSpecs = [];
var spec = LINK_TYPES[type];
if (!spec) {
return linkSpecs;
}
var regexp = spec.regexp;
var matchFilter = spec.matchFilter;
var match, linkSpec;
// while we match stuff...
while ((match = regexp.exec(string))) {
// if the match isn't at the begining of the string, check for a safe
// character before the match
var rest = string.slice(match.index - 1);
if (match.index && !safeStart.test(rest.charAt(0))) {
// we should only advance the regexp to the next safeStart
var nextSafe = safeStart.exec(rest);
if (nextSafe) {
regexp.lastIndex = match.index + nextSafe.index;
}
continue;
}
linkSpec = {
type: type,
start: match.index,
length: match[0].length,
end: match.index + match[0].length,
match: match
};
if (matchFilter) {
linkSpec = matchFilter(match[0], linkSpec);
}
if (linkSpec) {
linkSpecs.push(linkSpec);
regexp.lastIndex = linkSpec.end;
}
}
return linkSpecs;
}
function linkSort(a, b) {
// sort by starting position first
// then by ending position reversed
// then by the order of the type in the LINK_TYPES
return (a.start - b.start) ||
(b.end - a.end) ||
(LINK_TYPES_KEYS.indexOf(a.type) - LINK_TYPES_KEYS.indexOf(b.type));
}
function removeOverlapping(linkSpecs) {
linkSpecs.sort(linkSort);
for (var index = 0; index < linkSpecs.length - 1; index++) {
var end = linkSpecs[index].end;
// while there are more linkSpecs, and they start before we end remove the
// overlapping matches
while (linkSpecs[index + 1] && linkSpecs[index + 1].start < end) {
linkSpecs.splice(index + 1, 1);
}
}
}
var LinkHelper = window.LinkHelper = {
searchAndLinkUrl: function lh_searchAndLinkUrl(inputText) {
return LinkHelper.searchAndLinkClickableData(inputText, { url: true });
},
searchAndLinkEmail: function lh_searchAndLinkEmail(inputText) {
return LinkHelper.searchAndLinkClickableData(inputText, { email: true });
},
searchAndLinkPhone: function lh_searchAndLinkPhone(inputText) {
return LinkHelper.searchAndLinkClickableData(inputText, { phone: true });
},
// Invokes resepective functions to change url, phone and email strings
// and make them active links
// |inputText| should be already html escaped
searchAndLinkClickableData:
function lh_searchAndLinkClickableData(inputText, mode) {
// default is everything enabled
mode = mode || LINK_TYPES;
var linkSpecs = [];
var type;
for (type in mode) {
if (mode[type] && LINK_TYPES[type]) {
linkSpecs = linkSpecs.concat(searchForLinks(type, inputText));
}
}
removeOverlapping(linkSpecs);
var result = '';
var lastEnd = 0;
linkSpecs.forEach(function replaceLink(link) {
result += inputText.slice(lastEnd, link.start);
var replacing = inputText.slice(link.start, link.end);
var replaceWith = LINK_TYPES[link.type].transform(replacing, link);
result += replaceWith;
lastEnd = link.end;
});
result += inputText.slice(lastEnd);
return result;
}
};
})();