-
Notifications
You must be signed in to change notification settings - Fork 4
/
util.js
324 lines (288 loc) 路 8.69 KB
/
util.js
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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
'use strict';
const path = require('path');
const shell = require('shell');
const remote = require('remote');
const Menu = remote.require('menu');
const MenuItem = remote.require('menu-item');
const webFrame = require('electron').webFrame;
try {
const checker = require('spellchecker');
} catch (e) {
console.log(e);
}
/**
* Activates spell checking for every text input that is in the application
* At the moment the default language is en-US, this will eventually be
* determined by the language selected in the settings
* @return {void} void
*/
function activateSpellChecking() {
// Return if spell checker isn't found
if (typeof checker === 'undefined') return;
// set the initial context menu so that a context menu exists even before spellcheck is called
let template = [{
label: 'Copy',
role: 'copy',
}, {
label: 'Paste',
role: 'paste',
}, {
label: 'Cut',
role: 'cut',
}];
let menu = new Menu();
menu = Menu.buildFromTemplate(template);
webFrame.setSpellCheckProvider("en-US", false, {
spellCheck: function (text) {
if (checker.isMisspelled(text)) {
//if this is a misspelling, get suggestions
let options = checker.getCorrectionsForMisspelling(text);
// get the number of suggestions if any
let numSuggestions = options.length ? options.length : 0;
// restrict it to 3 suggestions
let maxItems = numSuggestions > 3 ? 3 : numSuggestions;
let lastSuggestion = null;
// if there are suggestions
if (maxItems > 0) {
for (var i = maxItems - 1; i >= 0; i--) {
let item = options[i];
template.unshift({
label: item,
click: function (menuItem, browserWindow) {
remote.getCurrentWebContents().replaceMisspelling(menuItem.label);
}
});
}
lastSuggestion = maxItems;
template.splice(lastSuggestion, 0, {
type: 'separator'
});
} else {
// no suggestions found
template.unshift({
label: 'no suggestions',
click: function () {}
});
lastSuggestion = maxItems + 1;
template.splice(lastSuggestion, 0, {
type: 'separator'
});
}
}
// build the new template for the context menu
menu = Menu.buildFromTemplate(template);
//reset the template object
template = [{
label: 'Copy',
role: 'copy',
}, {
label: 'Paste',
role: 'paste',
}, {
label: 'Cut',
role: 'cut',
}];
return !checker.isMisspelled(text);
}
});
$('input').on('contextmenu', function (e) {
// use current menu, probably the one that was built the last time spellcheck ran
menu.popup(remote.getCurrentWindow());
// build a new one with only select all in it
menu = Menu.buildFromTemplate(template);
})
}
/**
* Autocompletes a list of users and returns the next matched user.
* @param {string} str String that is used for autocompletion
* @param {array} users List of users
* @param {function} callback callback
* @return {string} Username that was matched
*/
function autocomplete(str, users, callback) {
for (let key in users) {
let user = users[key];
user = user.split(':')[0];
//Check if str is the start of user
if (user.indexOf(str) === 0) {
callback(user);
}
}
}
/**
* Fills the usermenu with the entries from the given array.
* @param {array} usersArr Array of users
* @return {void} void
*/
function fillUsermenu(usersArr) {
$('usermenu users').empty();
let sortedUsers = usersArr.sort(function (a, b) {
return (a.name > b.name) - (a.name < b.name);
});
for (let key in sortedUsers) {
let user = sortedUsers[key];
if (user.rank === '') {
$('usermenu users').append('<user>' + user.name + '</user>');
} else if (user.rank === '+') {
$('usermenu users').append('<user><i class="fa fa-user-plus"></i>' + user.name + '</user>');
} else if (user.rank === '%') {
$('usermenu users').append('<user><i class="fa fa-percent"></i>' + user.name + '</user>');
} else if (user.rank === '@') {
$('usermenu users').append('<user><i class="fa fa-user-md"></i>' + user.name + '</user>');
} else {
$('usermenu users').append('<user>' + user.name + '</user>');
}
}
$('usermenu').attr('data-before', usersArr.length);
}
/**
* Use native notification-system libnotify. Works on most Mac and
* Linux systems, no support for windows.
* @param {string} title Title to display
* @param {string} body Body to display
* @return {void} void
*/
function doNotify(title, body) {
let options = {
title: title,
body: body,
icon: path.join(__dirname, '../images/icon.png')
};
new Notification(options.title, options);
}
/**
* Escapes all potentially dangerous characters, so that the
* resulting string can be safely inserted into attribute or
* element text.
* @param value
* @returns {string} escaped text
*/
function encodeEntities(value) {
let surrogate_pair_regexp = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
// Match everything outside of normal chars and " (quote character)
let non_alphanumeric_regexp = /([^\#-~| |!])/g;
return value.
replace(/&/g, '&').
replace(surrogate_pair_regexp, function (value) {
let hi = value.charCodeAt(0);
let low = value.charCodeAt(1);
return '&#' + (((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000) + ';';
}).
replace(non_alphanumeric_regexp, function (value) {
return '&#' + value.charCodeAt(0) + ';';
}).
replace(/</g, '<').
replace(/>/g, '>');
}
/**
* Takes a string and returns a matching color for that specific string.
* @param {string} str String to match against
* @return {string} Hex-color code
*/
function stringToColour(str) {
let colorsExtrapol = [];
let colors = [
'#859900', '#cb4b16',
'#4dd1c6', '#dc322f',
'#268bd2', '#6c71c4',
'#d33682', '#b58900'
]
for (let i = 0; i < colors.length; i++) {
let hsvColor = please.HEX_to_HSV(colors[i]);
let scheme = please.make_scheme(hsvColor, {
scheme_type: 'analogous',
format: 'hex'
})
colorsExtrapol = colorsExtrapol.concat(scheme);
}
let hashCode = str.hashCode();
let number = Math.abs(hashCode % colorsExtrapol.length);
return colorsExtrapol[number];
}
/**
* Sets the scrollState of the messageArea to the last appended line.
* @return {void} void
*/
function updateScrollState() {
//Scroll to last appended message
$("#messageArea").animate({
scrollTop: $("#messageArea")[0].scrollHeight
}, 0);
}
function setCursorToEnd(jqObj) {
//Scroll to the right in case the input field is long
jqObj[0].scrollLeft = jqObj[0].scrollWidth;
//Multiply by 2 to make sure it is always the end
let strLength = jqObj.val().length * 2;
jqObj[0].setSelectionRange(strLength, strLength);
}
/**
* Regex that matches urls in a string in a permissive way.
* @param {string} str String to match against
* @return {boolean} If the string contains urls
*/
function findLinks(str) {
let pattern = /\b(?:[a-z]{2,}?:\/\/)?([^\s./]+\.)+[^\d\s./:?]\w+(?::\d{1,5})?(?:\/[^\s]*\b|\b)(?![:.?#]\S)/gi;
return str.match(pattern);
}
/**
* Checks if the last nick appended is unique until the next nick. This is
* used to remove the nickname from the ui when possible, e.g. when one
* user sends multiple messages.
* @param {string} nextNick The next nick to be appended
* @param {jquery-object} $channel The dom node where the nicks are at
* @return {boolean} If nick is unique
*/
function lastNicksUnique(nextNick, $channel) {
let unique = true;
let iteratedNicks = [];
//Get last nicks of provided channel
let lastNicks = $channel.find('line nick');
//Iterate over nicks in reverse, break if nextNick is not empty,
//add all nicks to a list
$(lastNicks).reverse().each(function () {
iteratedNicks.push($(this).text());
if ($(this).text() !== '') {
return false;
}
})
//Iterate over all nicks, return true when nick is not nextNick,
//return false, when nick is empty or nextNick
for (let key in iteratedNicks) {
let nick = iteratedNicks[key];
if (nick != nextNick) {
unique = true;
} else if (nick === '' || nick == nextNick) {
unique = false;
//Break loop since nick can't be unique anymore
break;
}
}
return unique;
}
/**
* Opens a given url with the default browser of the systems
* @param {string} string Url to open
* @return {void} void
*/
function openLink(string) {
//Check if "http://" is there and add it if necessary
if (string.match(/^[^/]+:\/\//)) {
shell.openExternal(string);
} else {
shell.openExternal('http://' + string);
}
}
module.exports = {
activateSpellChecking: activateSpellChecking,
autocomplete: autocomplete,
fillUsermenu: fillUsermenu,
doNotify: doNotify,
encodeEntities: encodeEntities,
stringToColour: stringToColour,
lastNicksUnique: lastNicksUnique,
findLinks: findLinks,
updateScrollState: updateScrollState,
setCursorToEnd: setCursorToEnd,
openLink: openLink
}