-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
insert.js
54 lines (48 loc) · 1.45 KB
/
insert.js
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
/**
* Internal dependencies
*/
import { create } from './create';
import { normaliseFormats } from './normalise-formats';
/** @typedef {import('./types').RichTextValue} RichTextValue */
/**
* Insert a Rich Text value, an HTML string, or a plain text string, into a
* Rich Text value at the given `startIndex`. Any content between `startIndex`
* and `endIndex` will be removed. Indices are retrieved from the selection if
* none are provided.
*
* @param {RichTextValue} value Value to modify.
* @param {RichTextValue|string} valueToInsert Value to insert.
* @param {number} [startIndex] Start index.
* @param {number} [endIndex] End index.
*
* @return {RichTextValue} A new value with the value inserted.
*/
export function insert(
value,
valueToInsert,
startIndex = value.start,
endIndex = value.end
) {
const { formats, replacements, text } = value;
if ( typeof valueToInsert === 'string' ) {
valueToInsert = create( { text: valueToInsert } );
}
const index = startIndex + valueToInsert.text.length;
return normaliseFormats( {
formats: formats
.slice( 0, startIndex )
.concat( valueToInsert.formats, formats.slice( endIndex ) ),
replacements: replacements
.slice( 0, startIndex )
.concat(
valueToInsert.replacements,
replacements.slice( endIndex )
),
text:
text.slice( 0, startIndex ) +
valueToInsert.text +
text.slice( endIndex ),
start: index,
end: index,
} );
}