Replace text and shift, split, or merge its style ranges
Design tools and rich text editors usually store formatting separately from the text: the text is a plain string, and the styling is a list of ranges over it. Every edit to the text must shift, shrink, split, or merge those ranges.
A document looks like this:
const doc = {
text: 'Hello brave world',
ranges: [
{ start: 0, end: 5, style: 'bold' }, // 'Hello'
{ start: 6, end: 11, style: 'italic' }, // 'brave'
],
};
Each range covers the characters from start (inclusive) to end (exclusive) and has one style string. A character has at most one style. Characters that no range covers are unstyled.
Implement replaceText(doc, from, to, insert). It replaces the characters from from (inclusive) to to (exclusive) with the string insert, and returns a new document { text, ranges }.
Every character of insert gets the same style, chosen like a text editor would:
from < to (text is being replaced), use the style of the first replaced character, at index from.from - 1.0, use the style of the character at index 0.Every other character keeps its own style.
The input ranges are normalized, and the output ranges must be too:
start.start < end) and non-overlapping.from and to must be integers with 0 <= from <= to <= doc.text.length. Otherwise throw a RangeError.insert can be an empty string, which deletes the range.doc or its ranges.const doc = {
text: 'Hello brave world',
ranges: [
{ start: 0, end: 5, style: 'bold' },
{ start: 6, end: 11, style: 'italic' },
],
};
// Replace 'brave' (italic) with 'new': takes the style of 'b'.
replaceText(doc, 6, 11, 'new');
// => { text: 'Hello new world',
// ranges: [{ start: 0, end: 5, style: 'bold' }, { start: 6, end: 9, style: 'italic' }] }
// Type '!!' right after 'Hello': takes the style of 'o'.
replaceText(doc, 5, 5, '!!');
// => { text: 'Hello!! brave world',
// ranges: [{ start: 0, end: 7, style: 'bold' }, { start: 8, end: 13, style: 'italic' }] }
// Replace 'lo br' with '-': takes the style of the first 'l' (bold).
replaceText(doc, 3, 8, '-');
// => { text: 'Hel-ave world',
// ranges: [{ start: 0, end: 4, style: 'bold' }, { start: 4, end: 7, style: 'italic' }] }
// Deleting the gap joins two ranges with the same style into one.
replaceText(
{ text: 'one two', ranges: [{ start: 0, end: 3, style: 'code' }, { start: 4, end: 7, style: 'code' }] },
3, 4, ''
);
// => { text: 'onetwo', ranges: [{ start: 0, end: 6, style: 'code' }] }