forked from lonekorean/highlight-within-textarea
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jquery.highlight-within-textarea.js
218 lines (189 loc) · 6.28 KB
/
jquery.highlight-within-textarea.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
/*
* highlight-within-textarea v1.0.2
*
* @author Will Boyd
* @github https://github.com/lonekorean/highlight-within-textarea
*/
(function($) {
var ID = 'hwt';
var HighlightWithinTextarea = function($el, onInput) {
this.$el = $el;
this.onInput = onInput || this.onInput;
this.generate();
};
HighlightWithinTextarea.prototype = {
onInput: function(text) {
throw 'onInput callback not provided.'
},
generate: function() {
this.$el
.addClass(ID + '-input ' + ID + '-content')
.on('input.' + ID, this.handleInput.bind(this))
.on('scroll.' + ID, this.handleScroll.bind(this));
this.$highlights = $('<div>', { class: ID + '-highlights ' + ID + '-content' });
this.$backdrop = $('<div>', { class: ID + '-backdrop' })
.append(this.$highlights);
this.$container = $('<div>', { class: ID + '-container' })
.insertAfter(this.$el)
.append(this.$backdrop, this.$el) // moves $el into $container
.on('scroll', this.blockContainerScroll.bind(this));
this.browser = this.detectBrowser();
switch (this.browser) {
case 'firefox':
this.fixFirefox();
break;
case 'ios':
this.fixIOS();
break;
}
// pre-fire this event to highlight any existing input
this.handleInput(this.$el[0]);
},
// yeah, browser sniffing sucks, but there are browser-specific quirks
// to handle that are not a matter of feature detection
detectBrowser: function() {
var ua = window.navigator.userAgent.toLowerCase();
if (ua.indexOf('firefox') !== -1) {
return 'firefox';
} else if (!!ua.match(/msie|trident\/7|edge/)) {
return 'ie';
} else if (!!ua.match(/ipad|iphone|ipod/) && ua.indexOf('windows phone') === -1) {
// Windows Phone flags itself as "like iPhone", thus the extra check
return 'ios';
} else {
return 'other';
}
},
// Firefox doesn't show text that scrolls into the padding of a
// textarea, so rearrange a couple box models to make highlights
// behave the same way
fixFirefox: function() {
// take padding and border pixels from highlights div
var padding = this.$highlights.css([
'padding-top', 'padding-right', 'padding-bottom', 'padding-left'
]);
var border = this.$highlights.css([
'border-top-width', 'border-right-width', 'border-bottom-width', 'border-left-width'
]);
this.$highlights.css({
'padding': '0',
'border-width': '0'
});
this.$backdrop
.css({
// give padding pixels to backdrop div
'margin-top': '+=' + padding['padding-top'],
'margin-right': '+=' + padding['padding-right'],
'margin-bottom': '+=' + padding['padding-bottom'],
'margin-left': '+=' + padding['padding-left'],
})
.css({
// give border pixels to backdrop div
'margin-top': '+=' + border['border-top-width'],
'margin-right': '+=' + border['border-right-width'],
'margin-bottom': '+=' + border['border-bottom-width'],
'margin-left': '+=' + border['border-left-width'],
});
},
// iOS adds 3px of (unremovable) padding to the left and right of a
// textarea, so adjust highlights div to match
fixIOS: function() {
this.$highlights.css({
'padding-left': '+=3px',
'padding-right': '+=3px'
});
},
getType: function(instance) {
return Object.prototype.toString.call(instance)
.replace('[object ', '')
.replace(']', '')
.toLowerCase();
},
handleInput: function() {
var input = this.$el.val()
var payload = this.onInput(input);
if (payload) {
switch (this.getType(payload)) {
case 'array':
input = this.markArray(input, payload);
break;
case 'regexp':
input = this.markRegExp(input, payload);
break;
case 'object':
input = this.markObject(input, payload);
break;
default:
throw 'Unrecognized payload type returned from onInput callback.';
}
}
// this keeps scrolling aligned when input ends with a newline
input = input.replace(/\n(<\/mark>)?$/, '\n\n');
if (this.browser === 'ie') {
// IE wraps whitespace differently in a div vs textarea, this fixes it
input = input.replace(/ /g, ' <wbr>');
}
this.$highlights.html(input);
},
handleScroll: function() {
var scrollTop = this.$el.scrollTop();
this.$backdrop.scrollTop(scrollTop);
// Chrome and Safari won't break long strings of spaces, which can cause
// horizontal scrolling, this compensates by shifting highlights by the
// horizontally scrolled amount to keep things aligned
var scrollLeft = this.$el.scrollLeft();
this.$backdrop.css('transform', (scrollLeft > 0) ? 'translateX(' + -scrollLeft + 'px)' : '');
},
// in Chrome, page up/down in the textarea will shift stuff within the
// container (despite the CSS), this immediately reverts the shift
blockContainerScroll: function(e) {
this.$container.scrollLeft(0);
},
markArray: function(input, payload) {
var offset = 0;
payload.forEach(function(element) {
// insert open tag
var open = element[0] + offset;
input = input.slice(0, open) + '<mark>' + input.slice(open);
offset += 6;
// insert close tag
var close = element[1] + offset;
input = input.slice(0, close) + '</mark>' + input.slice(close);
offset += 7;
}, this);
return input;
},
markRegExp: function(input, payload) {
return input.replace(payload, '<mark>$&</mark>');
},
markObject: function(input, payload) {
for (var key in payload) {
// skip loop if the property is from prototype
if (!payload.hasOwnProperty(key)) continue;
var regex = payload[key];
input = input.replace(regex, '<mark class="'+key+'">$&</mark>');
}
return input;
},
destroy: function() {
this.$backdrop.remove();
this.$el
.unwrap()
.removeClass(ID + '-text ' + ID + '-input')
.off(ID)
.removeData(ID);
},
};
// register the jQuery plugin
$.fn.highlightWithinTextarea = function(onInput) {
return this.each(function() {
var $this = $(this);
var highlightWithinTextarea = $this.data(ID);
if (highlightWithinTextarea) {
highlightWithinTextarea.destroy();
}
highlightWithinTextarea = new HighlightWithinTextarea($this, onInput);
$this.data(ID, highlightWithinTextarea);
});
};
})(jQuery);