From 707d7bdf8b2b8d77e734d88893c6bce4bc692451 Mon Sep 17 00:00:00 2001 From: soxa <6390896+Soxasora@users.noreply.github.com> Date: Wed, 27 Nov 2024 22:31:46 +0100 Subject: [PATCH] fix: cannot add images above text (#1659) * fix: cannot add images above text * make sure there are always 2 newlines on either side of media --------- Co-authored-by: k00b --- components/form.js | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) 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)