-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjquery.toTextarea.js
551 lines (520 loc) · 17.4 KB
/
jquery.toTextarea.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
/*
* Author: Tony Brix, http://tonybrix.info
* License: MIT
* Version: 0.4.0
*/
/*doubleEnter option added by Carl Hempel 6/19/2019*/
;
(function ($, window, document, undefined) {
// modified from http://stackoverflow.com/a/12924488/806777
var getRangeFromPoint = function (x, y) {
var range = null;
// First try ie way
if (document.body.createTextRange !== undefined) {
range = document.body.createTextRange();
range.moveToPoint(x, y);
range.select();
range = window.getSelection().getRangeAt(0);
} else if (document.createRange !== undefined) {
// Try the standards-based way next
if (document.caretPositionFromPoint) {
var pos = document.caretPositionFromPoint(x, y);
range = document.createRange();
range.setStart(pos.offsetNode, pos.offset);
range.collapse(true);
}
// Next, the WebKit way
else if (document.caretRangeFromPoint) {
range = document.caretRangeFromPoint(x, y);
}
}
return range;
};
var getLastNode = function (childNodes) {
for (var i = childNodes.length - 1; i >= 0; i--) {
if (childNodes[i].childNodes.length > 0) {
var lastNode = getLastNode(childNodes[i].childNodes);
if (lastNode !== null) {
return lastNode;
} else {
continue;
}
} else if (childNodes[i].data !== "") {
return childNodes[i];
}
}
return null;
};
// modified from http://stackoverflow.com/a/20398132/806777
var insertTextAtCursor = function (text, x, y) {
if (typeof text !== "string") {
return;
}
var sel = window.getSelection();
// fix a bug that won't create a new line if there isn't a new line at the end of the text
var textLastChar = text.substring(text.length - 1);
var fulltext = $(this).text();
var newLineNode = document.createTextNode("\n");
if (fulltext !== "") {
lastChar = fulltext.substring(fulltext.length - 1);
lastNode = getLastNode(this.childNodes);
}
var needsExtra = (textLastChar === "\n" && lastChar !== "\n" && (lastChar === null || (sel.anchorNode === lastNode && sel.anchorOffset === lastNode.length) || (sel.focusNode === lastNode && sel.focusOffset === lastNode.length)));
// make the text replace selection
var textNode = document.createTextNode(text);
var range = null;
if (x !== undefined && y !== undefined) {
range = getRangeFromPoint(x, y);
} else {
range = sel.getRangeAt(0);
}
range.deleteContents();
// check if it needs an extra new line
if (needsExtra) {
range.insertNode(newLineNode);
}
range.insertNode(textNode);
// create a new range
range = document.createRange();
range.setStartAfter(textNode);
range.collapse(true);
// make the cursor there
sel.removeAllRanges();
sel.addRange(range);
// combine text nodes
this.normalize();
};
var insertHTMLAtCursor = function (html, x, y) {
var sel = window.getSelection();
// make the text replace selection
var temp = document.createElement("div");
temp.innerHTML = html;
var htmlNodes = temp.childNodes;
var range = null;
if (x !== undefined && y !== undefined) {
range = getRangeFromPoint(x, y);
} else {
range = sel.getRangeAt(0);
}
range.deleteContents();
// insert all child nodes
var lastNode = null;
for (var i = 0; i < htmlNodes.length; i++) {
lastNode = htmlNodes[i];
range.insertNode(lastNode);
}
// create a new range
range = document.createRange();
range.setStartAfter(lastNode);
range.collapse(true);
// make the cursor there
sel.removeAllRanges();
sel.addRange(range);
// combine text nodes
this
.normalize();
};
var addImgOnDrop = function (file, caretX, caretY) {
// PENDING: make image resizable?
// PENDING: set default image dimensions?
// PENDING: resize large images to default dimensions using canvas?
// PENDING: set cursor: move; on img?
var $this = $(this);
var reader = new FileReader();
reader.onload = function (event) {
var image = new Image();
image.onload = function () {
// copy img to mouse position
var sel = window.getSelection();
var range = getRangeFromPoint(caretX, caretY);
if (range !== null) {
range.insertNode(this);
// set cursor after <img/>
range.collapse(false);
sel.removeAllRanges();
sel.addRange(range);
} else if ($this.is(":focus")) {
// add <img/> after selection
range = sel.getRangeAt(0);
range.collapse(false);
range.insertNode(this);
// set cursor after <img/>
range.collapse(false);
sel.removeAllRanges();
sel.addRange(range);
} else {
$this.append(this);
}
};
image.onerror = function () {
// PENDING: more verbose error message?
alert("Not an image");
};
image.src = event.target.result;
};
reader.readAsDataURL(file);
};
// modified from http://stackoverflow.com/a/12244703/806777
var selectAllText = function () {
if (document.body.createTextRange) {
var range = document.body.createTextRange();
range.moveToElementText(this);
range.select();
} else if (window.getSelection) {
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(this);
selection.removeAllRanges();
selection.addRange(range);
}
};
$.fn.toTextarea = function (options) {
if (options === "destroy" || options === true) {
return this.each(function () {
var $this = $(this);
if ($this.data().isTextarea) {
if (this.id) {
$("label[for='" + this.id + "']").off(".toTextarea");
}
$this
.prop({
contentEditable: false
})
.off(".toTextarea")
.data({
isTextarea: false
})
.removeClass("toTextarea-disabled toTextarea-placeholder toTextarea");
}
});
} else if (options === "disable") {
return this.each(function () {
var $this = $(this);
if ($this.data().isTextarea && !$this.data().disabled) {
if (this.id) {
$("label[for='" + this.id + "']").off(".toTextarea");
}
$this
.prop({
contentEditable: false
})
.data({
disabled: true
})
.addClass("toTextarea-disabled");
}
});
} else if (options === "enable") {
return this.each(function () {
var $this = $(this);
if ($this.data().isTextarea && $this.data().disabled) {
if (this.id) {
$("label[for='" + this.id + "']").on("click.toTextarea", function () {
$this.focus();
});
}
$this
.prop({
contentEditable: true
})
.data({
disabled: false
})
.removeClass("toTextarea-disabled");
}
});
} else {
var settings = {
allowHTML: false,
allowImg: false,
singleLine: false,
doubleEnter: false,
pastePlainText: true,
placeholder: false
};
if ($.isPlainObject(options)) {
$.extend(settings, options);
}
var cur_char = '';
var prev_char = ' ';
return this.each(function () {
var $this = $(this);
var isTextarea = $this.data().isTextarea || false;
if (!isTextarea) {
if (this.id) {
$("label[for='" + this.id + "']").on("click.toTextarea", function () {
$this.focus();
});
}
var allowHTML = settings.allowHTML;
if (typeof settings.allowHTML === "function") {
allowHTML = settings.allowHTML.call(this);
}
var allowImg = settings.allowImg;
if (typeof settings.allowImg === "function") {
allowImg = settings.allowImg.call(this);
}
var doubleEnter = settings.doubleEnter; //Added for splitting chunks automatically
if (typeof settings.doubleEnter === "function") {
doubleEnter = settings.doubleEnter.call(this);
}
var singleLine = settings.singleLine;
if (typeof settings.singleLine === "function") {
singleLine = settings.singleLine.call(this);
}
var pastePlainText = settings.pastePlainText;
if (typeof settings.pastePlainText === "function") {
pastePlainText = settings.pastePlainText.call(this);
}
var placeholder = settings.placeholder;
if (typeof settings.placeholder === "function") {
placeholder = settings.placeholder.call(this);
}
if (!placeholder) {
// check attributes
placeholder = $this.attr("placeholder") || $this.data().placeholder;
}
$this
.addClass("toTextarea")
.prop({
contentEditable: true
})
.data({
isTextarea: true,
disabled: false
})
.on("select.toTextarea", function () {
if (!$(this).data().disabled) {
selectAllText.call(this);
}
})
.on("keypress.toTextarea keyup.toTextarea", function () {
$(this).trigger("input");
});
if (placeholder) {
$this.attr({ "data-placeholder": placeholder }).addClass("toTextarea-placeholder");
}
if (doubleEnter) {
$this
.addClass("toTextarea-doubleEnter")
.on("keydown.toTextarea", function (e) {
var chunk = $(this).closest('chunk');
var wrap = $(this).closest('.wrap');
prev_char = cur_char;
cur_char = e.which;
if (!$(this).data().disabled && e.which === 13 && chunk.length != 0) {
//check if the last character is a "\n"
//if current line is empty then clone the chunk and move all data after this point into that chunk
if(cur_char == prev_char) { //change if to proper statement
e.preventDefault();
var selection = window.getSelection();
var rangeBefore = document.createRange();
var rangeAfter = document.createRange();
var r = selection.getRangeAt(0);
rangeBefore.setStart(r.startContainer,0);
rangeBefore.setEnd(r.startContainer,r.startOffset);
rangeAfter.setStart(r.endContainer,r.endOffset);
rangeAfter.setEnd(r.endContainer,r.endContainer.length);
var new_chunk_text = rangeAfter.toString();
var old_chunk_text = rangeBefore.toString();
var new_wrap = wrap.clone().insertAfter(wrap);
bind_chunk_edit(new_wrap[0]);
new_wrap.find('select').val(wrap.find('select').val());
var new_chunk = new_wrap.find('chunk');
chunk.text(old_chunk_text);
new_chunk.text(new_chunk_text).toTextarea({
doubleEnter: true,//make a single line so it will only expand horizontally
pastePlainText: false,//paste text without styling as source
placeholder: true//a placeholder when no text is entered. This can also be set by a placeholder="..." or data-placeholder="..." attribute
});
scrollIntoViewIfNeed(new_chunk[0]);
//put the cursor positioned at the end of the new chunk
var range = document.createRange();
var sel = window.getSelection();
range.setStart(new_chunk[0].childNodes[0], 0);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}
return true;
}
if (!$(this).data().disabled && e.which === 8 && chunk.length != 0) {
var prev_wrap = wrap.prev('.wrap');
var prev_chunk = prev_wrap.find('chunk');
//check if there are no characters prior to this one and there is a prev chunk
if (window.getSelection().anchorOffset == '0' && prev_wrap.length != '0') {
e.preventDefault();
var prev_chunk_length = prev_chunk.text().length;
prev_chunk.text(prev_chunk.text().replace(/^\s+|\s+$/g, '') + '\n' + chunk.text());
wrap.remove();
//put the cursor positioned at the end of the old chunk
var range = document.createRange();
var sel = window.getSelection();
range.setStart(prev_chunk[0].childNodes[0], prev_chunk_length);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}
return true;
}
});
}
if (singleLine) {
$this
.addClass("toTextarea-singleLine")
.on("keypress.toTextarea", function (e) {
if (!$(this).data().disabled && e.which === 13) {
e.preventDefault();
return false;
}
});
// if (!allowHTML || pastePlainText) {
// PENDING: not allowing pasting html for now.
$this
.on("paste.toTextarea", function (e) {
if (!$(this).data().disabled) {
var text = null;
if (window.clipboardData) {
text = window.clipboardData.getData("Text");
} else if (e.originalEvent.clipboardData) {
text = e.originalEvent.clipboardData.getData("text/plain");
} else {
return true;
}
text = text.replace(/[\n]/g, " ");
insertTextAtCursor.call(this, text);
e.preventDefault();
$(this).trigger("input");
return false;
}
})
.on("drop.toTextarea", function (e) {
if (!$(this).data().disabled) {
var text = null;
text = e.originalEvent.dataTransfer.getData("text");
text = text.replace(/[\n]/g, " ");
insertTextAtCursor.call(this, text, e.originalEvent.clientX, e.originalEvent.clientY);
e.preventDefault();
$(this).trigger("input");
return false;
}
});
/* } else {
//PENDING: this is giving me problems, For now if they allow html let it go to multiple lines.
//PENDING: maybe check after paste and remove new lines? a little jumpy but probably the only way to do it
$this
.on("paste.toTextarea", function (e) {
if (!$(this).data().disabled) {
var text = null;
if (window.clipboardData) {
text = window.clipboardData.getData("Text");
} else if (e.originalEvent.clipboardData) {
text = e.originalEvent.clipboardData.getData("text/html");
} else {
return true;
}
text = text.replace(/[\n]/g, " ");
insertHTMLAtCursor.call(this, text);
e.preventDefault();
$(this).trigger("input");
return false;
}
})
.on("drop.toTextarea", function (e) {
if (!$(this).data().disabled) {
var text = null;
text = e.originalEvent.dataTransfer.getData("text/html");
text = text.replace(/[\n]/g, " ");
insertHTMLAtCursor.call(this, text, e.originalEvent.clientX, e.originalEvent.clientY);
e.preventDefault();
$(this).trigger("input");
return false;
}
});
}*/
} else {
$this.on("keypress.toTextarea", function (e) {
if (!$(this).data().disabled && e.which === 13) {
insertTextAtCursor.call(this, "\n");
e.preventDefault();
return false;
}
});
if (!allowHTML || pastePlainText) {
$this
.on("paste.toTextarea", function (e) {
if (!$(this).data().disabled) {
var text = null;
if (window.clipboardData) {
text = window.clipboardData.getData("Text");
} else if (e.originalEvent.clipboardData) {
text = e.originalEvent.clipboardData.getData("text/plain");
} else {
return true;
}
insertTextAtCursor.call(this, text);
e.preventDefault();
$(this).trigger("input");
return false;
}
})
.on("drop.toTextarea", function (e) {
if (!$(this).data().disabled) {
var text = null;
text = e.originalEvent.dataTransfer.getData("text");
insertTextAtCursor.call(this, text, e.originalEvent.clientX, e.originalEvent.clientY);
e.preventDefault();
$(this).trigger("input");
return false;
}
});
}
}
if (allowImg) {
$this
.on("drop.toTextarea", function (e) {
if (!$(this).data().disabled && e.originalEvent.dataTransfer.files.length > 0) {
for (var i = 0, length = e.originalEvent.dataTransfer.files.length; i < length; i++) {
addImgOnDrop.call(this, e.originalEvent.dataTransfer.files[i], e.originalEvent.clientX, e.originalEvent.clientY);
}
e.preventDefault();
$(this).trigger("input");
return false;
}
})
.on("dragover.toTextarea", function (e) {
if (!$(this).data().disabled && e.originalEvent.dataTransfer.types.length > 0 && e.originalEvent.dataTransfer.types[0] === "Files") {
e.preventDefault();
return false;
}
});
}
if (!allowHTML) {
$this.on("keydown.toTextarea", function (e) {
if (!$(this).data().disabled && e.ctrlKey) {
if (e.which === 66 || e.which === 73 || e.which === 75 || e.which === 85) {
e.preventDefault();
return false;
}
}
});
}
}
});
}
};
$(function () {
var $style = ''/*$("<style class='toTextarea-stylesheet'>" +
" .toTextarea { text-align: left; border: 1px solid #aaa; white-space: pre-wrap; word-wrap: break-word; padding: 1px; }" +
" .toTextarea-singleLine { white-space: pre; }" +
" .toTextarea-disabled { background-color: var(--edit-color); color: var(--light-text-color); }" +
" .toTextarea-placeholder:empty:after { color: var(--light-text-color); font-style: italic; cursor: text; content: attr(data-placeholder); }" +
"</style>");*/
var $styles = $("head link[rel='stylesheet'], head style");
if ($styles.length > 0) {
$styles.eq(0).before($style);
} else {
$("head").append($style);
}
});
})(jQuery, window, document);