blob: 8d51fb481ff683eba3d361e27a86ac5e208fb0ca (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
// Wraps string in at least two newlines on each side,
// as long as the field doesn't already have them.
// Code adapted from GitHub.
export default function smartBlockWrap(
content: string,
field: HTMLTextAreaElement
): string {
const before = field.value.slice(0, field.selectionStart);
const after = field.value.slice(field.selectionEnd);
const [whitespaceAtStart] = /\n*$/.exec(before)!;
const [whitespaceAtEnd] = /^\n*/.exec(after)!;
let newlinesToAppend = '';
let newlinesToPrepend = '';
if (/\S/.test(before) && whitespaceAtStart.length < 2) {
newlinesToPrepend = '\n'.repeat(2 - whitespaceAtStart.length);
}
if (/\S/.test(after) && whitespaceAtEnd.length < 2) {
newlinesToAppend = '\n'.repeat(2 - whitespaceAtEnd.length);
}
return newlinesToPrepend + content + newlinesToAppend;
}
|