Merge a style patch into a character range of styled text
In a design tool, selecting some text and clicking “Italic” or picking a color does not replace the existing formatting. It patches it: the new properties are added on top of whatever each character already has.
A document stores its text and a list of style ranges. Each range covers the characters from start (inclusive) to end (exclusive) and has a style object, a flat map from property names to strings, numbers, or booleans:
const doc = {
text: 'Ship it today',
ranges: [
{ start: 0, end: 4, style: { bold: true } }, // 'Ship'
{ start: 8, end: 13, style: { color: 'red' } }, // 'today'
],
};
Characters that no range covers have an empty style {}.
Implement applyStylePatch(doc, from, to, patch). It returns a new document with the same text, where every character from from (inclusive) to to (exclusive) has patch merged into its style.
null removes that property. Removing a property the character doesn’t have does nothing.false, 0, and '' are ordinary values, not removals.[from, to) keep their style.The input ranges are normalized, and the output ranges must be too:
start, non-empty (start < end), and non-overlapping.end equals the next one’s start) must have different styles. Styles are equal when they have the same keys with the same values (===), in any key order. Merge touching ranges with equal styles.from and to must be integers with 0 <= from <= to <= doc.text.length. Otherwise throw a RangeError. from === to is valid and changes nothing.doc, its ranges, or their style objects. The returned ranges and style objects must be new objects.// Italicize 'ip it to' (indexes 2 to 10).
applyStylePatch(doc, 2, 10, { italic: true });
// => { text: 'Ship it today', ranges: [
// { start: 0, end: 2, style: { bold: true } },
// { start: 2, end: 4, style: { bold: true, italic: true } },
// { start: 4, end: 8, style: { italic: true } },
// { start: 8, end: 10, style: { color: 'red', italic: true } },
// { start: 10, end: 13, style: { color: 'red' } },
// ] }
// Bold ' it ' too: it now touches 'Ship' with an equal style, so they merge.
applyStylePatch(doc, 4, 8, { bold: true });
// => { text: 'Ship it today', ranges: [
// { start: 0, end: 8, style: { bold: true } },
// { start: 8, end: 13, style: { color: 'red' } },
// ] }
// Remove bold from 'Sh': those characters become unstyled.
applyStylePatch(doc, 0, 2, { bold: null });
// => { text: 'Ship it today', ranges: [
// { start: 2, end: 4, style: { bold: true } },
// { start: 8, end: 13, style: { color: 'red' } },
// ] }