-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathSECommentLinkHelper.user.js
More file actions
241 lines (202 loc) · 9.46 KB
/
SECommentLinkHelper.user.js
File metadata and controls
241 lines (202 loc) · 9.46 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
// ==UserScript==
// @name SE Comment Link Helper
// @description A hook to transform raw links to properly titled links in comments
// @version 1.24
// @homepageURL https://stackapps.com/questions/2378/se-comment-link-helper
// @namespace https://github.com/rchern/StackExchangeScripts
// @match *://stackoverflow.com/*
// @match *://meta.stackoverflow.com/*
// @match *://es.stackoverflow.com/*
// @match *://es.meta.stackoverflow.com/*
// @match *://ja.stackoverflow.com/*
// @match *://ja.meta.stackoverflow.com/*
// @match *://pt.stackoverflow.com/*
// @match *://pt.meta.stackoverflow.com/*
// @match *://ru.stackoverflow.com/*
// @match *://ru.meta.stackoverflow.com/*
// @match *://mathoverflow.net/*
// @match *://meta.mathoverflow.net/*
// @match *://superuser.com/*
// @match *://meta.superuser.com/*
// @match *://serverfault.com/*
// @match *://meta.serverfault.com/*
// @match *://askubuntu.com/*
// @match *://meta.askubuntu.com/*
// @match *://stackapps.com/*
// @match *://*.stackexchange.com/*
// @match *://*.meta.stackexchange.com/*
// @exclude *://chat.stackexchange.com/*
// @exclude *://chat.*.stackexchange.com/*
// @exclude *://api.*.stackexchange.com/*
// @exclude *://data.stackexchange.com/*
// @exclude *://*/reputation
// @author @TimStone
// ==/UserScript==
function inject() {
for (var i = 0; i < arguments.length; ++i) {
if (typeof(arguments[i]) == 'function') {
var script = document.createElement('script');
script.type = 'text/javascript';
script.textContent = '(' + arguments[i].toString() + ')(jQuery)';
document.body.appendChild(script);
}
}
}
inject(function ($) {
function HijackedTextarea(t) {
var filters = { questions: '-ox0X.YDyJfh', answers: '!b6vl_mZrb8iVXs' },
textarea = t.addClass('link-hijacked')[0],
form = t.closest('form'),
span = document.createElement('span'),
link = new RegExp('(?:^|[^\\w\\\\])https?://([^\\s/]+)/(q(?:uestions)?|a)/([0-9]+)', 'ig'),
lock = 0,
submitComment = $._data(form[0], 'events').submit[0].handler,
// regex tested with
// $.getJSON('https://api.stackexchange.com/2.2/sites?pagesize=1000&filter=!6P.Ehvyb0IX7X')
// .done(data => {
// const domains = data.items.map(item => new URL(item.site_url).hostname),
// missed = domains.filter(d => !validSites.test(d))
// if (missed.length) { console.error('Domains missed', missed) }
// else { console.log('Test passed') }
// });
validSites = new RegExp(
'^(?:' + // one of: top-level names, with their meta sites
'(?:' +
'(?:meta\\.)?' +
'(?:' + // one of: <domain>.com names
'(?:stackoverflow|serverfault|askubuntu|superuser)\\.com' +
'|' + // or: mathoverflow.net
'mathoverflow\\.net' +
')' +
')' +
'|' + // or: stackapps, which has no meta.
'stackapps\\.com' +
'|' + // or: the language-variants of stackoverflow.com
'(?:es|ja|pt|ru)\\.(?:meta\\.)?stackoverflow\\.com' +
'|' + // or: .stackexchange sites, with their meta sites.
'[^.]+\\.(?:meta\\.)?stackexchange\\.com' +
')$',
'i'
),
miniLink = /(^|\W)(\[([^\]]+)\]\((?:(?:https?|ftp):\/\/[^)\s]+?)(?:\s(?:"|")(?:[^"]+?)(?:"|"))?\))/g,
miniCode = /(^|\W)(`(?:.+?)`)(?=\W|$)/g,
results = [];
$._data(form[0], 'events').submit[0].handler = handler;
function handler() {
if (lock)
return;
lock = -1;
var url, questions = {}, answers = {},
comment = textarea.value.replace(miniLink, "$1##").replace(miniCode, "$1##");
while (url = link.exec(comment)) {
var type = url[2] === 'a' ? answers : questions,
domain = url[1];
if (!type[domain])
type[domain] = [];
type[domain].push(url[3]);
}
if (Object.keys(questions).length || Object.keys(answers).length) {
request(questions, 'questions', callback);
request(answers, 'answers', callback);
}
if (lock < 0) {
// either no question and answer links were detected, *or* none of the
// links were for valid sites and so no AJAX requests were started.
// In either case we need to trigger the comment submit at this point.
submit();
}
link.lastIndex = 0;
return false;
}
function callback(data, domain) {
lock = lock - 1 === 0 ? -1 : lock - 1;
if (!data.items || !data.items.length) {
if (lock < 0) {
submit();
}
return;
}
data.domain = domain;
results.push(data);
if (lock < 0) {
submit();
}
}
function submit() {
var i, j, id, post, pattern, swaps = [],
swapper = function (s, m1, m2) {
swaps.push(m2);
return m1 + "~%" + (swaps.length - 1) + "#";
},
comment = textarea.value;
if (results.length) {
for (i = 0; i < results.length; ++i) {
comment = comment.replace(miniLink, swapper).replace(miniCode, swapper);
for (j = 0; j < results[i].items.length; ++j) {
post = results[i].items[j];
id = post.question_id || post.answer_id;
pattern = '(^|[^\\w\\\\])http(s?)://' + results[i].domain.replace('.', '\\.') + '/(q(?:uestions)?|a)/' + id + '(?:/[-\\w]*)?(/[0-9]+)?(?:\\?[a-z]+=1)?(#\\w+)?';
comment = comment.replace(new RegExp(pattern, 'gi'), function (s, leading, https, type, trailing, anchor) {
leading = leading || '';
trailing = trailing || '';
anchor = /^#comment(\d+)_/.exec(anchor || '');
var url;
if (anchor) {
url = '/posts/comments/' + anchor[1];
} else if (type === 'questions' && trailing) {
url = '/a' + trailing;
} else if (type === 'a') {
url = '/a/' + id;
} else {
url = '/q/' + id;
}
return leading + '[' + escapeMarkdown(cleanWhitespace(toText(post.title))) + '](https://' + results[i].domain + url + ')';
});
}
}
textarea.value = comment.replace(/~%(\d+)#/g, function (s, m1) {
return swaps[+m1];
});
$(textarea).trigger('keyup');
}
submitComment.call(form[0]);
results = [];
lock = 0;
}
function toText(html) {
span.innerHTML = html;
return span.textContent;
}
function cleanWhitespace(text) {
// remove leading and trailing whitespace, collapse multiple spaces
// into one everywhere else.
return text.replace(/^\s+|\s+$/g, '').replace(/\s+/g, ' ');
}
function escapeMarkdown(text) {
return text.replace(/\[/g, '\\[')
.replace(/\]/g, '\\]')
.replace(/\*/g, '\\*')
.replace(/_/g, '\\_')
.replace(/`/g, '\\`');
}
function request(ids, type, callback) {
Object.keys(ids).forEach(function (domain) {
if (validSites.test(domain)) {
lock = lock < 0 ? 1 : lock + 1;
$.get(window.location.protocol + '//api.stackexchange.com/2.1/' + type + '/' + ids[domain].join(';') + '?site=' + domain + '&filter=' + filters[type] + '&key=p0r10MZ01l1H4So8wqT*qA((',
function (data) {
// Go home Firefox you are drunk
if (typeof(data) === 'string') {
data = JSON.parse(data);
}
callback(data, domain);
}
);
}
});
}
}
$(document).on('focus', 'textarea[name="comment"]:not(.link-hijacked)', function () {
new HijackedTextarea($(this));
});
});