forked from garysieling/jquery-highlighttextarea
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jquery.highlighttextarea.js
584 lines (502 loc) · 17.2 KB
/
jquery.highlighttextarea.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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
/*!
* jQuery highlightTextarea
* Copyright 2014 Damien "Mistic" Sorel (http://www.strangeplanet.fr)
* Licensed under MIT (http://opensource.org/licenses/MIT)
*/
(function($){
"use strict";
// Highlighter CLASS DEFINITON
// ===============================
var Highlighter = function($el, options) {
// global variables
this.settings = $.extend({}, Highlighter.DEFAULTS);
this.scrollbarWidth = Utilities.getScrollbarWidth();
this.isInput = $el[0].tagName.toLowerCase()=='input';
this.active = false;
// build HTML
this.$el = $el;
this.$el.wrap('<div class="highlightTextarea"></div>');
this.$main = this.$el.parent();
this.$main.prepend('<div class="highlightTextarea-container"><div class="highlightTextarea-highlighter"></div></div>');
this.$container = this.$main.children().first();
this.$highlighter = this.$container.children();
this.setOptions(options);
// set id
if (this.settings.id) {
this.$main[0].id = this.settings.id;
}
// resizable
if (this.settings.resizable) {
this.applyResizable();
}
// run
this.updateCss();
this.bindEvents();
this.highlight();
};
Highlighter.DEFAULTS = {
words: {},
ranges: {},
color: '#ffff00',
caseSensitive: true,
resizable: false,
id: '',
debug: false
};
// PUBLIC METHODS
// ===============================
/*
* Refresh highlight
*/
Highlighter.prototype.highlight = function() {
var text = Utilities.htmlEntities(this.$el.val()),
that = this;
$.each(this.settings.words, function(color, words) {
text = text.replace(
new RegExp('('+ words.join('|') +')', that.regParam),
'<mark style="background-color:'+ color +';">$1</mark>'
);
});
$.each(this.settings.ranges, function(i, range) {
if (range.start < text.length) {
text = Utilities.strInsert(text, range.end, '</mark>');
text = Utilities.strInsert(text, range.start, '<mark style="background-color:'+ range.color +';">');
}
});
this.$highlighter.html(text);
this.updateSizePosition();
};
/*
* Change highlighted words
* @param words {mixed}
*/
Highlighter.prototype.setWords = function(words) {
this.setOptions({ words: words, ranges: {} });
};
/*
* Change highlighted ranges
* @param ranges {mixed}
*/
Highlighter.prototype.setRanges = function(ranges) {
this.setOptions({ words: {}, ranges: ranges });
};
/*
* Enable highlight and events
*/
Highlighter.prototype.enable = function() {
this.bindEvents();
this.highlight();
};
/*
* Disable highlight and events
*/
Highlighter.prototype.disable = function() {
this.unbindEvents();
this.$highlighter.empty();
};
/*
* Remove the plugin
*/
Highlighter.prototype.destroy = function() {
this.disable();
Utilities.cloneCss(this.$container, this.$el, [
'background-image','background-color','background-position','background-repeat',
'background-origin','background-clip','background-size','background-attachment'
]);
this.$main.replaceWith(this.$el);
this.$el.removeData('highlighter');
};
// PRIVATE METHODS
// ===============================
/*
* Change options
* @param options {object}
*/
Highlighter.prototype.setOptions = function(options) {
if (typeof options != 'object' || $.isEmptyObject(options)) {
return;
}
$.extend(this.settings, options);
this.regParam = this.settings.caseSensitive ? 'gm' : 'gim';
if (!$.isEmptyObject(this.settings.words)) {
this.settings.words = Utilities.cleanWords(this.settings.words, this.settings.color);
this.settings.ranges = {};
}
else if (!$.isEmptyObject(this.settings.ranges)) {
this.settings.words = {};
this.settings.ranges = Utilities.cleanRanges(this.settings.ranges, this.settings.color);
}
if (this.settings.debug) {
this.$main.addClass('debug');
}
else {
this.$main.removeClass('debug');
}
if (this.active) {
this.highlight();
}
};
/*
* Attach event listeners
*/
Highlighter.prototype.bindEvents = function() {
if (this.active) {
return;
}
this.active = true;
var that = this;
// prevent positioning errors by always focusing the textarea
this.$highlighter.on({
'this.highlighter': function() {
that.$el.focus();
}
});
// add triggers to textarea
this.$el.on({
'input.highlightTextarea': Utilities.throttle(function() {
this.highlight();
}, 100, this),
'resize.highlightTextarea': Utilities.throttle(function() {
this.updateSizePosition(true);
}, 50, this),
'scroll.highlightTextarea select.highlightTextarea': Utilities.throttle(function() {
this.updateSizePosition();
}, 50, this)
});
if (this.isInput) {
this.$el.on({
// Prevent Cmd-Left Arrow and Cmd-Right Arrow on Mac strange behavior
'keydown.highlightTextarea keypress.highlightTextarea keyup.highlightTextarea': function() {
setTimeout($.proxy(that.updateSizePosition, that), 1);
},
// Force Chrome behavior on all browsers: reset input position on blur
'blur.highlightTextarea': function() {
this.value = this.value;
this.scrollLeft = 0;
that.updateSizePosition.call(that);
}
});
}
};
/*
* Detach event listeners
*/
Highlighter.prototype.unbindEvents = function() {
if (!this.active) {
return;
}
this.active = false;
this.$highlighter.off('.highlightTextarea');
this.$el.off('.highlightTextarea');
};
/*
* Update CSS of wrapper and containers
*/
Highlighter.prototype.updateCss = function() {
// the main container has the same size and position than the original textarea
Utilities.cloneCss(this.$el, this.$main, [
'float','vertical-align'
]);
this.$main.css({
'width': this.$el.outerWidth(true),
'height': this.$el.outerHeight(true)
});
// the highlighter container is positionned at "real" top-left corner of the textarea and takes its background
Utilities.cloneCss(this.$el, this.$container, [
'background-image','background-color','background-position','background-repeat',
'background-origin','background-clip','background-size','background-attachment',
'padding-top','padding-right','padding-bottom','padding-left'
]);
this.$container.css({
'top': Utilities.toPx(this.$el.css('margin-top')) + Utilities.toPx(this.$el.css('border-top-width')),
'left': Utilities.toPx(this.$el.css('margin-left')) + Utilities.toPx(this.$el.css('border-left-width')),
'width': this.$el.width(),
'height': this.$el.height()
});
// the highlighter has the same size than the "inner" textarea and must have the same font properties
Utilities.cloneCss(this.$el, this.$highlighter, [
'font-size','font-family','font-style','font-weight','font-variant','font-stretch',
'line-height','vertical-align','word-spacing','text-align','letter-spacing', 'text-rendering'
]);
// now make the textarea transparent to see the highlighter through
this.$el.css({
'background': 'none'
});
};
/*
* Apply jQueryUi Resizable if available
*/
Highlighter.prototype.applyResizable = function() {
if (jQuery.ui) {
this.$el.resizable({
'handles': 'se',
'resize': Utilities.throttle(function() {
this.updateSizePosition(true);
}, 50, this)
});
}
};
/*
* Update size and position of the highlighter
* @param forced {boolean} true to resize containers
*/
Highlighter.prototype.updateSizePosition = function(forced) {
// resize containers
if (forced) {
this.$main.css({
'width': this.$el.outerWidth(true),
'height': this.$el.outerHeight(true)
});
this.$container.css({
'width': this.$el.width(),
'height': this.$el.height()
});
}
var padding = 0, width;
if (!this.isInput) {
// account for vertical scrollbar width
if (this.$el.css('overflow') == 'scroll' ||
this.$el.css('overflow-y') == 'scroll' ||
(
this.$el.css('overflow') != 'hidden' &&
this.$el.css('overflow-y') != 'hidden' &&
this.$el[0].clientHeight < this.$el[0].scrollHeight
)
) {
padding = this.scrollbarWidth;
}
width = this.$el.width()-padding;
}
else {
// TODO: There's got to be a better way of going about this than just using 99999px...
width = 99999;
}
this.$highlighter.css({
'width': width,
'height': this.$el.height() + this.$el.scrollTop(),
'top': -this.$el.scrollTop(),
'left': -this.$el.scrollLeft()
});
};
// Utilities CLASS DEFINITON
// ===============================
var Utilities = function(){};
/*
* Get the scrollbar with on this browser
*/
Utilities.getScrollbarWidth = function() {
var parent = $('<div style="width:50px;height:50px;overflow:auto"><div> </div></div>').appendTo('body'),
child = parent.children(),
width = child.innerWidth() - child.height(100).innerWidth();
parent.remove();
return width;
};
/*
* Copy a list of CSS properties from one object to another
* @param from {jQuery}
* @param to {jQuery}
* @param what {string[]}
*/
Utilities.cloneCss = function(from, to, what) {
for (var i=0, l=what.length; i<l; i++) {
to.css(what[i], from.css(what[i]));
}
};
/*
* Convert a size value to pixels value
* @param value {mixed}
* @return {int}
*/
Utilities.toPx = function(value) {
if (value != value.replace('em', '')) {
var el = $('<div style="font-size:1em;margin:0;padding:0;height:auto;line-height:1;border:0;"> </div>').appendTo('body');
value = Math.round(parseFloat(value.replace('em', '')) * el.height());
el.remove();
return value;
}
else if (value != value.replace('px', '')) {
return parseInt(value.replace('px', ''));
}
else {
return parseInt(value);
}
};
/*
* Converts HTMl entities
* @param str {string}
* @return {string}
*/
Utilities.htmlEntities = function(str) {
if (str) {
return $('<div></div>').text(str).html();
}
else {
return '';
}
};
/*
* Inserts a string in another string at given position
* @param string {string}
* @param index {int}
* @param value {string}
* @return {string}
*/
Utilities.strInsert = function(string, index, value) {
return string.slice(0, index) + value + string.slice(index);
};
/*
* Apply throttling to a callback
* @param callback {function}
* @param delay {int} milliseconds
* @param context {object|null}
* @return {function}
*/
Utilities.throttle = function(callback, delay, context) {
var state = {
pid: null,
last: 0
};
return function() {
var elapsed = new Date().getTime() - state.last,
args = arguments,
that = this;
function exec() {
state.last = new Date().getTime();
if (context) {
return callback.apply(context, Array.prototype.slice.call(args));
}
else {
return callback.apply(that, Array.prototype.slice.call(args));
}
}
if (elapsed > delay) {
return exec();
}
else {
clearTimeout(state.pid);
state.pid = setTimeout(exec, delay - elapsed);
}
};
};
/*
* Formats a list of words into a hash of arrays (Color => Words list)
* @param words {mixed}
* @param color {string} default color
* @return {object[]}
*/
Utilities.cleanWords = function(words, color) {
var out = {};
if (!$.isArray(words)) {
words = [words];
}
for (var i=0, l=words.length; i<l; i++) {
var group = words[i];
if ($.isPlainObject(group)) {
if (!out[group.color]) {
out[group.color] = [];
}
if (!$.isArray(group.words)) {
group.words = [group.words];
}
for (var j=0, m=group.words.length; j<m; j++) {
out[group.color].push(Utilities.htmlEntities(group.words[j]));
}
}
else {
if (!out[color]) {
out[color] = [];
}
out[color].push(Utilities.htmlEntities(group));
}
}
return out;
};
/*
* Formats a list of ranges into a hash of arrays (Color => Ranges list)
* @param ranges {mixed}
* @param color {string} default color
* @return {object[]}
*/
Utilities.cleanRanges = function(ranges, color) {
var out = [];
if ($.isPlainObject(ranges) || $.isNumeric(ranges[0])) {
ranges = [ranges];
}
for (var i=0, l=ranges.length; i<l; i++) {
var range = ranges[i];
if ($.isArray(range)) {
out.push({
color: color,
start: range[0],
end: range[1]
});
}
else {
if (range.ranges) {
if ($.isPlainObject(range.ranges) || $.isNumeric(range.ranges[0])) {
range.ranges = [range.ranges];
}
for (var j=0, m=range.ranges.length; j<m; j++) {
if ($.isArray(range.ranges[j])) {
out.push({
color: range.color,
start: range.ranges[j][0],
end: range.ranges[j][1]
});
}
else {
if (range.ranges[j].length) {
range.ranges[j].end = range.ranges[j].start + range.ranges[j].length;
}
out.push(range.ranges[j]);
}
}
}
else {
if (range.length) {
range.end = range.start + range.length;
}
out.push(range);
}
}
}
out.sort(function(a, b) {
if (a.start == b.start) {
return a.end - b.end;
}
return a.start - b.start;
});
var current = -1;
$.each(out, function(i, range) {
if (range.start >= range.end) {
$.error('Invalid range end/start');
}
if (range.start < current) {
$.error('Ranges overlap');
}
current = range.end;
});
out.reverse();
return out;
};
// JQUERY PLUGIN DEFINITION
// ===============================
$.fn.highlightTextarea = function(option) {
var args = arguments;
return this.each(function() {
var $this = $(this),
data = $this.data('highlighter'),
options = typeof option == 'object' && option;
if (!data && option == 'destroy') {
return;
}
if (!data) {
data = new Highlighter($this, options);
$this.data('highlighter', data);
}
if (typeof option == 'string') {
data[option].apply(data, Array.prototype.slice.call(args, 1));
}
});
};
}(window.jQuery || window.Zepto));