getTextAndRangesFromOps: Don't trim leading whitespace if monospace

This commit is contained in:
Scott Nonnenberg 2023-11-10 15:10:39 -08:00 committed by GitHub
parent 61b4558140
commit 092936b69d
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 52 additions and 2 deletions

View file

@ -157,6 +157,7 @@ export const getTextAndRangesFromOps = (
ops: Array<Op>
): { text: string; bodyRanges: DraftBodyRanges } => {
const startingBodyRanges: Array<DraftBodyRange> = [];
let earliestMonospaceIndex = Number.MAX_SAFE_INTEGER;
let formats: Record<BodyRange.Style, { start: number } | undefined> = {
[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;

View file

@ -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 = [
{