/
messageBoxAutogrow.ts
91 lines (69 loc) · 2.34 KB
/
messageBoxAutogrow.ts
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
import _ from 'underscore';
const replaceWhitespaces = (whitespaces: string) => `${' '.repeat(whitespaces.length - 1)} `;
export const setupAutogrow = (textarea: HTMLTextAreaElement, shadow: HTMLElement, callback: (() => void) | undefined) => {
const width = textarea.clientWidth;
const height = textarea.clientHeight;
const { font, lineHeight, maxHeight: maxHeightPx } = window.getComputedStyle(textarea);
shadow.style.position = 'fixed';
shadow.style.top = '-10000px';
shadow.style.left = '-10000px';
shadow.style.width = `${width}px`;
shadow.style.font = font;
shadow.style.lineHeight = lineHeight;
shadow.style.resize = 'none';
shadow.style.wordWrap = 'break-word';
const minHeight = height;
const maxHeight = parseInt(maxHeightPx, 10);
let lastWidth = width;
let lastHeight = minHeight;
let textLenght = 0;
const update = () => {
const { clientWidth: width, value: text } = textarea;
const isMaximumHeightReached = lastHeight >= maxHeight;
const isTextLengthOutdated = textLenght && textLenght < text.length;
const wasWidthChanged = width !== lastWidth;
if (isMaximumHeightReached && isTextLengthOutdated && !wasWidthChanged) {
return true;
}
const shadowText = text
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/\n$/, '<br/> ')
.replace(/\n/g, '<br/>')
.replace(/ {2,}/g, replaceWhitespaces);
if (wasWidthChanged) {
shadow.style.width = `${width}px`;
lastWidth = width;
}
shadow.innerHTML = shadowText;
const shadowHeight = Math.max(shadow.clientHeight + 1, minHeight) + 1;
const height = Math.min(shadowHeight, maxHeight);
if (height === lastHeight) {
return true;
}
lastHeight = height;
const overflow = height < maxHeight ? 'hidden' : '';
if (height < maxHeight) {
textLenght = text.length;
}
textarea.style.overflow = overflow;
textarea.style.height = `${height}px`;
callback?.();
};
const updateThrottled = _.throttle(update, 300);
const $textarea = $(textarea);
$textarea.on('focus', update);
$textarea.on('change input', updateThrottled);
window.addEventListener('resize', updateThrottled, false);
const destroy = () => {
$textarea.off('focus', update);
$textarea.off('change input', updateThrottled);
window.removeEventListener('resize', updateThrottled);
};
update();
return {
update,
destroy,
};
};