feat(autocomplete): auto-format textarea on blur (#884)

This commit is contained in:
Will Miao
2026-04-08 07:55:41 +08:00
parent b6dd6938b0
commit 18ddadc9ec
3 changed files with 135 additions and 0 deletions

View File

@@ -3,6 +3,7 @@ import { app } from "../../scripts/app.js";
import { TextAreaCaretHelper } from "./textarea_caret_helper.js";
import {
getAutocompleteAppendCommaPreference,
getAutocompleteAutoFormatPreference,
getAutocompleteAcceptKeyPreference,
getPromptTagAutocompletePreference,
getTagSpaceReplacementPreference,
@@ -122,6 +123,32 @@ function formatAutocompleteInsertion(text = '') {
return getAutocompleteAppendCommaPreference() ? `${trimmed},` : `${trimmed} `;
}
function normalizeAutocompleteSegment(segment = '') {
return segment.replace(/\s+/g, ' ').trim();
}
export function formatAutocompleteTextOnBlur(text = '') {
if (typeof text !== 'string') {
return '';
}
return text
.split('\n')
.map((line) => {
if (!line.trim()) {
return '';
}
const cleanedSegments = line
.split(',')
.map(normalizeAutocompleteSegment)
.filter(Boolean);
return cleanedSegments.join(', ');
})
.join('\n');
}
function shouldAcceptAutocompleteKey(key) {
const mode = getAutocompleteAcceptKeyPreference();
@@ -481,6 +508,14 @@ class AutoComplete {
// Handle focus out to hide dropdown
this.onBlur = () => {
if (getAutocompleteAutoFormatPreference()) {
const formattedValue = formatAutocompleteTextOnBlur(this.inputElement.value);
if (formattedValue !== this.inputElement.value) {
this.inputElement.value = formattedValue;
this.inputElement.dispatchEvent(new Event('input', { bubbles: true }));
}
}
// Delay hiding to allow for clicks on dropdown items
setTimeout(() => {
this.hide();