-
Notifications
You must be signed in to change notification settings - Fork 71
/
MarkdownTextInput.web.tsx
784 lines (693 loc) · 27 KB
/
MarkdownTextInput.web.tsx
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
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
/* eslint-disable @typescript-eslint/no-explicit-any */
import type {
TextInput,
TextInputSubmitEditingEventData,
TextStyle,
NativeSyntheticEvent,
TextInputSelectionChangeEventData,
TextInputProps,
TextInputKeyPressEventData,
TextInputFocusEventData,
TextInputContentSizeChangeEventData,
GestureResponderEvent,
} from 'react-native';
import React, {useEffect, useRef, useCallback, useMemo, useLayoutEffect} from 'react';
import type {CSSProperties, MutableRefObject, ReactEventHandler, FocusEventHandler, MouseEvent, KeyboardEvent, SyntheticEvent, ClipboardEventHandler, TouchEvent} from 'react';
import {StyleSheet} from 'react-native';
import {updateInputStructure} from './web/utils/parserUtils';
import InputHistory from './web/InputHistory';
import type {TreeNode} from './web/utils/treeUtils';
import {getCurrentCursorPosition, removeSelection, setCursorPosition} from './web/utils/cursorUtils';
import './web/MarkdownTextInput.css';
import type {MarkdownStyle} from './MarkdownTextInputDecoratorViewNativeComponent';
import {getElementHeight, getPlaceholderValue, isEventComposing, normalizeValue, parseInnerHTMLToText} from './web/utils/inputUtils';
import {parseToReactDOMStyle, processMarkdownStyle} from './web/utils/webStyleUtils';
import {forceRefreshAllImages} from './web/inputElements/inlineImage';
import type {MarkdownRange, InlineImagesInputProps} from './commonTypes';
const useClientEffect = typeof window === 'undefined' ? useEffect : useLayoutEffect;
interface MarkdownTextInputProps extends TextInputProps, InlineImagesInputProps {
markdownStyle?: MarkdownStyle;
parser: (text: string) => MarkdownRange[];
onClick?: (e: MouseEvent<HTMLDivElement>) => void;
dir?: string;
disabled?: boolean;
}
interface MarkdownNativeEvent extends Event {
inputType?: string;
}
type MarkdownTextInput = TextInput & React.Component<MarkdownTextInputProps>;
type Selection = {
start: number;
end: number;
};
type Dimensions = {
width: number;
height: number;
};
type ParseTextResult = {
text: string;
cursorPosition: number | null;
};
let focusTimeout: NodeJS.Timeout | null = null;
type MarkdownTextInputElement = HTMLDivElement &
HTMLInputElement & {
tree: TreeNode;
selection: Selection;
imageElements: HTMLImageElement[];
};
type HTMLMarkdownElement = HTMLElement & {
value: string;
};
const MarkdownTextInput = React.forwardRef<MarkdownTextInput, MarkdownTextInputProps>(
(
{
accessibilityLabel,
accessibilityLabelledBy,
accessibilityRole,
autoCapitalize = 'sentences',
autoCorrect = true,
blurOnSubmit = false,
clearTextOnFocus,
dir = 'auto',
disabled = false,
numberOfLines,
multiline = false,
markdownStyle,
parser,
onBlur,
onChange,
onChangeText,
onClick,
onFocus,
onKeyPress,
onSelectionChange,
onSubmitEditing,
placeholder,
placeholderTextColor = `rgba(0,0,0,0.2)`,
selectTextOnFocus,
spellCheck,
selection,
style = {},
value,
autoFocus = false,
onContentSizeChange,
id,
inputMode,
onTouchStart,
maxLength,
addAuthTokenToImageURLCallback,
imagePreviewAuthRequiredURLs,
},
ref,
) => {
if (parser === undefined) {
throw new Error('[react-native-live-markdown] `parser` is undefined');
}
if (typeof parser !== 'function') {
throw new Error('[react-native-live-markdown] `parser` is not a function');
}
const compositionRef = useRef<boolean>(false);
const divRef = useRef<MarkdownTextInputElement | null>(null);
const currentlyFocusedField = useRef<HTMLDivElement | null>(null);
const contentSelection = useRef<Selection | null>(null);
const className = `react-native-live-markdown-input-${multiline ? 'multiline' : 'singleline'}`;
const history = useRef<InputHistory>();
const dimensions = useRef<Dimensions | null>(null);
const pasteContent = useRef<string | null>(null);
const hasJustBeenFocused = useRef<boolean>(false);
if (!history.current) {
history.current = new InputHistory(100, 150, value || '');
}
const flattenedStyle = useMemo(() => StyleSheet.flatten(style), [style]);
// Empty placeholder would collapse the div, so we need to use zero-width space to prevent it
const heightSafePlaceholder = useMemo(() => getPlaceholderValue(placeholder), [placeholder]);
const setEventProps = useCallback((e: NativeSyntheticEvent<any>) => {
if (divRef.current) {
const text = divRef.current.value;
if (e.target) {
// TODO: change the logic here so every event have value property
(e.target as unknown as HTMLInputElement).value = text;
}
if (e.nativeEvent && e.nativeEvent.text) {
e.nativeEvent.text = text;
}
}
return e;
}, []);
const parseText = useCallback(
(
parserFunction: (input: string) => MarkdownRange[],
target: MarkdownTextInputElement,
text: string | null,
customMarkdownStyles: MarkdownStyle,
cursorPosition: number | null = null,
shouldAddToHistory = true,
shouldForceDOMUpdate = false,
shouldScrollIntoView = false,
): ParseTextResult => {
if (!divRef.current) {
return {text: text || '', cursorPosition: null};
}
if (text === null) {
return {text: divRef.current.value, cursorPosition: null};
}
const parsedText = updateInputStructure(parserFunction, target, text, cursorPosition, multiline, customMarkdownStyles, false, shouldForceDOMUpdate, shouldScrollIntoView, {
addAuthTokenToImageURLCallback,
imagePreviewAuthRequiredURLs,
});
divRef.current.value = parsedText.text;
if (history.current && shouldAddToHistory) {
history.current.throttledAdd(parsedText.text, parsedText.cursorPosition);
}
return parsedText;
},
[addAuthTokenToImageURLCallback, imagePreviewAuthRequiredURLs, multiline],
);
const processedMarkdownStyle = useMemo(() => {
const newMarkdownStyle = processMarkdownStyle(markdownStyle);
if (divRef.current) {
parseText(parser, divRef.current, divRef.current.value, newMarkdownStyle, null, false, false);
}
return newMarkdownStyle;
}, [parser, markdownStyle, parseText]);
const inputStyles = useMemo(
() =>
StyleSheet.flatten([
styles.defaultInputStyles,
flattenedStyle && {
caretColor: (flattenedStyle as TextStyle).color || 'black',
},
{whiteSpace: multiline ? 'pre-wrap' : 'nowrap'},
disabled && styles.disabledInputStyles,
parseToReactDOMStyle(flattenedStyle),
]) as CSSProperties,
[flattenedStyle, multiline, disabled],
);
const undo = useCallback(
(target: MarkdownTextInputElement): ParseTextResult => {
if (!history.current) {
return {
text: '',
cursorPosition: 0,
};
}
const item = history.current.undo();
const undoValue = item ? item.text : null;
return parseText(parser, target, undoValue, processedMarkdownStyle, item ? item.cursorPosition : null, false);
},
[parser, parseText, processedMarkdownStyle],
);
const redo = useCallback(
(target: MarkdownTextInputElement): ParseTextResult => {
if (!history.current) {
return {
text: '',
cursorPosition: 0,
};
}
const item = history.current.redo();
const redoValue = item ? item.text : null;
return parseText(parser, target, redoValue, processedMarkdownStyle, item ? item.cursorPosition : null, false);
},
[parser, parseText, processedMarkdownStyle],
);
// Placeholder text color logic
const updateTextColor = useCallback(
(node: HTMLDivElement, text: string) => {
// eslint-disable-next-line no-param-reassign -- we need to change the style of the node, so we need to modify it
node.style.color = String(placeholder && (text === '' || text === '\n') ? placeholderTextColor : flattenedStyle.color || 'black');
},
[flattenedStyle.color, placeholder, placeholderTextColor],
);
const handleSelectionChange: ReactEventHandler<HTMLDivElement> = useCallback(
(event) => {
const e = event as unknown as NativeSyntheticEvent<TextInputSelectionChangeEventData>;
setEventProps(e);
if (onSelectionChange && contentSelection.current) {
e.nativeEvent.selection = contentSelection.current;
onSelectionChange(e);
}
},
[onSelectionChange, setEventProps],
);
const updateRefSelectionVariables = useCallback((newSelection: Selection) => {
if (!divRef.current) {
return;
}
const {start, end} = newSelection;
divRef.current.selection = {start, end};
}, []);
const updateSelection = useCallback(
(e: SyntheticEvent<HTMLDivElement>, predefinedSelection: Selection | null = null) => {
if (!divRef.current) {
return;
}
const newSelection = predefinedSelection || getCurrentCursorPosition(divRef.current);
if (newSelection && (!contentSelection.current || contentSelection.current.start !== newSelection.start || contentSelection.current.end !== newSelection.end)) {
updateRefSelectionVariables(newSelection);
contentSelection.current = newSelection;
handleSelectionChange(e);
}
},
[handleSelectionChange, updateRefSelectionVariables],
);
const handleOnSelect = useCallback(
(e: React.SyntheticEvent<HTMLDivElement>) => {
updateSelection(e);
// If the input has just been focused, we need to scroll the cursor into view
if (divRef.current && contentSelection.current && hasJustBeenFocused.current) {
setCursorPosition(divRef.current, contentSelection.current?.start, contentSelection.current?.end, true);
hasJustBeenFocused.current = false;
}
},
[updateSelection],
);
const handleContentSizeChange = useCallback(() => {
if (!divRef.current || !multiline || !onContentSizeChange) {
return;
}
const {offsetWidth: newWidth, offsetHeight: newHeight} = divRef.current;
if (newHeight !== dimensions.current?.height || newWidth !== dimensions.current.width) {
dimensions.current = {height: newHeight, width: newWidth};
onContentSizeChange({
nativeEvent: {
contentSize: dimensions.current,
},
} as NativeSyntheticEvent<TextInputContentSizeChangeEventData>);
}
}, [multiline, onContentSizeChange]);
const handleOnChangeText = useCallback(
(e: SyntheticEvent<HTMLDivElement>) => {
if (!divRef.current || !(e.target instanceof HTMLElement) || !contentSelection.current) {
return;
}
const nativeEvent = e.nativeEvent as MarkdownNativeEvent;
const inputType = nativeEvent.inputType;
updateTextColor(divRef.current, e.target.textContent ?? '');
const previousText = divRef.current.value;
let parsedText = normalizeValue(
inputType === 'pasteText' ? pasteContent.current || '' : parseInnerHTMLToText(e.target as MarkdownTextInputElement, contentSelection.current.start, inputType),
);
if (pasteContent.current) {
pasteContent.current = null;
}
if (maxLength !== undefined && parsedText.length > maxLength) {
parsedText = previousText;
}
const prevSelection = contentSelection.current ?? {start: 0, end: 0};
const newCursorPosition =
inputType === 'deleteContentForward' && contentSelection.current.start === contentSelection.current.end
? Math.max(contentSelection.current.start, 0) // Don't move the caret when deleting forward with no characters selected
: Math.max(Math.max(contentSelection.current.end, 0) + (parsedText.length - previousText.length), 0);
if (compositionRef.current) {
updateTextColor(divRef.current, parsedText);
updateSelection(e, {
start: newCursorPosition,
end: newCursorPosition,
});
divRef.current.value = parsedText;
if (onChangeText) {
onChangeText(parsedText);
}
return;
}
let newInputUpdate: ParseTextResult;
switch (inputType) {
case 'historyUndo':
newInputUpdate = undo(divRef.current);
break;
case 'historyRedo':
newInputUpdate = redo(divRef.current);
break;
default:
newInputUpdate = parseText(parser, divRef.current, parsedText, processedMarkdownStyle, newCursorPosition, true, !inputType, inputType === 'pasteText');
}
const {text, cursorPosition} = newInputUpdate;
updateTextColor(divRef.current, text);
updateSelection(e, {
start: cursorPosition ?? 0,
end: cursorPosition ?? 0,
});
if (onChange) {
const event = e as unknown as NativeSyntheticEvent<{
count: number;
before: number;
start: number;
}>;
setEventProps(event);
// The new text is between the prev start selection and the new end selection, can be empty
const addedText = text.slice(prevSelection.start, cursorPosition ?? 0);
// The length of the text that replaced the before text
const count = addedText.length;
// The start index of the replacement operation
let start = prevSelection.start;
const prevSelectionRange = prevSelection.end - prevSelection.start;
// The length the deleted text had before
let before = prevSelectionRange;
if (prevSelectionRange === 0 && (inputType === 'deleteContentBackward' || inputType === 'deleteContentForward')) {
// its possible the user pressed a delete key without a selection range, so we need to adjust the before value to have the length of the deleted text
before = previousText.length - text.length;
}
if (inputType === 'deleteContentBackward') {
// When the user does a backspace delete he expects the content before the cursor to be removed.
// For this the start value needs to be adjusted (its as if the selection was before the text that we want to delete)
start = Math.max(start - before, 0);
}
event.nativeEvent.count = count;
event.nativeEvent.before = before;
event.nativeEvent.start = start;
// @ts-expect-error TODO: Remove once react native PR merged https://github.com/facebook/react-native/pull/45248
onChange(event);
}
if (onChangeText) {
onChangeText(text);
}
handleContentSizeChange();
},
[parser, updateTextColor, updateSelection, onChange, onChangeText, handleContentSizeChange, undo, redo, parseText, processedMarkdownStyle, setEventProps, maxLength],
);
const insertText = useCallback(
(e: SyntheticEvent<HTMLDivElement, Event>, text: string) => {
if (!contentSelection.current || !divRef.current) {
return;
}
const previousText = divRef.current.value;
let insertedText = text;
let availableLength = text.length;
const prefix = divRef.current.value.substring(0, contentSelection.current.start);
const suffix = divRef.current.value.substring(contentSelection.current.end);
if (maxLength !== undefined) {
availableLength = maxLength - prefix.length - suffix.length;
insertedText = text.slice(0, Math.max(availableLength, 0));
}
const newText = `${prefix}${insertedText}${suffix}`;
if (previousText === newText) {
document.execCommand('delete');
}
pasteContent.current = availableLength > 0 ? newText : previousText;
(e.nativeEvent as MarkdownNativeEvent).inputType = 'pasteText';
handleOnChangeText(e);
},
[handleOnChangeText, maxLength],
);
const handleKeyPress = useCallback(
(e: KeyboardEvent<HTMLDivElement>) => {
if (!divRef.current) {
return;
}
const hostNode = e.target;
e.stopPropagation();
if (e.key === 'z' && (e.ctrlKey || e.metaKey)) {
e.preventDefault();
const nativeEvent = e.nativeEvent as unknown as MarkdownNativeEvent;
if (e.shiftKey) {
nativeEvent.inputType = 'historyRedo';
} else {
nativeEvent.inputType = 'historyUndo';
}
handleOnChangeText(e);
return;
}
const blurOnSubmitDefault = !multiline;
const shouldBlurOnSubmit = blurOnSubmit === null ? blurOnSubmitDefault : blurOnSubmit;
const nativeEvent = e.nativeEvent;
const isComposing = isEventComposing(nativeEvent);
const event = e as unknown as NativeSyntheticEvent<TextInputKeyPressEventData>;
setEventProps(event);
if (onKeyPress) {
onKeyPress(event);
}
if (
e.key === 'Enter' &&
// Do not call submit if composition is occuring.
!isComposing &&
!e.isDefaultPrevented()
) {
// prevent "Enter" from inserting a newline or submitting a form
e.preventDefault();
if (!e.shiftKey && (blurOnSubmit || !multiline) && onSubmitEditing) {
onSubmitEditing(event as unknown as NativeSyntheticEvent<TextInputSubmitEditingEventData>);
} else if (multiline) {
// We need to change normal behavior of "Enter" key to insert a line breaks, to prevent wrapping contentEditable text in <div> tags.
// Thanks to that in every situation we have proper amount of new lines in our parsed text. Without it pressing enter in empty lines will add 2 more new lines.
insertText(e, '\n');
}
if (!e.shiftKey && ((shouldBlurOnSubmit && hostNode !== null) || !multiline)) {
setTimeout(() => divRef.current && divRef.current.blur(), 0);
}
}
},
[multiline, blurOnSubmit, setEventProps, onKeyPress, handleOnChangeText, onSubmitEditing, insertText],
);
const handleFocus: FocusEventHandler<HTMLDivElement> = useCallback(
(event) => {
hasJustBeenFocused.current = true;
const e = event as unknown as NativeSyntheticEvent<TextInputFocusEventData>;
const hostNode = e.target as unknown as HTMLDivElement;
currentlyFocusedField.current = hostNode;
setEventProps(e);
if (divRef.current) {
if (contentSelection.current) {
setCursorPosition(divRef.current, contentSelection.current.start, contentSelection.current.end);
} else {
const valueLength = value ? value.length : (divRef.current.value || '').length;
setCursorPosition(divRef.current, valueLength, null);
}
}
if (divRef.current) {
divRef.current.scrollIntoView({
block: 'nearest',
});
}
if (onFocus) {
setEventProps(e);
onFocus(e);
}
if (hostNode !== null) {
if (clearTextOnFocus && divRef.current) {
divRef.current.textContent = '';
}
if (selectTextOnFocus) {
// Safari requires selection to occur in a setTimeout
if (focusTimeout !== null) {
clearTimeout(focusTimeout);
}
focusTimeout = setTimeout(() => {
if (hostNode === null) {
return;
}
document.execCommand('selectAll', false, '');
}, 0);
}
}
},
[clearTextOnFocus, onFocus, selectTextOnFocus, setEventProps, value],
);
const handleBlur: FocusEventHandler<HTMLDivElement> = useCallback(
(event) => {
const e = event as unknown as NativeSyntheticEvent<TextInputFocusEventData>;
removeSelection();
currentlyFocusedField.current = null;
if (onBlur) {
setEventProps(e);
onBlur(e);
}
},
[onBlur, setEventProps],
);
const handleClick = useCallback(
(e: MouseEvent<HTMLDivElement, globalThis.MouseEvent>) => {
if (!onClick || !divRef.current) {
return;
}
(e.target as HTMLInputElement).value = divRef.current.value;
onClick(e);
},
[onClick],
);
const handleCopy: ClipboardEventHandler<HTMLDivElement> = useCallback((e) => {
if (!divRef.current || !contentSelection.current) {
return;
}
e.preventDefault();
const text = divRef.current?.value.substring(contentSelection.current.start, contentSelection.current.end);
e.clipboardData.setData('text/plain', text ?? '');
}, []);
const handleCut = useCallback(
(e: React.ClipboardEvent<HTMLDivElement>) => {
if (!divRef.current || !contentSelection.current) {
return;
}
handleCopy(e);
if (contentSelection.current.start !== contentSelection.current.end) {
document.execCommand('delete');
}
},
[handleCopy],
);
const handlePaste = useCallback(
(e: React.ClipboardEvent<HTMLDivElement>) => {
if (e.isDefaultPrevented() || !divRef.current || !contentSelection.current) {
return;
}
e.preventDefault();
const clipboardData = e.clipboardData;
const text = clipboardData.getData('text/plain');
insertText(e, text);
},
[insertText],
);
const startComposition = useCallback(() => {
compositionRef.current = true;
}, []);
const endComposition = useCallback(
(e: React.CompositionEvent<HTMLDivElement>) => {
compositionRef.current = false;
handleOnChangeText(e);
},
[handleOnChangeText],
);
const setRef = (currentRef: HTMLDivElement | null) => {
const r = currentRef;
if (r) {
(r as unknown as TextInput).isFocused = () => document.activeElement === r;
(r as unknown as TextInput).clear = () => {
r.textContent = '';
updateTextColor(r, '');
};
if (value === '' || value === undefined) {
// update to placeholder color when value is empty
updateTextColor(r, r.textContent ?? '');
}
}
if (ref) {
if (typeof ref === 'object') {
// eslint-disable-next-line no-param-reassign
(ref as MutableRefObject<HTMLDivElement | null>).current = r;
} else if (typeof ref === 'function') {
(ref as (elementRef: HTMLDivElement | null) => void)(r);
}
}
divRef.current = r as MarkdownTextInputElement;
};
const handleTouchStart = (event: TouchEvent<HTMLDivElement>) => {
if (!onTouchStart) {
return;
}
const e = event as unknown as GestureResponderEvent;
onTouchStart(e);
};
useClientEffect(
function parseAndStyleValue() {
if (!divRef.current || value === divRef.current.value) {
return;
}
if (value === undefined) {
parseText(parser, divRef.current, divRef.current.value, processedMarkdownStyle);
return;
}
const normalizedValue = normalizeValue(value);
divRef.current.value = normalizedValue;
parseText(parser, divRef.current, normalizedValue, processedMarkdownStyle, null, true, false, true);
updateTextColor(divRef.current, value);
},
[parser, multiline, processedMarkdownStyle, value, maxLength],
);
useClientEffect(
function adjustHeight() {
if (!divRef.current || !multiline) {
return;
}
const elementHeight = getElementHeight(divRef.current, inputStyles, numberOfLines);
divRef.current.style.height = elementHeight;
divRef.current.style.maxHeight = elementHeight;
},
[numberOfLines],
);
useEffect(() => {
if (!divRef.current) {
return;
}
// focus the input on mount if autoFocus is set
if (autoFocus) {
divRef.current.focus();
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useEffect(() => {
// update content size when the input styles change
handleContentSizeChange();
}, [handleContentSizeChange, inputStyles]);
useEffect(() => {
if (!divRef.current || !selection || (contentSelection.current && selection.start === contentSelection.current.start && selection.end === contentSelection.current.end)) {
return;
}
const newSelection: Selection = {start: selection.start, end: selection.end ?? selection.start};
contentSelection.current = newSelection;
updateRefSelectionVariables(newSelection);
setCursorPosition(divRef.current, newSelection.start, newSelection.end);
}, [selection, updateRefSelectionVariables]);
useEffect(() => {
const handleReconnect = () => {
forceRefreshAllImages(divRef.current as MarkdownTextInputElement, processedMarkdownStyle);
};
window.addEventListener('online', handleReconnect);
return () => {
window.removeEventListener('online', handleReconnect);
};
}, [processedMarkdownStyle]);
return (
// eslint-disable-next-line jsx-a11y/no-static-element-interactions
<div
id={id}
ref={setRef}
contentEditable={!disabled}
style={inputStyles}
role={accessibilityRole || 'textbox'}
aria-label={accessibilityLabel}
aria-labelledby={`${accessibilityLabelledBy}`}
aria-placeholder={heightSafePlaceholder}
aria-multiline={multiline}
autoCorrect={autoCorrect ? 'on' : 'off'}
autoCapitalize={autoCapitalize}
className={className}
onKeyDown={handleKeyPress}
onCompositionStart={startComposition}
onCompositionEnd={endComposition}
onInput={handleOnChangeText}
onClick={handleClick}
onFocus={handleFocus}
onBlur={handleBlur}
onCopy={handleCopy}
onCut={handleCut}
onPaste={handlePaste}
// @ts-expect-error: we use placeholder prop to style it in CSS even though its not handled internally
placeholder={heightSafePlaceholder}
spellCheck={spellCheck}
dir={dir}
inputMode={inputMode}
onSelect={handleOnSelect}
onTouchStart={handleTouchStart}
/>
);
},
);
const styles = StyleSheet.create({
defaultInputStyles: {
borderColor: 'black',
borderWidth: 1,
borderStyle: 'solid',
fontFamily: 'sans-serif',
// @ts-expect-error it works on web
boxSizing: 'border-box',
overflowY: 'auto',
overflowX: 'auto',
overflowWrap: 'break-word',
},
disabledInputStyles: {
opacity: 0.75,
cursor: 'auto',
},
});
export default MarkdownTextInput;
export type {MarkdownTextInputProps, MarkdownTextInputElement, HTMLMarkdownElement};