Skip to content

Commit 0907f1a

Browse files
committed
fix: indentation breaking for multiline elements or complex elements with many children
1 parent 47b0dab commit 0907f1a

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

src/extensionsIntegrated/phoenix-pro/LivePreviewEdit.js

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -719,6 +719,56 @@ define(function (require, exports, module) {
719719
}
720720
}
721721

722+
/**
723+
* This function reindents multiline text so that after the drag-drop operation the target indentation is matched
724+
* note: it preserves the relative indentation
725+
*
726+
* @param {String} sourceText - the text to re-indent
727+
* @param {String} targetIndent - the target indentation string
728+
* @returns {String} - the re-indented text
729+
*/
730+
function _reindentMultilineText(sourceText, targetIndent) {
731+
const lines = sourceText.split('\n');
732+
// for single lines no reindentation is needed
733+
if (lines.length <= 1) {
734+
return sourceText;
735+
}
736+
737+
// find the source indent from last non-empty line (normally its the closing tag)
738+
// this will represent the original indentation level of the element
739+
let sourceIndentLen = 0;
740+
for (let j = lines.length - 1; j >= 0; j--) {
741+
if (lines[j].trim() !== '') {
742+
let len = 0;
743+
while (len < lines[j].length && (lines[j][len] === ' ' || lines[j][len] === '\t')) {
744+
len++;
745+
}
746+
sourceIndentLen = len;
747+
break;
748+
}
749+
}
750+
751+
// calculate the indentation delta
752+
const delta = targetIndent.length - sourceIndentLen;
753+
754+
// adjust all lines by the delta to maintain relative indentation
755+
for (let j = 0; j < lines.length; j++) {
756+
if (lines[j].trim() === '') { continue; } // preserve empty lines
757+
758+
let currentIndent = 0;
759+
while (currentIndent < lines[j].length &&
760+
(lines[j][currentIndent] === ' ' || lines[j][currentIndent] === '\t')) {
761+
currentIndent++;
762+
}
763+
764+
const newIndent = Math.max(0, currentIndent + delta);
765+
const indentChar = targetIndent.length > 0 ? targetIndent[0] : ' ';
766+
lines[j] = indentChar.repeat(newIndent) + lines[j].substring(currentIndent);
767+
}
768+
769+
return lines.join('\n');
770+
}
771+
722772
/**
723773
* this function is to make sure that we insert elements with proper indentation
724774
*
@@ -729,6 +779,8 @@ define(function (require, exports, module) {
729779
* @param {String} sourceText - the text to insert
730780
*/
731781
function _insertElementWithIndentation(editor, insertPos, insertAfterMode, targetIndent, sourceText) {
782+
sourceText = _reindentMultilineText(sourceText, targetIndent);
783+
732784
if (insertAfterMode) {
733785
// Insert after the target element
734786
editor.replaceRange("\n" + targetIndent + sourceText, insertPos);

0 commit comments

Comments
 (0)