Slice a string and clip its overlapping style ranges to match
When you copy part of a text layer in a design tool, the clipboard must carry the formatting of just the copied characters. The tool stores text as a plain string plus a list of style ranges, so copying means slicing the string and cutting the ranges down to match.
A styled document looks like this:
const doc = {
text: 'Launch day is Friday',
ranges: [
{ start: 0, end: 6, style: 'bold' }, // 'Launch'
{ start: 4, end: 10, style: 'italic' }, // 'ch day'
{ start: 14, end: 20, style: 'link' }, // 'Friday'
],
};
Each range covers the characters from start (inclusive) to end (exclusive) and applies one style string. Ranges with different styles can overlap (a character can be bold and italic). Ranges in the input are not sorted, and can be empty (start === end). You can assume 0 <= start <= end <= text.length for every input range.
Implement sliceStyledText(doc, start, end). It returns a new document { text, ranges } for the characters doc.text.slice(start, end).
String.prototype.slice: start defaults to 0, end defaults to the text length, negative values count from the end, values are clamped to the text, and if start is not before end the result is { text: '', ranges: [] }.0).a.end >= b.start) into one range. Ranges with different styles are never merged.start, then end, then style (plain < string comparison).doc or its ranges. Return new range objects with exactly the keys start, end, and style.sliceStyledText(doc, 4, 17);
// => {
// text: 'ch day is Fri',
// ranges: [
// { start: 0, end: 2, style: 'bold' }, // 'ch'
// { start: 0, end: 6, style: 'italic' }, // 'ch day'
// { start: 10, end: 13, style: 'link' }, // 'Fri'
// ],
// }
sliceStyledText(doc, -6);
// => { text: 'Friday', ranges: [{ start: 0, end: 6, style: 'link' }] }
sliceStyledText(
{
text: 'abcdefgh',
ranges: [
{ start: 5, end: 8, style: 'bold' },
{ start: 0, end: 3, style: 'bold' },
{ start: 3, end: 5, style: 'bold' },
{ start: 2, end: 2, style: 'code' },
],
},
1,
);
// => { text: 'bcdefgh', ranges: [{ start: 0, end: 7, style: 'bold' }] }
// (the three touching bold ranges merge; the empty code range is dropped)
sliceStyledText(doc, 8, 3);
// => { text: '', ranges: [] }