From 59feec1fe24a13995da3478ed74b742e7e348364 Mon Sep 17 00:00:00 2001 From: Henry Heino <46334387+personalizedrefrigerator@users.noreply.github.com> Date: Sat, 26 Oct 2024 13:03:13 -0700 Subject: [PATCH] Desktop,Mobile: Fix list renumbering in the Markdown editor resets the first list item number to 1 (#11220) --- .../utils/renumberSelectedLists.test.ts | 26 +++++++++++++++++++ .../markdown/utils/renumberSelectedLists.ts | 10 ++++++- 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/packages/editor/CodeMirror/markdown/utils/renumberSelectedLists.test.ts b/packages/editor/CodeMirror/markdown/utils/renumberSelectedLists.test.ts index f7c4a1836..17d777a0b 100644 --- a/packages/editor/CodeMirror/markdown/utils/renumberSelectedLists.test.ts +++ b/packages/editor/CodeMirror/markdown/utils/renumberSelectedLists.test.ts @@ -38,4 +38,30 @@ describe('renumberSelectedLists', () => { '# End', ].join('\n')); }); + + it('should preserve the first list number if not 1', async () => { + const listText = [ + '2. This', + '4. is', + '5. a', + '6. test', + ].join('\n'); + + const editor = await createTestEditor( + `${listText}\n\n# End`, + EditorSelection.range(0, listText.length), + ['OrderedList', 'ATXHeading1'], + ); + + editor.dispatch(renumberSelectedLists(editor.state)); + + expect(editor.state.doc.toString()).toBe([ + '2. This', + '3. is', + '4. a', + '5. test', + '', + '# End', + ].join('\n')); + }); }); diff --git a/packages/editor/CodeMirror/markdown/utils/renumberSelectedLists.ts b/packages/editor/CodeMirror/markdown/utils/renumberSelectedLists.ts index 1e6aabfd0..e67db80b3 100644 --- a/packages/editor/CodeMirror/markdown/utils/renumberSelectedLists.ts +++ b/packages/editor/CodeMirror/markdown/utils/renumberSelectedLists.ts @@ -13,6 +13,14 @@ const renumberSelectedLists = (state: EditorState): TransactionSpec => { // Re-numbers ordered lists and sublists with numbers on each line in [linesToHandle] const handleLines = (linesToHandle: Line[]) => { const changes: ChangeSpec[] = []; + if (linesToHandle.length === 0) { + return changes; + } + + let firstListNumber = Number(listItemRegex.exec(linesToHandle[0].text)?.[2]); + if (!isFinite(firstListNumber) || firstListNumber < 1) { + firstListNumber = 1; + } type ListItemRecord = { nextListNumber: number; @@ -20,7 +28,7 @@ const renumberSelectedLists = (state: EditorState): TransactionSpec => { }; const listNumberStack: ListItemRecord[] = []; let currentGroupIndentation = ''; - let nextListNumber = 1; + let nextListNumber = firstListNumber; let prevLineNumber; for (const line of linesToHandle) {