diff --git a/components/form.js b/components/form.js index 9864b0ea..b34af25f 100644 --- a/components/form.js +++ b/components/form.js @@ -360,12 +360,22 @@ export function MarkdownInput ({ label, topLevel, groupClassName, onChange, onKe onUpload={file => { const uploadMarker = `![Uploading ${file.name}…]()` const text = innerRef.current.value - const cursorPosition = innerRef.current.selectionStart || text.length + const cursorPosition = innerRef.current.selectionStart let preMarker = text.slice(0, cursorPosition) - const postMarker = text.slice(cursorPosition) + let postMarker = text.slice(cursorPosition) // when uploading multiple files at once, we want to make sure the upload markers are separated by blank lines - if (preMarker && !/\n+\s*$/.test(preMarker)) { - preMarker += '\n\n' + if (preMarker) { + // Count existing newlines at the end of preMarker + const existingNewlines = preMarker.match(/[\n]+$/)?.[0].length || 0 + // Add only the needed newlines to reach 2 + preMarker += '\n'.repeat(Math.max(0, 2 - existingNewlines)) + } + // if there's text after the cursor, we want to make sure the upload marker is separated by a blank line + if (postMarker) { + // Count existing newlines at the start of postMarker + const existingNewlines = postMarker.match(/^[\n]*/)?.[0].length || 0 + // Add only the needed newlines to reach 2 + postMarker = '\n'.repeat(Math.max(0, 2 - existingNewlines)) + postMarker } const newText = preMarker + uploadMarker + postMarker helpers.setValue(newText)