forked from dailydotdev/apps
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtextarea.ts
230 lines (192 loc) · 6.85 KB
/
textarea.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
import type { MutableRefObject } from 'react';
import { nextTick } from './func';
export const isFalsyOrSpace = (value: string): boolean =>
!value || value === ' ' || value === '\n';
const getSelectedString = (textarea: HTMLTextAreaElement) => {
const [start, end] = [textarea.selectionStart, textarea.selectionEnd];
const last = start === end ? start + 1 : end;
const text = textarea.value.substring(start, last);
const trailing = textarea.value[start - 1];
const leading = textarea.value[start - 1];
return [text, trailing, leading];
};
const splitString = (value: string, [start, end]: number[]) => {
const left = value.substring(0, start);
const right = value.substring(end);
return [left, right];
};
const concatReplacement = (
textarea: HTMLTextAreaElement,
selected: number[],
replace: string,
) => {
const [left, right] = splitString(textarea.value, selected);
return left + replace + right;
};
/* eslint-disable no-param-reassign */
export const focusInput = async (
textarea: HTMLTextAreaElement,
[start, end]: number[],
): Promise<void> => {
textarea.focus();
await nextTick(); // for the selection to work, we need to wait for the input to get updated
textarea.selectionStart = start;
textarea.selectionEnd = end;
};
export const getCloseWord = (
textarea: HTMLTextAreaElement,
selected: number[],
): [string, number] => {
const [, end] = selected;
const index = textarea.value.substring(0, end).split('\n').length - 1;
const lines = textarea.value.split('\n');
const line = lines[index];
const preLines = lines.slice(0, index).join('\n');
const offset = index === 0 ? 0 : 1;
const base = end - preLines.length - offset;
let lastIndex = 0;
let startIndex = 0;
const found = line.split(' ').find((word) => {
startIndex = lastIndex;
const current = lastIndex + word.length;
if (current >= base) {
return true;
}
lastIndex = current + 1;
return false;
});
return [found ?? '', preLines.length + startIndex + offset];
};
/**
* Enum to describe the current cursor's state.
* The character `|` denotes the cursor
* @enum CursorType
* Isolated: when the cursor is in-between spaces (ex. " | ").
* Adjacent: when the cursor is beside any character (ex. "Test |word" or "Test| word").
* Highlighted: when the cursor is highlighting any string (ex. "|Tes|t" or "|Test|").
*/
export enum CursorType {
Isolated = 'isolated',
Adjacent = 'adjacent',
Highlighted = 'highlighted',
}
export const getCursorType = (textarea: HTMLTextAreaElement): CursorType => {
const [start, end] = [textarea.selectionStart, textarea.selectionEnd];
const [highlighted, trailing] = getSelectedString(textarea);
if (isFalsyOrSpace(highlighted) && isFalsyOrSpace(trailing)) {
return CursorType.Isolated;
}
return start !== end ? CursorType.Highlighted : CursorType.Adjacent;
};
export interface GetReplacement {
addSpaceBeforeHighlighted?: boolean;
offset?: number[];
replacement: string;
}
interface GetReplacementOptionalProps {
word: string;
selection: number[];
trailingChar?: string;
leadingChar?: string;
url?: string;
}
interface Replacement {
result: string;
position: number[];
replacement: string;
}
type TypeReplacementFn = (getReplacement: GetReplacementFn) => Replacement;
type ReplacedFn = (result: string) => void;
export type GetReplacementFn = (
type: CursorType,
props: GetReplacementOptionalProps,
) => GetReplacement;
export const getTemporaryUploadString = (filename: string): string =>
`![${filename}]()`;
export class TextareaCommand {
private textareaRef: MutableRefObject<HTMLTextAreaElement>;
constructor(textareaRef: MutableRefObject<HTMLTextAreaElement>) {
this.textareaRef = textareaRef;
}
get textarea(): HTMLTextAreaElement {
return this.textareaRef.current;
}
private getIsolatedReplacement: TypeReplacementFn = (getReplacement) => {
const start = this.textarea.selectionStart;
const selection = [start, start];
const { replacement, offset } = getReplacement(CursorType.Isolated, {
word: '',
selection,
trailingChar: this.textarea.value[start - 1],
leadingChar: this.textarea.value[start + 1],
});
const result = concatReplacement(this.textarea, selection, replacement);
const index = start + replacement.length;
return { result, position: offset ?? [index, index], replacement };
};
private getAdjacentReplacement: TypeReplacementFn = (getReplacement) => {
const selection = [
this.textarea.selectionStart,
this.textarea.selectionEnd,
];
const [word, start] = getCloseWord(this.textarea, selection);
const position = [start, start + word.length];
const { replacement, offset } = getReplacement(CursorType.Adjacent, {
word,
selection: position,
});
const defaultOffset = start + replacement.length;
const result = concatReplacement(this.textarea, position, replacement);
const finalPosition = offset ?? [defaultOffset, defaultOffset];
return { result, position: finalPosition, replacement };
};
private getHighlightedReplacement: TypeReplacementFn = (getReplacement) => {
const start = this.textarea.selectionStart;
const selection = [start, this.textarea.selectionEnd];
const [highlighted, trailingChar, leadingChar] = getSelectedString(
this.textarea,
);
const { replacement, offset } = getReplacement(CursorType.Highlighted, {
word: highlighted,
trailingChar,
leadingChar,
selection,
});
const result = concatReplacement(this.textarea, selection, replacement);
const end = start + replacement.length;
return { result, position: offset ?? [end, end], replacement };
};
private getResult(getReplacement: GetReplacementFn, forcedType?: CursorType) {
const type = forcedType ?? getCursorType(this.textarea);
if (type === CursorType.Isolated) {
return this.getIsolatedReplacement(getReplacement);
}
if (type === CursorType.Highlighted) {
return this.getHighlightedReplacement(getReplacement);
}
return this.getAdjacentReplacement(getReplacement);
}
async replaceWord(
getReplacement: GetReplacementFn,
onReplaced: ReplacedFn,
forcedType?: CursorType,
): Promise<Replacement> {
const { result, position, replacement } = this.getResult(
getReplacement,
forcedType,
);
onReplaced(result);
await focusInput(this.textarea, position);
return { result, position, replacement };
}
onReplaceUpload(url: string, filename: string): string {
const temporary = getTemporaryUploadString(filename);
const start = this.textarea.value.indexOf(temporary);
const file = filename.split('.');
file.pop();
const position = [start, start + temporary.length];
const alt = file.join('.');
const replacement = ``;
return concatReplacement(this.textarea, position, replacement);
}
}