From 092936b69d838fa0b6d904bb7ee009a7316341d0 Mon Sep 17 00:00:00 2001 From: Scott Nonnenberg Date: Fri, 10 Nov 2023 15:10:39 -0800 Subject: [PATCH] getTextAndRangesFromOps: Don't trim leading whitespace if monospace --- ts/quill/util.ts | 18 +++++++++++++++-- ts/test-node/quill/util_test.ts | 36 +++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 2 deletions(-) diff --git a/ts/quill/util.ts b/ts/quill/util.ts index 7f3f733ce..73a26f93b 100644 --- a/ts/quill/util.ts +++ b/ts/quill/util.ts @@ -157,6 +157,7 @@ export const getTextAndRangesFromOps = ( ops: Array ): { text: string; bodyRanges: DraftBodyRanges } => { const startingBodyRanges: Array = []; + let earliestMonospaceIndex = Number.MAX_SAFE_INTEGER; let formats: Record = { [BOLD]: undefined, [ITALIC]: undefined, @@ -175,6 +176,12 @@ export const getTextAndRangesFromOps = ( // Start or finish format sections as needed formats = extractAllFormats(startingBodyRanges, formats, acc.length, op); + const newMonospaceStart = + formats[MONOSPACE]?.start ?? earliestMonospaceIndex; + if (newMonospaceStart < earliestMonospaceIndex) { + earliestMonospaceIndex = newMonospaceStart; + } + if (typeof op.insert === 'string') { return acc + op.insert; } @@ -201,8 +208,15 @@ export const getTextAndRangesFromOps = ( extractAllFormats(startingBodyRanges, formats, preTrimText.length); // Now repair bodyRanges after trimming - const trimStart = preTrimText.trimStart(); - const trimmedFromStart = preTrimText.length - trimStart.length; + let trimStart = preTrimText.trimStart(); + let trimmedFromStart = preTrimText.length - trimStart.length; + + // We don't want to trim leading monospace text + if (earliestMonospaceIndex < trimmedFromStart) { + trimStart = preTrimText.slice(earliestMonospaceIndex); + trimmedFromStart = earliestMonospaceIndex; + } + const text = trimStart.trimEnd(); const textLength = text.length; diff --git a/ts/test-node/quill/util_test.ts b/ts/test-node/quill/util_test.ts index ceee76240..a49655431 100644 --- a/ts/test-node/quill/util_test.ts +++ b/ts/test-node/quill/util_test.ts @@ -224,6 +224,42 @@ describe('getTextAndRangesFromOps', () => { ]); }); + it('does not trim at beginning of the message if monospace', () => { + const ops = [ + { + insert: ' ', + }, + { + insert: ' Text with leading ', + attributes: { monospace: true }, + }, + { + insert: 'whitespace!!', + attributes: { bold: true, italic: true }, + }, + ]; + const { text, bodyRanges } = getTextAndRangesFromOps(ops); + assert.equal(text, ' Text with leading whitespace!!'); + assert.equal(bodyRanges.length, 3); + assert.deepEqual(bodyRanges, [ + { + start: 0, + length: 20, + style: BodyRange.Style.MONOSPACE, + }, + { + start: 20, + length: 12, + style: BodyRange.Style.BOLD, + }, + { + start: 20, + length: 12, + style: BodyRange.Style.ITALIC, + }, + ]); + }); + it('handles formatting of whitespace at beginning/ending of message', () => { const ops = [ {