-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
textareaview.ts
280 lines (234 loc) · 8.5 KB
/
textareaview.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
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
/**
* @license Copyright (c) 2003-2024, CKSource Holding sp. z o.o. All rights reserved.
* For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
/**
* @module ui/textarea/textareaview
*/
import { Rect, type Locale, toUnit, getBorderWidths, global, CKEditorError, isVisible, ResizeObserver } from '@ckeditor/ckeditor5-utils';
import InputBase from '../input/inputbase.js';
import '../../theme/components/input/input.css';
import '../../theme/components/textarea/textarea.css';
/**
* The textarea view class.
*
* ```ts
* const textareaView = new TextareaView();
*
* textareaView.minRows = 2;
* textareaView.maxRows = 10;
*
* textareaView.render();
*
* document.body.append( textareaView.element );
* ```
*/
export default class TextareaView extends InputBase<HTMLTextAreaElement> {
/**
* Specifies the visible height of a text area, in lines.
*
* @observable
* @default 2
*/
declare public minRows: number;
/**
* Specifies the maximum number of rows.
*
* @observable
* @default 5
*/
declare public maxRows: number;
/**
* Specifies the value of HTML attribute that indicates whether the user can resize the element.
*
* @observable
* @default 'none'
*/
declare public resize: 'both' | 'horizontal' | 'vertical' | 'none';
/**
* An internal property that stores the current height of the textarea. Used for the DOM binding.
*
* @observable
* @default null
* @internal
*/
declare public _height: number | null;
/**
* An instance of the resize observer used to detect when the view is visible or not and update
* its height if any changes that affect it were made while it was invisible.
*
* **Note:** Created in {@link #render}.
*/
private _resizeObserver: ResizeObserver | null;
/**
* A flag that indicates whether the {@link #_updateAutoGrowHeight} method should be called when the view becomes
* visible again. See {@link #_resizeObserver}.
*/
private _isUpdateAutoGrowHeightPending: boolean = false;
/**
* @inheritDoc
*/
constructor( locale?: Locale ) {
super( locale );
const toPx = toUnit( 'px' );
this.set( 'minRows', 2 );
this.set( 'maxRows', 5 );
this.set( '_height', null );
this.set( 'resize', 'none' );
this._resizeObserver = null;
this.on( 'change:minRows', this._validateMinMaxRows.bind( this ) );
this.on( 'change:maxRows', this._validateMinMaxRows.bind( this ) );
const bind = this.bindTemplate;
this.template!.tag = 'textarea';
this.extendTemplate( {
attributes: {
class: [ 'ck-textarea' ],
style: {
height: bind.to( '_height', height => height ? toPx( height ) : null ),
resize: bind.to( 'resize' )
},
rows: bind.to( 'minRows' )
}
} );
}
/**
* @inheritDoc
*/
public override render(): void {
super.render();
let wasVisible: boolean = false;
this.on( 'input', () => {
this._updateAutoGrowHeight( true );
this.fire<TextareaViewUpdateEvent>( 'update' );
} );
this.on( 'change:value', () => {
// The content needs to be updated by the browser after the value is changed. It takes a few ms.
global.window.requestAnimationFrame( () => {
if ( !isVisible( this.element ) ) {
this._isUpdateAutoGrowHeightPending = true;
return;
}
this._updateAutoGrowHeight();
this.fire<TextareaViewUpdateEvent>( 'update' );
} );
} );
// It may occur that the Textarea size needs to be updated (e.g. because it's content was changed)
// when it is not visible or detached from DOM.
// In such case, we need to detect the moment when it becomes visible again and update its height then.
// We're using ResizeObserver for that as it is the most reliable way to detect when the element becomes visible.
// IntersectionObserver didn't work well with the absolute positioned containers.
this._resizeObserver = new ResizeObserver( this.element!, evt => {
const isVisible = !!evt.contentRect.width && !!evt.contentRect.height;
if ( !wasVisible && isVisible && this._isUpdateAutoGrowHeightPending ) {
// We're wrapping the auto-grow logic in RAF because otherwise there is an error thrown
// by the browser about recursive calls to the ResizeObserver. It used to happen in unit
// tests only, though. Since there is no risk of infinite loop here, it can stay here.
global.window.requestAnimationFrame( () => {
this._updateAutoGrowHeight();
this.fire<TextareaViewUpdateEvent>( 'update' );
} );
}
wasVisible = isVisible;
} );
}
/**
* @inheritDoc
*/
public override destroy(): void {
if ( this._resizeObserver ) {
this._resizeObserver.destroy();
}
}
/**
* @inheritDoc
*/
public override reset(): void {
super.reset();
this._updateAutoGrowHeight();
this.fire<TextareaViewUpdateEvent>( 'update' );
}
/**
* Updates the {@link #_height} of the view depending on {@link #minRows}, {@link #maxRows}, and the current content size.
*
* **Note**: This method overrides manual resize done by the user using a handle. It's a known bug.
*/
private _updateAutoGrowHeight( shouldScroll?: boolean ): void {
const viewElement = this.element!;
if ( !viewElement.offsetParent ) {
this._isUpdateAutoGrowHeightPending = true;
return;
}
this._isUpdateAutoGrowHeightPending = false;
const singleLineContentClone = getTextareaElementClone( viewElement, '1' );
const fullTextValueClone = getTextareaElementClone( viewElement, viewElement.value );
const singleLineContentStyles = singleLineContentClone.ownerDocument.defaultView!.getComputedStyle( singleLineContentClone );
const verticalPaddings = parseFloat( singleLineContentStyles.paddingTop ) + parseFloat( singleLineContentStyles.paddingBottom );
const borders = getBorderWidths( singleLineContentClone );
const lineHeight = parseFloat( singleLineContentStyles.lineHeight );
const verticalBorder = borders.top + borders.bottom;
const singleLineAreaDefaultHeight = new Rect( singleLineContentClone ).height;
const numberOfLines = Math.round( ( fullTextValueClone.scrollHeight - verticalPaddings ) / lineHeight );
const maxHeight = this.maxRows * lineHeight + verticalPaddings + verticalBorder;
// There's a --ck-ui-component-min-height CSS custom property that enforces min height of the component.
// This min-height is relevant only when there's one line of text. Other than that, we can rely on line-height.
const minHeight = numberOfLines === 1 ? singleLineAreaDefaultHeight : this.minRows * lineHeight + verticalPaddings + verticalBorder;
// The size of textarea is controlled by height style instead of rows attribute because event though it is
// a more complex solution, it is immune to the layout textarea has been rendered in (gird, flex).
this._height = Math.min(
Math.max(
Math.max( numberOfLines, this.minRows ) * lineHeight + verticalPaddings + verticalBorder,
minHeight
),
maxHeight
);
if ( shouldScroll ) {
viewElement.scrollTop = viewElement.scrollHeight;
}
singleLineContentClone.remove();
fullTextValueClone.remove();
}
/**
* Validates the {@link #minRows} and {@link #maxRows} properties and warns in the console if the configuration is incorrect.
*/
private _validateMinMaxRows() {
if ( this.minRows > this.maxRows ) {
/**
* The minimum number of rows is greater than the maximum number of rows.
*
* @error ui-textarea-view-min-rows-greater-than-max-rows
* @param textareaView The misconfigured textarea view instance.
* @param minRows The value of `minRows` property.
* @param maxRows The value of `maxRows` property.
*/
throw new CKEditorError( 'ui-textarea-view-min-rows-greater-than-max-rows', {
textareaView: this,
minRows: this.minRows,
maxRows: this.maxRows
} );
}
}
}
function getTextareaElementClone( element: HTMLTextAreaElement, value: string ): HTMLTextAreaElement {
const clone = element.cloneNode() as HTMLTextAreaElement;
clone.style.position = 'absolute';
clone.style.top = '-99999px';
clone.style.left = '-99999px';
clone.style.height = 'auto';
clone.style.overflow = 'hidden';
clone.style.width = element.ownerDocument.defaultView!.getComputedStyle( element ).width;
clone.tabIndex = -1;
clone.rows = 1;
clone.value = value;
element.parentNode!.insertBefore( clone, element );
return clone;
}
/**
* Fired every time the layout of the {@link module:ui/textarea/textareaview~TextareaView} possibly changed as a result
* of the user input or the value change via {@link module:ui/textarea/textareaview~TextareaView#value}.
*
* @eventName ~TextareaView#update
*/
export type TextareaViewUpdateEvent = {
name: 'update';
args: [];
};